diff --git a/.github/workflows/go-test.yml b/.github/workflows/go-test.yml index 29afb9e23..21f3f0bbc 100644 --- a/.github/workflows/go-test.yml +++ b/.github/workflows/go-test.yml @@ -18,7 +18,7 @@ jobs: shard: name: test shard (${{ matrix.shard }}) env: - RAFT_NATIVE_MEMORY_TESTS: '^(TestMigrationQuorumCommitFollowsForcedLeadershipTransfer|TestMigrationQuorumPartitionAcceptance|TestEnginePipelineNativeEncryptedLargeQuorumSnapshotRestart)$' + RAFT_NATIVE_MEMORY_TESTS: '^(TestMigrationQuorumCommitFollowsForcedLeadershipTransfer|TestMigrationQuorumPartitionAcceptance|TestEnginePipelineNativeEncryptedLargeQuorumSnapshotRestart|TestSyncInflightMessageTargets)$' strategy: fail-fast: false matrix: @@ -72,7 +72,7 @@ jobs: run: go test -race -timeout=30m ./adapter -run "$RAFT_NATIVE_MEMORY_TESTS" - name: Run encrypted native large-value race acceptance if: matrix.shard == 'raft-crypto' - run: go test -race -timeout=30m ./internal/raftengine/etcd -run "$RAFT_NATIVE_MEMORY_TESTS" + run: go test -race -v -timeout=30m ./internal/raftengine/etcd -run "$RAFT_NATIVE_MEMORY_TESTS" # Branch protection requires the "test (ubuntu-latest)" check, so this # job keeps that name and passes only when every shard passed. test: diff --git a/.github/workflows/jepsen-test-scheduled.yml b/.github/workflows/jepsen-test-scheduled.yml index 3c8f307f9..2b76a8eab 100644 --- a/.github/workflows/jepsen-test-scheduled.yml +++ b/.github/workflows/jepsen-test-scheduled.yml @@ -187,7 +187,7 @@ jobs: SPLIT_MEMBERSHIP_FAULT: none run: LEIN="$HOME/lein" bash scripts/jepsen-split-preflight.sh --online-member-change - name: Launch demo cluster - if: matrix.workload != 'unit' && matrix.workload != 'split-membership' && !startsWith(matrix.workload, 'filesystem-') && !startsWith(matrix.workload, 'sqs-') && matrix.workload != 'sqlite' + if: matrix.workload != 'unit' && matrix.workload != 'split-membership' && matrix.workload != 'grpc-version-cas' && !startsWith(matrix.workload, 'filesystem-') && !startsWith(matrix.workload, 'sqs-') && matrix.workload != 'sqlite' run: | set -euo pipefail nohup /tmp/elastickv-demo > /tmp/elastickv-demo.log 2>&1 & @@ -351,7 +351,7 @@ jobs: --sqs-ports 63501,63502,63503 --host 127.0.0.1 \ "${EXTRA_ARGS[@]}" - name: Run public gRPC Elle workload - if: startsWith(matrix.workload, 'grpc-') + if: matrix.workload == 'grpc-raw' || matrix.workload == 'grpc-transactional' working-directory: jepsen env: GRPC_TIME_LIMIT: ${{ inputs.time-limit || '300' }} @@ -372,6 +372,15 @@ jobs: --grpc-ports 50051,50052,50053 --grpc-api "${WORKLOAD#grpc-}" \ --time-limit "$GRPC_TIME_LIMIT" --rate "$GRPC_RATE" \ --concurrency 6 --key-count "$S3_KEY_COUNT" --max-writes-per-key "$S3_MAX_OPS_PER_KEY" + - name: Run protected three-voter CAS Jepsen with follower restart + if: matrix.workload == 'grpc-version-cas' + timeout-minutes: 40 + env: + ELASTICKV_CAS_JEPSEN_SECONDS: ${{ inputs.time-limit || '300' }} + ELASTICKV_CAS_JEPSEN_CLIENT: /tmp/jepsen-grpc-client + run: | + export PATH="$HOME:$PATH" + go test ./internal/server -run '^TestVersionCASJepsenStress$' -count=1 -v -timeout=35m - name: Launch filesystem cluster if: startsWith(matrix.workload, 'filesystem-') || matrix.workload == 'sqlite' # Mirrors the cluster in jepsen-test.yml: every node mounts the shared diff --git a/.github/workflows/tla-check.yml b/.github/workflows/tla-check.yml index cc37c9dc3..66043f263 100644 --- a/.github/workflows/tla-check.yml +++ b/.github/workflows/tla-check.yml @@ -1,20 +1,13 @@ name: TLA+ model check -# Runs `make tla-check` on PRs (and pushes to main) that touch the -# subsystems modelled by the spec or the spec / tooling themselves. -# Per docs/design/2026_05_28_implemented_tla_safety_spec.md ยง7.3. -# -# The job runs both MCHLC.cfg (correct design โ€” expected PASS) and -# MCHLC_gap.cfg (preconditions disabled โ€” expected FAIL with the HLC-4 -# counterexample); the Makefile target greps for the specific HLC-4 -# violation string so the gap evidence is validated, not just the exit -# code. +# Checks the Lean proofs and bounded TLC models for the affected subsystems. on: pull_request: types: [opened, synchronize, reopened] paths: - 'tla/**' + - 'lean/**' - 'Makefile' - 'kv/hlc*.go' - 'kv/tso*.go' @@ -22,10 +15,16 @@ on: - 'kv/sharded_coordinator.go' - 'kv/transaction.go' - 'kv/fsm.go' + - 'kv/fsm_cas.go' + - 'kv/fsm_migration_cleanup.go' + - 'kv/migration_version_identity.go' + - 'kv/version_cas_*.go' - 'kv/fsm_migration_serving.go' - 'kv/lock_resolver.go' - 'store/mvcc_store.go' - 'store/lsm_store.go' + - 'store/migration_cleanup.go' + - 'store/raft_entry*.go' - 'store/migration_online*.go' - 'store/migration_capture*.go' - 'adapter/split_job*.go' @@ -37,6 +36,7 @@ on: branches: [main] paths: - 'tla/**' + - 'lean/**' - 'Makefile' - 'kv/hlc*.go' - 'kv/tso*.go' @@ -44,10 +44,16 @@ on: - 'kv/sharded_coordinator.go' - 'kv/transaction.go' - 'kv/fsm.go' + - 'kv/fsm_cas.go' + - 'kv/fsm_migration_cleanup.go' + - 'kv/migration_version_identity.go' + - 'kv/version_cas_*.go' - 'kv/fsm_migration_serving.go' - 'kv/lock_resolver.go' - 'store/mvcc_store.go' - 'store/lsm_store.go' + - 'store/migration_cleanup.go' + - 'store/raft_entry*.go' - 'store/migration_online*.go' - 'store/migration_capture*.go' - 'adapter/split_job*.go' @@ -100,3 +106,23 @@ jobs: - name: Run make tla-check run: make tla-check + + lean-check: + name: lean-check + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Check out + uses: actions/checkout@v7 + + - name: Install pinned Lean + run: | + version="$(cut -d: -f2 lean/lean-toolchain)" + release="lean-${version#v}-linux" + archive="$RUNNER_TEMP/$release.tar.zst" + curl -fsSL "https://github.com/leanprover/lean4/releases/download/$version/$release.tar.zst" -o "$archive" + tar --zstd -xf "$archive" -C "$RUNNER_TEMP" + printf '%s\n' "$RUNNER_TEMP/$release/bin" >> "$GITHUB_PATH" + + - name: Run make lean-check + run: make lean-check diff --git a/Makefile b/Makefile index 71bee2744..8b91aa52e 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,7 @@ .PHONY: build test lean-check +LEAN ?= lean + build: go build ./... @@ -7,7 +9,7 @@ test: go test -v -race ./... lean-check: - cd lean && for proof in *.lean; do lean -DwarningAsError=true "$$proof" || exit 1; done + cd lean && for proof in *.lean; do "$(LEAN)" -DwarningAsError=true "$$proof" || exit 1; done sh lean/adapter/check.sh run: @@ -36,7 +38,7 @@ TLA_SHA256 := 936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88 TLA_URL := https://github.com/tlaplus/tlaplus/releases/download/$(TLA_VERSION)/tla2tools.jar TLA_LIB := ../lib -.PHONY: tla-check tla-tools +.PHONY: tla-check tla-cas-check tla-tools tla-tools: @mkdir -p $(dir $(TLA_JAR)) @@ -72,7 +74,10 @@ tla-tools: trap - EXIT HUP INT TERM; \ echo "tla2tools.jar ready at $(TLA_JAR) (SHA-256 $(TLA_SHA256))" -tla-check: tla-tools +tla-cas-check: tla-tools + @bash tla/cas/check.sh "$(abspath $(TLA_JAR))" + +tla-check: tla-cas-check @# Per-module orchestration lives in scripts/tla-check.sh so adding @# M3..M5 only needs an entry in that script's TLA_MODULES array @# and a `case` line for the gap-invariant string. The script does diff --git a/adapter/distribution_server.go b/adapter/distribution_server.go index ebef64eab..64c1132b1 100644 --- a/adapter/distribution_server.go +++ b/adapter/distribution_server.go @@ -536,6 +536,9 @@ func (s *DistributionServer) promoteSplitJobTargetAndComplete(ctx context.Contex if client == nil { return errors.New("split promotion client is nil") } + if err := s.prepareSplitVersionAdoption(ctx, job, client); err != nil { + return err + } if err := promoteSplitJobTarget(ctx, client, job); err != nil { return errors.WithStack(err) } diff --git a/adapter/distribution_server_test.go b/adapter/distribution_server_test.go index 6714f6ed5..af4460021 100644 --- a/adapter/distribution_server_test.go +++ b/adapter/distribution_server_test.go @@ -1847,7 +1847,7 @@ func coordinatorStubMutation(elem *kv.Elem[kv.OP], commitTS uint64) (*store.KVPa Op: store.OpTypeDelete, Key: distribution.CloneBytes(elem.Key), }, nil - case kv.DelPrefix: + case kv.DelPrefix, kv.CompareAndSwap: return nil, kv.ErrInvalidRequest default: return nil, kv.ErrInvalidRequest diff --git a/adapter/dynamodb_item_write.go b/adapter/dynamodb_item_write.go index 7c2a7d71c..26ed1c37c 100644 --- a/adapter/dynamodb_item_write.go +++ b/adapter/dynamodb_item_write.go @@ -464,7 +464,7 @@ func (d *DynamoDBServer) reuseMutationMatches(ctx context.Context, elem *kv.Elem return true, nil } return false, errors.Wrap(err, "read reuse tombstone") - case kv.DelPrefix: + case kv.DelPrefix, kv.CompareAndSwap: return false, nil } return false, nil diff --git a/adapter/fenced_floor_proxy_test.go b/adapter/fenced_floor_proxy_test.go new file mode 100644 index 000000000..cb15dd64c --- /dev/null +++ b/adapter/fenced_floor_proxy_test.go @@ -0,0 +1,99 @@ +package adapter + +import ( + "context" + "fmt" + "sync/atomic" + "testing" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type fencedFloorReadEngine struct { + localCompactionReadEngine + err error + reads atomic.Int32 +} + +func (e *fencedFloorReadEngine) LinearizableRead(context.Context) (uint64, error) { + e.reads.Add(1) + return 0, e.err +} + +func fencedFloorShardStore(st store.MVCCStore, engine *fencedFloorReadEngine) *kv.ShardStore { + routes := distribution.NewEngine() + routes.UpdateRoute(nil, nil, 1) + return kv.NewShardStore(routes, map[uint64]*kv.ShardGroup{1: {Store: st, Engine: engine}}) +} + +type fencedFloorTargetCoordinator struct { + *verifyHookCoordinator + mutations atomic.Int32 +} + +func (c *fencedFloorTargetCoordinator) Dispatch(ctx context.Context, req *kv.OperationGroup[kv.OP]) (*kv.CoordinateResponse, error) { + if !isDynamoSnapshotSealRequest(req) { + c.mutations.Add(1) + } + return c.localAdapterCoordinator.Dispatch(ctx, req) +} + +func dialFencedFloorProxy(t *testing.T, targetStore store.MVCCStore, coord kv.Coordinator) *redisWireClient { + t.Helper() + target := startRedisWireServer(t, targetStore, coord, newRedisWireTestGate(t), WithOnePhaseTxnDedup(true)) + st := newRedisWireStore(t) + follower := newLocalAdapterCoordinator(st) + follower.leaderSet, follower.leader, follower.raftLeader = true, false, "target" + proxy := startRedisWireServer(t, st, follower, newRedisWireTestGate(t), func(s *RedisServer) { + s.leaderRedis = map[string]string{"target": target.listen.Addr().String()} + }) + return dialRedisWire(t, proxy) +} + +func TestFencedFloorRedisProxyTransfer(t *testing.T) { + base := newRedisWireStore(t) + engine := &fencedFloorReadEngine{err: raftengine.ErrLeadershipTransferInProgress} + shards := fencedFloorShardStore(base, engine) + coord := &fencedFloorTargetCoordinator{verifyHookCoordinator: newVerifyHookCoordinator(base)} + client := dialFencedFloorProxy(t, shards, coord) + client.send(t, []string{cmdMulti}, []string{cmdRPush, "a", "1"}, []string{cmdRPush, "b", "2"}, + []string{cmdRPush, "c", "3"}, []string{cmdExec}, []string{cmdPing}) + client.want(t, "+OK\r\n+QUEUED\r\n+QUEUED\r\n+QUEUED\r\n") + frame, err := client.r.ReadString('\n') + require.NoError(t, err) + coord.mu.Lock() + leases := coord.leaseCalls + coord.mu.Unlock() + require.Positive(t, leases, "the target must pass the initial lease check") + require.EqualValues(t, 1, engine.reads.Load(), "the target must reach the actual floor fence") + require.Zero(t, coord.mutations.Load()) + require.Equal(t, "-"+redisNotLeaderReply+"\r\n", frame) + client.want(t, "+PONG\r\n") +} + +func TestFencedFloorRedisProxyMixedExec(t *testing.T) { + st := newRedisWireStore(t) + client := dialFencedFloorProxy(t, st, newLocalAdapterCoordinator(st)) + client.send(t, []string{cmdMulti}, []string{cmdSet, "a", "v"}, []string{cmdRPush, "a", "x"}, + []string{cmdGet, "a"}, []string{cmdExec}, []string{cmdPing}) + client.want(t, "+OK\r\n+QUEUED\r\n+QUEUED\r\n+QUEUED\r\n*3\r\n+OK\r\n-"+wrongTypeMessage+"\r\n$1\r\nv\r\n+PONG\r\n") +} + +func TestFencedFloorRawGroupWatermarkInternalDeadline(t *testing.T) { + engine := &fencedFloorReadEngine{err: fmt.Errorf("synthetic-key: %w", context.DeadlineExceeded)} + shards := fencedFloorShardStore(newRedisWireStore(t), engine) + ctx := t.Context() + reply, err := NewGRPCServer(shards, nil).RawLatestCommitTS(ctx, &pb.RawLatestCommitTSRequest{GroupId: 1}) + require.NoError(t, ctx.Err()) + require.EqualValues(t, 1, engine.reads.Load()) + require.Nil(t, reply) + require.Equal(t, codes.Unavailable, status.Code(err)) + require.NotContains(t, status.Convert(err).Message(), "synthetic-key") +} diff --git a/adapter/fenced_floor_reuse_test.go b/adapter/fenced_floor_reuse_test.go new file mode 100644 index 000000000..bbd7ed654 --- /dev/null +++ b/adapter/fenced_floor_reuse_test.go @@ -0,0 +1,175 @@ +package adapter + +import ( + "context" + "io" + "testing" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/kv" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" + "github.com/tidwall/redcon" +) + +// Apply the first mutation to MVCC before returning its synthetic response. +// Only a subsequent commit timestamp allocation is allowed to fail. +type fencedFloorReuseCoordinator struct { + *dedupTestCoordinator + first *kv.OperationGroup[kv.OP] + response error + allocErr error + failedAfter []uint64 +} + +func (c *fencedFloorReuseCoordinator) Dispatch(ctx context.Context, req *kv.OperationGroup[kv.OP]) (*kv.CoordinateResponse, error) { + resp, err := c.dedupTestCoordinator.Dispatch(ctx, req) + if err == nil && !isDynamoSnapshotSealRequest(req) && c.first == nil { + c.first = req + return nil, c.response + } + return resp, err +} + +func (c *fencedFloorReuseCoordinator) TimestampAllocator() kv.TimestampAllocator { + return c +} + +func (c *fencedFloorReuseCoordinator) Next(ctx context.Context) (uint64, error) { + return c.NextAfter(ctx, 0) +} + +func (c *fencedFloorReuseCoordinator) NextAfter(_ context.Context, min uint64) (uint64, error) { + if c.first != nil { + c.failedAfter = append(c.failedAfter, min) + return 0, c.allocErr + } + c.Clock().Observe(min) + return c.Clock().NextFenced() +} + +func TestFencedFloorRedisPendingOutcome(t *testing.T) { + key := []byte("list-or-stream") + values := [][]byte{[]byte("v")} + for _, op := range []struct { + name string + run func(*testing.T, *RedisServer) error + }{ + {"EXEC", func(t *testing.T, s *RedisServer) error { + results, err := s.runTransaction([]redcon.Command{{Args: [][]byte{[]byte(cmdRPush), key, values[0]}}}, t.Context()) + require.Nil(t, results) + return err + }}, + {"RPUSH", func(t *testing.T, s *RedisServer) error { + length, err := s.listRPush(t.Context(), key, values) + require.Zero(t, length) + return err + }}, + {"XADD", func(t *testing.T, s *RedisServer) error { + id, err := s.xaddTxnWithDedup(t.Context(), key, xaddRequest{id: "*", fields: []string{"f", "v"}, maxLen: -1}) + require.Empty(t, id) + return err + }}, + } { + for _, fault := range []struct { + name string + response error + allocErr error + }{ + {"reuse-allocation", store.ErrWriteConflict, raftengine.ErrLeadershipTransferInProgress}, + {"retryable-allocation", store.ErrWriteConflict, kv.ErrTxnLocked}, + {"lost-response", io.EOF, raftengine.ErrLeadershipTransferInProgress}, + } { + t.Run(op.name+"/"+fault.name, func(t *testing.T) { + st := newRedisWireStore(t) + coord := &fencedFloorReuseCoordinator{ + dedupTestCoordinator: newDedupTestCoordinator(st, 0, false), + response: fault.response, + allocErr: fault.allocErr, + } + s := NewRedisServer(nil, "", st, coord, nil, nil, WithOnePhaseTxnDedup(true)) + t.Cleanup(s.Stop) + err := op.run(t, s) + require.Equal(t, 1, coord.dispatches) + first := coord.first + require.NotNil(t, first) + require.Greater(t, first.CommitTS, first.StartTS) + require.Zero(t, first.PrevCommitTS) + require.NotEmpty(t, first.Elems) + for _, elem := range first.Elems { + landed, probeErr := st.CommittedVersionAt(t.Context(), elem.Key, first.CommitTS) + require.NoError(t, probeErr) + require.True(t, landed, "missing original write at its commit timestamp") + } + if errors.Is(fault.response, store.ErrWriteConflict) { + require.Equal(t, []uint64{first.StartTS}, coord.failedAfter) + } else { + require.Empty(t, coord.failedAfter) + } + require.ErrorIs(t, err, kv.ErrTransactionOutcomeUnknown) + require.False(t, isRetryableRedisTxnErr(err)) + require.False(t, isTransientLeaderRedisError(err)) + require.False(t, kv.IsCertifiedCASMismatch(err)) + reply := &captureConn{} + writeRedisError(reply, err) + require.Equal(t, redisOutcomeUnknownReply, reply.lastErr) + }) + } + } +} + +// The retry loops release their private pending record on terminal return. +// Check that allocation failure also leaves that record intact at the reuse +// boundary, including cached results that must never be returned as success. +func TestFencedFloorRedisReusePreservesAttempt(t *testing.T) { + st := newRedisWireStore(t) + coord := &fencedFloorReuseCoordinator{ + dedupTestCoordinator: newDedupTestCoordinator(st, 0, false), + first: &kv.OperationGroup[kv.OP]{StartTS: 3, CommitTS: 7}, + allocErr: kv.ErrCeilingExpired, + } + server := NewRedisServer(nil, "", st, coord, nil, nil) + t.Cleanup(server.Stop) + // Fresh slices on each call detect in-place changes as well as replacement. + elems := func() []*kv.Elem[kv.OP] { + return []*kv.Elem[kv.OP]{{Op: kv.Put, Key: []byte("entry"), Value: []byte("value")}} + } + reads := func() [][]byte { return [][]byte{[]byte("boundary")} } + t.Run("EXEC", func(t *testing.T) { + attempt := func() *reusableExecTxn { + return &reusableExecTxn{startTS: 3, commitTS: 7, elems: elems(), readKeys: reads(), + results: []redisResult{{typ: resultBulk, bulk: []byte("value")}}} + } + pending := attempt() + result, drop, err := server.dispatchExecReuse(t.Context(), pending) + require.ErrorIs(t, err, kv.ErrTransactionOutcomeUnknown) + require.False(t, drop) + require.Nil(t, result) + require.Equal(t, attempt(), pending) + }) + t.Run("RPUSH", func(t *testing.T) { + attempt := func() *reusableListPush { + return &reusableListPush{startTS: 3, commitTS: 7, ops: elems(), readKeys: reads(), length: 4} + } + pending := attempt() + length, drop, err := server.dispatchListPushReuse(t.Context(), []byte("list"), pending) + require.ErrorIs(t, err, kv.ErrTransactionOutcomeUnknown) + require.False(t, drop) + require.Zero(t, length) + require.Equal(t, attempt(), pending) + }) + t.Run("XADD", func(t *testing.T) { + attempt := func() *reusableXAdd { + return &reusableXAdd{startTS: 3, commitTS: 7, elems: elems(), readKeys: reads(), + probeKey: []byte("entry"), id: "4-1"} + } + pending := attempt() + id, drop, err := server.dispatchXAddReuse(t.Context(), []byte("stream"), pending) + require.ErrorIs(t, err, kv.ErrTransactionOutcomeUnknown) + require.False(t, drop) + require.Empty(t, id) + require.Equal(t, attempt(), pending) + }) + require.Zero(t, coord.dispatches) +} diff --git a/adapter/forward_version_cas.go b/adapter/forward_version_cas.go new file mode 100644 index 000000000..376e5d2e3 --- /dev/null +++ b/adapter/forward_version_cas.go @@ -0,0 +1,24 @@ +package adapter + +import ( + "context" + + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (i *Internal) ForwardCompareAndSwap(context.Context, *pb.ForwardRequest) (*pb.ForwardResponse, error) { + return nil, errors.WithStack(kv.VersionCASForwardUnavailable(kv.ErrVersionCASUnavailable)) +} + +// The receiver must support Raft-ordered routing before it can accept this +// request. An older server has no V2 method and cannot submit the write. +func (i *Internal) ForwardCompareAndSwapV2(ctx context.Context, req *pb.ForwardRequest) (*pb.ForwardResponse, error) { + if !kv.HasCASMutation(req.GetRequests()) { + return nil, errors.WithStack(status.Error(codes.InvalidArgument, "expected compare-and-swap")) + } + return i.forwardRequests(ctx, req) +} diff --git a/adapter/grpc.go b/adapter/grpc.go index c752f3db0..66d862d2c 100644 --- a/adapter/grpc.go +++ b/adapter/grpc.go @@ -231,42 +231,47 @@ func (r *GRPCServer) RawGet(ctx context.Context, req *pb.RawGetRequest) (respons if err := r.requireReadReady(); err != nil { return nil, errors.WithStack(err) } - resolvedTS, err := r.resolveRawReadSnapshot(ctx, req.GetTs(), req.GetGroupId(), req.GetKey()) + snapshot, err := resolveRawReadSnapshot(ctx, readRequest, req.GetTs(), req.GetGroupId(), req.GetKey()) if err != nil { return nil, errors.WithStack(err) } - readTS = resolvedTS - var v []byte - if fenceGetter, ok := r.store.(rawReadFenceGetter); ok { - v, err = requestGetAtWithReadFence(ctx, fenceGetter, req.Key, readTS, req.GetGroupId(), r.readRouteVersion(req.GetReadRouteVersion())) - } else if req.GetReadRouteVersion() != 0 { - return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "raw get with read fence requires a read-fence-aware store")) - } else if groupID := req.GetGroupId(); groupID != 0 { - groupGetter, ok := r.store.(rawGroupGetter) - if !ok { - return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "raw get with explicit group requires a group-aware store")) - } - v, err = requestGetGroupAt(ctx, groupGetter, groupID, req.Key, readTS) - } else { - v, err = requestGetAt(ctx, r.store, req.Key, readTS) + readTS = snapshot.Timestamp() + if req.GetNeedCommitTs() { + return r.rawGetVersion(ctx, readRequest, snapshot, req) } - r.observeGRPCPointRead(ctx, req.GetKey(), req.GetGroupId()) - if errors.Is(err, store.ErrKeyNotFound) { - return &pb.RawGetResponse{Value: nil, Exists: false}, nil - } - if errors.Is(err, store.ErrReadTSCompacted) { - return nil, errors.WithStack(status.Error(codes.FailedPrecondition, store.ErrReadTSCompacted.Error())) - } - if err != nil { - return nil, errors.WithStack(err) - } - r.logGet(ctx, req.Key, v) - - return &pb.RawGetResponse{Value: v, Exists: true}, nil - + return r.rawGetValue(ctx, readRequest, snapshot, req) }) } +func (r *GRPCServer) rawGetValue(ctx context.Context, readRequest *kv.ReadRequest, snapshot kv.ReadSnapshot, req *pb.RawGetRequest) (*pb.RawGetResponse, error) { + var v []byte + var err error + if _, ok := r.store.(rawReadFenceGetter); ok { + v, err = readRequest.GetWithFence(ctx, snapshot, req.Key, req.GetGroupId(), r.readRouteVersion(req.GetReadRouteVersion())) + } else if req.GetReadRouteVersion() != 0 { + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "raw get with read fence requires a read-fence-aware store")) + } else if groupID := req.GetGroupId(); groupID != 0 { + if _, ok := r.store.(rawGroupGetter); !ok { + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "raw get with explicit group requires a group-aware store")) + } + v, err = readRequest.GetGroup(ctx, snapshot, groupID, req.Key) + } else { + v, err = readRequest.Get(ctx, snapshot, req.Key) + } + r.observeGRPCPointRead(ctx, req.GetKey(), req.GetGroupId()) + if errors.Is(err, store.ErrKeyNotFound) { + return &pb.RawGetResponse{Value: nil, Exists: false}, nil + } + if errors.Is(err, store.ErrReadTSCompacted) { + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, store.ErrReadTSCompacted.Error())) + } + if err != nil { + return nil, errors.WithStack(err) + } + r.logGet(ctx, req.Key, v) + return &pb.RawGetResponse{Value: v, Exists: true}, nil +} + func (r *GRPCServer) logGet(ctx context.Context, key, value []byte) { if r.log.Enabled(ctx, slog.LevelInfo) { r.log.InfoContext(ctx, "Get", @@ -275,6 +280,31 @@ func (r *GRPCServer) logGet(ctx context.Context, key, value []byte) { } } +func (r *GRPCServer) rawGetVersion(ctx context.Context, readRequest *kv.ReadRequest, snapshot kv.ReadSnapshot, req *pb.RawGetRequest) (*pb.RawGetResponse, error) { + record, err := readRequest.GetVersionWithFence(ctx, snapshot, req.GetKey(), req.GetGroupId(), r.readRouteVersion(req.GetReadRouteVersion())) + r.observeGRPCPointRead(ctx, req.GetKey(), req.GetGroupId()) + if errors.Is(err, store.ErrKeyNotFound) { + return &pb.RawGetResponse{Version: &pb.RawGetResponse_Missing{Missing: true}}, nil + } + if errors.Is(err, store.ErrReadTSCompacted) { + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, store.ErrReadTSCompacted.Error())) + } + if err := versionedGetError(record, err); err != nil { + return nil, err + } + return &pb.RawGetResponse{Value: record.Value, Exists: true, Version: &pb.RawGetResponse_CommitTs{CommitTs: record.TS}}, nil +} + +func versionedGetError(record store.VersionedValue, err error) error { + if errors.Is(err, kv.ErrVersionCASUnavailable) { + return errors.WithStack(status.Error(codes.FailedPrecondition, "version token admission unavailable")) + } + if errors.Is(err, store.ErrNotSupported) || (err == nil && record.TS == 0) { + return errors.WithStack(status.Error(codes.Unimplemented, "commit timestamp is unavailable for this read")) + } + return errors.WithStack(err) +} + // rawGroupWatermark answers the keyless leader-fenced watermark for one Raft // group. LeaderFenced is set because the floor is read behind that group's own // leader fence, which is what makes it usable as a read watermark. @@ -867,6 +897,18 @@ func (r *GRPCServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetRespon if err != nil { return nil, errors.WithStack(err) } + if req.GetNeedCommitTs() { + record, err := readRequest.GetVersion(ctx, snapshot, req.GetKey()) + r.observeGRPCPointRead(ctx, req.GetKey(), 0) + if errors.Is(err, store.ErrKeyNotFound) { + return &pb.GetResponse{Version: &pb.GetResponse_Missing{Missing: true}}, nil + } + if err := versionedGetError(record, err); err != nil { + return nil, err + } + return &pb.GetResponse{Value: record.Value, Version: &pb.GetResponse_CommitTs{CommitTs: record.TS}}, nil + } + v, err := readRequest.Get(ctx, snapshot, req.Key) r.observeGRPCPointRead(ctx, req.GetKey(), 0) if err != nil { @@ -988,15 +1030,21 @@ func (r *GRPCServer) beginLatestReadSnapshot(ctx context.Context, groupID uint64 return stamp.Timestamp(), err } -func (r *GRPCServer) resolveRawReadSnapshot(ctx context.Context, requested, groupID uint64, key []byte) (uint64, error) { +func resolveRawReadSnapshot(ctx context.Context, request *kv.ReadRequest, requested, groupID uint64, key []byte) (kv.ReadSnapshot, error) { if requested != 0 { - if request, ok := kv.ReadRequestFromContext(ctx); ok { - snapshot, err := request.Historical(ctx, requested) - return snapshot.Timestamp(), err - } - return requested, nil + snapshot, err := request.Historical(ctx, requested) + return snapshot, errors.WithStack(err) + } + if groupID != 0 { + snapshot, err := request.LatestTargets(ctx, "grpc group read", []kv.ReadFenceTarget{{GroupID: groupID, Key: key}}) + return snapshot, errors.WithStack(err) + } + var keys [][]byte + if key != nil { + keys = [][]byte{key} } - return r.beginLatestReadSnapshot(ctx, groupID, key) + snapshot, err := request.Latest(ctx, "grpc latest read", keys...) + return snapshot, errors.WithStack(err) } func WithGRPCActiveTimestampTracker(tracker *kv.ActiveTimestampTracker) GRPCServerOption { diff --git a/adapter/grpc_cas_catalog_test.go b/adapter/grpc_cas_catalog_test.go new file mode 100644 index 000000000..c28cf01bb --- /dev/null +++ b/adapter/grpc_cas_catalog_test.go @@ -0,0 +1,87 @@ +package adapter + +import ( + "math" + "testing" + + "github.com/bootjp/elastickv/distribution" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestCompareAndSwapCatalogChangeAfterForwardAdmission(t *testing.T) { + for _, tc := range []struct { + name string + owner uint64 + state distribution.RouteState + }{ + {name: "fenced", owner: casRPCGroup, state: distribution.RouteStateWriteFenced}, + {name: "moved", owner: casRPCGroup + 1, state: distribution.RouteStateActive}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newCASRPCFixture(t) + key := []byte("row-on-right") + version := f.put(t, key, []byte("before")) + req := &pb.CompareAndSwapRequest{Key: key, ExpectedCommitTs: version, Value: []byte("after")} + f.proposals.park.Store(true) + done := make(chan error, 1) + go func() { + _, err := f.follower.CompareAndSwap(f.ctx, req) + done <- err + }() + select { + case <-f.proposals.parked: + case err := <-done: + t.Fatalf("forwarded CAS returned before proposing: %v", err) + case <-f.ctx.Done(): + t.Fatal(f.ctx.Err()) + } + + muts := []*store.KVPairMutation{ + {Op: store.OpTypePut, Key: distribution.CatalogVersionKey(), Value: distribution.EncodeCatalogVersion(2)}, + } + for _, route := range []distribution.RouteDescriptor{ + {RouteID: 1, End: []byte("m"), GroupID: casRPCGroup, State: distribution.RouteStateActive}, + {RouteID: 2, Start: []byte("m"), GroupID: tc.owner, State: tc.state}, + } { + raw, err := distribution.EncodeRouteDescriptorForCatalogWrite(route, true) + require.NoError(t, err) + muts = append(muts, &store.KVPairMutation{ + Op: store.OpTypePut, Key: distribution.CatalogRouteKey(route.RouteID), Value: raw, + }) + } + replicateCASCatalogMutations(t, f.ctx, f.proposals, f.local.LastCommitTS(), muts) + f.proposals.park.Store(false) + close(f.proposals.release) + + err := <-done + st := status.Convert(err) + require.Equal(t, codes.Aborted, st.Code(), "the indexed fence was definitive: %v", err) + require.NotEmpty(t, st.Details()) + detail, ok := st.Details()[0].(*errdetails.ErrorInfo) + require.True(t, ok) + require.Equal(t, "CAS_ROUTE_FENCED", detail.GetReason()) + + // The front end still resolves the old owner. Its next forward + // must be rejected by the receiver before any Raft proposal. + for _, client := range []pb.TransactionalKVClient{f.leader, f.follower} { + _, err = client.CompareAndSwap(f.ctx, req) + st := status.Convert(err) + require.Equal(t, codes.FailedPrecondition, st.Code(), "%v", err) + require.Len(t, st.Details(), 1) + info, ok := st.Details()[0].(*errdetails.ErrorInfo) + require.True(t, ok) + require.Equal(t, publicGRPCNotAdmittedReason, info.GetReason()) + } + require.EqualValues(t, 2, f.forwards.Load()) + require.EqualValues(t, 1, f.proposals.attempts.Load()) + row, err := store.GetVersionAt(f.ctx, f.local, key, math.MaxUint64) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: version, Value: []byte("before")}, row) + }) + } +} diff --git a/adapter/grpc_compare_and_swap.go b/adapter/grpc_compare_and_swap.go new file mode 100644 index 000000000..9f80cb0dd --- /dev/null +++ b/adapter/grpc_compare_and_swap.go @@ -0,0 +1,55 @@ +package adapter + +import ( + "context" + + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (r *GRPCServer) CompareAndSwap(ctx context.Context, req *pb.CompareAndSwapRequest) (*pb.CompareAndSwapResponse, error) { + if err := validateCompareAndSwapRequest(req); err != nil { + return nil, err + } + resp, err := r.coordinator.Dispatch(ctx, &kv.OperationGroup[kv.OP]{ + IsTxn: true, + Elems: []*kv.Elem[kv.OP]{{ + Op: kv.CompareAndSwap, Key: req.GetKey(), Value: req.GetValue(), ExpectedCommitTS: req.GetExpectedCommitTs(), + }}, + }) + if err != nil { + return compareAndSwapFailure(err) + } + if resp == nil || resp.CommitIndex == 0 || resp.CommitTS <= req.GetExpectedCommitTs() { + return nil, projectPublicGRPCMutationError(kv.ErrTransactionOutcomeUnknown) + } + return &pb.CompareAndSwapResponse{Result: &pb.CompareAndSwapResponse_NewCommitTs{NewCommitTs: resp.CommitTS}}, nil +} + +func compareAndSwapFailure(err error) (*pb.CompareAndSwapResponse, error) { + if kv.IsCertifiedCASMismatch(err) { + return &pb.CompareAndSwapResponse{Result: &pb.CompareAndSwapResponse_Mismatch{Mismatch: true}}, nil + } + if !errors.Is(err, kv.ErrTransactionOutcomeUnknown) && kv.IsCertifiedOnePhaseConflict(err) { + switch { + case errors.Is(err, kv.ErrRouteWriteFenced): + return nil, publicMutationStatus(codes.Aborted, "Compare-and-swap route is write-fenced", "CAS_ROUTE_FENCED") + case errors.Is(err, kv.ErrTxnLocked): + return nil, publicMutationStatus(codes.Aborted, "Compare-and-swap key is locked", "CAS_LOCKED") + } + } + return nil, projectPublicGRPCMutationError(err) +} + +func validateCompareAndSwapRequest(req *pb.CompareAndSwapRequest) error { + if len(req.GetKey()) == 0 || req.GetExpectedCommitTs() == 0 { + return errors.WithStack(status.Error(codes.InvalidArgument, "key and positive expected commit timestamp are required")) + } + if !kv.IsCASUserKey(req.GetKey()) { + return errors.WithStack(status.Error(codes.PermissionDenied, "compare-and-swap requires a public key")) + } + return nil +} diff --git a/adapter/grpc_compare_and_swap_test.go b/adapter/grpc_compare_and_swap_test.go new file mode 100644 index 000000000..ed46a76f8 --- /dev/null +++ b/adapter/grpc_compare_and_swap_test.go @@ -0,0 +1,602 @@ +package adapter + +import ( + "context" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + etcdraftengine "github.com/bootjp/elastickv/internal/raftengine/etcd" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +const casRPCGroup = 2 + +type casRPCFollower struct { + raftengine.Engine + leader raftengine.LeaderInfo +} + +func (e *casRPCFollower) State() raftengine.State { return raftengine.StateFollower } +func (e *casRPCFollower) Leader() raftengine.LeaderInfo { return e.leader } +func (e *casRPCFollower) Status() raftengine.Status { + return raftengine.Status{State: e.State(), Leader: e.Leader()} +} + +type casRPCProposalFault struct { + *etcdraftengine.Engine + attempts atomic.Int32 + loseResult atomic.Bool + fenceVerdict atomic.Bool + park atomic.Bool + parked chan struct{} + release chan struct{} +} + +func (e *casRPCProposalFault) Propose(ctx context.Context, payload []byte) (*raftengine.ProposalResult, error) { + isCAS := raftengine.IsVersionCASRaftPayload(payload) + if isCAS { + e.attempts.Add(1) + if e.fenceVerdict.Load() { + // Inject an indexed FSM refusal at the proposer result boundary. + return &raftengine.ProposalResult{CommitIndex: 17, Response: kv.ErrRouteWriteFenced}, nil + } + if e.park.Load() { + close(e.parked) + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-e.release: + } + } + } + result, err := e.Engine.Propose(ctx, payload) + if isCAS && err == nil && e.loseResult.Load() { + return nil, raftengine.ErrLeadershipLost + } + return result, err +} + +type casRPCFixture struct { + ctx context.Context + leader, single, follower pb.TransactionalKVClient + internal pb.InternalClient + local store.MVCCStore + proposals *casRPCProposalFault + forwards atomic.Int32 + dropReply atomic.Bool + allowCAS atomic.Bool +} + +func replicateCASFixtureCatalog(t testing.TB, ctx context.Context, proposer raftengine.Proposer, local store.MVCCStore, group uint64) { + t.Helper() + catalog := distribution.NewCatalogStore(local) + plan, err := catalog.BuildBootstrapPlanAt(ctx, 1, []distribution.Route{ + {GroupID: group, State: distribution.RouteStateActive}, + }) + require.NoError(t, err) + replicateCASCatalogMutations(t, ctx, proposer, 1, plan.Mutations) + seedCASFixtureReaderPolicy(t, ctx, local, group) +} + +func seedCASFixtureReaderPolicy(t testing.TB, ctx context.Context, local store.MVCCStore, group uint64) { + t.Helper() + // These RPC/count fixtures replace native admission with a local proof. + // Supply its durable policy precondition rather than bypassing the reader + // floor check. Real protected activation is covered by server TLS tests. + policy := raftbootstrap.PolicyRecord{ + Version: raftbootstrap.PolicyVersion, Identity: raftbootstrap.Identity{Cluster: raftbootstrap.UUID{1}, Group: group}, + BaselineDigest: raftbootstrap.Digest{2}, Minimum: raftbootstrap.Versions{Entry: 1, Snapshot: 1, Session: 1}, + ActivationIndex: 1, Generation: 1, LastConfigurationIndex: 1, + Configuration: raftbootstrap.Configuration{Index: 1, State: raftbootstrap.ConfState{Voters: []uint64{1}}, + Members: []raftbootstrap.Member{{ID: 1, Address: "fixture:9000", PublicKeyDigest: raftbootstrap.Digest{3}}}}, + } + key, err := kv.BootstrapPolicyMetadataKey(policy.Identity) + require.NoError(t, err) + data, err := raftbootstrap.MarshalPolicyRecord(policy) + require.NoError(t, err) + metadata, ok := local.(store.RaftControlMetadataStore) + require.True(t, ok) + require.NoError(t, metadata.ApplyRaftControlMetadata(ctx, func(ctx context.Context) error { + return metadata.StageRaftControlMetadata(ctx, key, data) + })) +} + +func replicateCASCatalogMutations(t testing.TB, ctx context.Context, proposer raftengine.Proposer, startTS uint64, muts []*store.KVPairMutation) { + t.Helper() + key := distribution.CatalogVersionKey() + request := &pb.Request{IsTxn: true, Ts: startTS, Mutations: []*pb.Mutation{ + {Op: pb.Op_PUT, Key: []byte(kv.TxnMetaPrefix), Value: kv.EncodeTxnMeta(kv.TxnMeta{PrimaryKey: key, CommitTS: startTS + 1})}, + }} + for _, mut := range muts { + request.Mutations = append(request.Mutations, &pb.Mutation{Op: pb.Op_PUT, Key: mut.Key, Value: mut.Value}) + request.ReadKeys = append(request.ReadKeys, mut.Key) + } + txn := kv.NewTransactionWithProposer(proposer) + defer txn.Close() + _, err := txn.Commit(ctx, []*pb.Request{request}) + require.NoError(t, err) +} + +func newCASRPCFixture(t *testing.T) *casRPCFixture { + t.Helper() + return newCASRPCFixtureWithAllocator(t, nil) +} + +func newCASRPCFixtureWithAllocator(t *testing.T, allocator kv.TimestampAllocator) *casRPCFixture { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + t.Cleanup(cancel) + local, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, local.Close()) }) + f := &casRPCFixture{ctx: ctx, local: local} + f.allowCAS.Store(true) + routes := distribution.NewEngine() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: casRPCGroup, State: distribution.RouteStateActive}, + }})) + hlc := kv.NewHLC() + factory := etcdraftengine.NewFactory(etcdraftengine.FactoryConfig{ + TickInterval: 10 * time.Millisecond, HeartbeatTick: 1, ElectionTick: 10, + MaxSizePerMsg: 1 << 20, MaxInflightMsg: 256, + }) + node, err := factory.Create(raftengine.FactoryConfig{ + LocalID: "cas-rpc-leader", LocalAddress: "cas-rpc-leader", DataDir: t.TempDir(), Bootstrap: true, + StateMachine: kv.NewKvFSMWithHLC(local, hlc, kv.WithRouteHistory(kv.WrapDistributionEngine(routes), casRPCGroup), + kv.WithRaftBootstrapIdentity(raftbootstrap.UUID{1}, casRPCGroup)), + }) + require.NoError(t, err) + t.Cleanup(func() { + require.NoError(t, node.Engine.Close()) + if node.Close != nil { + require.NoError(t, node.Close()) + } + }) + etcdEngine, ok := node.Engine.(*etcdraftengine.Engine) + require.True(t, ok, "expected an etcd raft engine, got %T", node.Engine) + engine := &casRPCProposalFault{ + Engine: etcdEngine, parked: make(chan struct{}), release: make(chan struct{}), + } + f.proposals = engine + require.Eventually(t, func() bool { return engine.State() == raftengine.StateLeader }, 5*time.Second, 10*time.Millisecond) + localProof := func(ctx context.Context) (context.Context, error) { + if !f.allowCAS.Load() { + return nil, kv.ErrVersionCASUnavailable + } + s := engine.Status() + return raftengine.WithVersionCASProof(ctx, raftengine.VersionCASProof{Term: s.Term, ConfigurationIndex: s.ConfigurationIndex}), nil + } + proof := kv.WithVersionCASAdmission(localProof) + leaderProxy := kv.NewLeaderProxyWithEngine(engine, proof) + t.Cleanup(func() { require.NoError(t, leaderProxy.Close()) }) + group := &kv.ShardGroup{Engine: engine, Store: local, Txn: leaderProxy} + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + groups := map[uint64]*kv.ShardGroup{casRPCGroup: group} + shards := kv.NewShardStore(routes, groups) + coord := kv.NewShardedCoordinator(routes, groups, casRPCGroup, hlc, shards) + coord.WithTSOAllocator(allocator) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + activated, err := engine.Propose(ctx, kv.EncodeCommitTSFenceActivation()) + require.NoError(t, err) + require.NotNil(t, activated) + require.Nil(t, activated.Response) + replicateCASFixtureCatalog(t, ctx, engine, local, casRPCGroup) + proofCtx, err := localProof(ctx) + require.NoError(t, err) + identity, err := engine.Propose(proofCtx, kv.EncodeMigrationVersionIdentityActivation()) + require.NoError(t, err) + require.NotNil(t, identity) + require.Nil(t, identity.Response) + require.NoError(t, coord.RecoverHLCLease(ctx)) + + txn := NewInternalMigrationTransaction(engine, nil, local, casRPCGroup, proof) + t.Cleanup(txn.Close) + leaderRPC := grpc.NewServer(grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if info.FullMethod != pb.Internal_ForwardCompareAndSwapV2_FullMethodName { + return handler(ctx, req) + } + f.forwards.Add(1) + resp, err := handler(ctx, req) + if err == nil && f.dropReply.Load() { + return nil, status.Error(codes.Unavailable, "injected lost reply after commit") + } + return resp, err + })) + pb.RegisterTransactionalKVServer(leaderRPC, NewGRPCServer(shards, coord)) + pb.RegisterInternalServer(leaderRPC, NewInternalWithEngine(txn, engine, hlc, nil, + WithInternalTimestampAllocator(allocator), WithInternalStore(local), WithInternalWriteGate(coord), WithInternalLastCommitTimestamp(local.LastCommitTS), + WithInternalCASForwardRouting(casRPCGroup, shards.CheckVersionCASForwardRoute))) + leaderAddr, leaderConn := serveCASRPC(t, leaderRPC) + f.leader = pb.NewTransactionalKVClient(leaderConn) + f.internal = pb.NewInternalClient(leaderConn) + + singleCoord := kv.NewCoordinatorWithEngine(txn, engine, kv.WithHLC(hlc)) + t.Cleanup(func() { require.NoError(t, singleCoord.Close()) }) + singleRPC := grpc.NewServer() + pb.RegisterTransactionalKVServer(singleRPC, NewGRPCServer(local, singleCoord)) + _, singleConn := serveCASRPC(t, singleRPC) + f.single = pb.NewTransactionalKVClient(singleConn) + + follower := &casRPCFollower{leader: raftengine.LeaderInfo{ID: "cas-rpc-leader", Address: leaderAddr}} + followerProxy := kv.NewLeaderProxyWithEngine(follower, proof) + t.Cleanup(func() { require.NoError(t, followerProxy.Close()) }) + followerStore := store.NewMVCCStore() + followerGroups := map[uint64]*kv.ShardGroup{casRPCGroup: {Engine: follower, Store: followerStore, Txn: followerProxy}} + followerCoord := kv.NewShardedCoordinator(routes, followerGroups, 1, kv.NewHLC(), followerStore) + t.Cleanup(func() { require.NoError(t, followerCoord.Close()) }) + followerRPC := grpc.NewServer() + pb.RegisterTransactionalKVServer(followerRPC, NewGRPCServer(followerStore, followerCoord)) + _, followerConn := serveCASRPC(t, followerRPC) + f.follower = pb.NewTransactionalKVClient(followerConn) + return f +} + +func serveCASRPC(t *testing.T, srv *grpc.Server) (string, *grpc.ClientConn) { + t.Helper() + var lc net.ListenConfig + listener, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") + require.NoError(t, err) + go func() { _ = srv.Serve(listener) }() + t.Cleanup(srv.Stop) + addr := listener.Addr().String() + conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, conn.Close()) }) + return addr, conn +} + +func (f *casRPCFixture) put(t *testing.T, key, value []byte) uint64 { + t.Helper() + resp, err := f.leader.Put(f.ctx, &pb.PutRequest{Key: key, Value: value}) + require.NoError(t, err) + require.True(t, resp.GetSuccess()) + ts, found, err := f.local.LatestCommitTS(f.ctx, key) + require.NoError(t, err) + require.True(t, found) + require.NotZero(t, ts) + return ts +} + +func TestCompareAndSwapPublicRPC(t *testing.T) { + f := newCASRPCFixture(t) + for _, tc := range []struct { + name string + client pb.TransactionalKVClient + }{ + {"sharded leader", f.leader}, + {"sharded follower ingress", f.follower}, + } { + t.Run(tc.name, func(t *testing.T) { + key := []byte(tc.name) + original := f.put(t, key, []byte("original")) + get, err := f.leader.Get(f.ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, original, get.GetCommitTs()) + req := &pb.CompareAndSwapRequest{Key: key, ExpectedCommitTs: get.GetCommitTs()} + applied, err := tc.client.CompareAndSwap(f.ctx, req) + require.NoError(t, err) + require.IsType(t, &pb.CompareAndSwapResponse_NewCommitTs{}, applied.GetResult()) + require.Greater(t, applied.GetNewCommitTs(), original) + get, err = f.leader.Get(f.ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Empty(t, get.GetValue()) + require.Equal(t, applied.GetNewCommitTs(), get.GetCommitTs()) + + mismatch, err := tc.client.CompareAndSwap(f.ctx, req) + require.NoError(t, err) + require.IsType(t, &pb.CompareAndSwapResponse_Mismatch{}, mismatch.GetResult()) + require.True(t, mismatch.GetMismatch()) + req.ExpectedCommitTs = applied.GetNewCommitTs() + sameValue, err := tc.client.CompareAndSwap(f.ctx, req) + require.NoError(t, err) + require.Greater(t, sameValue.GetNewCommitTs(), applied.GetNewCommitTs()) + req.Key = []byte("missing") + req.ExpectedCommitTs = ^uint64(0) + missing, err := tc.client.CompareAndSwap(f.ctx, req) + require.NoError(t, err) + require.True(t, missing.GetMismatch()) + }) + } + + for _, tc := range []struct { + req *pb.CompareAndSwapRequest + code codes.Code + }{ + {&pb.CompareAndSwapRequest{ExpectedCommitTs: 1}, codes.InvalidArgument}, + {&pb.CompareAndSwapRequest{Key: []byte("no expected version")}, codes.InvalidArgument}, + {&pb.CompareAndSwapRequest{Key: []byte(kv.TxnMetaPrefix), ExpectedCommitTs: 1}, codes.PermissionDenied}, + } { + before := f.forwards.Load() + resp, err := f.follower.CompareAndSwap(f.ctx, tc.req) + require.Equal(t, tc.code, status.Code(err)) + require.Nil(t, resp) + require.Equal(t, before, f.forwards.Load()) + } +} + +// The legacy coordinator has no authoritative route history. Even a local +// leader must use the protected sharded coordinator to admit a version CAS. +func TestCompareAndSwapLegacyCoordinatorRequiresRouteHistory(t *testing.T) { + f := newCASRPCFixture(t) + key := []byte("legacy-coordinator") + version := f.put(t, key, []byte("before")) + resp, err := f.single.CompareAndSwap(f.ctx, &pb.CompareAndSwapRequest{ + Key: key, ExpectedCommitTs: version, Value: []byte("after"), + }) + require.Nil(t, resp) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + require.Zero(t, f.proposals.attempts.Load()) + get, err := f.leader.Get(f.ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, version, get.GetCommitTs()) + require.Equal(t, []byte("before"), get.GetValue()) +} + +func TestCompareAndSwapLostForwardReply(t *testing.T) { + f := newCASRPCFixture(t) + key := []byte("lost-forward") + original := f.put(t, key, []byte("before")) + f.dropReply.Store(true) + req := &pb.CompareAndSwapRequest{Key: key, ExpectedCommitTs: original, Value: []byte("committed")} + resp, err := f.follower.CompareAndSwap(f.ctx, req) + require.Nil(t, resp) + require.True(t, isIndeterminateGRPCMutation(err), "RPC error: %v", err) + require.EqualValues(t, 1, f.forwards.Load()) + f.dropReply.Store(false) + get, err := f.leader.Get(f.ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, req.GetValue(), get.GetValue()) + require.Greater(t, get.GetCommitTs(), original) + mismatch, err := f.follower.CompareAndSwap(f.ctx, req) + require.NoError(t, err) + require.True(t, mismatch.GetMismatch()) + require.EqualValues(t, 2, f.forwards.Load()) +} + +func TestCompareAndSwapLostLocalProposalResult(t *testing.T) { + f := newCASRPCFixture(t) + key := []byte("lost-local-result") + original := f.put(t, key, []byte("before")) + f.proposals.loseResult.Store(true) + req := &pb.CompareAndSwapRequest{Key: key, ExpectedCommitTs: original, Value: []byte("committed")} + resp, err := f.leader.CompareAndSwap(f.ctx, req) + require.Nil(t, resp) + require.True(t, isIndeterminateGRPCMutation(err), "RPC error: %v", err) + require.EqualValues(t, 1, f.proposals.attempts.Load()) + f.proposals.loseResult.Store(false) + get, err := f.leader.Get(f.ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, req.GetValue(), get.GetValue()) + require.Greater(t, get.GetCommitTs(), original) +} + +func TestCompareAndSwapTimestampRejectionIsNotMismatch(t *testing.T) { + f := newCASRPCFixture(t) + key := []byte("target") + original := f.put(t, key, []byte("before")) + f.proposals.park.Store(true) + type rpcResult struct { + resp *pb.CompareAndSwapResponse + err error + } + done := make(chan rpcResult, 1) + go func() { + resp, err := f.follower.CompareAndSwap(f.ctx, &pb.CompareAndSwapRequest{Key: key, ExpectedCommitTs: original}) + done <- rpcResult{resp: resp, err: err} + }() + select { + case <-f.proposals.parked: + case got := <-done: + t.Fatalf("CAS returned before proposal reached the gate: %v", got.err) + case <-f.ctx.Done(): + t.Fatal(f.ctx.Err()) + } + f.put(t, []byte("unrelated"), []byte("advances write fence")) + f.proposals.park.Store(false) + close(f.proposals.release) + got := <-done + require.Nil(t, got.resp) + require.Equal(t, codes.Aborted, status.Code(got.err)) + require.EqualValues(t, 1, f.proposals.attempts.Load()) + require.EqualValues(t, 1, f.forwards.Load()) + get, err := f.leader.Get(f.ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, original, get.GetCommitTs()) +} + +func TestCompareAndSwapForwardPreflight(t *testing.T) { + f := newCASRPCFixture(t) + key := []byte("protected-from-forged-stamp") + original := f.put(t, key, []byte("before")) + req := &pb.Request{ + IsTxn: true, + VersionCasGroupId: casRPCGroup, + Mutations: []*pb.Mutation{ + {Op: pb.Op_PUT, Key: []byte(kv.TxnMetaPrefix), Value: kv.EncodeTxnMeta(kv.TxnMeta{PrimaryKey: key})}, + {Op: pb.Op_COMPARE_AND_SWAP, Key: key, ExpectedCommitTs: original, Value: []byte("after")}, + }, + } + envelope := &pb.ForwardRequest{IsTxn: true, Requests: []*pb.Request{req}, DecisionDetailVersion: kv.ForwardDecisionSchemaVersion} + legacy, err := f.internal.Forward(f.ctx, envelope) + require.Nil(t, legacy) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + + req.Ts = original + resp, err := f.internal.ForwardCompareAndSwapV2(f.ctx, envelope) + require.Nil(t, resp) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + req.Ts = 0 + req.VersionCasGroupId = casRPCGroup + 1 + resp, err = f.internal.ForwardCompareAndSwapV2(f.ctx, envelope) + require.Nil(t, resp) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + req.VersionCasGroupId = casRPCGroup + req.ObservedRouteVersion = 1 + resp, err = f.internal.ForwardCompareAndSwapV2(f.ctx, envelope) + require.Nil(t, resp) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + req.ObservedRouteVersion = 0 + req.WriteFenceBypassKeys = [][]byte{key} + resp, err = f.internal.ForwardCompareAndSwapV2(f.ctx, envelope) + require.Nil(t, resp) + require.Equal(t, codes.PermissionDenied, status.Code(err)) + req.WriteFenceBypassKeys = nil + + f.allowCAS.Store(false) + cas := &pb.CompareAndSwapRequest{Key: key, ExpectedCommitTs: original, Value: []byte("after")} + for _, client := range []pb.TransactionalKVClient{f.leader, f.follower} { + respCAS, err := client.CompareAndSwap(f.ctx, cas) + require.Nil(t, respCAS) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + } + get, err := f.leader.Get(f.ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, original, get.GetCommitTs()) + require.Equal(t, []byte("before"), get.GetValue()) + require.Zero(t, f.proposals.attempts.Load()) +} + +func TestCompareAndSwapForwardRequiresConfiguredPeerAuth(t *testing.T) { + unary, _ := SplitMigrationTokenAuth("test-peer-token", false, false) + server := grpc.NewServer(grpc.UnaryInterceptor(unary)) + pb.RegisterInternalServer(server, &pb.UnimplementedInternalServer{}) + _, conn := serveCASRPC(t, server) + client := pb.NewInternalClient(conn) + _, err := client.ForwardCompareAndSwapV2(t.Context(), &pb.ForwardRequest{Requests: []*pb.Request{{ + Mutations: []*pb.Mutation{{Op: pb.Op_COMPARE_AND_SWAP}}, + }}}) + require.Equal(t, codes.Unauthenticated, status.Code(err)) +} + +func TestCompareAndSwapIndexedLockRejection(t *testing.T) { + f := newCASRPCFixture(t) + key := []byte("cas-locked") + version := f.put(t, key, []byte("original")) + req := &pb.Request{ + IsTxn: true, Phase: pb.Phase_PREPARE, Ts: version + 1, + Mutations: []*pb.Mutation{ + {Key: []byte(kv.TxnMetaPrefix), Value: kv.EncodeTxnMeta(kv.TxnMeta{PrimaryKey: key, CommitTS: version + 2, LockTTLms: 10000})}, + {Key: key, Value: []byte("prepared")}, + }, + } + res, err := f.internal.Forward(f.ctx, &pb.ForwardRequest{IsTxn: true, Requests: []*pb.Request{req}}) + require.NoError(t, err) + require.True(t, res.GetSuccess()) + for _, client := range []pb.TransactionalKVClient{f.leader, f.follower} { + reply, err := client.CompareAndSwap(f.ctx, &pb.CompareAndSwapRequest{Key: key, ExpectedCommitTs: version, Value: []byte("replacement")}) + require.Nil(t, reply) + st := status.Convert(err) + require.Equal(t, codes.Aborted, st.Code()) + require.Len(t, st.Details(), 1) + info, ok := st.Details()[0].(*errdetails.ErrorInfo) + require.True(t, ok) + require.Equal(t, "CAS_LOCKED", info.GetReason()) + } + value, err := f.local.GetAt(f.ctx, key, ^uint64(0)) + require.NoError(t, err) + require.Equal(t, []byte("original"), value) +} + +func TestCompareAndSwapCertifiedRouteFence(t *testing.T) { + f := newCASRPCFixture(t) + key := []byte("route-fence") + version := f.put(t, key, []byte("before")) + f.proposals.fenceVerdict.Store(true) + for _, tc := range []struct { + name string + client pb.TransactionalKVClient + }{{"leader", f.leader}, {"follower", f.follower}} { + t.Run(tc.name, func(t *testing.T) { + reply, err := tc.client.CompareAndSwap(f.ctx, &pb.CompareAndSwapRequest{ + Key: key, ExpectedCommitTs: version, Value: []byte("after"), + }) + require.Nil(t, reply) + st := status.Convert(err) + require.Equal(t, codes.Aborted, st.Code()) + require.Len(t, st.Details(), 1) + info, ok := st.Details()[0].(*errdetails.ErrorInfo) + require.True(t, ok) + require.Equal(t, "CAS_ROUTE_FENCED", info.GetReason()) + }) + } + require.EqualValues(t, 1, f.forwards.Load()) + require.EqualValues(t, 2, f.proposals.attempts.Load()) +} + +// Reserve the CAS start timestamp and pause before issuing its commit +// timestamp. Other callers can still obtain timestamps and commit writes. +type casCommitTimestampGate struct { + clock *kv.HLC + calls atomic.Int32 + parked chan struct{} + release chan struct{} +} + +func (g *casCommitTimestampGate) Next(ctx context.Context) (uint64, error) { + if g.calls.Add(1) == 2 { + close(g.parked) + select { + case <-g.release: + case <-ctx.Done(): + return 0, ctx.Err() + } + } + return g.clock.Next(), nil +} + +func TestCompareAndSwapInterveningKeyChangeReturnsMismatch(t *testing.T) { + for _, ingress := range []string{"leader", "follower"} { + t.Run(ingress, func(t *testing.T) { + gate := &casCommitTimestampGate{clock: kv.NewHLC(), parked: make(chan struct{}), release: make(chan struct{})} + gate.calls.Store(2) // Fixture setup may allocate timestamps. + f := newCASRPCFixtureWithAllocator(t, gate) + key := []byte("intervening") + version := f.put(t, key, []byte("before")) + client := f.leader + if ingress == "follower" { + client = f.follower + } + gate.calls.Store(0) + type result struct { + reply *pb.CompareAndSwapResponse + err error + } + done := make(chan result, 1) + go func() { + resp, err := client.CompareAndSwap(f.ctx, &pb.CompareAndSwapRequest{ + Key: key, ExpectedCommitTs: version, Value: []byte("stale replacement"), + }) + done <- result{resp, err} + }() + select { + case <-gate.parked: + case early := <-done: + t.Fatalf("CAS returned before timestamp barrier: %v, %v", early.reply, early.err) + case <-f.ctx.Done(): + t.Fatal(f.ctx.Err()) + } + intervening := f.put(t, key, []byte("new value")) + close(gate.release) + got := <-done + require.NoError(t, got.err) + require.True(t, got.reply.GetMismatch()) + stored, err := f.leader.Get(f.ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, intervening, stored.GetCommitTs()) + require.Equal(t, []byte("new value"), stored.GetValue()) + }) + } +} diff --git a/adapter/grpc_mutation_error.go b/adapter/grpc_mutation_error.go index 5c67a75e6..986979970 100644 --- a/adapter/grpc_mutation_error.go +++ b/adapter/grpc_mutation_error.go @@ -22,6 +22,10 @@ func projectPublicGRPCMutationError(err error) error { return nil } code, message, reason := publicGRPCMutationFailure(err) + return publicMutationStatus(code, message, reason) +} + +func publicMutationStatus(code codes.Code, message, reason string) error { st, detailErr := status.New(code, message).WithDetails(&errdetails.ErrorInfo{ Domain: publicGRPCFailureDomain, Reason: reason, @@ -45,6 +49,8 @@ func publicGRPCMutationFailure(err error) (codes.Code, string, string) { return codes.Unknown, "Operation outcome unknown", publicGRPCUnknownReason } switch { + case errors.Is(err, kv.ErrVersionCASUnavailable): + return codes.FailedPrecondition, "Version CAS admission unavailable", publicGRPCNotAdmittedReason case errors.Is(err, kv.ErrTimestampBindingInvalid): return codes.FailedPrecondition, "Timestamp binding admission unavailable", publicGRPCNotAdmittedReason case errors.Is(err, kv.ErrLeaderProxyCircuitOpen): diff --git a/adapter/grpc_remote_version_ttl_test.go b/adapter/grpc_remote_version_ttl_test.go new file mode 100644 index 000000000..33baa8fa8 --- /dev/null +++ b/adapter/grpc_remote_version_ttl_test.go @@ -0,0 +1,56 @@ +package adapter + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/encryption" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil/grpctest" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" +) + +func TestFollowerVersionReadEncryptedTTL(t *testing.T) { + keys := encryption.NewKeystore() + require.NoError(t, keys.Set(1, make([]byte, encryption.KeySize))) + cipher, err := encryption.NewCipher(keys) + require.NoError(t, err) + primary, err := store.NewPebbleStore(t.TempDir(), store.WithEncryption(cipher, + encryption.NewDeterministicNonceFactory(1, 1), func() (uint32, bool) { return 1, true })) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, primary.Close()) }) + seedVersionReadCatalog(t, primary, 1) + key := []byte("ttl-key") + require.NoError(t, primary.PutAt(t.Context(), key, []byte("secret"), 10, 20)) + require.NoError(t, primary.PutAt(t.Context(), []byte("watermark"), []byte("later"), 30, 0)) + + routes := distribution.NewEngine() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, + Routes: []distribution.RouteDescriptor{{RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}}})) + makeShards := func(st store.MVCCStore, engine raftengine.Engine) *kv.ShardStore { + group := &kv.ShardGroup{Store: st, Engine: engine} + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + shards := kv.NewShardStore(routes, map[uint64]*kv.ShardGroup{1: group}) + t.Cleanup(func() { require.NoError(t, shards.Close()) }) + return shards + } + leader := makeShards(primary, &localCompactionReadEngine{}) + addr := grpctest.Serve(t, func(s *grpc.Server) { + pb.RegisterRawKVServer(s, NewGRPCServer(leader, &stubAdapterCoordinator{})) + }) + empty := store.NewMVCCStore() + t.Cleanup(func() { require.NoError(t, empty.Close()) }) + follower := makeShards(empty, &casRPCFollower{leader: raftengine.LeaderInfo{ID: "leader", Address: addr}}) + + got, err := follower.GetVersionAt(t.Context(), key, 19) + require.NoError(t, err) + require.Equal(t, []byte("secret"), got.Value) + require.EqualValues(t, 10, got.TS) + _, err = follower.GetVersionAt(t.Context(), key, 20) + require.ErrorIs(t, err, store.ErrKeyNotFound) +} diff --git a/adapter/grpc_test.go b/adapter/grpc_test.go index 5444b56ad..7274d10f1 100644 --- a/adapter/grpc_test.go +++ b/adapter/grpc_test.go @@ -5,14 +5,18 @@ import ( "context" "strconv" "sync" + "sync/atomic" "testing" "time" _ "github.com/Jille/grpc-multi-resolver" "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil/grpctest" kvstore "github.com/bootjp/elastickv/kv" pb "github.com/bootjp/elastickv/proto" "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/genproto/googleapis/rpc/errdetails" @@ -64,6 +68,117 @@ func isIndeterminateGRPCMutation(err error) bool { return false } +func isCertifiedGRPCNonAdmission(err error) bool { + st, ok := status.FromError(err) + if !ok || st.Code() != codes.Unavailable { + return false + } + details := st.Details() + if len(details) != 1 { + return false + } + info, ok := details[0].(*errdetails.ErrorInfo) + return ok && info.Domain == publicGRPCFailureDomain && info.Reason == publicGRPCNotAdmittedReason +} + +func readSequenceValue(ctx context.Context, c pb.RawKVClient, key []byte) (*pb.RawGetResponse, error) { + deadline := time.Now().Add(leaderChurnRetryTimeout) + for { + response, err := c.RawGet(ctx, &pb.RawGetRequest{Key: key}) + if err == nil || (!isTransientNotLeaderErr(err) && !isSequenceReadFenceLost(err)) || !time.Now().Before(deadline) { + return response, err + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(leaderChurnRetryInterval): + } + } +} + +// This read-only helper must not broaden mutation replay classification. +func isSequenceReadFenceLost(err error) bool { + var provider interface{ GRPCStatus() *status.Status } + if !errors.As(err, &provider) { + return false + } + st := provider.GRPCStatus() + return st != nil && st.Code() == codes.Unknown && len(st.Details()) == 0 && + st.Message() == "grpc latest read: read fence: raft engine: leadership lost" +} + +type sequenceReadFenceCoordinator struct { + *localAdapterCoordinator + reads atomic.Int32 +} + +func (c *sequenceReadFenceCoordinator) LinearizableRead(ctx context.Context) (uint64, error) { + if c.reads.Add(1) == 1 { + return 0, raftengine.ErrLeadershipLost + } + return c.localAdapterCoordinator.LinearizableRead(ctx) +} + +func TestReadSequenceValueRetriesLostReadFence(t *testing.T) { + t.Parallel() + st := store.NewMVCCStore() + key, value := []byte("sequence-read"), []byte("committed") + require.NoError(t, st.PutAt(t.Context(), key, value, 10, 0)) + coord := &sequenceReadFenceCoordinator{localAdapterCoordinator: newLocalAdapterCoordinator(st)} + address := grpctest.Serve(t, func(server *grpc.Server) { + pb.RegisterRawKVServer(server, NewGRPCServer(st, coord)) + }) + client := pb.NewRawKVClient(grpctest.Dial(t, address)) + response, err := readSequenceValue(t.Context(), client, key) + require.NoError(t, err) + require.Equal(t, value, response.GetValue()) + require.EqualValues(t, 2, coord.reads.Load()) +} + +type sequenceReadClient struct { + pb.RawKVClient + read func() (*pb.RawGetResponse, error) +} + +func (c sequenceReadClient) RawGet(context.Context, *pb.RawGetRequest, ...grpc.CallOption) (*pb.RawGetResponse, error) { + return c.read() +} + +func TestReadSequenceValuePreservesTerminalErrors(t *testing.T) { + t.Parallel() + for _, err := range []error{ + status.Error(codes.Unknown, "unrelated read failure"), + status.Error(codes.PermissionDenied, "grpc latest read: read fence: raft engine: leadership lost"), + publicMutationStatus(codes.Unknown, "grpc latest read: read fence: raft engine: leadership lost", publicGRPCUnknownReason), + status.Error(codes.Unavailable, "Route unavailable"), + context.DeadlineExceeded, + } { + calls := 0 + client := sequenceReadClient{read: func() (*pb.RawGetResponse, error) { + calls++ + return nil, err + }} + _, got := readSequenceValue(t.Context(), client, []byte("key")) + require.ErrorIs(t, got, err) + require.Equal(t, 1, calls) + } +} + +func TestReadSequenceValueCancellation(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + calls := 0 + client := sequenceReadClient{read: func() (*pb.RawGetResponse, error) { + calls++ + cancel() + return nil, status.Error(codes.Unknown, "grpc latest read: read fence: raft engine: leadership lost") + }} + _, err := readSequenceValue(ctx, client, []byte("key")) + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, 1, calls) +} + func putSequenceValue(ctx context.Context, c pb.RawKVClient, key, want []byte) error { deadline := time.Now().Add(leaderChurnRetryTimeout) for { @@ -75,12 +190,7 @@ func putSequenceValue(ctx context.Context, c pb.RawKVClient, key, want []byte) e return putErr } - var resp *pb.RawGetResponse - getErr := retryNotLeader(ctx, func() error { - var err error - resp, err = c.RawGet(ctx, &pb.RawGetRequest{Key: key}) - return err - }) + resp, getErr := readSequenceValue(ctx, c, key) if getErr != nil { return getErr } @@ -151,6 +261,36 @@ func TestPutSequenceValueResolvesIndeterminateOutcome(t *testing.T) { } } +func TestPutSequenceValueRetriesCertifiedNonAdmission(t *testing.T) { + t.Parallel() + puts, reads := 0, 0 + c := sequenceRawKVClient{ + put: func() error { + puts++ + if puts == 1 { + return publicMutationStatus(codes.Unavailable, "Route unavailable", publicGRPCNotAdmittedReason) + } + return nil + }, + get: func() []byte { reads++; return nil }, + } + require.NoError(t, putSequenceValue(t.Context(), c, []byte("key"), []byte("new"))) + require.Equal(t, 2, puts) + require.Zero(t, reads, "a certified non-admission is not an ambiguous write") +} + +func TestLeadershipRetryDoesNotTreatGenericStatusAsProof(t *testing.T) { + t.Parallel() + for _, err := range []error{ + status.Error(codes.Unavailable, "Route unavailable"), + status.Error(codes.Unknown, "grpc latest read: read fence: raft engine: leadership lost"), + publicMutationStatus(codes.Unknown, "Operation outcome unknown: not leader", publicGRPCUnknownReason), + publicMutationStatus(codes.Aborted, "Operation aborted", publicGRPCAbortedReason), + } { + require.False(t, isTransientNotLeaderErr(err)) + } +} + func Test_value_can_be_deleted(t *testing.T) { t.Parallel() nodes, adders, _ := createNode(t, 3) @@ -1263,12 +1403,7 @@ func Test_consistency_satisfy_write_after_read_sequence(t *testing.T) { break } - var resp *pb.RawGetResponse - err = retryNotLeader(ctx, func() error { - var gerr error - resp, gerr = c.RawGet(ctx, &pb.RawGetRequest{Key: key}) - return gerr - }) + resp, err := readSequenceValue(ctx, c, key) if !assert.NoError(t, err, "Get RPC failed") { break } diff --git a/adapter/grpc_transcoder_prop_test.go b/adapter/grpc_transcoder_prop_test.go index 5ace325a5..e4e12ff03 100644 --- a/adapter/grpc_transcoder_prop_test.go +++ b/adapter/grpc_transcoder_prop_test.go @@ -143,6 +143,8 @@ func applyOps(t interface { delete(mem, k) } } + case kv.CompareAndSwap: + require.FailNow(t, "unconditional transcoder produced a conditional operation") default: require.Fail(t, "unknown operation", "op=%v", elem.Op) } diff --git a/adapter/grpc_versioned_read_test.go b/adapter/grpc_versioned_read_test.go new file mode 100644 index 000000000..da0a7791e --- /dev/null +++ b/adapter/grpc_versioned_read_test.go @@ -0,0 +1,144 @@ +package adapter + +import ( + "context" + "testing" + "time" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/testutil/grpctest" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestGRPCVersionedPointReads(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + st := store.NewMVCCStore() + t.Cleanup(func() { require.NoError(t, st.Close()) }) + seedVersionReadCatalog(t, st, 1) + key := []byte("key") + require.NoError(t, st.PutAt(ctx, key, []byte("old"), 10, 0)) + require.NoError(t, st.PutAt(ctx, key, []byte{}, 20, 0)) + require.NoError(t, st.PutAt(ctx, []byte("other-key"), []byte("other"), 30, 0)) + engine := distribution.NewEngine() + require.NoError(t, engine.ApplySnapshot(distribution.CatalogSnapshot{ + Version: 1, + Routes: []distribution.RouteDescriptor{{RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}}, + })) + group := &kv.ShardGroup{Store: st, Engine: &localCompactionReadEngine{}} + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + shards := kv.NewShardStore(engine, map[uint64]*kv.ShardGroup{1: group}) + t.Cleanup(func() { require.NoError(t, shards.Close()) }) + server := NewGRPCServer(shards, &stubAdapterCoordinator{}) + addr := grpctest.Serve(t, func(grpcServer *grpc.Server) { + pb.RegisterRawKVServer(grpcServer, server) + pb.RegisterTransactionalKVServer(grpcServer, server) + }) + conn := grpctest.Dial(t, addr) + + txn := pb.NewTransactionalKVClient(conn) + got, err := txn.Get(ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, &pb.GetResponse_CommitTs{CommitTs: 20}, got.GetVersion()) + require.Empty(t, got.GetValue()) + + got, err = txn.Get(ctx, &pb.GetRequest{Key: []byte("missing"), NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, &pb.GetResponse_Missing{Missing: true}, got.GetVersion()) + got, err = txn.Get(ctx, &pb.GetRequest{Key: key}) + require.NoError(t, err) + require.Nil(t, got.GetVersion()) + + raw := pb.NewRawKVClient(conn) + latest, err := raw.RawGet(ctx, &pb.RawGetRequest{Key: key, NeedCommitTs: true}) + require.NoError(t, err) + require.True(t, latest.GetExists()) + require.Equal(t, &pb.RawGetResponse_CommitTs{CommitTs: 20}, latest.GetVersion()) + historical, err := raw.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: 15, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, &pb.RawGetResponse_CommitTs{CommitTs: 10}, historical.GetVersion()) + require.Equal(t, []byte("old"), historical.GetValue()) + empty, err := raw.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: 30, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, &pb.RawGetResponse_CommitTs{CommitTs: 20}, empty.GetVersion()) + require.True(t, empty.GetExists()) + require.Empty(t, empty.GetValue()) + missing, err := raw.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: 5, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, &pb.RawGetResponse_Missing{Missing: true}, missing.GetVersion()) + require.False(t, missing.GetExists()) + legacy, err := raw.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: 15}) + require.NoError(t, err) + require.Nil(t, legacy.GetVersion()) + require.Equal(t, []byte("old"), legacy.GetValue()) +} + +func TestGRPCVersionedPointReadRequiresVersionAwareRoute(t *testing.T) { + t.Parallel() + ctx := context.Background() + st := &recordingRawGroupStore{MVCCStore: store.NewMVCCStore()} + t.Cleanup(func() { require.NoError(t, st.Close()) }) + key := []byte("key") + require.NoError(t, st.PutAt(ctx, key, []byte("value"), 10, 0)) + server := NewGRPCServer(st, &stubAdapterCoordinator{}) + _, err := server.Get(ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.Equal(t, codes.Unimplemented, status.Code(err)) + _, err = server.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: 10, GroupId: 42, NeedCommitTs: true}) + require.Equal(t, codes.Unimplemented, status.Code(err)) + require.False(t, st.fallbackGet) + require.Zero(t, st.getGroupID) + + fenceErr := context.DeadlineExceeded + server = NewGRPCServer(st, &stubAdapterCoordinator{verifyLeaderErr: fenceErr}) + _, err = server.Get(ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) + require.ErrorIs(t, err, fenceErr) +} + +func TestGRPCVersionedRawGetHonorsExplicitGroup(t *testing.T) { + t.Parallel() + ctx := t.Context() + engine := distribution.NewEngine() + require.NoError(t, engine.ApplySnapshot(distribution.CatalogSnapshot{ + Version: 8, + Routes: []distribution.RouteDescriptor{{RouteID: 1, GroupID: 2, State: distribution.RouteStateActive}}, + })) + groups := map[uint64]*kv.ShardGroup{ + 1: {Store: store.NewMVCCStore()}, + 2: {Store: store.NewMVCCStore()}, + } + for _, group := range groups { + t.Cleanup(func() { require.NoError(t, group.Store.Close()) }) + } + groups[2].ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + seedVersionReadCatalog(t, groups[2].Store, 2) + st := kv.NewShardStore(engine, groups) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + key := []byte("key") + require.NoError(t, groups[1].Store.PutAt(ctx, key, []byte("routed"), 10, 0)) + require.NoError(t, groups[2].Store.PutAt(ctx, key, []byte("explicit"), 20, 0)) + server := NewGRPCServer(st, nil) + + got, err := server.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: 30, GroupId: 2, ReadRouteVersion: 8, NeedCommitTs: true}) + require.NoError(t, err) + require.Equal(t, &pb.RawGetResponse_CommitTs{CommitTs: 20}, got.GetVersion()) + require.Equal(t, []byte("explicit"), got.GetValue()) + + _, err = server.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: 30, GroupId: 1, ReadRouteVersion: 8, NeedCommitTs: true}) + require.Equal(t, codes.Unimplemented, status.Code(err)) +} + +func seedVersionReadCatalog(t *testing.T, st store.MVCCStore, groupID uint64) { + t.Helper() + plan, err := distribution.NewCatalogStore(st).BuildBootstrapPlanAt(t.Context(), 1, []distribution.Route{ + {GroupID: groupID, State: distribution.RouteStateActive}, + }) + require.NoError(t, err) + require.NoError(t, st.ApplyMutationsRaftAtFenced(t.Context(), plan.Mutations, plan.ReadKeys, 1, 2, 0)) +} diff --git a/adapter/internal.go b/adapter/internal.go index b760baaf2..d86567849 100644 --- a/adapter/internal.go +++ b/adapter/internal.go @@ -205,6 +205,8 @@ type Internal struct { migrationPartitionProtocolReady func() bool migrationNamespaceReady func() bool transferSizeReady func() bool + casForwardRoute func(context.Context, uint64, []byte) error + casForwardGroup uint64 routeEngine *distribution.Engine readTracker *kv.ActiveTimestampTracker migrationExportGroupID uint64 @@ -254,19 +256,36 @@ const ( ) func (i *Internal) Forward(ctx context.Context, req *pb.ForwardRequest) (*pb.ForwardResponse, error) { + if kv.HasCASMutation(req.GetRequests()) { + return nil, errors.WithStack(kv.VersionCASForwardUnavailable(kv.ErrVersionCASUnavailable)) + } + return i.forwardRequests(ctx, req) +} + +func (i *Internal) preflightForwardRequests(ctx context.Context, req *pb.ForwardRequest) error { // Before the leader check, so a non-leader gets the accurate reason and a // leader can never reach stampTimestamps and propose. if i.kvForwardRejected { - return nil, forwardStatusForReceiver(req, ErrKVForwardNotSupported, false) + return forwardStatusForReceiver(req, ErrKVForwardNotSupported, false) + } + if err := i.preflightForwardCAS(ctx, req); err != nil { + return err } if i.leader == nil || i.leader.State() != raftengine.StateLeader { - return nil, forwardStatusForReceiver(req, kv.ErrLeaderNotFound, false) + return forwardStatusForReceiver(req, kv.ErrLeaderNotFound, false) } if err := i.leader.VerifyLeader(ctx); err != nil { - return nil, forwardStatusForReceiver(req, err, false) + return forwardStatusForReceiver(req, err, false) } if err := rejectUnactivatedBoundForward(req.GetRequests()); err != nil { - return nil, forwardStatusForReceiver(req, err, false) + return forwardStatusForReceiver(req, err, false) + } + return nil +} + +func (i *Internal) forwardRequests(ctx context.Context, req *pb.ForwardRequest) (*pb.ForwardResponse, error) { + if err := i.preflightForwardRequests(ctx, req); err != nil { + return nil, err } commitTS, err := i.stampTimestamps(ctx, req) @@ -281,6 +300,9 @@ func (i *Internal) Forward(ctx context.Context, req *pb.ForwardRequest) (*pb.For } r, err := i.transactionManager.Commit(ctx, req.Requests) + if errors.Is(err, kv.ErrVersionCASUnavailable) && !errors.Is(err, kv.ErrTransactionOutcomeUnknown) { + return nil, errors.WithStack(kv.VersionCASForwardUnavailable(err)) + } if err != nil { return &pb.ForwardResponse{ Success: false, @@ -308,10 +330,24 @@ func forwardStatusForReceiver(req *pb.ForwardRequest, err error, commitAttempt b if commitAttempt { return forwardCommitStatus(req.GetRequests(), err) } + if _, shapeErr := kv.ForwardCASMutation(req.GetRequests()); shapeErr == nil && + (errors.Is(err, kv.ErrLeaderNotFound) || errors.Is(err, raftengine.ErrNotLeader)) { + return &forwardWireFailure{ + wire: kv.ForwardDecisionStatus(pb.ForwardFailurePhase_FORWARD_FAILURE_PHASE_ONE_PHASE_APPLY, + pb.ForwardFailureReason_FORWARD_FAILURE_REASON_NO_LEADER, + pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION), + cause: err, + } + } return forwardUnknownStatus(req.GetRequests(), err) } func forwardCommitStatus(reqs []*pb.Request, err error) error { + if kv.HasCASMutation(reqs) && kv.ValidateCASProposalShape(reqs) == nil && kv.IsCertifiedCASPrecheckMismatch(err) { + return &forwardWireFailure{wire: kv.ForwardDecisionStatus(pb.ForwardFailurePhase_FORWARD_FAILURE_PHASE_ONE_PHASE_APPLY, + pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH, + pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION), cause: err} + } phase, ok := kv.ForwardFailurePhaseForRequests(reqs) if ok { if reason, definitive := indexedForwardRejection(reqs, phase, err); definitive { @@ -321,6 +357,36 @@ func forwardCommitStatus(reqs []*pb.Request, err error) error { return forwardUnknownStatus(reqs, err) } +func forwardApplyRejectionReason(reqs []*pb.Request, err error) pb.ForwardFailureReason { + conflict := errors.Is(err, store.ErrWriteConflict) + fence := errors.Is(err, kv.ErrRouteWriteFenced) || errors.Is(err, kv.ErrRouteCutoverPending) + switch { + case conflict && fence: + return pb.ForwardFailureReason_FORWARD_FAILURE_REASON_UNSPECIFIED + case conflict: + return pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CONFLICT + case fence: + return pb.ForwardFailureReason_FORWARD_FAILURE_REASON_FENCE + } + return forwardCASRejectionReason(reqs, err) +} + +func forwardCASRejectionReason(reqs []*pb.Request, err error) pb.ForwardFailureReason { + var reason pb.ForwardFailureReason + switch { + case errors.Is(err, kv.ErrTxnLocked): + reason = pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_LOCKED + case errors.Is(err, kv.ErrCASMismatch): + reason = pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH + default: + return pb.ForwardFailureReason_FORWARD_FAILURE_REASON_UNSPECIFIED + } + if !kv.HasCASMutation(reqs) || kv.ValidateCASProposalShape(reqs) != nil { + return pb.ForwardFailureReason_FORWARD_FAILURE_REASON_UNSPECIFIED + } + return reason +} + // Only a terminal, indexed result for this eligible invocation can establish // noncommit. Joined errors and missing receipts remain indeterminate. func indexedForwardRejection(reqs []*pb.Request, phase pb.ForwardFailurePhase, err error) (pb.ForwardFailureReason, bool) { @@ -331,15 +397,8 @@ func indexedForwardRejection(reqs []*pb.Request, phase pb.ForwardFailurePhase, e if !errors.As(err, &rejected) || rejected.CommitIndex() == 0 { return 0, false } - conflict := errors.Is(err, store.ErrWriteConflict) - fence := errors.Is(err, kv.ErrRouteWriteFenced) || errors.Is(err, kv.ErrRouteCutoverPending) - if conflict == fence { - return 0, false - } - if conflict { - return pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CONFLICT, true - } - return pb.ForwardFailureReason_FORWARD_FAILURE_REASON_FENCE, true + reason := forwardApplyRejectionReason(reqs, err) + return reason, reason != pb.ForwardFailureReason_FORWARD_FAILURE_REASON_UNSPECIFIED } func forwardUnknownStatus(reqs []*pb.Request, err error) error { @@ -386,7 +445,7 @@ func (i *Internal) ProbeMigrationState(ctx context.Context, req *pb.ProbeMigrati } // A control read from an old configuration must never be stamped with a // newer configuration after the store read completes. - configurationBoundControl := req.GetRequireConfigurationIndex() && req.GetKind() == pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_CONTROL_APPLIED + configurationBoundControl := configurationBoundMigrationProbe(req) var controlConfiguration uint64 if configurationBoundControl { controlConfiguration = i.migrationAppliedConfigurationIndex() @@ -396,6 +455,9 @@ func (i *Internal) ProbeMigrationState(ctx context.Context, req *pb.ProbeMigrati return nil, err } i.decorateOnlineMigrationProbe(ctx, req, resp) + if err := i.decorateVersionAdoptionProbe(ctx, resp); err != nil { + return nil, err + } resp.NamespaceAdmissionVersion = i.migrationNamespaceProtocolVersion() i.decorateMigrationTransferCapability(req, resp) i.bindMigrationProbeConfiguration(req, resp) @@ -405,6 +467,10 @@ func (i *Internal) ProbeMigrationState(ctx context.Context, req *pb.ProbeMigrati return resp, nil } +func configurationBoundMigrationProbe(req *pb.ProbeMigrationStateRequest) bool { + return req.GetRequireConfigurationIndex() && (req.GetKind() == pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_CONTROL_APPLIED || req.GetKind() == pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS) +} + func (i *Internal) decorateMigrationTransferCapability(req *pb.ProbeMigrationStateRequest, resp *pb.ProbeMigrationStateResponse) { if req.GetKind() == pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_NAMESPACE_ADMISSION { resp.OwnershipPartitionProtocol = i.implementedPartitionProtocol() @@ -452,6 +518,9 @@ func migrationProbeConfigurationMatches(req *pb.ProbeMigrationStateRequest, resp } func (i *Internal) probeMigrationStateKind(ctx context.Context, req *pb.ProbeMigrationStateRequest) (*pb.ProbeMigrationStateResponse, error) { + if req.GetKind() == pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS { + return i.reclaimMigrationRetirement(ctx, req) + } if req.GetKind() == pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_NAMESPACE_ADMISSION { return i.probeMigrationNamespace(ctx, req) } @@ -474,6 +543,7 @@ func (i *Internal) probeLegacyMigrationStateKind(ctx context.Context, req *pb.Pr case pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_OWNERSHIP_CAPABILITY, pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_OWNERSHIP_APPLIED, pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_NAMESPACE_ADMISSION, + pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS, pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_PARTITION_APPLIED: return i.probeMigrationStateKind(ctx, req) case pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_CONTROL_APPLIED: @@ -1119,6 +1189,7 @@ func (i *Internal) CleanupMigration(ctx context.Context, req *pb.CleanupMigratio return nil, errors.WithStack(err) } return &pb.CleanupMigrationResponse{ + RetirementId: result.RetirementID, NextCursor: result.NextCursor, Done: result.Done, DeletedRows: result.DeletedRows, diff --git a/adapter/internal_compare_and_swap.go b/adapter/internal_compare_and_swap.go new file mode 100644 index 000000000..4c8872363 --- /dev/null +++ b/adapter/internal_compare_and_swap.go @@ -0,0 +1,41 @@ +package adapter + +import ( + "context" + + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// WithInternalCASForwardRouting binds CAS forwarding to the group served by +// this endpoint and checks that group's applied catalog. +func WithInternalCASForwardRouting(groupID uint64, check func(context.Context, uint64, []byte) error) InternalOption { + return func(i *Internal) { + i.casForwardGroup = groupID + i.casForwardRoute = check + } +} + +func (i *Internal) preflightForwardCAS(ctx context.Context, req *pb.ForwardRequest) error { + reqs := req.GetRequests() + if !kv.HasCASMutation(reqs) { + return nil + } + mut, err := kv.ForwardCASMutation(reqs) + if err != nil || !req.GetIsTxn() { + return errors.WithStack(status.Error(codes.InvalidArgument, "invalid forwarded compare-and-swap")) + } + if i.casForwardGroup != reqs[0].GetVersionCasGroupId() || i.casForwardRoute == nil { + return errors.WithStack(kv.VersionCASForwardUnavailable(kv.ErrVersionCASUnavailable)) + } + if len(reqs[0].GetWriteFenceBypassKeys()) != 0 { + return errors.WithStack(status.Error(codes.PermissionDenied, "compare-and-swap write fence bypass is unauthorized")) + } + if err := i.casForwardRoute(ctx, i.casForwardGroup, mut.Key); err != nil { + return errors.WithStack(kv.VersionCASForwardUnavailable(err)) + } + return nil +} diff --git a/adapter/migration_resplit_acceptance_test.go b/adapter/migration_resplit_acceptance_test.go index 611a8562b..5db6b45ee 100644 --- a/adapter/migration_resplit_acceptance_test.go +++ b/adapter/migration_resplit_acceptance_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" + "google.golang.org/protobuf/proto" ) // The existing runtime client executes real Internal/FSM/store commands, not @@ -134,17 +135,40 @@ func (r *resplitAcceptanceRuntime) migrate(t *testing.T, route, target uint64, s started, err := r.client.StartSplitMigration(t.Context(), &pb.StartSplitMigrationRequest{ ExpectedCatalogVersion: snapshot.Version, RouteId: route, TargetGroupId: target, SplitKey: []byte(split)}) require.NoError(t, err) + parent, found := findRouteByID(snapshot.Routes, route) + require.True(t, found) + source := r.clients[parent.GroupID] + var previous distribution.SplitJob + var replay *pb.ExportRangeVersionsRequest for range 200 { - require.NoError(t, r.server.RunSplitJobRunnerOnce(t.Context())) - job, found, loadErr := r.server.catalog.SplitJob(t.Context(), started.GetJobId()) - require.NoError(t, loadErr) - require.True(t, found) + exports := len(source.exports) + err := r.server.RunSplitJobRunnerOnce(t.Context()) + job := loadTransferJob(t, t.Context(), r.server.catalog, started.GetJobId()) + // The service retries a bounded member RPC on a fresh tick. Only + // allow that recovery from an intact, initialized preflight batch. + if replay == nil && splitPreflightIncomplete(previous) && previous.TransferPreflightTS != 0 && errors.Is(err, context.DeadlineExceeded) { + require.NoError(t, t.Context().Err()) + require.ErrorContains(t, err, "transfer guard member voter:") + require.Greater(t, len(source.exports), exports, "member probe must follow a preflight export") + require.True(t, distribution.SplitJobsEquivalent(previous, job), "expired probe advanced the durable job") + t.Logf("retrying preflight from its unchanged checkpoint: %s", err) + replay = source.exports[exports] + continue + } + require.NoError(t, err) + if replay != nil { + require.Greater(t, len(source.exports), exports) + require.True(t, proto.Equal(replay, source.exports[exports]), "retry must replay the uncheckpointed page") + require.True(t, preflightCheckpointChanged(previous, job) || job.TransferPreflightDone, "fresh tick must advance preflight") + replay = nil + } for _, check := range afterTick { check(job) } if job.Phase == distribution.SplitJobPhaseDone { return job } + previous = job } t.Fatal("bounded runner did not finish migration") return distribution.SplitJob{} diff --git a/adapter/migration_retirement.go b/adapter/migration_retirement.go new file mode 100644 index 000000000..d00820031 --- /dev/null +++ b/adapter/migration_retirement.go @@ -0,0 +1,122 @@ +package adapter + +import ( + "context" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" +) + +func (i *Internal) decorateVersionAdoptionProbe(ctx context.Context, response *pb.ProbeMigrationStateResponse) error { + active, err := kv.MigrationVersionAdoptionEnabled(ctx, i.store) + if err != nil || !active { + return errors.WithStack(err) + } + retirement, ok := i.store.(store.VersionRetirementStore) + if !ok { + return errors.WithStack(store.ErrVersionRetirementUnavailable) + } + if err := retirement.VersionAdoptionReady(ctx); err != nil { + return errors.WithStack(err) + } + response.VersionAdoptionActive = true + return nil +} + +func (s *DistributionServer) prepareSplitVersionAdoption(ctx context.Context, job distribution.SplitJob, promotion SplitPromotionClient) error { + // Legacy promotion-only implementations do not activate the new row format. + client, ok := promotion.(SplitMigrationClient) + if !ok { + return nil + } + attempt, cancel := splitPromotionAttemptContext(ctx) + response, err := client.ProbeMigrationState(attempt, &pb.ProbeMigrationStateRequest{ + JobId: job.JobID, Kind: pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_OWNERSHIP_CAPABILITY, + RequireConfigurationIndex: true, + }) + cancel() + if err != nil { + return errors.WithStack(err) + } + if !response.GetVersionAdoptionActive() { + return nil + } + if !response.GetReady() || response.GetAppliedConfigurationIndex() == 0 { + return errors.WithStack(errSplitMigrationVoterBarrierIncomplete) + } + return s.applySplitOwnership(ctx, job, job.TargetGroupID, client, + pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_OWNERSHIP_ACQUIRE, response.GetAppliedConfigurationIndex()) +} + +func (s *DistributionServer) cleanupAndConfirmSplitSource(ctx context.Context, job distribution.SplitJob, source SplitMigrationClient, req *pb.CleanupMigrationRequest) (*pb.CleanupMigrationResponse, error) { + resp, err := cleanupSplitMigration(ctx, source, req) + if err != nil { + return nil, err + } + if err := s.confirmSplitSourceRetirement(ctx, job, req, resp); err != nil { + return nil, err + } + return resp, nil +} + +func (s *DistributionServer) confirmSplitSourceRetirement(ctx context.Context, job distribution.SplitJob, req *pb.CleanupMigrationRequest, resp *pb.CleanupMigrationResponse) error { + if !resp.GetDone() || resp.GetRetirementId() == "" { + return nil + } + groupID, err := s.splitJobSourceGroupID(ctx, job) + if err != nil { + return err + } + return s.confirmMigrationRetirement(ctx, groupID, job.JobID, req.GetExpectedConfigurationIndex(), resp.GetRetirementId()) +} + +func (i *Internal) reclaimMigrationRetirement(ctx context.Context, req *pb.ProbeMigrationStateRequest) (*pb.ProbeMigrationStateResponse, error) { + index := i.migrationAppliedConfigurationIndex() + response := &pb.ProbeMigrationStateResponse{AppliedConfigurationIndex: index} + if !req.GetRequireConfigurationIndex() || index == 0 || index != req.GetExpectedConfigurationIndex() { + return response, nil + } + retirement, ok := i.store.(store.VersionRetirementStore) + if !ok || req.GetRetirementId() == "" { + return response, nil + } + result, err := retirement.ReclaimVersionRetirement(ctx, req.GetJobId(), req.GetRetirementId()) + if err != nil { + return nil, errors.WithStack(err) + } + response.Ready = result.Done + return response, nil +} + +// Each ACK is local physical absence for the exact committed retirement, not +// a leader page count. Include learners and revalidate the full roster after +// the probes. No persisted leader cursor substitutes for a fresh member ACK. +func (s *DistributionServer) confirmMigrationRetirement(ctx context.Context, groupID, jobID, configuration uint64, id string) error { + if id == "" { + return nil // Legacy cleanup, or an already-private staging namespace. + } + members, err := s.splitTransferApplyMembers(ctx, groupID) + if err != nil { + return err + } + if members.ConfigurationIndex != configuration { + return errors.WithStack(errSplitMigrationVoterBarrierIncomplete) + } + req := &pb.ProbeMigrationStateRequest{ + JobId: jobID, Kind: pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS, + RetirementId: id, RequireConfigurationIndex: true, ExpectedConfigurationIndex: configuration, + } + complete := true + for _, member := range members.Members { + ack := probeSplitMigrationVoter(ctx, member, req) + complete = complete && ack.acked + } + if !complete { + return errors.WithStack(errSplitMigrationVoterBarrierIncomplete) + } + _, err = s.revalidateSplitTransferMembers(ctx, &splitTransferAdmissionWitness{groupID: groupID, snapshot: members}) + return err +} diff --git a/adapter/migration_version_retirement_completion_test.go b/adapter/migration_version_retirement_completion_test.go new file mode 100644 index 000000000..3b3839f33 --- /dev/null +++ b/adapter/migration_version_retirement_completion_test.go @@ -0,0 +1,80 @@ +package adapter + +import ( + "context" + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func TestMigrationRetirementCompletionIncludesLearnersAndRevalidatesRoster(t *testing.T) { + learnerReady := false + configuration := uint64(9) + var probed []string + peer := func(id string, ready func() bool) SplitMigrationVoter { + return SplitMigrationVoter{ID: id, Address: id + ":1", Client: &splitMigrationClientStub{probeFn: func(req *pb.ProbeMigrationStateRequest) (*pb.ProbeMigrationStateResponse, error) { + probed = append(probed, id) + require.Equal(t, pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS, req.GetKind()) + require.Equal(t, "committed-retirement", req.GetRetirementId()) + require.Equal(t, uint64(11), req.GetJobId()) + return &pb.ProbeMigrationStateResponse{Ready: ready(), AppliedConfigurationIndex: 9}, nil + }}} + } + members := []SplitMigrationVoter{peer("voter", func() bool { return true }), peer("learner", func() bool { return learnerReady })} + reads := 0 + changeRoster := false + s := &DistributionServer{splitApplyMemberFactory: func(context.Context, uint64) (SplitMigrationApplyMemberSnapshot, error) { + reads++ + if changeRoster && reads > 1 { + configuration++ + } + return SplitMigrationApplyMemberSnapshot{ConfigurationIndex: configuration, Members: members}, nil + }} + err := s.confirmMigrationRetirement(t.Context(), 1, 11, 9, "committed-retirement") + require.ErrorIs(t, err, errSplitMigrationVoterBarrierIncomplete) + require.ElementsMatch(t, []string{"voter", "learner"}, probed) + learnerReady = true + require.NoError(t, s.confirmMigrationRetirement(t.Context(), 1, 11, 9, "committed-retirement")) + reads, changeRoster = 0, true + require.ErrorContains(t, s.confirmMigrationRetirement(t.Context(), 1, 11, 9, "committed-retirement"), "configuration changed") +} + +type reclaimProbeStore struct { + store.MVCCStore + store.VersionRetirementStore + calls int + after func() +} + +func (s *reclaimProbeStore) ReclaimVersionRetirement(context.Context, uint64, string) (store.CleanupVersionsResult, error) { + s.calls++ + if s.after != nil { + s.after() + } + return store.CleanupVersionsResult{Done: true}, nil +} + +func TestMigrationRetirementProbeRejectsWrongAndChangingConfiguration(t *testing.T) { + st := &reclaimProbeStore{MVCCStore: store.NewMVCCStore()} + i := NewInternalWithEngine(nil, migrationConfigurationLeader{index: 9}, nil, nil, WithInternalStore(st)) + req := &pb.ProbeMigrationStateRequest{JobId: 11, RetirementId: "retirement", + Kind: pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS, + RequireConfigurationIndex: true, ExpectedConfigurationIndex: 8} + resp, err := i.ProbeMigrationState(t.Context(), req) + require.NoError(t, err) + require.False(t, resp.GetReady()) + require.Zero(t, st.calls) + req.ExpectedConfigurationIndex = 9 + st.after = func() { i.leader = migrationConfigurationLeader{index: 10} } + resp, err = i.ProbeMigrationState(t.Context(), req) + require.NoError(t, err) + require.False(t, resp.GetReady()) + require.Equal(t, 1, st.calls) + st.after = nil + req.ExpectedConfigurationIndex = 10 + resp, err = i.ProbeMigrationState(t.Context(), req) + require.NoError(t, err) + require.True(t, resp.GetReady()) +} diff --git a/adapter/migration_version_retirement_moveback_test.go b/adapter/migration_version_retirement_moveback_test.go new file mode 100644 index 000000000..99cc8d36b --- /dev/null +++ b/adapter/migration_version_retirement_moveback_test.go @@ -0,0 +1,67 @@ +package adapter + +import ( + "testing" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func TestMigrationRetirementMoveBackPreservesUnchangedVersions(t *testing.T) { + r := newResplitAcceptanceRuntime(t) + for _, client := range r.clients { + proposer, ok := client.internal.migrationProposer.(*ownershipRuntimeProposer) + require.True(t, ok) + result, err := proposer.Propose(t.Context(), kv.EncodeMigrationVersionIdentityActivation()) + require.NoError(t, err) + require.Nil(t, result.Response) + } + first := r.migrate(t, 1, 2, "m") + r.migrate(t, r.ownership(t, 2)[0].RouteID, 3, "t") + returned := r.migrate(t, r.ownership(t, 3)[0].RouteID, 1, "x") + r.read(t, "n", "original-n") + r.read(t, "y", "original-y") + row, err := store.GetVersionAt(t.Context(), r.groups[1].Store, []byte("y"), ^uint64(0)) + require.NoError(t, err) + require.Equal(t, uint64(10), row.TS) + reader, ok := r.clients[1].internal.leader.(interface{ AppliedConfigurationIndex() (uint64, bool) }) + require.True(t, ok) + configuration, supported := reader.AppliedConfigurationIndex() + require.True(t, supported) + for _, req := range []*pb.CleanupMigrationRequest{ + {JobId: first.JobID, ExpectedSourceGroupId: 1}, + {JobId: returned.JobID, ExpectedSourceGroupId: 3}, + } { + req.Mode, req.RangeStart, req.RangeEnd = pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, []byte("x"), []byte("z") + req.RequireConfigurationIndex, req.ExpectedConfigurationIndex, req.MaxCommitTs = true, configuration, returned.FenceTS + _, err = r.clients[1].CleanupMigration(t.Context(), req) + require.Error(t, err, "an old job or a wrong-source cleanup cannot retire the returning owner") + r.read(t, "y", "original-y") + } + // Online migration requires a fresh target group, not merely an empty + // moving interval. Group 2 still owns n; group 3's old y is retired. + r.migrate(t, moveBackOwnerRoute(t, r, 1), 3, "xx") + returned = r.migrate(t, moveBackOwnerRoute(t, r, 3), 1, "xxx") + r.read(t, "y", "original-y") + row, err = store.GetVersionAt(t.Context(), r.groups[1].Store, []byte("y"), ^uint64(0)) + require.NoError(t, err) + require.Equal(t, uint64(10), row.TS, "repeat return must not manufacture a timestamp") + require.NoError(t, r.put(t, 1, "y", "returned-generation", returned.FenceTS+100)) + r.read(t, "y", "returned-generation") +} + +func moveBackOwnerRoute(t *testing.T, r *resplitAcceptanceRuntime, groupID uint64) uint64 { + t.Helper() + snapshot, err := r.server.catalog.Snapshot(t.Context()) + require.NoError(t, err) + for _, route := range snapshot.Routes { + if route.GroupID == groupID && route.State == distribution.RouteStateActive && splitOwnershipRouteContains(route, []byte("y")) { + return route.RouteID + } + } + t.Fatal("current owner route not found") + return 0 +} diff --git a/adapter/mvcc_cas_benchmark_test.go b/adapter/mvcc_cas_benchmark_test.go new file mode 100644 index 000000000..43bed7898 --- /dev/null +++ b/adapter/mvcc_cas_benchmark_test.go @@ -0,0 +1,1216 @@ +package adapter + +import ( + "bytes" + "cmp" + "context" + "encoding/binary" + "fmt" + "net" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + etcdraftengine "github.com/bootjp/elastickv/internal/raftengine/etcd" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/proto" +) + +const ( + casBenchService = "benchmark.FencedOnePhase" + casBenchPrefix = "/" + casBenchService + "/" + casBenchHandle = "bench-handle" + casBenchClient = "bench-client" + casBenchMeasure = "bench-measure" + casBenchPinTTL = 5 * time.Second +) + +type casBenchMeter struct { + proposals, completed, readFences, verifyLeader atomic.Uint64 + preReads, passedPrechecks, handlePinNS atomic.Uint64 + handleExpirations, casAdmissions, readAdmissions atomic.Uint64 + applyVerdicts sync.Map // typed apply reason -> *atomic.Uint64 + rpcs sync.Map // method -> *atomic.Uint64 + gate chan casBenchParked +} + +type casBenchParked struct { + commitTS uint64 + client int + release chan struct{} + done chan struct{} +} + +type casBenchMeterKey struct{} + +func casBenchMeasured(ctx context.Context) *casBenchMeter { + meter, _ := ctx.Value(casBenchMeterKey{}).(*casBenchMeter) + return meter +} + +// Embed the real engine so optional leases, serving checks and apply +// capabilities remain available to the production paths. +type casBenchEngine struct { + *etcdraftengine.Engine +} + +func (e *casBenchEngine) Propose(ctx context.Context, data []byte) (*raftengine.ProposalResult, error) { + m := casBenchMeasured(ctx) + if m == nil { + return e.Engine.Propose(ctx, data) + } + if m.gate != nil { + parked, err := m.parkProposal(ctx, data) + if err != nil { + return nil, err + } + defer close(parked.done) + } + m.proposals.Add(1) + res, err := e.Engine.Propose(ctx, data) + if err == nil && res != nil { + m.completed.Add(1) + casBenchIncrement(&m.applyVerdicts, casBenchApplyVerdict(res.Response)) + } + return res, err +} + +func (m *casBenchMeter) parkProposal(ctx context.Context, data []byte) (casBenchParked, error) { + parked := casBenchParked{release: make(chan struct{}), done: make(chan struct{})} + // The single-request Raft encoding is one tag byte followed by Request. + // Parse only in the diagnostic trial, never in the benchmark. + req, err := casBenchDecodeProposal(data) + if err != nil || len(req.GetMutations()) == 0 { + return casBenchParked{}, errors.New("parked trial requires one stamped 1PC request") + } + meta, err := kv.DecodeTxnMeta(req.GetMutations()[0].GetValue()) + if err != nil || meta.CommitTS == 0 { + return casBenchParked{}, errors.New("parked trial could not find the 1PC commit timestamp") + } + parked.commitTS = meta.CommitTS + md, _ := metadata.FromIncomingContext(ctx) + parked.client, err = strconv.Atoi(casBenchMD(md, casBenchClient)) + if err != nil { + return casBenchParked{}, err + } + select { + case m.gate <- parked: + case <-ctx.Done(): + return casBenchParked{}, ctx.Err() + } + select { + case <-parked.release: + case <-ctx.Done(): + return casBenchParked{}, ctx.Err() + } + return parked, nil +} + +func casBenchIncrement(counts *sync.Map, key string) { + counter, ok := counts.Load(key) + if !ok { + counter, _ = counts.LoadOrStore(key, new(atomic.Uint64)) + } + casBenchCounter(counter).Add(1) +} + +func casBenchCounter(value any) *atomic.Uint64 { + counter, ok := value.(*atomic.Uint64) + if !ok { + panic("invalid CAS benchmark counter") + } + return counter +} + +func casBenchRangeCounters(counts *sync.Map, visit func(string, uint64)) { + counts.Range(func(key, value any) bool { + name, ok := key.(string) + if !ok { + panic("invalid CAS benchmark counter name") + } + visit(name, casBenchCounter(value).Load()) + return true + }) +} + +// Record typed FSM verdicts before the public RPC projects its error details. +func casBenchApplyVerdict(response any) string { + if response == nil { + return "success" + } + err, ok := response.(error) + if !ok { + return "other" + } + switch { + case errors.Is(err, kv.ErrCASMismatch): + return "exact_mismatch" + case errors.Is(err, kv.ErrTxnLocked): + return "locked" + case errors.Is(err, kv.ErrRouteWriteFenced): + return "route_fenced" + case errors.Is(err, store.ErrWriteConflict): + return "write_conflict" + default: + return "other" + } +} + +func casBenchDecodeProposal(data []byte) (*pb.Request, error) { + if raftengine.IsVersionCASRaftPayload(data) { + return kv.DecodeVersionCASRaftPayload(data) + } + req := new(pb.Request) + if len(data) < 2 || data[0] != 0 { + return nil, errors.New("expected a single 1PC request") + } + return req, proto.Unmarshal(data[1:], req) +} + +func (e *casBenchEngine) LinearizableRead(ctx context.Context) (uint64, error) { + if m := casBenchMeasured(ctx); m != nil { + m.readFences.Add(1) + } + return e.Engine.LinearizableRead(ctx) +} + +func (e *casBenchEngine) VerifyLeader(ctx context.Context) error { + if m := casBenchMeasured(ctx); m != nil { + m.verifyLeader.Add(1) + } + return e.Engine.VerifyLeader(ctx) +} + +// Handle lifetime belongs to the load-generator session. The acquisition +// RPC's context ends with its reply, so its read pin is handed off separately. +type casBenchPin struct { + client, key string + startTS, version uint64 + started time.Time + release func() + timer *time.Timer + meter *casBenchMeter +} + +type casBenchControl struct { + coord *kv.ShardedCoordinator + shards *kv.ShardStore + tracker *kv.ActiveTimestampTracker + pinTTL time.Duration + + mu sync.Mutex + next uint64 + pins map[string]*casBenchPin +} + +func casBenchMD(md metadata.MD, key string) string { + values := md.Get(key) + if len(values) == 1 { + return values[0] + } + return "" +} + +func (c *casBenchControl) read(ctx context.Context, key []byte, visit func(store.VersionedValue, uint64) error) error { + if m := casBenchMeasured(ctx); m != nil { + m.preReads.Add(1) + } + read := kv.NewReadRequest(ctx, c.coord, c.shards, c.tracker) + defer read.Close() + snapshot, err := read.Latest(read.Context(), "benchmark fenced 1PC", key) + if err != nil { + return err + } + version, err := read.GetVersion(read.Context(), snapshot, key) + if err != nil { + return err + } + return visit(version, snapshot.Timestamp()) +} + +func (c *casBenchControl) issue(ctx context.Context, key []byte, startTS, version uint64) error { + md, _ := metadata.FromIncomingContext(ctx) + client := casBenchMD(md, casBenchClient) + if client == "" { + return status.Error(codes.InvalidArgument, "missing benchmark client") + } + if err := ctx.Err(); err != nil { + return err + } + c.mu.Lock() + c.next++ + id := strconv.FormatUint(c.next, 10) + pin := &casBenchPin{ + client: client, key: string(key), startTS: startTS, version: version, + started: time.Now(), release: c.tracker.Pin(startTS).Release, meter: casBenchMeasured(ctx), + } + pin.timer = time.AfterFunc(c.pinTTL, func() { + c.mu.Lock() + defer c.mu.Unlock() + if c.pins[id] != nil { + c.release(id, pin) + if pin.meter != nil { + pin.meter.handleExpirations.Add(1) + } + } + }) + c.pins[id] = pin + c.mu.Unlock() + if err := grpc.SetHeader(ctx, metadata.Pairs(casBenchHandle, id)); err != nil { + c.mu.Lock() + c.release(id, pin) + c.mu.Unlock() + return err + } + return nil +} + +// release is called under mu. Only the caller that removes the live handle +// observes the lifetime and releases the pin. +func (c *casBenchControl) release(id string, pin *casBenchPin) { + if c.pins[id] != pin { + return + } + delete(c.pins, id) + pin.timer.Stop() + pin.release() + if pin.meter != nil { + pin.meter.handlePinNS.Add(uint64(time.Since(pin.started))) + } +} + +func (c *casBenchControl) take(ctx context.Context, req *pb.CompareAndSwapRequest) (*casBenchPin, error) { + md, _ := metadata.FromIncomingContext(ctx) + id := casBenchMD(md, casBenchHandle) + c.mu.Lock() + defer c.mu.Unlock() + pin := c.pins[id] + if pin == nil || pin.client != casBenchMD(md, casBenchClient) || pin.key != string(req.Key) || pin.version != req.ExpectedCommitTs { + return nil, status.Error(codes.FailedPrecondition, "invalid or expired benchmark handle") + } + if pin.meter == nil { + pin.meter = casBenchMeasured(ctx) + } + c.release(id, pin) + if time.Since(pin.started) >= c.pinTTL { + if pin.meter != nil { + pin.meter.handleExpirations.Add(1) + } + return nil, status.Error(codes.FailedPrecondition, "expired benchmark handle") + } + return pin, nil +} + +func (c *casBenchControl) acquire(ctx context.Context, req *pb.CompareAndSwapRequest) (*pb.GetResponse, error) { + resp := &pb.GetResponse{} + err := c.read(ctx, req.Key, func(v store.VersionedValue, startTS uint64) error { + resp.Value = v.Value + resp.Version = &pb.GetResponse_CommitTs{CommitTs: v.TS} + if req.ExpectedCommitTs != 0 && req.ExpectedCommitTs != v.TS { + return nil + } + if m := casBenchMeasured(ctx); m != nil { + m.passedPrechecks.Add(1) + } + return c.issue(ctx, req.Key, startTS, v.TS) + }) + return resp, err +} + +func casBenchMismatch() *pb.CompareAndSwapResponse { + return &pb.CompareAndSwapResponse{Result: &pb.CompareAndSwapResponse_Mismatch{Mismatch: true}} +} + +func (c *casBenchControl) submit(ctx context.Context, req *pb.CompareAndSwapRequest, startTS uint64) (*pb.CompareAndSwapResponse, error) { + reply, err := kv.DispatchWithLeaderIssuedCommitTS(ctx, c.coord, &kv.OperationGroup[kv.OP]{ + IsTxn: true, StartTS: startTS, ReadKeys: [][]byte{req.Key}, + Elems: []*kv.Elem[kv.OP]{{Op: kv.Put, Key: req.Key, Value: req.Value}}, + }) + if err != nil { + return nil, casBenchControlError(err) + } + return &pb.CompareAndSwapResponse{Result: &pb.CompareAndSwapResponse_NewCommitTs{NewCommitTs: reply.CommitTS}}, nil +} + +func casBenchControlError(err error) error { + switch { + case errors.Is(err, kv.ErrTransactionOutcomeUnknown): + return status.Error(codes.Unknown, "1PC submission outcome unknown") + case errors.Is(err, kv.ErrTxnLocked): + return status.Error(codes.Aborted, "1PC lock conflict") + case errors.Is(err, kv.ErrRouteWriteFenced), errors.Is(err, raftengine.ErrNotLeader): + return status.Error(codes.Unavailable, "1PC route or leadership rejection") + case errors.Is(err, store.ErrWriteConflict): + return status.Error(codes.Aborted, "1PC write conflict") + default: + return err + } +} + +func (c *casBenchControl) fresh(ctx context.Context, req *pb.CompareAndSwapRequest) (*pb.CompareAndSwapResponse, error) { + var start uint64 + err := c.read(ctx, req.Key, func(v store.VersionedValue, startTS uint64) error { + if v.TS == req.ExpectedCommitTs { + start = startTS + } + return nil + }) + if err != nil { + return nil, err + } + if start == 0 { + return casBenchMismatch(), nil + } + if m := casBenchMeasured(ctx); m != nil { + m.passedPrechecks.Add(1) + } + return c.submit(ctx, req, start) +} + +func (c *casBenchControl) commit(ctx context.Context, req *pb.CompareAndSwapRequest) (*pb.CompareAndSwapResponse, error) { + pin, err := c.take(ctx, req) + if err != nil { + return nil, err + } + return c.submit(ctx, req, pin.startTS) +} + +func (c *casBenchControl) cancel(ctx context.Context, req *pb.CompareAndSwapRequest) (*pb.CompareAndSwapResponse, error) { + _, err := c.take(ctx, req) + return &pb.CompareAndSwapResponse{}, err +} + +func casBenchMethod[T any](name string, call func(context.Context, *pb.CompareAndSwapRequest) (*T, error)) grpc.MethodDesc { + return grpc.MethodDesc{ + MethodName: name, + Handler: func(srv any, ctx context.Context, decode func(any) error, intercept grpc.UnaryServerInterceptor) (any, error) { + req := new(pb.CompareAndSwapRequest) + if err := decode(req); err != nil { + return nil, err + } + return intercept(ctx, req, &grpc.UnaryServerInfo{Server: srv, FullMethod: casBenchPrefix + name}, + func(ctx context.Context, req any) (any, error) { + request, ok := req.(*pb.CompareAndSwapRequest) + if !ok { + panic("invalid CAS benchmark request type") + } + return call(ctx, request) + }) + }, + } +} + +type casBenchFixture struct { + control *casBenchControl + conn *grpc.ClientConn + public pb.TransactionalKVClient + local store.MVCCStore + meter *casBenchMeter +} + +func casBenchLocalProof(ctx context.Context, engine *casBenchEngine, local store.MVCCStore) (context.Context, error) { + st := engine.Status() + cfg, err := engine.Configuration(ctx) + if err != nil { + return nil, err + } + if st.State != raftengine.StateLeader || st.Term == 0 || st.ConfigurationIndex == 0 || + st.PendingConfChange || !casBenchSingleVoter(cfg, st.Leader.ID) { + return nil, kv.ErrVersionCASUnavailable + } + active, err := kv.CommitTSFenceEnabled(ctx, local) + if err != nil || !active { + return nil, errors.Join(kv.ErrVersionCASUnavailable, err) + } + return raftengine.WithVersionCASProof(ctx, raftengine.VersionCASProof{ + Term: st.Term, ConfigurationIndex: st.ConfigurationIndex, + }), nil +} + +func casBenchSingleVoter(cfg raftengine.Configuration, leaderID string) bool { + return len(cfg.Servers) == 1 && cfg.Servers[0].ID == leaderID && + cfg.Servers[0].Suffrage == etcdraftengine.SuffrageVoter +} + +func newCASBenchFixture(t testing.TB, parked bool) *casBenchFixture { + t.Helper() + t.Setenv("ELASTICKV_FSM_SYNC_MODE", "sync") + routes := distribution.NewEngine() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}, + }})) + local, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, local.Close()) }) + hlc := kv.NewHLC() + tracker := kv.NewActiveTimestampTracker() + factory := etcdraftengine.NewFactory(etcdraftengine.FactoryConfig{ + TickInterval: 10 * time.Millisecond, HeartbeatTick: 1, ElectionTick: 10, + MaxSizePerMsg: 1 << 20, MaxInflightMsg: 256, + }) + node, err := factory.Create(raftengine.FactoryConfig{ + LocalID: "cas-bench-1", LocalAddress: "cas-bench-1", DataDir: t.TempDir(), Bootstrap: true, + StateMachine: kv.NewKvFSMWithHLCAndTracker(local, hlc, tracker, kv.WithRouteHistory(kv.WrapDistributionEngine(routes), 1), + kv.WithRaftBootstrapIdentity(raftbootstrap.UUID{1}, 1)), + }) + require.NoError(t, err) + t.Cleanup(func() { + require.NoError(t, node.Engine.Close()) + if node.Close != nil { + require.NoError(t, node.Close()) + } + }) + require.Eventually(t, func() bool { return node.Engine.State() == raftengine.StateLeader }, 5*time.Second, 10*time.Millisecond) + raft, ok := node.Engine.(*etcdraftengine.Engine) + require.True(t, ok, "unexpected benchmark engine type %T", node.Engine) + engine := &casBenchEngine{Engine: raft} + proxy := kv.NewLeaderProxyWithEngine(engine) + t.Cleanup(func() { require.NoError(t, proxy.Close()) }) + groups := map[uint64]*kv.ShardGroup{1: {Engine: engine, Store: local, Txn: proxy}} + shards := kv.NewShardStore(routes, groups) + coord := kv.NewShardedCoordinator(routes, groups, 1, hlc, shards) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + activation, err := engine.Propose(ctx, kv.EncodeCommitTSFenceActivation()) + require.NoError(t, err) + require.NotNil(t, activation) + require.Nil(t, activation.Response) + replicateCASFixtureCatalog(t, ctx, engine, local, 1) + active, err := kv.CommitTSFenceEnabled(ctx, local) + require.NoError(t, err) + require.True(t, active) + proofCtx, err := casBenchLocalProof(ctx, engine, local) + require.NoError(t, err) + identity, err := engine.Propose(proofCtx, kv.EncodeMigrationVersionIdentityActivation()) + require.NoError(t, err) + require.NotNil(t, identity) + require.Nil(t, identity.Response) + identityActive, err := kv.MigrationVersionIdentityEnabled(ctx, local) + require.NoError(t, err) + require.True(t, identityActive) + casBenchConfigureAdmission(engine, local, proxy, groups[1]) + require.NoError(t, coord.RecoverHLCLease(ctx)) + renewCtx, stopRenew := context.WithCancel(context.Background()) + renewDone := make(chan struct{}) + go func() { + defer close(renewDone) + coord.RunHLCLeaseRenewal(renewCtx) + }() + t.Cleanup(func() { stopRenew(); <-renewDone }) + + control := &casBenchControl{coord: coord, shards: shards, tracker: tracker, pinTTL: casBenchPinTTL, pins: make(map[string]*casBenchPin)} + t.Cleanup(func() { + control.mu.Lock() + defer control.mu.Unlock() + for id, pin := range control.pins { + control.release(id, pin) + } + }) + meter := &casBenchMeter{} + if parked { + meter.gate = make(chan casBenchParked) + } + conn := casBenchConnect(t, control, meter) + return &casBenchFixture{control: control, conn: conn, public: pb.NewTransactionalKVClient(conn), local: local, meter: meter} +} + +func casBenchAdmit(ctx context.Context, engine *casBenchEngine, local store.MVCCStore) (context.Context, error) { + owned, err := casBenchLocalProof(ctx, engine, local) + if err != nil { + return nil, err + } + active, err := kv.MigrationVersionIdentityEnabled(owned, local) + if err != nil || !active { + return nil, errors.Join(kv.ErrVersionCASUnavailable, err) + } + return owned, nil +} + +func casBenchConfigureAdmission(engine *casBenchEngine, local store.MVCCStore, proxy *kv.LeaderProxy, group *kv.ShardGroup) { + proxy.ConfigureVersionCASAdmission(func(ctx context.Context) (context.Context, error) { + if m := casBenchMeasured(ctx); m != nil { + m.casAdmissions.Add(1) + } + return casBenchAdmit(ctx, engine, local) + }) + group.ConfigureVersionReadAdmission(func(ctx context.Context) error { + if m := casBenchMeasured(ctx); m != nil { + m.readAdmissions.Add(1) + } + owned, err := casBenchAdmit(ctx, engine, local) + if err != nil { + return err + } + proof, _ := raftengine.VersionCASProposalProof(owned) + st := engine.Status() + if st.State != raftengine.StateLeader || st.Term != proof.Term || + st.ConfigurationIndex != proof.ConfigurationIndex || st.PendingConfChange { + return kv.ErrVersionCASUnavailable + } + return nil + }) +} + +func casBenchConnect(t testing.TB, control *casBenchControl, meter *casBenchMeter) *grpc.ClientConn { + t.Helper() + server := grpc.NewServer(grpc.UnaryInterceptor(func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) { + md, _ := metadata.FromIncomingContext(ctx) + if casBenchMD(md, casBenchMeasure) != "" { + ctx = context.WithValue(ctx, casBenchMeterKey{}, meter) + } + return next(ctx, req) + })) + public := NewGRPCServer(control.shards, control.coord) + public.readTracker = control.tracker + pb.RegisterTransactionalKVServer(server, public) + server.RegisterService(&grpc.ServiceDesc{ + ServiceName: casBenchService, HandlerType: (*interface{})(nil), + Methods: []grpc.MethodDesc{ + casBenchMethod("Acquire", control.acquire), casBenchMethod("Fresh", control.fresh), + casBenchMethod("Commit", control.commit), casBenchMethod("Cancel", control.cancel), + }, + }, control) + listener := bufconn.Listen(1 << 20) + go func() { _ = server.Serve(listener) }() + t.Cleanup(server.Stop) + conn, err := grpc.NewClient("passthrough:///cas-bench", + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }), + grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDisableRetry(), + grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, + invoke grpc.UnaryInvoker, opts ...grpc.CallOption) error { + md, _ := metadata.FromOutgoingContext(ctx) + if casBenchMD(md, casBenchMeasure) != "" { + casBenchIncrement(&meter.rpcs, method) + } + return invoke(ctx, method, req, reply, cc, opts...) + })) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, conn.Close()) }) + return conn +} + +type casBenchArm string + +const ( + casBenchCAS casBenchArm = "CAS" + casBenchFresh casBenchArm = "Fresh" + casBenchTwoCall casBenchArm = "TwoCall" + casBenchRetained casBenchArm = "Retained" +) + +var casBenchArms = []casBenchArm{casBenchCAS, casBenchFresh, casBenchTwoCall, casBenchRetained} + +type casBenchWorkload struct { + name string + workers int + stale int // number of disjoint keys advanced after its original read + hot bool + inclusive bool +} + +type casBenchAttempt struct { + key, value []byte + client, handle string + expected uint64 + before uint64 + injectedStale bool +} + +func (f *casBenchFixture) acquire(ctx context.Context, attempt casBenchAttempt, expected uint64) (uint64, string, error) { + var header metadata.MD + resp := &pb.GetResponse{} + err := f.conn.Invoke(ctx, casBenchPrefix+"Acquire", + &pb.CompareAndSwapRequest{Key: attempt.key, ExpectedCommitTs: expected}, resp, grpc.Header(&header)) + return resp.GetCommitTs(), casBenchMD(header, casBenchHandle), err +} + +func (f *casBenchFixture) get(ctx context.Context, key []byte) (*pb.GetResponse, error) { + return f.public.Get(ctx, &pb.GetRequest{Key: key, NeedCommitTs: true}) +} + +func (f *casBenchFixture) seed(t testing.TB, ctx context.Context, key, value []byte) uint64 { + t.Helper() + r, err := kv.DispatchWithLeaderIssuedCommitTS(ctx, f.control.coord, &kv.OperationGroup[kv.OP]{ + IsTxn: true, StartTS: max(f.local.LastCommitTS(), 1), + Elems: []*kv.Elem[kv.OP]{{Op: kv.Put, Key: key, Value: value}}, + }) + require.NoError(t, err) + require.Positive(t, r.CommitTS) + return r.CommitTS +} + +func (f *casBenchFixture) prepare(t testing.TB, arm casBenchArm, workload casBenchWorkload, round int) []casBenchAttempt { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + attempts := make([]casBenchAttempt, workload.workers) + initial := bytes.Repeat([]byte{'a'}, 1024) + for i := range attempts { + keyIndex := i + if workload.hot { + keyIndex = 0 + } + key := fmt.Appendf(nil, "cas-bench/%04d", keyIndex) + var version uint64 + if workload.hot && i > 0 { + version = attempts[0].expected + } else { + version = f.seed(t, ctx, key, initial) + } + value := bytes.Clone(initial) + binary.BigEndian.PutUint64(value, uint64(round)) + binary.BigEndian.PutUint64(value[8:], uint64(i)) + attempt := casBenchAttempt{ + key: key, value: value, client: strconv.Itoa(i), + expected: version, before: version, injectedStale: i < workload.stale, + } + if !workload.inclusive { + if arm == casBenchRetained { + readCtx := metadata.AppendToOutgoingContext(ctx, casBenchClient, attempt.client) + observed, handle, err := f.acquire(readCtx, attempt, 0) + require.NoError(t, err) + require.Equal(t, version, observed) + require.NotEmpty(t, handle) + attempt.handle = handle + } else { + observed, err := f.get(ctx, key) + require.NoError(t, err) + require.Equal(t, version, observed.GetCommitTs()) + require.Equal(t, initial, observed.GetValue()) + } + } + if attempt.injectedStale { + // Rewrite identical bytes. The old token has become stale without + // changing the logical value or creating a racing writer. + attempt.before = f.seed(t, ctx, key, initial) + require.Greater(t, attempt.before, version) + } + attempts[i] = attempt + } + return attempts +} + +type casBenchResult struct { + latency time.Duration + version uint64 + reason string + err error +} + +func (f *casBenchFixture) attempt(ctx context.Context, arm casBenchArm, a casBenchAttempt, inclusive bool) casBenchResult { + ctx = metadata.AppendToOutgoingContext(ctx, casBenchMeasure, "1", casBenchClient, a.client) + if inclusive && arm != casBenchRetained { + observed, err := f.get(ctx, a.key) + if err != nil { + return casBenchResult{reason: "read_error", err: err} + } + if observed.GetCommitTs() != a.expected { + return casBenchResult{reason: "read_error", err: errors.New("unexpected acquisition version")} + } + } + if arm == casBenchTwoCall || (arm == casBenchRetained && inclusive) { + handle, result := f.acquireForAttempt(ctx, a) + if result.reason != "" { + return result + } + a.handle = handle + } + resp, err := f.submitAttempt(ctx, arm, a) + return casBenchAttemptResult(arm, a.expected, resp, err) +} + +func casBenchAttemptResult(arm casBenchArm, expected uint64, resp *pb.CompareAndSwapResponse, err error) casBenchResult { + if err != nil { + return casBenchResult{reason: casBenchRejection(arm, err), err: err} + } + if resp.GetNewCommitTs() > expected { + return casBenchResult{version: resp.GetNewCommitTs(), reason: "applied"} + } + if resp.GetMismatch() { + if arm == casBenchCAS { + return casBenchResult{reason: "exact_mismatch"} + } + return casBenchResult{reason: "precheck_mismatch"} + } + return casBenchResult{reason: "invalid_reply", err: errors.New("missing outcome or non-advancing version")} +} + +func (f *casBenchFixture) acquireForAttempt(ctx context.Context, a casBenchAttempt) (string, casBenchResult) { + version, handle, err := f.acquire(ctx, a, a.expected) + if err != nil { + return "", casBenchResult{reason: "read_error", err: err} + } + if version == 0 { + return "", casBenchResult{reason: "read_error", err: errors.New("acquisition omitted version")} + } + if version != a.expected { + return "", casBenchResult{reason: "precheck_mismatch"} + } + if handle == "" { + return "", casBenchResult{reason: "read_error", err: errors.New("acquisition omitted handle")} + } + return handle, casBenchResult{} +} + +func (f *casBenchFixture) submitAttempt(ctx context.Context, arm casBenchArm, a casBenchAttempt) (*pb.CompareAndSwapResponse, error) { + req := &pb.CompareAndSwapRequest{Key: a.key, ExpectedCommitTs: a.expected, Value: a.value} + resp := &pb.CompareAndSwapResponse{} + var err error + switch arm { + case casBenchCAS: + resp, err = f.public.CompareAndSwap(ctx, req) + case casBenchFresh: + err = f.conn.Invoke(ctx, casBenchPrefix+"Fresh", req, resp) + case casBenchTwoCall, casBenchRetained: + handleCtx := metadata.AppendToOutgoingContext(ctx, casBenchHandle, a.handle) + err = f.conn.Invoke(handleCtx, casBenchPrefix+"Commit", req, resp) + if code := status.Code(err); code == codes.Canceled || code == codes.DeadlineExceeded { + cleanupCtx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + cleanupCtx = metadata.AppendToOutgoingContext(cleanupCtx, casBenchMeasure, "1", casBenchClient, a.client, casBenchHandle, a.handle) + _ = f.conn.Invoke(cleanupCtx, casBenchPrefix+"Cancel", req, &pb.CompareAndSwapResponse{}) + } + } + return resp, err +} + +func casBenchRejection(arm casBenchArm, err error) string { + st := status.Convert(err) + switch st.Message() { + case "1PC lock conflict": + return "lock" + case "1PC route or leadership rejection": + return "route" + case "1PC write conflict": + // Existing 1PC uses the same error type for its timestamp fence and + // OCC. The parked trial disambiguates by ordering known stamps. + return "one_phase_conflict" + case "invalid or expired benchmark handle", "expired benchmark handle": + return "handle_rejected" + } + return casBenchStatusRejection(arm, st) +} + +func casBenchStatusRejection(arm casBenchArm, st *status.Status) string { + switch st.Code() { + case codes.DeadlineExceeded, codes.Canceled: + return "deadline_unknown" + case codes.Aborted: + if arm != casBenchCAS { + return "aborted" + } + if casBenchCASLocked(st) { + return "lock" + } + return "cas_timestamp_conflict" + case codes.Unavailable: + return "unavailable" + case codes.FailedPrecondition: + return "not_admitted" + case codes.OK, codes.Unknown, codes.InvalidArgument, codes.NotFound, codes.AlreadyExists, + codes.PermissionDenied, codes.ResourceExhausted, codes.OutOfRange, codes.Unimplemented, + codes.Internal, codes.DataLoss, codes.Unauthenticated: + return "unknown" + default: + return "unknown" + } +} + +func casBenchCASLocked(st *status.Status) bool { + for _, detail := range st.Details() { + info, ok := detail.(*errdetails.ErrorInfo) + if ok && info.GetDomain() == publicGRPCFailureDomain && info.GetReason() == "CAS_LOCKED" { + return true + } + } + return false +} + +func (f *casBenchFixture) run(t testing.TB, arm casBenchArm, workload casBenchWorkload, attempts []casBenchAttempt) []casBenchResult { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + start := make(chan struct{}) + results := make([]casBenchResult, len(attempts)) + if workload.stale > 0 { + // Keep injected staleness independent of the shard-wide timestamp + // ordering race. The hot-key cells exercise that race separately. + for i, attempt := range attempts { + issued := time.Now() + results[i] = f.attempt(ctx, arm, attempt, workload.inclusive) + results[i].latency = time.Since(issued) + } + return results + } + var released time.Time + var ready, done sync.WaitGroup + ready.Add(len(attempts)) + done.Add(len(attempts)) + for i, attempt := range attempts { + go func() { + defer done.Done() + ready.Done() + <-start + results[i] = f.attempt(ctx, arm, attempt, workload.inclusive) + results[i].latency = time.Since(released) + }() + } + ready.Wait() + released = time.Now() + close(start) + var order []casBenchParked + if f.meter.gate != nil { + var err error + order, err = f.releaseParked(ctx, len(attempts), workload.name == "parked-reversed") + if err != nil { + cancel() + done.Wait() + t.Fatalf("parked proposals: %v (results: %+v)", err, results) + } + } + done.Wait() + if len(order) > 0 { + casBenchVerifyParked(t, arm, order, results) + } + return results +} + +func casBenchVerifyParked(t testing.TB, arm casBenchArm, order []casBenchParked, results []casBenchResult) { + t.Helper() + winner := order[0] + require.Equal(t, winner.commitTS, results[winner.client].version) + for _, loser := range order[1:] { + got := results[loser.client].reason + switch { + case arm != casBenchCAS: + require.Equal(t, "one_phase_conflict", got) + if loser.commitTS <= winner.commitTS { + got = "timestamp_order" + } else { + got = "occ_conflict" + } + case loser.commitTS <= winner.commitTS: + require.Equal(t, "cas_timestamp_conflict", got) + got = "timestamp_order" + default: + require.Equal(t, "exact_mismatch", got) + } + results[loser.client].reason = got + } +} + +func (f *casBenchFixture) releaseParked(ctx context.Context, count int, reverse bool) ([]casBenchParked, error) { + parked := make([]casBenchParked, count) + for i := range parked { + select { + case parked[i] = <-f.meter.gate: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + slices.SortFunc(parked, func(a, b casBenchParked) int { return cmp.Compare(a.commitTS, b.commitTS) }) + for i := 1; i < len(parked); i++ { + if parked[i].commitTS <= parked[i-1].commitTS { + return nil, errors.New("non-increasing 1PC timestamps") + } + } + if reverse { + slices.Reverse(parked) + } + for _, contender := range parked { + close(contender.release) + select { + case <-contender.done: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return parked, nil +} + +// Reconcile replies against all versions appended since the setup watermark, +// including invisible extra writes that a final Get alone could miss. +func (f *casBenchFixture) verify(t testing.TB, arm casBenchArm, attempts []casBenchAttempt, results []casBenchResult) { + t.Helper() + type keyHistory struct { + before uint64 + applied []store.MVCCVersion + } + history := make(map[string]*keyHistory) + for i, a := range attempts { + key := string(a.key) + if history[key] == nil { + history[key] = &keyHistory{before: a.before} + } + r := results[i] + switch r.reason { + case "applied": + require.False(t, a.injectedStale, "stale token applied") + require.Greater(t, r.version, a.before) + history[key].applied = append(history[key].applied, store.MVCCVersion{CommitTS: r.version, Value: a.value}) + case "exact_mismatch", "precheck_mismatch", "one_phase_conflict", "cas_timestamp_conflict", "timestamp_order", "occ_conflict": + if a.injectedStale { + require.Equal(t, casBenchStaleReason(arm), r.reason) + } + default: + t.Fatalf("%s: unexpected outcome %s on key %s: %v", arm, r.reason, a.key, r.err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for key, h := range history { + f.verifyHistory(t, ctx, key, h.before, h.applied) + } +} + +func casBenchStaleReason(arm casBenchArm) string { + switch arm { + case casBenchCAS: + return "exact_mismatch" + case casBenchRetained: + return "one_phase_conflict" + case casBenchFresh, casBenchTwoCall: + return "precheck_mismatch" + default: + return "precheck_mismatch" + } +} + +func (f *casBenchFixture) verifyHistory(t testing.TB, ctx context.Context, key string, before uint64, applied []store.MVCCVersion) { + t.Helper() + const ( + maxWinners = 1 + maxVersions = 1 + maxWinners + 1 // Seed, winner, and room to detect an extra version. + ) + require.LessOrEqual(t, len(applied), maxWinners, "multiple winners at one version for %s", key) + versions, err := f.local.ExportVersions(ctx, store.ExportVersionsOptions{ + StartKey: []byte(key), EndKey: append([]byte(key), 0), MinCommitTSExclusive: before - 1, + MaxVersions: maxVersions, + }) + require.NoError(t, err) + require.True(t, versions.Done) + require.Len(t, versions.Versions, 1+len(applied)) + byTimestamp := make(map[uint64]store.MVCCVersion, len(versions.Versions)) + for _, version := range versions.Versions { + require.False(t, version.Tombstone) + byTimestamp[version.CommitTS] = version + } + require.Equal(t, bytes.Repeat([]byte{'a'}, 1024), byTimestamp[before].Value) + for _, version := range applied { + require.Equal(t, version.Value, byTimestamp[version.CommitTS].Value) + } +} + +func TestMVCCCASContention(t *testing.T) { + for _, arm := range casBenchArms { + t.Run(string(arm), func(t *testing.T) { + for _, workload := range []casBenchWorkload{ + {name: "known", workers: 1}, + {name: "stale", workers: 8, stale: 4}, + {name: "hot", workers: 8, hot: true}, + {name: "parked", workers: 8, hot: true}, + {name: "parked-reversed", workers: 8, hot: true}, + } { + t.Run(workload.name, func(t *testing.T) { + checkCASBenchContention(t, arm, workload) + }) + } + }) + } +} + +func checkCASBenchContention(t *testing.T, arm casBenchArm, workload casBenchWorkload) { + t.Helper() + parked := strings.HasPrefix(workload.name, "parked") + f := newCASBenchFixture(t, parked) + outcomes := make(map[string]int) + for round := range 3 { + attempts := f.prepare(t, arm, workload, round) + results := f.run(t, arm, workload, attempts) + f.verify(t, arm, attempts, results) + successes := 0 + for _, result := range results { + outcomes[result.reason]++ + if result.reason == "applied" { + successes++ + } + } + if workload.hot { + require.Equal(t, 1, successes) + } else { + require.Equal(t, workload.workers-workload.stale, successes) + proposals := workload.workers + if arm == casBenchFresh || arm == casBenchTwoCall { + proposals -= workload.stale + } + require.EqualValues(t, (round+1)*proposals, f.meter.proposals.Load()) + rpcs := workload.workers + if arm == casBenchTwoCall { + rpcs += successes + } + require.EqualValues(t, (round+1)*rpcs, f.meter.rpcCount()) + } + } + if parked { + require.EqualValues(t, 3*workload.workers, f.meter.proposals.Load()) + require.Equal(t, f.meter.proposals.Load(), f.meter.completed.Load()) + } + t.Logf("rpc=%d proposals=%d completed=%d prechecks_passed=%d outcomes=%v", f.meter.rpcCount(), f.meter.proposals.Load(), f.meter.completed.Load(), f.meter.passedPrechecks.Load(), outcomes) + require.Zero(t, f.control.tracker.Oldest(), "all read and retained-handle pins must be released") +} + +func TestMVCCCASContentionHandles(t *testing.T) { + f := newCASBenchFixture(t, false) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + key := []byte("cas-bench/handle") + version := f.seed(t, ctx, key, []byte("initial")) + a := casBenchAttempt{key: key} + clientCtx := metadata.AppendToOutgoingContext(ctx, casBenchClient, "owner", casBenchMeasure, "1") + bind := func() string { + observed, handle, err := f.acquire(clientCtx, a, version) + require.NoError(t, err) + require.Equal(t, version, observed) + require.NotEmpty(t, handle) + return handle + } + + handle := bind() + req := &pb.CompareAndSwapRequest{Key: key, ExpectedCommitTs: version} + wrongClient := metadata.AppendToOutgoingContext(ctx, casBenchClient, "other", casBenchHandle, handle) + err := f.conn.Invoke(wrongClient, casBenchPrefix+"Commit", req, &pb.CompareAndSwapResponse{}) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + require.Positive(t, f.control.tracker.Oldest(), "another client cannot consume a handle") + owner := metadata.AppendToOutgoingContext(clientCtx, casBenchHandle, handle) + require.NoError(t, f.conn.Invoke(owner, casBenchPrefix+"Cancel", req, &pb.CompareAndSwapResponse{})) + err = f.conn.Invoke(owner, casBenchPrefix+"Commit", req, &pb.CompareAndSwapResponse{}) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + require.Zero(t, f.control.tracker.Oldest()) + + // Shorten only this diagnostic's deadline; all workload cells use five seconds. + f.control.mu.Lock() + f.control.pinTTL = 50 * time.Millisecond + f.control.mu.Unlock() + expired := metadata.AppendToOutgoingContext(clientCtx, casBenchHandle, bind()) + require.Eventually(t, func() bool { + return f.meter.handleExpirations.Load() == 1 + }, time.Second, 5*time.Millisecond) + err = f.conn.Invoke(expired, casBenchPrefix+"Commit", req, &pb.CompareAndSwapResponse{}) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + require.Zero(t, f.control.tracker.Oldest()) + require.Zero(t, f.meter.proposals.Load()) +} + +func (m *casBenchMeter) rpcCount() uint64 { + var total uint64 + m.rpcs.Range(func(_, value any) bool { + total += casBenchCounter(value).Load() + return true + }) + return total +} + +func BenchmarkMVCCCASContention(b *testing.B) { + workloads := []casBenchWorkload{ + {name: "known", workers: 1}, + {name: "known-inclusive", workers: 1, inclusive: true}, + {name: "stale50", workers: 8, stale: 4}, + {name: "stale100", workers: 8, stale: 8}, + {name: "hot2", workers: 2, hot: true}, + {name: "hot8", workers: 8, hot: true}, + {name: "hot32", workers: 32, hot: true}, + } + for _, workload := range workloads { + for _, arm := range casBenchArms { + b.Run(workload.name+"/"+string(arm), func(b *testing.B) { + b.StopTimer() + f := newCASBenchFixture(b, false) + outcomes := make(map[string]int) + var all, applied []time.Duration + for round := range b.N { + attempts := f.prepare(b, arm, workload, round) + b.StartTimer() + results := f.run(b, arm, workload, attempts) + b.StopTimer() + f.verify(b, arm, attempts, results) + for _, result := range results { + outcomes[result.reason]++ + all = append(all, result.latency) + if result.reason == "applied" { + applied = append(applied, result.latency) + } + } + } + f.report(b, workload, outcomes) + casBenchLatency(b, "all", all) + casBenchLatency(b, "applied", applied) + }) + } + } +} + +func (f *casBenchFixture) report(b *testing.B, workload casBenchWorkload, outcomes map[string]int) { + attempts := float64(b.N * workload.workers) + successes := float64(outcomes["applied"]) + proposals := float64(f.meter.proposals.Load()) + b.ReportMetric(float64(b.Elapsed().Nanoseconds())/attempts, "ns/attempt") + b.ReportMetric(float64(workload.stale)/float64(workload.workers), "injected_stale/attempt") + b.ReportMetric(proposals, "proposals_total") + b.ReportMetric(proposals/attempts, "proposals/attempt") + b.ReportMetric(float64(f.meter.completed.Load())/attempts, "proposal_replies/attempt") + b.ReportMetric(float64(f.meter.readFences.Load())/attempts, "applied_fences/attempt") + b.ReportMetric(float64(f.meter.verifyLeader.Load())/attempts, "leader_checks/attempt") + b.ReportMetric(float64(f.meter.preReads.Load())/attempts, "control_reads/attempt") + b.ReportMetric(float64(f.meter.passedPrechecks.Load())/attempts, "precheck_passes/attempt") + b.ReportMetric(float64(f.meter.handlePinNS.Load())/attempts, "handle_pin_ns/attempt") + b.ReportMetric(float64(f.meter.handleExpirations.Load()), "handle_expirations_total") + b.ReportMetric(float64(f.meter.casAdmissions.Load())/attempts, "cas_admission_checks/attempt") + b.ReportMetric(float64(f.meter.readAdmissions.Load())/attempts, "version_read_admission_checks/attempt") + casBenchRangeCounters(&f.meter.applyVerdicts, func(reason string, count uint64) { + b.ReportMetric(float64(count)/attempts, "fsm_"+reason+"/attempt") + }) + var rpcs float64 + casBenchRangeCounters(&f.meter.rpcs, func(method string, count uint64) { + b.ReportMetric(float64(count)/attempts, method[strings.LastIndexByte(method, '/')+1:]+"_rpc/attempt") + rpcs += float64(count) + }) + b.ReportMetric(rpcs/attempts, "rpc/attempt") + if successes > 0 { + b.ReportMetric(successes/b.Elapsed().Seconds(), "applied/s") + b.ReportMetric(proposals/successes, "proposals/success") + b.ReportMetric(rpcs/successes, "rpc/success") + } + for reason, count := range outcomes { + b.ReportMetric(float64(count)/attempts, reason+"/attempt") + } +} + +func casBenchLatency(b *testing.B, name string, samples []time.Duration) { + if len(samples) == 0 { + return + } + slices.Sort(samples) + for _, percentile := range []int{50, 95, 99} { + i := (percentile*len(samples)+99)/100 - 1 + b.ReportMetric(float64(samples[i].Nanoseconds()), fmt.Sprintf("%s_p%d_ns", name, percentile)) + } +} diff --git a/adapter/ordinary_get_comparison_test.go b/adapter/ordinary_get_comparison_test.go new file mode 100644 index 000000000..301a54a2b --- /dev/null +++ b/adapter/ordinary_get_comparison_test.go @@ -0,0 +1,71 @@ +package adapter + +import ( + "bytes" + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" +) + +func BenchmarkOrdinaryPointRead(b *testing.B) { + for _, backend := range []string{"Memory", "Pebble"} { + b.Run(backend, func(b *testing.B) { + ctx := b.Context() + st := store.NewMVCCStore() + if backend == "Pebble" { + var err error + st, err = store.NewPebbleStore(b.TempDir()) + if err != nil { + b.Fatal(err) + } + } + b.Cleanup(func() { _ = st.Close() }) + key := []byte("key") + if err := st.PutAt(ctx, key, bytes.Repeat([]byte{'x'}, 1024), 10, 0); err != nil { + b.Fatal(err) + } + srv := NewGRPCServer(st, &stubAdapterCoordinator{}) + b.Run("Get", func(b *testing.B) { + req := &pb.GetRequest{Key: key} + b.ReportAllocs() + for b.Loop() { + if _, err := srv.Get(ctx, req); err != nil { + b.Fatal(err) + } + } + }) + b.Run("RawGet", func(b *testing.B) { + req := &pb.RawGetRequest{Key: key, Ts: 10} + b.ReportAllocs() + for b.Loop() { + if _, err := srv.RawGet(ctx, req); err != nil { + b.Fatal(err) + } + } + }) + }) + } +} + +// BenchmarkOrdinaryPebbleGetAt isolates the bytes-only storage read from +// adapter dispatch and timestamp selection. +func BenchmarkOrdinaryPebbleGetAt(b *testing.B) { + st, err := store.NewPebbleStore(b.TempDir()) + if err != nil { + b.Fatal(err) + } + b.Cleanup(func() { _ = st.Close() }) + ctx := b.Context() + key := []byte("key") + if err := st.PutAt(ctx, key, bytes.Repeat([]byte{'x'}, 1024), 10, 0); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for b.Loop() { + value, err := st.GetAt(ctx, key, 10) + if err != nil || len(value) != 1024 { + b.Fatalf("GetAt returned %d bytes, %v", len(value), err) + } + } +} diff --git a/adapter/redis_lists.go b/adapter/redis_lists.go index 6baa356a6..36e34c689 100644 --- a/adapter/redis_lists.go +++ b/adapter/redis_lists.go @@ -207,16 +207,11 @@ type reusableListPush struct { // fresh meta. Extracted from listPushCoreWithDedup to keep that closure // under the cyclop / gocognit / nestif limits. func (r *RedisServer) dispatchListPushReuse(ctx context.Context, key []byte, pending *reusableListPush) (newLen int64, drop bool, err error) { - // HLC-4 parity: persistence-grade commit_ts allocation must honor - // the physical-ceiling fence so a stale-leader window cannot mint a - // timestamp that collides with the successor's. The error path - // returns ErrCeilingExpired which isRetryableRedisTxnErr classifies - // as non-retryable, so it exits retryRedisWrite directly to the - // client โ€” same shape as the other persistence-grade Next call - // sites in this file. + // Reuse still requires a ceiling-fenced timestamp. If allocation fails, + // the prior dispatch may already have applied the captured push. commitTS, allocErr := r.nextCommitTSAfter(ctx, pending.startTS, "redis list-push reuse: allocate commitTS") if allocErr != nil { - return 0, false, errors.WithStack(allocErr) + return 0, false, errors.WithStack(kv.ErrTransactionOutcomeUnknown) } dispatchCtx := pending.readTimestamp.WithDispatchVoucher(ctx) _, dispErr := kv.DispatchWithReadTimestamp(dispatchCtx, r.coordinator, &kv.OperationGroup[kv.OP]{ diff --git a/adapter/redis_stream_cmds.go b/adapter/redis_stream_cmds.go index 9d2d3f77f..823621d9b 100644 --- a/adapter/redis_stream_cmds.go +++ b/adapter/redis_stream_cmds.go @@ -452,7 +452,8 @@ func (r *RedisServer) dispatchXAddReuse( ) (id string, drop bool, err error) { commitTS, allocErr := r.nextCommitTSAfter(ctx, pending.startTS, "redis xadd reuse: allocate commitTS") if allocErr != nil { - return "", false, cockerrors.WithStack(allocErr) + // The original generated ID may already have been appended. + return "", false, cockerrors.WithStack(kv.ErrTransactionOutcomeUnknown) } attemptCtx := pending.readTimestamp.WithDispatchVoucher(ctx) _, dispErr := kv.DispatchWithReadTimestamp(attemptCtx, r.coordinator, &kv.OperationGroup[kv.OP]{ diff --git a/adapter/redis_txn.go b/adapter/redis_txn.go index a87602ee5..891e58a29 100644 --- a/adapter/redis_txn.go +++ b/adapter/redis_txn.go @@ -3191,7 +3191,8 @@ func (r *RedisServer) dispatchExecReuse(ctx context.Context, pending *reusableEx // rule out. commitTS, allocErr := r.nextCommitTSAfter(ctx, pending.startTS, "redis exec reuse: allocate commitTS") if allocErr != nil { - return nil, false, errors.WithStack(allocErr) + // Allocation failed before reuse could resolve the prior dispatch. + return nil, false, errors.WithStack(kv.ErrTransactionOutcomeUnknown) } _, dispErr := kv.DispatchWithReadTimestamp(ctx, r.coordinator, &kv.OperationGroup[kv.OP]{ IsTxn: true, diff --git a/adapter/request_read_architecture_test.go b/adapter/request_read_architecture_test.go index cbc8b94cb..8f00aa162 100644 --- a/adapter/request_read_architecture_test.go +++ b/adapter/request_read_architecture_test.go @@ -43,6 +43,8 @@ func requestReadPolicy() map[string]map[string]bool { allowed["request"+name] = legacyRequestReadScopes allowed["requestReadSnapshot"]["request_read_ports.go:request"+name] = true } + allowed["GetVersionAt"] = map[string]bool{} + allowed["GetVersionAtWithReadFence"] = map[string]bool{} allowed["requestReadSnapshot"]["request_read_ports.go:requestScanGroupOwnedPageAt"] = true allowed["requestScanPhysicalAt"] = legacyRequestReadScopes allowed["Historical"] = map[string]bool{ @@ -91,6 +93,8 @@ func requestReadViolations(name string, file *ast.File, allowed map[string]map[s func TestCapabilityReadPortGuardRejectsNewRawOrHistoricalEscapes(t *testing.T) { for _, body := range []string{ "store.GetAt(ctx,key,oldTimestamp)", + "store.GetVersionAt(ctx,backend,key,oldTimestamp)", + "store.GetVersionAtWithReadFence(ctx,key,oldTimestamp,groupID,routeVersion)", "store.ScanAt(ctx,start,end,10,oldTimestamp)", "old := requestGetAt; old(ctx, store, key, oldTimestamp)", "request.Historical(ctx,oldTimestamp)", diff --git a/adapter/request_read_ports.go b/adapter/request_read_ports.go index 5b8fc669e..4e7bfba69 100644 --- a/adapter/request_read_ports.go +++ b/adapter/request_read_ports.go @@ -71,15 +71,6 @@ func requestScanGroupKeysAt(ctx context.Context, backend any, groupID uint64, st return wrappedReadResult(request.ScanGroupKeys(requestReadContext(ctx, request), snapshot, groupID, start, end, limit)) } -func requestGetAtWithReadFence(ctx context.Context, backend any, key []byte, ts uint64, groupID uint64, readRouteVersion uint64) ([]byte, error) { - request, snapshot, closeRead, err := requestReadSnapshot(ctx, backend, ts) - if err != nil { - return nil, errors.WithStack(err) - } - defer closeRead() - return wrappedReadResult(request.GetWithFence(requestReadContext(ctx, request), snapshot, key, groupID, readRouteVersion)) -} - func requestScanKeysAtWithReadFence(ctx context.Context, backend any, start []byte, end []byte, limit int, ts uint64, groupID uint64, readRouteVersion uint64) ([][]byte, error) { request, snapshot, closeRead, err := requestReadSnapshot(ctx, backend, ts) if err != nil { diff --git a/adapter/s3_chunkref_rc.go b/adapter/s3_chunkref_rc.go index 56cd92bbc..c4ea0e0e3 100644 --- a/adapter/s3_chunkref_rc.go +++ b/adapter/s3_chunkref_rc.go @@ -88,22 +88,31 @@ func collectS3ChunkRefChanges(elems []*kv.Elem[kv.OP]) ([]*s3ChunkRefChange, err changes[key] = change order = append(order, change) } - switch elem.Op { - case kv.Put: - ref, ok := s3keys.DecodeChunkRefValue(elem.Value) - if !ok { - return nil, errors.New("s3: malformed chunkref value") - } - change.after = &ref - case kv.Del: - change.after = nil - case kv.DelPrefix: - return nil, errors.New("s3: prefix deletion requires explicit chunkref accounting") + if err := change.applyMutation(elem); err != nil { + return nil, err } } return order, nil } +func (change *s3ChunkRefChange) applyMutation(elem *kv.Elem[kv.OP]) error { + switch elem.Op { + case kv.Put: + ref, ok := s3keys.DecodeChunkRefValue(elem.Value) + if !ok { + return errors.New("s3: malformed chunkref value") + } + change.after = &ref + case kv.Del: + change.after = nil + case kv.DelPrefix: + return errors.New("s3: prefix deletion requires explicit chunkref accounting") + case kv.CompareAndSwap: + return errors.New("s3: conditional chunkref changes require explicit accounting") + } + return nil +} + func (s *S3Server) readS3ChunkRefAt(ctx context.Context, key []byte, readTS uint64) (*s3keys.ChunkRefValue, error) { raw, err := requestGetAt(ctx, s.store, key, readTS) if errors.Is(err, store.ErrKeyNotFound) { diff --git a/adapter/split_job_configuration.go b/adapter/split_job_configuration.go index 35683b4b6..dd38f0992 100644 --- a/adapter/split_job_configuration.go +++ b/adapter/split_job_configuration.go @@ -60,6 +60,10 @@ func (s *DistributionServer) bindSplitSourceCleanup(ctx context.Context, job dis } req.RequireConfigurationIndex = true req.ExpectedConfigurationIndex = index + req.ExpectedSourceGroupId, err = s.splitJobSourceGroupID(ctx, job) + if err != nil { + return err + } return nil } diff --git a/adapter/split_job_runner.go b/adapter/split_job_runner.go index 0640e6f2d..dd6fa5d5a 100644 --- a/adapter/split_job_runner.go +++ b/adapter/split_job_runner.go @@ -804,7 +804,7 @@ func (s *DistributionServer) cleanupSplitJobSourceData(ctx context.Context, job if err := s.bindSplitSourceCleanup(ctx, job, source, routeEnd, req); err != nil { return err } - resp, err := cleanupSplitMigration(ctx, source, req) + resp, err := s.cleanupAndConfirmSplitSource(ctx, job, source, req) if err != nil { return errors.WithStack(err) } diff --git a/adapter/split_migration_auth.go b/adapter/split_migration_auth.go index 6043a6d17..bbc86d190 100644 --- a/adapter/split_migration_auth.go +++ b/adapter/split_migration_auth.go @@ -49,7 +49,11 @@ func splitMigrationProtectedMethod(method string) bool { func splitMigrationAuthenticatedMethod(method string, peerAuthEnforced bool) bool { // Forward can write arbitrary system/transaction metadata. In a migration // cluster it is a privileged peer RPC, not an alternative public write API. - return splitMigrationProtectedMethod(method) || (peerAuthEnforced && method == pb.Internal_Forward_FullMethodName) + return splitMigrationProtectedMethod(method) || (peerAuthEnforced && (method == pb.Internal_Forward_FullMethodName || isCASForwardMethod(method))) +} + +func isCASForwardMethod(method string) bool { + return method == pb.Internal_ForwardCompareAndSwap_FullMethodName || method == pb.Internal_ForwardCompareAndSwapV2_FullMethodName } // SplitMigrationTokenAuth protects catalog splits, migration control and raw MVCC exports. @@ -66,7 +70,7 @@ func SplitMigrationTokenAuth(token string, insecureNoAuth, peerAuthEnforced bool }, "split migration controller") controlAuth, _ := bearerTokenAuth(token, func(string) bool { return true }, "split migration peer") unary := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { - if info.FullMethod == pb.Internal_Forward_FullMethodName && splitForwardWritesJobControl(req) { + if splitForwardRequiresPeerAuth(info.FullMethod, token, req) { if err := checkSplitMigrationTransport(ctx, info.FullMethod, token, true); err != nil { return nil, err } @@ -92,6 +96,12 @@ func SplitMigrationTokenAuth(token string, insecureNoAuth, peerAuthEnforced bool return unary, stream } +func splitForwardRequiresPeerAuth(method, token string, req any) bool { + cas := isCASForwardMethod(method) + return (method == pb.Internal_Forward_FullMethodName || cas) && + (splitForwardWritesJobControl(req) || (token != "" && cas)) +} + // Job authority and typed migration metadata must never be planted during // send-first rollout. Ordinary legacy peer transaction writes remain compatible. func splitForwardWritesJobControl(req any) bool { diff --git a/adapter/split_migration_peer_ownership_readiness.go b/adapter/split_migration_peer_ownership_readiness.go index 979e8c299..da80a3630 100644 --- a/adapter/split_migration_peer_ownership_readiness.go +++ b/adapter/split_migration_peer_ownership_readiness.go @@ -13,8 +13,8 @@ import ( "google.golang.org/grpc/status" ) -func NewInternalMigrationTransaction(proposer raftengine.Proposer, observer kv.ProposalObserver, st store.MVCCStore, groupID uint64) *kv.TransactionManager { - opts := []kv.TransactionOption{kv.WithProposalObserver(observer)} +func NewInternalMigrationTransaction(proposer raftengine.Proposer, observer kv.ProposalObserver, st store.MVCCStore, groupID uint64, opts ...kv.TransactionOption) *kv.TransactionManager { + opts = append(opts, kv.WithProposalObserver(observer)) if groupID != 0 { opts = append(opts, kv.WithMigrationRequestAdmission(st, groupID)) } diff --git a/adapter/split_partition_preflight_test.go b/adapter/split_partition_preflight_test.go index cb0164b31..cb32bbbab 100644 --- a/adapter/split_partition_preflight_test.go +++ b/adapter/split_partition_preflight_test.go @@ -3,14 +3,70 @@ package adapter import ( "context" "testing" + "time" + "github.com/bootjp/elastickv/distribution" "github.com/bootjp/elastickv/kv" pb "github.com/bootjp/elastickv/proto" "github.com/bootjp/elastickv/store" "github.com/cockroachdb/errors" "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/protobuf/proto" ) +// Delay one configuration-bound ownership read after a real preflight export. +// The member still runs the ordinary Internal probe with its original deadline. +type delayedPreflightMember struct { + *resplitAcceptanceClient + t *testing.T + exportsAtStart int + expired error +} + +func (m *delayedPreflightMember) ProbeMigrationState(ctx context.Context, req *pb.ProbeMigrationStateRequest, opts ...grpc.CallOption) (*pb.ProbeMigrationStateResponse, error) { + if m.expired == nil && len(m.exports) > m.exportsAtStart && req.GetKind() == pb.MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_OWNERSHIP_APPLIED && + req.GetRequireConfigurationIndex() && req.GetTransferSizeGuardVersion() == store.MigrationTransferSizeGuardVersion { + deadline, bounded := ctx.Deadline() + require.True(m.t, bounded) + require.LessOrEqual(m.t, time.Until(deadline), defaultSplitMigrationVoterProbeTimeout) + <-ctx.Done() + resp, err := m.resplitAcceptanceClient.ProbeMigrationState(ctx, req, opts...) + require.ErrorIs(m.t, err, context.DeadlineExceeded) + m.expired = err + return resp, err + } + return m.resplitAcceptanceClient.ProbeMigrationState(ctx, req, opts...) +} + +func TestMigrationResplitPreflightRecoversExpiredMemberProbe(t *testing.T) { + r := newResplitAcceptanceRuntime(t) + source := r.clients[1] + member := &delayedPreflightMember{resplitAcceptanceClient: source, t: t} + installed := false + job := r.migrate(t, 1, 2, "m", func(job distribution.SplitJob) { + if installed || job.TransferPreflightTS == 0 || job.TransferPreflightDone { + return + } + installed = true + member.exportsAtStart = len(source.exports) + factory := r.server.splitApplyMemberFactory + r.server.splitApplyMemberFactory = func(ctx context.Context, id uint64) (SplitMigrationApplyMemberSnapshot, error) { + snapshot, err := factory(ctx, id) + if err == nil && id == job.SourceGroupID { + require.Len(t, snapshot.Members, 1) + snapshot.Members[0].Client = member + } + return snapshot, err + } + }) + require.ErrorIs(t, member.expired, context.DeadlineExceeded) + require.Greater(t, len(source.exports), member.exportsAtStart+1) + require.True(t, proto.Equal(source.exports[member.exportsAtStart], source.exports[member.exportsAtStart+1]), "retry must replay the uncheckpointed page") + require.True(t, job.TransferPreflightDone) + r.read(t, "n", "original-n") +} + func TestMigrationResplitDoesNotWaitForOfflineHistoricalNonOwner(t *testing.T) { t.Parallel() r := newResplitAcceptanceRuntime(t) diff --git a/adapter/sqs_messages.go b/adapter/sqs_messages.go index a9a943eec..ee1cd2611 100644 --- a/adapter/sqs_messages.go +++ b/adapter/sqs_messages.go @@ -518,51 +518,12 @@ func (s *SQSServer) sendMessage(w http.ResponseWriter, r *http.Request) { return } - rec, recordBytes, apiErr := buildSendRecord(meta, in, delay) - if apiErr != nil { - writeSQSErrorFromErr(w, apiErr) - return - } - - // Standard queues never have PartitionCount > 1 (the cross- - // attribute validator rejects it), so partition is always 0 - // here and the dispatch helpers route to the legacy keyspace - // โ€” byte-identical to the pre-PR-5b output. - const partition uint32 = 0 - dataKey := sqsMsgDataKeyDispatch(meta, queueName, partition, meta.Generation, rec.MessageID) - visKey := sqsMsgVisKeyDispatch(meta, queueName, partition, meta.Generation, rec.AvailableAtMillis, rec.MessageID) - byAgeKey := sqsMsgByAgeKeyDispatch(meta, queueName, partition, meta.Generation, rec.SendTimestampMillis, rec.MessageID) - metaKey := sqsQueueMetaKey(queueName) - genKey := sqsQueueGenKey(queueName) - // StartTS + ReadKeys fence against a concurrent DeleteQueue / - // PurgeQueue / SetQueueAttributes that commits between our meta - // read and this dispatch. Without the fence, a DeleteQueue that - // bumps the generation would land first, and this send would then - // commit under the old generation โ€” silently storing a message - // that is no longer reachable via routing (acknowledged loss). - // ErrWriteConflict surfaces via writeSQSErrorFromErr so clients - // retry against the current queue state. - req := &kv.OperationGroup[kv.OP]{ - IsTxn: true, - StartTS: readTS, - ReadKeys: [][]byte{metaKey, genKey}, - Elems: []*kv.Elem[kv.OP]{ - {Op: kv.Put, Key: dataKey, Value: recordBytes}, - {Op: kv.Put, Key: visKey, Value: []byte(rec.MessageID)}, - {Op: kv.Put, Key: byAgeKey, Value: []byte(rec.MessageID)}, - }, - } - dispatchCtx := readTimestamp.WithDispatchVoucher(r.Context()) - if err := s.dispatchSQSMutation(dispatchCtx, req); err != nil { + resp, err := s.sendStandardMessageWithRetry(r.Context(), queueName, in, meta, readTimestamp, delay) + if err != nil { writeSQSErrorFromErr(w, err) return } - - writeSQSJSON(w, map[string]string{ - sqsFieldMessageID: rec.MessageID, - sqsFieldMD5OfMessageBody: rec.MD5OfBody, - sqsFieldMD5OfMessageAttributes: md5OfAttributesHex(in.MessageAttributes), - }) + writeSQSJSON(w, resp) } func (s *SQSServer) sendMessageCore(ctx context.Context, queueName string, in sqsSendMessageInput) (map[string]string, error) { @@ -571,7 +532,6 @@ func (s *SQSServer) sendMessageCore(ctx context.Context, queueName string, in sq if apiErr != nil { return nil, apiErr } - readTS := readTimestamp.Timestamp() if err := s.chargeQueueWithThrottleErr(queueName, bucketActionSend, 1, meta.Throttle, meta.Incarnation, throttleEpoch); err != nil { return nil, err } @@ -588,7 +548,42 @@ func (s *SQSServer) sendMessageCore(ctx context.Context, queueName string, in sq if meta.IsFIFO { return s.runFifoSendWithRetry(ctx, queueName, in) } + return s.sendStandardMessageWithRetry(ctx, queueName, in, meta, readTimestamp, delay) +} + +func (s *SQSServer) sendStandardMessageWithRetry(ctx context.Context, queueName string, in sqsSendMessageInput, meta *sqsQueueMeta, stamp kv.ReadTimestamp, delay int64) (map[string]string, error) { + backoff := transactRetryInitialBackoff + deadline := time.Now().Add(transactRetryMaxDuration) + for range transactRetryMaxAttempts { + result, err := s.trySendStandardMessage(ctx, queueName, in, meta, stamp, delay) + if err == nil { + return result, nil + } + // A raw conflict can follow a landed write. Only the isolated + // one-phase apply verdict proves this send did not commit. + if !errors.Is(err, store.ErrWriteConflict) || !kv.IsCertifiedOnePhaseConflict(err) { + return nil, err + } + if err := waitRetryWithDeadline(ctx, deadline, backoff); err != nil { + return nil, err + } + backoff = nextTransactRetryBackoff(backoff) + meta, stamp, err = s.loadQueueMetaForSend(ctx, queueName, []byte(in.MessageBody)) + if err != nil { + return nil, err + } + if err := validateSendFIFOParams(meta, in); err != nil { + return nil, err + } + delay, err = resolveSendDelay(meta, in.DelaySeconds) + if err != nil { + return nil, err + } + } + return nil, newSQSAPIError(http.StatusInternalServerError, sqsErrInternalFailure, "send message retry attempts exhausted") +} +func (s *SQSServer) trySendStandardMessage(ctx context.Context, queueName string, in sqsSendMessageInput, meta *sqsQueueMeta, readTimestamp kv.ReadTimestamp, delay int64) (map[string]string, error) { rec, recordBytes, apiErr := buildSendRecord(meta, in, delay) if apiErr != nil { return nil, apiErr @@ -599,7 +594,7 @@ func (s *SQSServer) sendMessageCore(ctx context.Context, queueName string, in sq byAgeKey := sqsMsgByAgeKeyDispatch(meta, queueName, partition, meta.Generation, rec.SendTimestampMillis, rec.MessageID) req := &kv.OperationGroup[kv.OP]{ IsTxn: true, - StartTS: readTS, + StartTS: readTimestamp.Timestamp(), ReadKeys: [][]byte{sqsQueueMetaKey(queueName), sqsQueueGenKey(queueName)}, Elems: []*kv.Elem[kv.OP]{ {Op: kv.Put, Key: dataKey, Value: recordBytes}, diff --git a/adapter/sqs_query_internal_error_test.go b/adapter/sqs_query_internal_error_test.go new file mode 100644 index 000000000..3258de2a0 --- /dev/null +++ b/adapter/sqs_query_internal_error_test.go @@ -0,0 +1,28 @@ +package adapter + +import ( + "log/slog" + "net/http" + "net/http/httptest" + "testing" + + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func TestSQSQueryInternalErrorLogsCauseWithoutExposingIt(t *testing.T) { + var logs lockedLogBuffer + prior := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + t.Cleanup(func() { slog.SetDefault(prior) }) + privateCause := "private storage detail /data/pebble-00017" + response := httptest.NewRecorder() + writeSQSQueryError(response, errors.New(privateCause)) + require.Equal(t, http.StatusInternalServerError, response.Code) + require.Contains(t, response.Body.String(), "internal error") + require.NotContains(t, response.Body.String(), privateCause) + require.NotContains(t, response.Header().Get("x-amzn-ErrorType"), privateCause) + logs.mu.Lock() + defer logs.mu.Unlock() + require.Contains(t, logs.buf.String(), privateCause) +} diff --git a/adapter/sqs_query_protocol.go b/adapter/sqs_query_protocol.go index 90a1e4905..51de8e098 100644 --- a/adapter/sqs_query_protocol.go +++ b/adapter/sqs_query_protocol.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "encoding/xml" "io" + "log/slog" "net/http" "net/url" "sort" @@ -1360,6 +1361,9 @@ func sqsQueryErrorDetails(err error) (int, string, string, int) { func writeSQSQueryError(w http.ResponseWriter, err error) { status, code, message, retryAfter := sqsQueryErrorDetails(err) + if status == http.StatusInternalServerError && code == sqsErrInternalFailure { + slog.Error("sqs query adapter internal error", "err", err) + } env := queryErrorEnvelope{ XMLName: xml.Name{Local: "ErrorResponse"}, XMLNS: sqsQueryNamespace, diff --git a/adapter/sqs_standard_send_retry_test.go b/adapter/sqs_standard_send_retry_test.go new file mode 100644 index 000000000..386323c53 --- /dev/null +++ b/adapter/sqs_standard_send_retry_test.go @@ -0,0 +1,160 @@ +package adapter + +import ( + "bytes" + "context" + "encoding/xml" + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + json "github.com/goccy/go-json" + "github.com/stretchr/testify/require" +) + +type sqsSendRejectingProposer struct{} + +func (sqsSendRejectingProposer) Propose(context.Context, []byte) (*raftengine.ProposalResult, error) { + return &raftengine.ProposalResult{CommitIndex: 7, Response: store.ErrWriteConflict}, nil +} + +func (p sqsSendRejectingProposer) ProposeAdmin(ctx context.Context, data []byte) (*raftengine.ProposalResult, error) { + return p.Propose(ctx, data) +} + +func certifiedSQSSendConflict(t *testing.T) error { + t.Helper() + manager := kv.NewTransactionWithProposer(sqsSendRejectingProposer{}) + t.Cleanup(manager.Close) + _, err := manager.Commit(t.Context(), []*pb.Request{{IsTxn: true, Ts: 1, + Mutations: []*pb.Mutation{{Op: pb.Op_PUT, Key: []byte("message"), Value: []byte("value")}}, + }}) + require.ErrorIs(t, err, store.ErrWriteConflict) + require.True(t, kv.IsCertifiedOnePhaseConflict(err)) + return err +} + +type sqsStandardSendCoordinator struct { + stubAdapterCoordinator + firstError error + requests []*kv.OperationGroup[kv.OP] + beforeFail func() +} + +func (c *sqsStandardSendCoordinator) Dispatch(_ context.Context, req *kv.OperationGroup[kv.OP]) (*kv.CoordinateResponse, error) { + c.requests = append(c.requests, req) + if len(c.requests) == 1 { + if c.beforeFail != nil { + c.beforeFail() + } + return nil, c.firstError + } + return &kv.CoordinateResponse{}, nil +} + +func TestSQSStandardSendRetriesCertifiedConflict(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"core", "json", "query"} { + t.Run(protocol, func(t *testing.T) { + t.Parallel() + st := store.NewMVCCStore() + t.Cleanup(func() { require.NoError(t, st.Close()) }) + seedStandardQueue(t, st) + coord := &sqsStandardSendCoordinator{firstError: certifiedSQSSendConflict(t)} + coord.beforeFail = func() { + meta := &sqsQueueMeta{Name: "q", Generation: 2, MaximumMessageSize: 262144, DelaySeconds: 60} + body, err := encodeSQSQueueMeta(meta) + require.NoError(t, err) + require.NoError(t, st.PutAt(t.Context(), sqsQueueMetaKey("q"), body, 100, 0)) + } + server := NewSQSServer(nil, st, coord) + input := sqsSendMessageInput{QueueUrl: "http://localhost/q", MessageBody: "one"} + var out map[string]string + switch protocol { + case "core": + var err error + out, err = server.sendMessageCore(t.Context(), "q", input) + require.NoError(t, err) + case "json": + body, err := json.Marshal(input) + require.NoError(t, err) + request := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(body)) + response := httptest.NewRecorder() + server.sendMessage(response, request) + require.Equal(t, http.StatusOK, response.Code, response.Body.String()) + require.NoError(t, json.Unmarshal(response.Body.Bytes(), &out)) + default: + request := httptest.NewRequest(http.MethodPost, "/", nil) + response := httptest.NewRecorder() + server.handleQuerySendMessage(response, request, url.Values{ + "QueueUrl": {input.QueueUrl}, "MessageBody": {input.MessageBody}, + }) + require.Equal(t, http.StatusOK, response.Code, response.Body.String()) + var envelope struct { + MessageID string `xml:"SendMessageResult>MessageId"` + } + require.NoError(t, xml.Unmarshal(response.Body.Bytes(), &envelope)) + out = map[string]string{sqsFieldMessageID: envelope.MessageID} + } + require.Len(t, coord.requests, 2) + retried := coord.requests[1] + require.Equal(t, uint64(100), retried.StartTS) + require.Equal(t, [][]byte{sqsQueueMetaKey("q"), sqsQueueGenKey("q")}, retried.ReadKeys) + record, err := decodeSQSMessageRecord(retried.Elems[0].Value) + require.NoError(t, err) + require.Equal(t, out[sqsFieldMessageID], record.MessageID) + require.Equal(t, int64(60_000), record.AvailableAtMillis-record.SendTimestampMillis) + require.Equal(t, sqsMsgDataKeyDispatch(&sqsQueueMeta{}, "q", 0, 2, record.MessageID), retried.Elems[0].Key) + }) + } +} + +func TestSQSStandardSendDoesNotRetryUnprovenConflict(t *testing.T) { + t.Parallel() + certified := certifiedSQSSendConflict(t) + for name, failure := range map[string]error{ + "raw conflict": store.ErrWriteConflict, + "lost reply": io.EOF, + "mixed verdict": errors.Join(certified, io.EOF), + "unknown": kv.ErrTransactionOutcomeUnknown, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + st := store.NewMVCCStore() + t.Cleanup(func() { require.NoError(t, st.Close()) }) + seedStandardQueue(t, st) + coord := &sqsStandardSendCoordinator{firstError: failure} + server := NewSQSServer(nil, st, coord) + _, err := server.sendMessageCore(t.Context(), "q", sqsSendMessageInput{MessageBody: "one"}) + require.Error(t, err) + require.Len(t, coord.requests, 1) + }) + } +} + +func TestSQSStandardSendRevalidatesSizeAfterCertifiedConflict(t *testing.T) { + t.Parallel() + st := store.NewMVCCStore() + t.Cleanup(func() { require.NoError(t, st.Close()) }) + seedStandardQueue(t, st) + coord := &sqsStandardSendCoordinator{firstError: certifiedSQSSendConflict(t)} + coord.beforeFail = func() { + meta := &sqsQueueMeta{Name: "q", Generation: 1, MaximumMessageSize: 2} + body, err := encodeSQSQueueMeta(meta) + require.NoError(t, err) + require.NoError(t, st.PutAt(t.Context(), sqsQueueMetaKey("q"), body, 100, 0)) + } + server := NewSQSServer(nil, st, coord) + _, err := server.sendMessageCore(t.Context(), "q", sqsSendMessageInput{MessageBody: "one"}) + var apiErr *sqsAPIError + require.ErrorAs(t, err, &apiErr) + require.Equal(t, sqsErrMessageTooLong, apiErr.errorType) + require.Len(t, coord.requests, 1) +} diff --git a/adapter/test_util_test.go b/adapter/test_util_test.go index aebb0dd31..52924750e 100644 --- a/adapter/test_util_test.go +++ b/adapter/test_util_test.go @@ -716,6 +716,12 @@ func isTransientNotLeaderErr(err error) bool { if err == nil { return false } + if isIndeterminateGRPCMutation(err) { + return false + } + if isCertifiedGRPCNonAdmission(err) { + return true + } s := strings.ToLower(err.Error()) return strings.Contains(s, "not leader") || strings.Contains(s, "leader not found") } diff --git a/cmd/casbench/artifacts_test.go b/cmd/casbench/artifacts_test.go new file mode 100644 index 000000000..8c7ba275c --- /dev/null +++ b/cmd/casbench/artifacts_test.go @@ -0,0 +1,160 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "encoding/pem" + "go/format" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCASVerdictCountersRequireExactRejectionGuards(t *testing.T) { + t.Parallel() + const source = `package kv +func compareAndStageCAS() error { + if commitTS <= watermark { return errors.WithStack(store.NewWriteConflictError(mut.Key)) } + if head.TS > startTS { return errors.WithStack(store.NewWriteConflictError(mut.Key)) } + return nil +}` + file, err := parser.ParseFile(token.NewFileSet(), "cas.go", source, 0) + require.NoError(t, err) + require.NoError(t, patchCASVerdictCounters(file)) + var body bytes.Buffer + require.NoError(t, format.Node(&body, token.NewFileSet(), file)) + require.Contains(t, body.String(), "cas_timestamp_fence_rejections") + require.Contains(t, body.String(), "cas_start_ts_occ_rejections") + for _, changed := range []string{ + strings.ReplaceAll(source, "commitTS <= watermark", "commitTS < watermark"), + strings.ReplaceAll(source, "head.TS > startTS", "head.TS >= startTS"), + strings.ReplaceAll(source, "store.NewWriteConflictError(mut.Key)", "store.ErrWriteConflict"), + } { + file, err := parser.ParseFile(token.NewFileSet(), "cas.go", changed, 0) + require.NoError(t, err) + require.Error(t, patchCASVerdictCounters(file), "changed rejection semantics cannot silently relabel counters") + } +} + +func TestOverlayIsExplicitAndFailsOnAnchorDrift(t *testing.T) { + t.Parallel() + root, err := filepath.Abs("../..") + require.NoError(t, err) + path := filepath.Join(root, "internal/server/raft_servers.go") + before, err := os.ReadFile(path) + require.NoError(t, err) + output := filepath.Join(t.TempDir(), "overlay") + require.NoError(t, makeOverlay(root, output)) + after, err := os.ReadFile(path) + require.NoError(t, err) + require.Equal(t, before, after) + require.NotContains(t, string(after), "internal/casbenchmark") + manifest, err := os.ReadFile(filepath.Join(output, "sha256.json")) + require.NoError(t, err) + var hashes map[string]string + require.NoError(t, json.Unmarshal(manifest, &hashes)) + for name, expected := range hashes { + body, err := os.ReadFile(filepath.Join(output, name)) + require.NoError(t, err) + digest := sha256.Sum256(body) + require.Equal(t, expected, hex.EncodeToString(digest[:])) + } + methods, err := os.ReadFile(filepath.Join(output, "internal/clusterbootstrap/public_methods.go")) + require.NoError(t, err) + require.Contains(t, string(methods), "/benchmark.FencedOnePhase/Fresh") + require.Contains(t, string(methods), "/benchmark.FencedOnePhase/Window") + classifier, err := os.ReadFile(filepath.Join(output, "kv/fsm_append_batch.go")) + require.NoError(t, err) + require.Contains(t, string(classifier), "if benchmeter.ApplyOnlyCAS() {") + walCounters, err := os.ReadFile(filepath.Join(output, "internal/raftengine/etcd/wal_store.go")) + require.NoError(t, err) + require.Contains(t, string(walCounters), "raft_wal_entry_save_attempts") + require.Error(t, makeOverlay(root, output), "artifacts are never overwritten") + require.Error(t, makeOverlay(t.TempDir(), filepath.Join(t.TempDir(), "missing"))) +} + +func TestCASPredicateCounterIncludesLostCallbacks(t *testing.T) { + t.Parallel() + const source = `package kv +func compareAndStageCAS() error { return ErrCASMismatch } +` + file, err := parser.ParseFile(token.NewFileSet(), "cas.go", source, 0) + require.NoError(t, err) + require.NoError(t, patchCASPredicateResult(file)) + var body bytes.Buffer + require.NoError(t, format.Node(&body, token.NewFileSet(), file)) + require.Contains(t, body.String(), "(benchVerdict error)") + require.Contains(t, body.String(), "defer func()") + require.Contains(t, body.String(), "benchmarkRecordCASPredicateVerdict(benchVerdict)") + require.Contains(t, body.String(), "return ErrCASMismatch") + require.Error(t, patchCASPredicateResult(file), "changed/named signatures require explicit instrumentation review") +} + +func TestCASPrecheckHintCounterRequiresExactBindings(t *testing.T) { + t.Parallel() + const source = `package kv +func adaptiveVersionCASMismatch() bool { + head, err := store.GetVersionAt(ctx, group.Store, mut.Key, ts) + return casPrecheckDiffers(head, mut.ExpectedCommitTs, err) +}` + file, err := parser.ParseFile(token.NewFileSet(), "cas.go", source, 0) + require.NoError(t, err) + require.NoError(t, patchCASPrecheckHint(file)) + var body bytes.Buffer + require.NoError(t, format.Node(&body, token.NewFileSet(), file)) + require.Contains(t, body.String(), "benchmarkRecordCASPrecheckHint(head, mut.ExpectedCommitTs, err)") + for _, changed := range []string{strings.ReplaceAll(source, "head, err :=", "other, err :="), strings.ReplaceAll(source, "store.GetVersionAt", "store.GetAt")} { + file, err := parser.ParseFile(token.NewFileSet(), "cas.go", changed, 0) + require.NoError(t, err) + require.Error(t, patchCASPrecheckHint(file)) + } +} + +func TestPKIBindsExactMembersAndVerifiableTLS(t *testing.T) { + t.Parallel() + output := filepath.Join(t.TempDir(), "pki") + addresses := "192.0.2.1:50051,192.0.2.2:50051,192.0.2.3:50051" + require.NoError(t, preparePKI(addresses, output, "/test/ops")) + require.Error(t, preparePKI(addresses, output, "/test/ops")) + body, err := os.ReadFile(filepath.Join(output, "experiment.json")) + require.NoError(t, err) + var exp experiment + require.NoError(t, json.Unmarshal(body, &exp)) + require.Len(t, exp.Nodes, voterCount) + for _, node := range exp.Nodes { + dir := filepath.Join(output, node.Name) + credentials, err := verifiedClientCredentials(dir) + require.NoError(t, err) + require.NotNil(t, credentials) + pair, err := tls.LoadX509KeyPair(filepath.Join(dir, "node.crt"), filepath.Join(dir, "node.key")) + require.NoError(t, err) + cert, err := x509.ParseCertificate(pair.Certificate[0]) + require.NoError(t, err) + require.NoError(t, cert.VerifyHostname("localhost")) + ca, err := os.ReadFile(filepath.Join(dir, "ca.pem")) + require.NoError(t, err) + block, _ := pem.Decode(ca) + require.NotNil(t, block) + root, err := x509.ParseCertificate(block.Bytes) + require.NoError(t, err) + roots := x509.NewCertPool() + roots.AddCert(root) + _, err = cert.Verify(x509.VerifyOptions{Roots: roots, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}) + require.NoError(t, err) + info, err := os.Stat(filepath.Join(dir, "node.key")) + require.NoError(t, err) + require.Equal(t, os.FileMode(privateFileMode), info.Mode().Perm()) + require.NotEmpty(t, node.MemberID, "identities use decimal strings without float rounding") + } + require.Error(t, preparePKI("192.0.2.1:1,192.0.2.1:1,192.0.2.3:1", filepath.Join(t.TempDir(), "invalid"), "/ops")) + require.Error(t, preparePKI(addresses, filepath.Join(t.TempDir(), "invalid"), "relative")) +} diff --git a/cmd/casbench/campaign.go b/cmd/casbench/campaign.go new file mode 100644 index 000000000..d9d103edd --- /dev/null +++ b/cmd/casbench/campaign.go @@ -0,0 +1,308 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + "path/filepath" + "time" + + "github.com/cockroachdb/errors" + "google.golang.org/grpc" +) + +const decisionDuration = 120 * time.Second +const decisionWarmup = 30 * time.Second +const decisionPairs = 10 +const maximumRate = 65536 +const namespacePrefixKey = "prefix" + +type campaignConfig struct { + Endpoint string `json:"endpoint"` + Voters string `json:"voters"` + TLS string `json:"-"` + Output string `json:"-"` + Duration time.Duration `json:"duration_ns"` + Warmup time.Duration `json:"warmup_ns"` + Pairs int `json:"pairs"` + Rate int `json:"fixed_rate"` + Cell string `json:"cell"` +} + +type campaign struct { + config campaignConfig + state *loadState + connections map[string]*grpc.ClientConn + identity map[string]nodeIdentity + summaries []trialSummary + root *os.Root +} + +type nodeIdentity struct { + Term uint64 `json:"term,string"` + Config uint64 `json:"config,string"` + Leader string `json:"leader"` +} + +func campaignCommand(fs *flag.FlagSet, args []string) error { + var c campaignConfig + fs.StringVar(&c.Endpoint, "endpoint", "", "fixed leader endpoint") + fs.StringVar(&c.Voters, "voters", "", "three voter endpoints") + fs.StringVar(&c.TLS, "tls-dir", "", "verified TLS directory") + fs.StringVar(&c.Output, "output", "", "new output directory") + fs.DurationVar(&c.Duration, "duration", decisionDuration, "measured and calibration duration") + fs.DurationVar(&c.Warmup, "warmup", decisionWarmup, "warmup before each measured arm") + fs.IntVar(&c.Pairs, "pairs", decisionPairs, "matched alternating pairs") + fs.IntVar(&c.Rate, "rate", 0, "diagnostic fixed rate; zero calibrates") + fs.StringVar(&c.Cell, "cell", cellPrimary, "primary or hot") + if err := fs.Parse(args); err != nil { + return errors.WithStack(err) + } + if err := c.validate(); err != nil { + return err + } + return runCampaign(c) +} + +func (c campaignConfig) validate() error { + if c.Output == "" || c.Endpoint == "" || c.Warmup < time.Second || c.Pairs < 1 || c.Pairs > decisionPairs || c.Rate < 0 || c.Rate > maximumRate { + return fmt.Errorf("invalid bounded campaign parameters") + } + return validateTrial(trialSpec{Arm: armFresh, Cell: c.Cell, Rate: max(1, c.Rate), Duration: c.Duration}) +} + +func runCampaign(config campaignConfig) error { + c, err := openCampaign(config) + if err != nil { + return err + } + defer c.close() + ctx := context.Background() + if err := c.initialize(ctx); err != nil { + return err + } + rate := config.Rate + if rate == 0 { + control, err := c.calibrate(ctx) + if err != nil { + return err + } + rate = max(1, control*decisionOfferedPercent/percentageDenominator) + } + if err := c.writeJSON("frozen-rate.json", map[string]int{"rate": rate}); err != nil { + return err + } + if err := c.prepareMeasurement(ctx); err != nil { + return err + } + if err := c.pairs(ctx, rate); err != nil { + return err + } + if err := c.verifyHeads(ctx); err != nil { + return err + } + return c.writeJSON("result.json", c.report()) +} + +func (c *campaign) prepareMeasurement(ctx context.Context) error { + state, err := seedState(ctx, c.connections[c.config.Endpoint], fmt.Sprintf("bench1535/measured-%d/", time.Now().UnixNano()), c.config.Cell) + if err != nil { + return err + } + c.state = state + if err := c.writeJSON("measurement-initial.json", state.initial); err != nil { + return err + } + return c.writeJSON("measurement-namespace.json", map[string]string{namespacePrefixKey: state.prefix}) +} + +func openCampaign(config campaignConfig) (*campaign, error) { + if err := privateDirectory(config.Output); err != nil { + return nil, err + } + root, err := os.OpenRoot(config.Output) + if err != nil { + return nil, errors.WithStack(err) + } + c := &campaign{config: config, root: root, connections: make(map[string]*grpc.ClientConn)} + if err := c.connect(); err != nil { + c.close() + return nil, err + } + if err := c.writeJSON("config.json", config); err != nil { + c.close() + return nil, err + } + return c, nil +} + +func (c *campaign) connect() error { + voters, err := validateVoters(c.config.Voters) + if err != nil { + return err + } + options, err := clientOptions(c.config.TLS, false) + if err != nil { + return err + } + for _, voter := range voters { + conn, err := grpc.NewClient("passthrough:///"+voter, options...) + if err != nil { + return errors.WithStack(err) + } + c.connections[voter] = conn + } + if c.connections[c.config.Endpoint] == nil { + return fmt.Errorf("fixed endpoint is not a voter") + } + return nil +} + +func (c *campaign) close() { + for _, conn := range c.connections { + _ = conn.Close() + } + _ = c.root.Close() +} + +func (c *campaign) initialize(ctx context.Context) error { + if err := c.stable(ctx, true); err != nil { + return err + } + prefix := fmt.Sprintf("bench1535/%s-%d/", c.config.Cell, time.Now().UnixNano()) + state, err := seedState(ctx, c.connections[c.config.Endpoint], prefix, c.config.Cell) + if err != nil { + return err + } + c.state = state + if err := c.writeJSON("initial.json", state.initial); err != nil { + return err + } + if err := c.writeJSON("namespace.json", map[string]string{namespacePrefixKey: prefix}); err != nil { + return err + } + // The first versioned read performs activation outside all measured windows. + record := new(eventRecord) + if !state.refresh(ctx, 0, 0, record) { + return fmt.Errorf("versioned-read activation failed") + } + return c.stable(ctx, false) +} + +func (c *campaign) writeJSON(name string, value any) error { + body, err := json.MarshalIndent(value, "", " ") + if err != nil { + return errors.WithStack(err) + } + return privateFile(filepath.Join(c.config.Output, name), body) +} + +func (c *campaign) calibrate(ctx context.Context) (int, error) { + low, high := 0, 16 + for { + passed, err := c.calibrationTrial(ctx, high) + if err != nil { + return 0, err + } + if !passed { + break + } + low = high + if high >= maximumRate { + return 0, fmt.Errorf("calibration did not reach capacity bound") + } + high *= 2 + } + if low == 0 { + return 0, fmt.Errorf("control cannot sustain initial 16/s rate") + } + for float64(high-low)/float64(low) > calibrationTolerance { + middle := (low + high) / bisectionDivisor + if middle == low { + break + } + passed, err := c.calibrationTrial(ctx, middle) + if err != nil { + return 0, err + } + if passed { + low = middle + } else { + high = middle + } + } + return low, c.writeJSON("calibration.json", map[string]int{"highest_passing": low, "lowest_failing": high}) +} + +func (c *campaign) calibrationTrial(ctx context.Context, rate int) (bool, error) { + name := fmt.Sprintf("calibration-%d", rate) + if err := c.seedCalibration(ctx, name); err != nil { + return false, err + } + warmup, err := c.window(ctx, trialSpec{Name: name + "-warm", Arm: armFresh, Cell: c.config.Cell, Rate: rate, Duration: c.config.Warmup, Seed: traceSeed}) + if err != nil { + return false, err + } + if warmup.Unknown > 0 { + if err := c.seedCalibration(ctx, name+"-postwarm"); err != nil { + return false, err + } + } + summary, err := c.window(ctx, trialSpec{Name: name, Arm: armFresh, Cell: c.config.Cell, Rate: rate, Duration: c.config.Duration, Seed: traceSeed}) + if err != nil { + return false, err + } + // Failed calibration windows are diagnostics only. Each subsequent trial + // uses a new namespace after all prior receiver work has drained. + return summary.calibrationPass(), nil +} + +func (c *campaign) seedCalibration(ctx context.Context, name string) error { + state, err := seedState(ctx, c.connections[c.config.Endpoint], fmt.Sprintf("bench1535/%s-%d/", name, time.Now().UnixNano()), c.config.Cell) + if err != nil { + return err + } + c.state = state + if err := c.writeJSON(name+".initial.json", state.initial); err != nil { + return err + } + return c.writeJSON(name+".namespace.json", map[string]string{namespacePrefixKey: state.prefix}) +} + +func (c *campaign) pairs(ctx context.Context, rate int) error { + plan := c.pairPlan(rate) + if err := c.writeJSON("frozen-plan.json", plan); err != nil { + return err + } + for _, spec := range plan { + summary, err := c.window(ctx, spec) + if err != nil { + return err + } + if summary.Unknown > 0 { + return fmt.Errorf("measurement/warmup has unknown writes; no accepted decision result") + } + } + return nil +} + +func (c *campaign) pairPlan(rate int) []trialSpec { + var plan []trialSpec + for pair := 0; pair < c.config.Pairs; pair++ { + arms := []string{armFresh, armCAS} + if pair%2 != 0 { + arms[0], arms[1] = arms[1], arms[0] + } + for _, arm := range arms { + seed := traceSeed + uint64(pair) + warm := trialSpec{Name: fmt.Sprintf("pair-%02d-%s-warm", pair, arm), Arm: arm, Cell: c.config.Cell, Rate: rate, Duration: c.config.Warmup, Seed: seed} + plan = append(plan, warm) + measured := warm + measured.Name, measured.Duration = fmt.Sprintf("pair-%02d-%s", pair, arm), c.config.Duration + plan = append(plan, measured) + } + } + return plan +} diff --git a/cmd/casbench/campaign_test.go b/cmd/casbench/campaign_test.go new file mode 100644 index 000000000..ee1fd2ab5 --- /dev/null +++ b/cmd/casbench/campaign_test.go @@ -0,0 +1,185 @@ +package main + +import ( + "context" + "fmt" + "testing" + "time" + + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestTraceMatchesArmsAndPartitions(t *testing.T) { + t.Parallel() + spec := trialSpec{Name: "pair", Cell: cellPrimary, Rate: 1024, Duration: time.Second, Seed: traceSeed} + first := makeTrace(spec) + spec.Arm = armCAS + require.Equal(t, first, makeTrace(spec)) + require.Len(t, first, 1024) + for _, item := range first { + require.Equal(t, item.ID%trialWorkers, item.Key/(primaryKeys/trialWorkers)) + require.GreaterOrEqual(t, item.ScheduledNS, int64(0)) + require.Less(t, item.ScheduledNS, int64(time.Second)) + } + for attempt := 0; attempt < maxAttempts-1; attempt++ { + for id := 0; id < 1000; id++ { + delay := retryDelay(traceSeed, id, attempt) + require.Equal(t, delay, retryDelay(traceSeed, id, attempt)) + require.GreaterOrEqual(t, delay, time.Duration(0)) + require.LessOrEqual(t, delay, time.Millisecond<= maxAttempts-1 { + return 0 + } + rng := deterministicStream{seed: seed + uint64(id), counter: uint64(attempt)} + bound := uint32(time.Millisecond) << attempt + return time.Duration(rng.bounded(bound + 1)) +} + +func (s *loadState) update(ctx context.Context, arm string, req *pb.CompareAndSwapRequest, start time.Time) (*pb.CompareAndSwapResponse, attemptRecord) { + step := attemptRecord{Expected: req.ExpectedCommitTs, SentNS: time.Since(start).Nanoseconds()} + response := new(pb.CompareAndSwapResponse) + var err error + if arm == armCAS { + response, err = s.client.CompareAndSwap(ctx, req) + } else { + err = s.connection.Invoke(ctx, casbenchmark.Prefix+"Fresh", req, response) + } + step.EndNS, step.Result = time.Since(start).Nanoseconds(), classifyUpdate(arm, req.ExpectedCommitTs, response, err) + if err != nil { + step.Code = status.Code(err).String() + } + if step.Result == outcomeSuccess { + step.New = response.GetNewCommitTs() + } + return response, step +} + +func classifyUpdate(arm string, expected uint64, response *pb.CompareAndSwapResponse, err error) string { + if err == nil { + if response.GetMismatch() { + return outcomeMismatch + } + if response.GetNewCommitTs() > expected { + return outcomeSuccess + } + return outcomeUnknown + } + if status.Code(err) != codes.Aborted { + return outcomeUnknown + } + if arm == armFresh { + return outcomeRejected + } + for _, detail := range status.Convert(err).Details() { + info, ok := detail.(*errdetails.ErrorInfo) + if ok && info.Domain == "elastickv.public.grpc" && info.Reason == "PROVEN_NONCOMMIT" { + return outcomeRejected + } + } + return outcomeUnknown +} + +func (s *loadState) confirm(worker, key int, ts uint64, value []byte) { + s.tokens[worker][key] = ts + s.mu.Lock() + defer s.mu.Unlock() + if ts > s.heads[key].TS { + s.heads[key] = knownHead{TS: ts, Value: value} + } +} + +func (s *loadState) refresh(ctx context.Context, worker, key int, record *eventRecord) bool { + record.Reads++ + response, err := s.client.Get(ctx, &pb.GetRequest{Key: s.key(key), NeedCommitTs: true}) + if err != nil || response.GetCommitTs() == 0 { + return false + } + s.tokens[worker][key] = response.GetCommitTs() + return true +} diff --git a/cmd/casbench/overlay.go b/cmd/casbench/overlay.go new file mode 100644 index 000000000..224bf2ec1 --- /dev/null +++ b/cmd/casbench/overlay.go @@ -0,0 +1,623 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "go/ast" + "go/format" + "go/parser" + "go/token" + "os" + "path/filepath" + "strconv" + + "github.com/cockroachdb/errors" +) + +const meterImport = "github.com/bootjp/elastickv/internal/casbenchmark/meter" + +type overlayBuilder struct { + root, output string + replace map[string]string + digests map[string]string +} + +func makeOverlay(root, output string) error { + b, err := newOverlayBuilder(root, output) + if err != nil { + return err + } + return b.generate() +} + +func newOverlayBuilder(root, output string) (*overlayBuilder, error) { + if output == "" { + return nil, fmt.Errorf("output directory is required") + } + var err error + root, err = filepath.Abs(root) + if err != nil { + return nil, errors.WithStack(err) + } + output, err = filepath.Abs(output) + if err != nil { + return nil, errors.WithStack(err) + } + if err := privateDirectory(output); err != nil { + return nil, errors.WithStack(err) + } + return &overlayBuilder{root: root, output: output, replace: make(map[string]string), digests: make(map[string]string)}, nil +} + +func (b *overlayBuilder) generate() error { + if err := b.patch("internal/server/raft_servers.go", patchBenchmarkServer); err != nil { + return errors.WithStack(err) + } + if err := b.patch("internal/clusterbootstrap/public_methods.go", patchBenchmarkMethods); err != nil { + return err + } + if err := b.patch("store/lsm_store.go", patchBenchmarkFS); err != nil { + return err + } + for path, functions := range map[string]map[string]string{ + "internal/raftengine/etcd/engine.go": { + "LinearizableRead": "benchmeter.Count(\"read_index_calls\", 1)", + "VerifyLeader": "benchmeter.Count(\"verify_leader_calls\", 1)", + "proposeWithTermAndTTLInlineCut": "benchmeter.Count(\"raft_proposal_calls\", 1); benchmeter.Count(\"raft_proposal_payload_bytes\", uint64(len(data)))", + "applyCommitted": "benchmeter.Count(\"raft_committed_entries\", uint64(len(entries)))", + }, + "internal/raftengine/etcd/wal_store.go": { + "persistReadyToWAL": "benchmeter.Count(\"raft_wal_persist_attempts\", 1); benchmeter.Count(\"raft_wal_persist_entries\", uint64(len(rd.Entries)))", + }, + "kv/fsm_append_batch.go": { + "IsAppendBatchPayload": "if benchmeter.ApplyOnlyCAS() { return false }", + }, + "kv/hlc.go": { + "Next": "benchmeter.Count(\"hlc_next_calls\", 1)", + "NextFenced": "benchmeter.Count(\"hlc_fenced_next_calls\", 1)", + "NextBatchFenced": "benchmeter.Count(\"hlc_fenced_batch_calls\", 1)", + }, + "kv/transaction.go": { + "submitUserProposal": "benchmarkRecordSubmission(reqs, data)", + "interpretProposalResult": "benchmarkRecordProposalResult(result, reqs)", + }, + "kv/fsm.go": { + "applyDecodedRequests": "benchmarkRecordApply(reqs)", + }, + "kv/fsm_cas.go": { + "applyCASEntry": "benchmarkRecordApply(reqs)", + "compareAndStageCAS": "benchmeter.Count(\"cas_predicate_checks\", 1)", + }, + "kv/sharded_coordinator.go": { + + "RunHLCLeaseRenewal": "if benchmeter.Preparing() { <-ctx.Done(); return }", + }, + "kv/version_cas_precheck.go": { + "WithAdaptiveVersionCASPrecheck": "if benchmeter.ApplyOnlyCAS() { return c }; benchmeter.EnableAdaptiveCAS()", + "adaptiveVersionCASMismatch": "benchmeter.Count(\"cas_precheck_hint_reads\", 1)", + "readCASPrecheckHead": "benchmeter.Count(\"cas_precheck_fenced_reads\", 1)", + }, + "internal/server/shutdown.go": { + "arm": "if benchmeter.Preparing() { return }", + }, + } { + if err := b.patch(path, func(_ *token.FileSet, file *ast.File) error { + return patchBenchmarkFunctions(path, file, functions) + }); err != nil { + return errors.WithStack(err) + } + } + if err := b.save("kv/cas_benchmark_overlay.go", []byte(verdictOverlay)); err != nil { + return errors.WithStack(err) + } + return b.manifests() +} + +func patchBenchmarkFunctions(path string, file *ast.File, functions map[string]string) error { + if err := instrumentFunctions(file, functions); err != nil { + return err + } + switch path { + case "internal/raftengine/etcd/wal_store.go": + return patchRaftWALEntrySaveCounter(file) + case "kv/fsm_cas.go": + if err := patchCASVerdictCounters(file); err != nil { + return err + } + return patchCASPredicateResult(file) + case "kv/version_cas_precheck.go": + return patchCASPrecheckHint(file) + default: + return nil + } +} + +func patchBenchmarkMethods(_ *token.FileSet, file *ast.File) error { + count := 0 + ast.Inspect(file, func(node ast.Node) bool { + fn, ok := node.(*ast.FuncDecl) + if !ok || fn.Name.Name != "BootstrapPublicGRPCMethods" { + return true + } + for _, statement := range fn.Body.List { + ret, ok := statement.(*ast.ReturnStmt) + if !ok || len(ret.Results) != 1 { + continue + } + name, ok := ret.Results[0].(*ast.Ident) + if !ok || name.Name != "methods" { + continue + } + args := []ast.Expr{name} + for _, method := range []string{"Fresh", "Acquire", "Commit", "Cancel", "Window", "Seed"} { + args = append(args, &ast.BasicLit{Kind: token.STRING, Value: strconv.Quote("/benchmark.FencedOnePhase/" + method)}) + } + ret.Results[0] = &ast.CallExpr{Fun: ast.NewIdent("append"), Args: args} + count++ + } + return false + }) + if count != 1 { + return fmt.Errorf("expected one benchmark public-method anchor, found %d", count) + } + return nil +} + +func (b *overlayBuilder) manifests() error { + for name, value := range map[string]any{"overlay.json": map[string]any{"Replace": b.replace}, "sha256.json": b.digests} { + if err := privateJSON(filepath.Join(b.output, name), value); err != nil { + return err + } + } + return nil +} + +func (b *overlayBuilder) patch(path string, edit func(*token.FileSet, *ast.File) error) error { + set := token.NewFileSet() + file, err := parser.ParseFile(set, filepath.Join(b.root, path), nil, parser.ParseComments) + if err != nil { + return errors.WithStack(err) + } + if err := edit(set, file); err != nil { + return fmt.Errorf("%s: %w", path, err) + } + ast.SortImports(set, file) + var data bytes.Buffer + if err := format.Node(&data, set, file); err != nil { + return errors.WithStack(err) + } + return b.save(path, data.Bytes()) +} + +func (b *overlayBuilder) save(path string, data []byte) error { + target := filepath.Join(b.output, path) + root, err := os.OpenRoot(b.output) + if err != nil { + return errors.WithStack(err) + } + defer root.Close() + if err := root.MkdirAll(filepath.Dir(path), privateDirectoryMode); err != nil { + return errors.WithStack(err) + } + if err := privateFile(target, data); err != nil { + return errors.WithStack(err) + } + b.replace[filepath.Join(b.root, path)] = target + digest := sha256.Sum256(data) + b.digests[path] = hex.EncodeToString(digest[:]) + return nil +} + +func statements(source string) ([]ast.Stmt, error) { + file, err := parser.ParseFile(token.NewFileSet(), "statements.go", "package p; func f(){"+source+"}", 0) + if err != nil { + return nil, errors.WithStack(err) + } + fn, ok := file.Decls[0].(*ast.FuncDecl) + if !ok { + return nil, fmt.Errorf("invalid instrumentation block") + } + return fn.Body.List, nil +} + +func instrumentFunctions(file *ast.File, functions map[string]string) error { + seen := make(map[string]int) + needsMeter := false + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + if source, found := functions[fn.Name.Name]; found { + added, err := statements(source) + if err != nil { + return errors.WithStack(err) + } + fn.Body.List = append(added, fn.Body.List...) + needsMeter = needsMeter || referencesMeter(added) + seen[fn.Name.Name]++ + } + } + for name := range functions { + if seen[name] != 1 { + return fmt.Errorf("instrumentation requires exactly one %s, found %d", name, seen[name]) + } + } + if needsMeter { + addNamedImport(file, "benchmeter", meterImport) + } + return nil +} + +func referencesMeter(statements []ast.Stmt) bool { + found := false + for _, statement := range statements { + ast.Inspect(statement, func(node ast.Node) bool { + name, ok := node.(*ast.Ident) + if ok && name.Name == "benchmeter" { + found = true + } + return true + }) + } + return found +} + +func patchBenchmarkFS(_ *token.FileSet, file *ast.File) error { + count := 0 + ast.Inspect(file, func(node ast.Node) bool { + fn, ok := node.(*ast.FuncDecl) + if !ok || fn.Name.Name != "defaultPebbleOptionsWithCache" { + return true + } + ast.Inspect(fn.Body, func(node ast.Node) bool { + field, ok := node.(*ast.KeyValueExpr) + if !ok { + return true + } + name, ok := field.Key.(*ast.Ident) + if ok && name.Name == "FS" { + field.Value = &ast.CallExpr{Fun: &ast.SelectorExpr{X: ast.NewIdent("benchmeter"), Sel: ast.NewIdent("WrapFS")}, Args: []ast.Expr{field.Value}} + count++ + } + return true + }) + return false + }) + if count != 1 { + return fmt.Errorf("expected one benchmark filesystem anchor, found %d", count) + } + addNamedImport(file, "benchmeter", meterImport) + return patchStoreFenceCounter(file) +} + +func namedFunction(file *ast.File, name string) (*ast.FuncDecl, error) { + var found *ast.FuncDecl + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if ok && fn.Name.Name == name { + if found != nil { + return nil, fmt.Errorf("ambiguous function %s", name) + } + found = fn + } + } + if found == nil || found.Body == nil { + return nil, fmt.Errorf("missing function %s", name) + } + return found, nil +} + +func expressionName(expr ast.Expr) string { + switch value := expr.(type) { + case *ast.Ident: + return value.Name + case *ast.SelectorExpr: + return expressionName(value.X) + "." + value.Sel.Name + default: + return "" + } +} + +func patchCASVerdictCounters(file *ast.File) error { + fn, err := namedFunction(file, "compareAndStageCAS") + if err != nil { + return err + } + guards := map[string]string{"commitTS<=watermark": "cas_timestamp_fence_rejections", "head.TS>startTS": "cas_start_ts_occ_rejections"} + for _, statement := range fn.Body.List { + branch, ok := statement.(*ast.IfStmt) + if !ok { + continue + } + condition, ok := branch.Cond.(*ast.BinaryExpr) + if !ok { + continue + } + signature := expressionName(condition.X) + condition.Op.String() + expressionName(condition.Y) + if counter, found := guards[signature]; found { + if len(branch.Body.List) != 1 || !conflictReturn(branch.Body.List[0]) { + return fmt.Errorf("changed CAS rejection guard %s", signature) + } + added, err := statements("benchmeter.Count(" + strconv.Quote(counter) + ", 1)") + if err != nil { + return err + } + branch.Body.List = append(added, branch.Body.List...) + delete(guards, signature) + } + } + if len(guards) != 0 { + return fmt.Errorf("missing CAS rejection guard") + } + return nil +} + +func conflictReturn(statement ast.Stmt) bool { + ret, ok := statement.(*ast.ReturnStmt) + if !ok { + return false + } + found := false + ast.Inspect(ret, func(node ast.Node) bool { + call, ok := node.(*ast.CallExpr) + if !ok { + return true + } + name := expressionName(call.Fun) + if name == "NewWriteConflictError" || name == "store.NewWriteConflictError" { + found = true + } + return true + }) + return found +} + +func patchCASPredicateResult(file *ast.File) error { + fn, err := namedFunction(file, "compareAndStageCAS") + if err != nil { + return err + } + if fn.Type.Results == nil || len(fn.Type.Results.List) != 1 || len(fn.Type.Results.List[0].Names) != 0 || expressionName(fn.Type.Results.List[0].Type) != "error" { + return fmt.Errorf("CAS predicate result signature changed") + } + fn.Type.Results.List[0].Names = []*ast.Ident{ast.NewIdent("benchVerdict")} + added, err := statements("defer func(){ benchmarkRecordCASPredicateVerdict(benchVerdict) }()") + if err != nil { + return err + } + fn.Body.List = append(added, fn.Body.List...) + return nil +} + +func patchCASPrecheckHint(file *ast.File) error { + fn, err := namedFunction(file, "adaptiveVersionCASMismatch") + if err != nil { + return err + } + count := 0 + var body []ast.Stmt + for _, statement := range fn.Body.List { + body = append(body, statement) + if !isCASPrecheckHint(statement) { + continue + } + added, err := statements("benchmarkRecordCASPrecheckHint(head, mut.ExpectedCommitTs, err)") + if err != nil { + return err + } + body = append(body, added...) + count++ + } + if count != 1 { + return fmt.Errorf("expected one CAS hint read, found %d", count) + } + fn.Body.List = body + return nil +} + +func isCASPrecheckHint(statement ast.Stmt) bool { + assign, ok := statement.(*ast.AssignStmt) + if !ok || len(assign.Rhs) != 1 || len(assign.Lhs) != 2 { + return false + } + call, ok := assign.Rhs[0].(*ast.CallExpr) + return ok && expressionName(call.Fun) == "store.GetVersionAt" && + expressionName(assign.Lhs[0]) == "head" && expressionName(assign.Lhs[1]) == "err" +} + +func patchStoreFenceCounter(file *ast.File) error { + fn, err := namedFunction(file, "checkCommitTSFence") + if err != nil { + return err + } + added, err := statements("benchmeter.Count(\"store_timestamp_fence_rejections\", 1)") + if err != nil { + return err + } + count := 0 + ast.Inspect(fn.Body, func(node ast.Node) bool { + block, ok := node.(*ast.BlockStmt) + if !ok { + return true + } + var updated []ast.Stmt + for _, statement := range block.List { + if conflictReturn(statement) { + updated = append(updated, added...) + count++ + } + updated = append(updated, statement) + } + block.List = updated + return true + }) + if count != 1 { + return fmt.Errorf("expected one store timestamp-fence rejection, found %d", count) + } + return nil +} + +func patchBenchmarkServer(set *token.FileSet, file *ast.File) error { + count := 0 + var patchErr error + ast.Inspect(file, func(node ast.Node) bool { + block, ok := node.(*ast.BlockStmt) + if !ok { + return true + } + for i, statement := range block.List { + if !isServerAssignment(statement) { + continue + } + before, err := statements("serverOptions = append(serverOptions, grpc.ChainUnaryInterceptor(benchmeter.Unary), grpc.StatsHandler(benchmeter.WireStats{}))") + if err != nil { + patchErr = err + return false + } + after, err := statements("benchfrontend.Register(gs, shardStore, coordinate, readTracker, clusterbootstrap.BootstrapRequestAdmissionForCoordinator(coordinate))") + if err != nil { + patchErr = err + return false + } + updated := append([]ast.Stmt{}, block.List[:i]...) + updated = append(updated, before...) + updated = append(updated, statement) + updated = append(updated, after...) + block.List = append(updated, block.List[i+1:]...) + count++ + return false + } + return true + }) + if patchErr != nil { + return patchErr + } + if count != 1 { + return fmt.Errorf("expected one benchmark registration anchor, found %d", count) + } + addNamedImport(file, "benchmeter", meterImport) + addNamedImport(file, "benchfrontend", "github.com/bootjp/elastickv/internal/casbenchmark") + return nil +} + +func isServerAssignment(statement ast.Stmt) bool { + assign, ok := statement.(*ast.AssignStmt) + if !ok || len(assign.Lhs) != 1 || len(assign.Rhs) != 1 { + return false + } + name, ok := assign.Lhs[0].(*ast.Ident) + if !ok || name.Name != "gs" { + return false + } + call, ok := assign.Rhs[0].(*ast.CallExpr) + if !ok { + return false + } + selector, ok := call.Fun.(*ast.SelectorExpr) + if !ok || selector.Sel.Name != "NewServer" { + return false + } + qualifier, ok := selector.X.(*ast.Ident) + return ok && qualifier.Name == "grpc" +} + +func addNamedImport(file *ast.File, name, path string) { + for _, imported := range file.Imports { + if imported.Path.Value == strconv.Quote(path) { + return + } + } + spec := &ast.ImportSpec{Name: ast.NewIdent(name), Path: &ast.BasicLit{Kind: token.STRING, Value: strconv.Quote(path)}} + file.Imports = append(file.Imports, spec) + for _, decl := range file.Decls { + if group, ok := decl.(*ast.GenDecl); ok && group.Tok == token.IMPORT { + if !group.Lparen.IsValid() { + group.Lparen = group.Pos() + } + group.Specs = append(group.Specs, spec) + return + } + } + file.Decls = append([]ast.Decl{&ast.GenDecl{Tok: token.IMPORT, Specs: []ast.Spec{spec}}}, file.Decls...) +} + +const verdictOverlay = `package kv +import ( + "bytes" + "github.com/bootjp/elastickv/internal/casbenchmark/meter" + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" +) +func benchmarkNamespace(reqs []*pb.Request) string { + for _, req := range reqs { + for _, mutation := range req.GetMutations() { + if bytes.HasPrefix(mutation.GetKey(), []byte("bench1535/")) { return "benchmark/" } + } + } + return "background/" +} +func benchmarkRecordSubmission(reqs []*pb.Request, data []byte) { + ns := benchmarkNamespace(reqs) + meter.Count(ns+"data_submission_attempts", 1) + meter.Count(ns+"data_submission_payload_bytes", uint64(len(data))) +} +func benchmarkRecordApply(reqs []*pb.Request) { + ns := benchmarkNamespace(reqs) + meter.Count(ns+"data_apply_entries", 1) + meter.Count(ns+"data_apply_requests", uint64(len(reqs))) + for _, req := range reqs { + meter.Count(ns+"data_apply_mutations", uint64(len(req.GetMutations()))) + for _, mutation := range req.GetMutations() { + if bytes.HasPrefix(mutation.GetKey(), []byte("bench1535/")) { + meter.Count("benchmark/data_apply_user_mutations", 1) + } else { meter.Count(ns+"data_apply_aux_mutations", 1) } + } + } +} +func benchmarkRecordProposalResult(result *raftengine.ProposalResult, reqs []*pb.Request) { + if result == nil { return } + ns := benchmarkNamespace(reqs) + record := func(err error) { + reason := "success" + switch { + case err == nil: + case errors.Is(err, ErrCASMismatch): reason = "exact_mismatch" + case errors.Is(err, ErrTxnLocked): reason = "locked" + case errors.Is(err, ErrRouteWriteFenced): reason = "route_fenced" + case errors.Is(err, store.ErrWriteConflict): + reason = "write_conflict" + default: reason = "other" + } + meter.Count(ns+"apply_verdict/"+reason, 1) + } + switch response := result.Response.(type) { + case nil: record(nil) + case error: record(response) + case *fsmApplyResponse: for _, err := range response.results { record(err) } + } +} +func benchmarkRecordCASPredicateVerdict(err error) { + reason := "other" + switch { + case err == nil: reason = "success" + case errors.Is(err, ErrCASMismatch): reason = "mismatch" + case errors.Is(err, ErrTxnLocked): reason = "locked" + case errors.Is(err, store.ErrWriteConflict): reason = "write_conflict" + } + meter.Count("cas_predicate_verdict/"+reason, 1) +} +func benchmarkRecordCASPrecheckHint(head store.VersionedValue, expected uint64, err error) { + reason := "error" + switch { + case errors.Is(err, store.ErrKeyNotFound): reason = "missing" + case err == nil && head.TS == expected: reason = "match" + case err == nil: reason = "different" + } + meter.Count("cas_precheck_hint/"+reason, 1) +} +` diff --git a/cmd/casbench/overlay_wal.go b/cmd/casbench/overlay_wal.go new file mode 100644 index 000000000..a1cfb9edd --- /dev/null +++ b/cmd/casbench/overlay_wal.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "go/ast" +) + +// Count immediately before the actual Save, not before a possibly failing +// SaveSnap. This is an attempt counter, not a physical sync-success counter. +func patchRaftWALEntrySaveCounter(file *ast.File) error { + fn, err := namedFunction(file, "persistReadyToWAL") + if err != nil { + return err + } + added, err := statements("if len(rd.Entries) > 0 { benchmeter.Count(\"raft_wal_entry_save_attempts\", 1) }") + if err != nil { + return err + } + matches := 0 + ast.Inspect(fn.Body, func(node ast.Node) bool { + block, ok := node.(*ast.BlockStmt) + if !ok { + return true + } + for i, statement := range block.List { + if !isRaftWALSave(statement) { + continue + } + replacement := make([]ast.Stmt, 0, len(block.List)+len(added)) + replacement = append(replacement, block.List[:i]...) + replacement = append(replacement, added...) + replacement = append(replacement, block.List[i:]...) + block.List = replacement + matches++ + break + } + return true + }) + if matches != 1 { + return fmt.Errorf("entry WAL counter requires one exact Save call, found %d", matches) + } + return nil +} + +func isRaftWALSave(statement ast.Stmt) bool { + branch, ok := statement.(*ast.IfStmt) + if !ok { + return false + } + assignment, ok := branch.Init.(*ast.AssignStmt) + if !ok || len(assignment.Rhs) != 1 { + return false + } + call, ok := assignment.Rhs[0].(*ast.CallExpr) + return ok && expressionName(call.Fun) == "persist.Save" && len(call.Args) == 2 && + expressionName(call.Args[0]) == "rd.HardState" && expressionName(call.Args[1]) == "rd.Entries" +} diff --git a/cmd/casbench/overlay_wal_test.go b/cmd/casbench/overlay_wal_test.go new file mode 100644 index 000000000..ecdd63ff5 --- /dev/null +++ b/cmd/casbench/overlay_wal_test.go @@ -0,0 +1,37 @@ +package main + +import ( + "bytes" + "go/format" + "go/parser" + "go/token" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRaftWALEntryCounterFollowsSnapshotPersistence(t *testing.T) { + const source = `package etcd +func persistReadyToWAL(persist Storage, rd Ready) error { + if rd.Snapshot != nil { if err := persist.SaveSnap(rd.Snapshot); err != nil { return err } } + if rd.HardState != nil || len(rd.Entries) > 0 { + if err := persist.Save(rd.HardState, rd.Entries); err != nil { return err } + } + return nil +}` + file, err := parser.ParseFile(token.NewFileSet(), "wal.go", source, 0) + require.NoError(t, err) + require.NoError(t, patchRaftWALEntrySaveCounter(file)) + var output bytes.Buffer + require.NoError(t, format.Node(&output, token.NewFileSet(), file)) + body := output.String() + count := strings.Index(body, "benchmeter.Count(") + require.Greater(t, count, strings.Index(body, "persist.SaveSnap(")) + require.Less(t, count, strings.Index(body, "persist.Save(")) + require.Equal(t, 1, strings.Count(body, "raft_wal_entry_save_attempts")) + require.Contains(t, body, "if len(rd.Entries) > 0 {") + changed, err := parser.ParseFile(token.NewFileSet(), "wal.go", strings.ReplaceAll(source, "rd.HardState, rd.Entries", "rd.HardState, otherEntries"), 0) + require.NoError(t, err) + require.Error(t, patchRaftWALEntrySaveCounter(changed)) +} diff --git a/cmd/casbench/pki.go b/cmd/casbench/pki.go new file mode 100644 index 000000000..07fd6f84c --- /dev/null +++ b/cmd/casbench/pki.go @@ -0,0 +1,231 @@ +package main + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/json" + "encoding/pem" + "fmt" + "math/big" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/bootjp/elastickv/internal/clusterbootstrap" + "github.com/bootjp/elastickv/internal/raftengine/etcd" + "github.com/cockroachdb/errors" +) + +type experimentNode struct { + Name string `json:"name"` + Address string `json:"address"` + MemberID string `json:"member_id"` +} + +type experiment struct { + Cluster string `json:"cluster_uuid"` + Operation string `json:"operation_id"` + Nodes []experimentNode `json:"nodes"` +} + +func privateFile(path string, data []byte) error { + root, err := os.OpenRoot(filepath.Dir(path)) + if err != nil { + return errors.WithStack(err) + } + defer root.Close() + f, err := root.OpenFile(filepath.Base(path), os.O_CREATE|os.O_EXCL|os.O_WRONLY, privateFileMode) + if err != nil { + return errors.WithStack(err) + } + _, writeErr := f.Write(data) + closeErr := f.Close() + if writeErr != nil { + return errors.WithStack(writeErr) + } + return errors.WithStack(closeErr) +} + +const privateFileMode = 0o600 +const privateDirectoryMode = 0o700 +const voterCount = 3 +const certificateLifetime = 48 * time.Hour +const firstLeafSerial = 2 + +func privateDirectory(path string) error { + root, err := os.OpenRoot(filepath.Dir(path)) + if err != nil { + return errors.WithStack(err) + } + defer root.Close() + return errors.WithStack(root.Mkdir(filepath.Base(path), privateDirectoryMode)) +} + +func privateJSON(path string, value any) error { + data, err := json.MarshalIndent(value, "", " ") + if err != nil { + return errors.WithStack(err) + } + return privateFile(path, data) +} + +func preparePKI(addresses, output, remote string) error { + if output == "" || !filepath.IsAbs(remote) { + return fmt.Errorf("output and absolute remote-root are required") + } + hosts, err := validateVoters(addresses) + if err != nil { + return err + } + return prepareVoterPKI(hosts, output, remote) +} + +func validateVoters(addresses string) ([]string, error) { + hosts := strings.Split(addresses, ",") + if len(hosts) != voterCount { + return nil, fmt.Errorf("exactly three voter addresses are required") + } + seen := make(map[string]bool) + for _, address := range hosts { + host, port, err := net.SplitHostPort(address) + if err != nil || net.ParseIP(host) == nil || seen[address] { + return nil, fmt.Errorf("distinct numeric voter addresses are required: %q", address) + } + parsed, err := strconv.ParseUint(port, 10, 16) + if err != nil || parsed == 0 { + return nil, fmt.Errorf("invalid voter port: %q", address) + } + seen[address] = true + } + return hosts, nil +} + +func prepareVoterPKI(hosts []string, output, remote string) error { + if err := privateDirectory(output); err != nil { + return errors.WithStack(err) + } + authority, err := newBenchmarkAuthority() + if err != nil { + return err + } + var cluster, operation, token [16]byte + for _, target := range [][]byte{cluster[:], operation[:], token[:]} { + if _, err := rand.Read(target); err != nil { + return errors.WithStack(err) + } + } + clusterName := fmt.Sprintf("%x-%x-%x-%x-%x", cluster[:4], cluster[4:6], cluster[6:8], cluster[8:10], cluster[10:]) + exp := experiment{Cluster: clusterName, Operation: hex.EncodeToString(operation[:])} + members := make([]clusterbootstrap.BootstrapPeerMemberJSON, 0, len(hosts)) + pins := clusterbootstrap.BootstrapObservationPinsJSON{Version: 1, Cluster: clusterName, Group: "1", + Minimum: clusterbootstrap.BootstrapBaselineMinimumJSON{Entry: 1, Snapshot: 1, Session: 1}} + configs := make([]clusterbootstrap.BootstrapPeerJSON, 0, len(hosts)) + for index, address := range hosts { + name := fmt.Sprintf("n%d", index+1) + id := etcd.DeriveNodeID(name) + pin, err := authority.writeVoter(output, name, address, index, token[:]) + if err != nil { + return err + } + members = append(members, clusterbootstrap.BootstrapPeerMemberJSON{ID: id, Address: address, Key: pin, Groups: []uint64{1}}) + pins.Members = append(pins.Members, clusterbootstrap.BootstrapBaselineMemberJSON{ID: strconv.FormatUint(id, 10), Address: address, Key: pin, Roles: []string{"voter"}}) + configs = append(configs, clusterbootstrap.BootstrapPeerJSON{Cluster: clusterName, Local: id, CA: filepath.Join(remote, "ca.pem"), + Cert: filepath.Join(remote, "node.crt"), Key: filepath.Join(remote, "node.key"), StartupTokenFile: filepath.Join(remote, "startup-token")}) + exp.Nodes = append(exp.Nodes, experimentNode{Name: name, Address: address, MemberID: strconv.FormatUint(id, 10)}) + } + if err := writeVoterConfigs(output, remote, exp, members, configs); err != nil { + return err + } + if err := privateJSON(filepath.Join(output, "pins.json"), pins); err != nil { + return errors.WithStack(err) + } + return privateJSON(filepath.Join(output, "experiment.json"), exp) +} + +func writeVoterConfigs(output, remote string, exp experiment, members []clusterbootstrap.BootstrapPeerMemberJSON, configs []clusterbootstrap.BootstrapPeerJSON) error { + for index := range configs { + configs[index].Members = members + if err := privateJSON(filepath.Join(output, exp.Nodes[index].Name, "group-1.json"), configs[index]); err != nil { + return errors.WithStack(err) + } + configs[index].ActivationFile = filepath.Join(remote, "activation.bin") + if err := privateJSON(filepath.Join(output, exp.Nodes[index].Name, "group-1.protected.json"), configs[index]); err != nil { + return errors.WithStack(err) + } + } + return nil +} + +type benchmarkAuthority struct { + cert *x509.Certificate + key ed25519.PrivateKey + pem []byte +} + +func newBenchmarkAuthority() (*benchmarkAuthority, error) { + pub, key, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return nil, errors.WithStack(err) + } + now := time.Now() + ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "elkv-cas-benchmark"}, + NotBefore: now.Add(-time.Hour), NotAfter: now.Add(certificateLifetime), IsCA: true, BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature} + der, err := x509.CreateCertificate(rand.Reader, ca, ca, pub, key) + if err != nil { + return nil, errors.WithStack(err) + } + ca, err = x509.ParseCertificate(der) + if err != nil { + return nil, errors.WithStack(err) + } + return &benchmarkAuthority{cert: ca, key: key, pem: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})}, nil +} + +func (a *benchmarkAuthority) writeVoter(output, name, address string, index int, token []byte) (string, error) { + host, _, _ := net.SplitHostPort(address) + public, private, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return "", errors.WithStack(err) + } + leaf := &x509.Certificate{SerialNumber: big.NewInt(int64(index + firstLeafSerial)), Subject: pkix.Name{CommonName: name}, + DNSNames: []string{name, "localhost"}, IPAddresses: []net.IP{net.ParseIP(host), net.ParseIP("127.0.0.1")}, + NotBefore: a.cert.NotBefore, NotAfter: a.cert.NotAfter, KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}} + der, err := x509.CreateCertificate(rand.Reader, leaf, a.cert, public, a.key) + if err != nil { + return "", errors.WithStack(err) + } + parsed, err := x509.ParseCertificate(der) + if err != nil { + return "", errors.WithStack(err) + } + keyDER, err := x509.MarshalPKCS8PrivateKey(private) + if err != nil { + return "", errors.WithStack(err) + } + var admin [sha256.Size]byte + if _, err := rand.Read(admin[:]); err != nil { + return "", errors.WithStack(err) + } + directory := filepath.Join(output, name) + if err := privateDirectory(directory); err != nil { + return "", err + } + for filename, body := range map[string][]byte{"ca.pem": a.pem, "node.crt": pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), + "node.key": pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), "startup-token": []byte(hex.EncodeToString(token)), + "admin-token": []byte(hex.EncodeToString(admin[:]))} { + if err := privateFile(filepath.Join(directory, filename), body); err != nil { + return "", err + } + } + digest := sha256.Sum256(parsed.RawSubjectPublicKeyInfo) + return hex.EncodeToString(digest[:]), nil +} diff --git a/cmd/casbench/put.go b/cmd/casbench/put.go new file mode 100644 index 000000000..e1395d9ef --- /dev/null +++ b/cmd/casbench/put.go @@ -0,0 +1,55 @@ +package main + +import ( + "context" + "flag" + "fmt" + "os" + "strings" + + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "google.golang.org/grpc" + "google.golang.org/protobuf/encoding/protojson" +) + +func putCommand(fs *flag.FlagSet, args []string) error { + address := fs.String("endpoint", "", "leader endpoint") + directory := fs.String("tls-dir", "", "verified TLS material directory") + key := fs.String("key", "bench1535/bootstrap", "isolated benchmark key") + value := fs.String("value", "accepted-baseline", "baseline value") + if err := fs.Parse(args); err != nil { + return errors.WithStack(err) + } + if !strings.HasPrefix(*key, "bench1535/") || len(*key) > 256 || len(*value) > 16*1024 { + return fmt.Errorf("invalid benchmark key/value") + } + return baselinePut(*address, *directory, *key, *value) +} + +func baselinePut(address, directory, key, value string) error { + options, err := clientOptions(directory, false) + if err != nil { + return err + } + conn, err := grpc.NewClient("passthrough:///"+address, options...) + if err != nil { + return errors.WithStack(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), setupTimeout) + defer cancel() + response, err := pb.NewTransactionalKVClient(conn).Put(ctx, &pb.PutRequest{Key: []byte(key), Value: []byte(value)}) + if err != nil { + return errors.WithStack(err) + } + if !response.Success || response.CommitIndex == 0 { + return fmt.Errorf("put lacks a committed acknowledgment") + } + encoded, err := protojson.Marshal(response) + if err != nil { + return errors.WithStack(err) + } + _, err = fmt.Fprintln(os.Stdout, string(encoded)) + return errors.WithStack(err) +} diff --git a/cmd/casbench/report.go b/cmd/casbench/report.go new file mode 100644 index 000000000..5bcf29087 --- /dev/null +++ b/cmd/casbench/report.go @@ -0,0 +1,82 @@ +package main + +import ( + "fmt" + "slices" +) + +type pairedInterval struct { + Median float64 `json:"median"` + Lower float64 `json:"second_order"` + Upper float64 `json:"ninth_order"` +} +type campaignReport struct { + DecisionEligible bool `json:"decision_eligible"` + Passed bool `json:"passed"` + Reasons []string `json:"reasons"` + P99 pairedInterval `json:"paired_p99_ratio"` + Goodput pairedInterval `json:"paired_goodput_ratio"` + Summaries []trialSummary `json:"summaries"` +} + +func interval(ratios []float64) pairedInterval { + if len(ratios) != decisionPairs { + return pairedInterval{} + } + slices.Sort(ratios) + return pairedInterval{Median: (ratios[4] + ratios[5]) / bisectionDivisor, Lower: ratios[1], Upper: ratios[8]} +} + +func (c *campaign) report() campaignReport { + r := campaignReport{DecisionEligible: c.config.Duration >= decisionDuration && c.config.Warmup >= decisionWarmup && c.config.Pairs == decisionPairs && c.config.Rate == 0, Summaries: c.summaries} + var latency, throughput []float64 + for pair := 0; pair < c.config.Pairs; pair++ { + control, candidate := c.pairSummaries(pair) + p99, goodput := r.addPair(control, candidate) + latency, throughput = append(latency, p99), append(throughput, goodput) + } + r.P99, r.Goodput = interval(latency), interval(throughput) + limit := 0.90 + if c.config.Cell == cellHot { + limit = 1.05 + } + if r.P99.Upper > limit { + r.Reasons = append(r.Reasons, "upper paired p99 ratio exceeds decision threshold") + } + if r.Goodput.Lower < goodputLowerLimit { + r.Reasons = append(r.Reasons, "lower paired goodput ratio below threshold") + } + if !r.DecisionEligible { + r.Reasons = append(r.Reasons, "diagnostic parameters; not an adoption decision") + } + r.Passed = r.DecisionEligible && len(r.Reasons) == 0 + return r +} + +const minimumP99Samples = 1000 + +func (r *campaignReport) addPair(control, candidate trialSummary) (float64, float64) { + if control.SuccessP99NS == 0 || candidate.SuccessP99NS == 0 || control.SuccessRate == 0 { + r.Reasons = append(r.Reasons, "missing paired successes") + return 0, 0 + } + for _, arm := range []trialSummary{control, candidate} { + if arm.Success < minimumP99Samples || !arm.onTime() { + r.Reasons = append(r.Reasons, arm.Spec.Name+": sample/outcome gate failed") + } + } + return float64(candidate.SuccessP99NS) / float64(control.SuccessP99NS), candidate.SuccessRate / control.SuccessRate +} + +func (c *campaign) pairSummaries(pair int) (trialSummary, trialSummary) { + var control, candidate trialSummary + for _, s := range c.summaries { + if s.Spec.Name == fmt.Sprintf("pair-%02d-fresh", pair) { + control = s + } + if s.Spec.Name == fmt.Sprintf("pair-%02d-cas", pair) { + candidate = s + } + } + return control, candidate +} diff --git a/cmd/casbench/trial.go b/cmd/casbench/trial.go new file mode 100644 index 000000000..822b4834b --- /dev/null +++ b/cmd/casbench/trial.go @@ -0,0 +1,269 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "fmt" + "slices" + "strings" + "sync" + "time" + + pb "github.com/bootjp/elastickv/proto" +) + +const trialWorkers = 8 +const primaryKeys = 65536 +const trialValueBytes = 1024 +const operationDeadline = time.Second +const maxAttempts = 4 +const traceSeed = uint64(1535) + +type arrival struct { + Run string `json:"run"` + Seed uint64 `json:"seed"` + ID int `json:"id"` + Key int `json:"key"` + ScheduledNS int64 `json:"scheduled_ns"` +} + +type attemptRecord struct { + Expected uint64 `json:"expected,string"` + New uint64 `json:"new,string,omitempty"` + SentNS int64 `json:"sent_ns"` + EndNS int64 `json:"end_ns"` + Result string `json:"result"` + Code string `json:"grpc_code,omitempty"` +} + +type eventRecord struct { + arrival + Worker int `json:"worker"` + EndNS int64 `json:"end_ns"` + Outcome string `json:"outcome"` + Reads int `json:"refresh_reads"` + Attempts []attemptRecord `json:"attempts"` +} + +type trialSpec struct { + Name string `json:"name"` + Arm string `json:"arm"` + Cell string `json:"cell"` + Rate int `json:"rate"` + Duration time.Duration `json:"duration_ns"` + Seed uint64 `json:"seed"` +} + +type trialSummary struct { + Spec trialSpec `json:"spec"` + Scheduled int `json:"scheduled"` + Outcomes map[string]int `json:"outcomes"` + Unknown int `json:"unknown"` + Missed int `json:"deadline_misses"` + Unsent int `json:"unsent"` + Success int `json:"success"` + OnTimeSuccess int `json:"on_time_success"` + OnTimeDefinitive int `json:"on_time_definitive"` + Timeouts int `json:"write_timeouts"` + Attempts int `json:"attempts"` + Reads int `json:"refresh_reads"` + SuccessP99NS int64 `json:"success_p99_ns"` + SuccessP50NS int64 `json:"success_p50_ns"` + SuccessP95NS int64 `json:"success_p95_ns"` + AllP99NS int64 `json:"all_outcome_p99_ns"` + AllP50NS int64 `json:"all_outcome_p50_ns"` + AllP95NS int64 `json:"all_outcome_p95_ns"` + SuccessRate float64 `json:"success_per_s"` + ElapsedNS int64 `json:"elapsed_ns"` + ClientCalls map[string]int `json:"client_calls"` +} + +type trialCall func(context.Context, arrival, int, time.Time) eventRecord + +func makeTrace(spec trialSpec) []arrival { + count := int(int64(spec.Rate) * int64(spec.Duration) / int64(time.Second)) + trace := make([]arrival, count) + rng := deterministicStream{seed: spec.Seed} + run := strings.ReplaceAll(spec.Name, "-"+spec.Arm, "") + for i := range trace { + key := 0 + if spec.Cell == cellPrimary { + key = (i%trialWorkers)*(primaryKeys/trialWorkers) + int(rng.bounded(primaryKeys/trialWorkers)) + } + trace[i] = arrival{Run: run, Seed: spec.Seed, ID: i, Key: key, ScheduledNS: int64(i) * int64(time.Second) / int64(spec.Rate)} + } + return trace +} + +type deterministicStream struct{ seed, counter uint64 } + +// SHA-256 with rejection sampling supplies reproducible uniform draws, not +// credentials. Arrival generation is outside all measurement windows. +func (s *deterministicStream) bounded(bound uint32) uint32 { + if bound == 0 { + return 0 + } + var input [16]byte + for { + binary.LittleEndian.PutUint64(input[:8], s.seed) + binary.LittleEndian.PutUint64(input[8:], s.counter) + s.counter++ + digest := sha256.Sum256(input[:]) + value := binary.LittleEndian.Uint32(digest[:4]) + if value >= -bound%bound { + return value % bound + } + } +} + +func waitUntil(ctx context.Context, target time.Time) bool { + delay := time.Until(target) + if delay <= 0 { + return ctx.Err() == nil + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} + +// Every scheduled arrival is retained, including queue overflow and work that +// expires before a worker can send it. Deadlines start at scheduled arrival. +func executeTrial(ctx context.Context, spec trialSpec, call trialCall) ([]eventRecord, time.Duration) { + trace := makeTrace(spec) + queues := make([]chan arrival, trialWorkers) + completed := make([][]eventRecord, trialWorkers) + unsent := make([]eventRecord, 0) + start := time.Now().Add(time.Second) + var workers sync.WaitGroup + for worker := range queues { + queues[worker] = make(chan arrival, max(1, spec.Rate/trialWorkers+1)) + workers.Go(func() { + for item := range queues[worker] { + completed[worker] = append(completed[worker], call(ctx, item, worker, start)) + } + }) + } + for _, item := range trace { + if !waitUntil(ctx, start.Add(time.Duration(item.ScheduledNS))) { + unsent = append(unsent, eventRecord{arrival: item, Outcome: outcomeUnsent, EndNS: time.Since(start).Nanoseconds()}) + continue + } + select { + case queues[item.ID%trialWorkers] <- item: + default: + unsent = append(unsent, eventRecord{arrival: item, Outcome: outcomeUnsent, EndNS: time.Since(start).Nanoseconds()}) + } + } + for _, queue := range queues { + close(queue) + } + workers.Wait() + _ = waitUntil(ctx, start.Add(spec.Duration)) + elapsed := time.Since(start) + for _, events := range completed { + unsent = append(unsent, events...) + } + slices.SortFunc(unsent, func(a, b eventRecord) int { return a.ID - b.ID }) + return unsent, elapsed +} + +func summarize(spec trialSpec, records []eventRecord, elapsed time.Duration) trialSummary { + s := trialSummary{Spec: spec, Scheduled: len(records), Outcomes: make(map[string]int), ElapsedNS: int64(elapsed)} + var success, all []int64 + for _, record := range records { + latency := max(0, record.EndNS-record.ScheduledNS) + all = append(all, latency) + s.Outcomes[record.Outcome]++ + s.Attempts += len(record.Attempts) + s.Reads += record.Reads + s.OnTimeDefinitive += definitiveOnTimeOutcomeCount(record.Outcome, latency) + if record.Outcome == outcomeSuccess { + success = append(success, latency) + s.Success++ + if latency <= int64(operationDeadline) { + s.OnTimeSuccess++ + } + } + if record.Outcome == outcomeUnknown { + s.Unknown++ + } + for _, step := range record.Attempts { + if step.Code == "DeadlineExceeded" { + s.Timeouts++ + } + } + if record.Outcome == outcomeUnsent { + s.Unsent++ + } else if latency > int64(operationDeadline) || record.Outcome == outcomeExpired { + s.Missed++ + } + } + slices.Sort(success) + slices.Sort(all) + s.SuccessP99NS, s.AllP99NS = quantile(success, p99Percentile), quantile(all, p99Percentile) + s.SuccessP50NS, s.AllP50NS = quantile(success, p50Percentile), quantile(all, p50Percentile) + s.SuccessP95NS, s.AllP95NS = quantile(success, p95Percentile), quantile(all, p95Percentile) + s.SuccessRate = float64(s.Success) / spec.Duration.Seconds() + s.ClientCalls = clientCallCounts(spec.Arm, s.Attempts, s.Reads) + return s +} + +func clientCallCounts(arm string, attempts, reads int) map[string]int { + method := "/benchmark.FencedOnePhase/Fresh" + if arm == armCAS { + method = pb.TransactionalKV_CompareAndSwap_FullMethodName + } + return map[string]int{method: attempts, pb.TransactionalKV_Get_FullMethodName: reads} +} + +func quantile(values []int64, percentile int) int64 { + if len(values) == 0 { + return 0 + } + return values[(len(values)*percentile+percentageDenominator-1)/percentageDenominator-1] +} + +func (s trialSummary) onTime() bool { + return s.Scheduled > 0 && s.Success > 0 && s.Unknown == 0 && float64(s.Missed+s.Unsent)/float64(s.Scheduled) <= maximumMissFraction +} + +func (s trialSummary) calibrationPass() bool { + if s.Scheduled <= 0 { + return false + } + if s.Spec.Cell == cellHot { + return float64(s.OnTimeDefinitive)/float64(s.Scheduled) >= 1-maximumMissFraction + } + return float64(s.OnTimeSuccess)/float64(s.Scheduled) >= 1-maximumMissFraction +} + +func definitiveOnTimeOutcomeCount(outcome string, latency int64) int { + if latency > int64(operationDeadline) { + return 0 + } + switch outcome { + case outcomeSuccess, outcomeExhausted, outcomeRefreshError: + return 1 + default: + return 0 + } +} + +func validateTrial(spec trialSpec) error { + if spec.Arm != armCAS && spec.Arm != armFresh { + return fmt.Errorf("unknown arm %q", spec.Arm) + } + if spec.Cell != cellPrimary && spec.Cell != cellHot { + return fmt.Errorf("unknown cell %q", spec.Cell) + } + if spec.Rate < 1 || spec.Rate > 65536 || spec.Duration < time.Second || spec.Duration > time.Hour { + return fmt.Errorf("invalid bounded rate/duration") + } + return nil +} diff --git a/cmd/casbench/windows.go b/cmd/casbench/windows.go new file mode 100644 index 000000000..d78609042 --- /dev/null +++ b/cmd/casbench/windows.go @@ -0,0 +1,264 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "slices" + "time" + + "github.com/bootjp/elastickv/internal/casbenchmark" + "github.com/bootjp/elastickv/internal/casbenchmark/meter" + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "golang.org/x/sync/errgroup" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +const stableSamples = 2 +const stableInterval = 100 * time.Millisecond + +var errUndrained = errors.New("receiver work is not drained") + +func (c *campaign) stable(ctx context.Context, initialize bool) error { + ctx, cancel := context.WithTimeout(ctx, setupTimeout) + defer cancel() + for sample := 0; sample < stableSamples; { + identity, err := c.observe(ctx) + if err != nil && !errors.Is(err, errUndrained) { + return err + } + if errors.Is(err, errUndrained) { + sample = 0 + if !waitUntil(ctx, time.Now().Add(stableInterval)) { + return errors.WithStack(ctx.Err()) + } + continue + } + if initialize && sample == 0 { + c.identity = identity + } + if err := c.matchIdentity(identity); err != nil { + return err + } + sample++ + if !waitUntil(ctx, time.Now().Add(stableInterval)) { + return errors.WithStack(ctx.Err()) + } + } + return nil +} + +func (c *campaign) matchIdentity(identity map[string]nodeIdentity) error { + for address, node := range identity { + if c.identity[address] != node { + return fmt.Errorf("term/config/leader changed at %s", address) + } + } + return nil +} + +func (c *campaign) observe(ctx context.Context) (map[string]nodeIdentity, error) { + identities := make(map[string]nodeIdentity) + var committedPrefix uint64 + for address, conn := range c.connections { + status, err := pb.NewRaftAdminClient(conn).Status(ctx, &pb.RaftAdminStatusRequest{}) + if err != nil { + return nil, errors.WithStack(err) + } + if err := c.validateNode(status, address); err != nil { + return nil, err + } + idle, err := c.windowRPC(ctx, address, "idle") + if err != nil { + return nil, err + } + if idle.InFlight != 0 { + return nil, errUndrained + } + // A follower can be locally idle while missing the leader's suffix. + // Do not carry that replication backlog into the next window. + if len(identities) != 0 && status.CommitIndex != committedPrefix { + return nil, errUndrained + } + committedPrefix = status.CommitIndex + identities[address] = nodeIdentity{Term: status.Term, Config: status.ConfigurationIndex, Leader: status.LeaderAddress} + } + return identities, nil +} + +func (c *campaign) validateNode(status *pb.RaftAdminStatusResponse, address string) error { + if !status.SupportsReplicatedCatalogCas || !status.SupportsVersionAdoption || status.PendingConfChange { + return fmt.Errorf("node %s is not capable/stable", address) + } + if status.LeaderAddress != c.config.Endpoint { + return fmt.Errorf("leader mismatch at %s: %s", address, status.LeaderAddress) + } + if status.CommitIndex != status.AppliedIndex || status.LastLogIndex != status.CommitIndex || status.FsmPending != 0 { + return errUndrained + } + return nil +} + +func (c *campaign) windowRPC(ctx context.Context, address, action string) (meter.Result, error) { + response := new(wrapperspb.BytesValue) + ctx, cancel := context.WithTimeout(ctx, setupTimeout) + defer cancel() + err := c.connections[address].Invoke(ctx, casbenchmark.Prefix+"Window", wrapperspb.String(action), response) + var result meter.Result + if err != nil { + return result, errors.WithStack(err) + } + return result, errors.WithStack(json.Unmarshal(response.Value, &result)) +} + +func (c *campaign) window(ctx context.Context, spec trialSpec) (trialSummary, error) { + if err := validateTrial(spec); err != nil { + return trialSummary{}, err + } + if err := c.stable(ctx, false); err != nil { + return trialSummary{}, err + } + before := make(map[int]knownHead, len(c.state.heads)) + for key, head := range c.state.heads { + before[key] = head + } + for address := range c.connections { + if _, err := c.windowRPC(ctx, address, "begin:"+spec.Name); err != nil { + return trialSummary{}, err + } + } + fmt.Printf("%s rate=%d duration=%s\n", spec.Name, spec.Rate, spec.Duration) + records, elapsed := executeTrial(ctx, spec, c.state.trialCaller(spec.Arm)) + summary := summarize(spec, records, elapsed) + drainErr := c.stable(ctx, false) + if err := c.finishWindow(ctx, spec, records, summary); err != nil { + return summary, err + } + if summary.Unknown == 0 { + if err := verifyChains(before, records); err != nil { + return summary, err + } + } + return summary, drainErr +} + +func (c *campaign) finishWindow(ctx context.Context, spec trialSpec, records []eventRecord, summary trialSummary) error { + // Remote metering can fail after a submitted write; preserve its history + // before waiting for any unavailable node, without treating missing meters as zero. + localErr := errors.CombineErrors(c.writeRecords(spec.Name+".jsonl", records), c.writeJSON(spec.Name+".summary.json", summary)) + c.summaries = append(c.summaries, summary) + fmt.Printf("%s success=%d unknown=%d misses=%d unsent=%d p99=%s\n", spec.Name, summary.Success, summary.Unknown, summary.Missed, summary.Unsent, time.Duration(summary.SuccessP99NS)) + meters, failures, remoteErr := c.endMeters(ctx, spec.Name) + localErr = errors.CombineErrors(localErr, c.writeJSON(spec.Name+".meters.json", meters)) + if len(failures) != 0 { + localErr = errors.CombineErrors(localErr, c.writeJSON(spec.Name+".meter-errors.json", failures)) + } + return errors.WithStack(errors.CombineErrors(localErr, remoteErr)) +} + +func (c *campaign) endMeters(ctx context.Context, name string) (map[string]meter.Result, map[string]string, error) { + meters := make(map[string]meter.Result) + failures := make(map[string]string) + var combined error + for address := range c.connections { + result, err := c.windowRPC(ctx, address, "end:"+name) + if err != nil { + failures[address] = err.Error() + combined = errors.CombineErrors(combined, errors.Wrapf(err, "end meter at %s", address)) + continue + } + meters[address] = result + } + return meters, failures, errors.WithStack(combined) +} + +func (c *campaign) writeRecords(name string, records []eventRecord) error { + file, err := c.root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, privateFileMode) + if err != nil { + return errors.WithStack(err) + } + buffer := bufio.NewWriter(file) + encoder := json.NewEncoder(buffer) + for _, record := range records { + if err := encoder.Encode(record); err != nil { + _ = file.Close() + return errors.WithStack(err) + } + } + flushErr := buffer.Flush() + closeErr := file.Close() + return errors.WithStack(errors.CombineErrors(flushErr, closeErr)) +} + +type acceptedUpdate struct { + key int + expected, next uint64 +} + +func verifyChains(before map[int]knownHead, records []eventRecord) error { + var updates []acceptedUpdate + for _, record := range records { + for _, step := range record.Attempts { + if step.Result == outcomeSuccess { + updates = append(updates, acceptedUpdate{key: record.Key, expected: step.Expected, next: step.New}) + } + } + } + slices.SortFunc(updates, func(a, b acceptedUpdate) int { + if a.next < b.next { + return -1 + } + if a.next > b.next { + return 1 + } + return 0 + }) + cursors := make(map[int]uint64) + for _, update := range updates { + previous, found := cursors[update.key] + if !found { + previous = before[update.key].TS + } + if previous != update.expected || update.next <= previous { + return fmt.Errorf("broken acknowledgment chain at key %d: expected=%d previous=%d next=%d", update.key, update.expected, previous, update.next) + } + cursors[update.key] = update.next + } + return nil +} + +func (c *campaign) verifyHeads(ctx context.Context) error { + // Verification is outside measurement and deliberately does not mutate tokens. + group, verification := errgroup.WithContext(ctx) + group.SetLimit(trialWorkers) + for key, head := range c.state.heads { + if verification.Err() != nil { + break + } + group.Go(func() error { return c.verifyHead(verification, key, head) }) + } + if err := group.Wait(); err != nil { + return errors.WithStack(err) + } + if err := c.stable(ctx, false); err != nil { + return err + } + return c.writeJSON("verified-heads.json", c.state.heads) +} + +func (c *campaign) verifyHead(ctx context.Context, key int, head knownHead) error { + ctx, cancel := context.WithTimeout(ctx, setupTimeout) + defer cancel() + response, err := c.state.client.Get(ctx, &pb.GetRequest{Key: c.state.key(key), NeedCommitTs: true}) + if err != nil { + return errors.WithStack(err) + } + if response.GetCommitTs() != head.TS || !bytes.Equal(response.Value, head.Value) { + return fmt.Errorf("final head mismatch at key %d", key) + } + return nil +} diff --git a/cmd/casbench/windows_test.go b/cmd/casbench/windows_test.go new file mode 100644 index 000000000..36337e0d9 --- /dev/null +++ b/cmd/casbench/windows_test.go @@ -0,0 +1,158 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "net" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/casbenchmark/meter" + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +func TestObserveRequiresCommonCommittedPrefix(t *testing.T) { + t.Parallel() + for _, followerIndex := range []uint64{99, 100, 101} { + t.Run(fmt.Sprint(followerIndex), func(t *testing.T) { + t.Parallel() + c := &campaign{config: campaignConfig{Endpoint: "leader"}, connections: map[string]*grpc.ClientConn{ + "leader": observationTestConnection(t, 100), + "follower": observationTestConnection(t, followerIndex), + }} + _, err := c.observe(t.Context()) + if followerIndex == 100 { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, errUndrained) + } + }) + } +} + +func observationTestConnection(t *testing.T, index uint64) *grpc.ClientConn { + t.Helper() + listener := bufconn.Listen(1 << 20) + server := grpc.NewServer(grpc.UnknownServiceHandler(func(_ any, stream grpc.ServerStream) error { + method, _ := grpc.MethodFromServerStream(stream) + if method == pb.RaftAdmin_Status_FullMethodName { + if err := stream.RecvMsg(new(pb.RaftAdminStatusRequest)); err != nil { + return err + } + return stream.SendMsg(&pb.RaftAdminStatusResponse{LeaderAddress: "leader", Term: 1, ConfigurationIndex: 1, + CommitIndex: index, AppliedIndex: index, LastLogIndex: index, + SupportsReplicatedCatalogCas: true, SupportsVersionAdoption: true}) + } + if err := stream.RecvMsg(new(wrapperspb.StringValue)); err != nil { + return err + } + return stream.SendMsg(wrapperspb.Bytes([]byte(`{"in_flight":0}`))) + })) + done := make(chan struct{}) + go func() { _ = server.Serve(listener); close(done) }() + t.Cleanup(func() { + server.Stop() + require.NoError(t, listener.Close()) + select { + case <-done: + case <-time.After(time.Second): + t.Error("observation test server did not stop") + } + }) + conn, err := grpc.NewClient("passthrough:///observation-test", grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) })) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, conn.Close()) }) + return conn +} + +func TestFailedMeterCollectionPreservesHistoryAndEndsReachableWindows(t *testing.T) { + t.Parallel() + output := t.TempDir() + root, err := os.OpenRoot(output) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, root.Close()) }) + var good, bad atomic.Int32 + c := &campaign{config: campaignConfig{Output: output}, root: root, connections: map[string]*grpc.ClientConn{ + "good": windowTestConnection(t, false, &good), "bad": windowTestConnection(t, true, &bad), + }} + spec := trialSpec{Name: "failed-window", Arm: armCAS, Cell: cellPrimary, Rate: 1, Duration: time.Second} + records := []eventRecord{{arrival: arrival{ID: 0, Key: 0}, Outcome: outcomeUnknown, EndNS: int64(time.Second), + Attempts: []attemptRecord{{Expected: 7, Result: outcomeUnknown, Code: codes.DeadlineExceeded.String()}}}} + summary := summarize(spec, records, time.Second) + require.Error(t, c.finishWindow(t.Context(), spec, records, summary)) + for _, file := range []string{spec.Name + ".jsonl", spec.Name + ".summary.json", spec.Name + ".meters.json", spec.Name + ".meter-errors.json"} { + require.FileExists(t, filepath.Join(output, file)) + } + var record eventRecord + body, err := os.ReadFile(filepath.Join(output, spec.Name+".jsonl")) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(body, &record)) + require.Equal(t, records[0], record) + var saved trialSummary + body, err = os.ReadFile(filepath.Join(output, spec.Name+".summary.json")) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(body, &saved)) + require.Equal(t, summary, saved) + var meters map[string]meter.Result + body, err = os.ReadFile(filepath.Join(output, spec.Name+".meters.json")) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(body, &meters)) + require.Contains(t, meters, "good") + require.NotContains(t, meters, "bad") + var failures map[string]string + body, err = os.ReadFile(filepath.Join(output, spec.Name+".meter-errors.json")) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(body, &failures)) + require.Contains(t, failures["bad"], codes.Unavailable.String()) + require.EqualValues(t, 1, good.Load()) + require.EqualValues(t, 1, bad.Load()) + require.False(t, c.report().Passed) +} + +func windowTestConnection(t *testing.T, fail bool, calls *atomic.Int32) *grpc.ClientConn { + t.Helper() + listener := bufconn.Listen(1 << 20) + server := grpc.NewServer(grpc.UnknownServiceHandler(func(_ any, stream grpc.ServerStream) error { + request := new(wrapperspb.StringValue) + if err := stream.RecvMsg(request); err != nil { + return err + } + calls.Add(1) + if fail { + return status.Error(codes.Unavailable, "node lost") + } + body, err := json.Marshal(meter.Result{Name: "failed-window"}) + if err != nil { + return err + } + return stream.SendMsg(wrapperspb.Bytes(body)) + })) + done := make(chan struct{}) + go func() { _ = server.Serve(listener); close(done) }() + t.Cleanup(func() { + server.Stop() + require.NoError(t, listener.Close()) + select { + case <-done: + case <-time.After(time.Second): + t.Error("window test server did not stop") + } + }) + conn, err := grpc.NewClient("passthrough:///window-test", grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) })) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, conn.Close()) }) + return conn +} diff --git a/cmd/jepsen-grpc-client/main.go b/cmd/jepsen-grpc-client/main.go index c7bf7aab1..04b604afe 100644 --- a/cmd/jepsen-grpc-client/main.go +++ b/cmd/jepsen-grpc-client/main.go @@ -32,15 +32,18 @@ const ( ) type request struct { - Op string `json:"op"` - Key string `json:"key"` - Value *int64 `json:"value"` + Op string `json:"op"` + Key string `json:"key"` + Value *int64 `json:"value"` + Expected uint64 `json:"expected,omitempty"` } type response struct { Type string `json:"type"` Value any `json:"value"` Error string `json:"error,omitempty"` + Version uint64 `json:"version,omitempty"` + Missing bool `json:"missing,omitempty"` GRPCCode string `json:"grpc_code,omitempty"` CommitIndex *uint64 `json:"commit_index,omitempty"` } @@ -133,6 +136,8 @@ func (c rpcClient) invoke(ctx context.Context, req request) response { return response{Type: outcomeFail, Error: "key is required"} } switch req.Op { + case "version-read", "cas": + return c.versionOperation(ctx, req) case "write": if req.Value == nil { return response{Type: outcomeFail, Error: "write value is required"} diff --git a/cmd/jepsen-grpc-client/main_test.go b/cmd/jepsen-grpc-client/main_test.go index fa33b3dac..c7c1d5c90 100644 --- a/cmd/jepsen-grpc-client/main_test.go +++ b/cmd/jepsen-grpc-client/main_test.go @@ -257,3 +257,13 @@ func TestJSONStreamAndInvalidRequests(t *testing.T) { backend.mu.Unlock() require.Equal(t, 1, writes) } + +func TestVersionOperationsOnOlderServer(t *testing.T) { + client, _ := fixture(t, apiTransactional) + ctx := t.Context() + require.Equal(t, outcomeInfo, client.invoke(ctx, request{Op: "version-read", Key: "key"}).Type, + "a successful Get from a server without version metadata is inconclusive") + value := int64(0) + require.Equal(t, outcomeInfo, client.invoke(ctx, request{Op: "cas", Key: "key", Value: &value, Expected: 7}).Type, + "an RPC error cannot certify a mismatch") +} diff --git a/cmd/jepsen-grpc-client/version.go b/cmd/jepsen-grpc-client/version.go new file mode 100644 index 000000000..05eb9ae8b --- /dev/null +++ b/cmd/jepsen-grpc-client/version.go @@ -0,0 +1,52 @@ +package main + +import ( + "context" + "strconv" + + pb "github.com/bootjp/elastickv/proto" +) + +// Preserve observed versions as JSON integers. A transport failure may follow +// a committed write, so only an explicit mismatch is a definitive CAS failure. +func (c rpcClient) versionOperation(ctx context.Context, req request) response { + if c.api != apiTransactional { + return response{Type: outcomeFail, Error: "version operations require transactional API"} + } + if req.Op == "version-read" { + reply, err := c.txn.Get(ctx, &pb.GetRequest{Key: []byte(req.Key), NeedCommitTs: true}) + if err != nil { + return response{Type: outcomeInfo, Error: err.Error()} + } + if reply.GetVersion() == nil { + return response{Type: outcomeInfo, Error: "server returned no version metadata"} + } + if reply.GetMissing() { + return response{Type: outcomeOK, Missing: true} + } + // Keep malformed bytes and versions in a successful observation so + // the checker reports the contract violation. + return response{Type: outcomeOK, Version: reply.GetCommitTs(), Value: registerValue(reply.GetValue())} + } + if req.Value == nil || req.Expected == 0 { + return response{Type: outcomeFail, Error: "a version and replacement are required"} + } + reply, err := c.txn.CompareAndSwap(ctx, &pb.CompareAndSwapRequest{ + Key: []byte(req.Key), ExpectedCommitTs: req.Expected, Value: []byte(strconv.FormatInt(*req.Value, 10)), + }) + if err != nil { + return response{Type: outcomeInfo, Error: err.Error()} + } + if reply.GetMismatch() { + return response{Type: outcomeFail, Error: "version-mismatch"} + } + return response{Type: outcomeOK, Version: reply.GetNewCommitTs(), Value: *req.Value} +} + +func registerValue(raw []byte) any { + value, err := strconv.ParseInt(string(raw), 10, 64) + if err != nil { + return "invalid integer: " + string(raw) + } + return value +} diff --git a/distribution/engine.go b/distribution/engine.go index 68d08fd40..22bce83cb 100644 --- a/distribution/engine.go +++ b/distribution/engine.go @@ -649,6 +649,32 @@ func RoutesFromCatalogSnapshot(snapshot CatalogSnapshot) ([]Route, error) { return routesFromCatalog(snapshot.Routes) } +// RouteSnapshotFromCatalog builds an immutable lookup over a durable catalog. +func RouteSnapshotFromCatalog(snapshot CatalogSnapshot) (RouteHistorySnapshot, error) { + routes, err := RoutesFromCatalogSnapshot(snapshot) + return RouteHistorySnapshot{version: snapshot.Version, routes: routes}, err +} + +// OwnsCatalogRoutes reports whether one group owns both the version record and +// the complete route descriptor key range. +func (s RouteHistorySnapshot) OwnsCatalogRoutes(groupID uint64) bool { + if owner, ok := s.OwnerOf(CatalogVersionKey()); !ok || owner != groupID { + return false + } + cursor := []byte(catalogRoutePrefix) + end := prefixScanEnd(cursor) + for _, route := range s.IntersectingRoutes(cursor, end) { + if route.GroupID != groupID || bytes.Compare(route.Start, cursor) > 0 { + return false + } + if route.End == nil || bytes.Compare(route.End, end) >= 0 { + return true + } + cursor = route.End + } + return false +} + func validateRouteOrder(routes []Route) error { if len(routes) < minRouteCountForOrderValidation { return nil diff --git a/docs/design/2026_11_20_proposed_single_key_mvcc_cas.md b/docs/design/2026_11_20_proposed_single_key_mvcc_cas.md new file mode 100644 index 000000000..7186a9294 --- /dev/null +++ b/docs/design/2026_11_20_proposed_single_key_mvcc_cas.md @@ -0,0 +1,196 @@ +# Single-key compare-and-swap by MVCC commit timestamp + +Status: Proposed. The disabled-by-default implementation includes replicated cleanup and unchanged ownership return. Adaptive source `7196894fa5` passes the full hot-key cell with zero decision-window unknowns, but still fails the primary p99 criterion. The later bounded follower-batching/storage trial stops on unknowns in the first fresh-control warmup, before a paired comparison. Neither it nor the short diagnostic overrides the primary failure or remaining adoption gates. Not ready for activation or merge. [Measured results](../evidence/2026_12_02_single_key_mvcc_cas_host_benchmark.md) ยท [Follower batching](2026_12_02_partial_protected_follower_append_batch.md) + +Author: bootjp + +Date: 2026-11-20 + +## Decision + +Add opt-in version metadata to `TransactionalKV.Get` and a dedicated `TransactionalKV.CompareAndSwap` RPC. A client that has read a live key can replace it if that exact version is still current. A client that receives the new version in a successful write response can use it for its next edit. The data group executes the comparison and replacement through its existing single-shard one-phase commit (1PC) path. + +The expected saving is a read round trip when the caller already has the version and replacement. Existing single-shard 1PC already takes one data-group proposal on a successful, unbatched attempt. CAS also takes one. The case for adoption depends on which reads disappear and how much failed contention costs. + +## What TiKV does + +TiKV provides two relevant operations. Its transactional `Get` accepts a snapshot version and a `need_commit_ts` flag. The returned `commit_ts` identifies the write that produced the visible value. Its separate `RawCAS` compares the current bytes with supplied bytes, or tests for absence. The response reports success and the previous value or absence. The request also has column-family, TTL and delete fields. TiKV exposes per-key MVCC history to operators through `tikv-ctl mvcc`. ElasticKV can follow that diagnostic pattern independently of the point-read API. [TiKV protocol](https://github.com/pingcap/kvproto/blob/master/proto/kvrpcpb.proto) ยท [TiKV Control guide](https://docs.pingcap.com/tidb/stable/tikv-control/) + +ElasticKV could implement the TiKV value predicate at the same atomic storage boundary. The choice is about the guarantee the caller needs. Suppose a client reads `A@10`, and two intervening commits write `B@11` and `A@12`. + +| Requested update | Outcome against `A@12` | Appropriate use | +| --- | --- | --- | +| Replace if the bytes equal `A` | Succeeds | The current content is the entire precondition. | +| Replace if the version equals `10` | Returns a mismatch | The caller's decision is valid only while its observed revision is current. | + +Value CAS also supports callers that know the expected bytes without ever reading a version. Version CAS avoids transmitting those bytes on each attempt and distinguishes intervening writes of identical content. Both require an atomic check. A future TiKV-compatible RawKV operation would need its own contract for absence, previous-value disclosure, TTL, deletion and keyspace mapping. TiKV's Go RawKV client also requires callers to coordinate atomic mode across writers to a key. ElasticKV must exercise ordinary writes, deletes and CAS against the same concurrency boundary. [TiKV RawKV client](https://github.com/tikv/client-go/blob/master/rawkv/rawkv.go) + +## Public contract + +| Operation | Request | Successful RPC response | +| --- | --- | --- | +| `TransactionalKV.Get` | Existing key and additive `need_commit_ts`, default false | An opted-in read returns the existing value and exactly one version result: a positive `commit_ts` for a live value, or an explicit `missing` marker. | +| `TransactionalKV.CompareAndSwap` | One public key, positive `expected_commit_ts`, replacement bytes (possibly empty) | One of `applied(new_commit_ts)` or `mismatch`. The applied timestamp is the actual new version. | + +Use a protobuf `oneof` for each result so that an old Get server which ignores the request flag produces a distinguishable *absent result*. An opted-in client treats that response as unsupported. A supported server returns the live version even for a zero-length value. The read snapshot selects the visible record. Its timestamp, the Raft read index, and the key's last write timestamp have different meanings. For example, a read at snapshot 50 can return `A@10`. Only 10 is a valid token for that observation. The initial API uses the existing latest transactional read. History enumeration and arithmetic updates are outside this change. [Current public schema](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/proto/service.proto#L13) ยท [Transactional Get](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/adapter/grpc.go#L836) ยท [Read snapshots](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/read_request.go#L143) + +A mismatch is a normal, definitive outcome for this attempt. Missing, deleted, expired and differently versioned keys all mismatch. Zero is an invalid expected version. Replacing a live value preserves its absolute expiry and generates a fresh version even when the bytes are identical. The initial response omits the losing value. A caller that derives its replacement from current content must re-read and recompute after a mismatch. A transport timeout after submission leaves the outcome unknown. Retrying the old token cannot apply a second replacement once the original landed, but a later mismatch cannot identify the winner of the first attempt. Expose that ambiguity to the caller and disable transparent retries after uncertain submission. + +The standalone RPC covers a decision based solely on the target key. A decision that also reads other keys retains its transaction snapshot and validates the complete OCC read set, including reads of absent point keys. Read dependencies outside the write shard use the existing multi-shard transaction. A range predicate additionally needs protection against insertions. Test write skew with two keys initially on: each client reads both and disables a different one conditional on the other. Independent single-key CAS operations may both succeed. Transactions validating both keys must admit at most one. + +Only the exact key predicate can produce the dedicated mismatch verdict, including across leader forwarding. A store-wide commit timestamp fence can reject an unchanged target when an unrelated proposal arrives first. Check the group watermark first. Once the proposed timestamp passes the watermark, test the exact predicate before testing whether the matching head exceeds the start timestamp. A different head yields a mismatch even if it arrived between start and commit. A certified indexed route write fence returns `Aborted/CAS_ROUTE_FENCED` on both ingress paths. A missing reply stays indeterminate. Retry a proven non-effect only within the original deadline with the same expected version. Terminate the logical operation on an ambiguous submission. + +## Read and apply paths + +1. Carry an opted-in read through the existing snapshot, ownership and group fences, including remote reads. In memory, copy the bytes and timestamp from the same visible record under the read lock. In Pebble, decode the timestamp from the iterator key that produced the authenticated visible value. Preserve decryption, expiry and tombstone checks. If the read traverses a cache or a forwarding hop, propagate the complete result or report that version metadata is unavailable. A second latest-version lookup can pair an old value with a newer token. [Shard reads](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/shard_store.go#L293) ยท [Memory store](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/store/mvcc_store.go#L342) ยท [Pebble store](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/store/lsm_store.go#L1192) +2. Validate the public key and route one replacement to its owning group. Add an explicitly gated exact-version predicate to the replicated 1PC mutation and carry it through forwarding and replay. The coordinator issues the new commit timestamp through the normal fenced leader path. The client token never supplies the new write time or the transaction start time. Keep existing lock, timestamp and migration admission checks. [Replicated mutation format](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/proto/internal.proto#L37) ยท [Single-shard dispatch](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/sharded_coordinator.go#L1905) +3. At apply, inspect the latest logical record, including earlier staged writes in the same entry. Require its version to equal the expected timestamp, require it to be live at the replicated write timestamp, and require the new timestamp to advance it. Use the store's Raft-entry staging scope for the CAS request. Evaluate the predicate in that scope before recording migration progress. Stage the tracker update, replacement, preserved expiry and durable applied index in the same batch, and publish notifications after commit. On an operational failure discard the entire scope and halt apply. On a mismatch explicitly persist only Raft progress, including for an otherwise empty Pebble batch. Add a tracking-armed test which compares the tracker and user record before rejection, after rejection and after restart. A mismatch stages no user write, migration effect or notification. Applying a committed no-op still advances the applied index. Keep operational failures distinct from per-request verdicts. Check durable entry replay before evaluating the predicate again. [1PC apply](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/fsm.go#L2260) ยท [Pebble entry staging](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/store/raft_entry.go#L307) +4. Verify that each visible logical overwrite gets a distinct, increasing version for its key, including through leader and ownership changes. Low-level historical writes can reuse a timestamp. Permit identical replay, and audit import, restore and migration paths for same-version replacement with different data before enabling CAS. Scope tokens to a key in one cluster history. A Raft snapshot install continues the same history. An administrative rewind can resurrect an old token. Require a new cluster incarnation bound to requests after a rewind, or keep CAS disabled on that restored cluster until old clients are fenced. + +## Where operations are saved + +The counts below model one logical attempt after feature activation, for a leader-connected client, one data group, no retries and one write per proposal. A client RPC is one application request/response. A data proposal is one call to the data-group Raft proposer. A quorum read fence, timestamp-service call, frontend-to-leader forward and Raft replication message each have their own counter. The baseline at `6943eff8a` sends one 1PC request to `Txn.Commit`; the proposal path serializes the requests and calls `Propose`. The public `PreWrite` and `Commit` handlers at that revision are stubs. The baseline below uses working internal 1PC, behind a benchmark-only frontend where necessary. [Single-shard commit](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/sharded_coordinator.go#L2156) ยท [Proposal boundary](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/transaction.go#L153) ยท [gRPC handlers](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/adapter/grpc.go#L800) + +| Work performed inside the timed update | Existing 1PC baseline: client RPCs / data proposals | Version CAS: client RPCs / data proposals | Explanation | +| --- | ---: | ---: | --- | +| Caller holds a token and replacement. Baseline opens a fresh read and submits its validated write as two client calls. | 2 / 1 | 1 / 1 | CAS removes the fresh read. Account separately for the earlier read that produced the token. | +| Same input, with the baseline read, check and 1PC submission inside one server handler | 1 / 1 | 1 / 1 | CAS can remove the handler's pre-read, its value copy and any remote storage read. Both still check storage at apply. Count the actual storage probes and timestamp allocation path on both sides. | +| Caller retains its original validated snapshot and prepared value | 1 / 1 | 1 / 1 | Charge acquisition, pin time, expiry and release in a separate full-lifecycle cell. | +| Caller must read the current value to compute the replacement | 2 / 1 | 2 / 1 | Both need the read. On conflict, recomputing requires a fresh read. | +| Supplied token is already stale when the server handles it | 1 / 0 with a fenced pre-read and early rejection | 1 / 1 with apply-only comparison | A failed CAS can consume **more** Raft work. A CAS variant with a linearizable precheck can reach 1 / 0 when it proves the mismatch. | +| Two callers observe the same version and both reach proposal before either update is applied | 2 write calls / 2 proposals across both callers | 2 write calls / 2 proposals across both callers | One winner in both designs. Initial reads are outside this row. | + +Blind `Get` followed by unconditional `Put` allows a lost update. For the equivalent 1PC control, read the value and its version at one fenced snapshot, reject an unexpected version, and submit the replacement using that snapshot's start timestamp and the key in the OCC read/write set. The benchmark frontend owns the original read scope and gives the client a single-use handle bound to that key, snapshot and client. Release its pin on submission, cancellation or expiry (five seconds). Record expired handles and memory/pin time. The retained-handle arm acquires the handle alongside the original read. The two-call fresh-read arm acquires it during the timed update. The single-handler control performs the same work locally. Keep the original start timestamp through submission. Use only fenced 1PC writers and non-expiring keys in the equivalent-control trials. Verify the replicated timestamp fence on every participating node. A delayed raw write at 15 can replace the visible version at 5 after the baseline took snapshot 20 when the fence is inactive. OCC then accepts a version changed below its snapshot, while exact CAS rejects. Exercise that history separately with fence activation on and off. Require active protection across mixed raw and transactional writers before enabling the write RPC, and test identical timestamp rewrites, import, migration and TTL separately. If a fenced precheck rejects R stale attempts before submission, it can avoid R individual proposals relative to proposing all attempts. The same precheck on both designs offers no inherent proposal advantage to CAS. Compare its read cost with the proposals actually avoided. + +## Adaptive pre-submission mismatch check + +The 2026-12-02 apply-only hot-key run failed with unknown writes. The revised +variant uses the published local head only to decide whether a confirming read +is worth attempting. A matching head proceeds directly to the existing FSM +predicate. A different or missing local head is not a rejection certificate: +the receiver first obtains the owning group's ReadIndex fence and a pinned, +request-owned applied-watermark snapshot, then rereads that key with the same +protected version-read admission, applied catalog and migration guards. If the +confirmed version differs or is absent, the standalone attempt can return +`mismatch` without proposing a data entry. An unreadable/locked key, failed +fence, changed route or unavailable admission falls back to the existing FSM +path. The check does not run lock resolution or return a success verdict. + +This is a separate sealed pre-submission certificate, not an indexed apply +receipt and not a generic retryable 1PC conflict. Dedicated CAS forwarding +carries `CAS_MISMATCH / REJECTED_BEFORE_SUBMISSION` only for the validated +standalone request. Generic Forward does not gain this meaning. Joined, +secondary and unknown-outcome errors invalidate the certificate. A failed +reply after submission remains unknown, even if a later invocation mismatches. +Startup installs the check on the receiving group's existing manager, shared +by local ingress and dedicated forwarding. Local leader ingress tries it before +write-only quorum verification and timestamp allocation; the confirming read +still performs its own ReadIndex and protected version-read capability checks. +An internal request-local mark prevents repeating the hint on the eventual +proposal path. Forwarded requests use the same check before proposal admission. +Unconfirmed attempts retain all ordinary write admission. All successful changes still pass +the atomic FSM predicate and synchronous durability boundary. + +The contention revision also bounds local CAS admission to 4,096 active or +waiting attempts per data-group manager. One synchronous CAS proposal attempt +per key holds a local lane. An arriving stale token can still obtain its own +fenced mismatch without waiting for that proposal. A contender whose hint +matches waits for the predecessor, then rechecks before its own write-only +admission and proposal. Lane ownership is claimed before the final hint check, +closing the check-to-reservation race. Different keys retain concurrency. +Only fixed-size SHA-256 key digests and active completion channels are retained; +a digest collision adds contention but never substitutes a key or predicate. +No read pin is held while waiting. Cancellation, shutdown and the admission +limit reject before submission without issuing a mismatch certificate. + +The local and forwarded paths share these lanes. A leadership-verification +failure releases the local lane before forwarding, so a retry back to the same +receiver cannot wait on itself. Release is idempotent and is not a commit or +noncommit proof: unknown replies remain unknown, and there is no resubmission +after an ambiguous proposal. The gate is disposable, does not coordinate +ordinary writers, and never replaces FSM atomicity or replicated admission. +The measured variant is labeled `adaptive-precheck-key-admission`; earlier +apply-only and precheck-only failures retain their original revisions/labels. + +Index-only rejected entries retain synchronous applied-index persistence, but +do not hold the metadata publication lock through WAL Sync; they change no +published user head or commit watermark. Control/data-bearing entries retain +their existing publication and sync rules. Neither change enables NoSync. + +Apply-only CAS remains available in explicit benchmark builds. Measure and +label adaptive-precheck separately; none of the numeric performance gates, +workload populations, deadlines or retry budgets below changes. + +## Contention benchmark + +**Setup.** Use three Linux voters on separate hosts, one data group with a fixed leader, a separate load generator, TLS, synchronous persistence and identical server settings. Use the sharded coordinator, record the leader timestamp allocation mode, and hold it fixed across builds. Use clean keys without secondary locks. Test fresh-read two-call 1PC, single-handler fresh-read 1PC, retained-handle 1PC and apply-only CAS. A zero start timestamp can trigger an internal latest-version probe even when the public Get disappears. Repeat with follower ingress and a separate secondary-lock-resolution fixture before attributing remote reads or proposals to the optimization. Measure optional fenced precheck CAS as a separate variant. Use the same seeded keys, payloads, traces, deadlines and retry policy. Keep the common opt-in read helper in all benchmark builds. Record revisions and settings; the following are planned experiments. + +| Workload | Parameters | What it tests | +| --- | --- | --- | +| Known token and read-dependent update | Uniform over 65,536 keys; 64 B, 1 KiB and 16 KiB values; 1, 8 and 32 workers | Separate saved reads from operations that intrinsically need a read. Run once with preloaded tokens and once charging their acquisition. | +| Synchronized contenders | Give 2, 8 or 32 writers the same token and distinct replacements. Release them together, disable retries and reset between rounds. Repeat at least 1,000 rounds per cell. | Count admissions, precheck passes, submitted proposals, applied predicate evaluations and definitive outcomes. Exclude setup and reset from every counter. In a second instrumented trial park all contenders after precheck and before proposal. Require one winner among valid monotonic timestamp attempts and attribute every loser to its actual reason; retry a certified timestamp-order rejection separately when testing the one-winner history. | +| Known stale tokens | Inject exactly 0%, 10%, 50%, 90% or 100% stale tokens on otherwise disjoint keys. Use each prepared key/token pair once in a window to keep the injected fractions exact. | Isolate early rejection from races after precheck. At 100% stale, report absolute proposals and cost per attempt. Cost per success is undefined. | +| Sustained contention | Uniform keys, 90% of requests on one key, and a single hot key. Drive identical open-loop arrivals at 50% and 80% of the baseline saturation rate. | Measure queueing, deadline misses and useful throughput. Run both single-attempt mode and a recompute loop capped at four attempts with identical seeded backoff and one end-to-end deadline. | + +For sustained runs, warm up for 30 seconds and measure at least 120 seconds. Alternate build order over ten matched pairs. Count logical updates separately from attempts. Capture client RPCs by method, internal forwards, timestamp calls, ReadIndex operations, data proposals, committed entries, writes per entry, comparison reads, bytes sent, server CPU and allocations. Record injected staleness as an input label. Classify each attempt by the returned verdict so an injected-stale attempt rejected by the timestamp fence counts as a fence rejection. Publish applied updates/s, RPCs and data proposals per attempt **and per successful update**, and p50/p95/p99 from scheduled arrival through the final outcome. Report successes, mismatches, exhausted retries, unsent or timed-out requests and unknown outcomes separately. The pinned implementation submits transactional requests individually. Its raw batcher combines raw requests only. Distinguish commands per proposal, proposals per committed entry and entries per durable flush. Count internal RawGet, RawLatestCommitTS, Forward, ForwardCompareAndSwap and RaftAdmin.Status by method. Include membership lookup, capability probes and timestamp-service traffic in the end-to-end latency and internal RPC totals. Report first-use activation proposals and reads separately from steady state. Separate rerouting, timestamp rejections, exact mismatches, locks and unknown outcomes. Reconcile counters with the history of each successful change. + +**Decision rule.** Correctness gates rollout. In the known-token two-call comparison, verify the predicted change from two client RPCs to one and one data proposal on both sides. Use the single-handler 1PC control for the performance decision. For the primary cell, use 1 KiB values, eight outstanding workers, leader ingress, known tokens prepared outside the measurement, and uniform disjoint per-worker key partitions. Update the cached version from each successful response in every arm (the fixture exposes the 1PC commit timestamp). Warm up the same way before each measurement. Replenish a rejected token only through a counted read. For the retained-handle arm count reacquisition when the handle is consumed. Also publish acquisition-inclusive results. + +Calibrate using the single-handler 1PC control. Double the offered rate from 16 logical updates/s until a 120-second window achieves less than 99% on-time successes, then use bisection to within 5% of the highest passing rate. Run the primary and each hot-key cell at 80% of its own control's calibrated rate (50% is diagnostic), with a 1 s deadline measured from scheduled arrival, including queue time. If the worker cap delays dispatch, count queueing and every unsent request. Freeze rates, traces and seeds before candidate runs. Hot-key decision cell: one key, eight workers, 1 KiB, four total attempts, full jitter using the same seeded uniform distribution from zero to 1, 2 and 4 ms on successive retries. For contention calibration use completed logical outcomes within deadline as the 99% criterion, record control goodput and compare goodput at that fixed offered rate. + +The primary metric is p99 among successful logical updates from scheduled arrival to confirmation. Record all-outcome latency separately. Compare ten matched candidate/control pairs using the median paired ratio and the interval from the second to ninth order statistic. Require primary upper p99 ratio โ‰ค0.90, hot-key upper successful p99 ratio โ‰ค1.05, and lower successful-throughput ratio โ‰ฅ0.95 in both cells. Require zero unknown outcomes and at most 1% deadline misses or unsent requests combined in every arm of both decision cells. Require at least 1,000 successes per evaluated p99; if any cell falls short rerun both arms with the same longer window. Report inconclusive intervals and defer adoption. Compare retained handles independently and publish the workload share benefiting from the fresh-read comparison before extrapolating savings. [Initial independent review](../evidence/2026_11_20_single_key_mvcc_cas_review.md) + +## Initial implementation scope + +The first release targets ordinary byte-range keys on the protected group that replicates the authoritative route catalog. Other data groups can use ordinary transactions. Extending version CAS to them requires ownership and fence evidence ordered in each group's own log. Production uses the sharded coordinator even for a single data group. The legacy coordinator lacks authoritative route history and rejects CAS before proposal. A forwarded CAS uses a dedicated internal RPC. A peer running an older binary rejects the method before it can append the operation in the legacy format. The new Raft frame also identifies the operation during replay. + +Start an eligible protected runtime with `--commitTSFence` and `--versionCAS`. Before serving the first token or admitting the first CAS, the group must have applied the commit timestamp fence. The leader also proposes a durable marker requiring imports and promotion to preserve the bytes, expiry and deletion state of existing CAS-visible version heads. Concurrent first users share activation. Once active, a matching historical import is idempotent and a conflicting import is refused. An external snapshot rewind makes the restored runtime ineligible for CAS. + +Versioned reads and CAS initially require an active range with ordinary byte-key routing and no migration ownership evidence or migration write floor. A range that moved away and back can still carry that evidence. The API returns a capability or routing error for these ranges. This restriction allows old groups to replay their historical migration commands while the first rollout protects the identity of every token it issues. + +The catalog watcher helps ingress locate the group. The authoritative routing decision must be reproducible from the data group's replicated state at the CAS entry. A replica that has applied the same log prefix must reach the same verdict even when its watcher is behind, ahead, or has evicted the observed route version. A same-owner split may preserve eligibility. Losing the key or fencing its route must prevent a stale replacement. Replay of a durable index preserves the original effects. + +Bounded migration cleanup can physically remove a visible head and expose its predecessor, including a token already consumed by CAS. Ownership exclusion alone does not fix this: replicas may have compacted different predecessors, so the same cleanup command can produce different ordinary read results at the same applied index. Validate ownership coverage before any effect, but never use physical deletion as the logical visibility decision. + +### Replicated retirement before physical reclamation + +Separate logical retirement from physical reclamation. First, commit a logical retirement record for the complete cleanup interval and commit-timestamp ceiling. Bind it to the migration job, source group, ownership generation and capability/configuration evidence. Apply the record atomically with Raft progress before exposing any physical reclamation. The first physical page may share that synced indexed batch: aborting either part aborts both. Replaying the same retirement is idempotent; a different interval or ceiling for the same identity is rejected before effects. A page cursor, deletion count or a local compaction decision cannot establish retirement. + +The current implementation stores canonical, strictly decoded `version-retirement/v1` control metadata. Each immutable record contains its identity, job/group/configuration, ownership-lineage digest, physical bounds, ceiling and versioned routing selector. The selector reuses the migration family's exclusions and route projection, including value-dependent families. The store owns visibility enforcement; the KV layer owns selector compilation. A missing compiler rejects affected reads instead of exposing the physical rows. Metadata is limited to 4096 records and 8 MiB; exceeding either bound rejects the entry before data changes. Evidence reclamation is deliberately not automatic. + +Once retirement applies, versions in that interval at or below the ceiling are logically absent on every replica, including on historical reads. This is irreversible migration-source retirement, not a user DELETE at a new MVCC timestamp. In-flight snapshots must not observe resurrected predecessors: existing read pins must be drained or fenced before retirement admission. Versions above the ceiling retain their existing semantics. Imported or promoted rows must not resurrect retired versions. Reacquiring ownership requires a new generation and an explicit transition that cannot expose the old generation's rows. + +Every read boundary must enforce the retirement rule: ordinary and versioned point reads, latest-version predicates, exists/batch reads, forward and reverse scans, exports and promoted/imported state. Keep the record in durable metadata and in memory/Pebble Raft-entry staging. Snapshot installation, restart, learner catch-up and replay must restore it before serving reads. Never garbage-collect retirement evidence while an older row, snapshot or import can reintroduce a retired version. + +Second, reclaim bounded pages of the retired physical versions. Replicas may reclaim different rows or counts because their local compaction histories differ. That local progress must not change replicated logical visibility or become an authoritative replicated completion count. Retain versions above the retirement ceiling. Operational failures during indexed apply halt without exposing partial logical state. Completion requires retirement plus physical-absence evidence from every required member, not a leader-local empty page. + +The cleanup response carries the committed retirement ID. Before advancing a completed source bracket, the runner sends `RECLAIM_RETIRED_VERSIONS` to every apply member, including learners, at the exact acknowledged configuration. This operation performs only local physical GC authorized by the existing record; it never changes the Raft applied index. Each page is bounded to 256 rows and a 4 MiB transfer/scan budget. Local cursors and completion caches are disposable and reset on restore/reopen. The runner requires every member's local end-of-interval ACK and revalidates the complete member inventory after probing. A failed local GC, missing record, old server, or changed configuration cannot complete the bracket. The existing source route-removal/read-drain barrier precedes retirement dispatch. Ordered apply also rejects retirement intersecting an online source session unless its sealed, fenced post-cutover proof authorizes the complete interval. + +Gate the new record and command on replicated capability support for voters and learners; reject incompatible membership changes and downgrade. Commands ordered before activation retain their legacy replay behavior, but cannot authorize new protected cleanup after activation. The activation gate stays disabled until all read/export paths and recovery paths enforce retirement. + +Activation negotiates explicit retirement and row-adoption support in addition to replicated-catalog CAS, including learners. It atomically advances the migration identity marker and protected policy reader floor to version 3. The version-3 policy digest is domain separated from versions 1 and 2, so sessions cannot reuse evidence for a different floor. Recovery validates the floor even when new CAS admission is disabled. Historical version-1/version-2 activation frames retain their original replay behavior. A legacy version-1 marker alone cannot authorize new protected cleanup. + +### Returning an unchanged version + +Version 3 permits a different live migration job to import old rows into its private staging namespace, never directly into the public key. Foreign row-generation tags are stripped. A closed or identical retired job cannot use this path. Ordinary imports and ordinary/prepared writes still reject retired timestamps. Before promotion, the runner commits and confirms the target's post-cutover, staged OWNER certificate from the root's committed catalog. The FSM uses only replicated evidence: the selected newest proof must match the local and owner group, new job, applied configuration and logical key; its known write floor must exceed every matching retirement ceiling. Missing, stale, NONOWNER or wrong-job evidence refuses the entire page before effects. The source cleanup separately binds its intended group and current job, preventing an old command from retiring a returning owner. + +Store `version-adoption/v1` control metadata is a schema byte and a monotonic, group-local 64-bit logical epoch, initially 1. Each new retirement consumes an epoch and records it immutably. Each indexed promotion command consumes one epoch, independently of how many historical rows local compaction retained; replay of an already durable index consumes none. An authorized returning row is stamped with the promotion epoch while retaining its original commit timestamp, value, tombstone and expiry. Counter, rows, staged-row deletion, promotion progress and applied index commit atomically. Counter exhaustion refuses the operation. The counter is not a Raft index and survives same-lineage snapshot recovery even when a log is reconstructed. + +The legacy Pebble value header remains nine bytes for unadopted rows. Adoption sets flag bit 3 and appends an eight-byte epoch, making the header 17 bytes. Encryption authenticates the complete header, including an adopted tombstone's empty body. Reads authenticate before using epochs for visibility; unknown/future epochs fail closed. Native row/SST snapshots preserve the raw header; memory streaming snapshots use format V9 with an epoch on each version and the durable counter. V1-V8 remain readable and remain the output format when adoption has not been activated. A reader without floor-3 support must not join, restart or serve an activated group. + +A retirement hides only matching rows whose timestamp is at or below its ceiling and whose epoch is at or below its own epoch. A returned row therefore supersedes old retirement evidence without deleting that evidence or minting a new MVCC timestamp. A later retirement gets a higher epoch and hides the returned generation again. Both indexed cleanup and local GC must retain rows adopted after the retirement they are collecting, even if local cursors are lost or an old snapshot is restored. Snapshot restore and reopening reset disposable collection state but never reset the epoch counter. External-lineage restore continues to reject migration/control evidence rather than importing these generations as local authority. + +Acceptance requires a two-replica fixture with identical applied logs and different compaction histories: both must return the same value and version before retirement, both must return absence after retirement, and bounded physical collection must not change either result. Repeat across restart, encrypted storage, snapshots, learners, stale imports and ownership return. Model checking must include independent compaction, reachable successful CAS and cleanup actions, and a negative control showing predecessor resurrection under the old physical-only rule. The history checker must reject fabricated value/version provenance and unjustified CAS mismatches, including overlapping and indeterminate operations. Until these gates and final-head review/CI pass, this PR remains draft. + +The proposal gate contacts the other configured voters and learners to check capability. For a three-voter group without learners, a live check can add two peer status RPCs per attempt, in parallel. Include these in the production benchmark. A local fixture that replaces this gate can establish public RPC and data-proposal counts, but cannot establish the three-host latency or adoption criteria. Report the cost of activating a newly eligible group separately. + +The single-voter smoke run confirmed the predicted public RPC and data-proposal counts. Eight contenders for one version produced one successful update per round. The 100% stale case used one proposal per attempt for apply-only CAS and zero proposals for either fresh-read control. [Recorded contention counters](../evidence/2026_11_20_single_key_mvcc_cas_review.md#local-contention-counters-2026-11-21) + +Ordinary reads and writes also need a performance comparison with the flag off. Three short, interleaved local samples showed unchanged allocation counts for ordinary 1PC and reads. Median times for adapter reads backed by Pebble and for 1PC increased, with overlapping ranges in all cells. Repeat on dedicated hosts before enabling the feature. [Ordinary-path measurements](../evidence/2026_11_20_single_key_mvcc_cas_review.md#ordinary-path-measurements) + +## Delivery and verification + +1. Implement opt-in transactional Get across memory, Pebble and forwarding. Verify missing and empty values, historical visibility in the underlying reader, expiry, encrypted values and old-server responses. Benchmark ordinary Get for regressions. +2. Add the dedicated RPC and gated replicated predicate. Enable proposal only when the group, including learners and forwarding paths, supports the command. An old frontend returns an unsupported-method error. Prevent incompatible membership changes or binary downgrade while the log may still contain this command. To disable new use, stop admission and drain accepted work. +3. Run model-based single-key histories with puts, deletes, reads and CAS. Cover identical-value rewrites, delete/recreate, TTL at the boundary, concurrent requests in one entry, routing changes, dropped replies, leader loss, WAL replay and snapshot restore. Verify one winner per observed version, durable successful acknowledgments, deterministic mismatch verdicts and absence of effects on rejected attempts. +4. Run the paired benchmarks and publish raw counters, latency distributions, histories and configuration alongside the decision. Decide separately whether a measured rate of stale submissions justifies adding the fenced precheck. diff --git a/docs/design/2026_11_21_single_key_mvcc_cas_local_benchmark.md b/docs/design/2026_11_21_single_key_mvcc_cas_local_benchmark.md new file mode 100644 index 000000000..6eece57e7 --- /dev/null +++ b/docs/design/2026_11_21_single_key_mvcc_cas_local_benchmark.md @@ -0,0 +1,70 @@ +# Local single-key MVCC CAS benchmark + +This fixture runs the transactional Get and CAS gRPC handlers against a real single-voter etcd Raft group and synchronous Pebble FSM persistence. +The client and server share a process and use gRPC over `bufconn` without TLS. +All update arms use the sharded coordinator and leader-issued HLC timestamps, with no dedicated TSO group. +The fixture activates and verifies the replicated commit timestamp fence and migration version identity marker before sending writes. +Its admission checks validate the live sole-voter configuration and both applied markers on each CAS submission and versioned read. + +Run from the repository root after building the CAS and opt-in Get implementation. + +```sh +go test ./adapter \ + -run '^TestMVCCCASContention(Handles)?$' -count=1 -v + +go test ./adapter \ + -run '^$' -bench '^BenchmarkMVCCCASContention/(known|stale100|hot8)$' \ + -benchtime=10x -count=1 -benchmem + +go test ./adapter \ + -run '^$' -bench '^BenchmarkMVCCCASContention$' \ + -benchtime=1000x -count=1 -benchmem +``` + +One benchmark iteration is one round. The fixture uses fixed 1 KiB values with distinct replacements for each contender. +The test-only 1PC frontend uses the same fenced versioned-read helper as the public Get. +It checks the observed version and submits the replacement with that snapshot's original timestamp and target in the OCC read and write sets. + +| Arm | Timed work with the original version already known | +| --- | --- | +| CAS | Public CompareAndSwap | +| Fresh | One RPC that reads, checks the version and submits 1PC | +| TwoCall | Acquire a fresh read handle, then submit 1PC if the version matched | +| Retained | Submit 1PC against the original read handle | + +Handles are bound to the client, key and observed version. +They release the snapshot pin on consumption, explicit cancellation, or expiry after five seconds. +The handle test checks client binding, cancellation, reuse and expiry. +For a successful update in `known`, expect one data proposal per arm and one extra client RPC in TwoCall. +`known-inclusive` charges the original acquisition in every arm, including the retained handle. + +`stale50` and `stale100` advance exactly four or eight of eight original versions by rewriting the same bytes. +The measured attempts use separate keys and run sequentially to isolate the injected stale predicate from shard-wide timestamp reordering. +The hot cells release 2, 8 or 32 contenders together against one version, with no client retries. +The separate parked correctness trials wait for all eight attempts at the Raft proposal boundary, then submit in ascending or descending commit timestamp order. +Together those trials distinguish the baseline's OCC conflicts from its commit-order rejections, which share a wire error. +The harness matches returned success timestamps and values against exported Pebble versions and requires one winner in each hot correctness round. + +The reported per-method RPC counts come from the unary client interceptor. +Proposal counts come from calls into the real Raft engine, including completed proposals whose FSM verdict rejected the update. +The engine wrapper counts typed FSM verdicts before gRPC projects them to public statuses. +Applied fences and leader checks count calls to the engine methods. The local election settings disable Raft lease reads, and a single voter can satisfy those checks locally. +Control reads count fenced pre-reads by the 1PC frontend. +Handle pin time includes already-retained pins carried into the timed update. +Setup, reset, history verification and background HLC renewal are excluded from request counters. +The natural hot benchmark reports baseline write conflicts together and reports CAS exact mismatch separately from its certified timestamp conflict. +Per-success ratios and success latency percentiles are omitted when there are no successes. +`ns/op` is per round, `ns/attempt` divides round wall time by the number of attempts, and p50/p95/p99 use individual latencies measured from release to reply. + +This is a local smoke and correctness fixture. The planned three-host adoption experiment also requires calibrated open-loop arrivals, a separate load generator, TLS, multi-voter replication, paired runs, and the broader instrumentation in the [CAS design](2026_11_20_proposed_single_key_mvcc_cas.md#contention-benchmark). + +## Ordinary-path comparison + +Run the same fixtures against the candidate and the base revision. For an older checkout, copy `adapter/ordinary_get_comparison_test.go` and `kv/ordinary_write_comparison_test.go` into the corresponding packages. Existing benchmark results used identical fixtures with Go overlays. Alternate the two revisions and retain the output from each run. + +```sh +GOMAXPROCS=2 go test -p 1 ./adapter ./kv -run '^$' \ + -bench '^BenchmarkOrdinary' -benchtime=150ms -count=1 -benchmem +``` + +The write fixture measures the leader-local path through the counting proposer with 1 or 64 ordinary mutations. The read fixture compares the plain Pebble point read and direct adapter calls on a hot 1 KiB value. [Boundaries and results](../evidence/2026_11_20_single_key_mvcc_cas_review.md#ordinary-path-measurements) diff --git a/docs/design/2026_12_02_partial_protected_follower_append_batch.md b/docs/design/2026_12_02_partial_protected_follower_append_batch.md new file mode 100644 index 000000000..6eb5fbf3a --- /dev/null +++ b/docs/design/2026_12_02_partial_protected_follower_append_batch.md @@ -0,0 +1,123 @@ +# Bounded Protected Follower Append Batching + +Author: bootjp + +Status: Implemented for recognized, plaintext CAS entries. Native-path regressions, +latest-head reviews, CI and hosted stress pass at `d09c8ddde8`. Its full combined +code/storage performance trial aborts on unknowns in the first fresh-control +warmup, before the CAS arm. It supplies no accepted performance result. This +does not enable CAS or override its failed primary adoption gate. + +## Motivation + +An index-correlated diagnostic on source `7196894fa5` identified a 643 ms +proposal wait. The first usable follower ACK followed a 640 ms required Raft +WAL sync. The other follower was already blocked by an older 1,209 ms WAL sync +and 292 ms FSM apply. The former follower then saved queued appends individually. +Independent 4 KiB appends reproduced 672 ms and 1,408 ms fdatasync maxima on +the two follower VMs with Elastickv stopped. Batching cannot remove an already +running sync or identify the physical device's reason for that delay. + +The narrow opportunity is to reduce subsequent entry-bearing WAL Saves while +catching up. Do not skip durability, dispatch ACKs early, change unknown outcomes, +or activate the separate asynchronous storage prototype to obtain a pass. + +## Owner Scheduling + +Only the existing synchronous owner groups already-waiting normal protected +messages before obtaining its next Ready. There is no batching timer or new +goroutine. A singleton takes the existing immediate path. Each grouped message +passes its own native admission and receipt revocation scope before RawNode.Step. +No scope is held across messages, persistence, FSM apply or outbound dispatch. +Batching requires an installed native admission arbiter as well as sealed peer +receipts; a receipt alone cannot opt an unprotected runtime into batching. + +Eligibility requires a stable follower, the same current leader and term, +commit equal to the completely applied prefix, no pending configuration change +or snapshot transition, and no outstanding Ready at batch start. Append entries +must strictly extend the known last index and term; retransmission, overwrite, +gaps and noncurrent entry terms retain single-message scheduling. All messages +retain the first receipt's generation, unchanged commit and configuration. + +Before starting, inspect the already-persisted but uncommitted suffix too. It +must contain only recognized current-term data entries, with inspection limited +to 64 entries and 128 KiB. An earlier uncommitted control, unknown command or +encrypted entry disables batching. Missing, compacted, larger or inconsistent +suffixes fall back without advancing or altering the log. This check prevents +an authority barrier already in the WAL from being hidden ahead of the batch. + +An optional, pure FSM classifier recognizes the exact cleartext payload. +The initial KV implementation accepts only fully decoded supported CAS frames +with valid standalone shape and no unknown request/mutation fields. Ordinary +1PC, HLC grants, activation, migration, encryption and other control payloads +remain single-message. Entries past the applied encryption cutover are not +classified or decrypted for batching. Unknown FSMs opt out. This changes no wire +or persisted format and introduces no new authority or capability grant. + +CAS metadata is decoded only after declared field sizes are bounded by both +`math.MaxInt` and the remaining reader bytes, before allocation. All four field +decoder callers return immediately on truncation, so none relies on consuming +the remaining input on failure. Existing field-specific errors are preserved. +Legacy V1 apply/read decoding still tolerates trailing bytes; only this scheduling +classifier requires exact V1 consumption. V2 already rejects trailing data. + +Stop before an uncertain payload, control entry, commit advance, term/leader or +configuration change, snapshot or byte/entry limit. Yield when priority steps, +reads, admin work, snapshot results, dispatch reports, ticks or close are pending. +Admission failure terminates the batch without consuming later requests. + +Reads/admin requests use unbuffered channels, and synchronous Go ticker channels +also report length zero when ready. A nonblocking select captures at most one +local event rather than inspecting those lengths. The owner services it through +the original handler only after draining Ready, rechecking context/admission. +Failure/leadership loss completes a captured API waiter even though it has not +entered the ordinary pending map yet. Shutdown releases deferred inputs; a +leadership change alone does not discard a captured Tick. + +## Bounds And FIFO + +A batch contains at most 32 messages, 64 entries and 128 KiB of protobuf-encoded +message bytes. Payloads are borrowed from the existing owned inbound messages; +the classifier may allocate bounded decode state but retains no payload. + +When reading the next normal message reveals a boundary, the owner defers that +one message until after the current Ready drains. It precedes all later normal +messages, while existing priority processing still takes precedence. Reserve +one slot from the normal protected channel for this deferred message, so the +old channel-plus-owner request-count bound does not grow. A deferred boundary +retains the existing inbound RPC size limit, not the batch's smaller byte limit. + +## Durability And Recovery + +The ordinary Ready drain remains unchanged: persist the complete entries and +HardState, apply committed work in order, reconcile protected authority, dispatch +responses, then Advance. An append ACK can cover persisted but uncommitted data; +it is not a public CAS receipt. Public success still requires quorum commit, +matching proposal ID/digest, durable local FSM apply and result admission. + +Every caller of `handleStepWithAdmission` and `handleProtectedStep` was audited. +Their new boolean reports only an error-free admitted Step, not append acceptance, +WAL durability or client success. Existing callers ignore it; the batching loop +uses false solely to stop after a failed admission or Step. Existing fatal/error +classification and snapshot cleanup remain unchanged. + +Protected-session native tests queue multiple independent appends, pause the +real WAL Save, verify no ACK escapes, then reopen the WAL and recover the original +indexes and distinct payloads. A pre-write Save failure emits no ACK and recovers +no new entries. A post-write error may recover the durable suffix but still +must emit no ACK. Neither error is proof of a definitive client noncommit. +Boundary tests cover commit/term, membership, unknown/control/encrypted payloads, +aggregate message/entry/byte limits, singleton/unknown-FSM fallback, authority +revocation between individual Steps, priority work, and deferred FIFO order. + +## Measurement Gate + +Instrumented results identify `adaptive-precheck-key-admission-follower-batch`. +The explicit apply-only diagnostic also disables this batching classifier in +its build overlay; it does not silently retain the new CAS scheduling hint. +`raft_wal_entry_save_attempts` counts entry-bearing Save attempts, not successful +physical device flushes. Record failures and distinguish commit-only HardState +updates. Preserve all earlier primary failures and the passing hot-key result. +New trials retain the original workload, calibration, deadlines, retries and +paired numeric gates. Storage placement changes are separate interventions, +not proof that batching alone removes physical storage latency. diff --git a/docs/design/2026_12_02_single_key_mvcc_cas_host_benchmark.md b/docs/design/2026_12_02_single_key_mvcc_cas_host_benchmark.md new file mode 100644 index 000000000..6ae5b9e62 --- /dev/null +++ b/docs/design/2026_12_02_single_key_mvcc_cas_host_benchmark.md @@ -0,0 +1,133 @@ +# Dedicated-Host CAS Benchmark + +Author: bootjp + +This is an experimental measurement harness for the single-key MVCC CAS +proposal, not a new production API or permission to enable CAS by default. +The normal server does not import or register `internal/casbenchmark`. + +## Build And Isolation + +Build `cmd/casbench` from a recorded, clean commit. Generate an explicit Go +overlay with `casbench overlay --root /checkout --output /new/overlay`, then +build the ordinary server with `go build -overlay /new/overlay/overlay.json .`. +Retain the source commit, build flags, binary SHA-256 and overlay `sha256.json`. +The overlay refuses missing or ambiguous AST anchors and never edits source. + +The revised server's `--versionCAS` startup installs adaptive-precheck. Meter +results explicitly record `cas_mode: adaptive-precheck-key-admission-follower-batch` and count local hint +reads and fenced confirmation reads separately from applied predicates and +data submissions. In an overlay build only, +`ELASTICKV_CAS_BENCH_APPLY_ONLY=1` omits that startup check and records +`cas_mode: apply-only`, retaining the original diagnostic variant. This +environment variable has no effect on ordinary production builds. Preserve +both failed apply-only histories and every revised run. Do not combine variants +or use a short fixed-rate diagnostic as an adoption result. All gates below +remain unchanged. + +The revised meters also record each window's UTC start and count CAS predicate +verdicts inside the FSM, independently of whether the client-side proposal +callback survived its deadline. Local hint outcomes are separate counters. +Callback success/mismatch totals alone undercount applied outcomes after a +timeout; neither set of counters resolves an unknown client operation. + +Use three disposable Linux voters on different physical hosts and a fourth +load-generator host. Keep mTLS, synchronous Pebble persistence, the sharded +coordinator, capability fanout, policy/session admission and normal HLC lease +renewal enabled. Restrict network access to this experiment. The additional +RPCs accept only the `bench1535/` namespace and bounded values/seed batches. +They require receiver-owned protected Data admission through completion. +They are not an administrative control surface for a shared cluster. + +`casbench pki --addresses IP1:50051,IP2:50051,IP3:50051 --remote-root /ops +--output /new/pki` creates fresh identities and private artifacts. Keep private +keys, admin/startup credentials and source backups out of published evidence. +Only signed public baseline/activation artifacts may be collected publicly. +Follow the existing offline bootstrap procedure without editing observations, +selecting a maximum cut or bypassing rejected pending state. + +An optional `ELASTICKV_CAS_BENCH_PREPARE=1` overlay-only mode suppresses HLC +background renewal and shutdown handoff solely while constructing a disposable +legacy source fixture. This is not a production quiesce protocol. A real +committed data operation is required to align native and FSM durable cuts. +The meter refuses to begin any measurement in this mode. All measured nodes +must restart without it after strict inspect/prepare/resume/attest/certify. + +## Workload And Evidence + +Run on the separate load VM, using a fixed leader: + +```sh +casbench campaign --endpoint IP2:50051 \ + --voters IP1:50051,IP2:50051,IP3:50051 --tls-dir /private/client \ + --cell primary --output /new/results-primary +casbench campaign --endpoint IP2:50051 \ + --voters IP1:50051,IP2:50051,IP3:50051 --tls-dir /private/client \ + --cell hot --output /new/results-hot +``` + +Defaults are 30-second warmups, 120-second measurements, ten alternating +matched pairs, eight workers, 1 KiB values and a one-second scheduled-arrival +deadline. Primary keys are uniform over 65,536 disjoint worker partitions. +Hot-key requests use four total attempts and deterministic uniform full jitter +over 0-1, 0-2 and 0-4 ms. Both arms update cached tokens from confirmations; +rejected tokens are refreshed only through counted reads. The control executes +one fenced read and 1PC in a single server handler with the original read +timestamp and voucher. Its read pin remains held until submission completes. + +Control calibration includes the same warmup, doubles from 16/s, then bisects within 5%; decision windows +use the frozen 80% rate. Primary calibration requires 99% on-time successes; +contention calibration uses definitive on-time outcomes. These 99% criteria +are separate from the decision's zero-unknown gate: +an indeterminate calibration attempt is not an on-time success or definitive +outcome, but does not invalidate a trial whose other 99% meet the criterion. +Unrecognized outcomes never count as definitive. Calibration +windows remain diagnostic, including unknown outcomes. Each calibration trial +uses a new namespace after receiver work drains. The measured pairs use a new +namespace, so indeterminate calibration writes cannot become decision tokens. +Unknown measured writes stop the campaign; they are never retried as absent. +An overloaded calibration warmup also requires a fresh namespace before its +120-second diagnostic window. No indeterminate warmup head is silently reused. +Rates, arm order and trace seeds are written before either measured arm runs. + +Raw JSONL includes every scheduled operation, queue expiry/overflow, attempts, +expected/new timestamps as decimal strings, RPC status and refresh calls. +Histories and summaries are saved before remote end-meter collection. All +reachable meter windows are ended even when another node is unavailable; +partial meters carry a separate error artifact and fail the campaign, never +silently becoming zero counters or an accepted decision result. +Bookended server counters include method-level RPCs, wire payload bytes, +ReadIndex/leader verification, timestamps, proposals/entries and typed apply +verdicts. Data counters distinguish benchmark keys from background traffic. +CPU and allocation deltas include all activity in the same wall-clock window; +they are not a request-causal trace. Pebble WAL sync counters count successful +VFS persistence calls, not physical device flushes; gRPC wire counters are not +TLS/IP byte totals. Collect OS/network/host-capacity evidence separately. + +The driver checks stable term/configuration/leader, drained unary handlers and +applied progress and absence of an uncommitted log tail between windows. Every +voter must also report the same committed prefix: a locally idle follower can +still be behind the leader. Divergent sampled positions reset the existing +two-sample stability check within the unchanged setup timeout; there is no +fixed cooldown or change to offered rates or client deadlines. Earlier results +used only the local check and remain recorded with that limitation. +It validates the predecessor chain of every +acknowledged update and reads final values/versions outside measurement. +It reports success p50/p95/p99 separately from all-outcome latency, goodput, +unknowns, exhausted retries, unsent work and deadline misses. Short or fixed-rate +parameters are diagnostic and cannot pass the decision gate. + +`result.json` evaluates the numeric primary or hot decision cell only. Even a +passing cell is not full adoption evidence: both cells, the ordinary flag-off +comparison, acquisition-inclusive and retained-handle diagnostics, the remaining +design matrix, correctness checks and final-HEAD review/CI are independent +requirements. Insufficient samples or failed/inconclusive intervals defer +adoption. Do not relax the design thresholds to promote a result. + +## Teardown + +Record every temporary VM's ID, name and physical placement before provisioning. +Install a bounded cleanup watchdog. Collect histories, counters, public +configuration, logs and checksums before deleting only those recorded VMs. +Verify cluster inventory and deletion tasks, then remove the watchdog and +ephemeral private keys. Never run this workload on production voters. diff --git a/docs/design/2026_12_03_proposed_acknowledged_append_feedback.md b/docs/design/2026_12_03_proposed_acknowledged_append_feedback.md new file mode 100644 index 000000000..7bb4d61e3 --- /dev/null +++ b/docs/design/2026_12_03_proposed_acknowledged_append_feedback.md @@ -0,0 +1,89 @@ +# Acknowledged Append Failure Feedback + +Status: implemented in the experimental branch; performance adoption pending. +Extends the dispatch-overload feedback design without changing its heartbeat +rules, storage format, or durability boundary. + +## Problem and Reproduction + +A transport failure or local drop can be delivered to the owner after a later +retransmission has durably reached the follower and its response has advanced +the leader's acknowledged prefix. Unconditionally reporting that older failure +as unreachable changes Replicate to Probe, empties its inflight window, and +allows another copy of an already queued suffix into the FIFO. + +Real RawNode regressions reproduce both a local drop and a delayed gRPC failure. +Before the fix they observe unchanged Match but a Replicate-to-Probe transition, +Next moving backwards, and duplicate suffix entries. This is an independently +reproduced amplification bug, not proof that it explains all performance misses. + +## Decision + +Both failure-report producers capture only the original nonempty data Append's +term and final contiguous entry index. They retain no message payload, receipt, +or positive authorization decision. The range must be locally sourced, have a +distinct nonzero destination, contain no snapshot side payload, and have valid +predecessor and entry indexes and nondecreasing nonzero entry terms no greater +than the message term. Unknown or malformed ranges use the existing fallback. + +On the RawNode owner, inside the existing native scope, suppress unreachable +feedback only when the current node is leader in the original term and the +current destination progress has Match at or beyond the entire original range. +Next, inflights, queued messages, and predicted progress are not acknowledgments. +A later-term report remains conservative even when Match happens to cover it. + +The check neither retires queued messages nor advances Match or commit. A real +unacknowledged suffix still takes the ordinary recovery path. Snapshot outcome +reporting remains unchanged. Drop and error counters increment before the report +is processed, including when obsolete feedback is subsequently suppressed. + +## Authority and Durability + +The report is local transport feedback, not a peer response or a client write. +It must enter the existing native callback; a denial is not bypassed by an +early acknowledged-range check. Engine shutdown also prevents a selected local +Append report from mutating progress after shutdown wins before delivery. + +The authority for Match comes from separately admitted inbound responses. A +protected response must pass its captured receipt and current native session +generation at owner delivery before it can affect RawNode. Tests use a real +session owner, arbiter, transport ingress, and follower-generated response. +Receipt revocation and generation suspension prevent that response from +advancing Match; an old response is also denied after forced numeric-ID reuse. +Protected membership policy rejects actual lifetime-ID reuse. Unprotected Raft +continues to require lifetime-unique IDs, as required by the Raft implementation. + +WithNative is also an internal serialization/observation primitive. A background +nil-request callback is not a client-operation capability: arbiter Suspend, +Close, or LatchFatal alone is not a blanket veto on such callbacks. This change +does not redefine that API. Its local-owner denial and shutdown tests are +separate from the production peer receipt/generation revocation tests. + +No persistence, FSM application, response payload, or outcome classification +changes. WAL synchronization, ordered apply, and ACK retain their existing +boundaries. Unknown outcomes are never converted into definitive mismatches. +The earlier snapshot durability proof does not establish this feedback rule or +verify the Go implementation of peer admission. + +## Validation and Adoption + +Regression coverage includes delayed real RPC failure, local drop, a later +same-term ACK, changed term, membership replacement, malformed ranges, zero/self +destinations, partial acknowledgment, full report queue, and genuine lost-suffix +recovery without another proposal or election. Progress and the original FIFO +are checked, not just eventual applied state. + +The preceding candidate's original R10 adoption cells both failed: primary had +2,309 unknown outcomes and hot had 684 in their first Fresh measurement. R11 is +a separate retained-process diagnostic, not an adoption retry: at primary 217/s +it recorded 25,957 successes and 83 unknowns out of 26,040 scheduled requests. +The leader and one follower had complete actual-sync accounting; the other +follower's capture has diagnostic/conservation errors and remains incomplete. +One-second role samples and bounded cross-host clock comparisons do not prove +the exact blocking dependency. No snapshot or disk-sync root cause is asserted +from these observations alone. + +The same original calibration, workloads, deadlines, thresholds, alternating +pairs, history checks, and independent hot cell must pass on the integrated +candidate. Partial windows, diagnostics, normal review, and CI do not substitute +for that adoption gate. The feature remains disabled by default. diff --git a/docs/design/2026_12_03_proposed_dispatch_overload_feedback.md b/docs/design/2026_12_03_proposed_dispatch_overload_feedback.md new file mode 100644 index 000000000..1e1a60324 --- /dev/null +++ b/docs/design/2026_12_03_proposed_dispatch_overload_feedback.md @@ -0,0 +1,155 @@ +# Dispatch Overload Feedback + +Status: Implemented candidate. Integrated verification and performance acceptance pending. + +## Failed Candidate + +The original performance campaign for `a86a8494ef` calibrated the primary fresh +control at 296 operations/s and froze 236 operations/s using the unchanged 80% +rule. Six complete alternating pairs had no unknown outcomes, deadline misses +or unsent operations. Their CAS/fresh p99 ratios were approximately 0.806, +0.717, 0.906, 0.823, 0.968 and 7.978. The ninth-order upper ratio could therefore +no longer satisfy the primary limit of 0.90, regardless of later pairs. + +Pair 06 fresh warmup also had no unknown outcomes. Its measurement then returned +26,925 successes and 1,395 unknowns out of 28,320 scheduled operations, including +696 deadline misses and no unsent operations. The following confirmation timed +out. This unexpected error stopped the campaign; the independent hot cell did +not run. Neither the six successful prefixes nor review and CI success override +this failed performance result. + +The first unknown had an Unavailable result after about 4 ms in its first +attempt, with about 87 ms between scheduled arrival and send. Thus this failure +is not solely operations that waited in the worker queue for the entire one +second. No unissued or ambiguous operation is reclassified by this design. + +Independent reconstruction validated calibration and 431,880 acknowledged +updates in the 25 complete decision windows before the first unknown window. +There is no complete-campaign or final-head validation claim. + +The final observations report n1 as leader in term 4. After the workload, all three voters were caught +up to within eight applied entries and their owner loops were idle. Leader n1 +recorded 261,229 outbound drops, with sampled MsgApp drops specifically to n2. +Follower n2 recorded 280,960 inbound-queue-full events and about 2.7 million +successful local stream sends over approximately 82 minutes. Heartbeat rejection +from n2 began during calibration. These are different counters, not matched +send/receive events; a stream send does not establish remote Step or durability. +There is no per-allocation attribution for the roughly 3 GB leader heap. + +All histories, meters, logs and durable synthetic fixtures were collected before +removing the four owned VMs, disks, watchdog and temporary credentials. Absence +was verified across all eight Proxmox hosts. No production node was used. + +## Source Mechanism + +Raft progress advances when RawNode emits an Append. The dispatcher separately +owns immutable queued and active copies. A non-snapshot send failure currently +reports the peer unreachable, even if the failed message was a heartbeat that +the receiving peer explicitly rejected because its ingress queue was full. + +ReportUnreachable moves Replicate to Probe and clears inflights; it does not +remove old Append copies from the dispatcher. A later heartbeat response, +including one with a ReadIndex context, can trigger another Append. Delayed +failure reports can also reset a peer that has already recovered. Repeated +delivery remains real decoding, receipt validation and owner work even if the +follower immediately reports its already-committed index. + +This is a source-supported amplification mechanism, not yet a measurement of +its contribution to pair 06. Earlier different-leader diagnostics had unknowns +without drops. Correcting this mechanism alone does not establish the p99 gate +or explain every observed failure. + +## First Change + +Distinguish only two known overload outcomes for MsgHeartbeat: a local dispatch +lane refusal and an explicit structured remote ingress-full response. Retain +error and drop accounting, but do not translate those outcomes into failure of +the independent Append replication window. Ordinary heartbeat, read retry and +CheckQuorum continue unchanged. No message is treated as delivered or acknowledged. + +Remote overload identification must use a narrowly checked structured status, +not error-string parsing or all ResourceExhausted errors. Old peers and ambiguous +network failures retain conservative existing reporting. Actual Append failure, +other message failures and snapshot finish/failure preserve their existing paths. + +Keep all queued Append messages in FIFO order. Do not discard by age, index, +apparent range overlap or a newer final applied index. Empty Appends can be the +probe needed to resume replication. No read context is merged or replaced. + +Avoid scanning a dedicated context-bearing heartbeat-response lane for a plain +heartbeat response that normal routing never places there. Every queued context +and its original order must remain intact. + +## Safety And Regression Evidence + +The change concerns negative transport feedback, not positive authority. Keep +each operation's native admission, each message's receipt/session generation, +owner-side Step validation and current result consumption validation. Revocation +between enqueue and Step must still deny the message. Revocation after issue +must not turn an ambiguous submitted write into a definitive mismatch. + +The original WAL synchronization, committed application and result publication +order is unchanged. A transport send is not a follower acknowledgment. Use real +RawNodes and genuine responses to reproduce the Replicate-to-Probe reset before +the fix. Keep an old Append outstanding while an explicitly overloaded heartbeat +fails, then test delayed failure after recovery. The candidate must retain the +Append window for known heartbeat overload while actual Append failure still +enters Probe and recovers. Test a healthy quorum and eventual slow-peer catch-up. + +Test structured status round trips and negative cases for wrong message type, +reason/domain, unstructured ResourceExhausted, legacy Unknown and connection +failure. Fill the context response lane without losing or merging existing +contexts. Run receipt-revocation, WAL/apply gating and shutdown regressions. +Audit all callers of changed report and transport helpers. + +`TestDispatchHeartbeatOverloadPreservesInflightAppend` reproduces the local +heartbeat-refusal reset with three real RawNodes and their actual responses. +Before the fix, the progress changes and the same entry appears twice in the +queued replication messages. With the fix, the original single entry remains +queued, the healthy quorum can commit and complete a read, and the slow peer +catches up. The same test loses a real Append and verifies that ordinary +unreachable reporting still enters Probe and repairs the missing entry. + +Separate recovery tests discard an outstanding Append without any failure +report and restore the link with only manual ticks and genuine follower +responses: no new proposal or leadership change is needed. Another test commits +a new write through the healthy voter while the slow heartbeat lane remains +full, then checks eventual catch-up. A real gRPC overload error is also held +until after the peer has acknowledged an old Append and a newer Append is +queued; its late completion must preserve Match, Next, inflights and queued +entry indexes while incrementing error accounting exactly once. + +`TestGRPCHeartbeatIngressFeedback` exercises actual gRPC status serialization, +keeps the local queue-full cause available through errors.Is, and distinguishes +typed heartbeat overload from other codes, details, domains, reasons, message +types and legacy errors. No protocol field or peer capability is added. +Mixed-version links preserve conservative reporting unless both endpoints +support the typed status. Downgrading either endpoint can restore the old +amplification, and new receivers change the corresponding per-code metric +bucket from Unknown to ResourceExhausted. This is not an authority downgrade. + +The earlier Lean publication and durable-prefix models remain unchanged: this +patch adds no positive issue, ACK, result or authority transition. Those models +do not prove the concrete dispatcher, retry liveness or performance. The real +RawNode and existing admission/durability tests supply separate runtime evidence. + +## Further Work And Acceptance + +The synchronous dispatcher still lacks the asynchronous pipeline's pre-clone +byte reservations. Count limits alone can retain large queued Append payloads. +Any subsequent byte-bound design must include active sends, independent control +capacity, peer fairness, maximum legal-message progress and every retirement +path. A smaller byte cap alone can increase drops and unreachable reports; it +must not be assumed to solve congestion. This is separate from the first change. + +Measure first-growing waits in a separately hashed diagnostic build if needed: +client queue, capability/native admission, dispatch enqueue-to-send, per-peer +Append ranges and progress transitions, WAL and Pebble sync, snapshot export and +pin lifetime. Keep all data synthetic and traces finite. Diagnostics cannot be +used as acceptance results or sent with credentials/raw stack arguments. + +After a real fix, require signed push, latest-HEAD normal/security review and CI, +durability and fault-injection tests, then fresh identities for the original +primary and hot campaigns. Keep independent calibration, ten alternating pairs, +deadlines, attempts, workload, control and every numeric gate unchanged. Preserve +every failed prefix; do not rerun unchanged failures to select a favorable result. diff --git a/docs/design/2026_12_03_proposed_fenced_floor_error_identity.md b/docs/design/2026_12_03_proposed_fenced_floor_error_identity.md new file mode 100644 index 000000000..f57cb7db3 --- /dev/null +++ b/docs/design/2026_12_03_proposed_fenced_floor_error_identity.md @@ -0,0 +1,85 @@ +# Fenced Read Floor Error Identity + +## Status and Scope + +Proposed corrective integration for single-key MVCC CAS acceptance. This is +not a claim that the normal-operation hot-key performance gate has passed. +The latest multi-group Redis fence GC CI recorded a three-append EXEC with +three `tso` error slots during an intentional leadership transfer. The saved +history lacks the underlying Go error, so it does not prove that this particular +EXEC took the path below or establish its outcome. + +Source inspection identifies a reproducible error-propagation defect: +`GroupCommittedTimestampFloor` formats a ReadIndex rejection with `%v`, retaining +only `ErrTSOCommitFloorUnavailable` as a typed cause. During transfer, an old +leader can still report leader while ReadIndex returns +`raftengine.ErrLeadershipTransferInProgress`. The existing Redis error mapper +recognizes this sentinel as an EXEC-level `NOTLEADER`, but cannot recognize it +after the floor wrapper erases its identity. A proxy can then reconstruct the +unrecognized EXEC error as one error per queued command. + +## Decisions + +1. Preserve floor-unavailable classification and the isolated, typed or + CockroachDB-marked leadership-transfer rejection across the local + leader-fenced floor boundary. Other ReadIndex failures retain their existing + floor-only error path; identical error text is not authority. Return no + floor or target proof on failure. Never substitute a local follower watermark + or another healthy group's watermark. Mixed, ambiguous causes must not + acquire a transfer-only classification. +2. Retain the existing EXEC-level error mapping and proxy terminal handling. + Prove the complete producer-to-proxy path with the actual typed transfer + rejection. Preserve genuine mixed EXEC arrays, including WRONGTYPE slots. +3. Do not add mutation retries or classify a submitted operation as uncommitted. + A failure preparing a later reuse attempt does not resolve an earlier + attempt. On timestamp-allocation failure while preparing an existing EXEC, + list-push or XADD reuse attempt, return outcome-unknown, preserve the prior + start/commit timestamp and write set, and perform no further mutation + dispatch. Lost responses and post-submission leadership changes remain + indeterminate. The Jepsen checker and recorded histories stay unchanged. +4. Do not change native admission, session/receipt generation validation, + per-operation revocation, timestamp ceilings, or WAL sync -> apply -> ACK. + No positive authority cache, early ACK, or new success fast path is added. +5. Audit every caller and error classifier affected by retaining an error cause, + including gRPC status precedence and global/keyed/startup floor consumers. + Raw watermark cancellation/deadline precedence must not change. At the local + TSO term-initialization boundary, project the new dual-identity data-group + transfer failure back to floor-only classification: it is not a TSO leader + routing rejection and must not enable a new reservation retry. Remote group + echo and leader-fenced validation remain unchanged. + +Independent design review identified two reasons for this narrower scope: +retaining arbitrary causes changes watermark RPC status and retry behavior; +even the transfer mark can activate TSO routing retries. It also identified +the existing reuse-allocation return sites where a later preparation failure +cannot resolve the earlier operation. These corrections are part of this +proposal before implementation. + +## Validation + +- Reproduce loss of the transfer sentinel with a leader-shaped engine whose + ReadIndex rejects during transfer. Require both error identities, zero floor, + no target proof, and no help from a healthy unrelated group. +- Require untyped same-text errors and mixed/ambiguous errors to stay outside + transfer classification. An internal ReadIndex deadline with a live caller + must retain the existing key-free Unavailable watermark reply. A data-group + transfer during local TSO term initialization must perform one floor attempt + and zero reservations, not trigger a new TSO routing retry. +- Exercise first-attempt EXEC with three RPUSH commands and the real floor + failure. Require zero mutation dispatches and one top-level NOTLEADER through + the proxy, not three fabricated error slots. Genuine mixed success/error arrays + must retain their original shape. +- Exercise post-submission loss and a later reuse-preparation failure. Preserve + unknown outcome, original attempt identity and no fresh mutation replay. +- Run focused normal/race tests, five separate review lenses, latest-HEAD review, + all CI including single/multi Redis GC, and unchanged CAS/ZSet stress. +- Only then perform the original independent primary/hot performance acceptance + with unchanged workload, deadlines, calibration, thresholds and full histories. + A protocol-shaped error correction alone is not a performance acceptance pass. + +## Non-Goals + +No successful-completion guarantee across a transfer, read-only successor lookup +retry, blanket retry of TSO errors, changes to the timestamp oracle's responsibility, +or relaxation of uncertainty handling is included. A successor-lookup retry needs +its own design and revocation/deadline evidence if later measurements require it. diff --git a/docs/design/2026_12_03_proposed_fresh_append_batching.md b/docs/design/2026_12_03_proposed_fresh_append_batching.md new file mode 100644 index 000000000..8b66c9995 --- /dev/null +++ b/docs/design/2026_12_03_proposed_fresh_append_batching.md @@ -0,0 +1,143 @@ +# Read-dependent Fresh1PC in protected follower append batches + +Status: Proposed +Author: bootjp +Date: 2026-12-03 + +Implementation is under review. Performance adoption remains open. + +## Scheduling change + +At `d797ee4b6`, a sharded coordinator could emit a single Fresh1PC PUT that +the leader recognized for its bounded proposal turn. The follower recognized +only standalone CAS commands for its bounded append turn. Four protected +appends at commit 1 carrying actual coordinator output reached the follower +WAL as a first Save of index 2, with indexes 3 through 5 still queued. + +The new follower case accepts a plaintext single-request frame of at most +128 KiB, including its opcode. The leader and follower share the existing +strict PUT shape check. It requires a stamped one-phase transaction, exactly +one complete V1 metadata header and one direct user-key PUT, matching primary +key, and a commit timestamp above the start timestamp. The follower additionally +requires a populated observed route version and exactly one read of the +written key. A plain PUT with no read dependency still takes the ordinary path. +The protobuf field allowlists, wire-size check and metadata validation exclude +unknown fields, other mutations, retry or binding metadata, internal namespaces, +and control commands. Batch frames and encrypted entries fall back. The CAS +decoder and its existing size and V2 metadata rules remain independent. + +Classification validates the decoded shape and encoded size without changing +the original bytes, read dependencies or routing proof. Valid protobuf field +order permutations are allowed; byte-for-byte canonical ordering is not a +condition for data-only scheduling. Unknown fields, duplicate/default encodings +that fail the size check, and unsupported request shapes still fall back. +The scheduling decision carries no authority. The normal +apply path verifies route ownership and performs OCC for each committed entry. + +## Owner and durability boundaries + +The synchronous protected follower starts with no pending Ready and an applied +index equal to commit. The queued appends must extend the exact previous index +and term with current-term normal data. Leader, term, commit, configuration and +receipt generation must match throughout the turn. The cursor also pins the +encryption cutover. The owner samples the actual cutover before validating the +persisted suffix, at each extension and when deciding whether to continue. +Even a change that leaves all the indexes in plaintext ends the turn. + +The owner inspects at most 64 existing uncommitted entries and 128 KiB of +suffix. A control entry in that suffix prevents grouping. The new turn retains +its separate limits of 32 messages, 64 entries and 128 KiB of encoded messages. +It consumes only already-waiting work. Priority traffic, ticks, local work, +configuration or snapshot transitions, and admission denial still end the turn. +A discovered normal boundary stays ahead of later normal messages in the FIFO. + +Each Step requires the individual native check and the actual receipt's +admission scope. One synchronous Ready persists the entries in order. Each +original append gets its own response after successful persistence. A failed +Save suppresses the responses even when WAL reopen finds the entries. A later +commit advances the FSM in log order, retaining each entry's own result and +Pebble durability boundary. + +## Regression evidence + +The classifier RED used the coordinator's sharded read-dependent frame. The +protected-owner RED used a real session over an in-process gRPC listener, the +production KV FSM classifier, and a gated etcd WAL. The old first Save contained +`[2]` against an expectation of `[2, 3, 4, 5]`. + +| Check | Observed result | +| --- | --- | +| Four prequeued frames | One entry-bearing Save of indexes 2-5, four native checks and four individually indexed responses. The queue contains zero ACKs while Save is held. | +| WAL reopen | Exact original proposal envelopes and payloads at all four indexes after success or injected post-write failure. Pre-write failure leaves zero entries. Both failures produce zero ACKs. | +| Uncommitted suffix | A persisted Fresh1PC at 2 allows the next Save of 3-5. A fence activation at 2 restricts that Save to 3. | +| Changed authority | Revoking the peer receipt before the second Step leaves only index 2 accepted. Changing the cutover within the plaintext range also stops extension. | +| Catch-up after a held entry Save | Four frames queued while the WAL held the independent-key Fresh prefix at index 2. After ACK 2, single stepping took four Saves, [3], [4], [5], [6]. Batching took one Save, [3, 4, 5, 6]. Both produced individual ACKs 3 through 6. Term 1, leader 2, configuration index 1 and session generation 1 held throughout the appends. The revocation callback ran zero times. | +| Term change | The original comparison disabled revocation and manually reopened native admission. Its old peer returned gRPC OK during the term-2 HardState Save, invalidating that comparison. In the separate revocation test, the callback calls `Owner.SuspendGroup`. The original heartbeat receipt returned PermissionDenied while the Save was held and again after release. Both old-client probes failed. | +| Ordered apply | The prefix committed at index 2. In both schedules, proposal IDs 801, 800, 799 and 798 returned commit indexes 3, 4, 5 and 6. The results were success, write conflict, success and write conflict. The visible values were value-0, value-0, value-2 and value-2. Pebble's durable applied indexes were 3, 3, 5 and 5. | +| Reordered Fresh fields | A permutation of outer protobuf fields retained mutation order and decoded to an equal request. The classifier accepted the frame and preserved its original bytes. | + +The catch-up comparison counts entry-bearing Saves after ACK 2. Timeouts in +the tests detect a stalled fixture. With Go 1.27.4, all 17 selected KV tests +and 36 selected etcd engine tests passed in both the normal and race runs, +with zero skips, including the suffix-boundary table. Full-repository lint +reported zero issues. To repeat +the focused checks with the repository's linter configuration, run + +```sh +tests='Test(IsAppendBatchPayload|IsProposalTurnPayload|Protected(FreshAppend|AppendBatch|ProposalTurn))' +go test -count=1 -run "$tests" ./kv ./internal/raftengine/etcd +go test -race -count=1 -run "$tests" ./kv ./internal/raftengine/etcd +golangci-lint run ./kv ./internal/raftengine/etcd +go test ./kv -run '^$' -bench '^BenchmarkIsAppendBatchPayload$' -benchmem -benchtime=200ms -count=5 +``` + +The five-run classifier microbenchmark on an Apple M1 Max with Go 1.27.4 +produced the following medians. These measurements were collected on a busy +development host, not the dedicated three-voter performance cluster. The value +size is 1 KiB unless the row names the complete 128 KiB frame. The measured +time is classification cost, not an end-to-end latency or paired p99 ratio. + +| Frame | Median ns/op | Range ns/op | B/op | Allocs/op | +| --- | ---: | ---: | ---: | ---: | +| Fresh, 1 KiB value | 1495 | 1489-2311 | 2064 | 28 | +| Fresh, 128 KiB frame | 15278 | 15176-15442 | 132112 | 28 | +| Existing CAS, 1 KiB value | 721.4 | 709.5-729.3 | 1632 | 14 | +| Plain PUT fallback | 1382 | 1372-1394 | 1984 | 25 | +| Control fallback | 2.911 | 2.908-2.953 | 0 | 0 | +| Truncated fallback | 1196 | 1192-1666 | 1888 | 14 | + +## Follow-up validation design + +Keep the real admission-change callback wired to suspend the peer session. +For the catch-up comparison, hold an entry-bearing WAL Save in the same term, +leader, configuration and session generation. Use a separate-key Fresh prefix +entry, then queue the four original read-dependent entries while that Save is +held. After release, consume the prefix ACK and compare the subsequent Saves +through the last queued ACK. The old session must remain live because no +authority transition occurred, not because revocation was replaced or undone. + +Retain a separate term-changing Save test with that callback wired normally. +It must reject the old peer session while persistence is held and after release; +it must not reopen that session merely to make the workload proceed. Keep +proposal IDs distinct from log indexes through transport, WAL reopen, pending +result correlation and ordered apply assertions. + +Add explicit empty/reversed/maximum-index suffix boundary cases. Measure the +classifier's CPU and allocation cost for eligible small and maximum-size Fresh +frames, existing CAS, plain PUT fallback and control frames. These microbenchmarks +do not replace the original primary/hot adoption gate. Test a valid reordered +protobuf body and assert both decoded equivalence and unchanged original bytes. + +## Performance evidence still required + +The original R10 performance gate failed with 2,309 UNKNOWN outcomes in primary +and 684 in hot. The separate R11 primary diagnostic at 217/s recorded 83 +UNKNOWN outcomes. Reported maximum sync times were 19.4/9.5 ms on the leader +and 53.5/36.4 ms on n3. The n2 capture was incomplete. The original VMs and +keys were all deleted, with deletion verified at 13:53 UTC. + +The source gap establishes a way to reduce subsequent follower Saves after +work accumulates. The contribution to UNKNOWN outcomes, including those in +the hot cell, remains undetermined. Adoption requires a full original trial +on a fresh lease after integration, with the original calibration, workloads, +deadlines, thresholds and checkers. diff --git a/docs/design/2026_12_03_proposed_native_large_entry_compatibility_budget.md b/docs/design/2026_12_03_proposed_native_large_entry_compatibility_budget.md new file mode 100644 index 000000000..095b3ccbb --- /dev/null +++ b/docs/design/2026_12_03_proposed_native_large_entry_compatibility_budget.md @@ -0,0 +1,62 @@ +# Native Large-Entry Compatibility Budget + +## Evidence and Scope + +The synchronous inflight-window candidate a799 and its test-only CI follow-up +f82 both failed the new exact-64-MiB wire case. f82 already placed that case in +the existing isolated native CI step. Its 9-MiB calibration was acknowledged +on both voters; the target returned UNKNOWN about five seconds later. No +intervening election appears in that CI log. This is consistent with caller +deadline exhaustion, but the hidden cause and parent context were not recorded. +It is not proof that all UNKNOWNs have that cause or that isolation solved it. + +Local two-core runs overlapped the 9999-iteration WAL-heavy sequence and failed +with both the candidate and old zero-window setting. Some failures followed +elections. A profiled derivative showed substantial Pebble apply/write waits, +not a CPU-only diagnosis. After the other owned heavy test ended, the unchanged +two-core cases passed twice. All failed runs remain adverse evidence. + +R14 original adoption still FAILED; hot was NOT RUN. R15 is unallocated. +This proposal changes no production behavior and does not claim a hot fix or +performance acceptance. The separately tested refill bound remains a candidate. + +## Decision + +Separate legal-size compatibility from a five-second large-value response +guarantee that the feature design never promised. Only inside +TestSyncInflightMessageTargets, use a finite 30-second caller budget for values +larger than 8 MiB, matching the existing native large-value acceptance budget. +Keep the original five-second caller budget for its small following entry. + +Do not change Raft election/heartbeat settings, the transport timeout, any +per-operation receipt/native check, WAL sync, ordered apply or individual ACK. +All five-second catch-up and recovery waits remain unchanged. Normal held-Save, +revoked-ACK, term-transfer, no-fault and worker refill tests are unchanged. +No retry of an UNKNOWN mutation, synthetic ACK, scope reopening, payload +reduction, status reclassification, skipped test or weaker value assertion. + +The exact 64-MiB envelope, custom 16-MiB message target, actual two-voter Match, +three-store byte equality and following-entry progress must still pass. A +caller failure remains a failure even if a later read finds the value. Log +parent context/cause classification before canceling the test context when a +write fails; this is diagnostic evidence, never a new error projection. + +## Unchanged Adoption Gate + +The original cmd/casbench and internal/casbenchmark sources, one-second deadline +from scheduled arrival for 1-KiB operations, calibration, ten paired windows, +zero UNKNOWN rule, p99/goodput criteria, history/final-head/identity checks and +three independent verifier hashes remain unchanged. A 30-second compatibility +success cannot satisfy any of those gates, nor be described as passing the old +five-second maximum-value case. + +## Validation and Limits + +Review and commit this design before changing the test. Require normal/race +maximum/custom/following-entry runs, unchanged revocation/error regressions, +latest-push review and actual CI with explicit isolated-case success. Preserve +the previous failed CI and local profiles separately. If the new caller budget +does not pass, inspect recorded cause/owner timings; do not keep increasing +budgets or discard failures. A genuine revocation must still produce UNKNOWN +or refusal, not an old-generation success. Full original primary/hot adoption +remains mandatory and separately reported. diff --git a/docs/design/2026_12_03_proposed_owned_snapshot_durability.md b/docs/design/2026_12_03_proposed_owned_snapshot_durability.md new file mode 100644 index 000000000..4fccba09f --- /dev/null +++ b/docs/design/2026_12_03_proposed_owned_snapshot_durability.md @@ -0,0 +1,179 @@ +# Owned Local Snapshot Capture + +Status: Proposed +Author: bootjp +Date: 2026-12-03 + +The implementation and proof are on the pending CAS branch, not yet on main. +This status does not authorize performance adoption. + +## Decisions + +- Keep foreground durability and all external formats unchanged. +- Opt in only on the synchronous file-backed owner with explicit pin ownership. +- Treat failed Close as unconfirmed release and reject source replacement. +- Keep protocol proofs, executable recovery tests and performance gates separate. + +## Milestones + +- Implement owner capture and retirement, with a source-side lifetime guard. +- Check Lean-to-Go ordering and crash/reopen regressions, including NoSync mode. +- Complete fixed-criteria performance revalidation and retain unsuccessful runs. +- Pass reviews and CI on the final pushed HEAD before integration. + +## Scope + +The synchronous, file-backed Raft engine may use the optional +`raftengine.OwnerSnapshotCapturer` capability. KV forwards this to the optional +store capability and preserves its backup-pin and encryption-checkpoint gates. +Capture pins one immutable Pebble view and its SST table format at the current +applied boundary. Header, cutover, index and cloned ConfState are captured by +the serialized Raft owner. Metadata and raw rows are read from that same pin +later, on the existing snapshot worker. No capture-time filesystem copy, +checkpoint, forced WAL sync, scratch directory or SST materialization is needed. + +This does not enable asynchronous Raft storage or acknowledge writes earlier. +Public Snapshot, backed TSO, bootstrap/configuration snapshots and the async +storage pipeline retain their ordinary capture path. The existing SST/native +wire formats are unchanged. Native fallback is allowed before SST output, not +after a partially emitted bundle. + +## Ownership And Failure + +The engine retains one pending identity across channel dequeue. Under +`snapshotMu`, either the worker exports, closes and publishes, or received +restore retires and closes the old capture before touching the source DB. +A retired callback skips both export and publication even if restore failed +before MemoryStorage's snapshot index advanced. Shutdown stops admission, +joins the worker and drains buffered or otherwise pending captures. + +Close is attempted once for each raw handle. Failure is reported and fences +later capture/restore; it does not prove physical release. The Pebble store +also counts its owned pins under `dbMu` and rejects Restore/Close before any +source replacement if one remains. This guards callers that log an engine +Close error and proceed to store cleanup. Only a successful pin Close releases +that count; a repeated Close cannot release another handle's pin. + +The worker retains persistence errors before delivering its result. Shutdown +joins it and reports these errors even when the result was discarded on stop +or left unread in the result channel. A normal-close sentinel cannot hide a +file-sync or SaveSnap failure. + +Cross-process artifact ownership uses a stable lock under +`/.elastickv-store-locks/`, outside the DB directory +that restore renames. It spans open, restore and close. Recovery of a missing +live directory requires that lock; scratch cleanup additionally follows a +successful Pebble open and metadata validation. A duplicate open, including +one blocked by a raw Pebble owner, cannot sweep an active export. Lock inodes +are never unlinked while stores may be open. + +The service must be able to create this lock directory in the DB's parent, +or the operator must pre-create a writable lock directory for its service +identity. Merely having write permission inside the DB is no longer sufficient +when the sibling lock directory is absent. A shared parent needs appropriately +scoped lock-directory ownership; do not make it world-writable. This permission +requirement is an accepted operational change, not a replicated data format. + +Offline dedicated-TSO preparation permits creation of only its fixed empty, +regular sibling anchor and its container. It still traverses that container: +unknown names, nonempty anchors, symlinks and type substitutions are rejected. +An anchor present in the original backup cannot disappear on resume. Other +source paths remain immutable, including empty directories. Reference stores +used for full-image verification keep their locks inside their private temporary +tree. A physically empty control-store directory is an allowed interrupted +creation prefix; a populated store must pass the existing exact image check. + +One in-flight capture bounds handle count, not retained disk bytes. Concurrent +writes and export duration determine how much history a Pebble pin retains. +There is no promise that the first device-sync delay disappears. + +## Durability Order + +Foreground write success still follows durable Raft WAL, quorum commit and FSM +apply. Default FSM sync and the existing optional WAL-backed NoSync mode retain +their prior semantics. A later successful update may occur while an older +captured image is being exported; its log suffix must remain recoverable. + +The local publication sequence is unchanged: + +1. Write the captured payload and CRC to a temporary file. +2. Flush buffers, sync and close the file, rename it, then sync its directory. +3. Successfully close the source pin. +4. Force the FSM durable applied-index fence before saving Raft metadata. +5. Persist the Raft snapshot record identifying the complete file. +6. Create the MemoryStorage snapshot and compact its prefix. +7. Release WAL locks for that prefix, then attempt segment/file purging. + +The source fence synchronously commits `max(existing, requested)` even when +the visible index is already equal or ahead: that visibility may come from a +NoSync batch. It must not return success without a sync or rewind the index. +Disabled WAL and actual sync failure do not establish this fence. This can +add one real sync per snapshot where the old early-return path skipped it; +foreground writes retain their configured sync mode. + +Failure before publication does not authorize log reclamation. A crash before +the new Raft record is durable uses the old complete snapshot and retained WAL. +An ambiguous SaveSnap can leave either the old or new whole record, but each +must identify a complete matching file. The suffix needed after either selected +cut remains durable. A successful operation is represented by the replayed +logical state, not necessarily by an indefinitely retained historical raw row: +later deletes, overwrites and TTL transitions still have their normal meaning. + +## Lean And Implementation Mapping + +`lean/OwnedSnapshot.lean` proves invariants by induction over arbitrary finite +modeled interleavings, not by assuming the desired invariant at each step. + +| Model / theorem | Go boundary | +| --- | --- | +| `capture_is_one_cut`, `durable_export_is_original_capture` | `captureLocalSnapshotRequest`, KV `captureSnapshot`, Pebble `CaptureOwnerSnapshot` and owned `WriteTo` | +| `late_dequeue_skips`, `failed_restore_invalidates` | pending pointer identity under `snapshotMu`, retirement before `applyReadySnapshotLocked` invokes FSM restore | +| `no_second_close_attempt`, `shutdown_closes_each_pending_pin` | `closeLocalSnapshotLocked`, worker join and `drainLocalSnapshots`; store pin guard prevents premature source close | +| Write stages through directory sync | `writeFSMSnapshotPayload` and `writeFSMSnapshotFile` | +| bump, save, create, compact, release | `persistLocalSnapshotPayloadLocked`, `persistCapturedLocalSnapshot`, `publishLocalSnapshot`, disk-phase purge | +| `publication_requires_durable_pair`, `reclaim_requires_publication` | complete-file token and persisted record precede memory publication/log release | +| `local_crash_covers_all_acks` | synced WAL extent, ordered apply/ACK history, same-cut image and retained suffix for every successful update | + +The durability theorem assumes a valid initial replay prefix and deterministic +foreground application at each Raft index. For every local trace and crash +choice it proves a matching complete recovery file and, for each ACK, either +inclusion in that snapshot prefix or retention of the entire durable log suffix +needed to replay through the ACK's index. Received restore/rebase durability is +a separate protocol; the local theorem excludes DB-swap events rather than +silently assuming an arbitrary received image preserves local history. + +The model's cut index is the outer Raft capture boundary. It is not an assertion +that Pebble's stored data-applied metadata equals that boundary: non-data Raft +entries may advance the former boundary without a new data batch. The captured +metadata's presence/absence is preserved byte-for-byte in the existing format. + +Assumptions remain explicit: immutable Pebble pins, correct atomic FSM batches, +deterministic replay, truthful sync, atomic rename, whole-record Raft recovery, +mutex/join ordering, and correct WAL retention above its release floor. CRC32C +is not treated as a cryptographic proof. This is a logical protocol proof, not +machine extraction or verification of all Go, Pebble, OS, device failures, +distributed transaction semantics, liveness or latency. + +Negative controls exhibit premature WAL release losing ACK coverage, index-only +validation accepting a retired DB generation, shutdown without drain leaking a +pin, and mixing older metadata with later live rows. Lean 4.24.0 checks without +`sorry`, `admit`, custom axioms or native evaluation. The main invariants and +durability theorem use only Lean's reported `propext` and `Quot.sound`. + +## Validation And Adoption + +Regression tests exercise real Pebble views, restore failure before/after DB +replacement, both lock winners, shutdown drainage, close errors, encrypted V3 +retirement/adoption rows and metadata fidelity. Subprocess crash recovery uses +the real file writer and Raft WAL in sync and NoSync modes, reconstructing into +a fresh store so surviving source Pebble files cannot mask a missing WAL suffix. +The same cases also reopen the original store through the native skip path. +Crashable VFS tests discard unsynced bytes before reopening and verify that the +source fence preserves both the monotone index and its row. These are storage- +model tests, not physical power-cut experiments. Not every syscall crash prefix +or failed directory/file close is injected. + +Performance adoption remains separate. Prior failed campaigns are retained in +the host-benchmark evidence; neither this proof nor short diagnostics turn them +into passes. Revalidation uses fresh test identities on disposable hosts, the +same workloads, calibration, deadlines, retry policy and paired thresholds. diff --git a/docs/design/2026_12_03_proposed_owned_snapshot_scratch.md b/docs/design/2026_12_03_proposed_owned_snapshot_scratch.md new file mode 100644 index 000000000..81712d82d --- /dev/null +++ b/docs/design/2026_12_03_proposed_owned_snapshot_scratch.md @@ -0,0 +1,138 @@ +# Owned Snapshot Scratch Durability + +Status: proposed, performance adoption pending. Extends the owned local snapshot +design; it does not change the CAS workload or admission contract. + +## Evidence And Non-Claims + +R8 on c5a7a23880 failed both original performance gates. Primary independently +calibrated 248/s and froze 198/s. Pair03 Fresh recorded 4,018 UNKNOWN responses +and 4,024 deadline misses in 23,760 scheduled operations. The 15 complete windows +before that failure verify 213,839 ACK links; there is no complete-primary or +final-head claim. Hot calibrated 62/s and froze 49/s. Its 40 windows contain +zero UNKNOWN, miss or unsent operations, and 145,799 ACK links and the exact +final head/value verify. Nevertheless the ninth-order paired p99 upper bound +was 1.102134, above 1.05; goodput lower bound was 1.0. Correctness, reviews and +CI passing do not override either performance failure. + +R9 restarted the retained R8 data/WAL/identity with a separately hashed timing +overlay. It elected n2 rather than original n1 and is diagnostic, not an +adoption comparison. Two pairs at primary 198/s and hot 49/s had zero UNKNOWN. +The predeclared hot-overload 192/s cell stopped during its first warmup with +nine UNKNOWN responses. All nine sent their last attempt after consuming most +of the one-second deadline in the eight-worker queue. For example, one sent at +8958ms relative to the window with a scheduled deadline of 9026ms, then consumed +further attempts before its final write expired. No snapshot export overlapped +these UNKNOWN responses. This isolates queue/deadline exhaustion in this +over-capacity reproduction, not the cause of every R8 UNKNOWN. + +Separately, two leader snapshot workers lasted 4.483s and 3.854s, with owned +export spans of 2.786s and 2.939s. One sampled CPU interval attributed 1.27s to +the prewrite retained-WAL scan. Exported SSTs also use Pebble's file writable, +which flushes, synchronizes and closes every scratch file before hashing and +copying it into the final snapshot stream. Neither observation establishes how +much UNKNOWN or p99 latency a scratch-sync optimization will remove. The full +WAL scan and retained-snapshot validation remain unchanged in this proposal. + +## Scope + +The synchronous, file-backed Raft owner can capture an immutable store view +between entries and serialize it on its snapshot worker. Only this owned +export selects a transient scratch-file writable. Its terminal operation still +flushes and closes; it does not synchronize the scratch SST. The files remain +exclusive, locally readable work products until copied into the outer image. +No scratch path is ingested, renamed into a recovery root, transmitted as a +path, or selected by restart. Only bytes and a manifest are serialized. + +The constructor is passed privately through the shared SST builder and +exporter. Ordinary checkpoint export explicitly retains Pebble's syncing +writable. The constructor is not selected by filename, a global filesystem +override or a process flag. The SST layout, manifest/digests, compression, +rotation, native fallback and pin lifetime are unchanged. + +| Caller | Selection | +| --- | --- | +| Owned local file-backed synchronous-Raft SST export | Transient scratch writable | +| Ordinary `Snapshot` and checkpoint SST export | Original syncing writable | +| Asynchronous storage pipeline | Ordinary capture; no transient selection | +| Backed TSO | Existing control snapshot | +| In-memory or missing owner capability | Existing ordinary capture/fallback | +| Owned capture with SST disabled | Existing native stream | +| Snapshot receiver and `db.Ingest` | Receiver-owned files, existing syncs | + +Every changed builder/exporter caller must supply its intended constructor. +The engine and KV capture dispatch are independently tested; a future owner +capability caller requires the same durability audit. + +## Error And Authority Boundaries + +The private wrapper reuses the pinned Pebble buffering and terminal semantics. +It converts a short nil-error underlying write to `io.ErrShortWrite`, including +direct writes larger than the buffer. Finish attempts close even on flush +failure, preserves the first write/flush error, and returns a close-only error. +Abort closes without flushing. The exporter relinquishes its SST writer before +terminal close so a failed Finish followed by Abort cannot close it twice. + +A builder failure can use the existing native stream from the same immutable +pin, before the store payload begins. Once SST serialization starts, copy, +destination, size and input-close failures propagate with their byte count; +appending a fallback would corrupt the stream. Best-effort scratch-directory +removal is not the pin release. Failed pin close continues to fence restore, +store close and publication as before. + +Scratch completion is not an authority or durability receipt. There is no +positive authority cache, admission reuse, UNKNOWN-to-mismatch conversion or +change to native generation, session, per-operation capability, term/config +invalidation or receipt checks. WAL synchronization, FSM apply and successful +ACK retain their ordering. In particular this optimization cannot make an +operation with an expired scheduled deadline definitively fail after submission. + +## Durability And Proof Correspondence + +The authoritative outer sequence remains payload/footer flush, file sync, +close, rename, directory sync, successful pin close, durable source-index fence, +`SaveSnap`, memory publication/compaction, then WAL release and success purge. +Source fencing still synchronizes equal/ahead metadata that NoSync apply may +have made visible. Prewrite pruning and its WAL/CRC validation are untouched. + +Before outer directory sync, recovery relies on the previous WAL-selected +snapshot and the entire retained committed suffix. Scratch files and the outer +temporary file may disappear. After directory sync but before SaveSnap, an +orphan complete image does not select itself. During an ambiguous SaveSnap, +recovery may select the old whole record or the new whole record; the latter +already references a complete image. WAL release cannot precede publication. +ACKs issued while an older pin exports are covered by the full durable suffix +above the recovered cut, not merely by the ACK's own entry. + +Scratch create/write/flush/close/hash/copy/remove project to stuttering in the +existing durable-disk model. Successful serialization additionally requires +exclusive coherent reads of the complete same-pin bytes. Physical scratch +durability is not a premise; successful outer syncs, atomic rename, immutable +pins, whole WAL records, retained contiguous suffix and deterministic replay +remain explicit assumptions. A scratch refinement must lift to +`local_crash_covers_all_acks`, not replace the theorem with a weaker statement. +Lean proves this abstract protocol, not Go buffering, filesystem behavior or +the implementation of session revocation. Deterministic Go fault tests, +crashable VFS and subprocess recovery remain separate evidence; process exit +alone does not evict the host page cache or prove power-loss durability. + +## Validation And Adoption + +Require real owned multi-SST export/restore with zero physical scratch syncs +and ordinary positive-sync controls; SST-disabled, async, TSO and missing-owner +dispatch controls; short/zero-progress writes, buffered/direct errors, close +precedence, abort and real SST Finish failure; same-cut fallback and partial +output error tests. Keep the existing outer sync, pin-close, source fence, +SaveSnap/release, restore exclusion, shutdown drain, crash recovery and +native/session/receipt revocation regressions. An unsynced scratch-loss test +does not establish outer-directory persistence. + +Run focused race regressions, full Go tests/lint, pinned Lean, fresh Jepsen and +latest-pushed-HEAD normal/security review plus all actual CI. Then use fresh +VM disks and identities on the same physical placement and limits, without +timing overlays or profiles. Independently calibrate both original workloads, +freeze 80% of their own passing capacity, retain ten alternating 30s/120s pairs, +eight workers, 1KiB values, four attempts and the one-second scheduled deadline. +Keep zero UNKNOWN, <=1% miss/unsent, >=1000 successes, ninth-order p99 upper +<=0.90 primary / <=1.05 hot and second-order goodput lower >=0.95. Preserve every +failed prefix. No unchanged favorable rerun or diagnostic prefix is a pass. diff --git a/docs/design/2026_12_03_proposed_protected_proposal_turns.md b/docs/design/2026_12_03_proposed_protected_proposal_turns.md new file mode 100644 index 000000000..53f21552c --- /dev/null +++ b/docs/design/2026_12_03_proposed_protected_proposal_turns.md @@ -0,0 +1,160 @@ +# Protected Data Proposal Turns + +Status: Implemented candidate. Review and original performance acceptance pending. + +## Observed Failure + +The uninstrumented `f91082d4bd` acceptance run failed during primary pair 04's +fresh-control warmup: 294 unknown outcomes out of 7,470 scheduled operations +at 249/s. Four preceding complete pairs do not establish acceptance. The hot +decision cell was not reached. Normal and security reviews, CI and the +fault-injection Jepsen run passed that revision; those results do not override +the performance failure. + +A separately hashed diagnostic build retained that run's data and identity. +Restart elected n2 rather than n1. The driver rejected the initial leader +mismatch before workload execution. A gated leadership-transfer request was +also rejected. The diagnostic then used the actual n2 leader, without bypassing +admission. This different placement, fixed rates and profiling exclude the run +from adoption evidence. + +The diagnostic primary fresh arm recorded 277 unknown outcomes in 29,880 +scheduled operations; its preceding warmup had none. Its first unknown spent +963.16 ms queued before its first send. At that point the background snapshot +export was active on all voters. Leader WAL and FSM means rose from about +1.6/1.4 ms to 2.1/1.7 ms. Snapshot export took 5.27 seconds on the leader, but +the eventual source durability fence took only 4.22 ms. There was no single +five-second owner lock hold established by these measurements. + +The subsequent diagnostic hot fresh warmup recorded four unknowns in 5,760 +scheduled operations at 192/s. A real leader `fdatasync` took 272.86 ms; +Ready persistence, outstanding ReadIndex completion and new reader admission +overlapped that wait. Before it, the worker-queue p99 had already reached +834 ms. The first unknown waited 952.84 ms before its first attempt and then +performed four attempts within the original one-second logical deadline. + +All three diagnostic outbound-drop counters remained zero. WAL lock acquisition +was ordinarily sub-microsecond, so shared WAL mutex contention and outbound +drop amplification do not explain this reproduction. This does not disprove +their involvement in the earlier n1-led failure. The original large sampled +drop count was engine-wide, not a per-n2 counter. The retained diagnostic +traces, profiles and histories are separate from the original failed result. + +## Scheduling Change + +The synchronous owner currently services a proposal and drains Ready before +receiving the next proposal. Waiting independent writes therefore incur +separate Raft WAL synchronization opportunities even after one disk pause has +accumulated a backlog. A bounded data-proposal turn can amortize that subsequent +work. It cannot remove the first disk pause or guarantee a deadline. + +The proposed turn handles the first request immediately and takes additional +already-waiting requests only. There is no fill timer. The synchronous protected +leader must have stable term, leader and configuration, no pending membership +change or snapshot transition, and an explicit FSM classifier for known +data-only payloads. Unknown payloads keep the ordinary one-request path. + +Use at most 32 requests and 128 KiB of clear payload per turn. A single larger +valid proposal still runs by itself; the optimization does not impose a new +write-size limit. Ordinary 1PC puts and standalone CAS can be classified without +enabling batching for control, lease, policy, encryption, migration or unknown +future commands. The existing follower-append classifier is not broadened. + +Before receiving another proposal, check close, deferred work, priority and +ordinary Step queues, snapshot results and dispatch reports. Capture a ready +read, admin request or tick, including unbuffered rendezvous, for the next owner +turn after Ready. Recovery reads remain separate. A received non-data or +over-budget proposal is likewise retained as one deferred event and handled +singly after Ready, never requeued behind later senders. + +On leadership loss, an unissued deferred proposal receives `ErrNotLeader`, +not the ambiguous `ErrLeadershipLost` used for entries already issued. The +deferred slot is the evidence that `handleProposal` and `RawNode.Propose` have +not run for it. No issued write is reclassified as definitely uncommitted. + +## Safety Boundaries + +Each member calls the existing proposal handler separately with its original +context, payload, digest, ID, term/configuration fences and `WithNative` scope. +One caller's authority is never reused for another. Cancellation or revocation +between members must reject the affected member without authorizing it from an +earlier check. No positive capability result is cached across operations. + +Each successful native issue remains one original Raft entry with its own +index and pending result. This is not a transaction merge or a store batch. +The unchanged Ready path persists entries and HardState before dispatch, +applies committed entries in order, performs required synchronous FSM writes, +and only then publishes each result. The original Ready is passed to Advance. +The optimization creates no follower ACK, successful client response or +definitive mismatch. An ambiguous submitted operation remains unknown. + +Proposal-turn scheduling is not enabled for the asynchronous storage pipeline +or unprotected engine. +Snapshot pin ownership, source durability fences, restore/shutdown joins and +peer-session receipt checks retain their existing behavior. + +### Cancellation Registration + +A separate deterministic test reproduced the pre-existing race between caller +cancellation and pending-proposal insertion. The caller can complete cleanup +while the owner is waiting for the engine state lock, before pending insertion. +The shared registration helper now rechecks cancellation under the pending-map +lock and reports whether it registered the waiter. A refused registration ends +`handleProposal` before `RawNode.Propose`; it cannot leave a new pending waiter. +If registration wins first, caller cleanup removes it under that same lock. +Cancellation after issue still does not prove that a write failed. + +This small shared fix also applies to the pipeline's existing single-proposal +handler. Its caller-owned proposal permit is released by the unchanged caller +return path; no new unstable work is created on refused registration. The +registration helper's production caller, pipeline wrapper and direct test +callers were audited. Tests retain the no-input-payload retention and original +ID/digest receipt-matching contracts. + +## Formal Mapping + +`lean/ProposalTurns.lean` is checked with Lean 4.24.0 and warnings as errors. + +| Go boundary | Model and theorem | +| --- | --- | +| Separate `handleProposal` / `WithNative` per member | `independent_issue`, `earlier_acceptance_cannot_issue_denied_member` | +| Change only the partition of native issues before Ready | `partition_preserves_entries`, for identical per-invocation observations | +| Nonblocking polls, count and byte limits | `extras_bounds`, `turn_bounds` | +| Actual grouped WAL completion, then commit/apply/publication | `grouped_wal_covers`, `step_safe`, `reachable_safe`, `two_members_one_save` | +| Original pending receipt and current result validation | `success_requires_original_durable_prefix`, `denied_cannot_consume` | + +The model does not assume that different schedules observe identical authority. +It proves partition equivalence only for fixed per-member observations. Context +and digest are provenance in the model, not additional Raft-envelope fields. +The successful-return boundary requires the original slot, durable WAL prefix, +completed synchronous FSM work, published result and current validation. A +later revocation prevents a new consumption; it does not withdraw an earlier +valid response. + +The proof assumes a stable Raft history, faithful polling and payload +classification, correct admission and quorum evidence, immutable bytes, +correct hashes and waiter matching, and truthful WAL/FSM synchronization. +There are no custom axioms or admitted proofs. Go races, concrete pending-map +locking, peer transport, device durability, scheduling and performance require +the separate runtime tests; they do not follow from this abstract model. + +## Verification And Adoption + +Require a deterministic regression demonstrating fewer Ready/WAL boundaries +for independently admitted waiting data proposals, without completing any +caller before required persistence and application. Test independent revocation, +denial and cancellation; original payload/index matching; count/byte bounds; +control and oversize fallback; close, recovery, priority and unbuffered events; +role, term and configuration transitions; and unchanged async/legacy behavior. + +Audit all callers of any altered handler or classifier. Formal statements must +model independent authorization, ordered issue, durable-prefix coverage and +result validation explicitly; they do not establish Go synchronization, +storage-device behavior, liveness or latency by themselves. + +After implementation, require signed commits, latest-HEAD normal and security +review, CI and durability regressions. Re-run the original independently +calibrated primary and hot cells on fresh identities, ten alternating matched +pairs, unchanged workload, one-second scheduled deadline and numeric gates. +Do not select a favorable repeat of an unchanged failed candidate. Every failure +remains a failure, and diagnostic-only runs never establish adoption. diff --git a/docs/design/2026_12_03_proposed_revocation_safe_read_cohorts.md b/docs/design/2026_12_03_proposed_revocation_safe_read_cohorts.md new file mode 100644 index 000000000..b436d44e0 --- /dev/null +++ b/docs/design/2026_12_03_proposed_revocation_safe_read_cohorts.md @@ -0,0 +1,68 @@ +# Protected ReadIndex dispatch and revocation + +Implementation candidate, 2026-12-03 ยท bootjp ยท Performance acceptance pending + +The synchronous protected owner can issue up to 32 independent reads before draining Ready. When one Ready contains only compatible read heartbeats, dispatch sends the last original heartbeat to each destination. Two identifiers explain why this works. The application's `RequestCtx` identifies one caller's result. Raft's heartbeat context identifies how far a voter has acknowledged the ordered sequence of issued reads. + +## Issue and completion + +In `read_index_batch.go`, the owner handles the first ordinary request immediately and receives additional waiting callers without a fill delay. This includes senders waiting on an unbuffered channel. Before taking another request, it checks close, pending events, priority Step queues and other queued work. It can capture a ready tick or admin request for the event loop. A recovery read received during the turn is deferred for separate handling with its own role and operation checks. These checks occur between calls and the turn has a hard count bound. + +Each ordinary caller goes through `handleRead` with its own context, role/admission check, pending ID, and `WithNative` scope. Inside that scope, `Check` authorizes the original operation through `RawNode.ReadIndex(encodeReadContext(req.id))`. A later arrival can join the owner turn because its own issue creates a fresh position when Raft adds it to the safe-read queue. There is no membership to seal. The unprotected branch in the same file has different semantics and can issue one ReadIndex for a pre-registered batch. + +On completion, `recordReadIndex` matches the original request ID. A synchronous VerifyLeader waiter can receive its index immediately. A waiter requesting local application retains that target until the applied index reaches it. `submitReadRequest` runs `ValidateResult` with the original caller's context before returning success. Revoking a caller after issue can therefore suppress its success even when Raft publishes its ReadState. A different caller with independent authority still needs its own matching result. + +### Cancellation and pipeline ownership + +The caller can finish cancellation after the owner's initial context check and before pending-map insertion. `storePendingRead` samples the context again under the same lock that `cancelPendingRead` uses for removal. If cleanup acquired the lock first, registration observes cancellation. If insertion acquired it first, cleanup can remove the entry. A rejected registration stops native issue. + +The storage pipeline has separate ownership. `admitPipelineRead` installs a control permit before registration. If registration fails, it deletes the ownership record, releases the permit and returns before ReadIndex. Once issued, caller cancellation alone cannot release the reservation for work still retained by RawNode. The pipeline tracks ReadState publication, native reset and disposal, including separate accounting for pre-current-term-commit work. Its result path also waits for local application. + +The pipeline ReadState path updates the target of an existing waiter under one pending-map lock in `recordPipelineReadIndex`. It does not register a missing waiter again or send a second registration error. Cancellation that removes the waiter first cannot be undone by the result update. The registration proof below covers the initial insert/cleanup race; permit retirement remains subject to actual ReadState/reset/disposal ownership. + +## Ready-local dispatch rule + +In `drainReady` and `applyAndDispatchReady`, protected dispatch follows persistence, committed-entry application, status refresh and successful admission reconciliation. In `sendReadyMessages`, the candidate requires native admission, the protected admission-change hook, a synchronous engine with a live RawNode, current leader role and local leader ID, and clear pending-configuration and snapshot-transition checks. + +1. Inspect one Ready. Require at least two messages, nil SoftState, empty HardState and Snapshot under the pinned Raft predicates, empty Entries, CommittedEntries and ReadStates, and false MustSync. +2. Require **every** message to be a pure, explicitly typed MsgHeartbeat from the current leader in its current term. Require an explicit destination and commit. Exclude zero, self and Raft's local append/apply destinations. The context is exactly eight bytes encoding a positive little-endian ordinal. Reject additional populated fields, including explicitly set optional scalars, nested messages and unknown protobuf data. +3. For each destination require identical commit values and nondecreasing ordinals in original order. If any check fails anywhere, dispatch the entire original sequence. Otherwise retain the **last original pointer** per destination and traverse the original sequence to preserve the relative order of the retained messages. If there is nothing to omit, use the original view. +4. Only the outbound view changes. Persistence, ReadStates and Advance retain the original Ready. The selection has no state across Readies, terms or runtime instances. Intentional omission generates neither an acknowledgement nor an unreachable report. + +## Why a later response can cover an earlier read + +This argument depends on the `go.mod` pin to `go.etcd.io/raft/v3 v3.7.0` and the engine's `ReadOnlySafe` setting. In the pinned `raft.go` and `read_only.go`, the multi-voter leader appends the original request with the committed index at entry into `readOnly`, records its self-vote and broadcasts the latest outstanding ordinal. A follower applies the bounded heartbeat commit and echoes the context. The leader takes the maximum echoed ordinal per responding voter. `quorum.MajorityConfig.CommittedIndex` selects the majority frontier. `JointConfig.CommittedIndex` takes the lower frontier of its two halves, with an empty outgoing half imposing no constraint. + +For example, suppose reads A and B occupy positions 6 and 7. Once a voter actually acknowledges 7, an additional ack of 6 from that voter leaves its maximum unchanged. When enough voters cover 7, `maybeAdvance` releases both original requests in order. `responseToReadIndexReq` emits each local ReadState with its own RequestCtx and stored index. A read issued at position 8 still needs quorum coverage through 8. A learner or duplicate vote cannot supply a missing voter majority. + +Each surviving payload goes through its own current peer-session Invoke. Inbound Step checks the receipt at enqueue and uses its generation and admission guard at native Step. The heartbeat response must itself reach the leader through the protected path. Losing a transport session generation can deny a send or Step. It does not itself reset Raft's `readOnly` queue or previously accepted votes. A later properly admitted response can cover outstanding positions in that same queue. Omitting an earlier packet grants neither its caller nor a later caller native authority. Borrowing the first caller's action for another read would skip that other caller's issue and binding checks. + +The baseline transport already permits packet loss. Withholding an earlier probe can delay completion if the retained probe or its response is lost. On a heartbeat tick, `MsgBeat` broadcasts `readOnly.heartbeatCtx()` again while reads are pending, even with no new issues. Progress depends on ticks, a stable eligible leader and reachable, admitted responses from a quorum. Safety alone gives no timing or progress bound. + +## Formal and test evidence + +`lean/ReadCohorts.lean` models a fixed readOnly instance with an append-only logical issue history, one maximum per voter, and separate issue, quorum publication and result consumption relations. Lean 4.24.0 checked the file with `lean -DwarningAsError=true lean/ReadCohorts.lean`. + +| Claim | Checked theorem | +| --- | --- | +| Dropping a delivered ack cannot create a publishable result. After a dominating response from the same voter, both histories publish exactly the same slots and results, even with intervening responses. | `omissionCannotCreateResult`, `omitDominated`, `sameAcceptedPrefix` | +| Coverage extends to lower ordinals. A missing majority in either required half blocks publication. An old vote map bounded by the preceding history cannot cover a freshly issued slot. | `coveredPrefix`, `missingQuorum`, `lateIssueCannotUseOldPrefix` | +| An authorized issue appends its own request and index. Publication preserves both fields. A different request ID cannot use that result. | `issueAppendsOwnRead`, `issuedResultKeepsContextAndIndex`, `otherCallerCannotUseResult` | +| Revocation blocks use under the affected binding and preserves eligibility under a distinct live binding. Applied reads must reach their own issue-time index. | `revokedCannotConsume`, `independentCanStillConsume`, `appliedReadReachedOwnIndex` | +| Either lock order leaves the individual slot empty after cancellation cleanup and registration have both finished. | `noOrphanAtRegistration` | + +The model assumes valid, unique request IDs, nonwrapping ordinals, authentic votes for issued positions, distinct voter IDs per configuration half, and continuity of leader, term, configuration and readOnly instance. It relies on the pinned quorum implementation, truthful binding of handles and receipts to operations, current session authority at message use, and faithful Go mapping of issue, delivery, result validation, context cancellation and lock order. It abstracts over network bytes, scheduling, reset, storage and concrete synchronization. Neither liveness nor performance follows from these theorems. + +Go test sources inspected include `TestReadProbeCoalesceCallerResults` (real follower echo, separate caller validation, late issue and local apply), `TestReadProbeCoalesceJointQuorum` (learner, duplicate ack and each missing half), and `TestReadProbeCoalesceTickRetry` (drop the retained probes, issue no new reads, tick and deliver a retry). The dispatch-view and fallback tests check pointers, order, changed commit, regressing ordinal and malformed Ready shapes. The owner-turn tests cover the bound, priority Step, recovery, close and cancellation before registration. These are source checks in this task. The parent is running the Go tests. The tick fixture exercises a specific loss/retry schedule; broader fair-tick, reachable-quorum liveness needs execution evidence. + +## Performance decision + +The anonymous hot control used 192 scheduled operations/s, a one-second deadline from schedule, up to four attempts and eight workers. Pair 00 recorded zero unknowns and deadline misses. Pair 01 recorded **648 unknowns and 1,580 deadline misses**. The first unknown spent about 842 ms in the worker queue. Pair 00 also recorded more aggregate Status calls than pair 01. The diagnostic fresh control in pair 02, under the same settings, recorded **1,392 unknowns and 3,042 deadline misses**. + +The diagnostic's first unknown waited 917.47 ms before its first send. Each of eight worker-local FIFOs receives 24 scheduled operations/s, leaving a sustained service budget of 41.67 ms per operation. An operation may execute four Fresh calls, three refresh reads and three backoffs. Ordinary phase averages therefore cannot be compared directly with the one-second logical-operation deadline. + +In the five-second bins before and during the first unknown, the slow follower repeatedly spent about 163 ms in WAL persistence. The leader's aggregate outbound queue reached seconds of delay and recorded drops before client queueing reached the deadline. Leader read-quorum averages subsequently rose from about 2.4 ms to as much as 11.2 ms; its own WAL and FSM averages remained about 0.4 ms and 0.3 ms. The later four-second follower WAL stall and snapshot exports cannot explain the earlier onset by themselves. Dispatch workers are per destination: a slow follower has no direct FIFO dependency on the healthy follower. Shared owner/receipt work and all-member capability checks must be distinguished from that indirect coupling. + +These observations support a backlog and retry-amplification hypothesis, not proof that the selected optimization alone removes the failure. The candidate reduces redundant transport only where several original probes coexist in an eligible Ready. Mostly singleton or mixed Readys would limit its benefit. Diagnostic timing and profiling perturb queueing, and three pairs are not acceptance evidence. The performance outcome remains pending under the original independent calibration, ten matched pairs, rate, deadlines and thresholds. + +The proposed fast path for sharing or caching Status capability rounds is deferred. A shared positive observation can precede another caller's arrival or survive a remote revocation at the same Raft term and configuration. Reusing it with a current-at-use guarantee would require a new distributed revocation fence. This candidate keeps capability checks and native scopes individual. diff --git a/docs/design/2026_12_03_proposed_sync_raft_inflight_byte_window.md b/docs/design/2026_12_03_proposed_sync_raft_inflight_byte_window.md new file mode 100644 index 000000000..85af3f6eb --- /dev/null +++ b/docs/design/2026_12_03_proposed_sync_raft_inflight_byte_window.md @@ -0,0 +1,95 @@ +# Synchronous Raft Inflight Byte Window + +## Status and Evidence + +Proposed additional design following the failed R14 acceptance run. The run +calibrated Fresh at 248/s passing and 256/s failing, then froze 198/s. Three +comparison pairs had no UNKNOWN. Pair 03 Fresh recorded 22362 successes, +1397 UNKNOWN, 1401 deadline misses, zero unsent and p99 925.6 ms. Its 30-second +all-voter drain failed; hot was not run. The complete prefix is retained as +failed evidence. No adoption retry or relaxed deadline is authorized by this +proposal. No claim is made that every prior hot failure has been explained. + +Anonymous window counters show about 1 GB received by the lagging follower +versus about 33 MB by the other follower. All three processes later recovered +at the same term/configuration and converged indexes. These totals do not +measure queue occupancy, identify the first disk pause or prove duplicate +ranges. Passive post-failure profiles are derivative diagnostics, not original +acceptance profiles or a performance pass. + +Source inspection identifies a separate bounded-work gap: synchronous RawNodes +set a 1024-message inflight count and a 1 MiB message target, but leave upstream +MaxInflightBytes at zero (unlimited). One advancing AppResp can refill a lagging +peer's window within RawNode.Step. Protected Step holds the current arbiter and +peer-receipt scopes across that call. Ready cloning follows on the same owner. +Per-destination transport workers do not prevent this shared-owner work from +delaying another peer's genuine ACK. The asynchronous path already configures +its own byte window and budgets; it is not changed here. + +## Decisions + +1. Set per-peer MaxInflightBytes to max(8 MiB, effective MaxSizePerMsg) on + synchronous RawNodes using + the upstream Raft facility, without changing the existing message count, + message target, ingress capacities or dispatch lanes. This is an initial + conservative owner-work budget, not a value inferred from cumulative traffic. + Normal runtime message targets remain 1 MiB, giving an 8 MiB window. Raising + a custom finite message target raises this floor: upstream rejects a byte + window smaller than its message target even before replication starts. + Do not change the asynchronous + path's existing 128 MiB window or its storage/dispatch budgets. +2. This bounds an inflight refill opportunity, not all retained bytes. Upstream + checks fullness before adding a message, so allow one legal-message overshoot. + A legal single entry larger than the target/window must still make progress. + Explicit custom message targets affect the window and overshoot; an explicit + unlimited message target remains outside the bounded-default claim. Preserve + those opening semantics. Do not claim a universal + 8 MiB message or heap limit or introduce a new RawKV value-size limit. +3. Keep each original message, receipt/native check, FIFO, failure feedback, + WAL sync, individual ordered apply and ACK. Never drop previously accepted + data, synthesize an ACK, share a positive authority observation, or reopen an + expired scope. Quorum and read semantics do not change. +4. Do not treat this as a hard dispatch-queue memory bound across Probe resets + or active/queued copies. If a lagging peer still monopolizes dispatch-owned + bytes, a separate pre-clone aggregate/per-peer/control reservation design is + required, with accounting through final release and liveness under refusal. +5. Preserve all-member capability queries and their per-caller freshness. This + proposal neither shares/caches their observations nor removes native scope + serialization. Distinguish that path from the independent A+C quorum path. + +## Red-Capable Validation Before Adoption + +Use real synchronous protected engines/RawNodes, current receipts from normal +peer reconciliation, normal gRPC ingress and production dispatch workers. +Use real WALs and coordinator-produced Fresh frames for end-to-end progress. +Do not insert/dequeue production channels by hand, edit Match/Next, fabricate +ACKs, or bypass revocation to obtain a passing queue count. + +- Separate matched no-fault, lagging-follower Save-held and response-transport- + held schedules. No ACK may escape the held Save. Test the independent healthy + quorum's commit/read progress separately from Fresh capability admission. +- Accumulate a suffix larger than the byte window plus one message through the + healthy quorum. Use a genuine pre-delivery Append failure to enter Probe, + then release a genuine lagging-peer response while a genuine healthy ACK is + pending. Count emitted and pre-clone bytes in one owner turn and the event + order before the healthy ACK advances. The old configuration must exceed the + proposed bound in a behavioral RED; compile failure is not evidence. +- Require the candidate bound, healthy quorum progress, FIFO accepted delivery + and eventual lagging-peer catch-up. If only byte counts improve but the + healthy peer still waits, do not claim that the interference is resolved. +- Exercise partial ACK, already-covered delayed failure, genuine missing suffix, + receipt revocation between queue and Step, term change during held Save, + pre/post-write Save errors, maximum legal entry and shutdown. Stale receipts + cannot advance Match; failed Saves emit no ACK; reservations must retire. +- A synchronous configuration with a 16 MiB message target must still open and + replicate. Separately, with the default 1 MiB target, a legal single entry + larger than the 8 MiB window must be acknowledged and permit the following + entry to commit. Check asynchronous configuration remains unchanged. +- Audit every RawNode factory/configuration caller and affected tests. Run normal + and race regressions, five separate review lenses, latest-HEAD review, all CI, + unchanged CAS/ZSet stress and the original primary/hot acceptance criteria. + +The production patch may proceed only after design review. If the fixture cannot +reproduce the refill mechanism, or diagnostics identify a different first wait, +record that limitation and revise the design instead of manufacturing an ACK +schedule or presenting a finite counter as a performance result. diff --git a/docs/evidence/2026_11_20_single_key_mvcc_cas_review.md b/docs/evidence/2026_11_20_single_key_mvcc_cas_review.md new file mode 100644 index 000000000..cb040984c --- /dev/null +++ b/docs/evidence/2026_11_20_single_key_mvcc_cas_review.md @@ -0,0 +1,279 @@ +# Independent review of single-key MVCC CAS + +Latest checkpoint (2026-12-02): the three-host primary campaign completed and +its 336,000 acknowledged updates and final heads were independently verified, +but its upper paired p99 ratio failed the predeclared threshold. The hot-key +campaign stopped on unknown writes in its first CAS warmup and has no accepted +decision result. The feature remains disabled and the PR remains draft. All +four temporary VMs, their disks, watchdog and private credentials were removed. +See the [measurement record](2026_12_02_single_key_mvcc_cas_host_benchmark.md) +for source/build hashes, all paired primary latencies, failed-run limitations +and teardown receipts. Historical reviews below are revision-specific, not +approval of a later HEAD. + +**Verdict (2026-11-20). Revise before using the benchmark for an adoption decision.** An independent read-only review traced the proposal against ElasticKV at `6943eff8ab66143ad023629dd238906eddd5a989`. The reviewed document has SHA-256 `b1dbd055013b4858201ebbd2a810d9c1b0ca4b33bdb1885daa9846279a35fe35`. References to proposal lines use that revision. The counts below are predictions from source inspection. [Reviewed design](../design/2026_11_20_proposed_single_key_mvcc_cas.md) + +## Correctness findings + +1. **High ยท Lines 44, 58 and 79. Specify which writers make the 1PC control equivalent.** Consider a read of A@5 at snapshot 20 followed by a delayed RawPut of B@15. OCC checks for a write newer than 20 and can pass. Exact CAS for version 5 must reject. The raw path has a regression test for a write landing below an observed watermark before fence activation. Use fenced 1PC writers for the equivalence experiment. Test active and inactive fences, same-timestamp replay versus replacement, and mixed raw/transactional writers separately. [Fence activation tests](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/commit_ts_fence_test.go#L47) ยท [OCC predicate](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/store/mvcc_store.go#L852) +2. **High ยท Lines 37, 42โ€“43 and 67โ€“73. Give token mismatch its own verdict.** A writer allocated timestamp 30 can arrive after an unrelated write at 31. The group timestamp fence can reject that attempt even if the target still has the expected version. Carry the precise predicate result over forwarding. Record token mismatches, timestamp-order rejections, locks, routing errors and unknown outcomes separately. Only a proven non-effect is eligible for retry, retaining the original token and deadline. [Commit timestamp fence](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/store/lsm_store.go#L2591) ยท [Forwarded failure classification](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/adapter/internal.go#L303) +3. **High ยท Lines 42โ€“43 and 79. Specify the atomic boundary for migration side effects.** The current 1PC path records migration progress before fenced store apply. Inserting the CAS predicate only in store apply could advance the migration tracker on a mismatch. Stage the tracker and user change behind the same verdict. With tracking active, reject a stale token and check the tracker, stored version, notifications and replay. [1PC apply ordering](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/fsm.go#L2260) ยท [Tracker write](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/fsm_migration_readiness.go#L161) + +## RPCs, Raft proposals and contention + +- **Confirmed ยท Lines 48โ€“56.** On the specified successful, leader-local, single-group, unbatched path, 1PC submits one data command and apply-only CAS is designed to submit one. Reducing two external calls to one applies to the benchmark frontend that performs a fresh read before submitting. The single-handler control already uses one external call. A fenced pre-read can reject stale input before proposing, while apply-only CAS consumes a proposal. [1PC dispatch](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/sharded_coordinator.go#L2156) ยท [Actual proposer call](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/transaction.go#L167) +- **Medium ยท Lines 48โ€“66. Include the retained-snapshot control.** A caller retaining a validated transaction snapshot can submit an OCC write directly. Measure fresh-read and retained-snapshot callers independently. Charge handle acquisition, pinning, expiry and release. The current public Get releases its read scope on return, so this comparison requires a benchmark frontend. With an allocate-on-zero start timestamp the sharded coordinator can also probe the target's latest version. Count the public Get, internal reads and forwards, timestamp allocations, read fences and storage probes separately. Isolate lock resolution and add a follower-connected case before claiming remote-read savings. [Get lifetime](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/adapter/grpc.go#L836) ยท [Sharded start timestamp](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/sharded_coordinator.go#L2643) ยท [Remote version probe](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/shard_store.go#L4954) +- **Medium ยท Lines 67โ€“73 and 79. Instrument the race and distinguish batching layers.** Transactional requests reach the proposer individually at this revision. The existing shared-entry batcher handles raw requests. Record submissions, proposals, committed entries and persistence flushes independently. Releasing clients together does not force all prechecks to finish before the first apply. Count survivors at each stage, or use a barrier after precheck in the controlled race. Exclude round setup and resets from all counters. [Transactional dispatch](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/transaction.go#L225) ยท [FSM batch eligibility](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/fsm.go#L499) +- **Adoption criterion ยท Lines 66โ€“73. Define a reproducible primary workload.** Fix the worker count, token acquisition and refresh policy, saturation calibration, offered arrival rate, deadline and latency population before candidate runs. Fast mismatches can lower pooled p99 even as fewer useful writes complete. Gate successful-update p99 and successful throughput in the primary workload, count every scheduled request, and bound deadline misses and unknown outcomes. Keep the stale-token sweep and separate per-attempt and per-success denominators, including the zero-success case. + +The following isolation assessment addresses the follow-up question alongside the independent review. + +## Scope of the isolation guarantee + +TiKV's optional commit timestamp on transactional reads is compatible with ElasticKV's snapshot isolation and optimistic validation. The timestamp identifies the observed version of one key. A transaction's original snapshot timestamp and the complete set of keys on which its decision depended have different roles. Either byte equality or version equality can be an additional predicate inside that transaction. + +Use a two-key write-skew history as a correctness control. Start with A and B both on. Two clients read both at the same snapshot. One turns A off if B is on, and the other turns B off if A is on. Independent CAS operations on A and B can both succeed. With both point keys in each transaction's read set and validation atomic with commit, the second committer must encounter a conflict. Run a same-shard case first. A read dependency on another shard selects the existing multi-shard path and must use its own RPC/proposal budget. A range predicate also needs coverage for matching keys inserted after the read. Listing only the keys returned by a scan cannot detect that phantom. [Read-set format](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/proto/internal.proto#L65) ยท [Read-only shard routing](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/kv/sharded_coordinator.go#L1855) ยท [Point-key conflict check](https://github.com/bootjp/elastickv/blob/6943eff8ab66143ad023629dd238906eddd5a989/store/mvcc_store.go#L852) + +## Independent re-review, 2026-11-21 + +The reviewer checked the revised proposal (SHA-256 `0d22e2f6eb56be25c75c4eef754d2dd1ed3cbb0e9609b3c6095e9a24a4cb8f56`) against source revision `9d2ed17d0` and approved starting implementation. The two-call baseline saves one external RPC. The single-handler and retained-snapshot controls already use one RPC and one data-group proposal. The fenced, non-expiring 1PC fixture and the separate mixed-writer test address the delayed-write counterexample. + +The review also checked the explicit predicate verdict, the transaction boundary around migration tracking and replacement, and the successful-update latency and throughput criteria. Two clarifications were incorporated. A mismatching entry must explicitly persist its applied index, because an untouched Pebble batch skips commit. Injected staleness is a workload input; the measured outcome comes from the returned verdict. A timestamp rejection on a stale-token request belongs in the timestamp bucket. The clarified proposal has SHA-256 `f6a5ba0b3286c536f0cef5856fd92543e01b41c2a34d68437c230500f2b36899`. + +This verdict covers the design. Rollout depends on implementation verification and the predeclared performance criteria. + +## Local contention counters, 2026-11-21 + +The fixture ran ten iterations per cell on Darwin/arm64 (Apple M1 Max) with one etcd/Raft voter, synchronous Pebble and three Go scheduler threads. Setup, token acquisition for the known-token cell, and activation are outside the measured window. The fixture intercepts actual client RPCs and data proposals. Its local admission hook omits the production peer capability fan-out. The hot-key cells used three correctness rounds plus ten separate measured rounds of eight synchronized attempts. The host was shared, so these measurements establish operation counts only. The separate Linux performance decision still requires three hosts. + +| Input | Arm | RPCs per attempt | Data proposals per attempt | Successful attempts | +| --- | --- | ---: | ---: | ---: | +| Known token | Apply-only CAS | 1 | 1 | 100.0% | +| Known token | Single-handler 1PC | 1 | 1 | 100.0% | +| Known token | Two-call 1PC | 2 | 1 | 100.0% | +| Known token | Retained-snapshot 1PC | 1 | 1 | 100.0% | +| 100% stale | Apply-only CAS | 1 | 1 | 0.0% | +| 100% stale | Single-handler 1PC | 1 | 0 | 0.0% | +| 100% stale | Two-call 1PC | 1 | 0 | 0.0% | +| 100% stale | Retained-snapshot 1PC | 1 | 1 | 0.0% | +| Eight contenders | Apply-only CAS | 1 | 1 | 12.5% | +| Eight contenders | Single-handler 1PC | 1 | 0.2375 | 12.5% | +| Eight contenders | Two-call 1PC | 1.975 | 0.975 | 12.5% | +| Eight contenders | Retained-snapshot 1PC | 1 | 1 | 12.5% | + +Every contended round produced one winner. The fixture checked successful versions and values against exported MVCC history. When all supplied tokens were stale, apply-only CAS made one proposal for each definitive mismatch. Both fresh-read 1PC variants rejected those tokens before proposing. The retained-snapshot control had already completed its precheck and submitted one proposal per attempt. The benchmark guide includes the exact invocation and the acquisition-inclusive variant. [Local benchmark guide](../design/2026_11_21_single_key_mvcc_cas_local_benchmark.md) + +## Implementation review and corrections + +The first implementation review identified a follower fixture that rejected requests before forwarding, loss of an indexed lock verdict, gaps in recovery and encrypted-read coverage, and repeated work on ordinary reads and writes. The follow-up review verified the dedicated forwarding path, including one unsupported-method response from a legacy leader and zero calls to generic forwarding. It also verified that indexed lock rejections return `Aborted/CAS_LOCKED`, lost replies remain indeterminate, and exact version mismatches have a distinct response. A protected three-voter TLS test exercised follower ingress. + +The recovery test submits an encoded CAS, injects a failure after staging, reopens Pebble, verifies the original value and applied index, then retries the entry and replays it. The follower read test reads an encrypted value immediately before expiry and sees it missing at expiry. A separate two-key test allows both standalone CAS operations to succeed and requires a transaction declaring both point reads to reject the second writer. + +A further independent review verified the ordinary-path changes and identified a malformed in-process follower batch that could dereference a nil request. Forwarding now rejects any nil request before assigning a forwarding ID. A regression test exercises nil requests at both ends of a CAS batch and a singleton nil request. + +## Ordinary-path measurements + +Three interleaved 150 ms samples compared the candidate with `9d2ed17d08c12e0ff6e977f7c07708cc48cac3ca` on the shared Apple M1 Max host with Go 1.27.3 and `GOMAXPROCS=2`. The table reports medians and the full observed range. Reads use a hot 1 KiB value. Adapter calls exclude network and serialization. The 1PC fixture measures local verification, transaction encoding and a counted proposer call. Replication, FSM apply, and storage I/O are outside the write measurement. + +| Operation | Base ns/op (range) | Candidate ns/op (range) | Allocations/op, both | +| --- | ---: | ---: | ---: | +| Ordinary 1PC, 1 mutation | 940 (754โ€“1,058) | 1,012 (804โ€“1,242) | 10 | +| Ordinary 1PC, 64 mutations | 6,749 (6,701โ€“7,233) | 7,575 (5,139โ€“11,223) | 10 | +| Pebble GetAt | 1,766 (1,331โ€“1,988) | 1,455 (1,192โ€“2,743) | 4 | +| Memory Get | 1,922 (1,455โ€“3,053) | 1,594 (1,559โ€“3,072) | 19 | +| Memory RawGet | 2,250 (1,505โ€“4,380) | 2,009 (1,326โ€“5,994) | 17 | +| Pebble Get | 3,889 (2,999โ€“4,561) | 4,929 (2,731โ€“6,910) | 21 | +| Pebble RawGet | 3,088 (2,770โ€“4,443) | 3,794 (2,763โ€“7,188) | 19 | + +Every write verified leadership once and submitted one ordinary proposal. Allocated bytes per write stayed at 496 for one mutation and 3,920 for 64. The median allocation size per adapter read increased by 15โ€“16 bytes. The samples overlap for every operation, including the slower candidate medians for ordinary 1PC and Pebble-backed adapter reads. The three-host experiment must quantify this cost alongside the benefit to version-aware callers. [Benchmark invocation](../design/2026_11_21_single_key_mvcc_cas_local_benchmark.md#ordinary-path-comparison) + +## Verification + +The full Go package run exposed two fixture assumptions about the legacy coordinator, a historical raw batch that the new proposal gate correctly refuses to construct, and a bootstrap test that could sample different published and durable apply indices. The corrected public tests exercise lost replies on the production leader path and verify that the legacy coordinator rejects CAS before proposal. The replay test encodes the historical entry explicitly. The three-voter bootstrap fixture now waits for a consistent index before checking for an absent policy. Two runs of the corrected public endpoint and Redis tests passed, as did two runs of the protected TLS cluster and absence-guard tests. + +The final adapter sweep passed with the two long-running sequencing tests excluded. Both sequencing tests had completed in the preceding full adapter run. All failures from the repository-wide Go run passed in the subsequent scoped runs. The complete suite has not been repeated in a single invocation on the final tree. + +The focused race-detector run passed in `store`, `kv`, and `adapter`. It covered the nil follower batch, legacy leader forwarding, write skew with and without read-set validation, indexed lock rejection, rollback and replay of a framed proposal, encrypted TTL reads through a follower, and contending gRPC writers. Repository-wide lint returned zero issues. The ordinary-path fixtures also compiled and completed on the candidate. + +At the pinned Jepsen revision `54ab5c10ace229fc780e43e188ef1b64c3a32ee4`, the main Leiningen suite passed 410 tests and 1,932 assertions. The separate Redis Leiningen project failed while loading its test namespace. Its test requires `jepsen.redis` and the source tree provides `jepsen.redis.core`. The distributed three-host performance campaign remains outstanding. + +## Final pre-PR review on main, 2026-11-21 + +**Publication blocked.** Two independent read-only reviews examined candidate `70b237c62c1c7ec8d574e54209a8c371c7b1742b` against `9edcad5d00a3a5e7f48aa466708a096977317714`. Both found correctness defects. Two focused tests on Pebble reproduce the following violations at the Raft FSM boundary. [Regression tests](../../kv/version_cas_review_regression_test.go) + +| Scenario | Observed result | Invariant required to publish | +| --- | --- | --- | +| Both replicas start with the same key at version 10 and apply the same CAS frame at index 2. One catalog watcher has observed a same-owner split and the other is one version behind. | The first replica acknowledged the replacement at version 20. The second returned a missing-catalog-version verdict, persisted index 2, and retained version 10 even after catalog catch-up and replay of index 2. | All replicas applying the same data-group log must reach the same value and version. A missing process-local catalog snapshot cannot authorize a permanent no-op. | +| A CAS consumes version 10 and creates version 20. A bounded migration version cleanup then deletes one row in that range. | Cleanup deleted version 20 and exposed version 10 again. A second CAS using the consumed token succeeded at version 30. The test invokes the encoded cleanup frame directly. The review separately traced namespace and configuration checks at the peer-only RPC. | Cleanup must preserve the identity of consumed tokens or durably exclude the range from CAS before deleting its visible head. | + +The spec review also identified two client-visible verdict discrepancies by source inspection. A head written after the CAS start but before its commit can trigger the OCC timestamp-conflict branch before the exact-version comparison. An indexed route write-fence rejection can reach public gRPC as an indeterminate outcome. Both need contract tests, including follower ingress, before publication. + +The standards review confirmed the integrated coordinator preserves the sealed-check timestamp handoff, ordinary 1PC mutation order and read dependencies introduced by main. Both DCO trailers match the designated author. The focused gRPC suite and the 12 local contention benchmark cells passed. A successful known-token update took 1 client RPC and 1 proposal with CAS and 2 RPCs and 1 proposal with two-call 1PC. At 100% stale, CAS used 1 proposal per attempt and both fresh-read controls used 0. With eight contenders CAS averaged one winner per round. Repository-wide lint found zero issues. The Jepsen harness on this base passed 442 tests and 6,184 assertions. The standalone Redis suite still failed to load `jepsen.redis`. The repository-wide race run was stopped after reproducing the replication defect. The three-host performance campaign is pending. + +A protocol revision must identify the replicated routing evidence that orders a CAS relative to ownership and write-fence changes. It must also cover cleanup that can remove the latest version while an older version remains. The two tests below are expected to fail on the reviewed commit with the review tests applied. + +```sh +go test ./kv -run '^TestCAS(ReplicasAgreeAcrossSameOwnerCatalogSplit|ConsumedVersionStaysConsumedAfterBoundedCleanup)$' -count=1 -v +``` + +## Remediation of the pre-PR findings + +| Prior finding | Implementation and regression evidence | +| --- | --- | +| Watcher lag could change the outcome of applying the same CAS frame. | The v2 frame identifies its group and carries the admitted catalog version. The FSM reads the authoritative catalog in its own indexed store scope. A same-owner split can advance the catalog while preserving eligibility. An actual ownership loss or write fence rejects the write. The paired Pebble regressions assert the durable value, version and index, including replay after the lagging watcher catches up. [Routing](../../kv/version_cas_route.go) ยท [Catalog tests](../../kv/version_cas_catalog_test.go) | +| A one-row cleanup could expose a consumed token again. | Once migration version protection is active, cleanup touching eligible keys requires durable migration evidence covering the requested interval. The verdict is independent of which rows survive on each replica. The Pebble test consumes a token, requests a one-row cleanup, reopens the store, replays and attempts to reuse the token. It checks both the public predicate's result at apply and the durable head. [Cleanup](../../kv/fsm_migration_cleanup.go) ยท [Regression](../../kv/version_cas_review_regression_test.go) | +| An intervening write could mask an exact-version mismatch. | Given a safe commit timestamp and an unlocked key, the FSM compares the head before checking the caller's start timestamp against a matching head. The public test commits an ordinary write between CAS timestamp allocations, then checks the mismatch and reads the surviving value and version. [RPC tests](../../adapter/grpc_compare_and_swap_test.go) | +| A certified route fence could surface as an unknown outcome. | Public ingress preserves the indexed refusal locally and across the dedicated forwarding RPC. A lost reply remains indeterminate. [Outcome mapping](../../adapter/grpc_compare_and_swap.go) ยท [RPC tests](../../adapter/grpc_compare_and_swap_test.go) | + +### Why the existing Jepsen suite missed these histories + +The register workloads recorded values and ordinary reads and writes. They did not capture the expected or returned MVCC version, or attempt reuse of a token after an acknowledged replacement. A forwarded read can also reach the leader while a follower has a different durable image at that index. + +The new public workload records invocation-time tokens and completion-time versions. Its history tests include an overlapping read that may return the old value, a subsequent read that must see the new version or a later one, and two successful CAS operations consuming the same token. A timeout cannot certify either a mismatch or a replacement. The workload requires positive evidence of a chain of successful replacements, a read after an acknowledgement, and rejection of a consumed token. [Checker and generator](../../jepsen/src/elastickv/version_cas.clj) ยท [History tests](../../jepsen/test/elastickv/version_cas_test.clj) ยท [Run instructions](../operations/mvcc_version_cas.md) + +Lean proves equal-index agreement and single consumption for an arbitrary finite committed log in the abstract model. TLC explored 15,419 distinct states for two replicas and six bounded workloads. With only the old watcher behavior enabled, TLC violated `EqualAppliedIndexAgrees`. With only the old cleanup behavior enabled, it violated `SingleConsumption`. The model assumes atomic persistence of data and index and abstracts the interval proof to a coverage predicate. [Assumptions and implementation mapping](../../tla/cas/README.md) + +### Follow-up review and publication status + +The three-voter TLS smoke used six Jepsen clients against the public gRPC endpoints and a fresh key. In six seconds it observed 11 acknowledged replacements, including 10 chained updates, 37 reads invoked after an acknowledged update, and 31 confirmed rejections of consumed tokens. The helper conservatively marked two RPC errors indeterminate. The checker recorded no violations. This run used ordinary client traffic on one host. + +Independent review of tree `e4e6b95faf02926e07c368f5bdbb13ef9e3953b8` identified a further replica-agreement failure on a permanently covered migration range. Two Pebble stores start with the same versions 10 and 20. One compacts its older row. After both apply the same one-row cleanup at index 12, the uncompacted store exposes version 10 and the compacted store reports the key missing. CAS is already excluded on the range, but its ordinary latest value differs at the same applied index. The [paired-store regression](../../kv/version_cas_review_regression_test.go) reproduces this failure. The positive Lean agreement theorem and the original bounded TLC check assume a common durable image and omit independent physical compaction. A separate Lean example and TLC retention scenario exercise the covered-range counterexample under different retention histories. The positive checks apply only within their original assumptions. + +The same review identified the public classification of a pre-proposal routing refusal and an obsolete expected verdict in the parked contention test. The follow-up changes distinguish pre-proposal refusal from an indexed fence on both ingress paths, and expect an exact mismatch for a higher-commit-timestamp loser that presents a consumed token. The existing 1PC conflict assertion remains part of the same trial. The draft PR tracks the open covered-range cleanup decision. Merge remains blocked on replica agreement. + +The focused public leader/follower tests passed for the pre-proposal and indexed route outcomes, including the case in which the front end still uses the old route. The parked and reverse-release trials passed for both CAS and the fresh 1PC control. On the updated generator the main Jepsen unit suite passed 445 tests and 6,198 assertions. The subsequent checker additions passed in the focused run of 8 tests and 40 assertions. The pinned standalone Redis subproject still fails while loading its pre-existing `jepsen.redis` namespace. The repository-wide Go sweeps started before the follow-up fixes and did not establish a passing final run. + +## Replicated retirement implementation, 2026-12-02 + +The original independently compacted two-replica regression now passes with an actual one-row deletion and explicit absence on both replicas. The implementation persists an immutable range/selector/ceiling retirement in the same synced batch as applied progress and the initial physical page. Historical and latest reads, scans, version predicates and export enforce that decision; import, promotion and ordinary/prepared writes reject retired stamps before effects. Invalid cursors and changed retirement identities have dedicated no-effect regressions. + +Memory, native Pebble and SST tests cover snapshot round trips, bounded physical GC and loss of its disposable completion cache on restore. An encrypted Pebble test covers cold reopen. Physical completion is checked against every configured apply member, including learners, and rejected if the member roster or configuration changes. The reader floor is upgraded with activation and bound into the policy digest. A real three-voter TLS test restores policy/session readiness and the exact versioned value after a cold cluster restart. This runtime test does not yet perform a migration cleanup inside the native cluster. + +Focused race tests passed in `store`, `kv`, `adapter` and `internal/server`, including retirement, the original regression, refusal boundaries, prepared mutations, prefix deletion and native cold restart. The full race sweep passed `store`, `kv` and `internal/server`; it exposed adapter RPC fixtures missing the new durable policy precondition and a policy test using the now-supported version 2 as an unsupported version. Correcting those fixtures, without relaxing production checks, made the full policy suite and the focused CAS RPC/contention/move-back suite pass. A final repository-wide CI pass is still required. An unrelated parallel move-back probe timeout in that sweep also passed on the focused rerun; this is not evidence of a passing full adapter sweep. + +Lean and TLC distinguish the new logical visibility rule from the retained physical-only negative controls. The new positive TLC scenario preserves visible-head agreement under independent compaction. Its separate reachability check reaches successful CAS, logical retirement and completed physical cleanup on both replicas with a newer surviving row. These models do not prove the RPC authorization, read-drain barrier or physical-absence ACK protocol. + +The PR remains draft. Returning an unchanged version at or below a previous retirement ceiling still needs an explicit new-generation adoption protocol, not a relaxation of the stale-import rejection. Final-head review, CI and renewed stress evidence must be recorded before merge; the earlier 300-second CAS/ZSet and fault runs did not execute this retirement implementation. + +### Final-head stress follow-up + +The 300-second run on `870d79779e` passed protected CAS with same-data follower restart. ZSet returned `unknown`, not a consistency counterexample: its 1,078 reads and 1,992 mutations exceeded the existing local operation-search budget, and the initial global search also exhausted its budget. The failed artifact is retained in [run 46678336329](https://github.com/bootjp/elastickv/actions/runs/46678336329). A read-first search-order experiment and a separate 30-second Knossos global search did not establish a witness; neither result was relabeled a pass. + +The replacement search first constructs candidate member projections, then merges their action-order constraints and replays every mandatory operation against one complete ZSet state. Real-time deadlines, full and bounded range reads, and exact increment arithmetic are checked again during that shared execution. A projection by itself never certifies the history. Incompatible guides fall back to the original full search. Guides, validation and fallback share the original 50,000-candidate budget; exhaustion remains `unknown`. The complete failed artifact replays as valid with this implementation and no budget increase. Regression tests reject individually valid projections with contradictory atomic reads, omitted mandatory reads, reversed real-time order, invalid arithmetic and nested budget resets. + +The final adapter race sweep passed in 656.470 seconds. Linux CI separately exposed a legal interrupted FUSE close in the large-directory fixture. That fixture now syncs before closing, closes each descriptor only once, accepts only `EINTR` at close and verifies the created file; other close errors still fail. The Linux kernel mount test must pass CI, not a macOS skipped mount test, before this repair is accepted. + +### Ownership-return implementation, 2026-12-02 + +The previously pushed `31380e0166` passed code/security review, every CI check, +and the renewed [300-second CAS/ZSet run](https://github.com/bootjp/elastickv/actions/runs/46684488643). +Those receipts precede the row-generation extension described below and do not +approve it. Earlier statements above that unchanged ownership return was +unimplemented describe the pre-extension tree. + +The approved extension adds a persisted logical epoch, authenticated 17-byte +headers for adopted rows, memory snapshot V9, and policy reader floor 3. Foreign +epoch tags cannot authorize an import. A fresh job may stage privately, but only +a current replicated staged OWNER proof can publish a retired version with its +original timestamp, value, TTL and tombstone. Old job/group cleanup requests +are refused. Both indexed cleanup and local GC preserve generations newer than +the exact retirement being collected. A subsequent migration retires that new +generation without discarding earlier evidence. + +The store regressions pass on memory, native Pebble and SST. They exercise +unauthorized promotion, private staging invisibility, old indexed/local cleanup, +two retire/return cycles, preservation of TTL and tombstones, snapshot restore, +foreign-tag stripping, atomic rollback, immutable-retirement retry, applied-index +replay, malformed/overflowed counters and old-format refusal. Encrypted tests +cover cold reopen, DEK rotation with historical keys retained, native/SST +snapshot restore, and header tampering before visibility decisions. A combined +adoption/encryption relabel initially turned corruption into absence; its new +regression now fails closed. The pre-existing best-effort cleartext relabel +guard still has its documented residual gap for unreconstructable simultaneous +header/body rewrites; this extension does not claim authenticated plaintext +metadata for legacy cleartext rows. + +The adapter fixture completes `1 -> 2 -> 3 -> 1 -> 3 -> 1`, verifies the original +version 10 after each return, rejects stale/wrong-source cleanup and accepts a +new post-fence write. It runs the actual catalog, Internal and ordered FSM/store +commands, but not Raft elections. Online migration's existing whole-target-group +freshness restriction is unchanged: group 2 still owns a separate live key, so +the second return cycle uses group 3, whose old rows are retired. A separate +native three-voter TLS test replicates typed retirement/import/adoption controls, +checks the preserved head before and after per-voter old GC, and cold-restarts +all voters from snapshots. Its catalog attestation is a fixture, not an +end-to-end production migration. The native recovery race test passed in +80.587 seconds and the repeated catalog move-back race test in 39.123 seconds. + +The full race sweep passed `store` (168.940s), `kv` (129.313s), +`internal/raftbootstrap` (8.666s), `internal/server` (538.998s) and `adapter` +(778.656s). The subsequent indexed-GC tightening and new authority/upgrade +tests passed their focused race reruns. The final exact-head CI run must cover +the complete publication tree. Full Lean checks pass. TLC explores 5,840 +distinct adoption states without violating visible-head agreement or the epoch +bound; the old timestamp-only collector fails the expected invariant and a +separate reachability control reaches both completed returns after restart/replay. +These models assume valid ownership authority and persistence; they do not +prove the RPC or storage codec. + +Publication still requires post-last-push review, CI and renewed stress on the +extension's own SHA. The feature remains opt-in, and dedicated-host paired +latency/throughput criteria in the proposal are not established by these local +correctness tests or the single-host stress harness. + +### Publication CI and SQS follow-up + +Head `81ce2ea4b9` passed the renewed [300-second CAS/ZSet stress](https://github.com/bootjp/elastickv/actions/runs/46698131595) +and post-push code/security reviews. Its encrypted adapter-transition CI failed +one SQS visibility fixture with a generic HTTP 500. That fixture includes queue +creation, send, receive and visibility changes, so its original history alone +does not identify which SQS request failed. No checker result was weakened. + +The Query/XML error path now logs the private underlying cause on the server +without exposing it in the response. An isolated encrypted three-node runtime +then reproduced HTTP 500 from `SendMessage`: its single one-phase Raft entry +was definitively rejected at apply with an OCC write conflict. This reproduction +does not by itself prove the original CI failure had the same cause. + +Both JSON and Query standard-send paths now share a bounded retry that requires +an isolated, certified one-phase write-conflict rejection. Raw conflicts, mixed +errors, lost replies and unknown outcomes are not retried. After a certified +rejection, the adapter obtains a fresh fenced snapshot and revalidates current +queue metadata, generation, body-size and delay before dispatch. Throttling is +charged once for the logical request. All callers of the changed send core and +both wire handlers were audited; FIFO and batch-send paths retain their existing +semantics. + +The focused race suite passed in 4.833 seconds, including both wire paths, +metadata refresh, a lowered size limit, and no-retry ambiguity regressions. +The isolated encrypted runtime then completed 300 queue create/send/receive/ +visibility/delete cycles across three nodes without errors. This is a local +correctness reproduction, not a replacement for the final-head CI and stress +gates, nor a production performance result. +The broader SQS and batch-send race suite also passed in 21.011 seconds. + +### Commuting-read guide follow-up + +The [300-second run on `6fad887855`](https://github.com/bootjp/elastickv/actions/runs/46701809404) +passed CAS, but ZSet remained `unknown`: its 1,039 reads and 1,925 mutations +exhausted local operation search and the subsequent common-witness search. +The history is retained; no inconsistency was proved and this run is not a pass. + +The minimized regression exposes unnecessary read-to-read guide edges. Two +valid member projections may order the same unchanged reads differently, +creating an artificial cycle when merged. Read batches now retain edges from +their preceding mutation to every read and from every read to their following +mutation, but not an arbitrary order among these commuting projected reads. +Mutation order, mandatory operations and the full shared-state replay remain +unchanged. The verifier still checks complete/bounded reads, exact increment +arithmetic and real-time deadlines; incompatible guides use the original +fallback. All paths share the unchanged 50,000-candidate budget. + +The original minimized positive case fails before the change. The repaired +checker verifies the complete failed history in 4.082 seconds and 21,774 total +guide/validation candidates. Its earlier 96-operation local-search limit is +retained in the result, rather than erased or raised. Regressions retain the +fractured-read negative control, every read's two mutation boundaries, omitted +mandatory reads, real-time order, increment arithmetic and budget sharing. +A small exhaustive comparison rejects any guided pass without an exhaustive +shared execution. Exact-final-head CI and fresh stress remain publication gates. diff --git a/docs/evidence/2026_12_02_single_key_mvcc_cas_host_benchmark.md b/docs/evidence/2026_12_02_single_key_mvcc_cas_host_benchmark.md new file mode 100644 index 000000000..03d066b2d --- /dev/null +++ b/docs/evidence/2026_12_02_single_key_mvcc_cas_host_benchmark.md @@ -0,0 +1,390 @@ +# Dedicated-Host CAS Measurement, 2026-12-02 + +Author: bootjp + +**Decision: defer adoption.** The completed primary cell fails the predeclared +successful-update p99 criterion. This is not permission to enable the feature +or merge the implementation. Correctness evidence and a performance decision +are separate gates. The original apply-only hot-key campaign stopped on unknown +writes. The later adaptive source passes its complete hot-key cell, but still +fails primary. Both results are retained separately below. +The later combined follower-batching/storage trial stops in its first control +warmup, before a paired result; the short diagnostic is not an adoption result. + +## Provenance And Conditions + +The measured source is `46cc33fd58bbf516f943b68c056b26a960d7ba7c`. +Both binaries report Go 1.27.4, Linux/amd64, CGO disabled, and a clean source +revision. The server uses the explicit, hashed benchmark build overlay; the +ordinary production executable does not register its additional handlers. + +| Artifact | SHA-256 | +| --- | --- | +| Server | `235aa581e906775f439177a253ed1b1b48e2cb8308621dfbebe71471c3c3d37a` | +| Driver | `1f5468c48dbe6844c15d46efd9dfc782ada08a0bd25e82ac1708eac184ab857c` | +| Offline validator | `b7132733fcafff14bae6b88fbd6d11a2dee603f1c6606c226ab053da11f6396b` | +| Primary raw archive | `49a5465b51dc373ec66eef03aadf10191e4a4fcff0ddb523b95ae36fcda7ac44` | +| Primary offline validation | `ccffec9b8bce28af9d82ddf77dee3fa1340cca8e554a4ea817e047f552edda08` | +| Combined campaign raw archive | `f91c200f8f7fb789fb9751e7c1ab1ca66dcf1fa4dfb4620cfa6ed08c85b0f36f` | +| Hot-key completed-prefix validation | `c36605f451fef2645b94ec55d8e3dcaf3da4290324083f6da9db958914b10185` | + +Three disposable voters run on separate Proxmox hosts; the load generator is +on a fourth host. These hypervisors are shared, not exclusive bare metal. +Voters have four vCPUs and 8 GiB RAM; the driver has four vCPUs and 4 GiB. +All use Ubuntu 24.04 and local-lvm disks. The leader is fixed at voter n1. +Production voters at 192.168.0.210-214 are not used. + +The measured configuration keeps mTLS, protected Data admission, synchronous +FSM persistence, production HLC renewal and the normal 100,000-entry snapshot +threshold. It enables the existing `ELASTICKV_PEBBLE_SST_INGEST_SNAPSHOT=true` +option and sets `GOMEMLIMIT=4GiB` on each voter. This soft Go heap target does +not bound total RSS or Pebble's manually allocated cache. These settings are +conditions of this result, not evidence about the default configuration. + +The value is 1 KiB with deterministic identifiers and zero padding. Its low +entropy strongly benefits snapshot compression; do not generalize the result +to encrypted or high-entropy values. Eight workers use identical seeded input +traces and payloads across each pair. Every arm has a 30-second warmup, +120-second measurement, and one-second deadline from scheduled arrival, +including queue time. The control is the single-handler fenced 1PC path. + +Private raw artifacts are retained under +`.cache/cas1535-host-20261202/`; they include JSONL histories, counters, +frozen plans, configurations, build metadata, logs and SHA-256 manifests. +This document publishes the bounded interpretation rather than private keys +or bootstrap credentials. See the [reproduction guide](../design/2026_12_02_single_key_mvcc_cas_host_benchmark.md). + +## Primary Cell + +Control calibration brackets 140 passing and 144 failing updates/s. The frozen +offered rate is 112/s, 80% of the passing rate. Calibration unknowns remain +diagnostic and are not counted as on-time definitive results. Each failed +calibration namespace is drained and replaced before the decision namespace. + +All ten alternating pairs completed. Each measured arm acknowledged 13,440 +updates; every warmup acknowledged 3,360. Unknowns, deadline misses and unsent +operations are zero in every decision window. The offline validator reconciles +all 40 warmup/measurement windows, 336,000 acknowledged updates, every paired +input trace, and the final values and versions of all 65,536 keys. + +| Pair | Control successful p99, ms | CAS successful p99, ms | +| --- | ---: | ---: | +| 0 | 213.076197 | 38.604084 | +| 1 | 145.116002 | 17.319079 | +| 2 | 18.373640 | 16.383559 | +| 3 | 23.881459 | 22.697627 | +| 4 | 41.104333 | 15.911037 | +| 5 | 194.584672 | 15.871613 | +| 6 | 22.859494 | 37.389511 | +| 7 | 19.462671 | 38.500591 | +| 8 | 140.981056 | 15.817969 | +| 9 | 193.725615 | 20.925221 | + +The median paired CAS/control p99 ratio is 0.284132. Its predeclared second-to- +ninth-order interval is [0.108015, 1.635623]. The upper endpoint exceeds 0.90: +**the primary performance criterion fails**, despite the lower median. +The successful-goodput ratio is exactly 1 in all pairs and satisfies its +0.95 lower-bound criterion. No slow pair is removed or relabeled. + +The table below aggregates each arm's ten measured windows and divides by +134,400 successful updates. It does not include calibration or warmup. + +| Meter per successful update | Control | CAS | +| --- | ---: | ---: | +| Client mutation RPCs | 1.000260 | 1.000499 | +| Data submission attempts | 1.000260 | 1.000499 | +| Leader ReadIndex calls | 1.002909 | 0.001496 | +| Fenced HLC next calls | 1.000260 | 2.000997 | +| Leader data apply entries | 1.000260 | 1.000499 | +| Leader auxiliary mutation records | 1.000260 | 1.000499 | +| Fleet process CPU, microseconds | 12,566.700 | 10,623.897 | +| Fleet allocated bytes | 1,657,778.309 | 1,445,550.054 | + +Both designs already use one external mutation RPC and one data proposal per +attempt. CAS removes the control's comparison ReadIndex, not a data proposal. +Decoded mutation records are not committed effects: certified rejected entries +remain in those counts. Fleet CPU/allocations include three replicas, +background work and meter bookends. They are not request-causal traces and do +not identify the cause of individual tail spikes. Successful VFS WAL syncs are +not counts of physical device flushes. The counters cannot override the failed +latency interval. + +## Diagnostic Failures And Limits + +Earlier runs are retained, not replaced by this configuration: + +- The 4 GiB/default-snapshot run overloaded during calibration. +- An 8 GiB/default-snapshot campaign completed four pairs, then stopped on 251 + unknowns in a subsequent control warmup. Its completed prefix is not a pass. +- Without `GOMEMLIMIT`, the SST calibration OOM-killed voter n2: the kernel + recorded about 7.8 GiB anonymous RSS in an 8 GiB VM with about 13 GiB disk + space still free. This is memory exhaustion, not evidence of a full disk. +- Short snapshot/no-snapshot diagnostics have fewer than ten pairs and cannot + establish adoption. Changing leader placement between some diagnostics also + prevents a matched causal claim about snapshot implementation alone. +- The earlier driver lost one failed window when remote end-meter collection + failed. Revision `46cc33fd58` persists history first and records unavailable + meters explicitly. No missing history is reconstructed as a pass. + +Even passing both numeric cells would leave independent requirements: the +ordinary flag-off comparison, acquisition-inclusive and retained-handle runs, +the remaining value/worker matrix, synchronized contender trials, follower +ingress, secondary-lock fixtures, first activation, and post-last-push review +and CI. No threshold, checker budget or deadline is relaxed here. + +## Hot-Key Cell + +Control calibration brackets 152 passing and 156 failing logical requests/s. +The frozen offered rate is 121/s. A passing calibration means 99% on-time +definitive outcomes, including exhausted certified retries, not 99% successful +updates. The first control warmup and measurement complete with zero unknowns, +deadline misses or unsent requests. The 120-second control measurement has +7,489 successful updates and 7,031 exhausted logical requests out of 14,520. + +The first CAS warmup then fails the zero-unknown gate. The campaign stops +without a CAS measurement or `result.json`; it never retries unknown writes +as if they were absent. These are failed warmup diagnostics, not a matched +performance comparison or an accepted final-value proof. + +| First 30-second warmup, 3,630 logical requests | Control | CAS | +| --- | ---: | ---: | +| Successful updates | 1,647 | 558 | +| Exhausted certified retries | 1,983 | 83 | +| Unknown writes | 0 | 2,184 | +| Refresh errors | 0 | 679 | +| Queue-expired requests | 0 | 126 | +| Deadline misses | 0 | 2,989 | +| Client mutation RPC attempts | 11,896 | 5,472 | +| Client refresh reads | 6,183 | 2,646 | +| Leader data submission attempts | 4,270 | 4,979 | +| Leader decoded data apply entries | 4,270 | 4,953 | +| Leader successful Pebble WAL sync calls | 1,647 | 4,954 | + +The control can refuse a changed version before proposal, whereas apply-only +CAS proposes its comparison and durably records indexed mismatch progress. +This table demonstrates the additional persistence work in the failed CAS +window. It does not establish the complete cause of its timeouts: queueing, +shared-host I/O and competing background work were not separately randomized. +Client attempts, submitted entries, decoded records and acknowledgements are +different populations, particularly after unknown responses; do not reconcile +them as one successful-update chain or call every decoded mutation an effect. +The captured bookends report no in-flight handlers, but that cannot resolve +which unknown requests committed. + +All voters are still running at collection. No new OOM or leader change is +recorded in the failed interval. The earlier n2 OOM belongs to the no-heap-limit +experiment, not this failure. The offline validator verifies only the two +completed control windows and their 9,136 acknowledged updates; it explicitly +reports `complete_campaign=false`, `final_heads_verified=false` and +`decision_eligible=false`. Ten matched hot-key pairs and a final-value proof +were not obtained. + +## Integration And Teardown + +The independent CI bootstrap repair [#1593](https://github.com/bootjp/elastickv/pull/1593) +and runtime-owned TLS credential repair [#1594](https://github.com/bootjp/elastickv/pull/1594) +were merged only after reviews requested after their final pushes and all CI +passed. The unsigned, identical-tree predecessor #1592 was closed as a +duplicate without rewriting its history. CAS merge `5bcb50897245c2720338bb44ba5e80af4080fc1e` +integrates those changes. Relative to measured source `46cc33fd58`, that merge +changes only the three Jepsen workflows and `scripts/install-leiningen.sh`: +Go source, protobufs, `go.mod` and `go.sum` are identical. Measurement provenance +remains `46cc33fd58`, not a claim that a later commit was physically deployed. + +The first publication integration exposed an obsolete installer fixture in the +rest CI shard. The follow-up [#1595](https://github.com/bootjp/elastickv/pull/1595) +restores a fixed SHA-256 check for the launcher itself, keeps the verified JAR +cache protocol, and tests both artifacts in isolated temporary directories. +The four tests cover changed launchers, corrupt downloaded/cached JARs, verified +cache reuse and repair without executing fixture payloads. A real isolated +cold install verifies both official digests and reports Leiningen 2.13.1. +All three workflow callers were audited; no test workload, deadline, assertion +or checker budget changed. The independent PR passed its post-final-push +reviews and CI before merge. These subsequent installer/test/document changes +do not change the Go/protobuf/module measurement inputs. + +The [300-second CAS/ZSet stress on `a25a245bd1`](https://github.com/bootjp/elastickv/actions/runs/46776453061) +passed both workloads. It precedes the installer-fixture follow-up and cannot +substitute for review and CI on the final publication push. Neither hosted +stress nor the dedicated-host completed prefix overrides the failed adoption +conditions above. + +The four temporary VMs (9811-9814) of this original campaign were deleted after raw artifact checksum +verification and server shutdown. At 2026-12-02 00:05:45 UTC the verifier +confirmed all four absent from cluster inventory and local-lvm content, and +all eight stop/destroy tasks stopped with `exitstatus=OK`. The cleanup watchdog +and its transient units were removed by 00:07:09 UTC. Ephemeral SSH keys, +per-node TLS private keys and startup/admin credentials were deleted locally; +the public bootstrap archive remains available. No production VM was deleted. +Receipts are retained in `.cache/cas1535-host-20261202/cleanup/`. + +## Adaptive Follow-Up At 7196894fa5 + +The separate follow-up uses clean source +`7196894fa5b00ab1c8ffa50fc58d17aa936088e0`, including the bounded per-key +proposal lane, fenced adaptive precheck, immutable native-configuration cache +and synced-WAL SST checkpoint capture. It does not include the later follower +append batching. Go 1.27.4, Linux/amd64, CGO disabled, normal HLC renewal, mTLS, +protected policy/session admission, synchronous FSM, snapshot count 100,000, +SST option and 4 GiB Go heap target remain unchanged. + +| Artifact | SHA-256 | +| --- | --- | +| Server | `12b0f8b0803fd30c903e92d81bc4ee9e7ecc5897ac84323a8546a4b782a1f253` | +| Driver | `121bfe633776666e33059e438e1149c5d08493ff35f6e640ff359cb15d62b19d` | + +A new disposable-VM lease uses three voters on separate physical hypervisors +and a fourth load host. Fresh UUID/keys and all-peer offline preparation derive +from the same retained synthetic legacy fixture. Older identities and histories +are preserved, not rewound into an identity that previously served requests. + +| Frozen decision cell | Primary | Hot key | +| --- | ---: | ---: | +| Highest passing / first failing calibrated control rate | 136 / 140 | 152 / 156 | +| Offered logical requests/s at frozen 80% | 108 | 121 | +| Complete alternating matched pairs / windows | 10 / 40 | 10 / 40 | +| Verified acknowledged updates including warmups | 324,000 | 194,154 | +| Unknowns / deadline misses / unsent in decision windows | 0 / 0 / 0 | 0 / 0 / 0 | +| Median successful-update p99 ratio | 0.735136 | 0.757974 | +| Second-order p99 ratio | 0.371717 | 0.429850 | +| Ninth-order p99 ratio / upper gate | 3.318612 / 0.90 | 0.875337 / 1.05 | +| Second-order successful-goodput ratio / lower gate | 1.000000 / 0.95 | 1.087457 / 0.95 | +| Decision | FAIL | PASS | + +The original orchestration stopped after the completed primary failure. The +hot-key addendum was declared before hot calibration, with no intervening +diagnostic workload or binary/configuration change. Its pass cannot cancel the +primary failure. Calibration unknowns remain diagnostic, not part of the +zero-unknown decision claim. Workload, workers, values, warmups, 120-second +windows, scheduled-arrival deadline, attempts, seeded jitter and gates are +unchanged. No pair is removed. + +| Primary pair | Control successful p99, ms | CAS successful p99, ms | +| --- | ---: | ---: | +| 0 | 40.783936 | 26.344200 | +| 1 | 40.645727 | 16.852059 | +| 2 | 19.134860 | 122.850335 | +| 3 | 40.549076 | 15.072777 | +| 4 | 20.018209 | 66.432668 | +| 5 | 19.690818 | 16.231664 | +| 6 | 27.148019 | 37.689895 | +| 7 | 40.394741 | 21.245589 | +| 8 | 20.865126 | 39.806621 | +| 9 | 87.270042 | 15.200265 | + +Two independent offline checks recompute raw percentiles, verdict/deadline +counts and paired intervals. They reconcile every acknowledged predecessor +chain, all paired input traces, and final values/versions for 65,536 primary +keys and the single hot key. Raw artifacts and validators are retained under +`.cache/cas1535-perf-20261202/`, including `collected-final/` and separate +primary, hot, intermediate failed-source and profiled diagnostic histories. +The older 1,566-file evidence manifest was reverified without changes. + +The [300-second CAS/ZSet stress at this source](https://github.com/bootjp/elastickv/actions/runs/46849334712) +passes both correctness checkers. Its fault-injected indeterminate responses +are separate from the zero-unknown numeric decision cells. Source review and +all CI passed, but do not override the failed primary performance gate. + +## Index-Correlated Storage Diagnostic + +A separately labeled trace build on the same source reproduced a primary +tail. This is not an acceptance campaign. For group 1, term 8, index 1,085,237, +proposal 114,430, leader ownership-to-resolution-attempt took 643.209 ms. +Follower n3 spent 639.753 ms in WAL Save, including 639.682 ms in fdatasync. +Its Ready had no older committed apply work. It queued the covering append ACK +39 microseconds after Save returned. Leader Step then advanced commit to that +index and reached receipt resolution about 2.047 ms later. + +Follower n2 was already 95 indexes behind: saving index 1,085,142 took +1,209.231 ms, followed by 291.646 ms applying that older entry, including a +Pebble WAL sync. Both response paths were therefore unavailable. Moving ACK +dispatch before same-Ready apply cannot remove n3's required sync. The trace +supports this specific proposal's quorum delay, not a claim that every formal +tail has the same cause. Receipt-resolution instrumentation alone is not a +public acknowledgement or proof of payload-digest matching. + +A separate native probe appends 4 KiB and calls fdatasync 6,000 times, with all +three Elastickv servers stopped. It does not use Raft, gRPC, KV or the benchmark +client. It is a storage diagnostic, not an identical WAL allocation pattern or +an adoption criterion. Each file is temporary and removed after measurement. + +| Voter | Original p50 sync, ms | Original p99 sync, ms | Original max sync, ms | Relocated p50 / p99 / max, ms | +| --- | ---: | ---: | ---: | ---: | +| n1 | 0.822403 | 1.535179 | 9.943281 | 0.815189 / 1.136370 / 9.808636 | +| n2 | 5.864157 | 11.089768 | 672.130458 | 2.428380 / 4.496230 / 10.723172 | +| n3 | 5.968899 | 12.077944 | 1,407.949581 | 2.627469 / 3.822353 / 23.755969 | + +The original followers use TWSC local-lvm storage on different physical hosts. +The predeclared placement-only diagnostic moves n2 to pve15intel, n3 to +pve16intel and the load VM to pve13amd; n1 remains on pve12amd. It preserves +the existing guests, disks, virtual hardware, flags and diagnostic binaries. +The tables retain both placements; they do not isolate device firmware from +filesystem, virtualization or competing host I/O. No production voter is used. + +Storage isolation and the [limited follower batching](../design/2026_12_02_partial_protected_follower_append_batch.md) +are separate interventions. The latter targets additional single-entry Saves +after a stall, not the original in-progress fdatasync. Neither this probe nor +the focused batching regressions supplies a new accepted performance result. + +## Combined Batching And Storage Trial At d09c8ddde8 + +Clean signed source `d09c8ddde85d2051cae61ee614fa6714eafa47fd` includes bounded +protected follower batching. This is a combined code-and-relocated-storage trial, +not evidence attributing improvement to batching alone. Fresh identities derive +from the identical retained legacy fixture after all-peer offline preparation. +All workload, calibration, rate-selection, deadline, retry and decision gates +remain unchanged. The trial started at 2026-12-02 15:08:24 UTC, or December 3 +00:08:24 JST. Raw artifacts are in `collected-d09-final/` under the follow-up +cache. Their archive SHA-256 is +`72b7bb4a246772d8821c94fc1b694621f592b8574fa8238d06ec449170006679`. + +| Artifact | SHA-256 | +| --- | --- | +| Server | `2381f3eacc01e1521b1f17f3ea0e7e3fa3ba4a9ab5ab41430e3de55d73ac557a` | +| Driver | `67577809d2e5518c6464ef9616b1cfdd8bb5730f063838633e904f4cf550d171` | + +Primary calibration passes at 336/s: 40,298 of 40,320 operations succeed on time, +with 21 unknowns retained. This satisfies the unchanged 99% calibration rule, +not the decision's zero-unknown rule. The offered decision rate freezes at +268/s. Its first 30-second fresh-control warmup has 7,750 successful updates, +including one late success, 290 unknowns, 291 deadline misses and no unsent work. +It stops before the measured control, CAS arm or hot cell. No pair, final-head +proof or accepted decision result is claimed. The fresh-control payload is not +eligible for the CAS-only follower batch. + +All unknowns are consecutive at the end. In scheduled second 29, median +arrival-to-send queueing reaches 971 ms, leaving about 30 ms for the RPC. Workers +start their next RPC promptly after the preceding one; load-host CPU/pressure +and server GC pause totals do not support scheduler starvation as the primary +cause. During that warmup n2 receives 399.3 MB and applies 4,852 data entries, +versus n3's 11.6 MB and 7,792 entries, matching the leader's apply count. The +leader records repeated outbound Append drops to n2. These observations support +replication pressure but do not identify the exact request-critical stall or +prove that the backlog originated during calibration. + +An audit finds the old drain check tests only each node's local log/commit/apply +equality, not equality with its leader. The follow-up requires a common committed +prefix across voters before completing the existing stability check. A bufconn +regression exercises the actual observer with locally idle but divergent indexes: +99/100 and 100/101 both incorrectly pass before the fix, then are refused. This +tightens setup/bookend validation; it does not lower the rate or relax a failed +window, and it cannot retroactively validate this trial. + +After evidence collection and restart with all voters caught up, a separately +instrumented 268/s diagnostic completes one pair of 30-second windows plus +30-second warmups. Unknowns, deadline misses and unsent work are zero; all +32,160 acknowledged predecessor changes, both paired traces and all 65,536 final +values/versions verify. Successful measured p99 is 29.343135 ms for fresh 1PC +and 18.075089 ms for CAS. This diagnostic uses trace-overlay server SHA-256 +`f108bc72ea2fd5290d9b78cfd392fc476bb7fad3ae8c74c8d760a9092d2407ea` and the same +old driver. It does not reproduce the failure or establish its cause. Its one +pair/fixed-rate/short duration is deliberately rejected by the ten-pair numeric +validator. It is not a replacement for the failed full trial. Complete raw +archive SHA-256 is +`4d4d741c5bc65fa3401e9887e15dab12cef3e752512e3daf0f9fd2fb0c2f10b0`. + +Normal and security reviews on `d09c8ddde8`, all 27 CI checks and the +[300-second CAS/ZSet stress](https://github.com/bootjp/elastickv/actions/runs/46908454366) +pass before this full trial. Fault-stress indeterminates remain distinct from +the decision windows' zero-unknown requirement. Any subsequent push requires +new latest-head reviews and CI. Adoption remains deferred. diff --git a/docs/operations/mvcc_version_cas.md b/docs/operations/mvcc_version_cas.md new file mode 100644 index 000000000..b604b321a --- /dev/null +++ b/docs/operations/mvcc_version_cas.md @@ -0,0 +1,61 @@ +# Rolling out MVCC version CAS + +`--versionCAS` defaults to false. It enables CAS admission on the node that receives a public request and on the group leader that submits it. Roll it out as follows. + +1. Deploy CAS-capable binaries to every voter and learner and enable protected Raft bootstrap and its pinned peer TLS. Use the protected [Raft bootstrap procedure](../raft_bootstrap_enablement.md) for its fixed membership. Protected native admission rejects voter and learner additions and promotions. +2. Drain transactions prepared before fence activation and start the nodes with `--commitTSFence`. Wait for the public services to become ready. The fence activation is a replicated entry. Public startup with this flag waits for every local data group to apply it. +3. Start the participating nodes with both `--commitTSFence` and `--versionCAS`. Exercise Get with the version requested and a CAS against its returned token. Check both direct leader and follower ingress. + +The leader checks its applied fence marker and uses pinned TLS to query every other configured replica, including learners, for `RaftAdmin.Status.supports_replicated_catalog_cas` at the same configuration index. Joint configurations are ineligible. A down, unprovisioned, incompatible, or reconfiguring replica prevents new CAS proposals, even if the group has a write quorum. Raft rechecks the term and configuration when appending the proposal. The first eligible versioned read or CAS activates a replicated migration-version identity guard for its data group. Allow the first request to finish before measuring steady-state latency. Versioned reads and CAS are initially available for ordinary keys on routes without migration floors or ownership transition evidence. The status bit covers activation, protected cleanup and the v2 CAS frame that binds the command to its catalog group. It can be true while the node's own CAS admission flag is off. + +Both opt-in point reads (`Get` and `RawGet`) and CAS use the leader's live replica check. The activation uses the same proposal protection as CAS and waits for local apply before serving a token. Activation is demand-driven per group and survives normal Raft snapshots. The catalog group must apply its own activation before serving any token. + +The initial rollout serves version tokens on the data group that replicates the authoritative catalog. Requests for routes on other groups receive an admission error and can use the existing transactional API. A follower may receive a request and forward it to the protected leader. Catalog watcher lag must never change the outcome of applying a committed CAS frame. + +A route is eligible only while it is active, has a zero migration write floor, has no staged visibility, and has no intersecting replicated migration ownership or armed readiness state. Explicit-group `RawGet` must select the same authoritative owner. Keys with auxiliary, legacy fallback, or partition routing are excluded. Migration cutover records a nonzero floor in the target route, promotion retains it, and descendant splits inherit it. The entire moved range stays ineligible, including writes newer than the floor and ranges routed back to their original group. The same policy applies when an inactive migration target later activates for its other ranges. Existing data on eligible initial routes can produce tokens without a rewrite. + +To stop new versioned reads and CAS, stop ingress and drain requests, then restart the nodes without `--versionCAS`. Keep the timestamp fence and CAS-capable binaries. Replicas continue to apply committed entries during catch-up or replay. Until the group's replicated migration identity marker, import and promotion replay with their legacy semantics. After the marker, strict identity checks apply even with the local flag off. Both new Raft frames use a reserved opcode that makes the preceding binary halt upon encountering either frame. Retain the compatible binary on the protected membership for restarts and snapshot recovery, since snapshots can compact away these frames. + +A client can reuse a successful response's new version for its next edit. A mismatch means the caller must read again before recomputing an update. `Aborted/CAS_ROUTE_FENCED` certifies that the routed CAS was rejected at apply. An unknown outcome after submission requires reconciliation before retrying a logical update. + +## Store directory permissions + +The Pebble store holds a stable process lock at +`/.elastickv-store-locks/`. This applies even with +`--versionCAS` off. The lock prevents a second open from recovering a live +restore backup or deleting a worker's SST export. + +The service identity must be able to create the lock directory in the parent, +or an operator must pre-create the lock directory with appropriately scoped +ownership and write permission. A writable DB alone is not enough when this +directory is absent. Parent-directory write access need not be granted if the +lock directory is pre-provisioned. Avoid world-writable permissions. + +Do not remove or replace lock files or their directory while any process may +have the store open. Stop the old process before starting another binary on +the same store. The files are local lock anchors, not replicated metadata. + +## Restore and rollback + +CAS tokens belong to one key in one cluster history. Raft snapshot installation and ordinary replay continue that history. An offline point-in-time restore can resurrect a version held by an old client. + +Servers refuse `--versionCAS` when a data group carries an external snapshot restore origin marker. Such a replica also reports CAS capability as false with the flag off, which prevents leaders with the flag on from submitting CAS in that group. These checks cover the offline restore tools that persist this marker. Preserve it with the restored data directory. + +A manual rewind that copies or replaces data directories can evade origin detection. Before serving a manually rewound cluster, stop all old CAS traffic and restart every node with `--versionCAS` off. Keep it off while old requests can reach the restored cluster. The API does not carry a cluster incarnation. Any future activation after a manual rewind requires fencing all old CAS clients, including pending retries, and requiring fresh version reads from the replacement endpoint before accepting CAS again. + +## Check the public CAS history with Jepsen + +On a disposable cluster with CAS enabled, point the client at the public endpoints for three voters. Use a fresh run for each cluster history. From the repository root: + +```sh +go build -o /tmp/jepsen-grpc-client ./cmd/jepsen-grpc-client +cd jepsen +lein run -m elastickv.grpc-workload --local --host 127.0.0.1 \ + --grpc-ports 50051,50052,50053 --grpc-tls-ca-file /path/to/cluster-ca.pem \ + --grpc-client-bin /tmp/jepsen-grpc-client --grpc-api version-cas \ + --concurrency 6 --time-limit 30 --rate 36 +``` + +The workload initializes one fresh non-expiring key, records versioned reads, and submits both current and previously consumed tokens. The history checker requires a successful CAS using the highest CAS version already acknowledged at invocation, a read after an update, and a confirmed rejection when reusing a consumed token. Insufficient coverage yields `:unknown`. A read that overlaps a successful update can legitimately return the preceding version. A read started after the acknowledgement must observe that version or a later one. Transport errors remain indeterminate. A run can pass with indeterminate operations when the observed history meets all three coverage conditions and contains no detected violations. + +Multiple public endpoints can forward to the same leader. A green client history therefore covers only the states those clients observed. The [indexed FSM regressions](../../kv/version_cas_review_regression_test.go) compare independently applied durable states and exercise one-row cleanup and reopen. The [formal model](../../tla/cas/README.md) checks both failure modes under its stated assumptions. diff --git a/internal/casbenchmark/front.go b/internal/casbenchmark/front.go new file mode 100644 index 000000000..5b8ba0ca2 --- /dev/null +++ b/internal/casbenchmark/front.go @@ -0,0 +1,313 @@ +// Package casbenchmark is an experimental frontend, not a production service. +// Only the explicit benchmark overlay registers it with a server. +package casbenchmark + +import ( + "context" + "encoding/json" + "strconv" + "strings" + "sync" + "time" + + "github.com/bootjp/elastickv/adapter" + "github.com/bootjp/elastickv/internal/casbenchmark/meter" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +const Service = "benchmark.FencedOnePhase" +const Prefix = "/" + Service + "/" +const ClientHeader = "bench-client" +const HandleHeader = "bench-handle" +const pinTTL = 5 * time.Second +const maxPins = 4096 + +type pin struct { + client, key string + stamp kv.ReadTimestamp + version uint64 + created time.Time + release func() + timer *time.Timer +} + +type Frontend struct { + coord kv.Coordinator + store store.MVCCStore + tracker *kv.ActiveTimestampTracker + admit adapter.RequestAdmission + mu sync.Mutex + next uint64 + pins map[string]*pin +} + +func Register(server *grpc.Server, st store.MVCCStore, coord kv.Coordinator, tracker *kv.ActiveTimestampTracker, admit adapter.RequestAdmission) { + f := &Frontend{coord: coord, store: st, tracker: tracker, admit: admit, pins: make(map[string]*pin)} + server.RegisterService(&grpc.ServiceDesc{ServiceName: Service, HandlerType: (*interface{})(nil), Methods: []grpc.MethodDesc{ + method("Fresh", f.fresh), method("Acquire", f.acquire), method("Commit", f.commit), method("Cancel", f.cancel), + {MethodName: "Window", Handler: f.window}, + {MethodName: "Seed", Handler: f.seed}, + }}, f) +} + +func header(ctx context.Context, key string) string { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get(key) + if len(values) == 1 { + return values[0] + } + return "" +} + +func method(name string, call func(context.Context, *pb.CompareAndSwapRequest) (any, error)) grpc.MethodDesc { + fullMethod := Prefix + name + return grpc.MethodDesc{MethodName: name, Handler: func(server any, ctx context.Context, decode func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) { + req := new(pb.CompareAndSwapRequest) + if err := decode(req); err != nil { + return nil, errors.WithStack(err) + } + front, ok := server.(*Frontend) + if !ok { + return nil, errors.WithStack(status.Error(codes.Internal, "invalid benchmark frontend")) + } + next := func(ctx context.Context, _ any) (any, error) { + if err := validateRequest(name, req); err != nil { + return nil, err + } + return front.owned(ctx, func(owned context.Context) (any, error) { return call(owned, req) }) + } + if interceptor == nil { + return next(ctx, req) + } + return interceptor(ctx, req, &grpc.UnaryServerInfo{Server: server, FullMethod: fullMethod}, next) + }} +} + +const maxKeyBytes = 256 +const maxValueBytes = 16 * 1024 + +func validateRequest(name string, req *pb.CompareAndSwapRequest) error { + if !strings.HasPrefix(string(req.Key), "bench1535/") { + return errors.WithStack(status.Error(codes.InvalidArgument, "benchmark key prefix required")) + } + if len(req.Key) > maxKeyBytes || len(req.Value) > maxValueBytes { + return errors.WithStack(status.Error(codes.InvalidArgument, "benchmark payload limit exceeded")) + } + if name != "Acquire" && req.ExpectedCommitTs == 0 { + return errors.WithStack(status.Error(codes.InvalidArgument, "positive expected version required")) + } + return nil +} + +func (f *Frontend) owned(ctx context.Context, call func(context.Context) (any, error)) (any, error) { + if f.admit == nil { + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "benchmark requires protected runtime")) + } + owner, err := f.admit(ctx) + if err != nil { + return nil, errors.WithStack(err) + } + if owner == nil { + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "benchmark ownership missing")) + } + defer owner.CancelAndJoin() + if owner.Context() == nil { + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "benchmark ownership context missing")) + } + response, err := call(owner.Context()) + if err = owner.Finish(err); err != nil { + return nil, errors.WithStack(err) + } + return response, nil +} + +func (f *Frontend) read(ctx context.Context, key []byte, visit func(store.VersionedValue, kv.ReadTimestamp) error) error { + meter.Count("control_fenced_reads", 1) + r := kv.NewReadRequest(ctx, f.coord, f.store, f.tracker) + defer r.Close() + snapshot, err := r.Latest(r.Context(), "benchmark fenced 1PC", key) + if err != nil { + return errors.WithStack(err) + } + v, err := r.GetVersion(r.Context(), snapshot, key) + if err != nil { + return errors.WithStack(err) + } + return visit(v, snapshot.TransactionTimestamp()) +} + +func mismatch() *pb.CompareAndSwapResponse { + return &pb.CompareAndSwapResponse{Result: &pb.CompareAndSwapResponse_Mismatch{Mismatch: true}} +} + +func (f *Frontend) submit(ctx context.Context, req *pb.CompareAndSwapRequest, stamp kv.ReadTimestamp) (any, error) { + reply, err := kv.DispatchWithLeaderIssuedCommitTS(stamp.WithDispatchVoucher(ctx), f.coord, &kv.OperationGroup[kv.OP]{ + IsTxn: true, StartTS: stamp.Timestamp(), ReadKeys: [][]byte{req.Key}, + Elems: []*kv.Elem[kv.OP]{{Op: kv.Put, Key: req.Key, Value: req.Value}}, + }) + if err != nil { + return nil, submissionError(err) + } + if reply == nil || reply.CommitTS <= req.ExpectedCommitTs { + return nil, errors.WithStack(status.Error(codes.Unknown, "missing 1PC commit proof")) + } + return &pb.CompareAndSwapResponse{Result: &pb.CompareAndSwapResponse_NewCommitTs{NewCommitTs: reply.CommitTS}}, nil +} + +func submissionError(err error) error { + if errors.Is(err, kv.ErrTransactionOutcomeUnknown) { + return errors.WithStack(status.Error(codes.Unknown, "1PC submission outcome unknown")) + } + if kv.IsCertifiedOnePhaseConflict(err) && (errors.Is(err, store.ErrWriteConflict) || errors.Is(err, kv.ErrTxnLocked)) { + return errors.WithStack(status.Error(codes.Aborted, "1PC rejected")) + } + return errors.WithStack(status.Error(codes.Unknown, "unproven 1PC submission outcome")) +} + +func (f *Frontend) fresh(ctx context.Context, req *pb.CompareAndSwapRequest) (any, error) { + var response any + err := f.read(ctx, req.Key, func(value store.VersionedValue, ts kv.ReadTimestamp) error { + if value.TS != req.ExpectedCommitTs { + response = mismatch() + return nil + } + var err error + response, err = f.submit(ctx, req, ts) + return err + }) + return response, errors.WithStack(err) +} + +func (f *Frontend) acquire(ctx context.Context, req *pb.CompareAndSwapRequest) (any, error) { + response := new(pb.GetResponse) + err := f.read(ctx, req.Key, func(value store.VersionedValue, stamp kv.ReadTimestamp) error { + response.Value, response.Version = value.Value, &pb.GetResponse_CommitTs{CommitTs: value.TS} + if req.ExpectedCommitTs != 0 && req.ExpectedCommitTs != value.TS { + return nil + } + client := header(ctx, ClientHeader) + if client == "" { + return errors.WithStack(status.Error(codes.InvalidArgument, "missing benchmark client")) + } + f.mu.Lock() + defer f.mu.Unlock() + if len(f.pins) >= maxPins { + return errors.WithStack(status.Error(codes.ResourceExhausted, "benchmark handle limit reached")) + } + f.next++ + id := strconv.FormatUint(f.next, 10) + p := &pin{client: client, key: string(req.Key), stamp: stamp, version: value.TS, created: time.Now(), release: f.tracker.Pin(stamp.Timestamp()).Release} + p.timer = time.AfterFunc(pinTTL, func() { + f.mu.Lock() + defer f.mu.Unlock() + if f.pins[id] == p { + f.release(id, p) + meter.Count("handle_expirations", 1) + } + }) + f.pins[id] = p + if err := grpc.SetHeader(ctx, metadata.Pairs(HandleHeader, id)); err != nil { + f.release(id, p) + return errors.WithStack(err) + } + return nil + }) + return response, errors.WithStack(err) +} + +func (f *Frontend) release(id string, p *pin) { + delete(f.pins, id) + p.timer.Stop() + finishPin(p) +} + +func finishPin(p *pin) { + p.release() + if elapsed := time.Since(p.created).Nanoseconds(); elapsed > 0 { + meter.Count("handle_pin_ns", uint64(elapsed)) + } +} + +func (f *Frontend) take(ctx context.Context, req *pb.CompareAndSwapRequest) (*pin, error) { + f.mu.Lock() + defer f.mu.Unlock() + id := header(ctx, HandleHeader) + p := f.pins[id] + if p == nil || p.client != header(ctx, ClientHeader) || p.key != string(req.Key) || p.version != req.ExpectedCommitTs { + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "invalid benchmark handle")) + } + delete(f.pins, id) + p.timer.Stop() + if time.Since(p.created) >= pinTTL { + finishPin(p) + meter.Count("handle_expirations", 1) + return nil, errors.WithStack(status.Error(codes.FailedPrecondition, "expired benchmark handle")) + } + return p, nil +} + +func (f *Frontend) commit(ctx context.Context, req *pb.CompareAndSwapRequest) (any, error) { + p, err := f.take(ctx, req) + if err != nil { + return nil, errors.WithStack(err) + } + defer finishPin(p) + return f.submit(ctx, req, p.stamp) +} + +func (f *Frontend) cancel(ctx context.Context, req *pb.CompareAndSwapRequest) (any, error) { + p, err := f.take(ctx, req) + if err == nil { + finishPin(p) + } + return &pb.CompareAndSwapResponse{}, errors.WithStack(err) +} + +func (f *Frontend) window(server any, ctx context.Context, decode func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) { + req := new(wrapperspb.StringValue) + if err := decode(req); err != nil { + return nil, errors.WithStack(err) + } + next := func(ctx context.Context, _ any) (any, error) { + return f.owned(ctx, func(context.Context) (any, error) { + result, err := windowResult(req.Value) + if err != nil { + return nil, err + } + body, err := json.Marshal(result) + if err != nil { + return nil, errors.WithStack(err) + } + return wrapperspb.Bytes(body), nil + }) + } + if interceptor == nil { + return next(ctx, req) + } + return interceptor(ctx, req, &grpc.UnaryServerInfo{Server: server, FullMethod: Prefix + "Window"}, next) +} + +func windowResult(action string) (meter.Result, error) { + if action == "idle" { + return meter.Result{InFlight: meter.InFlight()}, nil + } + var result meter.Result + var ok bool + if name, begin := strings.CutPrefix(action, "begin:"); begin { + ok = meter.Begin(name) + } else if name, end := strings.CutPrefix(action, "end:"); end { + result, ok = meter.End(name) + } + if !ok { + return result, errors.WithStack(status.Error(codes.FailedPrecondition, "invalid benchmark window transition")) + } + return result, nil +} diff --git a/internal/casbenchmark/front_test.go b/internal/casbenchmark/front_test.go new file mode 100644 index 000000000..3c2a61a8e --- /dev/null +++ b/internal/casbenchmark/front_test.go @@ -0,0 +1,162 @@ +package casbenchmark + +import ( + "context" + "io" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/adapter" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +type testOwner struct { + ctx context.Context + finishErr error + finished, canceled int +} + +func (o *testOwner) Context() context.Context { return o.ctx } +func (o *testOwner) Validate() error { return nil } +func (o *testOwner) CancelAndJoin() { o.canceled++ } +func (o *testOwner) Finish(err error) error { + o.finished++ + return errors.CombineErrors(err, o.finishErr) +} + +func TestOwnedRetainsAdmissionUntilResultValidation(t *testing.T) { + t.Parallel() + owner := &testOwner{ctx: t.Context(), finishErr: status.Error(codes.Unknown, "revoked")} + front := &Frontend{admit: func(context.Context) (adapter.RequestOwnership, error) { return owner, nil }} + result, err := front.owned(t.Context(), func(ctx context.Context) (any, error) { + require.Equal(t, owner.ctx, ctx) + return "not publishable", nil + }) + require.Nil(t, result) + require.Equal(t, codes.Unknown, status.Code(err)) + require.Equal(t, 1, owner.finished) + require.Equal(t, 1, owner.canceled) +} + +func TestOwnedRejectsAbsentOrInvalidOwnership(t *testing.T) { + t.Parallel() + invalid := &testOwner{} + for name, admit := range map[string]adapter.RequestAdmission{ + "unprotected": nil, + "nil owner": func(context.Context) (adapter.RequestOwnership, error) { return nil, nil }, + "nil context": func(context.Context) (adapter.RequestOwnership, error) { return invalid, nil }, + } { + t.Run(name, func(t *testing.T) { + called := false + _, err := (&Frontend{admit: admit}).owned(t.Context(), func(context.Context) (any, error) { called = true; return nil, nil }) + require.Error(t, err) + require.False(t, called) + }) + } + require.Equal(t, 1, invalid.canceled) +} + +type rejectionProposer struct{} + +func (rejectionProposer) Propose(context.Context, []byte) (*raftengine.ProposalResult, error) { + return &raftengine.ProposalResult{CommitIndex: 7, Response: store.ErrWriteConflict}, nil +} +func (p rejectionProposer) ProposeAdmin(ctx context.Context, data []byte) (*raftengine.ProposalResult, error) { + return p.Propose(ctx, data) +} + +func certifiedRejection(t *testing.T) error { + t.Helper() + manager := kv.NewTransactionWithProposer(rejectionProposer{}) + t.Cleanup(manager.Close) + _, err := manager.Commit(t.Context(), []*pb.Request{{IsTxn: true, Ts: 1, Mutations: []*pb.Mutation{{Op: pb.Op_PUT, Key: []byte("bench1535/key"), Value: []byte("value")}}}}) + require.True(t, kv.IsCertifiedOnePhaseConflict(err)) + return err +} + +type dispatchCoordinator struct { + kv.Coordinator + err error + response *kv.CoordinateResponse + request *kv.OperationGroup[kv.OP] +} + +func (c *dispatchCoordinator) Dispatch(_ context.Context, request *kv.OperationGroup[kv.OP]) (*kv.CoordinateResponse, error) { + c.request = request + return c.response, c.err +} +func (*dispatchCoordinator) Clock() *kv.HLC { return nil } + +func TestSubmitDoesNotCertifyUnknownOrMixedFailures(t *testing.T) { + t.Parallel() + certified := certifiedRejection(t) + for name, tc := range map[string]struct { + failure error + code codes.Code + }{ + "certified": {certified, codes.Aborted}, + "raw conflict": {store.ErrWriteConflict, codes.Unknown}, + "lost response": {io.EOF, codes.Unknown}, + "mixed": {errors.Join(certified, io.EOF), codes.Unknown}, + "unknown": {kv.ErrTransactionOutcomeUnknown, codes.Unknown}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + coord := &dispatchCoordinator{err: tc.failure} + stamp, err := kv.BeginReadTimestampThrough(t.Context(), nil, 1, "test") + require.NoError(t, err) + result, err := (&Frontend{coord: coord}).submit(t.Context(), &pb.CompareAndSwapRequest{Key: []byte("bench1535/key"), ExpectedCommitTs: 1}, stamp) + require.Nil(t, result) + require.Equal(t, tc.code, status.Code(err)) + require.Equal(t, uint64(1), coord.request.StartTS) + require.Equal(t, [][]byte{[]byte("bench1535/key")}, coord.request.ReadKeys) + }) + } +} + +func TestTakeBindsClientKeyVersionAndConsumesOnce(t *testing.T) { + t.Parallel() + stamp, err := kv.BeginReadTimestampThrough(t.Context(), nil, 1, "test") + require.NoError(t, err) + var released atomic.Int32 + p := &pin{client: "owner", key: "bench1535/key", stamp: stamp, version: 1, created: time.Now(), release: func() { released.Add(1) }, timer: time.AfterFunc(time.Hour, func() {})} + t.Cleanup(func() { p.timer.Stop() }) + front := &Frontend{pins: map[string]*pin{"id": p}} + req := &pb.CompareAndSwapRequest{Key: []byte(p.key), ExpectedCommitTs: 1} + ctx := metadata.NewIncomingContext(t.Context(), metadata.Pairs(ClientHeader, "other", HandleHeader, "id")) + _, err = front.take(ctx, req) + require.Error(t, err) + require.Zero(t, released.Load()) + ctx = metadata.NewIncomingContext(t.Context(), metadata.Pairs(ClientHeader, "owner", HandleHeader, "id")) + _, err = front.take(ctx, &pb.CompareAndSwapRequest{Key: []byte("bench1535/other"), ExpectedCommitTs: 1}) + require.Error(t, err) + _, err = front.take(ctx, &pb.CompareAndSwapRequest{Key: req.Key, ExpectedCommitTs: 2}) + require.Error(t, err) + taken, err := front.take(ctx, req) + require.NoError(t, err) + require.Zero(t, released.Load(), "consumption must retain the pin until submission returns") + finishPin(taken) + require.Equal(t, int32(1), released.Load()) + _, err = front.take(ctx, req) + require.Error(t, err) + require.Equal(t, int32(1), released.Load()) +} + +func TestBenchmarkRequestCannotTargetPrivateOrUnboundedKeys(t *testing.T) { + t.Parallel() + for _, key := range []string{"private/key", "bench1535/" + string(make([]byte, maxKeyBytes))} { + require.Error(t, validateRequest("Fresh", &pb.CompareAndSwapRequest{Key: []byte(key), ExpectedCommitTs: 1})) + } + require.Error(t, validateRequest("Fresh", &pb.CompareAndSwapRequest{Key: []byte("bench1535/key")})) + require.Error(t, validateRequest("Fresh", &pb.CompareAndSwapRequest{Key: []byte("bench1535/key"), ExpectedCommitTs: 1, Value: make([]byte, maxValueBytes+1)})) + require.NoError(t, validateRequest("Acquire", &pb.CompareAndSwapRequest{Key: []byte("bench1535/key")})) +} diff --git a/internal/casbenchmark/meter/fs.go b/internal/casbenchmark/meter/fs.go new file mode 100644 index 000000000..34e5d5e8e --- /dev/null +++ b/internal/casbenchmark/meter/fs.go @@ -0,0 +1,65 @@ +package meter + +import ( + "strings" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2/vfs" +) + +type measuredFS struct{ vfs.FS } +type measuredWAL struct{ vfs.File } + +// WrapFS counts completed Pebble WAL persistence calls, not physical device +// flushes. All filesystem semantics and descriptors remain with the wrapped FS. +func WrapFS(fs vfs.FS) vfs.FS { return measuredFS{FS: fs} } +func (f measuredFS) Unwrap() vfs.FS { return f.FS } + +func measuredFile(name string, file vfs.File, err error) (vfs.File, error) { + if err != nil { + return file, errors.WithStack(err) + } + if strings.HasSuffix(name, ".log") { + return measuredWAL{File: file}, nil + } + return file, nil +} + +func (f measuredFS) Create(name string, category vfs.DiskWriteCategory) (vfs.File, error) { + file, err := f.FS.Create(name, category) + return measuredFile(name, file, err) +} +func (f measuredFS) OpenReadWrite(name string, category vfs.DiskWriteCategory, options ...vfs.OpenOption) (vfs.File, error) { + file, err := f.FS.OpenReadWrite(name, category, options...) + return measuredFile(name, file, err) +} +func (f measuredFS) ReuseForWrite(oldName, newName string, category vfs.DiskWriteCategory) (vfs.File, error) { + file, err := f.FS.ReuseForWrite(oldName, newName, category) + return measuredFile(newName, file, err) +} +func (f measuredWAL) Write(data []byte) (int, error) { + n, err := f.File.Write(data) + Count("pebble_wal_written_bytes", uint64(max(0, n))) + return n, errors.WithStack(err) +} +func (f measuredWAL) Sync() error { + err := f.File.Sync() + if err == nil { + Count("pebble_wal_sync_successes", 1) + } + return errors.WithStack(err) +} +func (f measuredWAL) SyncData() error { + err := f.File.SyncData() + if err == nil { + Count("pebble_wal_sync_successes", 1) + } + return errors.WithStack(err) +} +func (f measuredWAL) SyncTo(length int64) (bool, error) { + full, err := f.File.SyncTo(length) + if err == nil && full { + Count("pebble_wal_sync_successes", 1) + } + return full, errors.WithStack(err) +} diff --git a/internal/casbenchmark/meter/fs_test.go b/internal/casbenchmark/meter/fs_test.go new file mode 100644 index 000000000..bf0024015 --- /dev/null +++ b/internal/casbenchmark/meter/fs_test.go @@ -0,0 +1,38 @@ +package meter + +import ( + "testing" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2/vfs" + "github.com/stretchr/testify/require" +) + +type failingSync struct{ vfs.File } + +func (failingSync) Sync() error { return errors.New("injected sync failure") } + +func TestWALMeterPreservesWritesAndOnlyCountsCompletedSyncs(t *testing.T) { + t.Setenv("ELASTICKV_CAS_BENCH_PREPARE", "") + require.True(t, Begin(t.Name())) + t.Cleanup(func() { End(t.Name()) }) + fs := WrapFS(vfs.NewMem()) + file, err := fs.Create("000001.log", vfs.WriteCategoryUnspecified) + require.NoError(t, err) + t.Cleanup(func() { _ = file.Close() }) + n, err := file.Write([]byte("record")) + require.NoError(t, err) + require.Equal(t, 6, n) + require.NoError(t, file.Sync()) + require.NoError(t, file.SyncData()) + failed := measuredWAL{File: failingSync{File: file}} + require.ErrorContains(t, failed.Sync(), "injected") + other, err := fs.Create("MANIFEST-000001", vfs.WriteCategoryUnspecified) + require.NoError(t, err) + t.Cleanup(func() { _ = other.Close() }) + require.NoError(t, other.Sync()) + result, ok := End(t.Name()) + require.True(t, ok) + require.Equal(t, uint64(6), result.Counters["pebble_wal_written_bytes"]) + require.Equal(t, uint64(2), result.Counters["pebble_wal_sync_successes"]) +} diff --git a/internal/casbenchmark/meter/meter.go b/internal/casbenchmark/meter/meter.go new file mode 100644 index 000000000..8924f4d23 --- /dev/null +++ b/internal/casbenchmark/meter/meter.go @@ -0,0 +1,153 @@ +// Package meter supplies counters for explicitly instrumented benchmark builds. +// Normal server builds do not import this package. +package meter + +import ( + "context" + "os" + "runtime" + "sync" + "sync/atomic" + "syscall" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/stats" +) + +type sample struct { + name string + started time.Time + before runtime.MemStats + cpu syscall.Rusage + cpuValid bool + mu sync.RWMutex + counters sync.Map +} + +type Result struct { + StartedUTC time.Time `json:"started_utc"` + CASMode string `json:"cas_mode"` + Name string `json:"name"` + ElapsedNS int64 `json:"elapsed_ns"` + AllocBytes uint64 `json:"alloc_bytes"` + Mallocs uint64 `json:"mallocs"` + GCPauseNS uint64 `json:"gc_pause_ns"` + HeapBytes uint64 `json:"heap_bytes"` + CPUMicros int64 `json:"cpu_micros"` + CPUValid bool `json:"cpu_valid"` + Counters map[string]uint64 `json:"counters"` + InFlight int64 `json:"in_flight"` +} + +var active atomic.Pointer[sample] +var windows sync.Mutex +var inFlight atomic.Int64 +var adaptiveCAS atomic.Bool + +// ApplyOnlyCAS preserves the old path only in an explicitly instrumented build. +func ApplyOnlyCAS() bool { return os.Getenv("ELASTICKV_CAS_BENCH_APPLY_ONLY") == "1" } + +func EnableAdaptiveCAS() { adaptiveCAS.Store(true) } + +func casMode() string { + if adaptiveCAS.Load() { + return "adaptive-precheck-key-admission-follower-batch" + } + return "apply-only" +} + +func InFlight() int64 { return inFlight.Load() } + +// Preparing only applies to the disposable legacy baseline fixture. The +// measurement gate refuses this mode; protected measured nodes use normal +// lease renewal and shutdown behavior. +func Preparing() bool { return os.Getenv("ELASTICKV_CAS_BENCH_PREPARE") == "1" } + +// Begin refuses to replace an unfinished window. +func Begin(name string) bool { + windows.Lock() + defer windows.Unlock() + if Preparing() || name == "" || len(name) > 128 || active.Load() != nil { + return false + } + s := &sample{name: name, started: time.Now()} + runtime.ReadMemStats(&s.before) + s.cpuValid = syscall.Getrusage(syscall.RUSAGE_SELF, &s.cpu) == nil + active.Store(s) + return true +} + +func End(name string) (Result, bool) { + windows.Lock() + defer windows.Unlock() + s := active.Load() + if s == nil || s.name != name { + return Result{}, false + } + s.mu.Lock() + defer s.mu.Unlock() + active.Store(nil) + var after runtime.MemStats + runtime.ReadMemStats(&after) + r := Result{StartedUTC: s.started.UTC(), CASMode: casMode(), Name: name, ElapsedNS: time.Since(s.started).Nanoseconds(), + AllocBytes: after.TotalAlloc - s.before.TotalAlloc, Mallocs: after.Mallocs - s.before.Mallocs, + GCPauseNS: after.PauseTotalNs - s.before.PauseTotalNs, HeapBytes: after.HeapAlloc, + Counters: make(map[string]uint64)} + var usage syscall.Rusage + if s.cpuValid && syscall.Getrusage(syscall.RUSAGE_SELF, &usage) == nil { + r.CPUValid = true + r.CPUMicros = (usage.Utime.Nano() + usage.Stime.Nano() - s.cpu.Utime.Nano() - s.cpu.Stime.Nano()) / int64(time.Microsecond) + } + s.counters.Range(func(key, value any) bool { + name, validName := key.(string) + count, validCount := value.(*atomic.Uint64) + if validName && validCount { + r.Counters[name] = count.Load() + } + return true + }) + return r, true +} + +// Count includes background activity during the same wall-clock window. +// Counters are not claimed to be a per-request causal trace. +func Count(name string, value uint64) { + if s := active.Load(); s != nil { + s.mu.RLock() + defer s.mu.RUnlock() + if active.Load() != s { + return + } + count, found := s.counters.Load(name) + if !found { + count, _ = s.counters.LoadOrStore(name, new(atomic.Uint64)) + } + if counter, ok := count.(*atomic.Uint64); ok { + counter.Add(value) + } + } +} + +func Unary(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) { + if info.FullMethod != "/benchmark.FencedOnePhase/Window" { + inFlight.Add(1) + defer inFlight.Add(-1) + } + Count(info.FullMethod, 1) + return next(ctx, req) +} + +type WireStats struct{} + +func (WireStats) TagRPC(ctx context.Context, _ *stats.RPCTagInfo) context.Context { return ctx } +func (WireStats) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context { return ctx } +func (WireStats) HandleConn(context.Context, stats.ConnStats) {} +func (WireStats) HandleRPC(_ context.Context, event stats.RPCStats) { + switch payload := event.(type) { + case *stats.InPayload: + Count("grpc_receive_wire_bytes", uint64(max(payload.WireLength, 0))) + case *stats.OutPayload: + Count("grpc_send_wire_bytes", uint64(max(payload.WireLength, 0))) + } +} diff --git a/internal/casbenchmark/meter/meter_test.go b/internal/casbenchmark/meter/meter_test.go new file mode 100644 index 000000000..f58b2aceb --- /dev/null +++ b/internal/casbenchmark/meter/meter_test.go @@ -0,0 +1,69 @@ +package meter + +import ( + "sync" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestWindowTransitionsAndConcurrentCounts(t *testing.T) { + t.Setenv("ELASTICKV_CAS_BENCH_PREPARE", "") + require.False(t, Begin("")) + require.True(t, Begin(t.Name())) + t.Cleanup(func() { End(t.Name()) }) + require.False(t, Begin("replacement")) + _, ok := End("wrong") + require.False(t, ok) + const workers = 8 + const increments = 1000 + var wg sync.WaitGroup + for range workers { + wg.Go(func() { + for range increments { + Count("test", 1) + } + }) + } + wg.Wait() + result, ok := End(t.Name()) + require.True(t, ok) + require.Equal(t, uint64(workers*increments), result.Counters["test"]) + require.Positive(t, result.ElapsedNS) + require.False(t, result.StartedUTC.IsZero()) + require.Equal(t, "UTC", result.StartedUTC.Location().String()) + require.True(t, result.CPUValid) + Count("outside", 1) + require.True(t, Begin("next")) + result, ok = End("next") + require.True(t, ok) + require.Empty(t, result.Counters) +} + +func TestPreparationCannotProduceMeasurement(t *testing.T) { + t.Setenv("ELASTICKV_CAS_BENCH_PREPARE", "1") + require.True(t, Preparing()) + require.False(t, Begin(t.Name())) + _, ok := End(t.Name()) + require.False(t, ok) +} + +func TestAdaptiveCASModeIsExplicit(t *testing.T) { + adaptiveCAS.Store(false) + t.Cleanup(func() { adaptiveCAS.Store(false) }) + require.Equal(t, "apply-only", casMode()) + t.Setenv("ELASTICKV_CAS_BENCH_APPLY_ONLY", "1") + require.True(t, ApplyOnlyCAS()) + t.Setenv("ELASTICKV_CAS_BENCH_APPLY_ONLY", "") + require.False(t, ApplyOnlyCAS()) + EnableAdaptiveCAS() + require.Equal(t, "adaptive-precheck-key-admission-follower-batch", casMode()) +} + +func TestSteadyCounterDoesNotAllocate(t *testing.T) { + t.Setenv("ELASTICKV_CAS_BENCH_PREPARE", "") + require.True(t, Begin(t.Name())) + t.Cleanup(func() { End(t.Name()) }) + Count("known", 1) + require.Zero(t, testing.AllocsPerRun(100, func() { Count("known", 1) })) +} diff --git a/internal/casbenchmark/seed.go b/internal/casbenchmark/seed.go new file mode 100644 index 000000000..5e324dc41 --- /dev/null +++ b/internal/casbenchmark/seed.go @@ -0,0 +1,113 @@ +package casbenchmark + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "strings" + + "github.com/bootjp/elastickv/kv" + "github.com/cockroachdb/errors" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +const MaxSeedKeys = 256 +const MaxKeys = 65536 +const maxSeedWireBytes = 64 * 1024 +const keyDigits = 6 + +type SeedRequest struct { + Prefix string `json:"prefix"` + First uint32 `json:"first"` + Count uint32 `json:"count"` + Value []byte `json:"value"` +} + +type SeedResponse struct { + CommitTS uint64 `json:"commit_ts,string"` +} + +func (r SeedRequest) validate() error { + if !strings.HasPrefix(r.Prefix, "bench1535/") || !strings.HasSuffix(r.Prefix, "/") || len(r.Prefix) > maxKeyBytes-keyDigits { + return errors.WithStack(status.Error(codes.InvalidArgument, "invalid seed key prefix")) + } + if r.Count == 0 || r.Count > MaxSeedKeys || r.First > MaxKeys-r.Count || len(r.Value) > maxValueBytes { + return errors.WithStack(status.Error(codes.InvalidArgument, "invalid seed batch bounds")) + } + return nil +} + +func (f *Frontend) seed(server any, ctx context.Context, decode func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) { + req := new(wrapperspb.BytesValue) + if err := decode(req); err != nil { + return nil, errors.WithStack(err) + } + next := func(ctx context.Context, _ any) (any, error) { + return f.owned(ctx, func(owned context.Context) (any, error) { + input, err := parseSeed(req.Value) + if err != nil { + return nil, err + } + response, err := f.seedCore(owned, input) + if err != nil { + return nil, err + } + body, err := json.Marshal(response) + if err != nil { + return nil, errors.WithStack(err) + } + return wrapperspb.Bytes(body), nil + }) + } + if interceptor == nil { + return next(ctx, req) + } + return interceptor(ctx, req, &grpc.UnaryServerInfo{Server: server, FullMethod: Prefix + "Seed"}, next) +} + +func parseSeed(body []byte) (SeedRequest, error) { + var input SeedRequest + if len(body) > maxSeedWireBytes { + return input, errors.WithStack(status.Error(codes.InvalidArgument, "seed request too large")) + } + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil { + return input, errors.WithStack(status.Error(codes.InvalidArgument, "invalid seed request")) + } + var extra any + if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { + return input, errors.WithStack(status.Error(codes.InvalidArgument, "trailing seed data")) + } + return input, input.validate() +} + +func (f *Frontend) seedCore(ctx context.Context, input SeedRequest) (SeedResponse, error) { + r := kv.NewReadRequest(ctx, f.coord, f.store, f.tracker) + defer r.Close() + keys := make([][]byte, 0, input.Count) + elems := make([]*kv.Elem[kv.OP], 0, input.Count) + for index := input.First; index < input.First+input.Count; index++ { + key := []byte(fmt.Sprintf("%s%06d", input.Prefix, index)) + keys = append(keys, key) + elems = append(elems, &kv.Elem[kv.OP]{Op: kv.Put, Key: key, Value: input.Value}) + } + snapshot, err := r.Latest(r.Context(), "benchmark seed", keys...) + if err != nil { + return SeedResponse{}, errors.WithStack(err) + } + stamp := snapshot.TransactionTimestamp() + reply, err := kv.DispatchWithLeaderIssuedCommitTS(stamp.WithDispatchVoucher(r.Context()), f.coord, &kv.OperationGroup[kv.OP]{IsTxn: true, StartTS: stamp.Timestamp(), Elems: elems}) + if err != nil { + return SeedResponse{}, submissionError(err) + } + if reply == nil || reply.CommitTS == 0 { + return SeedResponse{}, errors.WithStack(status.Error(codes.Unknown, "missing seed commit proof")) + } + return SeedResponse{CommitTS: reply.CommitTS}, nil +} diff --git a/internal/casbenchmark/seed_test.go b/internal/casbenchmark/seed_test.go new file mode 100644 index 000000000..e784cef9f --- /dev/null +++ b/internal/casbenchmark/seed_test.go @@ -0,0 +1,34 @@ +package casbenchmark + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSeedBoundariesAreStrict(t *testing.T) { + t.Parallel() + valid := SeedRequest{Prefix: "bench1535/test/", First: MaxKeys - MaxSeedKeys, Count: MaxSeedKeys, Value: []byte("v")} + body, err := json.Marshal(valid) + require.NoError(t, err) + decoded, err := parseSeed(body) + require.NoError(t, err) + require.Equal(t, valid, decoded) + for name, change := range map[string]func(*SeedRequest){ + "private": func(r *SeedRequest) { r.Prefix = "private/" }, + "no slash": func(r *SeedRequest) { r.Prefix = "bench1535/test" }, + "empty": func(r *SeedRequest) { r.Count = 0 }, + "oversized": func(r *SeedRequest) { r.Count++ }, + "past end": func(r *SeedRequest) { r.First++ }, + "overflow": func(r *SeedRequest) { r.First = ^uint32(0) }, + "value": func(r *SeedRequest) { r.Value = make([]byte, maxValueBytes+1) }, + } { + t.Run(name, func(t *testing.T) { input := valid; change(&input); require.Error(t, input.validate()) }) + } + for _, invalid := range []string{string(body) + "{}", `{"prefix":"bench1535/test/","count":1,"unknown":true}`, strings.Repeat(" ", maxSeedWireBytes+1)} { + _, err := parseSeed([]byte(invalid)) + require.Error(t, err) + } +} diff --git a/internal/clusterbootstrap/encrypted_payload.go b/internal/clusterbootstrap/encrypted_payload.go index 934fdbbb1..cc892dd28 100644 --- a/internal/clusterbootstrap/encrypted_payload.go +++ b/internal/clusterbootstrap/encrypted_payload.go @@ -7,6 +7,7 @@ import ( "github.com/bootjp/elastickv/internal/encryption" "github.com/bootjp/elastickv/internal/raftadmission" "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" "github.com/cockroachdb/errors" ) @@ -65,9 +66,10 @@ func (p BootstrapPayloadProjection) validate(group uint64) error { } type bootstrapPayloadValidation struct { - FinalDigest [sha256.Size]byte - PlaintextDigest [sha256.Size]byte - ProjectionGeneration uint64 + RequiresVersionCASProof bool + FinalDigest [sha256.Size]byte + PlaintextDigest [sha256.Size]byte + ProjectionGeneration uint64 } // Validate OUTSIDE A against a pinned installed projection. Seal the ACTUAL @@ -97,7 +99,7 @@ func ValidateBootstrapFinalPayload(cluster raftbootstrap.UUID, kind raftadmissio if kind == raftadmission.Rotation && !projection.authorizesRotation(plain) { return zero, errors.Join(ErrBootstrapAdmissionPayload, ErrBootstrapRotationRecipe) } - return bootstrapPayloadValidation{FinalDigest: sha256.Sum256(final), PlaintextDigest: sha256.Sum256(plain), ProjectionGeneration: projection.Generation}, nil + return bootstrapPayloadValidation{FinalDigest: sha256.Sum256(final), PlaintextDigest: sha256.Sum256(plain), ProjectionGeneration: projection.Generation, RequiresVersionCASProof: raftengine.RequiresVersionCASProof(plain)}, nil } func (p BootstrapPayloadProjection) Plaintext(final []byte) ([]byte, error) { diff --git a/internal/clusterbootstrap/encryption_domain.go b/internal/clusterbootstrap/encryption_domain.go index a71f0c866..899214d3d 100644 --- a/internal/clusterbootstrap/encryption_domain.go +++ b/internal/clusterbootstrap/encryption_domain.go @@ -8,6 +8,7 @@ import ( "github.com/bootjp/elastickv/internal/noderuntime" "github.com/bootjp/elastickv/internal/raftadmission" "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" "github.com/bootjp/elastickv/kv" pb "github.com/bootjp/elastickv/proto" "github.com/cockroachdb/errors" @@ -157,7 +158,7 @@ func (d *BootstrapDomain) InspectPayload(kind raftadmission.Kind, group uint64, if err := BootstrapPayloadValidator(d.cluster)(kind, group, final); err != nil { return zero, err } - return raftadmission.PayloadInspection{PlaintextDigest: sha256.Sum256(final)}, nil + return raftadmission.PayloadInspection{PlaintextDigest: sha256.Sum256(final), RequiresVersionCASProof: raftengine.RequiresVersionCASProof(final)}, nil } if kind == raftadmission.Rotation && recipe == (raftbootstrap.Digest{}) { return zero, errors.WithStack(ErrBootstrapRotationRecipe) @@ -172,7 +173,7 @@ func (d *BootstrapDomain) InspectPayload(kind raftadmission.Kind, group uint64, if err != nil { return zero, err } - return raftadmission.PayloadInspection{PlaintextDigest: proof.PlaintextDigest, ProjectionGeneration: proof.ProjectionGeneration}, nil + return raftadmission.PayloadInspection{PlaintextDigest: proof.PlaintextDigest, ProjectionGeneration: proof.ProjectionGeneration, RequiresVersionCASProof: proof.RequiresVersionCASProof}, nil } func (d *BootstrapDomain) loadEncryptionPayloadProjection(id uint64, recipe raftbootstrap.Digest) (BootstrapPayloadProjection, error) { diff --git a/internal/clusterbootstrap/group_runtime.go b/internal/clusterbootstrap/group_runtime.go index 50f5c7eb9..a6da1ea83 100644 --- a/internal/clusterbootstrap/group_runtime.go +++ b/internal/clusterbootstrap/group_runtime.go @@ -3,6 +3,7 @@ package clusterbootstrap import ( "github.com/bootjp/elastickv/internal/noderuntime" "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/kv" ) // GroupRuntime is a Raft group's runtime plus the protected-bootstrap @@ -13,6 +14,8 @@ type GroupRuntime struct { BootstrapDomain *BootstrapDomain BootstrapPeerConfig *BootstrapPeerConfig BootstrapNetwork *BootstrapNetwork + VersionCASCapable bool + VersionCASAdmission kv.VersionCASAdmission } // snapshotEngine is GroupRuntime.SnapshotEngine, nil-safe on the wrapper. diff --git a/internal/clusterbootstrap/network.go b/internal/clusterbootstrap/network.go index 0b37f8b57..5eec20f49 100644 --- a/internal/clusterbootstrap/network.go +++ b/internal/clusterbootstrap/network.go @@ -107,6 +107,21 @@ func (n *BootstrapNetwork) target(address string) (bootstrapNetworkTarget, error return target, err } +// HasStableConfiguration checks the protected projection, whose ConfState +// includes outgoing voters that are absent from the ordinary engine listing. +func (n *BootstrapNetwork) HasStableConfiguration(group, index uint64) bool { + local, ok := n.Control.groups[group] + if !ok { + return false + } + projection, ok := local.owner.GroupProjection(group) + if !ok || projection.Configuration.Index != index || projection.Pending != peersession.PendingClear { + return false + } + conf := projection.Configuration.State + return len(conf.VotersOutgoing) == 0 && len(conf.LearnersNext) == 0 && !conf.AutoLeave +} + func (n *BootstrapNetwork) DialOptions(address string) ([]grpc.DialOption, error) { target, err := n.target(address) if err != nil { diff --git a/internal/clusterbootstrap/payload.go b/internal/clusterbootstrap/payload.go index 5c5e330a2..c502db284 100644 --- a/internal/clusterbootstrap/payload.go +++ b/internal/clusterbootstrap/payload.go @@ -7,6 +7,7 @@ import ( "github.com/bootjp/elastickv/internal/encryption/fsmwire" "github.com/bootjp/elastickv/internal/raftadmission" "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" "github.com/bootjp/elastickv/kv" pb "github.com/bootjp/elastickv/proto" "github.com/cockroachdb/errors" @@ -166,13 +167,15 @@ func validateBootstrapDataPayload(payload []byte) error { if _, matched, err := kv.DecodeWatermarkAdvance(payload); matched { return errors.Wrap(err, "decode data read watermark") } + if bytes.Equal(payload, kv.EncodeMigrationVersionIdentityActivation()) { + return nil + } + if raftengine.IsVersionCASRaftPayload(payload) { + return validateBootstrapVersionCASPayload(payload) + } switch payload[0] { case BootstrapPayloadSingle: - var request pb.Request - if err := decodeBootstrapAdmissionProto(payload[1:], &request); err != nil { - return err - } - return validateBootstrapKVRequest(&request) + return validateBootstrapKVSingle(payload[1:]) case BootstrapPayloadBatch: return validateBootstrapKVBatch(payload[1:]) case BootstrapPayloadBackup: @@ -184,12 +187,34 @@ func validateBootstrapDataPayload(payload []byte) error { } } +func validateBootstrapKVSingle(body []byte) error { + var request pb.Request + if err := decodeBootstrapAdmissionProto(body, &request); err != nil { + return err + } + if kv.HasCASMutation([]*pb.Request{&request}) { + return errors.WithStack(ErrBootstrapAdmissionPayload) + } + return validateBootstrapKVRequest(&request) +} + +func validateBootstrapVersionCASPayload(payload []byte) error { + request, err := kv.DecodeVersionCASRaftPayload(payload) + if err != nil { + return errors.WithStack(err) + } + if err := decodeBootstrapAdmissionProto(payload[len(raftengine.VersionCASFrame):], request); err != nil { + return err + } + return validateBootstrapKVRequest(request) +} + func validateBootstrapKVBatch(payload []byte) error { var command pb.RaftCommand if err := decodeBootstrapAdmissionProto(payload, &command); err != nil { return err } - if len(command.Requests) == 0 { + if len(command.Requests) == 0 || kv.HasCASMutation(command.Requests) { return errors.WithStack(ErrBootstrapAdmissionPayload) } for _, request := range command.Requests { diff --git a/internal/clusterbootstrap/startup_gate.go b/internal/clusterbootstrap/startup_gate.go index cb9678e37..3ee72dd4f 100644 --- a/internal/clusterbootstrap/startup_gate.go +++ b/internal/clusterbootstrap/startup_gate.go @@ -147,7 +147,7 @@ func (g *StartupPublicKVGate) Blocked() bool { func startupRotationGatedMethod(fullMethod string) bool { switch fullMethod { - case pb.Internal_Forward_FullMethodName, + case pb.Internal_Forward_FullMethodName, pb.Internal_ForwardCompareAndSwap_FullMethodName, pb.Internal_ForwardCompareAndSwapV2_FullMethodName, pb.Internal_ApplyTargetStagedReadiness_FullMethodName, pb.Internal_ImportRangeVersions_FullMethodName, pb.Internal_PromoteStagedVersions_FullMethodName, diff --git a/internal/clusterbootstrap/tso.go b/internal/clusterbootstrap/tso.go index 00c374220..d1ec594d8 100644 --- a/internal/clusterbootstrap/tso.go +++ b/internal/clusterbootstrap/tso.go @@ -16,7 +16,7 @@ import ( "github.com/cockroachdb/pebble/v2/vfs" ) -const DedicatedTSOControlStoreName = "tso-control.db" +const DedicatedTSOControlStoreName = etcd.DedicatedTSOControlStoreName // Proposed shared startup seam: recovery needs an identity/boundary-bound policy // loader, not an MVCC data store. The existing shared startup remains unchanged; diff --git a/internal/clusterbootstrap/tso_baseline.go b/internal/clusterbootstrap/tso_baseline.go index e7f8c06c1..b6c9c797a 100644 --- a/internal/clusterbootstrap/tso_baseline.go +++ b/internal/clusterbootstrap/tso_baseline.go @@ -204,11 +204,11 @@ func ProbeOfflineTSOBaseline(ctx context.Context, dataDir string, ownership io.C } // InitializePreparedTSOBaseline is an EXPLICIT migration transformation under -// native offline ownership, after its immutable source backup. Only the fixed -// new control-store root may change. Existing roots are accepted solely after -// exact full-image comparison with the expected scalar+preparation transaction. +// native offline ownership, after its immutable source backup. Creating the +// control store also creates its stable sibling lifecycle lock. Completed roots +// must match the expected scalar and preparation transaction in full. // The native preparation callback must still verify its original source backup -// and all files outside this root before exchanging the WAL. +// and the immutable source tree before exchanging the WAL. func InitializePreparedTSOBaseline(ctx context.Context, dataDir string, state kv.TSOBaselineState, prepared kv.PreparedBootstrapActivation) (raftbootstrap.Digest, error) { if err := validateTSOBaselinePreparation(ctx, state, prepared); err != nil { return raftbootstrap.Digest{}, err @@ -244,6 +244,13 @@ func resumePreparedTSOStore(ctx context.Context, path string, state kv.TSOBaseli // A crash before the single batch may leave an empty Pebble directory. Only // that exact logical prefix may be completed; no metadata row is filtered out. func emptyPreparedTSOStore(path string) (empty bool, err error) { + // A stop after creating the DB directory or lifecycle lock can precede + // creation of Pebble's first file. Only a literally empty directory + // qualifies for this prefix without a successful read-only Pebble open. + entries, err := os.ReadDir(path) + if err != nil || len(entries) == 0 { + return err == nil, errors.WithStack(err) + } db, err := pebble.Open(path, &pebble.Options{ReadOnly: true}) if err != nil { return false, errors.WithStack(err) @@ -316,7 +323,8 @@ func VerifyPreparedTSOBaseline(ctx context.Context, path string, state kv.TSOBas return raftbootstrap.Digest{}, errors.WithStack(err) } defer func() { _ = os.RemoveAll(temporary) }() - expected, err := createPreparedTSOStore(ctx, temporary, state, prepared) + // Keep the reference DB and its sibling lifecycle lock in the private tree. + expected, err := createPreparedTSOStore(ctx, filepath.Join(temporary, DedicatedTSOControlStoreName), state, prepared) if err != nil { return raftbootstrap.Digest{}, err } diff --git a/internal/filesystem/fstest/memory.go b/internal/filesystem/fstest/memory.go index 2be140d54..dcead5d1c 100644 --- a/internal/filesystem/fstest/memory.go +++ b/internal/filesystem/fstest/memory.go @@ -62,6 +62,9 @@ func (d *MemoryDispatcher) Dispatch( func memoryMutations(elems []*kv.Elem[kv.OP], commitTS uint64) ([]*store.KVPairMutation, error) { mutations := make([]*store.KVPairMutation, 0, len(elems)) for _, elem := range elems { + if elem.ExpectedCommitTS != 0 { + return nil, errors.WithStack(kv.ErrVersionCASUnavailable) + } value := append([]byte(nil), elem.Value...) if elem.CommitTSValueOffset != 0 { if len(value) < commitTimestampBytes || elem.CommitTSValueOffset > uint64(len(value)-commitTimestampBytes) { @@ -74,15 +77,17 @@ func memoryMutations(elems []*kv.Elem[kv.OP], commitTS uint64) ([]*store.KVPairM mutations = append(mutations, &store.KVPairMutation{ Op: store.OpTypePut, Key: append([]byte(nil), elem.Key...), Value: value, }) + continue case kv.Del: mutations = append(mutations, &store.KVPairMutation{ Op: store.OpTypeDelete, Key: append([]byte(nil), elem.Key...), }) + continue + case kv.CompareAndSwap: + return nil, errors.WithStack(kv.ErrVersionCASUnavailable) case kv.DelPrefix: - return nil, errors.WithStack(store.ErrUnknownOp) - default: - return nil, errors.WithStack(store.ErrUnknownOp) } + return nil, errors.WithStack(store.ErrUnknownOp) } return mutations, nil } diff --git a/internal/filesystem/fuseadapter/mount_e2e_test.go b/internal/filesystem/fuseadapter/mount_e2e_test.go index f4a1eabc9..6971d7042 100644 --- a/internal/filesystem/fuseadapter/mount_e2e_test.go +++ b/internal/filesystem/fuseadapter/mount_e2e_test.go @@ -381,7 +381,7 @@ func TestKernelMountReaddirPagesLargeDirectory(t *testing.T) { want := make([]string, 0, count) for i := range count { name := "entry-" + strconv.Itoa(i) - require.NoError(t, os.WriteFile(filepath.Join(mountPoint, name), nil, 0o600)) + createSyncedEmptyMountEntry(t, filepath.Join(mountPoint, name)) want = append(want, name) } sort.Strings(want) @@ -395,6 +395,23 @@ func TestKernelMountReaddirPagesLargeDirectory(t *testing.T) { require.Equal(t, want, names) } +func createSyncedEmptyMountEntry(t *testing.T, path string) { + t.Helper() + file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + require.NoError(t, err) + closeOnce := closeCreatedDescriptor(t, file) + // The kernel can interrupt FLUSH even after successful creation. Establish + // durability before close, and never retry a descriptor already released + // by Linux. Other close errors still fail this test. + require.NoError(t, file.Sync()) + if err := closeOnce(); !errors.Is(err, syscall.EINTR) { + require.NoError(t, err) + } + info, err := os.Stat(path) + require.NoError(t, err) + require.Zero(t, info.Size()) +} + func TestKernelMountUnlinkWhileOpenKeepsDataReadable(t *testing.T) { // Not parallel: it reaches a real FUSE kernel mount. Concurrent mounts // hung the race shard on Linux CI past the 30m test timeout. diff --git a/internal/filesystem/operation_crash_test.go b/internal/filesystem/operation_crash_test.go index 6885f2067..2835f918b 100644 --- a/internal/filesystem/operation_crash_test.go +++ b/internal/filesystem/operation_crash_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "syscall" "testing" + "time" "github.com/bootjp/elastickv/kv" "github.com/bootjp/elastickv/store" @@ -118,7 +119,7 @@ func runOperationDecisionCrashHelper(t *testing.T, dir string) { require.NoError(t, err) require.NoError(t, fileOnDisk.Sync()) require.NoError(t, fileOnDisk.Close()) - require.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGKILL)) + killOperationCrashChild(t) } func TestJournalGenerationFenceSurvivesProcessKill(t *testing.T) { @@ -190,7 +191,7 @@ func runOperationFenceCrashHelper(t *testing.T, dir string) { require.NoError(t, err) require.NoError(t, fileOnDisk.Sync()) require.NoError(t, fileOnDisk.Close()) - require.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGKILL)) + killOperationCrashChild(t) } func TestJournalReceiptsSurviveProcessKill(t *testing.T) { @@ -263,5 +264,14 @@ func runOperationCrashHelper(t *testing.T, dir string) { require.NoError(t, fileOnDisk.Sync()) require.NoError(t, fileOnDisk.Close()) // Kill without closing Pebble or running test cleanup. + killOperationCrashChild(t) +} + +func killOperationCrashChild(t *testing.T) { + t.Helper() require.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGKILL)) + // Delivery may lag the syscall return. Do not let the test runner exit + // successfully before the pending signal actually terminates this child. + time.Sleep(10 * time.Second) + t.Fatal("crash child survived SIGKILL") } diff --git a/internal/grpc_forward_auth.go b/internal/grpc_forward_auth.go index f0c58d2cd..ae92f17ed 100644 --- a/internal/grpc_forward_auth.go +++ b/internal/grpc_forward_auth.go @@ -23,7 +23,7 @@ func ConfigureGRPCForwardToken(token string) { } func forwardTokenClientInterceptor(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - if token := grpcForwardToken.Load(); token != nil && method == pb.Internal_Forward_FullMethodName { + if token := grpcForwardToken.Load(); token != nil && (method == pb.Internal_Forward_FullMethodName || method == pb.Internal_ForwardCompareAndSwapV2_FullMethodName) { md, _ := metadata.FromOutgoingContext(ctx) md = md.Copy() md.Delete("authorization") diff --git a/internal/raftadmin/health.go b/internal/raftadmin/health.go index b19de6036..20ca79759 100644 --- a/internal/raftadmin/health.go +++ b/internal/raftadmin/health.go @@ -50,6 +50,7 @@ func RegisterOperationalServicesWithInterceptorAndStaticServing( leaderServiceNames []string, staticServingServiceNames []string, interceptor MembershipChangeInterceptor, + versionCASCapable ...bool, ) { if gs == nil { return @@ -58,7 +59,7 @@ func RegisterOperationalServicesWithInterceptorAndStaticServing( panic("raftadmin: RegisterOperationalServices requires non-nil context") } - pb.RegisterRaftAdminServer(gs, NewServerWithInterceptor(engine, interceptor)) + pb.RegisterRaftAdminServer(gs, NewServerWithInterceptor(engine, interceptor, versionCASCapable...)) healthSrv := health.NewServer() healthpb.RegisterHealthServer(gs, healthSrv) diff --git a/internal/raftadmin/server.go b/internal/raftadmin/server.go index 9749abdd5..0124c2d54 100644 --- a/internal/raftadmin/server.go +++ b/internal/raftadmin/server.go @@ -24,7 +24,8 @@ type Server struct { // proposal through completion. This closes the window where a concurrent // membership RPC could mutate encryption metadata before the engine exposes // the first request's pending configuration change in Status. - membershipMu sync.Mutex + membershipMu sync.Mutex + versionCASCapable bool pb.UnimplementedRaftAdminServer } @@ -38,12 +39,13 @@ func NewServer(engine raftengine.Engine) *Server { // conf-change. See [MembershipChangeInterceptor]. Passing nil is // equivalent to [NewServer] โ€” the pre-step is skipped and the // conf-change runs exactly as the pre-7c posture. -func NewServerWithInterceptor(engine raftengine.Engine, interceptor MembershipChangeInterceptor) *Server { +func NewServerWithInterceptor(engine raftengine.Engine, interceptor MembershipChangeInterceptor, versionCASCapable ...bool) *Server { admin, _ := any(engine).(raftengine.Admin) return &Server{ - engine: engine, - admin: admin, - interceptor: interceptor, + engine: engine, + admin: admin, + interceptor: interceptor, + versionCASCapable: len(versionCASCapable) != 0 && versionCASCapable[0], } } @@ -52,20 +54,24 @@ func (s *Server) Status(context.Context, *pb.RaftAdminStatusRequest) (*pb.RaftAd return nil, grpcStatus(codes.FailedPrecondition, "raft engine is not configured") } current := s.engine.Status() + // Leave the V1 capability unset. V1 proposals use watcher routing. return &pb.RaftAdminStatusResponse{ - State: stateToProto(current.State), - LeaderId: current.Leader.ID, - LeaderAddress: current.Leader.Address, - Term: current.Term, - CommitIndex: current.CommitIndex, - AppliedIndex: current.AppliedIndex, - LastLogIndex: current.LastLogIndex, - LastSnapshotIndex: current.LastSnapshotIndex, - FsmPending: current.FSMPending, - NumPeers: current.NumPeers, - LastContactNanos: current.LastContact.Nanoseconds(), - ConfigurationIndex: current.ConfigurationIndex, - PendingConfChange: current.PendingConfChange, + State: stateToProto(current.State), + LeaderId: current.Leader.ID, + LeaderAddress: current.Leader.Address, + Term: current.Term, + CommitIndex: current.CommitIndex, + AppliedIndex: current.AppliedIndex, + LastLogIndex: current.LastLogIndex, + LastSnapshotIndex: current.LastSnapshotIndex, + FsmPending: current.FSMPending, + NumPeers: current.NumPeers, + LastContactNanos: current.LastContact.Nanoseconds(), + ConfigurationIndex: current.ConfigurationIndex, + PendingConfChange: current.PendingConfChange, + SupportsReplicatedCatalogCas: s.versionCASCapable && current.State != raftengine.StateShutdown, + SupportsVersionRetirement: s.versionCASCapable && current.State != raftengine.StateShutdown, + SupportsVersionAdoption: s.versionCASCapable && current.State != raftengine.StateShutdown, }, nil } diff --git a/internal/raftadmission/arbiter.go b/internal/raftadmission/arbiter.go index 50a4b3ed5..38b70916d 100644 --- a/internal/raftadmission/arbiter.go +++ b/internal/raftadmission/arbiter.go @@ -54,8 +54,9 @@ type Config struct { } type PayloadInspection struct { - PlaintextDigest raftbootstrap.Digest - ProjectionGeneration uint64 + RequiresVersionCASProof bool + PlaintextDigest raftbootstrap.Digest + ProjectionGeneration uint64 } type group struct { diff --git a/internal/raftadmission/operation.go b/internal/raftadmission/operation.go index 61df46b42..ab849f9ad 100644 --- a/internal/raftadmission/operation.go +++ b/internal/raftadmission/operation.go @@ -10,6 +10,7 @@ import ( "github.com/bootjp/elastickv/internal/peersession" "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" "github.com/cockroachdb/errors" ) @@ -296,6 +297,11 @@ func (a *Arbiter) BindProposal(ctx context.Context, id uint64, payload []byte) ( if err != nil { return nil, errors.WithStack(err) } + if inspection.RequiresVersionCASProof { + if _, ok := raftengine.VersionCASProposalProof(ctx); !ok { + return nil, errors.WithStack(raftengine.ErrVersionCASUnavailable) + } + } digest := sha256.Sum256(payload) a.mu.Lock() defer a.mu.Unlock() diff --git a/internal/raftbootstrap/policy.go b/internal/raftbootstrap/policy.go index 11f20664c..0afdf5e1a 100644 --- a/internal/raftbootstrap/policy.go +++ b/internal/raftbootstrap/policy.go @@ -13,6 +13,8 @@ import ( const ( policyMagic = "EKVBP001" PolicyVersion uint32 = 1 + PolicyRetirementVersion uint32 = 2 + PolicyAdoptionVersion uint32 = 3 policyFrameOverhead = len(policyMagic) + 4 + 4 + checksumSize policyHeaderSize = len(policyMagic) + 4 + 4 policyGenerationMinimum = 2 @@ -120,7 +122,7 @@ func canonicalPolicy(in PolicyRecord) (PolicyRecord, error) { } func validatePolicyHeader(in PolicyRecord) error { - if in.Version != PolicyVersion { + if in.Version < PolicyVersion || in.Version > PolicyAdoptionVersion { return errors.WithStack(ErrUnsupported) } if in.Identity.Cluster == (UUID{}) || in.BaselineDigest == (Digest{}) || @@ -214,7 +216,7 @@ func ValidateReservationTransition(previous, next PolicyRecord) error { } func sameReservationBase(old, updated PolicyRecord) bool { - return old.Reservation == nil && updated.Reservation != nil && + return old.Version == updated.Version && old.Reservation == nil && updated.Reservation != nil && old.LastConfigurationIndex == updated.LastConfigurationIndex && sameConfiguration(old.Configuration, updated.Configuration) && slices.Equal(old.RetiredMemberIDs, updated.RetiredMemberIDs) && @@ -279,7 +281,7 @@ func validateTerminalRetiredMembers(old, updated PolicyRecord, outcome Membershi } func samePolicyLineage(old, updated PolicyRecord) bool { - return old.Identity == updated.Identity && old.BaselineDigest == updated.BaselineDigest && + return old.Version == updated.Version && old.Identity == updated.Identity && old.BaselineDigest == updated.BaselineDigest && old.Minimum == updated.Minimum && old.ActivationIndex == updated.ActivationIndex && updated.Generation == old.Generation+1 } @@ -618,7 +620,7 @@ func MarshalPolicyRecord(policy PolicyRecord) ([]byte, error) { } w := &encoder{limit: MaxFileSize} w.appendString(policyMagic) - w.fixed(PolicyVersion) + w.fixed(policy.Version) w.length(len(body)) w.appendBytes(body) sum := sha256.Sum256(w.Bytes()) @@ -712,7 +714,7 @@ func parsePolicyFrame(data []byte) (uint32, []byte, error) { return 0, nil, errors.WithStack(ErrUnsupported) } version := binary.BigEndian.Uint32(data[len(policyMagic):]) - if version != PolicyVersion { + if version < PolicyVersion || version > PolicyAdoptionVersion { return 0, nil, errors.WithStack(ErrUnsupported) } bodyLen := binary.BigEndian.Uint32(data[len(policyMagic)+4:]) @@ -734,6 +736,12 @@ func PolicyDigest(policy PolicyRecord) (Digest, error) { if err != nil { return Digest{}, err } + if policy.Version == PolicyRetirementVersion { + body = append([]byte("EKV-policy-retirement-v2\x00"), body...) + } + if policy.Version == PolicyAdoptionVersion { + body = append([]byte("EKV-policy-adoption-v3\x00"), body...) + } return sha256.Sum256(body), nil } diff --git a/internal/raftbootstrap/policy_adoption_test.go b/internal/raftbootstrap/policy_adoption_test.go new file mode 100644 index 000000000..12e2ad88a --- /dev/null +++ b/internal/raftbootstrap/policy_adoption_test.go @@ -0,0 +1,30 @@ +package raftbootstrap + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAdoptionReaderFloorRoundTripAndSessionDomain(t *testing.T) { + policy := policyFixture(t) + policy.Reservation = nil + policy.Version = PolicyAdoptionVersion + encoded, err := MarshalPolicyRecord(policy) + require.NoError(t, err) + restored, err := ParsePolicyRecord(encoded) + require.NoError(t, err) + require.Equal(t, PolicyAdoptionVersion, restored.Version) + reencoded, err := MarshalPolicyRecord(restored) + require.NoError(t, err) + require.Equal(t, encoded, reencoded) + digest, err := PolicyDigest(restored) + require.NoError(t, err) + for _, version := range []uint32{PolicyVersion, PolicyRetirementVersion} { + old := restored + old.Version = version + oldDigest, err := PolicyDigest(old) + require.NoError(t, err) + require.NotEqual(t, oldDigest, digest) + } +} diff --git a/internal/raftbootstrap/policy_test.go b/internal/raftbootstrap/policy_test.go index 4e19613bd..4aee0e35f 100644 --- a/internal/raftbootstrap/policy_test.go +++ b/internal/raftbootstrap/policy_test.go @@ -98,7 +98,7 @@ func TestPolicyRecordStrictFrame(t *testing.T) { require.ErrorIs(t, err, ErrInvalid) unknown := bytes.Clone(valid) - binary.BigEndian.PutUint32(unknown[len(policyMagic):], 2) + binary.BigEndian.PutUint32(unknown[len(policyMagic):], PolicyAdoptionVersion+1) rechecksumPolicy(unknown) _, err = ParsePolicyRecord(unknown) require.ErrorIs(t, err, ErrUnsupported) @@ -115,6 +115,28 @@ func rechecksumPolicy(data []byte) { copy(data[len(data)-checksumSize:], sum[:]) } +func TestRetirementReaderPolicyPreservesMandatoryVersion(t *testing.T) { + policy := policyFixture(t) + policy.Reservation = nil + policy.Version = PolicyRetirementVersion + encoded, err := MarshalPolicyRecord(policy) + require.NoError(t, err) + require.Equal(t, uint32(2), binary.BigEndian.Uint32(encoded[len(policyMagic):])) + restored, err := ParsePolicyRecord(encoded) + require.NoError(t, err) + require.Equal(t, PolicyRetirementVersion, restored.Version) + reencoded, err := MarshalPolicyRecord(restored) + require.NoError(t, err) + require.Equal(t, encoded, reencoded) + old := restored + old.Version = PolicyVersion + oldDigest, err := PolicyDigest(old) + require.NoError(t, err) + newDigest, err := PolicyDigest(restored) + require.NoError(t, err) + require.NotEqual(t, oldDigest, newDigest, "reader floor is authenticated in policy/session evidence") +} + func TestPolicyRecordValidation(t *testing.T) { t.Parallel() tests := []struct { @@ -122,7 +144,7 @@ func TestPolicyRecordValidation(t *testing.T) { change func(*PolicyRecord) want error }{ - {"unknown-version", func(p *PolicyRecord) { p.Version = 2 }, ErrUnsupported}, + {"unknown-version", func(p *PolicyRecord) { p.Version = PolicyAdoptionVersion + 1 }, ErrUnsupported}, {"zero-cluster", func(p *PolicyRecord) { p.Identity.Cluster = UUID{} }, ErrInvalid}, {"zero-baseline", func(p *PolicyRecord) { p.BaselineDigest = Digest{} }, ErrInvalid}, {"zero-minimum", func(p *PolicyRecord) { p.Minimum.Entry = 0 }, ErrInvalid}, @@ -266,7 +288,7 @@ func TestValidateReservationTransition(t *testing.T) { change func(*PolicyRecord, *PolicyRecord) want error }{ - {"invalid-previous", func(p, _ *PolicyRecord) { p.Version = 2 }, ErrUnsupported}, + {"invalid-previous", func(p, _ *PolicyRecord) { p.Version = PolicyAdoptionVersion + 1 }, ErrUnsupported}, {"invalid-next", func(_, n *PolicyRecord) { n.Reservation.EvidenceDigest = Digest{} }, ErrInvalid}, {"previous-reserved", func(p, _ *PolicyRecord) { p.Reservation = reservedPrevious }, ErrInvalid}, {"next-unreserved", func(_, n *PolicyRecord) { n.Reservation = nil }, ErrInvalid}, diff --git a/internal/raftengine/append_batch.go b/internal/raftengine/append_batch.go new file mode 100644 index 000000000..5cb238804 --- /dev/null +++ b/internal/raftengine/append_batch.go @@ -0,0 +1,11 @@ +package raftengine + +// AppendBatchClassifier is an optional FSM hint for grouping already-waiting +// follower appends before one synchronous Ready. Implementations inspect only +// the supplied cleartext FSM payload and return true only for known data-only +// commands. Without this hint the engine schedules one message at a time. +// Each message retains its admission checks; WAL persistence, ordered committed +// apply and response dispatch must keep their existing durability boundaries. +type AppendBatchClassifier interface { + IsAppendBatchPayload(payload []byte) bool +} diff --git a/internal/raftengine/etcd/apply_native_configuration.go b/internal/raftengine/etcd/apply_native_configuration.go index 1962df552..e098f4b57 100644 --- a/internal/raftengine/etcd/apply_native_configuration.go +++ b/internal/raftengine/etcd/apply_native_configuration.go @@ -5,8 +5,38 @@ import ( "slices" "github.com/bootjp/elastickv/internal/raftengine" + "github.com/cockroachdb/errors" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" + "go.etcd.io/raft/v3/tracker" ) +// Owner-only immutable roster cache. Never cache progress, term or peer +// addresses. Config changes and incoming snapshots invalidate before mutation. +type nativeConfigurationCache struct { + node *etcdraft.RawNode + index uint64 + config tracker.Config +} + +func (e *Engine) applyNativeTrackerConfig() tracker.Config { + if cached := e.nativeConfigurationCache; cached != nil && cached.node == e.rawNode && cached.index == e.nativeConfigurationIndex { + return cached.config + } + config := e.rawNode.Status().Config + e.nativeConfigurationCache = &nativeConfigurationCache{node: e.rawNode, index: e.nativeConfigurationIndex, config: config} + return config +} + +// Snapshot Step may replace RawNode's roster before its durable configuration +// index is published. Invalidating only at index publication would be too late. +func (e *Engine) stepRawNode(message *raftpb.Message) error { + if message.GetType() == raftpb.MsgSnap || !etcdraft.IsEmptySnap(message.Snapshot) { + e.nativeConfigurationCache = nil + } + return errors.WithStack(e.rawNode.Step(message)) +} + func (e *Engine) deliverApplyNativeConfiguration() func() { return deliverNativeConfiguration(e.fsm, e.captureApplyNativeConfiguration()) } @@ -28,7 +58,7 @@ func (e *Engine) captureApplyNativeConfiguration() *raftengine.NativeConfigurati if e.rawNode == nil || e.recoveredIdentity == nil { return nil } - config := e.rawNode.Status().Config + config := e.applyNativeTrackerConfig() image := raftengine.NativeConfiguration{Index: e.nativeConfigurationIndex, AutoLeave: config.AutoLeave} for id := range config.Voters[0] { image.Voters = append(image.Voters, id) diff --git a/internal/raftengine/etcd/apply_native_configuration_allocation_test.go b/internal/raftengine/etcd/apply_native_configuration_allocation_test.go new file mode 100644 index 000000000..73e631f18 --- /dev/null +++ b/internal/raftengine/etcd/apply_native_configuration_allocation_test.go @@ -0,0 +1,54 @@ +package etcd + +import ( + "testing" + + "github.com/stretchr/testify/require" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" +) + +func nativeConfigurationLeaderWithInflights(t testing.TB) *Engine { + t.Helper() + storage := etcdraft.NewMemoryStorage() + require.NoError(t, storage.ApplySnapshot(&raftpb.Snapshot{Metadata: &raftpb.SnapshotMetadata{ + Index: uint64Ptr(1), Term: uint64Ptr(1), ConfState: &raftpb.ConfState{Voters: []uint64{1, 2, 3}}, + }})) + raw, err := etcdraft.NewRawNode(&etcdraft.Config{ID: 1, Storage: storage, + ElectionTick: 10, HeartbeatTick: 1, MaxInflightMsgs: 1024, MaxSizePerMsg: 1024}) + require.NoError(t, err) + require.NoError(t, raw.Campaign()) + term := raw.BasicStatus().GetTerm() + require.NoError(t, raw.Step(&raftpb.Message{Type: messageTypePtr(raftpb.MsgVoteResp), From: uint64Ptr(2), To: uint64Ptr(1), Term: uint64Ptr(term)})) + require.NoError(t, raw.Step(&raftpb.Message{Type: messageTypePtr(raftpb.MsgVoteResp), From: uint64Ptr(3), To: uint64Ptr(1), Term: uint64Ptr(term)})) + require.Equal(t, etcdraft.StateLeader, raw.BasicStatus().RaftState) + require.NoError(t, raw.Step(&raftpb.Message{Type: messageTypePtr(raftpb.MsgAppResp), From: uint64Ptr(2), To: uint64Ptr(1), Term: uint64Ptr(term), Index: uint64Ptr(2)})) + for range 512 { + require.NoError(t, raw.Propose([]byte("payload"))) + } + require.GreaterOrEqual(t, raw.Status().Progress[2].Inflights.Count(), 512) + return &Engine{rawNode: raw, recoveredIdentity: &WALIdentity{}, nativeConfigurationIndex: 3, + peers: map[uint64]Peer{1: {NodeID: 1, Address: "n1"}, 2: {NodeID: 2, Address: "n2"}, 3: {NodeID: 3, Address: "n3"}}} +} + +func TestNativeConfigurationCaptureDoesNotCloneInflightBuffers(t *testing.T) { + e := nativeConfigurationLeaderWithInflights(t) + require.NotNil(t, e.captureApplyNativeConfiguration()) + result := testing.Benchmark(func(b *testing.B) { + b.ReportAllocs() + for range b.N { + e.captureApplyNativeConfiguration() + } + }) + require.LessOrEqual(t, result.AllocedBytesPerOp(), int64(4096), "configuration capture must not scale with the inflight ring") +} + +func BenchmarkNativeConfigurationCapture(b *testing.B) { + e := nativeConfigurationLeaderWithInflights(b) + e.captureApplyNativeConfiguration() + b.ReportAllocs() + b.ResetTimer() + for range b.N { + e.captureApplyNativeConfiguration() + } +} diff --git a/internal/raftengine/etcd/apply_native_configuration_cache_test.go b/internal/raftengine/etcd/apply_native_configuration_cache_test.go new file mode 100644 index 000000000..b542b0de2 --- /dev/null +++ b/internal/raftengine/etcd/apply_native_configuration_cache_test.go @@ -0,0 +1,83 @@ +package etcd + +import ( + "testing" + + "github.com/stretchr/testify/require" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" +) + +func configurationCacheFixture(t *testing.T) *Engine { + t.Helper() + raw, err := etcdraft.NewRawNode(&etcdraft.Config{ID: 1, Storage: etcdraft.NewMemoryStorage(), ElectionTick: 10, HeartbeatTick: 1, MaxInflightMsgs: 1}) + require.NoError(t, err) + require.NoError(t, raw.Bootstrap([]etcdraft.Peer{{ID: 1}, {ID: 2}})) + return &Engine{rawNode: raw, recoveredIdentity: &WALIdentity{}, nativeConfigurationIndex: 2, + peers: map[uint64]Peer{1: {NodeID: 1, Address: "n1"}, 2: {NodeID: 2, Address: "n2"}, 3: {NodeID: 3, Address: "n3"}}} +} + +func TestNativeConfigurationCacheTracksJointAndLearnerTransitions(t *testing.T) { + t.Parallel() + e := configurationCacheFixture(t) + before := e.captureApplyNativeConfiguration() + _, err := e.applyNativeConfChange(&raftpb.ConfChange{Type: confChangeTypePtr(raftpb.ConfChangeAddLearnerNode), NodeId: uint64Ptr(3)}, 3) + require.NoError(t, err) + learner := e.captureApplyNativeConfiguration() + require.Equal(t, []uint64{3}, learner.Learners) + _, err = e.applyNativeConfChange(&raftpb.ConfChangeV2{Transition: raftpb.ConfChangeTransitionJointExplicit.Enum(), Changes: []*raftpb.ConfChangeSingle{ + {Type: confChangeTypePtr(raftpb.ConfChangeAddNode), NodeId: uint64Ptr(3)}, + {Type: confChangeTypePtr(raftpb.ConfChangeAddLearnerNode), NodeId: uint64Ptr(2)}, + }}, 4) + require.NoError(t, err) + joint := e.captureApplyNativeConfiguration() + require.Equal(t, []uint64{1, 3}, joint.Voters) + require.Equal(t, []uint64{1, 2}, joint.VotersOutgoing) + require.Equal(t, []uint64{2}, joint.LearnersNext) + require.False(t, joint.AutoLeave) + _, err = e.applyNativeConfChange(&raftpb.ConfChangeV2{}, 5) + require.NoError(t, err) + left := e.captureApplyNativeConfiguration() + require.Equal(t, []uint64{1, 3}, left.Voters) + require.Equal(t, []uint64{2}, left.Learners) + require.Empty(t, left.VotersOutgoing) + require.Empty(t, left.LearnersNext) + require.False(t, left.AutoLeave) + require.EqualValues(t, 5, left.Index) + require.Equal(t, []uint64{1, 2}, before.Voters) + require.Empty(t, before.Learners) + left.Voters[0] = 99 + e.peers[1] = Peer{NodeID: 1, Address: "changed"} + again := e.captureApplyNativeConfiguration() + require.Equal(t, []uint64{1, 3}, again.Voters) + require.Equal(t, "changed", again.Members[0].Address, "peer metadata is never cached") + require.Equal(t, "n1", before.Members[0].Address) +} + +func TestNativeConfigurationCacheInvalidatesBeforeSnapshotPublication(t *testing.T) { + t.Parallel() + e := configurationCacheFixture(t) + before := e.captureApplyNativeConfiguration() + require.NoError(t, e.stepRawNode(&raftpb.Message{Type: messageTypePtr(raftpb.MsgSnap), From: uint64Ptr(2), To: uint64Ptr(1), Term: uint64Ptr(3), + Snapshot: &raftpb.Snapshot{Metadata: &raftpb.SnapshotMetadata{Index: uint64Ptr(100), Term: uint64Ptr(2), + ConfState: &raftpb.ConfState{Voters: []uint64{1, 3}, Learners: []uint64{2}}}}})) + after := e.captureApplyNativeConfiguration() + require.EqualValues(t, 2, after.Index, "durable configuration publication has not occurred") + require.Equal(t, []uint64{1, 3}, after.Voters, "the native roster already changed at Snapshot Step") + require.Equal(t, []uint64{2}, after.Learners) + require.Equal(t, []uint64{1, 2}, before.Voters) +} + +func TestNativeConfigurationCacheTracksRawNodeReplacement(t *testing.T) { + t.Parallel() + e := configurationCacheFixture(t) + before := e.captureApplyNativeConfiguration() + replacement, err := etcdraft.NewRawNode(&etcdraft.Config{ID: 1, Storage: etcdraft.NewMemoryStorage(), ElectionTick: 10, HeartbeatTick: 1, MaxInflightMsgs: 1}) + require.NoError(t, err) + require.NoError(t, replacement.Bootstrap([]etcdraft.Peer{{ID: 1}, {ID: 3}})) + e.rawNode = replacement + after := e.captureApplyNativeConfiguration() + require.Equal(t, before.Index, after.Index) + require.Equal(t, []uint64{1, 3}, after.Voters) + require.Equal(t, []uint64{1, 2}, before.Voters) +} diff --git a/internal/raftengine/etcd/bootstrap_baseline_preparation.go b/internal/raftengine/etcd/bootstrap_baseline_preparation.go index bed9eced1..98566468c 100644 --- a/internal/raftengine/etcd/bootstrap_baseline_preparation.go +++ b/internal/raftengine/etcd/bootstrap_baseline_preparation.go @@ -3,6 +3,7 @@ package etcd import ( "context" "crypto/sha256" + "io" "os" "path/filepath" "slices" @@ -84,7 +85,51 @@ func validateBaselineMutablePath(path string) error { return nil } -func baselineImmutablePreparationDigest(ctx context.Context, root string, preparation *BaselinePreparationCallbacks) (raftbootstrap.Digest, error) { +// The journal already binds this exact mutable root in its transformation +// digest. Derive the one permitted sibling anchor from it on every resume. +const DedicatedTSOControlStoreName = "tso-control.db" + +const baselineStoreLockDir = ".elastickv-store-locks" + +// Only creation is permitted. Preserve an anchor (or its directory) already +// present in the signed source. A crash can leave just the directory. +type baselinePreparationTree struct { + digest raftbootstrap.Digest + lock baselineLockState +} + +type baselineLockState uint8 + +const ( + baselineLockDirectoryPresent baselineLockState = iota + 1 + baselineLockAnchorPresent +) + +func (tree *baselinePreparationTree) visitTSOLock(rel string, entry os.DirEntry) error { + switch rel { + case baselineStoreLockDir: + if !entry.IsDir() { + return errors.Wrap(ErrOfflineBaseline, "expected TSO lock directory") + } + tree.lock = baselineLockDirectoryPresent + case filepath.Join(baselineStoreLockDir, DedicatedTSOControlStoreName): + info, err := entry.Info() // Lstat semantics, including for dangling symlinks. + if err != nil { + return errors.WithStack(err) + } + if !info.Mode().IsRegular() || info.Size() != 0 { + return errors.Wrap(ErrOfflineBaseline, "expected empty regular TSO lock file") + } + tree.lock = baselineLockAnchorPresent + default: + return errors.Wrapf(ErrOfflineBaseline, "unexpected TSO lock entry %q", rel) + } + return nil +} + +func baselineImmutablePreparationDigest(ctx context.Context, root string, preparation *BaselinePreparationCallbacks) (baselinePreparationTree, error) { + var tree baselinePreparationTree + tso := baselinePreparationPathMutable(DedicatedTSOControlStoreName, preparation) h := sha256.New() err := filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error { if walkErr != nil { @@ -94,23 +139,44 @@ func baselineImmutablePreparationDigest(ctx context.Context, root string, prepar if err != nil { return errors.WithStack(err) } + if tso && (rel == baselineStoreLockDir || strings.HasPrefix(rel, baselineStoreLockDir+string(filepath.Separator))) { + return tree.visitTSOLock(rel, entry) // Keep walking the container. + } if baselinePreparationPathMutable(rel, preparation) { - if entry.Type()&os.ModeSymlink != 0 { - return errors.Wrap(ErrOfflineBaseline, "symlink preparation path") - } - if entry.IsDir() { - return filepath.SkipDir - } - return nil + return skipBaselineMutableEntry(entry) + } + if err := baselineHashTreeEntry(ctx, h, root, walDirName, path, entry, nil); err != nil { + return err } - return baselineHashTreeEntry(ctx, h, root, walDirName, path, entry, nil) + return hashBaselinePreparationDirectory(h, rel, entry) }) if err != nil { - return raftbootstrap.Digest{}, errors.WithStack(err) + return tree, errors.WithStack(err) } - var digest raftbootstrap.Digest - copy(digest[:], h.Sum(nil)) - return digest, nil + copy(tree.digest[:], h.Sum(nil)) + return tree, nil +} + +func skipBaselineMutableEntry(entry os.DirEntry) error { + if entry.Type()&os.ModeSymlink != 0 { + return errors.Wrap(ErrOfflineBaseline, "symlink preparation path") + } + if entry.IsDir() { + return filepath.SkipDir + } + return nil +} + +func hashBaselinePreparationDirectory(h io.Writer, rel string, entry os.DirEntry) error { + if !entry.IsDir() || rel == "." { + return nil + } + // Include empty directories in the comparison. A trailing slash + // distinguishes their frames from every regular filename. + name := filepath.ToSlash(rel) + "/" + frame := baselineAppendUint64(nil, uint64(len(name))) + _, err := h.Write(baselineAppendUint64(append(frame, name...), 0)) + return errors.WithStack(err) } func baselinePreparationPathMutable(path string, preparation *BaselinePreparationCallbacks) bool { @@ -129,7 +195,7 @@ func verifyBaselineImmutablePreparation(ctx context.Context, o OfflineBaselineOp if err != nil { return err } - if source != target { + if source.digest != target.digest || target.lock < source.lock { return errors.Wrap(ErrOfflineBaseline, "unexpected non-preparation source mutation") } return nil @@ -183,6 +249,9 @@ func stageBaselinePreparation(ctx context.Context, o OfflineBaselineOptions, man if target.wal.fileDigest != original.fileDigest { return paths, errors.Wrap(ErrOfflineBaseline, "preparation changed original WAL") } + if err := syncBaselinePreparationLock(o); err != nil { + return paths, err + } journal.phase, journal.preparedAux, journal.preparedData = baselinePrepared, target.auxDigest, data if err := writeBaselineJournal(paths.Directory, journal); err != nil { return paths, err @@ -191,6 +260,19 @@ func stageBaselinePreparation(ctx context.Context, o OfflineBaselineOptions, man return paths, nil } +func syncBaselinePreparationLock(o OfflineBaselineOptions) error { + if !baselinePreparationPathMutable(DedicatedTSOControlStoreName, o.Preparation) { + return nil + } + // preparedAux includes the anchor. Persist its directory entry before + // publishing that digest. A pre-lifecycle-lock image may lack the dir. + err := baselineSyncDirectory(filepath.Join(o.DataDir, baselineStoreLockDir)) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return baselineSyncDirectory(o.DataDir) +} + func verifyCompleteBaselineBackup(ctx context.Context, o OfflineBaselineOptions, manifest raftbootstrap.BaselineManifest, paths OfflineBaselineMigration, journal baselineMigrationJournal) error { digest, err := baselineTreeDigest(ctx, paths.BackupDir, "") if err != nil { diff --git a/internal/raftengine/etcd/bootstrap_baseline_preparation_lock_test.go b/internal/raftengine/etcd/bootstrap_baseline_preparation_lock_test.go new file mode 100644 index 000000000..6b0becce5 --- /dev/null +++ b/internal/raftengine/etcd/bootstrap_baseline_preparation_lock_test.go @@ -0,0 +1,70 @@ +package etcd + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBaselinePreparationTSOLockShape(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name, path, kind string + }{ + {"foreign lock", ".elastickv-store-locks/another.db", "empty file"}, + {"foreign directory", ".elastickv-store-locks/another.db", "directory"}, + {"nonempty anchor", ".elastickv-store-locks/tso-control.db", "bytes"}, + {"directory anchor", ".elastickv-store-locks/tso-control.db", "directory"}, + {"symlink anchor", ".elastickv-store-locks/tso-control.db", "file symlink"}, + {"file container", ".elastickv-store-locks", "empty file"}, + {"symlink container", ".elastickv-store-locks", "directory symlink"}, + {"sibling file", ".elastickv-store-locks.extra", "empty file"}, + {"sibling directory", ".elastickv-store-locks.extra", "directory"}, + } { + t.Run(tc.name, func(t *testing.T) { + o := OfflineBaselineOptions{DataDir: t.TempDir(), Preparation: &BaselinePreparationCallbacks{MutablePaths: []string{DedicatedTSOControlStoreName}}} + paths := OfflineBaselineMigration{BackupDir: t.TempDir()} + path := filepath.Join(o.DataDir, tc.path) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700)) + switch tc.kind { + case "directory": + require.NoError(t, os.Mkdir(path, 0o700)) + case "directory symlink": + require.NoError(t, os.Symlink(paths.BackupDir, path)) + case "file symlink": + empty := filepath.Join(t.TempDir(), "empty") + require.NoError(t, os.WriteFile(empty, nil, 0o600)) + require.NoError(t, os.Symlink(empty, path)) + case "empty file": + require.NoError(t, os.WriteFile(path, nil, 0o600)) + case "bytes": + require.NoError(t, os.WriteFile(path, []byte{1}, 0o600)) + } + require.ErrorIs(t, verifyBaselineImmutablePreparation(t.Context(), o, paths), ErrOfflineBaseline) + }) + } +} + +func TestBaselinePreparationTSOLockPrefixes(t *testing.T) { + t.Parallel() + o := OfflineBaselineOptions{DataDir: t.TempDir(), Preparation: &BaselinePreparationCallbacks{MutablePaths: []string{DedicatedTSOControlStoreName}}} + paths := OfflineBaselineMigration{BackupDir: t.TempDir()} + target := filepath.Join(o.DataDir, baselineStoreLockDir) + check := func() error { return verifyBaselineImmutablePreparation(t.Context(), o, paths) } + require.NoError(t, check()) + require.NoError(t, os.Mkdir(target, 0o700)) + require.NoError(t, check()) + anchor := filepath.Join(target, DedicatedTSOControlStoreName) + require.NoError(t, os.WriteFile(anchor, nil, 0o600)) + require.NoError(t, check()) + o.Preparation.MutablePaths = []string{"fsm.db"} + require.ErrorIs(t, check(), ErrOfflineBaseline) + + o.Preparation.MutablePaths = []string{DedicatedTSOControlStoreName} + require.NoError(t, copyBaselineTree(t.Context(), o.DataDir, paths.BackupDir)) + require.NoError(t, check()) + require.NoError(t, os.Remove(anchor)) + require.ErrorIs(t, check(), ErrOfflineBaseline, "an existing source anchor cannot disappear") +} diff --git a/internal/raftengine/etcd/dispatch_append_report_test.go b/internal/raftengine/etcd/dispatch_append_report_test.go new file mode 100644 index 000000000..06458dcb5 --- /dev/null +++ b/internal/raftengine/etcd/dispatch_append_report_test.go @@ -0,0 +1,546 @@ +package etcd + +import ( + "context" + "math" + "net" + "testing" + + "github.com/bootjp/elastickv/internal/peersession" + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil" + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" + "go.etcd.io/raft/v3/tracker" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/proto" +) + +func proposeDispatchEntry(t *testing.T, leader *Engine) uint64 { + t.Helper() + last, err := leader.storage.LastIndex() + require.NoError(t, err) + require.NoError(t, leader.rawNode.Propose(encodeProposalEnvelope(leader.nextID(), []byte("entry")))) + require.NoError(t, leader.drainReady()) + return last + 1 +} + +func TestDispatchAcknowledgedAppendDropPreservesPipeline(t *testing.T) { + leader, slow, healthy := newDispatchRecoveryCluster(t) + q := leader.peerDispatchers[slow.nodeID] + require.Empty(t, q.normal) + normal := q.normal + q.normal = make(chan dispatchRequest, 1) + proposeDispatchEntry(t, leader) + require.Len(t, q.normal, 1) + lost := proposeDispatchEntry(t, leader) + require.Equal(t, uint64(1), leader.DispatchDropCount()) + require.Len(t, leader.dispatchReportCh, 1) + report := <-leader.dispatchReportCh + normal <- <-q.normal + q.normal = normal + drainDispatchLink(t, leader, healthy) + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + drainDispatchLink(t, leader, slow) + require.Equal(t, lost, slow.applied) + suffix := proposeDispatchEntry(t, leader) + verifyAcknowledgedDispatchReport(t, leader, slow, report, suffix) +} + +func TestDispatchAcknowledgedAppendRPCFailurePreservesPipeline(t *testing.T) { + leader, slow, _ := newDispatchRecoveryCluster(t) + received := make(chan raftpb.Message, 1) + release := make(chan struct{}) + receiver := &GRPCTransport{} + receiver.SetHandler(func(ctx context.Context, msg raftpb.Message) error { + received <- msg + select { + case <-release: + return status.Error(codes.ResourceExhausted, "delayed failure") + case <-ctx.Done(): + return ctx.Err() + } + }) + listener := bufconn.Listen(1 << 16) + server := grpc.NewServer() + receiver.Register(server) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { server.Stop(); _ = listener.Close() }) + conn, err := grpc.NewClient("passthrough:///peer", grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) })) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + peer := leader.peers[slow.nodeID] + leader.transport.peers[slow.nodeID] = peer + leader.transport.clients[peer.Address] = pb.NewEtcdRaftClient(conn) + leader.transport.SetSendStreamEnabled(false) + + index := proposeDispatchEntry(t, leader) + q := leader.peerDispatchers[slow.nodeID] + require.Len(t, q.normal, 1) + req := <-q.normal + done := make(chan struct{}) + go func() { + leader.handleDispatchRequest(t.Context(), req) + close(done) + }() + msg := testutil.Recv(t, received, testDispatchReportTimeout, "Append RPC did not reach the receiver") + require.Equal(t, raftpb.MsgApp, msg.GetType()) + require.NoError(t, slow.rawNode.Step(&msg)) + drainDispatchLink(t, leader, slow) + require.Equal(t, index, slow.applied) + suffix := proposeDispatchEntry(t, leader) + close(release) + testutil.Closed(t, done, testDispatchReportTimeout, "Append RPC did not complete") + require.Equal(t, map[string]uint64{codes.ResourceExhausted.String(): 1}, leader.DispatchErrorCountsByCode()) + require.Len(t, leader.dispatchReportCh, 1) + verifyAcknowledgedDispatchReport(t, leader, slow, <-leader.dispatchReportCh, suffix) +} + +func verifyAcknowledgedDispatchReport(t *testing.T, leader, slow *Engine, report dispatchReport, suffix uint64) { + t.Helper() + q := leader.peerDispatchers[slow.nodeID] + before := leader.rawNode.Status().Progress[slow.nodeID] + require.Equal(t, tracker.StateReplicate, before.State) + require.Equal(t, suffix-1, before.Match) + require.Equal(t, suffix+1, before.Next) + require.Equal(t, 1, before.Inflights.Count()) + queued := queuedDispatchMessages(q.normal) + leader.handleDispatchReport(report) + after := leader.rawNode.Status().Progress[slow.nodeID] + require.Equal(t, queued, queuedDispatchMessages(q.normal)) + + // Deliver a real heartbeat and response ahead of the outstanding suffix. + // A reset to Probe permits another copy of the suffix to enter the FIFO. + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + require.NoError(t, leader.drainReady()) + require.Len(t, q.heartbeat, 1) + hb := <-q.heartbeat + require.NoError(t, slow.rawNode.Step(&hb.msg)) + require.NoError(t, hb.Close()) + require.NoError(t, slow.drainReady()) + replies := slow.peerDispatchers[leader.nodeID].heartbeat + require.Len(t, replies, 1) + reply := <-replies + require.Equal(t, raftpb.MsgHeartbeatResp, reply.msg.GetType()) + require.NoError(t, leader.rawNode.Step(&reply.msg)) + require.NoError(t, reply.Close()) + require.NoError(t, leader.drainReady()) + afterHeartbeat := queuedDispatchMessages(q.normal) + var indexes []uint64 + for _, msg := range afterHeartbeat { + for _, entry := range msg.Entries { + indexes = append(indexes, entry.GetIndex()) + } + } + t.Logf("Match %d, %s -> %s, Next %d -> %d, inflights %d -> %d, queued data %v", + before.Match, before.State, after.State, before.Next, after.Next, before.Inflights.Count(), after.Inflights.Count(), indexes) + require.Equal(t, []uint64{suffix}, indexes) + require.Equal(t, before, after) + // The heartbeat response also prompts an empty Append behind the suffix. + require.Len(t, afterHeartbeat, len(queued)+1) + require.Equal(t, queued, afterHeartbeat[:len(queued)]) + require.Equal(t, raftpb.MsgApp, afterHeartbeat[len(queued)].GetType()) + require.Empty(t, afterHeartbeat[len(queued)].Entries) + drainDispatchLink(t, leader, slow) + require.Equal(t, suffix, slow.applied) +} + +func TestDispatchLostAppendRecovery(t *testing.T) { + for _, feedback := range []string{"data", "legacy", "empty", "full report queue"} { + t.Run(feedback, func(t *testing.T) { + leader, slow, healthy := newDispatchRecoveryCluster(t) + term := leader.rawNode.BasicStatus().GetTerm() + index := proposeDispatchEntry(t, leader) + q := leader.peerDispatchers[slow.nodeID] + require.Len(t, q.normal, 1) + lost := <-q.normal + require.Len(t, lost.msg.Entries, 1) + require.Equal(t, index, lost.msg.Entries[0].GetIndex()) + require.Less(t, leader.rawNode.Status().Progress[slow.nodeID].Match, index) + drainDispatchLink(t, leader, healthy) + filler := dispatchReport{to: healthy.nodeID, msgType: raftpb.MsgHeartbeat} + switch feedback { + case "legacy": + leader.postDispatchReport(dispatchReport{to: slow.nodeID, msgType: raftpb.MsgApp}) + case "empty": + commitOnly := lost.msg + commitOnly.Entries = nil + commitOnly.Commit = uint64Ptr(index) + leader.reportFailedDispatch(commitOnly) + case "full report queue": + leader.dispatchReportCh = make(chan dispatchReport, 1) + leader.dispatchReportCh <- filler + leader.reportFailedDispatch(lost.msg) + case "data": + leader.reportFailedDispatch(lost.msg) + } + require.NoError(t, lost.Close()) + require.Len(t, leader.dispatchReportCh, 1) + report := <-leader.dispatchReportCh + if feedback == "full report queue" { + require.Equal(t, filler, report) + } else { + leader.handleDispatchReport(report) + require.Equal(t, tracker.StateProbe, leader.rawNode.Status().Progress[slow.nodeID].State) + } + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + drainDispatchLink(t, leader, slow) + progress := leader.rawNode.Status().Progress[slow.nodeID] + require.Equal(t, tracker.StateReplicate, progress.State) + require.Equal(t, index, progress.Match) + require.Equal(t, index, slow.applied) + require.Equal(t, term, leader.rawNode.BasicStatus().GetTerm()) + }) + } +} + +func TestDispatchLostAppendRecoveryAfterPartialAck(t *testing.T) { + leader, follower, healthy := newDispatchRecoveryCluster(t) + term := leader.rawNode.BasicStatus().GetTerm() + q := leader.peerDispatchers[follower.nodeID].normal + first := proposeDispatchEntry(t, leader) + require.Len(t, q, 1) + delayed := <-q + leader.rawNode.ReportUnreachable(follower.nodeID) + last := proposeDispatchEntry(t, leader) + require.Len(t, q, 1) + lost := <-q + require.Len(t, lost.msg.Entries, 2) + require.Equal(t, first, lost.msg.Entries[0].GetIndex()) + require.Equal(t, last, lost.msg.Entries[1].GetIndex()) + leader.reportFailedDispatch(lost.msg) + require.NoError(t, lost.Close()) + require.Len(t, leader.dispatchReportCh, 1) + report := <-leader.dispatchReportCh + require.Equal(t, last, report.appendLast) + + // Only the original single-entry Append reaches the follower. + require.NoError(t, follower.rawNode.Step(&delayed.msg)) + require.NoError(t, delayed.Close()) + require.NoError(t, follower.drainReady()) + replies := follower.peerDispatchers[leader.nodeID].normal + require.Len(t, replies, 1) + ack := <-replies + require.Equal(t, raftpb.MsgAppResp, ack.msg.GetType()) + require.NoError(t, leader.rawNode.Step(&ack.msg)) + require.NoError(t, ack.Close()) + require.NoError(t, leader.drainReady()) + pr := leader.rawNode.Status().Progress[follower.nodeID] + require.Equal(t, tracker.StateReplicate, pr.State) + require.Equal(t, first, pr.Match) + require.Greater(t, pr.Next, last) + discardDispatchAppends(t, q, last) + leader.handleDispatchReport(report) + require.Equal(t, tracker.StateProbe, leader.rawNode.Status().Progress[follower.nodeID].State) + drainDispatchLink(t, leader, healthy) + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + drainDispatchLink(t, leader, follower) + require.Equal(t, last, leader.rawNode.Status().Progress[follower.nodeID].Match) + require.Equal(t, last, follower.applied) + require.Equal(t, term, leader.rawNode.BasicStatus().GetTerm()) +} + +// Hold a failure report while the real follower receives and acknowledges the +// entire Append. Callers change exactly one condition before owner delivery. +func holdAcknowledgedDispatchReport(t *testing.T, leader, follower *Engine) dispatchReport { + t.Helper() + index := proposeDispatchEntry(t, leader) + messages := queuedDispatchMessages(leader.peerDispatchers[follower.nodeID].normal) + require.Len(t, messages, 1) + leader.reportFailedDispatch(messages[0]) + require.Len(t, leader.dispatchReportCh, 1) + report := <-leader.dispatchReportCh + require.Equal(t, index, report.appendLast) + require.Equal(t, leader.rawNode.BasicStatus().GetTerm(), report.appendTerm) + drainDispatchLink(t, leader, follower) + require.Equal(t, index, leader.rawNode.Status().Progress[follower.nodeID].Match) + return report +} + +func TestDispatchAppendReportAfterTermChange(t *testing.T) { + leader, follower, _ := newDispatchRecoveryCluster(t) + report := holdAcknowledgedDispatchReport(t, leader, follower) + leader.rawNode.TransferLeader(follower.nodeID) + drainDispatchLink(t, leader, follower) + require.Equal(t, follower.nodeID, follower.rawNode.BasicStatus().Lead) + follower.rawNode.TransferLeader(leader.nodeID) + drainDispatchLink(t, follower, leader) + status := leader.rawNode.Status() + require.Equal(t, leader.nodeID, status.Lead) + require.Greater(t, status.GetTerm(), report.appendTerm) + require.Greater(t, status.Progress[follower.nodeID].Match, report.appendLast) + require.Equal(t, tracker.StateReplicate, status.Progress[follower.nodeID].State) + leader.handleDispatchReport(report) + require.Equal(t, tracker.StateProbe, leader.rawNode.Status().Progress[follower.nodeID].State) +} + +func TestDispatchAppendReportAfterLaterAck(t *testing.T) { + leader, follower, _ := newDispatchRecoveryCluster(t) + report := holdAcknowledgedDispatchReport(t, leader, follower) + later := proposeDispatchEntry(t, leader) + drainDispatchLink(t, leader, follower) + require.Greater(t, later, report.appendLast) + require.Equal(t, later, leader.rawNode.Status().Progress[follower.nodeID].Match) + suffix := proposeDispatchEntry(t, leader) + require.Equal(t, report.appendTerm, leader.rawNode.BasicStatus().GetTerm()) + verifyAcknowledgedDispatchReport(t, leader, follower, report, suffix) +} + +func TestDispatchAppendReportAfterMembershipReplacement(t *testing.T) { + leader, old, _ := newDispatchRecoveryCluster(t) + report := holdAcknowledgedDispatchReport(t, leader, old) + id := old.nodeID + leader.rawNode.ApplyConfChange(&raftpb.ConfChange{Type: raftpb.ConfChangeRemoveNode.Enum(), NodeId: &id}) + require.NotContains(t, leader.rawNode.Status().Progress, id) + require.False(t, leader.acknowledgedDispatchAppend(report)) + leader.rawNode.ApplyConfChange(&raftpb.ConfChange{Type: raftpb.ConfChangeAddNode.Enum(), NodeId: &id}) + require.Zero(t, leader.rawNode.Status().Progress[id].Match) + require.False(t, leader.acknowledgedDispatchAppend(report)) + leader.handleDispatchReport(report) + replacement := identityElectionEngine(t, id) + replacement.raftCutoverIndex = orInertCutover(nil) + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + drainDispatchLink(t, leader, replacement) + require.Equal(t, report.appendLast, replacement.applied) + require.Equal(t, report.appendTerm, leader.rawNode.BasicStatus().GetTerm()) + suffix := proposeDispatchEntry(t, leader) + verifyAcknowledgedDispatchReport(t, leader, replacement, report, suffix) +} + +func TestDispatchAppendReportUnknownRange(t *testing.T) { + for _, tc := range []struct { + name string + change func(*raftpb.Message) + }{ + {"missing term", func(m *raftpb.Message) { m.Term = nil }}, + {"unscoped sender", func(m *raftpb.Message) { m.From = nil }}, + {"foreign sender", func(m *raftpb.Message) { m.From = uint64Ptr(3) }}, + {"commit only", func(m *raftpb.Message) { m.Entries = nil }}, + {"missing predecessor", func(m *raftpb.Message) { m.Index = nil }}, + {"missing predecessor term", func(m *raftpb.Message) { m.LogTerm = nil }}, + {"zero predecessor term", func(m *raftpb.Message) { m.LogTerm = uint64Ptr(0) }}, + {"missing entry term", func(m *raftpb.Message) { m.Entries[0].Term = nil }}, + {"zero entry term", func(m *raftpb.Message) { m.Entries[0].Term = uint64Ptr(0) }}, + {"future entry term", func(m *raftpb.Message) { m.Entries[0].Term = uint64Ptr(m.GetTerm() + 1) }}, + {"older than predecessor", func(m *raftpb.Message) { m.Entries[0].Term = uint64Ptr(m.GetLogTerm() - 1) }}, + {"decreasing terms", func(m *raftpb.Message) { + m.Entries = append(m.Entries, &raftpb.Entry{Index: uint64Ptr(m.Entries[0].GetIndex() + 1), Term: uint64Ptr(1)}) + }}, + {"index overflow", func(m *raftpb.Message) { + m.Index, m.Entries[0].Index = uint64Ptr(math.MaxUint64), uint64Ptr(0) + }}, + {"snapshot side payload", func(m *raftpb.Message) { m.Snapshot = &raftpb.Snapshot{} }}, + {"missing last index", func(m *raftpb.Message) { m.Entries[0].Index = nil }}, + {"gap", func(m *raftpb.Message) { m.Index = uint64Ptr(0) }}, + {"nil entry", func(m *raftpb.Message) { m.Entries[0] = nil }}, + } { + t.Run(tc.name, func(t *testing.T) { + leader, follower, _ := newDispatchRecoveryCluster(t) + index := proposeDispatchEntry(t, leader) + messages := queuedDispatchMessages(leader.peerDispatchers[follower.nodeID].normal) + require.Len(t, messages, 1) + tc.change(&messages[0]) + leader.reportFailedDispatch(messages[0]) + drainDispatchLink(t, leader, follower) + pr := leader.rawNode.Status().Progress[follower.nodeID] + require.Equal(t, index, pr.Match) + require.Equal(t, tracker.StateReplicate, pr.State) + require.Len(t, leader.dispatchReportCh, 1) + report := <-leader.dispatchReportCh + require.Zero(t, report.appendTerm) + require.Zero(t, report.appendLast) + leader.handleDispatchReport(report) + require.Equal(t, tracker.StateProbe, leader.rawNode.Status().Progress[follower.nodeID].State) + }) + } +} + +func TestDispatchAppendReportConstruction(t *testing.T) { + e := &Engine{nodeID: 1} + msg := raftpb.Message{Type: raftpb.MsgApp.Enum(), From: uint64Ptr(1), To: uint64Ptr(2), + Index: uint64Ptr(0), LogTerm: uint64Ptr(0), Term: uint64Ptr(4), + Entries: []*raftpb.Entry{ + {Index: uint64Ptr(1), Term: uint64Ptr(1)}, + {Index: uint64Ptr(2), Term: uint64Ptr(2)}, + {Index: uint64Ptr(3), Term: uint64Ptr(2)}, + }} + require.Equal(t, dispatchReport{to: 2, msgType: raftpb.MsgApp, appendTerm: 4, appendLast: 3}, e.failedDispatchReport(msg)) + for _, to := range []uint64{0, e.nodeID} { + msg.To = &to + require.Equal(t, dispatchReport{to: to, msgType: raftpb.MsgApp}, e.failedDispatchReport(msg)) + } +} + +func dispatchReportArbiter(t *testing.T, leader *Engine) *raftadmission.Arbiter { + t.Helper() + a, err := raftadmission.New(raftadmission.Config{Cluster: raftbootstrap.UUID{1}, DefaultGroup: 1, Groups: []uint64{1}, + ValidatePayload: func(raftadmission.Kind, uint64, []byte) error { return raftadmission.ErrClosed }}) + require.NoError(t, err) + t.Cleanup(a.Close) + leader.groupID, leader.nativeAdmission, leader.nativeConfigurationIndex = 1, a, leader.currentConfigIndex() + require.NoError(t, leader.withNative(t.Context(), nil, func() error { return nil })) + return a +} + +func TestDispatchAppendReportLocalOwnerDenial(t *testing.T) { + for _, tc := range []struct { + name string + covered, unassigned bool + }{ + {"shutdown/covered", true, false}, {"shutdown/outstanding", false, false}, + {"unassigned group/covered", true, true}, {"unassigned group/outstanding", false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + leader, follower, _ := newDispatchRecoveryCluster(t) + dispatchReportArbiter(t, leader) + leader.closeCh = make(chan struct{}) + report := holdAcknowledgedDispatchReport(t, leader, follower) + index := proposeDispatchEntry(t, leader) + q := leader.peerDispatchers[follower.nodeID].normal + queued := queuedDispatchMessages(q) + if !tc.covered { + require.Len(t, queued, 1) + report = leader.failedDispatchReport(queued[0]) + require.Equal(t, index, report.appendLast) + } + require.Equal(t, tc.covered, leader.acknowledgedDispatchAppend(report)) + before := leader.rawNode.Status().Progress[follower.nodeID] + require.Equal(t, tracker.StateReplicate, before.State) + leader.dispatchReportCh <- report + if tc.unassigned { + // WithNative itself refuses an unregistered local group. + leader.groupID = 2 + } else { + leader.requestShutdown() + running, err := leader.handleEvent(nil) + require.NoError(t, err) + require.False(t, running) + require.Len(t, leader.dispatchReportCh, 1) + } + // Deliver as though the select had already dequeued the report. + leader.handleDispatchReport(<-leader.dispatchReportCh) + if tc.unassigned { + require.ErrorIs(t, leader.Err(), raftengine.ErrNativeAdmissionDenied) + require.ErrorIs(t, leader.Err(), raftadmission.ErrClosed) + require.Equal(t, raftengine.StateShutdown, leader.State()) + } + require.Equal(t, before, leader.rawNode.Status().Progress[follower.nodeID]) + require.Equal(t, queued, queuedDispatchMessages(q)) + }) + } +} + +// Capture the follower's actual response at protected ingress while holding +// the local failed-send report for the same Append on the leader. +func queuedDispatchAck(t *testing.T, leader, follower *Engine, client pb.EtcdRaftClient) (dispatchReport, protectedStep) { + t.Helper() + index := proposeDispatchEntry(t, leader) + q := leader.peerDispatchers[follower.nodeID].normal + require.Len(t, q, 1) + appendReq := <-q + leader.reportFailedDispatch(appendReq.msg) + require.NoError(t, follower.rawNode.Step(&appendReq.msg)) + require.NoError(t, appendReq.Close()) + require.NoError(t, follower.drainReady()) + replies := follower.peerDispatchers[leader.nodeID].normal + require.Len(t, replies, 1) + reply := <-replies + require.Equal(t, raftpb.MsgAppResp, reply.msg.GetType()) + require.Equal(t, index, reply.msg.GetIndex()) + wire, err := proto.Marshal(&reply.msg) + require.NoError(t, err) + require.NoError(t, reply.Close()) + _, err = client.Send(t.Context(), &pb.EtcdRaftMessage{Message: wire}) + require.NoError(t, err) + in := protectedTestQueue(leader, raftpb.MsgAppResp) + require.Len(t, in, 1) + require.Len(t, leader.dispatchReportCh, 1) + return <-leader.dispatchReportCh, <-in +} + +func TestDispatchAppendReportProtectedAck(t *testing.T) { + for _, mode := range []string{"live", "receipt revoked", "generation suspended", "numeric ID reinstalled"} { + t.Run(mode, func(t *testing.T) { + leader, owner, client := protectedQueueFixture(t) + follower := identityElectionEngine(t, 2) + leader.raftCutoverIndex, follower.raftCutoverIndex = orInertCutover(nil), orInertCutover(nil) + leader.dispatchReportCh = make(chan dispatchReport, 1) + require.NoError(t, leader.rawNode.Campaign()) + drainDispatchLink(t, leader, follower) + + a := dispatchReportArbiter(t, leader) + publishRecoveryReadProjection(t, &transportTestNode{engine: leader}, &recoveryReadTestAdmission{Arbiter: a}, 1, false) + leader.admissionChanged = func() { owner.SuspendGroup(leader.groupID) } + report, ack := queuedDispatchAck(t, leader, follower, client) + require.NoError(t, ack.receipt.Check(t.Context())) + require.Equal(t, report.appendTerm, ack.message.GetTerm()) + require.Equal(t, report.appendLast, ack.message.GetIndex()) + require.ErrorIs(t, leader.handleTransportMessage(t.Context(), ack.message), peersession.ErrDenied) + switch mode { + case "receipt revoked": + owner.SuspendGroup(leader.groupID) + require.Equal(t, codes.PermissionDenied, status.Code(ack.receipt.Check(t.Context()))) + case "generation suspended": + a.Suspend(leader.groupID) + require.NoError(t, ack.receipt.Check(t.Context())) + case "numeric ID reinstalled": + // Stress the owner boundary even if the native configuration is + // forced through ID reuse, which protected policy forbids. + projection, ok := owner.GroupProjection(leader.groupID) + require.True(t, ok) + // The production protected apply path stops before removing + // the member, and invalidates the queued receipt at this point. + remove := raftpb.ConfChange{Type: raftpb.ConfChangeRemoveNode.Enum(), NodeId: &follower.nodeID} + _, err := leader.transitionConfChange(leader.nativeConfigurationIndex+1, remove) + require.ErrorContains(t, err, "protected configuration change requires exact policy context") + require.Contains(t, leader.rawNode.Status().Progress, follower.nodeID) + require.Equal(t, codes.PermissionDenied, status.Code(ack.receipt.Check(t.Context()))) + for _, kind := range []raftpb.ConfChangeType{raftpb.ConfChangeRemoveNode, raftpb.ConfChangeAddNode} { + _, err := leader.applyNativeConfChange(&raftpb.ConfChange{Type: kind.Enum(), NodeId: &follower.nodeID}, leader.nativeConfigurationIndex+1) + require.NoError(t, err) + } + leader.configIndex.Store(leader.nativeConfigurationIndex) + leader.refreshStatus() + projection.Generation++ + projection.Configuration.Index = leader.nativeConfigurationIndex + require.NoError(t, owner.UpdateGroup(projection)) + publishRecoveryReadProjection(t, &transportTestNode{engine: leader}, &recoveryReadTestAdmission{Arbiter: a}, projection.Generation, false) + require.Zero(t, leader.rawNode.Status().Progress[follower.nodeID].Match) + require.Equal(t, codes.PermissionDenied, status.Code(ack.receipt.Check(t.Context()))) + } + before := leader.rawNode.Status().Progress[follower.nodeID] + require.Less(t, before.Match, report.appendLast) + require.Equal(t, mode == "live", leader.handleProtectedStep(ack)) + after := leader.rawNode.Status().Progress[follower.nodeID] + if mode == "live" { + require.Equal(t, report.appendLast, after.Match) + leader.handleDispatchReport(report) + require.Equal(t, after, leader.rawNode.Status().Progress[follower.nodeID]) + return + } + require.Equal(t, before, after) + leader.handleDispatchReport(report) + pr := leader.rawNode.Status().Progress[follower.nodeID] + require.Equal(t, before.Match, pr.Match) + require.Equal(t, tracker.StateProbe, pr.State) + }) + } +} diff --git a/internal/raftengine/etcd/dispatch_overload_recovery_test.go b/internal/raftengine/etcd/dispatch_overload_recovery_test.go new file mode 100644 index 000000000..bc0eec810 --- /dev/null +++ b/internal/raftengine/etcd/dispatch_overload_recovery_test.go @@ -0,0 +1,158 @@ +package etcd + +import ( + "context" + "net" + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" + "go.etcd.io/raft/v3/tracker" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/proto" +) + +func newDispatchRecoveryCluster(t *testing.T) (leader, slow, healthy *Engine) { + t.Helper() + leader, slow, healthy = identityElectionEngine(t, 1), identityElectionEngine(t, 2), identityElectionEngine(t, 3) + for _, node := range []*Engine{leader, slow, healthy} { + node.raftCutoverIndex = orInertCutover(nil) + } + leader.dispatchReportCh = make(chan dispatchReport, 8) + require.NoError(t, leader.rawNode.Campaign()) + drainDispatchLink(t, leader, slow) + drainDispatchLink(t, leader, healthy) + drainDispatchLink(t, leader, slow) + return leader, slow, healthy +} + +func TestDispatchUnreportedAppendLossRecoversDuringHeartbeatOverload(t *testing.T) { + leader, slow, healthy := newDispatchRecoveryCluster(t) + index := commitWithDispatchGates(t, leader, healthy) + q := leader.peerDispatchers[slow.nodeID] + discardDispatchAppends(t, q.normal, index) + require.Empty(t, leader.dispatchReportCh) + require.Equal(t, tracker.StateReplicate, leader.rawNode.Status().Progress[slow.nodeID].State) + + q.heartbeat = make(chan dispatchRequest, 1) + for range 2 { + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + require.NoError(t, leader.drainReady()) + } + require.Positive(t, leader.DispatchDropCount()) + require.Empty(t, leader.dispatchReportCh) + require.Len(t, q.heartbeat, 1) + // The original Append has no failure report. A new write still commits + // through the other voter while the slow heartbeat lane remains full. + require.Equal(t, index+1, commitWithDispatchGates(t, leader, healthy)) + require.Less(t, slow.applied, index) + drainDispatchLink(t, leader, slow) + require.Equal(t, index+1, slow.applied) + progress := leader.rawNode.Status().Progress[slow.nodeID] + require.Equal(t, tracker.StateReplicate, progress.State) + require.Equal(t, slow.applied, progress.Match) +} + +func TestDispatchUnreportedAppendLossRecoversWithoutNewProposal(t *testing.T) { + leader, slow, healthy := newDispatchRecoveryCluster(t) + index := commitWithDispatchGates(t, leader, healthy) + q := leader.peerDispatchers[slow.nodeID] + discardDispatchAppends(t, q.normal, index) + require.Empty(t, leader.dispatchReportCh) + require.Equal(t, tracker.StateReplicate, leader.rawNode.Status().Progress[slow.nodeID].State) + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + drainDispatchLink(t, leader, slow) + require.Equal(t, index, slow.applied) + progress := leader.rawNode.Status().Progress[slow.nodeID] + require.Equal(t, tracker.StateReplicate, progress.State) + require.Equal(t, index, progress.Match) +} + +func TestDispatchDelayedRemoteHeartbeatOverloadKeepsRecoveredProgress(t *testing.T) { + leader, slow, healthy := newDispatchRecoveryCluster(t) + heartbeat := raftpb.Message{Type: raftpb.MsgHeartbeat.Enum(), From: uint64Ptr(leader.nodeID), To: uint64Ptr(slow.nodeID)} + held := remoteHeartbeatOverload(t, heartbeat) + index := commitWithDispatchGates(t, leader, healthy) + drainDispatchLink(t, leader, slow) + require.Equal(t, index, slow.applied) + require.Equal(t, index+1, commitWithDispatchGates(t, leader, healthy)) + before := leader.rawNode.Status().Progress[slow.nodeID] + require.Equal(t, tracker.StateReplicate, before.State) + require.Equal(t, index, before.Match) + require.Equal(t, 1, before.Inflights.Count()) + q := leader.peerDispatchers[slow.nodeID] + queuedBefore := queuedDispatchMessages(q.normal) + var indexes []uint64 + for _, message := range queuedBefore { + for _, entry := range message.Entries { + indexes = append(indexes, entry.GetIndex()) + } + } + require.Equal(t, []uint64{index + 1}, indexes) + leader.dispatchFn = func(context.Context, dispatchRequest) error { return held } + leader.handleDispatchRequest(t.Context(), dispatchRequest{msg: heartbeat}) + require.Equal(t, map[string]uint64{codes.ResourceExhausted.String(): 1}, leader.DispatchErrorCountsByCode()) + require.Empty(t, leader.dispatchReportCh) + require.Equal(t, before, leader.rawNode.Status().Progress[slow.nodeID]) + require.Equal(t, queuedBefore, queuedDispatchMessages(q.normal)) + drainDispatchLink(t, leader, slow) + require.Equal(t, index+1, slow.applied) +} + +func discardDispatchAppends(t *testing.T, queue chan dispatchRequest, index uint64) { + t.Helper() + entries := 0 + for len(queue) > 0 { + request := <-queue + require.Equal(t, raftpb.MsgApp, request.msg.GetType()) + for _, entry := range request.msg.Entries { + require.Equal(t, index, entry.GetIndex()) + entries++ + } + require.NoError(t, request.Close()) + } + require.Equal(t, 1, entries) +} + +// These fixtures have no dispatch workers. Preserve every request and its +// ownership while taking an independent copy of the FIFO's message contents. +func queuedDispatchMessages(queue chan dispatchRequest) []raftpb.Message { + count := len(queue) + messages := make([]raftpb.Message, 0, count) + for range count { + request := <-queue + messages = append(messages, cloneDispatchMessage(request.msg)) + queue <- request + } + return messages +} + +func remoteHeartbeatOverload(t *testing.T, message raftpb.Message) error { + t.Helper() + receiver := &GRPCTransport{} + receiver.SetHandler(func(context.Context, raftpb.Message) error { return errStepQueueFull }) + listener := bufconn.Listen(1 << 16) + server := grpc.NewServer() + receiver.Register(server) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { server.Stop(); _ = listener.Close() }) + conn, err := grpc.NewClient("passthrough:///peer", grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) })) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + raw, err := proto.Marshal(&message) + require.NoError(t, err) + ack, err := pb.NewEtcdRaftClient(conn).Send(t.Context(), &pb.EtcdRaftMessage{Message: raw}) + require.Nil(t, ack) + require.Error(t, err) + require.True(t, isHeartbeatIngressFull(err)) + return err +} diff --git a/internal/raftengine/etcd/dispatch_overload_test.go b/internal/raftengine/etcd/dispatch_overload_test.go new file mode 100644 index 000000000..fdd8c5133 --- /dev/null +++ b/internal/raftengine/etcd/dispatch_overload_test.go @@ -0,0 +1,216 @@ +package etcd + +import ( + "context" + "sync" + "testing" + + "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" + "go.etcd.io/raft/v3/tracker" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Deliver only this link, in FIFO order within each dispatch lane. The other +// voter's queued messages stay in their original production channels. +func drainDispatchLink(t *testing.T, a, b *Engine) { + t.Helper() + for range 20 { + moved := false + for _, source := range []*Engine{a, b} { + target := a + if source == a { + target = b + } + require.NoError(t, source.drainReady()) + q := source.peerDispatchers[target.nodeID] + for _, lane := range []chan dispatchRequest{q.heartbeat, q.readIndexResp, q.normal} { + for len(lane) > 0 { + req := <-lane + require.NoError(t, target.rawNode.Step(&req.msg)) + require.NoError(t, req.Close()) + moved = true + } + } + } + if !moved { + return + } + } + t.Fatal("Raft link did not quiesce") +} + +func TestDispatchHeartbeatOverloadPreservesInflightAppend(t *testing.T) { + leader, slow, healthy := identityElectionEngine(t, 1), identityElectionEngine(t, 2), identityElectionEngine(t, 3) + for _, node := range []*Engine{leader, slow, healthy} { + node.raftCutoverIndex = orInertCutover(nil) + } + leader.dispatchReportCh = make(chan dispatchReport, 8) + require.NoError(t, leader.rawNode.Campaign()) + drainDispatchLink(t, leader, slow) + drainDispatchLink(t, leader, healthy) + drainDispatchLink(t, leader, slow) + q := leader.peerDispatchers[2] + q.heartbeat = make(chan dispatchRequest, 1) + index := commitWithDispatchGates(t, leader, healthy) + require.Less(t, slow.applied, index) + read := readRequest{ctx: t.Context(), id: leader.nextID(), done: make(chan readResult, 1)} + leader.handleRead(read) + require.NoError(t, leader.drainReady()) + require.Empty(t, read.done) + require.Len(t, q.heartbeat, 1) + + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + require.NoError(t, leader.drainReady()) + require.Equal(t, uint64(1), leader.DispatchDropCount()) + before := leader.rawNode.Status().Progress[2] + require.Equal(t, tracker.StateReplicate, before.State) + require.Equal(t, 1, before.Inflights.Count()) + for len(leader.dispatchReportCh) > 0 { + leader.handleDispatchReport(<-leader.dispatchReportCh) + } + after := leader.rawNode.Status().Progress[2] + drainDispatchLink(t, leader, healthy) + require.Len(t, read.done, 1) + require.Equal(t, readResult{index: index}, <-read.done) + // Release the earlier ReadIndex heartbeat alone, while the append stays queued. + probe := <-q.heartbeat + require.NotEmpty(t, probe.msg.Context) + require.NoError(t, slow.rawNode.Step(&probe.msg)) + require.NoError(t, probe.Close()) + require.NoError(t, slow.drainReady()) + replies := slow.peerDispatchers[1].readIndexResp + require.Len(t, replies, 1) + reply := <-replies + require.Equal(t, raftpb.MsgHeartbeatResp, reply.msg.GetType()) + require.Equal(t, probe.msg.Context, reply.msg.Context) + require.NoError(t, leader.rawNode.Step(&reply.msg)) + require.NoError(t, reply.Close()) + require.NoError(t, leader.drainReady()) + + var entries []uint64 + for len(q.normal) > 0 { + req := <-q.normal + for _, entry := range req.msg.Entries { + entries = append(entries, entry.GetIndex()) + } + require.NoError(t, slow.rawNode.Step(&req.msg)) + require.NoError(t, req.Close()) + } + t.Logf("heartbeat refusal: %s -> %s, Next %d -> %d, inflights %d -> %d, queued entry indexes %v", + before.State, after.State, before.Next, after.Next, before.Inflights.Count(), after.Inflights.Count(), entries) + require.Equal(t, []uint64{index}, entries) + require.Equal(t, before, after) + drainDispatchLink(t, leader, slow) + require.Equal(t, index, slow.applied) + + verifyDispatchAppendLossRecovery(t, leader, slow, index) +} + +func verifyDispatchAppendLossRecovery(t *testing.T, leader, slow *Engine, index uint64) { + t.Helper() + q := leader.peerDispatchers[slow.nodeID] + // Lose the next actual Append. A tick and a real follower reply must + // still drive a probe that repairs the missing entry. + require.NoError(t, leader.rawNode.Propose(encodeProposalEnvelope(leader.nextID(), []byte("next")))) + require.NoError(t, leader.drainReady()) + require.Len(t, q.normal, 1) + lost := <-q.normal + require.Equal(t, raftpb.MsgApp, lost.msg.GetType()) + require.Len(t, lost.msg.Entries, 1) + leader.dispatchFn = func(context.Context, dispatchRequest) error { return status.Error(codes.Unavailable, "link failed") } + leader.handleDispatchRequest(t.Context(), lost) + require.Len(t, leader.dispatchReportCh, 1) + leader.handleDispatchReport(<-leader.dispatchReportCh) + require.Equal(t, tracker.StateProbe, leader.rawNode.Status().Progress[2].State) + for range defaultHeartbeatTick { + leader.rawNode.Tick() + } + drainDispatchLink(t, leader, slow) + require.Equal(t, index+1, slow.applied) + recovered := leader.rawNode.Status().Progress[2] + require.Equal(t, tracker.StateReplicate, recovered.State) + require.Equal(t, slow.applied, recovered.Match) +} + +// Hold the synchronous leader's WAL Save, then its FSM Apply after the +// healthy voter's real MsgAppResp. The other voter's append stays queued. +func commitWithDispatchGates(t *testing.T, leader, healthy *Engine) uint64 { + t.Helper() + proposal := proposalRequest{ctx: t.Context(), id: leader.nextID(), payload: []byte("entry"), done: make(chan proposalResult, 1)} + gate := proposalTurnWAL(t) + leader.persist = gate + releaseSave := sync.OnceFunc(func() { close(gate.release) }) + defer releaseSave() + fsm := &asyncStorageFSM{payload: proposal.payload, applyEntered: make(chan uint64, 1), + applyRelease: make(chan struct{}), applyReturned: make(chan struct{})} + leader.fsm = fsm + defer fsm.unblock() + want := leader.applied + 1 + leader.handleProposal(proposal) + drained := make(chan error, 1) + go func() { drained <- leader.drainReady() }() + select { + case indexes := <-gate.entered: + require.Equal(t, []uint64{want}, indexes) + case err := <-drained: + t.Fatalf("drain returned before WAL Save: %v", err) + } + require.Empty(t, proposal.done) + require.Empty(t, fsm.Applied()) + releaseSave() + require.NoError(t, <-drained) + require.Empty(t, proposal.done) + + deliver := func(source, target *Engine, kind raftpb.MessageType) { + t.Helper() + queue := source.peerDispatchers[target.nodeID].normal + require.Len(t, queue, 1) + req := <-queue + require.Equal(t, kind, req.msg.GetType()) + require.NoError(t, target.rawNode.Step(&req.msg)) + require.NoError(t, req.Close()) + } + deliver(leader, healthy, raftpb.MsgApp) + require.NoError(t, healthy.drainReady()) + deliver(healthy, leader, raftpb.MsgAppResp) + go func() { drained <- leader.drainReady() }() + select { + case index := <-fsm.applyEntered: + require.Equal(t, want, index) + case err := <-drained: + t.Fatalf("drain returned before FSM Apply: %v", err) + } + require.Empty(t, proposal.done) + fsm.unblock() + require.NoError(t, <-drained) + require.Len(t, proposal.done, 1) + result := <-proposal.done + require.NoError(t, result.err) + require.Equal(t, want, result.result.CommitIndex) + drainDispatchLink(t, leader, healthy) + require.Equal(t, want, healthy.applied) + return want +} + +func TestDispatchFullReadResponseLaneKeepsFIFO(t *testing.T) { + q := &peerQueues{readIndexResp: make(chan dispatchRequest, 2)} + e := &Engine{peerDispatchers: map[uint64]*peerQueues{2: q}, dispatchReportCh: make(chan dispatchReport, 1)} + for _, id := range []string{"first", "second", "third"} { + require.NoError(t, e.enqueueDispatchMessage(raftpb.Message{ + Type: raftpb.MsgHeartbeatResp.Enum(), To: uint64Ptr(2), Context: []byte(id), + })) + } + require.Equal(t, uint64(1), e.DispatchDropCount()) + require.Len(t, e.dispatchReportCh, 1) + require.Equal(t, dispatchReport{to: 2, msgType: raftpb.MsgHeartbeatResp}, <-e.dispatchReportCh) + require.Len(t, q.readIndexResp, 2) + for _, id := range []string{"first", "second"} { + req := <-q.readIndexResp + require.Equal(t, id, string(req.msg.Context)) + require.NoError(t, req.Close()) + } +} diff --git a/internal/raftengine/etcd/engine.go b/internal/raftengine/etcd/engine.go index bac64e27a..6e4068681 100644 --- a/internal/raftengine/etcd/engine.go +++ b/internal/raftengine/etcd/engine.go @@ -62,6 +62,7 @@ const ( // memory remains much lower than that worst-case bound. defaultMaxInflightMsg = 1024 defaultMaxSizePerMsg = 1 << 20 + syncInflightBytes = 8 << 20 // minInboundQueueCapacity keeps very small test/operator inflight limits // from shrinking the shared inbound queue enough to drop heartbeats. minInboundQueueCapacity = 128 @@ -326,6 +327,7 @@ type Engine struct { nativeAdmission raftengine.NativeAdmission groupID uint64 nativeConfigurationIndex uint64 // actual native configuration, owned by the loop + nativeConfigurationCache *nativeConfigurationCache // Published with status under mu; never read RawNode from an RPC goroutine. nativeConfigurationView *raftengine.NativeConfiguration admissionDirty bool // owned by the native loop, like RawNode @@ -378,6 +380,8 @@ type Engine struct { adminCh chan adminRequest stepCh chan raftpb.Message protectedStepCh chan protectedStep + pendingProtectedStep *protectedStep + pendingProtectedBatchEvent *protectedBatchEvent protectedPriorityStepCh chan protectedStep priorityStepCh chan raftpb.Message priorityStepBurst int @@ -470,9 +474,12 @@ type Engine struct { lastLeaderContactAt time.Time lastLeaderContactFrom uint64 - // Restore swaps the underlying store state and must not race with the short - // critical section that publishes a newly persisted local snapshot. + // Serialize source restore with file-backed capture, export, pin close and + // publication. The pending identity and close error are guarded by this lock. snapshotMu sync.Mutex + pendingLocalSnapshot *localSnapshotCapture + snapshotCloseErr error + snapshotWorkerErr error // worker-owned; observed only after joining it protectedReceivedFSMSnaps map[uint64]int pendingReceivedFSMSnapshotStep map[uint64]int pendingReceivedFSMReleaseIndex atomic.Uint64 @@ -563,6 +570,7 @@ type Engine struct { snapshotSendContext context.Context snapshotSendCancel context.CancelFunc dispatchFn func(context.Context, dispatchRequest) error + syncObserver *syncRaftObserver } type adminAction byte @@ -713,6 +721,7 @@ func Open(ctx context.Context, cfg OpenConfig) (*Engine, error) { dispatchCancel() }() + // Reserve one protected normal queue slot for the owner's deferred boundary. engine := &Engine{ baselineStartupGuard: guard, recoveredAdmission: prepared.cfg.RecoveredAdmission, @@ -742,7 +751,7 @@ func Open(ctx context.Context, cfg OpenConfig) (*Engine, error) { readCh: make(chan readRequest), adminCh: make(chan adminRequest), stepCh: make(chan raftpb.Message, inboundQueueCap), - protectedStepCh: make(chan protectedStep, inboundQueueCap), + protectedStepCh: make(chan protectedStep, inboundQueueCap-1), protectedPriorityStepCh: make(chan protectedStep, priorityStepQueueCapacity), priorityStepCh: make(chan raftpb.Message, priorityStepQueueCapacity), dispatchReportCh: make(chan dispatchReport, inboundQueueCap), @@ -1094,6 +1103,10 @@ func newRawNodeWithStorageMode(cfg OpenConfig, storage *etcdraft.MemoryStorage, config.MaxCommittedSizePerReady = pipelineCommittedBatchBytes config.MaxUncommittedEntriesSize = pipelineUncommittedBytes config.MaxInflightBytes = pipelineEntryRoom + } else { + // Bound a peer's refill while allowing one message to cross the window. + // Raft requires the window to accommodate the configured message target. + config.MaxInflightBytes = max(uint64(syncInflightBytes), cfg.MaxSizePerMsg) } rawNode, err := etcdraft.NewRawNode(config) if err != nil { @@ -1158,7 +1171,9 @@ func waitForEngineSignal(ctx context.Context, engine *Engine, ready <-chan struc select { case <-ctx.Done(): if closeOnCancel { - _ = engine.Close() + if closeErr := engine.Close(); engine.snapshotShutdownError() != nil { + return errors.Join(errors.WithStack(ctx.Err()), closeErr) + } } return errors.WithStack(ctx.Err()) case <-ready: @@ -1179,7 +1194,7 @@ func (e *Engine) Close() error { close(e.closeCh) }) <-e.doneCh - if err := e.currentError(); err != nil && !errors.Is(err, errClosed) { + if err := e.currentError(); err != nil && (e.snapshotShutdownError() != nil || !errors.Is(err, errClosed)) { return err } return nil @@ -2079,6 +2094,15 @@ func (e *Engine) handleEvent(tick <-chan time.Time) (bool, error) { if e.tryHandlePriorityStep() { return true, nil } + if e.pendingProtectedBatchEvent != nil { + return e.handlePendingProtectedBatchEvent(tick) + } + if e.pendingProtectedStep != nil { + request := *e.pendingProtectedStep + e.pendingProtectedStep = nil + e.handleProtectedAppendQueue(request, tick) + return true, nil + } return e.handleBlockingEvent(tick) } @@ -2103,9 +2127,9 @@ func (e *Engine) handleBlockingEvent(tick <-chan time.Time) (bool, error) { //no return false, err } case req := <-e.proposeCh: - e.handleProposal(req) + e.handleProposalTurn(req, tick) case req := <-e.readCh: - e.handleReadQueue(req) + e.handleReadQueueWithTick(req, tick) case req := <-e.adminCh: e.handleAdmin(req) case msg := <-e.priorityStepCh: @@ -2113,7 +2137,7 @@ func (e *Engine) handleBlockingEvent(tick <-chan time.Time) (bool, error) { //no case request := <-e.protectedPriorityStepCh: e.handleProtectedStep(request) case request := <-e.protectedStepCh: - e.handleProtectedStep(request) + e.handleProtectedAppendQueue(request, tick) case msg := <-e.stepCh: e.handleStep(msg) case report := <-e.dispatchReportCh: @@ -2168,38 +2192,103 @@ func (e *Engine) tryReceivePriorityStep() (raftpb.Message, bool) { // does not silently stall. type dispatchReport struct { to uint64 + appendTerm uint64 + appendLast uint64 msgType raftpb.MessageType snapshotFinish bool snapshotTerm uint64 snapshotRetry bool } +func (e *Engine) failedDispatchReport(msg raftpb.Message) dispatchReport { + report := dispatchReport{to: msg.GetTo(), msgType: msg.GetType()} + if report.msgType != raftpb.MsgApp || msg.GetFrom() == 0 || msg.GetFrom() != e.nodeID || + report.to == 0 || report.to == e.nodeID || msg.Snapshot != nil || msg.Index == nil || msg.LogTerm == nil { + return report + } + if last := contiguousDispatchAppendLast(&msg); last != 0 { + report.appendTerm, report.appendLast = msg.GetTerm(), last + } + return report +} + +func contiguousDispatchAppendLast(msg *raftpb.Message) uint64 { + last, term := msg.GetIndex(), msg.GetLogTerm() + if len(msg.Entries) == 0 || (last == 0) != (term == 0) { + return 0 + } + // A leader can retransmit entries from earlier terms. Log terms may + // increase across the range, including at the predecessor boundary. + for _, entry := range msg.Entries { + index, entryTerm := entry.GetIndex(), entry.GetTerm() + if index == 0 || index != last+1 || entryTerm == 0 || entryTerm < term || entryTerm > msg.GetTerm() { + return 0 + } + last, term = index, entryTerm + } + return last +} + +func (e *Engine) acknowledgedDispatchAppend(report dispatchReport) bool { + if report.msgType != raftpb.MsgApp || report.appendTerm == 0 || report.appendLast == 0 { + return false + } + status := e.rawNode.BasicStatus() + if status.RaftState != etcdraft.StateLeader || status.GetTerm() != report.appendTerm { + return false + } + // Read the current membership's acknowledged prefix on the RawNode owner. + // Next and inflights can already include entries that never reached the peer. + acked := false + e.rawNode.WithProgress(func(id uint64, _ etcdraft.ProgressType, pr tracker.Progress) { + if id == report.to { + acked = pr.Match >= report.appendLast + } + }) + return acked +} + func (e *Engine) handleDispatchReport(report dispatchReport) { if e.rawNode == nil { return } // MsgSnap requires the distinct SnapshotFailure path: raft tracks // PendingSnapshot in Progress, and only ReportSnapshot clears it. - // All other message types use ReportUnreachable, which transitions the + // Other outstanding failures use ReportUnreachable, which transitions the // peer from StateReplicate to StateProbe so the next heartbeat response // drives a fresh sendAppend attempt. if report.msgType == raftpb.MsgSnap { - if report.snapshotTerm != 0 && report.snapshotTerm != e.rawNode.BasicStatus().GetTerm() { - return - } - if pd := e.peerDispatchers[report.to]; report.snapshotRetry && pd != nil { - pd.snapshotRetryAt = time.Now().Add(snapshotTransferRetryDelay) - } - status := etcdraft.SnapshotFailure - if report.snapshotFinish { - status = etcdraft.SnapshotFinish + e.handleSnapshotDispatchReport(report) + return + } + if err := e.withNative(context.Background(), nil, func() error { + // This local feedback reads Match. Protected peer responses pass + // receipt admission at Step. Shutdown can win after the owner + // selects the report and before it enters this native scope. + if e.isClosing() { + return nil } - if err := e.withNative(context.Background(), nil, func() error { e.rawNode.ReportSnapshot(report.to, status); return nil }); err != nil { - e.fail(err) + if !e.acknowledgedDispatchAppend(report) { + e.rawNode.ReportUnreachable(report.to) } + return nil + }); err != nil { + e.fail(err) + } +} + +func (e *Engine) handleSnapshotDispatchReport(report dispatchReport) { + if report.snapshotTerm != 0 && report.snapshotTerm != e.rawNode.BasicStatus().GetTerm() { return } - if err := e.withNative(context.Background(), nil, func() error { e.rawNode.ReportUnreachable(report.to); return nil }); err != nil { + if pd := e.peerDispatchers[report.to]; report.snapshotRetry && pd != nil { + pd.snapshotRetryAt = time.Now().Add(snapshotTransferRetryDelay) + } + status := etcdraft.SnapshotFailure + if report.snapshotFinish { + status = etcdraft.SnapshotFinish + } + if err := e.withNative(context.Background(), nil, func() error { e.rawNode.ReportSnapshot(report.to, status); return nil }); err != nil { e.fail(err) } } @@ -2254,12 +2343,8 @@ func (e *Engine) handleProposal(req proposalRequest) { req.done <- proposalResult{err: errors.WithStack(errNotLeader)} return } - if req.expectedTerm != 0 && e.rawNode.BasicStatus().GetTerm() != req.expectedTerm { - req.done <- proposalResult{err: raftengine.ErrStaleAdmissionTerm} - return - } - if index := raftengine.ProposalConfigurationFence(req.ctx); index != 0 && !e.proposalConfigurationMatches(index) { - req.done <- proposalResult{err: raftengine.ErrProposalConfigurationChanged} + if err := e.checkProposalFences(req); err != nil { + req.done <- proposalResult{err: err} return } // etcd/raft drops proposals while a leadership transfer is in flight @@ -2271,10 +2356,15 @@ func (e *Engine) handleProposal(req proposalRequest) { req.done <- proposalResult{err: errors.WithStack(errLeadershipTransferInProgress)} return } - e.storePendingProposal(req) + if !e.storePendingProposal(req) { + return + } request := &raftengine.NativeRequest{Operation: raftengine.NativeProposal, Payload: req.payload, PayloadDigest: req.payloadDigest} envelope := encodeProposalEnvelope(req.id, req.payload) if err := e.withNative(req.ctx, request, func() error { + if err := e.checkVersionCASProposal(req); err != nil { + return err + } return e.rawNode.Propose(envelope) }); err != nil { e.cancelPendingProposal(req.id) @@ -2282,6 +2372,16 @@ func (e *Engine) handleProposal(req proposalRequest) { } } +func (e *Engine) checkProposalFences(req proposalRequest) error { + if req.expectedTerm != 0 && e.rawNode.BasicStatus().GetTerm() != req.expectedTerm { + return raftengine.ErrStaleAdmissionTerm + } + if index := raftengine.ProposalConfigurationFence(req.ctx); index != 0 && !e.proposalConfigurationMatches(index) { + return raftengine.ErrProposalConfigurationChanged + } + return nil +} + func (e *Engine) proposalConfigurationMatches(index uint64) bool { e.mu.RLock() joint := e.redisFenceGCJointConfig @@ -2298,7 +2398,9 @@ func (e *Engine) handleRead(req readRequest) { req.done <- readResult{err: err} return } - e.storePendingRead(req) + if !e.storePendingRead(req) { + return + } request := &raftengine.NativeRequest{Operation: raftengine.NativeReadIndex} if req.recovery { request.Operation = raftengine.NativeRecoveryReadIndex @@ -2535,6 +2637,9 @@ func (e *Engine) drainReady() error { } for { rd := e.rawNode.Ready() + if e.syncObserver != nil { + e.syncObserver.observeReady(rd.Messages) + } e.invalidateNativeAuthority() dispatchReady, err := e.dispatchParallelAppend(rd) if err != nil { @@ -2625,43 +2730,45 @@ func (e *Engine) handleStep(msg raftpb.Message) { e.handleStepWithAdmission(msg, &raftengine.NativeRequest{Operation: raftengine.NativePeerStep}, func(action func() error) error { return action() }) } -func (e *Engine) handleStepWithAdmission(msg raftpb.Message, request *raftengine.NativeRequest, admit func(func() error) error) { +// The result reports error-free Step admission, not persistence or an ACK. +func (e *Engine) handleStepWithAdmission(msg raftpb.Message, request *raftengine.NativeRequest, admit func(func() error) error) bool { if e.rawNode == nil { - return + return false } commitBeforeStep := e.rawNode.BasicStatus().GetCommit() err := e.mutateNative(context.Background(), request, msg.GetType() == raftpb.MsgSnap, func() error { return admit(func() error { e.recordLeaderContact(msg) e.recordQuorumAck(msg) - return e.rawNode.Step(&msg) + return e.stepRawNode(&msg) }) }) if err != nil { if errors.Is(err, peersession.ErrDenied) || errors.Is(err, raftengine.ErrNativeAdmissionDenied) || errors.Is(err, context.Canceled) { e.removeReceivedFSMSnapshotToken(msg) e.unprotectReceivedFSMSnapshotToken(msg) - return + return false } if errors.Is(err, etcdraft.ErrStepPeerNotFound) { e.removeReceivedFSMSnapshotToken(msg) e.unprotectReceivedFSMSnapshotToken(msg) - return + return false } e.fail(errors.WithStack(err)) - return + return false } if e.unprotectReceivedFSMSnapshotTokenIfCommitted(msg, commitBeforeStep) { e.removeReceivedFSMSnapshotToken(msg) - return + return true } if !e.rawNode.HasReady() { e.removeReceivedFSMSnapshotToken(msg) e.unprotectReceivedFSMSnapshotToken(msg) - return + return true } e.trackReceivedFSMSnapshotStep(msg) e.unprotectReceivedFSMSnapshotTokenIfApplied(msg) + return true } // recordQuorumAck updates the per-peer last-response time when msg is @@ -2770,7 +2877,7 @@ func (e *Engine) skipDispatchMessage(msg raftpb.Message) bool { func (e *Engine) enqueueDispatchMessage(msg raftpb.Message) error { pd, ok := e.peerDispatchers[msg.GetTo()] if !ok { - e.recordDroppedDispatch(msg) + e.recordDroppedDispatch(msg, false) return nil } if msg.GetType() == raftpb.MsgSnap && time.Now().Before(pd.snapshotRetryAt) { @@ -2782,10 +2889,10 @@ func (e *Engine) enqueueDispatchMessage(msg raftpb.Message) error { // is already full. The len/cap check is safe here because this function is // only ever called from the single engine event-loop goroutine. if len(ch) >= cap(ch) { - if msg.GetType() == raftpb.MsgHeartbeatResp && e.coalesceHeartbeatResp(ch, msg) { + if msg.GetType() == raftpb.MsgHeartbeatResp && ch != pd.readIndexResp && e.coalesceHeartbeatResp(ch, msg) { return nil } - e.recordDroppedDispatch(msg) + e.recordDroppedDispatch(msg, ch != nil) return nil } return e.queueDispatchRequest(ch, msg) @@ -2794,7 +2901,7 @@ func (e *Engine) enqueueDispatchMessage(msg raftpb.Message) error { func (e *Engine) queueDispatchRequest(ch chan dispatchRequest, msg raftpb.Message) error { dispatchReq, admitted := e.tryPrepareOwnedDispatchRequest(msg) if !admitted { - e.recordDroppedDispatch(msg) + e.recordDroppedDispatch(msg, false) return nil } if msg.GetType() == raftpb.MsgSnap && e.dispatchCtx != nil && e.rawNode != nil { @@ -2805,7 +2912,7 @@ func (e *Engine) queueDispatchRequest(ch chan dispatchRequest, msg raftpb.Messag return nil default: _ = dispatchReq.Close() - e.recordDroppedDispatch(msg) + e.recordDroppedDispatch(msg, ch != nil) return nil } } @@ -2958,6 +3065,9 @@ func (e *Engine) applyReadySnapshotLocked(snapshot *raftpb.Snapshot) error { } e.snapshotRestoring.Store(true) e.invalidateAdmission() + if err := e.retireLocalSnapshotLocked(); err != nil { + return err + } // etcdraft.IsEmptySnap only validates the raft metadata. This backend also // requires FSM payload bytes so it can restore local state before applying // the metadata snapshot to MemoryStorage. @@ -3210,19 +3320,14 @@ func snapshotDeferred(err error, site string, index uint64) bool { func (e *Engine) enqueueSnapshotRequest(req snapshotRequest) error { select { case <-e.doneCh: - if req.snapshot != nil { - _ = req.snapshot.Close() - } - return e.currentErrorOrClosed() case <-e.snapshotStopCh: - if req.snapshot != nil { - _ = req.snapshot.Close() - } - return e.currentErrorOrClosed() case e.snapshotReqCh <- req: e.snapshotInFlight = true return nil } + e.snapshotMu.Lock() + defer e.snapshotMu.Unlock() + return errors.Join(e.currentErrorOrClosed(), e.closeLocalSnapshotLocked(req.snapshot)) } func (e *Engine) applyCommitted(entries []raftpb.Entry) error { @@ -4262,7 +4367,15 @@ func (e *Engine) shutdown() { // A storage pipeline must drain its own actors before entering this phase. func (e *Engine) finishShutdown(err error) { e.stopDispatchWorkers() - e.stopSnapshotWorker() + if closeErr := e.stopSnapshotWorker(); closeErr != nil { + e.mu.Lock() + if !errors.Is(e.runErr, closeErr) { + e.runErr = errors.Join(e.runErr, closeErr) + } + err = e.runErr + e.mu.Unlock() + e.readinessFailed.Store(true) + } _ = closePersist(e.persist) if err := e.transport.Close(); err != nil { slog.Warn("etcd raft engine: transport close", @@ -4271,6 +4384,8 @@ func (e *Engine) finishShutdown(err error) { ) } e.failPending(err) + e.pendingProtectedStep = nil + e.pendingProtectedBatchEvent = nil } func (e *Engine) fail(err error) { @@ -4297,6 +4412,7 @@ func (e *Engine) fail(err error) { func (e *Engine) failPending(err error) { proposals, reads, configs := e.drainPending() + e.failPendingProtectedBatchEvent(err) for _, req := range proposals { req.done <- proposalResult{err: err} } @@ -4308,11 +4424,16 @@ func (e *Engine) failPending(err error) { } } -func (e *Engine) storePendingProposal(req proposalRequest) { +func (e *Engine) storePendingProposal(req proposalRequest) bool { req.payload = nil e.pending.Lock() defer e.pending.Unlock() + if err := contextErr(req.ctx); err != nil { + req.done <- proposalResult{err: err} + return false + } e.pendingProposals[req.id] = req + return true } func (e *Engine) popPendingProposal(id uint64) (proposalRequest, bool) { @@ -4334,10 +4455,15 @@ func (e *Engine) cancelPendingProposal(id uint64) { e.pending.Unlock() } -func (e *Engine) storePendingRead(req readRequest) { +func (e *Engine) storePendingRead(req readRequest) bool { e.pending.Lock() defer e.pending.Unlock() + if err := contextErr(req.ctx); err != nil { + req.done <- readResult{err: err} + return false + } e.pendingReads[req.id] = req + return true } func (e *Engine) pendingRead(id uint64) (readRequest, bool) { @@ -5157,25 +5283,30 @@ func (e *Engine) handleDispatchRequest(ctx context.Context, req dispatchRequest) if errors.Is(dispatchErr, ctx.Err()) { return } + e.recordDispatchFailure(&req.msg, dispatchErr) + // A refused heartbeat leaves queued appends intact. Even a delayed + // refusal must not rewind the peer's current replication progress. + if req.msg.GetType() == raftpb.MsgHeartbeat && isHeartbeatIngressFull(dispatchErr) { + return + } + e.reportFailedDispatch(req.msg) +} + +func (e *Engine) recordDispatchFailure(msg *raftpb.Message, dispatchErr error) { code := dispatchErrorCodeOf(dispatchErr) count := e.recordDispatchErrorCode(code) if shouldLogDispatchEvent(count) { if logger := slog.Default(); logger.Enabled(context.Background(), slog.LevelWarn) { logger.Warn("etcd raft outbound dispatch failed", "node_id", e.nodeID, - "to", req.msg.GetTo(), - "type", req.msg.GetType().String(), + "to", msg.GetTo(), + "type", msg.GetType().String(), "dispatch_error_count", count, "code", code, "err", dispatchErr, ) } } - // Inform etcd/raft that the peer is unreachable so Progress transitions - // out of StateReplicate / StateSnapshot. Without this the leader keeps - // Progress stuck and never retries sendAppend/sendSnap for the peer, - // leaving the follower indefinitely stale even after heartbeats resume. - e.reportFailedDispatch(req.msg) } func (e *Engine) reportSuccessfulDispatch(msg raftpb.Message) { @@ -5223,6 +5354,13 @@ func (e *Engine) runSnapshotWorker(ctx context.Context) { index: req.index, err: e.persistLocalSnapshotWithContext(ctx, req), } + if result.err != nil && !errors.Is(result.err, errCatchUpSnapshotWrite) { + if e.snapshotWorkerErr == nil { + e.snapshotWorkerErr = result.err + } else { + e.snapshotWorkerErr = errors.Join(e.snapshotWorkerErr, result.err) + } + } select { case <-e.snapshotStopCh: return @@ -5232,7 +5370,7 @@ func (e *Engine) runSnapshotWorker(ctx context.Context) { } } -func (e *Engine) stopSnapshotWorker() { +func (e *Engine) stopSnapshotWorker() error { e.snapshotOnce.Do(func() { if e.snapshotStopCh != nil { close(e.snapshotStopCh) @@ -5241,14 +5379,9 @@ func (e *Engine) stopSnapshotWorker() { e.snapshotCancel() } e.snapshotWG.Wait() - select { - case req := <-e.snapshotReqCh: - if err := req.snapshot.Close(); err != nil { - slog.Warn("close queued FSM snapshot", "index", req.index, "error", err) - } - default: - } + e.drainLocalSnapshots() }) + return e.snapshotShutdownError() } func (e *Engine) leaderInfo(leaderNodeID uint64) raftengine.LeaderInfo { @@ -5537,7 +5670,7 @@ func shouldLogDispatchEvent(count uint64) bool { return count == 1 || count%128 == 0 } -func (e *Engine) recordDroppedDispatch(msg raftpb.Message) { +func (e *Engine) recordDroppedDispatch(msg raftpb.Message, laneFull bool) { count := e.dispatchDropCount.Add(1) if shouldLogDispatchEvent(count) { if logger := slog.Default(); logger.Enabled(context.Background(), slog.LevelWarn) { @@ -5549,11 +5682,16 @@ func (e *Engine) recordDroppedDispatch(msg raftpb.Message) { ) } } + // A full heartbeat lane says nothing about the peer's append FIFO. + // Raft retries heartbeats (including pending reads) on its normal tick. + if laneFull && msg.GetType() == raftpb.MsgHeartbeat { + return + } e.reportDroppedDispatch(msg) } func (e *Engine) reportDroppedDispatch(msg raftpb.Message) { - report := dispatchReport{to: msg.GetTo(), msgType: msg.GetType()} + report := e.failedDispatchReport(msg) if msg.GetType() == raftpb.MsgSnap { e.deferReadyDispatchReport(report) return @@ -5565,7 +5703,7 @@ func (e *Engine) reportDroppedDispatch(msg raftpb.Message) { } func (e *Engine) reportFailedDispatch(msg raftpb.Message) { - report := dispatchReport{to: msg.GetTo(), msgType: msg.GetType()} + report := e.failedDispatchReport(msg) if msg.GetType() == raftpb.MsgSnap { report.snapshotTerm = msg.GetTerm() report.snapshotRetry = true @@ -5674,11 +5812,11 @@ func (e *Engine) persistLocalSnapshot(req snapshotRequest) error { func (e *Engine) persistLocalSnapshotWithContext(ctx context.Context, req snapshotRequest) error { ctx, release := snapshotTermContext(ctx, req.leadership) defer release() - if ctx.Err() != nil { - return errors.WithStack(req.snapshot.Close()) - } if e.fsmSnapDir == "" { // No fsmSnapDir set (in-memory or test engine): use the legacy path. + if ctx.Err() != nil { + return errors.WithStack(req.snapshot.Close()) + } payload, err := snapshotBytesAndClose(req.snapshot, e.dataDir) if err != nil { return err @@ -5690,16 +5828,36 @@ func (e *Engine) persistLocalSnapshotWithContext(ctx context.Context, req snapsh e.snapshotMu.Lock() defer e.snapshotMu.Unlock() - current, err := e.storage.Snapshot() - if err != nil { - return errors.Join(errors.WithStack(err), errors.WithStack(req.snapshot.Close())) + if ctx.Err() != nil { + return e.closeLocalSnapshotLocked(req.snapshot) } - if req.index <= current.GetMetadata().GetIndex() || e.protectedReceivedFSMSnaps[req.index] > 0 { - return errors.WithStack(req.snapshot.Close()) + if ready, err := e.localSnapshotExportReadyLocked(req); !ready || err != nil { + return err } return e.writeAndPublishLocalSnapshot(ctx, req) } +// After the payload stream completes, the file writer still has buffered bytes +// to flush and a file to sync, close, rename and directory-sync. +type catchUpSnapshotExport struct { + limitedCatchUpSnapshot + payloadComplete bool +} + +func (s *catchUpSnapshotExport) WriteTo(w io.Writer) (int64, error) { + n, err := s.limitedCatchUpSnapshot.WriteTo(w) + s.payloadComplete = err == nil + return n, err +} + +func (s *catchUpSnapshotExport) retryableWrite(err error) bool { + if !s.payloadComplete || errors.Is(err, io.ErrShortWrite) { + return true + } + var fileErr *os.PathError + return errors.As(err, &fileErr) && fileErr.Op == "write" +} + func (e *Engine) writeAndPublishLocalSnapshot(ctx context.Context, req snapshotRequest) error { if err := e.prepareFSMSnapshotWrite(req.index); err != nil { slog.Warn("failed to prepare fsm snapshot write", @@ -5708,19 +5866,19 @@ func (e *Engine) writeAndPublishLocalSnapshot(ctx context.Context, req snapshotR ) } snapshot := req.snapshot - var limited *limitedCatchUpSnapshot + var limited *catchUpSnapshotExport start := time.Now() if req.forNewMember { - limited = &limitedCatchUpSnapshot{Snapshot: snapshot, ctx: ctx} + limited = &catchUpSnapshotExport{limitedCatchUpSnapshot: limitedCatchUpSnapshot{Snapshot: snapshot, ctx: ctx}} snapshot = limited slog.Info("etcd raft catch-up snapshot started", "group_id", e.groupID, "node_id", e.nodeID, "index", req.index) } crc32c, writeErr := writeFSMSnapshotFile(snapshot, e.fsmSnapDir, req.index) - if closeErr := snapshot.Close(); closeErr != nil { - return errors.Join(writeErr, errors.WithStack(closeErr)) + if closeErr := e.closeLocalSnapshotLocked(req.snapshot); closeErr != nil { + return errors.Join(writeErr, closeErr) } if writeErr != nil { - if req.forNewMember { + if limited != nil && limited.retryableWrite(writeErr) { return errors.WithStack(errors.Mark(writeErr, errCatchUpSnapshotWrite)) } return writeErr diff --git a/internal/raftengine/etcd/engine_dispatch_budget.go b/internal/raftengine/etcd/engine_dispatch_budget.go index 9817b1072..186aaee5a 100644 --- a/internal/raftengine/etcd/engine_dispatch_budget.go +++ b/internal/raftengine/etcd/engine_dispatch_budget.go @@ -13,6 +13,9 @@ const outboundCapacityFactor = 2 // completion report is not retirement: Close follows the last dispatch use. func (e *Engine) tryPrepareOwnedDispatchRequest(message raftpb.Message) (dispatchRequest, bool) { if e.storagePipeline == nil { + if e.syncObserver != nil { + e.syncObserver.observeAppend(&message, true) + } return prepareDispatchRequest(message), true } p := e.storagePipeline diff --git a/internal/raftengine/etcd/engine_snapshot_disk_phases_test.go b/internal/raftengine/etcd/engine_snapshot_disk_phases_test.go index 642f99862..fda777ef3 100644 --- a/internal/raftengine/etcd/engine_snapshot_disk_phases_test.go +++ b/internal/raftengine/etcd/engine_snapshot_disk_phases_test.go @@ -470,7 +470,7 @@ func TestEngineSnapshotDiskPhasesLocalWaitsForRelease(t *testing.T) { t.Cleanup(func() { unblockSave() unblockRelease() - e.stopSnapshotWorker() + require.NoError(t, e.stopSnapshotWorker()) }) require.NoError(t, e.enqueueSnapshotRequest(snapshotRequest{index: configPhaseIndex, snapshot: &testSnapshot{data: []byte("prefix")}})) testutil.Closed(t, saveEntered, time.Second, "SaveSnap did not start") diff --git a/internal/raftengine/etcd/engine_storage_pipeline.go b/internal/raftengine/etcd/engine_storage_pipeline.go index c1f7884eb..3c83ea66c 100644 --- a/internal/raftengine/etcd/engine_storage_pipeline.go +++ b/internal/raftengine/etcd/engine_storage_pipeline.go @@ -320,7 +320,7 @@ func (e *Engine) routePipelineResponses(messages []*raftpb.Message) error { func (e *Engine) stepPipelineResponse(message *raftpb.Message) error { term := e.rawNode.BasicStatus().GetTerm() - if err := e.rawNode.Step(message); err != nil { + if err := e.stepRawNode(message); err != nil { return errors.WithStack(err) } if message.GetType() == raftpb.MsgStorageAppendResp { @@ -455,14 +455,20 @@ func (e *Engine) handlePipelineReadStates(states []etcdraft.ReadState) { if owned := e.storagePipeline.readOwnership[id]; owned != nil { owned.ready, owned.pendingCommit = true, false } - if req, found := e.pendingRead(id); found { - req.target, req.waitApplied = state.Index, true - e.storePendingRead(req) - } + e.recordPipelineReadIndex(id, state.Index) } } } +func (e *Engine) recordPipelineReadIndex(id, index uint64) { + e.pending.Lock() + defer e.pending.Unlock() + if req, found := e.pendingReads[id]; found { + req.target, req.waitApplied = index, true + e.pendingReads[id] = req + } +} + func detachPipelineMessage(message *raftpb.Message) { // Detach pointer arrays without copying user data. Task lifetime must not // pin an unrelated unstable suffix through an upstream slice's capacity. @@ -743,7 +749,7 @@ func (e *Engine) stepPipelineOwner(message *raftpb.Message) error { return e.queuePipelineReceivedFront(message) } e.recordLeaderContact(*message) - if err := e.rawNode.Step(message); err != nil { + if err := e.stepRawNode(message); err != nil { if errors.Is(err, etcdraft.ErrStepPeerNotFound) { return nil } @@ -1024,6 +1030,7 @@ func (e *Engine) finishStoragePipeline() { // Closed completion channels precede worker done; join the final epilogue. <-p.disk.done <-p.apply.done + e.nativeConfigurationCache = nil e.rawNode = nil p.failedReady = nil p.failedReadyPermit.Release() diff --git a/internal/raftengine/etcd/engine_storage_pipeline_configuration_test.go b/internal/raftengine/etcd/engine_storage_pipeline_configuration_test.go index cb63d0da6..8b43516c9 100644 --- a/internal/raftengine/etcd/engine_storage_pipeline_configuration_test.go +++ b/internal/raftengine/etcd/engine_storage_pipeline_configuration_test.go @@ -457,8 +457,11 @@ func TestEnginePipelineConfigurationSelfRemovalPublishesAndJoins(t *testing.T) { index := asyncStorageAwait(t, h, gate.entered, "self-removal SaveSnap") require.Less(t, h.engine.currentConfigIndex(), index) require.True(t, h.engine.LastQuorumAck().IsZero()) + require.True(t, h.engine.configurationTransition.Load()) gate.unblock() - require.Eventually(t, func() bool { return h.engine.currentConfigIndex() == index }, 5*time.Second, time.Millisecond) + // The configuration and applied indexes are separate publications. + require.Eventually(t, func() bool { return !h.engine.configurationTransition.Load() }, 5*time.Second, time.Millisecond) + require.Equal(t, index, h.engine.currentConfigIndex()) require.GreaterOrEqual(t, h.engine.AppliedIndex(), index) h.engine.mu.RLock() _, present := h.engine.peers[1] diff --git a/internal/raftengine/etcd/engine_storage_pipeline_control.go b/internal/raftengine/etcd/engine_storage_pipeline_control.go index b6e328c39..cfd8b0e80 100644 --- a/internal/raftengine/etcd/engine_storage_pipeline_control.go +++ b/internal/raftengine/etcd/engine_storage_pipeline_control.go @@ -86,7 +86,11 @@ func (e *Engine) admitPipelineRead(request readRequest) { } p.readOwnership[request.id] = &pipelineReadOwnership{permit: permit, term: status.GetTerm(), pendingCommit: !e.pipelineCurrentTermCommitted()} - e.storePendingRead(request) + if !e.storePendingRead(request) { + delete(p.readOwnership, request.id) + permit.Release() + return + } e.rawNode.ReadIndex(encodeReadContext(request.id)) } diff --git a/internal/raftengine/etcd/engine_storage_pipeline_snapshot_receive.go b/internal/raftengine/etcd/engine_storage_pipeline_snapshot_receive.go index eacac1a27..290eeda28 100644 --- a/internal/raftengine/etcd/engine_storage_pipeline_snapshot_receive.go +++ b/internal/raftengine/etcd/engine_storage_pipeline_snapshot_receive.go @@ -29,7 +29,7 @@ func (e *Engine) queuePipelineReceivedFrontWithLease(message *raftpb.Message, le if err := e.queuePipelineSnapshotDisk(plan, pipelineReceivedDiscard); err != nil { return err } - return errors.WithStack(e.rawNode.Step(message)) + return errors.WithStack(e.stepRawNode(message)) } plan, err := e.newPipelineSnapshotPlanWithLease(message, lease) if err != nil { @@ -72,7 +72,7 @@ func (e *Engine) frontPipelineReceivedSnapshot(request *pipelineSnapshotRequest) e.singleNodeLeaderAckMonoNs.Store(0) e.fireLeaderLossCallbacks() e.recordLeaderContact(*plan.message) - if err := e.rawNode.Step(plan.message); err != nil { + if err := e.stepRawNode(plan.message); err != nil { request.reply <- err return errors.WithStack(err) } diff --git a/internal/raftengine/etcd/engine_storage_pipeline_snapshot_view.go b/internal/raftengine/etcd/engine_storage_pipeline_snapshot_view.go index 18a6c6e48..35868ff0f 100644 --- a/internal/raftengine/etcd/engine_storage_pipeline_snapshot_view.go +++ b/internal/raftengine/etcd/engine_storage_pipeline_snapshot_view.go @@ -93,6 +93,7 @@ func (e *Engine) attachPipelineSnapshotView(cfg OpenConfig, selected *raftpb.Sna if err != nil { return err } + e.nativeConfigurationCache = nil e.rawNode = raw if len(selected.Data) == 0 { view.publish(selected, true) diff --git a/internal/raftengine/etcd/engine_test.go b/internal/raftengine/etcd/engine_test.go index 2193a757e..4328f2e88 100644 --- a/internal/raftengine/etcd/engine_test.go +++ b/internal/raftengine/etcd/engine_test.go @@ -304,6 +304,7 @@ func TestOpenConfigMaxInflightSizesInboundQueues(t *testing.T) { }) require.Equal(t, minInboundQueueCapacity, cap(engine.stepCh)) + require.Equal(t, minInboundQueueCapacity, cap(engine.protectedStepCh)+1, "one slot belongs to the deferred normal boundary") require.Equal(t, minInboundQueueCapacity, cap(engine.dispatchReportCh)) } @@ -1171,7 +1172,7 @@ func TestMaybePersistLocalSnapshotRunsInBackground(t *testing.T) { engine.startSnapshotWorker() t.Cleanup(func() { release() - engine.stopSnapshotWorker() + require.NoError(t, engine.stopSnapshotWorker()) }) done := make(chan struct{}) diff --git a/internal/raftengine/etcd/external_restore_origin.go b/internal/raftengine/etcd/external_restore_origin.go index b2b7a52b5..add7880a0 100644 --- a/internal/raftengine/etcd/external_restore_origin.go +++ b/internal/raftengine/etcd/external_restore_origin.go @@ -61,6 +61,14 @@ func writeExternalRestoreOrigin(dir string, opts ExternalSnapshotRestoreOptions, return syncDir(dir) } +// HasExternalRestoreOrigin reports whether this data directory descends from +// an offline external snapshot rebase. The marker survives later restarts and +// native snapshots. +func HasExternalRestoreOrigin(dir string) (bool, error) { + marker, err := readExternalRestoreOrigin(dir) + return marker != nil, err +} + func readExternalRestoreOrigin(dir string) (*externalRestoreOrigin, error) { f, err := openRegularExternalFSMInput(filepath.Join(dir, externalRestoreOriginFile)) if os.IsNotExist(errors.UnwrapAll(err)) { diff --git a/internal/raftengine/etcd/external_restore_origin_test.go b/internal/raftengine/etcd/external_restore_origin_test.go index 5ac1cbf2c..158a8381c 100644 --- a/internal/raftengine/etcd/external_restore_origin_test.go +++ b/internal/raftengine/etcd/external_restore_origin_test.go @@ -228,6 +228,12 @@ func TestExternalOriginSuccessfulOpenRetainsCompletedBinding(t *testing.T) { require.NoError(t, err) require.NotNil(t, marker) require.True(t, marker.Completed) + rebased, err := HasExternalRestoreOrigin(dir) + require.NoError(t, err) + require.True(t, rebased, "CAS must still see the origin after the external restore finishes") + rebased, err = HasExternalRestoreOrigin(t.TempDir()) + require.NoError(t, err) + require.False(t, rebased) require.NoError(t, engine.Close()) require.Equal(t, []raftengine.SnapshotRestoreOrigin{raftengine.SnapshotRestoreExternalRebase}, fsm.origins) // Completion never lets the original bytes bypass origin validation. diff --git a/internal/raftengine/etcd/grpc_transport.go b/internal/raftengine/etcd/grpc_transport.go index 32deef6bb..f26914a15 100644 --- a/internal/raftengine/etcd/grpc_transport.go +++ b/internal/raftengine/etcd/grpc_transport.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "context" + stderrors "errors" "io" "log/slog" "os" @@ -18,6 +19,7 @@ import ( raftpb "go.etcd.io/raft/v3/raftpb" "golang.org/x/sync/singleflight" "golang.org/x/time/rate" + "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -1066,10 +1068,45 @@ func (t *GRPCTransport) handleRaftRequest(ctx context.Context, req *pb.EtcdRaftM if err := proto.Unmarshal(req.Message, &msg); err != nil { return errors.WithStack(err) } - if err := t.handle(ctx, msg); err != nil { + err := t.handle(ctx, msg) + if msg.GetType() != raftpb.MsgHeartbeat || !stderrors.Is(err, errStepQueueFull) { return err } - return nil + st, detailErr := status.New(codes.ResourceExhausted, err.Error()).WithDetails(&errdetails.ErrorInfo{ + Domain: raftTransportErrorDomain, Reason: heartbeatIngressFullReason, + }) + if detailErr != nil { + return err + } + return &heartbeatIngressError{error: err, status: st} +} + +const ( + raftTransportErrorDomain = "raft.elastickv.bootjp.me" + heartbeatIngressFullReason = "HEARTBEAT_INGRESS_FULL" +) + +// Keep the local cause for in-process callers. Only the status crosses gRPC. +type heartbeatIngressError struct { + error + status *status.Status +} + +func (e *heartbeatIngressError) Unwrap() error { return e.error } +func (e *heartbeatIngressError) GRPCStatus() *status.Status { return e.status } + +func isHeartbeatIngressFull(err error) bool { + st, ok := status.FromError(err) + if !ok || st.Code() != codes.ResourceExhausted { + return false + } + for _, detail := range st.Details() { + if info, ok := detail.(*errdetails.ErrorInfo); ok && + info.Domain == raftTransportErrorDomain && info.Reason == heartbeatIngressFullReason { + return true + } + } + return false } func (t *GRPCTransport) sendSnapshot(ctx context.Context, msg raftpb.Message) error { diff --git a/internal/raftengine/etcd/grpc_transport_overload_test.go b/internal/raftengine/etcd/grpc_transport_overload_test.go new file mode 100644 index 000000000..def593951 --- /dev/null +++ b/internal/raftengine/etcd/grpc_transport_overload_test.go @@ -0,0 +1,104 @@ +package etcd + +import ( + "context" + "net" + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/proto" +) + +func TestGRPCHeartbeatIngressFeedback(t *testing.T) { + receiver := &GRPCTransport{} + listener := bufconn.Listen(1 << 16) + server := grpc.NewServer() + receiver.Register(server) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { server.Stop(); _ = listener.Close() }) + conn, err := grpc.NewClient("passthrough:///peer", grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) })) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + client := pb.NewEtcdRaftClient(conn) + + // Reuse the old error text for unrelated failures to rule out string matching. + reason := func(code codes.Code, domain, reason string) error { + st, err := status.New(code, errStepQueueFull.Error()).WithDetails(&errdetails.ErrorInfo{Domain: domain, Reason: reason}) + require.NoError(t, err) + return st.Err() + } + wrongDetail, err := status.New(codes.ResourceExhausted, errStepQueueFull.Error()).WithDetails(&errdetails.RetryInfo{}) + require.NoError(t, err) + typed := reason(codes.ResourceExhausted, raftTransportErrorDomain, heartbeatIngressFullReason) + for _, tc := range []struct { + name string + kind raftpb.MessageType + injected error // nil exercises a real full ingress channel + code codes.Code + wantReport bool + }{ + {"heartbeat ingress full", raftpb.MsgHeartbeat, nil, codes.ResourceExhausted, false}, + {"response ingress full", raftpb.MsgHeartbeatResp, nil, codes.Unknown, true}, + {"bare exhausted", raftpb.MsgHeartbeat, status.Error(codes.ResourceExhausted, errStepQueueFull.Error()), codes.ResourceExhausted, true}, + {"unrelated local error with same text", raftpb.MsgHeartbeat, errors.New(errStepQueueFull.Error()), codes.Unknown, true}, + {"old peer", raftpb.MsgHeartbeat, status.Error(codes.Unknown, errStepQueueFull.Error()), codes.Unknown, true}, + {"network", raftpb.MsgHeartbeat, status.Error(codes.Unavailable, "connection lost"), codes.Unavailable, true}, + {"wrong code", raftpb.MsgHeartbeat, reason(codes.Unavailable, raftTransportErrorDomain, heartbeatIngressFullReason), codes.Unavailable, true}, + {"wrong detail", raftpb.MsgHeartbeat, wrongDetail.Err(), codes.ResourceExhausted, true}, + {"wrong domain", raftpb.MsgHeartbeat, reason(codes.ResourceExhausted, "other", heartbeatIngressFullReason), codes.ResourceExhausted, true}, + {"wrong reason", raftpb.MsgHeartbeat, reason(codes.ResourceExhausted, raftTransportErrorDomain, "OTHER"), codes.ResourceExhausted, true}, + {"append", raftpb.MsgApp, typed, codes.ResourceExhausted, true}, + {"read response", raftpb.MsgHeartbeatResp, typed, codes.ResourceExhausted, true}, + {"snapshot", raftpb.MsgSnap, typed, codes.ResourceExhausted, true}, + } { + t.Run(tc.name, func(t *testing.T) { + ingress := &Engine{priorityStepCh: make(chan raftpb.Message, 1)} + ingress.priorityStepCh <- raftpb.Message{} + receiver.SetHandler(func(ctx context.Context, msg raftpb.Message) error { + if tc.injected != nil { + return tc.injected + } + return ingress.enqueueStep(ctx, msg) + }) + msg := raftpb.Message{Type: tc.kind.Enum(), To: uint64Ptr(2), Term: uint64Ptr(1), Context: []byte("read")} + raw, err := proto.Marshal(&msg) + require.NoError(t, err) + wire := &pb.EtcdRaftMessage{Message: raw} + if tc.injected == nil { + ack, err := receiver.Send(t.Context(), wire) + require.Nil(t, ack) + require.ErrorIs(t, err, errStepQueueFull) + } + sender := &Engine{dispatchReportCh: make(chan dispatchReport, 1)} + sender.dispatchFn = func(ctx context.Context, _ dispatchRequest) error { + return receiver.dispatchRegularUnary(ctx, client, wire) + } + sender.handleDispatchRequest(t.Context(), dispatchRequest{msg: msg}) + require.Equal(t, map[string]uint64{tc.code.String(): 1}, sender.DispatchErrorCountsByCode()) + if tc.injected == nil { + require.Equal(t, uint64(2), ingress.StepQueueFullCount()) + } + if tc.wantReport { + require.Len(t, sender.dispatchReportCh, 1) + want := dispatchReport{to: 2, msgType: tc.kind} + if tc.kind == raftpb.MsgSnap { + want.snapshotTerm = msg.GetTerm() + want.snapshotRetry = true + } + require.Equal(t, want, <-sender.dispatchReportCh) + } else { + require.Empty(t, sender.dispatchReportCh) + } + }) + } +} diff --git a/internal/raftengine/etcd/learner_test.go b/internal/raftengine/etcd/learner_test.go index 8aecef3a8..960f261c3 100644 --- a/internal/raftengine/etcd/learner_test.go +++ b/internal/raftengine/etcd/learner_test.go @@ -3,12 +3,14 @@ package etcd import ( "context" "os" + "sync" "testing" "time" "github.com/bootjp/elastickv/internal/raftengine" "github.com/cockroachdb/errors" "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" ) // TestAddLearnerReplicatesWithoutCountingAsVoter is the headline M1 @@ -110,6 +112,7 @@ func TestPromoteLearnerSwapsRoleToVoter(t *testing.T) { // learner having actually applied something. var promoteIndex uint64 var promoteErr error + waitForPromotionConfiguration(t, leader.engine.Status, addIndex) require.Eventually(t, func() bool { promoteIndex, promoteErr = leader.engine.PromoteLearner(ctx, nodes[1].peer.ID, addIndex, warmResult.CommitIndex, false) if promoteErr == nil { @@ -267,6 +270,7 @@ func requireLearnerPromoted( minAppliedIndex uint64, ) { t.Helper() + waitForPromotionConfiguration(t, engine.Status, addIndex) var promoteErr error require.Eventually(t, func() bool { _, promoteErr = engine.PromoteLearner(ctx, learnerID, addIndex, minAppliedIndex, false) @@ -275,6 +279,15 @@ func requireLearnerPromoted( require.NoError(t, promoteErr) } +// PromoteLearner checks the index and peer progress in the same Status +// snapshot. Configuration can already list the member before that refresh. +func waitForPromotionConfiguration(t *testing.T, status func() raftengine.Status, index uint64) { + t.Helper() + require.Eventually(t, func() bool { + return status().ConfigurationIndex == index + }, 5*time.Second, 20*time.Millisecond, "leader status must publish configuration %d", index) +} + func requireTransportNodeSuffrage( t *testing.T, ctx context.Context, @@ -360,11 +373,12 @@ func TestPromoteLearnerRejectsNonLearner(t *testing.T) { require.NoError(t, openTransportTestNode(ctx, nodes[1], peers, false)) // Add as a regular voter, then attempt to promote โ€” should fail. - _, err := leader.engine.AddVoter(ctx, nodes[1].peer.ID, nodes[1].peer.Address, 0) + addIndex, err := leader.engine.AddVoter(ctx, nodes[1].peer.ID, nodes[1].peer.Address, 0) require.NoError(t, err) waitForConfigSize(t, leader.engine, 2) + waitForPromotionConfiguration(t, leader.engine.Status, addIndex) - _, err = leader.engine.PromoteLearner(ctx, nodes[1].peer.ID, 0, 0, true) + _, err = leader.engine.PromoteLearner(ctx, nodes[1].peer.ID, addIndex, 0, true) require.Error(t, err) require.True(t, errors.Is(err, errPromoteLearnerNotLearner), "expected errPromoteLearnerNotLearner, got %v", err) } @@ -499,9 +513,68 @@ func TestPromoteLearnerRejectsNotCaughtUp(t *testing.T) { // Demand catch-up to a future index that has not been committed. const unreachableIndex = uint64(1 << 60) + waitForPromotionConfiguration(t, leader.engine.Status, addIndex) _, err = leader.engine.PromoteLearner(ctx, nodes[1].peer.ID, addIndex, unreachableIndex, false) - require.Error(t, err) - require.True(t, errors.Is(err, errPromoteLearnerNotCaughtUp), "expected errPromoteLearnerNotCaughtUp, got %v", err) + require.ErrorIs(t, err, errPromoteLearnerNotCaughtUp) +} + +// The synchronous apply loop clears the entry identity after returning the +// membership receipt and before refreshing Status for this Ready. +type heldLearnerConfiguration struct { + testStateMachine + hold bool + armed chan struct{} + release chan struct{} +} + +func (f *heldLearnerConfiguration) SetApplyEntryIdentity(id raftengine.AppliedEntryIdentity) { + f.hold = id.Type == int32(raftpb.EntryConfChange) +} + +func (f *heldLearnerConfiguration) ClearApplyEntryIdentity() { + if f.hold { + select { + case <-f.armed: + <-f.release + default: + } + } +} + +func TestPromoteLearnerAfterStatusPublication(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + fsm := &heldLearnerConfiguration{armed: make(chan struct{}), release: make(chan struct{})} + engine, err := Open(ctx, OpenConfig{ + NodeID: 1, LocalID: "n1", LocalAddress: "127.0.0.1:7001", + DataDir: t.TempDir(), Bootstrap: true, StateMachine: fsm, + }) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, engine.Close()) }) + release := sync.OnceFunc(func() { close(fsm.release) }) + t.Cleanup(release) + require.Eventually(t, func() bool { return engine.State() == raftengine.StateLeader }, 5*time.Second, 20*time.Millisecond) + close(fsm.armed) + addIndex, err := engine.AddLearner(ctx, "n2", "127.0.0.1:7002", 0) + require.NoError(t, err) + waitForConfigSize(t, engine, 2) + + // Let the owner finish the Ready only after the wait has seen one stale + // snapshot. A wait that accepts the first observation leaves the owner + // paused, so promotion deterministically returns errConfigIndexMismatch. + observed := false + waitForPromotionConfiguration(t, func() raftengine.Status { + if observed { + release() + } + observed = true + return engine.Status() + }, addIndex) + + const unreachableIndex = uint64(1 << 60) + _, err = engine.PromoteLearner(ctx, "n2", addIndex, unreachableIndex, false) + require.ErrorIs(t, err, errPromoteLearnerNotCaughtUp) } // TestJoinAsLearnerAlarmFiresWhenAddedAsVoter exercises the ยง4.5 diff --git a/internal/raftengine/etcd/local_snapshot_catchup_test.go b/internal/raftengine/etcd/local_snapshot_catchup_test.go new file mode 100644 index 000000000..52b767789 --- /dev/null +++ b/internal/raftengine/etcd/local_snapshot_catchup_test.go @@ -0,0 +1,86 @@ +package etcd + +import ( + "context" + "os" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/testutil" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func TestOwnedCatchUpSnapshotCancelledBeforeExport(t *testing.T) { + f := newOwnershipFixture(t, false) + e := f.e + req, err := e.captureLocalSnapshotRequest(e.applied) + require.NoError(t, err) + req.forNewMember = true + leadership, cancel := context.WithCancel(t.Context()) + req.leadership = leadership + cancel() + + require.NoError(t, e.persistLocalSnapshot(req)) + require.NoError(t, e.stopSnapshotWorker()) + require.Zero(t, f.fsm.probe.writes.Load()) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + require.NoFileExists(t, fsmSnapPath(e.fsmSnapDir, req.index)) +} + +func TestOwnedCatchUpSnapshotWorkerFailures(t *testing.T) { + for _, phase := range []string{"write", "cancel-during-write", "write-and-close", "rename"} { + t.Run(phase, func(t *testing.T) { + f := newOwnershipFixture(t, false) + e := f.e + req, err := e.captureLocalSnapshotRequest(e.applied) + require.NoError(t, err) + req.forNewMember = true + e.startSnapshotWorker() + t.Cleanup(func() { _ = e.stopSnapshotWorker() }) + switch phase { + case "rename": + // Install the obstruction after pre-write orphan cleanup. + f.fsm.probe.beforeWrite = func() { + f.fsm.probe.writeErr = os.Mkdir(fsmSnapPath(e.fsmSnapDir, req.index), 0o700) + } + case "cancel-during-write": + f.fsm.probe.beforeWrite = e.snapshotCancel + default: + f.fsm.probe.writeErr = errors.New("injected payload write failure") + } + if phase == "write-and-close" { + f.fsm.probe.closeErr = errors.New("injected source close failure") + } + require.NoError(t, e.enqueueSnapshotRequest(req)) + result := testutil.Recv(t, e.snapshotResCh, time.Second, "catch-up export") + ownerErr := e.handleSnapshotResult(result) + shutdownErr := e.stopSnapshotWorker() + switch phase { + case "write", "cancel-during-write": + require.True(t, errors.Is(result.err, errCatchUpSnapshotWrite)) + require.NoError(t, ownerErr) + require.False(t, e.snapshotRetryAt.IsZero()) + require.NoError(t, shutdownErr) + case "write-and-close": + requireCatchUpSnapshotErrors(t, []error{ownerErr, shutdownErr}, f.fsm.probe.writeErr, f.fsm.probe.closeErr) + case "rename": + for _, err := range []error{ownerErr, shutdownErr} { + var linkErr *os.LinkError + require.ErrorAs(t, err, &linkErr) + require.Equal(t, "rename", linkErr.Op) + } + } + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + snapshotPhaseRequireMemoryState(t, e.storage, configPhaseBaseIndex, 1, configPhaseIndex) + }) + } +} + +func requireCatchUpSnapshotErrors(t *testing.T, results []error, writeErr, closeErr error) { + t.Helper() + for _, err := range results { + require.ErrorIs(t, err, writeErr) + require.ErrorIs(t, err, closeErr) + } +} diff --git a/internal/raftengine/etcd/local_snapshot_durability_test.go b/internal/raftengine/etcd/local_snapshot_durability_test.go new file mode 100644 index 000000000..fe78432c5 --- /dev/null +++ b/internal/raftengine/etcd/local_snapshot_durability_test.go @@ -0,0 +1,334 @@ +package etcd + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/server/v3/storage/wal" + "go.etcd.io/raft/v3/raftpb" + "google.golang.org/protobuf/proto" +) + +const ( + ownedCrashPhase = "ELASTICKV_TEST_OWNED_SNAPSHOT_CRASH" + ownedCrashExit = 77 + ownedCutIndex = uint64(5) // bootstrap, leader no-op, then three PUTs +) + +// The header has reached the real file writer. Stop before the owned snapshot +// serializes the pinned rows, so a later proposal can commit during WriteTo. +type ownedCrashWriter struct { + io.Writer + pause func() +} + +func (w *ownedCrashWriter) Write(p []byte) (int, error) { + n, err := w.Writer.Write(p) + if w.pause != nil && err == nil { + w.pause() + w.pause = nil + } + return n, err +} + +type ownedCrashSnapshot struct { + Snapshot + pause func() +} + +func (s *ownedCrashSnapshot) WriteTo(w io.Writer) (int64, error) { + return s.Snapshot.WriteTo(&ownedCrashWriter{w, s.pause}) +} + +type ownedCrashMachine interface { + pipelineNativeConfigurationStateMachine + raftengine.ApplyEntryIdentityAware + raftengine.OwnerSnapshotCapturer +} + +type ownedCrashFSM struct { + ownedCrashMachine + pause func() +} + +func (f *ownedCrashFSM) CaptureOwnerSnapshot() (Snapshot, error) { + s, err := f.ownedCrashMachine.CaptureOwnerSnapshot() + if err != nil { + return nil, err + } + return &ownedCrashSnapshot{s, f.pause}, nil +} + +func ownedCrashConfig(dir string, fsm StateMachine) OpenConfig { + return OpenConfig{NodeID: 1, LocalID: "n1", LocalAddress: "127.0.0.1:7001", + DataDir: dir, StateMachine: fsm} +} + +func ownedCrashValue(ts uint64) []byte { + // Each proposal rotates the child's small WAL. Distinct MVCC versions let + // us check both the selected image and the retained tail after replay. + return bytes.Repeat([]byte{byte(ts)}, 8192) +} + +func ownedCrashPut(t *testing.T, e *Engine, ts uint64) uint64 { + t.Helper() + payload, err := proto.Marshal(&pb.RaftCommand{Requests: []*pb.Request{{Ts: ts, + Mutations: []*pb.Mutation{{Op: pb.Op_PUT, Key: []byte("history"), Value: ownedCrashValue(ts)}}, + }}}) + require.NoError(t, err) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + result, err := e.Propose(ctx, payload) + require.NoError(t, err) + require.NotNil(t, result) + require.Nil(t, result.Response, "the committed PUT must succeed") + return result.CommitIndex +} + +func TestOwnedSnapshotWALCrashRecovery(t *testing.T) { + if phase := os.Getenv(ownedCrashPhase); phase != "" { + runOwnedSnapshotCrash(t, phase) + return + } + for _, mode := range []string{"sync", "nosync"} { + for _, phase := range []string{"exporting", "save-error", "published"} { + t.Run(mode+"/"+phase, func(t *testing.T) { + t.Setenv("ELASTICKV_FSM_SYNC_MODE", mode) + dir := t.TempDir() + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestOwnedSnapshotWALCrashRecovery$") + cmd.Dir = dir + cmd.Env = append(os.Environ(), ownedCrashPhase+"="+phase) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + require.ErrorAs(t, err, &exit, "%s", out) + require.Equal(t, ownedCrashExit, exit.ExitCode(), "%s", out) + require.NotContains(t, string(out), "WARNING: DATA RACE") + verifyOwnedSnapshotRecovery(t, dir, phase) + }) + } + } +} + +func runOwnedSnapshotCrash(t *testing.T, phase string) { + t.Helper() + // Process-private settings. Only the fatal SaveSnap branch shuts its + // engine down. All branches leave the source Pebble store open at exit. + wal.SegmentSizeBytes = 4096 + t.Setenv(snapshotEveryEnvVar, "4") + t.Setenv(maxWALFilesEnvVar, "1") + st, err := store.NewPebbleStore("source", store.WithSSTIngestSnapshots(true)) + require.NoError(t, err) + label, ok := st.(interface{ FSMApplySyncModeLabel() string }) + require.True(t, ok) + require.Equal(t, os.Getenv("ELASTICKV_FSM_SYNC_MODE"), label.FSMApplySyncModeLabel()) + clock := kv.NewHLC() + clock.SetPhysicalCeiling(10) + actual := kv.NewKvFSMWithHLC(st, clock) + pause, writing, unblock := ownershipBarrier() + machine, ok := actual.(ownedCrashMachine) + require.True(t, ok) + fsm := &ownedCrashFSM{machine, pause} + cfg := ownedCrashConfig("raft", fsm) + cfg.Bootstrap = true + e, err := Open(t.Context(), cfg) + require.NoError(t, err) + clock.SetPhysicalCeiling(20) + ownedCrashPut(t, e, 1) + ownedCrashPut(t, e, 2) + require.Equal(t, ownedCutIndex, ownedCrashPut(t, e, 3)) + testutil.Closed(t, writing, 10*time.Second, "owned WriteTo after header") + clock.SetPhysicalCeiling(30) + require.Equal(t, ownedCutIndex+1, ownedCrashPut(t, e, 4)) + + walDir := filepath.Join(e.dataDir, walDirName) + before := listWALFiles(t, walDir) + require.Greater(t, len(before), 2) + current, err := e.storage.Snapshot() + require.NoError(t, err) + require.Equal(t, uint64(1), snapshotIndex(current)) + switch phase { + case "exporting": + // Exit with the writer still blocked and the Pebble pin still live. + case "save-error": + // Make the native snapshotter's write fail at the new .snap path. + // The old .snap and the new synced .fsm remain accessible. + term, err := e.storage.Term(ownedCutIndex) + require.NoError(t, err) + path := filepath.Join(e.dataDir, snapDirName, fmt.Sprintf("%016x-%016x.snap", term, ownedCutIndex)) + require.NoError(t, os.Mkdir(path, 0o700)) + unblock() + testutil.Closed(t, e.doneCh, 10*time.Second, "SaveSnap failure") + var pathErr *os.PathError + require.ErrorAs(t, e.Err(), &pathErr) + require.Equal(t, path, pathErr.Path) + require.FileExists(t, fsmSnapPath(e.fsmSnapDir, ownedCutIndex)) + require.Equal(t, before, listWALFiles(t, walDir)) + current, err = e.storage.Snapshot() + require.NoError(t, err) + require.Equal(t, uint64(1), snapshotIndex(current)) + case "published": + unblock() + // WriteTo already holds snapshotMu. Acquiring it waits through + // SaveSnap, memory publication, WAL Release and segment purge. + e.snapshotMu.Lock() + current, err = e.storage.Snapshot() + require.NoError(t, err) + require.Equal(t, ownedCutIndex, snapshotIndex(current)) + require.Less(t, len(listWALFiles(t, walDir)), len(before), "must exercise real WAL reclamation") + e.snapshotMu.Unlock() + default: + t.Fatalf("unexpected crash phase %q", phase) + } + os.Exit(ownedCrashExit) +} + +func verifyOwnedSnapshotRecovery(t *testing.T, dir, phase string) { + t.Helper() + // Discard all source-Pebble state as a recovery oracle. In particular a + // surviving NoSync memtable or OS page cache cannot satisfy this check. + st, err := store.NewPebbleStore(filepath.Join(dir, "recovered")) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + clock := kv.NewHLC() + cfg := ownedCrashConfig(filepath.Join(dir, "raft"), kv.NewKvFSMWithHLC(st, clock)) + disk, err := openDiskState(cfg, nil) + require.NoError(t, err) + require.NoError(t, closePersist(disk.Persist)) + hs, _, err := disk.Storage.InitialState() + require.NoError(t, err) + require.Equal(t, ownedCutIndex+1, hs.GetCommit(), "persisted commit must cover the ACK") + idx, ceiling := uint64(1), int64(10) + term := uint64(1) + if phase == "published" { + idx, ceiling = ownedCutIndex, 20 + term, err = disk.Storage.Term(ownedCutIndex + 1) // same single-node leadership term + require.NoError(t, err) + } + meta := disk.LocalSnap.GetMetadata() + require.Equal(t, idx, meta.GetIndex()) + require.Equal(t, term, meta.GetTerm()) + require.NoError(t, meta.GetConfState().Equivalent(&raftpb.ConfState{Voters: []uint64{1}})) + token, err := decodeSnapshotToken(disk.LocalSnap.GetData()) + require.NoError(t, err) + require.Equal(t, idx, token.Index) + require.Equal(t, ceiling, clock.PhysicalCeiling()) + epoch, err := kv.MigrationConfigurationIndex(t.Context(), st) + require.NoError(t, err) + require.Equal(t, uint64(1), epoch) + version, err := store.GetVersionAt(t.Context(), st, []byte("history"), 4) + if phase == "published" { + require.NoError(t, err) + require.EqualValues(t, 3, version.TS, "snapshot must contain the cut before the ACK") + require.True(t, bytes.Equal(ownedCrashValue(3), version.Value), "corrupt value at snapshot cut") + reader, ok := cfg.StateMachine.(raftengine.AppliedIndexReader) + require.True(t, ok) + applied, present, readErr := reader.LastAppliedIndex() + require.NoError(t, readErr) + require.True(t, present) + require.Equal(t, idx, applied, "raw applied-index row must agree with the token") + } else { + require.ErrorIs(t, err, store.ErrKeyNotFound) + } + // Re-enter native startup and let Raft deliver the committed WAL suffix. + e, err := Open(t.Context(), cfg) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, e.Close()) }) + require.GreaterOrEqual(t, e.AppliedIndex(), ownedCutIndex+1) + for ts := uint64(1); ts <= 4; ts++ { + version, err = store.GetVersionAt(t.Context(), st, []byte("history"), ts) + require.NoError(t, err) + require.Equal(t, ts, version.TS) + require.True(t, bytes.Equal(ownedCrashValue(ts), version.Value), "corrupt version at ts=%d", ts) + } + require.NoError(t, e.Close()) + verifyOwnedSnapshotExistingStoreRecovery(t, dir) +} + +func verifyOwnedSnapshotExistingStoreRecovery(t *testing.T, dir string) { + t.Helper() + // Supplement the fresh-store oracle with the normal existing-store skip + // path. Process exit retains OS cache; CrashClone tests cover lost NoSync + // bytes separately at the source durability fence. + st, err := store.NewPebbleStore(filepath.Join(dir, "source")) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + e, err := Open(t.Context(), ownedCrashConfig(filepath.Join(dir, "raft"), kv.NewKvFSMWithHLC(st, kv.NewHLC()))) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, e.Close()) }) + require.GreaterOrEqual(t, e.AppliedIndex(), ownedCutIndex+1) + for ts := uint64(1); ts <= 4; ts++ { + version, err := store.GetVersionAt(t.Context(), st, []byte("history"), ts) + require.NoError(t, err) + require.Equal(t, ts, version.TS) + require.True(t, bytes.Equal(ownedCrashValue(ts), version.Value), "corrupt existing-store version at ts=%d", ts) + } +} + +type partialOwnedSnapshot struct{ Snapshot } + +func (s partialOwnedSnapshot) WriteTo(w io.Writer) (int64, error) { + // Force an actual temp-file prefix past the production bufio buffer. + n, err := w.Write(make([]byte, fsmWriteBufSize+1)) + return int64(n), errors.Join(err, io.ErrUnexpectedEOF) +} + +func TestOwnedSnapshotFailureBeforeRelease(t *testing.T) { + for _, phase := range []string{"partial", "close", "save"} { + t.Run(phase, func(t *testing.T) { + f := newOwnershipFixture(t, true) + e := f.e + req, err := e.captureLocalSnapshotRequest(e.applied) + require.NoError(t, err) + failure := errors.New("injected " + phase) + if phase == "partial" { + f.fsm.probe.Snapshot = partialOwnedSnapshot{f.fsm.probe.Snapshot} + failure = io.ErrUnexpectedEOF + } + if phase == "close" { + f.fsm.probe.closeErr = failure + } + saveCalls := 0 + e.persist = &snapshotPhaseCallbackStorage{Storage: e.persist, + beforeSave: func(*raftpb.Snapshot) error { + saveCalls++ + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + require.Equal(t, "save", phase, "publication after failed export or Close") + return failure + }, + beforeRelease: func(*raftpb.Snapshot) error { + t.Fatal("WAL Release before successful publication") + return nil + }, + } + walDir := snapshotDiskPurgeFixture(t, e) + require.ErrorIs(t, e.persistLocalSnapshot(req), failure) + if phase == "save" { + require.Equal(t, 1, saveCalls) + } else { + require.Zero(t, saveCalls) + } + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + snapshotPhaseRequireMemoryState(t, e.storage, configPhaseBaseIndex, 1, configPhaseIndex) + require.Len(t, listWALFiles(t, walDir), 2, "failed snapshot purged WAL") + if phase == "partial" { + require.NoFileExists(t, fsmSnapPath(e.fsmSnapDir, req.index)) + } + }) + } +} diff --git a/internal/raftengine/etcd/local_snapshot_ownership.go b/internal/raftengine/etcd/local_snapshot_ownership.go new file mode 100644 index 000000000..84968b68b --- /dev/null +++ b/internal/raftengine/etcd/local_snapshot_ownership.go @@ -0,0 +1,107 @@ +package etcd + +import ( + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/cockroachdb/errors" +) + +// Request copies share this identity across the queue and worker. Only the +// pending identity may be exported or closed, always under snapshotMu. +type localSnapshotCapture struct{ Snapshot } + +func (e *Engine) captureLocalSnapshot() (Snapshot, error) { + if e.fsmSnapDir == "" || e.storagePipeline != nil { + snapshot, err := e.fsm.Snapshot() + return snapshot, errors.WithStack(err) + } + e.snapshotMu.Lock() + defer e.snapshotMu.Unlock() + if e.snapshotCloseErr != nil { + return nil, e.snapshotCloseErr + } + if e.pendingLocalSnapshot != nil { + return nil, errors.New("local snapshot capture already pending") + } + capture := e.fsm.Snapshot + if fsm, ok := e.fsm.(raftengine.OwnerSnapshotCapturer); ok { + capture = fsm.CaptureOwnerSnapshot + } + snapshot, err := capture() + if err != nil { + return nil, err + } + if snapshot == nil { + return nil, errors.New("local snapshot capture returned a nil handle") + } + e.pendingLocalSnapshot = &localSnapshotCapture{snapshot} + return e.pendingLocalSnapshot, nil +} + +func (e *Engine) localSnapshotExportReadyLocked(req snapshotRequest) (bool, error) { + if capture, ok := req.snapshot.(*localSnapshotCapture); ok && capture != e.pendingLocalSnapshot { + return false, e.snapshotCloseErr + } + select { + case <-e.snapshotStopCh: + return false, e.closeLocalSnapshotLocked(req.snapshot) + default: + } + current, err := e.storage.Snapshot() + if err != nil { + return false, errors.Join(errors.WithStack(err), e.closeLocalSnapshotLocked(req.snapshot)) + } + if req.index <= current.GetMetadata().GetIndex() || e.protectedReceivedFSMSnaps[req.index] > 0 { + return false, e.closeLocalSnapshotLocked(req.snapshot) + } + return true, nil +} + +func (e *Engine) closeLocalSnapshotLocked(snapshot Snapshot) error { + if capture, ok := snapshot.(*localSnapshotCapture); ok { + if capture != e.pendingLocalSnapshot { + return e.snapshotCloseErr + } + e.pendingLocalSnapshot = nil + snapshot = capture.Snapshot + capture.Snapshot = nil + } + if snapshot != nil { + if err := snapshot.Close(); err != nil { + // A failed Close does not establish that the source can be + // replaced. Remember it even if shutdown discards the result. + e.snapshotCloseErr = errors.Join(e.snapshotCloseErr, err) + } + } + return e.snapshotCloseErr +} + +func (e *Engine) retireLocalSnapshotLocked() error { + if e.pendingLocalSnapshot != nil { + return e.closeLocalSnapshotLocked(e.pendingLocalSnapshot) + } + return e.snapshotCloseErr +} + +// The Raft owner has stopped admitting requests and the worker has joined. +// Finish every close attempt. stopSnapshotWorker returns the accumulated error. +func (e *Engine) drainLocalSnapshots() { + e.snapshotMu.Lock() + defer e.snapshotMu.Unlock() + for len(e.snapshotReqCh) > 0 { + req := <-e.snapshotReqCh + _ = e.closeLocalSnapshotLocked(req.snapshot) + } + _ = e.retireLocalSnapshotLocked() +} + +// The worker has joined before callers read this error. Its result may have +// been discarded on stop or left unread in snapshotResCh, but is still fatal. +func (e *Engine) snapshotShutdownError() error { + if e.snapshotWorkerErr == nil { + return e.snapshotCloseErr + } + if e.snapshotCloseErr == nil || errors.Is(e.snapshotWorkerErr, e.snapshotCloseErr) { + return e.snapshotWorkerErr + } + return errors.Join(e.snapshotWorkerErr, e.snapshotCloseErr) +} diff --git a/internal/raftengine/etcd/local_snapshot_ownership_pending_test.go b/internal/raftengine/etcd/local_snapshot_ownership_pending_test.go new file mode 100644 index 000000000..ee1f8bb2c --- /dev/null +++ b/internal/raftengine/etcd/local_snapshot_ownership_pending_test.go @@ -0,0 +1,51 @@ +package etcd + +import ( + "fmt" + "sync" + "sync/atomic" + "testing" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type ownedSnapshotCloseProbe struct { + raftengine.Snapshot + calls atomic.Int32 + once sync.Once + err error +} + +func (p *ownedSnapshotCloseProbe) Close() error { + p.calls.Add(1) + p.once.Do(func() { p.err = p.Snapshot.Close() }) + return p.err +} + +func TestStopSnapshotWorkerReleasesBufferedPebbleSnapshot(t *testing.T) { + t.Parallel() + for _, sst := range []bool{false, true} { + t.Run(fmt.Sprintf("sst=%t", sst), func(t *testing.T) { + t.Parallel() + st, err := store.NewPebbleStore(t.TempDir(), store.WithSSTIngestSnapshots(sst)) + require.NoError(t, err) + snapshot, err := st.Snapshot() + require.NoError(t, err) + probe := &ownedSnapshotCloseProbe{Snapshot: snapshot} + e := &Engine{snapshotReqCh: make(chan snapshotRequest, 1), snapshotStopCh: make(chan struct{})} + e.snapshotReqCh <- snapshotRequest{index: 1, snapshot: probe} + require.NoError(t, e.stopSnapshotWorker()) + assert.EqualValues(t, 1, probe.calls.Load(), "accepted buffered capture must be closed before the store") + assert.Empty(t, e.snapshotReqCh) + if probe.calls.Load() == 0 { + require.NoError(t, probe.Close()) + } + require.NoError(t, st.Close(), "no Pebble snapshot pin may remain after worker shutdown") + }) + } +} + +var _ raftengine.Snapshot = (*ownedSnapshotCloseProbe)(nil) diff --git a/internal/raftengine/etcd/local_snapshot_ownership_test.go b/internal/raftengine/etcd/local_snapshot_ownership_test.go new file mode 100644 index 000000000..dedc5cdb8 --- /dev/null +++ b/internal/raftengine/etcd/local_snapshot_ownership_test.go @@ -0,0 +1,400 @@ +package etcd + +import ( + "bytes" + "errors" + "fmt" + "io" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil" + "github.com/bootjp/elastickv/kv" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/server/v3/mock/mockstorage" + etcdraft "go.etcd.io/raft/v3" + raftpb "go.etcd.io/raft/v3/raftpb" +) + +type ownershipFSM struct { + kv.FSM + owner raftengine.OwnerSnapshotCapturer + captureErr error + afterRestoreErr error + probe ownershipProbe + restores atomic.Int32 + closesAtRestore atomic.Int32 +} + +// Instrument the real KV capture, including its completion of raw Close. +func (f *ownershipFSM) CaptureOwnerSnapshot() (Snapshot, error) { + if f.captureErr != nil { + return nil, f.captureErr + } + snapshot, err := f.owner.CaptureOwnerSnapshot() + if err != nil { + return nil, err + } + f.probe.Snapshot = snapshot + return &f.probe, nil +} + +func (f *ownershipFSM) Restore(r io.Reader) error { + f.restores.Add(1) + f.closesAtRestore.Store(f.probe.closes.Load()) + if err := f.FSM.Restore(r); err != nil { + return err + } + return f.afterRestoreErr +} + +type ownershipProbe struct { + Snapshot + writes, closes atomic.Int32 + beforeWrite, beforeClose func() + writeErr, closeErr error +} + +func (p *ownershipProbe) WriteTo(w io.Writer) (int64, error) { + p.writes.Add(1) + if p.beforeWrite != nil { + p.beforeWrite() + } + if p.writeErr != nil { + return 0, p.writeErr + } + return p.Snapshot.WriteTo(w) +} + +func (p *ownershipProbe) Close() error { + if p.beforeClose != nil { + p.beforeClose() + } + err := p.Snapshot.Close() + p.closes.Add(1) + return errors.Join(err, p.closeErr) +} + +type ownershipFixture struct { + e *Engine + fsm *ownershipFSM + store store.MVCCStore + clock *kv.HLC + incoming raftpb.Snapshot +} + +func newOwnershipFixture(t *testing.T, sst bool) ownershipFixture { + t.Helper() + st, err := store.NewPebbleStore(t.TempDir(), store.WithSSTIngestSnapshots(sst)) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + clock := kv.NewHLC() + actual := kv.NewKvFSMWithHLC(st, clock) + owner, ok := actual.(raftengine.OwnerSnapshotCapturer) + require.True(t, ok) + fsm := &ownershipFSM{FSM: actual, owner: owner} + require.NoError(t, st.PutAt(t.Context(), []byte("k"), []byte("received"), 1, 0)) + snap, err := actual.Snapshot() + require.NoError(t, err) + var payload bytes.Buffer + _, err = snap.WriteTo(&payload) + require.NoError(t, errors.Join(err, snap.Close())) + require.NoError(t, st.PutAt(t.Context(), []byte("k"), []byte("local"), 2, 0)) + + e := &Engine{ + fsm: fsm, persist: mockstorage.NewStorageRecorder(""), dataDir: t.TempDir(), + storage: etcdraft.NewMemoryStorage(), + peers: map[uint64]Peer{1: {NodeID: 1, ID: "n1", Address: "127.0.0.1:7001", Suffrage: SuffrageVoter}}, + } + base := raftTestSnapshot(configPhaseBaseIndex, 1, []uint64{1}, nil) + require.NoError(t, e.storage.ApplySnapshot(&base)) + entry := testEntry(configPhaseIndex, 1, nil) + require.NoError(t, e.storage.Append([]*raftpb.Entry{&entry})) + e.setApplied(configPhaseIndex) + e.fsmSnapDir = filepath.Join(e.dataDir, fsmSnapDirName) + e.snapshotEvery = 1 + e.snapshotReqCh = make(chan snapshotRequest, 1) + e.snapshotResCh = make(chan snapshotResult, 1) + e.snapshotStopCh = make(chan struct{}) + return ownershipFixture{e: e, fsm: fsm, store: st, clock: clock, + incoming: raftTestSnapshot(configPhaseIndex+1, 1, []uint64{1}, payload.Bytes())} +} + +func TestLocalSnapshotRestoreAfterDequeue(t *testing.T) { + for _, sst := range []bool{false, true} { + for _, restore := range []string{"success", "corrupt", "after-swap"} { + t.Run(fmt.Sprintf("sst=%t/%s", sst, restore), func(t *testing.T) { + f := newOwnershipFixture(t, sst) + e := f.e + switch restore { + case "corrupt": + f.incoming.Data = []byte("invalid KV snapshot") + case "after-swap": + f.fsm.afterRestoreErr = errors.New("restore failed after source swap") + } + req, err := e.captureLocalSnapshotRequest(e.applied) + require.NoError(t, err) + e.snapshotReqCh = make(chan snapshotRequest) + e.startSnapshotWorker() + t.Cleanup(func() { require.NoError(t, e.stopSnapshotWorker()) }) + func() { + e.snapshotMu.Lock() + defer e.snapshotMu.Unlock() + // Unbuffered send returns only once the production worker has + // dequeued. It cannot enter persistLocalSnapshot's lock yet. + require.NoError(t, e.enqueueSnapshotRequest(req)) + err := e.applyReadySnapshotLocked(&f.incoming) + switch restore { + case "corrupt": + require.Error(t, err) + case "after-swap": + require.ErrorIs(t, err, f.fsm.afterRestoreErr) + default: + require.NoError(t, err) + } + }() + result := testutil.Recv(t, e.snapshotResCh, time.Second, "retired request") + require.NoError(t, result.err) + require.EqualValues(t, 1, f.fsm.closesAtRestore.Load()) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + require.Zero(t, f.fsm.probe.writes.Load()) + require.NoFileExists(t, fsmSnapPath(e.fsmSnapDir, req.index)) + recorder, ok := e.persist.(*mockstorage.StorageRecorder) + require.True(t, ok) + require.Empty(t, recorder.Action()) + current, err := e.storage.Snapshot() + require.NoError(t, err) + if restore == "success" { + require.Equal(t, snapshotIndex(&f.incoming), snapshotIndex(current)) + } else { + require.Equal(t, configPhaseBaseIndex, snapshotIndex(current)) + } + if restore != "corrupt" { + value, err := f.store.GetAt(t.Context(), []byte("k"), 3) + require.NoError(t, err) + require.Equal(t, "received", string(value)) + } + }) + } + } +} + +// Gate a concrete WriteTo or Close while another goroutine requests restore +// or shutdown. Cleanup releases the barrier even on an assertion failure. +func ownershipBarrier() (func(), <-chan struct{}, func()) { + entered, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + return func() { close(entered); <-release }, entered, unblock +} + +func TestLocalSnapshotWorkerWinsRestore(t *testing.T) { + f := newOwnershipFixture(t, true) + e := f.e + write, writing, allowWrite := ownershipBarrier() + closePin, closing, allowClose := ownershipBarrier() + recorder, ok := e.persist.(*mockstorage.StorageRecorder) + require.True(t, ok) + var saved *raftpb.Snapshot + e.persist = &snapshotPhaseCallbackStorage{Storage: recorder, + beforeSave: func(s *raftpb.Snapshot) error { saved = s; return nil }, + beforeRelease: func(*raftpb.Snapshot) error { return nil }, + } + f.fsm.probe.beforeWrite, f.fsm.probe.beforeClose = write, closePin + e.startSnapshotWorker() + t.Cleanup(func() { + allowWrite() + allowClose() + require.NoError(t, e.stopSnapshotWorker()) + }) + f.clock.SetPhysicalCeiling(100) + require.NoError(t, e.maybePersistLocalSnapshot()) + testutil.Closed(t, writing, time.Second, "worker WriteTo") + snapshotDiskRequireLocked(t, e) + f.clock.SetPhysicalCeiling(200) + require.NoError(t, e.snapshotConfigurations.record(configPhaseIndex+1, fullSnapshotTestConfiguration())) + require.NoError(t, f.store.PutAt(t.Context(), []byte("k"), []byte("later"), 3, 0)) + restored := make(chan error, 1) + go func() { restored <- e.applyReadySnapshot(&f.incoming) }() + allowWrite() + // The barriers establish order; these waits include real file sync and + // restore I/O and are deadlock watchdogs, not latency assertions. + testutil.Closed(t, closing, 10*time.Second, "worker Close") + snapshotDiskRequireLocked(t, e) + require.Zero(t, f.fsm.restores.Load()) + allowClose() + require.NoError(t, testutil.Recv(t, e.snapshotResCh, 10*time.Second, "worker receipt").err) + require.NoError(t, testutil.Recv(t, restored, 10*time.Second, "restore after worker")) + require.EqualValues(t, 1, f.fsm.closesAtRestore.Load()) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + actions := recorder.Action() + require.Len(t, actions, 2) + require.Equal(t, "SaveSnap", actions[0].Name) + require.Equal(t, "Release", actions[1].Name) + // Inspect the bytes actually exported by the worker after the later write. + fresh, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, fresh.Close()) }) + path := fsmSnapPath(e.fsmSnapDir, configPhaseIndex) + require.Equal(t, configPhaseIndex, snapshotIndex(saved)) + require.Equal(t, []uint64{1}, saved.GetMetadata().GetConfState().GetVoters()) + token, err := decodeSnapshotToken(saved.GetData()) + require.NoError(t, err) + clock := kv.NewHLC() + require.NoError(t, openAndRestoreFSMSnapshot(kv.NewKvFSMWithHLC(fresh, clock), path, token.CRC32C)) + require.EqualValues(t, 100, clock.PhysicalCeiling()) + value, err := fresh.GetAt(t.Context(), []byte("k"), 3) + require.NoError(t, err) + require.Equal(t, "local", string(value)) +} + +func TestLocalSnapshotShutdownJoinsActiveAndDrainsBuffered(t *testing.T) { + f := newOwnershipFixture(t, false) + e := f.e + closePin, closing, allowClose := ownershipBarrier() + failure := errors.New("active pin close failure") + f.fsm.probe.beforeClose, f.fsm.probe.closeErr = closePin, failure + // No receipt receiver during shutdown. The active worker can only + // exit through stop after its real pin has finished closing. + e.snapshotResCh = nil + e.startSnapshotWorker() + t.Cleanup(func() { + allowClose() + require.ErrorIs(t, e.stopSnapshotWorker(), failure) + }) + require.NoError(t, e.maybePersistLocalSnapshot()) + testutil.Closed(t, closing, time.Second, "active close") + // Normal admission allows only one owner capture. Also exercise the + // directly constructed legacy requests that can occupy the buffer. + snap, err := f.fsm.Snapshot() + require.NoError(t, err) + bufferedFailure := errors.New("buffered close failure") + buffered := &ownershipProbe{Snapshot: snap, closeErr: bufferedFailure} + e.snapshotReqCh <- snapshotRequest{index: e.applied + 1, snapshot: buffered} + e.closeCh, e.doneCh = make(chan struct{}), make(chan struct{}) + go func() { + <-e.closeCh + e.shutdown() + close(e.doneCh) + }() + done := make(chan error, 1) + go func() { done <- e.Close() }() + testutil.Closed(t, e.snapshotStopCh, time.Second, "worker stop") + snapshotDiskRequireLocked(t, e) + require.Zero(t, buffered.closes.Load()) + require.Zero(t, f.fsm.probe.closes.Load()) + allowClose() + err = testutil.Recv(t, done, time.Second, "engine close") + for _, want := range []error{failure, bufferedFailure} { + require.ErrorIs(t, err, want) + require.ErrorIs(t, e.Err(), want) + require.ErrorIs(t, e.Close(), want) + } + require.Empty(t, e.snapshotReqCh) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + require.EqualValues(t, 1, buffered.closes.Load()) + require.Zero(t, buffered.writes.Load()) +} + +func TestLocalSnapshotCloseErrorsFenceRestoreAndPublication(t *testing.T) { + for _, stage := range []string{"restore", "worker", "enqueue", "shutdown", "buffered"} { + t.Run(stage, func(t *testing.T) { + f := newOwnershipFixture(t, true) + e := f.e + closeErr := errors.New("injected pin close failure") + f.fsm.probe.closeErr = closeErr + request, err := e.captureLocalSnapshotRequest(e.applied) + require.NoError(t, err) + _, err = e.captureLocalSnapshotRequest(e.applied) + require.Error(t, err, "only one capture can own the slot") + switch stage { + case "restore": + require.ErrorIs(t, e.applyReadySnapshot(&f.incoming), closeErr) + case "worker": + writeErr := errors.New("injected export error") + f.fsm.probe.writeErr = writeErr + err := e.persistLocalSnapshot(request) + require.ErrorIs(t, err, writeErr) + require.ErrorIs(t, err, closeErr) + case "enqueue": + e.snapshotReqCh = nil + e.doneCh = make(chan struct{}) + close(e.doneCh) + err := e.enqueueSnapshotRequest(request) + require.ErrorIs(t, err, errClosed) + require.ErrorIs(t, err, closeErr) + case "shutdown": + // Owner has captured but no queue copy exists. + require.ErrorIs(t, e.stopSnapshotWorker(), closeErr) + case "buffered": + require.NoError(t, e.enqueueSnapshotRequest(request)) + require.ErrorIs(t, e.stopSnapshotWorker(), closeErr) + require.Empty(t, e.snapshotReqCh) + } + require.ErrorIs(t, e.persistLocalSnapshot(request), closeErr) + require.ErrorIs(t, e.applyReadySnapshot(&f.incoming), closeErr) + _, err = e.captureLocalSnapshotRequest(e.applied) + require.ErrorIs(t, err, closeErr) + require.ErrorIs(t, e.stopSnapshotWorker(), closeErr) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + require.Zero(t, f.fsm.restores.Load()) + if stage == "worker" { + require.EqualValues(t, 1, f.fsm.probe.writes.Load()) + } else { + require.Zero(t, f.fsm.probe.writes.Load()) + } + recorder, ok := e.persist.(*mockstorage.StorageRecorder) + require.True(t, ok) + require.Empty(t, recorder.Action()) + current, err := e.storage.Snapshot() + require.NoError(t, err) + require.Equal(t, configPhaseBaseIndex, snapshotIndex(current)) + }) + } +} + +func TestLocalSnapshotCaptureUsesOwnerOnlyForSynchronousFiles(t *testing.T) { + for _, mode := range []string{"inline", "pipeline", "file"} { + t.Run(mode, func(t *testing.T) { + f := newOwnershipFixture(t, false) + e := f.e + switch mode { + case "inline": + e.fsmSnapDir = "" + case "pipeline": + e.storagePipeline = &engineStoragePipeline{} + } + req, err := e.captureLocalSnapshotRequest(e.applied) + require.NoError(t, err) + if mode == "file" { + require.NotNil(t, f.fsm.probe.Snapshot) + require.NoError(t, e.stopSnapshotWorker()) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + } else { + require.Nil(t, f.fsm.probe.Snapshot) + require.NoError(t, req.snapshot.Close()) + } + }) + } +} + +func TestLocalSnapshotOwnerCapturePreservesDeferralAndFailure(t *testing.T) { + f := newOwnershipFixture(t, false) + f.fsm.captureErr = raftengine.ErrSnapshotDeferred + require.NoError(t, f.e.maybePersistLocalSnapshot()) + require.Empty(t, f.e.snapshotReqCh) + require.Nil(t, f.e.pendingLocalSnapshot) + f.fsm.captureErr = errors.New("owner capture failed") + require.ErrorIs(t, f.e.maybePersistLocalSnapshot(), f.fsm.captureErr) + require.Empty(t, f.e.snapshotReqCh) + require.Nil(t, f.e.pendingLocalSnapshot) + f.fsm.captureErr = nil + require.NoError(t, f.e.maybePersistLocalSnapshot()) + require.Len(t, f.e.snapshotReqCh, 1) + require.NoError(t, f.e.stopSnapshotWorker()) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) +} diff --git a/internal/raftengine/etcd/local_snapshot_shutdown_error_test.go b/internal/raftengine/etcd/local_snapshot_shutdown_error_test.go new file mode 100644 index 000000000..b57f3c584 --- /dev/null +++ b/internal/raftengine/etcd/local_snapshot_shutdown_error_test.go @@ -0,0 +1,67 @@ +package etcd + +import ( + "errors" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/testutil" + "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" +) + +func TestSnapshotShutdownRetainsPersistenceErrors(t *testing.T) { + for _, phase := range []string{"export", "save", "buffered"} { + t.Run(phase, func(t *testing.T) { + f := newOwnershipFixture(t, false) + e := f.e + failure := errors.New("injected snapshot persistence failure") + pause, entered, release := ownershipBarrier() + t.Cleanup(release) + if phase == "export" { + f.fsm.probe.writeErr = failure + f.fsm.probe.beforeClose = pause + e.snapshotResCh = nil + } else { + e.persist = &snapshotPhaseCallbackStorage{Storage: e.persist, + beforeSave: func(*raftpb.Snapshot) error { + if phase == "save" { + pause() + } + return failure + }, + } + if phase == "save" { + e.snapshotResCh = nil + } + } + e.startSnapshotWorker() + t.Cleanup(func() { + release() + _ = e.stopSnapshotWorker() + }) + require.NoError(t, e.maybePersistLocalSnapshot()) + if phase == "buffered" { + require.Eventually(t, func() bool { return len(e.snapshotResCh) == 1 }, 10*time.Second, time.Millisecond) + } else { + testutil.Closed(t, entered, 10*time.Second, "active snapshot persistence") + } + // A normal-close sentinel must not hide an independent I/O failure. + e.runErr = errClosed + e.closeCh, e.doneCh = make(chan struct{}), make(chan struct{}) + go func() { + <-e.closeCh + e.shutdown() + close(e.doneCh) + }() + closed := make(chan error, 1) + go func() { closed <- e.Close() }() + testutil.Closed(t, e.snapshotStopCh, 10*time.Second, "shutdown joins worker") + release() + require.ErrorIs(t, testutil.Recv(t, closed, 10*time.Second, "shutdown result"), failure) + require.ErrorIs(t, e.Err(), failure) + require.ErrorIs(t, e.Close(), failure) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + }) + } +} diff --git a/internal/raftengine/etcd/local_snapshot_sync_failure_test.go b/internal/raftengine/etcd/local_snapshot_sync_failure_test.go new file mode 100644 index 000000000..45f3390e3 --- /dev/null +++ b/internal/raftengine/etcd/local_snapshot_sync_failure_test.go @@ -0,0 +1,91 @@ +//go:build darwin || linux + +package etcd + +import ( + "io" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/server/v3/mock/mockstorage" + "golang.org/x/sys/unix" +) + +func TestOwnedSnapshotFileSyncFailure(t *testing.T) { + for _, tc := range []struct { + name string + forNewMember bool + }{ + {"regular", false}, + {"catch-up", true}, + } { + t.Run(tc.name, func(t *testing.T) { + testOwnedSnapshotFileSyncFailure(t, tc.forNewMember) + }) + } +} + +func testOwnedSnapshotFileSyncFailure(t *testing.T, forNewMember bool) { + t.Helper() + f := newOwnershipFixture(t, true) + e := f.e + req, err := e.captureLocalSnapshotRequest(e.applied) + require.NoError(t, err) + req.forNewMember = forNewMember + walDir := snapshotDiskPurgeFixture(t, e) + + // The production file writer uses a concrete *os.File. A pipe accepts + // the entire KV image and footer but rejects fsync. Redirect only the + // private temp file while its owning WriteTo call is on this stack. + f.fsm.probe.beforeWrite = func() { redirectSnapshotTempToPipe(t, e.fsmSnapDir) } + err = e.persistLocalSnapshot(req) + var pe *os.PathError + require.ErrorAs(t, err, &pe) + require.Equal(t, "sync", pe.Op) + require.NotErrorIs(t, err, errCatchUpSnapshotWrite) + require.Equal(t, e.fsmSnapDir, filepath.Dir(pe.Path)) + require.NoFileExists(t, pe.Path) + require.NoFileExists(t, fsmSnapPath(e.fsmSnapDir, req.index)) + require.EqualValues(t, 1, f.fsm.probe.closes.Load()) + recorder, ok := e.persist.(*mockstorage.StorageRecorder) + require.True(t, ok) + require.Empty(t, recorder.Action(), "fsync failure reached SaveSnap or Release") + snapshotPhaseRequireMemoryState(t, e.storage, configPhaseBaseIndex, 1, configPhaseIndex) + require.Len(t, listWALFiles(t, walDir), 2) +} + +func redirectSnapshotTempToPipe(t *testing.T, dir string) { + t.Helper() + files, err := filepath.Glob(filepath.Join(dir, "*"+fsmTmpFileSuffix)) + require.NoError(t, err) + require.Len(t, files, 1) + var tmp unix.Stat_t + require.NoError(t, unix.Stat(files[0], &tmp)) + fds, err := os.ReadDir("/dev/fd") + require.NoError(t, err) + var matches []int + for _, entry := range fds { + fd, err := strconv.Atoi(entry.Name()) + var st unix.Stat_t + if err == nil && unix.Fstat(fd, &st) == nil && tmp.Dev == st.Dev && tmp.Ino == st.Ino { + matches = append(matches, fd) + } + } + require.Len(t, matches, 1, "only the open descriptor for this test's unique temp inode may be redirected") + r, w, err := os.Pipe() + require.NoError(t, err) + defer func() { require.NoError(t, w.Close()) }() + done := make(chan struct{}) + t.Cleanup(func() { + require.NoError(t, r.Close()) + <-done + }) + go func() { + defer close(done) + _, _ = io.Copy(io.Discard, r) + }() + require.NoError(t, unix.Dup2(int(w.Fd()), matches[0])) +} diff --git a/internal/raftengine/etcd/native_admission.go b/internal/raftengine/etcd/native_admission.go index aad0900a9..9d5912649 100644 --- a/internal/raftengine/etcd/native_admission.go +++ b/internal/raftengine/etcd/native_admission.go @@ -38,6 +38,7 @@ func (e *Engine) nativeState() raftengine.NativeState { func (e *Engine) applyNativeConfChange(change raftpb.ConfChangeI, index uint64) (*raftpb.ConfState, error) { var conf *raftpb.ConfState err := e.withNative(context.Background(), nil, func() error { + e.nativeConfigurationCache = nil conf = e.rawNode.ApplyConfChange(change) e.nativeConfigurationIndex = index return nil @@ -131,3 +132,22 @@ func (e *Engine) nativeProposalResult(ctx context.Context, result proposalResult } return result.result, nil } + +// checkVersionCASProposal runs on the RawNode owner immediately before append. +// Protected payload inspection also requires a proof when the frame is encrypted. +func (e *Engine) checkVersionCASProposal(req proposalRequest) error { + proof, ok := raftengine.VersionCASProposalProof(req.ctx) + if !ok { + if raftengine.RequiresVersionCASProof(req.payload) { + return raftengine.ErrVersionCASUnavailable + } + return nil + } + if proof.Term == 0 || proof.ConfigurationIndex == 0 || + proof.Term != e.rawNode.BasicStatus().GetTerm() || + proof.ConfigurationIndex != e.currentConfigIndex() || + proof.ConfigurationIndex != e.nativeConfigurationIndex || e.hasPendingConfChange() { + return raftengine.ErrVersionCASUnavailable + } + return nil +} diff --git a/internal/raftengine/etcd/proposal_pending_registration_test.go b/internal/raftengine/etcd/proposal_pending_registration_test.go new file mode 100644 index 000000000..1e99548fc --- /dev/null +++ b/internal/raftengine/etcd/proposal_pending_registration_test.go @@ -0,0 +1,50 @@ +package etcd + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/stretchr/testify/require" +) + +func TestProposalCancellationBeforePendingRegistration(t *testing.T) { + for _, pipeline := range []bool{false, true} { + name := "sync" + if pipeline { + name = "pipeline" + } + t.Run(name, func(t *testing.T) { + e, admission := newProposalTurnEngine(t) + if pipeline { + e.storagePipeline = newPipelineAdmissionFixture(t).storagePipeline + } + parent, operation, err := admission.Begin(t.Context(), raftadmission.Data) + require.NoError(t, err) + defer operation.CancelAndJoin() + ctx, cancel := context.WithCancel(parent) + defer cancel() + observed := &readTurnObservedContext{Context: ctx, checked: make(chan struct{})} + result := make(chan error, 1) + go func() { _, callErr := e.Propose(observed, []byte("data-probe")); result <- callErr }() + request := <-e.proposeCh + observed.armed.Store(true) + e.mu.Lock() + ownerDone := make(chan struct{}) + go func() { e.handleProposal(request); close(ownerDone) }() + <-observed.checked + cancel() + callerErr := <-result + e.mu.Unlock() + <-ownerDone + require.ErrorIs(t, callerErr, context.Canceled) + require.NotContains(t, e.pendingProposals, request.id) + require.False(t, e.rawNode.HasReady(), "canceled registration cannot issue a proposal") + if pipeline { + bytes, items := e.storagePipeline.proposalBudget.usage() + require.Zero(t, bytes) + require.Zero(t, items) + } + }) + } +} diff --git a/internal/raftengine/etcd/protected_append_batch.go b/internal/raftengine/etcd/protected_append_batch.go new file mode 100644 index 000000000..4497840c6 --- /dev/null +++ b/internal/raftengine/etcd/protected_append_batch.go @@ -0,0 +1,198 @@ +package etcd + +import ( + "context" + "math" + "time" + + "github.com/bootjp/elastickv/internal/raftengine" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" + "google.golang.org/protobuf/proto" +) + +const ( + protectedAppendBatchMessages = 32 + protectedAppendBatchEntries = 64 + protectedAppendBatchBytes = 128 << 10 +) + +type protectedAppendCursor struct { + term, leader, commit, configuration, generation uint64 + index, logTerm, cutover uint64 + messages, entries, bytes int +} + +func (cursor protectedAppendCursor) full() bool { + return cursor.messages >= protectedAppendBatchMessages || cursor.entries >= protectedAppendBatchEntries || cursor.bytes >= protectedAppendBatchBytes +} + +func (cursor protectedAppendCursor) boundedSuffix() bool { + // Entries uses the half-open range [commit+1, index+1). + return cursor.commit < cursor.index && cursor.index != math.MaxUint64 && cursor.index-cursor.commit <= protectedAppendBatchEntries +} + +// Only already-waiting extensions share a Ready. Admission remains per message; +// the unchanged Ready drain owns WAL sync, ordered apply and response dispatch. +func (e *Engine) handleProtectedAppendQueue(request protectedStep, tick <-chan time.Time) { + cursor, classifier, ok := e.beginProtectedAppendBatch(request, tick) + if !ok { + e.handleProtectedStep(request) + return + } + for { + if !e.handleProtectedStep(request) { + return + } + if !e.canContinueProtectedAppendBatch(cursor, request, tick) { + return + } + select { + case request = <-e.protectedStepCh: + default: + return + } + next, eligible := e.extendProtectedAppendBatch(cursor, request, classifier) + if !eligible { + e.pendingProtectedStep = &request + return + } + cursor = next + } +} + +func (e *Engine) canContinueProtectedAppendBatch(cursor protectedAppendCursor, request protectedStep, tick <-chan time.Time) bool { + return !cursor.full() && e.protectedAppendCutoverMatches(cursor) && e.protectedAppendStateMatches(cursor) && !e.protectedAppendPriorityPending(tick) && + request.receipt.Check(context.Background()) == nil +} + +func (e *Engine) beginProtectedAppendBatch(request protectedStep, tick <-chan time.Time) (protectedAppendCursor, raftengine.AppendBatchClassifier, bool) { + classifier, ok := e.fsm.(raftengine.AppendBatchClassifier) + if !ok || !e.protectedAppendRuntimeReady(request) || e.rawNode.HasReady() || e.protectedAppendPriorityPending(tick) { + return protectedAppendCursor{}, nil, false + } + basic := e.rawNode.BasicStatus() + cursor := protectedAppendCursor{term: basic.GetTerm(), leader: basic.Lead, commit: basic.GetCommit(), + configuration: e.currentConfigIndex(), generation: request.receipt.LocalGeneration(), cutover: e.raftCutoverIndex()} + if !e.protectedAppendStateMatches(cursor) { + return protectedAppendCursor{}, nil, false + } + var err error + cursor.index, err = e.storage.LastIndex() + if err != nil { + return protectedAppendCursor{}, nil, false + } + cursor.logTerm, err = e.storage.Term(cursor.index) + if err != nil || !e.protectedAppendPrefixIsData(cursor, classifier) { + return protectedAppendCursor{}, nil, false + } + cursor, eligible := e.extendProtectedAppendBatch(cursor, request, classifier) + if !eligible { + return protectedAppendCursor{}, nil, false + } + return cursor, classifier, true +} + +func (e *Engine) protectedAppendRuntimeReady(request protectedStep) bool { + return len(e.protectedStepCh) != 0 && e.storagePipeline == nil && e.rawNode != nil && e.storage != nil && + e.raftCutoverIndex != nil && request.receipt != nil && e.nativeAdmission != nil +} + +func (e *Engine) protectedAppendStateMatches(cursor protectedAppendCursor) bool { + basic := e.rawNode.BasicStatus() + return basic.RaftState == etcdraft.StateFollower && basic.GetTerm() == cursor.term && cursor.term != 0 && + basic.Lead == cursor.leader && cursor.leader != 0 && basic.GetCommit() == cursor.commit && + e.applied == cursor.commit && e.currentConfigIndex() == cursor.configuration && + !e.hasPendingConfChange() && !e.snapshotTransition.Load() +} + +func (e *Engine) protectedAppendCutoverMatches(cursor protectedAppendCursor) bool { + return e.raftCutoverIndex != nil && e.raftCutoverIndex() == cursor.cutover +} + +func (e *Engine) protectedAppendPriorityPending(tick <-chan time.Time) bool { + if e.isClosing() || e.pendingProtectedBatchEvent != nil || len(e.protectedPriorityStepCh) != 0 || len(e.priorityStepCh) != 0 || + len(e.stepCh) != 0 || len(e.snapshotResCh) != 0 || len(e.dispatchReportCh) != 0 { + return true + } + return e.captureProtectedBatchEvent(tick) +} + +func (e *Engine) extendProtectedAppendBatch(cursor protectedAppendCursor, request protectedStep, classifier raftengine.AppendBatchClassifier) (protectedAppendCursor, bool) { + msg := &request.message + if !e.protectedAppendCutoverMatches(cursor) || !e.protectedAppendHeaderMatches(cursor, request) || + len(msg.Entries) == 0 || len(msg.Entries) > protectedAppendBatchEntries-cursor.entries { + return cursor, false + } + size := proto.Size(msg) + if size > protectedAppendBatchBytes-cursor.bytes { + return cursor, false + } + for _, entry := range msg.Entries { + if !protectedAppendEntryIsData(cursor, entry, classifier) { + return cursor, false + } + cursor.index, cursor.logTerm = entry.GetIndex(), entry.GetTerm() + } + cursor.messages++ + cursor.entries += len(msg.Entries) + cursor.bytes += size + return cursor, true +} + +func (e *Engine) protectedAppendPrefixIsData(cursor protectedAppendCursor, classifier raftengine.AppendBatchClassifier) bool { + if !e.protectedAppendCutoverMatches(cursor) { + return false + } + if cursor.index == cursor.commit { + return true + } + if !cursor.boundedSuffix() { + return false + } + entries, err := e.storage.Entries(cursor.commit+1, cursor.index+1, protectedAppendBatchBytes) + if err != nil || uint64(len(entries)) != cursor.index-cursor.commit { + return false + } + cursor.index = cursor.commit + remaining := protectedAppendBatchBytes + for _, entry := range entries { + size := proto.Size(entry) + if size > remaining || !protectedAppendEntryIsData(cursor, entry, classifier) { + return false + } + remaining -= size + cursor.index = entry.GetIndex() + } + return true +} + +func protectedAppendEntryIsData(cursor protectedAppendCursor, entry *raftpb.Entry, classifier raftengine.AppendBatchClassifier) bool { + if !protectedAppendEntryExtends(cursor, entry) { + return false + } + id, payload, valid := decodeProposalEnvelope(entry.GetData()) + return valid && id != 0 && classifier.IsAppendBatchPayload(payload) +} + +func (e *Engine) protectedAppendHeaderMatches(cursor protectedAppendCursor, request protectedStep) bool { + msg := &request.message + return request.receipt != nil && cursor.generation != 0 && request.receipt.LocalGeneration() == cursor.generation && + e.protectedAppendLeaderMatches(cursor, msg) && ordinaryProtectedAppendHeader(msg) +} + +func (e *Engine) protectedAppendLeaderMatches(cursor protectedAppendCursor, msg *raftpb.Message) bool { + return msg.GetType() == raftpb.MsgApp && msg.GetFrom() == cursor.leader && msg.GetTo() == e.nodeID && + msg.GetTerm() == cursor.term && msg.GetCommit() == cursor.commit && msg.GetIndex() == cursor.index && msg.GetLogTerm() == cursor.logTerm && + msg.GetFrom() != 0 +} + +func ordinaryProtectedAppendHeader(msg *raftpb.Message) bool { + return msg.Snapshot == nil && !msg.GetReject() && msg.GetRejectHint() == 0 && msg.GetVote() == 0 && + len(msg.GetContext()) == 0 && len(msg.GetResponses()) == 0 && len(msg.ProtoReflect().GetUnknown()) == 0 +} + +func protectedAppendEntryExtends(cursor protectedAppendCursor, entry *raftpb.Entry) bool { + return entry != nil && entry.GetType() == raftpb.EntryNormal && entry.GetTerm() == cursor.term && + cursor.index != math.MaxUint64 && entry.GetIndex() == cursor.index+1 && entry.GetIndex() <= cursor.cutover && len(entry.ProtoReflect().GetUnknown()) == 0 +} diff --git a/internal/raftengine/etcd/protected_append_batch_test.go b/internal/raftengine/etcd/protected_append_batch_test.go new file mode 100644 index 000000000..9032024ad --- /dev/null +++ b/internal/raftengine/etcd/protected_append_batch_test.go @@ -0,0 +1,609 @@ +package etcd + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/peersession" + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/server/v3/etcdserver/api/snap" + etcdstorage "go.etcd.io/etcd/server/v3/storage" + "go.etcd.io/etcd/server/v3/storage/wal" + "go.etcd.io/etcd/server/v3/storage/wal/walpb" + "go.etcd.io/raft/v3/raftpb" + "go.uber.org/zap" + "google.golang.org/protobuf/proto" +) + +type appendBatchTestFSM struct{ raftengine.StateMachine } + +func (*appendBatchTestFSM) IsAppendBatchPayload(payload []byte) bool { + return bytes.HasPrefix(payload, []byte("batch-data-")) +} + +type appendBatchSaveGate struct { + etcdstorage.Storage + entered chan []uint64 + release chan struct{} + saves atomic.Int32 + failure error + afterWrite bool +} + +func (g *appendBatchSaveGate) Save(state *raftpb.HardState, entries []*raftpb.Entry) error { + if len(entries) != 0 { + indexes := make([]uint64, len(entries)) + for i, entry := range entries { + indexes[i] = entry.GetIndex() + } + g.saves.Add(1) + g.entered <- indexes + <-g.release + } + if g.failure != nil && !g.afterWrite { + return g.failure + } + if err := g.Storage.Save(state, entries); err != nil { + return err + } + return g.failure +} + +func appendBatchFixture(t *testing.T) (*Engine, *peersession.Owner, pb.EtcdRaftClient) { + t.Helper() + e, owner, client := protectedQueueFixture(t) + e.raftCutoverIndex = orInertCutover(nil) + e.fsm = &appendBatchTestFSM{StateMachine: e.fsm} + heartbeat := peerDecoderWire(t, raftpb.MsgHeartbeat, 2, 1) + _, err := client.Send(t.Context(), &pb.EtcdRaftMessage{Message: heartbeat}) + require.NoError(t, err) + e.handleProtectedStep(<-e.protectedPriorityStepCh) + require.NoError(t, e.drainReady()) + require.Equal(t, uint64(2), e.rawNode.BasicStatus().Lead) + for _, queues := range e.peerDispatchers { + for _, queue := range []chan dispatchRequest{queues.normal, queues.heartbeat, queues.readIndexResp} { + for len(queue) != 0 { + request := <-queue + require.NoError(t, request.Close()) + } + } + } + e.groupID = 1 + e.nativeConfigurationIndex = 1 + e.nativeAdmission = &recordingAdmission{} + return e, owner, client +} + +func enqueueBatchAppend(t *testing.T, client pb.EtcdRaftClient, index uint64, change func(*raftpb.Message)) { + t.Helper() + message := &raftpb.Message{Type: raftpb.MsgApp.Enum(), From: proto.Uint64(2), To: proto.Uint64(1), + Term: proto.Uint64(1), LogTerm: proto.Uint64(1), Index: proto.Uint64(index - 1), Commit: proto.Uint64(1), + Entries: []*raftpb.Entry{{Type: raftpb.EntryNormal.Enum(), Term: proto.Uint64(1), Index: proto.Uint64(index), + Data: encodeProposalEnvelope(index, []byte(fmt.Sprintf("batch-data-%d", index)))}}} + if change != nil { + change(message) + } + wire, err := proto.Marshal(message) + require.NoError(t, err) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + _, err = client.Send(ctx, &pb.EtcdRaftMessage{Message: wire}) + require.NoError(t, err) +} + +type appendBatchSaveCase struct { + name string + failure error + afterWrite bool + expectedEntries int +} + +func TestProtectedAppendBatchSharesDurableSaveWithoutEarlyAck(t *testing.T) { + failure := errors.New("injected WAL Save failure") + for _, tc := range []appendBatchSaveCase{ + {name: "success", expectedEntries: 4}, + {name: "pre-write-failure", failure: failure}, + {name: "post-write-failure", failure: failure, afterWrite: true, expectedEntries: 4}, + } { + t.Run(tc.name, func(t *testing.T) { testProtectedAppendSharedSave(t, tc) }) + } +} + +func testProtectedAppendSharedSave(t *testing.T, tc appendBatchSaveCase) { + t.Helper() + e, _, client := appendBatchFixture(t) + dir := t.TempDir() + log := zap.NewNop() + w, err := wal.Create(log, filepath.Join(dir, "wal"), nil) + require.NoError(t, err) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "snap"), 0o700)) + disk := etcdstorage.NewStorage(log, w, snap.New(log, filepath.Join(dir, "snap"))) + var closeOnce sync.Once + closeDisk := func() { closeOnce.Do(func() { require.NoError(t, disk.Close()) }) } + t.Cleanup(closeDisk) + initial, err := e.storage.Snapshot() + require.NoError(t, err) + require.NoError(t, disk.SaveSnap(initial)) + require.NoError(t, disk.Save(&raftpb.HardState{Term: proto.Uint64(1), Commit: proto.Uint64(1)}, nil)) + gate := &appendBatchSaveGate{Storage: disk, entered: make(chan []uint64, 8), release: make(chan struct{}), failure: tc.failure, afterWrite: tc.afterWrite} + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(gate.release) }) } + t.Cleanup(release) + e.persist = gate + for index := uint64(2); index <= 5; index++ { + enqueueBatchAppend(t, client, index, nil) + } + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Empty(t, e.protectedStepCh, "already-queued safe appends must share the next Ready") + done := make(chan error, 1) + go func() { done <- e.drainReady() }() + select { + case indexes := <-gate.entered: + require.Equal(t, []uint64{2, 3, 4, 5}, indexes) + case <-time.After(5 * time.Second): + t.Fatal("batched Ready did not reach durable Save") + } + queue := e.peerDispatchers[2].normal + require.Empty(t, queue, "no covering ACK may escape while WAL Save is held") + release() + select { + case err := <-done: + require.ErrorIs(t, err, gate.failure) + case <-time.After(5 * time.Second): + t.Fatal("durable batch did not complete") + } + require.Equal(t, int32(1), gate.saves.Load()) + admission, ok := e.nativeAdmission.(*recordingAdmission) + require.True(t, ok) + require.Len(t, admission.checks, 4, "every append crosses native admission independently") + for _, request := range admission.checks { + require.Equal(t, raftengine.NativePeerStep, request.Operation) + require.Equal(t, uint64(1), request.SessionGeneration) + } + assertProtectedAppendResponses(t, e, tc.failure != nil) + closeDisk() + recovered, err := wal.Open(log, filepath.Join(dir, "wal"), &walpb.Snapshot{Index: proto.Uint64(1), Term: proto.Uint64(1)}) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, recovered.Close()) }) + _, _, entries, err := recovered.ReadAll() + require.NoError(t, err) + require.Len(t, entries, tc.expectedEntries) + for i, entry := range entries { + require.Equal(t, uint64(i+2), entry.GetIndex()) + id, payload, valid := decodeProposalEnvelope(entry.GetData()) + require.True(t, valid) + require.Equal(t, entry.GetIndex(), id) + require.Equal(t, []byte(fmt.Sprintf("batch-data-%d", id)), payload) + } +} + +func assertProtectedAppendResponses(t *testing.T, e *Engine, fail bool) { + t.Helper() + queue := e.peerDispatchers[2].normal + if fail { + require.Empty(t, queue, "failed durability cannot produce an ACK") + require.Equal(t, uint64(1), e.applied) + } else { + require.Len(t, queue, 4, "each accepted append keeps its own response") + for index := uint64(2); index <= 5; index++ { + request := <-queue + require.Equal(t, raftpb.MsgAppResp, request.msg.GetType()) + require.Equal(t, index, request.msg.GetIndex()) + require.NoError(t, request.Close()) + } + } +} + +func TestProtectedAppendBatchStopsAtBoundary(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*raftpb.Message) + }{ + {"commit", func(m *raftpb.Message) { m.Commit = proto.Uint64(2) }}, + {"term", func(m *raftpb.Message) { m.Term = proto.Uint64(2); m.Entries[0].Term = proto.Uint64(2) }}, + {"control", func(m *raftpb.Message) { m.Entries[0].Data = encodeProposalEnvelope(3, []byte("control")) }}, + {"membership", func(m *raftpb.Message) { m.Entries[0].Type = raftpb.EntryConfChange.Enum() }}, + {"previous term", func(m *raftpb.Message) { m.LogTerm = proto.Uint64(2) }}, + {"gap", func(m *raftpb.Message) { m.Index = proto.Uint64(9); m.Entries[0].Index = proto.Uint64(10) }}, + {"ciphertext boundary", func(m *raftpb.Message) { m.Entries[0].Data = []byte("opaque ciphertext") }}, + {"byte limit", func(m *raftpb.Message) { + m.Entries[0].Data = encodeProposalEnvelope(3, append([]byte("batch-data-"), make([]byte, protectedAppendBatchBytes)...)) + }}, + {"entry limit", func(m *raftpb.Message) { + for i := uint64(4); i <= protectedAppendBatchEntries+3; i++ { + entry := proto.CloneOf(m.Entries[0]) + entry.Index = proto.Uint64(i) + m.Entries = append(m.Entries, entry) + } + }}, + } { + t.Run(tc.name, func(t *testing.T) { + e, _, client := appendBatchFixture(t) + enqueueBatchAppend(t, client, 2, nil) + enqueueBatchAppend(t, client, 3, tc.edit) + enqueueBatchAppend(t, client, 4, nil) + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.protectedStepCh, 1) + require.NotNil(t, e.pendingProtectedStep, "a boundary remains first in the normal FIFO") + rd := e.rawNode.Ready() + require.Len(t, rd.Entries, 1) + require.Equal(t, uint64(2), rd.Entries[0].GetIndex()) + require.Empty(t, rd.CommittedEntries) + }) + } +} + +func TestProtectedAppendBatchRevalidatesEveryAdmission(t *testing.T) { + for _, nativeDenied := range []bool{false, true} { + name := "session-revoked" + if nativeDenied { + name = "native-denied" + } + t.Run(name, func(t *testing.T) { + e, owner, client := appendBatchFixture(t) + for index := uint64(2); index <= 5; index++ { + enqueueBatchAppend(t, client, index, nil) + } + checks := 0 + e.nativeAdmission = &recordingAdmission{check: func(_ context.Context, request raftengine.NativeRequest) error { + require.Equal(t, raftengine.NativePeerStep, request.Operation) + require.NotZero(t, request.SessionGeneration) + checks++ + if checks == 2 { + if nativeDenied { + return errors.New("native authority revoked") + } + owner.SuspendGroup(1) + } + return nil + }} + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Equal(t, 2, checks) + require.Len(t, e.protectedStepCh, 2, "no further request is consumed after denial") + require.Nil(t, e.pendingProtectedStep) + rd := e.rawNode.Ready() + require.Len(t, rd.Entries, 1, "a fresh receipt is required before every Step") + require.Equal(t, uint64(2), rd.Entries[0].GetIndex()) + }) + } +} + +func TestProtectedAppendBatchMessageBound(t *testing.T) { + e, _, client := appendBatchFixture(t) + e.protectedStepCh = make(chan protectedStep, 64) + for index := uint64(2); index <= protectedAppendBatchMessages+5; index++ { + enqueueBatchAppend(t, client, index, nil) + } + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.protectedStepCh, 4) + require.Nil(t, e.pendingProtectedStep) + require.Len(t, e.rawNode.Ready().Entries, protectedAppendBatchMessages) +} + +func TestProtectedAppendBatchBoundaryPreservesFIFO(t *testing.T) { + e, _, client := appendBatchFixture(t) + enqueueBatchAppend(t, client, 2, nil) + enqueueBatchAppend(t, client, 3, func(m *raftpb.Message) { m.Commit = proto.Uint64(2) }) + enqueueBatchAppend(t, client, 4, nil) + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.NoError(t, e.drainReady()) + require.NotNil(t, e.pendingProtectedStep) + ok, err = e.handleEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Nil(t, e.pendingProtectedStep) + require.Len(t, e.protectedStepCh, 1, "later data cannot overtake the deferred boundary") + require.NoError(t, e.drainReady()) + require.Equal(t, uint64(2), e.applied) +} + +func TestProtectedAppendBatchFallback(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*Engine) + }{ + {"unknown FSM", func(e *Engine) { e.fsm = &testStateMachine{} }}, + {"missing native admission", func(e *Engine) { e.nativeAdmission = nil }}, + {"unapplied commit", func(e *Engine) { e.applied = 0 }}, + {"pending membership", func(e *Engine) { e.markPendingConfChange(2) }}, + {"snapshot transition", func(e *Engine) { e.snapshotTransition.Store(true) }}, + {"encryption cutover", func(e *Engine) { e.raftCutoverIndex = func() uint64 { return 1 } }}, + {"missing cutover", func(e *Engine) { e.raftCutoverIndex = nil }}, + {"read waiting", func(e *Engine) { e.readCh = make(chan readRequest, 1); e.readCh <- readRequest{} }}, + {"admin waiting", func(e *Engine) { e.adminCh = make(chan adminRequest, 1); e.adminCh <- adminRequest{} }}, + } { + t.Run(tc.name, func(t *testing.T) { + e, _, client := appendBatchFixture(t) + for index := uint64(2); index <= 4; index++ { + enqueueBatchAppend(t, client, index, nil) + } + first := <-e.protectedStepCh + tc.edit(e) + e.handleProtectedAppendQueue(first, nil) + require.Len(t, e.protectedStepCh, 2) + require.Nil(t, e.pendingProtectedStep) + require.Len(t, e.rawNode.Ready().Entries, 1) + }) + } +} + +func TestProtectedAppendBatchYieldsToNewPriorityWork(t *testing.T) { + e, _, client := appendBatchFixture(t) + e.priorityStepCh = make(chan raftpb.Message, 1) + checks := 0 + e.nativeAdmission = &recordingAdmission{check: func(context.Context, raftengine.NativeRequest) error { + checks++ + e.priorityStepCh <- raftpb.Message{Type: raftpb.MsgHeartbeat.Enum(), From: proto.Uint64(2), To: proto.Uint64(1), Term: proto.Uint64(1)} + return nil + }} + for index := uint64(2); index <= 4; index++ { + enqueueBatchAppend(t, client, index, nil) + } + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Equal(t, 1, checks) + require.Len(t, e.priorityStepCh, 1) + require.Len(t, e.protectedStepCh, 2) + require.Len(t, e.rawNode.Ready().Entries, 1) +} + +func TestProtectedAppendBatchAggregateEntryLimit(t *testing.T) { + e, _, client := appendBatchFixture(t) + for start := uint64(2); start < 82; start += 16 { + enqueueBatchAppend(t, client, start, func(m *raftpb.Message) { + for index := start + 1; index < start+16; index++ { + entry := proto.CloneOf(m.Entries[0]) + entry.Index = proto.Uint64(index) + entry.Data = encodeProposalEnvelope(index, []byte("batch-data-value")) + m.Entries = append(m.Entries, entry) + } + }) + } + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.protectedStepCh, 1) + require.Nil(t, e.pendingProtectedStep) + require.Len(t, e.rawNode.Ready().Entries, protectedAppendBatchEntries) +} + +func TestProtectedAppendBatchAggregateByteLimit(t *testing.T) { + e, _, client := appendBatchFixture(t) + for index := uint64(2); index <= 6; index++ { + enqueueBatchAppend(t, client, index, func(m *raftpb.Message) { + m.Entries[0].Data = encodeProposalEnvelope(index, append([]byte("batch-data-"), make([]byte, 32<<10)...)) + }) + } + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.protectedStepCh, 1) + require.NotNil(t, e.pendingProtectedStep) + rd := e.rawNode.Ready() + require.Len(t, rd.Entries, 3) + bytes := 0 + for _, entry := range rd.Entries { + bytes += len(entry.GetData()) + } + require.Less(t, bytes, protectedAppendBatchBytes) +} + +func TestProtectedAppendBatchRejectsUncommittedControlPrefix(t *testing.T) { + e, _, client := appendBatchFixture(t) + enqueueBatchAppend(t, client, 2, func(m *raftpb.Message) { m.Entries[0].Data = encodeProposalEnvelope(2, []byte("uncommitted-control")) }) + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.NoError(t, e.drainReady()) + require.Equal(t, uint64(1), e.applied) + enqueueBatchAppend(t, client, 3, nil) + enqueueBatchAppend(t, client, 4, nil) + ok, err = e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.protectedStepCh, 1, "uncommitted control cannot hide ahead of a data-only batch") + require.Len(t, e.rawNode.Ready().Entries, 1) +} + +func TestProtectedAppendBatchAcceptsUncommittedDataPrefix(t *testing.T) { + e, _, client := appendBatchFixture(t) + enqueueBatchAppend(t, client, 2, nil) + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.NoError(t, e.drainReady()) + require.Equal(t, uint64(1), e.applied) + for index := uint64(3); index <= 5; index++ { + enqueueBatchAppend(t, client, index, nil) + } + ok, err = e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Empty(t, e.protectedStepCh) + require.Len(t, e.rawNode.Ready().Entries, 3, "a known data suffix must not defeat catch-up batching") +} + +func TestProtectedAppendBatchBoundsExistingSuffix(t *testing.T) { + for _, manyEntries := range []bool{false, true} { + name := "bytes" + if manyEntries { + name = "entries" + } + t.Run(name, func(t *testing.T) { + e, _, client := appendBatchFixture(t) + last := uint64(2) + enqueueBatchAppend(t, client, 2, func(m *raftpb.Message) { + if !manyEntries { + m.Entries[0].Data = encodeProposalEnvelope(2, append([]byte("batch-data-"), make([]byte, protectedAppendBatchBytes)...)) + return + } + for index := uint64(3); index <= protectedAppendBatchEntries+2; index++ { + entry := proto.CloneOf(m.Entries[0]) + entry.Index = proto.Uint64(index) + entry.Data = encodeProposalEnvelope(index, []byte("batch-data-value")) + m.Entries = append(m.Entries, entry) + last = index + } + }) + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.NoError(t, e.drainReady()) + enqueueBatchAppend(t, client, last+1, nil) + enqueueBatchAppend(t, client, last+2, nil) + ok, err = e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.protectedStepCh, 1) + require.Len(t, e.rawNode.Ready().Entries, 1) + }) + } +} + +func TestProtectedAppendBatchDetectsUnbufferedLocalWork(t *testing.T) { + for _, kind := range []string{"read", "admin", "ticker"} { + t.Run(kind, func(t *testing.T) { + e, _, _ := appendBatchFixture(t) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + input := queueProtectedBatchLocalInput(t, e, kind, ctx) + require.Eventually(t, func() bool { return e.protectedAppendPriorityPending(input.tick) }, time.Second, time.Millisecond, + "a ready unbuffered local input must stop batching") + }) + } +} + +type protectedBatchLocalInput struct { + readDone chan readResult + adminDone chan adminResult + tick <-chan time.Time +} + +func queueProtectedBatchLocalInput(t *testing.T, e *Engine, kind string, ctx context.Context) protectedBatchLocalInput { + t.Helper() + input := protectedBatchLocalInput{readDone: make(chan readResult, 1), adminDone: make(chan adminResult, 1)} + switch kind { + case "read": + e.readCh = make(chan readRequest) + go func() { + select { + case e.readCh <- readRequest{ctx: ctx, done: input.readDone}: + case <-ctx.Done(): + } + }() + case "admin": + e.adminCh = make(chan adminRequest) + go func() { + select { + case e.adminCh <- adminRequest{ctx: ctx, done: input.adminDone}: + case <-ctx.Done(): + } + }() + case "ticker": + ticker := time.NewTicker(time.Millisecond) + t.Cleanup(ticker.Stop) + input.tick = ticker.C + } + return input +} + +func TestProtectedAppendBatchServicesCapturedLocalWorkAfterReady(t *testing.T) { + for _, kind := range []string{"read", "admin", "ticker"} { + t.Run(kind, func(t *testing.T) { testProtectedAppendCapturedEvent(t, kind) }) + } +} + +func testProtectedAppendCapturedEvent(t *testing.T, kind string) { + t.Helper() + e, _, client := appendBatchFixture(t) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + input := queueProtectedBatchLocalInput(t, e, kind, ctx) + require.Eventually(t, func() bool { return e.protectedAppendPriorityPending(input.tick) }, time.Second, time.Millisecond) + require.NotNil(t, e.pendingProtectedBatchEvent) + for index := uint64(2); index <= 4; index++ { + enqueueBatchAppend(t, client, index, nil) + } + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.protectedStepCh, 2) + require.Empty(t, input.readDone) + require.Empty(t, input.adminDone) + require.NoError(t, e.drainReady()) + cancel() + guard, isRecording := e.nativeAdmission.(*recordingAdmission) + require.True(t, isRecording) + observations := len(guard.states) + ok, err = e.handleEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Nil(t, e.pendingProtectedBatchEvent) + switch kind { + case "read": + require.ErrorIs(t, (<-input.readDone).err, context.Canceled) + case "admin": + require.ErrorIs(t, (<-input.adminDone).err, context.Canceled) + case "ticker": + require.Len(t, guard.states, observations+2, "captured tick crosses the normal native scope exactly once") + } + require.Empty(t, e.pendingReads) + require.NoError(t, e.drainReady()) + ok, err = e.handleEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Empty(t, e.protectedStepCh) + require.Len(t, e.rawNode.Ready().Entries, 2, "later normal work resumes without losing FIFO") +} + +func TestProtectedAppendBatchFailsCapturedAPIWaiters(t *testing.T) { + for _, admin := range []bool{false, true} { + name := "read" + if admin { + name = "admin" + } + t.Run(name, func(t *testing.T) { + e, _, _ := appendBatchFixture(t) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan error, 1) + if admin { + e.adminCh = make(chan adminRequest) + go func() { _, err := e.submitAdminEx(ctx, adminRequest{action: adminActionAddVoter}); done <- err }() + } else { + e.readCh = make(chan readRequest) + go func() { _, err := e.submitRead(ctx, true); done <- err }() + } + require.Eventually(t, func() bool { return e.protectedAppendPriorityPending(nil) }, time.Second, time.Millisecond) + e.failPending(errClosed) + select { + case err := <-done: + require.ErrorIs(t, err, errClosed) + case <-time.After(time.Second): + t.Fatal("captured API waiter was omitted from failure completion") + } + require.Nil(t, e.pendingProtectedBatchEvent) + }) + } +} diff --git a/internal/raftengine/etcd/protected_append_cutover_test.go b/internal/raftengine/etcd/protected_append_cutover_test.go new file mode 100644 index 000000000..046f26eea --- /dev/null +++ b/internal/raftengine/etcd/protected_append_cutover_test.go @@ -0,0 +1,45 @@ +package etcd + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/stretchr/testify/require" +) + +func TestProtectedAppendBatchCutoverChangeBetweenMessages(t *testing.T) { + e, _, client := appendBatchFixture(t) + cutover := uint64(100) + e.raftCutoverIndex = func() uint64 { return cutover } + e.nativeAdmission = &recordingAdmission{check: func(context.Context, raftengine.NativeRequest) error { + cutover = 99 // Both bounds cover every queued index. + return nil + }} + for index := uint64(2); index <= 5; index++ { + enqueueBatchAppend(t, client, index, nil) + } + handleFreshAppend(t, e) + require.Len(t, e.protectedStepCh, 3) + require.Nil(t, e.pendingProtectedStep) + require.Len(t, e.rawNode.Ready().Entries, 1) +} + +func TestProtectedAppendBatchCutoverChangeAfterSuffixRead(t *testing.T) { + e, _, client := appendBatchFixture(t) + enqueueBatchAppend(t, client, 2, nil) + handleFreshAppend(t, e) + require.NoError(t, e.drainReady()) + cutover := uint64(100) + e.raftCutoverIndex = func() uint64 { return cutover } + enqueueBatchAppend(t, client, 3, nil) + enqueueBatchAppend(t, client, 4, nil) + first := <-e.protectedStepCh + cursor, classifier, ok := e.beginProtectedAppendBatch(first, nil) + require.True(t, ok) + cutover = 101 + _, ok = e.extendProtectedAppendBatch(cursor, <-e.protectedStepCh, classifier) + require.False(t, ok) + cursor.index = 2 // The persisted prefix ends at 2. + require.False(t, e.protectedAppendPrefixIsData(cursor, classifier)) +} diff --git a/internal/raftengine/etcd/protected_append_events.go b/internal/raftengine/etcd/protected_append_events.go new file mode 100644 index 000000000..5d92df870 --- /dev/null +++ b/internal/raftengine/etcd/protected_append_events.go @@ -0,0 +1,88 @@ +package etcd + +import ( + "context" + "time" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/cockroachdb/errors" +) + +type protectedBatchEventKind uint8 + +const ( + protectedBatchRead protectedBatchEventKind = iota + protectedBatchAdmin + protectedBatchTick + protectedBatchProposal +) + +type protectedBatchEvent struct { + kind protectedBatchEventKind + read readRequest + admin adminRequest + proposal proposalRequest +} + +// Unbuffered reads/admin sends and synchronous Go timers report len zero even +// when ready. Capture at most one input without servicing it ahead of Ready. +func (e *Engine) captureProtectedBatchEvent(tick <-chan time.Time) bool { + select { + case request := <-e.readCh: + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchRead, read: request} + case request := <-e.adminCh: + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchAdmin, admin: request} + case <-tick: + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchTick} + default: + return false + } + return true +} + +// Only the owner calls this after draining the previous Ready. Reuse the normal +// handlers so cancellation, admission and native invalidation remain unchanged. +func (e *Engine) handlePendingProtectedBatchEvent(tick <-chan time.Time) (bool, error) { + event := e.pendingProtectedBatchEvent + e.pendingProtectedBatchEvent = nil + switch event.kind { + case protectedBatchRead: + e.handleReadQueueWithTick(event.read, tick) + case protectedBatchAdmin: + e.handleAdmin(event.admin) + case protectedBatchProposal: + e.handleProposal(event.proposal) + case protectedBatchTick: + if err := e.withNative(context.Background(), nil, func() error { e.rawNode.Tick(); return nil }); err != nil { + return false, err + } + default: + return false, errors.New("invalid protected batch event") + } + return true, nil +} + +func (e *Engine) failPendingProtectedBatchEvent(err error) { + event := e.pendingProtectedBatchEvent + if event == nil { + return + } + switch event.kind { + case protectedBatchRead: + e.pendingProtectedBatchEvent = nil + event.read.done <- readResult{err: err} + case protectedBatchAdmin: + e.pendingProtectedBatchEvent = nil + event.admin.done <- adminResult{err: err} + case protectedBatchProposal: + e.pendingProtectedBatchEvent = nil + // This request has not reached handleProposal or RawNode.Propose. + // Do not give it the ambiguous verdict of already-issued proposals. + if errors.Is(err, raftengine.ErrLeadershipLost) { + err = errors.WithStack(raftengine.ErrNotLeader) + } + event.proposal.done <- proposalResult{err: err} + case protectedBatchTick: + // Leadership loss cancels API waiters, not the owner's next Tick. + } +} diff --git a/internal/raftengine/etcd/protected_append_suffix_bounds_test.go b/internal/raftengine/etcd/protected_append_suffix_bounds_test.go new file mode 100644 index 000000000..d0d08a554 --- /dev/null +++ b/internal/raftengine/etcd/protected_append_suffix_bounds_test.go @@ -0,0 +1,30 @@ +package etcd + +import ( + "math" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestProtectedAppendBatchSuffixBounds(t *testing.T) { + for _, tc := range []struct { + name string + commit, index uint64 + want bool + }{ + {"empty", 1, 1, false}, + {"reversed", 2, 1, false}, + {"zero index", 1, 0, false}, + {"one entry", 1, 2, true}, + {"entry bound", 1, 1 + protectedAppendBatchEntries, true}, + {"over entry bound", 1, 2 + protectedAppendBatchEntries, false}, + {"half-open end overflow", math.MaxUint64 - 1, math.MaxUint64, false}, + {"last representable end", math.MaxUint64 - 2, math.MaxUint64 - 1, true}, + } { + t.Run(tc.name, func(t *testing.T) { + cursor := protectedAppendCursor{commit: tc.commit, index: tc.index} + require.Equal(t, tc.want, cursor.boundedSuffix()) + }) + } +} diff --git a/internal/raftengine/etcd/protected_fresh_append_test.go b/internal/raftengine/etcd/protected_fresh_append_test.go new file mode 100644 index 000000000..e7f4c9803 --- /dev/null +++ b/internal/raftengine/etcd/protected_fresh_append_test.go @@ -0,0 +1,436 @@ +package etcd + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/peersession" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/bootjp/elastickv/store/storetest" + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/server/v3/etcdserver/api/snap" + etcdstorage "go.etcd.io/etcd/server/v3/storage" + "go.etcd.io/etcd/server/v3/storage/wal" + "go.etcd.io/etcd/server/v3/storage/wal/walpb" + "go.etcd.io/raft/v3/raftpb" + "go.uber.org/zap" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// Capture exactly what the ordinary sharded coordinator proposes. +type freshFrameLeader struct { + raftengine.Engine + frames [][]byte +} + +func (*freshFrameLeader) State() raftengine.State { return raftengine.StateLeader } +func (*freshFrameLeader) Leader() raftengine.LeaderInfo { return raftengine.LeaderInfo{} } +func (*freshFrameLeader) Status() raftengine.Status { return raftengine.Status{} } +func (*freshFrameLeader) VerifyLeader(context.Context) error { return nil } +func (l *freshFrameLeader) Propose(_ context.Context, frame []byte) (*raftengine.ProposalResult, error) { + l.frames = append(l.frames, bytes.Clone(frame)) + return &raftengine.ProposalResult{CommitIndex: uint64(len(l.frames))}, nil +} + +type freshProposal struct { + id uint64 + payload []byte +} + +func freshFrames(t *testing.T) (*distribution.Engine, freshProposal, []freshProposal) { + t.Helper() + routes := distribution.NewEngine() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}, + }})) + leader := &freshFrameLeader{} + proxy := kv.NewLeaderProxyWithEngine(leader) + t.Cleanup(func() { require.NoError(t, proxy.Close()) }) + groups := map[uint64]*kv.ShardGroup{1: {Engine: leader, Txn: proxy, Store: store.NewMVCCStore()}} + coord := kv.NewShardedCoordinator(routes, groups, 1, kv.NewHLC(), kv.NewShardStore(routes, groups)) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + propose := func(id, start, commit uint64, key, value string) freshProposal { + t.Helper() + next := len(leader.frames) + _, err := coord.Dispatch(t.Context(), &kv.OperationGroup[kv.OP]{ + IsTxn: true, StartTS: start, CommitTS: commit, + ReadKeys: [][]byte{[]byte(key)}, ObservedRouteVersion: kv.EncodeObservedRouteVersion(1), + Elems: []*kv.Elem[kv.OP]{{Op: kv.Put, Key: []byte(key), Value: []byte(value)}}, + }) + require.NoError(t, err) + require.Len(t, leader.frames, next+1) + return freshProposal{id: id, payload: leader.frames[next]} + } + prefix := propose(909, 5, 10, "prefix", "prefix-value") + var frames []freshProposal + for i, start := range []uint64{15, 16, 25, 26} { + frames = append(frames, propose(uint64(801-i), start, uint64(20+5*i), "key", fmt.Sprintf("value-%d", i))) + } + return routes, prefix, frames +} + +func enqueueFreshFrame(t *testing.T, client pb.EtcdRaftClient, index uint64, frame freshProposal) { + t.Helper() + enqueueBatchAppend(t, client, index, func(m *raftpb.Message) { + m.Entries[0].Data = encodeProposalEnvelope(frame.id, frame.payload) + }) +} + +func freshSaveGate(t *testing.T, e *Engine) (*appendBatchSaveGate, func() []*raftpb.Entry) { + t.Helper() + path := filepath.Join(t.TempDir(), "wal") + log := zap.NewNop() + w, err := wal.Create(log, path, nil) + require.NoError(t, err) + disk := etcdstorage.NewStorage(log, w, snap.New(log, t.TempDir())) + closeDisk := sync.OnceFunc(func() { require.NoError(t, disk.Close()) }) + t.Cleanup(closeDisk) + initial, err := e.storage.Snapshot() + require.NoError(t, err) + require.NoError(t, disk.SaveSnap(initial)) + require.NoError(t, disk.Save(&raftpb.HardState{Term: proto.Uint64(1), Commit: proto.Uint64(1)}, nil)) + gate := &appendBatchSaveGate{Storage: disk, entered: make(chan []uint64, 8), release: make(chan struct{})} + e.persist = gate + return gate, func() []*raftpb.Entry { + closeDisk() + reopened, err := wal.Open(log, path, &walpb.Snapshot{Index: proto.Uint64(1), Term: proto.Uint64(1)}) + require.NoError(t, err) + defer func() { require.NoError(t, reopened.Close()) }() + _, state, entries, err := reopened.ReadAll() + require.NoError(t, err) + require.EqualValues(t, 1, state.GetCommit()) + return entries + } +} + +func handleFreshAppend(t *testing.T, e *Engine) { + t.Helper() + ok, err := e.handleBlockingEvent(nil) + require.NoError(t, err) + require.True(t, ok) +} + +func holdFreshSave(t *testing.T, e *Engine, gate *appendBatchSaveGate) ([]uint64, func() error) { + t.Helper() + done := make(chan error, 1) + go func() { done <- e.drainReady() }() + indexes := testutil.Recv(t, gate.entered, 5*time.Second, "Ready did not enter Save") + return indexes, func() error { + close(gate.release) + return testutil.Recv(t, done, 5*time.Second, "Ready did not finish") + } +} + +func TestProtectedFreshAppendDurability(t *testing.T) { + failure := errors.New("injected Save failure") + for _, tc := range []appendBatchSaveCase{ + {name: "success", expectedEntries: 4}, + {name: "pre-write", failure: failure}, + {name: "post-write", failure: failure, afterWrite: true, expectedEntries: 4}, + } { + t.Run(tc.name, func(t *testing.T) { + routes, _, frames := freshFrames(t) + e, _, client := appendBatchFixture(t) + e.fsm = kv.NewKvFSMWithHLC(store.NewMVCCStore(), nil, kv.WithRouteHistory(kv.WrapDistributionEngine(routes), 1)) + gate, reopen := freshSaveGate(t, e) + gate.failure, gate.afterWrite = tc.failure, tc.afterWrite + for i, frame := range frames { + enqueueFreshFrame(t, client, uint64(2+i), frame) + } + handleFreshAppend(t, e) + indexes, release := holdFreshSave(t, e, gate) + earlyACKs := len(e.peerDispatchers[2].normal) + appliedDuringSave := e.applied + err := release() + require.Equal(t, []uint64{2, 3, 4, 5}, indexes) + require.Zero(t, earlyACKs) + require.EqualValues(t, 1, appliedDuringSave) + require.ErrorIs(t, err, tc.failure) + require.EqualValues(t, 1, gate.saves.Load()) + admission, ok := e.nativeAdmission.(*recordingAdmission) + require.True(t, ok) + require.Len(t, admission.checks, 4) + for _, check := range admission.checks { + require.Equal(t, raftengine.NativePeerStep, check.Operation) + require.EqualValues(t, 1, check.SessionGeneration) + } + assertProtectedAppendResponses(t, e, tc.failure != nil) + require.EqualValues(t, 1, e.applied) + entries := reopen() + require.Len(t, entries, tc.expectedEntries) + for i, entry := range entries { + index := uint64(i + 2) + require.Equal(t, index, entry.GetIndex()) + require.Equal(t, encodeProposalEnvelope(frames[i].id, frames[i].payload), entry.GetData()) + } + }) + } +} + +func TestProtectedFreshAppendSuffix(t *testing.T) { + routes, _, frames := freshFrames(t) + for _, tc := range []struct { + name string + prefix freshProposal + next []uint64 + }{ + {"fresh", frames[0], []uint64{3, 4, 5}}, + {"control", freshProposal{id: 910, payload: kv.EncodeCommitTSFenceActivation()}, []uint64{3}}, + } { + t.Run(tc.name, func(t *testing.T) { + e, _, client := appendBatchFixture(t) + e.fsm = kv.NewKvFSMWithHLC(store.NewMVCCStore(), nil, kv.WithRouteHistory(kv.WrapDistributionEngine(routes), 1)) + gate, _ := freshSaveGate(t, e) + close(gate.release) + enqueueFreshFrame(t, client, 2, tc.prefix) + handleFreshAppend(t, e) + require.NoError(t, e.drainReady()) + require.Equal(t, []uint64{2}, testutil.Recv(t, gate.entered, time.Second, "missing prefix Save")) + require.EqualValues(t, 1, e.applied) + for i, frame := range frames[1:] { + enqueueFreshFrame(t, client, uint64(3+i), frame) + } + handleFreshAppend(t, e) + require.NoError(t, e.drainReady()) + require.Equal(t, tc.next, testutil.Recv(t, gate.entered, time.Second, "missing suffix extension Save")) + require.Equal(t, 3-len(tc.next), len(e.protectedStepCh)) + }) + } +} + +func TestProtectedFreshAppendRevoked(t *testing.T) { + routes, _, frames := freshFrames(t) + e, owner, client := appendBatchFixture(t) + e.fsm = kv.NewKvFSMWithHLC(store.NewMVCCStore(), nil, kv.WithRouteHistory(kv.WrapDistributionEngine(routes), 1)) + for i, frame := range frames { + enqueueFreshFrame(t, client, uint64(2+i), frame) + } + checks := 0 + e.nativeAdmission = &recordingAdmission{check: func(context.Context, raftengine.NativeRequest) error { + checks++ + if checks == 2 { + owner.SuspendGroup(1) + } + return nil + }} + handleFreshAppend(t, e) + require.Equal(t, 2, checks) + require.Len(t, e.protectedStepCh, 2) + require.NoError(t, e.drainReady()) + queue := e.peerDispatchers[2].normal + require.Len(t, queue, 1) + ack := <-queue + require.Equal(t, raftpb.MsgAppResp, ack.msg.GetType()) + require.EqualValues(t, 2, ack.msg.GetIndex()) + require.NoError(t, ack.Close()) +} + +// Observe the term change at the WAL boundary, before durable publication. +type freshHardStateGate struct { + etcdstorage.Storage + entered chan *raftpb.HardState + release chan struct{} +} + +func (g *freshHardStateGate) Save(state *raftpb.HardState, entries []*raftpb.Entry) error { + g.entered <- state + <-g.release + return g.Storage.Save(state, entries) +} + +func freshHeartbeat(t *testing.T, client pb.EtcdRaftClient, term, commit uint64) { + t.Helper() + message := &raftpb.Message{Type: raftpb.MsgHeartbeat.Enum(), From: proto.Uint64(2), To: proto.Uint64(1), + Term: proto.Uint64(term), Commit: proto.Uint64(commit)} + wire, err := proto.Marshal(message) + require.NoError(t, err) + _, err = client.Send(t.Context(), &pb.EtcdRaftMessage{Message: wire}) + require.NoError(t, err) +} + +func observeFreshRevocations(t *testing.T, e *Engine, owner *peersession.Owner) *int { + t.Helper() + require.Equal(t, raftengine.NativeState{Term: 1, Role: raftengine.StateFollower, LeaderID: 2, ConfigurationIndex: 1}, e.nativeState()) + calls := 0 + e.admissionChanged = func() { + owner.SuspendGroup(e.groupID) + calls++ + } + return &calls +} + +func TestProtectedFreshAppendTermChangeRevokesSession(t *testing.T) { + e, owner, client := appendBatchFixture(t) + calls := observeFreshRevocations(t, e, owner) + gate, _ := freshSaveGate(t, e) + prior := &freshHardStateGate{Storage: gate.Storage, entered: make(chan *raftpb.HardState, 1), release: make(chan struct{})} + e.persist = prior + freshHeartbeat(t, client, 2, 1) + heartbeat := testutil.Recv(t, e.protectedPriorityStepCh, time.Second, "missing term-changing heartbeat") + require.NoError(t, heartbeat.receipt.Check(t.Context())) + require.True(t, e.handleProtectedStep(heartbeat)) + done := make(chan error, 1) + go func() { done <- e.drainReady() }() + release := sync.OnceFunc(func() { + close(prior.release) + require.NoError(t, testutil.Recv(t, done, 5*time.Second, "preceding Save did not finish")) + }) + defer release() + state := testutil.Recv(t, prior.entered, 5*time.Second, "preceding Save did not begin") + require.EqualValues(t, 2, state.GetTerm()) + require.EqualValues(t, 1, state.GetCommit()) + require.Positive(t, *calls) + probe := &pb.EtcdRaftMessage{Message: peerDecoderWire(t, raftpb.MsgHeartbeat, 2, 1)} + assertDenied := func() { + t.Helper() + // SuspendGroup also closes the transport. Check the original inbound + // receipt for the admission decision independently of the RPC error. + require.Equal(t, codes.PermissionDenied, status.Code(heartbeat.receipt.Check(t.Context()))) + _, err := client.Send(t.Context(), probe) + require.Error(t, err) + require.Empty(t, e.protectedPriorityStepCh) + } + assertDenied() + release() + assertDenied() +} + +func queueFreshDuringSave(t *testing.T, e *Engine, client pb.EtcdRaftClient, gate *appendBatchSaveGate, prefix freshProposal, frames []freshProposal) { + t.Helper() + enqueueFreshFrame(t, client, 2, prefix) + handleFreshAppend(t, e) + indexes, finish := holdFreshSave(t, e, gate) + release := sync.OnceFunc(func() { require.NoError(t, finish()) }) + defer release() + require.Equal(t, []uint64{2}, indexes) + for i, frame := range frames { + enqueueFreshFrame(t, client, uint64(3+i), frame) + } + require.Len(t, e.protectedStepCh, 4) + require.Empty(t, e.peerDispatchers[2].normal) + require.EqualValues(t, 1, e.applied) + release() + require.EqualValues(t, 1, gate.saves.Load()) + checkFreshACKs(t, e, []uint64{2}) +} + +func checkFreshACKs(t *testing.T, e *Engine, indexes []uint64) { + t.Helper() + queue := e.peerDispatchers[2].normal + require.Len(t, queue, len(indexes)) + for _, index := range indexes { + ack := <-queue + require.Equal(t, raftpb.MsgAppResp, ack.msg.GetType()) + require.False(t, ack.msg.GetReject()) + require.Equal(t, index, ack.msg.GetIndex()) + require.NoError(t, ack.Close()) + } +} + +func TestProtectedFreshAppendRecoveryAndApply(t *testing.T) { + routes, prefix, frames := freshFrames(t) + for _, tc := range []struct { + name string + saves [][]uint64 + }{ + {"single step", [][]uint64{{3}, {4}, {5}, {6}}}, + {"batched", [][]uint64{{3, 4, 5, 6}}}, + } { + t.Run(tc.name, func(t *testing.T) { + e, owner, client := appendBatchFixture(t) + calls := observeFreshRevocations(t, e, owner) + initial := e.nativeState() + st := storetest.NewPebble(t) + e.fsm = kv.NewKvFSMWithHLC(st, kv.NewHLC(), kv.WithRouteHistory(kv.WrapDistributionEngine(routes), 1)) + require.NoError(t, e.persistStartupAppliedIndex()) + gate, _ := freshSaveGate(t, e) + queueFreshDuringSave(t, e, client, gate, prefix, frames) + for _, want := range tc.saves { + if len(tc.saves) == 1 { + handleFreshAppend(t, e) + } else { + require.True(t, e.handleProtectedStep(<-e.protectedStepCh)) + } + require.NoError(t, e.drainReady()) + require.Equal(t, want, testutil.Recv(t, gate.entered, time.Second, "missing entry-bearing Save")) + checkFreshACKs(t, e, want) + } + require.EqualValues(t, len(tc.saves), gate.saves.Load()-1) + require.Empty(t, e.protectedStepCh) + require.EqualValues(t, 1, e.applied) + guard, ok := e.nativeAdmission.(*recordingAdmission) + require.True(t, ok) + require.Len(t, guard.checks, 5) + for _, check := range guard.checks { + require.Equal(t, raftengine.NativePeerStep, check.Operation) + require.EqualValues(t, 1, check.SessionGeneration) + } + checkFreshApplyResults(t, e, client, st, prefix, frames) + require.Zero(t, *calls) + require.Equal(t, initial, e.nativeState()) + require.False(t, guard.suspended) + }) + } +} + +func checkFreshApplyResults(t *testing.T, e *Engine, client pb.EtcdRaftClient, st store.MVCCStore, prefix freshProposal, frames []freshProposal) { + t.Helper() + reader, ok := st.(raftengine.AppliedIndexReader) + require.True(t, ok) + durable, present, err := reader.LastAppliedIndex() + require.NoError(t, err) + require.True(t, present) + require.EqualValues(t, 1, durable) + proposals := append([]freshProposal{prefix}, frames...) + for _, frame := range proposals { + e.pendingProposals[frame.id] = proposalRequest{id: frame.id, payloadDigest: sha256.Sum256(frame.payload), done: make(chan proposalResult, 1)} + } + for i, tc := range []struct { + conflict bool + durable uint64 + key string + value string + }{ + {false, 2, "prefix", "prefix-value"}, + {false, 3, "key", "value-0"}, {true, 3, "key", "value-0"}, {false, 5, "key", "value-2"}, {true, 5, "key", "value-2"}, + } { + index := uint64(i + 2) + done := e.pendingProposals[proposals[i].id].done + freshHeartbeat(t, client, 1, index) + handleFreshAppend(t, e) + require.NoError(t, e.drainReady()) + result := testutil.Recv(t, done, time.Second, "missing ordered apply result") + require.NoError(t, result.err) + require.Equal(t, index, result.result.CommitIndex) + if tc.conflict { + err, ok := result.result.Response.(error) + require.True(t, ok) + require.ErrorIs(t, err, store.ErrWriteConflict) + } else { + require.Nil(t, result.result.Response) + } + require.Equal(t, index, e.applied) + durable, present, err := reader.LastAppliedIndex() + require.NoError(t, err) + require.True(t, present) + require.Equal(t, tc.durable, durable) + value, err := st.GetAt(t.Context(), []byte(tc.key), 35) + require.NoError(t, err) + require.Equal(t, tc.value, string(value)) + } + require.Empty(t, e.pendingProposals) +} diff --git a/internal/raftengine/etcd/protected_proposal_quorum_test.go b/internal/raftengine/etcd/protected_proposal_quorum_test.go new file mode 100644 index 000000000..4d2b19cf0 --- /dev/null +++ b/internal/raftengine/etcd/protected_proposal_quorum_test.go @@ -0,0 +1,143 @@ +package etcd + +import ( + "testing" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" +) + +func TestProtectedProposalTurnUsesDurableFollowerResponse(t *testing.T) { + e, admission := newProposalTurnEngine(t) + for _, queues := range e.peerDispatchers { + for _, lane := range []chan dispatchRequest{queues.normal, queues.heartbeat, queues.election, queues.heartbeatResp, queues.readIndexResp} { + for len(lane) != 0 { + closeDispatchRequest(<-lane) + } + } + } + _, configuration, err := e.storage.InitialState() + require.NoError(t, err) + term, err := e.storage.Term(e.applied) + require.NoError(t, err) + followerStorage := etcdraft.NewMemoryStorage() + snapshot := &raftpb.Snapshot{Metadata: &raftpb.SnapshotMetadata{ + Index: uint64Ptr(e.applied), Term: &term, ConfState: configuration, + }} + require.NoError(t, followerStorage.ApplySnapshot(snapshot)) + require.NoError(t, followerStorage.SetHardState(&raftpb.HardState{ + Term: uint64Ptr(e.nativeState().Term), Commit: uint64Ptr(e.applied), + })) + follower := mustRawNode(t, followerStorage, 2) + followerDisk := proposalTurnWAL(t) + require.NoError(t, followerDisk.SaveSnap(snapshot)) + first, _ := turnProposal(t, e, admission, "data-first") + second, _ := turnProposal(t, e, admission, "data-second") + e.proposeCh <- first + e.proposeCh <- second + turnOwnerEvent(t, e) + require.NoError(t, e.drainReady()) + queue := e.peerDispatchers[2].normal + require.NotEmpty(t, queue) + for len(queue) != 0 { + request := <-queue + require.NoError(t, follower.Step(&request.msg)) + closeDispatchRequest(request) + } + ready := follower.Ready() + require.Len(t, ready.Entries, 2) + durable := make(chan error, 1) + go func() { durable <- followerDisk.Save(ready.HardState, ready.Entries) }() + release := false + defer func() { + if !release { + close(followerDisk.release) + } + }() + require.Equal(t, []uint64{3, 4}, <-followerDisk.entered) + require.Empty(t, first.done) + require.Empty(t, second.done) + require.Equal(t, uint64(2), e.rawNode.BasicStatus().GetCommit()) + close(followerDisk.release) + release = true + require.NoError(t, <-durable) + require.NoError(t, followerStorage.Append(ready.Entries)) + if !etcdraft.IsEmptyHardState(ready.HardState) { + require.NoError(t, followerStorage.SetHardState(ready.HardState)) + } + var responses []uint64 + for _, message := range ready.Messages { + if message.GetType() == raftpb.MsgAppResp { + require.False(t, message.GetReject()) + responses = append(responses, message.GetIndex()) + } + require.NoError(t, e.rawNode.Step(message)) + } + require.Equal(t, []uint64{3, 4}, responses, "use the real follower's responses, not constructed ACKs") + follower.Advance(ready) + require.NoError(t, e.drainReady()) + for i, request := range []proposalRequest{first, second} { + result, resultErr := e.nativeProposalResult(request.ctx, <-request.done) + require.NoError(t, resultErr) + require.Equal(t, uint64(i+3), result.CommitIndex) + require.Equal(t, string(request.payload), result.Response) + } +} + +func TestProtectedProposalTurnStepdownDistinguishesUnsubmitted(t *testing.T) { + e, admission := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, admission, "data-first") + deferred, _ := turnProposal(t, e, admission, "data-"+string(make([]byte, maxProposalTurnBytes))) + e.proposeCh <- first + e.proposeCh <- deferred + turnOwnerEvent(t, e) + require.NotNil(t, e.pendingProtectedBatchEvent) + require.Equal(t, deferred.id, e.pendingProtectedBatchEvent.proposal.id) + require.NoError(t, e.drainReady()) + require.Empty(t, first.done) + require.Empty(t, deferred.done) + require.NoError(t, e.rawNode.Step(&raftpb.Message{ + Type: raftpb.MsgHeartbeat.Enum(), From: uint64Ptr(2), To: uint64Ptr(1), Term: uint64Ptr(3), + })) + require.NoError(t, e.drainReady()) + require.Nil(t, e.pendingProtectedBatchEvent) + require.ErrorIs(t, (<-first.done).err, raftengine.ErrLeadershipLost) + result := <-deferred.done + require.ErrorIs(t, result.err, raftengine.ErrNotLeader) + require.NotErrorIs(t, result.err, raftengine.ErrLeadershipLost) + require.Nil(t, result.result) +} + +func TestProtectedProposalTurnFailedSaveDoesNotComplete(t *testing.T) { + for _, afterWrite := range []bool{false, true} { + name := "before-write" + if afterWrite { + name = "after-write" + } + t.Run(name, func(t *testing.T) { + e, admission := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, admission, "data-first") + second, _ := turnProposal(t, e, admission, "data-second") + failure := errors.New("injected proposal-turn Save failure") + gate := proposalTurnWAL(t) + gate.failure, gate.afterWrite = failure, afterWrite + close(gate.release) + e.persist = gate + e.proposeCh <- first + e.proposeCh <- second + turnOwnerEvent(t, e) + require.ErrorIs(t, e.drainReady(), failure) + require.Empty(t, first.done) + require.Empty(t, second.done) + e.failPending(failure) + for _, request := range []proposalRequest{first, second} { + result := <-request.done + require.ErrorIs(t, result.err, failure) + require.Nil(t, result.result) + } + }) + } +} diff --git a/internal/raftengine/etcd/protected_proposal_turn.go b/internal/raftengine/etcd/protected_proposal_turn.go new file mode 100644 index 000000000..2c820aa1d --- /dev/null +++ b/internal/raftengine/etcd/protected_proposal_turn.go @@ -0,0 +1,72 @@ +package etcd + +import ( + "time" + + "github.com/bootjp/elastickv/internal/raftengine" + etcdraft "go.etcd.io/raft/v3" +) + +const ( + maxProposalTurnCount = 32 + maxProposalTurnBytes = 128 << 10 +) + +type proposalTurn struct { + term, configuration uint64 + classifier raftengine.ProposalTurnClassifier +} + +// Only the synchronous owner calls this between Ready drains. Each rendezvous +// runs the ordinary proposal handler with the caller's original request. +func (e *Engine) handleProposalTurn(first proposalRequest, tick <-chan time.Time) { + turn := e.beginProposalTurn() + e.handleProposal(first) + remaining := maxProposalTurnBytes - len(first.payload) + if turn.classifier == nil || remaining <= 0 || !e.rawNode.HasReady() || !turn.classifier.IsProposalTurnPayload(first.payload) { + return + } + e.handleWaitingProposals(turn, remaining, tick) +} + +func (e *Engine) beginProposalTurn() proposalTurn { + classifier, ok := e.fsm.(raftengine.ProposalTurnClassifier) + if !ok || e.nativeAdmission == nil || e.admissionChanged == nil || e.storagePipeline != nil || e.rawNode == nil || e.rawNode.HasReady() { + return proposalTurn{} + } + turn := proposalTurn{term: e.rawNode.BasicStatus().GetTerm(), configuration: e.nativeConfigurationIndex, classifier: classifier} + if !e.proposalTurnStateMatches(turn.term, turn.configuration) { + return proposalTurn{} + } + return turn +} + +func (e *Engine) handleWaitingProposals(turn proposalTurn, remaining int, tick <-chan time.Time) { + for count := 1; count < maxProposalTurnCount && remaining > 0; count++ { + if !e.proposalTurnStateMatches(turn.term, turn.configuration) || e.proposalTurnEventPending(tick) { + return + } + select { + case req := <-e.proposeCh: + if len(req.payload) > remaining || !turn.classifier.IsProposalTurnPayload(req.payload) { + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchProposal, proposal: req} + return + } + e.handleProposal(req) + remaining -= len(req.payload) + default: + return + } + } +} + +func (e *Engine) proposalTurnStateMatches(term, configuration uint64) bool { + status := e.rawNode.BasicStatus() + return status.RaftState == etcdraft.StateLeader && status.Lead == e.nodeID && status.LeadTransferee == 0 && + term != 0 && status.GetTerm() == term && configuration != 0 && e.nativeConfigurationIndex == configuration && + e.proposalConfigurationMatches(configuration) && !e.configurationTransition.Load() && !e.snapshotTransition.Load() +} + +func (e *Engine) proposalTurnEventPending(tick <-chan time.Time) bool { + return e.pendingProtectedStep != nil || len(e.protectedStepCh) != 0 || e.protectedAppendPriorityPending(tick) +} diff --git a/internal/raftengine/etcd/protected_proposal_turn_events_test.go b/internal/raftengine/etcd/protected_proposal_turn_events_test.go new file mode 100644 index 000000000..d2cf13bd0 --- /dev/null +++ b/internal/raftengine/etcd/protected_proposal_turn_events_test.go @@ -0,0 +1,232 @@ +package etcd + +import ( + "context" + "strings" + "testing" + "testing/synctest" + "time" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" +) + +func TestProtectedProposalTurnDefersRendezvousSingly(t *testing.T) { + for _, tc := range []struct { + name string + payload string + fatal bool + }{ + {"unknown", "unknown", false}, + {"over-budget", "data-" + strings.Repeat("x", (128<<10)-6), false}, + {"fatal", "control", true}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e, a := newProposalTurnEngine(t) + e.proposeCh = make(chan proposalRequest) + first, _ := turnProposal(t, e, a, "data-first") + deferred, _ := turnProposal(t, e, a, tc.payload) + third, _ := turnProposal(t, e, a, "data-third") + stop := make(chan struct{}) + defer close(stop) + for _, req := range []proposalRequest{first, deferred, third} { + queueTurnInput(e.proposeCh, req, stop) + } + turnOwnerEvent(t, e) + event := e.pendingProtectedBatchEvent + require.NotNil(t, event) + require.Equal(t, protectedBatchProposal, event.kind) + require.Equal(t, deferred.id, event.proposal.id) + require.True(t, deferred.ctx == event.proposal.ctx) + require.Len(t, e.pendingProposals, 1) + require.Empty(t, deferred.done) + if tc.fatal { + e.failPending(errClosed) + require.Nil(t, e.pendingProtectedBatchEvent) + require.Len(t, deferred.done, 1) + require.ErrorIs(t, (<-deferred.done).err, errClosed) + require.Empty(t, third.done) + return + } + require.NoError(t, e.drainReady()) + base, err := e.storage.LastIndex() + require.NoError(t, err) + require.Equal(t, uint64(3), base) + turnOwnerEvent(t, e) + require.Nil(t, e.pendingProtectedBatchEvent) + require.Contains(t, e.pendingProposals, deferred.id) + require.NotContains(t, e.pendingProposals, third.id) + require.NoError(t, e.drainReady()) + entries, err := e.storage.Entries(4, 5, ^uint64(0)) + require.NoError(t, err) + require.Equal(t, encodeProposalEnvelope(deferred.id, deferred.payload), entries[0].GetData()) + turnOwnerEvent(t, e) + require.Contains(t, e.pendingProposals, third.id) + }) + }) + } +} + +func TestProtectedProposalTurnCapturesControl(t *testing.T) { + for _, kind := range []protectedBatchEventKind{protectedBatchRead, protectedBatchAdmin, protectedBatchTick} { + name := map[protectedBatchEventKind]string{protectedBatchRead: "read", protectedBatchAdmin: "admin", protectedBatchTick: "tick"}[kind] + t.Run(name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e, a := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, a, "data-first") + second, _ := turnProposal(t, e, a, "data-second") + ticks := make(chan time.Time) + stop := make(chan struct{}) + defer close(stop) + queue, verify := proposalTurnControl(t, kind, e, a, ticks, stop) + a.boundary = func(ctx context.Context) { + if ctx == first.ctx { + queue() + } + } + e.proposeCh <- first + e.proposeCh <- second + ok, err := e.handleEvent(ticks) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.proposeCh, 1) + require.NotNil(t, e.pendingProtectedBatchEvent) + require.Equal(t, kind, e.pendingProtectedBatchEvent.kind) + require.NoError(t, e.drainReady()) + turnOwnerEvent(t, e) + require.Nil(t, e.pendingProtectedBatchEvent) + require.Len(t, e.proposeCh, 1) + verify() + }) + }) + } +} + +func queueTurnInput[T any](ch chan<- T, input T, stop <-chan struct{}) { + go func() { + select { + case ch <- input: + case <-stop: + } + }() + synctest.Wait() +} + +func proposalTurnControl(t *testing.T, kind protectedBatchEventKind, e *Engine, a *readTurnAdmission, ticks chan time.Time, stop <-chan struct{}) (queue, verify func()) { + t.Helper() + switch kind { + case protectedBatchRead: + e.readCh = make(chan readRequest) + read, _ := newTurnRead(t, e, a, raftadmission.Recovery) + return func() { queueTurnInput(e.readCh, read, stop) }, func() { require.Contains(t, e.pendingReads, read.id) } + case protectedBatchAdmin: + e.adminCh = make(chan adminRequest) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + admin := adminRequest{ctx: ctx, done: make(chan adminResult, 1)} + return func() { queueTurnInput(e.adminCh, admin, stop) }, func() { + require.Len(t, admin.done, 1) + require.ErrorIs(t, (<-admin.done).err, context.Canceled) + } + case protectedBatchTick: + // The captured tick must be the one that issues the heartbeat. + for range defaultHeartbeatTick - 1 { + e.rawNode.Tick() + } + require.False(t, e.rawNode.HasReady()) + return func() { queueTurnInput(ticks, time.Unix(1, 0), stop) }, func() { require.True(t, e.rawNode.HasReady()) } + case protectedBatchProposal: + t.Fatal("expected a control event") + } + return nil, nil +} + +func TestProtectedProposalTurnYieldsBetweenMembers(t *testing.T) { + for _, tc := range []struct { + name string + change func(*testing.T, *Engine) + }{ + {"role-term", func(t *testing.T, e *Engine) { + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: raftpb.MsgHeartbeat.Enum(), From: uint64Ptr(2), Term: uint64Ptr(3)})) + }}, + {"configuration", func(t *testing.T, e *Engine) { + _, err := e.applyNativeConfChange(&raftpb.ConfChange{Type: raftpb.ConfChangeAddLearnerNode.Enum(), NodeId: uint64Ptr(4)}, 3) + require.NoError(t, err) + e.setConfigIndex(3) + }}, + {"pending-conf", func(_ *testing.T, e *Engine) { e.pendingConfChangeIndex.Store(3) }}, + {"joint", func(_ *testing.T, e *Engine) { e.redisFenceGCJointConfig = true }}, + {"configuration-transition", func(_ *testing.T, e *Engine) { e.configurationTransition.Store(true) }}, + {"transfer", func(_ *testing.T, e *Engine) { e.rawNode.TransferLeader(2) }}, + {"snapshot-transition", func(_ *testing.T, e *Engine) { e.snapshotTransition.Store(true) }}, + {"snapshot-result", func(_ *testing.T, e *Engine) { + e.snapshotResCh = make(chan snapshotResult, 1) + e.snapshotResCh <- snapshotResult{} + }}, + {"dispatch", func(_ *testing.T, e *Engine) { + e.dispatchReportCh = make(chan dispatchReport, 1) + e.dispatchReportCh <- dispatchReport{} + }}, + {"step", func(_ *testing.T, e *Engine) { e.stepCh = make(chan raftpb.Message, 1); e.stepCh <- raftpb.Message{} }}, + {"priority-step", func(_ *testing.T, e *Engine) { + e.priorityStepCh = make(chan raftpb.Message, 1) + e.priorityStepCh <- raftpb.Message{} + }}, + {"protected-step", func(_ *testing.T, e *Engine) { + e.protectedStepCh = make(chan protectedStep, 1) + e.protectedStepCh <- protectedStep{} + }}, + {"protected-priority", func(_ *testing.T, e *Engine) { + e.protectedPriorityStepCh = make(chan protectedStep, 1) + e.protectedPriorityStepCh <- protectedStep{} + }}, + {"pending-step", func(_ *testing.T, e *Engine) { e.pendingProtectedStep = &protectedStep{} }}, + {"pending-event", func(_ *testing.T, e *Engine) { + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchTick} + }}, + {"close", func(_ *testing.T, e *Engine) { e.closeCh = make(chan struct{}); close(e.closeCh) }}, + } { + t.Run(tc.name, func(t *testing.T) { + e, a := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, a, "data-first") + second, _ := turnProposal(t, e, a, "data-second") + e.nativeAdmission = &proposalTurnAdmission{a, func(ctx context.Context) { + if ctx == first.ctx { + tc.change(t, e) + } + }} + e.proposeCh <- first + e.proposeCh <- second + turnOwnerEvent(t, e) + require.Len(t, e.proposeCh, 1) + require.Contains(t, e.pendingProposals, first.id) + require.NotContains(t, e.pendingProposals, second.id) + }) + } +} + +func TestProtectedProposalTurnRequiresProtectedSyncClassifier(t *testing.T) { + for _, tc := range []struct { + name string + change func(*Engine) + }{ + {"unprotected", func(e *Engine) { e.nativeAdmission = nil }}, + {"missing-callback", func(e *Engine) { e.admissionChanged = nil }}, + {"async", func(e *Engine) { e.storagePipeline = &engineStoragePipeline{} }}, + {"missing-classifier", func(e *Engine) { e.fsm = &testStateMachine{} }}, + } { + t.Run(tc.name, func(t *testing.T) { + e, a := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, a, "data-one") + second, _ := turnProposal(t, e, a, "data-two") + tc.change(e) + e.proposeCh <- first + e.proposeCh <- second + turnOwnerEvent(t, e) + require.Contains(t, e.pendingProposals, first.id) + require.Len(t, e.proposeCh, 1) + }) + } +} diff --git a/internal/raftengine/etcd/protected_proposal_turn_test.go b/internal/raftengine/etcd/protected_proposal_turn_test.go new file mode 100644 index 000000000..be89b6fcc --- /dev/null +++ b/internal/raftengine/etcd/protected_proposal_turn_test.go @@ -0,0 +1,310 @@ +package etcd + +import ( + "bytes" + "context" + "path/filepath" + "strings" + "sync" + "testing" + "testing/synctest" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/server/v3/etcdserver/api/snap" + etcdstorage "go.etcd.io/etcd/server/v3/storage" + "go.etcd.io/etcd/server/v3/storage/wal" + "go.etcd.io/raft/v3/raftpb" + "go.uber.org/zap" +) + +type proposalTurnFSM struct{ StateMachine } + +func (*proposalTurnFSM) IsProposalTurnPayload(payload []byte) bool { + return bytes.HasPrefix(payload, []byte("data-")) +} + +func newProposalTurnEngine(t *testing.T) (*Engine, *readTurnAdmission) { + t.Helper() + e, a := newReadTurnEngine(t, true) + e.admissionChanged = func() {} + e.raftCutoverIndex = orInertCutover(nil) + e.proposeCh = make(chan proposalRequest, 40) + e.fsm = &proposalTurnFSM{e.fsm} + return e, a +} + +func turnProposal(t *testing.T, e *Engine, a *readTurnAdmission, payload string) (proposalRequest, *raftadmission.Operation) { + t.Helper() + ctx, op, err := a.Begin(t.Context(), raftadmission.Data) + require.NoError(t, err) + t.Cleanup(op.CancelAndJoin) + req, err := e.ownedNativeProposal(ctx, []byte(payload)) + require.NoError(t, err) + return req, op +} + +func turnOwnerEvent(t *testing.T, e *Engine) { + t.Helper() + ok, err := e.handleEvent(nil) + require.NoError(t, err) + require.True(t, ok) +} + +func proposalTurnWAL(t *testing.T) *appendBatchSaveGate { + t.Helper() + log := zap.NewNop() + w, err := wal.Create(log, filepath.Join(t.TempDir(), "wal"), nil) + require.NoError(t, err) + disk := etcdstorage.NewStorage(log, w, snap.New(log, t.TempDir())) + t.Cleanup(func() { require.NoError(t, disk.Close()) }) + return &appendBatchSaveGate{Storage: disk, entered: make(chan []uint64, 2), release: make(chan struct{})} +} + +func TestProtectedProposalTurnSharesOneWALSave(t *testing.T) { + e, a := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, a, "data-first") + second, _ := turnProposal(t, e, a, "data-second") + e.proposeCh <- first + e.proposeCh <- second + gate := proposalTurnWAL(t) + close(gate.release) + e.persist = gate + for len(e.proposeCh) != 0 { + turnOwnerEvent(t, e) + require.NoError(t, e.drainReady()) + } + var saves [][]uint64 + for len(gate.entered) != 0 { + saves = append(saves, <-gate.entered) + } + require.Equal(t, [][]uint64{{3, 4}}, saves, "WAL Saves containing entries for the two already-waiting proposals") + require.Empty(t, first.done) + require.Empty(t, second.done) + ackProposalPrefix(t, e, 4) + require.NoError(t, e.drainReady()) + for i, req := range []proposalRequest{first, second} { + require.Len(t, req.done, 1) + res, err := e.nativeProposalResult(req.ctx, <-req.done) + require.NoError(t, err) + require.Equal(t, uint64(i+3), res.CommitIndex) + require.Equal(t, string(req.payload), res.Response) + } +} + +func ackProposalPrefix(t *testing.T, e *Engine, index uint64) { + t.Helper() + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: raftpb.MsgAppResp.Enum(), From: uint64Ptr(2), Term: uint64Ptr(2), Index: &index})) +} + +func TestProtectedProposalTurnWaitsForSaveQuorumAndApply(t *testing.T) { + e, a := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, a, "data-one") + second, _ := turnProposal(t, e, a, "data-two") + e.proposeCh <- first + e.proposeCh <- second + gate := proposalTurnWAL(t) + e.persist = gate + fsm := &asyncStorageFSM{payload: second.payload, applyEntered: make(chan uint64, 1), applyRelease: make(chan struct{}), applyReturned: make(chan struct{})} + releaseSave := sync.OnceFunc(func() { close(gate.release) }) + defer releaseSave() + defer fsm.unblock() + e.fsm = &proposalTurnFSM{fsm} + beforeDispatch := len(e.peerDispatchers[2].normal) + turnOwnerEvent(t, e) + done := make(chan error, 1) + go func() { done <- e.drainReady() }() + select { + case indexes := <-gate.entered: + require.Equal(t, []uint64{3, 4}, indexes) + require.Empty(t, first.done) + require.Empty(t, second.done) + require.Empty(t, fsm.Applied()) + require.Len(t, e.peerDispatchers[2].normal, beforeDispatch) + releaseSave() + case err := <-done: + t.Fatalf("expected WAL Save, drain returned %v", err) + } + require.NoError(t, <-done) + require.Empty(t, first.done) + require.Empty(t, second.done) + require.Empty(t, fsm.Applied()) + ackProposalPrefix(t, e, 4) + go func() { done <- e.drainReady() }() + select { + case <-fsm.applyEntered: + require.Len(t, first.done, 1, "index 3 completed after its own apply") + require.Empty(t, second.done, "index 4 is still inside Apply") + case err := <-done: + t.Fatalf("expected FSM Apply, drain returned %v", err) + } + fsm.unblock() + require.NoError(t, <-done) + require.Equal(t, [][]byte{first.payload, second.payload}, fsm.Applied()) + require.Len(t, second.done, 1) +} + +type proposalTurnScope struct { + raftengine.NativeScope + req proposalRequest + t *testing.T + checked bool +} + +func (s *proposalTurnScope) Check(ctx context.Context, req raftengine.NativeRequest) error { + require.False(s.t, s.checked) + require.True(s.t, s.req.ctx == ctx) + require.Equal(s.t, raftengine.NativeProposal, req.Operation) + require.Equal(s.t, s.req.payload, req.Payload) + require.Equal(s.t, s.req.payloadDigest, req.PayloadDigest) + s.checked = true + return s.NativeScope.Check(ctx, req) +} + +// The boundary hook runs after the real arbiter releases its mutex. +type proposalTurnAdmission struct { + *readTurnAdmission + after func(context.Context) +} + +func (a *proposalTurnAdmission) WithNative(ctx context.Context, group uint64, action func(raftengine.NativeScope) error) error { + err := a.readTurnAdmission.WithNative(ctx, group, action) + a.after(ctx) + return err +} + +func TestProtectedProposalTurnChecksEachCallerAcrossRevocation(t *testing.T) { + e, a := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, a, "data-first") + second, revoke := turnProposal(t, e, a, "data-second") + second.ctx = context.WithoutCancel(second.ctx) + requests := map[context.Context]proposalRequest{first.ctx: first, second.ctx: second} + var scopes []*proposalTurnScope + a.inside = func(ctx context.Context, scope raftengine.NativeScope) raftengine.NativeScope { + req, ok := requests[ctx] + if !ok { + return scope + } + s := &proposalTurnScope{NativeScope: scope, req: req, t: t} + scopes = append(scopes, s) + return s + } + e.nativeAdmission = &proposalTurnAdmission{a, func(ctx context.Context) { + if ctx == first.ctx { + revoke.CancelAndJoin() + } + }} + e.proposeCh <- first + e.proposeCh <- second + turnOwnerEvent(t, e) + require.Len(t, scopes, 2) + require.True(t, scopes[0].checked && scopes[1].checked) + require.Len(t, second.done, 1) + require.ErrorIs(t, (<-second.done).err, raftengine.ErrNativeAdmissionDenied) + require.NoError(t, e.drainReady()) + last, err := e.storage.LastIndex() + require.NoError(t, err) + require.Equal(t, uint64(3), last) + ackProposalPrefix(t, e, last) + require.NoError(t, e.drainReady()) + require.Len(t, first.done, 1) + require.Empty(t, second.done) +} + +func TestProtectedProposalTurnPublicLateCancelAndResultValidation(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e, a := newProposalTurnEngine(t) + e.proposeCh = make(chan proposalRequest) + type caller struct { + result chan proposalResult + op *raftadmission.Operation + cancel context.CancelFunc + } + var callers []caller + for _, data := range []string{"data-cancel", "data-stale", "data-ok"} { + ctx, op, err := a.Begin(t.Context(), raftadmission.Data) + require.NoError(t, err) + t.Cleanup(op.CancelAndJoin) + ctx, cancel := context.WithCancel(context.WithoutCancel(ctx)) + t.Cleanup(cancel) + done := make(chan proposalResult, 1) + callers = append(callers, caller{done, op, cancel}) + go func() { + res, err := e.Propose(ctx, []byte(data)) + done <- proposalResult{res, err} + }() + synctest.Wait() + } + turnOwnerEvent(t, e) + require.Len(t, e.pendingProposals, 3) + callers[0].cancel() + res := <-callers[0].result + require.Nil(t, res.result) + require.ErrorIs(t, res.err, context.Canceled) + require.Len(t, e.pendingProposals, 2) + callers[1].op.CancelAndJoin() + require.NoError(t, e.drainReady()) + ackProposalPrefix(t, e, 5) + require.NoError(t, e.drainReady()) + res = <-callers[1].result + require.Nil(t, res.result) + require.ErrorIs(t, res.err, raftengine.ErrLeadershipLost) + res = <-callers[2].result + require.NoError(t, res.err) + require.Equal(t, uint64(5), res.result.CommitIndex) + require.Equal(t, "data-ok", res.result.Response) + require.Empty(t, e.pendingProposals) + }) +} + +func TestProtectedProposalTurnBounds(t *testing.T) { + for _, tc := range []struct { + name string + first string + next int + pending int + }{ + {"count", "data-x", 32, 32}, + {"bytes", "data-" + strings.Repeat("x", (128<<10)-11), 2, 2}, + {"oversize-first", "data-" + strings.Repeat("x", 128<<10), 1, 1}, + {"unknown-first", "control", 1, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + e, a := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, a, tc.first) + e.proposeCh <- first + for range tc.next { + next, _ := turnProposal(t, e, a, "data-y") + e.proposeCh <- next + } + turnOwnerEvent(t, e) + require.Len(t, e.pendingProposals, tc.pending) + require.Len(t, e.proposeCh, tc.next+1-tc.pending) + require.Nil(t, e.pendingProtectedBatchEvent) + }) + } +} + +func TestProtectedProposalTurnHonorsEachProposalFence(t *testing.T) { + e, a := newProposalTurnEngine(t) + first, _ := turnProposal(t, e, a, "data-current") + term, _ := turnProposal(t, e, a, "data-old-term") + config, _ := turnProposal(t, e, a, "data-old-config") + term.expectedTerm = 1 + config.ctx = raftengine.WithProposalConfigurationFence(config.ctx, 9) + e.proposeCh <- first + e.proposeCh <- term + e.proposeCh <- config + turnOwnerEvent(t, e) + require.Len(t, term.done, 1) + require.ErrorIs(t, (<-term.done).err, raftengine.ErrStaleAdmissionTerm) + require.Len(t, config.done, 1) + require.ErrorIs(t, (<-config.done).err, raftengine.ErrProposalConfigurationChanged) + require.Len(t, e.pendingProposals, 1) + require.Contains(t, e.pendingProposals, first.id) + require.NoError(t, e.drainReady()) + last, err := e.storage.LastIndex() + require.NoError(t, err) + require.Equal(t, uint64(3), last) +} diff --git a/internal/raftengine/etcd/protected_read_turn_extra_test.go b/internal/raftengine/etcd/protected_read_turn_extra_test.go new file mode 100644 index 000000000..1583e0175 --- /dev/null +++ b/internal/raftengine/etcd/protected_read_turn_extra_test.go @@ -0,0 +1,98 @@ +package etcd + +import ( + "context" + "sync/atomic" + "testing" + "testing/synctest" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" +) + +func TestProtectedReadTurnYieldsToNewPriorityStep(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + e.readCh = make(chan readRequest) // Production senders rendezvous with the owner. + e.protectedPriorityStepCh = make(chan protectedStep, 1) + stop := make(chan struct{}) + defer close(stop) + callers := map[context.Context]bool{} + for range 2 { + req, _ := newTurnRead(t, e, guard, raftadmission.Data) + callers[req.ctx] = true + go func() { + select { + case e.readCh <- req: + case <-stop: + } + }() + } + synctest.Wait() + + issued := 0 + overtookPriority := false + guard.boundary = func(ctx context.Context) { + if !callers[ctx] { + return + } + issued++ + if issued == 1 { + // Only queue readiness matters here. Peer admission is separate. + e.protectedPriorityStepCh <- protectedStep{message: raftpb.Message{Type: raftpb.MsgHeartbeat.Enum()}} + } else if len(e.protectedPriorityStepCh) != 0 { + overtookPriority = true + } + } + ok, err := e.handleEvent(nil) + require.NoError(t, err) + require.True(t, ok) + require.Positive(t, issued) + require.False(t, overtookPriority, "the second read overtook a waiting priority step") + }) +} + +// Notify the test when the owner has sampled Err. The owner's next role lookup +// takes e.mu.RLock, so the test can hold it there until caller cleanup finishes. +type readTurnObservedContext struct { + context.Context + armed atomic.Bool + checked chan struct{} +} + +func (c *readTurnObservedContext) Err() error { + err := c.Context.Err() + if c.armed.Swap(false) { + close(c.checked) + } + return err +} + +func TestProtectedReadTurnCancelBeforePendingRegistration(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + read, _ := newTurnRead(t, e, guard, raftadmission.Data) + ctx, cancel := context.WithCancel(read.ctx) + defer cancel() + result := make(chan error, 1) + observed := &readTurnObservedContext{Context: ctx, checked: make(chan struct{})} + go func() { result <- e.VerifyLeader(observed) }() + req := <-e.readCh + observed.armed.Store(true) + + e.mu.Lock() + finished := make(chan struct{}) + go func() { + e.handleReadQueue(req) + close(finished) + }() + <-observed.checked + cancel() + callerErr := <-result + e.mu.Unlock() + <-finished + + require.ErrorIs(t, callerErr, context.Canceled) + _, pending := e.pendingRead(req.id) + require.False(t, pending, "the owner registered the read after its caller finished cancellation") +} diff --git a/internal/raftengine/etcd/protected_read_turn_priority_test.go b/internal/raftengine/etcd/protected_read_turn_priority_test.go new file mode 100644 index 000000000..639e4bdcd --- /dev/null +++ b/internal/raftengine/etcd/protected_read_turn_priority_test.go @@ -0,0 +1,88 @@ +package etcd + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/stretchr/testify/require" +) + +func TestProtectedReadTurnCapturesControlBeforeNextRead(t *testing.T) { + for _, kind := range []protectedBatchEventKind{protectedBatchAdmin, protectedBatchTick} { + t.Run(map[protectedBatchEventKind]string{protectedBatchAdmin: "admin", protectedBatchTick: "tick"}[kind], func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + e.readCh = make(chan readRequest) + e.adminCh = make(chan adminRequest) + ticks := make(chan time.Time, 1) + stop := make(chan struct{}) + defer close(stop) + callers := make(map[context.Context]bool) + for range 2 { + read, _ := newTurnRead(t, e, guard, raftadmission.Data) + callers[read.ctx] = true + go func() { + select { + case e.readCh <- read: + case <-stop: + } + }() + } + synctest.Wait() + issued := 0 + guard.boundary = func(ctx context.Context) { + if !callers[ctx] { + return + } + issued++ + if issued != 1 { + return + } + makeReadTurnControlReady(e, kind, ticks, stop) + } + ok, err := e.handleEvent(ticks) + require.NoError(t, err) + require.True(t, ok) + require.Equal(t, 1, issued) + require.NotNil(t, e.pendingProtectedBatchEvent) + require.Equal(t, kind, e.pendingProtectedBatchEvent.kind) + require.True(t, e.rawNode.HasReady(), "defer the captured event until the issued reads' Ready is drained") + }) + }) + } +} + +func makeReadTurnControlReady(e *Engine, kind protectedBatchEventKind, ticks chan<- time.Time, stop <-chan struct{}) { + if kind == protectedBatchTick { + ticks <- time.Unix(1, 0) + return + } + go func() { + select { + case e.adminCh <- adminRequest{}: + case <-stop: + } + }() + synctest.Wait() +} + +func TestProtectedDeferredReadTurnPreservesTick(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + first, _ := newTurnRead(t, e, guard, raftadmission.Data) + second, _ := newTurnRead(t, e, guard, raftadmission.Data) + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchRead, read: first} + e.readCh <- second + ticks := make(chan time.Time, 1) + ticks <- time.Unix(1, 0) + ok, err := e.handleEvent(ticks) + require.NoError(t, err) + require.True(t, ok) + require.Len(t, e.pendingReads, 1) + require.Contains(t, e.pendingReads, first.id) + require.Len(t, e.readCh, 1) + require.NotNil(t, e.pendingProtectedBatchEvent) + require.Equal(t, protectedBatchTick, e.pendingProtectedBatchEvent.kind) +} diff --git a/internal/raftengine/etcd/protected_read_turn_test.go b/internal/raftengine/etcd/protected_read_turn_test.go new file mode 100644 index 000000000..14b92df37 --- /dev/null +++ b/internal/raftengine/etcd/protected_read_turn_test.go @@ -0,0 +1,355 @@ +package etcd + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/stretchr/testify/require" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" +) + +// All operation checks and result validation delegate to the real arbiter. +// These are local handles. Peer receipts and transport are outside this fixture. +type readTurnAdmission struct { + *raftadmission.Arbiter + inside func(context.Context, raftengine.NativeScope) raftengine.NativeScope + boundary func(context.Context) +} + +func (a *readTurnAdmission) WithNative(ctx context.Context, group uint64, action func(raftengine.NativeScope) error) error { + return a.Arbiter.WithNative(ctx, group, func(scope raftengine.NativeScope) error { + if a.inside != nil { + scope = a.inside(ctx, scope) + } + err := action(scope) + if err == nil && a.boundary != nil { + a.boundary(ctx) + } + return err + }) +} + +type readTurnScope struct { + raftengine.NativeScope + t *testing.T + owner context.Context + checked bool +} + +func (s *readTurnScope) Check(ctx context.Context, req raftengine.NativeRequest) error { + require.True(s.t, ctx == s.owner, "read checked under a different caller's scope") + require.False(s.t, s.checked, "two reads checked in one scope") + require.Equal(s.t, raftengine.NativeReadIndex, req.Operation) + s.checked = true + return s.NativeScope.Check(ctx, req) +} + +func newReadTurnEngine(t *testing.T, leader bool) (*Engine, *readTurnAdmission) { + t.Helper() + e := identityElectionEngine(t, 1) + if leader { + require.NoError(t, e.rawNode.Campaign()) + for _, kind := range []raftpb.MessageType{raftpb.MsgPreVoteResp, raftpb.MsgVoteResp} { + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: kind.Enum(), From: uint64Ptr(2), Term: uint64Ptr(2)})) + require.NoError(t, e.drainReady()) + } + // Acknowledge the new leader's no-op, enabling ReadOnlySafe heartbeats. + last, err := e.storage.LastIndex() + require.NoError(t, err) + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: raftpb.MsgAppResp.Enum(), From: uint64Ptr(2), Term: uint64Ptr(2), Index: &last})) + require.NoError(t, e.drainReady()) + require.Equal(t, raftengine.StateLeader, e.State()) + require.Equal(t, last, e.applied) + require.False(t, e.rawNode.HasReady()) + } else { + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: raftpb.MsgHeartbeat.Enum(), From: uint64Ptr(2), Term: uint64Ptr(1)})) + require.NoError(t, e.drainReady()) + } + a, err := raftadmission.New(raftadmission.Config{Cluster: raftbootstrap.UUID{1}, DefaultGroup: 1, Groups: []uint64{1}, + ValidatePayload: func(raftadmission.Kind, uint64, []byte) error { return nil }}) + require.NoError(t, err) + t.Cleanup(a.Close) + guard := &readTurnAdmission{Arbiter: a} + e.groupID, e.nativeConfigurationIndex, e.nativeAdmission = 1, e.currentConfigIndex(), guard + e.readCh = make(chan readRequest, 40) + require.NoError(t, e.withNative(t.Context(), nil, func() error { return nil })) + publishRecoveryReadProjection(t, &transportTestNode{engine: e}, &recoveryReadTestAdmission{Arbiter: a}, 1, true) + return e, guard +} + +func newTurnRead(t *testing.T, e *Engine, a *readTurnAdmission, kind raftadmission.Kind) (readRequest, *raftadmission.Operation) { + t.Helper() + ctx, op, err := a.Begin(t.Context(), kind) + require.NoError(t, err) + t.Cleanup(op.CancelAndJoin) + return readRequest{ctx: ctx, id: e.nextID(), recovery: kind == raftadmission.Recovery, done: make(chan readResult, 1)}, op +} + +func turnReadState(req readRequest, index uint64) etcdraft.ReadState { + return etcdraft.ReadState{RequestCtx: encodeReadContext(req.id), Index: index} +} + +// Return the opaque quorum tokens actually emitted to one voter. Raft's +// heartbeat token and the application's ReadState.RequestCtx are distinct. +func readTurnTokens(t *testing.T, e *Engine) [][]byte { + t.Helper() + require.NoError(t, e.drainReady()) + var tokens [][]byte + queue := e.peerDispatchers[2].heartbeat + for len(queue) > 0 { + out := <-queue + if out.msg.GetType() == raftpb.MsgHeartbeat && len(out.msg.GetContext()) > 0 { + tokens = append(tokens, out.msg.GetContext()) + } + require.NoError(t, out.Close()) + } + return tokens +} + +func acknowledgeTurnRead(t *testing.T, e *Engine, token []byte, req readRequest) { + t.Helper() + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: raftpb.MsgHeartbeatResp.Enum(), + From: uint64Ptr(2), Term: uint64Ptr(e.nativeState().Term), Context: token})) + require.NoError(t, e.drainReady()) + require.Len(t, req.done, 1) + require.Equal(t, readResult{index: e.applied}, <-req.done) +} + +func TestProtectedReadTurnIssuesBothWaitingReads(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + require.Empty(t, readTurnTokens(t, e)) + first, _ := newTurnRead(t, e, guard, raftadmission.Data) + second, _ := newTurnRead(t, e, guard, raftadmission.Data) + ids := map[context.Context]uint64{first.ctx: first.id, second.ctx: second.id} + var scope *readTurnScope + var checked []uint64 + guard.inside = func(owner context.Context, native raftengine.NativeScope) raftengine.NativeScope { + scope = &readTurnScope{NativeScope: native, t: t, owner: owner} + return scope + } + guard.boundary = func(owner context.Context) { + id, ok := ids[owner] + if !ok { + return + } + require.True(t, scope.checked) + require.True(t, e.rawNode.HasReady(), "native work must be visible before releasing the caller's scope") + checked = append(checked, id) + } + e.readCh <- first + e.readCh <- second + e.handleReadQueue(<-e.readCh) + require.Equal(t, []uint64{first.id, second.id}, checked, "one owner turn must check both waiting reads under their own scopes") + require.Empty(t, e.peerDispatchers[2].heartbeat, "both issues must precede the Ready dispatch") + tokens := readTurnTokens(t, e) + require.Len(t, tokens, 2) + require.NotEqual(t, tokens[0], tokens[1]) + acknowledgeTurnRead(t, e, tokens[0], first) + require.Empty(t, second.done) + acknowledgeTurnRead(t, e, tokens[1], second) +} + +// Drive a second owner turn if the current implementation yielded after one. +// The safety cases run on either side of the scheduling change. +func runReadTurnPair(e *Engine, first, second readRequest) { + e.readCh <- second + e.handleReadQueue(first) + if len(e.readCh) != 0 { + e.handleReadQueue(<-e.readCh) + } +} + +func TestProtectedReadTurnIndependentRevocation(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + a, _ := newTurnRead(t, e, guard, raftadmission.Data) + b, op := newTurnRead(t, e, guard, raftadmission.Data) + // Keep the queued context live while retiring its underlying operation. + // This forces rejection at native admission, beyond the ctx.Err fast path. + b.ctx = context.WithoutCancel(b.ctx) + op.CancelAndJoin() + runReadTurnPair(e, a, b) + require.Len(t, b.done, 1) + require.ErrorIs(t, (<-b.done).err, raftengine.ErrNativeAdmissionDenied) + tokens := readTurnTokens(t, e) + require.Len(t, tokens, 1) + acknowledgeTurnRead(t, e, tokens[0], a) + e.handleReadStates([]etcdraft.ReadState{turnReadState(b, 9)}) + require.Empty(t, b.done) +} + +func TestProtectedReadTurnLateArrival(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + first, _ := newTurnRead(t, e, guard, raftadmission.Data) + late, _ := newTurnRead(t, e, guard, raftadmission.Data) + guard.boundary = func(ctx context.Context) { + if ctx == first.ctx { + e.readCh <- late + } + } + e.handleReadQueue(first) + tokens := readTurnTokens(t, e) + require.Len(t, tokens, 2) + require.NotEqual(t, tokens[0], tokens[1], "a late caller must issue its own newer quorum context") + acknowledgeTurnRead(t, e, tokens[0], first) + require.Empty(t, late.done) + acknowledgeTurnRead(t, e, tokens[1], late) +} + +func TestProtectedReadTurnCanceledFirstAndAppliedTarget(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + first, op := newTurnRead(t, e, guard, raftadmission.Data) + read, _ := newTurnRead(t, e, guard, raftadmission.Data) + read.waitApplied = true + runReadTurnPair(e, first, read) + op.CancelAndJoin() + e.cancelPendingRead(first.id) + e.handleReadStates([]etcdraft.ReadState{turnReadState(first, 8), turnReadState(read, 9)}) + e.applied = 8 + e.resolveReadyReads() + require.Empty(t, read.done) + e.applied = 9 + e.resolveReadyReads() + require.Len(t, read.done, 1) + require.Equal(t, readResult{index: 9}, <-read.done) + require.Empty(t, first.done) +} + +func TestProtectedReadTurnResultLosesAuthority(t *testing.T) { + for _, loss := range []string{"term", "configuration"} { + t.Run(loss, func(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + read, _ := newTurnRead(t, e, guard, raftadmission.Data) + // Mask cancellation so submitReadRequest must exercise ValidateResult. + ctx, cancel := context.WithCancel(context.WithoutCancel(read.ctx)) + defer cancel() + result := make(chan error, 1) + go func() { result <- e.VerifyLeader(ctx) }() + req := <-e.readCh + e.handleReadQueue(req) + require.Empty(t, req.done) + require.Contains(t, e.pendingReads, req.id) + if loss == "term" { + require.NoError(t, e.withNative(t.Context(), nil, func() error { + return e.rawNode.Step(&raftpb.Message{Type: raftpb.MsgHeartbeat.Enum(), From: uint64Ptr(2), Term: uint64Ptr(3)}) + })) + } else { + _, err := e.applyNativeConfChange(&raftpb.ConfChange{Type: raftpb.ConfChangeAddLearnerNode.Enum(), NodeId: uint64Ptr(4)}, 3) + require.NoError(t, err) + } + e.handleReadStates([]etcdraft.ReadState{turnReadState(req, 9)}) + require.ErrorIs(t, <-result, raftengine.ErrLeadershipLost) + }) + } +} + +func TestProtectedReadTurnValidatesEachResult(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + start := func() (readRequest, *raftadmission.Operation, <-chan error) { + read, op := newTurnRead(t, e, guard, raftadmission.Data) + ctx, cancel := context.WithCancel(context.WithoutCancel(read.ctx)) + t.Cleanup(cancel) + result := make(chan error, 1) + go func() { result <- e.VerifyLeader(ctx) }() + return <-e.readCh, op, result + } + first, _, firstResult := start() + second, revoke, secondResult := start() + runReadTurnPair(e, first, second) + require.Contains(t, e.pendingReads, first.id) + require.Contains(t, e.pendingReads, second.id) + revoke.CancelAndJoin() + e.handleReadStates([]etcdraft.ReadState{turnReadState(first, 8), turnReadState(second, 9)}) + require.NoError(t, <-firstResult) + require.ErrorIs(t, <-secondResult, raftengine.ErrLeadershipLost) +} + +func TestProtectedReadTurnDefersQueuedRecovery(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + data, _ := newTurnRead(t, e, guard, raftadmission.Data) + recovery, _ := newTurnRead(t, e, guard, raftadmission.Recovery) + e.readCh <- recovery + e.handleReadQueue(data) + tokens := readTurnTokens(t, e) + require.Len(t, tokens, 1) + acknowledgeTurnRead(t, e, tokens[0], data) + e.handleReadStates([]etcdraft.ReadState{turnReadState(recovery, 9)}) + require.Empty(t, recovery.done, "a queued recovery read must wait for a separate turn") + require.NotNil(t, e.pendingProtectedBatchEvent) + require.Equal(t, recovery.id, e.pendingProtectedBatchEvent.read.id) + handled, err := e.handlePendingProtectedBatchEvent(nil) + require.NoError(t, err) + require.True(t, handled) + require.Nil(t, e.pendingProtectedBatchEvent) + e.handleReadStates([]etcdraft.ReadState{turnReadState(recovery, 9)}) + require.Equal(t, readResult{index: 9}, <-recovery.done) +} + +func TestProtectedReadTurnDeferredRecoveryFailsOnClose(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + data, _ := newTurnRead(t, e, guard, raftadmission.Data) + recovery, _ := newTurnRead(t, e, guard, raftadmission.Recovery) + e.readCh <- recovery + e.handleReadQueue(data) + require.NotNil(t, e.pendingProtectedBatchEvent) + e.failPending(errClosed) + require.ErrorIs(t, (<-data.done).err, errClosed) + require.ErrorIs(t, (<-recovery.done).err, errClosed) + require.Nil(t, e.pendingProtectedBatchEvent) + e.handleReadStates([]etcdraft.ReadState{turnReadState(data, 9), turnReadState(recovery, 9)}) + require.Empty(t, data.done) + require.Empty(t, recovery.done) +} + +func TestProtectedReadTurnCloseBetweenMembers(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + first, _ := newTurnRead(t, e, guard, raftadmission.Data) + second, _ := newTurnRead(t, e, guard, raftadmission.Data) + e.closeCh = make(chan struct{}) + guard.boundary = func(ctx context.Context) { + if ctx == first.ctx { + close(e.closeCh) + } + } + e.readCh <- second + e.handleReadQueue(first) + require.Len(t, e.readCh, 1, "close yields before receiving another caller") + require.Empty(t, second.done) + tokens := readTurnTokens(t, e) + require.Len(t, tokens, 1) + e.failPending(errClosed) + require.ErrorIs(t, (<-first.done).err, errClosed) + require.Empty(t, second.done) +} + +func TestProtectedReadTurnRecoveryRole(t *testing.T) { + e, guard := newReadTurnEngine(t, false) + recovery, _ := newTurnRead(t, e, guard, raftadmission.Recovery) + data, _ := newTurnRead(t, e, guard, raftadmission.Data) + e.readCh <- data + e.handleReadQueue(recovery) + require.Empty(t, recovery.done) + require.Empty(t, data.done, "recovery cannot consume the ordinary caller's turn") + require.Len(t, e.readCh, 1) + e.handleReadQueue(<-e.readCh) + require.Len(t, data.done, 1) + require.ErrorIs(t, (<-data.done).err, errNotLeader) + e.handleReadStates([]etcdraft.ReadState{turnReadState(recovery, 9)}) + require.Len(t, recovery.done, 1) + require.Equal(t, readResult{index: 9}, <-recovery.done) +} + +func TestProtectedReadTurnBound(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + for range 33 { + req, _ := newTurnRead(t, e, guard, raftadmission.Data) + e.readCh <- req + } + e.handleReadQueue(<-e.readCh) + issued := len(readTurnTokens(t, e)) + require.Equal(t, maxReadIndexBatch, issued, "process the bounded already-waiting ordinary prefix") + require.Len(t, e.readCh, 1, "yield to other owner work after at most 32 reads including the first") +} diff --git a/internal/raftengine/etcd/protected_step.go b/internal/raftengine/etcd/protected_step.go index 107c5642d..fea2511e8 100644 --- a/internal/raftengine/etcd/protected_step.go +++ b/internal/raftengine/etcd/protected_step.go @@ -14,6 +14,32 @@ type protectedStep struct { receipt *peersession.Receipt } +// Installed before startup. Only scalar observations leave the owner, outside +// both admission scopes. Observers have no access to receipts or message data. +type syncRaftObserver struct { + // An optional completion observes the same owner turn after both scopes + // return, including when admission denies the selected message. + beforeStep func(from uint64, kind raftpb.MessageType, index uint64, reject bool) func() + appendBytes func(to, first, last uint64, bytes int, preclone bool) +} + +func (o *syncRaftObserver) observeReady(messages []*raftpb.Message) { + for _, msg := range messages { + o.observeAppend(msg, false) + } +} + +func (o *syncRaftObserver) observeAppend(m *raftpb.Message, preclone bool) { + if m.GetType() != raftpb.MsgApp || len(m.Entries) == 0 { + return + } + var size int + for _, entry := range m.Entries { + size += len(entry.Data) + } + o.appendBytes(m.GetTo(), m.Entries[0].GetIndex(), m.Entries[len(m.Entries)-1].GetIndex(), size, preclone) +} + func (e *Engine) enqueueProtectedStep(ctx context.Context, msg raftpb.Message, receipt *peersession.Receipt) error { if err := ctx.Err(); err != nil { return errors.WithStack(err) @@ -45,11 +71,17 @@ func (e *Engine) enqueueProtectedStep(ctx context.Context, msg raftpb.Message, r } } -func (e *Engine) handleProtectedStep(request protectedStep) { +func (e *Engine) handleProtectedStep(request protectedStep) bool { + if o := e.syncObserver; o != nil { + m := &request.message + if complete := o.beforeStep(m.GetFrom(), m.GetType(), m.GetIndex(), m.GetReject()); complete != nil { + defer complete() + } + } // The apply loop owns Step and invalidation ordering. The RPC may already // have completed; retain session generation, not the RPC's short lifetime. nativeRequest := &raftengine.NativeRequest{Operation: raftengine.NativePeerStep, SessionGeneration: request.receipt.LocalGeneration()} - e.handleStepWithAdmission(request.message, nativeRequest, func(action func() error) error { + return e.handleStepWithAdmission(request.message, nativeRequest, func(action func() error) error { return request.receipt.WithAdmission(context.Background(), action) }) } diff --git a/internal/raftengine/etcd/read_index_batch.go b/internal/raftengine/etcd/read_index_batch.go index 1eb4eb112..7df4cbe83 100644 --- a/internal/raftengine/etcd/read_index_batch.go +++ b/internal/raftengine/etcd/read_index_batch.go @@ -1,5 +1,7 @@ package etcd +import "time" + const maxReadIndexBatch = 32 // A batch's first ID identifies the one Raft read context. Each member @@ -11,10 +13,13 @@ type readIndexBatch struct { } func (e *Engine) handleReadQueue(first readRequest) { - // Native admission must authorize the original request at its own - // execution boundary. These requests keep their individual ReadIndex. + e.handleReadQueueWithTick(first, nil) +} + +func (e *Engine) handleReadQueueWithTick(first readRequest, tick <-chan time.Time) { + // Each protected request keeps its own native action and ReadIndex. if e.nativeAdmission != nil { - e.handleRead(first) + e.handleProtectedReadTurn(first, tick) return } @@ -47,6 +52,50 @@ drain: } } +// Amortize Ready dispatch, not authority or quorum contexts. Each newly received +// caller issues a fresh native ReadIndex. Recovery and higher-priority events +// end the turn before another caller is received. +func (e *Engine) handleProtectedReadTurn(first readRequest, tick <-chan time.Time) { + if first.recovery || e.pendingProtectedBatchEvent != nil { + e.handleRead(first) + return + } + e.handleRead(first) + for count := 1; count < maxReadIndexBatch && !e.protectedReadPriorityPending(tick); count++ { + select { + case req := <-e.readCh: + if req.recovery { + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchRead, read: req} + return + } + e.handleRead(req) + default: + return + } + } +} + +func (e *Engine) protectedReadPriorityPending(tick <-chan time.Time) bool { + if e.protectedReadControlPending() || len(e.snapshotResCh) != 0 || len(e.dispatchReportCh) != 0 || len(e.proposeCh) != 0 { + return true + } + select { + case req := <-e.adminCh: + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchAdmin, admin: req} + return true + case <-tick: + e.pendingProtectedBatchEvent = &protectedBatchEvent{kind: protectedBatchTick} + return true + default: + return false + } +} + +func (e *Engine) protectedReadControlPending() bool { + return e.isClosing() || e.pendingProtectedBatchEvent != nil || len(e.protectedPriorityStepCh) != 0 || + len(e.priorityStepCh) != 0 || len(e.stepCh) != 0 +} + func (e *Engine) storeReadIndexBatch(requests []readRequest) uint64 { e.pending.Lock() defer e.pending.Unlock() diff --git a/internal/raftengine/etcd/read_pending_registration_test.go b/internal/raftengine/etcd/read_pending_registration_test.go new file mode 100644 index 000000000..dbfefe1ef --- /dev/null +++ b/internal/raftengine/etcd/read_pending_registration_test.go @@ -0,0 +1,55 @@ +package etcd + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/stretchr/testify/require" + etcdraft "go.etcd.io/raft/v3" +) + +type readRegistrationCancelContext struct { + context.Context + cancel context.CancelFunc +} + +func (c *readRegistrationCancelContext) Err() error { + err := c.Context.Err() + c.cancel() + return err +} + +func TestPipelineReadCanceledRegistrationReturnsReservation(t *testing.T) { + e, admission := newReadTurnEngine(t, true) + p := newPipelineAdmissionFixture(t).storagePipeline + e.storagePipeline = p + read, _ := newTurnRead(t, e, admission, raftadmission.Data) + ctx, cancel := context.WithCancel(read.ctx) + defer cancel() + read.ctx = &readRegistrationCancelContext{Context: ctx, cancel: cancel} + e.admitPipelineRead(read) + require.ErrorIs(t, (<-read.done).err, context.Canceled) + require.Empty(t, e.pendingReads) + require.Empty(t, p.readOwnership) + require.False(t, e.rawNode.HasReady(), "a rejected registration must not issue ReadIndex") + requireStorageWorkUsage(t, p.controlOwnership, 0, 0) +} + +func TestPipelineReadStateCannotRegisterRemovedWaiter(t *testing.T) { + e, admission := newReadTurnEngine(t, true) + e.storagePipeline = newPipelineAdmissionFixture(t).storagePipeline + read, _ := newTurnRead(t, e, admission, raftadmission.Data) + ctx, cancel := context.WithCancel(read.ctx) + read.ctx = ctx + e.admitPipelineRead(read) + requireStorageWorkUsage(t, e.storagePipeline.controlOwnership, pipelineTaskOverhead, 1) + cancel() + e.cancelPendingRead(read.id) + e.handlePipelineReadStates([]etcdraft.ReadState{turnReadState(read, e.applied)}) + require.Empty(t, e.pendingReads) + require.Empty(t, read.done, "an absent waiter must not get a second registration result") + e.retirePipelineReadOwnership() + require.Empty(t, e.storagePipeline.readOwnership) + requireStorageWorkUsage(t, e.storagePipeline.controlOwnership, 0, 0) +} diff --git a/internal/raftengine/etcd/read_probe_coalesce.go b/internal/raftengine/etcd/read_probe_coalesce.go new file mode 100644 index 000000000..6f749f3ab --- /dev/null +++ b/internal/raftengine/etcd/read_probe_coalesce.go @@ -0,0 +1,86 @@ +package etcd + +import ( + "encoding/binary" + + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" +) + +// With raft v3.7 ReadOnlySafe, a later heartbeat confirms a prefix of reads, +// retaining each request's original context and issue-time commit index. Only +// omit earlier probes in a transition-free, read-only Ready. Never change the +// original Ready passed to Advance or combine callers' native admission scopes. +func coalesceProtectedReadProbes(rd etcdraft.Ready, nodeID, term uint64) []*raftpb.Message { + if !readProbeOnlyReady(rd) { + return rd.Messages + } + last, ok := lastProtectedReadProbes(rd.Messages, nodeID, term) + if !ok || len(last) == len(rd.Messages) { + return rd.Messages + } + retained := make([]*raftpb.Message, 0, len(last)) + for i, msg := range rd.Messages { + if last[msg.GetTo()] == i { + retained = append(retained, msg) + } + } + return retained +} + +func (e *Engine) readProbeDispatchMessages(rd etcdraft.Ready) []*raftpb.Message { + if e.nativeAdmission == nil || e.admissionChanged == nil || e.storagePipeline != nil || e.rawNode == nil || + e.hasPendingConfChange() || e.snapshotTransition.Load() { + return rd.Messages + } + status := e.rawNode.BasicStatus() + if status.RaftState != etcdraft.StateLeader || status.Lead != e.nodeID { + return rd.Messages + } + return coalesceProtectedReadProbes(rd, e.nodeID, status.GetTerm()) +} + +func readProbeOnlyReady(rd etcdraft.Ready) bool { + return len(rd.Messages) >= 2 && !rd.MustSync && rd.SoftState == nil && etcdraft.IsEmptyHardState(rd.HardState) && + etcdraft.IsEmptySnap(rd.Snapshot) && len(rd.Entries) == 0 && len(rd.CommittedEntries) == 0 && len(rd.ReadStates) == 0 +} + +func lastProtectedReadProbes(messages []*raftpb.Message, nodeID, term uint64) (map[uint64]int, bool) { + last := make(map[uint64]int) + for i, msg := range messages { + if !isProtectedReadProbe(msg, nodeID, term) { + return nil, false + } + if previous, ok := last[msg.GetTo()]; ok { + prior := messages[previous] + if prior.GetCommit() != msg.GetCommit() || binary.LittleEndian.Uint64(prior.Context) > binary.LittleEndian.Uint64(msg.Context) { + return nil, false + } + } + last[msg.GetTo()] = i + } + return last, true +} + +func isProtectedReadProbe(msg *raftpb.Message, nodeID, term uint64) bool { + return msg != nil && readProbeHeaderMatches(msg, nodeID, term) && readProbeFieldsMatch(msg) && + len(msg.Context) == 8 && binary.LittleEndian.Uint64(msg.Context) != 0 +} + +func readProbeHeaderMatches(msg *raftpb.Message, nodeID, term uint64) bool { + return msg.Type != nil && msg.GetType() == raftpb.MsgHeartbeat && msg.From != nil && msg.GetFrom() == nodeID && + msg.To != nil && readProbeDestination(msg.GetTo(), nodeID) && msg.Term != nil && msg.GetTerm() == term && msg.Commit != nil +} + +func readProbeDestination(to, nodeID uint64) bool { + return to != 0 && to != nodeID && to != etcdraft.LocalAppendThread && to != etcdraft.LocalApplyThread +} + +func readProbeFieldsMatch(msg *raftpb.Message) bool { + return msg.LogTerm == nil && msg.Index == nil && len(msg.Entries) == 0 && msg.Vote == nil && + msg.Snapshot == nil && msg.Reject == nil && msg.RejectHint == nil && readProbeExtensionFieldsEmpty(msg) +} + +func readProbeExtensionFieldsEmpty(msg *raftpb.Message) bool { + return len(msg.Responses) == 0 && len(msg.ProtoReflect().GetUnknown()) == 0 +} diff --git a/internal/raftengine/etcd/read_probe_coalesce_test.go b/internal/raftengine/etcd/read_probe_coalesce_test.go new file mode 100644 index 000000000..00f737e8a --- /dev/null +++ b/internal/raftengine/etcd/read_probe_coalesce_test.go @@ -0,0 +1,276 @@ +package etcd + +import ( + "context" + "slices" + "testing" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/stretchr/testify/require" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" + "google.golang.org/protobuf/proto" +) + +// Consume only the dispatch view. Advance always receives the original Ready. +func takeReadProbes(t *testing.T, e *Engine, reads, peers int) map[uint64]*raftpb.Message { + t.Helper() + status := e.rawNode.BasicStatus() + require.Equal(t, etcdraft.StateLeader, status.RaftState) + rd := e.rawNode.Ready() + require.Len(t, rd.Messages, reads*peers) + require.Empty(t, rd.ReadStates) + view := coalesceProtectedReadProbes(rd, status.ID, status.GetTerm()) + require.Len(t, view, peers) + last := make(map[uint64]*raftpb.Message) + for _, msg := range rd.Messages { + last[msg.GetTo()] = msg + } + require.Len(t, last, peers) + byPeer := make(map[uint64]*raftpb.Message) + for _, msg := range view { + require.Same(t, last[msg.GetTo()], msg) + delete(last, msg.GetTo()) + byPeer[msg.GetTo()] = msg + } + require.Empty(t, last) + e.rawNode.Advance(rd) + return byPeer +} + +// Quorum tests model delivery and echo exactly the selected probe's context. +func echoReadProbe(t *testing.T, e *Engine, msg *raftpb.Message) { + t.Helper() + require.NotNil(t, msg) + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: raftpb.MsgHeartbeatResp.Enum(), + From: msg.To, To: msg.From, Term: msg.Term, Context: msg.Context})) +} + +func TestReadProbeCoalesceCallerResults(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + start := func(waitApplied bool) (readRequest, *raftadmission.Operation, <-chan readResult) { + handle, op := newTurnRead(t, e, guard, raftadmission.Data) + // Exercise result validation even after retiring the operation. + ctx, cancel := context.WithCancel(context.WithoutCancel(handle.ctx)) + t.Cleanup(cancel) + result := make(chan readResult, 1) + go func() { + index, err := e.submitRead(ctx, waitApplied) + result <- readResult{index: index, err: err} + }() + select { + case req := <-e.readCh: + return req, op, result + case res := <-result: + t.Fatalf("read returned before issue: %v", res) + return readRequest{}, nil, nil + } + } + first, _, firstResult := start(true) + second, revoke, secondResult := start(false) + var scopes []*readTurnScope + guard.inside = func(ctx context.Context, native raftengine.NativeScope) raftengine.NativeScope { + scope := &readTurnScope{NativeScope: native, t: t, owner: ctx} + scopes = append(scopes, scope) + return scope + } + runReadTurnPair(e, first, second) + require.Len(t, scopes, 2) + for i, req := range []readRequest{first, second} { + require.True(t, scopes[i].owner == req.ctx && scopes[i].checked) + require.Contains(t, e.pendingReads, req.id) + } + guard.inside = nil + pair := takeReadProbes(t, e, 2, 2) + late, _ := newTurnRead(t, e, guard, raftadmission.Data) + e.handleRead(late) + next := takeReadProbes(t, e, 1, 2) + require.NotEqual(t, pair[2].Context, next[2].Context) + revoke.CancelAndJoin() + + // Start a follower at the same durable log and drive its real heartbeat + // handler. This fixture shares storage for reads only during the exchange. + follower := mustRawNode(t, e.storage, 2) + require.NoError(t, follower.Step(pair[2])) + reply := follower.Ready() + var responses int + for _, msg := range reply.Messages { + if msg.GetType() == raftpb.MsgHeartbeatResp { + require.NoError(t, e.rawNode.Step(msg)) + responses++ + } + } + require.Equal(t, 1, responses) + follower.Advance(reply) + index := e.rawNode.BasicStatus().GetCommit() + rd := e.rawNode.Ready() + require.Equal(t, []etcdraft.ReadState{turnReadState(first, index), turnReadState(second, index)}, rd.ReadStates) + e.applied = index - 1 // Hold the local FSM one entry behind the quorum result. + e.handleReadStates(rd.ReadStates) + e.rawNode.Advance(rd) + e.resolveReadyReads() + require.Contains(t, e.pendingReads, first.id) + require.Equal(t, index, e.pendingReads[first.id].target) + require.Empty(t, firstResult) + require.ErrorIs(t, (<-secondResult).err, raftengine.ErrLeadershipLost) + e.applied = index + e.resolveReadyReads() + require.Equal(t, readResult{index: index}, <-firstResult) + require.Empty(t, late.done) + echoReadProbe(t, e, next[2]) + require.NoError(t, e.drainReady()) + require.Len(t, late.done, 1) + require.Equal(t, readResult{index: index}, <-late.done) +} + +func TestReadProbeCoalesceTickRetry(t *testing.T) { + e, guard := newReadTurnEngine(t, true) + a, _ := newTurnRead(t, e, guard, raftadmission.Data) + b, _ := newTurnRead(t, e, guard, raftadmission.Data) + runReadTurnPair(e, a, b) + lost := takeReadProbes(t, e, 2, 2) + require.False(t, e.rawNode.HasReady()) + for range defaultHeartbeatTick { + e.rawNode.Tick() + } + retry := takeReadProbes(t, e, 1, 2) + require.Equal(t, lost[2].Context, retry[2].Context) + require.Empty(t, a.done) + require.Empty(t, b.done) + echoReadProbe(t, e, retry[2]) + require.NoError(t, e.drainReady()) + for _, req := range []readRequest{a, b} { + require.Len(t, req.done, 1) + require.Equal(t, readResult{index: e.applied}, <-req.done) + } +} + +func TestReadProbeCoalesceJointQuorum(t *testing.T) { + e, _ := newReadTurnEngine(t, true) + // Exercise RawNode quorum accounting in a fixed joint configuration. + cs := e.rawNode.ApplyConfChange(&raftpb.ConfChangeV2{Transition: raftpb.ConfChangeTransitionJointExplicit.Enum(), + Changes: []*raftpb.ConfChangeSingle{ + {Type: raftpb.ConfChangeRemoveNode.Enum(), NodeId: uint64Ptr(2)}, + {Type: raftpb.ConfChangeRemoveNode.Enum(), NodeId: uint64Ptr(3)}, + {Type: raftpb.ConfChangeAddNode.Enum(), NodeId: uint64Ptr(4)}, + {Type: raftpb.ConfChangeAddNode.Enum(), NodeId: uint64Ptr(5)}, + {Type: raftpb.ConfChangeAddLearnerNode.Enum(), NodeId: uint64Ptr(6)}, + }}) + require.ElementsMatch(t, []uint64{1, 2, 3}, cs.VotersOutgoing) + require.ElementsMatch(t, []uint64{1, 4, 5}, cs.Voters) + require.Equal(t, []uint64{6}, cs.Learners) + e.rawNode.Advance(e.rawNode.Ready()) + // Withhold each half in turn. A learner and a duplicate response cannot + // supply the missing majority; acknowledgments from round one cannot + // satisfy round two. + for _, voters := range [][2]uint64{{2, 4}, {4, 2}} { + first, second := []byte{byte(voters[0]), 1}, []byte{byte(voters[0]), 2} + e.rawNode.ReadIndex(first) + e.rawNode.ReadIndex(second) + probes := takeReadProbes(t, e, 2, 5) + for _, id := range []uint64{6, voters[0], voters[0]} { + echoReadProbe(t, e, probes[id]) + rd := e.rawNode.Ready() + require.Empty(t, rd.ReadStates, "ack from peer %d", id) + e.rawNode.Advance(rd) + } + echoReadProbe(t, e, probes[voters[1]]) + rd := e.rawNode.Ready() + require.Equal(t, []etcdraft.ReadState{{Index: e.applied, RequestCtx: first}, + {Index: e.applied, RequestCtx: second}}, rd.ReadStates) + e.rawNode.Advance(rd) + } +} + +func readProbeReady() etcdraft.Ready { + probe := func(to, commit uint64, opaque byte) *raftpb.Message { + return &raftpb.Message{Type: raftpb.MsgHeartbeat.Enum(), To: uint64Ptr(to), From: uint64Ptr(1), + Term: uint64Ptr(2), Commit: uint64Ptr(commit), Context: []byte{opaque, 0, 0, 0, 0, 0, 0, 0}} + } + return etcdraft.Ready{Messages: []*raftpb.Message{ + probe(2, 0, 1), probe(3, 1, 1), probe(4, 0, 2), probe(2, 0, 3), probe(3, 1, 3), + }} +} + +func TestReadProbeCoalesceDispatchView(t *testing.T) { + rd := readProbeReady() + ptrs := slices.Clone(rd.Messages) + values := readProbeReady() + view := coalesceProtectedReadProbes(rd, 1, 2) + require.Len(t, view, 3) + for i, original := range []int{2, 3, 4} { + require.Same(t, ptrs[original], view[i]) + } + view[0] = nil + for i, msg := range rd.Messages { + require.Same(t, ptrs[i], msg) + require.True(t, proto.Equal(values.Messages[i], msg)) + } + rd.Messages = rd.Messages[:3] + view = coalesceProtectedReadProbes(rd, 1, 2) + require.Len(t, view, 3) + require.Same(t, &rd.Messages[0], &view[0]) +} + +func TestReadProbeCoalesceRegressingOrdinal(t *testing.T) { + rd := readProbeReady() + rd.Messages[0].Context[0] = 9 + view := coalesceProtectedReadProbes(rd, 1, 2) + require.Len(t, view, len(rd.Messages)) + require.Same(t, &rd.Messages[0], &view[0], "an unexpected ordinal discontinuity preserves all probes") +} + +func TestReadProbeCoalesceDistinctCommit(t *testing.T) { + rd := readProbeReady() + rd.Messages[2].To = uint64Ptr(2) + rd.Messages[3].Commit = uint64Ptr(1) + // A changing commit is outside the transition-free optimization contract. + view := coalesceProtectedReadProbes(rd, 1, 2) + require.Len(t, view, len(rd.Messages)) + require.Same(t, &rd.Messages[0], &view[0]) +} + +func TestReadProbeCoalesceFallback(t *testing.T) { + for name, change := range map[string]func(*etcdraft.Ready){ + "sync without state": func(r *etcdraft.Ready) { r.MustSync = true }, + "soft state": func(r *etcdraft.Ready) { r.SoftState = &etcdraft.SoftState{} }, + "term change": func(r *etcdraft.Ready) { r.HardState = &raftpb.HardState{Term: uint64Ptr(3)} }, + "snapshot": func(r *etcdraft.Ready) { + r.Snapshot = &raftpb.Snapshot{Metadata: &raftpb.SnapshotMetadata{Index: uint64Ptr(1)}} + }, + "unstable": func(r *etcdraft.Ready) { r.Entries = []*raftpb.Entry{{}} }, + "committed config": func(r *etcdraft.Ready) { r.CommittedEntries = []*raftpb.Entry{{Type: raftpb.EntryConfChangeV2.Enum()}} }, + "read state": func(r *etcdraft.Ready) { r.ReadStates = []etcdraft.ReadState{{Index: 1}} }, + "nil": func(r *etcdraft.Ready) { r.Messages[4] = nil }, + "response": func(r *etcdraft.Ready) { r.Messages[4].Type = raftpb.MsgHeartbeatResp.Enum() }, + "missing type": func(r *etcdraft.Ready) { r.Messages[4].Type = nil }, + "missing to": func(r *etcdraft.Ready) { r.Messages[4].To = nil }, + "missing from": func(r *etcdraft.Ready) { r.Messages[4].From = nil }, + "missing term": func(r *etcdraft.Ready) { r.Messages[4].Term = nil }, + "missing commit": func(r *etcdraft.Ready) { r.Messages[4].Commit = nil }, + "wrong leader": func(r *etcdraft.Ready) { r.Messages[4].From = uint64Ptr(9) }, + "stale term": func(r *etcdraft.Ready) { r.Messages[4].Term = uint64Ptr(1) }, + "no destination": func(r *etcdraft.Ready) { r.Messages[4].To = uint64Ptr(0) }, + "self": func(r *etcdraft.Ready) { r.Messages[4].To = uint64Ptr(1) }, + "local apply": func(r *etcdraft.Ready) { r.Messages[4].To = uint64Ptr(etcdraft.LocalApplyThread) }, + "local append": func(r *etcdraft.Ready) { r.Messages[4].To = uint64Ptr(etcdraft.LocalAppendThread) }, + "ordinary heartbeat": func(r *etcdraft.Ready) { r.Messages[4].Context = nil }, + "short": func(r *etcdraft.Ready) { r.Messages[4].Context = []byte{1} }, + "long": func(r *etcdraft.Ready) { r.Messages[4].Context = append(r.Messages[4].Context, 1) }, + "zero context": func(r *etcdraft.Ready) { r.Messages[4].Context = make([]byte, 8) }, + "explicit false": func(r *etcdraft.Ready) { r.Messages[4].Reject = proto.Bool(false) }, + "nested response": func(r *etcdraft.Ready) { r.Messages[4].Responses = []*raftpb.Message{{}} }, + "unknown": func(r *etcdraft.Ready) { r.Messages[4].ProtoReflect().SetUnknown([]byte{0xa0, 0x06, 0x01}) }, + } { + t.Run(name, func(t *testing.T) { + rd := readProbeReady() + change(&rd) + before := slices.Clone(rd.Messages) + view := coalesceProtectedReadProbes(rd, 1, 2) + require.Len(t, view, len(before)) + require.Same(t, &rd.Messages[0], &view[0]) + require.True(t, slices.Equal(before, view)) + }) + } +} diff --git a/internal/raftengine/etcd/read_probe_peer_session_test.go b/internal/raftengine/etcd/read_probe_peer_session_test.go new file mode 100644 index 000000000..f640eb29f --- /dev/null +++ b/internal/raftengine/etcd/read_probe_peer_session_test.go @@ -0,0 +1,282 @@ +package etcd + +import ( + "context" + "errors" + "slices" + "sync/atomic" + "testing" + + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// Supply an already connected unary client at the transport cache boundary. +// A missing client has no provisioned node to dial in this fixture. +type probeUnaryClient struct { + pb.EtcdRaftClient + send func(context.Context, *pb.EtcdRaftMessage, ...grpc.CallOption) (*pb.EtcdRaftAck, error) +} + +func (c probeUnaryClient) Send(ctx context.Context, message *pb.EtcdRaftMessage, opts ...grpc.CallOption) (*pb.EtcdRaftAck, error) { + return c.send(ctx, message, opts...) +} + +func bindProbeClient(e *Engine, id uint64, client probeUnaryClient) { + peer := e.peers[id] + e.transport.peerSession = &peerSessionTransport{} + e.transport.peers[id] = peer + e.transport.clients[peer.Address] = client +} + +func TestReadProbeReadyDispatchGuards(t *testing.T) { + for _, mode := range []string{"protected", "no native admission", "no reconciliation", "pipeline", "follower", "pending configuration", "snapshot transition", "MustSync"} { + t.Run(mode, func(t *testing.T) { + e, _ := newReadTurnEngine(t, mode != "follower") + e.admissionChanged = func() {} + q := e.peerDispatchers[2].heartbeat + retireQueuedDispatchRequests(q) + rd := readProbeReady() + rd.Messages = []*raftpb.Message{rd.Messages[0], rd.Messages[3]} + rd.Messages[1].Context[0] = 2 + for _, m := range rd.Messages { + m.Term = proto.Uint64(e.rawNode.BasicStatus().GetTerm()) + } + setReadProbeDispatchMode(e, &rd, mode) + want := rd.Messages + if mode == "protected" { + want = want[1:] + } + require.NoError(t, e.sendReadyMessages(rd)) + require.Len(t, q, len(want)) + for _, expected := range want { + sent := <-q + require.True(t, proto.Equal(expected, &sent.msg)) + require.NoError(t, sent.Close()) + } + }) + } +} + +func setReadProbeDispatchMode(e *Engine, rd *etcdraft.Ready, mode string) { + switch mode { + case "no native admission": + e.nativeAdmission = nil + case "no reconciliation": + e.admissionChanged = nil + case "pipeline": + e.storagePipeline = &engineStoragePipeline{outboundControl: newStorageWorkBudget(pipelineControlBytes, pipelineControlItems)} + case "pending configuration": + e.pendingConfChangeIndex.Store(e.applied + 1) + case "snapshot transition": + e.snapshotTransition.Store(true) + case "MustSync": + rd.MustSync = true + } +} + +func TestReadProbeFailedReconciliationPreventsDispatch(t *testing.T) { + e, a := newReadTurnEngine(t, true) + e.admissionChanged = func() {} + e.admissionDirty = true + for _, queues := range e.peerDispatchers { + retireQueuedDispatchRequests(queues.heartbeat) + } + first, _ := newTurnRead(t, e, a, raftadmission.Data) + last, _ := newTurnRead(t, e, a, raftadmission.Data) + e.readCh <- last + e.handleReadQueue(first) + require.True(t, e.rawNode.HasReady()) + reconcileErr := errors.New("test reconciliation failed") + e.recoveredAdmission = func(RecoveredState) error { return reconcileErr } + require.ErrorIs(t, e.drainReady(), reconcileErr) + for _, queues := range e.peerDispatchers { + require.Empty(t, queues.heartbeat) + } + require.Empty(t, first.done) + require.Empty(t, last.done) +} + +// Drive the production send hook on the unmodified RawNode Ready. Derive the +// expected bytes from each destination's final message before dispatch. +func queuedReadProbePair(t *testing.T, e *Engine, a *readTurnAdmission) (readRequest, map[uint64]dispatchRequest) { + t.Helper() + e.admissionChanged = func() {} + for _, queues := range e.peerDispatchers { + retireQueuedDispatchRequests(queues.heartbeat) + } + live, _ := newTurnRead(t, e, a, raftadmission.Data) + lastHandle, cancelLast := newTurnRead(t, e, a, raftadmission.Data) + lastResult := make(chan error, 1) + go func() { lastResult <- e.VerifyLeader(lastHandle.ctx) }() + var last readRequest + select { + case last = <-e.readCh: + case err := <-lastResult: + t.Fatalf("last caller returned before issue: %v", err) + } + e.readCh <- last + e.handleReadQueue(live) + rd := e.rawNode.Ready() + require.Len(t, rd.Messages, 4) + original := slices.Clone(rd.Messages) + values := make([]*raftpb.Message, len(original)) + expected := make(map[uint64]*raftpb.Message) + for i, m := range original { + values[i] = proto.CloneOf(m) + expected[m.GetTo()] = values[i] + } + require.Len(t, expected, 2) + require.NoError(t, e.sendReadyMessages(rd)) + for i, m := range rd.Messages { + require.Same(t, original[i], m) + require.True(t, proto.Equal(values[i], m)) + } + got := make(map[uint64]dispatchRequest) + for id, m := range expected { + q := e.peerDispatchers[id].heartbeat + require.Len(t, q, 1) + out := <-q + t.Cleanup(func() { require.NoError(t, out.Close()) }) + require.True(t, proto.Equal(m, &out.msg)) + got[id] = out + } + e.rawNode.Advance(rd) + require.False(t, e.rawNode.HasReady()) + require.Len(t, e.pendingReads, 2) + for _, req := range []readRequest{live, last} { + got, ok := e.pendingRead(req.id) + require.True(t, ok) + require.Equal(t, req, got) + require.Empty(t, req.done) + } + cancelLast.CancelAndJoin() + require.ErrorIs(t, <-lastResult, context.Canceled) + _, pending := e.pendingRead(last.id) + require.False(t, pending) + require.NoError(t, live.ctx.Err()) + return live, got +} + +// Elect node 2 with voter 3; the fixture's authenticated transport connects +// node 2 to the remaining voter, node 1. +func probeSessionLeader(t *testing.T) (*Engine, *readTurnAdmission) { + t.Helper() + e := identityElectionEngine(t, 2) + require.NoError(t, e.rawNode.Campaign()) + for _, kind := range []raftpb.MessageType{raftpb.MsgPreVoteResp, raftpb.MsgVoteResp} { + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: kind.Enum(), From: proto.Uint64(3), Term: proto.Uint64(2)})) + require.NoError(t, e.drainReady()) + } + index, err := e.storage.LastIndex() + require.NoError(t, err) + require.NoError(t, e.rawNode.Step(&raftpb.Message{Type: raftpb.MsgAppResp.Enum(), From: proto.Uint64(3), Term: proto.Uint64(2), Index: &index})) + require.NoError(t, e.drainReady()) + // Use an independent local arbiter for this leader's two callers. + arbiter, err := raftadmission.New(raftadmission.Config{Cluster: raftbootstrap.UUID{1}, DefaultGroup: 1, Groups: []uint64{1}, + ValidatePayload: func(raftadmission.Kind, uint64, []byte) error { return nil }}) + require.NoError(t, err) + t.Cleanup(arbiter.Close) + a := &readTurnAdmission{Arbiter: arbiter} + e.groupID, e.nativeConfigurationIndex, e.nativeAdmission = 1, e.currentConfigIndex(), a + e.readCh = make(chan readRequest, 2) + require.NoError(t, e.withNative(t.Context(), nil, func() error { return nil })) + publishRecoveryReadProjection(t, &transportTestNode{engine: e}, &recoveryReadTestAdmission{Arbiter: arbiter}, 1, true) + return e, a +} + +// This exchange runs Raft locally. The generation check is the real arbiter; +// the receipt callback here models a live receipt, without a transport session. +func TestReadProbeCanceledLastAndStaleGeneration(t *testing.T) { + e, a := probeSessionLeader(t) + publishRecoveryReadProjection(t, &transportTestNode{engine: e}, &recoveryReadTestAdmission{Arbiter: a.Arbiter}, 2, true) + live, queued := queuedReadProbePair(t, e, a) + probe := queued[1] + follower := mustRawNode(t, e.storage, 1) + bindProbeClient(e, 1, probeUnaryClient{send: func(ctx context.Context, wire *pb.EtcdRaftMessage, _ ...grpc.CallOption) (*pb.EtcdRaftAck, error) { + require.NoError(t, ctx.Err()) + var received raftpb.Message + require.NoError(t, proto.Unmarshal(wire.Message, &received)) + require.True(t, proto.Equal(&probe.msg, &received)) + return &pb.EtcdRaftAck{}, follower.Step(&received) + }}) + e.handleDispatchRequest(t.Context(), probe) + rd := follower.Ready() + var reply *raftpb.Message + for _, m := range rd.Messages { + if m.GetType() == raftpb.MsgHeartbeatResp { + require.Nil(t, reply) + reply = proto.CloneOf(m) + } + } + require.NotNil(t, reply) + require.Equal(t, probe.msg.GetContext(), reply.GetContext()) + follower.Advance(rd) + + for _, generation := range []uint64{1, 2} { + entered := false + ok := e.handleStepWithAdmission(*reply, &raftengine.NativeRequest{ + Operation: raftengine.NativePeerStep, SessionGeneration: generation, + }, func(step func() error) error { entered = true; return step() }) + require.Equal(t, generation == 2, ok) + require.Equal(t, ok, entered) + if !ok { + require.False(t, e.rawNode.HasReady()) + require.Empty(t, live.done) + } + } + require.NoError(t, e.drainReady()) + require.Len(t, live.done, 1) + require.Equal(t, readResult{index: e.applied}, <-live.done) + require.NoError(t, e.validateNativeResult(live.ctx)) +} + +// The fixture session is bound to 2 -> 1. Its client passes OnFinish through +// to gRPC, so a locally denied payload can be distinguished from a server denial. +func TestReadProbePeerSession(t *testing.T) { + receiver, owner, client := protectedQueueFixture(t) + e, a := probeSessionLeader(t) + live, probes := queuedReadProbePair(t, e, a) + var finished atomic.Int32 + var sendErr error + observed := probeUnaryClient{send: func(ctx context.Context, wire *pb.EtcdRaftMessage, opts ...grpc.CallOption) (*pb.EtcdRaftAck, error) { + opts = append(opts, grpc.OnFinish(func(error) { finished.Add(1) })) + ack, err := client.Send(ctx, wire, opts...) + sendErr = err + return ack, err + }} + bindProbeClient(e, 3, observed) + bindProbeClient(e, 1, observed) + e.handleDispatchRequest(t.Context(), probes[3]) + require.Equal(t, codes.PermissionDenied, status.Code(sendErr)) + require.Zero(t, finished.Load()) + require.Empty(t, receiver.protectedPriorityStepCh) + e.handleDispatchRequest(t.Context(), probes[1]) + require.NoError(t, sendErr) + require.Equal(t, int32(1), finished.Load()) + require.Len(t, receiver.protectedPriorityStepCh, 1) + in := <-receiver.protectedPriorityStepCh + expected := probes[1] + require.True(t, proto.Equal(&expected.msg, &in.message)) + require.NoError(t, in.receipt.Check(t.Context())) + group, found := owner.GroupProjection(1) + require.True(t, found) + require.Equal(t, group.Generation, in.receipt.LocalGeneration()) + group.Generation++ + retire, err := owner.UpdateGroupProjection(group) + require.NoError(t, err) + defer retire() // Exercise generation invalidation before physical connection cleanup. + require.Error(t, in.receipt.Check(t.Context())) + require.False(t, receiver.handleProtectedStep(in)) + require.Zero(t, receiver.lastLeaderContactFrom) + require.Empty(t, live.done) +} diff --git a/internal/raftengine/etcd/removal_notification.go b/internal/raftengine/etcd/removal_notification.go index 38fe5a8d5..34457b973 100644 --- a/internal/raftengine/etcd/removal_notification.go +++ b/internal/raftengine/etcd/removal_notification.go @@ -32,7 +32,7 @@ func (e *Engine) sendReadyMessages(rd etcdraft.Ready) error { return errors.WithStack(raftengine.ErrNativeAdmissionDenied) } if len(removed) == 0 || e.transport == nil { - return e.sendMessages(messageValues(rd.Messages)) + return e.sendMessages(messageValues(e.readProbeDispatchMessages(rd))) } notifications := make(map[uint64]removalNotification) for _, msg := range messageValues(rd.Messages) { diff --git a/internal/raftengine/etcd/snapshot_configuration.go b/internal/raftengine/etcd/snapshot_configuration.go index 4012471fa..3bc151fe0 100644 --- a/internal/raftengine/etcd/snapshot_configuration.go +++ b/internal/raftengine/etcd/snapshot_configuration.go @@ -123,7 +123,7 @@ func (e *Engine) captureLocalSnapshotRequest(index uint64) (snapshotRequest, err if err != nil { return snapshotRequest{}, err } - snapshot, err := e.fsm.Snapshot() + snapshot, err := e.captureLocalSnapshot() if err != nil { return snapshotRequest{}, errors.WithStack(err) } diff --git a/internal/raftengine/etcd/sync_inflight_cluster_test.go b/internal/raftengine/etcd/sync_inflight_cluster_test.go new file mode 100644 index 000000000..9bd95f28d --- /dev/null +++ b/internal/raftengine/etcd/sync_inflight_cluster_test.go @@ -0,0 +1,361 @@ +package etcd + +import ( + "context" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "errors" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/peersession" + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/bootjp/elastickv/store/storetest" + "github.com/stretchr/testify/require" + "go.etcd.io/raft/v3/raftpb" + "google.golang.org/grpc" + "google.golang.org/protobuf/proto" +) + +type inflightMember struct { + *transportTestNode + store store.MVCCStore + routes *distribution.Engine + arbiter *raftadmission.Arbiter +} + +type inflightCluster struct { + members []*inflightMember +} + +func TestSyncInflightCatalogRecovery(t *testing.T) { + for _, damage := range []string{"missing-version", "missing-routes", "equal-version-invalid-order"} { + t.Run(damage, func(t *testing.T) { + var damaged atomic.Pointer[inflightMember] + type recoveryResult struct { + term uint64 + stage peersession.Stage + err error + } + recovered := make(chan recoveryResult, 1) + cluster := newInflightCluster(t, 0, func(e *Engine) { + recoverMember := e.recoveredAdmission + e.recoveredAdmission = func(state RecoveredState) error { + err := recoverMember(state) + if m := damaged.Load(); m != nil && m.peer.NodeID == e.nodeID { + select { + case recovered <- recoveryResult{state.HardState().GetTerm(), m.arbiter.Stage(1), err}: + default: + } + } + return err + } + }) + a, b, c := cluster.voters(t) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + require.NoError(t, cluster.writer(t, a)(ctx, 0, []byte("warm"))) + requireInflightReplicated(t, a, b, c, a.engine.AppliedIndex()) + require.Equal(t, peersession.DataReady, b.arbiter.Stage(1)) + require.EqualValues(t, 1, b.routes.Version()) + before, err := b.arbiter.Ticket(1) + require.NoError(t, err) + // Model damage to just B's committed MVCC image. In the malformed + // case the version is unchanged and both records decode separately. + ts := b.store.LastCommitTS() + switch damage { + case "missing-version": + require.NoError(t, b.store.DeleteAt(ctx, distribution.CatalogVersionKey(), ts+1)) + case "missing-routes": + require.NoError(t, b.store.DeleteAt(ctx, distribution.CatalogRouteKey(1), ts+1)) + default: + raw, err := distribution.EncodeRouteDescriptor(distribution.RouteDescriptor{RouteID: 2, GroupID: 1}) + require.NoError(t, err) + require.NoError(t, b.store.PutAt(ctx, distribution.CatalogRouteKey(2), raw, ts+1, 0)) + } + term := b.engine.Status().Term + damaged.Store(b) + transferInflightLeadership(t, ctx, a, c) + result := testutil.Recv(t, recovered, 5*time.Second, "B did not recover after transfer") + require.Greater(t, result.term, term) + after, ticketErr := b.arbiter.Ticket(1) + require.NoError(t, ticketErr) + require.NotEqual(t, before, after) + require.NotEqual(t, peersession.DataReady, result.stage, "damaged local catalog reopened DataReady") + if damage == "equal-version-invalid-order" { + require.ErrorIs(t, result.err, distribution.ErrEngineSnapshotRouteOrder) + } else { + require.ErrorContains(t, result.err, "committed catalog is uninitialized") + } + require.ErrorIs(t, b.engine.Close(), result.err) + b.engine = nil // Already joined and checked the expected terminal error. + }) + } +} + +func transferInflightLeadership(t *testing.T, ctx context.Context, from, to *inflightMember) { + t.Helper() + owned, op, err := from.arbiter.Begin(ctx, raftadmission.Control) + require.NoError(t, err) + err = from.engine.TransferLeadershipToServer(owned, to.peer.ID, to.peer.Address) + op.CancelAndJoin() + if err != nil && !errors.Is(err, context.Canceled) { + require.ErrorIs(t, err, raftengine.ErrLeadershipLost) + } +} + +// Bootstrap a known three-voter FSM snapshot. On *each* recovery the native +// owner checks the durable prefix, then the callback reads its applied policy +// and publishes a new generation. The schedule never publishes authority. +func inflightRecovery(t *testing.T, member *inflightMember, owner *peersession.Owner, policy raftbootstrap.PolicyRecord, peers []Peer) (*WALIdentity, func(RecoveredState) error) { + t.Helper() + st := member.store + raw, err := raftbootstrap.MarshalPolicyRecord(policy) + require.NoError(t, err) + key, err := kv.BootstrapPolicyMetadataKey(policy.Identity) + require.NoError(t, err) + applier, ok := st.(store.RaftEntryApplier) + require.True(t, ok) + metadata, ok := st.(store.RaftControlMetadataStore) + require.True(t, ok) + // Construct each restored index-1 image in one Pebble entry batch. + plan, err := distribution.NewCatalogStore(st).BuildBootstrapPlanAt(t.Context(), 1, []distribution.Route{{GroupID: 1}}) + require.NoError(t, err) + require.NoError(t, applier.ApplyRaftEntry(t.Context(), 1, func(ctx context.Context) error { + if err := st.ApplyMutationsRaftAt(ctx, plan.Mutations, plan.ReadKeys, 1, 2, 1); err != nil { + return err + } + return metadata.StageRaftControlMetadata(ctx, key, raw) + })) + files := raftbootstrap.NewStore(t.TempDir()) + floor := raftbootstrap.Floor{ActivationIndex: 1, Generation: 1} + seed := policy.Configuration + seed.Index = 0 + intent := raftbootstrap.Intent{Identity: policy.Identity, BaselineKind: raftbootstrap.Seed, Baseline: seed, Minimum: policy.Minimum, Floor: floor} + require.NoError(t, files.Publish(intent, raftbootstrap.Evidence{Identity: &policy.Identity, BaselineDigest: &policy.BaselineDigest, RaftState: raftbootstrap.Intact, + Policy: &raftbootstrap.Policy{Identity: policy.Identity, BaselineDigest: policy.BaselineDigest, Minimum: policy.Minimum, Floor: floor}})) + expected := WALIdentity{Identity: policy.Identity, NodeID: member.peer.NodeID, BaselineDigest: policy.BaselineDigest} + a := member.arbiter + return &expected, func(state RecoveredState) error { + if actual, ok := state.Identity(); !ok || actual != expected || state.ConfigurationIndex() != 1 { + return ErrWALIdentity + } + if err := validateConfState(*state.ConfState(), peers); err != nil { + return err + } + ticket, err := a.Ticket(1) + if err != nil { + return err + } + applied, err := kv.LoadAppliedBootstrapPolicy(context.Background(), st, expected.Identity, state.AppliedIndex()) + if err != nil { + return err + } + group, err := owner.RecoverPolicyProjection(files, 1, applied, raftbootstrap.Intact) + if err != nil { + return err + } + return member.publishInflightRecovery(owner, ticket, applied, group) + } +} + +func (m *inflightMember) publishInflightRecovery(owner *peersession.Owner, ticket raftadmission.RecoveryTicket, policy raftbootstrap.PolicyRecord, group peersession.Group) error { + a := m.arbiter + publish := func(stage peersession.Stage, generation uint64) (func(), error) { + group.Stage, group.Generation = stage, generation + return owner.UpdateGroupProjection(group) + } + if err := a.PublishRecoveryWith(ticket, policy, raftadmission.RegistrationNotConfigured, publish); err != nil { + return err + } + ticket, err := a.Ticket(1) + if err != nil { + return err + } + // Mirror loadProtectedRuntimeCatalog. ApplySnapshot skips equal versions, + // so independently validate the committed local image in every generation. + snapshot, err := distribution.NewCatalogStore(m.store).Snapshot(context.Background()) + if err != nil { + return err + } + if snapshot.Version == 0 || len(snapshot.Routes) == 0 { + return errors.New("committed catalog is uninitialized") + } + if _, err := distribution.RoutesFromCatalogSnapshot(snapshot); err != nil { + return err + } + if err := m.routes.ApplySnapshot(snapshot); err != nil { + return err + } + if err := a.MarkCatalogLoaded(ticket); err != nil { + return err + } + return a.PublishStage(1, publish) +} + +func newInflightCluster(t *testing.T, size uint64, install func(*Engine)) *inflightCluster { + t.Helper() + nodes, peers := newTransportTestNodes(t, 3) + c := &inflightCluster{} + roots := x509.NewCertPool() + certs := make([]tls.Certificate, len(nodes)) + ids := map[uint64]peersession.Node{} + var provisions []peersession.Provision + policy := raftbootstrap.PolicyRecord{Version: raftbootstrap.PolicyVersion, Identity: raftbootstrap.Identity{Cluster: raftbootstrap.UUID{1}, Group: 1}, + Configuration: raftbootstrap.Configuration{Index: 1}, Minimum: raftbootstrap.Versions{Entry: 1, Session: 1, Snapshot: 1}, ActivationIndex: 1, Generation: 1, LastConfigurationIndex: 1} + for i, n := range nodes { + cert, leaf := queueCertificate(t, int64(i+1)) + certs[i] = cert + roots.AddCert(leaf) + id := n.peer.NodeID + local := peersession.Node{Cluster: policy.Identity.Cluster, Member: id, Address: n.peer.Address, Key: sha256.Sum256(leaf.RawSubjectPublicKeyInfo)} + ids[id] = local + provisions = append(provisions, peersession.Provision{Node: local, Groups: []uint64{1}}) + policy.Configuration.State.Voters = append(policy.Configuration.State.Voters, id) + policy.Configuration.Members = append(policy.Configuration.Members, raftbootstrap.Member{ID: id, Address: local.Address, PublicKeyDigest: local.Key}) + } + var err error + seed := policy.Configuration + seed.Index = 0 + policy.BaselineDigest, err = raftbootstrap.ConfigurationDigest(seed) + require.NoError(t, err) + for i, n := range nodes { + m := &inflightMember{transportTestNode: n, store: storetest.NewPebble(t), routes: distribution.NewEngine()} + c.members = append(c.members, m) + machine := kv.NewKvFSMWithHLC(m.store, kv.NewHLC(), kv.WithRouteHistory(kv.WrapDistributionEngine(m.routes), 1)) + classifier, ok := machine.(raftengine.AppendBatchClassifier) + require.True(t, ok) + m.arbiter, err = raftadmission.New(raftadmission.Config{Cluster: policy.Identity.Cluster, DefaultGroup: 1, Groups: []uint64{1}, + ValidatePayload: func(kind raftadmission.Kind, group uint64, payload []byte) error { + if kind != raftadmission.Data || group != 1 { + return raftadmission.ErrClosed + } + return validateInflightFrame(classifier, payload) + }}) + require.NoError(t, err) + t.Cleanup(m.arbiter.Close) + owner, err := peersession.NewOwner(peersession.Config{Local: ids[n.peer.NodeID], Versions: policy.Minimum, Provisioned: provisions, + MethodFactory: func(o *peersession.Owner) ([]peersession.Method, error) { return PeerSessionMethodsForOwner(1, o), nil }}) + require.NoError(t, err) + t.Cleanup(owner.Close) + options, err := owner.ServerOptions(&tls.Config{Certificates: []tls.Certificate{certs[i]}, ClientCAs: roots, ClientAuth: tls.VerifyClientCertIfGiven, MinVersion: tls.VersionTLS13}) + require.NoError(t, err) + n.transport = NewGRPCTransport(peers) + // A unary Send returns after protected enqueue. A stream Send can + // return after writing to the transport, before server admission. + n.transport.SetSendStreamEnabled(false) + require.NoError(t, n.transport.ConfigurePeerSessions(owner, 1, &tls.Config{Certificates: []tls.Certificate{certs[i]}, RootCAs: roots, ServerName: "peer.test", MinVersion: tls.VersionTLS13}, ids)) + n.server = grpc.NewServer(options...) + owner.Register(n.server) + n.transport.Register(n.server) + go func() { _ = n.server.Serve(n.lis) }() + t.Cleanup(func() { cleanupTransportTestNodes(t, []*transportTestNode{n}) }) + identity, recovery := inflightRecovery(t, m, owner, policy, peers) + cfg := OpenConfig{NodeID: n.peer.NodeID, LocalID: n.peer.ID, LocalAddress: n.peer.Address, DataDir: n.dir, Bootstrap: true, Peers: peers, + StateMachine: machine, MaxSizePerMsg: size, Transport: n.transport, GroupID: 1, NativeIdentity: identity, NativeAdmission: m.arbiter, + RecoveredAdmission: recovery, AdmissionChanged: func() { owner.SuspendGroup(1) }} + n.engine = openInflightMember(t, cfg, install) + } + return c +} + +func validateInflightFrame(classifier raftengine.AppendBatchClassifier, payload []byte) error { + if classifier.IsAppendBatchPayload(payload) { + return nil + } + // Only the large-entry configuration test needs the single-request + // fallback. Its legal frame is larger than the classifier's byte limit. + if len(payload) <= 8<<20 || payload[0] != 0 { + return raftadmission.ErrClosed + } + var request pb.Request + if err := proto.Unmarshal(payload[1:], &request); err != nil { + return err + } + if !request.IsTxn || request.Ts == 0 || len(request.Mutations) != 2 || len(request.ReadKeys) != 1 { + return raftadmission.ErrClosed + } + return nil +} + +// Like the native snapshot fixture, install the per-engine gates before +// initTransport starts any worker and before the owner goroutine starts. +func openInflightMember(t *testing.T, cfg OpenConfig, install func(*Engine)) *Engine { + t.Helper() + p, err := prepareOpenState(cfg) + require.NoError(t, err) + raw, applied, rawApplied, err := recoveredRawNodeForOpen(p) + require.NoError(t, err) + peerMap := make(map[uint64]Peer) + for _, peer := range p.peers { + peerMap[peer.NodeID] = peer + } + capacity := inboundQueueCapacity(len(peerMap), p.cfg.MaxInflightMsg) + ctx, cancel := context.WithCancel(context.Background()) + e := &Engine{groupID: cfg.GroupID, nodeID: cfg.NodeID, localID: cfg.LocalID, localAddress: cfg.LocalAddress, dataDir: cfg.DataDir, + fsmSnapDir: filepath.Join(cfg.DataDir, fsmSnapDirName), storage: p.disk.Storage, rawNode: raw, persist: p.disk.Persist, fsm: cfg.StateMachine, + recoveredIdentity: p.disk.VerifiedIdentity, recoveredAdmission: cfg.RecoveredAdmission, admissionChanged: cfg.AdmissionChanged, nativeAdmission: cfg.NativeAdmission, + peers: peerMap, transport: cfg.Transport, tickInterval: p.cfg.TickInterval, electionTick: p.cfg.ElectionTick, raftCutoverIndex: orInertCutover(nil), + voterCount: len(peerMap), config: configurationFromConfState(peerMap, confStateValue(p.disk.LocalSnap.GetMetadata().GetConfState())), applied: applied, + proposeCh: make(chan proposalRequest), readCh: make(chan readRequest), adminCh: make(chan adminRequest), + stepCh: make(chan raftpb.Message, capacity), protectedStepCh: make(chan protectedStep, capacity-1), protectedPriorityStepCh: make(chan protectedStep, priorityStepQueueCapacity), + priorityStepCh: make(chan raftpb.Message, priorityStepQueueCapacity), dispatchReportCh: make(chan dispatchReport, capacity), + closeCh: make(chan struct{}), doneCh: make(chan struct{}), startedCh: make(chan struct{}), leaderReady: make(chan struct{}), + pendingProposals: map[uint64]proposalRequest{}, pendingConfigs: map[uint64]adminRequest{}, pendingReads: map[uint64]readRequest{}, + dispatchCtx: ctx, dispatchCancel: cancel, snapshotEvery: defaultSnapshotEvery} + e.appliedIndex.Store(applied) + e.configIndex.Store(maxAppliedIndex(p.disk.LocalSnap)) + require.NoError(t, e.recoverOpenConfiguration(p, rawApplied)) + e.nativeConfigurationIndex = e.currentConfigIndex() + install(e) + e.initTransport(p.cfg) + e.initSnapshotWorker() + e.refreshStatus() + go e.run() + require.NoError(t, waitForOpenSignal(t.Context(), e, e.startedCh)) + return e +} + +func (c *inflightCluster) voters(t *testing.T) (a, b, d *inflightMember) { + t.Helper() + require.Eventually(t, func() bool { + for i, m := range c.members { + if m.engine.State() == raftengine.StateLeader && m.arbiter.Stage(1) == peersession.DataReady { + a, b, d = m, c.members[(i+1)%3], c.members[(i+2)%3] + return true + } + } + return false + }, 5*time.Second, time.Millisecond) + return +} + +func (c *inflightCluster) writer(t *testing.T, a *inflightMember) func(context.Context, int, []byte) error { + t.Helper() + proxy := kv.NewLeaderProxyWithEngine(a.engine) + t.Cleanup(func() { require.NoError(t, proxy.Close()) }) + groups := map[uint64]*kv.ShardGroup{1: {Engine: a.engine, Txn: proxy, Store: a.store}} + coord := kv.NewShardedCoordinator(a.routes, groups, 1, kv.NewHLC(), kv.NewShardStore(a.routes, groups)) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + return func(parent context.Context, i int, value []byte) error { + ctx, op, err := a.arbiter.Begin(parent, raftadmission.Data) + if err != nil { + return err + } + defer op.CancelAndJoin() + ts := uint64(10 + i*2) + _, err = coord.Dispatch(ctx, &kv.OperationGroup[kv.OP]{IsTxn: true, StartTS: ts, CommitTS: ts + 1, ReadKeys: [][]byte{[]byte("key")}, + ObservedRouteVersion: kv.EncodeObservedRouteVersion(1), Elems: []*kv.Elem[kv.OP]{{Op: kv.Put, Key: []byte("key"), Value: value}}}) + return err + } +} diff --git a/internal/raftengine/etcd/sync_inflight_window_test.go b/internal/raftengine/etcd/sync_inflight_window_test.go new file mode 100644 index 000000000..7e3625718 --- /dev/null +++ b/internal/raftengine/etcd/sync_inflight_window_test.go @@ -0,0 +1,629 @@ +package etcd + +import ( + "bytes" + "context" + "math" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/peersession" + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + etcdstorage "go.etcd.io/etcd/server/v3/storage" + etcdraft "go.etcd.io/raft/v3" + "go.etcd.io/raft/v3/raftpb" + "go.etcd.io/raft/v3/tracker" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" +) + +// Keep the steady Fresh frames small enough for the protected append +// classifier, with a committed suffix larger than the window plus one MsgApp. +const ( + inflightValueSize = 96 << 10 + inflightWrites = 128 + inflightLargeValueThreshold = 8 << 20 + inflightLargeWriteTimeout = 30 * time.Second +) + +type inflightGate struct { + entered chan struct{} + release chan struct{} + start, finish sync.Once +} + +func newInflightGate(t *testing.T) *inflightGate { + g := &inflightGate{entered: make(chan struct{}), release: make(chan struct{})} + t.Cleanup(g.open) + return g +} +func (g *inflightGate) hold() { + g.start.Do(func() { close(g.entered) }) + <-g.release +} +func (g *inflightGate) open() { g.finish.Do(func() { close(g.release) }) } +func (g *inflightGate) wait(t *testing.T) { + t.Helper() + testutil.Closed(t, g.entered, 5*time.Second, "schedule gate") +} + +type inflightAppend struct { + first, last uint64 + bytes int +} +type inflightAckProgress struct { + match, commit uint64 +} + +func inflightProgress(e *Engine, peer uint64) inflightAckProgress { + status := e.rawNode.Status() + return inflightAckProgress{status.Progress[peer].Match, status.GetCommit()} +} + +type inflightSchedule struct { + a, b, c, first uint64 + saveHeld bool + save, response, healthy, selected, suffix *inflightGate + healthyEnqueued chan error + revokeSelected *inflightGate + target atomic.Uint64 + attempts atomic.Uint64 + saved atomic.Uint64 + early atomic.Bool + // Only the leader owner writes the following fields. The pending proposal + // cannot return until the healthy ACK passes the closing observation. + measuring bool + emitted, cloned []inflightAppend + selectedHealthy bool + beforeHealthy inflightAckProgress + afterHealthy chan inflightAckProgress + initialState tracker.StateType + refillNext uint64 + // A separate record covers the worker FIFO, including the injected failure. + mu sync.Mutex + queued, dispatched []inflightAppend +} + +type inflightDisk struct { + etcdstorage.Storage + id uint64 + current *atomic.Pointer[inflightSchedule] +} + +func (d *inflightDisk) Save(hs *raftpb.HardState, entries []*raftpb.Entry) error { + s := d.current.Load() + track := s != nil && d.id == s.b && len(entries) > 0 && entries[len(entries)-1].GetIndex() >= s.first + if track && s.saveHeld { + s.save.hold() + } + err := d.Storage.Save(hs, entries) + if track && err == nil { + s.saved.Store(entries[len(entries)-1].GetIndex()) + } + return err +} + +func installInflightSchedule(current *atomic.Pointer[inflightSchedule], e *Engine) { + e.persist = &inflightDisk{e.persist, e.nodeID, current} + e.syncObserver = &syncRaftObserver{ + beforeStep: func(from uint64, kind raftpb.MessageType, index uint64, reject bool) func() { + s := current.Load() + if s == nil || e.nodeID != s.a || kind != raftpb.MsgAppResp || reject { + return nil + } + return s.selectResponse(e, from, index) + }, + appendBytes: func(to, first, last uint64, size int, preclone bool) { + s := current.Load() + if s == nil || e.nodeID != s.a || to != s.b { + return + } + s.observeAppend(e, inflightAppend{first, last, size}, preclone) + }, + } + e.dispatchFn = func(ctx context.Context, req dispatchRequest) error { + m := &req.msg + s := current.Load() + if s == nil { + return e.transport.Dispatch(ctx, *m) + } + return s.dispatch(ctx, e, m) + } +} + +func (s *inflightSchedule) selectResponse(e *Engine, from, index uint64) func() { + if from == s.b && index >= s.first && !s.selectedHealthy && !s.measuring { + s.selected.hold() + s.measuring = true + } + if from == s.c && index == s.target.Load() && s.measuring { + s.beforeHealthy = inflightProgress(e, from) + s.measuring = false + s.selectedHealthy = true + if s.revokeSelected != nil { + s.revokeSelected.hold() + } + return func() { s.afterHealthy <- inflightProgress(e, from) } + } + return nil +} + +func (s *inflightSchedule) observeAppend(e *Engine, m inflightAppend, preclone bool) { + if preclone { + s.mu.Lock() + if len(s.queued) == 0 { + s.initialState = e.rawNode.Status().Progress[s.b].State + } + s.queued = append(s.queued, m) + s.mu.Unlock() + } + if !s.measuring { + return + } + if preclone { + if len(s.cloned) == 0 { + s.refillNext = e.rawNode.Status().Progress[s.b].Next + } + s.cloned = append(s.cloned, m) + } else { + s.emitted = append(s.emitted, m) + } +} + +func (s *inflightSchedule) beforeLeaderSend(m *raftpb.Message) error { + if m.GetTo() != s.b || m.GetType() != raftpb.MsgApp || len(m.Entries) == 0 { + return nil + } + var size int + for _, entry := range m.Entries { + size += len(entry.Data) + } + s.mu.Lock() + s.dispatched = append(s.dispatched, inflightAppend{m.Entries[0].GetIndex(), m.Entries[len(m.Entries)-1].GetIndex(), size}) + s.mu.Unlock() + switch s.attempts.Add(1) { + case 1: + return status.Error(codes.Unavailable, "pre-delivery Append failure") + case 2: // Deliver the real retry, allowing B to persist the probe. + default: + s.suffix.hold() + } + return nil +} + +func (s *inflightSchedule) beforeLaggingResponse(m *raftpb.Message) error { + if m.GetTo() != s.a { + return nil + } + if m.GetType() == raftpb.MsgHeartbeatResp && len(m.Context) > 0 { + return status.Error(codes.Unavailable, "read requires the independent healthy voter") + } + if m.GetType() == raftpb.MsgAppResp && !m.GetReject() && m.GetIndex() >= s.first { + if s.saved.Load() < m.GetIndex() { + s.early.Store(true) + } + s.response.hold() + } + return nil +} + +func (s *inflightSchedule) dispatch(ctx context.Context, e *Engine, m *raftpb.Message) error { + var fault error + switch e.nodeID { + case s.a: + fault = s.beforeLeaderSend(m) + case s.b: + fault = s.beforeLaggingResponse(m) + case s.c: + if m.GetType() != raftpb.MsgAppResp || m.GetReject() || m.GetIndex() != s.target.Load() { + break + } + s.healthy.hold() + err := e.transport.Dispatch(ctx, *m) + select { + case s.healthyEnqueued <- err: + default: + } + return err + } + if fault != nil { + return fault + } + return e.transport.Dispatch(ctx, *m) +} + +func requireInflightRead(t *testing.T, a *inflightMember, index uint64) { + t.Helper() + parent, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + ctx, op, err := a.arbiter.Begin(parent, raftadmission.Data) + require.NoError(t, err) + defer op.CancelAndJoin() + read, err := a.engine.LinearizableRead(ctx) + require.NoError(t, err) + require.GreaterOrEqual(t, read, index) +} + +func TestSyncInflightRefill(t *testing.T) { + for _, mode := range []string{"response-held", "save-held"} { + t.Run(mode, func(t *testing.T) { testSyncInflightRefill(t, mode == "save-held", false) }) + } +} + +func TestSyncInflightRevokedHealthyACK(t *testing.T) { + testSyncInflightRefill(t, false, true) +} + +func startInflightCaller(t *testing.T, cancel context.CancelFunc, gates []*inflightGate, call func() error) <-chan error { + t.Helper() + done := make(chan error, 1) + finished := make(chan struct{}) + t.Cleanup(func() { + cancel() + for _, gate := range gates { + if gate != nil { + gate.open() + } + } + testutil.Closed(t, finished, 5*time.Second, "proposal caller join") + }) + go func() { + defer close(finished) + done <- call() + }() + return done +} + +func TestSyncInflightCallerCleanup(t *testing.T) { + joinedBeforeResources := false + t.Run("abandoned-call", func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + gate := newInflightGate(t) + started, finished := make(chan struct{}), make(chan struct{}) + // The fallback keeps the RED case from leaving a caller behind. + t.Cleanup(func() { + cancel() + gate.open() + testutil.Closed(t, finished, 5*time.Second, "fallback caller join") + }) + t.Cleanup(func() { + select { + case <-finished: + joinedBeforeResources = true + default: + } + }) + startInflightCaller(t, cancel, []*inflightGate{gate, nil}, func() error { + close(started) + <-ctx.Done() + gate.hold() + close(finished) + return ctx.Err() + }) + testutil.Closed(t, started, 5*time.Second, "caller start") + // Leave before receiving the result, as an earlier fatal assertion does. + }) + require.True(t, joinedBeforeResources, "caller must join before earlier resource cleanups") +} + +func (s *inflightSchedule) checkSelectedACK(t *testing.T, a *inflightMember, committed uint64) { + t.Helper() + if s.revokeSelected != nil { + s.revokeSelected.wait(t) + a.transport.peerSession.owner.SuspendGroup(1) + s.revokeSelected.open() + } + after := testutil.Recv(t, s.afterHealthy, 5*time.Second, "selected C ACK did not finish processing") + target := s.target.Load() + require.Equal(t, committed, s.beforeHealthy.commit) + require.Less(t, s.beforeHealthy.match, target) + t.Logf("selected C ACK %d: Match %d -> %d, commit %d -> %d", target, s.beforeHealthy.match, after.match, s.beforeHealthy.commit, after.commit) + if s.revokeSelected != nil { + require.Equal(t, s.beforeHealthy, after, "revoked C ACK advanced Raft") + return + } + require.Equal(t, inflightAckProgress{target, target}, after, "selected C ACK must advance both Match and commit") +} + +func testSyncInflightRefill(t *testing.T, saveHeld, revokeHealthy bool) { + var current atomic.Pointer[inflightSchedule] + cluster := newInflightCluster(t, 0, func(e *Engine) { installInflightSchedule(¤t, e) }) + a, b, c := cluster.voters(t) + write := cluster.writer(t, a) + propose := func(i int, value []byte) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + require.NoError(t, write(ctx, i, value)) + } + propose(0, []byte("warm")) + warm := a.engine.AppliedIndex() + requireInflightReplicated(t, a, b, c, warm) + s := &inflightSchedule{a: a.peer.NodeID, b: b.peer.NodeID, c: c.peer.NodeID, first: warm + 1, saveHeld: saveHeld, + afterHealthy: make(chan inflightAckProgress, 1), + save: newInflightGate(t), response: newInflightGate(t), healthy: newInflightGate(t), selected: newInflightGate(t), suffix: newInflightGate(t), healthyEnqueued: make(chan error, 1)} + if revokeHealthy { + s.revokeSelected = newInflightGate(t) + } + current.Store(s) + propose(1, []byte("probe")) + if saveHeld { + s.save.wait(t) + select { + case <-s.response.entered: + t.Fatal("B dispatched an ACK during Save") + default: + } + } else { + s.response.wait(t) + } + value := bytes.Repeat([]byte("v"), inflightValueSize) + for i := range inflightWrites { + propose(i+2, value) + } + committed := a.engine.AppliedIndex() + require.Equal(t, s.first+inflightWrites, committed) + require.Equal(t, warm, a.engine.Status().PerPeer[s.b].Match) + requireInflightRead(t, a, committed) + if saveHeld { + s.save.open() + s.response.wait(t) + } + require.Equal(t, s.first, s.saved.Load()) + s.target.Store(committed + 1) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + done := startInflightCaller(t, cancel, []*inflightGate{s.save, s.response, s.healthy, s.selected, s.suffix, s.revokeSelected}, func() error { + return write(ctx, inflightWrites+2, []byte("final")) + }) + s.healthy.wait(t) + s.response.open() + s.selected.wait(t) + // The owner is parked before native admission. No other goroutine + // operates the RawNode. This read-only inspection never advances it. + pr := a.engine.rawNode.Status().Progress[s.b] + require.Equal(t, tracker.StateProbe, pr.State) + require.Equal(t, warm, pr.Match) + s.healthy.open() + require.NoError(t, testutil.Recv(t, s.healthyEnqueued, 5*time.Second, "healthy RPC did not enqueue")) + require.Equal(t, committed, a.engine.AppliedIndex()) + s.selected.open() + s.checkSelectedACK(t, a, committed) + if revokeHealthy { + cancel() + require.Error(t, testutil.Recv(t, done, 5*time.Second, "canceled proposal did not return")) + return + } + require.NoError(t, testutil.Recv(t, done, 5*time.Second, "healthy ACK did not commit")) + require.Equal(t, tracker.StateReplicate, s.initialState) + require.Equal(t, s.emitted, s.cloned) + require.NotEmpty(t, s.emitted) + var total, maxMessage int + next := s.first + 1 + for _, m := range s.emitted { + require.Equal(t, next, m.first) + next = m.last + 1 + total += m.bytes + maxMessage = max(maxMessage, m.bytes) + } + require.Equal(t, s.refillNext, next, "entire range was emitted by the initial refill") + require.Equal(t, s.target.Load(), a.engine.AppliedIndex()) + requireInflightRead(t, a, s.target.Load()) + s.suffix.open() + requireInflightReplicated(t, a, b, c, s.target.Load()) + for _, m := range cluster.members { + got, err := m.store.GetAt(t.Context(), []byte("key"), 9999) + require.NoError(t, err) + require.Equal(t, "final", string(got)) + } + s.mu.Lock() + queued, dispatched := slices.Clone(s.queued), slices.Clone(s.dispatched) + s.mu.Unlock() + require.Equal(t, queued, dispatched) + require.False(t, s.early.Load()) + require.LessOrEqual(t, maxMessage, defaultMaxSizePerMsg) + require.GreaterOrEqual(t, total, 8<<20) + t.Logf("committed lag suffix %d value bytes; before healthy Step %d messages, %d emitted and preclone payload bytes, largest %d; healthy commit/read and all-member catch-up through %d", inflightWrites*len(value), len(s.emitted), total, maxMessage, s.target.Load()) + require.LessOrEqual(t, total, (8<<20)+maxMessage) +} + +func requireInflightReplicated(t *testing.T, a, b, c *inflightMember, index uint64) { + t.Helper() + require.EventuallyWithT(t, func(check *assert.CollectT) { + p := a.engine.Status().PerPeer + assert.Equal(check, index, p[b.peer.NodeID].Match, "B Match") + assert.Equal(check, index, p[c.peer.NodeID].Match, "C Match") + assert.Equal(check, index, b.engine.AppliedIndex(), "B applied") + assert.Equal(check, index, c.engine.AppliedIndex(), "C applied") + }, 5*time.Second, time.Millisecond) +} + +func TestSyncInflightNoFault(t *testing.T) { + cluster := newInflightCluster(t, 0, func(*Engine) {}) + a, b, c := cluster.voters(t) + write := cluster.writer(t, a) + value := bytes.Repeat([]byte("v"), inflightValueSize) + for i := range inflightWrites + 3 { + payload := value + switch i { + case 0: + payload = []byte("warm") + case 1: + payload = []byte("probe") + case inflightWrites + 2: + payload = []byte("final") + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + err := write(ctx, i, payload) + cancel() + require.NoError(t, err) + } + final := a.engine.AppliedIndex() + requireInflightRead(t, a, final) + require.Eventually(t, func() bool { return b.engine.AppliedIndex() == final && c.engine.AppliedIndex() == final }, 5*time.Second, time.Millisecond) +} + +func TestSyncInflightCompatibilityBudgets(t *testing.T) { + for _, tc := range []struct { + name string + size int + timeout time.Duration + }{ + {"threshold", inflightLargeValueThreshold, 5 * time.Second}, + {"large", inflightLargeValueThreshold + 1, 30 * time.Second}, + {"following", len("following"), 5 * time.Second}, + } { + t.Run(tc.name, func(t *testing.T) { + var caller context.Context + var deadline time.Time + start := time.Now() + requireInflightCompatibilityWrite(t, func(ctx context.Context, _ int, _ []byte) error { + caller = ctx + var ok bool + deadline, ok = ctx.Deadline() + require.True(t, ok) + return nil + }, 0, make([]byte, tc.size)) + end := time.Now() + require.False(t, deadline.Before(start.Add(tc.timeout))) + require.False(t, deadline.After(end.Add(tc.timeout))) + require.ErrorIs(t, caller.Err(), context.Canceled) + }) + } +} + +func requireInflightCompatibilityWrite(t *testing.T, write func(context.Context, int, []byte) error, i int, value []byte) { + t.Helper() + writeTimeout := 5 * time.Second + if len(value) > inflightLargeValueThreshold { + writeTimeout = inflightLargeWriteTimeout + } + ctx, cancel := context.WithTimeout(t.Context(), writeTimeout) + defer cancel() + err := write(ctx, i, value) + if err != nil { + t.Logf("compatibility write failed: bytes=%d caller=%v deadline=%t canceled=%t leadership_lost=%t admission_stale=%t admission_closed=%t", + len(value), ctx.Err(), errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled), + errors.Is(err, raftengine.ErrLeadershipLost), errors.Is(err, raftadmission.ErrStale), errors.Is(err, raftadmission.ErrClosed)) + } + require.NoError(t, err) +} + +func TestSyncInflightMessageTargets(t *testing.T) { + for _, tc := range []struct { + name string + target uint64 + }{ + {"default-large-entry", 0}, + {"custom-16MiB", 16 << 20}, + } { + t.Run(tc.name, func(t *testing.T) { + // Measure the real wire envelope. Both large values use the same + // protobuf length widths; all fixture indexes fit in one byte. + var wireBytes atomic.Int64 + cluster := newInflightCluster(t, tc.target, func(e *Engine) { + e.dispatchFn = func(ctx context.Context, r dispatchRequest) error { + m := &r.msg + if m.GetType() == raftpb.MsgApp && len(m.Entries) == 1 && len(m.Entries[0].Data) > 8<<20 { + wireBytes.Store(int64(protowire.SizeTag(1) + protowire.SizeBytes(proto.Size(m)))) + } + return e.transport.Dispatch(ctx, *m) + } + }) + a, b, c := cluster.voters(t) + write := cluster.writer(t, a) + const calibration = 9 << 20 + sizes := []int{calibration} + if tc.target == 0 { + sizes = append(sizes, peersession.TransportMaxMessageSize) + } + sizes = append(sizes, len("following")) + for i, size := range sizes { + if size == peersession.TransportMaxMessageSize { + size -= int(wireBytes.Load()) - calibration + } + value := bytes.Repeat([]byte("v"), size) + requireInflightCompatibilityWrite(t, write, i, value) + index := a.engine.AppliedIndex() + requireInflightReplicated(t, a, b, c, index) + entries, err := a.engine.storage.Entries(index, index+1, math.MaxUint64) + require.NoError(t, err) + require.Len(t, entries, 1) + if sizes[i] == peersession.TransportMaxMessageSize { + require.EqualValues(t, peersession.TransportMaxMessageSize, wireBytes.Load()) + } + require.Greater(t, len(entries[0].Data), len(value)) + for _, member := range cluster.members { + got, err := member.store.GetAt(t.Context(), []byte("key"), 9999) + require.NoError(t, err) + require.True(t, bytes.Equal(value, got)) + } + t.Logf("both voters acknowledged index %d, entry payload %d bytes", index, len(entries[0].Data)) + } + }) + } +} + +func TestInflightWindowOpenLimits(t *testing.T) { + cfg := normalizeLimitConfig(normalizeTimingConfig(OpenConfig{NodeID: 1, MaxSizePerMsg: math.MaxUint64})) + _, err := newRawNode(cfg, etcdraft.NewMemoryStorage(), 0) + require.NoError(t, err) + // Upstream refuses a message target larger than the inflight byte limit. + // These two opens pin the independent async setting at exactly 128 MiB. + cfg.MaxSizePerMsg = 128 << 20 + _, err = newStorageRawNode(cfg, etcdraft.NewMemoryStorage(), 0) + require.NoError(t, err) + cfg.MaxSizePerMsg++ + require.PanicsWithValue(t, "max inflight bytes must be >= max message size", func() { + _, _ = newStorageRawNode(cfg, etcdraft.NewMemoryStorage(), 0) + }) +} + +func TestSyncInflightTermChangeDuringSave(t *testing.T) { + var current atomic.Pointer[inflightSchedule] + var enqueuedTerm atomic.Uint64 + cluster := newInflightCluster(t, 0, func(e *Engine) { + e.persist = &inflightDisk{e.persist, e.nodeID, ¤t} + e.dispatchFn = func(ctx context.Context, r dispatchRequest) error { + err := e.transport.Dispatch(ctx, r.msg) + s := current.Load() + if err == nil && s != nil && e.nodeID == s.c && r.msg.GetTo() == s.b && r.msg.GetType() == raftpb.MsgHeartbeat { + enqueuedTerm.Store(r.msg.GetTerm()) + } + return err + } + }) + a, b, c := cluster.voters(t) + write := cluster.writer(t, a) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + require.NoError(t, write(ctx, 0, []byte("warm"))) + base := a.engine.AppliedIndex() + requireInflightReplicated(t, a, b, c, base) + term := a.engine.Status().Term + s := &inflightSchedule{a: a.peer.NodeID, b: b.peer.NodeID, c: c.peer.NodeID, first: base + 1, saveHeld: true, save: newInflightGate(t)} + current.Store(s) + require.NoError(t, write(ctx, 1, []byte("before-transfer"))) + s.save.wait(t) + transferInflightLeadership(t, ctx, a, c) + require.Eventually(t, func() bool { return enqueuedTerm.Load() > term && c.engine.State() == raftengine.StateLeader }, 5*time.Second, time.Millisecond) + require.Equal(t, term, b.engine.Status().Term) + require.Zero(t, s.saved.Load()) + require.Equal(t, base, b.engine.AppliedIndex()) + s.save.open() + next, finish := context.WithTimeout(t.Context(), 5*time.Second) + defer finish() + require.NoError(t, cluster.writer(t, c)(next, 2, []byte("after-transfer"))) + requireInflightReplicated(t, c, b, a, c.engine.AppliedIndex()) + require.Equal(t, c.engine.Status().Term, b.engine.Status().Term) +} diff --git a/internal/raftengine/etcd/version_cas_test.go b/internal/raftengine/etcd/version_cas_test.go new file mode 100644 index 000000000..bbbdc740e --- /dev/null +++ b/internal/raftengine/etcd/version_cas_test.go @@ -0,0 +1,36 @@ +package etcd + +import ( + "testing" + + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/stretchr/testify/require" +) + +func TestVersionCASConfigurationCheckedAtAppend(t *testing.T) { + engine, err := Open(t.Context(), OpenConfig{ + NodeID: 1, LocalID: "n1", LocalAddress: "127.0.0.1:7001", + DataDir: t.TempDir(), Bootstrap: true, StateMachine: &testStateMachine{}, + }) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, engine.Close()) }) + st := engine.Status() + require.NotZero(t, st.ConfigurationIndex) + payloads := [][]byte{[]byte(raftengine.MigrationVersionIdentityFrame), []byte(raftengine.VersionCASFrame + "test")} + for i, payload := range payloads { + _, err := engine.Propose(t.Context(), payload) + require.ErrorIs(t, err, raftengine.ErrVersionCASUnavailable) + for _, proof := range []raftengine.VersionCASProof{ + {Term: st.Term + 1, ConfigurationIndex: st.ConfigurationIndex}, + {Term: st.Term, ConfigurationIndex: st.ConfigurationIndex + 1}, + } { + _, err := engine.Propose(raftengine.WithVersionCASProof(t.Context(), proof), payload) + require.ErrorIs(t, err, raftengine.ErrVersionCASUnavailable) + } + + proof := raftengine.VersionCASProof{Term: st.Term, ConfigurationIndex: st.ConfigurationIndex} + result, err := engine.Propose(raftengine.WithVersionCASProof(t.Context(), proof), payload) + require.NoError(t, err) + require.Equal(t, st.LastLogIndex+uint64(i)+1, result.CommitIndex, "only a matching proof may append") + } +} diff --git a/internal/raftengine/proposal_turn.go b/internal/raftengine/proposal_turn.go new file mode 100644 index 000000000..9c99a65b0 --- /dev/null +++ b/internal/raftengine/proposal_turn.go @@ -0,0 +1,8 @@ +package raftengine + +// ProposalTurnClassifier identifies ordinary cleartext data proposals that can +// precede the same Ready drain. Implementations must reject unknown, wrapped +// and control payloads. Classification grants no admission authority. +type ProposalTurnClassifier interface { + IsProposalTurnPayload([]byte) bool +} diff --git a/internal/raftengine/statemachine.go b/internal/raftengine/statemachine.go index 79a8c15bb..36ddc2c79 100644 --- a/internal/raftengine/statemachine.go +++ b/internal/raftengine/statemachine.go @@ -33,6 +33,13 @@ type Snapshot interface { Close() error } +// OwnerSnapshotCapturer optionally captures a stable view at the owner's applied +// cut. The caller owns the handle and must finish or retire it and successfully +// close it before restoring or closing the source state machine or store. +type OwnerSnapshotCapturer interface { + CaptureOwnerSnapshot() (Snapshot, error) +} + // StateMachine is the interface that engine-agnostic state machines must // implement. Both the hashicorp and etcd backends use this contract. type StateMachine interface { diff --git a/internal/raftengine/version_cas.go b/internal/raftengine/version_cas.go new file mode 100644 index 000000000..8da771a9b --- /dev/null +++ b/internal/raftengine/version_cas.go @@ -0,0 +1,45 @@ +package raftengine + +import ( + "bytes" + "context" + "errors" +) + +var ErrVersionCASUnavailable = errors.New("version CAS admission unavailable") + +// VersionCASFrame requires routing evidence from the same Raft log as the CAS. +const VersionCASFrame = "\x06CAS\x02" + +const versionCASFramePrefix = "\x06CAS" + +const MigrationVersionIdentityFrame = "\x06MVI\x03" + +const RetirementMigrationVersionIdentityFrame = "\x06MVI\x02" + +const LegacyMigrationVersionIdentityFrame = "\x06MVI\x01" + +func IsVersionCASRaftPayload(payload []byte) bool { + return bytes.HasPrefix(payload, []byte(versionCASFramePrefix)) +} + +// RequiresVersionCASProof covers both the activation and subsequent CAS. +func RequiresVersionCASProof(payload []byte) bool { + return IsVersionCASRaftPayload(payload) || bytes.HasPrefix(payload, []byte("\x06MVI")) +} + +type versionCASProofKey struct{} + +type VersionCASProof struct { + Term uint64 + ConfigurationIndex uint64 +} + +func WithVersionCASProof(ctx context.Context, proof VersionCASProof) context.Context { + return context.WithValue(ctx, versionCASProofKey{}, proof) +} + +func VersionCASProposalProof(ctx context.Context) (VersionCASProof, bool) { + proof, ok := ctx.Value(versionCASProofKey{}).(VersionCASProof) + return proof, ok +} diff --git a/internal/server/bootstrap_enablement_multi_e2e_test.go b/internal/server/bootstrap_enablement_multi_e2e_test.go index 6e2a5a4aa..1198d8986 100644 --- a/internal/server/bootstrap_enablement_multi_e2e_test.go +++ b/internal/server/bootstrap_enablement_multi_e2e_test.go @@ -27,6 +27,7 @@ import ( "github.com/bootjp/elastickv/internal/clusterbootstrap" "github.com/bootjp/elastickv/internal/noderuntime" "github.com/bootjp/elastickv/internal/peersession" + "github.com/bootjp/elastickv/internal/raftadmin" "github.com/bootjp/elastickv/internal/raftadmission" "github.com/bootjp/elastickv/internal/raftbootstrap" "github.com/bootjp/elastickv/internal/raftengine" @@ -198,7 +199,7 @@ func multiEnablementStartMember(t *testing.T, base string, identity *multiEnable process.eg, process.ctx = errgroup.WithContext(process.ctx) options := append([]grpc.ServerOption{}, runtime.TransportServerOptions...) if protected { - options = append(options, multiEnablementNetwork(t, process, routes, clock)...) + options = append(options, multiEnablementNetwork(t, process, routes, clock, base, identity.id)...) } process.server = grpc.NewServer(options...) clusterbootstrap.RuntimeCore(runtime).RegisterGRPC(process.server) @@ -209,7 +210,7 @@ func multiEnablementStartMember(t *testing.T, base string, identity *multiEnable return process } -func multiEnablementNetwork(t *testing.T, process *multiEnablementProcess, routes *distribution.Engine, clock *kv.HLC) []grpc.ServerOption { +func multiEnablementNetwork(t *testing.T, process *multiEnablementProcess, routes *distribution.Engine, clock *kv.HLC, base, raftID string) []grpc.ServerOption { t.Helper() id := process.runtime.Spec.ID groups := map[uint64]*kv.ShardGroup{id: process.shard} @@ -218,7 +219,14 @@ func multiEnablementNetwork(t *testing.T, process *multiEnablementProcess, route network, err := clusterbootstrap.ConfigureBootstrapNetwork(process.ctx, []*clusterbootstrap.GroupRuntime{process.runtime}, process.shards, groups, &process.cleanup) require.NoError(t, err) require.NotNil(t, network, "ordinary forwarding must use the actual runtime-scoped pinned TLS factory") + flags := defaultServerFlags() + flags.raft.id, flags.raft.dataDir = raftID, base + flags.consistency.versionCAS = true + flags.consistency.commitTSFence = true + require.NoError(t, configureVersionCAS(flags, noderuntime.RuntimeConfig{Groups: []noderuntime.GroupSpec{process.runtime.Spec}}, + []*clusterbootstrap.GroupRuntime{process.runtime}, groups, &process.cleanup)) process.coordinate = kv.NewShardedCoordinator(routes, groups, id, clock, process.shards).WithOperationAdmission(process.domain.OperationAdmission) + process.coordinate.WithAdaptiveVersionCASPrecheck(nil) catalog := distributionCatalogStoreForGroup([]*clusterbootstrap.GroupRuntime{process.runtime}, id) clusterbootstrap.StartBootstrapReadinessReconciler(process.ctx, process.eg, []*clusterbootstrap.GroupRuntime{process.runtime}, catalog, routes) process.gate = multiEnablementGate(process) @@ -237,10 +245,12 @@ func multiEnablementServices(process *multiEnablementProcess, clock *kv.HLC) { pb.RegisterRawKVServer(process.server, service) pb.RegisterTransactionalKVServer(process.server, service) proposer := process.shard.Proposer() - process.transaction = adapter.NewInternalMigrationTransaction(proposer, nil, process.runtime.Store, process.runtime.Spec.ID) + process.transaction = adapter.NewInternalMigrationTransaction(proposer, nil, process.runtime.Store, process.runtime.Spec.ID, kv.WithVersionCASAdmission(process.runtime.VersionCASAdmission)) options := internalServerOptions(coordinate, nil, proposer, process.shard, process.runtime.Spec.ID) + options = append(options, adapter.WithInternalCASForwardRouting(process.runtime.Spec.ID, process.shards.CheckVersionCASForwardRoute)) options = append(options, adapter.WithInternalStore(process.runtime.Store), adapter.WithInternalPrimaryCommitEvidence(process.shards)) pb.RegisterInternalServer(process.server, adapter.NewInternalWithEngine(process.transaction, process.runtime.Engine, clock, nil, options...)) + pb.RegisterRaftAdminServer(process.server, raftadmin.NewServerWithInterceptor(process.runtime.Engine, nil, process.runtime.VersionCASCapable)) } func multiEnablementStop(t *testing.T, processes []*multiEnablementProcess) { @@ -530,6 +540,9 @@ func multiEnablementRun(t *testing.T, lagging bool) { multiEnablementReplicatedRead(t, process, "protected-key", "replicated-protected") } multiEnablementFollowerForward(t, protected, leader) + if !lagging { + multiEnablementVersionCAS(t, protected, leader) + } if lagging { multiEnablementActiveSnapshotRestart(t, base, identities, protected, manifest, activation) } diff --git a/internal/server/bootstrap_tso_baseline_test.go b/internal/server/bootstrap_tso_baseline_test.go index a0d18a283..68c9b9c5a 100644 --- a/internal/server/bootstrap_tso_baseline_test.go +++ b/internal/server/bootstrap_tso_baseline_test.go @@ -5,6 +5,7 @@ import ( "context" "crypto" "encoding/binary" + "errors" "os" "path/filepath" "testing" @@ -245,7 +246,8 @@ func TestOfflineTSOPreparationRejectsChangedManifestAndSource(t *testing.T) { require.Error(t, err) } -func TestOfflineTSOPreparationNativeBound(t *testing.T) { +func nativeTSOPreparationFixture(t *testing.T) (etcd.OfflineBaselineOptions, raftbootstrap.BaselineManifest, *clusterbootstrap.GroupBootstrapSpec) { + t.Helper() callbacks, c, _, spec := tsoPreparationCallbackFixture(t) dir := c.BackupDir // The fixture's original legacy source, not a prepared target. ownership, err := etcd.AcquireOfflineBaselineOwnership(dir) @@ -257,21 +259,61 @@ func TestOfflineTSOPreparationNativeBound(t *testing.T) { _, proof, err := clusterbootstrap.ProbeOfflineTSOBaseline(ctx, dir, ownership) return proof, err }} - migration, err := etcd.PrepareOfflineBaseline(t.Context(), options, c.Manifest) + return options, c.Manifest, spec +} + +func TestOfflineTSOPreparationNativeBound(t *testing.T) { + options, manifest, spec := nativeTSOPreparationFixture(t) + migration, err := etcd.PrepareOfflineBaseline(t.Context(), options, manifest) require.NoError(t, err) require.Equal(t, "prepared", migration.Phase) for range 4 { - migration, err = etcd.ResumeOfflineBaseline(t.Context(), options, c.Manifest) + migration, err = etcd.ResumeOfflineBaseline(t.Context(), options, manifest) require.NoError(t, err) if migration.Phase == "bound" { break } } require.Equal(t, "bound", migration.Phase) - _, err = etcd.VerifyBoundOfflineBaseline(t.Context(), options, c.Manifest) + _, err = etcd.VerifyBoundOfflineBaseline(t.Context(), options, manifest) require.NoError(t, err) - require.NoError(t, ownership.Close()) - verifyBoundTSOControl(t, dir, spec, c.Manifest) + require.NoError(t, options.Ownership.Close()) + verifyBoundTSOControl(t, options.DataDir, spec, manifest) +} + +func TestOfflineTSOPreparationResumeAfterLockCreation(t *testing.T) { + options, manifest, _ := nativeTSOPreparationFixture(t) + stage := options.Preparation.StagePreparation + interrupted := errors.New("interrupted before Pebble opened the control store") + dir := filepath.Join(options.DataDir, ".elastickv-store-locks") + anchor := filepath.Join(dir, clusterbootstrap.DedicatedTSOControlStoreName) + options.Preparation.StagePreparation = func(context.Context, etcd.BaselinePreparationContext) error { + require.NoError(t, os.Mkdir(filepath.Join(options.DataDir, clusterbootstrap.DedicatedTSOControlStoreName), 0o700)) + require.NoError(t, os.Mkdir(dir, 0o700)) + require.NoError(t, os.WriteFile(anchor, nil, 0o600)) + return interrupted + } + _, err := etcd.PrepareOfflineBaseline(t.Context(), options, manifest) + require.ErrorIs(t, err, interrupted) + before, err := os.Lstat(anchor) + require.NoError(t, err) + options.Preparation.StagePreparation = stage + paths, err := etcd.ResumeOfflineBaseline(t.Context(), options, manifest) + require.NoError(t, err) + require.Equal(t, "prepared", paths.Phase) + after, err := os.Lstat(anchor) + require.NoError(t, err) + require.True(t, os.SameFile(before, after), "resume must reuse the stable lock inode") + + // The journal now binds the complete physical target, including the anchor. + held := filepath.Join(t.TempDir(), "held") + require.NoError(t, os.Rename(anchor, held)) + _, err = etcd.ResumeOfflineBaseline(t.Context(), options, manifest) + require.ErrorContains(t, err, "prepared target changed") + require.NoError(t, os.Rename(held, anchor)) + paths, err = etcd.ResumeOfflineBaseline(t.Context(), options, manifest) + require.NoError(t, err) + require.Equal(t, "bound", paths.Phase) } func verifyBoundTSOControl(t *testing.T, dir string, spec *clusterbootstrap.GroupBootstrapSpec, manifest raftbootstrap.BaselineManifest) { diff --git a/internal/server/commit_ts_fence.go b/internal/server/commit_ts_fence.go index 06349b7bf..c7ab12cf2 100644 --- a/internal/server/commit_ts_fence.go +++ b/internal/server/commit_ts_fence.go @@ -22,10 +22,12 @@ func configureCommitTSFenceActivation(coordinate *kv.ShardedCoordinator, enabled // enabled. type consistencyFlags struct { commitTSFence bool + versionCAS bool readWatermarkAdvance bool } func (f *consistencyFlags) register(fs *flag.FlagSet) { + fs.BoolVar(&f.versionCAS, "versionCAS", false, "Enable MVCC version tokens and CAS for unmigrated keys on protected Raft data groups after replicated activation and live replica checks") fs.BoolVar(&f.commitTSFence, "commitTSFence", false, "Reserved for replicated catalog bootstrap; activation is rejected until the startup catalog no longer writes outside Raft") fs.BoolVar(&f.readWatermarkAdvance, "readWatermarkAdvance", false, "Raise a lagging group's commit watermark before a cross-group snapshot read so late one-phase writes cannot land below the snapshot; enable only after every node runs a binary that understands the advance entry") } diff --git a/internal/server/forward_transaction.go b/internal/server/forward_transaction.go index 2e6c2721d..14b834b34 100644 --- a/internal/server/forward_transaction.go +++ b/internal/server/forward_transaction.go @@ -12,5 +12,5 @@ func forwardTransactionForGroup(rt *clusterbootstrap.GroupRuntime, groups map[ui return tx } } - return adapter.NewInternalMigrationTransaction(proposerForGroup(rt, groups), observer, rt.Store, rt.Spec.ID) + return adapter.NewInternalMigrationTransaction(proposerForGroup(rt, groups), observer, rt.Store, rt.Spec.ID, kv.WithVersionCASAdmission(rt.VersionCASAdmission)) } diff --git a/internal/server/raft_servers.go b/internal/server/raft_servers.go index 42063e997..842c4f2a1 100644 --- a/internal/server/raft_servers.go +++ b/internal/server/raft_servers.go @@ -142,6 +142,7 @@ func startRaftServers( pb.RegisterRawKVServer(gs, grpcSvc) pb.RegisterTransactionalKVServer(gs, grpcSvc) internalOpts := internalServerOptions(coordinate, adminServer, proposerForGroup(rt, shardGroups), shardGroups[rt.Spec.ID], rt.Spec.ID) + internalOpts = append(internalOpts, adapter.WithInternalCASForwardRouting(rt.Spec.ID, shardStore.CheckVersionCASForwardRoute)) internalOpts = append(internalOpts, clusterbootstrap.BootstrapInternalPolicyOptions(rt, proposerForGroup(rt, shardGroups))...) internalOpts = append(internalOpts, ttlInlineInternalOptions(rt)...) internalOpts = append(internalOpts, dedicatedTimestampCutoverOptions(shardGroups)...) @@ -205,6 +206,7 @@ func startRaftServers( []string{"RawKV"}, staticServingServices, migrationMembershipInterceptor(rt, shardStore, proposerForGroup(rt, shardGroups), adminGRPCOpts.MigrationToken, confChangeInterceptor), + rt.VersionCASCapable, ) reflection.Register(gs) diff --git a/internal/server/run.go b/internal/server/run.go index eec622f96..bb343d5ad 100644 --- a/internal/server/run.go +++ b/internal/server/run.go @@ -198,7 +198,7 @@ func Run(flags *Flags) error { } }) bootstrapDomain, resolverOptions := clusterbootstrap.ConfigureBootstrapOperations(ctx, runtimes, shardStore, &cleanup) - bootstrapNetwork, err := clusterbootstrap.ConfigureBootstrapNetwork(ctx, runtimes, shardStore, shardGroups, &cleanup) + bootstrapNetwork, err := configureProtectedShardNetwork(ctx, flags, cfg, runtimes, shardStore, shardGroups, &cleanup) if err != nil { return errors.WithStack(err) } @@ -227,6 +227,7 @@ func Run(flags *Flags) error { return err } cleanup.Add(tsoWiring.CloseWithLog) + configureAdaptiveVersionCAS(coordinate, flags.consistency.versionCAS, readTracker) readTracker.SetBackupTimestampFloorObserver(coordinate.ObserveTimestampFloor) // SQS HT-FIFO ยง8 leadership-refusal: install per-group diff --git a/internal/server/runtime_config.go b/internal/server/runtime_config.go index 8623cbee8..79ac579a4 100644 --- a/internal/server/runtime_config.go +++ b/internal/server/runtime_config.go @@ -61,6 +61,9 @@ func (f *topologyFlags) register(fs *flag.FlagSet) { } func resolveValidatedRuntimeInputs(flags *Flags) (noderuntime.RuntimeConfig, noderuntime.RaftEngineType, noderuntime.BootstrapConfig, bool, error) { + if flags.consistency.versionCAS && !flags.consistency.commitTSFence { + return noderuntime.RuntimeConfig{}, "", noderuntime.BootstrapConfig{}, false, errors.New("versionCAS requires --commitTSFence") + } if err := validateCommitTSFenceStartup(flags.consistency.commitTSFence, flags.bootstrap.peerConfigDir != ""); err != nil { return noderuntime.RuntimeConfig{}, "", noderuntime.BootstrapConfig{}, false, err } diff --git a/internal/server/sync_inflight_fresh_test.go b/internal/server/sync_inflight_fresh_test.go new file mode 100644 index 000000000..73ea583fb --- /dev/null +++ b/internal/server/sync_inflight_fresh_test.go @@ -0,0 +1,71 @@ +package server + +import ( + "context" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/casbenchmark" + "github.com/bootjp/elastickv/internal/clusterbootstrap" + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/testutil/grpctest" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" +) + +func TestSyncInflightFreshRequiresEveryMember(t *testing.T) { + t.Setenv("ELASTICKV_RAFT_SNAPSHOT_COUNT", "1") + base := t.TempDir() + processes := startVersionCASStressCluster(t, base, multiEnablementIdentities(t, base)) + defer multiEnablementStop(t, processes) + leader := multiEnablementLeader(t, processes) + coord := clusterbootstrap.NewStartupGatedCoordinator(leader.coordinate, leader.gate) + tracker := kv.NewActiveTimestampTracker() + defer tracker.Close() + address := grpctest.Serve(t, func(server *grpc.Server) { + casbenchmark.Register(server, leader.shards, coord, tracker, clusterbootstrap.BootstrapRequestAdmissionForCoordinator(coord)) + }) + client := grpctest.Dial(t, address) + key := []byte("bench1535/quorum") + put := func(value string) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + _, err := leader.coordinate.Dispatch(ctx, &kv.OperationGroup[kv.OP]{Elems: []*kv.Elem[kv.OP]{{Op: kv.Put, Key: key, Value: []byte(value)}}}) + require.NoError(t, err) + } + put("seed") + version, ok, err := leader.runtime.Store.LatestCommitTS(t.Context(), key) + require.NoError(t, err) + require.True(t, ok) + fresh := func(version uint64) (uint64, error) { + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + result := new(pb.CompareAndSwapResponse) + err := client.Invoke(ctx, casbenchmark.Prefix+"Fresh", &pb.CompareAndSwapRequest{Key: key, Value: []byte("fresh"), ExpectedCommitTs: version}, result) + return result.GetNewCommitTs(), err + } + version, err = fresh(version) + require.NoError(t, err) + require.Positive(t, version) + for _, member := range processes { + if member != leader { + multiEnablementStop(t, []*multiEnablementProcess{member}) + break + } + } + _, err = fresh(version) + require.ErrorContains(t, err, "replica capability check failed") + before := leader.runtime.Engine.Status().CommitIndex + put("quorum") + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + owned, op, err := leader.domain.Admission.Begin(ctx, raftadmission.Data) + require.NoError(t, err) + defer op.CancelAndJoin() + index, err := leader.runtime.Engine.LinearizableRead(owned) + require.NoError(t, err) + require.Greater(t, index, before) +} diff --git a/internal/server/version_adoption_recovery_test.go b/internal/server/version_adoption_recovery_test.go new file mode 100644 index 000000000..b3984b03b --- /dev/null +++ b/internal/server/version_adoption_recovery_test.go @@ -0,0 +1,107 @@ +package server + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func proposeAdoptionRecoveryFrame(t *testing.T, process *multiEnablementProcess, frame []byte, err error) any { + t.Helper() + require.NoError(t, err) + ctx, cancel := context.WithTimeout(t.Context(), bootstrapE2EWaitTimeout) + defer cancel() + owned, finish, err := process.domain.OperationAdmission(ctx, 1, kv.AdmissionMaintenance) + require.NoError(t, err) + result, err := process.shard.Proposer().Propose(owned, frame) + err = finish(err) + require.NoError(t, err) + if verdict, ok := result.Response.(error); ok { + require.NoError(t, verdict) + } + return result.Response +} + +// Native voters replicate the typed store controls and restore their real +// snapshots. The attestation fixture is synthetic; catalog production and +// routing of a complete move-back are covered separately in adapter tests. +func TestVersionAdoptionNativeVotersColdRestart(t *testing.T) { + t.Setenv("ELASTICKV_RAFT_SNAPSHOT_COUNT", "1") + base := t.TempDir() + identities := multiEnablementIdentities(t, base) + processes := startVersionCASStressCluster(t, base, identities) + defer func() { multiEnablementStop(t, processes) }() + leader := multiEnablementLeader(t, processes) + key := []byte("protected-key") + before, err := store.GetVersionAt(t.Context(), leader.runtime.Store, key, ^uint64(0)) + require.NoError(t, err) + configuration := leader.runtime.Engine.Status().ConfigurationIndex + frame, err := kv.MarshalTargetStagedReadinessCommand(&pb.TargetStagedReadinessRequest{ + JobId: 11, MigrationJobId: 11, Armed: true, TrackWrites: true, RouteStart: []byte("p"), RouteEnd: []byte("q"), + ExpectedCutoverVersion: 1, MinWriteTsExclusive: before.TS, RetentionPinTs: 1, + }) + proposeAdoptionRecoveryFrame(t, leader, frame, err) + proof := &pb.MigrationOwnershipProof{Generation: "0123456789abcdef0123456789abcdef", LocalGroupId: 1, OwnerGroupId: 1, + CatalogVersion: 1, RouteId: 1, RouteStart: []byte("p"), RouteEnd: []byte("q"), WriteFloorKnown: true, + MinWriteTsExclusive: before.TS, SourceTrackerVersion: 1, DescriptorHash: bytes.Repeat([]byte{1}, 32), + Role: pb.MigrationOwnershipRole_MIGRATION_OWNERSHIP_ROLE_OWNER} + frame, err = kv.MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{JobId: 11, + Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_SOURCE_OWNERSHIP_ACQUIRE, + RequireConfigurationIndex: true, ExpectedConfigurationIndex: configuration, Ownership: proof}) + proposeAdoptionRecoveryFrame(t, leader, frame, err) + frame, err = kv.MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{JobId: 11, + Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, RangeStart: key, RangeEnd: []byte("protected-kez"), + MaxCommitTs: before.TS, MaxVersions: 1, RequireConfigurationIndex: true, ExpectedConfigurationIndex: configuration, + ExpectedSourceGroupId: 1}) + retirement, ok := proposeAdoptionRecoveryFrame(t, leader, frame, err).(store.CleanupVersionsResult) + require.True(t, ok) + require.NotEmpty(t, retirement.RetirementID) + frame, err = kv.MarshalTargetStagedReadinessCommand(&pb.TargetStagedReadinessRequest{JobId: 12, MigrationJobId: 12, + Armed: true, RouteStart: []byte("p"), RouteEnd: []byte("q"), ExpectedCutoverVersion: 2, MinWriteTsExclusive: before.TS + 1}) + proposeAdoptionRecoveryFrame(t, leader, frame, err) + proof.CatalogVersion, proof.Staged, proof.SourceTrackerVersion = 2, true, 0 + proof.MinWriteTsExclusive = before.TS + 1 + frame, err = kv.MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{JobId: 12, + Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_OWNERSHIP_ACQUIRE, RequireConfigurationIndex: true, + ExpectedConfigurationIndex: configuration, Ownership: proof}) + proposeAdoptionRecoveryFrame(t, leader, frame, err) + frame, err = kv.MarshalMigrationImportCommand(&pb.ImportRangeVersionsRequest{JobId: 12, BatchSeq: 1, + Versions: []*pb.MVCCVersion{{Key: key, CommitTs: before.TS, Value: before.Value, ExpireAt: before.ExpireAt}}}) + proposeAdoptionRecoveryFrame(t, leader, frame, err) + frame, err = kv.MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 12}) + proposeAdoptionRecoveryFrame(t, leader, frame, err) + assertRecoveredAdoption(t, processes, before, retirement.RetirementID) + for _, process := range processes { + require.Eventually(t, func() bool { + return process.runtime.Engine.Status().LastSnapshotIndex >= process.runtime.Engine.Status().AppliedIndex + }, bootstrapE2EWaitTimeout, 10*time.Millisecond) + } + multiEnablementStop(t, processes) + processes = multiEnablementStart(t, base, identities, true) + assertRecoveredAdoption(t, processes, before, retirement.RetirementID) +} + +func assertRecoveredAdoption(t *testing.T, processes []*multiEnablementProcess, before store.VersionedValue, id string) { + t.Helper() + for _, process := range processes { + require.Eventually(t, func() bool { + value, err := store.GetVersionAt(t.Context(), process.runtime.Store, []byte("protected-key"), ^uint64(0)) + return err == nil && bytes.Equal(value.Value, before.Value) && value.TS == before.TS && value.ExpireAt == before.ExpireAt + }, bootstrapE2EWaitTimeout, 10*time.Millisecond) + retirement, ok := process.runtime.Store.(store.VersionRetirementStore) + require.True(t, ok) + require.NoError(t, retirement.VersionAdoptionReady(t.Context())) + gc, err := retirement.ReclaimVersionRetirement(t.Context(), 11, id) + require.NoError(t, err) + require.True(t, gc.Done, "old predecessors may be collected, but the adopted head must survive") + value, err := store.GetVersionAt(t.Context(), process.runtime.Store, []byte("protected-key"), ^uint64(0)) + require.NoError(t, err) + require.Equal(t, before, value) + } +} diff --git a/internal/server/version_cas.go b/internal/server/version_cas.go new file mode 100644 index 000000000..c157a4ba3 --- /dev/null +++ b/internal/server/version_cas.go @@ -0,0 +1,342 @@ +package server + +import ( + "context" + "time" + + internalutil "github.com/bootjp/elastickv/internal" + "github.com/bootjp/elastickv/internal/clusterbootstrap" + "github.com/bootjp/elastickv/internal/noderuntime" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + etcdraftengine "github.com/bootjp/elastickv/internal/raftengine/etcd" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "golang.org/x/sync/errgroup" + "google.golang.org/grpc" +) + +const versionCASProbeTimeout = 2 * time.Second + +func configureAdaptiveVersionCAS(coordinate *kv.ShardedCoordinator, enabled bool, tracker *kv.ActiveTimestampTracker) { + if enabled { + coordinate.WithAdaptiveVersionCASPrecheck(tracker) + } +} + +func configureProtectedShardNetwork(ctx context.Context, flags *Flags, cfg noderuntime.RuntimeConfig, runtimes []*clusterbootstrap.GroupRuntime, shards *kv.ShardStore, groups map[uint64]*kv.ShardGroup, cleanup *internalutil.CleanupStack) (*clusterbootstrap.BootstrapNetwork, error) { + network, err := clusterbootstrap.ConfigureBootstrapNetwork(ctx, runtimes, shards, groups, cleanup) + if err != nil { + return nil, errors.WithStack(err) + } + if err := configureVersionCAS(flags, cfg, runtimes, groups, cleanup); err != nil { + return nil, err + } + return network, nil +} + +func configureVersionCAS(flags *Flags, cfg noderuntime.RuntimeConfig, runtimes []*clusterbootstrap.GroupRuntime, groups map[uint64]*kv.ShardGroup, cleanup *internalutil.CleanupStack) error { + enabled := flags.consistency.versionCAS + multi := noderuntime.EffectiveMultiDataDirs(cfg.Groups, cfg.Multi) + var conns *kv.GRPCConnCache + if enabled { + conns = clusterbootstrap.NewBootstrapRuntimeConnCache(runtimes) + cleanup.Add(func() { _ = conns.Close() }) + } + for _, rt := range runtimes { + if rt.Spec.ID == noderuntime.DedicatedTSORaftGroupID { + continue + } + dir := noderuntime.GroupDataDir(flags.raft.dataDir, flags.raft.id, rt.Spec.ID, multi) + if err := configureVersionCASGroup(rt, groups[rt.Spec.ID], dir, flags.raft.id, conns); err != nil { + return errors.Wrapf(err, "configure version CAS for group %d", rt.Spec.ID) + } + } + return nil +} + +func unsupportedVersionCASGroup(enabled bool, reason string) error { + if enabled { + return errors.Wrap(kv.ErrVersionCASUnavailable, reason) + } + return nil +} + +func configureVersionCASGroup(rt *clusterbootstrap.GroupRuntime, group *kv.ShardGroup, dir, localID string, conns *kv.GRPCConnCache) error { + // A connection cache is installed only with --versionCAS. + enabled := conns != nil + if rt.BootstrapNetwork == nil || rt.BootstrapPeerConfig == nil { + return unsupportedVersionCASGroup(enabled, "no protected runtime network") + } + rewound, err := etcdraftengine.HasExternalRestoreOrigin(dir) + if err != nil { + return errors.Wrap(err, "check restore origin") + } + if rewound { + return unsupportedVersionCASGroup(enabled, "group descends from an external snapshot restore") + } + // Capability attests replay support for both reserved frames even + // while the replica's own proposal admission is disabled. + if !versionCASStoreCapable(rt.Store) { + return unsupportedVersionCASGroup(enabled, "group lacks replicated metadata storage") + } + native, ok := rt.StateMachine.(interface { + NativeGroupIdentity() raftbootstrap.Identity + VersionRetirementReady() error + }) + if !ok || native.NativeGroupIdentity() != (raftbootstrap.Identity{Cluster: rt.BootstrapPeerConfig.Local.Cluster, Group: rt.Spec.ID}) { + return unsupportedVersionCASGroup(enabled, "FSM is not bound to the protected data group") + } + if err := validateVersionCASRetirementRecovery(rt, native.NativeGroupIdentity(), native.VersionRetirementReady); err != nil { + return err + } + rt.VersionCASCapable = true + if !enabled { + return nil + } + return installVersionCASAdmission(rt, group, localID, conns) +} + +func versionCASStoreCapable(st store.MVCCStore) bool { + _, canApply := st.(store.RaftEntryApplier) + _, hasMetadata := st.(store.RaftControlMetadataStore) + _, hasRetirement := st.(store.VersionRetirementStore) + return canApply && hasMetadata && hasRetirement +} + +func validateVersionCASRetirementRecovery(rt *clusterbootstrap.GroupRuntime, identity raftbootstrap.Identity, ready func() error) error { + if err := ready(); err != nil { + return errors.Wrap(err, "load version retirement before public readiness") + } + return validateVersionRetirementReaderFloor(rt, identity) +} + +func validateVersionRetirementReaderFloor(rt *clusterbootstrap.GroupRuntime, identity raftbootstrap.Identity) error { + ctx := context.Background() + active, err := kv.MigrationVersionRetirementEnabled(ctx, rt.Store) + if err != nil || !active { + return errors.WithStack(err) + } + indexed, ok := rt.Store.(interface{ LastAppliedIndex() (uint64, bool, error) }) + if !ok { + return errors.Wrap(kv.ErrVersionCASUnavailable, "retirement has no durable applied index") + } + index, known, err := indexed.LastAppliedIndex() + if err != nil { + return errors.WithStack(err) + } + if !known { + return errors.Wrap(kv.ErrVersionCASUnavailable, "retirement has no durable applied boundary") + } + policy, err := kv.LoadAppliedBootstrapPolicy(ctx, rt.Store, identity, index) + if err != nil { + return errors.WithStack(err) + } + return validateVersionAdoptionReaderFloor(ctx, rt.Store, policy.Version) +} + +func validateVersionAdoptionReaderFloor(ctx context.Context, st store.MVCCStore, policyVersion uint32) error { + adopting, err := kv.MigrationVersionAdoptionEnabled(ctx, st) + if err != nil { + return errors.WithStack(err) + } + if policyVersion < raftbootstrap.PolicyRetirementVersion || (adopting && policyVersion != raftbootstrap.PolicyAdoptionVersion) { + return errors.Wrap(kv.ErrVersionCASUnavailable, "retirement reader floor was downgraded") + } + return nil +} + +func installVersionCASAdmission(rt *clusterbootstrap.GroupRuntime, group *kv.ShardGroup, localID string, conns *kv.GRPCConnCache) error { + if group == nil { + return errors.Wrap(kv.ErrVersionCASUnavailable, "data group is not configured") + } + proxy, ok := group.Txn.(*kv.LeaderProxy) + if !ok { + return errors.Wrap(kv.ErrVersionCASUnavailable, "data group has no leader proxy") + } + gate := versionCASGate{ + engine: group.Engine, + proposer: group.Proposer(), + fence: func(ctx context.Context) (bool, error) { return kv.CommitTSFenceEnabled(ctx, rt.Store) }, + identity: func(ctx context.Context) (bool, error) { return kv.MigrationVersionAdoptionEnabled(ctx, rt.Store) }, + activation: make(chan struct{}, 1), + localID: localID, + checkPeer: versionCASPeerCheck(rt, conns), + stableConfiguration: func(index uint64) bool { + return rt.BootstrapNetwork.HasStableConfiguration(rt.Spec.ID, index) + }, + } + rt.VersionCASAdmission = gate.admit + proxy.ConfigureVersionCASAdmission(gate.admit) + group.ConfigureVersionReadAdmission(gate.admitRead) + return nil +} + +type versionCASGate struct { + engine raftengine.Engine + proposer raftengine.Proposer + fence func(context.Context) (bool, error) + identity func(context.Context) (bool, error) + activation chan struct{} + localID string + checkPeer func(context.Context, raftengine.Server, uint64) error + stableConfiguration func(uint64) bool +} + +func (g versionCASGate) admit(ctx context.Context) (context.Context, error) { + proof, err := g.prove(ctx) + if err != nil { + return nil, err + } + if err := g.activate(proof); err != nil { + return nil, err + } + return proof, nil +} + +func (g versionCASGate) admitRead(ctx context.Context) error { + admitted, err := g.admit(ctx) + if err != nil { + return err + } + proof, _ := raftengine.VersionCASProposalProof(admitted) + st := g.engine.Status() + if !g.configurationReady(st) || st.Term != proof.Term || st.ConfigurationIndex != proof.ConfigurationIndex { + return errors.Wrap(kv.ErrVersionCASUnavailable, "membership or leadership changed during token admission") + } + return nil +} + +// The only maintenance proposal is the first operation's sticky marker. +// Recheck under the per-group slot to avoid a burst of duplicate proposals. +func (g versionCASGate) activate(ctx context.Context) error { + active, err := g.identity(ctx) + if err != nil { + return errors.Join(kv.ErrVersionCASUnavailable, err) + } + if active { + return nil + } + select { + case g.activation <- struct{}{}: + defer func() { <-g.activation }() + case <-ctx.Done(): + return errors.Join(kv.ErrVersionCASUnavailable, ctx.Err()) + } + return g.proposeActivationIfNeeded(ctx) +} + +func (g versionCASGate) proposeActivationIfNeeded(ctx context.Context) error { + active, err := g.identity(ctx) + if err != nil { + return errors.Join(kv.ErrVersionCASUnavailable, err) + } + if active { + return nil + } + result, err := g.proposer.Propose(ctx, kv.EncodeMigrationVersionIdentityActivation()) + if err != nil { + return errors.Wrap(errors.Join(kv.ErrVersionCASUnavailable, err), "activate migration version identity") + } + if result == nil || result.CommitIndex == 0 || result.Response != nil { + return errors.Wrap(kv.ErrVersionCASUnavailable, "migration version identity activation did not apply") + } + active, err = g.identity(ctx) + if err != nil || !active { + return errors.Wrap(errors.Join(kv.ErrVersionCASUnavailable, err), "migration version identity activation is absent") + } + return nil +} + +func (g versionCASGate) requireCommitFence(ctx context.Context) error { + active, err := g.fence(ctx) + if err != nil || !active { + return errors.Wrap(errors.Join(kv.ErrVersionCASUnavailable, err), "commit-ts fence is inactive") + } + return nil +} + +func (g versionCASGate) prove(ctx context.Context) (context.Context, error) { + st := g.engine.Status() + if !g.configurationReady(st) { + return nil, errors.Wrap(kv.ErrVersionCASUnavailable, "membership or leadership is unsettled") + } + if err := g.requireCommitFence(ctx); err != nil { + return nil, err + } + cfg, err := g.engine.Configuration(ctx) + if err != nil { + return nil, errors.Join(kv.ErrVersionCASUnavailable, err) + } + probes, cancel := context.WithTimeout(ctx, versionCASProbeTimeout) + defer cancel() + if err := g.checkConfiguration(probes, cfg, st.ConfigurationIndex); err != nil { + return nil, err + } + return raftengine.WithVersionCASProof(ctx, raftengine.VersionCASProof{ + Term: st.Term, ConfigurationIndex: st.ConfigurationIndex, + }), nil +} + +func (g versionCASGate) configurationReady(st raftengine.Status) bool { + return st.State == raftengine.StateLeader && st.Leader.ID == g.localID && st.Term != 0 && + st.ConfigurationIndex != 0 && !st.PendingConfChange && g.stableConfiguration(st.ConfigurationIndex) +} + +func (g versionCASGate) checkConfiguration(ctx context.Context, cfg raftengine.Configuration, index uint64) error { + probes, ctx := errgroup.WithContext(ctx) + localVoter := false + for _, peer := range cfg.Servers { + if peer.ID == g.localID && peer.Suffrage == etcdraftengine.SuffrageVoter && peer.Address != "" { + localVoter = true + continue + } + probes.Go(func() error { return g.checkPeer(ctx, peer, index) }) + } + err := probes.Wait() + if !localVoter || err != nil { + return errors.Wrap(errors.Join(kv.ErrVersionCASUnavailable, err), "replica capability check failed") + } + return nil +} + +func versionCASPeerCheck(rt *clusterbootstrap.GroupRuntime, conns *kv.GRPCConnCache) func(context.Context, raftengine.Server, uint64) error { + return func(ctx context.Context, peer raftengine.Server, index uint64) error { + if !versionCASPeerProvisioned(rt, peer) { + return errors.Newf("replica %q at %q lacks a protected identity", peer.ID, peer.Address) + } + conn, err := conns.ConnFor(peer.Address) + if err != nil { + return errors.Wrapf(err, "connect to replica %s", peer.ID) + } + status, err := pb.NewRaftAdminClient(conn).Status(ctx, &pb.RaftAdminStatusRequest{}, grpc.WaitForReady(false)) + if err != nil { + return errors.Wrapf(err, "check replica %s", peer.ID) + } + if !versionCASPeerStatusReady(status, index) { + return errors.Newf("replica %s lacks version CAS capability at configuration %d", peer.ID, index) + } + return nil + } +} + +func versionCASPeerStatusReady(status *pb.RaftAdminStatusResponse, index uint64) bool { + return status.GetSupportsReplicatedCatalogCas() && status.GetSupportsVersionRetirement() && status.GetSupportsVersionAdoption() && + !status.GetPendingConfChange() && status.GetConfigurationIndex() == index +} + +func versionCASPeerProvisioned(rt *clusterbootstrap.GroupRuntime, peer raftengine.Server) bool { + for _, provision := range rt.BootstrapPeerConfig.Provisions { + if provision.Node.Member != etcdraftengine.DeriveNodeID(peer.ID) || provision.Node.Address != peer.Address { + continue + } + for _, group := range provision.Groups { + if group == rt.Spec.ID { + return true + } + } + } + return false +} diff --git a/internal/server/version_cas_jepsen_test.go b/internal/server/version_cas_jepsen_test.go new file mode 100644 index 000000000..925bd6c8f --- /dev/null +++ b/internal/server/version_cas_jepsen_test.go @@ -0,0 +1,130 @@ +package server + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/clusterbootstrap" + "github.com/bootjp/elastickv/kv" + "github.com/stretchr/testify/require" +) + +// This opt-in test needs Leiningen and the JSON-line client. It exercises the +// public API on three real protected voters, not the single-voter RPC fixture. +func TestVersionCASJepsenStress(t *testing.T) { + secondsText := os.Getenv("ELASTICKV_CAS_JEPSEN_SECONDS") + if secondsText == "" { + t.Skip("set ELASTICKV_CAS_JEPSEN_SECONDS and ELASTICKV_CAS_JEPSEN_CLIENT to run") + } + seconds, err := strconv.Atoi(secondsText) + require.NoError(t, err) + require.GreaterOrEqual(t, seconds, 30) + require.LessOrEqual(t, seconds, 1800) + client := os.Getenv("ELASTICKV_CAS_JEPSEN_CLIENT") + require.NotEmpty(t, client) + client, err = filepath.Abs(client) + require.NoError(t, err) + lein, err := exec.LookPath("lein") + require.NoError(t, err) + t.Setenv("ELASTICKV_RAFT_SNAPSHOT_COUNT", "1") + + base := t.TempDir() + identities := multiEnablementIdentities(t, base) + processes := startVersionCASStressCluster(t, base, identities) + defer multiEnablementStop(t, processes) + ctx, cancel := context.WithTimeout(t.Context(), time.Duration(seconds+180)*time.Second) + defer cancel() + ports := make([]string, 0, len(identities)) + for _, identity := range identities { + ports = append(ports, strings.TrimPrefix(identity.address, "127.0.0.1:")) + } + args := []string{"-o"} + if source := os.Getenv("ELASTICKV_JEPSEN_REDIS_SOURCE"); source != "" { + args = append(args, "update-in", ":source-paths", "conj", strconv.Quote(source), "--") + } + args = append(args, "run", "-m", "elastickv.grpc-workload", "--local", "--host", "127.0.0.1", + "--nodes", "n1,n2,n3", "--grpc-ports", strings.Join(ports, ","), "--grpc-api", "version-cas", + "--grpc-tls-ca-file", identities[0].raw.CA, "--grpc-client-bin", client, + "--concurrency", "6", "--rate", "10", "--time-limit", secondsText) + command := exec.CommandContext(ctx, lein, args...) + command.Dir = filepath.Join("..", "..", "jepsen") + command.Stdout, command.Stderr = os.Stdout, os.Stderr + t.Logf("Jepsen parameters: duration=%ds rate=10 concurrency=6 voters=3 TLS=true; histories: jepsen/store", seconds) + require.NoError(t, command.Start()) + waited := false + defer func() { + if !waited { + _ = command.Process.Kill() + _ = command.Wait() + } + }() + // Leave startup and seed time before stopping a follower. Admission must + // reject uncertain capability evidence while it is down and recover later. + timer := time.NewTimer(time.Duration(seconds/2) * time.Second) + defer timer.Stop() + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-timer.C: + } + leader := multiEnablementLeader(t, processes) + for i, process := range processes { + if process == leader { + continue + } + t.Logf("restarting follower %s with the same WAL and Pebble data", identities[i].id) + multiEnablementStop(t, []*multiEnablementProcess{process}) + time.Sleep(2 * time.Second) + servers, err := leader.runtime.Engine.Configuration(ctx) + require.NoError(t, err) + processes[i] = multiEnablementStartMember(t, base, identities[i], servers.Servers, true) + require.Eventually(t, processes[i].runtime.PublicReady, bootstrapE2EWaitTimeout, 10*time.Millisecond) + break + } + err = command.Wait() + waited = true + require.NoError(t, err, "Jepsen must return valid=true, not false or unknown") + for _, process := range processes { + require.Eventually(t, process.runtime.PublicReady, bootstrapE2EWaitTimeout, 10*time.Millisecond) + } +} + +func startVersionCASStressCluster(t *testing.T, base string, identities []*multiEnablementIdentity) []*multiEnablementProcess { + t.Helper() + legacy := multiEnablementStart(t, base, identities, false) + multiEnablementPopulate(t, legacy) + multiEnablementStop(t, legacy) + manifest := multiEnablementBaseline(t, identities) + acks := make([][]byte, 0, len(identities)) + for _, identity := range identities { + acks = append(acks, multiEnablementPrepareAck(t, identity, manifest)) + } + payload, err := clusterbootstrap.AssembleBootstrapActivation(manifest, manifest.BaselineContext, acks) + require.NoError(t, err) + activationPath := filepath.Join(t.TempDir(), "activation.bin") + require.NoError(t, os.WriteFile(activationPath, payload, 0o600)) + for _, identity := range identities { + identity.raw.ActivationFile = activationPath + multiEnablementWriteConfig(t, identity) + } + processes := multiEnablementStart(t, base, identities, true) + leader := multiEnablementLeader(t, processes) + clusterbootstrap.StartBootstrapActivationWorkers(leader.ctx, leader.eg, + []*clusterbootstrap.GroupRuntime{leader.runtime}, map[uint64]*kv.ShardGroup{1: leader.shard}) + multiEnablementAssertActivePolicy(t, processes, manifest) + ctx, cancel := context.WithTimeout(t.Context(), bootstrapE2EWaitTimeout) + defer cancel() + _, err = leader.coordinate.Dispatch(ctx, &kv.OperationGroup[kv.OP]{Elems: []*kv.Elem[kv.OP]{ + {Op: kv.Put, Key: []byte("protected-key"), Value: []byte("replicated-protected")}, + }}) + require.NoError(t, err) + multiEnablementVersionCAS(t, processes, leader) + t.Logf("protected CAS admission active on %d voters", len(processes)) + return processes +} diff --git a/internal/server/version_cas_recovery_test.go b/internal/server/version_cas_recovery_test.go new file mode 100644 index 000000000..ae0e6e892 --- /dev/null +++ b/internal/server/version_cas_recovery_test.go @@ -0,0 +1,51 @@ +package server + +import ( + "testing" + "time" + + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/kv" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestVersionCASReaderFloorColdRestart(t *testing.T) { + t.Setenv("ELASTICKV_RAFT_SNAPSHOT_COUNT", "1") + base := t.TempDir() + identities := multiEnablementIdentities(t, base) + processes := startVersionCASStressCluster(t, base, identities) + defer func() { multiEnablementStop(t, processes) }() + leader := multiEnablementLeader(t, processes) + before, err := store.GetVersionAt(t.Context(), leader.runtime.Store, []byte("protected-key"), ^uint64(0)) + require.NoError(t, err) + for _, process := range processes { + require.Eventually(t, func() bool { + return process.runtime.Engine.Status().LastSnapshotIndex >= process.runtime.Engine.Status().AppliedIndex + }, bootstrapE2EWaitTimeout, 10*time.Millisecond) + } + multiEnablementStop(t, processes) + processes = multiEnablementStart(t, base, identities, true) + for _, process := range processes { + require.Eventually(t, process.runtime.PublicReady, bootstrapE2EWaitTimeout, 10*time.Millisecond) + native, ok := process.runtime.StateMachine.(interface{ NativeGroupIdentity() raftbootstrap.Identity }) + require.True(t, ok) + // The restarted owner is live: its status and durable projection can + // advance between reads. Require a consistent observed boundary. + var policy raftbootstrap.PolicyRecord + require.EventuallyWithT(t, func(c *assert.CollectT) { + var policyErr error + policy, policyErr = kv.LoadAppliedBootstrapPolicy(t.Context(), process.runtime.Store, + native.NativeGroupIdentity(), process.runtime.Engine.Status().AppliedIndex) + assert.NoError(c, policyErr) + }, bootstrapE2EWaitTimeout, bootstrapE2EWaitInterval) + require.Equal(t, raftbootstrap.PolicyAdoptionVersion, policy.Version) + active, err := kv.MigrationVersionRetirementEnabled(t.Context(), process.runtime.Store) + require.NoError(t, err) + require.True(t, active) + after, err := store.GetVersionAt(t.Context(), process.runtime.Store, []byte("protected-key"), ^uint64(0)) + require.NoError(t, err) + require.Equal(t, before, after) + } +} diff --git a/internal/server/version_cas_retirement_test.go b/internal/server/version_cas_retirement_test.go new file mode 100644 index 000000000..345835c4e --- /dev/null +++ b/internal/server/version_cas_retirement_test.go @@ -0,0 +1,27 @@ +package server + +import ( + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" +) + +func TestVersionCASPeerRequiresRetirementCapability(t *testing.T) { + cases := map[string]func(*pb.RaftAdminStatusResponse){ + "missing CAS": func(s *pb.RaftAdminStatusResponse) { s.SupportsReplicatedCatalogCas = false }, + "old binary": func(s *pb.RaftAdminStatusResponse) { s.SupportsVersionRetirement = false }, + "retirement-only binary": func(s *pb.RaftAdminStatusResponse) { s.SupportsVersionAdoption = false }, + "wrong configuration": func(s *pb.RaftAdminStatusResponse) { s.ConfigurationIndex++ }, + "pending membership": func(s *pb.RaftAdminStatusResponse) { s.PendingConfChange = true }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + status := &pb.RaftAdminStatusResponse{SupportsReplicatedCatalogCas: true, SupportsVersionRetirement: true, SupportsVersionAdoption: true, ConfigurationIndex: 9} + require.True(t, versionCASPeerStatusReady(status, 9)) + mutate(status) + require.False(t, versionCASPeerStatusReady(status, 9)) + }) + } + require.False(t, versionCASPeerStatusReady(nil, 9)) +} diff --git a/internal/server/version_cas_test.go b/internal/server/version_cas_test.go new file mode 100644 index 000000000..97099cf60 --- /dev/null +++ b/internal/server/version_cas_test.go @@ -0,0 +1,182 @@ +package server + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/bootjp/elastickv/internal/clusterbootstrap" + "github.com/bootjp/elastickv/internal/raftadmission" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/kv" + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func TestVersionCASStartupRequiresCommitTSFence(t *testing.T) { + flags := defaultServerFlags() + require.False(t, flags.consistency.versionCAS) + flags.consistency.versionCAS = true + _, _, _, _, err := resolveValidatedRuntimeInputs(flags) + require.ErrorContains(t, err, "versionCAS requires --commitTSFence") +} + +func TestVersionCASRejectsExternalRestoreOrigin(t *testing.T) { + dir := t.TempDir() + marker := []byte(`{"version":1,"index":3,"term":2,"completed":true,"fsm_payload_sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`) + require.NoError(t, os.WriteFile(filepath.Join(dir, "external-restore-origin.json"), marker, 0o600)) + rt := &clusterbootstrap.GroupRuntime{ + BootstrapNetwork: &clusterbootstrap.BootstrapNetwork{}, + BootstrapPeerConfig: &clusterbootstrap.BootstrapPeerConfig{}, + } + + conns := kv.NewGRPCConnCache(nil) + defer func() { require.NoError(t, conns.Close()) }() + err := configureVersionCASGroup(rt, nil, dir, "member", conns) + require.ErrorIs(t, err, kv.ErrVersionCASUnavailable) + require.ErrorContains(t, err, "external snapshot restore") + require.False(t, rt.VersionCASCapable) + + require.NoError(t, configureVersionCASGroup(rt, nil, dir, "member", nil)) + require.False(t, rt.VersionCASCapable) + require.Nil(t, rt.VersionCASAdmission) +} + +type versionCASGateEngine struct { + raftengine.Engine + status raftengine.Status + config raftengine.Configuration +} + +func (e versionCASGateEngine) Status() raftengine.Status { return e.status } + +func (e versionCASGateEngine) Configuration(context.Context) (raftengine.Configuration, error) { + return e.config, nil +} + +func TestVersionCASGateRequiresFenceAndEveryReplica(t *testing.T) { + engine := &versionCASGateEngine{ + status: raftengine.Status{ + State: raftengine.StateLeader, Term: 12, ConfigurationIndex: 7, + Leader: raftengine.LeaderInfo{ID: "leader"}, + }, + config: raftengine.Configuration{Servers: []raftengine.Server{ + {ID: "leader", Address: "leader", Suffrage: "voter"}, + {ID: "voter", Address: "voter", Suffrage: "voter"}, + {ID: "learner", Address: "learner", Suffrage: "learner"}, + }}, + } + active := false + g := versionCASGate{ + engine: engine, localID: "leader", + fence: func(context.Context) (bool, error) { return active, nil }, + identity: func(context.Context) (bool, error) { return true, nil }, + stableConfiguration: func(uint64) bool { return true }, + checkPeer: func(_ context.Context, peer raftengine.Server, index uint64) error { + if peer.ID == "learner" { + return errors.New("learner uses an older binary") + } + return nil + }, + } + _, err := g.admit(t.Context()) + require.ErrorContains(t, err, "commit-ts fence is inactive") + active = true + _, err = g.admit(t.Context()) + require.ErrorIs(t, err, kv.ErrVersionCASUnavailable) + require.ErrorContains(t, err, "older binary") + checked := make(chan string, 2) + g.checkPeer = func(_ context.Context, peer raftengine.Server, index uint64) error { + if index != 7 { + return errors.New("wrong configuration index") + } + checked <- peer.ID + return nil + } + ctx, err := g.admit(t.Context()) + require.NoError(t, err) + require.ElementsMatch(t, []string{"voter", "learner"}, []string{<-checked, <-checked}) + proof, ok := raftengine.VersionCASProposalProof(ctx) + require.True(t, ok) + require.Equal(t, raftengine.VersionCASProof{Term: 12, ConfigurationIndex: 7}, proof) + engine.status.PendingConfChange = true + _, err = g.admit(t.Context()) + require.ErrorIs(t, err, kv.ErrVersionCASUnavailable) + engine.status.PendingConfChange = false + g.stableConfiguration = func(uint64) bool { return false } + _, err = g.admit(t.Context()) + require.ErrorIs(t, err, kv.ErrVersionCASUnavailable) +} + +func multiEnablementVersionCAS(t *testing.T, processes []*multiEnablementProcess, leader *multiEnablementProcess) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), bootstrapE2EWaitTimeout) + defer cancel() + const key = "protected-key" + oldVersion, found, err := leader.runtime.Store.LatestCommitTS(ctx, []byte(key)) + require.NoError(t, err) + require.True(t, found) + attempt := func(process *multiEnablementProcess) (*kv.CoordinateResponse, error) { + return process.coordinate.Dispatch(ctx, &kv.OperationGroup[kv.OP]{IsTxn: true, Elems: []*kv.Elem[kv.OP]{ + {Op: kv.CompareAndSwap, Key: []byte(key), Value: []byte("cas-on-three-replicas"), ExpectedCommitTS: oldVersion}, + }}) + } + _, err = attempt(leader) + require.ErrorIs(t, err, kv.ErrVersionCASUnavailable, "configured feature is still off until fence apply") + owned, op, err := leader.domain.Admission.Begin(ctx, raftadmission.Data) + require.NoError(t, err) + defer op.CancelAndJoin() + result, err := leader.shard.Proposer().Propose(owned, kv.EncodeCommitTSFenceActivation()) + require.NoError(t, clusterbootstrap.FinishBootstrapIngress(op, err)) + require.Nil(t, result.Response) + + var follower *multiEnablementProcess + for _, process := range processes { + require.Eventually(t, func() bool { + active, readErr := kv.CommitTSFenceEnabled(ctx, process.runtime.Store) + return readErr == nil && active && process.runtime.PublicReady() + }, bootstrapE2EWaitTimeout, clusterbootstrap.BootstrapReadinessRetryInterval) + if process != leader { + follower = process + } + } + require.NotNil(t, follower) + conns := clusterbootstrap.NewBootstrapRuntimeConnCache([]*clusterbootstrap.GroupRuntime{follower.runtime}) + defer func() { require.NoError(t, conns.Close()) }() + conn, err := conns.ConnFor(leader.runtime.Spec.Address) + require.NoError(t, err) + value, err := pb.NewTransactionalKVClient(conn).Get(ctx, &pb.GetRequest{Key: []byte(key), NeedCommitTs: true}) + require.NoError(t, err, "the first token read activates migration identity protection") + require.Equal(t, oldVersion, value.GetCommitTs()) + require.Equal(t, []byte("replicated-protected"), value.GetValue()) + for _, process := range processes { + require.Eventually(t, func() bool { + active, readErr := kv.MigrationVersionIdentityEnabled(ctx, process.runtime.Store) + return readErr == nil && active && process.runtime.PublicReady() + }, bootstrapE2EWaitTimeout, clusterbootstrap.BootstrapReadinessRetryInterval) + } + + leaderConns := clusterbootstrap.NewBootstrapRuntimeConnCache([]*clusterbootstrap.GroupRuntime{leader.runtime}) + defer func() { require.NoError(t, leaderConns.Close()) }() + followerConn, err := leaderConns.ConnFor(follower.runtime.Spec.Address) + require.NoError(t, err) + res, err := pb.NewTransactionalKVClient(followerConn).CompareAndSwap(ctx, &pb.CompareAndSwapRequest{ + Key: []byte(key), ExpectedCommitTs: value.GetCommitTs(), Value: []byte("cas-on-three-replicas"), + }) + require.NoError(t, err, "public follower ingress reaches the admitted leader over pinned TLS") + require.Greater(t, res.GetNewCommitTs(), oldVersion) + + for _, process := range processes { + multiEnablementReplicatedRead(t, process, key, "cas-on-three-replicas") + } + _, err = attempt(leader) + require.True(t, kv.IsCertifiedCASMismatch(err), "old token returns a certified mismatch: %v", err) + require.True(t, kv.IsCertifiedCASPrecheckMismatch(err), "the startup-wired adaptive path rejects before proposal") + res, err = pb.NewTransactionalKVClient(followerConn).CompareAndSwap(ctx, &pb.CompareAndSwapRequest{ + Key: []byte(key), ExpectedCommitTs: oldVersion, Value: []byte("must-not-commit"), + }) + require.NoError(t, err, "a pre-submission mismatch survives dedicated follower forwarding") + require.True(t, res.GetMismatch()) +} diff --git a/internal/testutil/cmd/importguard/layers.go b/internal/testutil/cmd/importguard/layers.go index a78ea8a86..9fabac33b 100644 --- a/internal/testutil/cmd/importguard/layers.go +++ b/internal/testutil/cmd/importguard/layers.go @@ -142,6 +142,8 @@ var layerRules = []layerRule{ var importAllowlists = []layerRule{ {Dir: "jepsen/tools/write-skew-wal", Only: []string{"proto"}, Why: "offline Jepsen WAL diagnostics decode protocol records without depending on server wiring"}, {Dir: "internal/loadtest", Exact: true, Only: []string{"proto"}, Why: "the production load client uses only the public wire API"}, + {Dir: "internal/casbenchmark", Exact: true, Only: []string{"adapter", "internal/casbenchmark/meter", "kv", "proto", "store"}, Why: "the isolated experimental frontend composes the real fenced read and transaction APIs, never production wiring"}, + {Dir: "internal/casbenchmark/meter", Deny: []string{anyModulePackage}, Why: "explicit benchmark instrumentation is a leaf over runtime, gRPC and Pebble VFS"}, // Data plane, bottom up. {Dir: "internal/encryption", Only: []string{}, Why: "encryption is a library over its own KEK and wire subpackages"}, {Dir: "store", Only: []string{"internal/encryption", "internal/raftbootstrap", "internal/s3keys"}, Why: "MVCC storage is the bottom of the data plane"}, @@ -229,6 +231,7 @@ var coverageExempt = []string{".", "cmd", "third_party"} // restrictedPackages may only be imported at the binary wiring edge. var restrictedPackages = []restrictedPackage{ + {Pkg: "internal/casbenchmark", AllowedFrom: []string{"cmd/casbench"}, Why: "experimental services and instrumentation are selected only by the explicit benchmark tool; normal server and data-plane source must not import them"}, { Pkg: "internal/raftengine/etcd", AllowedFrom: []string{"internal/server", "cmd", "internal/raftengine", "internal/snapshotoffload", "internal/encryptionwiring", "internal/clusterbootstrap"}, diff --git a/internal/testutil/cmd/importguard/layers_test.go b/internal/testutil/cmd/importguard/layers_test.go index 28b696a95..708ff1e27 100644 --- a/internal/testutil/cmd/importguard/layers_test.go +++ b/internal/testutil/cmd/importguard/layers_test.go @@ -20,6 +20,15 @@ func TestCheckLayering(t *testing.T) { {"stdlib is ignored", "store", "fmt", false}, {"load client uses wire API", "internal/loadtest", m + "proto", false}, {"load client cannot call data plane", "internal/loadtest", m + "kv", true}, + {"benchmark CLI may use its frontend", "cmd/casbench", m + "internal/casbenchmark", false}, + {"benchmark CLI may use its meter", "cmd/casbench", m + "internal/casbenchmark/meter", false}, + {"normal server must not register benchmark services", "internal/server", m + "internal/casbenchmark", true}, + {"normal binary must not import benchmark services", ".", m + "internal/casbenchmark", true}, + {"normal storage must not import benchmark instrumentation", "store", m + "internal/casbenchmark/meter", true}, + {"normal KV must not import benchmark instrumentation", "kv", m + "internal/casbenchmark/meter", true}, + {"benchmark frontend may use public admission interfaces", "internal/casbenchmark", m + "adapter", false}, + {"benchmark frontend must not import server wiring", "internal/casbenchmark", m + "internal/server", true}, + {"benchmark meter is a leaf", "internal/casbenchmark/meter", m + "proto", true}, {"third party is ignored", "store", "github.com/cockroachdb/pebble/v2", false}, {"store below kv", "store", m + "kv", true}, {"store subpackage below kv", "store/sub", m + "kv", true}, @@ -146,6 +155,9 @@ func TestCheckCoverage(t *testing.T) { {"deny rule covers subpackages", "kv/sub", true}, {"allowlist", "internal/nodeauth", true}, {"production load client", "internal/loadtest", true}, + {"experimental frontend", "internal/casbenchmark", true}, + {"experimental meter", "internal/casbenchmark/meter", true}, + {"unregistered experimental package", "internal/casbenchmark/unregistered", false}, {"exact rule does not cover subpackages", "distribution/newsub", false}, {"exact allowlist does not cover subpackages", "internal/newpkg", false}, {"root is checked by rootImports", ".", true}, diff --git a/jepsen/src/elastickv/grpc_workload.clj b/jepsen/src/elastickv/grpc_workload.clj index 28a674319..36ad4fb14 100644 --- a/jepsen/src/elastickv/grpc_workload.clj +++ b/jepsen/src/elastickv/grpc_workload.clj @@ -5,6 +5,7 @@ [clojure.java.io :as io] [clojure.string :as str] [elastickv.cli :as cli] + [elastickv.version-cas :as version-cas] [elastickv.elle-checker :as elle] [elastickv.redis-workload :as redis] [elastickv.s3-workload :as s3] @@ -87,22 +88,30 @@ (throw (ex-info "Use hosted-fault-workload for managed gRPC fault tests" {}))) (let [ports (or (:node->port opts) (zipmap (:nodes opts) (repeat (or (:grpc-port opts) 50051)))) concurrency (or (:concurrency opts) 6) - workload (grpc-register-workload (assoc opts :node->port ports))] + cas? (= :version-cas (:grpc-api opts)) + workload (if cas? + (version-cas/workload + (->GRPCClient ports :transactional + (or (:grpc-client-bin opts) "/tmp/jepsen-grpc-client") nil nil nil) + exchange! opts) + (grpc-register-workload (assoc opts :node->port ports)))] (when-not (and (pos? concurrency) (even? concurrency)) (throw (ex-info "gRPC concurrency must be positive and divisible by two" {}))) (merge (redis/elastickv-redis-test opts) workload {:name (str "elastickv-grpc-" (name (or (:grpc-api opts) :raw))) - :grpc-host (:grpc-host opts) + :grpc-host (:grpc-host opts) :grpc-tls-ca-file (:grpc-tls-ca-file opts) :concurrency concurrency :wrap-generator nil :final-generator nil - :generator (->> (:generator workload) + :generator (if cas? (gen/clients (:generator workload)) + (->> (:generator workload) (gen/stagger (/ (double (or (:rate opts) 5)))) - (gen/time-limit (or (:time-limit opts) 30)))}))) + (gen/time-limit (or (:time-limit opts) 30))))}))) (def grpc-cli-opts [[nil "--grpc-ports PORTS" "Comma-separated public gRPC ports." :parse-fn #(mapv (fn [port] (Integer/parseInt port)) (str/split % #","))] [nil "--concurrency N" "Workers, divisible by two." :default 6 :parse-fn #(Integer/parseInt %)] - [nil "--grpc-api API" "raw or transactional" :default :raw :parse-fn keyword] + [nil "--grpc-tls-ca-file PATH" "CA certificate for the public gRPC endpoints."] + [nil "--grpc-api API" "raw, transactional, or version-cas" :default :raw :parse-fn keyword] [nil "--grpc-client-bin PATH" "JSON-line gRPC helper binary." :default "/tmp/jepsen-grpc-client"]]) (defn prepare-opts [options] diff --git a/jepsen/src/elastickv/history_windows.clj b/jepsen/src/elastickv/history_windows.clj index 467c68daa..87883b0af 100644 --- a/jepsen/src/elastickv/history_windows.clj +++ b/jepsen/src/elastickv/history_windows.clj @@ -23,30 +23,46 @@ (into done (vals pending)))) (def ^:dynamic *candidate-budget* 50000) +(def ^:dynamic ^:private *remaining-candidates* nil) -(defn serial-witness +(defn consume-candidate! [] + (when (neg? (vswap! *remaining-candidates* dec)) + (throw (ex-info "Candidate budget exhausted" {:reason ::budget})))) + +(defn with-shared-budget + "Nested searches and validation share one candidate limit." + [search] + (binding [*remaining-candidates* (or *remaining-candidates* (volatile! *candidate-budget*))] + (try (search) + (catch clojure.lang.ExceptionInfo e + (if (= ::budget (:reason (ex-data e))) :unknown (throw e)))))) + +(defn serial-execution "Search for a single execution of all mandatory actions. The earliest outstanding completion bounds the next choice. Optional actions have an open deadline and may be omitted once every mandatory action is satisfied. - advance returns the next [state remaining-actions], or nil on a mismatch." + Return the complete action-ID path, false, or :unknown. advance returns + the next [state remaining-actions], or nil on a mismatch." [actions advance] - (let [initial (into (sorted-map) (map (fn [op] [[(:end op) (:start op)] op]) actions)) - budget (volatile! *candidate-budget*)] - (try - (loop [todo (list [{} initial]), visited #{}] - (if-let [[state remaining] (first todo)] - (if (contains? visited [state remaining]) - (recur (rest todo) visited) - (let [deadline (ffirst (first remaining))] - (if (or (nil? deadline) (= Long/MAX_VALUE deadline)) - true - (let [branches (keep (fn [[_ op :as candidate]] - (when (<= (:start op) deadline) - (when (neg? (vswap! budget dec)) - (throw (ex-info "Candidate budget exhausted" {:reason ::budget}))) - (advance state remaining candidate))) - remaining)] - (recur (concat branches (rest todo)) (conj visited [state remaining])))))) - false)) - (catch clojure.lang.ExceptionInfo e - (if (= ::budget (:reason (ex-data e))) :unknown (throw e)))))) + (let [initial (into (sorted-map) (map (fn [op] [[(:end op) (:start op)] op]) actions))] + (with-shared-budget + (fn [] + (loop [todo (list [{} initial []]), visited #{}] + (if-let [[state remaining path] (first todo)] + (if (contains? visited [state remaining]) + (recur (rest todo) visited) + (let [deadline (ffirst (first remaining))] + (if (or (nil? deadline) (= Long/MAX_VALUE deadline)) + path + (let [branches (keep (fn [[id op :as candidate]] + (when (<= (:start op) deadline) + (consume-candidate!) + (when-let [[next-state next-remaining] (advance state remaining candidate)] + [next-state next-remaining (conj path id)]))) + remaining)] + (recur (concat branches (rest todo)) (conj visited [state remaining])))))) + false)))))) + +(defn serial-witness [actions advance] + (let [result (serial-execution actions advance)] + (if (vector? result) true result))) diff --git a/jepsen/src/elastickv/redis_zset_safety_workload.clj b/jepsen/src/elastickv/redis_zset_safety_workload.clj index b8657d6dd..d98e7e239 100644 --- a/jepsen/src/elastickv/redis_zset_safety_workload.clj +++ b/jepsen/src/elastickv/redis_zset_safety_workload.clj @@ -1364,6 +1364,10 @@ next-db (cond (:read op) (when (range-matches? db (:read op)) db) (and (= :zrem (:f op)) (not= :ok (:type op))) (dissoc db member) + (and (= :zincrby (:f op)) (= :ok (:type op)) + (some? (:score op)) + (not (== (+ (double (get db member 0.0)) (:delta op)) + (double (:score op))))) nil :else (let [score (get db member) st (if (some? score) {:present? true :score score} absent-state)] @@ -1371,13 +1375,75 @@ (if (:present? after) (assoc db member (:score after)) (dissoc db member)))))] (when next-db [next-db (dissoc remaining id)]))) +(defn- zset-action-id [op] [(:end op) (:start op)]) + +(defn- zset-member-guide [actions member] + (let [local (for [op actions :when (or (= member (:member op)) (:read op))] + (if (:read op) + (update-in op (if (= :zrange-all (get-in op [:read :f])) + [:read :value] [:read :value :members]) + #(filterv (fn [[m _]] (= member m)) %)) + op))] + (windows/serial-execution local advance-zset))) + +(defn- zset-guide-paths [actions] + (reduce (fn [paths member] + (let [path (zset-member-guide actions member)] + (if (vector? path) (conj paths path) (reduced nil)))) + [] (sort (set (keep :member actions))))) + +(defn- advance-guided-zset [db remaining predecessors deadline] + (first (keep (fn [[id op :as candidate]] + (when (and (<= (:start op) deadline) (empty? (get predecessors id))) + (windows/consume-candidate!) + (when-let [[next-db _] (advance-zset db remaining candidate)] + [id next-db]))) remaining))) + +(defn- zset-guide-edges [all path] + (let [read? #(boolean (:read (get all %))) + groups (partition-by read? path)] + ;; Reads without an intervening mutation commute in this projection. + ;; Retain both mutation boundaries for EVERY read, not an arbitrary + ;; read-to-read order that can cycle against another member's guide. + (concat (mapcat #(when-not (read? (first %)) (partition 2 1 %)) groups) + (for [[before after] (partition 2 1 groups) + a (if (read? (first before)) before [(last before)]) + b (if (read? (first after)) after [(first after)])] + [a b])))) + +(defn- verify-zset-guides + "A member projection is never a verdict. Replay ONE shared execution of + every mandatory read and mutation, including reads covering many members." + [actions paths] + (let [all (into (sorted-map) (map (juxt zset-action-id identity) actions)) + selected (set (concat (mapcat identity paths) + (keep (fn [[id op]] (when (< (:end op) Long/MAX_VALUE) id)) all))) + remaining (into (sorted-map) (select-keys all selected)) + successors (reduce (fn [g [a b]] (update g a (fnil conj #{}) b)) + {} (mapcat #(zset-guide-edges all %) paths)) + predecessors (reduce-kv (fn [g a bs] (reduce #(update %1 %2 (fnil conj #{}) a) g bs)) {} successors)] + (loop [db {} remaining remaining predecessors predecessors] + (let [deadline (ffirst (first remaining))] + (if (or (nil? deadline) (= Long/MAX_VALUE deadline)) + true + (if-let [[id next-db] (advance-guided-zset db remaining predecessors deadline)] + (recur next-db (dissoc remaining id) + (reduce #(update %1 %2 disj id) predecessors (get successors id))) + false)))))) + (defn- zset-witness [mutations reads] - (windows/serial-witness - (concat (for [m mutations :when (not= :fail (:type m))] - (assoc m :start (:invoke-idx m) :end (or (:complete-idx m) Long/MAX_VALUE))) - (for [{:keys [invoke complete]} reads] - {:start (:index invoke) :end (:index complete) :read complete})) - advance-zset)) + (let [actions (vec (concat (for [m mutations :when (not= :fail (:type m))] + (assoc m :start (:invoke-idx m) :end (or (:complete-idx m) Long/MAX_VALUE))) + (for [{:keys [invoke complete]} reads] + {:start (:index invoke) :end (:index complete) :read complete})))] + (windows/with-shared-budget + (fn [] + (let [paths (zset-guide-paths actions)] + ;; A cyclic/incompatible guide does not prove inconsistency. Fall + ;; back to full search, using only the remaining original budget. + (if (and paths (verify-zset-guides actions paths)) + true + (windows/serial-witness actions advance-zset))))))) (defn- check-zset-history "Custom Jepsen checker: validates ZSet safety properties using a @@ -1404,7 +1470,12 @@ all-errors (if (seq all-errors) all-errors (check-read-stability mutations-by-m read-pairs)) all-errors (vec (distinct all-errors)) - witness (when (and (empty? all-errors) (seq read-pairs)) (zset-witness mutations read-pairs)) + concrete-errors (remove #(= :inconclusive-zadd-history (:kind %)) all-errors) + ;; A local search limit is not a counterexample. Only a complete, + ;; common execution witness may discharge that inconclusive result. + witness (when (and (empty? concrete-errors) (seq read-pairs)) (zset-witness mutations read-pairs)) + local-limits (when (true? witness) (filterv #(= :inconclusive-zadd-history (:kind %)) all-errors)) + all-errors (if (true? witness) (vec concrete-errors) all-errors) all-errors (cond-> all-errors (false? witness) (conj {:kind :no-consistent-zset-history})) by-kind (group-by :kind all-errors) ;; Vacuous-pass guard: if the run produced zero @@ -1423,11 +1494,13 @@ no-successful-reads? :unknown :else witness)] (cond-> {:valid? valid? + :linearizable {:valid? witness} :reads (count read-pairs) :mutations (count mutations) :error-count (count all-errors) :errors-by-kind (into {} (map (fn [[k v]] [k (count v)]) by-kind)) :first-errors (take 20 all-errors)} + (seq local-limits) (assoc :local-search-limits local-limits) (= :unknown witness) (assoc :reason :zset-search-limit) (and (= :unknown valid?) (seq all-errors)) (assoc :reason :zset-search-limit) no-successful-reads? diff --git a/jepsen/src/elastickv/version_cas.clj b/jepsen/src/elastickv/version_cas.clj new file mode 100644 index 000000000..30e776cc2 --- /dev/null +++ b/jepsen/src/elastickv/version_cas.clj @@ -0,0 +1,117 @@ +(ns elastickv.version-cas + "Client-observable invariants for a non-expiring register initialized once per run." + (:require [jepsen.client :as client] + [jepsen.checker :as checker] + [jepsen.generator :as gen] + [elastickv.version-cas-model :as model])) + +(defn- version? [v] (and (integer? v) (pos? v))) + +(defn- observe [state path value] + (update-in state path (fnil max 0) value)) + +(defn- violation [s kind call completion] + (update s :errors conj {:kind kind :invoke call :completion completion})) + +(defn- check-result [s call op bound] + (let [{:keys [key f expected]} call + {:keys [version value missing]} op + cas? (= :cas f) + row? (and (version? version) (integer? value)) + known (get-in s [:values [key version]])] + (cond + (= :seed f) (observe s [:floor key] 1) + (and (= :version-read f) missing) + (if (pos? bound) (violation s :lost-key call op) s) + (not row?) (violation s :invalid-versioned-result call op) + :else + (cond-> (-> s (observe [:floor key] version) (assoc-in [:values [key version]] value)) + (< version bound) (violation :version-regressed call op) + (and (some? known) (not= known value)) (violation :version-value-changed call op) + (and cas? (or (not (version? expected)) (<= version expected) + (< expected bound) (not= (:value call) value))) + (violation :invalid-replacement call op) + (and cas? (contains? (:consumed s) [key expected])) + (violation :token-consumed-twice call op) + cas? (update :consumed conj [key expected]) + cas? (update :successes inc) + cas? (observe [:ack key] version) + (and cas? (version? expected) (= expected (:after-ack call))) (update :chained-successes inc) + (and (= f :version-read) (:after-ack call)) (update :reads-after-ack inc))))) + +(defn check-history [history] + (let [step (fn [s {:keys [type f key process expected] :as op}] + (if-not (#{:seed :version-read :cas} f) + s + (if (= type :invoke) + (assoc-in s [:pending process] + [(assoc op :after-ack (get-in s [:ack key])) + (get-in s [:floor key] 0) + (contains? (:consumed s) [key expected])]) + (let [[call bound stale?] (get-in s [:pending process]) + s (update s :pending dissoc process)] + (cond + (nil? call) (violation s :missing-invocation nil op) + (or (not= f (:f call)) (not= key (:key call))) + (violation s :wrong-completion call op) + (= :ok type) (check-result s call op bound) + (and stale? (= f :cas) (= :fail type) (= "version-mismatch" (:error op))) + (update s :rejected-reuses inc) + (= :info type) (update s :indeterminate inc) + :else s))))) + s (reduce step {:successes 0 :chained-successes 0 :reads-after-ack 0 :rejected-reuses 0 + :indeterminate 0 :errors [] :consumed #{}} + history) + witness (model/check-history history)] + (assoc (select-keys s [:successes :chained-successes :reads-after-ack :rejected-reuses :indeterminate :errors]) + :linearizable witness + :valid? (checker/merge-valid + [(:valid? witness) + (cond (seq (:errors s)) false + (every? pos? ((juxt :chained-successes :reads-after-ack :rejected-reuses) s)) true + :else :unknown)])))) + +(defn- record-version! [tokens k token] + (when (version? token) + (swap! tokens update-in [k :current] (fnil max 0) token))) + +(defrecord VersionClient [transport exchange! tokens] + client/Client + (open! [this test node] (assoc this :transport (client/open! transport test node))) + (setup! [this _] this) + (invoke! [_ _ {:keys [f key expected value] :as op}] + (if (and (= :cas f) (not (version? expected))) + (assoc op :type :fail :error :no-token) + (try + (let [args (case f + :seed {:op "write" :value value} + :version-read {:op "version-read"} + :cas {:op "cas" :expected expected :value value}) + r (exchange! (:writer transport) (:reader transport) (assoc args :key key)) + completion (merge op (select-keys r [:version :value :missing :error]) + {:type (keyword (:type r))})] + (when (= :ok (:type completion)) + (record-version! tokens key (:version r)) + (when (= :cas f) (swap! tokens assoc-in [key :consumed] expected))) + completion) + (catch Exception e (assoc op :type :info :error (.getMessage e)))))) + (teardown! [_ _]) + (close! [this test] (assoc this :transport (client/close! transport test)))) + +(defn workload [transport exchange! opts] + (let [k (str "jepsen-version-cas/" (java.util.UUID/randomUUID)) + tokens (atom {}) + payload (atom 0) + read-op {:f :version-read :key k} + update-op (fn [source] + (fn [] {:f :cas :key k :expected (get-in @tokens [k source]) + :value (swap! payload inc)})) + attempts (gen/mix [(gen/repeat read-op) (update-op :current) (update-op :consumed)])] + {:client (->VersionClient transport exchange! tokens) + :generator (gen/phases + (gen/once {:f :seed :key k :value 0}) + (gen/once read-op) + (->> attempts (gen/stagger (/ (double (or (:rate opts) 5)))) + (gen/time-limit (or (:time-limit opts) 30))) + (gen/each-thread (gen/once read-op))) + :checker (reify checker/Checker (check [_ _ history _] (check-history history)))})) diff --git a/jepsen/src/elastickv/version_cas_model.clj b/jepsen/src/elastickv/version_cas_model.clj new file mode 100644 index 000000000..a6b369915 --- /dev/null +++ b/jepsen/src/elastickv/version_cas_model.clj @@ -0,0 +1,85 @@ +(ns elastickv.version-cas-model + "One execution must explain every returned value/version and CAS verdict." + (:require [knossos.linear :as linear] + [knossos.model :as model] + [knossos.search :as search])) + +(defn- version? [v] (and (integer? v) (pos? v))) + +(defn- matches-version? [row version] + (and row (version? version) + (if-let [known (:version row)] + (= version known) + (and (> version (:floor row)) + (not (contains? (:excluded row) version)))))) + +(defn- replacement [row call result] + (let [{:keys [expected value]} call + version (:version result)] + (when (and (matches-version? row expected) (integer? value) + (or (nil? result) (and (version? version) (> version expected) + (= value (:value result))))) + (if result {:value value :version version} + {:value value :floor expected :excluded #{}})))) + +(defn- observation [row result] + (if (:missing result) + (when (nil? row) ::absent) + (when (and (= (:value row) (:value result)) + (matches-version? row (:version result))) + {:value (:value row) :version (:version result)}))) + +(defrecord Register [rows] + knossos.model.Model + (step [_ {:keys [f value]}] + (let [{:keys [call result]} value + {:keys [key expected]} call + row (get rows key) + next-row + (case f + :seed {:value (:value call) + :floor (or (:version row) (:floor row) 0) :excluded #{}} + :cas (replacement row call result) + :version-read (observation row result) + :cas-mismatch + (when (and (version? expected) (or (nil? row) (not= expected (:version row)))) + (cond + (nil? row) ::absent + (:version row) row + :else (update row :excluded conj expected))))] + (if next-row + (->Register (if (= ::absent next-row) (dissoc rows key) (assoc rows key next-row))) + (model/inconsistent (str "No issued version explains " f " " (pr-str value))))))) + +(defn- project-operation [start call end result] + (let [mismatch? (and (= :cas (:f call)) (= :fail (:type result)) + (= "version-mismatch" (:error result))) + success? (= :ok (:type result)) + uncertain? (or (nil? result) (= :info (:type result)))] + (when (or success? mismatch? (and uncertain? (#{:seed :cas} (:f call)))) + (let [op {:process start :f (if mismatch? :cas-mismatch (:f call)) + :value {:call call :result (when success? result)} :index start :type :invoke}] + (cond-> [op] + (or success? mismatch?) (conj (assoc op :type :ok :index end))))))) + +(defn projected-history [history] + (let [{:keys [pending operations]} + (reduce (fn [state [index op]] + (if-not (#{:seed :cas :version-read} (:f op)) + state + (let [process (:process op)] + (if (= :invoke (:type op)) + (assoc-in state [:pending process] [index op]) + (let [[start call] (get-in state [:pending process])] + (cond-> (update state :pending dissoc process) + call (update :operations into (project-operation start call index op)))))))) + {:pending {} :operations []} (map-indexed vector history))] + (sort-by :index + (into operations (mapcat (fn [[_ [start call]]] + (project-operation start call nil nil)) pending))))) + +(defn check-history [history] + (let [analysis (linear/start-analysis (->Register {}) (projected-history history))] + (try + (select-keys (search/run analysis {:time-limit 30000}) [:valid? :cause :op]) + (finally (search/abort! analysis :finished))))) diff --git a/jepsen/test/elastickv/history_windows_test.clj b/jepsen/test/elastickv/history_windows_test.clj index 18fa0750b..8d02ae10e 100644 --- a/jepsen/test/elastickv/history_windows_test.clj +++ b/jepsen/test/elastickv/history_windows_test.clj @@ -15,3 +15,19 @@ (when-not (:required op) [state (dissoc remaining id)]))] (is (false? (binding [windows/*candidate-budget* 5000] (windows/serial-witness actions advance)))))) + +(deftest execution-path-includes-every-mandatory-action + (let [actions [{:start 0 :end 1} {:start 2 :end 3}] + advance (fn [state remaining [id _]] [state (dissoc remaining id)])] + (is (= [[1 0] [3 2]] (windows/serial-execution actions advance))) + (is (true? (windows/serial-witness actions advance))))) + +(deftest guided-search-cannot-reset-the-shared-budget + (let [actions [{:start 0 :end 1}] + advance (fn [state remaining [id _]] [state (dissoc remaining id)])] + (is (= :unknown + (binding [windows/*candidate-budget* 1] + (windows/with-shared-budget + (fn [] + (is (= [[1 0]] (windows/serial-execution actions advance))) + (windows/serial-witness actions advance)))))))) diff --git a/jepsen/test/elastickv/redis_zset_safety_workload_test.clj b/jepsen/test/elastickv/redis_zset_safety_workload_test.clj index ee84e2d91..faab17179 100644 --- a/jepsen/test/elastickv/redis_zset_safety_workload_test.clj +++ b/jepsen/test/elastickv/redis_zset_safety_workload_test.clj @@ -6,6 +6,7 @@ [clojure.java.io :as io] [jepsen.checker :as checker] [jepsen.client :as client] + [elastickv.history-windows :as windows] [elastickv.redis-zset-safety-workload :as workload])) ;; --------------------------------------------------------------------------- @@ -935,7 +936,7 @@ {:type :ok :process 1 :f :zrange-all :value [["m1" score]] :index 3}] result (with-redefs-fn {#'workload/check-indeterminate-mutations (fn [& _] {:kind :inconclusive-zadd-history :cause :timeout})} - #(run-checker history))] + #(binding [windows/*candidate-budget* 0] (run-checker history)))] (is (= expected (:valid? result)) (pr-str result))))) (deftest oversized-timed-out-zadd-search-remains-inconclusive @@ -952,7 +953,7 @@ {:type :invoke :process 256 :f :zrange-all} {:type :ok :process 256 :f :zrange-all :value [["m1" 49.0]]}]) (range)) - result (run-checker history)] + result (binding [windows/*candidate-budget* 0] (run-checker history))] (is (= :unknown (:valid? result))) (is (= 1 (get-in result [:errors-by-kind :inconclusive-zadd-history]))) (is (= :read-search-budget-exhausted (:cause (first (:first-errors result))))) @@ -970,7 +971,7 @@ [{:type :invoke :process 300 :f :zrange-all} {:type :ok :process 300 :f :zrange-all :value []}]) (range)) - result (run-checker history)] + result (binding [windows/*candidate-budget* 0] (run-checker history))] (is (= :unknown (:valid? result))) (is (= :operations (:budget (first (:first-errors result)))))))) @@ -981,10 +982,26 @@ (deftest long-uncertain-history-remains-inconclusive-at-the-search-budget ;; This is the member-local part of the scheduled Jepsen history whose ;; completed read at index 5169 exhausted the checker's 4096-state budget. - (let [result (run-checker (long-uncertain-zset-history))] + (let [result (binding [windows/*candidate-budget* 0] + (run-checker (long-uncertain-zset-history)))] (is (= :unknown (:valid? result)) (pr-str result)) (is (= :zset-search-limit (:reason result))))) +(deftest common-execution-witness-can-discharge-local-search-exhaustion + (let [result (run-checker (long-uncertain-zset-history))] + (is (true? (:valid? result)) (pr-str result)) + (is (true? (get-in result [:linearizable :valid?]))) + (is (= :operations (:budget (first (:local-search-limits result))))))) + +(deftest common-execution-witness-requires-exact-increment-replies + (let [history (mapv #(assoc %1 :index %2) + [{:type :invoke :process 0 :f :zincrby :value ["m1" 1.0]} + {:type :ok :process 0 :f :zincrby :value ["m1" 1.0000000001]} + {:type :invoke :process 0 :f :zrange-all} + {:type :ok :process 0 :f :zrange-all :value [["m1" 1.0000000001]]}] + (range))] + (is (false? (:valid? (run-checker history)))))) + (deftest modified-long-uncertain-history-is-never-certified (let [history (mapv (fn [op] (if (= 5169 (:index op)) @@ -1704,3 +1721,73 @@ check (fn [h] (:valid? (run-checker (map-indexed #(assoc %2 :index %1) h))))] (is (false? (check h))) (is (true? (check (assoc-in h [5 :value] [["m" 1.0]])))))) + +(deftest independent-member-guides-do-not-certify-fractured-full-reads + (let [actions [{:f :zadd :type :ok :member "a" :score 1.0 :start 0 :end 4} + {:f :zadd :type :ok :member "b" :score 1.0 :start 1 :end 5} + {:start 2 :end 6 :read {:f :zrange-all :value [["a" 1.0]]}} + {:start 3 :end 7 :read {:f :zrange-all :value [["b" 1.0]]}}]] + (windows/with-shared-budget + (fn [] + (let [paths (#'workload/zset-guide-paths actions)] + (is (every? vector? paths) "each member alone has a valid projection") + (is (false? (#'workload/verify-zset-guides actions paths)) + "the projections must share one atomic execution")))))) + +(deftest guide-validation-cannot-omit-an-acknowledged-read + (let [actions [{:f :zadd :type :ok :member "a" :score 1.0 :start 0 :end 1} + {:start 2 :end 3 :read {:f :zrange-all :value []}}]] + (is (false? (windows/with-shared-budget + #(#'workload/verify-zset-guides actions [[[1 0]]])))))) + +(deftest guide-validation-preserves-real-time-and-increment-arithmetic + (let [actions [{:f :zincrby :type :ok :member "a" :delta 1.0 :score 2.0 :start 0 :end 1} + {:start 2 :end 3 :read {:f :zrange-all :value [["a" 2.0]]}}]] + (is (false? (windows/with-shared-budget + #(#'workload/verify-zset-guides actions [[[3 2] [1 0]]])))) + (is (false? (windows/with-shared-budget + #(#'workload/verify-zset-guides actions [[[1 0] [3 2]]])))))) + +(deftest member-guides-do-not-order-commuting-read-batches + (let [actions [{:f :zadd :type :ok :member "a" :score 1.0 :start 0 :end 1} + {:f :zadd :type :ok :member "b" :score 1.0 :start 2 :end 3} + {:start 4 :end 7 :read {:f :zrange-all :value [["a" 1.0] ["b" 1.0]]}} + {:start 5 :end 6 :read {:f :zrange-all :value [["a" 1.0] ["b" 1.0]]}}] + paths [[[1 0] [7 4] [6 5]] [[3 2] [6 5] [7 4]]]] + (is (true? (windows/with-shared-budget + #(#'workload/verify-zset-guides actions paths))) + "opposite orders of commuting projected reads must not create a cycle") + (is (false? (windows/with-shared-budget + #(#'workload/verify-zset-guides + (assoc-in actions [3 :read :value] [["a" 1.0]]) paths))) + "the complete read is still checked against one shared ZSet"))) + +(deftest commuting-read-batches-retain-both-mutation-boundaries + (let [actions [{:f :zadd :type :ok :member "a" :score 1.0 :start 0 :end 5} + {:start 1 :end 6 :read {:f :zrange-all :value [["a" 1.0]]}} + {:start 2 :end 7 :read {:f :zrange-all :value [["a" 1.0]]}} + {:f :zadd :type :ok :member "a" :score 2.0 :start 3 :end 8} + {:start 4 :end 9 :read {:f :zrange-all :value [["a" 2.0]]}}] + path [[5 0] [6 1] [7 2] [8 3] [9 4]]] + (is (true? (windows/with-shared-budget + #(#'workload/verify-zset-guides actions [path])))) + (doseq [index [1 2]] + (is (false? (windows/with-shared-budget + #(#'workload/verify-zset-guides + (assoc-in actions [index :read :value] [["a" 2.0]]) [path]))) + "every read remains between its preceding and following mutation")))) + +(deftest guided-full-read-results-agree-with-exhaustive-small-search + (let [observations [[] [["a" 1.0]] [["b" 1.0]] [["a" 1.0] ["b" 1.0]]]] + (doseq [before observations after observations] + (let [actions [{:f :zadd :type :ok :member "a" :score 1.0 :start 0 :end 4} + {:f :zadd :type :ok :member "b" :score 1.0 :start 1 :end 5} + {:start 2 :end 6 :read {:f :zrange-all :value before}} + {:start 3 :end 7 :read {:f :zrange-all :value after}}] + guided (windows/with-shared-budget + #(when-let [paths (#'workload/zset-guide-paths actions)] + (#'workload/verify-zset-guides actions paths))) + exhaustive (windows/serial-witness actions #'workload/advance-zset)] + (is (not= :unknown exhaustive)) + (is (or (not (true? guided)) (true? exhaustive)) + (str "a guide cannot certify a history rejected by exhaustive search: " before " -> " after)))))) diff --git a/jepsen/test/elastickv/version_cas_test.clj b/jepsen/test/elastickv/version_cas_test.clj new file mode 100644 index 000000000..dfef9a2fb --- /dev/null +++ b/jepsen/test/elastickv/version_cas_test.clj @@ -0,0 +1,87 @@ +(ns elastickv.version-cas-test + (:require [clojure.test :refer :all] + [elastickv.version-cas :as cas] + [knossos.search :as search])) + +(defn call [process f fields] + (merge {:type :invoke :key "k" :process process :f f} fields)) +(defn finish [call type fields] (merge call {:type type} fields)) + +(def seed (call 8 :seed {:value 0})) +(def seeded (finish seed :ok {})) +(defn check [history] (cas/check-history (into [seed seeded] history))) + +(def edit (call 0 :cas {:expected 10 :value 1})) +(def applied (finish edit :ok {:version 20})) +(def read-key (call 1 :version-read {})) +(def latest (finish read-key :ok {:version 20 :value 1})) +(def old (finish read-key :ok {:version 10 :value 0})) +(def reuse (call 2 :cas {:expected 10 :value 2})) +(def rejected (finish reuse :fail {:error "version-mismatch"})) +(def chain (call 0 :cas {:expected 20 :value 3})) +(def chained (finish chain :ok {:version 30})) +(def healthy [edit applied read-key latest reuse rejected chain chained]) + +(deftest clean-history-needs-positive-and-negative-observations + (is (true? (:valid? (check healthy)))) + (doseq [history [[] [edit (finish edit :info {}) read-key old] [edit applied read-key latest] + [edit applied read-key latest reuse rejected]]] + (is (= :unknown (:valid? (check history)))))) + +(deftest previously-missed-histories + (is (= :version-regressed (-> [edit applied read-key old] check :errors first :kind))) + (is (contains? (set (map :kind (:errors (check + [edit reuse applied (finish reuse :ok {:version 30})])))) + :token-consumed-twice)) + (is (false? (:valid? (check [edit applied reuse (finish reuse :ok {:version 30})])))) + (is (= :lost-key (-> [edit applied read-key (finish read-key :ok {:missing true})] + check :errors first :kind)))) + +(deftest real-time-overlap-and-ambiguous-outcomes + ;; The old read began before the CAS completed; it may linearize first. + (is (true? (:valid? (check + [read-key edit applied old read-key latest reuse rejected chain chained])))) + (is (true? (:valid? (check + (into healthy [reuse (finish reuse :info {:error "reply lost"})]))))) + (let [other (assoc edit :key "another")] + (is (true? (:valid? (cas/check-history + (into [seed seeded (assoc seed :key "another") + (assoc seeded :key "another")] (into healthy [other (finish other :ok {:version 20})]))))))) + (is (false? (:valid? (check + [edit applied read-key (assoc latest :value 42)])))) + (is (false? (:valid? (check [edit (finish edit :ok {:version 10})]))))) + +(deftest reuse-coverage-requires-an-acknowledged-consumption-before-invocation + (let [ambiguous (check [edit applied chain chained read-key + (finish read-key :ok {:version 30 :value 3}) + reuse (finish reuse :info {:error "reply lost"})]) + overlap (check [edit reuse applied rejected read-key latest chain chained])] + (is (= :unknown (:valid? ambiguous))) + (is (= 1 (:indeterminate ambiguous))) + (is (zero? (:rejected-reuses ambiguous))) + (is (= :unknown (:valid? overlap))) + (is (zero? (:rejected-reuses overlap))))) + +(deftest fabricated-version-and-spurious-mismatch-are-rejected + (is (false? (:valid? (check (into healthy [read-key (finish read-key :ok {:version 40 :value 99})]))))) + (let [read-initial (finish read-key :ok {:version 10 :value 0})] + (is (false? (:valid? (check [read-key read-initial edit + (finish edit :fail {:error "version-mismatch"})])))) + (is (false? (:valid? (check [edit (finish edit :fail {:error "version-mismatch"}) + read-key read-initial])))))) + +(deftest uncertain-writes-explain-only-matching-values-and-fresh-versions + (let [unknown (finish edit :info {:error "reply lost"})] + (is (true? (get-in (check [read-key old edit unknown read-key latest]) [:linearizable :valid?]))) + (is (false? (:valid? (check [read-key old edit unknown read-key + (finish read-key :ok {:version 20 :value 99})])))) + (is (false? (:valid? (check [read-key old edit unknown read-key + (finish read-key :ok {:version 10 :value 1})])))))) + +(deftest unobserved-initial-version-must-respect-prior-mismatches + (is (false? (:valid? (check [edit (finish edit :fail {:error "version-mismatch"}) + read-key old]))))) + +(deftest model-search-timeout-is-not-a-pass + (with-redefs [search/run (fn [& _] {:valid? :unknown :cause :timeout})] + (is (= :unknown (:valid? (check healthy)))))) diff --git a/kv/absence_guard_test.go b/kv/absence_guard_test.go index a277c7d41..9f4d8b98b 100644 --- a/kv/absence_guard_test.go +++ b/kv/absence_guard_test.go @@ -116,7 +116,11 @@ func TestAbsenceGuardRawBatchRefusalDoesNotHalt(t *testing.T) { f := g17FSM(t, s) guarded := g17RawPut(10, "guarded", "blocked") guarded.Mutations[0].RequireAbsent = true - response := f.Apply(g17Entry(t, guarded, g17RawPut(11, "ordinary", "accepted"))) + // Replay a historical batch directly. Current proposal admission refuses + // require_absent before serialization, while replay must classify it. + raw, err := proto.Marshal(&pb.RaftCommand{Requests: []*pb.Request{guarded, g17RawPut(11, "ordinary", "accepted")}}) + require.NoError(t, err) + response := f.Apply(prependByte(raftEncodeBatch, raw)) result, ok := response.(*fsmApplyResponse) require.True(t, ok, "a deterministic capability refusal must not halt apply: %T", response) require.Len(t, result.results, 2) diff --git a/kv/applied_rejection.go b/kv/applied_rejection.go index 40d96a0a1..4e4271207 100644 --- a/kv/applied_rejection.go +++ b/kv/applied_rejection.go @@ -30,6 +30,10 @@ func singleRequestApplyVerdict(req *pb.Request, requestCount int, commitIndex ui (req.Phase != pb.Phase_NONE && req.Phase != pb.Phase_PREPARE) { return false } + if errors.Is(err, ErrCASMismatch) || errors.Is(err, ErrVersionCASUnavailable) { + reqs := []*pb.Request{req} + return HasCASMutation(reqs) && ValidateCASProposalShape(reqs) == nil + } return recognizedApplyVerdict(err) } diff --git a/kv/compare_and_swap.go b/kv/compare_and_swap.go new file mode 100644 index 000000000..a5970abd8 --- /dev/null +++ b/kv/compare_and_swap.go @@ -0,0 +1,132 @@ +package kv + +import ( + "bytes" + "context" + + "github.com/bootjp/elastickv/distribution" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" +) + +func validCASOperation(group *OperationGroup[OP], elem *Elem[OP]) bool { + return group.IsTxn && len(group.Elems) == 1 && len(group.ReadKeys) == 0 && + len(group.PrimaryKey) == 0 && !group.RequireAllParticipants && + group.StartTS == 0 && group.CommitTS == 0 && group.PrevCommitTS == 0 && + group.ObservedRouteVersion == 0 && + validCASElem(elem) +} + +func validCASElem(elem *Elem[OP]) bool { + return IsCASUserKey(elem.Key) && elem.ExpectedCommitTS != 0 && + !elem.RequireAbsent && elem.CommitTSValueOffset == 0 && + elem.GroupID == 0 && !elem.RequireGroupMatch && elem.ExpectedGroupID == 0 +} + +// HasCASMutation also detects a predicate attached to another operation, so +// validation cannot silently discard the expected version. +func HasCASMutation(reqs []*pb.Request) bool { + for _, req := range reqs { + if requestUsesCAS(req) { + return true + } + } + return false +} + +// IsCASUserKey is the key namespace shared by public and forwarded CAS. +func IsCASUserKey(key []byte) bool { + return len(key) != 0 && !distribution.IsReservedControlKey(key) && !IsTxnInternalKey(key) && + !distribution.IsMigrationKnownInternalKey(key) && !store.IsReplicatedControlKey(key) +} + +// ValidateCASProposalShape accepts only a stamped standalone one-phase CAS. +func ValidateCASProposalShape(reqs []*pb.Request) error { + if !HasCASMutation(reqs) { + return nil + } + return validateCASProposalShape(reqs) +} + +func validateCASProposalShape(reqs []*pb.Request) error { + _, meta, ok := casRequestMutation(reqs) + if !ok || reqs[0].GetVersionCasGroupId() == 0 || reqs[0].Ts == 0 || meta.CommitTS <= reqs[0].Ts { + return errors.WithStack(ErrInvalidRequest) + } + return nil +} + +// ForwardCASMutation leaves timestamp and catalog proof stamping to the +// receiving leader. +func ForwardCASMutation(reqs []*pb.Request) (*pb.Mutation, error) { + mut, meta, ok := casRequestMutation(reqs) + if !ok || reqs[0].GetVersionCasGroupId() == 0 || reqs[0].Ts != 0 || meta.CommitTS != 0 || reqs[0].TimestampAdmissionFloor != 0 || + reqs[0].ObservedRouteVersion != 0 { + return nil, errors.WithStack(ErrInvalidRequest) + } + return mut, nil +} + +func casRequestMutation(reqs []*pb.Request) (*pb.Mutation, TxnMeta, bool) { + if len(reqs) != 1 { + return nil, TxnMeta{}, false + } + req := reqs[0] + if !req.GetIsTxn() || req.Phase != pb.Phase_NONE || len(req.Mutations) != 2 || + len(req.ReadKeys) != 0 || len(req.TimestampBindingOperationId) != 0 { + return nil, TxnMeta{}, false + } + header, mut := req.Mutations[0], req.Mutations[1] + if !validCASHeader(header) || + !validCASMutation(mut) || !validCASBypass(req.WriteFenceBypassKeys, mut.Key) { + return nil, TxnMeta{}, false + } + return decodeCASRequestMeta(header, mut) +} + +func validCASHeader(header *pb.Mutation) bool { + return header != nil && header.Op == pb.Op_PUT && string(header.Key) == txnMetaPrefix && + header.ExpectedCommitTs == 0 && !header.RequireAbsent && header.CommitTsValueOffset == 0 +} + +func decodeCASRequestMeta(header, mut *pb.Mutation) (*pb.Mutation, TxnMeta, bool) { + meta, err := DecodeTxnMeta(header.Value) + return mut, meta, err == nil && bytes.Equal(meta.PrimaryKey, mut.Key) && + meta.PrevCommitTS == 0 && meta.PrepareCommitTS == 0 && meta.LockTTLms == 0 +} + +func validCASMutation(mut *pb.Mutation) bool { + return mut != nil && mut.Op == pb.Op_COMPARE_AND_SWAP && IsCASUserKey(mut.Key) && + mut.ExpectedCommitTs != 0 && !mut.RequireAbsent && mut.CommitTsValueOffset == 0 +} + +func validCASBypass(bypass [][]byte, key []byte) bool { + return len(bypass) == 0 || (len(bypass) == 1 && bytes.Equal(bypass[0], key)) +} + +// IsCertifiedCASMismatch recognizes an indexed rejection or a fenced +// pre-submission mismatch, including a validated dedicated CAS Forward reply. +func IsCertifiedCASMismatch(err error) bool { + return !errors.Is(err, ErrTransactionOutcomeUnknown) && errors.Is(err, ErrCASMismatch) && + (IsCertifiedOnePhaseConflict(err) || IsCertifiedCASPrecheckMismatch(err)) +} + +func (c *ShardedCoordinator) dispatchCAS(ctx context.Context, group *OperationGroup[OP]) (*CoordinateResponse, error) { + elem := group.Elems[0] + if !versionCASDirectKey(elem.Key) || c.partitionResolverRecognisesPointKey(elem.Key) { + return nil, errors.Wrap(ErrVersionCASUnavailable, "key requires alternate routing") + } + if c.engine == nil { + return nil, errors.Wrap(ErrVersionCASUnavailable, "route catalog is unavailable") + } + route, ok := c.engine.GetRoute(elem.Key) + if !ok || !versionCASInitialRoute(route) { + return nil, errors.Wrap(ErrVersionCASUnavailable, "route has migration history or is unavailable") + } + mut := elemToMutation(elem) + c.observeMutation(route.RouteID, mut, group.KeyVizLabel) + ctx = context.WithValue(ctx, leaderIssuedCommitTSContextKey{}, true) + return c.dispatchSingleShardTxn(ctx, 0, 0, 0, elem.Key, route.GroupID, []*pb.Mutation{mut}, nil, + 0, nil) +} diff --git a/kv/compare_and_swap_proposal_test.go b/kv/compare_and_swap_proposal_test.go new file mode 100644 index 000000000..e022c8d2e --- /dev/null +++ b/kv/compare_and_swap_proposal_test.go @@ -0,0 +1,89 @@ +package kv + +import ( + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" +) + +func TestCASProposalShape(t *testing.T) { + t.Parallel() + key := []byte("cas-key") + elem := &Elem[OP]{Op: CompareAndSwap, Key: key, ExpectedCommitTS: 5} + makeProposal := func(start, commit uint64) *pb.Request { + req := onePhaseTxnRequestWithPrevCommit(start, commit, 0, key, []*Elem[OP]{elem}, nil, 0, nil) + req.VersionCasGroupId = 1 + return req + } + require.NoError(t, ValidateCASProposalShape([]*pb.Request{makeProposal(6, 7)})) + unstamped := []*pb.Request{makeProposal(0, 0)} + mut, err := ForwardCASMutation(unstamped) + require.NoError(t, err) + require.EqualValues(t, 5, mut.GetExpectedCommitTs()) + require.ErrorIs(t, ValidateCASProposalShape(unstamped), ErrInvalidRequest) + + for _, tc := range []struct { + name string + edit func(*pb.Request) + }{ + {"raw", func(req *pb.Request) { req.IsTxn = false }}, + {"prepare", func(req *pb.Request) { req.Phase = pb.Phase_PREPARE }}, + {"missing group binding", func(req *pb.Request) { req.VersionCasGroupId = 0 }}, + {"missing predicate", func(req *pb.Request) { req.Mutations[1].ExpectedCommitTs = 0 }}, + {"predicate on ordinary put", func(req *pb.Request) { req.Mutations[1].Op = pb.Op_PUT }}, + {"extra mutation", func(req *pb.Request) { req.Mutations = append(req.Mutations, req.Mutations[1]) }}, + {"read dependency", func(req *pb.Request) { req.ReadKeys = [][]byte{[]byte("other")} }}, + {"prior attempt", func(req *pb.Request) { + req.Mutations[0].Value = EncodeTxnMeta(TxnMeta{PrimaryKey: key, CommitTS: 7, PrevCommitTS: 4}) + }}, + {"different primary", func(req *pb.Request) { + req.Mutations[0].Value = EncodeTxnMeta(TxnMeta{PrimaryKey: []byte("other"), CommitTS: 7}) + }}, + {"unrelated bypass", func(req *pb.Request) { req.WriteFenceBypassKeys = [][]byte{[]byte("other")} }}, + } { + t.Run(tc.name, func(t *testing.T) { + req := makeProposal(6, 7) + tc.edit(req) + require.ErrorIs(t, ValidateCASProposalShape([]*pb.Request{req}), ErrInvalidRequest) + _, err := marshalRaftCommand([]*pb.Request{req}) + require.ErrorIs(t, err, ErrInvalidRequest) + }) + } + require.ErrorIs(t, ValidateCASProposalShape([]*pb.Request{makeProposal(6, 7), makeProposal(8, 9)}), ErrInvalidRequest) +} + +func TestCASForwardMismatchRequiresMatchingRequestShape(t *testing.T) { + t.Parallel() + key := []byte("cas-key") + err := ForwardDecisionStatus(pb.ForwardFailurePhase_FORWARD_FAILURE_PHASE_ONE_PHASE_APPLY, + pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH, + pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_DEFINITIVELY_ABORTED) + elem := &Elem[OP]{Op: CompareAndSwap, Key: key, ExpectedCommitTS: 5} + req := onePhaseTxnRequestWithPrevCommit(0, 0, 0, key, []*Elem[OP]{elem}, nil, 0, nil) + req.VersionCasGroupId = 1 + proven := classifyForwardRPCError(err, []*pb.Request{req}) + require.True(t, IsCertifiedCASMismatch(proven)) + req.Mutations[1].Op = pb.Op_PUT + req.Mutations[1].ExpectedCommitTs = 0 + unknown := classifyForwardRPCError(err, []*pb.Request{req}) + require.False(t, IsCertifiedCASMismatch(unknown)) + require.ErrorIs(t, unknown, ErrTransactionOutcomeUnknown) +} + +func TestCASForwardPrecheckMismatchRequiresDedicatedRequest(t *testing.T) { + t.Parallel() + wire := ForwardDecisionStatus(pb.ForwardFailurePhase_FORWARD_FAILURE_PHASE_ONE_PHASE_APPLY, + pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH, + pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION) + req := casApplyRequest(0, 0, 5, "key", "replacement") + req.ObservedRouteVersion = 0 + proof := classifyForwardRPCError(wire, []*pb.Request{req}) + require.True(t, IsCertifiedCASPrecheckMismatch(proof)) + require.False(t, IsCertifiedOnePhaseConflict(proof)) + req.Mutations[1].Op = pb.Op_PUT + req.Mutations[1].ExpectedCommitTs = 0 + unknown := classifyForwardRPCError(wire, []*pb.Request{req}) + require.False(t, IsCertifiedCASMismatch(unknown)) + require.ErrorIs(t, unknown, ErrTransactionOutcomeUnknown) +} diff --git a/kv/coordinator.go b/kv/coordinator.go index 4f3d4255a..ce8dd6792 100644 --- a/kv/coordinator.go +++ b/kv/coordinator.go @@ -610,14 +610,23 @@ func (c *Coordinate) Dispatch(ctx context.Context, reqs *OperationGroup[OP]) (*C }) } +func validateLegacyCoordinatorRequest(reqs *OperationGroup[OP]) error { + if err := validateOperationGroupForDispatch(reqs); err != nil { + return err + } + // Single-group production servers use ShardedCoordinator for version CAS. + if reqs.Elems[0].Op == CompareAndSwap { + return errors.WithStack(ErrVersionCASUnavailable) + } + return nil +} + func (c *Coordinate) dispatchWithRetry(ctx context.Context, reqs *OperationGroup[OP]) (*CoordinateResponse, error) { if ctx == nil { ctx = context.Background() } - // Validate the request before any use to avoid panics on malformed input. - // Validation errors are not retryable, so do this once outside the loop. - if err := validateOperationGroupForDispatch(reqs); err != nil { + if err := validateLegacyCoordinatorRequest(reqs); err != nil { return nil, err } @@ -1562,6 +1571,8 @@ func (c *Coordinate) toRawRequest(req *Elem[OP]) *pb.Request { }, }, } + case CompareAndSwap: + panic("compare-and-swap requires a transaction") } panic("unreachable") @@ -1614,6 +1625,7 @@ func (c *Coordinate) redirect(ctx context.Context, reqs *OperationGroup[OP]) (*C fwdCtx, cancel := context.WithTimeout(ctx, redirectForwardTimeout) defer cancel() + // Dispatch rejects CAS on this legacy coordinator before routing. r, err := cli.Forward(fwdCtx, c.toForwardRequest(requests)) if err != nil { return nil, classifyForwardRPCError(err, requests) @@ -1683,6 +1695,10 @@ func (c *Coordinate) toForwardRequest(reqs []*pb.Request) *pb.ForwardRequest { func elemToMutation(req *Elem[OP]) *pb.Mutation { switch req.Op { + case CompareAndSwap: + return &pb.Mutation{ + Op: pb.Op_COMPARE_AND_SWAP, Key: req.Key, Value: req.Value, ExpectedCommitTs: req.ExpectedCommitTS, + } case Put: value := req.Value if req.CommitTSValueOffset != 0 { diff --git a/kv/fenced_floor_error_test.go b/kv/fenced_floor_error_test.go new file mode 100644 index 000000000..116fc82ef --- /dev/null +++ b/kv/fenced_floor_error_test.go @@ -0,0 +1,143 @@ +package kv + +import ( + "context" + stderrors "errors" + "io" + "net" + "testing" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func markedFloorTransfer() error { + // Match the private etcd engine's checkReadAdmission error shape. + return errors.WithStack(errors.Mark(errors.New("etcd raft leadership transfer is in progress"), + raftengine.ErrLeadershipTransferInProgress)) +} + +func TestFencedFloorReadIndexIdentity(t *testing.T) { + transfer := raftengine.ErrLeadershipTransferInProgress + generic := errors.New("read rejected") + for _, tc := range []struct { + name string + cause error + transfer bool + }{ + {"wrapped sentinel", errors.Wrap(transfer, "read index"), true}, + {"marked transfer", markedFloorTransfer(), true}, + {"same text", errors.New(transfer.Error()), false}, + {"generic", generic, false}, + {"canceled", context.Canceled, false}, + {"deadline", context.DeadlineExceeded, false}, + {"EOF", io.EOF, false}, + {"network", net.ErrClosed, false}, + {"status", status.Error(codes.Aborted, "interrupted"), false}, + {"leadership lost", raftengine.ErrLeadershipLost, false}, + {"unknown", ErrTransactionOutcomeUnknown, false}, + {"unknown marked transfer", errors.Mark(ErrTransactionOutcomeUnknown, transfer), false}, + {"wrapped join", errors.Wrap(stderrors.Join(transfer, generic), "read index"), false}, + {"marked join", errors.Mark(stderrors.Join(generic, io.EOF), transfer), false}, + {"hidden secondary", errors.WithSecondaryError(markedFloorTransfer(), generic), false}, + {"secondary transfer", errors.WithSecondaryError(generic, transfer), false}, + } { + t.Run(tc.name, func(t *testing.T) { + data := store.NewMVCCStore() + engine := &recordingTSOEngine{state: raftengine.StateLeader, readIndex: func(context.Context) (uint64, error) { + return 0, tc.cause + }} + shards := NewShardStore(nil, map[uint64]*ShardGroup{1: {Engine: engine, Store: data}}) + t.Cleanup(func() { require.NoError(t, shards.Close()) }) + require.NoError(t, data.PutAt(t.Context(), []byte("a"), []byte("v"), 42, 0)) + + ts, err := shards.GroupCommittedTimestampFloor(t.Context(), 1) + require.Zero(t, ts) + require.ErrorIs(t, err, ErrTSOCommitFloorUnavailable) + require.Equal(t, tc.transfer, errors.Is(err, transfer)) + if tc.transfer { + require.True(t, isolatedMutationFailure(err)) + } else { + require.False(t, errors.Is(err, tc.cause)) + require.False(t, isTransientTSORouteError(err)) + } + require.Equal(t, codes.Unknown, status.Code(err)) + }) + } +} + +func TestFencedFloorFailedGroupReturnsNoProof(t *testing.T) { + catalog := distribution.NewEngine() + require.NoError(t, catalog.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, End: []byte("m"), GroupID: 1, State: distribution.RouteStateActive}, + {RouteID: 2, Start: []byte("m"), GroupID: 2, State: distribution.RouteStateActive}, + }})) + rejecting := &recordingTSOEngine{state: raftengine.StateLeader, readIndex: func(context.Context) (uint64, error) { + return 0, markedFloorTransfer() + }} + healthy := store.NewMVCCStore() + shards := NewShardStore(catalog, map[uint64]*ShardGroup{ + 1: {Engine: rejecting, Store: store.NewMVCCStore()}, + 2: {Engine: &recordingTSOEngine{state: raftengine.StateLeader}, Store: healthy}, + }) + t.Cleanup(func() { require.NoError(t, shards.Close()) }) + require.NoError(t, healthy.PutAt(t.Context(), []byte("z"), []byte("v"), 99, 0)) + ts, targets, err := shards.CommittedTimestampFloorForKeysWithTargets(t.Context(), [][]byte{[]byte("z")}) + require.NoError(t, err) + require.Equal(t, uint64(99), ts) + require.Equal(t, []ReadFenceTarget{{GroupID: 2}}, targets) + + check := func(t *testing.T, ts uint64, err error) { + t.Helper() + require.Zero(t, ts) + require.ErrorIs(t, err, ErrTSOCommitFloorUnavailable) + require.True(t, errors.Is(err, raftengine.ErrLeadershipTransferInProgress)) + } + t.Run("keyed", func(t *testing.T) { + ts, err := shards.CommittedTimestampFloorForKeys(t.Context(), [][]byte{[]byte("a")}) + check(t, ts, err) + }) + t.Run("targets", func(t *testing.T) { + ts, targets, err := shards.CommittedTimestampFloorForKeysWithTargets(t.Context(), [][]byte{[]byte("z"), []byte("a")}) + require.Nil(t, targets) + check(t, ts, err) + }) + t.Run("global", func(t *testing.T) { + ts, err := shards.GlobalCommittedTimestampFloor(t.Context()) + check(t, ts, err) + }) +} + +func TestFencedFloorTransferDoesNotRetryTSOReservation(t *testing.T) { + calls := 0 + dataEngine := &recordingTSOEngine{state: raftengine.StateLeader, readIndex: func(context.Context) (uint64, error) { + calls++ + if calls == 1 { + return 0, markedFloorTransfer() + } + return 0, errors.New("unexpected second floor call") + }} + shards := NewShardStore(nil, map[uint64]*ShardGroup{1: {Engine: dataEngine, Store: store.NewMVCCStore()}}) + t.Cleanup(func() { require.NoError(t, shards.Close()) }) + clock := NewHLC() + state := NewTSOStateMachine(clock) + engine := &recordingTSOEngine{state: raftengine.StateLeader, term: 1} + local, err := NewRaftTSOAllocator(&ShardGroup{Engine: engine, TSOState: state}, clock, WithTSOCutoverFloorProvider(shards)) + require.NoError(t, err) + routed, err := NewLeaderRoutedTSOAllocator(local, engine) + require.NoError(t, err) + + ts, err := routed.Next(t.Context()) + require.Zero(t, ts) + require.Equal(t, 1, calls) + require.Empty(t, engine.proposedPayloads()) + require.Zero(t, state.AllocationFloor()) + require.ErrorIs(t, err, ErrTSOCommitFloorUnavailable) + require.False(t, errors.Is(err, raftengine.ErrLeadershipTransferInProgress)) + require.False(t, isTransientTSORouteError(err)) +} diff --git a/kv/forward_decision_detail.go b/kv/forward_decision_detail.go index af68b442b..4b84c9db7 100644 --- a/kv/forward_decision_detail.go +++ b/kv/forward_decision_detail.go @@ -80,10 +80,15 @@ func validForwardDecision(phase pb.ForwardFailurePhase, reason pb.ForwardFailure func validOnePhaseForwardDecision(reason pb.ForwardFailureReason, decision pb.ForwardDecisionClass) bool { if decision == pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION { - return reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_NO_LEADER || reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_FENCE + return reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_NO_LEADER || + reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_FENCE || + reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH } if decision == pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_DEFINITIVELY_ABORTED { - return reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CONFLICT || reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_FENCE + return reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CONFLICT || + reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_FENCE || + reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH || + reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_LOCKED } return decision == pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_OUTCOME_UNKNOWN && validUnknownForwardReason(reason) } @@ -123,5 +128,8 @@ func forwardDecisionMessage(reason pb.ForwardFailureReason) string { if reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_INTERRUPTED { return "forward interrupted" } + if reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH { + return "forward compare-and-swap mismatch" + } return "forward aborted" } diff --git a/kv/forward_decision_detail_test.go b/kv/forward_decision_detail_test.go index 113af9414..999301e31 100644 --- a/kv/forward_decision_detail_test.go +++ b/kv/forward_decision_detail_test.go @@ -32,18 +32,20 @@ func TestForwardDecisionStatusAllowedPairs(t *testing.T) { leader = pb.ForwardFailureReason_FORWARD_FAILURE_REASON_NO_LEADER broken = pb.ForwardFailureReason_FORWARD_FAILURE_REASON_INTERRUPTED aborted = pb.ForwardFailureReason_FORWARD_FAILURE_REASON_ABORTED + mismatch = pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH + locked = pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_LOCKED reject = pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION settled = pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_DEFINITIVELY_ABORTED unknown = pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_OUTCOME_UNKNOWN ) allowed := map[pb.ForwardFailurePhase]map[pb.ForwardDecisionClass][]pb.ForwardFailureReason{ - one: {reject: {leader, fence}, settled: {conflict, fence}, unknown: {conflict, fence, leader, broken}}, + one: {reject: {leader, fence, mismatch}, settled: {conflict, fence, mismatch, locked}, unknown: {conflict, fence, leader, broken}}, prepare: {settled: {aborted}, unknown: {conflict, fence, leader, broken}}, commit: {settled: {aborted}, unknown: {conflict, fence, leader, broken}}, abort: {settled: {aborted}, unknown: {conflict, fence, leader, broken}}, } phases := []pb.ForwardFailurePhase{0, one, prepare, commit, abort, 99} - reasons := []pb.ForwardFailureReason{0, conflict, fence, leader, broken, aborted, 99} + reasons := []pb.ForwardFailureReason{0, conflict, fence, leader, broken, aborted, mismatch, locked, 99} decisions := []pb.ForwardDecisionClass{0, reject, settled, unknown, 99} for _, phase := range phases { for _, reason := range reasons { diff --git a/kv/fsm.go b/kv/fsm.go index 44c64fa28..0920be000 100644 --- a/kv/fsm.go +++ b/kv/fsm.go @@ -8,6 +8,7 @@ import ( "io" "log/slog" "os" + "sync" "sync/atomic" "github.com/bootjp/elastickv/distribution" @@ -140,6 +141,8 @@ type kvFSM struct { // timestamped before the backup cut and reached apply too late. backupTimestampFloor atomic.Uint64 backupFloorLoadErr error + versionRetirementLoadErr error + versionRetirementConfigured bool replicatedPins *replicatedPinJournal replicatedPinLoadErr error prepareEvidenceEnabled atomic.Bool @@ -365,6 +368,7 @@ func NewKvFSMWithHLC(store store.MVCCStore, hlc *HLC, opts ...FSMOption) FSM { f.backupFloorLoadErr = f.reloadBackupTimestampFloor(context.Background()) f.replicatedPinLoadErr = f.reloadReplicatedBackupPins(context.Background()) f.ttlInlineCapabilityLoadErr = f.reloadTTLInlineCapability(context.Background()) + f.versionRetirementLoadErr = f.configureVersionRetirement() f.snapLatch.log = f.log observeStoreLastCommitTS(hlc, store) return f @@ -433,8 +437,8 @@ func (f *kvFSM) Apply(data []byte) any { if f.replicatedPinLoadErr != nil { return replicatedBackupHalt(f.replicatedPinLoadErr, "load journal") } - if f.ttlInlineCapabilityLoadErr != nil { - return haltErr(errors.Wrap(f.ttlInlineCapabilityLoadErr, "kv/fsm: load TTL-inline capability")) + if err := errors.Join(f.ttlInlineCapabilityLoadErr, f.versionRetirementLoadErr); err != nil { + return haltErr(errors.Wrap(err, "kv/fsm: load read/write capabilities")) } if f.backupFloorLoadErr != nil { return haltErr(errors.Wrap(errors.Mark(f.backupFloorLoadErr, ErrBackupApply), "kv/fsm: load backup timestamp floor")) @@ -449,6 +453,12 @@ func (f *kvFSM) Apply(data []byte) any { if resp, handled := f.applyGuardedBootstrap(ctx, data); handled { return resp } + if raftengine.IsVersionCASRaftPayload(data) { + return f.applyVersionCASFrame(ctx, data) + } + if IsMigrationVersionIdentityActivation(data) { + return f.applyMigrationVersionIdentityActivation(ctx, data) + } if resp, handled := f.applyReservedOpcode(ctx, data); handled { return resp } @@ -461,6 +471,9 @@ func (f *kvFSM) applyRaftDataRequests(ctx context.Context, data []byte) (respons if err != nil { return errors.WithStack(err) } + if HasCASMutation(reqs) { + return haltErr(errors.Mark(errors.New("version CAS mutation outside its Raft frame"), ErrRaftEntryApply)) + } if response, handled := f.applyOnlineMigrationRequests(ctx, data, reqs); handled { return response } @@ -906,29 +919,37 @@ func (f *kvFSM) applyRequestErr(ctx context.Context, r *pb.Request) error { } func (f *kvFSM) applyRequestData(ctx context.Context, r *pb.Request) (uint64, error) { - if err := f.verifyApplyRequestIngress(ctx, r); err != nil { + ctx, commitTS, err := f.prepareRequestForApply(ctx, r) + if err != nil { return 0, err } + if err := f.handleRequest(ctx, r, commitTS); err != nil { + return 0, errors.WithStack(err) + } + return commitTS, nil +} + +func (f *kvFSM) prepareRequestForApply(ctx context.Context, r *pb.Request) (context.Context, uint64, error) { + if err := f.verifyApplyRequestIngress(ctx, r); err != nil { + return ctx, 0, err + } ctx = context.WithValue(ctx, applyReadinessContextKey{}, struct{}{}) var err error ctx, err = f.withMigrationOwnershipEvidence(ctx, r) if err != nil { - return 0, markMigrationApplyRejection(r, err) + return ctx, 0, markMigrationApplyRejection(r, err) } if err := f.verifyPrepareCreationGate(r); err != nil { - return 0, err + return ctx, 0, err } commitTS, err := requestCommitTS(r) if err != nil { - return 0, err + return ctx, 0, err } if err := f.verifyBackupTimestampFloor(r, commitTS); err != nil { - return 0, err - } - if err := f.handleRequest(ctx, r, commitTS); err != nil { - return 0, errors.WithStack(err) + return ctx, 0, err } - return commitTS, nil + return ctx, commitTS, nil } func (f *kvFSM) verifyApplyRequestIngress(ctx context.Context, r *pb.Request) error { @@ -1718,13 +1739,54 @@ var routeMappedRawPrefixes = append([][]byte{ var ErrNotImplemented = errors.New("not implemented") func (f *kvFSM) Snapshot() (raftengine.Snapshot, error) { + return f.captureSnapshot(false) +} + +var _ raftengine.OwnerSnapshotCapturer = (*kvFSM)(nil) + +func (f *kvFSM) CaptureOwnerSnapshot() (raftengine.Snapshot, error) { + return f.captureSnapshot(true) +} + +// Guard the entire envelope, including the header and stores reached by fallback. +type ownedKVSnapshot struct { + mu sync.Mutex + snapshot raftengine.Snapshot + closeErr error +} + +func (s *ownedKVSnapshot) WriteTo(w io.Writer) (int64, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.snapshot == nil { + return 0, errors.New("owned snapshot is closed") + } + n, err := s.snapshot.WriteTo(w) + return n, errors.WithStack(err) +} + +func (s *ownedKVSnapshot) Close() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.snapshot != nil { + s.closeErr = s.snapshot.Close() + s.snapshot = nil + } + return s.closeErr +} + +func (f *kvFSM) captureSnapshot(owned bool) (raftengine.Snapshot, error) { if err := f.rejectSnapshotWithActiveBackupPin(); err != nil { return nil, err } if err := f.checkSnapshotCheckpointConsistency(); err != nil { return nil, err } - snapshot, err := f.store.Snapshot() + capture := f.store.Snapshot + if owner, ok := f.store.(store.OwnerSnapshotCapturer); owned && ok { + capture = owner.CaptureOwnerSnapshot + } + snapshot, err := capture() if err != nil { return nil, errors.WithStack(err) } @@ -1736,13 +1798,17 @@ func (f *kvFSM) Snapshot() (raftengine.Snapshot, error) { emitted := f.snapLatch.observe(cutover) useV2 := emitted != 0 || f.snapLatch.latched() || f.encryptionCheckpoint.Index != 0 - return &kvFSMSnapshot{ + envelope := &kvFSMSnapshot{ snapshot: snapshot, ceilingMs: hlcCeilingFromHLC(f.hlc), cutover: emitted, useV2: useV2, checkpoint: f.encryptionCheckpoint, - }, nil + } + if owned { + return &ownedKVSnapshot{snapshot: envelope}, nil + } + return envelope, nil } func (f *kvFSM) Restore(r io.Reader) error { @@ -1802,6 +1868,10 @@ func (f *kvFSM) reloadSnapshotControlState() error { if f.backupFloorLoadErr != nil { return errors.Wrap(f.backupFloorLoadErr, "restore backup timestamp floor") } + f.versionRetirementLoadErr = f.configureVersionRetirement() + if f.versionRetirementLoadErr != nil { + return errors.Wrap(f.versionRetirementLoadErr, "restore version retirement") + } f.replicatedPinLoadErr = f.reloadReplicatedBackupPins(context.Background()) if f.replicatedPinLoadErr != nil { return errors.Wrap(f.replicatedPinLoadErr, "restore replicated backup pins") @@ -3076,7 +3146,7 @@ func txnIntentFromPBMutation(mut *pb.Mutation, startTS uint64) (txnIntent, error return txnIntent{StartTS: startTS, Op: txnIntentOpPut, Value: mut.Value}, nil case pb.Op_DEL: return txnIntent{StartTS: startTS, Op: txnIntentOpDel, Value: nil}, nil - case pb.Op_DEL_PREFIX: + case pb.Op_DEL_PREFIX, pb.Op_COMPARE_AND_SWAP: return txnIntent{}, errors.WithStack(ErrUnknownRequestType) default: return txnIntent{}, errors.WithStack(ErrUnknownRequestType) @@ -3391,7 +3461,7 @@ func toStoreMutations(muts []*pb.Mutation) ([]*store.KVPairMutation, error) { Key: mut.Key, RequireAbsent: mut.RequireAbsent, }) - case pb.Op_DEL_PREFIX: + case pb.Op_DEL_PREFIX, pb.Op_COMPARE_AND_SWAP: return nil, ErrUnknownRequestType default: return nil, ErrUnknownRequestType diff --git a/kv/fsm_append_batch.go b/kv/fsm_append_batch.go new file mode 100644 index 000000000..1d8d1d189 --- /dev/null +++ b/kv/fsm_append_batch.go @@ -0,0 +1,47 @@ +package kv + +import ( + "bytes" + + "github.com/bootjp/elastickv/internal/raftengine" +) + +var _ raftengine.AppendBatchClassifier = (*kvFSM)(nil) + +func (*kvFSM) IsAppendBatchPayload(payload []byte) bool { + if put := boundedProposalTurnPut(payload); put != nil { + // The validated read set is either empty or exactly the written key. + return len(put.ReadKeys) == 1 && put.ObservedRouteVersion != 0 + } + if len(payload) > maxMarshaledCommandSize || !bytes.HasPrefix(payload, []byte(versionCASFrame)) { + return false + } + // The decoder checks the standalone CAS shape, including the user key and + // route proof. An admission term belongs only to a timestamp-bound request. + req, err := DecodeVersionCASRaftPayload(payload) + if err != nil || req.GetTimestampBindingAdmissionTerm() != 0 || len(req.ProtoReflect().GetUnknown()) != 0 { + return false + } + for _, mutation := range req.GetMutations() { + if len(mutation.ProtoReflect().GetUnknown()) != 0 { + return false + } + } + return appendBatchMetadataIsComplete(req.Mutations[0].Value, req.Mutations[1].Key) +} + +func appendBatchMetadataIsComplete(meta, primary []byte) bool { + if len(meta) == 0 { + return false + } + switch meta[0] { + case txnMetaVersionV1: + // Shape validation matched the decoded primary to the CAS key. + // Legacy V1 reads allow a suffix after that primary. + return len(meta)-txnMetaV1HeaderSize == len(primary) + case txnMetaVersionV2: + return true // The V2 decoder already checked for trailing bytes. + default: + return false + } +} diff --git a/kv/fsm_append_batch_benchmark_test.go b/kv/fsm_append_batch_benchmark_test.go new file mode 100644 index 000000000..29ccef20f --- /dev/null +++ b/kv/fsm_append_batch_benchmark_test.go @@ -0,0 +1,62 @@ +package kv + +import ( + "bytes" + "testing" + + pb "github.com/bootjp/elastickv/proto" + "google.golang.org/protobuf/proto" +) + +func appendClassifierBenchmarkFrame(b *testing.B, request *pb.Request) []byte { + b.Helper() + frame, err := marshalRaftCommand([]*pb.Request{request}) + if err != nil { + b.Fatal(err) + } + return frame +} + +func BenchmarkIsAppendBatchPayload(b *testing.B) { + fresh := freshAppendPut() + fresh.Mutations[1].Value = bytes.Repeat([]byte("v"), 1024) + small := appendClassifierBenchmarkFrame(b, fresh) + large := proto.CloneOf(fresh) + large.Mutations[1].Value = make([]byte, maxProposalTurnPayloadSize) + oversize := appendClassifierBenchmarkFrame(b, large) + valueSize := len(large.Mutations[1].Value) - (len(oversize) - maxProposalTurnPayloadSize) + large.Mutations[1].Value = large.Mutations[1].Value[:valueSize] + maximum := appendClassifierBenchmarkFrame(b, large) + if len(maximum) != maxProposalTurnPayloadSize { + b.Fatalf("maximum frame has %d bytes", len(maximum)) + } + plain := proto.CloneOf(fresh) + plain.ReadKeys = nil + cas := casApplyRequest(15, 20, 10, "key", string(bytes.Repeat([]byte("v"), 1024))) + for _, tc := range []struct { + name string + payload []byte + want bool + }{ + {"fresh-value-1KiB", small, true}, + {"fresh-frame-128KiB", maximum, true}, + {"existing-CAS-value-1KiB", appendClassifierBenchmarkFrame(b, cas), true}, + {"plain-PUT-fallback", appendClassifierBenchmarkFrame(b, plain), false}, + {"control-fallback", EncodeCommitTSFenceActivation(), false}, + {"truncated-fallback", small[:len(small)-1], false}, + } { + b.Run(tc.name, func(b *testing.B) { + var f *kvFSM + if got := f.IsAppendBatchPayload(tc.payload); got != tc.want { + b.Fatalf("classification = %t, want %t", got, tc.want) + } + b.ReportAllocs() + b.SetBytes(int64(len(tc.payload))) + for b.Loop() { + if got := f.IsAppendBatchPayload(tc.payload); got != tc.want { + b.Fatalf("classification = %t, want %t", got, tc.want) + } + } + }) + } +} diff --git a/kv/fsm_append_batch_reordered_test.go b/kv/fsm_append_batch_reordered_test.go new file mode 100644 index 000000000..b5bdd909a --- /dev/null +++ b/kv/fsm_append_batch_reordered_test.go @@ -0,0 +1,43 @@ +package kv + +import ( + "bytes" + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" +) + +func TestIsAppendBatchPayloadFreshReorderedFields(t *testing.T) { + req := freshAppendPut() + normal := proposalTurnTestFrame(t, []byte{raftEncodeSingle}, req) + body := normal[1:] + first, _, size := protowire.ConsumeField(body) + require.Positive(t, size) + + // Move every occurrence of the first field to the end in wire order. + // Repeated mutations retain their order whichever field comes first. + frame := []byte{raftEncodeSingle} + var moved []byte + for len(body) > 0 { + number, _, n := protowire.ConsumeField(body) + require.Positive(t, n) + if number == first { + moved = append(moved, body[:n]...) + } else { + frame = append(frame, body[:n]...) + } + body = body[n:] + } + frame = append(frame, moved...) + require.NotEqual(t, normal, frame) + var decoded pb.Request + require.NoError(t, proto.Unmarshal(frame[1:], &decoded)) + require.True(t, proto.Equal(req, &decoded)) + + before := bytes.Clone(frame) + require.True(t, (*kvFSM)(nil).IsAppendBatchPayload(frame)) + require.Equal(t, before, frame) +} diff --git a/kv/fsm_append_batch_test.go b/kv/fsm_append_batch_test.go new file mode 100644 index 000000000..3e65bf5aa --- /dev/null +++ b/kv/fsm_append_batch_test.go @@ -0,0 +1,193 @@ +package kv + +import ( + "bytes" + "testing" + + "github.com/bootjp/elastickv/internal/encryption/fsmwire" + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" +) + +func TestIsAppendBatchPayload(t *testing.T) { + req := casApplyRequest(15, 20, 10, "key", "\x00after\xff") + frame, err := marshalRaftCommand([]*pb.Request{req}) + require.NoError(t, err) + before := bytes.Clone(frame) + var f *kvFSM // Classification needs no FSM state. + require.True(t, f.IsAppendBatchPayload(frame)) + require.Equal(t, before, frame) + + put := onePhaseReq(15, 20, 0, []byte("key"), []byte("after")) + single, err := marshalRaftCommand([]*pb.Request{put}) + require.NoError(t, err) + batch, err := marshalRaftCommand([]*pb.Request{put, put}) + require.NoError(t, err) + for _, tc := range []struct { + name string + payload []byte + }{ + {"empty", nil}, + {"ordinary put", single}, + {"ordinary batch", batch}, + {"unframed CAS", frame[len(versionCASFrame):]}, + {"unsupported CAS version", append([]byte("\x06CAS\xff"), frame[len(versionCASFrame):]...)}, + {"truncated prefix", frame[:len(versionCASFrame)-1]}, + {"missing body", frame[:len(versionCASFrame)]}, + {"truncated body", frame[:len(frame)-1]}, + {"migration activation", EncodeMigrationVersionIdentityActivation()}, + {"commit timestamp fence activation", EncodeCommitTSFenceActivation()}, + {"timestamp lease", marshalHLCLeaseRenew(20)}, + {"encryption control", prependByte(fsmwire.OpRegistration, frame)}, + {"migration cleanup", prependByte(raftEncodeMigrationCleanup, frame)}, + } { + t.Run(tc.name, func(t *testing.T) { + require.False(t, f.IsAppendBatchPayload(tc.payload)) + }) + } +} + +func TestIsAppendBatchPayloadRejectsInvalidCAS(t *testing.T) { + unknown := protowire.AppendVarint(protowire.AppendTag(nil, 100, protowire.VarintType), 1) + for _, tc := range []struct { + name string + edit func(*pb.Request) + }{ + {"missing expected version", func(r *pb.Request) { r.Mutations[1].ExpectedCommitTs = 0 }}, + {"missing route version", func(r *pb.Request) { r.ObservedRouteVersion = 0 }}, + {"write fence bypass", func(r *pb.Request) { r.WriteFenceBypassKeys = [][]byte{r.Mutations[1].Key} }}, + {"extra mutation", func(r *pb.Request) { r.Mutations = append(r.Mutations, r.Mutations[1]) }}, + {"orphan binding term", func(r *pb.Request) { r.TimestampBindingAdmissionTerm = 1 }}, + {"unknown request field", func(r *pb.Request) { r.ProtoReflect().SetUnknown(unknown) }}, + {"unknown header field", func(r *pb.Request) { r.Mutations[0].ProtoReflect().SetUnknown(unknown) }}, + {"unknown CAS mutation field", func(r *pb.Request) { r.Mutations[1].ProtoReflect().SetUnknown(unknown) }}, + } { + t.Run(tc.name, func(t *testing.T) { + req := casApplyRequest(15, 20, 10, "key", "after") + tc.edit(req) + // Bypass proposal validation to exercise the receiving FSM boundary. + body, err := proto.Marshal(req) + require.NoError(t, err) + require.False(t, (*kvFSM)(nil).IsAppendBatchPayload(append([]byte(versionCASFrame), body...))) + }) + } +} + +func TestIsAppendBatchPayloadTxnMeta(t *testing.T) { + meta := TxnMeta{PrimaryKey: []byte("key"), CommitTS: 20} + emptyPrimary := TxnMeta{CommitTS: 20} + legacyEmpty := append(encodeTxnMetaV1(emptyPrimary), 0xff) + decoded, err := DecodeTxnMeta(legacyEmpty) + require.NoError(t, err) + require.Equal(t, emptyPrimary, decoded) + + for _, tc := range []struct { + name string + wire []byte + wantFrame bool + wantBatch bool + }{ + {"V1", encodeTxnMetaV1(meta), true, true}, + {"V2", encodeTxnMetaV2(meta), true, true}, + {"V1 trailing", append(encodeTxnMetaV1(meta), 0xff), true, false}, + {"V1 zero primary trailing", legacyEmpty, false, false}, + {"V2 trailing", append(encodeTxnMetaV2(meta), 0xff), false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + req := casApplyRequest(15, 20, 10, "key", "after") + req.Mutations[0].Value = tc.wire + body, err := proto.Marshal(req) + require.NoError(t, err) + frame := append([]byte(versionCASFrame), body...) + _, err = DecodeVersionCASRaftPayload(frame) + if tc.wantFrame { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, ErrInvalidRequest) + } + require.Equal(t, tc.wantBatch, (*kvFSM)(nil).IsAppendBatchPayload(frame)) + }) + } +} + +func freshAppendPut() *pb.Request { + req := proposalTurnPut() + req.ReadKeys = [][]byte{req.Mutations[1].Key} + req.ObservedRouteVersion = EncodeObservedRouteVersion(1) + return req +} + +// The follower's existing CAS predicate has different limits and V2 metadata +// rules from the leader proposal turn. Preserve both independently. +func TestIsAppendBatchPayloadPreservesCASRules(t *testing.T) { + req := casApplyRequest(15, 20, 10, "key", "value") + meta := encodeTxnMetaV2(TxnMeta{PrimaryKey: req.Mutations[1].Key, CommitTS: 20}) + meta[1] |= txnMetaFlagPrevCommitTS + meta = append(meta, make([]byte, uint64FieldSize)...) + req.Mutations[0].Value = meta + frame := proposalTurnTestFrame(t, []byte(versionCASFrame), req) + var f *kvFSM + require.False(t, f.IsProposalTurnPayload(frame)) + require.True(t, f.IsAppendBatchPayload(frame)) + req = casApplyRequest(15, 20, 10, "key", "value") + req.Mutations[1].Value = make([]byte, maxProposalTurnPayloadSize) + frame = proposalTurnTestFrame(t, []byte(versionCASFrame), req) + require.False(t, f.IsProposalTurnPayload(frame)) + require.True(t, f.IsAppendBatchPayload(frame)) +} + +func TestIsAppendBatchPayloadFreshShape(t *testing.T) { + unknown := protowire.AppendVarint(protowire.AppendTag(nil, 100, protowire.VarintType), 1) + for _, tc := range []struct { + name string + edit func(*pb.Request) + }{ + {"no read dependency", func(r *pb.Request) { r.ReadKeys = nil }}, + {"no route proof", func(r *pb.Request) { r.ObservedRouteVersion = 0 }}, + {"different read key", func(r *pb.Request) { r.ReadKeys = [][]byte{[]byte("other")} }}, + {"repeated read key", func(r *pb.Request) { r.ReadKeys = append(r.ReadKeys, r.ReadKeys[0]) }}, + {"extra write", func(r *pb.Request) { r.Mutations = append(r.Mutations, &pb.Mutation{Key: []byte("other")}) }}, + {"internal namespace", func(r *pb.Request) { + key := []byte("!mig|alias|key") + r.Mutations[1].Key, r.ReadKeys[0] = key, key + r.Mutations[0].Value = EncodeTxnMeta(TxnMeta{PrimaryKey: key, CommitTS: 20}) + }}, + {"retry", func(r *pb.Request) { + r.Mutations[0].Value = EncodeTxnMeta(TxnMeta{PrimaryKey: r.ReadKeys[0], CommitTS: 20, PrevCommitTS: 12}) + }}, + {"binding", func(r *pb.Request) { r.TimestampBindingOperationId = []byte("op") }}, + {"request unknown", func(r *pb.Request) { r.ProtoReflect().SetUnknown(unknown) }}, + {"mutation unknown", func(r *pb.Request) { r.Mutations[1].ProtoReflect().SetUnknown(unknown) }}, + {"header unknown", func(r *pb.Request) { r.Mutations[0].ProtoReflect().SetUnknown(unknown) }}, + } { + t.Run(tc.name, func(t *testing.T) { + req := freshAppendPut() + tc.edit(req) + frame := proposalTurnTestFrame(t, []byte{raftEncodeSingle}, req) + require.False(t, (*kvFSM)(nil).IsAppendBatchPayload(frame)) + }) + } +} + +func TestIsAppendBatchPayloadFreshSizeAndFraming(t *testing.T) { + req := freshAppendPut() + batch, err := marshalRaftCommand([]*pb.Request{req, req}) + require.NoError(t, err) + var f *kvFSM + require.False(t, f.IsAppendBatchPayload(batch)) + req.Mutations[1].Value = make([]byte, maxProposalTurnPayloadSize) + frame := proposalTurnTestFrame(t, []byte{raftEncodeSingle}, req) + excess := len(frame) - maxProposalTurnPayloadSize + req.Mutations[1].Value = req.Mutations[1].Value[:maxProposalTurnPayloadSize-excess+1] + frame = proposalTurnTestFrame(t, []byte{raftEncodeSingle}, req) + require.Len(t, frame, maxProposalTurnPayloadSize+1) + require.False(t, f.IsAppendBatchPayload(frame)) + req.Mutations[1].Value = req.Mutations[1].Value[:len(req.Mutations[1].Value)-1] + frame = proposalTurnTestFrame(t, []byte{raftEncodeSingle}, req) + require.Len(t, frame, maxProposalTurnPayloadSize) + before := bytes.Clone(frame) + require.True(t, f.IsAppendBatchPayload(frame)) + require.Equal(t, before, frame) +} diff --git a/kv/fsm_cas.go b/kv/fsm_cas.go new file mode 100644 index 000000000..f9455d515 --- /dev/null +++ b/kv/fsm_cas.go @@ -0,0 +1,171 @@ +package kv + +import ( + "context" + + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" +) + +// ErrCASMismatch means the latest logical record failed the exact-version +// predicate at the replicated commit timestamp. +var ErrCASMismatch = errors.New("compare-and-swap version mismatch") + +func requestUsesCAS(req *pb.Request) bool { + for _, mut := range req.GetMutations() { + if usesCAS(mut) { + return true + } + } + return false +} + +func usesCAS(mut *pb.Mutation) bool { + return mut.GetOp() == pb.Op_COMPARE_AND_SWAP || mut.GetExpectedCommitTs() != 0 +} + +func (f *kvFSM) applyCASEntry(ctx context.Context, reqs []*pb.Request, apply func(context.Context, *pb.Request) error) any { + applier, ok := f.store.(store.RaftEntryApplier) + if !ok { + return casEntryHalt(store.ErrNotSupported) + } + resp := &fsmApplyResponse{results: make([]error, len(reqs))} + f.beginDeferredApplyNotices() + err := applier.ApplyRaftEntry(ctx, f.pendingApplyIdx, func(ctx context.Context) error { + return f.stageCASEntry(ctx, reqs, resp.results, apply) + }) + if err != nil { + f.discardDeferredApplyNotices() + return casEntryHalt(err) + } + f.flushDeferredApplyNotices() + if len(reqs) == 1 { + return resp.results[0] + } + for _, err := range resp.results { + if err != nil { + return resp + } + } + return nil +} + +func (f *kvFSM) stageCASEntry(ctx context.Context, reqs []*pb.Request, results []error, apply func(context.Context, *pb.Request) error) error { + replayed, err := store.StageRaftEntryProgress(ctx, f.pendingApplyIdx) + if err != nil || replayed { + return errors.WithStack(err) + } + for i, req := range reqs { + err := apply(ctx, req) + if err != nil && !isCASApplyVerdict(err) { + return errors.Wrapf(err, "CAS request %d", i) + } + results[i] = err + } + return nil +} + +func (f *kvFSM) applyFramedCAS(ctx context.Context, req *pb.Request) error { + mut := req.Mutations[1] + // A committed owner change or write fence takes precedence over the + // more general exclusion of ranges with migration history. + if err := f.checkAppliedVersionCASRoute(ctx, req.GetVersionCasGroupId(), req.GetObservedRouteVersion(), mut.Key); err != nil { + return err + } + if err := f.verifySourceWriteFenceForRange(ctx, mut.Key, nextScanCursor(mut.Key)); err != nil { + return err + } + if err := checkVersionCASMigrationRange(ctx, f.store, mut.Key); err != nil { + return err + } + ctx, commitTS, err := f.prepareRequestForApply(ctx, req) + if err != nil { + return err + } + // The catalog and migration guards proved this is an initial range + // without staged visibility aliases. + return f.compareAndStageCAS(ctx, mut, nil, req.GetTs(), commitTS) +} + +func casEntryHalt(err error) any { + if classified := haltResponseFor(err); classified != nil { + err = classified.HaltApply() + } + return haltErr(errors.Wrap(errors.Mark(err, ErrRaftEntryApply), "kv/fsm: apply CAS entry")) +} + +func isCASApplyVerdict(err error) bool { + if haltResponseFor(err) != nil { + return false + } + return isRawApplyVerdict(err) || errors.Is(err, ErrCASMismatch) || + errors.Is(err, ErrTxnCommitTSRequired) || errors.Is(err, ErrVersionCASUnavailable) +} + +func (f *kvFSM) compareAndStageCAS(ctx context.Context, mut *pb.Mutation, readKeys [][]byte, startTS, commitTS uint64) error { + _, _, _, locked, err := f.txnLockForMutationKey(ctx, mut.Key, readKeys) + if err != nil { + return err + } + if locked { + return NewTxnLockedError(mut.Key) + } + watermark, err := store.RaftEntryCommitWatermark(ctx) + if err != nil { + return errors.WithStack(err) + } + if commitTS <= watermark { + return errors.WithStack(store.NewWriteConflictError(mut.Key)) + } + head, err := latestCASRecord(ctx, mut.Key, readKeys) + if err != nil { + return err + } + if !casRecordMatches(head, mut.ExpectedCommitTs, commitTS) { + return ErrCASMismatch + } + // The token matches. A start timestamp behind that version still fails OCC. + if head.TS > startTS { + return errors.WithStack(store.NewWriteConflictError(mut.Key)) + } + return f.stageCASReplacement(ctx, mut, readKeys, startTS, commitTS, head.ExpireAt) +} + +func casRecordMatches(head store.VersionedValue, expectedTS, commitTS uint64) bool { + return head.TS == expectedTS && !head.Tombstone && (head.ExpireAt == 0 || head.ExpireAt > commitTS) +} + +func latestCASRecord(ctx context.Context, key []byte, readKeys [][]byte) (store.VersionedValue, error) { + keys := append([][]byte{key}, stagedVisibilityKeysForReadAlias(readKeys, key, key)...) + var head store.VersionedValue + for _, key := range keys { + record, err := store.RaftEntryLatestRecord(ctx, key) + if errors.Is(err, store.ErrKeyNotFound) { + continue + } + if err != nil { + return store.VersionedValue{}, errors.WithStack(err) + } + // When versions tie, the staged alias wins as on the point-read path. + if record.TS >= head.TS { + head = record + } + } + return head, nil +} + +func (f *kvFSM) stageCASReplacement(ctx context.Context, mut *pb.Mutation, readKeys [][]byte, startTS, commitTS, expireAt uint64) error { + muts := []*store.KVPairMutation{{Op: store.OpTypePut, Key: mut.Key, Value: mut.Value, ExpireAt: expireAt}} + if err := f.verifyMigrationTransferSize(ctx, muts); err != nil { + return err + } + if err := f.store.ApplyMutationsRaftAtFenced(ctx, muts, readKeys, startTS, commitTS, f.pendingApplyIdx); err != nil { + return errors.WithStack(err) + } + if err := f.recordMigrationWrite(ctx, []*pb.Mutation{mut}, commitTS); err != nil { + return err + } + f.notifyApplyObserver(commitTS, pb.Op_PUT, mut.Key) + return nil +} diff --git a/kv/fsm_cas_test.go b/kv/fsm_cas_test.go new file mode 100644 index 000000000..80c77792f --- /dev/null +++ b/kv/fsm_cas_test.go @@ -0,0 +1,433 @@ +package kv + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftbootstrap" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func applyDecodedCASBatch(t *testing.T, f *kvFSM, reqs []*pb.Request) any { + t.Helper() + return f.applyCASEntry(t.Context(), reqs, func(ctx context.Context, r *pb.Request) error { + if err := validateCASProposalShape([]*pb.Request{r}); err != nil { + return err + } + ctx, commitTS, err := f.prepareRequestForApply(ctx, r) + if err != nil { + return err + } + muts := r.Mutations[1:] + readKeys, err := f.onePhaseConflictReadKeys(ctx, muts, r.ReadKeys) + if err != nil { + return err + } + return f.compareAndStageCAS(ctx, muts[0], readKeys, r.Ts, commitTS) + }) +} + +func casApplyRequest(startTS, commitTS, expectedTS uint64, key, value string) *pb.Request { + req := onePhaseReq(startTS, commitTS, 0, []byte(key), []byte(value)) + req.Mutations[1].Op = pb.Op_COMPARE_AND_SWAP + req.Mutations[1].ExpectedCommitTs = expectedTS + req.VersionCasGroupId = 1 + req.ObservedRouteVersion = 1 + return req +} + +func applyCASFrame(t *testing.T, f *kvFSM, index uint64, req *pb.Request) any { + t.Helper() + bindCASTestGroup(f) + payload, err := marshalRaftCommand([]*pb.Request{req}) + require.NoError(t, err) + f.SetApplyIndex(index) + return f.Apply(payload) +} + +// The initial rollout excludes migration ranges before the predicate. This +// helper exercises the shared atomic apply path with migration evidence armed. +func applyCASInScope(t *testing.T, f *kvFSM, index uint64, req *pb.Request) any { + t.Helper() + f.SetApplyIndex(index) + return applyDecodedCASBatch(t, f, []*pb.Request{req}) +} + +func enableCASApplyForTest(t *testing.T, f *kvFSM) { + t.Helper() + bindCASTestGroup(f) + seedCASTestCatalog(t, f.store, f.shardGroupID) + enableCASMarkersForTest(t, f) +} + +func bindCASTestGroup(f *kvFSM) { + if f.shardGroupID == 0 { + f.shardGroupID = 1 + } + f.raftBootstrapIdentity = raftbootstrap.Identity{Cluster: raftbootstrap.UUID{1}, Group: f.shardGroupID} +} + +func seedCASTestCatalog(t *testing.T, st store.MVCCStore, groupID uint64) { + t.Helper() + plan, err := distribution.NewCatalogStore(st).BuildBootstrapPlanAt(t.Context(), 1, []distribution.Route{ + {GroupID: groupID, State: distribution.RouteStateActive}, + }) + require.NoError(t, err) + require.NoError(t, st.ApplyMutationsRaftAtFenced(t.Context(), plan.Mutations, plan.ReadKeys, 1, 2, 0)) +} + +func enableCASMarkersForTest(t *testing.T, f *kvFSM) { + t.Helper() + seedCASReaderPolicyForTest(t, f) + activateCommitTSFence(t, f) + f.SetApplyIndex(1) + require.Nil(t, f.Apply(EncodeMigrationVersionIdentityActivation())) +} + +func seedCASReaderPolicyForTest(t *testing.T, f *kvFSM) { + t.Helper() + metadata, ok := f.store.(store.RaftControlMetadataStore) + require.True(t, ok) + key, err := BootstrapPolicyMetadataKey(f.raftBootstrapIdentity) + require.NoError(t, err) + _, err = metadata.ReadRaftControlMetadata(t.Context(), key) + if !errors.Is(err, store.ErrKeyNotFound) { + require.NoError(t, err) + return + } + policy := guardedNewPolicy() + policy.Identity = f.raftBootstrapIdentity + policy.ActivationIndex, policy.LastConfigurationIndex, policy.Configuration.Index = 1, 1, 1 + // Unit fixtures start immediately before the first indexed activation. + // Real protected startup is separately exercised with three native voters. + require.NoError(t, metadata.ApplyRaftControlMetadata(t.Context(), func(ctx context.Context) error { + stageGuardedNewPolicy(t, ctx, f.store, policy) + return nil + })) +} + +func TestFSMCASABAExpiryAndOrder(t *testing.T) { + t.Parallel() + for _, backend := range []string{"memory", "pebble"} { + t.Run(backend, func(t *testing.T) { + t.Parallel() + var st store.MVCCStore + if backend == "pebble" { + var err error + st, err = store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + } else { + st = store.NewMVCCStore() + } + t.Cleanup(func() { require.NoError(t, st.Close()) }) + f, ok := NewKvFSMWithHLC(st, NewHLC()).(*kvFSM) + require.True(t, ok) + enableCASApplyForTest(t, f) + + ctx := t.Context() + key := []byte("k") + require.NoError(t, st.PutAt(ctx, key, []byte("A"), 10, 0)) + require.NoError(t, st.PutAt(ctx, key, []byte("B"), 20, 0)) + require.NoError(t, st.PutAt(ctx, key, []byte("A"), 30, 90)) + + rejected := applyCASFrame(t, f, 2, casApplyRequest(31, 40, 10, "k", "old token")) + requireCASRejection(t, rejected, ErrCASMismatch) + require.NoError(t, st.PutAt(ctx, []byte("unrelated"), []byte("write"), 50, 0)) + rejected = applyCASFrame(t, f, 3, casApplyRequest(31, 45, 30, "k", "old timestamp")) + requireCASRejection(t, rejected, store.ErrWriteConflict) + rejected = applyCASFrame(t, f, 4, casApplyRequest(29, 60, 30, "k", "stale snapshot")) + requireCASRejection(t, rejected, store.ErrWriteConflict) + require.Nil(t, applyCASFrame(t, f, 5, casApplyRequest(60, 70, 30, "k", "A"))) + version, err := store.GetVersionAt(ctx, st, key, 89) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 70, Value: []byte("A"), ExpireAt: 90}, version) + rejected = applyCASFrame(t, f, 6, casApplyRequest(89, 90, 70, "k", "expired")) + requireCASRejection(t, rejected, ErrCASMismatch) + _, err = st.GetAt(ctx, key, 90) + require.ErrorIs(t, err, store.ErrKeyNotFound) + + require.NoError(t, st.DeleteAt(ctx, key, 100)) + rejected = applyCASFrame(t, f, 7, casApplyRequest(101, 110, 100, "k", "tombstone")) + requireCASRejection(t, rejected, ErrCASMismatch) + require.NoError(t, st.PutAt(ctx, key, []byte("A"), 120, 0)) + rejected = applyCASFrame(t, f, 8, casApplyRequest(121, 130, 70, "k", "before delete")) + requireCASRejection(t, rejected, ErrCASMismatch) + rejected = applyCASFrame(t, f, 9, casApplyRequest(131, 135, 120, "missing", "must not create")) + requireCASRejection(t, rejected, ErrCASMismatch) + require.Nil(t, applyCASFrame(t, f, 10, casApplyRequest(136, 140, 120, "k", ""))) + version, err = store.GetVersionAt(ctx, st, key, 140) + require.NoError(t, err) + require.Equal(t, uint64(140), version.TS) + require.Empty(t, version.Value) + }) + } +} + +func requireCASRejection(t *testing.T, resp any, want error) { + t.Helper() + got, ok := resp.(error) + require.True(t, ok, "response = %v", resp) + require.ErrorIs(t, got, want) +} + +func TestFSMCASRejectsInvalidApplyShapes(t *testing.T) { + t.Parallel() + f, st := newCommitTSFenceFSM(t) + require.NoError(t, st.PutAt(t.Context(), []byte("k"), []byte("original"), 10, 0)) + resp := applyCASFrame(t, f, 1, casApplyRequest(11, 20, 10, "k", "no fence")) + _, halted := resp.(interface{ HaltApply() error }) + require.True(t, halted, "frame without the replicated fence returned %v", resp) + enableCASMarkersForTest(t, f) + + raw := casApplyRequest(11, 20, 10, "k", "raw") + raw.IsTxn = false + twoPhase := casApplyRequest(11, 20, 10, "k", "two phase") + twoPhase.Phase = pb.Phase_PREPARE + multiKey := casApplyRequest(11, 20, 10, "k", "multiple keys") + multiKey.Mutations = append(multiKey.Mutations, &pb.Mutation{Op: pb.Op_PUT, Key: []byte("other")}) + internalKey := casApplyRequest(11, 20, 10, string(txnLockKey([]byte("k"))), "internal") + for i, invalid := range []*pb.Request{raw, twoPhase, multiKey, internalKey} { + index := uint64(i + 2) + f.SetApplyIndex(index) + requireCASRejection(t, applyDecodedCASBatch(t, f, []*pb.Request{invalid}), ErrInvalidRequest) + requireCASProgress(t, f, index) + } + got, err := st.GetAt(t.Context(), []byte("k"), 20) + require.NoError(t, err) + require.Equal(t, "original", string(got)) +} + +func TestFSMCASUsesStagedHeadAndLocks(t *testing.T) { + t.Parallel() + engine := distribution.NewEngine() + route := distribution.RouteDescriptor{ + RouteID: 1, Start: []byte("a"), End: []byte("z"), GroupID: 1, + State: distribution.RouteStateActive, StagedVisibilityActive: true, + MigrationJobID: 9, MinWriteTSExclusive: 20, + } + applyComposed1Snapshot(t, engine, 2, []distribution.RouteDescriptor{route}) + st, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + f, ok := NewKvFSMWithHLC(st, NewHLC(), WithRouteHistory(WrapDistributionEngine(engine), 1)).(*kvFSM) + require.True(t, ok) + enableCASApplyForTest(t, f) + installStagedOwnershipEvidence(t, f, 2, route) + + ctx := t.Context() + key := []byte("n") + stagedKey := distribution.MigrationStagedDataKey(9, key) + require.NoError(t, st.PutAt(ctx, key, []byte("old live"), 10, 0)) + require.NoError(t, st.PutAt(ctx, stagedKey, []byte("newer staged"), 30, 100)) + stale := casApplyRequest(40, 50, 10, "n", "stale") + requireCASRejection(t, applyCASFrame(t, f, 4, stale), ErrVersionCASUnavailable) + requireCASProgress(t, f, 4) + stale.ObservedRouteVersion = 2 + requireCASRejection(t, applyCASInScope(t, f, 5, stale), ErrCASMismatch) + + stagedLockKey := distribution.MigrationStagedDataKey(9, txnLockKey(key)) + require.NoError(t, st.PutAt(ctx, stagedLockKey, encodeTxnLock(txnLock{ + StartTS: 60, CommitTS: 70, PrimaryKey: key, IsPrimaryKey: true, + }), 60, 0)) + hit := casApplyRequest(61, 75, 30, "n", "new live") + hit.ObservedRouteVersion = 2 + requireCASRejection(t, applyCASInScope(t, f, 6, hit), ErrTxnLocked) + require.NoError(t, st.DeleteAt(ctx, stagedLockKey, 65)) + require.Nil(t, applyCASInScope(t, f, 7, hit)) + requireCASValue(t, st, 90, 75, "new live") +} + +func TestFSMCASStagedContendersAndOperationalRollback(t *testing.T) { + t.Parallel() + f, st := newCommitTSFenceFSM(t) + observer := &recordingApplyObserver{} + f.applyObservers = append(f.applyObservers, observer) + enableCASApplyForTest(t, f) + require.NoError(t, st.PutAt(t.Context(), []byte("k"), []byte("original"), 10, 0)) + require.NoError(t, st.PutAt(t.Context(), txnLockKey([]byte("corrupt")), []byte("broken lock"), 11, 0)) + + winner := casApplyRequest(15, 20, 10, "k", "winner") + f.SetApplyIndex(2) + resp := applyDecodedCASBatch(t, f, []*pb.Request{winner, casApplyRequest(25, 30, 10, "corrupt", "fail")}) + halt, ok := resp.(interface{ HaltApply() error }) + require.True(t, ok, "response = %v", resp) + require.True(t, errors.Is(halt.HaltApply(), ErrRaftEntryApply), "%v", halt.HaltApply()) + require.Empty(t, observer.calls) + requireCASProgress(t, f, 1) + original, err := st.GetAt(t.Context(), []byte("k"), 30) + require.NoError(t, err) + require.Equal(t, "original", string(original)) + + resp = applyDecodedCASBatch(t, f, []*pb.Request{winner, + casApplyRequest(25, 30, 10, "k", "contender"), + casApplyRequest(17, 19, 10, "missing", "out of order"), + casApplyRequest(30, 40, 20, "k", "successor"), + }) + batch, ok := resp.(*fsmApplyResponse) + require.True(t, ok, "response = %v", resp) + require.NoError(t, batch.results[0]) + require.ErrorIs(t, batch.results[1], ErrCASMismatch) + require.ErrorIs(t, batch.results[2], store.ErrWriteConflict) + require.NoError(t, batch.results[3]) + require.Equal(t, []recordedApply{{op: pb.Op_PUT, key: "k"}, {op: pb.Op_PUT, key: "k"}}, observer.calls) + staged, err := store.GetVersionAt(t.Context(), st, []byte("k"), 40) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 40, Value: []byte("successor")}, staged) +} + +type pausingCASStore struct { + store.MVCCStore + store.RaftControlMetadataStore + applier store.RaftEntryApplier + staged chan struct{} + resume chan struct{} +} + +func (s pausingCASStore) ApplyRaftEntry(ctx context.Context, index uint64, fn func(context.Context) error) error { + return s.applier.ApplyRaftEntry(ctx, index, func(ctx context.Context) error { + if err := fn(ctx); err != nil { + return err + } + close(s.staged) + <-s.resume + return nil + }) +} + +func TestFSMCASSerializesWithConcurrentOrdinaryWriter(t *testing.T) { + t.Parallel() + f, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + ctx := t.Context() + key := []byte("k") + require.NoError(t, st.PutAt(ctx, key, []byte("original"), 10, 0)) + applier, ok := st.(store.RaftEntryApplier) + require.True(t, ok) + meta, ok := st.(store.RaftControlMetadataStore) + require.True(t, ok) + wrapped := pausingCASStore{ + MVCCStore: st, RaftControlMetadataStore: meta, applier: applier, + staged: make(chan struct{}), resume: make(chan struct{}), + } + f.store = wrapped + payload, err := marshalRaftCommand([]*pb.Request{casApplyRequest(10, 20, 10, "k", "winner")}) + require.NoError(t, err) + f.SetApplyIndex(2) + applied := make(chan any, 1) + go func() { applied <- f.Apply(payload) }() + select { + case <-wrapped.staged: + case response := <-applied: + t.Fatalf("CAS finished without staging: %v", response) + } + + started := make(chan struct{}) + written := make(chan error, 1) + go func() { + close(started) + muts := []*store.KVPairMutation{{Op: store.OpTypePut, Key: key, Value: []byte("competing put")}} + written <- st.ApplyMutations(ctx, muts, nil, 10, 30) + }() + <-started + close(wrapped.resume) + require.Nil(t, <-applied) + require.ErrorIs(t, <-written, store.ErrWriteConflict) + version, err := store.GetVersionAt(ctx, st, key, 30) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 20, Value: []byte("winner")}, version) +} + +func TestFSMCASMigrationTrackerAndWALReplay(t *testing.T) { + t.Parallel() + dir := t.TempDir() + observer := &recordingApplyObserver{} + open := func() (*kvFSM, store.MVCCStore) { + st, err := store.NewPebbleStore(dir) + require.NoError(t, err) + f, ok := NewKvFSMWithHLC(st, NewHLC(), WithRouteHistory(nil, 1), WithApplyObserver(observer)).(*kvFSM) + require.True(t, ok) + return f, st + } + f, st := open() + enableCASApplyForTest(t, f) + installSourceOwnershipForTest(t, f, 0) + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("original"), 20, 100)) + miss := casApplyRequest(30, 40, 10, "n", "must not land") + miss.ObservedRouteVersion = EncodeObservedRouteVersion(1) + hit := casApplyRequest(41, 50, 20, "n", "replacement") + hit.ObservedRouteVersion = miss.ObservedRouteVersion + + requireCASProgress(t, f, 11) + require.Zero(t, migrationTrackerMinimum(t, f)) + requireCASRejection(t, applyCASInScope(t, f, 12, miss), ErrCASMismatch) + requireCASProgress(t, f, 12) + require.Zero(t, migrationTrackerMinimum(t, f)) + require.Empty(t, observer.calls) + requireCASValue(t, st, 40, 20, "original") + + require.NoError(t, st.Close()) + f, st = open() + requireCASProgress(t, f, 12) + require.Zero(t, migrationTrackerMinimum(t, f)) + requireCASValue(t, st, 40, 20, "original") + + require.Nil(t, applyCASInScope(t, f, 12, miss), "a durable rejection must skip predicate evaluation on replay") + require.Empty(t, observer.calls) + require.NoError(t, st.PutAt(t.Context(), txnLockKey([]byte("b")), []byte("broken lock"), 22, 0)) + f.SetApplyIndex(13) + resp := applyDecodedCASBatch(t, f, []*pb.Request{hit, casApplyRequest(51, 60, 20, "b", "fails operationally")}) + _, halted := resp.(interface{ HaltApply() error }) + require.True(t, halted, "response = %v", resp) + requireCASProgress(t, f, 12) + require.Zero(t, migrationTrackerMinimum(t, f)) + requireCASValue(t, st, 60, 20, "original") + require.Empty(t, observer.calls) + + require.Nil(t, applyCASInScope(t, f, 13, hit)) + requireCASProgress(t, f, 13) + require.Equal(t, uint64(50), migrationTrackerMinimum(t, f)) + requireCASValue(t, st, 60, 50, "replacement") + require.Len(t, observer.calls, 1) + + require.NoError(t, st.Close()) + f, st = open() + t.Cleanup(func() { require.NoError(t, st.Close()) }) + requireCASProgress(t, f, 13) + require.Equal(t, uint64(50), migrationTrackerMinimum(t, f)) + requireCASValue(t, st, 60, 50, "replacement") + require.Nil(t, applyCASInScope(t, f, 13, hit), "success must replay before watermark and CAS checks") + require.Len(t, observer.calls, 1) +} + +func requireCASProgress(t *testing.T, f *kvFSM, want uint64) { + t.Helper() + idx, ok, err := f.LastAppliedIndex() + require.NoError(t, err) + require.True(t, ok) + require.Equal(t, want, idx) +} + +func requireCASValue(t *testing.T, st store.MVCCStore, readTS, wantTS uint64, value string) { + t.Helper() + got, err := store.GetVersionAt(t.Context(), st, []byte("n"), readTS) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: wantTS, Value: []byte(value), ExpireAt: 100}, got) +} + +func TestFSMCASNewerHeadIsAnExactMismatch(t *testing.T) { + f, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + key := []byte("target") + require.NoError(t, st.PutAt(t.Context(), key, []byte("original"), 10, 0)) + require.NoError(t, st.PutAt(t.Context(), key, []byte("intervening write"), 30, 0)) + rejected := applyCASFrame(t, f, 2, casApplyRequest(20, 40, 10, string(key), "replacement")) + requireCASRejection(t, rejected, ErrCASMismatch) + requireCASProgress(t, f, 2) + row, err := store.GetVersionAt(t.Context(), st, key, 40) + require.NoError(t, err) + require.Equal(t, uint64(30), row.TS) +} diff --git a/kv/fsm_migration_cleanup.go b/kv/fsm_migration_cleanup.go index 78201857d..648b7337c 100644 --- a/kv/fsm_migration_cleanup.go +++ b/kv/fsm_migration_cleanup.go @@ -36,6 +36,10 @@ func MarshalMigrationCleanupCommand(req *pb.CleanupMigrationRequest) ([]byte, er func (f *kvFSM) applyMigrationCleanup(ctx context.Context, data []byte) any { req := &pb.CleanupMigrationRequest{} if err := proto.Unmarshal(data, req); err != nil { + protected, markerErr := MigrationVersionIdentityEnabled(ctx, f.store) + if protected || markerErr != nil { + return haltErr(errors.Wrap(errors.Mark(errors.Join(err, markerErr), ErrMigrationCleanupApply), "kv/fsm: decode migration cleanup")) + } return errors.WithStack(err) } if req.GetMode() == pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_NAMESPACE_ADMISSION { @@ -51,6 +55,20 @@ func (f *kvFSM) applyMigrationCleanup(ctx context.Context, data []byte) any { } func (f *kvFSM) applyMigrationCleanupRequest(ctx context.Context, req *pb.CleanupMigrationRequest) any { + if migrationOwnershipControlMode(req.GetMode()) || req.GetMode() == pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_METADATA { + return f.applyLegacyMigrationCleanupRequest(ctx, req) + } + protected, err := MigrationVersionIdentityEnabled(ctx, f.store) + if err != nil { + return haltErr(errors.Wrap(errors.Mark(err, ErrMigrationCleanupApply), "kv/fsm: load migration version identity")) + } + if protected { + return f.applyVersionIdentityCleanup(ctx, req) + } + return f.applyLegacyMigrationCleanupRequest(ctx, req) +} + +func (f *kvFSM) applyLegacyMigrationCleanupRequest(ctx context.Context, req *pb.CleanupMigrationRequest) any { if err := f.verifyMigrationCleanupConfiguration(ctx, req); err != nil { if errors.Is(err, ErrMigrationConfigurationChanged) { return err @@ -83,6 +101,82 @@ func (f *kvFSM) applyMigrationCleanupRequest(ctx context.Context, req *pb.Cleanu return result } +func (f *kvFSM) applyVersionIdentityCleanup(ctx context.Context, req *pb.CleanupMigrationRequest) any { + active, err := MigrationVersionRetirementEnabled(ctx, f.store) + if err != nil { + return haltErr(errors.Mark(err, ErrMigrationCleanupApply)) + } + applier, ok := f.store.(store.RaftEntryApplier) + if !ok || f.pendingApplyIdx == 0 { + return haltErr(errors.Mark(store.ErrRaftControlScopeRequired, ErrMigrationCleanupApply)) + } + var response any + err = applier.ApplyRaftEntry(ctx, f.pendingApplyIdx, func(ctx context.Context) error { + replayed, err := store.StageRaftEntryProgress(ctx, f.pendingApplyIdx) + if err != nil || replayed { + return errors.WithStack(err) + } + if !active { + response = errors.WithStack(store.ErrVersionRetirementUnavailable) + return nil + } + result, err := f.stageVersionIdentityCleanup(ctx, req) + if err == nil { + response = result + return nil + } + if isVersionIdentityCleanupVerdict(err) { + response = err + return nil + } + return err + }) + if err != nil { + return haltErr(errors.Wrap(errors.Mark(err, ErrMigrationCleanupApply), "kv/fsm: apply version identity cleanup")) + } + return response +} + +func isVersionIdentityCleanupVerdict(err error) bool { + return errors.Is(err, ErrMigrationConfigurationChanged) || errors.Is(err, store.ErrMigrationOwnership) || + errors.Is(err, store.ErrMigrationRetired) || errors.Is(err, store.ErrInvalidExportCursor) || + errors.Is(err, store.ErrVersionRetirementUnavailable) || errors.Is(err, store.ErrVersionRetirementConflict) || + errors.Is(err, store.ErrValueTooLarge) +} + +func (f *kvFSM) stageVersionIdentityCleanup(ctx context.Context, req *pb.CleanupMigrationRequest) (store.CleanupVersionsResult, error) { + if err := f.verifyMigrationCleanupConfiguration(ctx, req); err != nil { + return store.CleanupVersionsResult{}, err + } + if err := verifyMigrationVersionCleanupCoverage(ctx, f.store, req); err != nil { + return store.CleanupVersionsResult{}, err + } + retirement, record, err := f.prepareMigrationVersionRetirement(ctx, req) + if err != nil { + return store.CleanupVersionsResult{}, err + } + if record != nil { + if err := retirement.ValidateVersionRetirement(ctx, *record); err != nil { + return store.CleanupVersionsResult{}, errors.WithStack(err) + } + } + opts := migrationCleanupOptionsFromProto(req, f.pendingApplyIdx) + opts.Retirement = record + result, err := store.StageRaftEntryMigrationCleanup(ctx, opts) + if err != nil { + return result, errors.WithStack(err) + } + if record != nil { + // Neither staged physical deletes nor this logical decision is visible + // until the same synced batch publishes both with the applied index. + if err := retirement.StageVersionRetirement(ctx, *record); err != nil { + return store.CleanupVersionsResult{}, errors.WithStack(err) + } + result.RetirementID = record.ID + } + return result, nil +} + func (f *kvFSM) applyLegacyMigrationMetadataClear(ctx context.Context, cleaner store.MigrationCleaner, jobID uint64) any { if err := f.verifyLegacyMigrationMetadataClear(ctx, jobID); err != nil { if errors.Is(err, store.ErrMigrationOwnership) || errors.Is(err, store.ErrNotSupported) { diff --git a/kv/fsm_migration_cleanup_halt_test.go b/kv/fsm_migration_cleanup_halt_test.go index 75016a54f..918db2a54 100644 --- a/kv/fsm_migration_cleanup_halt_test.go +++ b/kv/fsm_migration_cleanup_halt_test.go @@ -88,3 +88,44 @@ func TestApplyMigrationCleanupKeepsDeterministicErrorsOrdinary(t *testing.T) { require.True(t, ok) require.ErrorIs(t, err, store.ErrValueTooLarge) } + +type cleanupCoverageFailureStore struct { + store.MVCCStore + store.RaftControlMetadataStore + store.RaftEntryApplier + err error +} + +func (s *cleanupCoverageFailureStore) MigrationServingAdmissionState(context.Context) (store.MigrationServingState, error) { + return store.MigrationServingState{}, s.err +} + +func TestVersionIdentityCleanupCoverageReadFailureLeavesProgressUnchanged(t *testing.T) { + t.Parallel() + backing, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, backing.Close()) }) + fsm, ok := NewKvFSMWithHLC(backing, nil).(*kvFSM) + require.True(t, ok) + enableCASApplyForTest(t, fsm) + key := []byte("a") + require.NoError(t, backing.PutAt(t.Context(), key, []byte("live"), 10, 0)) + metadata, ok := backing.(store.RaftControlMetadataStore) + require.True(t, ok) + applier, ok := backing.(store.RaftEntryApplier) + require.True(t, ok) + local := errors.New("cannot read ownership coverage") + fsm.store = &cleanupCoverageFailureStore{MVCCStore: backing, RaftControlMetadataStore: metadata, RaftEntryApplier: applier, err: local} + fsm.SetApplyIndex(2) + halt := haltApplyOf(fsm.Apply(cleanupCommand(t, pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS))) + require.True(t, errors.Is(halt, ErrMigrationCleanupApply), "got %v", halt) + require.ErrorIs(t, halt, local) + fsm.store = backing + fsm.SetApplyIndex(2) + halt = haltApplyOf(fsm.Apply(prependByte(raftEncodeMigrationCleanup, []byte{0xff}))) + require.True(t, errors.Is(halt, ErrMigrationCleanupApply), "got %v", halt) + requireCASProgress(t, fsm, 1) + row, err := store.GetVersionAt(t.Context(), backing, key, 20) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 10, Value: []byte("live")}, row) +} diff --git a/kv/fsm_migration_cleanup_test.go b/kv/fsm_migration_cleanup_test.go index 80f880dbe..15fb335bf 100644 --- a/kv/fsm_migration_cleanup_test.go +++ b/kv/fsm_migration_cleanup_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/bootjp/elastickv/distribution" pb "github.com/bootjp/elastickv/proto" "github.com/bootjp/elastickv/store" "github.com/stretchr/testify/require" @@ -41,3 +42,85 @@ func TestApplyMigrationCleanupCommandDeletesBoundedVersions(t *testing.T) { _, err = st.GetAt(ctx, []byte("a"), 10) require.ErrorIs(t, err, store.ErrKeyNotFound) } + +func TestVersionIdentityCleanupRejectsTombstoneRemovalWithDifferentRetainedHistory(t *testing.T) { + t.Parallel() + for _, name := range []string{"retained", "compacted"} { + t.Run(name, func(t *testing.T) { + ctx := t.Context() + st, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + fsm, ok := NewKvFSMWithHLC(st, nil).(*kvFSM) + require.True(t, ok) + enableCASApplyForTest(t, fsm) + key := []byte("a") + require.NoError(t, st.PutAt(ctx, key, []byte("issued"), 10, 0)) + issued, err := store.GetVersionAt(ctx, st, key, 10) + require.NoError(t, err) + require.NoError(t, st.DeleteAt(ctx, key, 20)) + if name == "compacted" { + require.NoError(t, st.Compact(ctx, 21)) + } + cmd, err := MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{ + JobId: 7, Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, + RangeStart: key, RangeEnd: nextScanCursor(key), MaxCommitTs: 20, MaxVersions: 1, + }) + require.NoError(t, err) + fsm.SetApplyIndex(2) + requireCASRejection(t, fsm.Apply(cmd), store.ErrMigrationOwnership) + requireCASProgress(t, fsm, 2) + requireCASRejection(t, applyCASFrame(t, fsm, 3, casApplyRequest(25, 30, issued.TS, string(key), "resurrect")), ErrCASMismatch) + requireCASProgress(t, fsm, 3) + _, err = store.GetVersionAt(ctx, st, key, 30) + require.ErrorIs(t, err, store.ErrKeyNotFound) + }) + } +} + +func TestVersionIdentityCleanupAllowsAbandonedStagedRows(t *testing.T) { + t.Parallel() + for _, name := range []string{"memory", "pebble"} { + t.Run(name, func(t *testing.T) { + ctx := t.Context() + st := store.NewMVCCStore() + if name == "pebble" { + var err error + st, err = store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + } + t.Cleanup(func() { require.NoError(t, st.Close()) }) + fsm, ok := NewKvFSMWithHLC(st, nil).(*kvFSM) + require.True(t, ok) + enableCASApplyForTest(t, fsm) + const jobID = 7 + key := []byte("a") + require.NoError(t, st.PutAt(ctx, key, []byte("live"), 11, 0)) + require.IsType(t, store.ImportVersionsResult{}, applyMigrationVersionIdentityImport(t, fsm, &pb.ImportRangeVersionsRequest{ + JobId: jobID, BracketId: 1, BatchSeq: 1, Versions: []*pb.MVCCVersion{{Key: key, CommitTs: 10, Value: []byte("staged")}}, + }, 2)) + // The retained staged head is older than the local read floor. + require.NoError(t, st.Compact(ctx, 11)) + prefix := distribution.MigrationStagedDataKeyPrefix(jobID) + cmd, err := MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{ + JobId: jobID, Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, KeyFamily: distribution.MigrationFamilyUser, + RangeStart: prefix, RangeEnd: store.PrefixScanEnd(prefix), MaxCommitTs: 10, + }) + require.NoError(t, err) + fsm.SetApplyIndex(3) + response := fsm.Apply(cmd) + cleaned, ok := response.(store.CleanupVersionsResult) + require.True(t, ok, "cleanup returned %v", response) + require.True(t, cleaned.Done) + require.Equal(t, uint64(1), cleaned.DeletedRows) + if name == "pebble" { + requireCASProgress(t, fsm, 3) + } + _, err = st.GetAt(ctx, distribution.MigrationStagedDataKey(jobID, key), 20) + require.ErrorIs(t, err, store.ErrKeyNotFound) + live, err := store.GetVersionAt(ctx, st, key, 20) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 11, Value: []byte("live")}, live) + }) + } +} diff --git a/kv/fsm_migration_import.go b/kv/fsm_migration_import.go index c4f80e040..667ce86da 100644 --- a/kv/fsm_migration_import.go +++ b/kv/fsm_migration_import.go @@ -74,6 +74,16 @@ func (f *kvFSM) applyMigrationImportBatch(ctx context.Context, req *pb.ImportRan if err := validateStagedKeySizes(opts.Versions); err != nil { return errors.Wrap(err, "kv/fsm: apply migration import") } + protected, err := MigrationVersionIdentityEnabled(ctx, f.store) + if err != nil { + return haltErr(errors.Wrap(errors.Mark(err, ErrMigrationImportApply), "kv/fsm: load migration version identity")) + } + opts.LogicalKey = migrationImportLogicalKey + opts.AllowLegacyVersionOverwrite = !protected + opts.AllowRetiredStaging, err = MigrationVersionAdoptionEnabled(ctx, f.store) + if err != nil { + return haltErr(errors.Mark(err, ErrMigrationImportApply)) + } result, err := f.store.ImportVersionsRaft(ctx, opts) if err != nil { if isMigrationImportOrdinaryApplyError(err) { @@ -113,17 +123,6 @@ func (f *kvFSM) validateImportedPrepareEvidence(versions []*pb.MVCCVersion) erro return nil } -// isMigrationImportOrdinaryApplyError reports whether err is a verdict on the -// request bytes rather than a failure of this replica's store. Only those may -// be returned as an ordinary apply error: the engine advances setApplied past -// a response that does not implement HaltApply, and every replica applying the -// same entry decides an ordinary error identically, so the group stays in step. -// -// A store-side failure -- Pebble I/O, an encryption gate rejecting the write -- -// is per-replica. Letting it advance setApplied would leave the leader acking -// the batch while the failed voter skips the imported versions for good, which -// surfaces as missing data after failover or promotion. Those halt instead, -// matching applyMigrationPromote. // validateStagedKeySizes rejects a batch whose staged form would not fit in the // physical stored-key snapshot budget. // @@ -141,17 +140,29 @@ func validateStagedKeySizes(versions []store.MVCCVersion) error { return nil } +// Only verdicts determined by the request and replicated state can advance +// apply. An I/O or decryption failure must halt this replica so it cannot skip +// versions that another voter successfully imported. func isMigrationImportOrdinaryApplyError(err error) bool { return errors.Is(err, store.ErrOnlineMigrationIdentity) || errors.Is(err, store.ErrOnlineMigrationTargetClosed) || errors.Is(err, store.ErrMigrationCaptureConflict) || errors.Is(err, store.ErrMigrationRetired) || errors.Is(err, store.ErrImportBatchGap) || + errors.Is(err, store.ErrMigrationVersionConflict) || errors.Is(err, store.ErrInvalidImportVersion) || errors.Is(err, store.ErrValueTooLarge) || errors.Is(err, store.ErrSnapshotKeyTooLarge) } +func migrationImportLogicalKey(staged []byte) []byte { + _, key, ok := distribution.MigrationStagedDataKeyParts(staged) + if !ok { + return staged + } + return key +} + func (f *kvFSM) migrationHLCFloorForApply(ctx context.Context, req *pb.ImportRangeVersionsRequest, result store.ImportVersionsResult) (uint64, error) { if result.MaxImportedTS > 0 || len(req.GetVersions()) == 0 { return result.MaxImportedTS, nil diff --git a/kv/fsm_migration_promote.go b/kv/fsm_migration_promote.go index 26fb23ac8..0af4c3af7 100644 --- a/kv/fsm_migration_promote.go +++ b/kv/fsm_migration_promote.go @@ -59,16 +59,18 @@ func (f *kvFSM) applyMigrationPromote(ctx context.Context, data []byte) any { return haltErr(errors.Wrap(errors.Mark(store.ErrNotSupported, ErrMigrationPromoteApply), "kv/fsm: migration promote store")) } opts := migrationPromoteOptionsFromProto(req, f.pendingApplyIdx) + protected, err := MigrationVersionIdentityEnabled(ctx, f.store) + if err != nil { + return haltErr(errors.Wrap(errors.Mark(err, ErrMigrationPromoteApply), "kv/fsm: load migration version identity")) + } + opts.AllowLegacyVersionOverwrite = !protected + opts.AdoptionAuthority, err = f.migrationAdoptionAuthority(ctx, req.GetJobId()) + if err != nil { + return haltErr(errors.Mark(err, ErrMigrationPromoteApply)) + } mapTarget := opts.TargetKey rejectedPeerLocal := false - opts.TargetKey = func(stagedKey []byte) ([]byte, bool) { - key, valid := mapTarget(stagedKey) - if valid && isTxnPeerLocalControlKey(key) { - rejectedPeerLocal = true - return nil, false - } - return key, valid - } + opts.TargetKey = migrationPromotionPeerLocalGuard(mapTarget, &rejectedPeerLocal) guard, err := f.onlineMaintenanceGuard(ctx, nil) if err != nil { return haltErr(errors.Mark(err, ErrMigrationPromoteApply)) @@ -84,6 +86,17 @@ func (f *kvFSM) applyMigrationPromote(ctx context.Context, data []byte) any { return result } +func migrationPromotionPeerLocalGuard(mapTarget func([]byte) ([]byte, bool), rejected *bool) func([]byte) ([]byte, bool) { + return func(stagedKey []byte) ([]byte, bool) { + key, valid := mapTarget(stagedKey) + if valid && isTxnPeerLocalControlKey(key) { + *rejected = true + return nil, false + } + return key, valid + } +} + func migrationPromoteFailure(err error, rejectedPeerLocal bool) any { // A legacy staged control row is a deterministic input refusal, not // a store failure that should halt replication. Promotion plans the @@ -135,7 +148,8 @@ func clampMigrationPromoteBound(requested, fallback, ceiling uint64) uint64 { } func isMigrationPromoteOrdinaryApplyError(err error) bool { - return errors.Is(err, store.ErrOnlineMigrationSealed) || errors.Is(err, store.ErrMigrationRetired) || errors.Is(err, store.ErrInvalidExportCursor) || errors.Is(err, store.ErrInvalidImportVersion) + return errors.Is(err, store.ErrMigrationOwnership) || errors.Is(err, store.ErrOnlineMigrationSealed) || errors.Is(err, store.ErrMigrationRetired) || errors.Is(err, store.ErrInvalidExportCursor) || + errors.Is(err, store.ErrInvalidImportVersion) || errors.Is(err, store.ErrMigrationVersionConflict) } func migrationPromoteTargetKey(jobID uint64) func([]byte) ([]byte, bool) { diff --git a/kv/fsm_migration_serving.go b/kv/fsm_migration_serving.go index 3277b7013..7a28dbf3c 100644 --- a/kv/fsm_migration_serving.go +++ b/kv/fsm_migration_serving.go @@ -15,12 +15,27 @@ import ( // timestamps, metadata and footprint. The FSM repeats this check at apply; // a successful check does not authorize a different or later request. func CheckMigrationRequest(ctx context.Context, localStore store.MVCCStore, groupID uint64, req *pb.Request) error { + return checkMigrationRequest(ctx, localStore, groupID, req, requestUsesCAS(req)) +} + +func checkMigrationRequest(ctx context.Context, localStore store.MVCCStore, groupID uint64, req *pb.Request, cas bool) error { if localStore == nil || req == nil { return errors.WithStack(ErrInvalidRequest) } if err := verifyRequestMigrationControlKeys(req); err != nil { return err } + if cas { + // The transaction manager validates the standalone CAS shape before + // entering migration admission. + if err := validateCASProposalShape([]*pb.Request{req}); err != nil { + return err + } + if err := checkVersionCASMigrationRange(ctx, localStore, req.Mutations[1].Key); err != nil { + return errors.Wrap(ErrVersionCASUnavailable, err.Error()) + } + return nil + } f := &kvFSM{store: localStore, shardGroupID: groupID} index, err := MigrationConfigurationIndex(ctx, localStore) if err != nil { diff --git a/kv/fsm_migration_version_identity_test.go b/kv/fsm_migration_version_identity_test.go new file mode 100644 index 000000000..8fc22fac5 --- /dev/null +++ b/kv/fsm_migration_version_identity_test.go @@ -0,0 +1,239 @@ +package kv + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/distribution" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func TestMigrationVersionIdentityLegacyAndProtectedImport(t *testing.T) { + t.Parallel() + ctx := context.Background() + st := store.NewMVCCStore() + fsm := &kvFSM{store: st} + key := []byte("k") + staged := distribution.MigrationStagedDataKey(1, key) + version := &pb.MVCCVersion{Key: key, CommitTs: 10, Value: []byte("first")} + req := &pb.ImportRangeVersionsRequest{JobId: 1, BracketId: 1, BatchSeq: 1, Versions: []*pb.MVCCVersion{version}} + + require.IsType(t, store.ImportVersionsResult{}, applyMigrationVersionIdentityImport(t, fsm, req, 1)) + req.BatchSeq++ + version.Value = []byte("legacy replacement") + require.IsType(t, store.ImportVersionsResult{}, applyMigrationVersionIdentityImport(t, fsm, req, 2)) + got, err := st.GetAt(ctx, staged, 10) + require.NoError(t, err) + require.Equal(t, version.Value, got) + + fsm.SetApplyIndex(3) + require.Nil(t, fsm.Apply(EncodeMigrationVersionIdentityActivation())) + protected, err := MigrationVersionIdentityEnabled(ctx, st) + require.NoError(t, err) + require.True(t, protected) + + req.BatchSeq++ + version.Value = []byte("protected replacement") + resp := applyMigrationVersionIdentityImport(t, fsm, req, 4) + requireMigrationVersionConflict(t, resp) + got, err = st.GetAt(ctx, staged, 10) + require.NoError(t, err) + require.Equal(t, []byte("legacy replacement"), got) + + // A new staged job must also respect the public key's existing version. + require.NoError(t, st.PutAt(ctx, key, []byte("live"), 10, 0)) + req.JobId, req.BatchSeq = 2, 1 + resp = applyMigrationVersionIdentityImport(t, fsm, req, 5) + requireMigrationVersionConflict(t, resp) + _, err = st.GetAt(ctx, distribution.MigrationStagedDataKey(2, key), 10) + require.ErrorIs(t, err, store.ErrKeyNotFound) +} + +func TestMigrationVersionIdentityPromotionPreservesStageOnConflict(t *testing.T) { + t.Parallel() + ctx := context.Background() + st := store.NewMVCCStore() + fsm := &kvFSM{store: st} + key := []byte("k") + staged := distribution.MigrationStagedDataKey(1, key) + require.NoError(t, st.PutWithTTLAt(ctx, key, []byte("value"), 10, 20)) + require.NoError(t, st.PutWithTTLAt(ctx, staged, []byte("value"), 10, 21)) + + fsm.SetApplyIndex(1) + require.Nil(t, fsm.Apply(EncodeMigrationVersionIdentityActivation())) + cmd, err := MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 1}) + require.NoError(t, err) + fsm.SetApplyIndex(2) + resp := fsm.Apply(cmd) + requireMigrationVersionConflict(t, resp) + _, err = st.GetAt(ctx, key, 20) + require.ErrorIs(t, err, store.ErrKeyNotFound) + got, err := st.GetAt(ctx, staged, 20) + require.NoError(t, err) + require.Equal(t, []byte("value"), got) + reader, ok := st.(store.MigrationPromotionStateReader) + require.True(t, ok) + _, present, err := reader.MigrationPromotionState(ctx, 1) + require.NoError(t, err) + require.False(t, present) + + // Identical versions are a successful move and only the staged copy is removed. + cmd, err = MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 2}) + require.NoError(t, err) + duplicate := distribution.MigrationStagedDataKey(2, key) + require.NoError(t, st.PutWithTTLAt(ctx, duplicate, []byte("value"), 10, 20)) + fsm.SetApplyIndex(3) + require.IsType(t, store.PromoteVersionsResult{}, fsm.Apply(cmd)) + _, err = st.GetAt(ctx, duplicate, 10) + require.ErrorIs(t, err, store.ErrKeyNotFound) + got, err = st.GetAt(ctx, key, 10) + require.NoError(t, err) + require.Equal(t, []byte("value"), got) +} + +func applyMigrationVersionIdentityImport(t *testing.T, fsm *kvFSM, req *pb.ImportRangeVersionsRequest, index uint64) any { + t.Helper() + cmd, err := MarshalMigrationImportCommand(req) + require.NoError(t, err) + fsm.SetApplyIndex(index) + return fsm.Apply(cmd) +} + +func TestMigrationVersionIdentityActivationSurvivesPebbleReopen(t *testing.T) { + t.Parallel() + ctx := context.Background() + dir := t.TempDir() + st, err := store.NewPebbleStore(dir) + require.NoError(t, err) + fsm := &kvFSM{store: st} + fsm.SetApplyIndex(1) + resp := fsm.Apply(EncodeMigrationVersionIdentityActivation()) + require.NoError(t, haltApplyOf(resp)) + require.Nil(t, resp) + require.NoError(t, st.Close()) + + st, err = store.NewPebbleStore(dir) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + protected, err := MigrationVersionIdentityEnabled(ctx, st) + require.NoError(t, err) + require.True(t, protected) + fsm = &kvFSM{store: st} + + req := &pb.ImportRangeVersionsRequest{ + JobId: 1, BracketId: 1, BatchSeq: 1, + Versions: []*pb.MVCCVersion{ + {Key: []byte("same"), CommitTs: 10, Value: []byte("original")}, + {Key: []byte("same"), CommitTs: 10, Value: []byte("collision")}, + }, + } + resp = applyMigrationVersionIdentityImport(t, fsm, req, 2) + requireMigrationVersionConflict(t, resp) + _, err = st.GetAt(ctx, distribution.MigrationStagedDataKey(1, []byte("same")), 10) + require.ErrorIs(t, err, store.ErrKeyNotFound) +} + +func TestMigrationVersionIdentityLegacyPromotionOverwrites(t *testing.T) { + t.Parallel() + ctx := context.Background() + st := store.NewMVCCStore() + fsm := &kvFSM{store: st} + key := []byte("k") + staged := distribution.MigrationStagedDataKey(1, key) + require.NoError(t, st.PutAt(ctx, key, []byte("unknown to old tokens"), 10, 0)) + require.NoError(t, st.DeleteAt(ctx, staged, 10)) + cmd, err := MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 1}) + require.NoError(t, err) + fsm.SetApplyIndex(1) + require.IsType(t, store.PromoteVersionsResult{}, fsm.Apply(cmd)) + _, err = st.GetAt(ctx, key, 10) + require.ErrorIs(t, err, store.ErrKeyNotFound) + _, err = st.GetAt(ctx, staged, 10) + require.ErrorIs(t, err, store.ErrKeyNotFound) +} + +func TestMigrationVersionIdentityProtectsObservedCASToken(t *testing.T) { + t.Parallel() + ctx := context.Background() + fsm, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, fsm) + key := []byte("key") + staged := distribution.MigrationStagedDataKey(1, key) + require.NoError(t, st.PutAt(ctx, key, []byte("A"), 10, 0)) + require.NoError(t, st.PutAt(ctx, staged, []byte("B"), 10, 0)) + + observed, err := store.GetVersionAt(ctx, st, key, 10) + require.NoError(t, err) + require.Equal(t, []byte("A"), observed.Value) + require.Equal(t, uint64(10), observed.TS) + + req := &pb.ImportRangeVersionsRequest{ + JobId: 2, BracketId: 1, BatchSeq: 1, + Versions: []*pb.MVCCVersion{{Key: key, CommitTs: observed.TS, Value: []byte("C")}}, + } + resp := applyMigrationVersionIdentityImport(t, fsm, req, 2) + requireMigrationVersionConflict(t, resp) + + cmd, err := MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 1}) + require.NoError(t, err) + fsm.SetApplyIndex(3) + requireMigrationVersionConflict(t, fsm.Apply(cmd)) + + current, err := store.GetVersionAt(ctx, st, key, 10) + require.NoError(t, err) + require.Equal(t, observed, current) + require.Nil(t, applyCASFrame(t, fsm, 4, casApplyRequest(10, 20, observed.TS, string(key), "updated"))) + current, err = store.GetVersionAt(ctx, st, key, 20) + require.NoError(t, err) + require.Equal(t, []byte("updated"), current.Value) + require.Equal(t, uint64(20), current.TS) +} + +func TestMigrationVersionIdentityDoesNotExposeMigratedTokens(t *testing.T) { + t.Parallel() + ctx := context.Background() + shards, group := newStagedVisibilityShardStore(t) + t.Cleanup(func() { require.NoError(t, shards.Close()) }) + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + fsm := &kvFSM{store: group.Store} + fsm.SetApplyIndex(1) + require.Nil(t, fsm.Apply(EncodeMigrationVersionIdentityActivation())) + key := []byte("key") + req := &pb.ImportRangeVersionsRequest{ + JobId: 9, BracketId: 1, BatchSeq: 1, + Versions: []*pb.MVCCVersion{{Key: key, CommitTs: 90, Value: []byte("migrated")}}, + } + require.IsType(t, store.ImportVersionsResult{}, applyMigrationVersionIdentityImport(t, fsm, req, 2)) + value, err := shards.GetAt(ctx, key, 100) + require.NoError(t, err) + require.Equal(t, []byte("migrated"), value) + _, err = shards.GetVersionAt(ctx, key, 100) + require.ErrorIs(t, err, store.ErrNotSupported) + + cmd, err := MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 9}) + require.NoError(t, err) + fsm.SetApplyIndex(3) + require.IsType(t, store.PromoteVersionsResult{}, fsm.Apply(cmd)) + require.NoError(t, shards.engine.ApplySnapshot(distribution.CatalogSnapshot{ + Version: 2, + Routes: []distribution.RouteDescriptor{{ + RouteID: 1, Start: []byte("a"), End: []byte("z"), GroupID: 1, State: distribution.RouteStateActive, + MinWriteTSExclusive: 100, + }}, + })) + value, err = shards.GetAt(ctx, key, 100) + require.NoError(t, err) + require.Equal(t, []byte("migrated"), value) + _, err = shards.GetVersionAt(ctx, key, 100) + require.ErrorIs(t, err, store.ErrNotSupported) +} + +func requireMigrationVersionConflict(t *testing.T, resp any) { + t.Helper() + require.NoError(t, haltApplyOf(resp)) + err, ok := resp.(error) + require.True(t, ok, "expected migration conflict, got %T", resp) + require.ErrorIs(t, err, store.ErrMigrationVersionConflict) +} diff --git a/kv/fsm_proposal_turn.go b/kv/fsm_proposal_turn.go new file mode 100644 index 000000000..d090e3445 --- /dev/null +++ b/kv/fsm_proposal_turn.go @@ -0,0 +1,102 @@ +package kv + +import ( + "bytes" + "slices" + + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" +) + +const maxProposalTurnPayloadSize = 128 << 10 + +var _ raftengine.ProposalTurnClassifier = (*kvFSM)(nil) + +// IsProposalTurnPayload recognizes independent, already-stamped proposals. +// Classification uses only the frame. Admission and apply still run per entry. +func (*kvFSM) IsProposalTurnPayload(payload []byte) bool { + if bytes.HasPrefix(payload, []byte(versionCASFrame)) { + return len(payload) <= maxProposalTurnPayloadSize && proposalTurnCAS(payload) + } + return boundedProposalTurnPut(payload) != nil +} + +func boundedProposalTurnPut(payload []byte) *pb.Request { + if len(payload) < 2 || len(payload) > maxProposalTurnPayloadSize || payload[0] != raftEncodeSingle { + return nil + } + requests, err := decodeRaftRequests(payload) + if err != nil || !proposalTurnPutShape(requests[0], len(payload)-1) { + return nil + } + return requests[0] +} + +func proposalTurnCAS(payload []byte) bool { + req, err := DecodeVersionCASRaftPayload(payload) + if err != nil { + return false + } + header, cas := req.Mutations[0], req.Mutations[1] + // V2 CAS metadata can carry just the commit timestamp. The shared decoder + // has already validated the version, header length and optional fields. + if header.Value[0] == txnMetaVersionV2 && header.Value[1] != txnMetaFlagCommitTS { + return false + } + return proposalTurnRequestFields(req, len(payload)-len(versionCASFrame), "is_txn", "ts", "mutations", "observed_route_version", "version_cas_group_id") && + proposalTurnFields(cas, "op", "key", "value", "expected_commit_ts") && + proposalTurnHeaderAndKey(header, cas.Key) +} + +func proposalTurnPutShape(req *pb.Request, bodySize int) bool { + if !req.IsTxn || req.Ts == 0 || len(req.Mutations) != 2 || + !proposalTurnRequestFields(req, bodySize, "is_txn", "ts", "mutations", "read_keys", "observed_route_version") { + return false + } + header, put := req.Mutations[0], req.Mutations[1] + if !proposalTurnFields(put, "key", "value") || !proposalTurnHeaderAndKey(header, put.Key) || + !proposalTurnReadSet(req.ReadKeys, put.Key) { + return false + } + // The coordinator emits V1 for a fresh PUT. Retry and prepare metadata + // have other versions. + if header.Value[0] != txnMetaVersionV1 { + return false + } + _, meta, ok := decodeCASRequestMeta(header, put) + return ok && meta.CommitTS > req.Ts +} + +func proposalTurnReadSet(keys [][]byte, written []byte) bool { + return len(keys) == 0 || (len(keys) == 1 && bytes.Equal(keys[0], written)) +} + +func proposalTurnRequestFields(req *pb.Request, wireSize int, allowed ...protoreflect.Name) bool { + return proto.Size(req) == wireSize && proposalTurnFields(req, allowed...) +} + +func proposalTurnHeaderAndKey(header *pb.Mutation, key []byte) bool { + // Logical routing keys (including partition-resolver keys) can themselves + // resemble direct point keys. Leave namespace-prefixed keys to normal scheduling. + return validCASHeader(header) && proposalTurnFields(header, "key", "value") && + versionCASDirectKey(key) && (key[0] != '!' || bytes.IndexByte(key, '|') < 0) && + appendBatchMetadataIsComplete(header.Value, key) +} + +// Check populated fields by name so a newly generated proto field also falls +// back. The caller checks the decoded size against the wire size to catch +// overwritten singular fields and explicitly encoded defaults lost on decode. +func proposalTurnFields(message proto.Message, allowed ...protoreflect.Name) bool { + m := message.ProtoReflect() + if len(m.GetUnknown()) != 0 { + return false + } + ok := true + m.Range(func(field protoreflect.FieldDescriptor, _ protoreflect.Value) bool { + ok = slices.Contains(allowed, field.Name()) + return ok + }) + return ok +} diff --git a/kv/fsm_proposal_turn_test.go b/kv/fsm_proposal_turn_test.go new file mode 100644 index 000000000..08baa02ac --- /dev/null +++ b/kv/fsm_proposal_turn_test.go @@ -0,0 +1,270 @@ +package kv + +import ( + "bytes" + "testing" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/encryption/fsmwire" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" +) + +func proposalTurnPut() *pb.Request { + key := []byte("key") + return onePhaseTxnRequestWithPrevCommit(15, 20, 0, key, + []*Elem[OP]{{Op: Put, Key: key, Value: []byte("value")}}, nil, 0, nil) +} + +func TestIsProposalTurnPayloadOrdinary1PC(t *testing.T) { + leader := &ordinaryBenchmarkLeader{} + proxy := NewLeaderProxyWithEngine(leader) + t.Cleanup(func() { require.NoError(t, proxy.Close()) }) + coord := NewCoordinatorWithEngine(proxy, leader) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + _, err := coord.Dispatch(t.Context(), &OperationGroup[OP]{ + IsTxn: true, StartTS: 15, CommitTS: 20, + Elems: []*Elem[OP]{{Op: Put, Key: []byte("key"), Value: []byte("value")}}, + }) + require.NoError(t, err) + require.EqualValues(t, 1, leader.proposals) + frame := leader.frame + require.NotEmpty(t, frame) + require.Equal(t, raftEncodeSingle, frame[0]) + var f *kvFSM + before := bytes.Clone(frame) + require.True(t, f.IsProposalTurnPayload(frame)) + require.Equal(t, before, frame) + require.False(t, f.IsAppendBatchPayload(frame)) +} + +func TestIsProposalTurnPayloadReadDependentSharded1PC(t *testing.T) { + leader := &ordinaryBenchmarkLeader{} + proxy := NewLeaderProxyWithEngine(leader) + t.Cleanup(func() { require.NoError(t, proxy.Close()) }) + routes := distribution.NewEngine() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}, + }})) + st := store.NewMVCCStore() + group := &ShardGroup{Engine: leader, Txn: proxy, Store: st} + groups := map[uint64]*ShardGroup{1: group} + shards := NewShardStore(routes, groups) + coord := NewShardedCoordinator(routes, groups, 1, NewHLC(), shards) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + key := []byte("key") + _, err := coord.Dispatch(t.Context(), &OperationGroup[OP]{ + IsTxn: true, StartTS: 15, CommitTS: 20, + ReadKeys: [][]byte{key}, ObservedRouteVersion: EncodeObservedRouteVersion(1), + Elems: []*Elem[OP]{{Op: Put, Key: key, Value: []byte("value")}}, + }) + require.NoError(t, err) + requests, err := decodeRaftRequests(leader.frame) + require.NoError(t, err) + require.Len(t, requests, 1) + require.Equal(t, [][]byte{key}, requests[0].ReadKeys) + require.Equal(t, EncodeObservedRouteVersion(1), requests[0].ObservedRouteVersion) + require.True(t, (*kvFSM)(nil).IsProposalTurnPayload(leader.frame)) + require.True(t, (*kvFSM)(nil).IsAppendBatchPayload(leader.frame)) +} + +// Marshal directly so malformed requests can reach the classifier in tests. +func proposalTurnTestFrame(t *testing.T, prefix []byte, req *pb.Request) []byte { + t.Helper() + body, err := proto.Marshal(req) + require.NoError(t, err) + return append(bytes.Clone(prefix), body...) +} + +func TestIsProposalTurnPayloadFrames(t *testing.T) { + put := proposalTurnPut() + cas := casApplyRequest(15, 20, 10, "key", "value") + batch, err := marshalRaftCommand([]*pb.Request{put, put}) + require.NoError(t, err) + casFrame, err := marshalRaftCommand([]*pb.Request{cas}) + require.NoError(t, err) + single := proposalTurnTestFrame(t, []byte{raftEncodeSingle}, put) + for _, tc := range []struct { + name string + frame []byte + want bool + }{ + {"standalone CAS", casFrame, true}, + {"empty", nil, false}, + {"missing put body", single[:1], false}, + {"truncated put", single[:len(single)-1], false}, + {"truncated CAS prefix", casFrame[:len(versionCASFrame)-1], false}, + {"truncated CAS body", casFrame[:len(casFrame)-1], false}, + {"bare protobuf", single[1:], false}, + {"CAS inside single", proposalTurnTestFrame(t, single[:1], cas), false}, + {"ordinary in CAS frame", proposalTurnTestFrame(t, []byte(versionCASFrame), put), false}, + {"batch", batch, false}, + {"unknown opcode", prependByte(0xff, single), false}, + {"future CAS version", append([]byte("\x06CAS\xff"), casFrame[len(versionCASFrame):]...), false}, + {"migration activation", EncodeMigrationVersionIdentityActivation(), false}, + {"migration cleanup", prependByte(raftEncodeMigrationCleanup, single), false}, + {"fence activation", EncodeCommitTSFenceActivation(), false}, + {"encryption", prependByte(fsmwire.OpRegistration, single), false}, + {"lease", marshalHLCLeaseRenew(20), false}, + {"duplicate txn flag", append(bytes.Clone(single), 0x08, 1), false}, + } { + t.Run(tc.name, func(t *testing.T) { + before := bytes.Clone(tc.frame) + require.Equal(t, tc.want, (*kvFSM)(nil).IsProposalTurnPayload(tc.frame)) + require.Equal(t, before, tc.frame) + }) + } +} + +func TestIsProposalTurnPayloadRequestFields(t *testing.T) { + unknown := protowire.AppendVarint(protowire.AppendTag(nil, 100, protowire.VarintType), 1) + for _, tc := range []struct { + name string + edit func(*pb.Request) + }{ + {"raw", func(r *pb.Request) { r.IsTxn = false }}, + {"prepare", func(r *pb.Request) { r.Phase = pb.Phase_PREPARE }}, + {"commit", func(r *pb.Request) { r.Phase = pb.Phase_COMMIT }}, + {"rollback", func(r *pb.Request) { r.Phase = pb.Phase_ABORT }}, + {"zero start", func(r *pb.Request) { r.Ts = 0 }}, + {"start at commit", func(r *pb.Request) { r.Ts = 20 }}, + {"missing data", func(r *pb.Request) { r.Mutations = r.Mutations[:1] }}, + {"extra data", func(r *pb.Request) { r.Mutations = append(r.Mutations, r.Mutations[1]) }}, + {"reordered", func(r *pb.Request) { r.Mutations[0], r.Mutations[1] = r.Mutations[1], r.Mutations[0] }}, + {"read set", func(r *pb.Request) { r.ReadKeys = [][]byte{[]byte("r")} }}, + {"fence bypass", func(r *pb.Request) { r.WriteFenceBypassKeys = [][]byte{r.Mutations[1].Key} }}, + {"floor", func(r *pb.Request) { r.TimestampAdmissionFloor = 1 }}, + {"operation ID", func(r *pb.Request) { r.TimestampBindingOperationId = []byte("op") }}, + {"orphan admission term", func(r *pb.Request) { r.TimestampBindingAdmissionTerm = 1 }}, + {"unknown request", func(r *pb.Request) { r.ProtoReflect().SetUnknown(unknown) }}, + {"unknown header", func(r *pb.Request) { r.Mutations[0].ProtoReflect().SetUnknown(unknown) }}, + {"unknown mutation", func(r *pb.Request) { r.Mutations[1].ProtoReflect().SetUnknown(unknown) }}, + {"changed header key", func(r *pb.Request) { r.Mutations[0].Key = []byte(txnMetaPrefix + "x") }}, + {"header absent", func(r *pb.Request) { r.Mutations[0].RequireAbsent = true }}, + {"stamp offset", func(r *pb.Request) { r.Mutations[1].CommitTsValueOffset = 1 }}, + {"absent", func(r *pb.Request) { r.Mutations[1].RequireAbsent = true }}, + {"prefix delete", func(r *pb.Request) { r.Mutations[1].Op = pb.Op_DEL_PREFIX }}, + {"delete", func(r *pb.Request) { r.Mutations[1].Op = pb.Op_DEL }}, + {"unknown op", func(r *pb.Request) { r.Mutations[1].Op = pb.Op(99) }}, + {"trailing metadata", func(r *pb.Request) { r.Mutations[0].Value = append(r.Mutations[0].Value, 0xff) }}, + {"empty metadata", func(r *pb.Request) { r.Mutations[0].Value = nil }}, + {"wrong primary", func(r *pb.Request) { r.Mutations[1].Key = []byte("bad") }}, + } { + t.Run(tc.name, func(t *testing.T) { + put, cas := proposalTurnPut(), casApplyRequest(15, 20, 10, "key", "value") + tc.edit(put) + tc.edit(cas) + require.False(t, (*kvFSM)(nil).IsProposalTurnPayload(proposalTurnTestFrame(t, []byte{raftEncodeSingle}, put))) + require.False(t, (*kvFSM)(nil).IsProposalTurnPayload(proposalTurnTestFrame(t, []byte(versionCASFrame), cas))) + }) + } +} + +func TestIsProposalTurnPayloadPutShape(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*pb.Request) + }{ + {"multiple read keys", func(r *pb.Request) { r.ReadKeys = [][]byte{[]byte("key"), []byte("other")} }}, + {"internal read alias", func(r *pb.Request) { r.ReadKeys = [][]byte{[]byte("!mig|alias|key")} }}, + {"CAS group", func(r *pb.Request) { r.VersionCasGroupId = 1 }}, + {"expected version on PUT", func(r *pb.Request) { r.Mutations[1].ExpectedCommitTs = 1 }}, + {"predicate on header", func(r *pb.Request) { r.Mutations[0].ExpectedCommitTs = 1 }}, + } { + t.Run(tc.name, func(t *testing.T) { + req := proposalTurnPut() + tc.edit(req) + require.False(t, (*kvFSM)(nil).IsProposalTurnPayload(proposalTurnTestFrame(t, []byte{raftEncodeSingle}, req))) + }) + } +} + +func TestIsProposalTurnPayloadCASProof(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*pb.Request) + }{ + {"missing route proof", func(r *pb.Request) { r.ObservedRouteVersion = 0 }}, + {"missing group", func(r *pb.Request) { r.VersionCasGroupId = 0 }}, + {"missing expected version", func(r *pb.Request) { r.Mutations[1].ExpectedCommitTs = 0 }}, + } { + t.Run(tc.name, func(t *testing.T) { + req := casApplyRequest(15, 20, 10, "key", "value") + tc.edit(req) + frame := proposalTurnTestFrame(t, []byte(versionCASFrame), req) + require.False(t, (*kvFSM)(nil).IsProposalTurnPayload(frame)) + }) + } +} + +func TestIsProposalTurnPayloadCASMetadataV2(t *testing.T) { + req := casApplyRequest(15, 20, 10, "key", "value") + meta := encodeTxnMetaV2(TxnMeta{PrimaryKey: req.Mutations[1].Key, CommitTS: 20}) + req.Mutations[0].Value = meta + frame := proposalTurnTestFrame(t, []byte(versionCASFrame), req) + require.True(t, (*kvFSM)(nil).IsProposalTurnPayload(frame)) + + // An explicitly encoded zero retry timestamp decodes to the same value. + meta[1] |= txnMetaFlagPrevCommitTS + meta = append(meta, make([]byte, uint64FieldSize)...) + req.Mutations[0].Value = meta + frame = proposalTurnTestFrame(t, []byte(versionCASFrame), req) + _, err := DecodeVersionCASRaftPayload(frame) + require.NoError(t, err) + require.False(t, (*kvFSM)(nil).IsProposalTurnPayload(frame)) +} + +func TestIsProposalTurnPayloadMetadata(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*TxnMeta) + }{ + {"no commit", func(m *TxnMeta) { m.CommitTS = 0 }}, + {"lock TTL", func(m *TxnMeta) { m.LockTTLms = 1 }}, + {"retry", func(m *TxnMeta) { m.PrevCommitTS = 12 }}, + {"prepare evidence", func(m *TxnMeta) { m.PrepareCommitTS = 20 }}, + } { + t.Run(tc.name, func(t *testing.T) { + req := proposalTurnPut() + meta := TxnMeta{PrimaryKey: req.Mutations[1].Key, CommitTS: 20} + tc.edit(&meta) + req.Mutations[0].Value = EncodeTxnMeta(meta) + require.False(t, (*kvFSM)(nil).IsProposalTurnPayload(proposalTurnTestFrame(t, []byte{raftEncodeSingle}, req))) + }) + } +} + +func TestIsProposalTurnPayloadInternalKeys(t *testing.T) { + for _, key := range [][]byte{ + nil, txnLockKey([]byte("k")), []byte(txnMetaPrefix), distribution.CatalogVersionKey(), + distribution.MigrationStagedDataKey(7, []byte("k")), []byte("!dist|route|1"), + []byte(sqsRoutePrefix + "global"), []byte(store.ReplicatedControlPrefix + "state"), + []byte(store.RaftControlMetadataPrefix + "P"), + } { + req := onePhaseReq(15, 20, 0, key, []byte("value")) + require.Falsef(t, (*kvFSM)(nil).IsProposalTurnPayload(proposalTurnTestFrame(t, []byte{raftEncodeSingle}, req)), "%q", key) + } +} + +func TestIsProposalTurnPayloadSize(t *testing.T) { + for _, req := range []*pb.Request{proposalTurnPut(), casApplyRequest(15, 20, 10, "key", "value")} { + req.Mutations[1].Value = make([]byte, maxProposalTurnPayloadSize) + frame, err := marshalRaftCommand([]*pb.Request{req}) + require.NoError(t, err) + excess := len(frame) - maxProposalTurnPayloadSize + // These lengths use the same protobuf varint width. + req.Mutations[1].Value = req.Mutations[1].Value[:maxProposalTurnPayloadSize-excess+1] + frame, err = marshalRaftCommand([]*pb.Request{req}) + require.NoError(t, err) + require.Len(t, frame, maxProposalTurnPayloadSize+1) + require.False(t, (*kvFSM)(nil).IsProposalTurnPayload(frame)) + req.Mutations[1].Value = req.Mutations[1].Value[:len(req.Mutations[1].Value)-1] + frame, err = marshalRaftCommand([]*pb.Request{req}) + require.NoError(t, err) + require.Len(t, frame, maxProposalTurnPayloadSize) + require.True(t, (*kvFSM)(nil).IsProposalTurnPayload(frame)) + } +} diff --git a/kv/kvtest/coordinator.go b/kv/kvtest/coordinator.go index ad9db6f8b..8cb7562b3 100644 --- a/kv/kvtest/coordinator.go +++ b/kv/kvtest/coordinator.go @@ -20,7 +20,15 @@ type NopCoordinator struct { clock *kv.HLC } -func (*NopCoordinator) Dispatch(context.Context, *kv.OperationGroup[kv.OP]) (*kv.CoordinateResponse, error) { +func (*NopCoordinator) Dispatch(_ context.Context, req *kv.OperationGroup[kv.OP]) (*kv.CoordinateResponse, error) { + if req == nil { + return &kv.CoordinateResponse{}, nil + } + for _, elem := range req.Elems { + if elem != nil && (elem.Op == kv.CompareAndSwap || elem.ExpectedCommitTS != 0) { + return nil, errors.WithStack(kv.ErrVersionCASUnavailable) + } + } return &kv.CoordinateResponse{}, nil } func (*NopCoordinator) IsLeader() bool { return true } @@ -160,11 +168,16 @@ func operationShape(elems []*kv.Elem[kv.OP]) (bool, bool, error) { if elem == nil { continue } + if elem.ExpectedCommitTS != 0 { + return false, false, errors.WithStack(kv.ErrVersionCASUnavailable) + } switch elem.Op { case kv.Put, kv.Del: points = true case kv.DelPrefix: prefixes = true + case kv.CompareAndSwap: + return false, false, errors.WithStack(kv.ErrVersionCASUnavailable) default: return false, false, errors.WithStack(store.ErrUnknownOp) } @@ -275,6 +288,8 @@ func (c *LocalCoordinator) applyOCC(ctx context.Context, req *kv.OperationGroup[ mutations = append(mutations, &store.KVPairMutation{Op: store.OpTypeDelete, Key: elem.Key}) case kv.DelPrefix: // PrefixIgnore was validated before entering this path. + case kv.CompareAndSwap: + return errors.WithStack(kv.ErrVersionCASUnavailable) } } var reads [][]byte @@ -296,6 +311,8 @@ func (c *LocalCoordinator) applySequential(ctx context.Context, elems []*kv.Elem if c.options.DelPrefix == PrefixApply { err = c.st.DeletePrefixAt(ctx, elem.Key, nil, ts) } + case kv.CompareAndSwap: + return errors.WithStack(kv.ErrVersionCASUnavailable) } if err != nil { return errors.Wrap(err, "apply local operation") diff --git a/kv/leader_proxy.go b/kv/leader_proxy.go index e00cd450a..7d0ffa787 100644 --- a/kv/leader_proxy.go +++ b/kv/leader_proxy.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "slices" "sync/atomic" "time" @@ -61,17 +62,37 @@ func (p *LeaderProxy) Commit(ctx context.Context, reqs []*pb.Request) (*Transact // hook only after the proxy has selected and verified the local leader path. // A follower can become leader after the coordinator chose to forward a seal. func (p *LeaderProxy) commitWithLocalStamp(ctx context.Context, reqs []*pb.Request, stamp func(context.Context, []*pb.Request) (uint64, error)) (*TransactionResponse, error) { + conditions := classifyProposalConditions(reqs) + if conditions.cas && p.tm.versionCASAdmission == nil { + return nil, errors.WithStack(ErrVersionCASUnavailable) + } if !isLeaderEngine(p.engine) { return p.forwardWithRetry(ctx, reqs) } + ctx, releaseCAS, err := p.precheckLocalCAS(ctx, reqs, conditions.cas) + if err != nil { + return nil, err + } + if releaseCAS != nil { + defer releaseCAS() + } // Verify leadership with a quorum to avoid accepting writes on a stale leader. // The caller's ctx (via verifyLeaderEngineCtx) bounds the ReadIndex // round-trip, with a five-second fallback for deadline-less callers (#745). if err := verifyLeaderEngineCtx(ctx, p.engine); err != nil { + if releaseCAS != nil { + releaseCAS() + } return p.forwardWithRetry(ctx, reqs) } p.forwardBreaker.reset(leaderProxyIdentityFromEngine(p.engine)) + return p.commitVerifiedLocal(ctx, reqs, stamp, conditions) +} + +func (p *LeaderProxy) commitVerifiedLocal(ctx context.Context, reqs []*pb.Request, stamp func(context.Context, []*pb.Request) (uint64, error), conditions proposalConditions) (*TransactionResponse, error) { var commitTS uint64 + // The internal stamp hook changes timestamps and values, preserving all + // mutation operations and predicates classified before leader selection. if stamp != nil { var err error commitTS, err = stamp(ctx, reqs) @@ -79,7 +100,7 @@ func (p *LeaderProxy) commitWithLocalStamp(ctx context.Context, reqs []*pb.Reque return nil, err } } - resp, err := p.tm.Commit(ctx, reqs) + resp, err := p.tm.commitClassified(ctx, reqs, conditions) if err != nil || resp == nil || commitTS == 0 { return resp, err } @@ -91,6 +112,9 @@ func (p *LeaderProxy) commitWithLocalStamp(ctx context.Context, reqs []*pb.Reque } func (p *LeaderProxy) Abort(ctx context.Context, reqs []*pb.Request) (*TransactionResponse, error) { + if HasCASMutation(reqs) { + return nil, errors.WithStack(ErrInvalidRequest) + } if !isLeaderEngine(p.engine) { return p.forwardWithRetry(ctx, reqs) } @@ -129,6 +153,9 @@ func (p *LeaderProxy) forwardWithRetry(callerCtx context.Context, reqs []*pb.Req if len(reqs) == 0 { return &TransactionResponse{}, nil } + if slices.Contains(reqs, nil) { + return nil, errors.WithStack(ErrInvalidRequest) + } deadline := time.Now().Add(leaderProxyRetryBudget) // Parent context carries the retry deadline so forward()'s per-call @@ -245,6 +272,8 @@ func (p *LeaderProxy) runForwardCycle(callerCtx context.Context, parentCtx conte func isTerminalForwardError(err error) bool { return errors.Is(err, ErrTransactionOutcomeUnknown) || + errors.Is(err, ErrCASMismatch) || + errors.Is(err, ErrVersionCASUnavailable) || errors.Is(err, store.ErrWriteConflict) || errors.Is(err, ErrRouteWriteFenced) || errors.Is(err, ErrTxnLocked) || @@ -295,7 +324,11 @@ func (p *LeaderProxy) forward(callerCtx context.Context, parentCtx context.Conte ctx, cancel := context.WithTimeout(parentCtx, leaderForwardTimeout) defer cancel() - resp, err := cli.Forward(ctx, &pb.ForwardRequest{ + forward := cli.Forward + if HasCASMutation(reqs) { + forward = cli.ForwardCompareAndSwapV2 + } + resp, err := forward(ctx, &pb.ForwardRequest{ IsTxn: reqs[0].IsTxn, Requests: reqs, DecisionDetailVersion: ForwardDecisionSchemaVersion, @@ -320,18 +353,30 @@ func classifyForwardRPCError(err error, reqs []*pb.Request) error { if !isolatedMutationFailure(err) { return &ForwardFailure{Decision: pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_OUTCOME_UNKNOWN} } - if phase, ok := ForwardFailurePhaseForRequests(reqs); ok { - reason, decision, valid := DecodeForwardDecisionStatus(err, phase) - if valid { - if rawPreSubmissionDecision(reqs, reason, decision) { - return &dataRequestNotSubmitted{cause: ErrRouteWriteFenced} - } - return classifyValidatedForwardFailure(phase, reason, decision, ForwardOnePhaseDecisionEligible(reqs)) - } + _, casErr := ForwardCASMutation(reqs) + if casErr == nil && isVersionCASForwardUnavailable(err) { + return errors.WithStack(ErrVersionCASUnavailable) } // Legacy ErrorInfo, malformed details, and unrecognized decisions do // not prove the logical operation was absent or aborted. - return &ForwardFailure{Decision: pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_OUTCOME_UNKNOWN} + unknown := &ForwardFailure{Decision: pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_OUTCOME_UNKNOWN} + phase, ok := ForwardFailurePhaseForRequests(reqs) + if !ok { + return unknown + } + reason, decision, valid := DecodeForwardDecisionStatus(err, phase) + if !valid { + return unknown + } + if rawPreSubmissionDecision(reqs, reason, decision) { + return &dataRequestNotSubmitted{cause: ErrRouteWriteFenced} + } + if casErr == nil { + if err := classifyDedicatedCASForwardFailure(reason, decision); err != nil { + return err + } + } + return classifyValidatedForwardFailure(phase, reason, decision, ForwardOnePhaseDecisionEligible(reqs)) } func classifyValidatedForwardFailure(phase pb.ForwardFailurePhase, reason pb.ForwardFailureReason, decision pb.ForwardDecisionClass, onePhaseEligible bool) error { @@ -350,15 +395,33 @@ func classifyValidatedForwardFailure(phase pb.ForwardFailurePhase, reason pb.For case pb.ForwardFailureReason_FORWARD_FAILURE_REASON_UNSPECIFIED, pb.ForwardFailureReason_FORWARD_FAILURE_REASON_NO_LEADER, pb.ForwardFailureReason_FORWARD_FAILURE_REASON_INTERRUPTED, - pb.ForwardFailureReason_FORWARD_FAILURE_REASON_ABORTED: - return &ForwardFailure{Decision: pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_OUTCOME_UNKNOWN} - default: - return &ForwardFailure{Decision: pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_OUTCOME_UNKNOWN} + pb.ForwardFailureReason_FORWARD_FAILURE_REASON_ABORTED, + pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH, + pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_LOCKED: + // These reasons carry no definitive verdict through the generic path. } } return &ForwardFailure{Decision: pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_OUTCOME_UNKNOWN} } +func classifyDedicatedCASForwardFailure(reason pb.ForwardFailureReason, decision pb.ForwardDecisionClass) error { + switch { + case reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH && + decision == pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION: + return &casPrecheckMismatch{} + case reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_LOCKED && + decision == pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_DEFINITIVELY_ABORTED: + return errors.WithStack(&ForwardApplyRejection{cause: ErrTxnLocked}) + case reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH && + decision == pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_DEFINITIVELY_ABORTED: + return errors.WithStack(&ForwardApplyRejection{cause: ErrCASMismatch}) + case reason == pb.ForwardFailureReason_FORWARD_FAILURE_REASON_NO_LEADER && + decision == pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION: + return errors.WithStack(ErrLeaderNotFound) + } + return nil +} + // IsTransientReadBarrierError reports whether an unsuccessful read-only // barrier can be retried after a leader election or transport interruption. func IsTransientReadBarrierError(err error) bool { diff --git a/kv/leader_routed_store.go b/kv/leader_routed_store.go index af45d46db..013854a4f 100644 --- a/kv/leader_routed_store.go +++ b/kv/leader_routed_store.go @@ -77,49 +77,52 @@ func (s *LeaderRoutedStore) leaderAddrForKey(key []byte) string { return s.coordinator.RaftLeaderForKey(key) } -func (s *LeaderRoutedStore) proxyRawGet(ctx context.Context, key []byte, ts uint64) ([]byte, error) { - return s.proxyRawGetWithReadFence(ctx, key, ts, 0) -} - -func (s *LeaderRoutedStore) proxyRawGetWithReadFence(ctx context.Context, key []byte, ts uint64, readRouteVersion uint64) ([]byte, error) { - addr := s.leaderAddrForKey(key) +func (s *LeaderRoutedStore) proxyRawGet(ctx context.Context, req *pb.RawGetRequest) (store.VersionedValue, error) { + addr := s.leaderAddrForKey(req.Key) if addr == "" { - return nil, errors.WithStack(ErrLeaderNotFound) + return store.VersionedValue{}, errors.WithStack(ErrLeaderNotFound) } conn, err := s.connCache.ConnFor(addr) if err != nil { - return nil, err + return store.VersionedValue{}, err } - cli := pb.NewRawKVClient(conn) ctx, cancel := context.WithTimeout(ctx, proxyForwardTimeout) defer cancel() - resp, err := cli.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: ts, ReadRouteVersion: readRouteVersion}) - if err != nil { - return nil, errors.WithStack(err) - } - // Compatibility with older nodes that don't set RawGetResponse.exists: - // treat any non-nil payload as found even when exists=false. - if !resp.GetExists() && resp.GetValue() == nil { - return nil, store.ErrKeyNotFound - } - return resp.Value, nil + return readRawPoint(ctx, conn, req) } func (s *LeaderRoutedStore) GetAtWithReadFence(ctx context.Context, key []byte, ts uint64, groupID uint64, readRouteVersion uint64) ([]byte, error) { + result, err := s.readPointWithFence(ctx, key, ts, groupID, readRouteVersion, false) + return result.Value, err +} + +func (s *LeaderRoutedStore) GetVersionAt(ctx context.Context, key []byte, ts uint64) (store.VersionedValue, error) { + return s.GetVersionAtWithReadFence(ctx, key, ts, 0, 0) +} + +func (s *LeaderRoutedStore) GetVersionAtWithReadFence(ctx context.Context, key []byte, ts uint64, groupID uint64, readRouteVersion uint64) (store.VersionedValue, error) { + return s.readPointWithFence(ctx, key, ts, groupID, readRouteVersion, true) +} + +func (s *LeaderRoutedStore) readPointWithFence(ctx context.Context, key []byte, ts uint64, groupID uint64, readRouteVersion uint64, needCommitTS bool) (store.VersionedValue, error) { if s == nil || s.local == nil { - return nil, store.ErrKeyNotFound + return store.VersionedValue{}, unavailablePointRead(needCommitTS) } if groupID != 0 { - return nil, store.ErrNotSupported + return store.VersionedValue{}, store.ErrNotSupported } ok, fenceTS := s.leaderFenceTS(ctx, key) if ok { + if needCommitTS { + value, err := store.GetVersionAt(ctx, s.local, key, max(ts, fenceTS)) + return value, errors.WithStack(err) + } val, err := s.local.GetAt(ctx, key, max(ts, fenceTS)) - return val, errors.WithStack(err) + return store.VersionedValue{Value: val}, errors.WithStack(err) } - return s.proxyRawGetWithReadFence(ctx, key, ts, readRouteVersion) + return s.proxyRawGet(ctx, &pb.RawGetRequest{Key: key, Ts: ts, ReadRouteVersion: readRouteVersion, NeedCommitTs: needCommitTS}) } func (s *LeaderRoutedStore) proxyRawLatestCommitTS(ctx context.Context, key []byte) (uint64, bool, error) { @@ -319,15 +322,7 @@ func (s *LeaderRoutedStore) scanLocalRouteFilteredAt(ctx context.Context, start } func (s *LeaderRoutedStore) GetAt(ctx context.Context, key []byte, ts uint64) ([]byte, error) { - if s == nil || s.local == nil { - return nil, store.ErrKeyNotFound - } - ok, fenceTS := s.leaderFenceTS(ctx, key) - if ok { - val, err := s.local.GetAt(ctx, key, max(ts, fenceTS)) - return val, errors.WithStack(err) - } - return s.proxyRawGet(ctx, key, ts) + return s.GetAtWithReadFence(ctx, key, ts, 0, 0) } func (s *LeaderRoutedStore) ExistsAt(ctx context.Context, key []byte, ts uint64) (bool, error) { @@ -346,7 +341,7 @@ func (s *LeaderRoutedStore) ExistsAt(ctx context.Context, key []byte, ts uint64) // Via proxy path: RawGet returns a nil Value for a key that exists with an // empty value because proto3 strips zero-valued bytes fields on the wire. // Determine existence from the error alone, not from whether Value is non-nil. - _, err := s.proxyRawGet(ctx, key, ts) + _, err := s.proxyRawGet(ctx, &pb.RawGetRequest{Key: key, Ts: ts}) if errors.Is(err, store.ErrKeyNotFound) { return false, nil } diff --git a/kv/migration_version_adoption.go b/kv/migration_version_adoption.go new file mode 100644 index 000000000..466ac6d6d --- /dev/null +++ b/kv/migration_version_adoption.go @@ -0,0 +1,73 @@ +package kv + +import ( + "context" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" +) + +func (f *kvFSM) migrationAdoptionAuthority(ctx context.Context, jobID uint64) (func(store.MVCCVersion, store.VersionRetirement) error, error) { + active, err := MigrationVersionAdoptionEnabled(ctx, f.store) + if err != nil || !active { + return nil, err + } + view, err := readMigrationServingState(ctx, f.store) + if err != nil { + return nil, err + } + configuration := f.AppliedConfigurationIndex() + return func(version store.MVCCVersion, retirement store.VersionRetirement) error { + return verifyMigrationVersionAdoption(view, f.shardGroupID, jobID, configuration, version, retirement) + }, nil +} + +func verifyMigrationVersionAdoption(view store.MigrationServingState, groupID, jobID, configuration uint64, version store.MVCCVersion, retirement store.VersionRetirement) error { + if retirement.GroupID != groupID || retirement.JobID == jobID || configuration == 0 { + return errors.WithStack(store.ErrMigrationOwnership) + } + selector, err := decodeMigrationRetirementSelector(retirement.Selector) + if err != nil { + return err + } + version.KeyFamily = selector.GetKeyFamily() + for _, key := range migrationAdoptionRouteKeys(version) { + if err := verifyMigrationAdoptionKey(view, groupID, jobID, configuration, retirement.CommitCeiling, key); err != nil { + return err + } + } + return nil +} + +func verifyMigrationAdoptionKey(view store.MigrationServingState, groupID, jobID, configuration, ceiling uint64, key []byte) error { + proofs, err := migrationAdmissionRangeProofs(view, migrationApplyRange{key, nextScanCursor(key)}) + if err != nil || len(proofs) == 0 { + return errors.WithStack(store.ErrMigrationOwnership) + } + for _, proof := range proofs { + if !validMigrationAdoptionProof(proof, view, groupID, jobID, configuration, ceiling) { + return errors.WithStack(store.ErrMigrationOwnership) + } + } + return nil +} + +func validMigrationAdoptionProof(proof migrationAdmissionProof, view store.MigrationServingState, groupID, jobID, configuration, ceiling uint64) bool { + return proof.evidenceValid(view) && proof.Role == store.MigrationOwner && proof.Staged && + proof.LocalGroupID == groupID && proof.OwnerGroupID == groupID && proof.JobID == jobID && + proof.ConfigurationIndex == configuration && proof.WriteFloorKnown && proof.MinWriteTSExclusive > ceiling +} + +func migrationAdoptionRouteKeys(version store.MVCCVersion) [][]byte { + if version.KeyFamily == distribution.MigrationFamilyLegacyListMetaDelta { + if version.Tombstone { + return [][]byte{store.ExtractListUserKey(version.Key), store.ExtractLegacyListUserKeyFromDelta(version.Key)} + } + if store.IsListMetaDeltaValue(version.Value) { + return [][]byte{store.ExtractLegacyListUserKeyFromDelta(version.Key)} + } + return [][]byte{store.ExtractListUserKey(version.Key)} + } + return [][]byte{RouteOwnershipKey(version.Key)} +} diff --git a/kv/migration_version_adoption_test.go b/kv/migration_version_adoption_test.go new file mode 100644 index 000000000..fc5f16690 --- /dev/null +++ b/kv/migration_version_adoption_test.go @@ -0,0 +1,56 @@ +package kv + +import ( + "bytes" + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func adoptionOwnerForTest() store.MigrationOwnershipState { + return store.MigrationOwnershipState{Generation: "0123456789abcdef0123456789abcdef", + JobID: 12, LocalGroupID: 1, OwnerGroupID: 1, Role: store.MigrationOwner, Staged: true, + RouteID: 2, RouteStart: []byte("m"), RouteEnd: []byte("z"), CatalogVersion: 2, + ConfigurationIndex: 9, AppliedIndex: 13, WriteFloorKnown: true, MinWriteTSExclusive: 21, + DescriptorHash: bytes.Repeat([]byte{2}, 32), Receipts: []store.MigrationOwnershipReceipt{{ + Operation: store.MigrationOwnershipAcquire, CatalogVersion: 2, ConfigurationIndex: 9, AppliedIndex: 13, + Staged: true, DescriptorHash: bytes.Repeat([]byte{2}, 32), + }}} +} + +func TestMigrationVersionAdoptionRequiresCurrentStagedOwner(t *testing.T) { + selector, err := encodeMigrationRetirementSelector(&pb.CleanupMigrationRequest{RangeStart: []byte("m"), RangeEnd: []byte("z")}) + require.NoError(t, err) + retirement := store.VersionRetirement{JobID: 7, GroupID: 1, CommitCeiling: 20, Selector: selector} + version := store.MVCCVersion{Key: []byte("n"), CommitTS: 10, Value: []byte("unchanged")} + owner := adoptionOwnerForTest() + require.True(t, store.MigrationOwnershipEvidenceValid(owner)) + require.NoError(t, verifyMigrationVersionAdoption(store.MigrationServingState{Ownership: []store.MigrationOwnershipState{owner}}, 1, 12, 9, version, retirement)) + cases := map[string]func(*store.MigrationOwnershipState){ + "old job": func(p *store.MigrationOwnershipState) { p.JobID = 7 }, + "wrong group": func(p *store.MigrationOwnershipState) { p.LocalGroupID = 2 }, + "old config": func(p *store.MigrationOwnershipState) { p.ConfigurationIndex = 8 }, + "not staged": func(p *store.MigrationOwnershipState) { p.Staged = false }, + "unknown floor": func(p *store.MigrationOwnershipState) { p.WriteFloorKnown = false }, + "low floor": func(p *store.MigrationOwnershipState) { p.MinWriteTSExclusive = 20 }, + "outside range": func(p *store.MigrationOwnershipState) { p.RouteStart = []byte("o") }, + "no receipt": func(p *store.MigrationOwnershipState) { p.Receipts = nil }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + proof := adoptionOwnerForTest() + mutate(&proof) + view := store.MigrationServingState{Ownership: []store.MigrationOwnershipState{proof}} + require.ErrorIs(t, verifyMigrationVersionAdoption(view, 1, 12, 9, version, retirement), store.ErrMigrationOwnership) + }) + } + newer := adoptionOwnerForTest() + newer.JobID, newer.CatalogVersion, newer.OwnerGroupID, newer.Role, newer.Staged = 13, 3, 2, store.MigrationNonOwner, false + newer.Receipts[0].Operation, newer.Receipts[0].CatalogVersion, newer.Receipts[0].Staged = store.MigrationOwnershipClear, 3, false + require.True(t, store.MigrationOwnershipEvidenceValid(newer)) + view := store.MigrationServingState{Ownership: []store.MigrationOwnershipState{owner, newer}} + require.ErrorIs(t, verifyMigrationVersionAdoption(view, 1, 12, 9, version, retirement), store.ErrMigrationOwnership, + "a valid old OWNER must not bypass a newer NONOWNER certificate") +} diff --git a/kv/migration_version_adoption_upgrade_test.go b/kv/migration_version_adoption_upgrade_test.go new file mode 100644 index 000000000..d8a53338e --- /dev/null +++ b/kv/migration_version_adoption_upgrade_test.go @@ -0,0 +1,52 @@ +package kv + +import ( + "testing" + + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func TestMigrationVersionAdoptionPreservesVersionTwoReplay(t *testing.T) { + st, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + f, ok := NewKvFSMWithHLC(st, NewHLC()).(*kvFSM) + require.True(t, ok) + bindCASTestGroup(f) + seedCASReaderPolicyForTest(t, f) + f.SetApplyIndex(1) + require.Nil(t, f.Apply([]byte(raftengine.RetirementMigrationVersionIdentityFrame))) + version, err := migrationVersionIdentityVersion(t.Context(), st) + require.NoError(t, err) + require.Equal(t, migrationIdentityRetirementVersion, version) + metadata, ok := st.(store.RaftControlMetadataStore) + require.True(t, ok) + policy, err := readAppliedBootstrapPolicy(t.Context(), metadata, f.raftBootstrapIdentity, 1) + require.NoError(t, err) + require.Equal(t, raftbootstrap.PolicyRetirementVersion, policy.Version) + require.NoError(t, f.VersionRetirementReady()) + installSourceOwnershipForTest(t, f, 0) + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("old"), 10, 0)) + frame, err := MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{ + JobId: 11, Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, + RangeStart: []byte("n"), RangeEnd: []byte("o"), MaxCommitTs: 20, + RequireConfigurationIndex: true, ExpectedConfigurationIndex: 9, + }) + require.NoError(t, err) + f.SetApplyIndex(12) + result, ok := f.Apply(frame).(store.CleanupVersionsResult) + require.True(t, ok) + require.Equal(t, uint64(1), result.DeletedRows, "v2 replay must not require the new source-group field") + f.SetApplyIndex(13) + require.Nil(t, f.Apply(EncodeMigrationVersionIdentityActivation())) + active, err := MigrationVersionAdoptionEnabled(t.Context(), st) + require.NoError(t, err) + require.True(t, active) + require.NoError(t, f.VersionRetirementReady()) + _, err = st.GetAt(t.Context(), []byte("n"), 30) + require.ErrorIs(t, err, store.ErrKeyNotFound) +} diff --git a/kv/migration_version_identity.go b/kv/migration_version_identity.go new file mode 100644 index 000000000..0f0ce847c --- /dev/null +++ b/kv/migration_version_identity.go @@ -0,0 +1,237 @@ +package kv + +import ( + "bytes" + "context" + "slices" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" +) + +var migrationVersionIdentityKey = []byte("migration-version-identity") + +const migrationIdentityRetirementVersion byte = 2 +const migrationIdentityAdoptionVersion byte = 3 + +var migrationVersionIdentityValue = []byte{migrationIdentityAdoptionVersion} + +var errMigrationRetirementActivationBusy = errors.New("migration retirement activation overlaps a membership reservation") + +// EncodeMigrationVersionIdentityActivation returns the Raft frame that makes +// future migration imports, promotions and cleanup preserve CAS version identity. +func EncodeMigrationVersionIdentityActivation() []byte { + return []byte(raftengine.MigrationVersionIdentityFrame) +} + +// IsMigrationVersionIdentityActivation recognizes the replicated marker frame. +func IsMigrationVersionIdentityActivation(data []byte) bool { + return bytes.HasPrefix(data, []byte("\x06MVI")) +} + +// MigrationVersionIdentityEnabled reports whether the store has applied the +// replicated migration version identity marker. +func MigrationVersionIdentityEnabled(ctx context.Context, st store.MVCCStore) (bool, error) { + version, err := migrationVersionIdentityVersion(ctx, st) + return version != 0, err +} + +func MigrationVersionRetirementEnabled(ctx context.Context, st store.MVCCStore) (bool, error) { + version, err := migrationVersionIdentityVersion(ctx, st) + return version >= migrationIdentityRetirementVersion, err +} + +func MigrationVersionAdoptionEnabled(ctx context.Context, st store.MVCCStore) (bool, error) { + version, err := migrationVersionIdentityVersion(ctx, st) + return version == migrationVersionIdentityValue[0], err +} + +func migrationVersionIdentityVersion(ctx context.Context, st store.MVCCStore) (byte, error) { + metadata, ok := st.(store.RaftControlMetadataStore) + if !ok { + return 0, nil + } + value, err := metadata.ReadRaftControlMetadata(ctx, migrationVersionIdentityKey) + if errors.Is(err, store.ErrKeyNotFound) { + return 0, nil + } + if err != nil { + return 0, errors.WithStack(err) + } + if len(value) != 1 || value[0] < 1 || value[0] > migrationVersionIdentityValue[0] { + return 0, errors.New("invalid migration version identity marker") + } + return value[0], nil +} + +func (f *kvFSM) applyMigrationVersionIdentityActivation(ctx context.Context, data []byte) any { + version := migrationVersionIdentityValue[0] + switch { + case bytes.Equal(data, []byte(raftengine.LegacyMigrationVersionIdentityFrame)): + version = 1 + case bytes.Equal(data, []byte(raftengine.RetirementMigrationVersionIdentityFrame)): + version = migrationIdentityRetirementVersion + case !bytes.Equal(data, []byte(raftengine.MigrationVersionIdentityFrame)): + return haltErr(errors.Mark(errors.New("invalid migration version identity frame"), ErrRaftEntryApply)) + } + err := f.persistMigrationVersionIdentity(ctx, version) + if errors.Is(err, errMigrationRetirementActivationBusy) { + return errors.Wrap(ErrVersionCASUnavailable, err.Error()) + } + if err != nil { + return haltErr(errors.Wrap(errors.Mark(err, ErrRaftEntryApply), "kv/fsm: activate migration version identity")) + } + return nil +} + +func (f *kvFSM) persistMigrationVersionIdentity(ctx context.Context, version byte) error { + if !f.versionRetirementConfigured { + if err := f.configureVersionRetirement(); err != nil { + return err + } + } + applier, ok := f.store.(store.RaftEntryApplier) + if !ok || f.pendingApplyIdx == 0 { + return errors.WithStack(store.ErrRaftControlScopeRequired) + } + metadata, ok := f.store.(store.RaftControlMetadataStore) + if !ok { + return errors.WithStack(store.ErrNotSupported) + } + var verdict error + err := applier.ApplyRaftEntry(ctx, f.pendingApplyIdx, func(ctx context.Context) error { + replayed, err := store.StageRaftEntryProgress(ctx, f.pendingApplyIdx) + if err != nil || replayed { + return errors.WithStack(err) + } + err = f.stageMigrationVersionIdentity(ctx, metadata, version) + if errors.Is(err, errMigrationRetirementActivationBusy) { + verdict = err + return nil + } + return err + }) + return errors.WithStack(errors.Join(err, verdict)) +} + +func (f *kvFSM) stageMigrationVersionIdentity(ctx context.Context, metadata store.RaftControlMetadataStore, version byte) error { + current, err := migrationVersionIdentityVersion(ctx, f.store) + if err != nil || current >= version { + return err + } + if version >= migrationIdentityRetirementVersion { + if err := f.stageRetirementReaderFloor(ctx, metadata, version); err != nil { + return err + } + } + if version >= migrationIdentityAdoptionVersion { + retirement, ok := f.store.(store.VersionRetirementStore) + if !ok { + return errors.WithStack(store.ErrVersionRetirementUnavailable) + } + if err := retirement.StageVersionAdoptionActivation(ctx); err != nil { + return errors.WithStack(err) + } + } + return errors.WithStack(metadata.StageRaftControlMetadata(ctx, migrationVersionIdentityKey, []byte{version})) +} + +func (f *kvFSM) stageRetirementReaderFloor(ctx context.Context, metadata store.RaftControlMetadataStore, version byte) error { + // Embedded, unprotected FSMs do not advertise production capability. Native + // protected groups persist the reader floor with activation so old binaries + // reject recovery even if the activating log frame was snapshotted away. + if f.raftBootstrapIdentity.Cluster == (raftbootstrap.UUID{}) { + return nil + } + policy, err := readAppliedBootstrapPolicy(ctx, metadata, f.raftBootstrapIdentity, f.pendingApplyIdx) + if err != nil { + return err + } + floor := raftbootstrap.PolicyRetirementVersion + if version >= migrationIdentityAdoptionVersion { + floor = raftbootstrap.PolicyAdoptionVersion + } + if policy.Version >= floor { + return nil + } + if policy.Reservation != nil { + return errors.WithStack(errMigrationRetirementActivationBusy) + } + policy.Version = floor + data, err := raftbootstrap.MarshalPolicyRecord(policy) + if err != nil { + return errors.WithStack(err) + } + key, err := BootstrapPolicyMetadataKey(policy.Identity) + if err != nil { + return err + } + return errors.WithStack(metadata.StageRaftControlMetadata(ctx, key, data)) +} + +// Decide before scanning MVCC rows. A replica may have pruned a different set +// of historical rows, and a cursor or page budget can even hide a head behind +// that history. The entire effective direct-key range needs lasting coverage. +func verifyMigrationVersionCleanupCoverage(ctx context.Context, st store.MVCCStore, req *pb.CleanupMigrationRequest) error { + start, end := req.GetRangeStart(), req.GetRangeEnd() + if cleanupRangeCannotIssueVersions(start, end) { + return nil + } + // On CAS-eligible keys routeKey is the identity. Special family filters + // have their own semantics, so only the ordinary route filter narrows this + // bound. Normal special-family scans are exempt by their physical prefix. + if req.GetRequiresRouteKeyCheck() && !req.GetRequiresDecodedS3() && req.GetKeyFamily() != distribution.MigrationFamilyLegacyListMetaDelta { + start, end = prefixDeleteRouteIntersection(distribution.Route{Start: req.GetRouteStart(), End: req.GetRouteEnd()}, start, end) + } + if len(end) != 0 && bytes.Compare(start, end) >= 0 { + return nil + } + view, err := readMigrationServingState(ctx, st) + if err != nil { + return errors.WithStack(err) + } + if !migrationVersionCleanupCovered(view, start, end) { + return errors.Wrap(store.ErrMigrationOwnership, "version cleanup requires durable CAS range coverage") + } + return nil +} + +func cleanupRangeCannotIssueVersions(start, end []byte) bool { + if len(end) == 0 { + return false + } + prefixes := append(distribution.MigrationKnownInternalPrefixes(), distribution.MigrationStagedDataScanPrefix()) + for _, prefix := range prefixes { + if bytes.HasPrefix(start, prefix) && bytes.Compare(end, store.PrefixScanEnd(prefix)) <= 0 { + return true + } + } + return false +} + +func migrationVersionCleanupCovered(view store.MigrationServingState, start, end []byte) bool { + // CAS excludes both kinds of ownership evidence. Per-job retirement + // preserves the ledger, and frontier transitions preserve or expand its + // interval coverage. Readiness alone can disappear when a job retires. + proofs := migrationAdmissionProofs(view) + slices.SortFunc(proofs, func(a, b migrationAdmissionProof) int { return bytes.Compare(a.RouteStart, b.RouteStart) }) + for _, proof := range proofs { + if bytes.Compare(proof.RouteStart, start) > 0 { + break + } + if !proof.evidenceValid(view) { + continue + } + if len(proof.RouteEnd) == 0 || (len(end) != 0 && bytes.Compare(proof.RouteEnd, end) >= 0) { + return true + } + if bytes.Compare(proof.RouteEnd, start) > 0 { + start = proof.RouteEnd + } + } + return false +} diff --git a/kv/migration_version_retirement.go b/kv/migration_version_retirement.go new file mode 100644 index 000000000..843a4a674 --- /dev/null +++ b/kv/migration_version_retirement.go @@ -0,0 +1,204 @@ +package kv + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "slices" + + "github.com/bootjp/elastickv/distribution" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "google.golang.org/protobuf/proto" +) + +const migrationRetirementSelectorVersion byte = 1 + +func (f *kvFSM) VersionRetirementReady() error { + if f.versionRetirementLoadErr != nil { + return f.versionRetirementLoadErr + } + if !f.versionRetirementConfigured { + return errors.WithStack(store.ErrVersionRetirementUnavailable) + } + active, err := MigrationVersionAdoptionEnabled(context.Background(), f.store) + if err != nil { + return err + } + if active { + retirement, ok := f.store.(store.VersionRetirementStore) + if !ok { + return errors.WithStack(store.ErrVersionRetirementUnavailable) + } + return errors.WithStack(retirement.VersionAdoptionReady(context.Background())) + } + return nil +} + +func compileMigrationRetirementSelector(data []byte) (func([]byte, []byte) bool, error) { + request, err := decodeMigrationRetirementSelector(data) + if err != nil { + return nil, err + } + return migrationCleanupOptionsFromProto(request, 0).AcceptVersion, nil +} + +func decodeMigrationRetirementSelector(data []byte) (*pb.CleanupMigrationRequest, error) { + if len(data) == 0 || data[0] != migrationRetirementSelectorVersion { + return nil, errors.WithStack(store.ErrVersionRetirementUnavailable) + } + request := &pb.CleanupMigrationRequest{} + if err := proto.Unmarshal(data[1:], request); err != nil { + return nil, errors.Wrap(err, "decode retirement selector") + } + if len(request.ProtoReflect().GetUnknown()) != 0 { + return nil, errors.WithStack(store.ErrVersionRetirementUnavailable) + } + return request, nil +} + +func encodeMigrationRetirementSelector(req *pb.CleanupMigrationRequest) ([]byte, error) { + selector := &pb.CleanupMigrationRequest{ + RangeStart: bytes.Clone(req.GetRangeStart()), RangeEnd: bytes.Clone(req.GetRangeEnd()), + KeyFamily: req.GetKeyFamily(), ExcludePrefixes: cloneMigrationByteSlices(req.GetExcludePrefixes()), + ExcludeKnownInternal: req.GetExcludeKnownInternal(), RequiresRouteKeyCheck: req.GetRequiresRouteKeyCheck(), + RequiresDecodedS3: req.GetRequiresDecodedS3(), RouteStart: bytes.Clone(req.GetRouteStart()), RouteEnd: bytes.Clone(req.GetRouteEnd()), + } + data, err := (proto.MarshalOptions{Deterministic: true}).Marshal(selector) + return append([]byte{migrationRetirementSelectorVersion}, data...), errors.WithStack(err) +} + +func (f *kvFSM) configureVersionRetirement() error { + retirement, ok := f.store.(store.VersionRetirementStore) + if !ok { + return nil + } + if err := retirement.ConfigureVersionRetirement(compileMigrationRetirementSelector); err != nil { + return errors.WithStack(err) + } + f.versionRetirementConfigured = true + return nil +} + +func (f *kvFSM) prepareMigrationVersionRetirement(ctx context.Context, req *pb.CleanupMigrationRequest) (store.VersionRetirementStore, *store.VersionRetirement, error) { + // Retired private staging belongs to an already closed job. It cannot be + // returned by public reads or promoted after the durable job retirement. + if privateMigrationRetirement(req) { + return nil, nil, nil + } + if req.GetMaxCommitTs() == 0 || !req.GetRequireConfigurationIndex() || f.shardGroupID == 0 { + return nil, nil, errors.WithStack(store.ErrVersionRetirementUnavailable) + } + if err := f.validateRetirementSourceGroup(ctx, req); err != nil { + return nil, nil, err + } + if err := f.verifyRetirementSourceSessions(ctx, req); err != nil { + return nil, nil, err + } + retirement, ok := f.store.(store.VersionRetirementStore) + if !ok { + return nil, nil, errors.WithStack(store.ErrNotSupported) + } + generation, err := f.migrationRetirementGeneration(ctx, req) + if err != nil { + return nil, nil, err + } + selector, err := encodeMigrationRetirementSelector(req) + if err != nil { + return nil, nil, err + } + return retirement, &store.VersionRetirement{ + ID: fmt.Sprintf("job/%d/family/%d/config/%d/%s", req.GetJobId(), req.GetKeyFamily(), req.GetExpectedConfigurationIndex(), generation), + JobID: req.GetJobId(), GroupID: f.shardGroupID, ConfigurationIndex: req.GetExpectedConfigurationIndex(), Generation: generation, + CommitCeiling: req.GetMaxCommitTs(), StartKey: bytes.Clone(req.GetRangeStart()), EndKey: bytes.Clone(req.GetRangeEnd()), Selector: selector, + }, nil +} + +func (f *kvFSM) validateRetirementSourceGroup(ctx context.Context, req *pb.CleanupMigrationRequest) error { + adopting, err := MigrationVersionAdoptionEnabled(ctx, f.store) + if err != nil { + return err + } + if adopting && req.GetExpectedSourceGroupId() != f.shardGroupID { + return errors.WithStack(store.ErrMigrationOwnership) + } + return nil +} + +func privateMigrationRetirement(req *pb.CleanupMigrationRequest) bool { + private := distribution.MigrationStagedDataScanPrefix() + return bytes.HasPrefix(req.GetRangeStart(), private) && len(req.GetRangeEnd()) != 0 && + bytes.Compare(req.GetRangeEnd(), store.PrefixScanEnd(private)) <= 0 +} + +func (f *kvFSM) verifyRetirementSourceSessions(ctx context.Context, req *pb.CleanupMigrationRequest) error { + guard, err := f.onlineMaintenanceGuard(ctx, req) + if err != nil || guard == nil { + return err + } + start, end := req.GetRouteStart(), req.GetRouteEnd() + if len(start) == 0 && len(end) == 0 { + start, end = readinessRouteRangeForScan(req.GetRangeStart(), req.GetRangeEnd()) + } + for _, session := range guard.Sessions { + if routeRangeIntersects(start, end, session.RouteStart, session.RouteEnd) { + // Protect the entire logical interval, not just locally retained + // rows on this page. Only the sealed, fenced post-cutover proof + // accepted by onlineMaintenanceGuard can exempt a live session. + return errors.WithStack(store.ErrVersionRetirementUnavailable) + } + } + return nil +} + +func (f *kvFSM) migrationRetirementGeneration(ctx context.Context, req *pb.CleanupMigrationRequest) (string, error) { + view, err := readMigrationServingState(ctx, f.store) + if err != nil { + return "", err + } + start, end := req.GetRouteStart(), req.GetRouteEnd() + if len(start) == 0 && len(end) == 0 { + start, end = req.GetRangeStart(), req.GetRangeEnd() + } + proofs, err := migrationAdmissionRangeProofs(view, migrationApplyRange{start: start, end: end}) + if err != nil || len(proofs) == 0 { + return "", errors.Wrap(errors.Join(store.ErrMigrationOwnership, err), "retirement requires replicated ownership lineage") + } + adopting, err := MigrationVersionAdoptionEnabled(ctx, f.store) + if err != nil { + return "", err + } + var jobID uint64 + if adopting { + jobID = req.GetJobId() + } + identities, err := retirementProofIdentities(view, proofs, f.shardGroupID, jobID) + if err != nil { + return "", err + } + slices.Sort(identities) + identities = slices.Compact(identities) + hash := sha256.New() + for _, identity := range identities { + _, _ = fmt.Fprintf(hash, "%d:%s", len(identity), identity) + } + return hex.EncodeToString(hash.Sum(nil)), nil +} + +func retirementProofIdentities(view store.MigrationServingState, proofs []migrationAdmissionProof, groupID, jobID uint64) ([]string, error) { + identities := make([]string, 0, len(proofs)) + for _, proof := range proofs { + if proof.Generation == "" || proof.LocalGroupID != groupID || !retirementProofJobMatches(proof, jobID) || !proof.evidenceValid(view) { + return nil, errors.WithStack(store.ErrMigrationOwnership) + } + identities = append(identities, proof.Generation+"/"+proof.identity) + } + return identities, nil +} + +func retirementProofJobMatches(proof migrationAdmissionProof, jobID uint64) bool { + return jobID == 0 || proof.JobID == jobID +} diff --git a/kv/mutation_nonadmission_test.go b/kv/mutation_nonadmission_test.go index 84817cec2..93a27252d 100644 --- a/kv/mutation_nonadmission_test.go +++ b/kv/mutation_nonadmission_test.go @@ -34,7 +34,7 @@ func TestRawMigrationPreproposalRejectionCarriesRequestEvidence(t *testing.T) { f, _, _ := frontierAdmissionSplitFixture(t) proposer := &fakeProposer{} admission := &transactionMigrationAdmission{store: f.store, groupID: 3} - index, results, err := admission.apply(t.Context(), proposer, []*pb.Request{{Ts: 200, Mutations: []*pb.Mutation{{Op: pb.Op_PUT, Key: []byte("n"), Value: []byte("v")}}}}, nil) + index, results, err := admission.apply(t.Context(), proposer, []*pb.Request{{Ts: 200, Mutations: []*pb.Mutation{{Op: pb.Op_PUT, Key: []byte("n"), Value: []byte("v")}}}}, nil, false) require.NoError(t, err) require.Zero(t, index) require.Zero(t, proposer.calls.Load()) diff --git a/kv/ordinary_write_comparison_test.go b/kv/ordinary_write_comparison_test.go new file mode 100644 index 000000000..bfc09939c --- /dev/null +++ b/kv/ordinary_write_comparison_test.go @@ -0,0 +1,70 @@ +package kv + +import ( + "context" + "fmt" + "testing" + + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" +) + +type ordinaryBenchmarkLeader struct { + raftengine.Engine + verifications uint64 + proposals uint64 + frame []byte +} + +func (*ordinaryBenchmarkLeader) State() raftengine.State { return raftengine.StateLeader } +func (*ordinaryBenchmarkLeader) Leader() raftengine.LeaderInfo { + return raftengine.LeaderInfo{} +} +func (*ordinaryBenchmarkLeader) Status() raftengine.Status { return raftengine.Status{} } +func (e *ordinaryBenchmarkLeader) VerifyLeader(context.Context) error { + e.verifications++ + return nil +} +func (e *ordinaryBenchmarkLeader) Propose(_ context.Context, frame []byte) (*raftengine.ProposalResult, error) { + e.proposals++ + e.frame = frame + return &raftengine.ProposalResult{CommitIndex: e.proposals}, nil +} + +func BenchmarkOrdinaryLeaderLocal1PC(b *testing.B) { + for _, count := range []int{1, 64} { + b.Run(fmt.Sprintf("Mutations%d", count), func(b *testing.B) { + ctx := b.Context() + leader := &ordinaryBenchmarkLeader{} + proxy := NewLeaderProxyWithEngine(leader) + b.Cleanup(func() { _ = proxy.Close() }) + key := []byte("key-0") + mutations := []*pb.Mutation{{ + Op: pb.Op_PUT, Key: []byte(txnMetaPrefix), + Value: EncodeTxnMeta(TxnMeta{PrimaryKey: key, CommitTS: 11}), + }} + for i := range count { + mutations = append(mutations, &pb.Mutation{ + Op: pb.Op_PUT, Key: fmt.Appendf(nil, "key-%d", i), Value: []byte("ordinary-value"), + }) + } + req := &pb.Request{IsTxn: true, Phase: pb.Phase_NONE, Ts: 10, Mutations: mutations} + reqs := []*pb.Request{req} + b.ReportAllocs() + for b.Loop() { + res, err := proxy.Commit(ctx, reqs) + if err != nil || res.CommitIndex != leader.proposals { + b.Fatalf("Commit returned %v, %v", res, err) + } + } + if leader.proposals != uint64(b.N) || leader.verifications != uint64(b.N) { + b.Fatalf("got %d proposals and %d verifications for %d commits", leader.proposals, leader.verifications, b.N) + } + if len(leader.frame) == 0 || leader.frame[0] != raftEncodeSingle { + b.Fatal("expected ordinary single-request Raft framing") + } + b.ReportMetric(float64(leader.proposals)/float64(b.N), "proposals/op") + b.ReportMetric(float64(leader.verifications)/float64(b.N), "verifications/op") + }) + } +} diff --git a/kv/owned_snapshot_test.go b/kv/owned_snapshot_test.go new file mode 100644 index 000000000..9f1279b75 --- /dev/null +++ b/kv/owned_snapshot_test.go @@ -0,0 +1,141 @@ +package kv + +import ( + "bufio" + "bytes" + "testing" + "time" + + "github.com/bootjp/elastickv/internal/encryption" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +type snapshotDispatchStore struct { + store.MVCCStore + standard, owned int +} + +func (s *snapshotDispatchStore) Snapshot() (store.Snapshot, error) { + s.standard++ + return s.MVCCStore.Snapshot() +} + +func (s *snapshotDispatchStore) CaptureOwnerSnapshot() (store.Snapshot, error) { + s.owned++ + return s.MVCCStore.Snapshot() +} + +func TestKVOwnerSnapshotDispatch(t *testing.T) { + st := &snapshotDispatchStore{MVCCStore: store.NewMVCCStore()} + defer func() { require.NoError(t, st.Close()) }() + f := NewKvFSMWithHLC(st, nil) + standard, err := f.Snapshot() + require.NoError(t, err) + require.NoError(t, standard.Close()) + require.Equal(t, 1, st.standard) + require.Zero(t, st.owned) + owner, ok := f.(raftengine.OwnerSnapshotCapturer) + require.True(t, ok) + snap, err := owner.CaptureOwnerSnapshot() + require.NoError(t, err) + require.NoError(t, snap.Close()) + require.Equal(t, 1, st.standard) + require.Equal(t, 1, st.owned) +} + +func TestKVOwnerSnapshotHeaderAndStoreCut(t *testing.T) { + st, err := store.NewPebbleStore(t.TempDir(), store.WithSSTIngestSnapshots(true)) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + cutover := &staticCutoverSource{v: 5} + f, ok := NewKvFSMWithHLC(st, NewHLC()).(*kvFSM) + require.True(t, ok) + f.cutoverSource = cutover + f.hlc.SetPhysicalCeiling(100) + cp := encryption.SnapshotCheckpoint{Index: 6, State: [32]byte{1}} + f.encryption = &checkpointApplier{checkpoint: cp} + require.NoError(t, f.captureEncryptionCheckpoint(6)) + require.NoError(t, st.PutAt(t.Context(), []byte("key"), []byte("cut"), 7, 0)) + snap, err := f.CaptureOwnerSnapshot() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, snap.Close()) }) + cutover.v = 9 + f.hlc.SetPhysicalCeiling(200) + f.encryption = &checkpointApplier{checkpoint: encryption.SnapshotCheckpoint{Index: 9, State: [32]byte{2}}} + require.NoError(t, f.captureEncryptionCheckpoint(9)) + require.NoError(t, st.PutAt(t.Context(), []byte("key"), []byte("later"), 10, 0)) + var raw bytes.Buffer + _, err = snap.WriteTo(&raw) + require.NoError(t, err) + reader := bufio.NewReader(bytes.NewReader(raw.Bytes())) + ceiling, index, restoredCP, err := ReadSnapshotHeaderWithCheckpoint(reader) + require.NoError(t, err) + require.Equal(t, uint64(100), ceiling) + require.Equal(t, uint64(5), index) + require.Equal(t, cp, restoredCP) + bodyMagic, err := reader.Peek(8) + require.NoError(t, err) + require.Equal(t, "EKVSSTI1", string(bodyMagic)) + require.NoError(t, snap.Close()) + require.NoError(t, snap.Close()) + var afterClose bytes.Buffer + n, err := snap.WriteTo(&afterClose) + require.Error(t, err) + require.Zero(t, n) + require.Zero(t, afterClose.Len(), "closed KV handle cannot emit even the header") + require.NoError(t, f.Restore(&raw)) + require.Equal(t, cp, f.encryptionCheckpoint) + v, err := st.GetAt(t.Context(), []byte("key"), 10) + require.NoError(t, err) + require.Equal(t, []byte("cut"), v) +} + +func TestKVOwnerSnapshotGatesAndFallback(t *testing.T) { + tracker := NewActiveTimestampTracker(WithActiveTimestampTrackerSweepInterval(0)) + f := newBackupTestFSMWithGroup(t, tracker, 7) + pin := backupTrackerTestPinID(1) + require.NoError(t, haltApplyOf(f.Apply(EncodeBackupPinEntry(BackupPinEntry{ + PinID: pin, ReadTS: 75, Deadline: time.Now().Add(time.Hour), + })))) + snap, err := f.CaptureOwnerSnapshot() + require.Nil(t, snap) + require.ErrorIs(t, err, ErrBackupSnapshotBlocked) + require.ErrorIs(t, err, raftengine.ErrSnapshotDeferred) + require.NoError(t, haltApplyOf(f.Apply(EncodeBackupReleaseEntry(BackupReleaseEntry{PinID: pin})))) + + // This wrapper exposes the standard store API and the checkpoint gate, + // so capture must still enforce the gate and support the generic image. + st := &durableCheckpointFixture{MVCCStore: f.store, checkpoint: encryption.SnapshotCheckpoint{Index: 6}} + f.store = st + snap, err = f.CaptureOwnerSnapshot() + require.Nil(t, snap) + require.ErrorContains(t, err, "durable tail must reconcile") + f.encryptionCheckpoint = st.checkpoint + require.NoError(t, st.PutAt(t.Context(), []byte("generic"), []byte("cut"), 80, 0)) + snap, err = f.CaptureOwnerSnapshot() + require.NoError(t, err) + defer func() { require.NoError(t, snap.Close()) }() + var raw bytes.Buffer + _, err = snap.WriteTo(&raw) + require.NoError(t, err) + target := store.NewMVCCStore() + t.Cleanup(func() { require.NoError(t, target.Close()) }) + require.NoError(t, NewKvFSMWithHLC(target, nil).Restore(&raw)) + v, err := target.GetAt(t.Context(), []byte("generic"), 80) + require.NoError(t, err) + require.Equal(t, []byte("cut"), v) +} + +func TestBackedTSODoesNotAdvertiseOwnerSnapshot(t *testing.T) { + st, err := store.NewPebbleStore(t.TempDir(), store.WithSSTIngestSnapshots(true)) + require.NoError(t, err) + defer func() { require.NoError(t, st.Close()) }() + backing, ok := st.(TSODurableBacking) + require.True(t, ok) + f, err := NewDurableTSOStateMachine(NewHLC(), backing) + require.NoError(t, err) + _, ok = any(f).(raftengine.OwnerSnapshotCapturer) + require.False(t, ok) +} diff --git a/kv/raft_bootstrap_guard.go b/kv/raft_bootstrap_guard.go index e0c7fbc81..07afacfb9 100644 --- a/kv/raft_bootstrap_guard.go +++ b/kv/raft_bootstrap_guard.go @@ -154,7 +154,8 @@ func validGuardedCatalogCommitHeader(request *pb.Request) bool { } func guardedCatalogMutationOptionsValid(mutation *pb.Mutation) bool { - return len(mutation.ProtoReflect().GetUnknown()) == 0 && mutation.CommitTsValueOffset == 0 && !mutation.RequireAbsent + return len(mutation.ProtoReflect().GetUnknown()) == 0 && mutation.CommitTsValueOffset == 0 && + !mutation.RequireAbsent && mutation.ExpectedCommitTs == 0 } func validateGuardedCatalogMutation(mutation *pb.Mutation) error { @@ -173,7 +174,7 @@ func validateGuardedCatalogMutation(mutation *pb.Mutation) error { return errors.WithStack(ErrInvalidGuardedBootstrapInner) } return nil - case pb.Op_DEL_PREFIX: + case pb.Op_DEL_PREFIX, pb.Op_COMPARE_AND_SWAP: return errors.WithStack(ErrInvalidGuardedBootstrapInner) } return errors.WithStack(ErrInvalidGuardedBootstrapInner) diff --git a/kv/raw_point_read.go b/kv/raw_point_read.go new file mode 100644 index 000000000..3e9477c3b --- /dev/null +++ b/kv/raw_point_read.go @@ -0,0 +1,39 @@ +package kv + +import ( + "context" + + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "google.golang.org/grpc" +) + +func readRawPoint(ctx context.Context, conn grpc.ClientConnInterface, req *pb.RawGetRequest) (store.VersionedValue, error) { + resp, err := pb.NewRawKVClient(conn).RawGet(ctx, req) + if err != nil { + return store.VersionedValue{}, errors.WithStack(err) + } + if req.NeedCommitTs { + return decodeRawPointVersion(resp) + } + // Older nodes may omit Exists when returning a value. + if !resp.GetExists() && resp.GetValue() == nil { + return store.VersionedValue{}, store.ErrKeyNotFound + } + return store.VersionedValue{Value: resp.GetValue()}, nil +} + +func decodeRawPointVersion(resp *pb.RawGetResponse) (store.VersionedValue, error) { + switch version := resp.GetVersion().(type) { + case *pb.RawGetResponse_CommitTs: + if version.CommitTs > 0 && resp.GetExists() { + return store.VersionedValue{TS: version.CommitTs, Value: resp.GetValue()}, nil + } + case *pb.RawGetResponse_Missing: + if version.Missing && !resp.GetExists() && len(resp.GetValue()) == 0 { + return store.VersionedValue{}, store.ErrKeyNotFound + } + } + return store.VersionedValue{}, store.ErrNotSupported +} diff --git a/kv/read_request_ports.go b/kv/read_request_ports.go index 4e6db39af..68edad558 100644 --- a/kv/read_request_ports.go +++ b/kv/read_request_ports.go @@ -25,6 +25,28 @@ func withReadSnapshot[T any](r *ReadRequest, ctx context.Context, snapshot ReadS return value, errors.WithStack(err) } +// GetVersion reads the visible record behind the request's point-read snapshot. +func (r *ReadRequest) GetVersion(ctx context.Context, snapshot ReadSnapshot, key []byte) (store.VersionedValue, error) { + return withReadSnapshot(r, ctx, snapshot, func() error { return r.validateKeyScope(snapshot, key) }, func(timestamp uint64) (store.VersionedValue, error) { + shards, ok := r.st.(*ShardStore) + if !ok { + return store.VersionedValue{}, store.ErrNotSupported + } + return shards.GetVersionAt(ctx, key, timestamp) + }) +} + +// GetVersionWithFence preserves the explicit group and route fence on RawGet. +func (r *ReadRequest) GetVersionWithFence(ctx context.Context, snapshot ReadSnapshot, key []byte, groupID uint64, readRouteVersion uint64) (store.VersionedValue, error) { + return withReadSnapshot(r, ctx, snapshot, func() error { return r.validateGroupScope(snapshot, groupID, key) }, func(timestamp uint64) (store.VersionedValue, error) { + reader, ok := r.st.(*ShardStore) + if !ok { + return store.VersionedValue{}, store.ErrNotSupported + } + return reader.GetVersionAtWithReadFence(ctx, key, timestamp, groupID, readRouteVersion) + }) +} + func (r *ReadRequest) Exists(ctx context.Context, snapshot ReadSnapshot, key []byte) (bool, error) { return withReadSnapshot(r, ctx, snapshot, func() error { return r.validateKeyScope(snapshot, key) }, func(timestamp uint64) (bool, error) { reader, ok := r.st.(interface { diff --git a/kv/shard_store.go b/kv/shard_store.go index 50b9e2fb3..91ab74e37 100644 --- a/kv/shard_store.go +++ b/kv/shard_store.go @@ -56,6 +56,16 @@ var ( var ErrTSOCommitFloorUnavailable = errors.New("tso: authoritative data-group commit floor is unavailable") +// Keep the original diagnostic for term initialization. Wrapf attaches its +// error arguments as secondary causes, so expose only the two known identities. +type dataGroupFloorTransfer struct{ floorOnly error } + +func (e *dataGroupFloorTransfer) Error() string { return e.floorOnly.Error() } +func (*dataGroupFloorTransfer) Unwrap() error { return ErrTSOCommitFloorUnavailable } +func (*dataGroupFloorTransfer) Is(target error) bool { + return target == raftengine.ErrLeadershipTransferInProgress +} + // TSOCutoverFloorProvider supplies the highest commit timestamp that the // dedicated TSO must exceed before a leader term can issue a window. type TSOCutoverFloorProvider interface { @@ -311,6 +321,37 @@ func (s *ShardStore) GetAt(ctx context.Context, key []byte, ts uint64) ([]byte, return s.GetAtWithReadFence(ctx, key, ts, 0, 0) } +func (s *ShardStore) GetVersionAt(ctx context.Context, key []byte, ts uint64) (store.VersionedValue, error) { + return s.GetVersionAtWithReadFence(ctx, key, ts, 0, 0) +} + +func (s *ShardStore) GetVersionAtWithReadFence(ctx context.Context, key []byte, ts uint64, groupID uint64, readRouteVersion uint64) (store.VersionedValue, error) { + ctx = migrationServingReadContext(ctx, readRouteVersion) + if err := s.awaitReadRouteVersion(ctx, readRouteVersion); err != nil { + return store.VersionedValue{}, err + } + route, version, ok := s.versionReadRoute(key, groupID) + if !ok { + return store.VersionedValue{}, store.ErrNotSupported + } + g, ok := s.groupForID(route.GroupID) + if !ok || g == nil || g.Store == nil || g.versionReadAdmission == nil { + return store.VersionedValue{}, store.ErrNotSupported + } + return s.readPointInGroup(ctx, g, route, key, ts, route.GroupID, max(version, readRouteVersion), true) +} + +func (s *ShardStore) versionReadRoute(key []byte, groupID uint64) (distribution.Route, uint64, bool) { + if s.engine == nil || !versionCASDirectKey(key) { + return distribution.Route{}, 0, false + } + if _, partitioned, err := s.partitionOwner(key); partitioned || err != nil { + return distribution.Route{}, 0, false + } + route, version, ok := s.engine.GetRouteWithVersion(key) + return route, version, ok && versionCASInitialRoute(route) && (groupID == 0 || groupID == route.GroupID) +} + func (s *ShardStore) GetAtWithReadFence(ctx context.Context, key []byte, ts uint64, groupID uint64, readRouteVersion uint64) ([]byte, error) { ctx = migrationServingReadContext(ctx, readRouteVersion) if err := s.awaitReadRouteVersion(ctx, readRouteVersion); err != nil { @@ -359,7 +400,7 @@ func (s *ShardStore) getGroupAtWithReadFence(ctx context.Context, groupID uint64 return nil, err } g, ok := s.groupForID(groupID) - if !ok || g.Store == nil { + if !ok || g == nil || g.Store == nil { return nil, store.ErrKeyNotFound } route, err := s.routeForExplicitGroupKey(groupID, key) @@ -372,26 +413,38 @@ func (s *ShardStore) getGroupAtWithReadFence(ctx context.Context, groupID uint64 func (s *ShardStore) getRouteAt(ctx context.Context, route distribution.Route, key []byte, ts uint64, readRouteVersion uint64) ([]byte, error) { g, ok := s.groupForID(route.GroupID) - if !ok || g.Store == nil { + if !ok || g == nil || g.Store == nil { return nil, store.ErrKeyNotFound } return s.getGroupAt(ctx, g, route, key, ts, route.GroupID, readRouteVersion) } func (s *ShardStore) getGroupAt(ctx context.Context, g *ShardGroup, route distribution.Route, key []byte, ts uint64, groupID uint64, readRouteVersion uint64) ([]byte, error) { + record, err := s.readPointInGroup(ctx, g, route, key, ts, groupID, readRouteVersion, false) + return record.Value, err +} + +func unavailablePointRead(needCommitTS bool) error { + if needCommitTS { + return store.ErrNotSupported + } + return store.ErrKeyNotFound +} + +func (s *ShardStore) readPointInGroup(ctx context.Context, g *ShardGroup, route distribution.Route, key []byte, ts uint64, groupID uint64, readRouteVersion uint64, needCommitTS bool) (store.VersionedValue, error) { if err := s.ensureReadWatermark(ctx, g, ts); err != nil { - return nil, err + return store.VersionedValue{}, err } if engineForGroup(g) == nil { - return s.localGetAt(ctx, g, route, key, ts) + return s.localReadPoint(ctx, g, route, key, ts, needCommitTS) } if isLinearizableRaftLeader(ctx, engineForGroup(g)) { - return s.leaderGetAt(ctx, g, route, key, ts) + return s.leaderReadPoint(ctx, g, route, key, ts, needCommitTS) } if err := s.verifyTargetReadinessForRange(ctx, g, route, key, nextScanCursor(key)); err != nil { - return nil, err + return store.VersionedValue{}, err } - return s.proxyRawGet(ctx, g, key, ts, groupID, readRouteVersion) + return s.proxyRawGet(ctx, g, &pb.RawGetRequest{Key: key, Ts: ts, GroupId: groupID, ReadRouteVersion: readRouteVersion, NeedCommitTs: needCommitTS}) } // routeHasLatestVersionVisibleAt reports whether this route can answer the read @@ -569,34 +622,44 @@ func isLinearizableRaftLeader(ctx context.Context, engine raftengine.LeaderView) return err == nil } -func (s *ShardStore) leaderGetAt(ctx context.Context, g *ShardGroup, route distribution.Route, key []byte, ts uint64) ([]byte, error) { +func (s *ShardStore) leaderReadPoint(ctx context.Context, g *ShardGroup, route distribution.Route, key []byte, ts uint64, needCommitTS bool) (store.VersionedValue, error) { var err error route, err = s.targetReadyRouteForRange(ctx, g, route, key, nextScanCursor(key)) if err != nil { - return nil, err + return store.VersionedValue{}, err } if !isTxnInternalKey(key) { if err := s.maybeResolveTxnLock(ctx, g, key, ts); err != nil { - return nil, err + return store.VersionedValue{}, err } } - return s.localGetAt(ctx, g, route, key, ts) + return s.localReadPoint(ctx, g, route, key, ts, needCommitTS) } func (s *ShardStore) localGetAt(ctx context.Context, g *ShardGroup, route distribution.Route, key []byte, ts uint64) ([]byte, error) { + result, err := s.localReadPoint(ctx, g, route, key, ts, false) + return result.Value, err +} + +func (s *ShardStore) localReadPoint(ctx context.Context, g *ShardGroup, route distribution.Route, key []byte, ts uint64, needCommitTS bool) (store.VersionedValue, error) { var err error route, err = s.targetReadyRouteForRange(ctx, g, route, key, nextScanCursor(key)) if err != nil { - return nil, err + return store.VersionedValue{}, err } if routeHasStagedVisibility(route) { - return s.getAtWithStagedVisibility(ctx, g, route, key, ts) + // This path merges a staged and live key using separate store reads. + if needCommitTS { + return store.VersionedValue{}, store.ErrNotSupported + } + value, err := s.getAtWithStagedVisibility(ctx, g, route, key, ts) + return store.VersionedValue{Value: value}, err } - val, err := g.Store.GetAt(ctx, key, ts) - if err != nil { - return nil, errors.WithStack(err) + if needCommitTS { + return readVersionOnInitialRoute(ctx, g, route, key, ts) } - return val, nil + value, err := g.Store.GetAt(ctx, key, ts) + return store.VersionedValue{Value: value}, errors.WithStack(err) } func routeHasStagedVisibility(route distribution.Route) bool { @@ -6510,8 +6573,12 @@ func (s *ShardStore) GroupCommittedTimestampFloor(ctx context.Context, groupID u defer cancel() readIndex, err := linearizableReadEngineCtx(readCtx, engine) if err != nil { - return 0, errors.Wrapf(ErrTSOCommitFloorUnavailable, + floorErr := errors.Wrapf(ErrTSOCommitFloorUnavailable, "fence data group %d leader: %v", groupID, err) + if errors.Is(err, raftengine.ErrLeadershipTransferInProgress) && isolatedMutationFailure(err) { + return 0, &dataGroupFloorTransfer{floorErr} + } + return 0, floorErr } ts := group.Store.LastCommitTS() traceRawReadFloor(ctx, groupID, readIndex, ts) @@ -6813,34 +6880,24 @@ func (s *ShardStore) s3BucketAuxiliaryOwnerRouteForKey(key []byte) (distribution return s3BucketAuxiliaryOwnerRouteFromRange(start, end, s.engine.GetIntersectingRoutes(start, end)) } -func (s *ShardStore) proxyRawGet(ctx context.Context, g *ShardGroup, key []byte, ts uint64, groupID uint64, readRouteVersion uint64) ([]byte, error) { +func (s *ShardStore) proxyRawGet(ctx context.Context, g *ShardGroup, req *pb.RawGetRequest) (store.VersionedValue, error) { engine := engineForGroup(g) if engine == nil { - return nil, store.ErrKeyNotFound + return store.VersionedValue{}, unavailablePointRead(req.NeedCommitTs) } addr := leaderAddrFromEngine(engine) if addr == "" { - return nil, errors.WithStack(ErrLeaderNotFound) + return store.VersionedValue{}, errors.WithStack(ErrLeaderNotFound) } conn, err := s.connCache.ConnFor(addr) if err != nil { - return nil, err + return store.VersionedValue{}, err } ctx, cancel := context.WithTimeout(ctx, proxyForwardTimeout) defer cancel() - cli := pb.NewRawKVClient(conn) - resp, err := cli.RawGet(ctx, &pb.RawGetRequest{Key: key, Ts: ts, GroupId: groupID, ReadRouteVersion: readRouteVersion}) - if err != nil { - return nil, errors.WithStack(err) - } - // Compatibility with older nodes that don't set RawGetResponse.exists: - // treat any non-nil payload as found even when exists=false. - if !resp.GetExists() && resp.GetValue() == nil { - return nil, store.ErrKeyNotFound - } - return resp.Value, nil + return readRawPoint(ctx, conn, req) } func (s *ShardStore) proxyRawScanAt( diff --git a/kv/shard_store_test.go b/kv/shard_store_test.go index 3c09a66e6..84ec7cdb4 100644 --- a/kv/shard_store_test.go +++ b/kv/shard_store_test.go @@ -2075,6 +2075,13 @@ func TestShardStoreReadFenceFailsClosedWhileCatalogVersionIsBehind(t *testing.T) return err }, }, + { + name: "versioned point read", + read: func(ctx context.Context) error { + _, err := st.GetVersionAtWithReadFence(ctx, []byte("k"), 1, 0, 2) + return err + }, + }, { name: "latest commit timestamp", read: func(ctx context.Context) error { @@ -5178,6 +5185,11 @@ func TestShardStoreSourceReadFenceRejectsPointRead(t *testing.T) { _, err := st.GetAt(ctx, []byte("n"), 60) require.ErrorIs(t, err, ErrRouteCutoverPending) + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + _, err = st.GetVersionAt(ctx, []byte("n"), 60) + require.ErrorIs(t, err, ErrRouteCutoverPending) + _, err = st.GetVersionAtWithReadFence(ctx, []byte("n"), 60, 1, 0) + require.ErrorIs(t, err, ErrRouteCutoverPending) _, _, err = st.LatestCommitTSGroupWithReadFence(ctx, []byte("n"), 1, 0) require.ErrorIs(t, err, ErrRouteCutoverPending) diff --git a/kv/shard_store_txn_lock_test.go b/kv/shard_store_txn_lock_test.go index 245411dfe..d93cfa636 100644 --- a/kv/shard_store_txn_lock_test.go +++ b/kv/shard_store_txn_lock_test.go @@ -112,6 +112,9 @@ func TestShardStoreGetAt_ReturnsTxnLockedForPendingLock(t *testing.T) { _, err = shardStore.GetAt(ctx, key, ^uint64(0)) require.Error(t, err) require.True(t, errors.Is(err, ErrTxnLocked), "expected ErrTxnLocked, got %v", err) + groups[1].ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + _, err = shardStore.GetVersionAt(ctx, key, ^uint64(0)) + require.ErrorIs(t, err, ErrTxnLocked) } func TestShardStoreLeaderGetAtChecksReadinessBeforeResolvingPendingLock(t *testing.T) { @@ -137,7 +140,7 @@ func TestShardStoreLeaderGetAtChecksReadinessBeforeResolvingPendingLock(t *testi resolvedRoute, _, ok := shardStore.routeAndGroupForKey(key) require.True(t, ok) - _, err := shardStore.leaderGetAt(ctx, group, resolvedRoute, key, ^uint64(0)) + _, err := shardStore.leaderReadPoint(ctx, group, resolvedRoute, key, ^uint64(0), false) require.ErrorIs(t, err, ErrRouteCutoverPending) _, lockErr := group.Store.GetAt(ctx, txnLockKey(key), ^uint64(0)) diff --git a/kv/sharded_coordinator.go b/kv/sharded_coordinator.go index 0e6afa277..4854b362f 100644 --- a/kv/sharded_coordinator.go +++ b/kv/sharded_coordinator.go @@ -23,9 +23,10 @@ import ( ) type ShardGroup struct { - Engine raftengine.Engine - Store store.MVCCStore - Txn Transactional + Engine raftengine.Engine + Store store.MVCCStore + Txn Transactional + versionReadAdmission func(context.Context) error // Installed only with the opt-in two-group coordinator. Never public Forward. twoGroupTerminalResolver func(context.Context, *pb.TwoGroupPrepareManifest, pb.Phase) error // TSOState is set only for reserved group 0. Keeping the applied floor and @@ -385,6 +386,13 @@ func (t *leaseRefreshingTxn) stampLeaderIssuedTxnForVerifiedLocalCommit(ctx cont if meta.CommitTS != 0 { return 0, nil } + if err := t.stampCASStartTimestamp(ctx, r); err != nil { + return 0, err + } + return t.stampLeaderIssuedCommitTimestamp(ctx, r, metaMutation, meta) +} + +func (t *leaseRefreshingTxn) stampLeaderIssuedCommitTimestamp(ctx context.Context, r *pb.Request, metaMutation *pb.Mutation, meta TxnMeta) (uint64, error) { commitTS, err := t.coord.resolveTxnCommitTS(ctx, r.Ts, 0) if err != nil { return 0, err @@ -400,6 +408,18 @@ func (t *leaseRefreshingTxn) stampLeaderIssuedTxnForVerifiedLocalCommit(ctx cont return commitTS, nil } +func (t *leaseRefreshingTxn) stampCASStartTimestamp(ctx context.Context, req *pb.Request) error { + if req.Ts != 0 || !HasCASMutation([]*pb.Request{req}) { + return nil + } + ts, err := t.coord.allocateTimestamp(ctx, "allocate CAS startTS") + if err != nil { + return err + } + req.Ts = ts + return nil +} + func leaderIssuedOnePhaseRequest(reqs []*pb.Request) (*pb.Request, *pb.Mutation) { if len(reqs) != 1 || reqs[0] == nil || !reqs[0].IsTxn || reqs[0].Phase != pb.Phase_NONE || len(reqs[0].Mutations) == 0 { @@ -1104,6 +1124,13 @@ func (c *ShardedCoordinator) dispatchAdmitted(ctx context.Context, reqs *Operati return nil, err } + if reqs.Elems[0].Op == CompareAndSwap { + return c.dispatchCAS(ctx, reqs) + } + return c.dispatchOrdinaryOperation(ctx, reqs) +} + +func (c *ShardedCoordinator) dispatchOrdinaryOperation(ctx context.Context, reqs *OperationGroup[OP]) (*CoordinateResponse, error) { // Capture whether the caller supplied a non-zero StartTS BEFORE // the coordinator-allocates-on-zero branch below mutates the // field. A caller-supplied StartTS names a specific snapshot @@ -2135,8 +2162,7 @@ func (c *ShardedCoordinator) dispatchSingleShardTxn(ctx context.Context, startTS if err != nil { return nil, err } - readKeys = c.readKeysWithStagedVisibilityAliasesForGroup(gid, readKeys) - readKeys = c.readKeysWithStagedVisibilityMutationAliasesForGroup(gid, readKeys, muts) + readKeys = c.onePhaseReadKeys(gid, readKeys, muts) if len(readKeys) > maxReadKeys { return nil, errors.WithStack(ErrInvalidRequest) } @@ -2146,6 +2172,9 @@ func (c *ShardedCoordinator) dispatchSingleShardTxn(ctx context.Context, startTS // attempt's write set. request := newOnePhaseTxnRequest(startTS, commitTS, prevCommitTS, primaryKey, len(muts), readKeys, observedRouteVersion, writeFenceBypassKeys) request.Mutations = append(request.Mutations, muts...) + if singleCASMutation(muts) { + request.VersionCasGroupId = gid + } resp, err := g.Txn.Commit(ctx, []*pb.Request{request}) if err != nil { return nil, errors.WithStack(err) @@ -2166,6 +2195,20 @@ func (c *ShardedCoordinator) dispatchSingleShardTxn(ctx context.Context, startTS return &CoordinateResponse{CommitIndex: resp.CommitIndex, CommitTS: commitTS}, nil } +func singleCASMutation(muts []*pb.Mutation) bool { + return len(muts) == 1 && muts[0].GetOp() == pb.Op_COMPARE_AND_SWAP +} + +func (c *ShardedCoordinator) onePhaseReadKeys(gid uint64, readKeys [][]byte, muts []*pb.Mutation) [][]byte { + // A standalone CAS uses an exact-version predicate and is admitted only on + // initial routes. Keep its wire shape free of auxiliary OCC read keys. + if singleCASMutation(muts) { + return readKeys + } + readKeys = c.readKeysWithStagedVisibilityAliasesForGroup(gid, readKeys) + return c.readKeysWithStagedVisibilityMutationAliasesForGroup(gid, readKeys, muts) +} + func (c *ShardedCoordinator) readKeysWithStagedVisibilityAliasesForGroup(gid uint64, readKeys [][]byte) [][]byte { if len(readKeys) == 0 { return readKeys @@ -3486,25 +3529,35 @@ func validateOperationGroup(reqs *OperationGroup[OP]) error { if e == nil { return ErrInvalidRequest } - } - if len(reqs.PrimaryKey) != 0 { - if !reqs.IsTxn { - return ErrInvalidRequest - } - found := false - for _, e := range reqs.Elems { - if bytes.Equal(e.Key, reqs.PrimaryKey) { - found = true - break + if e.Op == CompareAndSwap { + if !validCASOperation(reqs, e) { + return ErrInvalidRequest } - } - if !found { + } else if e.ExpectedCommitTS != 0 { return ErrInvalidRequest } } + if !validOperationPrimaryKey(reqs) { + return ErrInvalidRequest + } return nil } +func validOperationPrimaryKey(reqs *OperationGroup[OP]) bool { + if len(reqs.PrimaryKey) == 0 { + return true + } + if !reqs.IsTxn { + return false + } + for _, e := range reqs.Elems { + if bytes.Equal(e.Key, reqs.PrimaryKey) { + return true + } + } + return false +} + func (c *ShardedCoordinator) requestLogs(ctx context.Context, reqs *OperationGroup[OP]) ([]*pb.Request, error) { if reqs.IsTxn { return c.txnLogs(ctx, reqs) @@ -3753,7 +3806,7 @@ func (c *ShardedCoordinator) ensureMutationWriteAllowed(mut *pb.Mutation, commit } } return nil - case pb.Op_PUT, pb.Op_DEL: + case pb.Op_PUT, pb.Op_DEL, pb.Op_COMPARE_AND_SWAP: return c.rejectWriteTimestampFloorPointKey(mut.Key, commitTS) default: return errors.WithStack(ErrInvalidRequest) diff --git a/kv/transaction.go b/kv/transaction.go index b4c289e03..a12a2e496 100644 --- a/kv/transaction.go +++ b/kv/transaction.go @@ -16,6 +16,9 @@ import ( type TransactionManager struct { proposer raftengine.Proposer + versionCASAdmission VersionCASAdmission + versionCASPrecheck func(context.Context, *pb.Request) bool + versionCASProposals *casProposalGate proposalObserver ProposalObserver timestampAdmission atomic.Pointer[transactionTimestampAdmission] migrationAdmission atomic.Pointer[transactionMigrationAdmission] @@ -126,16 +129,51 @@ type TransactionResponse struct { CommitTS uint64 } -func marshalRaftCommand(reqs []*pb.Request) ([]byte, error) { - if len(reqs) == 1 { - b, err := proto.Marshal(reqs[0]) - if err != nil { - return nil, errors.WithStack(err) +// proposalConditions classifies caller-supplied mutations in one pass. In +// particular, require_absent must stay out of the log while a replica could +// still decode it as an unknown field and apply an unconditional PUT. +type proposalConditions struct { + cas bool + absent bool +} + +func classifyProposalConditions(reqs []*pb.Request) proposalConditions { + var conditions proposalConditions + for _, req := range reqs { + for _, mutation := range req.GetMutations() { + conditions.cas = conditions.cas || usesCAS(mutation) + conditions.absent = conditions.absent || mutation.GetRequireAbsent() } - if len(b) >= maxMarshaledCommandSize { - return nil, errors.New("marshaled request too large") + } + return conditions +} + +func (c proposalConditions) validate(reqs []*pb.Request) error { + if c.cas { + // The standalone CAS shape also forbids require_absent. + return validateCASProposalShape(reqs) + } + if c.absent { + for _, req := range reqs { + if err := validateAbsenceMutationKinds(req.GetMutations()); err != nil { + return err + } } - return prependByte(raftEncodeSingle, b), nil + } + return nil +} + +func marshalRaftCommand(reqs []*pb.Request) ([]byte, error) { + conditions := classifyProposalConditions(reqs) + if err := conditions.validate(reqs); err != nil { + return nil, err + } + return marshalClassifiedRaftCommand(reqs, conditions.cas) +} + +func marshalClassifiedRaftCommand(reqs []*pb.Request, cas bool) ([]byte, error) { + if len(reqs) == 1 { + return marshalSingleRaftRequest(reqs[0], cas) } b, err := proto.Marshal(&pb.RaftCommand{Requests: reqs}) if err != nil { @@ -147,6 +185,23 @@ func marshalRaftCommand(reqs []*pb.Request) ([]byte, error) { return prependByte(raftEncodeBatch, b), nil } +func marshalSingleRaftRequest(req *pb.Request, cas bool) ([]byte, error) { + b, err := proto.Marshal(req) + if err != nil { + return nil, errors.WithStack(err) + } + if len(b) >= maxMarshaledCommandSize { + return nil, errors.New("marshaled request too large") + } + if !cas { + return prependByte(raftEncodeSingle, b), nil + } + if len(b) > maxMarshaledCommandSize-len(versionCASFrame) { + return nil, errors.New("marshaled version CAS request too large") + } + return append([]byte(versionCASFrame), b...), nil +} + // prependByte returns a new slice with prefix followed by data. func prependByte(prefix byte, data []byte) []byte { if len(data) >= math.MaxInt { @@ -162,25 +217,43 @@ func prependByte(prefix byte, data []byte) []byte { // HashiCorp Raft delivers FSM responses via ApplyFuture.Response(), not Error(), // so we must inspect the response to avoid silently treating failed writes as // successes. -func applyRequests(ctx context.Context, proposer raftengine.Proposer, reqs []*pb.Request, proposalObserver ProposalObserver, admission ...*transactionMigrationAdmission) (uint64, []error, error) { - if len(admission) > 0 && admission[0] != nil { - return admission[0].apply(ctx, proposer, reqs, proposalObserver) +func applyRequests(ctx context.Context, proposer raftengine.Proposer, reqs []*pb.Request, observer ProposalObserver, admission ...*transactionMigrationAdmission) (uint64, []error, error) { + conditions := classifyProposalConditions(reqs) + if err := conditions.validate(reqs); err != nil { + return 0, nil, err + } + var migration *transactionMigrationAdmission + if len(admission) > 0 { + migration = admission[0] } - b, err := marshalRaftCommand(reqs) + return applyClassifiedRequests(ctx, proposer, reqs, observer, migration, conditions.cas) +} + +// applyClassifiedRequests is called after all mutations have been checked. +// A CAS command is always standalone, including through migration admission. +func applyClassifiedRequests(ctx context.Context, proposer raftengine.Proposer, reqs []*pb.Request, observer ProposalObserver, migration *transactionMigrationAdmission, cas bool) (uint64, []error, error) { + if migration != nil { + return migration.apply(ctx, proposer, reqs, observer, cas) + } + b, err := marshalClassifiedRaftCommand(reqs, cas) if err != nil { return 0, nil, errors.WithStack(err) } if proposer == nil { - recordProposalFailure(proposalObserver) + recordProposalFailure(observer) return 0, nil, errors.WithStack(ErrLeaderNotFound) } + if raftengine.IsVersionCASRaftPayload(b) { + if _, ok := raftengine.VersionCASProposalProof(ctx); !ok { + return 0, nil, errors.WithStack(ErrVersionCASUnavailable) + } + } result, err := submitUserProposal(ctx, proposer, reqs, b) if err != nil { - recordProposalFailure(proposalObserver) - if errors.Is(err, raftengine.ErrNotLeader) || errors.Is(err, raftengine.ErrLeadershipTransferInProgress) || - errors.Is(err, raftengine.ErrStaleAdmissionTerm) { + recordProposalFailure(observer) + if rejectedBeforeProposal(err) { // The etcd engine returns these before appending the entry. return 0, nil, errors.WithStack(err) } @@ -189,11 +262,16 @@ func applyRequests(ctx context.Context, proposer raftengine.Proposer, reqs []*pb return 0, nil, &unknownTransactionFailure{cause: err} } if result == nil { - recordProposalFailure(proposalObserver) + recordProposalFailure(observer) return 0, nil, &unknownTransactionFailure{cause: errors.New("raft proposal returned nil result")} } - return interpretProposalResult(result, reqs, proposalObserver) + return interpretProposalResult(result, reqs, observer) +} + +func rejectedBeforeProposal(err error) bool { + return errors.Is(err, raftengine.ErrNotLeader) || errors.Is(err, raftengine.ErrLeadershipTransferInProgress) || + errors.Is(err, raftengine.ErrStaleAdmissionTerm) || errors.Is(err, ErrVersionCASUnavailable) } func submitUserProposal(ctx context.Context, proposer raftengine.Proposer, reqs []*pb.Request, data []byte) (*raftengine.ProposalResult, error) { @@ -265,13 +343,27 @@ func recordProposalFailure(observer ProposalObserver) { } func (t *TransactionManager) Commit(ctx context.Context, reqs []*pb.Request) (*TransactionResponse, error) { - return t.commitWithTimestampAdmission(ctx, reqs, t.timestampAdmission.Load()) + return t.commitClassified(ctx, reqs, classifyProposalConditions(reqs)) +} + +func (t *TransactionManager) commitClassified(ctx context.Context, reqs []*pb.Request, conditions proposalConditions) (*TransactionResponse, error) { + return t.commitClassifiedWithTimestampAdmission(ctx, reqs, conditions, t.timestampAdmission.Load()) } func (t *TransactionManager) commitWithTimestampAdmission(ctx context.Context, reqs []*pb.Request, admission *transactionTimestampAdmission) (*TransactionResponse, error) { + return t.commitClassifiedWithTimestampAdmission(ctx, reqs, classifyProposalConditions(reqs), admission) +} + +func (t *TransactionManager) commitClassifiedWithTimestampAdmission(ctx context.Context, reqs []*pb.Request, conditions proposalConditions, admission *transactionTimestampAdmission) (*TransactionResponse, error) { if len(reqs) == 0 { return &TransactionResponse{}, nil } + if conditions.cas && t.versionCASAdmission == nil { + return nil, errors.WithStack(ErrVersionCASUnavailable) + } + if err := conditions.validate(reqs); err != nil { + return nil, err + } if err := refuseAbsenceProposal(reqs, t.ttlInlineCapability); err != nil { return nil, err } @@ -280,12 +372,34 @@ func (t *TransactionManager) commitWithTimestampAdmission(ctx context.Context, r return nil, err } reqs = owned + if conditions.cas { + return t.commitVersionCAS(ctx, reqs[0]) + } if hasTxnRequests(reqs) { - return t.commitSequential(ctx, reqs) + return t.commitSequential(ctx, reqs, false) } return t.commitRaw(ctx, reqs) } +func (t *TransactionManager) commitVersionCAS(ctx context.Context, request *pb.Request) (*TransactionResponse, error) { + req, err := t.admitVersionCASRequest(ctx, request) + if err != nil { + return nil, err + } + ctx, releaseCAS, err := t.beginAdaptiveCAS(ctx, req) + if err != nil { + return nil, err + } + if releaseCAS != nil { + defer releaseCAS() + } + ctx, err = t.versionCASAdmission(ctx) + if err != nil { + return nil, errors.WithStack(err) + } + return t.commitSequential(ctx, []*pb.Request{req}, true) +} + func (t *TransactionManager) applyRequests(ctx context.Context, reqs []*pb.Request) (uint64, []error, error) { if err := refuseAbsenceProposal(reqs, t.ttlInlineCapability); err != nil { return 0, nil, err @@ -302,8 +416,8 @@ func hasTxnRequests(reqs []*pb.Request) bool { return false } -func (t *TransactionManager) commitSequential(ctx context.Context, reqs []*pb.Request) (*TransactionResponse, error) { - commitIndex, err := t.applySequentialRequests(ctx, reqs) +func (t *TransactionManager) commitSequential(ctx context.Context, reqs []*pb.Request, cas bool) (*TransactionResponse, error) { + commitIndex, err := t.applySequentialRequests(ctx, reqs, cas) if err != nil { // Only the coordinator can decide whether earlier participants or an @@ -316,10 +430,10 @@ func (t *TransactionManager) commitSequential(ctx context.Context, reqs []*pb.Re }, nil } -func (t *TransactionManager) applySequentialRequests(ctx context.Context, reqs []*pb.Request) (uint64, error) { +func (t *TransactionManager) applySequentialRequests(ctx context.Context, reqs []*pb.Request, cas bool) (uint64, error) { commitIndex := uint64(0) for _, req := range reqs { - idx, results, err := t.applyRequests(ctx, []*pb.Request{req}) + idx, results, err := applyClassifiedRequests(ctx, t.proposer, []*pb.Request{req}, t.proposalObserver, t.migrationAdmission.Load(), cas) if err != nil { return 0, err } @@ -529,6 +643,9 @@ func combineApplyErrors(errs []error) error { } func (t *TransactionManager) Abort(ctx context.Context, reqs []*pb.Request) (*TransactionResponse, error) { + if HasCASMutation(reqs) { + return nil, errors.WithStack(ErrInvalidRequest) + } var abortReqs []*pb.Request for _, req := range reqs { if abortReq := abortRequestFor(req); abortReq != nil { diff --git a/kv/transaction_migration_admission.go b/kv/transaction_migration_admission.go index 3a77a1fe8..15443f46a 100644 --- a/kv/transaction_migration_admission.go +++ b/kv/transaction_migration_admission.go @@ -6,6 +6,7 @@ import ( "github.com/bootjp/elastickv/internal/raftengine" pb "github.com/bootjp/elastickv/proto" "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" ) type transactionMigrationAdmission struct { @@ -59,12 +60,16 @@ func configureMigrationRequestAdmission(tx Transactional, st store.MVCCStore, gr } } -func (a *transactionMigrationAdmission) apply(ctx context.Context, proposer raftengine.Proposer, reqs []*pb.Request, observer ProposalObserver) (uint64, []error, error) { +func (a *transactionMigrationAdmission) apply(ctx context.Context, proposer raftengine.Proposer, reqs []*pb.Request, observer ProposalObserver, cas bool) (uint64, []error, error) { results := make([]error, len(reqs)) accepted := make([]*pb.Request, 0, len(reqs)) positions := make([]int, 0, len(reqs)) for i, req := range reqs { - results[i] = markDataRequestNotSubmitted([]*pb.Request{req}, CheckMigrationRequest(ctx, a.store, a.groupID, req)) + results[i] = checkMigrationRequest(ctx, a.store, a.groupID, req, cas) + if errors.Is(results[i], ErrVersionCASUnavailable) { + return 0, nil, results[i] + } + results[i] = markDataRequestNotSubmitted([]*pb.Request{req}, results[i]) if results[i] == nil { accepted, positions = append(accepted, req), append(positions, i) } @@ -72,7 +77,7 @@ func (a *transactionMigrationAdmission) apply(ctx context.Context, proposer raft if len(accepted) == 0 { return 0, results, nil } - index, applied, err := applyRequests(ctx, proposer, accepted, observer) + index, applied, err := applyClassifiedRequests(ctx, proposer, accepted, observer, nil, cas) if err != nil { return 0, nil, err } diff --git a/kv/transcoder.go b/kv/transcoder.go index f32b5ce1f..8843e8b3b 100644 --- a/kv/transcoder.go +++ b/kv/transcoder.go @@ -12,6 +12,7 @@ const ( // DelPrefix deletes all visible keys matching the prefix stored in Key. // An empty Key means "all keys". Transaction-internal keys are excluded. DelPrefix + CompareAndSwap ) // ObservedRouteVersionZero encodes a transaction pinned to catalog version 0. @@ -57,6 +58,8 @@ type Elem[T OP] struct { // RequireAbsent is an apply-time precondition for a capability-gated, // single-owner TTL-inline relocation. Tombstones also count as present. RequireAbsent bool + // ExpectedCommitTS is the exact live version required by CompareAndSwap. + ExpectedCommitTS uint64 // CommitTSValueOffset, when non-zero, asks the coordinator or forwarded // leader to stamp the resolved transaction commit timestamp into Value at // this byte offset before committing the mutation. diff --git a/kv/tso_raft.go b/kv/tso_raft.go index 83e4ca709..ca42cea7e 100644 --- a/kv/tso_raft.go +++ b/kv/tso_raft.go @@ -345,6 +345,12 @@ func (a *RaftTSOAllocator) termCommitFloor(ctx context.Context, term uint64, for } floor, err := a.floorProvider.GlobalCommittedTimestampFloor(ctx) if err != nil { + // A transferring data group cannot supply a floor for this term. + // Only the TSO group's own leadership can redirect a reservation. + var transfer *dataGroupFloorTransfer + if errors.As(err, &transfer) && isolatedMutationFailure(err) { + err = transfer.floorOnly + } return 0, errors.Wrap(err, "tso initialize leader term commit floor") } return max(floor, a.state.AllocationFloor()), nil diff --git a/kv/txn_codec.go b/kv/txn_codec.go index 37d8b9e3a..80760f462 100644 --- a/kv/txn_codec.go +++ b/kv/txn_codec.go @@ -37,6 +37,7 @@ const ( ) const txnMetaHeaderSize = 2 +const txnMetaV1HeaderSize = 1 + 3*uint64FieldSize // version, TTL, commit TS, primary length // uint64FieldSize is the byte size of a serialized uint64 field. const uint64FieldSize = 8 @@ -82,13 +83,13 @@ func EncodeTxnMeta(m TxnMeta) []byte { func encodeTxnMetaV1(m TxnMeta) []byte { // version(1) + LockTTLms(8) + CommitTS(8) + primaryLen(8) + primaryKey - size := 1 + uint64FieldSize + uint64FieldSize + uint64FieldSize + len(m.PrimaryKey) + size := txnMetaV1HeaderSize + len(m.PrimaryKey) b := make([]byte, size) b[0] = txnMetaVersionV1 binary.BigEndian.PutUint64(b[1:], m.LockTTLms) binary.BigEndian.PutUint64(b[9:], m.CommitTS) binary.BigEndian.PutUint64(b[17:], uint64(len(m.PrimaryKey))) - copy(b[25:], m.PrimaryKey) + copy(b[txnMetaV1HeaderSize:], m.PrimaryKey) return b } @@ -455,9 +456,14 @@ func readTxnSizedBytes(r *bytes.Reader, n uint64) ([]byte, error) { return nil, nil } - // n has already been validated by readTxnField to be <= math.MaxInt, - // so this conversion is safe. - out := make([]byte, int(n)) //nolint:gosec // n validated as <= math.MaxInt by caller + if n > math.MaxInt { + return nil, errors.WithStack(io.ErrUnexpectedEOF) + } + size := int(n) + if size > r.Len() { + return nil, errors.WithStack(io.ErrUnexpectedEOF) + } + out := make([]byte, size) if _, err := io.ReadFull(r, out); err != nil { return nil, errors.WithStack(err) } diff --git a/kv/txn_codec_bounds_test.go b/kv/txn_codec_bounds_test.go new file mode 100644 index 000000000..c5bcbf9bb --- /dev/null +++ b/kv/txn_codec_bounds_test.go @@ -0,0 +1,79 @@ +package kv + +import ( + "bytes" + "encoding/binary" + "io" + "math" + "runtime" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDecodeTxnMetaTruncatedPrimaryAllocation(t *testing.T) { + // TotalAlloc is process-wide. Keep these single-decode measurements serial. + const declaredSize = 8 << 20 + const allocationLimit = 64 << 10 + for _, tc := range []struct { + name string + header []byte + }{ + {"V1", encodeTxnMetaV1(TxnMeta{})}, + {"V2", encodeTxnMetaV2(TxnMeta{})}, + } { + t.Run(tc.name, func(t *testing.T) { + // With no optional fields or primary key, the length ends the header. + binary.BigEndian.PutUint64(tc.header[len(tc.header)-uint64FieldSize:], declaredSize) + wire := bytes.Clone(tc.header) + wire = append(wire, 'k') + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, err := DecodeTxnMeta(wire) + runtime.ReadMemStats(&after) + + require.EqualError(t, err, "txn meta: primary key truncated") + allocated := after.TotalAlloc - before.TotalAlloc + t.Logf("%d-byte input, %d bytes allocated", len(wire), allocated) + require.Less(t, allocated, uint64(allocationLimit)) + }) + } +} + +func TestReadTxnSizedBytesBoundaries(t *testing.T) { + for _, tc := range []struct { + name string + n uint64 + want []byte + left int + err error + }{ + {"zero", 0, nil, 2, nil}, + {"prefix", 1, []byte("b"), 1, nil}, + {"exact", 2, []byte("bc"), 0, nil}, + {"past remaining", 3, nil, 2, io.ErrUnexpectedEOF}, + } { + t.Run(tc.name, func(t *testing.T) { + r := bytes.NewReader([]byte("abc")) + _, err := r.ReadByte() + require.NoError(t, err) + got, err := readTxnSizedBytes(r, tc.n) + require.ErrorIs(t, err, tc.err) + require.Equal(t, tc.want, got) + require.Equal(t, tc.left, r.Len()) + }) + } +} + +func TestReadTxnFieldBoundsErrors(t *testing.T) { + const truncated = "txn intent: value truncated" + for _, input := range [][]byte{nil, {'v'}} { + got, err := readTxnField(bytes.NewReader(input), 2, truncated) + require.Nil(t, got) + require.EqualError(t, err, truncated) + } + got, err := readTxnField(bytes.NewReader(nil), math.MaxUint64, truncated) + require.Nil(t, got) + require.EqualError(t, err, truncated+": field size 18446744073709551615 overflows int") +} diff --git a/kv/version_cas_activation_test.go b/kv/version_cas_activation_test.go new file mode 100644 index 000000000..021b234f5 --- /dev/null +++ b/kv/version_cas_activation_test.go @@ -0,0 +1,229 @@ +package kv + +import ( + "bytes" + "context" + "testing" + + "github.com/bootjp/elastickv/distribution" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func TestVersionCASMoveToUnactivatedGroupAndBack(t *testing.T) { + t.Parallel() + ctx := t.Context() + dir := t.TempDir() + source, err := store.NewPebbleStore(dir) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, source.Close()) }) + target := store.NewMVCCStore() + sourceFSM, targetFSM := &kvFSM{store: source, shardGroupID: 1}, &kvFSM{store: target} + enableCASApplyForTest(t, sourceFSM) + key := []byte("n") + require.NoError(t, source.PutAt(ctx, key, []byte("source"), 10, 0)) + routes := distribution.NewEngine() + setOwner := func(version, groupID, floor uint64) { + t.Helper() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{ + Version: version, Routes: []distribution.RouteDescriptor{{ + RouteID: version, GroupID: groupID, State: distribution.RouteStateActive, MinWriteTSExclusive: floor, + }}, + })) + } + setOwner(1, 1, 0) + groups := map[uint64]*ShardGroup{1: {Store: source}, 2: {Store: target}} + for _, group := range groups { + group.ConfigureVersionReadAdmission(func(ctx context.Context) error { + active, err := MigrationVersionIdentityEnabled(ctx, group.Store) + if err == nil && !active { + return ErrVersionCASUnavailable + } + return err + }) + } + shards := NewShardStore(routes, groups) + t.Cleanup(func() { require.NoError(t, shards.Close()) }) + coordinator := NewShardedCoordinator(routes, groups, 1, NewHLC(), shards) + t.Cleanup(func() { require.NoError(t, coordinator.Close()) }) + + token, err := shards.GetVersionAt(ctx, key, 20) + require.NoError(t, err) + require.Equal(t, uint64(10), token.TS) + require.Equal(t, []byte("source"), token.Value) + owner, err := shards.ResolveVersionCASGroupForKey(key) + require.NoError(t, err) + require.Equal(t, uint64(1), owner) + staleCAS := &OperationGroup[OP]{IsTxn: true, Elems: []*Elem[OP]{ + {Op: CompareAndSwap, Key: key, ExpectedCommitTS: token.TS, Value: []byte("wrong")}, + }} + + // The target can apply a legacy exact-timestamp overwrite before being + // enabled. The promoted version has the same numeric identity. + version := &pb.MVCCVersion{Key: key, CommitTs: token.TS, Value: []byte("copy")} + importReq := &pb.ImportRangeVersionsRequest{JobId: 1, BracketId: 1, BatchSeq: 1, Versions: []*pb.MVCCVersion{version}} + require.IsType(t, store.ImportVersionsResult{}, applyMigrationVersionIdentityImport(t, targetFSM, importReq, 1)) + importReq.BatchSeq++ + version.Value = []byte("legacy overwrite") + require.IsType(t, store.ImportVersionsResult{}, applyMigrationVersionIdentityImport(t, targetFSM, importReq, 2)) + promote, err := MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 1}) + require.NoError(t, err) + targetFSM.SetApplyIndex(3) + require.IsType(t, store.PromoteVersionsResult{}, targetFSM.Apply(promote)) + active, err := MigrationVersionIdentityEnabled(ctx, target) + require.NoError(t, err) + require.False(t, active) + + setOwner(2, 2, 20) + value, err := shards.GetAt(ctx, key, 50) + require.NoError(t, err) + require.Equal(t, version.Value, value) + _, err = shards.GetVersionAt(ctx, key, 50) + require.ErrorIs(t, err, store.ErrNotSupported) + _, err = coordinator.Dispatch(ctx, staleCAS) + require.ErrorIs(t, err, ErrVersionCASUnavailable) + _, err = shards.ResolveVersionCASGroupForKey(key) + require.ErrorIs(t, err, ErrVersionCASUnavailable) + + targetFSM.SetApplyIndex(4) + require.Nil(t, targetFSM.Apply(EncodeMigrationVersionIdentityActivation())) + freshKey := []byte("fresh") + require.NoError(t, target.PutAt(ctx, freshKey, []byte("post-cutover"), 30, 0)) + _, err = shards.GetVersionAt(ctx, freshKey, 50) + require.ErrorIs(t, err, store.ErrNotSupported) + _, err = coordinator.Dispatch(ctx, staleCAS) + require.ErrorIs(t, err, ErrVersionCASUnavailable) + + // Cleanup removes the old source row. A return import can then carry + // the substituted bytes at the same timestamp without an exact row + // remaining in the source against which to detect the old overwrite. + installSourceOwnershipForTest(t, sourceFSM, 0) + cleanupReq := &pb.CleanupMigrationRequest{ + JobId: 11, Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, + RangeStart: []byte("a"), RangeEnd: []byte("z"), MaxCommitTs: 20, + RouteStart: []byte("m"), RouteEnd: []byte("z"), + RequireConfigurationIndex: true, ExpectedConfigurationIndex: 9, + ExpectedSourceGroupId: 1, + } + cleanup, err := MarshalMigrationCleanupCommand(cleanupReq) + require.NoError(t, err) + sourceFSM.SetApplyIndex(12) + requireCASRejection(t, sourceFSM.Apply(cleanup), store.ErrMigrationOwnership) + requireCASProgress(t, sourceFSM, 12) + cleanupReq.RequiresRouteKeyCheck = true + cleanup, err = MarshalMigrationCleanupCommand(cleanupReq) + require.NoError(t, err) + sourceFSM.SetApplyIndex(13) + cleaned, ok := sourceFSM.Apply(cleanup).(store.CleanupVersionsResult) + require.True(t, ok) + require.Equal(t, uint64(1), cleaned.DeletedRows) + requireCASProgress(t, sourceFSM, 13) + _, err = store.GetVersionAt(ctx, source, key, 50) + require.ErrorIs(t, err, store.ErrKeyNotFound) + fence, err := MarshalTargetStagedReadinessCommand(&pb.TargetStagedReadinessRequest{ + JobId: 11, MigrationJobId: 11, Armed: true, TrackWrites: true, SourceWriteFence: true, SourceReadFence: true, + RouteStart: []byte("m"), RouteEnd: []byte("z"), ExpectedCutoverVersion: 2, MinWriteTsExclusive: 20, RetentionPinTs: 1, + }) + require.NoError(t, err) + sourceFSM.SetApplyIndex(14) + require.Nil(t, sourceFSM.Apply(fence)) + retire, err := MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{ + JobId: 11, Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_OWNERSHIP_CLEAR, + RequireConfigurationIndex: true, ExpectedConfigurationIndex: 9, + Ownership: &pb.MigrationOwnershipProof{ + Generation: "0123456789abcdef0123456789abcdef", RouteId: 2, LocalGroupId: 1, OwnerGroupId: 2, + Role: pb.MigrationOwnershipRole_MIGRATION_OWNERSHIP_ROLE_NONOWNER, CatalogVersion: 2, + RouteStart: []byte("m"), RouteEnd: []byte("z"), MinWriteTsExclusive: 20, DescriptorHash: bytes.Repeat([]byte{1}, 32), + }, + }) + require.NoError(t, err) + sourceFSM.SetApplyIndex(15) + require.IsType(t, store.CleanupVersionsResult{}, sourceFSM.Apply(retire)) + importReq.JobId, importReq.BatchSeq = 2, 1 + require.IsType(t, store.ImportVersionsResult{}, applyMigrationVersionIdentityImport(t, sourceFSM, importReq, 16)) + _, err = source.GetAt(ctx, key, 50) + require.ErrorIs(t, err, store.ErrKeyNotFound, "a private stage must not resurrect retired public data") + unauthorized, err := MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 2}) + require.NoError(t, err) + sourceFSM.SetApplyIndex(17) + requireCASRejection(t, sourceFSM.Apply(unauthorized), store.ErrMigrationOwnership) + // The staged old version needs a new OWNER proof before publication. A + // genuinely newer version in another job needs no adoption of old rows. + importReq.JobId = 3 + version.CommitTs, version.Value = 40, []byte("newer return") + require.IsType(t, store.ImportVersionsResult{}, applyMigrationVersionIdentityImport(t, sourceFSM, importReq, 18)) + promote, err = MarshalMigrationPromoteCommand(&pb.PromoteStagedVersionsRequest{JobId: 3}) + require.NoError(t, err) + sourceFSM.SetApplyIndex(19) + require.IsType(t, store.PromoteVersionsResult{}, sourceFSM.Apply(promote)) + require.NoError(t, source.Close()) + source, err = store.NewPebbleStore(dir) + require.NoError(t, err) + groups[1].Store = source + sourceFSM, ok = NewKvFSMWithHLC(source, NewHLC()).(*kvFSM) + require.True(t, ok) + requireCASProgress(t, sourceFSM, 19) + view, err := readMigrationServingState(ctx, source) + require.NoError(t, err) + require.Empty(t, view.Readiness) + requireCASRejection(t, applyCASFrame(t, sourceFSM, 20, casApplyRequest(50, 60, token.TS, string(key), "wrong")), ErrVersionCASUnavailable) + requireCASProgress(t, sourceFSM, 20) + setOwner(3, 1, 40) + returned, err := store.GetVersionAt(ctx, source, key, 50) + require.NoError(t, err) + require.Equal(t, uint64(40), returned.TS) + require.Equal(t, version.Value, returned.Value) + _, err = shards.GetVersionAtWithReadFence(ctx, key, 50, 1, 3) + require.ErrorIs(t, err, store.ErrNotSupported) + _, err = coordinator.Dispatch(ctx, staleCAS) + require.ErrorIs(t, err, ErrVersionCASUnavailable) + _, err = shards.ResolveVersionCASGroupForKey(key) + require.ErrorIs(t, err, ErrVersionCASUnavailable) +} + +func TestVersionCASApplyRejectsMigrationGuardAfterAdmission(t *testing.T) { + t.Parallel() + f, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + ctx := t.Context() + key := []byte("key") + require.NoError(t, st.PutAt(ctx, key, []byte("source"), 10, 0)) + request := casApplyRequest(30, 40, 10, string(key), "wrong") + require.NoError(t, CheckMigrationRequest(ctx, st, 1, request)) + writer, ok := st.(store.MigrationTargetReadinessRaftWriter) + require.True(t, ok) + require.NoError(t, writer.ApplyTargetStagedReadinessAt(ctx, + store.TargetStagedReadinessState{JobID: 7, MigrationJobID: 7, Armed: true, + SourceWriteFence: true, RetentionPinTS: 1, RouteStart: key, MinWriteTSExclusive: 20, ExpectedCutoverVersion: 2}, 2)) + require.ErrorIs(t, CheckMigrationRequest(ctx, st, 1, request), ErrVersionCASUnavailable) + requireCASRejection(t, applyCASFrame(t, f, 3, request), ErrRouteWriteFenced) + requireCASProgress(t, f, 3) + value, err := st.GetAt(ctx, key, 50) + require.NoError(t, err) + require.Equal(t, []byte("source"), value) +} + +func TestMigrationVersionIdentitySurvivesSnapshot(t *testing.T) { + t.Parallel() + src, backing := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, src) + ctx := t.Context() + require.NoError(t, backing.PutAt(ctx, []byte("key"), []byte("before"), 10, 0)) + snapshot, err := backing.Snapshot() + require.NoError(t, err) + var raw bytes.Buffer + _, err = snapshot.WriteTo(&raw) + require.NoError(t, err) + require.NoError(t, snapshot.Close()) + + dst, reloaded := newCommitTSFenceFSM(t) + require.NoError(t, dst.Restore(bytes.NewReader(raw.Bytes()))) + active, err := MigrationVersionIdentityEnabled(ctx, reloaded) + require.NoError(t, err) + require.True(t, active) + require.Nil(t, applyCASFrame(t, dst, 2, casApplyRequest(15, 20, 10, "key", "after"))) + record, err := store.GetVersionAt(ctx, reloaded, []byte("key"), 20) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 20, Value: []byte("after")}, record) +} diff --git a/kv/version_cas_admission.go b/kv/version_cas_admission.go new file mode 100644 index 000000000..cabcd8afd --- /dev/null +++ b/kv/version_cas_admission.go @@ -0,0 +1,127 @@ +package kv + +import ( + "bytes" + "context" + + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "github.com/cockroachdb/errors" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +var ErrVersionCASUnavailable = raftengine.ErrVersionCASUnavailable + +const versionCASFrame = raftengine.VersionCASFrame + +func IsVersionCASRaftPayload(payload []byte) bool { + return raftengine.IsVersionCASRaftPayload(payload) +} + +func DecodeVersionCASRaftPayload(payload []byte) (*pb.Request, error) { + if !bytes.HasPrefix(payload, []byte(versionCASFrame)) { + return nil, errors.Wrap(ErrInvalidRequest, "unsupported version CAS Raft frame") + } + var request pb.Request + if err := proto.Unmarshal(payload[len(versionCASFrame):], &request); err != nil { + return nil, errors.WithStack(err) + } + if !HasCASMutation([]*pb.Request{&request}) { + return nil, errors.WithStack(ErrInvalidRequest) + } + if err := ValidateCASProposalShape([]*pb.Request{&request}); err != nil { + return nil, err + } + if version, _ := DecodeObservedRouteVersion(request.GetObservedRouteVersion()); version == 0 || len(request.GetWriteFenceBypassKeys()) != 0 { + return nil, errors.Wrap(ErrInvalidRequest, "version CAS frame requires a catalog version and forbids routing bypasses") + } + return &request, nil +} + +func (f *kvFSM) applyVersionCASFrame(ctx context.Context, payload []byte) any { + req, err := DecodeVersionCASRaftPayload(payload) + if err != nil { + return haltErr(errors.Mark(err, ErrRaftEntryApply)) + } + if !f.commitTSFenceEnabled.Load() { + return haltErr(errors.Mark(errors.New("version CAS entry precedes commit-ts fence activation"), ErrRaftEntryApply)) + } + active, err := MigrationVersionIdentityEnabled(ctx, f.store) + if err != nil || !active { + return haltErr(errors.Mark(errors.Wrap(errors.Join(ErrVersionCASUnavailable, err), + "version CAS entry requires migration version identity activation"), ErrRaftEntryApply)) + } + if f.pendingApplyIdx == 0 { + return casEntryHalt(errors.New("CAS entry requires a Raft applied index")) + } + return f.applyCASEntry(ctx, []*pb.Request{req}, f.applyFramedCAS) +} + +// VersionCASAdmission verifies the local leader and every configured replica. +// The returned context carries the proof's term and configuration to Raft. +type VersionCASAdmission func(context.Context) (context.Context, error) + +// WithVersionCASAdmission enables the local proposal path only when check is installed. +func WithVersionCASAdmission(check VersionCASAdmission) TransactionOption { + return func(t *TransactionManager) { t.versionCASAdmission = check } +} + +// ConfigureVersionCASAdmission is called during startup before the proxy serves requests. +func (p *LeaderProxy) ConfigureVersionCASAdmission(check VersionCASAdmission) { + WithVersionCASAdmission(check)(p.tm) +} + +func (t *TransactionManager) admitVersionCASRequest(ctx context.Context, req *pb.Request) (*pb.Request, error) { + if req.GetObservedRouteVersion() != 0 || len(req.GetWriteFenceBypassKeys()) != 0 { + return nil, errors.Wrap(ErrInvalidRequest, "CAS leader must supply the route proof") + } + admission := t.migrationAdmission.Load() + if admission == nil || admission.store == nil || admission.groupID != req.GetVersionCasGroupId() { + return nil, errors.Wrap(ErrVersionCASUnavailable, "CAS proposal is not bound to its receiving data group") + } + key := req.GetMutations()[1].GetKey() + if err := checkVersionCASMigrationRange(ctx, admission.store, key); err != nil { + return nil, errors.Wrap(ErrVersionCASUnavailable, err.Error()) + } + version, err := admitVersionCASRoute(ctx, admission.store, admission.groupID, key) + if err != nil { + return nil, err + } + owned := proto.CloneOf(req) + owned.ObservedRouteVersion = version + return owned, nil +} + +const versionCASForwardDomain = "elastickv.internal.version_cas" +const versionCASForwardNotAdmitted = "NOT_ADMITTED" + +func VersionCASForwardUnavailable(cause error) error { + st, err := status.New(codes.FailedPrecondition, "Version CAS admission unavailable").WithDetails(&errdetails.ErrorInfo{ + Domain: versionCASForwardDomain, + Reason: versionCASForwardNotAdmitted, + }) + if err != nil { + return cause + } + return errors.WithStack(st.Err()) +} + +func isVersionCASForwardUnavailable(err error) bool { + st := status.Convert(err) + if st.Code() == codes.Unimplemented { + // A preceding binary has no CAS Forward RPC and cannot have executed it. + return true + } + if st.Code() != codes.FailedPrecondition { + return false + } + details := st.Details() + if len(details) != 1 { + return false + } + detail, ok := details[0].(*errdetails.ErrorInfo) + return ok && detail.GetDomain() == versionCASForwardDomain && detail.GetReason() == versionCASForwardNotAdmitted +} diff --git a/kv/version_cas_catalog_test.go b/kv/version_cas_catalog_test.go new file mode 100644 index 000000000..d3bd8f5c6 --- /dev/null +++ b/kv/version_cas_catalog_test.go @@ -0,0 +1,229 @@ +package kv + +import ( + "context" + "testing" + "time" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +func newCASCatalogFSM(t *testing.T, st store.MVCCStore, watcher *distribution.Engine) (*kvFSM, raftbootstrap.PolicyRecord) { + t.Helper() + policy := guardedNewPolicy() + policy.Identity.Group = 1 + seedGuardedNewPolicy(t, st, policy, 10) + fsm, ok := NewKvFSMWithHLC(st, NewHLC(), WithRouteHistory(WrapDistributionEngine(watcher), policy.Identity.Group), + WithRaftBootstrapIdentity(policy.Identity.Cluster, policy.Identity.Group)).(*kvFSM) + require.True(t, ok) + plan, err := distribution.NewCatalogStore(st).BuildBootstrapPlanAt(t.Context(), 1, []distribution.Route{ + {GroupID: policy.Identity.Group, State: distribution.RouteStateActive}, + }) + require.NoError(t, err) + applyCASCatalogCommit(t, fsm, policy, 11, 1, 2, plan.Mutations) + return fsm, policy +} + +func applyCASCatalogCommit(t *testing.T, f *kvFSM, policy raftbootstrap.PolicyRecord, index, startTS, commitTS uint64, muts []*store.KVPairMutation) { + t.Helper() + metadata, ok := f.store.(store.RaftControlMetadataStore) + require.True(t, ok) + current, err := readAppliedBootstrapPolicy(t.Context(), metadata, policy.Identity, index) + require.NoError(t, err) + policy = current + key := distribution.CatalogVersionKey() + req := newOnePhaseTxnRequest(startTS, commitTS, 0, key, len(muts), nil, 0, nil) + for _, mut := range muts { + req.Mutations = append(req.Mutations, &pb.Mutation{Op: pb.Op_PUT, Key: mut.Key, Value: mut.Value}) + req.ReadKeys = append(req.ReadKeys, mut.Key) + } + command := guardedNewCommand(t, policy, raftbootstrap.ControlGuardedCatalog) + command.OperationID = raftbootstrap.OperationID{byte(index)} + command.Inner = encodeGuardedCatalogRequest(t, req) + result := applyGuardedNewCommand(t, f, command, index) + receipt, ok := result.(raftbootstrap.GuardedReceipt) + require.True(t, ok, "catalog apply returned %v", result) + require.Equal(t, raftbootstrap.GuardedReceiptApplied, receipt.Verdict) +} + +func applyCASCatalogRoutes(t *testing.T, f *kvFSM, policy raftbootstrap.PolicyRecord, index, commitTS uint64, snapshot distribution.CatalogSnapshot) { + t.Helper() + muts := []*store.KVPairMutation{ + {Op: store.OpTypePut, Key: distribution.CatalogVersionKey(), Value: distribution.EncodeCatalogVersion(snapshot.Version)}, + {Op: store.OpTypePut, Key: distribution.CatalogNextRouteIDKey(), Value: distribution.EncodeCatalogNextRouteID(3)}, + } + delta := distribution.CatalogDelta{Version: snapshot.Version, PreviousVersion: snapshot.Version - 1} + for _, route := range snapshot.Routes { + raw, err := distribution.EncodeRouteDescriptorForCatalogWrite(route, true) + require.NoError(t, err) + muts = append(muts, &store.KVPairMutation{Op: store.OpTypePut, Key: distribution.CatalogRouteKey(route.RouteID), Value: raw}) + delta.Mutations = append(delta.Mutations, distribution.CatalogRouteMutation{ + Op: distribution.CatalogMutationUpsert, RouteID: route.RouteID, Route: route, + }) + } + startTS := f.store.LastCommitTS() + deltaMuts, err := distribution.NewCatalogStore(f.store).BuildDeltaMutationsAt(t.Context(), startTS, delta) + require.NoError(t, err) + applyCASCatalogCommit(t, f, policy, index, startTS, commitTS, append(muts, deltaMuts...)) +} + +type casCatalogProposer func(context.Context, []byte) (*raftengine.ProposalResult, error) + +func (p casCatalogProposer) Propose(ctx context.Context, payload []byte) (*raftengine.ProposalResult, error) { + return p(ctx, payload) +} + +func (p casCatalogProposer) ProposeAdmin(ctx context.Context, payload []byte) (*raftengine.ProposalResult, error) { + return p(ctx, payload) +} + +func TestVersionCASOrdersCatalogChangeBetweenAdmissionAndApply(t *testing.T) { + for _, tc := range []struct { + name string + route distribution.RouteDescriptor + want error + }{ + {name: "split", route: distribution.RouteDescriptor{GroupID: 1, State: distribution.RouteStateActive}}, + {name: "move", route: distribution.RouteDescriptor{GroupID: 2, State: distribution.RouteStateActive}, want: ErrRouteWriteFenced}, + {name: "fence", route: distribution.RouteDescriptor{GroupID: 1, State: distribution.RouteStateWriteFenced}, want: ErrRouteWriteFenced}, + {name: "staged visibility", route: distribution.RouteDescriptor{GroupID: 1, State: distribution.RouteStateActive, + StagedVisibilityActive: true, MigrationJobID: 7, MinWriteTSExclusive: 12}, want: ErrVersionCASUnavailable}, + {name: "write floor", route: distribution.RouteDescriptor{GroupID: 1, State: distribution.RouteStateActive, + MinWriteTSExclusive: 12}, want: ErrVersionCASUnavailable}, + } { + t.Run(tc.name, func(t *testing.T) { + st, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + watcher := distribution.NewEngine() + require.NoError(t, watcher.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}, + }})) + f, policy := newCASCatalogFSM(t, st, watcher) + activateCommitTSFence(t, f) + f.SetApplyIndex(12) + require.Nil(t, f.Apply(EncodeMigrationVersionIdentityActivation())) + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("before"), 10, 0)) + + proposals := 0 + right := tc.route + right.RouteID, right.Start = 2, []byte("m") + proposer := casCatalogProposer(func(_ context.Context, payload []byte) (*raftengine.ProposalResult, error) { + proposals++ + req, err := DecodeVersionCASRaftPayload(payload) + require.NoError(t, err) + require.EqualValues(t, 1, req.GetObservedRouteVersion()) + require.EqualValues(t, 1, req.GetVersionCasGroupId()) + applyCASCatalogRoutes(t, f, policy, 13, 12, distribution.CatalogSnapshot{Version: 2, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive, End: []byte("m")}, + right, + }}) + f.SetApplyIndex(14) + return &raftengine.ProposalResult{CommitIndex: 14, Response: f.Apply(payload)}, nil + }) + tx := NewTransactionWithProposer(proposer, WithMigrationRequestAdmission(st, 1), + WithVersionCASAdmission(func(ctx context.Context) (context.Context, error) { + return raftengine.WithVersionCASProof(ctx, raftengine.VersionCASProof{Term: 3, ConfigurationIndex: 5}), nil + })) + t.Cleanup(tx.Close) + req := casApplyRequest(15, 20, 10, "n", "after") + req.ObservedRouteVersion = 0 + _, err = tx.Commit(t.Context(), []*pb.Request{req}) + wantTS := uint64(20) + if tc.want == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, tc.want) + var rejection *AppliedRequestRejection + require.ErrorAs(t, err, &rejection) + require.EqualValues(t, 14, rejection.CommitIndex()) + wantTS = 10 + _, err = tx.Commit(t.Context(), []*pb.Request{req}) + require.ErrorIs(t, err, ErrVersionCASUnavailable, "stale retries must stop before proposal") + } + require.Equal(t, 1, proposals) + require.EqualValues(t, 1, watcher.Version(), "watcher stayed behind throughout") + requireCASProgress(t, f, 14) + row, err := store.GetVersionAt(t.Context(), st, []byte("n"), 30) + require.NoError(t, err) + require.Equal(t, wantTS, row.TS) + }) + } +} + +func TestVersionCASRequiresCatalogDescriptorRangeInGroup(t *testing.T) { + f, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + _, err := admitVersionCASRoute(t.Context(), st, 1, []byte("key")) + require.NoError(t, err) + catalog := distribution.NewCatalogStore(st) + _, err = catalog.Save(t.Context(), 1, []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive, End: []byte("!dist|route|")}, + {RouteID: 2, GroupID: 2, State: distribution.RouteStateActive, Start: []byte("!dist|route|"), End: []byte("a")}, + {RouteID: 3, GroupID: 1, State: distribution.RouteStateActive, Start: []byte("a")}, + }) + require.NoError(t, err) + _, err = admitVersionCASRoute(t.Context(), st, 1, []byte("key")) + require.ErrorIs(t, err, ErrVersionCASUnavailable) +} + +func TestVersionCASPreservesBackupTimestampFloor(t *testing.T) { + f, st := newCommitTSFenceFSM(t) + f.readTracker = NewActiveTimestampTracker(WithActiveTimestampTrackerSweepInterval(0)) + enableCASApplyForTest(t, f) + require.NoError(t, st.PutAt(t.Context(), []byte("key"), []byte("before"), 10, 0)) + f.SetApplyIndex(2) + require.Nil(t, f.Apply(EncodeBackupPinEntry(BackupPinEntry{ + PinID: backupTrackerTestPinID(1), ReadTS: 25, Deadline: time.Now().Add(time.Hour), + }))) + requireCASRejection(t, applyCASFrame(t, f, 3, casApplyRequest(15, 20, 10, "key", "after")), ErrBackupTimestampFenced) + requireCASProgress(t, f, 3) + row, err := store.GetVersionAt(t.Context(), st, []byte("key"), 30) + require.NoError(t, err) + require.EqualValues(t, 10, row.TS) +} + +func TestVersionCASFrameRejectsWrongGroup(t *testing.T) { + f, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + require.NoError(t, st.PutAt(t.Context(), []byte("key"), []byte("before"), 10, 0)) + req := casApplyRequest(15, 20, 10, "key", "after") + req.VersionCasGroupId = 2 + requireCASRejection(t, applyCASFrame(t, f, 2, req), ErrRouteWriteFenced) + requireCASProgress(t, f, 2) + row, err := store.GetVersionAt(t.Context(), st, []byte("key"), 30) + require.NoError(t, err) + require.EqualValues(t, 10, row.TS) +} + +func TestVersionCASFrameHaltsWithoutAppliedCatalog(t *testing.T) { + f, st := newCommitTSFenceFSM(t) + bindCASTestGroup(f) + enableCASMarkersForTest(t, f) + require.NoError(t, st.PutAt(t.Context(), []byte("key"), []byte("before"), 10, 0)) + resp := applyCASFrame(t, f, 2, casApplyRequest(15, 20, 10, "key", "after")) + require.ErrorContains(t, haltApplyOf(resp), "lacks an applied catalog") + requireCASProgress(t, f, 1) + row, err := store.GetVersionAt(t.Context(), st, []byte("key"), 30) + require.NoError(t, err) + require.EqualValues(t, 10, row.TS) +} + +func TestVersionCASLegacyFrameHaltsWithoutAdvancing(t *testing.T) { + f, _ := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + req := casApplyRequest(15, 20, 10, "key", "after") + req.VersionCasGroupId = 0 + body, err := proto.Marshal(req) + require.NoError(t, err) + f.SetApplyIndex(2) + result := f.Apply(append([]byte("\x06CAS\x01"), body...)) + require.ErrorContains(t, haltApplyOf(result), "unsupported version CAS Raft frame") + requireCASProgress(t, f, 1) +} diff --git a/kv/version_cas_forward_compat_test.go b/kv/version_cas_forward_compat_test.go new file mode 100644 index 000000000..347061fa3 --- /dev/null +++ b/kv/version_cas_forward_compat_test.go @@ -0,0 +1,61 @@ +package kv + +import ( + "context" + "sync/atomic" + "testing" + + "github.com/bootjp/elastickv/internal/testutil/grpctest" + pb "github.com/bootjp/elastickv/proto" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestVersionCASForwardRejectsNilRequests(t *testing.T) { + proxy := NewLeaderProxyWithEngine(newStubFollowerEngine(""), WithVersionCASAdmission(func(ctx context.Context) (context.Context, error) { return ctx, nil })) + req := onePhaseReq(0, 0, 0, []byte("switch"), []byte("off")) + req.Mutations[1].Op = pb.Op_COMPARE_AND_SWAP + req.Mutations[1].ExpectedCommitTs = 10 + req.VersionCasGroupId = 1 + for _, requests := range [][]*pb.Request{{nil, req}, {req, nil}, {nil}} { + _, err := proxy.Commit(t.Context(), requests) + require.ErrorIs(t, err, ErrInvalidRequest) + } + require.Zero(t, proxy.forwardSeq.Load()) +} + +func TestVersionCASForwardToLegacyLeader(t *testing.T) { + legacy := &fakeInternal{resp: &pb.ForwardResponse{Success: true, CommitIndex: 15, CommitTs: 20}} + var dedicatedCalls atomic.Int32 + addr := grpctest.Serve(t, func(s *grpc.Server) { + desc := pb.Internal_ServiceDesc + desc.Methods = nil + for _, method := range pb.Internal_ServiceDesc.Methods { + if method.MethodName != "ForwardCompareAndSwapV2" { + desc.Methods = append(desc.Methods, method) + } + } + s.RegisterService(&desc, legacy) + }, grpc.UnknownServiceHandler(func(_ any, stream grpc.ServerStream) error { + method, _ := grpc.MethodFromServerStream(stream) + if method == pb.Internal_ForwardCompareAndSwapV2_FullMethodName { + dedicatedCalls.Add(1) + } + return status.Error(codes.Unimplemented, "unknown method") + })) + proxy := NewLeaderProxyWithEngine(newStubFollowerEngine(addr), WithVersionCASAdmission(func(ctx context.Context) (context.Context, error) { return ctx, nil })) + t.Cleanup(func() { _ = proxy.connCache.Close() }) + req := onePhaseReq(0, 0, 0, []byte("switch"), []byte("off")) + req.Mutations[1].Op = pb.Op_COMPARE_AND_SWAP + req.Mutations[1].ExpectedCommitTs = 10 + req.VersionCasGroupId = 1 + + _, err := proxy.Commit(t.Context(), []*pb.Request{req}) + require.ErrorIs(t, err, ErrVersionCASUnavailable) + require.EqualValues(t, 1, dedicatedCalls.Load()) + legacy.mu.Lock() + defer legacy.mu.Unlock() + require.Zero(t, legacy.calls, "legacy Forward would append an unframed operation") +} diff --git a/kv/version_cas_frame_recovery_test.go b/kv/version_cas_frame_recovery_test.go new file mode 100644 index 000000000..06622144b --- /dev/null +++ b/kv/version_cas_frame_recovery_test.go @@ -0,0 +1,52 @@ +package kv + +import ( + "testing" + + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func TestVersionCASFrameRecoveryAfterCommitFailure(t *testing.T) { + dir := t.TempDir() + open := func() (*kvFSM, store.MVCCStore) { + st, err := store.NewPebbleStore(dir) + require.NoError(t, err) + f, ok := NewKvFSMWithHLC(st, NewHLC()).(*kvFSM) + require.True(t, ok) + return f, st + } + f, st := open() + enableCASApplyForTest(t, f) + key := []byte("original-key") + require.NoError(t, st.PutAt(t.Context(), key, []byte("prior"), 10, 0)) + injected := errors.New("injected failure after staging CAS") + metadata, ok := st.(store.RaftControlMetadataStore) + require.True(t, ok) + f.store = &struct { + *g17FailingEntryStore + store.RaftControlMetadataStore + }{&g17FailingEntryStore{MVCCStore: st, err: injected}, metadata} + req := casApplyRequest(15, 20, 10, string(key), "replacement") + result := applyCASFrame(t, f, 2, req) + halt, ok := result.(interface{ HaltApply() error }) + require.True(t, ok, "response = %v", result) + require.ErrorIs(t, halt.HaltApply(), injected) + require.NoError(t, st.Close()) + + f, st = open() + t.Cleanup(func() { require.NoError(t, st.Close()) }) + requireCASProgress(t, f, 1) + old, err := store.GetVersionAt(t.Context(), st, key, 20) + require.NoError(t, err) + require.EqualValues(t, 10, old.TS) + require.Equal(t, []byte("prior"), old.Value) + require.Nil(t, applyCASFrame(t, f, 2, req)) + requireCASProgress(t, f, 2) + require.Nil(t, applyCASFrame(t, f, 2, req), "durable replay skips the predicate") + newValue, err := store.GetVersionAt(t.Context(), st, key, 20) + require.NoError(t, err) + require.EqualValues(t, 20, newValue.TS) + require.Equal(t, []byte("replacement"), newValue.Value) +} diff --git a/kv/version_cas_isolation_test.go b/kv/version_cas_isolation_test.go new file mode 100644 index 000000000..5dc562118 --- /dev/null +++ b/kv/version_cas_isolation_test.go @@ -0,0 +1,59 @@ +package kv + +import ( + "testing" + + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +// The invariant is that at least one switch stays on. Both clients read both +// switches at the same snapshot. A single-key CAS protects only its own switch. +func TestVersionCASAndReadSetWriteSkew(t *testing.T) { + for _, mode := range []string{"exact-key", "validate-read-set"} { + t.Run(mode, func(t *testing.T) { + fsm, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, fsm) + keys := [][]byte{[]byte("a"), []byte("b")} + expected := []uint64{10, 20} + for i, k := range keys { + fsm.SetApplyIndex(uint64(i + 2)) + require.NoError(t, applyFSMRequest(t, fsm, rawPut(expected[i], string(k), "on"))) + } + snapshot := st.LastCommitTS() + for _, k := range keys { + value, err := st.GetAt(t.Context(), k, snapshot) + require.NoError(t, err) + require.Equal(t, []byte("on"), value) + } + + for i, k := range keys { + req := onePhaseReq(snapshot, uint64(30+i), 0, k, []byte("off")) + if mode == "exact-key" { + req = casApplyRequest(snapshot, uint64(30+i), expected[i], string(k), "off") + } else { + req.ReadKeys = keys + } + fsm.SetApplyIndex(uint64(100 + i)) + payload, err := marshalRaftCommand([]*pb.Request{req}) + require.NoError(t, err) + result := fsm.Apply(payload) + if mode == "validate-read-set" && i == 1 { + rejection, ok := result.(error) + require.True(t, ok) + require.ErrorIs(t, rejection, store.ErrWriteConflict) + } else { + require.Nil(t, result) + } + } + value, err := st.GetAt(t.Context(), keys[1], st.LastCommitTS()) + require.NoError(t, err) + if mode == "validate-read-set" { + require.Equal(t, []byte("on"), value) + } else { + require.Equal(t, []byte("off"), value) + } + }) + } +} diff --git a/kv/version_cas_precheck.go b/kv/version_cas_precheck.go new file mode 100644 index 000000000..7e0f16ebe --- /dev/null +++ b/kv/version_cas_precheck.go @@ -0,0 +1,127 @@ +package kv + +import ( + "context" + "crypto/sha256" + + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" +) + +// casPrecheckMismatch is issued only before this standalone CAS is submitted. +// It is deliberately not an indexed apply rejection or a generic 1PC conflict. +type casPrecheckMismatch struct{} + +type casPrecheckedContextKey struct{} + +func (*casPrecheckMismatch) Error() string { return ErrCASMismatch.Error() } +func (*casPrecheckMismatch) Unwrap() error { return ErrCASMismatch } + +// IsCertifiedCASPrecheckMismatch recognizes an isolated pre-submission verdict. +func IsCertifiedCASPrecheckMismatch(err error) bool { + var proof *casPrecheckMismatch + return isolatedMutationFailure(err) && errors.As(err, &proof) +} + +func (p *LeaderProxy) precheckLocalCAS(ctx context.Context, reqs []*pb.Request, cas bool) (context.Context, func(), error) { + if !cas || p.tm.versionCASPrecheck == nil { + return ctx, nil, nil + } + if !unstampedCASPrecheckEligible(reqs) { + return ctx, nil, nil + } + return p.tm.beginAdaptiveCAS(ctx, reqs[0]) +} + +func unstampedCASPrecheckEligible(reqs []*pb.Request) bool { + _, err := ForwardCASMutation(reqs) + return err == nil && len(reqs[0].GetWriteFenceBypassKeys()) == 0 +} + +func (t *TransactionManager) beginAdaptiveCAS(ctx context.Context, req *pb.Request) (context.Context, func(), error) { + if ctx.Value(casPrecheckedContextKey{}) != nil || t.versionCASPrecheck == nil { + return ctx, nil, nil + } + check := func() bool { return t.versionCASPrecheck(ctx, req) } + var release func() + if t.versionCASProposals != nil { + var err error + release, err = t.versionCASProposals.acquire(ctx, t.closeCh, sha256.Sum256(req.Mutations[1].Key), check) + if err != nil { + return nil, nil, err + } + } else if check() { + return nil, nil, &casPrecheckMismatch{} + } + return context.WithValue(ctx, casPrecheckedContextKey{}, true), release, nil +} + +// WithAdaptiveVersionCASPrecheck is startup wiring for local and forwarded CAS. +// Omitting it retains the apply-only path for diagnostics and custom stores. +func (c *ShardedCoordinator) WithAdaptiveVersionCASPrecheck(tracker *ActiveTimestampTracker) *ShardedCoordinator { + if _, ok := c.store.(*ShardStore); !ok { + return c + } + for _, group := range c.groups { + manager := group.localGroupTransactionManager(group.Txn) + if manager != nil && manager.versionCASAdmission != nil { + manager.versionCASProposals = newCASProposalGate(maxCASAdmissionAttempts) + manager.versionCASPrecheck = func(ctx context.Context, req *pb.Request) bool { + return c.adaptiveVersionCASMismatch(ctx, group, req, tracker) + } + } + } + return c +} + +func (c *ShardedCoordinator) adaptiveVersionCASMismatch(ctx context.Context, group *ShardGroup, req *pb.Request, tracker *ActiveTimestampTracker) bool { + mut, _, valid := casRequestMutation([]*pb.Request{req}) + if !valid || group == nil || group.Store == nil || group.versionReadAdmission == nil { + return false + } + shards, ok := c.store.(*ShardStore) + if !ok || shards.groups[req.GetVersionCasGroupId()] != group { + return false + } + // A published local head is only a hint. In particular a lagging head must + // never reject a token which the subsequent ReadIndex fence makes visible. + head, err := store.GetVersionAt(ctx, group.Store, mut.Key, max(group.Store.LastCommitTS(), 1)) + if !casPrecheckDiffers(head, mut.ExpectedCommitTs, err) { + return false + } + reader := NewReadRequest(ctx, c, c.store, tracker) + defer reader.Close() + ctx = reader.Context() + snapshot, err := reader.LatestTargets(ctx, "CAS adaptive precheck", []ReadFenceTarget{{GroupID: req.GetVersionCasGroupId(), Key: mut.Key}}) + if err != nil { + return false + } + head, err = c.readCASPrecheckHead(ctx, reader, snapshot, group, req, mut.Key) + return casPrecheckDiffers(head, mut.ExpectedCommitTs, err) +} + +func casPrecheckDiffers(head store.VersionedValue, expected uint64, err error) bool { + return (isolatedMutationFailure(err) && errors.Is(err, store.ErrKeyNotFound)) || (err == nil && head.TS != expected) +} + +func (c *ShardedCoordinator) readCASPrecheckHead(ctx context.Context, reader *ReadRequest, snapshot ReadSnapshot, group *ShardGroup, req *pb.Request, key []byte) (store.VersionedValue, error) { + return withReadSnapshot(reader, ctx, snapshot, func() error { + return reader.validateGroupScope(snapshot, req.GetVersionCasGroupId(), key) + }, func(ts uint64) (store.VersionedValue, error) { + shards, ok := c.store.(*ShardStore) + if !ok { + return store.VersionedValue{}, store.ErrNotSupported + } + route, version, ok := shards.versionReadRoute(key, req.GetVersionCasGroupId()) + if !ok || version < req.GetObservedRouteVersion() { + return store.VersionedValue{}, store.ErrNotSupported + } + // Do not invoke the ordinary read's lock resolver. A lock or an unreadable + // lock leaves priority and the definitive outcome to the existing FSM. + if _, locked, err := loadTxnLockAt(ctx, group, key, ts); err != nil || locked { + return store.VersionedValue{}, ErrTxnLocked + } + return readVersionOnInitialRoute(ctx, group, route, key, ts) + }) +} diff --git a/kv/version_cas_precheck_test.go b/kv/version_cas_precheck_test.go new file mode 100644 index 000000000..8930abe2e --- /dev/null +++ b/kv/version_cas_precheck_test.go @@ -0,0 +1,156 @@ +package kv + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftengine" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func TestAdaptiveVersionCASPrecheck(t *testing.T) { + for _, name := range []string{"match", "mismatch", "absent", "stale hint", "read failure", "admission failure", "locked", "route change"} { + t.Run(name, func(t *testing.T) { + f, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + key := []byte("key") + if name != "absent" { + require.NoError(t, st.PutAt(t.Context(), key, []byte("before"), 10, 0)) + } + routes := distribution.NewEngine() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}, + }})) + fences := 0 + engine := &recordingTSOEngine{state: raftengine.StateLeader, readIndex: func(context.Context) (uint64, error) { + fences++ + switch name { + case "stale hint": + require.NoError(t, st.PutAt(t.Context(), key, []byte("new"), 20, 0)) + case "read failure": + return 0, context.DeadlineExceeded + case "route change": + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 2, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 2, State: distribution.RouteStateActive}, + }})) + } + return 1, nil + }} + group := &ShardGroup{Engine: engine, Store: st} + group.ConfigureVersionReadAdmission(func(context.Context) error { + if name == "admission failure" { + return ErrVersionCASUnavailable + } + return nil + }) + if name == "locked" { + require.NoError(t, st.PutAt(t.Context(), txnLockKey(key), []byte("malformed lock must not be resolved"), 11, 0)) + } + groups := map[uint64]*ShardGroup{1: group} + shards := NewShardStore(routes, groups) + coord := NewShardedCoordinator(routes, groups, 1, NewHLC(), shards) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + expected := max(uint64(5), map[string]uint64{"match": 10, "stale hint": 20}[name]) + req := casApplyRequest(30, 40, expected, string(key), "after") + got := coord.adaptiveVersionCASMismatch(t.Context(), group, req, nil) + wantMismatch := map[string]bool{"mismatch": true, "absent": true} + require.Equal(t, wantMismatch[name], got) + if name == "match" { + require.Zero(t, fences, "matching hint must leave the decision to the FSM without a read barrier") + } else { + require.Equal(t, 1, fences) + } + }) + } +} + +func TestAdaptiveVersionCASRejectsBeforeAnyProposal(t *testing.T) { + f, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + require.NoError(t, st.PutAt(t.Context(), []byte("key"), []byte("before"), 10, 0)) + routes := distribution.NewEngine() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}, + }})) + engine := &recordingTSOEngine{state: raftengine.StateLeader} + group := &ShardGroup{Engine: engine, Store: st} + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + proxy := NewLeaderProxyForShardGroup(group, WithVersionCASAdmission(func(ctx context.Context) (context.Context, error) { + return raftengine.WithVersionCASProof(ctx, raftengine.VersionCASProof{Term: 1, ConfigurationIndex: 1}), nil + })) + proposals := 0 + proxy.tm.proposer = casCatalogProposer(func(context.Context, []byte) (*raftengine.ProposalResult, error) { + proposals++ + return nil, context.DeadlineExceeded + }) + group.Txn = proxy + groups := map[uint64]*ShardGroup{1: group} + shards := NewShardStore(routes, groups) + coord := NewShardedCoordinator(routes, groups, 1, NewHLC(), shards).WithAdaptiveVersionCASPrecheck(nil) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + req := casApplyRequest(20, 30, 5, "key", "must-not-commit") + req.ObservedRouteVersion = 0 + _, err := group.ForwardTransaction(1).Commit(t.Context(), []*pb.Request{req}) + require.True(t, IsCertifiedCASPrecheckMismatch(err)) + require.Zero(t, proposals) + row, err := store.GetVersionAt(t.Context(), st, []byte("key"), 40) + require.NoError(t, err) + require.EqualValues(t, 10, row.TS) + + // A matching hint is never a success certificate. The original proposal + // still runs and its lost/empty reply remains indeterminate. + req.Mutations[1].ExpectedCommitTs = 10 + _, err = group.ForwardTransaction(1).Commit(t.Context(), []*pb.Request{req}) + require.ErrorIs(t, err, ErrTransactionOutcomeUnknown) + require.False(t, IsCertifiedCASMismatch(err)) + require.Equal(t, 1, proposals) + require.Empty(t, proxy.tm.versionCASProposals.active, "an unknown result releases admission, not its outcome") + require.Empty(t, proxy.tm.versionCASProposals.slots) +} + +func TestCASPrecheckMismatchCertificate(t *testing.T) { + proof := &casPrecheckMismatch{} + require.True(t, IsCertifiedCASMismatch(proof)) + require.False(t, IsCertifiedOnePhaseConflict(proof), "precheck has no indexed apply receipt") + for _, err := range []error{ErrCASMismatch, errors.Join(proof, ErrCASMismatch), errors.Join(proof, ErrTransactionOutcomeUnknown), errors.WithSecondaryError(proof, ErrCASMismatch)} { + require.False(t, IsCertifiedCASMismatch(err)) + } + require.False(t, casPrecheckDiffers(store.VersionedValue{}, 10, errors.Join(store.ErrKeyNotFound, context.DeadlineExceeded))) + forwarded := classifyDedicatedCASForwardFailure(pb.ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH, + pb.ForwardDecisionClass_FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION) + require.True(t, IsCertifiedCASPrecheckMismatch(forwarded)) +} + +func TestAdaptiveLocalCASPrecheckPrecedesWriteStampAndAdmission(t *testing.T) { + engine := &recordingTSOEngine{state: raftengine.StateLeader} + admissions, stamps, checks := 0, 0, 0 + proxy := NewLeaderProxyWithEngine(engine, WithVersionCASAdmission(func(ctx context.Context) (context.Context, error) { + admissions++ + return ctx, nil + })) + proxy.tm.versionCASPrecheck = func(context.Context, *pb.Request) bool { + checks++ + return true + } + req := casApplyRequest(0, 0, 5, "key", "replacement") + req.ObservedRouteVersion = 0 + _, err := proxy.commitWithLocalStamp(t.Context(), []*pb.Request{req}, func(context.Context, []*pb.Request) (uint64, error) { + stamps++ + return 0, errors.New("must not stamp a proven pre-submission mismatch") + }) + require.True(t, IsCertifiedCASPrecheckMismatch(err)) + require.Equal(t, 1, checks) + require.Zero(t, stamps) + require.Zero(t, admissions) + require.Empty(t, engine.proposedPayloads()) + + // A malformed request cannot be certified just because a callback says yes. + req.WriteFenceBypassKeys = [][]byte{[]byte("key")} + _, err = proxy.commitWithLocalStamp(t.Context(), []*pb.Request{req}, nil) + require.False(t, IsCertifiedCASMismatch(err)) + require.Equal(t, 1, checks) +} diff --git a/kv/version_cas_proposal_gate.go b/kv/version_cas_proposal_gate.go new file mode 100644 index 000000000..d83552d2e --- /dev/null +++ b/kv/version_cas_proposal_gate.go @@ -0,0 +1,109 @@ +package kv + +import ( + "context" + "sync" + + "github.com/cockroachdb/errors" +) + +const maxCASAdmissionAttempts = 4096 + +// Only CAS proposals for the same key share a lane. Waiting requests recheck +// after the predecessor finishes; neither a lane nor its release proves commit. +// Digests bound retained key memory. A collision only adds contention. +type casProposalGate struct { + mu sync.Mutex + active map[[32]byte]chan struct{} + slots chan struct{} +} + +func newCASProposalGate(limit int) *casProposalGate { + return &casProposalGate{active: make(map[[32]byte]chan struct{}), slots: make(chan struct{}, limit)} +} + +func (g *casProposalGate) acquire(ctx context.Context, closed <-chan struct{}, key [32]byte, mismatch func() bool) (func(), error) { + select { + case g.slots <- struct{}{}: + default: + return nil, errors.Wrap(ErrVersionCASUnavailable, "CAS admission limit reached") + } + retained := false + defer func() { + if !retained { + <-g.slots + } + }() + for { + if err := casAdmissionContextError(ctx, closed); err != nil { + return nil, err + } + pending, owned := g.claim(key) + if owned { + retained = true + return g.confirmClaim(key, pending, mismatch) + } + if mismatch() { + return nil, &casPrecheckMismatch{} + } + if err := waitCASPredecessor(ctx, closed, pending); err != nil { + return nil, err + } + } +} + +func (g *casProposalGate) confirmClaim(key [32]byte, pending chan struct{}, mismatch func() bool) (func(), error) { + release := g.release(key, pending) + if mismatch() { + release() + return nil, &casPrecheckMismatch{} + } + return release, nil +} + +func casAdmissionContextError(ctx context.Context, closed <-chan struct{}) error { + if err := ctx.Err(); err != nil { + return errors.WithStack(err) + } + select { + case <-closed: + return errShuttingDown + default: + return nil + } +} + +func waitCASPredecessor(ctx context.Context, closed, pending <-chan struct{}) error { + select { + case <-ctx.Done(): + return errors.WithStack(ctx.Err()) + case <-closed: + return errShuttingDown + case <-pending: + return nil + } +} + +func (g *casProposalGate) claim(key [32]byte) (chan struct{}, bool) { + g.mu.Lock() + defer g.mu.Unlock() + if pending, exists := g.active[key]; exists { + return pending, false + } + pending := make(chan struct{}) + g.active[key] = pending + return pending, true +} + +func (g *casProposalGate) release(key [32]byte, pending chan struct{}) func() { + var once sync.Once + return func() { + once.Do(func() { + g.mu.Lock() + delete(g.active, key) + close(pending) + g.mu.Unlock() + <-g.slots + }) + } +} diff --git a/kv/version_cas_proposal_gate_integration_test.go b/kv/version_cas_proposal_gate_integration_test.go new file mode 100644 index 000000000..981464de5 --- /dev/null +++ b/kv/version_cas_proposal_gate_integration_test.go @@ -0,0 +1,149 @@ +package kv + +import ( + "context" + "crypto/sha256" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftengine" + "github.com/bootjp/elastickv/internal/testutil/grpctest" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" +) + +func TestAdaptiveCASProposesOneEntryForWaitingContenders(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + f, st := newCommitTSFenceFSM(t) + enableCASApplyForTest(t, f) + require.NoError(t, st.PutAt(t.Context(), []byte("key"), []byte("before"), 10, 0)) + routes := distribution.NewEngine() + require.NoError(t, routes.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}, + }})) + group := &ShardGroup{Engine: &recordingTSOEngine{state: raftengine.StateLeader}, Store: st} + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + proxy := NewLeaderProxyForShardGroup(group, WithVersionCASAdmission(func(ctx context.Context) (context.Context, error) { + return raftengine.WithVersionCASProof(ctx, raftengine.VersionCASProof{Term: 1, ConfigurationIndex: 1}), nil + })) + group.Txn = proxy + groups := map[uint64]*ShardGroup{1: group} + shards := NewShardStore(routes, groups) + coord := NewShardedCoordinator(routes, groups, 1, NewHLC(), shards).WithAdaptiveVersionCASPrecheck(nil) + t.Cleanup(func() { require.NoError(t, coord.Close()) }) + var checks, proposals atomic.Int32 + check := proxy.tm.versionCASPrecheck + proxy.tm.versionCASPrecheck = func(ctx context.Context, req *pb.Request) bool { + checks.Add(1) + return check(ctx, req) + } + apply := make(chan struct{}) + var releaseApply sync.Once + unblock := func() { releaseApply.Do(func() { close(apply) }) } + t.Cleanup(unblock) + entered := make(chan struct{}, 8) + var mu sync.Mutex + index := uint64(1) + proxy.tm.proposer = casCatalogProposer(func(ctx context.Context, payload []byte) (*raftengine.ProposalResult, error) { + proposals.Add(1) + entered <- struct{}{} + select { + case <-apply: + case <-ctx.Done(): + return nil, ctx.Err() + } + mu.Lock() + defer mu.Unlock() + index++ + f.SetApplyIndex(index) + return &raftengine.ProposalResult{CommitIndex: index, Response: f.Apply(payload)}, nil + }) + results := make(chan error, 8) + commit := func() { + req := casApplyRequest(15, 20, 10, "key", "after") + req.ObservedRouteVersion = 0 + _, err := group.ForwardTransaction(1).Commit(ctx, []*pb.Request{req}) + results <- err + } + go func() { + req := casApplyRequest(0, 0, 10, "key", "after") + req.ObservedRouteVersion = 0 + _, err := proxy.commitWithLocalStamp(ctx, []*pb.Request{req}, func(_ context.Context, requests []*pb.Request) (uint64, error) { + requests[0].Ts = 15 + requests[0].Mutations[0].Value = EncodeTxnMeta(TxnMeta{PrimaryKey: []byte("key"), CommitTS: 20}) + return 20, nil + }) + results <- err + }() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + for range 7 { + go commit() + } + require.Eventually(t, func() bool { return checks.Load() >= 8 }, 5*time.Second, time.Millisecond) + require.EqualValues(t, 1, proposals.Load()) + unblock() + successes := 0 + for range 8 { + err := <-results + if err == nil { + successes++ + } else { + require.True(t, IsCertifiedCASPrecheckMismatch(err), "%v", err) + } + } + require.Equal(t, 1, successes) + require.EqualValues(t, 1, proposals.Load(), "losers do not persist rejected entries") + requireCASProgress(t, f, 2) + row, err := store.GetVersionAt(t.Context(), st, []byte("key"), 30) + require.NoError(t, err) + require.EqualValues(t, 20, row.TS) +} + +type casGateForwardServer struct { + pb.UnimplementedInternalServer + gate *casProposalGate + closed chan struct{} +} + +func (s *casGateForwardServer) ForwardCompareAndSwapV2(ctx context.Context, req *pb.ForwardRequest) (*pb.ForwardResponse, error) { + key := req.GetRequests()[0].GetMutations()[1].GetKey() + release, err := s.gate.acquire(ctx, s.closed, sha256.Sum256(key), func() bool { return false }) + if err != nil { + return nil, err + } + defer release() + return &pb.ForwardResponse{Success: true, CommitIndex: 2, CommitTs: 20}, nil +} + +func TestCASProposalGateReleasesBeforeLeadershipRetry(t *testing.T) { + gate := newCASProposalGate(4) + server := &casGateForwardServer{gate: gate, closed: make(chan struct{})} + address := grpctest.Serve(t, func(s *grpc.Server) { pb.RegisterInternalServer(s, server) }) + engine := newStubFollowerEngine(address) + engine.StateValue = raftengine.StateLeader + engine.StatusValue.State = raftengine.StateLeader + engine.VerifyErr = raftengine.ErrNotLeader + proxy := NewLeaderProxyWithEngine(engine, WithVersionCASAdmission(func(ctx context.Context) (context.Context, error) { return ctx, nil })) + t.Cleanup(func() { require.NoError(t, proxy.Close()) }) + proxy.tm.versionCASProposals = gate + proxy.tm.versionCASPrecheck = func(context.Context, *pb.Request) bool { return false } + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + req := casApplyRequest(0, 0, 10, "key", "after") + req.ObservedRouteVersion = 0 + resp, err := proxy.Commit(ctx, []*pb.Request{req}) + require.NoError(t, err, "a retry returning to this group must not wait on its caller's own lane") + require.EqualValues(t, 2, resp.CommitIndex) + require.Empty(t, gate.active) + require.Empty(t, gate.slots) +} diff --git a/kv/version_cas_proposal_gate_test.go b/kv/version_cas_proposal_gate_test.go new file mode 100644 index 000000000..47defc1df --- /dev/null +++ b/kv/version_cas_proposal_gate_test.go @@ -0,0 +1,78 @@ +package kv + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestCASProposalGateRechecksWaitingContenders(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + gate := newCASProposalGate(16) + closed := make(chan struct{}) + key := [32]byte{1} + release, err := gate.acquire(ctx, closed, key, func() bool { return false }) + require.NoError(t, err) + var head atomic.Uint64 + head.Store(10) + checked := make(chan struct{}, 16) + results := make(chan error, 7) + for range 7 { + go func() { + _, err := gate.acquire(ctx, closed, key, func() bool { + checked <- struct{}{} + return head.Load() != 10 + }) + results <- err + }() + } + for range 7 { + select { + case <-checked: + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } + require.Empty(t, results, "matching hints cannot create additional in-flight proposals for this key") + head.Store(20) + release() + release() + for range 7 { + select { + case err := <-results: + require.True(t, IsCertifiedCASPrecheckMismatch(err), "%v", err) + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } + require.Empty(t, gate.active) + require.Empty(t, gate.slots) +} + +func TestCASProposalGateBoundsAndIndependentKeys(t *testing.T) { + gate := newCASProposalGate(2) + closed := make(chan struct{}) + check := func() bool { return false } + first, err := gate.acquire(t.Context(), closed, [32]byte{1}, check) + require.NoError(t, err) + second, err := gate.acquire(t.Context(), closed, [32]byte{2}, check) + require.NoError(t, err, "unrelated keys keep their proposal concurrency") + _, err = gate.acquire(t.Context(), closed, [32]byte{3}, check) + require.ErrorIs(t, err, ErrVersionCASUnavailable) + require.False(t, IsCertifiedCASMismatch(err)) + first() + second() + ctx, cancel := context.WithCancel(t.Context()) + cancel() + _, err = gate.acquire(ctx, closed, [32]byte{1}, func() bool { t.Fatal("must not read after cancellation"); return true }) + require.ErrorIs(t, err, context.Canceled) + close(closed) + _, err = gate.acquire(t.Context(), closed, [32]byte{1}, check) + require.ErrorIs(t, err, errShuttingDown) + require.Empty(t, gate.active) + require.Empty(t, gate.slots) +} diff --git a/kv/version_cas_review_regression_test.go b/kv/version_cas_review_regression_test.go new file mode 100644 index 000000000..bbf6f4e13 --- /dev/null +++ b/kv/version_cas_review_regression_test.go @@ -0,0 +1,173 @@ +package kv + +import ( + "testing" + + "github.com/bootjp/elastickv/distribution" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func TestCASReplicasAgreeAcrossSameOwnerCatalogSplit(t *testing.T) { + request := casApplyRequest(15, 20, 10, "a", "after") + request.ObservedRouteVersion = EncodeObservedRouteVersion(2) + frame, err := marshalRaftCommand([]*pb.Request{request}) + require.NoError(t, err) + for _, replica := range []string{"up_to_date", "lagging"} { + t.Run(replica, func(t *testing.T) { + catalog := distribution.NewEngine() + require.NoError(t, catalog.ApplySnapshot(distribution.CatalogSnapshot{Version: 1, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}, + }})) + split := distribution.CatalogSnapshot{Version: 2, Routes: []distribution.RouteDescriptor{ + {RouteID: 1, GroupID: 1, End: []byte("m"), State: distribution.RouteStateActive}, + {RouteID: 2, GroupID: 1, Start: []byte("m"), State: distribution.RouteStateActive}, + }} + if replica == "up_to_date" { + require.NoError(t, catalog.ApplySnapshot(split)) + } + backing, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, backing.Close()) }) + f, policy := newCASCatalogFSM(t, backing, catalog) + applyCASCatalogRoutes(t, f, policy, 12, 5, split) + activateCommitTSFence(t, f) + f.SetApplyIndex(13) + require.Nil(t, f.Apply(EncodeMigrationVersionIdentityActivation())) + require.NoError(t, backing.PutAt(t.Context(), []byte("a"), []byte("before"), 10, 0)) + f.SetApplyIndex(14) + require.Nil(t, f.Apply(frame)) + requireCASProgress(t, f, 14) + if replica == "lagging" { + require.NoError(t, catalog.ApplySnapshot(split)) + f.SetApplyIndex(14) + require.Nil(t, f.Apply(frame)) + } + row, err := store.GetVersionAt(t.Context(), backing, []byte("a"), 30) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 20, Value: []byte("after")}, row) + }) + } +} + +func TestCASConsumedVersionStaysConsumedAfterBoundedCleanup(t *testing.T) { + dir := t.TempDir() + backing, err := store.NewPebbleStore(dir) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, backing.Close()) }) + f, ok := NewKvFSMWithHLC(backing, NewHLC()).(*kvFSM) + require.True(t, ok) + enableCASApplyForTest(t, f) + key := []byte("a") + require.NoError(t, backing.PutAt(t.Context(), key, []byte("before"), 10, 0)) + require.Nil(t, applyCASFrame(t, f, 2, casApplyRequest(15, 20, 10, "a", "first"))) + cleanup, err := MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{ + JobId: 7, Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, + RangeStart: key, RangeEnd: nextScanCursor(key), MaxCommitTs: 20, MaxVersions: 1, + }) + require.NoError(t, err) + f.SetApplyIndex(3) + cleaned := f.Apply(cleanup) + require.NoError(t, haltApplyOf(cleaned)) + requireCASRejection(t, cleaned, store.ErrMigrationOwnership) + requireCASProgress(t, f, 3) + beforeRetry, err := store.GetVersionAt(t.Context(), backing, key, 25) + require.NoError(t, err) + wantHead := store.VersionedValue{TS: 20, Value: []byte("first")} + require.Equal(t, wantHead, beforeRetry) + require.NoError(t, backing.Close()) + backing, err = store.NewPebbleStore(dir) + require.NoError(t, err) + f, ok = NewKvFSMWithHLC(backing, NewHLC()).(*kvFSM) + require.True(t, ok) + requireCASProgress(t, f, 3) + f.SetApplyIndex(3) + require.Nil(t, f.Apply(cleanup), "durable replay skips the decided cleanup") + verdict := applyCASFrame(t, f, 4, casApplyRequest(25, 30, 10, "a", "second")) + requireCASRejection(t, verdict, ErrCASMismatch) + requireCASProgress(t, f, 4) + afterRetry, err := store.GetVersionAt(t.Context(), backing, key, 35) + require.NoError(t, err) + require.Equal(t, wantHead, afterRetry) +} + +func TestCoveredCleanupAgreesAcrossReplicaRetention(t *testing.T) { + ctx := t.Context() + key := []byte("n") + frame, err := MarshalMigrationCleanupCommand(&pb.CleanupMigrationRequest{ + JobId: 11, Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, + RangeStart: key, RangeEnd: nextScanCursor(key), MaxCommitTs: 20, MaxVersions: 1, + RequireConfigurationIndex: true, ExpectedConfigurationIndex: 9, + ExpectedSourceGroupId: 1, + }) + require.NoError(t, err) + var heads []store.VersionedValue + for _, compact := range []bool{false, true} { + st, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + f := &kvFSM{store: st, shardGroupID: 1} + enableCASApplyForTest(t, f) + require.NoError(t, st.PutAt(ctx, key, []byte("old"), 10, 0)) + require.NoError(t, st.PutAt(ctx, key, []byte("current"), 20, 0)) + if compact { + require.NoError(t, st.Compact(ctx, 21)) + } + installSourceOwnershipForTest(t, f, 0) + before, err := store.GetVersionAt(ctx, st, key, 30) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 20, Value: []byte("current")}, before) + f.SetApplyIndex(12) + result, ok := f.Apply(frame).(store.CleanupVersionsResult) + require.True(t, ok) + require.Equal(t, uint64(1), result.DeletedRows, "cleanup must actually reclaim the head row") + requireCASProgress(t, f, 12) + after, err := store.GetVersionAt(ctx, st, key, 30) + require.ErrorIs(t, err, store.ErrKeyNotFound, "logical retirement must hide retained predecessors") + heads = append(heads, after) + } + require.Equal(t, heads[0], heads[1], "a protected cleanup must preserve agreement on the visible head") +} + +func TestCoveredCleanupRejectionsHaveNoRetirementOrPhysicalEffects(t *testing.T) { + ctx := t.Context() + st, err := store.NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + f := &kvFSM{store: st, shardGroupID: 1} + enableCASApplyForTest(t, f) + installSourceOwnershipForTest(t, f, 0) + key := []byte("n") + require.NoError(t, st.PutAt(ctx, key, []byte("old"), 10, 0)) + require.NoError(t, st.PutAt(ctx, key, []byte("head"), 20, 0)) + req := &pb.CleanupMigrationRequest{ + JobId: 11, Mode: pb.MigrationCleanupMode_MIGRATION_CLEANUP_MODE_VERSIONS, + RangeStart: key, RangeEnd: nextScanCursor(key), MaxCommitTs: 20, MaxVersions: 1, + RequireConfigurationIndex: true, ExpectedConfigurationIndex: 9, Cursor: []byte{0xff}, + ExpectedSourceGroupId: 1, + } + apply := func(index uint64) any { + frame, err := MarshalMigrationCleanupCommand(req) + require.NoError(t, err) + f.SetApplyIndex(index) + result := f.Apply(frame) + requireCASProgress(t, f, index) + return result + } + requireCASRejection(t, apply(12), store.ErrInvalidExportCursor) + before, err := store.GetVersionAt(ctx, st, key, 30) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 20, Value: []byte("head")}, before) + req.Cursor = nil + cleaned, ok := apply(13).(store.CleanupVersionsResult) + require.True(t, ok) + require.Equal(t, uint64(1), cleaned.DeletedRows) + require.NotEmpty(t, cleaned.RetirementID) + require.NoError(t, st.PutAt(ctx, key, []byte("newer"), 25, 0)) + req.MaxCommitTs = 30 + requireCASRejection(t, apply(14), store.ErrVersionRetirementConflict) + after, err := store.GetVersionAt(ctx, st, key, 40) + require.NoError(t, err) + require.Equal(t, store.VersionedValue{TS: 25, Value: []byte("newer")}, after) +} diff --git a/kv/version_cas_route.go b/kv/version_cas_route.go new file mode 100644 index 000000000..a1c70e673 --- /dev/null +++ b/kv/version_cas_route.go @@ -0,0 +1,165 @@ +package kv + +import ( + "bytes" + "context" + "math" + + "github.com/bootjp/elastickv/distribution" + "github.com/bootjp/elastickv/internal/raftbootstrap" + "github.com/bootjp/elastickv/store" + "github.com/cockroachdb/errors" +) + +// Only keys with a single byte-range owner participate in this rollout. +func versionCASDirectKey(key []byte) bool { + _, _, auxiliary := s3BucketAuxiliaryRouteRange(key) + return IsCASUserKey(key) && !auxiliary && legacyPointRouteKey(key) == nil && + bytes.Equal(key, routeKey(key)) && bytes.Equal(key, routeFilterKey(key)) +} + +func versionCASInitialRoute(route distribution.Route) bool { + return route.State == distribution.RouteStateActive && route.MinWriteTSExclusive == 0 && + !route.StagedVisibilityActive && route.MigrationJobID == 0 +} + +// versionCASCatalogRoute checks the catalog in this group's own store. The +// catalog's version and route records must belong to this group. A remote catalog +// observation cannot prove the ordering of changes in this group's log. +func versionCASCatalogRoute(ctx context.Context, st store.MVCCStore, groupID uint64, key []byte, readTS, minVersion uint64) (uint64, error) { + catalog, err := distribution.NewCatalogStore(st).SnapshotAt(ctx, readTS) + if err != nil { + return 0, errors.WithStack(err) + } + if catalog.Version == 0 || catalog.Version < minVersion { + return 0, errors.New("version CAS lacks an applied catalog at or above its admitted version") + } + routes, err := distribution.RouteSnapshotFromCatalog(catalog) + if err != nil { + return 0, errors.WithStack(err) + } + if !routes.OwnsCatalogRoutes(groupID) { + return 0, errors.New("version CAS group does not host the applied catalog") + } + route, ok := routes.RouteOf(key) + if !ok || route.GroupID != groupID || route.State == distribution.RouteStateWriteFenced { + return 0, errors.Wrap(ErrRouteWriteFenced, "applied catalog does not authorize writing the CAS key in this group") + } + if !versionCASInitialRoute(route) { + return 0, errors.Wrap(ErrVersionCASUnavailable, "applied catalog route has migration history or is inactive") + } + return catalog.Version, nil +} + +// admitVersionCASRoute is advisory. The indexed FSM checks the same group's +// catalog again before changing data. +func admitVersionCASRoute(ctx context.Context, st store.MVCCStore, groupID uint64, key []byte) (uint64, error) { + version, err := versionCASCatalogRoute(ctx, st, groupID, key, st.LastCommitTS(), 0) + if err != nil { + // No user proposal exists at this boundary. Keep the diagnostic text, + // not a secondary apply verdict which would describe another scope. + return 0, errors.Wrap(ErrVersionCASUnavailable, err.Error()) + } + return version, nil +} + +// checkAppliedVersionCASRoute uses the stage's indexed MVCC view. Reading at +// MaxUint64 includes any earlier staged catalog writes and needs no local HLC +// or follower watcher. +func (f *kvFSM) checkAppliedVersionCASRoute(ctx context.Context, groupID, version uint64, key []byte) error { + if groupID != f.shardGroupID { + return errors.Wrap(ErrRouteWriteFenced, "CAS frame is bound to a different data group") + } + if identity := f.NativeGroupIdentity(); identity.Group != groupID || identity.Cluster == (raftbootstrap.UUID{}) { + return errors.New("version CAS requires the native protected group identity") + } + _, err := versionCASCatalogRoute(ctx, f.store, groupID, key, math.MaxUint64, version) + return err +} + +// ResolveVersionCASGroupForKey finds a candidate in the watched catalog. +// Proposal admission independently verifies the receiving group's catalog. +func (s *ShardStore) ResolveVersionCASGroupForKey(key []byte) (uint64, error) { + route, _, ok := s.versionReadRoute(key, 0) + if !ok { + return 0, errors.Wrap(ErrVersionCASUnavailable, "route has migration history or is unavailable") + } + return route.GroupID, nil +} + +// CheckVersionCASForwardRoute verifies the fixed receiver independently of +// its watcher. Partition-routed keys are outside standalone CAS. +func (s *ShardStore) CheckVersionCASForwardRoute(ctx context.Context, groupID uint64, key []byte) error { + if _, partitioned, err := s.partitionOwner(key); partitioned || err != nil || !versionCASDirectKey(key) { + return errors.Wrap(ErrVersionCASUnavailable, "key requires alternate routing") + } + group, ok := s.groupForID(groupID) + if !ok || group == nil || group.Store == nil { + return errors.Wrap(ErrVersionCASUnavailable, "CAS receiver group is unavailable") + } + _, err := admitVersionCASRoute(ctx, group.Store, groupID, key) + return err +} + +// Check the local Raft-owned guard as well as the catalog route. In particular, +// a source with a stale catalog must stop admitting tokens and CAS once it +// applies a migration guard. Completed moves retain durable ownership +// evidence, and their catalog write floor is preserved through later splits. +// Exclude the entire range, including versions above that floor. +func checkVersionCASMigrationRange(ctx context.Context, st store.MVCCStore, key []byte) error { + if !versionCASDirectKey(key) { + return errors.Wrap(ErrVersionCASUnavailable, "key requires alternate routing") + } + view, err := readMigrationServingState(ctx, st) + if err != nil { + return errors.WithStack(err) + } + if migrationApplyIntersects(view, []migrationApplyRange{{key, nextScanCursor(key)}}) { + return errors.Wrap(ErrVersionCASUnavailable, "range has migration ownership or readiness state") + } + return nil +} + +// ConfigureVersionReadAdmission installs the protected group runtime's +// admission check before the group starts serving RPCs. +func (g *ShardGroup) ConfigureVersionReadAdmission(check func(context.Context) error) { + g.versionReadAdmission = check +} + +func readVersionOnInitialRoute(ctx context.Context, g *ShardGroup, route distribution.Route, key []byte, ts uint64) (store.VersionedValue, error) { + if !versionCASInitialRoute(route) { + return store.VersionedValue{}, store.ErrNotSupported + } + version, err := admitVersionCASRoute(ctx, g.Store, route.GroupID, key) + if err != nil { + return store.VersionedValue{}, err + } + if err := checkVersionCASMigrationRange(ctx, g.Store, key); err != nil { + return store.VersionedValue{}, err + } + if err := g.versionReadAdmission(ctx); err != nil { + return store.VersionedValue{}, err + } + record, err := store.GetVersionAt(ctx, g.Store, key, ts) + if err != nil && !errors.Is(err, store.ErrKeyNotFound) { + return store.VersionedValue{}, errors.WithStack(err) + } + if err := recheckVersionReadRoute(ctx, g.Store, route.GroupID, key, version); err != nil { + return store.VersionedValue{}, err + } + if err := checkVersionCASMigrationRange(ctx, g.Store, key); err != nil { + return store.VersionedValue{}, err + } + return record, errors.WithStack(err) +} + +func recheckVersionReadRoute(ctx context.Context, st store.MVCCStore, groupID uint64, key []byte, version uint64) error { + current, err := distribution.NewCatalogStore(st).Version(ctx) + if err != nil { + return errors.WithStack(err) + } + if current != version { + _, err = admitVersionCASRoute(ctx, st, groupID, key) + } + return err +} diff --git a/kv/versioned_point_read_test.go b/kv/versioned_point_read_test.go new file mode 100644 index 000000000..a6de086e1 --- /dev/null +++ b/kv/versioned_point_read_test.go @@ -0,0 +1,103 @@ +package kv + +import ( + "context" + "testing" + + "github.com/bootjp/elastickv/distribution" + pb "github.com/bootjp/elastickv/proto" + "github.com/bootjp/elastickv/store" + "github.com/stretchr/testify/require" +) + +func TestVersionedPointReadForwarding(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + resp *pb.RawGetResponse + want store.VersionedValue + err error + }{ + { + name: "empty live value", + resp: &pb.RawGetResponse{Exists: true, Version: &pb.RawGetResponse_CommitTs{CommitTs: 7}}, + want: store.VersionedValue{TS: 7}, + }, + { + name: "explicit missing", + resp: &pb.RawGetResponse{Version: &pb.RawGetResponse_Missing{Missing: true}}, + err: store.ErrKeyNotFound, + }, + { + name: "old server reports live value", + resp: &pb.RawGetResponse{Value: []byte("legacy"), Exists: true}, + err: store.ErrNotSupported, + }, + { + name: "old server reports missing", + resp: &pb.RawGetResponse{}, + err: store.ErrNotSupported, + }, + } { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeRawKVServer{getResp: tc.resp} + addr := startRawKVServer(t, fake) + key := []byte("key") + const snapshot = uint64(10) + const routeVersion = uint64(100) + routed := NewLeaderRoutedStore(store.NewMVCCStore(), &stubLeaderCoordinator{leader: addr}) + t.Cleanup(func() { require.NoError(t, routed.Close()) }) + got, err := routed.GetVersionAtWithReadFence(t.Context(), key, snapshot, 0, routeVersion) + require.ErrorIs(t, err, tc.err) + require.Equal(t, tc.want, got) + checkForwardedVersionRequest(t, fake, 0, snapshot, routeVersion, key) + + engine := distribution.NewEngine() + require.NoError(t, engine.ApplySnapshot(distribution.CatalogSnapshot{ + Version: routeVersion, + Routes: []distribution.RouteDescriptor{{RouteID: 1, GroupID: 1, State: distribution.RouteStateActive}}, + })) + group := &ShardGroup{Store: store.NewMVCCStore(), Engine: newStubFollowerEngine(addr)} + t.Cleanup(func() { require.NoError(t, group.Store.Close()) }) + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + shards := NewShardStore(engine, map[uint64]*ShardGroup{1: group}) + t.Cleanup(func() { require.NoError(t, shards.Close()) }) + got, err = shards.GetVersionAt(t.Context(), key, snapshot) + require.ErrorIs(t, err, tc.err) + require.Equal(t, tc.want, got) + checkForwardedVersionRequest(t, fake, 1, snapshot, routeVersion, key) + + fake.mu.Lock() + defer fake.mu.Unlock() + require.Equal(t, 2, fake.getCalls) + require.Zero(t, fake.latestCalls) + }) + } +} + +func checkForwardedVersionRequest(t *testing.T, fake *fakeRawKVServer, groupID, snapshot, routeVersion uint64, key []byte) { + t.Helper() + fake.mu.Lock() + defer fake.mu.Unlock() + req := fake.lastGetReq + require.True(t, req.GetNeedCommitTs()) + require.Equal(t, groupID, req.GetGroupId()) + require.Equal(t, snapshot, req.GetTs()) + require.Equal(t, routeVersion, req.GetReadRouteVersion()) + require.Equal(t, key, req.GetKey()) +} + +func TestVersionedPointReadWithStagedVisibilityIsUnsupported(t *testing.T) { + t.Parallel() + st, group := newStagedVisibilityShardStore(t) + group.ConfigureVersionReadAdmission(func(context.Context) error { return nil }) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + key := []byte("k") + require.NoError(t, group.Store.PutAt(t.Context(), distribution.MigrationStagedDataKey(9, key), []byte("staged"), 20, 0)) + + value, err := st.GetAt(t.Context(), key, 25) + require.NoError(t, err) + require.Equal(t, []byte("staged"), value) + _, err = st.GetVersionAt(t.Context(), key, 25) + require.ErrorIs(t, err, store.ErrNotSupported) +} diff --git a/lean/LogicalRetirement.lean b/lean/LogicalRetirement.lean new file mode 100644 index 000000000..83826af2d --- /dev/null +++ b/lean/LogicalRetirement.lean @@ -0,0 +1,79 @@ +import Std + +/-! Safety obligations for the proposed retirement protocol, not a proof of +the current physical-only Go cleanup. Physical histories may differ. -/ +namespace LogicalRetirement + +structure Row where + version : Nat + value : Nat + deriving DecidableEq, Repr + +def visibleRows (ceiling : Nat) (rows : List Row) : List Row := + rows.filter (fun row => ceiling < row.version) + +def visible (ceiling : Nat) (rows : List Row) : Option Row := + (visibleRows ceiling rows).head? + +def reclaim (rows selected : List Row) : List Row := + rows.filter (fun row => row โˆ‰ selected) + +-- Physical collection can remove any subset of retired rows. In particular, +-- two replicas need not select the same rows or have the same deletion count. +theorem reclaim_preserves_visible_rows (rows selected : List Row) (ceiling : Nat) + (retired : โˆ€ row โˆˆ selected, row.version โ‰ค ceiling) : + visibleRows ceiling (reclaim rows selected) = visibleRows ceiling rows := by + induction rows with + | nil => rfl + | cons row tail ih => + by_cases selectedRow : row โˆˆ selected + ยท have hidden : ยฌ ceiling < row.version := Nat.not_lt_of_ge (retired row selectedRow) + simpa [visibleRows, reclaim, selectedRow, hidden] using ih + ยท by_cases live : ceiling < row.version + ยท simpa [visibleRows, reclaim, selectedRow, live] using congrArg (List.cons row) ih + ยท simpa [visibleRows, reclaim, selectedRow, live] using ih + +theorem reclaim_preserves_visible (rows selected : List Row) (ceiling : Nat) + (retired : โˆ€ row โˆˆ selected, row.version โ‰ค ceiling) : + visible ceiling (reclaim rows selected) = visible ceiling rows := by + simp only [visible, reclaim_preserves_visible_rows rows selected ceiling retired] + +theorem retired_rows_are_absent (rows : List Row) (ceiling : Nat) + (bounded : โˆ€ row โˆˆ rows, row.version โ‰ค ceiling) : visibleRows ceiling rows = [] := by + induction rows with + | nil => rfl + | cons row tail ih => + have hidden : ยฌ ceiling < row.version := Nat.not_lt_of_ge (bounded row (by simp)) + have rest : โˆ€ r โˆˆ tail, r.version โ‰ค ceiling := fun r hr => bounded r (by simp [hr]) + simpa [visibleRows, hidden] using ih rest + +-- Replicating the retirement ceiling makes the visible result independent of +-- which older rows local compaction happened to retain before retirement. +theorem retired_replicas_agree (left right : List Row) (ceiling : Nat) + (leftBound : โˆ€ row โˆˆ left, row.version โ‰ค ceiling) + (rightBound : โˆ€ row โˆˆ right, row.version โ‰ค ceiling) : + visible ceiling left = visible ceiling right := by + simp [visible, retired_rows_are_absent left ceiling leftBound, + retired_rows_are_absent right ceiling rightBound] + +-- The ceiling does not hide a newer generation's write. +theorem newer_write_is_visible (rows : List Row) (ceiling : Nat) (row : Row) + (fresh : ceiling < row.version) : visible ceiling (row :: rows) = some row := by + simp [visible, visibleRows, fresh] + +private def head : Row := โŸจ20, 2โŸฉ +private def old : Row := โŸจ10, 1โŸฉ + +-- Negative control: deleting the common head alone resurrects a predecessor +-- only on the replica that retained it. +example : ([head, old] : List Row).head? = [head].head? โˆง + (reclaim [head, old] [head]).head? โ‰  (reclaim [head] [head]).head? := by decide + +-- Logical retirement precedes any physical page. Both replicas already agree +-- while one has reclaimed nothing and the other has reclaimed every row. +example : visible 20 [head, old] = none โˆง visible 20 (reclaim [head] [head]) = none := by + decide + +example : visible 20 (reclaim [โŸจ30, 3โŸฉ, head, old] [head]) = some โŸจ30, 3โŸฉ := by decide + +end LogicalRetirement diff --git a/lean/OwnedSnapshot.lean b/lean/OwnedSnapshot.lean new file mode 100644 index 000000000..91c5711bd --- /dev/null +++ b/lean/OwnedSnapshot.lean @@ -0,0 +1,1103 @@ +import Std + +/-! +# Local Raft owner snapshot (#1535) + +Logical protocol for the optional raftengine.OwnerSnapshotCapturer method +`CaptureOwnerSnapshot() (Snapshot, error)`, with KV wrapping the store-owned +handle on the synchronous, file-backed owner. Public Snapshot, BackedTSO, async +apply, received-snapshot durability and the wire format are outside this system. + +Assumptions to discharge in Go: the serialized owner pins an immutable Pebble +view and table format between entries together with the KV header, cutover and +ConfState for the owner's Raft index. Manifest.index is that Raft index. +Manifest.metadata is opaque pinned Pebble metadata: a no-op or configuration +entry can advance the former without changing the latter. Capturing a value +below denotes taking that handle, not enumerating +or copying a DB. The worker reads the immutable view. The engine retains the +unique request identity across dequeue. Tickets and the monotone serial are +logical names (e.g. pointer identity plus a retired bit in Go). Presenting +an obsolete request to the worker is allowed. Mutex acquisition, single ownership, +stop admission and worker join linearize at the transitions below. + +On disk, the addressed file is protected against external replacement/deletion, +rename is atomic, successful syncs are truthful, and recovery validates the +complete file/token pair. Cut equality models a matching payload and metadata, +not collision resistance of CRC32C. A file's Cut is a logical provenance label: +ConfState goes into Raft metadata and the token identifies the indexed CRC'd +file. This representation adds no fields to the file or token. +Raft recovery selects a whole old or new +SaveSnap record. The WAL suffix above the release floor is retained. The map +tracks recovery-relevant complete files, not temp names or orphan cleanup. +Disk.raft is the local publication record; receivedIndex abstracts the external +restore path's index check. Disk.applied is a lower bound established by the +local snapshot bump; it is independent of metadata inside an older pin. +An error after an ambiguous SaveSnap can keep either record. Recovery observes +a process crash at any boundary; it does not resume the old worker. + +As in RaftWALMetadata, one data batch installs rows and metadata atomically, +and successful sync precedes ACK. Here successful apply+sync is one foreground +transition; the earlier visibility and ambiguous batch-sync cases belong to +that model. syncWAL advances the durable extent of the fixed committed Raft +log independently of FSM sync and ACK. It counts durable entry bytes, not a +separately fsynced commit-only HardState. It omits unstable/uncommitted tails. +Recovery can read every entry above the +release floor through this extent. An ACK identifies its entry, hence all +operations of its atomic batch. A prefix represents their effects under +deterministic replay, including overwrites and deletes. This is not machine +extraction or a proof of arbitrary Go, OS, +whole distributed transactions, fairness, physical resource release on error, +or performance. + +The Write transitions follow writeFSMSnapshotPayload/writeFSMSnapshotFile in +fsm_snapshot_file.go. The dirSync, closePin and bump boundaries follow +persistLocalSnapshot and persistLocalSnapshotPayloadLocked in engine.go. +The save/create/compact/release transitions follow persistCapturedLocalSnapshot +and publishLocalSnapshot in wal_store.go and the subsequent disk-phase purge. +etcd Storage.SaveSnap writes the .snap file then WAL.SaveSnapshot; startup's +loadPersistedSnapshot selects LoadNewestAvailable among ValidSnapshotEntries. +An orphan .snap alone therefore cannot choose the new recovery prefix. +purgeOldWALFiles skips segments whose locks ReleaseLockTo has retained. + +For the foreground path, Engine.drainReady calls persistReady before +applyAndDispatchReady. WAL.Save requires sync for new entries. A later +commit-only Ready can refer to entries already on disk. Under the default +synchronous Pebble mode, the indexed batch commits before publishNormalApply +resolves the proposal. These are lower-layer contracts of the local model. +-/ +namespace OwnedSnapshot + +structure Manifest where + index : Nat + metadata : Nat + header : Nat + confState : Nat + cutover : Nat + tableFormat : Nat + deriving DecidableEq, Inhabited + +structure Cut where + manifest : Manifest + rows : List Nat + deriving DecidableEq, Inhabited + +abbrev Cut.index (c : Cut) := c.manifest.index + +structure Pin where + ticket : Nat + dbGeneration : Nat + cut : Cut + deriving DecidableEq + +inductive Seal | crc | flushed | synced | closed | renamed + deriving DecidableEq + +inductive Buffer + | temp + | manifest (m : Manifest) + | bytes (stage : Seal) (image : Cut) + deriving DecidableEq + +/-- WriteTo can sample the metadata and rows on opposite sides of a foreground apply. -/ +inductive Write (p : Pin) : Buffer โ†’ Buffer โ†’ Prop + | metadata : Write p .temp (.manifest p.cut.manifest) + | rowsCRC : Write p (.manifest m) (.bytes .crc โŸจm, p.cut.rowsโŸฉ) + | flush : Write p (.bytes .crc c) (.bytes .flushed c) + | syncFile : Write p (.bytes .flushed c) (.bytes .synced c) + | closeFile : Write p (.bytes .synced c) (.bytes .closed c) + | rename : Write p (.bytes .closed c) (.bytes .renamed c) + +def Buffer.matches (p : Pin) : Buffer โ†’ Prop + | .temp => True + | .manifest m => m = p.cut.manifest + | .bytes _ c => c = p.cut + +theorem write_preserves_cut (h : Write p b b') (ok : b.matches p) : b'.matches p := by + cases h <;> simp_all [Buffer.matches] + +structure Disk where + file : Nat โ†’ Option Cut + raft : Cut + memory : Cut + applied : Nat + floor : Nat + +def Disk.install (d : Disk) (c : Cut) : Disk := + { d with file := fun i => if i = c.index then some c else d.file i } + +def Disk.bump (d : Disk) (c : Cut) : Disk := { d with applied := max d.applied c.index } +def Disk.save (d : Disk) (c : Cut) : Disk := { d with raft := c } +def Disk.publish (d : Disk) (c : Cut) : Disk := { d with memory := c } +def Disk.release (d : Disk) (c : Cut) : Disk := { d with floor := c.index } + +structure Disk.Safe (d : Disk) : Prop where + raftFile : d.file d.raft.index = some d.raft + memoryFile : d.file d.memory.index = some d.memory + retained : d.floor โ‰ค d.memory.index + ordered : d.memory.index โ‰ค d.raft.index + synced : d.raft.index โ‰ค d.applied + +section +variable {d : Disk} {c : Cut} + +theorem Disk.install_safe (h : d.Safe) (fresh : d.raft.index < c.index) : + (d.install c).Safe := by + have older := Nat.lt_of_le_of_lt h.ordered fresh + exact โŸจby simpa [Disk.install, Nat.ne_of_lt fresh] using h.raftFile, + by simpa [Disk.install, Nat.ne_of_lt older] using h.memoryFile, + h.retained, h.ordered, h.syncedโŸฉ + +theorem Disk.bump_safe (h : d.Safe) : (d.bump c).Safe := + { h with synced := Nat.le_trans h.synced (Nat.le_max_left ..) } + +theorem Disk.save_safe (h : d.Safe) (fresh : d.raft.index < c.index) + (file : d.file c.index = some c) (bumped : c.index โ‰ค d.applied) : (d.save c).Safe := + โŸจfile, h.memoryFile, h.retained, Nat.le_trans h.ordered (Nat.le_of_lt fresh), bumpedโŸฉ + +theorem Disk.publish_safe (h : d.Safe) (saved : d.raft = c) : (d.publish c).Safe := by + subst c + exact โŸจh.raftFile, h.raftFile, Nat.le_trans h.retained h.ordered, Nat.le_refl _, h.syncedโŸฉ + +end + +inductive Reason | restore | shutdown + deriving DecidableEq +inductive Place | queued | dequeued + deriving DecidableEq +inductive Publication | pinClosed | bumped | saving | saved | created | compacted + deriving DecidableEq +inductive Phase + | idle + | pending (place : Place) (p : Pin) + | worker (p : Pin) (b : Buffer) + | exported (p : Pin) + | publishing (p : Pin) (stage : Publication) + | retired (reason : Reason) (p : Pin) + | exclusive (reason : Reason) + | swapped + | closeError + | ioError + | storeClosed + deriving DecidableEq + +inductive Lock | free | worker | restore | shutdown + deriving DecidableEq + +def Phase.lock : Phase โ†’ Lock + | .worker .. | .exported _ | .publishing .. => .worker + | .retired .restore _ | .exclusive .restore | .swapped => .restore + | .retired .shutdown _ | .exclusive .shutdown => .shutdown + | _ => .free + +def Phase.foreground : Phase โ†’ Bool + | .idle | .pending .. | .worker .. | .exported _ | .publishing .. => true + | _ => false + +/-- A callback may still hold the dequeued request after retirement. Compare +its identity with the engine slot under snapshotMu before using the handle. -/ +def Phase.claimable : Phase โ†’ Option Nat + | .pending .dequeued p => some p.ticket + | _ => none + +structure Tx where + currentDB : Cut + pendingAck : Option Nat + lastAck : Option Nat + +structure State where + disk : Disk + tx : Tx + generation : Nat + serial : Nat + issued : Nat + attempts : Nat + released : Nat + stopping : Bool + receivedIndex : Nat + walEnd : Nat + acked : List Nat + +def State.pin (s : State) : Pin := โŸจs.serial + 1, s.generation, s.tx.currentDBโŸฉ +def State.issue (s : State) : State := + { s with issued := s.issued + 1, serial := s.serial + 1 } +def State.invalidate (s : State) : State := { s with serial := s.serial + 1 } +def State.closeOK (s : State) : State := + { s with attempts := s.attempts + 1, released := s.released + 1 } +def State.closeFailed (s : State) : State := { s with attempts := s.attempts + 1 } +def State.withDisk (s : State) (d : Disk) : State := { s with disk := d } + +inductive Event + | capture (p : Pin) | dequeue | claim (ticket : Nat) | skipStale (ticket : Nat) + | write (ticket : Nat) | dirSync (ticket : Nat) + | closePin | closeError | bump | beginSave | save (ticket : Nat) | create (ticket : Nat) + | compact | release (ticket : Nat) | abort | saveError + | stop | retire (reason : Reason) | enter (reason : Reason) + | swap | restoreOK | restoreError | closeStore | syncWAL (through : Nat) + | applyBatch (next : Cut) | nonData (next : Cut) | ack (index : Nat) + deriving DecidableEq + +/-- The stop flag is set before join. Entry for shutdown denotes join returning: +an already claimed worker must leave its critical section first. A dequeued but +unclaimed request remains addressable in the pending slot. -/ +def mayEnter (s : State) : Reason โ†’ Prop + | .restore => s.stopping = false + | .shutdown => s.stopping = true + +inductive Step : Phase โ†’ State โ†’ Event โ†’ Phase โ†’ State โ†’ Prop + | capture (running : s.stopping = false) : + Step .idle s (.capture s.pin) (.pending .queued s.pin) s.issue + | dequeue : Step (.pending .queued p) s .dequeue (.pending .dequeued p) s + | claim (running : s.stopping = false) (fresh : s.disk.memory.index < p.cut.index) + (received : s.receivedIndex < p.cut.index) : + Step (.pending .dequeued p) s (.claim p.ticket) (.worker p .temp) s + | skipStale (available : q.lock = .free) (running : q.foreground = true) + (obsolete : q.claimable โ‰  some ticket) : Step q s (.skipStale ticket) q s + | write (h : Write p b b') : Step (.worker p b) s (.write p.ticket) (.worker p b') s + | dirSync : Step (.worker p (.bytes .renamed c)) s (.dirSync p.ticket) + (.exported p) (s.withDisk (s.disk.install c)) + | closePin : Step (.exported p) s .closePin (.publishing p .pinClosed) s.closeOK + | bump : Step (.publishing p .pinClosed) s .bump (.publishing p .bumped) + (s.withDisk (s.disk.bump p.cut)) + | beginSave : Step (.publishing p .bumped) s .beginSave (.publishing p .saving) s + | save : Step (.publishing p .saving) s (.save p.ticket) (.publishing p .saved) + (s.withDisk (s.disk.save p.cut)) + | create : Step (.publishing p .saved) s (.create p.ticket) (.publishing p .created) + (s.withDisk (s.disk.publish p.cut)) + | compact : Step (.publishing p .created) s .compact (.publishing p .compacted) s + -- Release authorizes the subsequent best-effort WAL purge of this prefix. + | release : Step (.publishing p .compacted) s (.release p.ticket) .idle + (s.withDisk (s.disk.release p.cut)) + | stop : Step q s .stop q { s with stopping := true } + | retire (enter : mayEnter s reason) : Step (.pending place p) s (.retire reason) + (.retired reason p) s.invalidate + | enter (allowed : mayEnter s reason) : Step .idle s (.enter reason) (.exclusive reason) s + | joinAfterIOError (stopped : s.stopping = true) : + Step .ioError s (.enter .shutdown) (.exclusive .shutdown) s + | drain : Step (.retired reason p) s .closePin (.exclusive reason) s.closeOK + | swap (replacement : Cut) : Step (.exclusive .restore) s .swap .swapped + { s with generation := s.generation + 1, + tx := { s.tx with currentDB := replacement, pendingAck := none } } + | restoreOK : Step .swapped s .restoreOK .idle + { s with receivedIndex := s.tx.currentDB.index } + -- Permit subsequent work even on this error to test invalidation independently + -- of any terminal admission fence. Neither failure advances the Raft index. + | restoreErrorEarly : Step (.exclusive .restore) s .restoreError .idle s + | restoreErrorLate : Step .swapped s .restoreError .idle s + | closeStore : Step (.exclusive .shutdown) s .closeStore .storeClosed s + -- A stale/preparation/stream error still consumes the pin. An unsuccessful + -- Close records an attempt only and is terminal for resource-sensitive work. + | discard : Step (.pending place p) s .abort .idle s.closeOK + | writeError : Step (.worker p b) s .abort .ioError s.closeOK + | pendingCloseError : Step (.pending place p) s .closeError .closeError s.closeFailed + | workerCloseError : Step (.worker p b) s .closeError .closeError s.closeFailed + | exportCloseError : Step (.exported p) s .closeError .closeError s.closeFailed + | drainCloseError : Step (.retired reason p) s .closeError .closeError s.closeFailed + | persistError : Step (.publishing p stage) s .abort .ioError s + | saveErrorOld : Step (.publishing p .saving) s .saveError .ioError s + | saveErrorNew : Step (.publishing p .saving) s .saveError .ioError + (s.withDisk (s.disk.save p.cut)) + | syncWAL (through : Nat) (openOwner : q.foreground = true) : Step q s (.syncWAL through) q + { s with walEnd := max s.walEnd through } + | applyBatch (openDB : q.foreground = true) (running : s.stopping = false) + (ready : s.tx.pendingAck = none) (fresh : s.tx.currentDB.index < next.index) + (persisted : next.index โ‰ค s.walEnd) : + Step q s (.applyBatch next) q { s with tx := โŸจnext, some next.index, s.tx.lastAckโŸฉ } + | nonData (openDB : q.foreground = true) (running : s.stopping = false) + (ready : s.tx.pendingAck = none) (fresh : s.tx.currentDB.index < next.index) + (persisted : next.index โ‰ค s.walEnd) (rows : next.rows = s.tx.currentDB.rows) + (metadata : next.manifest.metadata = s.tx.currentDB.manifest.metadata) : + Step q s (.nonData next) q { s with tx := { s.tx with currentDB := next } } + | ack (openDB : q.foreground = true) (synced : s.tx.pendingAck = some i) : + Step q s (.ack i) q { s with + tx := { s.tx with pendingAck := none, lastAck := some i }, acked := i :: s.acked } + +def Phase.owed : Phase โ†’ Nat + | .pending .. | .worker .. | .exported _ | .retired .. => 1 + | _ => 0 + +def Phase.errors : Phase โ†’ Nat + | .closeError => 1 + | _ => 0 + +def Phase.identity (serial gen : Nat) : Phase โ†’ Prop + | .pending _ p | .worker p _ | .exported p | .publishing p _ => + p.ticket = serial โˆง p.dbGeneration = gen + | .retired _ p => p.ticket < serial โˆง p.dbGeneration = gen + | _ => True + +def Lifetime (q : Phase) (s : State) : Prop := + s.issued = s.attempts + q.owed โˆง s.attempts = s.released + q.errors โˆง + q.identity s.serial s.generation + +theorem lifetime_step (h : Step q s e q' s') (ok : Lifetime q s) : Lifetime q' s' := by + cases h <;> + simp_all [Lifetime, Phase.owed, Phase.errors, Phase.identity, State.issue, State.pin, + State.invalidate, State.closeOK, State.closeFailed, State.withDisk, Nat.add_assoc] + +/-- The pre-SaveSnap candidate must be newer than *both* published indices. +Only a completed candidate needs a durable file; old metadata stays usable +while a temp is being written or a newer final file has no Raft record yet. -/ +def Pipeline (q : Phase) (d : Disk) : Prop := + match q with + | .worker p b => d.raft.index < p.cut.index โˆง b.matches p + | .exported p | .publishing p .pinClosed => + d.raft.index < p.cut.index โˆง d.file p.cut.index = some p.cut + | .publishing p .bumped | .publishing p .saving => + d.raft.index < p.cut.index โˆง d.file p.cut.index = some p.cut โˆง p.cut.index โ‰ค d.applied + | .publishing p .saved => d.raft = p.cut + | .publishing p .created | .publishing p .compacted => d.raft = p.cut โˆง d.memory = p.cut + | .ioError | .closeError | .exclusive .shutdown | .storeClosed => True + | _ => d.memory = d.raft + +theorem pipeline_step (h : Step q s e q' s') (ok : Pipeline q s.disk) : + Pipeline q' s'.disk := by + cases h <;> simp_all [Pipeline, State.issue, State.invalidate, State.closeOK, + State.withDisk, Disk.install, Disk.bump, Disk.save, + Disk.publish, Disk.release, Buffer.matches, Nat.le_max_right] + case write w => exact write_preserves_cut w ok.2 + case drain => cases โ€นReasonโ€บ <;> trivial + case enter => cases โ€นReasonโ€บ <;> trivial + +theorem disk_step (h : Step q s e q' s') (ok : Pipeline q s.disk) (safe : s.disk.Safe) : + s'.disk.Safe := by + cases h <;> first | exact safe | skip + case dirSync => + obtain โŸจfresh, sameโŸฉ := ok + change _ = _ at same + exact Disk.install_safe safe (same.symm โ–ธ fresh) + case bump => exact Disk.bump_safe safe + case save => exact Disk.save_safe safe ok.1 ok.2.1 ok.2.2 + case create => exact Disk.publish_safe safe ok + case release p => + exact { safe with retained := by change p.cut.index โ‰ค s.disk.memory.index; simp [ok.2] } + case saveErrorNew => exact Disk.save_safe safe ok.1 ok.2.1 ok.2.2 + +def initial (base : Cut) : State := + { disk := โŸจfun i => if i = base.index then some base else none, + base, base, base.index, base.indexโŸฉ + tx := โŸจbase, none, noneโŸฉ + generation := 0, serial := 0, issued := 0, attempts := 0, released := 0 + stopping := false, receivedIndex := base.index, walEnd := base.index, acked := [] } + +inductive Reachable : Phase โ†’ State โ†’ Prop + | boot (base : Cut) : Reachable .idle (initial base) + | step : Reachable q s โ†’ Step q s e q' s' โ†’ Reachable q' s' + +structure Invariant (q : Phase) (s : State) : Prop where + lifetime : Lifetime q s + pipeline : Pipeline q s.disk + storage : s.disk.Safe + ackIndex : โˆ€ i, s.tx.pendingAck = some i โ†’ s.tx.currentDB.index = i + +theorem invariant_step (h : Step q s e q' s') (ok : Invariant q s) : Invariant q' s' := by + refine โŸจlifetime_step h ok.lifetime, pipeline_step h ok.pipeline, + disk_step h ok.pipeline ok.storage, ?_โŸฉ + have old := ok.ackIndex + cases h <;> first | exact old | simp + case nonData ready _ _ _ _ => simp [ready] + +theorem reachable_safe (r : Reachable q s) : Invariant q s := by + induction r with + | boot base => + refine โŸจby simp [Lifetime, Phase.owed, Phase.errors, Phase.identity, initial], + rfl, โŸจ?_, ?_, ?_, ?_, ?_โŸฉ, ?_โŸฉ <;> simp [initial] + | step _ h ih => exact invariant_step h ih + +/-- Snoc traces allow induction at the publication boundary. -/ +inductive Run : Phase โ†’ State โ†’ List Event โ†’ Phase โ†’ State โ†’ Prop + | nil : Run q s [] q s + | snoc : Run q s es r t โ†’ Step r t e q' s' โ†’ Run q s (es ++ [e]) q' s' + +theorem Run.reachable (run : Run q s es q' s') (start : Reachable q s) : Reachable q' s' := by + induction run with + | nil => exact start + | snoc _ h ih => exact .step ih h + +def Phase.job : Phase โ†’ Option Pin + | .pending _ p | .worker p _ | .exported p | .publishing p _ | .retired _ p => some p + | _ => none + +theorem job_origin_step (h : Step q s e q' s') (job : q'.job = some p) : + e = .capture p โˆจ q.job = some p := by + cases h <;> simp_all [Phase.job] + +theorem job_origin (run : Run .idle start es q s) (job : q.job = some p) : + Event.capture p โˆˆ es := by + generalize initialPhase : Phase.idle = first at run + induction run with + | nil => simp [โ† initialPhase, Phase.job] at job + | snoc _ h ih => + rcases job_origin_step h job with new | old + ยท simp [new] + ยท exact List.mem_append_left _ (ih old) + +theorem capture_is_one_cut (h : Step q s (.capture p) q' s') : + p.cut = s.tx.currentDB โˆง p.dbGeneration = s.generation โˆง s'.disk = s.disk โˆง + s'.tx = s.tx โˆง q' = .pending .queued p := by cases h; exact โŸจrfl, rfl, rfl, rfl, rflโŸฉ + +theorem durable_export_is_original_capture + (run : Run .idle (initial base) es (.worker p (.bytes .renamed image)) s) : + image = p.cut โˆง Event.capture p โˆˆ es := by + have ok := (reachable_safe (run.reachable (.boot base))).pipeline + exact โŸจok.2, job_origin run rflโŸฉ + +theorem batch_during_export (running : s.stopping = false) (ready : s.tx.pendingAck = none) + (later : s.tx.currentDB.index < next.index) (persisted : next.index โ‰ค s.walEnd) : + Step (.worker p b) s (.applyBatch next) (.worker p b) + { s with tx := โŸจnext, some next.index, s.tx.lastAckโŸฉ } := + .applyBatch rfl running ready later persisted + +def Event.appliedCut : Event โ†’ Option Cut + | .applyBatch c | .nonData c => some c + | _ => none + +theorem snapshot_preserves_transaction (h : Step q s e q' s') + (apply : e.appliedCut = none) (ack : โˆ€ i, e โ‰  .ack i) (swap : e โ‰  .swap) : s'.tx = s.tx := by + cases h <;> first | rfl | simp_all [Event.appliedCut] + +theorem ack_is_synced_batch (r : Reachable q s) (h : Step q s (.ack i) q' s') : + s.tx.pendingAck = some s.tx.currentDB.index โˆง + s'.tx.lastAck = some s.tx.currentDB.index โˆง s'.tx.currentDB = s.tx.currentDB := by + cases h with + | ack _ synced => simp [(reachable_safe r).ackIndex _ synced, synced] + +theorem single_inflight (r : Reachable q s) : + s.attempts โ‰ค s.issued โˆง s.issued โ‰ค s.attempts + 1 := by + have count := (reachable_safe r).lifetime.1 + cases q <;> simp [Phase.owed] at count <;> omega + +/-- Includes the possibly unreleased physical handle after an unsuccessful Close. -/ +theorem at_most_one_unreleased_pin (r : Reachable q s) : + s.released โ‰ค s.issued โˆง s.issued โ‰ค s.released + 1 := by + obtain โŸจissued, attempts, _โŸฉ := (reachable_safe r).lifetime + cases q <;> simp [Phase.owed, Phase.errors] at issued attempts <;> omega + +theorem export_has_live_db {id : Nat} (r : Reachable q s) (h : Step q s (.write id) q' s') : + โˆƒ p b, q = .worker p b โˆง p.ticket = id โˆง p.dbGeneration = s.generation โˆง + q.lock = .worker โˆง q'.lock = .worker := by + cases h + exact โŸจ_, _, rfl, rfl, (reachable_safe r).lifetime.2.2.2, rfl, rflโŸฉ + +theorem db_swap_requires_exclusion (r : Reachable q s) (h : Step q s .swap q' s') : + q.lock = .restore โˆง q.owed = 0 โˆง s.issued = s.released โˆง s'.generation = s.generation + 1 := by + cases h + have ok := (reachable_safe r).lifetime + simp [Lifetime, Phase.owed, Phase.errors, Phase.identity] at ok + exact โŸจrfl, rfl, ok.1.trans ok.2, rflโŸฉ + +theorem store_close_requires_join_and_drain (r : Reachable q s) (h : Step q s .closeStore q' s') : + q = .exclusive .shutdown โˆง q.owed = 0 โˆง s.issued = s.attempts โˆง s.attempts = s.released := by + cases h + have ok := (reachable_safe r).lifetime + simpa [Lifetime, Phase.owed, Phase.errors, Phase.identity] using ok + +theorem worker_excludes_swap_and_store_close (locked : q.lock = .worker) : + ยฌ Step q s .swap q' s' โˆง ยฌ Step q s .closeStore q' s' := by + constructor <;> intro h <;> cases h <;> contradiction + +/-- The same successful shutdown sequence drains either channel position. -/ +theorem shutdown_drains_pending (s : State) (place : Place) (p : Pin) : + โˆƒ final, Run (.pending place p) s [.stop, .retire .shutdown, .closePin, .closeStore] + .storeClosed final โˆง final.attempts = s.attempts + 1 โˆง final.released = s.released + 1 := by + exact โŸจ_, .snoc (.snoc (.snoc (.snoc .nil .stop) (.retire (reason := .shutdown) rfl)) + .drain) .closeStore, rfl, rflโŸฉ + +theorem stop_persists (h : Step q s e q' s') (stopping : s.stopping = true) : + s'.stopping = true := by cases h <;> first | rfl | exact stopping + +theorem no_new_capture_after_stop (run : Run q s es q' s') (stopping : s.stopping = true) : + ยฌ Step q' s' (.capture p) q'' s'' := by + have stopped : s'.stopping = true := by + induction run with + | nil => exact stopping + | snoc _ h ih => exact stop_persists h ih + intro h + cases h + simp_all + +theorem serial_monotone (h : Step q s e q' s') : s.serial โ‰ค s'.serial := by + cases h <;> first | exact Nat.le_refl _ | exact Nat.le_succ _ + +theorem Run.serial_monotone (run : Run q s es q' s') : s.serial โ‰ค s'.serial := by + induction run with + | nil => exact Nat.le_refl _ + | snoc _ h ih => exact Nat.le_trans ih (OwnedSnapshot.serial_monotone h) + +def Event.workerTicket : Event โ†’ Option Nat + | .claim id | .write id | .dirSync id | .save id | .create id | .release id => some id + | _ => none + +theorem worker_ticket_current {id : Nat} (r : Reachable q s) (h : Step q s e q' s') + (work : e.workerTicket = some id) : id = s.serial := by + have identity := (reachable_safe r).lifetime.2.2 + cases h <;> simp_all [Event.workerTicket, Phase.identity] + +theorem retired_never_exports_or_publishes (r : Reachable (.retired reason p) s) + (run : Run (.retired reason p) s es q t) (h : Step q t e q' t') : + e.workerTicket โ‰  some p.ticket := by + intro work + have stale : p.ticket < s.serial := (reachable_safe r).lifetime.2.2.1 + have now := worker_ticket_current (run.reachable r) h work + have monotone := run.serial_monotone + omega + +theorem late_dequeue_skips (r : Reachable (.retired reason p) s) + (run : Run (.retired reason p) s es q t) (free : q.lock = .free) + (openDB : q.foreground = true) : Step q t (.skipStale p.ticket) q t := by + apply Step.skipStale free openDB + have identity := (reachable_safe (run.reachable r)).lifetime.2.2 + have stale : p.ticket < t.serial := + Nat.lt_of_lt_of_le (reachable_safe r).lifetime.2.2.1 run.serial_monotone + cases q <;> simp_all [Phase.claimable] + case pending place next => + cases place <;> simp_all [Phase.identity] <;> omega + +/-- The DB may already have been replaced when restore reports its error. +The old token is disabled even though neither snapshot index advanced. -/ +theorem failed_restore_invalidates (r : Reachable (.pending place p) s) + (running : s.stopping = false) (replacement : Cut) : + โˆƒ t, Run (.pending place p) s [.retire .restore, .closePin, .swap, .restoreError] .idle t โˆง + t.disk.raft = s.disk.raft โˆง t.receivedIndex = s.receivedIndex โˆง + โˆ€ {es q u e q' u'}, Run .idle t es q u โ†’ Step q u e q' u' โ†’ e.workerTicket โ‰  some p.ticket := by + have retire : Step (.pending place p) s (.retire .restore) (.retired .restore p) s.invalidate := + .retire running + have tail := Run.snoc (.snoc (.snoc .nil (Step.drain (s := s.invalidate) (p := p) + (reason := .restore))) (.swap replacement)) .restoreErrorLate + refine โŸจ_, .snoc (.snoc (.snoc (.snoc .nil retire) .drain) (.swap replacement)) .restoreErrorLate, + rfl, rfl, ?_โŸฉ + intro es q u e q' u' later h work + have stale : p.ticket < s.invalidate.serial := (reachable_safe (.step r retire)).lifetime.2.2.1 + have now := worker_ticket_current (later.reachable (tail.reachable (.step r retire))) h work + have bound := later.serial_monotone + change s.invalidate.serial โ‰ค u.serial at bound + omega + +theorem close_error_fails_closed (r : Reachable .closeError s) + (run : Run .closeError s es q t) : + q = .closeError โˆง t.issued = t.attempts โˆง t.attempts = t.released + 1 := by + have terminal : q = .closeError := by + generalize eqn : Phase.closeError = start at run + induction run with + | nil => rfl + | snoc _ step ih => + subst start + rw [ih] at step + cases step <;> trivial + subst q + have ok := (reachable_safe (run.reachable r)).lifetime + simpa [Lifetime, Phase.owed, Phase.errors, Phase.identity] using ok + +/-- A retired handle is still owed a Close, but cannot be claimed for reading. -/ +def Phase.closeTicket : Phase โ†’ Option Nat + | .pending _ p | .worker p _ | .exported p | .retired _ p => some p.ticket + | _ => none + +def Event.attemptsClose : Event โ†’ Bool + | .closePin | .closeError | .abort => true + | _ => false + +def CloseAttempt (q : Phase) (e : Event) (ticket : Nat) : Prop := + q.closeTicket = some ticket โˆง e.attemptsClose = true + +def Discharged (ticket : Nat) (q : Phase) (s : State) : Prop := + ticket โ‰ค s.serial โˆง q.closeTicket โ‰  some ticket + +theorem close_consumes_ticket (r : Reachable q s) (h : Step q s e q' s') + (closed : CloseAttempt q e ticket) : + s'.attempts = s.attempts + 1 โˆง Discharged ticket q' s' := by + have identity := (reachable_safe r).lifetime.2.2 + cases h <;> simp_all [CloseAttempt, Phase.closeTicket, Event.attemptsClose, Discharged, + Phase.identity, State.closeOK, State.closeFailed] + all_goals exact closed โ–ธ Nat.le_of_lt (reachable_safe r).lifetime.2.2.1 + +theorem discharged_step (h : Step q s e q' s') (old : Discharged ticket q s) : + Discharged ticket q' s' := by + obtain โŸจbound, absentโŸฉ := old + refine โŸจNat.le_trans bound (serial_monotone h), ?_โŸฉ + cases h <;> simp_all [Phase.closeTicket, State.pin] <;> omega + +theorem no_second_close_attempt (r : Reachable q s) (h : Step q s e q' s') + (closed : CloseAttempt q e ticket) (later : Run q' s' es q'' s'') : + โˆ€ e', ยฌ CloseAttempt q'' e' ticket := by + have spent := (close_consumes_ticket r h closed).2 + have final : Discharged ticket q'' s'' := by + induction later with + | nil => exact spent + | snoc _ step ih => exact discharged_step step ih + exact fun _ again => final.2 again.1 + +theorem obligation_carried_or_attempted (h : Step q s e q' s') + (held : q.closeTicket = some ticket) : q'.closeTicket = some ticket โˆจ CloseAttempt q e ticket := by + cases h <;> simp_all [Phase.closeTicket, CloseAttempt, Event.attemptsClose] + +/-- Locate the consuming step in the trace, including its actual prefix and +suffix. In combination with no_second_close_attempt this gives exactly one +attempt for each outstanding ticket on every shutdown reaching storeClosed. -/ +theorem run_carries_or_closes (run : Run q s es q' s') (held : q.closeTicket = some ticket) : + q'.closeTicket = some ticket โˆจ + โˆƒ pre e post a u b v, es = pre ++ e :: post โˆง Run q s pre a u โˆง + Step a u e b v โˆง CloseAttempt a e ticket โˆง Run b v post q' s' := by + induction run with + | nil => exact Or.inl held + | snoc prior step ih => + rcases ih with still | โŸจpre, e, post, a, u, b, v, eqn, left, h, closed, rightโŸฉ + ยท rcases obligation_carried_or_attempted step still with next | closed + ยท exact Or.inl next + ยท exact Or.inr โŸจ_, _, [], _, _, _, _, rfl, prior, step, closed, .nilโŸฉ + ยท exact Or.inr โŸจpre, e, _, a, u, b, v, by simp [eqn], left, h, closed, .snoc right stepโŸฉ + +theorem shutdown_closes_each_pending_pin (r : Reachable (.pending place p) s) + (run : Run (.pending place p) s es .storeClosed final) : + โˆƒ pre e post a u b v, es = pre ++ e :: post โˆง Run (.pending place p) s pre a u โˆง + Step a u e b v โˆง CloseAttempt a e p.ticket โˆง v.released = u.released + 1 โˆง + Run b v post .storeClosed final := by + rcases run_carries_or_closes run (ticket := p.ticket) rfl with impossible | + โŸจpre, e, post, a, u, b, v, eqn, left, step, attempt, rightโŸฉ + ยท contradiction + refine โŸจpre, e, post, a, u, b, v, eqn, left, step, attempt, ?_, rightโŸฉ + have success : b โ‰  .closeError := by + rintro rfl + exact Phase.noConfusion (close_error_fails_closed (.step (left.reachable r) step) right).1 + cases step <;> first | rfl | simp_all [CloseAttempt, Event.attemptsClose, Phase.closeTicket] + +theorem publication_requires_durable_pair {id : Nat} (r : Reachable q s) (h : Step q s (.create id) q' s') : + s'.disk.memory = s.disk.raft โˆง s.disk.file s'.disk.memory.index = some s'.disk.memory โˆง + s'.disk.memory.index โ‰ค s.disk.applied := by + cases h + have same := (reachable_safe r).pipeline + have safe := (reachable_safe r).storage + exact โŸจsame.symm, same โ–ธ safe.raftFile, same โ–ธ safe.syncedโŸฉ + +theorem reclaim_requires_publication {id : Nat} (r : Reachable q s) (h : Step q s (.release id) q' s') : + s'.disk.floor = s.disk.memory.index โˆง s.disk.memory = s.disk.raft โˆง + s.disk.file s'.disk.floor = some s.disk.raft := by + cases h + obtain โŸจsaved, createdโŸฉ := (reachable_safe r).pipeline + have safe := (reachable_safe r).storage + exact โŸจcongrArg Cut.index created.symm, created.trans saved.symm, + by simpa [State.withDisk, Disk.release, โ† saved] using safe.raftFileโŸฉ + +/-- A crash can observe the old record anywhere, or the complete new record +while SaveSnap is in progress. The recovered WAL suffix starts above floor. -/ +inductive Recover : Phase โ†’ State โ†’ Cut โ†’ Prop + | recorded : Recover q s s.disk.raft + | duringSave : Recover (.publishing p .saving) s p.cut + +theorem crash_requires_complete_file_and_wal (r : Reachable q s) (crash : Recover q s c) : + s.disk.file c.index = some c โˆง s.disk.floor โ‰ค c.index โˆง c.index โ‰ค s.disk.applied := by + have safe := (reachable_safe r).storage + have retained := Nat.le_trans safe.retained safe.ordered + cases crash with + | recorded => exact โŸจsafe.raftFile, retained, safe.syncedโŸฉ + | duringSave => + obtain โŸจfresh, file, bumpedโŸฉ := (reachable_safe r).pipeline + exact โŸจfile, Nat.le_trans retained (Nat.le_of_lt fresh), bumpedโŸฉ + +theorem crash_during_export_uses_old (h : Recover (.worker p b) s c) : + c = s.disk.raft := by cases h; rfl + +theorem crash_outside_save_uses_recorded (h : Recover q s c) + (outside : โˆ€ p, q โ‰  .publishing p .saving) : c = s.disk.raft := by + cases h with + | recorded => rfl + | duringSave => exact False.elim (outside _ rfl) + +theorem crash_during_save_choices : + Recover (.publishing p .saving) s c โ†” c = s.disk.raft โˆจ c = p.cut := by + constructor + ยท intro h + cases h <;> simp + ยท rintro (rfl | rfl) + ยท exact .recorded + ยท exact .duringSave + +/-- WAL persistence is independent of ACK. Only a successfully applied batch +creates a pending receipt, and only its ACK extends the history. -/ +structure WALBounds (s : State) : Prop where + pending : โˆ€ i, s.tx.pendingAck = some i โ†’ i โ‰ค s.walEnd + history : โˆ€ i โˆˆ s.acked, i โ‰ค s.walEnd + +theorem wal_bounds_step (h : Step q s e q' s') (ok : WALBounds s) : WALBounds s' := by + cases h <;> first | exact โŸจok.pending, ok.historyโŸฉ | skip + case syncWAL => + exact โŸจfun i hi => Nat.le_trans (ok.pending i hi) (Nat.le_max_left ..), + fun i hi => Nat.le_trans (ok.history i hi) (Nat.le_max_left ..)โŸฉ + case applyBatch persisted => exact โŸจby simpa using persisted, ok.historyโŸฉ + case swap => exact โŸจby simp, ok.historyโŸฉ + case ack synced => + refine โŸจby simp, ?_โŸฉ + intro i hi + rcases List.mem_cons.mp hi with rfl | old + ยท exact ok.pending _ synced + ยท exact ok.history _ old + +theorem reachable_wal_bounds (r : Reachable q s) : WALBounds s := by + induction r with + | boot base => constructor <;> simp [initial] + | step _ h ih => exact wal_bounds_step h ih + +theorem ack_history_step (h : Step q s e q' s') : + i โˆˆ s'.acked โ†” i โˆˆ s.acked โˆจ e = .ack i := by + cases h <;> simp [State.issue, State.closeOK, State.closeFailed, State.invalidate, + State.withDisk, or_comm, eq_comm] + +theorem Run.ack_history (run : Run q s es q' s') : + i โˆˆ s'.acked โ†” i โˆˆ s.acked โˆจ Event.ack i โˆˆ es := by + induction run with + | nil => simp + | snoc _ h ih => rw [ack_history_step h, ih]; simp [or_assoc, eq_comm] + +/-- The foreground supplies the logical meaning of a cut. No worker, file, +ACK or recovery property is a premise of a foreground or publication step. -/ +def LocalEvent (valid : Cut โ†’ Prop) (e : Event) : Prop := + e โ‰  .swap โˆง โˆ€ c, e.appliedCut = some c โ†’ valid c + +structure PrefixState (valid : Cut โ†’ Prop) (q : Phase) (s : State) : Prop where + current : valid s.tx.currentDB + recorded : valid s.disk.raft + job : โˆ€ p, q.job = some p โ†’ valid p.cut + +theorem prefix_state_step (h : Step q s e q' s') (event : LocalEvent valid e) + (ok : PrefixState valid q s) : PrefixState valid q' s' := by + refine โŸจ?_, ?_, ?_โŸฉ + ยท cases h <;> first | exact ok.current | exact event.2 _ rfl | exact (event.1 rfl).elim + ยท cases h <;> first | exact ok.recorded | exact ok.job _ rfl + ยท intro p job + rcases job_origin_step h job with rfl | old + ยท rw [(capture_is_one_cut h).1] + exact ok.current + ยท exact ok.job _ old + +theorem Run.prefix_state (run : Run q s es q' s') (start : PrefixState valid q s) + (events : โˆ€ e โˆˆ es, LocalEvent valid e) : PrefixState valid q' s' := by + induction run with + | nil => exact start + | snoc _ h ih => + exact prefix_state_step h (events _ (by simp)) + (ih (fun e he => events e (List.mem_append_left _ he))) + +/-- Every entry after the recovered snapshot up to this ACK is still on disk. +The range matters: the ACK's own entry alone need not suffice for replay. -/ +def AckCovered (s : State) (c : Cut) (i : Nat) : Prop := + i โ‰ค c.index โˆจ (c.index < i โˆง + โˆ€ j, c.index < j โ†’ j โ‰ค i โ†’ s.disk.floor < j โˆง j โ‰ค s.walEnd) + +/-- D, for every crash boundary of a finite local trace. The selected file +is an actual replay prefix. Each successful batch is in that prefix or the +entire suffix needed to replay through its index is retained and durable. +Recover includes both choices during SaveSnap and Step includes both error +outcomes. The proof does not require a subsequent successful publication. +`decode` projects the logical FSM state; `replay i` is deterministic replay +of the fixed committed history through i. Physical file layouts or DB metadata +need not themselves be deterministic functions of i. -/ +theorem local_crash_covers_all_acks (decode : Cut โ†’ ฮฑ) (replay : Nat โ†’ ฮฑ) + (run : Run .idle (initial base) es q s) (boot : decode base = replay base.index) + (events : โˆ€ e โˆˆ es, LocalEvent (fun x => decode x = replay x.index) e) + (crash : Recover q s c) : + s.disk.file c.index = some c โˆง decode c = replay c.index โˆง + โˆ€ i, Event.ack i โˆˆ es โ†’ AckCovered s c i := by + have r := run.reachable (.boot base) + obtain โŸจfile, floor, _โŸฉ := crash_requires_complete_file_and_wal r crash + have prefixes := run.prefix_state โŸจboot, boot, by simp [Phase.job]โŸฉ events + refine โŸจfile, ?_, ?_โŸฉ + ยท cases crash <;> first | exact prefixes.recorded | exact prefixes.job _ rfl + ยท intro i hi + have member := run.ack_history.mpr (Or.inr hi) + by_cases before : i โ‰ค c.index + ยท exact Or.inl before + ยท exact Or.inr โŸจNat.lt_of_not_ge before, fun _ lower upper => + โŸจNat.lt_of_le_of_lt floor lower, Nat.le_trans upper ((reachable_wal_bounds r).history i member)โŸฉโŸฉ + +/-- A successful trace reads rows after another batch has changed the live DB. +Start with a complete snapshot at 0, then apply 1, capture, and apply 2 between +the metadata and row reads. Check the actual file, ACK and release floor. -/ +private def sample (i : Nat) : Cut := + โŸจโŸจi, i, i + 20, i + 30, i + 40, i + 50โŸฉ, [i, i + 1]โŸฉ + +/-- A configuration entry can be captured at index 2 with the rows and +Pebble metadata from index 1. Only the first entry has a data receipt. -/ +theorem capture_after_non_data : + โˆƒ es p s, Run .idle (initial (sample 0)) es (.pending .queued p) s โˆง + p.cut.index = 2 โˆง p.cut.manifest.metadata = 1 โˆง + p.cut.rows = (sample 1).rows โˆง s.acked = [1] := by + let config := { sample 1 with manifest := { (sample 1).manifest with index := 2, confState := 32 } } + have wal := (Run.nil (q := .idle) (s := initial (sample 0))).snoc (.syncWAL 2 rfl) + have batch := wal.snoc (.applyBatch (next := sample 1) rfl rfl rfl (by decide) (by decide)) + have ack := batch.snoc (.ack rfl rfl) + have next := ack.snoc (.nonData (next := config) rfl rfl rfl (by decide) (by decide) rfl rfl) + exact โŸจ_, _, _, next.snoc (.capture rfl), rfl, rfl, rfl, rflโŸฉ + +theorem overlapping_export_completes : + โˆƒ es t, Run .idle (initial (sample 0)) es .idle t โˆง + t.tx.currentDB = sample 2 โˆง t.tx.lastAck = some 2 โˆง + t.disk.file 1 = some (sample 1) โˆง t.disk.raft = sample 1 โˆง + t.disk.memory = sample 1 โˆง t.disk.floor = 1 โˆง t.attempts = 1 โˆง t.released = 1 := by + have start := Run.nil (q := .idle) (s := initial (sample 0)) + have wal := start.snoc (.syncWAL 2 rfl) + have a := wal.snoc (Step.applyBatch (next := sample 1) rfl rfl rfl (by decide) (by decide)) + have b := a.snoc (Step.ack rfl rfl) + have c := (b.snoc (.capture rfl)).snoc .dequeue + have w := c.snoc (.claim rfl (by decide) (by decide)) + have m := w.snoc (.write .metadata) + have f := m.snoc (.applyBatch (next := sample 2) rfl rfl rfl (by decide) (by decide)) + have rows := (f.snoc (.ack rfl rfl)).snoc (.write .rowsCRC) + have fs := ((rows.snoc (.write .flush)).snoc (.write .syncFile)).snoc (.write .closeFile) + have file := (fs.snoc (.write .rename)).snoc .dirSync + have record := (((file.snoc .closePin).snoc .bump).snoc .beginSave).snoc .save + exact โŸจ_, _, ((record.snoc .create).snoc .compact).snoc .release, + rfl, rfl, rfl, rfl, rfl, rfl, rfl, rflโŸฉ + +namespace NegativeControls + +/-- Mutate only the release order: after a real WAL sync, apply and ACK, +reclaim through 1 while the recoverable record still selects 0. -/ +theorem premature_release_loses_ack : + โˆƒ es s, Run .idle (initial (sample 0)) es .idle s โˆง 1 โˆˆ s.acked โˆง + let broken := s.withDisk (s.disk.release (sample 1)) + Recover .idle broken (sample 0) โˆง ยฌ AckCovered broken (sample 0) 1 := by + have wal := (Run.nil (q := .idle) (s := initial (sample 0))).snoc (.syncWAL 1 rfl) + have batch := wal.snoc (.applyBatch (next := sample 1) rfl rfl rfl (by decide) (by decide)) + refine โŸจ_, _, batch.snoc (.ack rfl rfl), by decide, .recorded, ?_โŸฉ + rintro (before | โŸจ_, suffixโŸฉ) + ยท exact (by decide : ยฌ 1 โ‰ค (sample 0).index) before + ยท exact Nat.lt_irrefl 1 (suffix 1 (by decide) (by decide)).1 + +/-- Old design: dequeue removes the only discoverable reference. Failed +restore can replace the DB and retain the prior MemoryStorage index. -/ +structure Legacy where + queued : Option Pin + dequeued : Option Pin + generation : Nat + raftIndex : Nat + storeClosed : Bool + closeAttempts : Nat + +def dequeue (s : Legacy) : Legacy := { s with queued := none, dequeued := s.queued } +def failAfterSwap (s : Legacy) : Legacy := { s with generation := s.generation + 1 } +def indexOnly (s : Legacy) (p : Pin) : Bool := decide (s.raftIndex < p.cut.index) +def stopWithoutDrain (s : Legacy) : Legacy := { s with storeClosed := true } + +private def pin : Pin := โŸจ1, 0, sample 1โŸฉ +private def buffered : Legacy := โŸจsome pin, none, 0, 0, false, 0โŸฉ + +theorem index_only_accepts_closed_generation : + let t := failAfterSwap (dequeue buffered) + t.queued = none โˆง t.dequeued = some pin โˆง t.raftIndex = buffered.raftIndex โˆง + indexOnly t pin = true โˆง pin.dbGeneration โ‰  t.generation := by decide + +theorem stop_without_drain_leaks : + let t := stopWithoutDrain buffered + t.storeClosed = true โˆง t.queued = some pin โˆง t.closeAttempts = 0 := by decide + +theorem live_rows_mix_two_cuts : + let mixed : Cut := โŸจ(sample 1).manifest, (sample 2).rowsโŸฉ + mixed โ‰  sample 1 โˆง mixed โ‰  sample 2 := by decide + +end NegativeControls + +namespace Scratch + +/-! Refinement for the SST branch of ownedPebbleSnapshot.WriteTo, under the +file-backed synchronous Raft owner. The scratch directory is fresh and private +to this worker. Each successful Finish flushes and closes the writable. Until +power loss the two opens of that closed file see its complete bytes. These are +Go/filesystem contracts. In particular, writeFileTo checks length only. + +`files` lists the bytes inspected for each manifest entry in rotation order. +We retain the whole hash input as a proof witness. The Go manifest stores a +digest and size. `decodeRows` specifies the logical rows of an ordered SST +bundle at the captured format. Successful completion of the pinned iteration +must supply all of those rows, including for a zero-file export. -/ +abbrev Bytes := List UInt8 +abbrev Files := List Bytes +/-- Decode a complete bundle using only its table format and bytes. -/ +abbrev Decoder := Nat โ†’ Files โ†’ Option (List Nat) + +inductive ScratchFiles + | absent + | building (files : Files) + | writing (files : Files) (pending : Bytes) + | closed (files : Files) (bytes : Bytes) + | copying (inspected copied remaining : Files) + | buildError + | streamError + | spent (files : Files) + +/-- Local steps hold the worker pin. There is one writable at a time. Closing +freezes its contents, inspection appends its bytes, and the streaming reader +consumes these immutable files in manifest order. There is no physical scratch +Sync premise. A finite prefix may stop before any successful return. -/ +inductive Work (decodeRows : Decoder) (p : Pin) : ScratchFiles โ†’ ScratchFiles โ†’ Prop + | beginBuild : Work decodeRows p .absent (.building []) + | create : Work decodeRows p (.building fs) (.writing fs []) + | write (chunk : Bytes) : Work decodeRows p (.writing fs buf) (.writing fs (buf ++ chunk)) + | finish : Work decodeRows p (.writing fs buf) (.closed fs buf) + | inspect : Work decodeRows p (.closed fs buf) (.building (fs ++ [buf])) + | beginCopy (complete : decodeRows p.cut.manifest.tableFormat fs = some p.cut.rows) : + Work decodeRows p (.building fs) (.copying fs [] fs) + | read : Work decodeRows p (.copying fs copied (bytes :: rest)) + (.copying fs (copied ++ [bytes]) rest) + | createError : Work decodeRows p (.building fs) .buildError + | writableError : Work decodeRows p (.writing fs buf) .buildError + | inspectError : Work decodeRows p (.closed fs buf) .buildError + | copyError : Work decodeRows p (.copying fs copied rest) .streamError + +def ScratchFiles.Coherent (decodeRows : Decoder) (p : Pin) : ScratchFiles โ†’ Prop + | .copying fs copied rest => + fs = copied ++ rest โˆง decodeRows p.cut.manifest.tableFormat fs = some p.cut.rows + | _ => True + +theorem Work.coherent (h : Work dec p x y) (prior : x.Coherent dec p) : y.Coherent dec p := by + cases h <;> simp_all [ScratchFiles.Coherent, List.append_assoc] + case read => exact prior.1 โ–ธ prior.2 + +structure Machine where + phase : Phase + state : State + scratch : ScratchFiles + +def Machine.Coherent (m : Machine) (dec : Decoder) : Prop := + match m.phase with + | .worker p _ => m.scratch.Coherent dec p + | _ => True + +/-- All non-write protocol transitions retain their original guards. A +foreground transition can run between any two reads. Leaving a phase drops +the worker's scratch reference, including on abort with a leftover orphan. -/ +inductive Move (dec : Decoder) : Machine โ†’ Option Event โ†’ Machine โ†’ Prop + | protocol (h : Step q s e q' s') (other : โˆ€ id, e โ‰  .write id) : + Move dec โŸจq, s, xโŸฉ (some e) โŸจq', s', if q = q' then x else .absentโŸฉ + | metadata : Move dec โŸจ.worker p .temp, s, .absentโŸฉ (some (.write p.ticket)) + โŸจ.worker p (.manifest p.cut.manifest), s, .absentโŸฉ + | work (h : Work dec p x y) : Move dec โŸจ.worker p (.manifest p.cut.manifest), s, xโŸฉ none + โŸจ.worker p (.manifest p.cut.manifest), s, yโŸฉ + | serialize (payload : dec p.cut.manifest.tableFormat copied = some rows) : + Move dec โŸจ.worker p (.manifest p.cut.manifest), s, .copying fs copied []โŸฉ + (some (.write p.ticket)) + โŸจ.worker p (.bytes .crc โŸจp.cut.manifest, rowsโŸฉ), s, .spent fsโŸฉ + -- Before bundle.WriteTo, a build error permits the existing same-pin native + -- payload under the captured header. A partial stream has no such edge. + | nativeFallback : Move dec โŸจ.worker p (.manifest p.cut.manifest), s, .buildErrorโŸฉ + (some (.write p.ticket)) โŸจ.worker p (.bytes .crc p.cut), s, .absentโŸฉ + | remove : Move dec โŸจ.worker p (.bytes .crc c), s, .spent fsโŸฉ none + โŸจ.worker p (.bytes .crc c), s, .absentโŸฉ + -- Only the four outer-file steps start at a Buffer.bytes. Cleanup is + -- best effort and cannot prevent or authorize the outer durability steps. + | outer (h : Write p (.bytes stage c) b) : + Move dec โŸจ.worker p (.bytes stage c), s, xโŸฉ (some (.write p.ticket)) โŸจ.worker p b, s, .absentโŸฉ + +private theorem absent_coherent (q : Phase) : (Machine.mk q s .absent).Coherent dec := by + cases q <;> trivial + +theorem Move.coherent (h : Move dec m e n) (prior : m.Coherent dec) : n.Coherent dec := by + cases h with + | protocol => + split + ยท subst_vars + exact prior + ยท exact absent_coherent _ + | work h => exact h.coherent prior + | metadata | serialize | nativeFallback | remove | outer => trivial + +/-- At the serialization boundary the independently accumulated read inputs +are identical and the emitted rows are the captured rows. Digest collisions +and equal lengths are immaterial to this argument. -/ +theorem complete_copy {dec : Decoder} (ok : (ScratchFiles.copying fs copied []).Coherent dec p) + (payload : dec p.cut.manifest.tableFormat copied = some rows) : fs = copied โˆง rows = p.cut.rows := by + obtain โŸจsame, completeโŸฉ := ok + simp only [List.append_nil] at same + exact โŸจsame, Option.some.inj (payload.symm.trans (same โ–ธ complete))โŸฉ + +theorem Move.project (h : Move dec m e n) (ok : m.Coherent dec) : + match e with + | none => m.phase = n.phase โˆง m.state = n.state + | some event => Step m.phase m.state event n.phase n.state := by + cases h with + | work | remove => exact โŸจrfl, rflโŸฉ + | protocol step _ => exact step + | metadata => exact .write .metadata + | serialize payload => + obtain โŸจ_, rflโŸฉ := complete_copy ok payload + exact .write .rowsCRC + | nativeFallback => exact .write .rowsCRC + | outer h => exact .write h + +theorem local_observations (h : Move dec m none n) (c : Cut) (i : Nat) : + n.state.disk = m.state.disk โˆง (Recover n.phase n.state c โ†” Recover m.phase m.state c) โˆง + (AckCovered n.state c i โ†” AckCovered m.state c i) := by + cases h <;> exact โŸจrfl, Iff.rfl, Iff.rflโŸฉ + +/-- A finite concrete execution logs only its observable events. Local steps +are still present in the derivation, including failed and incomplete builds. -/ +inductive Trace (dec : Decoder) : Machine โ†’ List Event โ†’ Machine โ†’ Prop + | nil : Trace dec m [] m + | snoc : Trace dec m es n โ†’ Move dec n e t โ†’ Trace dec m (es ++ e.toList) t + +theorem Trace.refines (h : Trace dec m es n) (start : m.Coherent dec) : + Run m.phase m.state es n.phase n.state โˆง n.Coherent dec := by + induction h with + | nil => exact โŸจ.nil, startโŸฉ + | snoc earlier move ih => + obtain โŸจrun, okโŸฉ := ih + refine โŸจ?_, move.coherent okโŸฉ + have proj := move.project ok + cases โ€นOption Eventโ€บ with + | none => simpa [โ† proj.1, โ† proj.2] using run + | some event => exact run.snoc proj + +/-- Rotation witness: hash each finished SST before creating the next. Both +files are later copied into one payload. At removal the outer flush and both +durability barriers are still outstanding. -/ +theorem two_file_export (p : Pin) (s : State) (first second : Bytes) + (complete : dec p.cut.manifest.tableFormat [first, second] = some p.cut.rows) : + Trace dec โŸจ.worker p .temp, s, .absentโŸฉ [.write p.ticket, .write p.ticket] + โŸจ.worker p (.bytes .crc p.cut), s, .absentโŸฉ := by + have start := Trace.nil (dec := dec) (m := โŸจ.worker p .temp, s, .absentโŸฉ) + have build := (start.snoc .metadata).snoc (.work .beginBuild) + have a := (build.snoc (.work .create)).snoc (.work (.write first)) + have inspected := (a.snoc (.work .finish)).snoc (.work .inspect) + have b := (inspected.snoc (.work .create)).snoc (.work (.write second)) + have bundle := (b.snoc (.work .finish)).snoc (.work .inspect) + have stream := bundle.snoc (.work (.beginCopy complete)) + have copied := (stream.snoc (.work .read)).snoc (.work .read) + exact (copied.snoc (.serialize complete)).snoc .remove + +/-- After a partial bundle write fails, neither the SST success edge nor the +native fallback is available. The protocol can still record the pin close or +close failure, or crash at this prefix. -/ +theorem stream_error_blocks_write (ticket : Nat) : + ยฌ Move dec โŸจ.worker p (.manifest p.cut.manifest), s, .streamErrorโŸฉ (some (.write ticket)) n := by + intro move + cases move with + | protocol _ other => exact other ticket rfl + +/-- Power loss discards every scratch byte. This is a crash observation only: +the old worker never resumes. Retain the crash site for Recover.duringSave. -/ +def powerLoss (m : Machine) : Machine := { m with scratch := .absent } + +theorem powerLoss_observations (m : Machine) (c : Cut) (i : Nat) : + (powerLoss m).scratch = .absent โˆง (powerLoss m).state.disk = m.state.disk โˆง + (Recover (powerLoss m).phase (powerLoss m).state c โ†” Recover m.phase m.state c) โˆง + (AckCovered (powerLoss m).state c i โ†” AckCovered m.state c i) := + โŸจrfl, rfl, Iff.rfl, Iff.rflโŸฉ + +theorem scratch_crash_covers_all_acks (decode : Cut โ†’ ฮฑ) (replay : Nat โ†’ ฮฑ) + (h : Trace dec โŸจ.idle, initial base, .absentโŸฉ es m) + (boot : decode base = replay base.index) + (localOnly : โˆ€ e โˆˆ es, e โ‰  .swap) + (foreground : โˆ€ e โˆˆ es, โˆ€ c, e.appliedCut = some c โ†’ decode c = replay c.index) + (crash : Recover (powerLoss m).phase (powerLoss m).state c) : + m.state.disk.file c.index = some c โˆง decode c = replay c.index โˆง + โˆ€ i, Event.ack i โˆˆ es โ†’ AckCovered m.state c i := + local_crash_covers_all_acks decode replay (h.refines trivial).1 boot + (fun e he => โŸจlocalOnly e he, foreground e heโŸฉ) crash + +#print axioms scratch_crash_covers_all_acks + +end Scratch + +#print axioms reachable_safe +#print axioms local_crash_covers_all_acks +#print axioms NegativeControls.premature_release_loses_ack + +end OwnedSnapshot diff --git a/lean/ProposalTurns.lean b/lean/ProposalTurns.lean new file mode 100644 index 000000000..35fd43e1e --- /dev/null +++ b/lean/ProposalTurns.lean @@ -0,0 +1,282 @@ +import Std + +/-! Protected synchronous leader, one stable Raft history. Positions are offsets +from a common base index. Original context and digest below are provenance: +the Raft envelope contains only ID and payload. Assume owned immutable bytes, +correct hashing, fresh pending IDs in this process, and faithful envelope and +waiter matching. The owner observations abstract handleProposalTurn and +IsProposalTurnPayload. persistReady, applyCommitted and publishNormalApply +supply the Ready transitions. The per-scope check and acceptance, Raft commit +evidence, and truthful WAL/FSM sync completion are lower-layer inputs. +This safety model does not verify Go races, OS/device behavior, quorum +formation, liveness or performance. +-/ +namespace ProposalTurns + +structure Request where + ctx : Nat + id : Nat + payload : List UInt8 + digest : Nat + deriving DecidableEq + +/-- One observation per invocation, including failures. The check is scoped to +this invocation of WithNative. The other guards include cancellation, leader +and configuration fences; nativeOK denotes actual acceptance of RawNode.Propose. -/ +structure Attempt where + request : Request + guards : Bool + check : Nat โ†’ List UInt8 โ†’ Nat โ†’ Bool + nativeOK : Bool + dataOnly : Bool + +def Attempt.checked (a : Attempt) : Bool := + a.check a.request.ctx a.request.payload a.request.digest + +def Attempt.entry (a : Attempt) : Option Request := + if a.guards && a.checked && a.nativeOK then some a.request else none + +theorem independent_issue (a : Attempt) (r : Request) : + a.entry = some r โ†” + a.guards = true โˆง a.checked = true โˆง a.nativeOK = true โˆง a.request = r := by + simp [Attempt.entry, and_assoc] + +def entries (attempts : List Attempt) := attempts.filterMap Attempt.entry + +/-- An accepted request occupies exactly one slot between the accepted prefix +and suffix, even when some surrounding candidates were denied. -/ +theorem one_original_entry (before after : List Attempt) (a : Attempt) + (accepted : a.entry = some a.request) : + entries (before ++ a :: after) = entries before ++ [a.request] ++ entries after := by + simp [entries, accepted] + +/-- Changing the partition at Ready boundaries preserves every original entry, +including its position, for the *same* observations at each native scope. +Different schedules need not observe the same authorization or acceptance. -/ +theorem partition_preserves_entries (turns : List (List Attempt)) : + (turns.map entries).flatten = entries turns.flatten := by + induction turns with + | nil => rfl + | cons t ts ih => simpa [entries] using congrArg (entries t ++ ยท) ih + +theorem earlier_acceptance_cannot_issue_denied_member {a b : Attempt} + (first : a.entry = some a.request) (denied : b.checked = false) : + entries [a, b] = [a.request] := by + have no : b.entry = none := by simp [Attempt.entry, denied] + simp [entries, first, no] + +/-- Observations of nonblocking polls, in owner order. none stands for a +boundary (read/recovery read, admin, tick, close, step, snapshot, dispatch +or changed owner state). The suffix is left for subsequent owner work. -/ +def extras : Nat โ†’ Nat โ†’ List (Option Attempt) โ†’ List Attempt + | fuel + 1, bytes, some a :: rest => + if bytes > 0 โˆง a.dataOnly โˆง a.request.payload.length โ‰ค bytes then + a :: extras fuel (bytes - a.request.payload.length) rest + else [] + | _, _, _ => [] + +/-- First request is immediate even when oversized. extendOK represents the +owner eligibility and Ready tests around that first handleProposal call. -/ +def members (first : Attempt) (extendOK : Bool) (polls : List (Option Attempt)) := + first :: (if extendOK && first.dataOnly then + extras 31 (131072 - first.request.payload.length) polls else []) + +def byteCount (xs : List Attempt) := (xs.map (fun a => a.request.payload.length)).sum + +theorem extras_bounds (fuel bytes polls) : + (extras fuel bytes polls).length โ‰ค fuel โˆง byteCount (extras fuel bytes polls) โ‰ค bytes โˆง + ((extras fuel bytes polls).map some) <+: polls := by + induction fuel generalizing bytes polls with + | zero => simp [extras, byteCount] + | succ fuel ih => + cases polls with + | nil => simp [extras, byteCount] + | cons p rest => + cases p with + | none => simp [extras, byteCount] + | some a => + simp only [extras] + split + ยท rename_i ok + obtain โŸจcount, size, tailโŸฉ := ih (bytes - a.request.payload.length) rest + refine โŸจby simpa using count, ?_, List.cons_prefix_cons.mpr โŸจrfl, tailโŸฉโŸฉ + simp only [byteCount, List.map_cons, List.sum_cons] at size โŠข + omega + ยท simp [byteCount] + +theorem turn_bounds (a ext polls) : + (members a ext polls).length โ‰ค 32 โˆง + (members a ext polls = [a] โˆจ byteCount (members a ext polls) โ‰ค 131072) := by + unfold members + split + ยท obtain โŸจcount, size, _โŸฉ := extras_bounds 31 (131072 - a.request.payload.length) polls + by_cases large : 131072 โ‰ค a.request.payload.length + ยท simp only [Nat.sub_eq_zero_of_le large] at * + cases polls with + | nil => simp [extras] + | cons p ps => cases p <;> simp [extras] + ยท refine โŸจby simpa using count, Or.inr ?_โŸฉ + simp only [byteCount, List.map_cons, List.sum_cons] at size โŠข + omega + ยท simp + +structure Applied where + original : Request + response : Nat -- opaque return value of applying this entry + +structure State where + log : List Request := [] + wal : Nat := 0 + committed : Nat := 0 + applied : List Applied := [] + published : Nat := 0 + +/-- wal counts durable entry bytes by whole entries. committed is the prefix +exposed for local apply after Ready persistence, not the instant a quorum +first commits. Later Ready can expose entries persisted in an earlier Ready. +syncApply denotes completed required synchronous FSM work. publish counts +ordered resolution attempts, including ones without a matching pending caller. +Transport enqueue/issue/coalescing supplies no quorum, apply or receipt. -/ +inductive Step (s : State) : State โ†’ Prop + | turn (first ext polls) : Step s + { s with log := s.log ++ entries (members first ext polls) } + | message : Step s s + | persist (k) : s.wal โ‰ค k โ†’ k โ‰ค s.log.length โ†’ Step s { s with wal := k } + | commitReady (k) : s.committed โ‰ค k โ†’ k โ‰ค s.wal โ†’ Step s { s with committed := k } + | syncApply (r value) : s.applied.length < s.committed โ†’ + s.log[s.applied.length]? = some r โ†’ + Step s { s with applied := s.applied ++ [โŸจr, valueโŸฉ] } + | publish : s.published < s.applied.length โ†’ Step s { s with published := s.published + 1 } + +structure Safe (s : State) : Prop where + callbacks : s.published โ‰ค s.applied.length + fsm : s.applied.length โ‰ค s.committed + commit : s.committed โ‰ค s.wal + durable : s.wal โ‰ค s.log.length + originals : s.applied.map Applied.original = s.log.take s.applied.length + +theorem step_safe (h : Step s t) (ok : Safe s) : Safe t := by + obtain โŸจp, f, c, w, originalsโŸฉ := ok + cases h with + | turn => + exact โŸจp, f, c, by simp; omega, by + simpa only [List.take_append_of_le_length (show s.applied.length โ‰ค s.log.length by omega)] + using originalsโŸฉ + | message => exact โŸจp, f, c, w, originalsโŸฉ + | persist _ grows bound => exact โŸจp, f, Nat.le_trans c grows, bound, originalsโŸฉ + | commitReady _ grows bound => exact โŸจp, Nat.le_trans f grows, bound, w, originalsโŸฉ + | syncApply r v below atSlot => + refine โŸจ?_, ?_, c, w, ?_โŸฉ + ยท simpa using Nat.le_step p + ยท simpa using below + ยท simp [List.take_succ, atSlot, originals] + | publish next => exact โŸจnext, f, c, w, originalsโŸฉ + +inductive Reachable : State โ†’ Prop + | initial : Reachable {} + | next : Reachable s โ†’ Step s t โ†’ Reachable t + +theorem reachable_safe (h : Reachable s) : Safe s := by + induction h with + | initial => constructor <;> decide + | next _ step ih => exact step_safe step ih + +/-- Later turns and Ready events retain the old log, its durable prefix, +the per-entry application results, and the published callback prefix. -/ +theorem step_preserves_prefixes (h : Step s t) : + s.log <+: t.log โˆง s.log.take s.wal <+: t.log.take t.wal โˆง + s.applied <+: t.applied โˆง s.applied.take s.published <+: t.applied.take t.published := by + have growth : s.log <+: t.log โˆง s.wal โ‰ค t.wal โˆง + s.applied <+: t.applied โˆง s.published โ‰ค t.published := by + cases h <;> simp_all + obtain โŸจlogPrefix, wal, fsmPrefix, callbacksโŸฉ := growth + exact โŸจlogPrefix, List.prefix_take_iff.mpr โŸจ(List.take_prefix ..).trans logPrefix, + Nat.le_trans (List.length_take_le ..) walโŸฉ, fsmPrefix, + List.prefix_take_iff.mpr โŸจ(List.take_prefix ..).trans fsmPrefix, + Nat.le_trans (List.length_take_le ..) callbacksโŸฉโŸฉ + +/-- A single successful Save through the grouped suffix covers every accepted +member in that suffix by position. There is no requirement to commit or +publish it in that Ready. -/ +theorem grouped_wal_covers (old : List Request) (xs : List Attempt) (i k : Nat) + (covers : old.length + (entries xs).length โ‰ค k) (inside : i < (entries xs).length) : + ((old ++ entries xs).take k)[old.length + i]? = (entries xs)[i]? := by + rw [List.getElem?_take_of_lt (by omega), List.getElem?_append_right (by omega)] + simp + +/-- For an extant waiter r, resolveProposal matches ID and digest, and +nativeProposalResult separately validates the original caller context. +The slot is the callback's index (base+i+1); clients may consume out of order. +A missing waiter has no channel delivery. Error/ambiguous outcomes are outside +this success predicate. The validation instant is the return linearization +point: later revocation cannot withdraw a completed valid reply. -/ +def Success (s : State) (now : Nat โ†’ Bool) (r : Request) (i response : Nat) : Prop := + i < s.published โˆง โˆƒ a, s.applied[i]? = some a โˆง + a.original.id = r.id โˆง a.original.digest = r.digest โˆง + a.response = response โˆง now r.ctx = true + +theorem issue_cannot_create_reply (s : State) (first ext polls now r i v) : + Success { s with log := s.log ++ entries (members first ext polls) } now r i v โ†” + Success s now r i v := Iff.rfl + +theorem success_requires_original_durable_prefix (h : Reachable s) + (ret : Success s now r i v) + (ownID : โˆ€ e โˆˆ s.log, e.id = r.id โ†’ e = r) : + i < s.applied.length โˆง i < s.committed โˆง i < s.wal โˆง + (s.log.take s.wal)[i]? = some r โˆง s.applied[i]? = some โŸจr, vโŸฉ โˆง now r.ctx = true := by + obtain โŸจp, f, c, _, originalsโŸฉ := reachable_safe h + obtain โŸจpub, โŸจe, valueโŸฉ, atSlot, idMatch, _, rfl, validatedโŸฉ := ret + have lookup := congrArg (fun xs : List Request => xs[i]?) originals + simp only [List.getElem?_map, atSlot, Option.map_some, + List.getElem?_take_of_lt (show i < s.applied.length by omega)] at lookup + obtain rfl := ownID e (List.mem_of_getElem? lookup.symm) idMatch + exact โŸจby omega, by omega, by omega, by + rw [List.getElem?_take_of_lt (by omega)] + exact lookup.symm, atSlot, validatedโŸฉ + +theorem denied_cannot_consume (denied : now r.ctx = false) : + ยฌ Success s now r i v := by + rintro โŸจ_, _, _, _, _, _, validโŸฉ + exact Bool.noConfusion (denied.symm.trans valid) + +/-- A previous validation and a later denial refer to different instants, +even if exactly the same durable state and callback are visible at both. -/ +theorem later_revocation (prior : Success s thenValid r i v) + (revoked : now r.ctx = false) : + Success s thenValid r i v โˆง ยฌ Success s now r i v := + โŸจprior, denied_cannot_consume revokedโŸฉ + +private def sample (n : Nat) : Attempt where + request := โŸจn, n + 10, [UInt8.ofNat n], n + 100โŸฉ + guards := true + check := fun ctx payload digest => + ctx == n && payload == [UInt8.ofNat n] && digest == n + 100 + nativeOK := true + dataOnly := true + +/-- One two-member turn, one WAL frontier advance, two applications and two +ordered publications. At the first publication the second caller cannot yet +return; at the end each can observe its own value. -/ +theorem two_members_one_save : + โˆƒ middle final, Reachable middle โˆง Reachable final โˆง + middle.wal = 2 โˆง Success middle (ยท == 1) (sample 1).request 0 71 โˆง + (โˆ€ v, ยฌ Success middle (ยท == 2) (sample 2).request 1 v) โˆง + Success final (ยท == 2) (sample 2).request 1 82 := by + have turn := Reachable.initial.next (.turn (sample 1) true [some (sample 2)]) + have wal := turn.next (.persist 2 (by decide) (by decide)) + have committed := wal.next (.commitReady 2 (by decide) (by decide)) + have first := committed.next (.syncApply (sample 1).request 71 (by decide) rfl) + have middle := first.next (.publish (by decide)) + have second := middle.next (.syncApply (sample 2).request 82 (by decide) rfl) + have final := second.next (.publish (by decide)) + refine โŸจ_, _, middle, final, rfl, โŸจby decide, _, rfl, rfl, rfl, rfl, rflโŸฉ, ?_, + โŸจby decide, _, rfl, rfl, rfl, rfl, rflโŸฉโŸฉ + rintro v โŸจtooEarly, _โŸฉ + exact Nat.lt_irrefl 1 tooEarly + +#print axioms partition_preserves_entries +#print axioms reachable_safe +#print axioms success_requires_original_durable_prefix +#print axioms two_members_one_save + +end ProposalTurns diff --git a/lean/ReadCohorts.lean b/lean/ReadCohorts.lean new file mode 100644 index 000000000..910aef388 --- /dev/null +++ b/lean/ReadCohorts.lean @@ -0,0 +1,230 @@ +import Std + +/-! One fixed ReadOnlySafe leader, term, voter configuration and readOnly +instance. Ordinals are positive positions in its issue history. A remote Ack +denotes an accepted response to a real probe; dispatch alone has no transition. +The leader also records its local vote on issue. -/ +namespace ReadCohorts + +abbrev Votes := Nat โ†’ Nat + +structure Ack where + voter : Nat + ordinal : Nat + +def observe (a : Votes) (e : Ack) : Votes := + fun p => if p = e.voter then max (a p) e.ordinal else a p + +def replay (a : Votes) (events : List Ack) : Votes := events.foldl observe a + +private theorem observe_comm (a : Votes) (x y : Ack) : + observe (observe a x) y = observe (observe a y) x := by + funext p + simp only [observe] + split <;> split <;> simp_all <;> omega + +private theorem replay_comm (a : Votes) (x : Ack) (xs : List Ack) : + replay (observe a x) xs = observe (replay a xs) x := by + induction xs generalizing a with + | nil => rfl + | cons y ys ih => + change replay (observe (observe a x) y) ys = observe (replay (observe a y) ys) x + rw [observe_comm a x y, ih] + +-- Remove one dominated delivery anywhere before the real later response. +-- Equality of the entire vote map allows repeated deletions, any joint +-- configuration, and arbitrary common activity between/after the deliveries. +theorem omitDominated (a : Votes) (p lo hi : Nat) (between after : List Ack) + (ordered : lo โ‰ค hi) : + replay a (โŸจp, loโŸฉ :: between ++ โŸจp, hiโŸฉ :: after) = + replay a (between ++ โŸจp, hiโŸฉ :: after) := by + simp only [replay, List.foldl_cons, List.foldl_append] + rw [show between.foldl observe (observe a โŸจp, loโŸฉ) = + observe (between.foldl observe a) โŸจp, loโŸฉ from replay_comm ..] + congr 1 + funext q + by_cases h : q = p <;> simp [observe, h, Nat.max_assoc, Nat.max_eq_right ordered] + +structure Config where + incoming : List Nat + outgoing : List Nat + +-- Each list represents a set of distinct voter IDs. An empty outgoing half +-- is the ordinary (non-joint) case. Only membership of a voter set counts. +def votesAt (voters : List Nat) (a : Votes) (k : Nat) : Nat := + (voters.filter fun p => decide (k โ‰ค a p)).length + +def Majority (voters : List Nat) (a : Votes) (k : Nat) : Prop := + voters.length < 2 * votesAt voters a k + +def Covered (c : Config) (a : Votes) (k : Nat) : Prop := + Majority c.incoming a k โˆง (c.outgoing = [] โˆจ Majority c.outgoing a k) + +-- Transfer quorum coverage whenever every supporting vote is preserved. +private theorem coveredOfSupport {c : Config} {a b : Votes} {hi lo : Nat} + (transfer : โˆ€ p, hi โ‰ค a p โ†’ lo โ‰ค b p) (h : Covered c a hi) : Covered c b lo := by + have down (vs : List Nat) (m : Majority vs a hi) : Majority vs b lo := by + have counts : votesAt vs a hi โ‰ค votesAt vs b lo := by + clear m + induction vs with + | nil => simp [votesAt] + | cons p ps ih => + by_cases high : hi โ‰ค a p + ยท simp [votesAt, high, transfer p high] at ih โŠข + exact ih + ยท by_cases low : lo โ‰ค b p <;> simp [votesAt, high, low] at ih โŠข <;> omega + unfold Majority at * + omega + exact โŸจdown _ h.1, h.2.imp_right (down _)โŸฉ + +theorem coveredPrefix {c : Config} {a : Votes} {lo hi : Nat} (le : lo โ‰ค hi) + (h : Covered c a hi) : Covered c a lo := + coveredOfSupport (fun _ => Nat.le_trans le) h + +structure Binding where + operation : Nat + receipt : Option Nat + deriving DecidableEq + +structure Request where + id : Nat -- the application's unique RequestCtx + binding : Binding + waitApplied : Bool + +structure Issued where + request : Request + index : Nat -- committed index when queued by readOnly + +structure ReadState where + requestCtx : Nat + index : Nat + deriving DecidableEq + +def Issued.result (r : Issued) : ReadState := โŸจr.request.id, r.indexโŸฉ + +abbrev Live := Binding โ†’ Prop + +def Authorized (live : Live) (r : Request) (presented : Binding) : Prop := + presented = r.binding โˆง live presented + +-- One accepted native action appends one entry. Pre-current-term-commit +-- buffering and singleton reads are outside this multi-voter abstraction. +inductive Issue (live : Live) (history : List Issued) (r : Request) + (presented : Binding) (index : Nat) : List Issued โ†’ Prop where + | checked : Authorized live r presented โ†’ + Issue live history r presented index (history ++ [โŸจr, indexโŸฉ]) + +theorem issueAppendsOwnRead {live history r b index next} + (h : Issue live history r b index next) : + Authorized live r b โˆง next[history.length]? = some โŸจr, indexโŸฉ := by + cases h with + | checked ok => exact โŸจok, by simpโŸฉ + +-- A zero-based slot requires the corresponding one-based quorum ordinal. +def Published (c : Config) (a : Votes) (history : List Issued) (slot : Nat) + (rs : ReadState) : Prop := + Covered c a (slot + 1) โˆง (history[slot]?).map Issued.result = some rs + +theorem sameAcceptedPrefix (c : Config) (a : Votes) (history : List Issued) + (p lo hi : Nat) (between after : List Ack) (ordered : lo โ‰ค hi) : + Published c (replay a (โŸจp, loโŸฉ :: between ++ โŸจp, hiโŸฉ :: after)) history = + Published c (replay a (between ++ โŸจp, hiโŸฉ :: after)) history := by + rw [omitDominated a p lo hi between after ordered] + +-- Even if the retained probe never gets an answer, removing a delivery +-- cannot create a newly publishable read under the same other deliveries. +theorem omissionCannotCreateResult (c : Config) (a : Votes) (e : Ack) + (rest : List Ack) (history : List Issued) (slot : Nat) (rs : ReadState) + (pub : Published c (replay a rest) history slot rs) : + Published c (replay a (e :: rest)) history slot rs := by + change Published c (replay (observe a e) rest) history slot rs + rw [replay_comm] + refine โŸจcoveredOfSupport (fun p hp => ?_) pub.1, pub.2โŸฉ + by_cases hit : p = e.voter + ยท exact Nat.le_trans hp (by simpa only [observe, if_pos hit] using Nat.le_max_left (replay a rest p) e.ordinal) + ยท simpa [observe, hit] using hp + +theorem missingQuorum {c a history slot rs} + (missing : ยฌ Majority c.incoming a (slot + 1) โˆจ + (c.outgoing โ‰  [] โˆง ยฌ Majority c.outgoing a (slot + 1))) : + ยฌ Published c a history slot rs := by + intro h + rcases missing with no | โŸจjoint, noโŸฉ + ยท exact no h.1.1 + ยท exact no (h.1.2.resolve_left joint) + +theorem lateIssueCannotUseOldPrefix {live history r b index next} + (issue : Issue live history r b index next) (c : Config) (old : Votes) + (bounded : โˆ€ p โˆˆ c.incoming, old p โ‰ค history.length) (rs : ReadState) : + next[history.length]? = some โŸจr, indexโŸฉ โˆง ยฌ Published c old next history.length rs := by + refine โŸจ(issueAppendsOwnRead issue).2, ?_โŸฉ + apply missingQuorum + left + have none : (c.incoming.filter fun p => decide (history.length + 1 โ‰ค old p)) = [] := by + apply List.filter_eq_nil_iff.mpr + intro p hp + have := bounded p hp + simp only [decide_eq_true_eq] + omega + simp [Majority, votesAt, none] + +theorem issuedResultKeepsContextAndIndex {live history r b index next c a rs} + (h : Issue live history r b index next) + (pub : Published c a next history.length rs) : rs = โŸจr.id, indexโŸฉ := by + have result := pub.2 + rw [(issueAppendsOwnRead h).2] at result + exact (Option.some.inj result).symm + +-- Result authorization is a separate observation, after issue and quorum. +def Consume (live : Live) (r : Request) (b : Binding) (rs : ReadState) + (applied : Nat) : Prop := + Authorized live r b โˆง rs.requestCtx = r.id โˆง (r.waitApplied = true โ†’ rs.index โ‰ค applied) + +def revoke (live : Live) (lost : Binding) : Live := fun b => live b โˆง b โ‰  lost + +theorem otherCallerCannotUseResult {live history r b index next c a rs} + (issue : Issue live history r b index next) (pub : Published c a next history.length rs) + (other : Request) (distinct : r.id โ‰  other.id) (now handle applied) : + ยฌ Consume now other handle rs applied := by + intro used + rw [issuedResultKeepsContextAndIndex issue pub] at used + exact distinct used.2.1 + +theorem revokedCannotConsume (live : Live) (r : Request) (b rs applied) : + ยฌ Consume (revoke live r.binding) r b rs applied := by + intro h + exact h.1.2.2 h.1.1 + +theorem independentCanStillConsume {live r b rs applied lost} + (distinct : r.binding โ‰  lost) : + Consume (revoke live lost) r b rs applied โ†” Consume live r b rs applied := by + constructor + ยท intro h + exact โŸจโŸจh.1.1, h.1.2.1โŸฉ, h.2โŸฉ + ยท intro h + exact โŸจโŸจh.1.1, h.1.2, h.1.1 โ–ธ distinctโŸฉ, h.2โŸฉ + +theorem appliedReadReachedOwnIndex {live history r b index next c a rs now handle applied} + (issue : Issue live history r b index next) (pub : Published c a next history.length rs) + (used : Consume now r handle rs applied) (waits : r.waitApplied = true) : + index โ‰ค applied := by + rw [issuedResultKeepsContextAndIndex issue pub] at used + exact used.2.2 waits + +-- One waiter's pending-map slot. Registration samples ctx.Err inside the +-- same mutex used for cleanup. Cancellation is sticky; cleanup can lag it. +structure Waiter where + cancelled : Bool + pending : Bool + +def register (s : Waiter) : Waiter := if s.cancelled then s else { s with pending := true } +def cancel (s : Waiter) : Waiter := { s with cancelled := true } +def cleanup (s : Waiter) : Waiter := { s with pending := false } + +theorem noOrphanAtRegistration (s : Waiter) : + (register (cleanup (cancel s))).pending = false โˆง + (cleanup (register (cancel s))).pending = false โˆง + (cleanup (cancel (register s))).pending = false := by + simp [register, cleanup, cancel] + +end ReadCohorts diff --git a/lean/SingleKeyCAS.lean b/lean/SingleKeyCAS.lean new file mode 100644 index 000000000..b780646b2 --- /dev/null +++ b/lean/SingleKeyCAS.lean @@ -0,0 +1,369 @@ +import Std + +/-! One byte-range key in one Raft data group. See tla/cas/README.md for +the implementation correspondence, assumptions and TLC companion. -/ +namespace SingleKeyCAS + +structure Row where + version : Nat + value : Nat + deriving DecidableEq, Repr + +structure Catalog where + version : Nat := 1 + owns : Bool := true + fenced : Bool := false + deriving DecidableEq, Repr + +inductive Entry where + | activate + | catalog (catalog : Catalog) + | armMigration (armed : Bool) + | certifyMigration + | put (row : Row) + | cas (observed expected : Nat) (replacement : Row) + | cleanup (cursor ceiling limit : Nat) + deriving DecidableEq, Repr + +inductive Verdict where + | control + | written + | applied (version : Nat) + | mismatch + | timestamp + | unavailable + | routeFenced + | missingCatalog + | cleanupBlocked + | cleaned + deriving DecidableEq, Repr + +structure Image where + catalog : Option Catalog + protection : Bool := false + migrationArmed : Bool := false + migrationCovered : Bool := false + rows : List Row := [โŸจ1, 0โŸฉ] + issued : Nat := 1 + -- Proof history. Neither the consumed tokens nor the verdicts are stored by Go. + consumed : List Nat := [] + verdicts : List Verdict := [] + deriving DecidableEq, Repr + +def initial (authority : Bool) : Image := + { catalog := if authority then some {} else none } + +-- Admission binds the frame to this group and its observed catalog version. +-- A broken apply precondition halts without publishing the next index. +def canApply (s : Image) : Entry โ†’ Prop + | .cas observed _ _ => + s.protection = true โˆง โˆƒ route, s.catalog = some route โˆง observed โ‰ค route.version + | _ => True + +def headVersion (s : Image) : Nat := + (s.rows.head?.map Row.version).getD 0 + +def record (s : Image) (v : Verdict) : Image := + { s with verdicts := v :: s.verdicts } + +def write (s : Image) (row : Row) : Image := + { s with rows := row :: s.rows, issued := row.version } + +-- One command selects at most limit rows, newest first, after the cursor +-- and at or below the ceiling. Versions within a history are unique. +def cleanupRows (rows : List Row) (cursor ceiling limit : Nat) : List Row := + let selected := ((rows.drop cursor).filter (fun row => row.version โ‰ค ceiling)).take limit + rows.filter (fun row => row โˆ‰ selected) + +-- The two optional arguments only restore the old behavior in the examples. +-- The normal transition does not consult the watcher. +def step (s : Image) (e : Entry) (oldWatcher : Option Nat := none) + (oldCleanup : Bool := false) : Image := + match e with + | .activate => record { s with protection := true } .control + | .catalog next => record { s with catalog := s.catalog.map (fun _ => next) } .control + | .armMigration armed => record { s with migrationArmed := armed } .control + | .certifyMigration => record { s with migrationCovered := true } .control + | .put row => + if s.issued < row.version then record (write s row) .written + else record s .timestamp + | .cas observed expected row => + if !s.protection then record s .unavailable + else + match s.catalog with + | none => record s .unavailable + | some route => + if !route.owns || route.fenced then record s .routeFenced + else if s.migrationArmed || s.migrationCovered then record s .unavailable + else if oldWatcher.any (ยท < observed) then record s .missingCatalog + else if s.issued < row.version then + if expected = 0 โˆจ expected โ‰  headVersion s then record s .mismatch + else record { write s row with consumed := expected :: s.consumed } (.applied row.version) + else record s .timestamp + | .cleanup cursor ceiling limit => + if s.protection && !oldCleanup && !s.migrationCovered then record s .cleanupBlocked + else record { s with rows := cleanupRows s.rows cursor ceiling limit } .cleaned + +-- A committed log is fixed during the proof. Applying the next entry +-- publishes the image and progress together. A replay at an already +-- durable index is skipped, even if the watcher has since advanced. +structure Replica where + applied : Nat := 0 + watcher : Nat := 1 + image : Image + deriving DecidableEq, Repr + +inductive Run (authority : Bool) (log : List Entry) : Replica โ†’ Prop where + | start : Run authority log { image := initial authority } + | watch {r : Replica} (h : Run authority log r) (version : Nat) (advance : r.watcher โ‰ค version) : + Run authority log { r with watcher := version } + | apply {r : Replica} {e : Entry} (h : Run authority log r) (entry : log[r.applied]? = some e) + (ready : canApply r.image e) : + Run authority log { r with applied := r.applied + 1, image := step r.image e } + | restart {r : Replica} (h : Run authority log r) : + Run authority log { r with watcher := 1 } + | replay {r : Replica} (h : Run authority log r) (index : Nat) + (durable : 0 < index โˆง index โ‰ค r.applied) : Run authority log r + +def prefixImage (authority : Bool) (log : List Entry) (index : Nat) : Image := + (log.take index).foldl (fun s e => step s e) (initial authority) + +theorem applied_prefix {authority log r} (h : Run authority log r) : + r.applied โ‰ค log.length โˆง r.image = prefixImage authority log r.applied := by + induction h with + | start => simp [prefixImage] + | watch _ _ _ ih => exact ih + | restart _ ih => exact ih + | replay _ _ _ ih => exact ih + | @apply r e _ entry _ ih => + have inside := List.getElem?_eq_some_iff.mp entry + refine โŸจNat.succ_le_of_lt inside.1, ?_โŸฉ + simp [prefixImage, List.take_succ, entry, List.foldl_append, ih.2, prefixImage] + +-- The images include ownership/fences, protection, all version/value +-- rows, and the verdict of every entry in the prefix. Watchers may differ. +theorem replica_agreement {authority log a b} (ha : Run authority log a) (hb : Run authority log b) + (sameIndex : a.applied = b.applied) : a.image = b.image := by + rw [(applied_prefix ha).2, (applied_prefix hb).2, sameIndex] + +structure Safe (s : Image) : Prop where + headBound : headVersion s โ‰ค s.issued + -- Bound the whole history so that removal can never make the clock go backwards. + rowsBound : โˆ€ row โˆˆ s.rows, row.version โ‰ค s.issued + once : s.consumed.Nodup + issuedBound : โˆ€ token โˆˆ s.consumed, token < s.issued + unrevivable : s.migrationCovered = false โ†’ โˆ€ token โˆˆ s.consumed, token < headVersion s + beforeActivation : s.protection = false โ†’ s.consumed = [] + +private theorem head_le {s : Image} (h : โˆ€ row โˆˆ s.rows, row.version โ‰ค s.issued) : + headVersion s โ‰ค s.issued := by + cases hs : s.rows with + | nil => simp [headVersion, hs] + | cons row tail => simpa [headVersion, hs] using h row (by simp [hs]) + +private theorem safe_initial (authority : Bool) : Safe (initial authority) := by + constructor <;> simp [initial, headVersion] + +private theorem safe_write {s : Image} (h : Safe s) {row : Row} (fresh : s.issued < row.version) : + Safe (write s row) := by + have rows : โˆ€ v โˆˆ (write s row).rows, v.version โ‰ค (write s row).issued := by + intro v hv + simp only [write, List.mem_cons] at hv โŠข + rcases hv with rfl | hv + ยท exact Nat.le_refl _ + ยท exact Nat.le_trans (h.rowsBound v hv) (Nat.le_of_lt fresh) + refine โŸจhead_le rows, rows, h.once, ?_, ?_, h.beforeActivationโŸฉ + ยท exact fun t ht => Nat.lt_trans (h.issuedBound t ht) fresh + ยท exact fun _ t ht => Nat.lt_trans (h.issuedBound t ht) fresh + +private theorem safe_consume {s : Image} (h : Safe s) {row : Row} {token : Nat} + (active : s.protection = true) (eligible : s.migrationCovered = false) + (head : token = headVersion s) (fresh : s.issued < row.version) : + Safe { write s row with consumed := token :: s.consumed } := by + have hw := safe_write h fresh + have newToken : token โˆ‰ s.consumed := by + intro mem + have := h.unrevivable eligible token mem + omega + have newer : token < row.version := by + have := h.headBound + omega + refine โŸจhw.headBound, hw.rowsBound, List.nodup_cons.mpr โŸจnewToken, h.onceโŸฉ, ?_, ?_, ?_โŸฉ + ยท intro t ht + rcases List.mem_cons.mp ht with rfl | ht + ยท exact newer + ยท exact hw.issuedBound t ht + ยท intro _ t ht + rcases List.mem_cons.mp ht with rfl | ht + ยท exact newer + ยท exact hw.issuedBound t ht + ยท simp [write, active] + +private theorem safe_cleanup {s : Image} (h : Safe s) {c u l : Nat} + (allowed : s.protection = false โˆจ s.migrationCovered = true) : + Safe { s with rows := cleanupRows s.rows c u l } := by + have rows : โˆ€ v โˆˆ cleanupRows s.rows c u l, v.version โ‰ค s.issued := by + intro v hv + exact h.rowsBound v (List.mem_filter.mp hv).1 + refine โŸจhead_le rows, rows, h.once, h.issuedBound, ?_, h.beforeActivationโŸฉ + intro eligible t ht + rcases allowed with inactive | excluded + ยท simp [h.beforeActivation inactive] at ht + ยท exact False.elim (Bool.false_ne_true (eligible.symm.trans excluded)) + +private theorem safe_record {s : Image} (h : Safe s) (v : Verdict) : Safe (record s v) := + โŸจh.headBound, h.rowsBound, h.once, h.issuedBound, h.unrevivable, h.beforeActivationโŸฉ + +private theorem safe_step {s : Image} (h : Safe s) (e : Entry) : Safe (step s e) := by + cases e <;> simp only [step] + case activate => + exact โŸจh.headBound, h.rowsBound, h.once, h.issuedBound, h.unrevivable, by simp [record]โŸฉ + case catalog => + exact โŸจh.headBound, h.rowsBound, h.once, h.issuedBound, h.unrevivable, h.beforeActivationโŸฉ + case armMigration => + exact โŸจh.headBound, h.rowsBound, h.once, h.issuedBound, h.unrevivable, h.beforeActivationโŸฉ + case certifyMigration => + exact โŸจh.headBound, h.rowsBound, h.once, h.issuedBound, by simp [record], h.beforeActivationโŸฉ + case put => + split + ยท exact safe_record (safe_write h โ€น_โ€บ) _ + ยท exact safe_record h _ + case cas observed expected row => + split + ยท exact safe_record h _ + rename_i inactive + have active : s.protection = true := by simp at inactive; exact inactive + split + ยท exact safe_record h _ + split + ยท exact safe_record h _ + split + ยท exact safe_record h _ + rename_i migration + have uncovered : s.migrationCovered = false := by + cases hm : s.migrationCovered <;> simp_all + simp only [Option.any_none, Bool.false_eq_true, if_false] + split + ยท rename_i fresh + split + ยท exact safe_record h _ + ยท rename_i mismatch + have same : expected = headVersion s := by + apply Classical.byContradiction + intro neq + exact mismatch (Or.inr neq) + exact safe_record (safe_consume h active uncovered same fresh) _ + ยท exact safe_record h _ + case cleanup cursor ceiling limit => + split + ยท exact safe_record h _ + rename_i notBlocked + have allowed : s.protection = false โˆจ s.migrationCovered = true := by + cases hp : s.protection <;> cases hm : s.migrationCovered <;> simp_all + exact safe_record (safe_cleanup h allowed) _ + +theorem reachable_safe {authority log r} (h : Run authority log r) : Safe r.image := by + induction h with + | start => exact safe_initial authority + | watch _ _ _ ih => exact ih + | apply _ _ _ ih => exact safe_step ih _ + | restart _ ih => exact ih + | replay _ _ _ ih => exact ih + +theorem token_consumed_at_most_once {authority log r} (h : Run authority log r) : + r.image.consumed.Nodup := + (reachable_safe h).once + +-- Even with a changed catalog or leader, no consumed token can be +-- current in a range which remains eligible for CAS. +theorem consumed_token_stays_below_head {authority log r} (h : Run authority log r) + (eligible : r.image.migrationCovered = false) {token : Nat} (used : token โˆˆ r.image.consumed) : + token < headVersion r.image := + (reachable_safe h).unrevivable eligible token used + +theorem consumed_token_cannot_apply_again {authority log r} (h : Run authority log r) + {token : Nat} (used : token โˆˆ r.image.consumed) (observed version : Nat) (row : Row) : + (step r.image (.cas observed token row)).verdicts.head? โ‰  some (.applied version) := by + simp only [step, Option.any_none, Bool.false_eq_true, if_false] + split + ยท simp [record] + split + ยท simp [record] + split + ยท simp [record] + split + ยท simp [record] + rename_i migration + have uncovered : r.image.migrationCovered = false := by + cases hm : r.image.migrationCovered <;> simp_all + have stale := Nat.ne_of_lt (consumed_token_stays_below_head h uncovered used) + simp [stale, record] <;> split <;> simp + +theorem issued_never_decreases (s : Image) (e : Entry) : s.issued โ‰ค (step s e).issued := by + cases e <;> simp only [step] <;> + repeat (first | exact Nat.le_refl _ | exact Nat.le_of_lt (by assumption) | split) + +theorem producing_version_strictly_increases (s : Image) (e : Entry) : + s.rows.length < (step s e).rows.length โ†’ s.issued < (step s e).issued := by + cases e <;> simp only [step] + case cleanup cursor ceiling limit => + split + ยท simp [record] + ยท intro growth + have bound : (cleanupRows s.rows cursor ceiling limit).length โ‰ค s.rows.length := + List.length_filter_le _ _ + exact False.elim (Nat.not_lt_of_ge bound growth) + all_goals + repeat (first | simp [record, write, *] | split) + +private def active : Image := step (initial true) .activate +private def splitImage : Image := step active (.catalog { version := 2 }) +private def first : Entry := .cas 2 1 โŸจ2, 7โŸฉ +private def retry : Entry := .cas 2 1 โŸจ3, 8โŸฉ +private def boundedCleanup : Entry := .cleanup 0 2 1 + +example : canApply splitImage first := + โŸจrfl, { version := 2 }, rfl, Nat.le_refl _โŸฉ +example : ยฌ canApply active first := by simp [active, first, canApply, step, initial, record] +example : ยฌ canApply (step (initial false) .activate) first := by + simp [first, canApply, step, initial, record] + +-- Old apply skips a committed CAS on the replica behind the same-owner split +-- even though both replicas durably record the same progress. +private def oldReplica (watcher : Nat) : Replica := + { applied := 3, watcher, image := step splitImage first (some watcher) } + +example : (oldReplica 2).applied = (oldReplica 1).applied โˆง + (oldReplica 2).image.rows โ‰  (oldReplica 1).image.rows := by decide +example : (oldReplica 1).image.verdicts.head? = some .missingCatalog := by decide + +-- Old cleanup deletes only version 2, exposes version 1, and consumes it twice. +example : (step (step (step splitImage first) boundedCleanup none true) retry).consumed = [1, 1] := by + decide + +example : (step (step (step splitImage first) boundedCleanup) retry).verdicts.head? = some .mismatch := by + decide + +example : (step (step splitImage (.catalog { version := 3, fenced := true })) first).verdicts.head? = + some .routeFenced := by decide + +private def armedImage : Image := step (step splitImage first) (.armMigration true) + +example : (step armedImage boundedCleanup).verdicts.head? = some .cleanupBlocked := by decide + +example : + let cleaned := step (step armedImage .certifyMigration) boundedCleanup + headVersion cleaned = 1 โˆง + (step (step cleaned (.armMigration false)) retry).verdicts.head? = some .unavailable := by + decide + +-- Compaction may discard older physical rows independently while preserving +-- the same current row. Covered ranges can still have ordinary point readers. +example : + let kept := step armedImage .certifyMigration + let compacted := { kept with rows := kept.rows.take 1 } + kept.rows.head? = compacted.rows.head? โˆง + (step kept boundedCleanup).rows.head? โ‰  (step compacted boundedCleanup).rows.head? := by + decide + +end SingleKeyCAS diff --git a/lean/VersionAdoption.lean b/lean/VersionAdoption.lean new file mode 100644 index 000000000..df8a7a110 --- /dev/null +++ b/lean/VersionAdoption.lean @@ -0,0 +1,64 @@ +import Std + +namespace VersionAdoption + +structure Row where + timestamp : Nat + value : Nat + expiry : Nat + epoch : Nat + deriving DecidableEq, Repr + +def retained (ceiling retiredEpoch : Nat) (row : Row) : Prop := + ceiling < row.timestamp โˆจ retiredEpoch < row.epoch + +instance (ceiling retiredEpoch : Nat) (row : Row) : Decidable (retained ceiling retiredEpoch row) := + inferInstanceAs (Decidable (_ โˆจ _)) + +def visible (ceiling retiredEpoch : Nat) (rows : List Row) : List Row := + rows.filter (fun row => retained ceiling retiredEpoch row) + +def reclaim (rows selected : List Row) : List Row := + rows.filter (fun row => row โˆ‰ selected) + +theorem old_gc_preserves_returned_rows (rows selected : List Row) (ceiling retiredEpoch : Nat) + (onlyRetired : โˆ€ row โˆˆ selected, row.timestamp โ‰ค ceiling โˆง row.epoch โ‰ค retiredEpoch) : + visible ceiling retiredEpoch (reclaim rows selected) = visible ceiling retiredEpoch rows := by + induction rows with + | nil => rfl + | cons row tail ih => + by_cases selectedRow : row โˆˆ selected + ยท have bounds := onlyRetired row selectedRow + have hidden : ยฌ retained ceiling retiredEpoch row := by + simp only [retained, not_or] + exact โŸจNat.not_lt_of_ge bounds.1, Nat.not_lt_of_ge bounds.2โŸฉ + simpa [visible, reclaim, selectedRow, hidden] using ih + ยท by_cases live : retained ceiling retiredEpoch row + ยท simpa [visible, reclaim, selectedRow, live] using congrArg (List.cons row) ih + ยท simpa [visible, reclaim, selectedRow, live] using ih + +def adopt (row : Row) (epoch : Nat) : Row := { row with epoch := epoch } + +theorem adoption_preserves_timestamp_and_ttl (row : Row) (epoch : Nat) : + (adopt row epoch).timestamp = row.timestamp โˆง + (adopt row epoch).value = row.value โˆง (adopt row epoch).expiry = row.expiry := by + simp [adopt] + +theorem authorized_return_is_visible (row : Row) (ceiling retiredEpoch epoch : Nat) + (newEpoch : retiredEpoch < epoch) : retained ceiling retiredEpoch (adopt row epoch) := by + exact Or.inr newEpoch + +theorem later_retirement_hides_return (row : Row) (ceiling retiredEpoch : Nat) + (oldTimestamp : row.timestamp โ‰ค ceiling) (oldEpoch : row.epoch โ‰ค retiredEpoch) : + ยฌ retained ceiling retiredEpoch row := by + simp only [retained, not_or] + exact โŸจNat.not_lt_of_ge oldTimestamp, Nat.not_lt_of_ge oldEpochโŸฉ + +private def returned : Row := โŸจ10, 7, 1000, 3โŸฉ + +-- An old timestamp-only collector would physically erase this new generation. +example : visible 20 2 [returned] = [returned] โˆง reclaim [returned] [returned] = [] := by decide + +example : visible 20 4 [returned] = [] := by decide + +end VersionAdoption diff --git a/proto/internal.pb.go b/proto/internal.pb.go index 2de96d5dc..771911d94 100644 --- a/proto/internal.pb.go +++ b/proto/internal.pb.go @@ -33,6 +33,8 @@ const ( // node, so the Raft log contains only a single mutation regardless of how // many keys are deleted. Op_DEL_PREFIX Op = 2 + // Conditional replacement of exactly one live MVCC version in a 1PC. + Op_COMPARE_AND_SWAP Op = 3 ) // Enum value maps for Op. @@ -41,11 +43,13 @@ var ( 0: "PUT", 1: "DEL", 2: "DEL_PREFIX", + 3: "COMPARE_AND_SWAP", } Op_value = map[string]int32{ - "PUT": 0, - "DEL": 1, - "DEL_PREFIX": 2, + "PUT": 0, + "DEL": 1, + "DEL_PREFIX": 2, + "COMPARE_AND_SWAP": 3, } ) @@ -187,12 +191,14 @@ func (ForwardFailurePhase) EnumDescriptor() ([]byte, []int) { type ForwardFailureReason int32 const ( - ForwardFailureReason_FORWARD_FAILURE_REASON_UNSPECIFIED ForwardFailureReason = 0 - ForwardFailureReason_FORWARD_FAILURE_REASON_CONFLICT ForwardFailureReason = 1 - ForwardFailureReason_FORWARD_FAILURE_REASON_FENCE ForwardFailureReason = 2 - ForwardFailureReason_FORWARD_FAILURE_REASON_NO_LEADER ForwardFailureReason = 3 - ForwardFailureReason_FORWARD_FAILURE_REASON_INTERRUPTED ForwardFailureReason = 4 - ForwardFailureReason_FORWARD_FAILURE_REASON_ABORTED ForwardFailureReason = 5 + ForwardFailureReason_FORWARD_FAILURE_REASON_UNSPECIFIED ForwardFailureReason = 0 + ForwardFailureReason_FORWARD_FAILURE_REASON_CONFLICT ForwardFailureReason = 1 + ForwardFailureReason_FORWARD_FAILURE_REASON_FENCE ForwardFailureReason = 2 + ForwardFailureReason_FORWARD_FAILURE_REASON_NO_LEADER ForwardFailureReason = 3 + ForwardFailureReason_FORWARD_FAILURE_REASON_INTERRUPTED ForwardFailureReason = 4 + ForwardFailureReason_FORWARD_FAILURE_REASON_ABORTED ForwardFailureReason = 5 + ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_MISMATCH ForwardFailureReason = 6 + ForwardFailureReason_FORWARD_FAILURE_REASON_CAS_LOCKED ForwardFailureReason = 7 ) // Enum value maps for ForwardFailureReason. @@ -204,14 +210,18 @@ var ( 3: "FORWARD_FAILURE_REASON_NO_LEADER", 4: "FORWARD_FAILURE_REASON_INTERRUPTED", 5: "FORWARD_FAILURE_REASON_ABORTED", + 6: "FORWARD_FAILURE_REASON_CAS_MISMATCH", + 7: "FORWARD_FAILURE_REASON_CAS_LOCKED", } ForwardFailureReason_value = map[string]int32{ - "FORWARD_FAILURE_REASON_UNSPECIFIED": 0, - "FORWARD_FAILURE_REASON_CONFLICT": 1, - "FORWARD_FAILURE_REASON_FENCE": 2, - "FORWARD_FAILURE_REASON_NO_LEADER": 3, - "FORWARD_FAILURE_REASON_INTERRUPTED": 4, - "FORWARD_FAILURE_REASON_ABORTED": 5, + "FORWARD_FAILURE_REASON_UNSPECIFIED": 0, + "FORWARD_FAILURE_REASON_CONFLICT": 1, + "FORWARD_FAILURE_REASON_FENCE": 2, + "FORWARD_FAILURE_REASON_NO_LEADER": 3, + "FORWARD_FAILURE_REASON_INTERRUPTED": 4, + "FORWARD_FAILURE_REASON_ABORTED": 5, + "FORWARD_FAILURE_REASON_CAS_MISMATCH": 6, + "FORWARD_FAILURE_REASON_CAS_LOCKED": 7, } ) @@ -428,6 +438,8 @@ const ( MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_OWNERSHIP_APPLIED MigrationStateProbeKind = 8 MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_PARTITION_APPLIED MigrationStateProbeKind = 9 MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_NAMESPACE_ADMISSION MigrationStateProbeKind = 10 + // Bounded, local-only GC authorized exclusively by an existing retirement. + MigrationStateProbeKind_MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS MigrationStateProbeKind = 11 ) // Enum value maps for MigrationStateProbeKind. @@ -444,6 +456,7 @@ var ( 8: "MIGRATION_STATE_PROBE_KIND_OWNERSHIP_APPLIED", 9: "MIGRATION_STATE_PROBE_KIND_PARTITION_APPLIED", 10: "MIGRATION_STATE_PROBE_KIND_NAMESPACE_ADMISSION", + 11: "MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS", } MigrationStateProbeKind_value = map[string]int32{ "MIGRATION_STATE_PROBE_KIND_UNSPECIFIED": 0, @@ -457,6 +470,7 @@ var ( "MIGRATION_STATE_PROBE_KIND_OWNERSHIP_APPLIED": 8, "MIGRATION_STATE_PROBE_KIND_PARTITION_APPLIED": 9, "MIGRATION_STATE_PROBE_KIND_NAMESPACE_ADMISSION": 10, + "MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS": 11, } ) @@ -501,9 +515,10 @@ type Mutation struct { // require_absent is the TTL-inline relocation precondition: no committed // version of key, including tombstones, may exist when the 1PC applies. // It requires the replicated TTL-inline capability on every voter/learner. - RequireAbsent bool `protobuf:"varint,5,opt,name=require_absent,json=requireAbsent,proto3" json:"require_absent,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + RequireAbsent bool `protobuf:"varint,5,opt,name=require_absent,json=requireAbsent,proto3" json:"require_absent,omitempty"` + ExpectedCommitTs uint64 `protobuf:"varint,6,opt,name=expected_commit_ts,json=expectedCommitTs,proto3" json:"expected_commit_ts,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Mutation) Reset() { @@ -571,6 +586,13 @@ func (x *Mutation) GetRequireAbsent() bool { return false } +func (x *Mutation) GetExpectedCommitTs() uint64 { + if x != nil { + return x.ExpectedCommitTs + } + return 0 +} + type Request struct { state protoimpl.MessageState `protogen:"open.v1"` IsTxn bool `protobuf:"varint,1,opt,name=is_txn,json=isTxn,proto3" json:"is_txn,omitempty"` @@ -609,8 +631,11 @@ type Request struct { // The leader term that prepared this binding. The proposer checks it in // the Raft event loop before submitting the entry. TimestampBindingAdmissionTerm uint64 `protobuf:"varint,10,opt,name=timestamp_binding_admission_term,json=timestampBindingAdmissionTerm,proto3" json:"timestamp_binding_admission_term,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // The data group selected for a standalone CAS. Only its leader stamps + // observed_route_version, using that group's applied catalog. + VersionCasGroupId uint64 `protobuf:"varint,11,opt,name=version_cas_group_id,json=versionCasGroupId,proto3" json:"version_cas_group_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Request) Reset() { @@ -713,6 +738,13 @@ func (x *Request) GetTimestampBindingAdmissionTerm() uint64 { return 0 } +func (x *Request) GetVersionCasGroupId() uint64 { + if x != nil { + return x.VersionCasGroupId + } + return 0 +} + type RaftCommand struct { state protoimpl.MessageState `protogen:"open.v1"` Requests []*Request `protobuf:"bytes,1,rep,name=requests,proto3" json:"requests,omitempty"` @@ -2574,8 +2606,10 @@ type CleanupMigrationRequest struct { // Versioned namespace activation/prejoin control. Never propose until every // apply member (including learners) acknowledged support at this ConfChange. NamespaceAdmission []byte `protobuf:"bytes,21,opt,name=namespace_admission,json=namespaceAdmission,proto3" json:"namespace_admission,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Prevent a source cleanup from being replayed against a returning owner. + ExpectedSourceGroupId uint64 `protobuf:"varint,22,opt,name=expected_source_group_id,json=expectedSourceGroupId,proto3" json:"expected_source_group_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CleanupMigrationRequest) Reset() { @@ -2755,13 +2789,22 @@ func (x *CleanupMigrationRequest) GetNamespaceAdmission() []byte { return nil } +func (x *CleanupMigrationRequest) GetExpectedSourceGroupId() uint64 { + if x != nil { + return x.ExpectedSourceGroupId + } + return 0 +} + type CleanupMigrationResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - NextCursor []byte `protobuf:"bytes,1,opt,name=next_cursor,json=nextCursor,proto3" json:"next_cursor,omitempty"` - Done bool `protobuf:"varint,2,opt,name=done,proto3" json:"done,omitempty"` - DeletedRows uint64 `protobuf:"varint,3,opt,name=deleted_rows,json=deletedRows,proto3" json:"deleted_rows,omitempty"` - DeletedBytes uint64 `protobuf:"varint,4,opt,name=deleted_bytes,json=deletedBytes,proto3" json:"deleted_bytes,omitempty"` - ScannedBytes uint64 `protobuf:"varint,5,opt,name=scanned_bytes,json=scannedBytes,proto3" json:"scanned_bytes,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + NextCursor []byte `protobuf:"bytes,1,opt,name=next_cursor,json=nextCursor,proto3" json:"next_cursor,omitempty"` + Done bool `protobuf:"varint,2,opt,name=done,proto3" json:"done,omitempty"` + DeletedRows uint64 `protobuf:"varint,3,opt,name=deleted_rows,json=deletedRows,proto3" json:"deleted_rows,omitempty"` + DeletedBytes uint64 `protobuf:"varint,4,opt,name=deleted_bytes,json=deletedBytes,proto3" json:"deleted_bytes,omitempty"` + ScannedBytes uint64 `protobuf:"varint,5,opt,name=scanned_bytes,json=scannedBytes,proto3" json:"scanned_bytes,omitempty"` + // A committed logical retirement, not an all-member physical completion ACK. + RetirementId string `protobuf:"bytes,6,opt,name=retirement_id,json=retirementId,proto3" json:"retirement_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2831,6 +2874,13 @@ func (x *CleanupMigrationResponse) GetScannedBytes() uint64 { return 0 } +func (x *CleanupMigrationResponse) GetRetirementId() string { + if x != nil { + return x.RetirementId + } + return "" +} + type ProbeMigrationStateRequest struct { state protoimpl.MessageState `protogen:"open.v1"` JobId uint64 `protobuf:"varint,1,opt,name=job_id,json=jobId,proto3" json:"job_id,omitempty"` @@ -2861,6 +2911,7 @@ type ProbeMigrationStateRequest struct { // Canonical, immutable source seal required by the current apply members. OnlineSealedManifest []byte `protobuf:"bytes,23,opt,name=online_sealed_manifest,json=onlineSealedManifest,proto3" json:"online_sealed_manifest,omitempty"` RedisFenceReadFloor uint64 `protobuf:"varint,24,opt,name=redis_fence_read_floor,json=redisFenceReadFloor,proto3" json:"redis_fence_read_floor,omitempty"` + RetirementId string `protobuf:"bytes,25,opt,name=retirement_id,json=retirementId,proto3" json:"retirement_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -3063,6 +3114,13 @@ func (x *ProbeMigrationStateRequest) GetRedisFenceReadFloor() uint64 { return 0 } +func (x *ProbeMigrationStateRequest) GetRetirementId() string { + if x != nil { + return x.RetirementId + } + return "" +} + type ProbeMigrationStateResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Ready bool `protobuf:"varint,1,opt,name=ready,proto3" json:"ready,omitempty"` @@ -3085,8 +3143,10 @@ type ProbeMigrationStateResponse struct { // Resume nonce for this job's capture session before ownership activation. OnlineSourceGeneration string `protobuf:"bytes,14,opt,name=online_source_generation,json=onlineSourceGeneration,proto3" json:"online_source_generation,omitempty"` RedisFenceReadFloor uint64 `protobuf:"varint,15,opt,name=redis_fence_read_floor,json=redisFenceReadFloor,proto3" json:"redis_fence_read_floor,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Durable row-generation activation, not merely local binary support. + VersionAdoptionActive bool `protobuf:"varint,16,opt,name=version_adoption_active,json=versionAdoptionActive,proto3" json:"version_adoption_active,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ProbeMigrationStateResponse) Reset() { @@ -3224,6 +3284,13 @@ func (x *ProbeMigrationStateResponse) GetRedisFenceReadFloor() uint64 { return 0 } +func (x *ProbeMigrationStateResponse) GetVersionAdoptionActive() bool { + if x != nil { + return x.VersionAdoptionActive + } + return false +} + type IssueMigrationTimestampRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Return a linearizable floor observation without allocating a timestamp. @@ -4724,13 +4791,14 @@ var File_internal_proto protoreflect.FileDescriptor const file_internal_proto_rawDesc = "" + "\n" + - "\x0einternal.proto\"\xa3\x01\n" + + "\x0einternal.proto\"\xd1\x01\n" + "\bMutation\x12\x13\n" + "\x02op\x18\x01 \x01(\x0e2\x03.OpR\x02op\x12\x10\n" + "\x03key\x18\x02 \x01(\fR\x03key\x12\x14\n" + "\x05value\x18\x03 \x01(\fR\x05value\x123\n" + "\x16commit_ts_value_offset\x18\x04 \x01(\x04R\x13commitTsValueOffset\x12%\n" + - "\x0erequire_absent\x18\x05 \x01(\bR\rrequireAbsent\"\xcb\x03\n" + + "\x0erequire_absent\x18\x05 \x01(\bR\rrequireAbsent\x12,\n" + + "\x12expected_commit_ts\x18\x06 \x01(\x04R\x10expectedCommitTs\"\xfc\x03\n" + "\aRequest\x12\x15\n" + "\x06is_txn\x18\x01 \x01(\bR\x05isTxn\x12\x1c\n" + "\x05phase\x18\x02 \x01(\x0e2\x06.PhaseR\x05phase\x12\x0e\n" + @@ -4742,7 +4810,8 @@ const file_internal_proto_rawDesc = "" + "\x19timestamp_admission_floor\x18\b \x01(\x04R\x17timestampAdmissionFloor\x12C\n" + "\x1etimestamp_binding_operation_id\x18\t \x01(\fR\x1btimestampBindingOperationId\x12G\n" + " timestamp_binding_admission_term\x18\n" + - " \x01(\x04R\x1dtimestampBindingAdmissionTerm\"3\n" + + " \x01(\x04R\x1dtimestampBindingAdmissionTerm\x12/\n" + + "\x14version_cas_group_id\x18\v \x01(\x04R\x11versionCasGroupId\"3\n" + "\vRaftCommand\x12$\n" + "\brequests\x18\x01 \x03(\v2\b.RequestR\brequests\"\x85\x01\n" + "\x0eForwardRequest\x12\x15\n" + @@ -4903,7 +4972,7 @@ const file_internal_proto_rawDesc = "" + "\x0fdescriptor_hash\x18\f \x01(\fR\x0edescriptorHash\x12*\n" + "\x11write_floor_known\x18\r \x01(\bR\x0fwriteFloorKnown\x124\n" + "\x16source_tracker_version\x18\x0e \x01(\x04R\x14sourceTrackerVersion\x120\n" + - "\x14source_applied_index\x18\x0f \x01(\x04R\x12sourceAppliedIndex\"\x86\a\n" + + "\x14source_applied_index\x18\x0f \x01(\x04R\x12sourceAppliedIndex\"\xbf\a\n" + "\x17CleanupMigrationRequest\x12\x15\n" + "\x06job_id\x18\x01 \x01(\x04R\x05jobId\x12)\n" + "\x04mode\x18\x02 \x01(\x0e2\x15.MigrationCleanupModeR\x04mode\x12\x1f\n" + @@ -4929,14 +4998,16 @@ const file_internal_proto_rawDesc = "" + "\x1brequire_configuration_index\x18\x12 \x01(\bR\x19requireConfigurationIndex\x126\n" + "\townership\x18\x13 \x01(\v2\x18.MigrationOwnershipProofR\townership\x121\n" + "\x14partition_transition\x18\x14 \x01(\fR\x13partitionTransition\x12/\n" + - "\x13namespace_admission\x18\x15 \x01(\fR\x12namespaceAdmission\"\xbc\x01\n" + + "\x13namespace_admission\x18\x15 \x01(\fR\x12namespaceAdmission\x127\n" + + "\x18expected_source_group_id\x18\x16 \x01(\x04R\x15expectedSourceGroupId\"\xe1\x01\n" + "\x18CleanupMigrationResponse\x12\x1f\n" + "\vnext_cursor\x18\x01 \x01(\fR\n" + "nextCursor\x12\x12\n" + "\x04done\x18\x02 \x01(\bR\x04done\x12!\n" + "\fdeleted_rows\x18\x03 \x01(\x04R\vdeletedRows\x12#\n" + "\rdeleted_bytes\x18\x04 \x01(\x04R\fdeletedBytes\x12#\n" + - "\rscanned_bytes\x18\x05 \x01(\x04R\fscannedBytes\"\x87\t\n" + + "\rscanned_bytes\x18\x05 \x01(\x04R\fscannedBytes\x12#\n" + + "\rretirement_id\x18\x06 \x01(\tR\fretirementId\"\xac\t\n" + "\x1aProbeMigrationStateRequest\x12\x15\n" + "\x06job_id\x18\x01 \x01(\x04R\x05jobId\x12,\n" + "\x04kind\x18\x02 \x01(\x0e2\x18.MigrationStateProbeKindR\x04kind\x12\x1f\n" + @@ -4963,7 +5034,8 @@ const file_internal_proto_rawDesc = "" + "\x0fonline_sequence\x18\x15 \x01(\x04R\x0eonlineSequence\x12!\n" + "\fonline_ready\x18\x16 \x01(\bR\vonlineReady\x124\n" + "\x16online_sealed_manifest\x18\x17 \x01(\fR\x14onlineSealedManifest\x123\n" + - "\x16redis_fence_read_floor\x18\x18 \x01(\x04R\x13redisFenceReadFloor\"\xa3\x06\n" + + "\x16redis_fence_read_floor\x18\x18 \x01(\x04R\x13redisFenceReadFloor\x12#\n" + + "\rretirement_id\x18\x19 \x01(\tR\fretirementId\"\xdb\x06\n" + "\x1bProbeMigrationStateResponse\x12\x14\n" + "\x05ready\x18\x01 \x01(\bR\x05ready\x12'\n" + "\x0fcatalog_version\x18\x02 \x01(\x04R\x0ecatalogVersion\x12&\n" + @@ -4980,7 +5052,8 @@ const file_internal_proto_rawDesc = "" + "\x14partition_receipt_id\x18\f \x01(\fR\x12partitionReceiptId\x124\n" + "\x16online_capture_version\x18\r \x01(\rR\x14onlineCaptureVersion\x128\n" + "\x18online_source_generation\x18\x0e \x01(\tR\x16onlineSourceGeneration\x123\n" + - "\x16redis_fence_read_floor\x18\x0f \x01(\x04R\x13redisFenceReadFloor\"U\n" + + "\x16redis_fence_read_floor\x18\x0f \x01(\x04R\x13redisFenceReadFloor\x126\n" + + "\x17version_adoption_active\x18\x10 \x01(\bR\x15versionAdoptionActive\"U\n" + "\x1eIssueMigrationTimestampRequest\x123\n" + "\x16redis_fence_floor_only\x18\x01 \x01(\bR\x13redisFenceFloorOnly\"\xba\x01\n" + "\x1fIssueMigrationTimestampResponse\x12\x1c\n" + @@ -5099,12 +5172,13 @@ const file_internal_proto_rawDesc = "" + "\x06fenced\x18\n" + " \x01(\bR\x06fenced\x12\x1c\n" + "\tsupported\x18\v \x01(\bR\tsupported\x12\x1c\n" + - "\tchallenge\x18\f \x01(\fR\tchallenge*&\n" + + "\tchallenge\x18\f \x01(\fR\tchallenge*<\n" + "\x02Op\x12\a\n" + "\x03PUT\x10\x00\x12\a\n" + "\x03DEL\x10\x01\x12\x0e\n" + "\n" + - "DEL_PREFIX\x10\x02*5\n" + + "DEL_PREFIX\x10\x02\x12\x14\n" + + "\x10COMPARE_AND_SWAP\x10\x03*5\n" + "\x05Phase\x12\b\n" + "\x04NONE\x10\x00\x12\v\n" + "\aPREPARE\x10\x01\x12\n" + @@ -5116,14 +5190,16 @@ const file_internal_proto_rawDesc = "" + "%FORWARD_FAILURE_PHASE_ONE_PHASE_APPLY\x10\x01\x12!\n" + "\x1dFORWARD_FAILURE_PHASE_PREPARE\x10\x02\x12 \n" + "\x1cFORWARD_FAILURE_PHASE_COMMIT\x10\x03\x12\x1f\n" + - "\x1bFORWARD_FAILURE_PHASE_ABORT\x10\x04*\xf7\x01\n" + + "\x1bFORWARD_FAILURE_PHASE_ABORT\x10\x04*\xc7\x02\n" + "\x14ForwardFailureReason\x12&\n" + "\"FORWARD_FAILURE_REASON_UNSPECIFIED\x10\x00\x12#\n" + "\x1fFORWARD_FAILURE_REASON_CONFLICT\x10\x01\x12 \n" + "\x1cFORWARD_FAILURE_REASON_FENCE\x10\x02\x12$\n" + " FORWARD_FAILURE_REASON_NO_LEADER\x10\x03\x12&\n" + "\"FORWARD_FAILURE_REASON_INTERRUPTED\x10\x04\x12\"\n" + - "\x1eFORWARD_FAILURE_REASON_ABORTED\x10\x05*\xd2\x01\n" + + "\x1eFORWARD_FAILURE_REASON_ABORTED\x10\x05\x12'\n" + + "#FORWARD_FAILURE_REASON_CAS_MISMATCH\x10\x06\x12%\n" + + "!FORWARD_FAILURE_REASON_CAS_LOCKED\x10\a*\xd2\x01\n" + "\x14ForwardDecisionClass\x12&\n" + "\"FORWARD_DECISION_CLASS_UNSPECIFIED\x10\x00\x125\n" + "1FORWARD_DECISION_CLASS_REJECTED_BEFORE_SUBMISSION\x10\x01\x12/\n" + @@ -5142,7 +5218,7 @@ const file_internal_proto_rawDesc = "" + "\x16MigrationOwnershipRole\x12(\n" + "$MIGRATION_OWNERSHIP_ROLE_UNSPECIFIED\x10\x00\x12\"\n" + "\x1eMIGRATION_OWNERSHIP_ROLE_OWNER\x10\x01\x12%\n" + - "!MIGRATION_OWNERSHIP_ROLE_NONOWNER\x10\x02*\xcb\x04\n" + + "!MIGRATION_OWNERSHIP_ROLE_NONOWNER\x10\x02*\x84\x05\n" + "\x17MigrationStateProbeKind\x12*\n" + "&MIGRATION_STATE_PROBE_KIND_UNSPECIFIED\x10\x00\x12.\n" + "*MIGRATION_STATE_PROBE_KIND_CONTROL_APPLIED\x10\x01\x128\n" + @@ -5155,9 +5231,12 @@ const file_internal_proto_rawDesc = "" + ",MIGRATION_STATE_PROBE_KIND_OWNERSHIP_APPLIED\x10\b\x120\n" + ",MIGRATION_STATE_PROBE_KIND_PARTITION_APPLIED\x10\t\x122\n" + ".MIGRATION_STATE_PROBE_KIND_NAMESPACE_ADMISSION\x10\n" + - "2\xbf\r\n" + + "\x127\n" + + "3MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS\x10\v2\xbd\x0e\n" + "\bInternal\x12.\n" + - "\aForward\x12\x0f.ForwardRequest\x1a\x10.ForwardResponse\"\x00\x12U\n" + + "\aForward\x12\x0f.ForwardRequest\x1a\x10.ForwardResponse\"\x00\x12<\n" + + "\x15ForwardCompareAndSwap\x12\x0f.ForwardRequest\x1a\x10.ForwardResponse\"\x00\x12>\n" + + "\x17ForwardCompareAndSwapV2\x12\x0f.ForwardRequest\x1a\x10.ForwardResponse\"\x00\x12U\n" + "\x14ForwardAdminProposal\x12\x1c.ForwardAdminProposalRequest\x1a\x1d.ForwardAdminProposalResponse\"\x00\x12I\n" + "\x10ForwardLeaseRead\x12\x18.ForwardLeaseReadRequest\x1a\x19.ForwardLeaseReadResponse\"\x00\x12X\n" + "\x17GetPrepareEvidenceState\x12\x1c.PrepareEvidenceStateRequest\x1a\x1d.PrepareEvidenceStateResponse\"\x00\x12[\n" + @@ -5285,47 +5364,51 @@ var file_internal_proto_depIdxs = []int32{ 45, // 27: TwoGroupTerminalEntry.manifest:type_name -> TwoGroupPrepareManifest 1, // 28: TwoGroupTerminalEntry.decision:type_name -> Phase 11, // 29: Internal.Forward:input_type -> ForwardRequest - 14, // 30: Internal.ForwardAdminProposal:input_type -> ForwardAdminProposalRequest - 16, // 31: Internal.ForwardLeaseRead:input_type -> ForwardLeaseReadRequest - 18, // 32: Internal.GetPrepareEvidenceState:input_type -> PrepareEvidenceStateRequest - 58, // 33: Internal.GetTTLInlineCapability:input_type -> GetTTLInlineCapabilityRequest - 20, // 34: Internal.RelayPublish:input_type -> RelayPublishRequest - 22, // 35: Internal.ExportRangeVersions:input_type -> ExportRangeVersionsRequest - 25, // 36: Internal.ImportRangeVersions:input_type -> ImportRangeVersionsRequest - 27, // 37: Internal.PromoteStagedVersions:input_type -> PromoteStagedVersionsRequest - 29, // 38: Internal.ApplyTargetStagedReadiness:input_type -> TargetStagedReadinessRequest - 31, // 39: Internal.ProbeMigrationLocks:input_type -> ProbeMigrationLocksRequest - 34, // 40: Internal.CleanupMigration:input_type -> CleanupMigrationRequest - 36, // 41: Internal.ProbeMigrationState:input_type -> ProbeMigrationStateRequest - 38, // 42: Internal.IssueMigrationTimestamp:input_type -> IssueMigrationTimestampRequest - 40, // 43: Internal.IssueBoundTimestamp:input_type -> IssueBoundTimestampRequest - 42, // 44: Internal.LookupTimestampBinding:input_type -> LookupTimestampBindingRequest - 46, // 45: Internal.ProposeTwoGroupPrepare:input_type -> ProposeTwoGroupPrepareRequest - 48, // 46: Internal.VerifyTwoGroupPrepare:input_type -> VerifyTwoGroupPrepareRequest - 50, // 47: Internal.ProposeTwoGroupTerminal:input_type -> ProposeTwoGroupTerminalRequest - 52, // 48: Internal.ProbeTwoGroupPrepareEvidence:input_type -> ProbeTwoGroupPrepareEvidenceRequest - 12, // 49: Internal.Forward:output_type -> ForwardResponse - 15, // 50: Internal.ForwardAdminProposal:output_type -> ForwardAdminProposalResponse - 17, // 51: Internal.ForwardLeaseRead:output_type -> ForwardLeaseReadResponse - 19, // 52: Internal.GetPrepareEvidenceState:output_type -> PrepareEvidenceStateResponse - 59, // 53: Internal.GetTTLInlineCapability:output_type -> GetTTLInlineCapabilityResponse - 21, // 54: Internal.RelayPublish:output_type -> RelayPublishResponse - 23, // 55: Internal.ExportRangeVersions:output_type -> ExportRangeVersionsResponse - 26, // 56: Internal.ImportRangeVersions:output_type -> ImportRangeVersionsResponse - 28, // 57: Internal.PromoteStagedVersions:output_type -> PromoteStagedVersionsResponse - 30, // 58: Internal.ApplyTargetStagedReadiness:output_type -> TargetStagedReadinessResponse - 32, // 59: Internal.ProbeMigrationLocks:output_type -> ProbeMigrationLocksResponse - 35, // 60: Internal.CleanupMigration:output_type -> CleanupMigrationResponse - 37, // 61: Internal.ProbeMigrationState:output_type -> ProbeMigrationStateResponse - 39, // 62: Internal.IssueMigrationTimestamp:output_type -> IssueMigrationTimestampResponse - 41, // 63: Internal.IssueBoundTimestamp:output_type -> IssueBoundTimestampResponse - 43, // 64: Internal.LookupTimestampBinding:output_type -> LookupTimestampBindingResponse - 47, // 65: Internal.ProposeTwoGroupPrepare:output_type -> ProposeTwoGroupPrepareResponse - 49, // 66: Internal.VerifyTwoGroupPrepare:output_type -> VerifyTwoGroupPrepareResponse - 51, // 67: Internal.ProposeTwoGroupTerminal:output_type -> ProposeTwoGroupTerminalResponse - 53, // 68: Internal.ProbeTwoGroupPrepareEvidence:output_type -> ProbeTwoGroupPrepareEvidenceResponse - 49, // [49:69] is the sub-list for method output_type - 29, // [29:49] is the sub-list for method input_type + 11, // 30: Internal.ForwardCompareAndSwap:input_type -> ForwardRequest + 11, // 31: Internal.ForwardCompareAndSwapV2:input_type -> ForwardRequest + 14, // 32: Internal.ForwardAdminProposal:input_type -> ForwardAdminProposalRequest + 16, // 33: Internal.ForwardLeaseRead:input_type -> ForwardLeaseReadRequest + 18, // 34: Internal.GetPrepareEvidenceState:input_type -> PrepareEvidenceStateRequest + 58, // 35: Internal.GetTTLInlineCapability:input_type -> GetTTLInlineCapabilityRequest + 20, // 36: Internal.RelayPublish:input_type -> RelayPublishRequest + 22, // 37: Internal.ExportRangeVersions:input_type -> ExportRangeVersionsRequest + 25, // 38: Internal.ImportRangeVersions:input_type -> ImportRangeVersionsRequest + 27, // 39: Internal.PromoteStagedVersions:input_type -> PromoteStagedVersionsRequest + 29, // 40: Internal.ApplyTargetStagedReadiness:input_type -> TargetStagedReadinessRequest + 31, // 41: Internal.ProbeMigrationLocks:input_type -> ProbeMigrationLocksRequest + 34, // 42: Internal.CleanupMigration:input_type -> CleanupMigrationRequest + 36, // 43: Internal.ProbeMigrationState:input_type -> ProbeMigrationStateRequest + 38, // 44: Internal.IssueMigrationTimestamp:input_type -> IssueMigrationTimestampRequest + 40, // 45: Internal.IssueBoundTimestamp:input_type -> IssueBoundTimestampRequest + 42, // 46: Internal.LookupTimestampBinding:input_type -> LookupTimestampBindingRequest + 46, // 47: Internal.ProposeTwoGroupPrepare:input_type -> ProposeTwoGroupPrepareRequest + 48, // 48: Internal.VerifyTwoGroupPrepare:input_type -> VerifyTwoGroupPrepareRequest + 50, // 49: Internal.ProposeTwoGroupTerminal:input_type -> ProposeTwoGroupTerminalRequest + 52, // 50: Internal.ProbeTwoGroupPrepareEvidence:input_type -> ProbeTwoGroupPrepareEvidenceRequest + 12, // 51: Internal.Forward:output_type -> ForwardResponse + 12, // 52: Internal.ForwardCompareAndSwap:output_type -> ForwardResponse + 12, // 53: Internal.ForwardCompareAndSwapV2:output_type -> ForwardResponse + 15, // 54: Internal.ForwardAdminProposal:output_type -> ForwardAdminProposalResponse + 17, // 55: Internal.ForwardLeaseRead:output_type -> ForwardLeaseReadResponse + 19, // 56: Internal.GetPrepareEvidenceState:output_type -> PrepareEvidenceStateResponse + 59, // 57: Internal.GetTTLInlineCapability:output_type -> GetTTLInlineCapabilityResponse + 21, // 58: Internal.RelayPublish:output_type -> RelayPublishResponse + 23, // 59: Internal.ExportRangeVersions:output_type -> ExportRangeVersionsResponse + 26, // 60: Internal.ImportRangeVersions:output_type -> ImportRangeVersionsResponse + 28, // 61: Internal.PromoteStagedVersions:output_type -> PromoteStagedVersionsResponse + 30, // 62: Internal.ApplyTargetStagedReadiness:output_type -> TargetStagedReadinessResponse + 32, // 63: Internal.ProbeMigrationLocks:output_type -> ProbeMigrationLocksResponse + 35, // 64: Internal.CleanupMigration:output_type -> CleanupMigrationResponse + 37, // 65: Internal.ProbeMigrationState:output_type -> ProbeMigrationStateResponse + 39, // 66: Internal.IssueMigrationTimestamp:output_type -> IssueMigrationTimestampResponse + 41, // 67: Internal.IssueBoundTimestamp:output_type -> IssueBoundTimestampResponse + 43, // 68: Internal.LookupTimestampBinding:output_type -> LookupTimestampBindingResponse + 47, // 69: Internal.ProposeTwoGroupPrepare:output_type -> ProposeTwoGroupPrepareResponse + 49, // 70: Internal.VerifyTwoGroupPrepare:output_type -> VerifyTwoGroupPrepareResponse + 51, // 71: Internal.ProposeTwoGroupTerminal:output_type -> ProposeTwoGroupTerminalResponse + 53, // 72: Internal.ProbeTwoGroupPrepareEvidence:output_type -> ProbeTwoGroupPrepareEvidenceResponse + 51, // [51:73] is the sub-list for method output_type + 29, // [29:51] is the sub-list for method input_type 29, // [29:29] is the sub-list for extension type_name 29, // [29:29] is the sub-list for extension extendee 0, // [0:29] is the sub-list for field type_name diff --git a/proto/internal.proto b/proto/internal.proto index c6067521a..67b44878a 100644 --- a/proto/internal.proto +++ b/proto/internal.proto @@ -6,6 +6,9 @@ option go_package = "github.com/bootjp/elastickv/proto"; service Internal { // for internal leader redirect only rpc Forward(ForwardRequest) returns (ForwardResponse) {} + // A legacy leader must reject a forwarded CAS before proposing it. + rpc ForwardCompareAndSwap(ForwardRequest) returns (ForwardResponse) {} + rpc ForwardCompareAndSwapV2(ForwardRequest) returns (ForwardResponse) {} rpc ForwardAdminProposal(ForwardAdminProposalRequest) returns (ForwardAdminProposalResponse) {} rpc ForwardLeaseRead(ForwardLeaseReadRequest) returns (ForwardLeaseReadResponse) {} rpc GetPrepareEvidenceState(PrepareEvidenceStateRequest) returns (PrepareEvidenceStateResponse) {} @@ -39,6 +42,8 @@ enum Op { // node, so the Raft log contains only a single mutation regardless of how // many keys are deleted. DEL_PREFIX = 2; + // Conditional replacement of exactly one live MVCC version in a 1PC. + COMPARE_AND_SWAP = 3; } message Mutation { @@ -55,6 +60,7 @@ message Mutation { // version of key, including tombstones, may exist when the 1PC applies. // It requires the replicated TTL-inline capability on every voter/learner. bool require_absent = 5; + uint64 expected_commit_ts = 6; } enum Phase { @@ -101,6 +107,9 @@ message Request { // The leader term that prepared this binding. The proposer checks it in // the Raft event loop before submitting the entry. uint64 timestamp_binding_admission_term = 10; + // The data group selected for a standalone CAS. Only its leader stamps + // observed_route_version, using that group's applied catalog. + uint64 version_cas_group_id = 11; } message RaftCommand { @@ -137,6 +146,8 @@ enum ForwardFailureReason { FORWARD_FAILURE_REASON_NO_LEADER = 3; FORWARD_FAILURE_REASON_INTERRUPTED = 4; FORWARD_FAILURE_REASON_ABORTED = 5; + FORWARD_FAILURE_REASON_CAS_MISMATCH = 6; + FORWARD_FAILURE_REASON_CAS_LOCKED = 7; } enum ForwardDecisionClass { @@ -389,6 +400,8 @@ message CleanupMigrationRequest { // Versioned namespace activation/prejoin control. Never propose until every // apply member (including learners) acknowledged support at this ConfChange. bytes namespace_admission = 21; + // Prevent a source cleanup from being replayed against a returning owner. + uint64 expected_source_group_id = 22; } message CleanupMigrationResponse { @@ -397,6 +410,8 @@ message CleanupMigrationResponse { uint64 deleted_rows = 3; uint64 deleted_bytes = 4; uint64 scanned_bytes = 5; + // A committed logical retirement, not an all-member physical completion ACK. + string retirement_id = 6; } enum MigrationStateProbeKind { @@ -413,6 +428,8 @@ enum MigrationStateProbeKind { MIGRATION_STATE_PROBE_KIND_OWNERSHIP_APPLIED = 8; MIGRATION_STATE_PROBE_KIND_PARTITION_APPLIED = 9; MIGRATION_STATE_PROBE_KIND_NAMESPACE_ADMISSION = 10; + // Bounded, local-only GC authorized exclusively by an existing retirement. + MIGRATION_STATE_PROBE_KIND_RECLAIM_RETIRED_VERSIONS = 11; } message ProbeMigrationStateRequest { @@ -444,6 +461,7 @@ message ProbeMigrationStateRequest { // Canonical, immutable source seal required by the current apply members. bytes online_sealed_manifest = 23; uint64 redis_fence_read_floor = 24; + string retirement_id = 25; } message ProbeMigrationStateResponse { @@ -467,6 +485,8 @@ message ProbeMigrationStateResponse { // Resume nonce for this job's capture session before ownership activation. string online_source_generation = 14; uint64 redis_fence_read_floor = 15; + // Durable row-generation activation, not merely local binary support. + bool version_adoption_active = 16; } message IssueMigrationTimestampRequest { diff --git a/proto/internal_grpc.pb.go b/proto/internal_grpc.pb.go index d2ee684a9..77de237e2 100644 --- a/proto/internal_grpc.pb.go +++ b/proto/internal_grpc.pb.go @@ -20,6 +20,8 @@ const _ = grpc.SupportPackageIsVersion9 const ( Internal_Forward_FullMethodName = "/Internal/Forward" + Internal_ForwardCompareAndSwap_FullMethodName = "/Internal/ForwardCompareAndSwap" + Internal_ForwardCompareAndSwapV2_FullMethodName = "/Internal/ForwardCompareAndSwapV2" Internal_ForwardAdminProposal_FullMethodName = "/Internal/ForwardAdminProposal" Internal_ForwardLeaseRead_FullMethodName = "/Internal/ForwardLeaseRead" Internal_GetPrepareEvidenceState_FullMethodName = "/Internal/GetPrepareEvidenceState" @@ -47,6 +49,9 @@ const ( type InternalClient interface { // for internal leader redirect only Forward(ctx context.Context, in *ForwardRequest, opts ...grpc.CallOption) (*ForwardResponse, error) + // A legacy leader must reject a forwarded CAS before proposing it. + ForwardCompareAndSwap(ctx context.Context, in *ForwardRequest, opts ...grpc.CallOption) (*ForwardResponse, error) + ForwardCompareAndSwapV2(ctx context.Context, in *ForwardRequest, opts ...grpc.CallOption) (*ForwardResponse, error) ForwardAdminProposal(ctx context.Context, in *ForwardAdminProposalRequest, opts ...grpc.CallOption) (*ForwardAdminProposalResponse, error) ForwardLeaseRead(ctx context.Context, in *ForwardLeaseReadRequest, opts ...grpc.CallOption) (*ForwardLeaseReadResponse, error) GetPrepareEvidenceState(ctx context.Context, in *PrepareEvidenceStateRequest, opts ...grpc.CallOption) (*PrepareEvidenceStateResponse, error) @@ -88,6 +93,26 @@ func (c *internalClient) Forward(ctx context.Context, in *ForwardRequest, opts . return out, nil } +func (c *internalClient) ForwardCompareAndSwap(ctx context.Context, in *ForwardRequest, opts ...grpc.CallOption) (*ForwardResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ForwardResponse) + err := c.cc.Invoke(ctx, Internal_ForwardCompareAndSwap_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *internalClient) ForwardCompareAndSwapV2(ctx context.Context, in *ForwardRequest, opts ...grpc.CallOption) (*ForwardResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ForwardResponse) + err := c.cc.Invoke(ctx, Internal_ForwardCompareAndSwapV2_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *internalClient) ForwardAdminProposal(ctx context.Context, in *ForwardAdminProposalRequest, opts ...grpc.CallOption) (*ForwardAdminProposalResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ForwardAdminProposalResponse) @@ -293,6 +318,9 @@ func (c *internalClient) ProbeTwoGroupPrepareEvidence(ctx context.Context, in *P type InternalServer interface { // for internal leader redirect only Forward(context.Context, *ForwardRequest) (*ForwardResponse, error) + // A legacy leader must reject a forwarded CAS before proposing it. + ForwardCompareAndSwap(context.Context, *ForwardRequest) (*ForwardResponse, error) + ForwardCompareAndSwapV2(context.Context, *ForwardRequest) (*ForwardResponse, error) ForwardAdminProposal(context.Context, *ForwardAdminProposalRequest) (*ForwardAdminProposalResponse, error) ForwardLeaseRead(context.Context, *ForwardLeaseReadRequest) (*ForwardLeaseReadResponse, error) GetPrepareEvidenceState(context.Context, *PrepareEvidenceStateRequest) (*PrepareEvidenceStateResponse, error) @@ -327,6 +355,12 @@ type UnimplementedInternalServer struct{} func (UnimplementedInternalServer) Forward(context.Context, *ForwardRequest) (*ForwardResponse, error) { return nil, status.Error(codes.Unimplemented, "method Forward not implemented") } +func (UnimplementedInternalServer) ForwardCompareAndSwap(context.Context, *ForwardRequest) (*ForwardResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ForwardCompareAndSwap not implemented") +} +func (UnimplementedInternalServer) ForwardCompareAndSwapV2(context.Context, *ForwardRequest) (*ForwardResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ForwardCompareAndSwapV2 not implemented") +} func (UnimplementedInternalServer) ForwardAdminProposal(context.Context, *ForwardAdminProposalRequest) (*ForwardAdminProposalResponse, error) { return nil, status.Error(codes.Unimplemented, "method ForwardAdminProposal not implemented") } @@ -423,6 +457,42 @@ func _Internal_Forward_Handler(srv interface{}, ctx context.Context, dec func(in return interceptor(ctx, in, info, handler) } +func _Internal_ForwardCompareAndSwap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ForwardRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(InternalServer).ForwardCompareAndSwap(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Internal_ForwardCompareAndSwap_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(InternalServer).ForwardCompareAndSwap(ctx, req.(*ForwardRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Internal_ForwardCompareAndSwapV2_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ForwardRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(InternalServer).ForwardCompareAndSwapV2(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Internal_ForwardCompareAndSwapV2_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(InternalServer).ForwardCompareAndSwapV2(ctx, req.(*ForwardRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _Internal_ForwardAdminProposal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ForwardAdminProposalRequest) if err := dec(in); err != nil { @@ -769,6 +839,14 @@ var Internal_ServiceDesc = grpc.ServiceDesc{ MethodName: "Forward", Handler: _Internal_Forward_Handler, }, + { + MethodName: "ForwardCompareAndSwap", + Handler: _Internal_ForwardCompareAndSwap_Handler, + }, + { + MethodName: "ForwardCompareAndSwapV2", + Handler: _Internal_ForwardCompareAndSwapV2_Handler, + }, { MethodName: "ForwardAdminProposal", Handler: _Internal_ForwardAdminProposal_Handler, diff --git a/proto/service.pb.go b/proto/service.pb.go index 45135c4ca..05f5cda0a 100644 --- a/proto/service.pb.go +++ b/proto/service.pb.go @@ -195,6 +195,7 @@ type RawGetRequest struct { Ts uint64 `protobuf:"varint,3,opt,name=ts,proto3" json:"ts,omitempty"` // optional read timestamp; if zero, server uses current HLC GroupId uint64 `protobuf:"varint,4,opt,name=group_id,json=groupId,proto3" json:"group_id,omitempty"` // optional explicit Raft group for non-range-owned keyspaces ReadRouteVersion uint64 `protobuf:"varint,5,opt,name=read_route_version,json=readRouteVersion,proto3" json:"read_route_version,omitempty"` // stamped by server-side routing for migration read fences + NeedCommitTs bool `protobuf:"varint,6,opt,name=need_commit_ts,json=needCommitTs,proto3" json:"need_commit_ts,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -257,11 +258,23 @@ func (x *RawGetRequest) GetReadRouteVersion() uint64 { return 0 } +func (x *RawGetRequest) GetNeedCommitTs() bool { + if x != nil { + return x.NeedCommitTs + } + return false +} + type RawGetResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - ReadAtIndex uint64 `protobuf:"varint,1,opt,name=read_at_index,json=readAtIndex,proto3" json:"read_at_index,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - Exists bool `protobuf:"varint,3,opt,name=exists,proto3" json:"exists,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + ReadAtIndex uint64 `protobuf:"varint,1,opt,name=read_at_index,json=readAtIndex,proto3" json:"read_at_index,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + Exists bool `protobuf:"varint,3,opt,name=exists,proto3" json:"exists,omitempty"` + // Types that are valid to be assigned to Version: + // + // *RawGetResponse_CommitTs + // *RawGetResponse_Missing + Version isRawGetResponse_Version `protobuf_oneof:"version"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -317,6 +330,47 @@ func (x *RawGetResponse) GetExists() bool { return false } +func (x *RawGetResponse) GetVersion() isRawGetResponse_Version { + if x != nil { + return x.Version + } + return nil +} + +func (x *RawGetResponse) GetCommitTs() uint64 { + if x != nil { + if x, ok := x.Version.(*RawGetResponse_CommitTs); ok { + return x.CommitTs + } + } + return 0 +} + +func (x *RawGetResponse) GetMissing() bool { + if x != nil { + if x, ok := x.Version.(*RawGetResponse_Missing); ok { + return x.Missing + } + } + return false +} + +type isRawGetResponse_Version interface { + isRawGetResponse_Version() +} + +type RawGetResponse_CommitTs struct { + CommitTs uint64 `protobuf:"varint,4,opt,name=commit_ts,json=commitTs,proto3,oneof"` +} + +type RawGetResponse_Missing struct { + Missing bool `protobuf:"varint,5,opt,name=missing,proto3,oneof"` +} + +func (*RawGetResponse_CommitTs) isRawGetResponse_Version() {} + +func (*RawGetResponse_Missing) isRawGetResponse_Version() {} + type RawDeleteRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` @@ -1053,8 +1107,10 @@ func (x *DeleteResponse) GetSuccess() bool { } type GetRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + // Return the commit timestamp of the record that supplied the value. + NeedCommitTs bool `protobuf:"varint,2,opt,name=need_commit_ts,json=needCommitTs,proto3" json:"need_commit_ts,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1096,10 +1152,24 @@ func (x *GetRequest) GetKey() []byte { return nil } +func (x *GetRequest) GetNeedCommitTs() bool { + if x != nil { + return x.NeedCommitTs + } + return false +} + type GetResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - ReadAtIndex uint64 `protobuf:"varint,1,opt,name=read_at_index,json=readAtIndex,proto3" json:"read_at_index,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + ReadAtIndex uint64 `protobuf:"varint,1,opt,name=read_at_index,json=readAtIndex,proto3" json:"read_at_index,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + // Absent on a legacy response. A live value may have zero bytes. + // + // Types that are valid to be assigned to Version: + // + // *GetResponse_CommitTs + // *GetResponse_Missing + Version isGetResponse_Version `protobuf_oneof:"version"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1148,6 +1218,190 @@ func (x *GetResponse) GetValue() []byte { return nil } +func (x *GetResponse) GetVersion() isGetResponse_Version { + if x != nil { + return x.Version + } + return nil +} + +func (x *GetResponse) GetCommitTs() uint64 { + if x != nil { + if x, ok := x.Version.(*GetResponse_CommitTs); ok { + return x.CommitTs + } + } + return 0 +} + +func (x *GetResponse) GetMissing() bool { + if x != nil { + if x, ok := x.Version.(*GetResponse_Missing); ok { + return x.Missing + } + } + return false +} + +type isGetResponse_Version interface { + isGetResponse_Version() +} + +type GetResponse_CommitTs struct { + CommitTs uint64 `protobuf:"varint,3,opt,name=commit_ts,json=commitTs,proto3,oneof"` +} + +type GetResponse_Missing struct { + Missing bool `protobuf:"varint,4,opt,name=missing,proto3,oneof"` +} + +func (*GetResponse_CommitTs) isGetResponse_Version() {} + +func (*GetResponse_Missing) isGetResponse_Version() {} + +type CompareAndSwapRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + // A positive commit timestamp previously observed for this live key. + ExpectedCommitTs uint64 `protobuf:"varint,2,opt,name=expected_commit_ts,json=expectedCommitTs,proto3" json:"expected_commit_ts,omitempty"` + Value []byte `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CompareAndSwapRequest) Reset() { + *x = CompareAndSwapRequest{} + mi := &file_service_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CompareAndSwapRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CompareAndSwapRequest) ProtoMessage() {} + +func (x *CompareAndSwapRequest) ProtoReflect() protoreflect.Message { + mi := &file_service_proto_msgTypes[17] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CompareAndSwapRequest.ProtoReflect.Descriptor instead. +func (*CompareAndSwapRequest) Descriptor() ([]byte, []int) { + return file_service_proto_rawDescGZIP(), []int{17} +} + +func (x *CompareAndSwapRequest) GetKey() []byte { + if x != nil { + return x.Key + } + return nil +} + +func (x *CompareAndSwapRequest) GetExpectedCommitTs() uint64 { + if x != nil { + return x.ExpectedCommitTs + } + return 0 +} + +func (x *CompareAndSwapRequest) GetValue() []byte { + if x != nil { + return x.Value + } + return nil +} + +type CompareAndSwapResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Types that are valid to be assigned to Result: + // + // *CompareAndSwapResponse_NewCommitTs + // *CompareAndSwapResponse_Mismatch + Result isCompareAndSwapResponse_Result `protobuf_oneof:"result"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CompareAndSwapResponse) Reset() { + *x = CompareAndSwapResponse{} + mi := &file_service_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CompareAndSwapResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CompareAndSwapResponse) ProtoMessage() {} + +func (x *CompareAndSwapResponse) ProtoReflect() protoreflect.Message { + mi := &file_service_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CompareAndSwapResponse.ProtoReflect.Descriptor instead. +func (*CompareAndSwapResponse) Descriptor() ([]byte, []int) { + return file_service_proto_rawDescGZIP(), []int{18} +} + +func (x *CompareAndSwapResponse) GetResult() isCompareAndSwapResponse_Result { + if x != nil { + return x.Result + } + return nil +} + +func (x *CompareAndSwapResponse) GetNewCommitTs() uint64 { + if x != nil { + if x, ok := x.Result.(*CompareAndSwapResponse_NewCommitTs); ok { + return x.NewCommitTs + } + } + return 0 +} + +func (x *CompareAndSwapResponse) GetMismatch() bool { + if x != nil { + if x, ok := x.Result.(*CompareAndSwapResponse_Mismatch); ok { + return x.Mismatch + } + } + return false +} + +type isCompareAndSwapResponse_Result interface { + isCompareAndSwapResponse_Result() +} + +type CompareAndSwapResponse_NewCommitTs struct { + NewCommitTs uint64 `protobuf:"varint,1,opt,name=new_commit_ts,json=newCommitTs,proto3,oneof"` +} + +type CompareAndSwapResponse_Mismatch struct { + Mismatch bool `protobuf:"varint,2,opt,name=mismatch,proto3,oneof"` +} + +func (*CompareAndSwapResponse_NewCommitTs) isCompareAndSwapResponse_Result() {} + +func (*CompareAndSwapResponse_Mismatch) isCompareAndSwapResponse_Result() {} + type KeyError struct { state protoimpl.MessageState `protogen:"open.v1"` Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` @@ -1158,7 +1412,7 @@ type KeyError struct { func (x *KeyError) Reset() { *x = KeyError{} - mi := &file_service_proto_msgTypes[17] + mi := &file_service_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1170,7 +1424,7 @@ func (x *KeyError) String() string { func (*KeyError) ProtoMessage() {} func (x *KeyError) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[17] + mi := &file_service_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1183,7 +1437,7 @@ func (x *KeyError) ProtoReflect() protoreflect.Message { // Deprecated: Use KeyError.ProtoReflect.Descriptor instead. func (*KeyError) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{17} + return file_service_proto_rawDescGZIP(), []int{19} } func (x *KeyError) GetMessage() string { @@ -1211,7 +1465,7 @@ type Kv struct { func (x *Kv) Reset() { *x = Kv{} - mi := &file_service_proto_msgTypes[18] + mi := &file_service_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1223,7 +1477,7 @@ func (x *Kv) String() string { func (*Kv) ProtoMessage() {} func (x *Kv) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[18] + mi := &file_service_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1236,7 +1490,7 @@ func (x *Kv) ProtoReflect() protoreflect.Message { // Deprecated: Use Kv.ProtoReflect.Descriptor instead. func (*Kv) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{18} + return file_service_proto_rawDescGZIP(), []int{20} } func (x *Kv) GetError() *KeyError { @@ -1271,7 +1525,7 @@ type ScanRequest struct { func (x *ScanRequest) Reset() { *x = ScanRequest{} - mi := &file_service_proto_msgTypes[19] + mi := &file_service_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1283,7 +1537,7 @@ func (x *ScanRequest) String() string { func (*ScanRequest) ProtoMessage() {} func (x *ScanRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[19] + mi := &file_service_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1296,7 +1550,7 @@ func (x *ScanRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ScanRequest.ProtoReflect.Descriptor instead. func (*ScanRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{19} + return file_service_proto_rawDescGZIP(), []int{21} } func (x *ScanRequest) GetStartKey() []byte { @@ -1329,7 +1583,7 @@ type ScanResponse struct { func (x *ScanResponse) Reset() { *x = ScanResponse{} - mi := &file_service_proto_msgTypes[20] + mi := &file_service_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1341,7 +1595,7 @@ func (x *ScanResponse) String() string { func (*ScanResponse) ProtoMessage() {} func (x *ScanResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[20] + mi := &file_service_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1354,7 +1608,7 @@ func (x *ScanResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ScanResponse.ProtoReflect.Descriptor instead. func (*ScanResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{20} + return file_service_proto_rawDescGZIP(), []int{22} } func (x *ScanResponse) GetKv() []*Kv { @@ -1378,7 +1632,7 @@ type PreWriteRequest struct { func (x *PreWriteRequest) Reset() { *x = PreWriteRequest{} - mi := &file_service_proto_msgTypes[21] + mi := &file_service_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1390,7 +1644,7 @@ func (x *PreWriteRequest) String() string { func (*PreWriteRequest) ProtoMessage() {} func (x *PreWriteRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[21] + mi := &file_service_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1403,7 +1657,7 @@ func (x *PreWriteRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use PreWriteRequest.ProtoReflect.Descriptor instead. func (*PreWriteRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{21} + return file_service_proto_rawDescGZIP(), []int{23} } func (x *PreWriteRequest) GetMutations() []*Kv { @@ -1436,7 +1690,7 @@ type PreCommitResponse struct { func (x *PreCommitResponse) Reset() { *x = PreCommitResponse{} - mi := &file_service_proto_msgTypes[22] + mi := &file_service_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1448,7 +1702,7 @@ func (x *PreCommitResponse) String() string { func (*PreCommitResponse) ProtoMessage() {} func (x *PreCommitResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[22] + mi := &file_service_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1461,7 +1715,7 @@ func (x *PreCommitResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PreCommitResponse.ProtoReflect.Descriptor instead. func (*PreCommitResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{22} + return file_service_proto_rawDescGZIP(), []int{24} } func (x *PreCommitResponse) GetErrors() []*KeyError { @@ -1482,7 +1736,7 @@ type CommitRequest struct { func (x *CommitRequest) Reset() { *x = CommitRequest{} - mi := &file_service_proto_msgTypes[23] + mi := &file_service_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1494,7 +1748,7 @@ func (x *CommitRequest) String() string { func (*CommitRequest) ProtoMessage() {} func (x *CommitRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[23] + mi := &file_service_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1507,7 +1761,7 @@ func (x *CommitRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CommitRequest.ProtoReflect.Descriptor instead. func (*CommitRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{23} + return file_service_proto_rawDescGZIP(), []int{25} } func (x *CommitRequest) GetStartTs() uint64 { @@ -1535,7 +1789,7 @@ type CommitResponse struct { func (x *CommitResponse) Reset() { *x = CommitResponse{} - mi := &file_service_proto_msgTypes[24] + mi := &file_service_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1547,7 +1801,7 @@ func (x *CommitResponse) String() string { func (*CommitResponse) ProtoMessage() {} func (x *CommitResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[24] + mi := &file_service_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1560,7 +1814,7 @@ func (x *CommitResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CommitResponse.ProtoReflect.Descriptor instead. func (*CommitResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{24} + return file_service_proto_rawDescGZIP(), []int{26} } func (x *CommitResponse) GetCommitIndex() uint64 { @@ -1593,7 +1847,7 @@ type RollbackRequest struct { func (x *RollbackRequest) Reset() { *x = RollbackRequest{} - mi := &file_service_proto_msgTypes[25] + mi := &file_service_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1605,7 +1859,7 @@ func (x *RollbackRequest) String() string { func (*RollbackRequest) ProtoMessage() {} func (x *RollbackRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[25] + mi := &file_service_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1618,7 +1872,7 @@ func (x *RollbackRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RollbackRequest.ProtoReflect.Descriptor instead. func (*RollbackRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{25} + return file_service_proto_rawDescGZIP(), []int{27} } func (x *RollbackRequest) GetStartTs() uint64 { @@ -1637,7 +1891,7 @@ type RollbackResponse struct { func (x *RollbackResponse) Reset() { *x = RollbackResponse{} - mi := &file_service_proto_msgTypes[26] + mi := &file_service_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1649,7 +1903,7 @@ func (x *RollbackResponse) String() string { func (*RollbackResponse) ProtoMessage() {} func (x *RollbackResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[26] + mi := &file_service_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1662,7 +1916,7 @@ func (x *RollbackResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RollbackResponse.ProtoReflect.Descriptor instead. func (*RollbackResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{26} + return file_service_proto_rawDescGZIP(), []int{28} } func (x *RollbackResponse) GetSuccess() bool { @@ -1680,7 +1934,7 @@ type RaftAdminStatusRequest struct { func (x *RaftAdminStatusRequest) Reset() { *x = RaftAdminStatusRequest{} - mi := &file_service_proto_msgTypes[27] + mi := &file_service_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1692,7 +1946,7 @@ func (x *RaftAdminStatusRequest) String() string { func (*RaftAdminStatusRequest) ProtoMessage() {} func (x *RaftAdminStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[27] + mi := &file_service_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1705,31 +1959,35 @@ func (x *RaftAdminStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminStatusRequest.ProtoReflect.Descriptor instead. func (*RaftAdminStatusRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{27} + return file_service_proto_rawDescGZIP(), []int{29} } type RaftAdminStatusResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - State RaftAdminState `protobuf:"varint,1,opt,name=state,proto3,enum=RaftAdminState" json:"state,omitempty"` - LeaderId string `protobuf:"bytes,2,opt,name=leader_id,json=leaderId,proto3" json:"leader_id,omitempty"` - LeaderAddress string `protobuf:"bytes,3,opt,name=leader_address,json=leaderAddress,proto3" json:"leader_address,omitempty"` - Term uint64 `protobuf:"varint,4,opt,name=term,proto3" json:"term,omitempty"` - CommitIndex uint64 `protobuf:"varint,5,opt,name=commit_index,json=commitIndex,proto3" json:"commit_index,omitempty"` - AppliedIndex uint64 `protobuf:"varint,6,opt,name=applied_index,json=appliedIndex,proto3" json:"applied_index,omitempty"` - LastLogIndex uint64 `protobuf:"varint,7,opt,name=last_log_index,json=lastLogIndex,proto3" json:"last_log_index,omitempty"` - LastSnapshotIndex uint64 `protobuf:"varint,8,opt,name=last_snapshot_index,json=lastSnapshotIndex,proto3" json:"last_snapshot_index,omitempty"` - FsmPending uint64 `protobuf:"varint,9,opt,name=fsm_pending,json=fsmPending,proto3" json:"fsm_pending,omitempty"` - NumPeers uint64 `protobuf:"varint,10,opt,name=num_peers,json=numPeers,proto3" json:"num_peers,omitempty"` - LastContactNanos int64 `protobuf:"varint,11,opt,name=last_contact_nanos,json=lastContactNanos,proto3" json:"last_contact_nanos,omitempty"` - ConfigurationIndex uint64 `protobuf:"varint,12,opt,name=configuration_index,json=configurationIndex,proto3" json:"configuration_index,omitempty"` - PendingConfChange bool `protobuf:"varint,13,opt,name=pending_conf_change,json=pendingConfChange,proto3" json:"pending_conf_change,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + State RaftAdminState `protobuf:"varint,1,opt,name=state,proto3,enum=RaftAdminState" json:"state,omitempty"` + LeaderId string `protobuf:"bytes,2,opt,name=leader_id,json=leaderId,proto3" json:"leader_id,omitempty"` + LeaderAddress string `protobuf:"bytes,3,opt,name=leader_address,json=leaderAddress,proto3" json:"leader_address,omitempty"` + Term uint64 `protobuf:"varint,4,opt,name=term,proto3" json:"term,omitempty"` + CommitIndex uint64 `protobuf:"varint,5,opt,name=commit_index,json=commitIndex,proto3" json:"commit_index,omitempty"` + AppliedIndex uint64 `protobuf:"varint,6,opt,name=applied_index,json=appliedIndex,proto3" json:"applied_index,omitempty"` + LastLogIndex uint64 `protobuf:"varint,7,opt,name=last_log_index,json=lastLogIndex,proto3" json:"last_log_index,omitempty"` + LastSnapshotIndex uint64 `protobuf:"varint,8,opt,name=last_snapshot_index,json=lastSnapshotIndex,proto3" json:"last_snapshot_index,omitempty"` + FsmPending uint64 `protobuf:"varint,9,opt,name=fsm_pending,json=fsmPending,proto3" json:"fsm_pending,omitempty"` + NumPeers uint64 `protobuf:"varint,10,opt,name=num_peers,json=numPeers,proto3" json:"num_peers,omitempty"` + LastContactNanos int64 `protobuf:"varint,11,opt,name=last_contact_nanos,json=lastContactNanos,proto3" json:"last_contact_nanos,omitempty"` + ConfigurationIndex uint64 `protobuf:"varint,12,opt,name=configuration_index,json=configurationIndex,proto3" json:"configuration_index,omitempty"` + PendingConfChange bool `protobuf:"varint,13,opt,name=pending_conf_change,json=pendingConfChange,proto3" json:"pending_conf_change,omitempty"` + SupportsVersionCas bool `protobuf:"varint,14,opt,name=supports_version_cas,json=supportsVersionCas,proto3" json:"supports_version_cas,omitempty"` + SupportsReplicatedCatalogCas bool `protobuf:"varint,15,opt,name=supports_replicated_catalog_cas,json=supportsReplicatedCatalogCas,proto3" json:"supports_replicated_catalog_cas,omitempty"` + SupportsVersionRetirement bool `protobuf:"varint,16,opt,name=supports_version_retirement,json=supportsVersionRetirement,proto3" json:"supports_version_retirement,omitempty"` + SupportsVersionAdoption bool `protobuf:"varint,17,opt,name=supports_version_adoption,json=supportsVersionAdoption,proto3" json:"supports_version_adoption,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RaftAdminStatusResponse) Reset() { *x = RaftAdminStatusResponse{} - mi := &file_service_proto_msgTypes[28] + mi := &file_service_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1741,7 +1999,7 @@ func (x *RaftAdminStatusResponse) String() string { func (*RaftAdminStatusResponse) ProtoMessage() {} func (x *RaftAdminStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[28] + mi := &file_service_proto_msgTypes[30] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1754,7 +2012,7 @@ func (x *RaftAdminStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminStatusResponse.ProtoReflect.Descriptor instead. func (*RaftAdminStatusResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{28} + return file_service_proto_rawDescGZIP(), []int{30} } func (x *RaftAdminStatusResponse) GetState() RaftAdminState { @@ -1848,6 +2106,34 @@ func (x *RaftAdminStatusResponse) GetPendingConfChange() bool { return false } +func (x *RaftAdminStatusResponse) GetSupportsVersionCas() bool { + if x != nil { + return x.SupportsVersionCas + } + return false +} + +func (x *RaftAdminStatusResponse) GetSupportsReplicatedCatalogCas() bool { + if x != nil { + return x.SupportsReplicatedCatalogCas + } + return false +} + +func (x *RaftAdminStatusResponse) GetSupportsVersionRetirement() bool { + if x != nil { + return x.SupportsVersionRetirement + } + return false +} + +func (x *RaftAdminStatusResponse) GetSupportsVersionAdoption() bool { + if x != nil { + return x.SupportsVersionAdoption + } + return false +} + type RaftAdminConfigurationRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields @@ -1856,7 +2142,7 @@ type RaftAdminConfigurationRequest struct { func (x *RaftAdminConfigurationRequest) Reset() { *x = RaftAdminConfigurationRequest{} - mi := &file_service_proto_msgTypes[29] + mi := &file_service_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1868,7 +2154,7 @@ func (x *RaftAdminConfigurationRequest) String() string { func (*RaftAdminConfigurationRequest) ProtoMessage() {} func (x *RaftAdminConfigurationRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[29] + mi := &file_service_proto_msgTypes[31] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1881,7 +2167,7 @@ func (x *RaftAdminConfigurationRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminConfigurationRequest.ProtoReflect.Descriptor instead. func (*RaftAdminConfigurationRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{29} + return file_service_proto_rawDescGZIP(), []int{31} } type RaftAdminMember struct { @@ -1895,7 +2181,7 @@ type RaftAdminMember struct { func (x *RaftAdminMember) Reset() { *x = RaftAdminMember{} - mi := &file_service_proto_msgTypes[30] + mi := &file_service_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1907,7 +2193,7 @@ func (x *RaftAdminMember) String() string { func (*RaftAdminMember) ProtoMessage() {} func (x *RaftAdminMember) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[30] + mi := &file_service_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1920,7 +2206,7 @@ func (x *RaftAdminMember) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminMember.ProtoReflect.Descriptor instead. func (*RaftAdminMember) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{30} + return file_service_proto_rawDescGZIP(), []int{32} } func (x *RaftAdminMember) GetId() string { @@ -1953,7 +2239,7 @@ type RaftAdminConfigurationResponse struct { func (x *RaftAdminConfigurationResponse) Reset() { *x = RaftAdminConfigurationResponse{} - mi := &file_service_proto_msgTypes[31] + mi := &file_service_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1965,7 +2251,7 @@ func (x *RaftAdminConfigurationResponse) String() string { func (*RaftAdminConfigurationResponse) ProtoMessage() {} func (x *RaftAdminConfigurationResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[31] + mi := &file_service_proto_msgTypes[33] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1978,7 +2264,7 @@ func (x *RaftAdminConfigurationResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminConfigurationResponse.ProtoReflect.Descriptor instead. func (*RaftAdminConfigurationResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{31} + return file_service_proto_rawDescGZIP(), []int{33} } func (x *RaftAdminConfigurationResponse) GetServers() []*RaftAdminMember { @@ -1999,7 +2285,7 @@ type RaftAdminAddVoterRequest struct { func (x *RaftAdminAddVoterRequest) Reset() { *x = RaftAdminAddVoterRequest{} - mi := &file_service_proto_msgTypes[32] + mi := &file_service_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2011,7 +2297,7 @@ func (x *RaftAdminAddVoterRequest) String() string { func (*RaftAdminAddVoterRequest) ProtoMessage() {} func (x *RaftAdminAddVoterRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[32] + mi := &file_service_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2024,7 +2310,7 @@ func (x *RaftAdminAddVoterRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminAddVoterRequest.ProtoReflect.Descriptor instead. func (*RaftAdminAddVoterRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{32} + return file_service_proto_rawDescGZIP(), []int{34} } func (x *RaftAdminAddVoterRequest) GetId() string { @@ -2059,7 +2345,7 @@ type RaftAdminAddLearnerRequest struct { func (x *RaftAdminAddLearnerRequest) Reset() { *x = RaftAdminAddLearnerRequest{} - mi := &file_service_proto_msgTypes[33] + mi := &file_service_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2071,7 +2357,7 @@ func (x *RaftAdminAddLearnerRequest) String() string { func (*RaftAdminAddLearnerRequest) ProtoMessage() {} func (x *RaftAdminAddLearnerRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[33] + mi := &file_service_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2084,7 +2370,7 @@ func (x *RaftAdminAddLearnerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminAddLearnerRequest.ProtoReflect.Descriptor instead. func (*RaftAdminAddLearnerRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{33} + return file_service_proto_rawDescGZIP(), []int{35} } func (x *RaftAdminAddLearnerRequest) GetId() string { @@ -2131,7 +2417,7 @@ type RaftAdminPromoteLearnerRequest struct { func (x *RaftAdminPromoteLearnerRequest) Reset() { *x = RaftAdminPromoteLearnerRequest{} - mi := &file_service_proto_msgTypes[34] + mi := &file_service_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2143,7 +2429,7 @@ func (x *RaftAdminPromoteLearnerRequest) String() string { func (*RaftAdminPromoteLearnerRequest) ProtoMessage() {} func (x *RaftAdminPromoteLearnerRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[34] + mi := &file_service_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2156,7 +2442,7 @@ func (x *RaftAdminPromoteLearnerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminPromoteLearnerRequest.ProtoReflect.Descriptor instead. func (*RaftAdminPromoteLearnerRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{34} + return file_service_proto_rawDescGZIP(), []int{36} } func (x *RaftAdminPromoteLearnerRequest) GetId() string { @@ -2197,7 +2483,7 @@ type RaftAdminRemoveServerRequest struct { func (x *RaftAdminRemoveServerRequest) Reset() { *x = RaftAdminRemoveServerRequest{} - mi := &file_service_proto_msgTypes[35] + mi := &file_service_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2209,7 +2495,7 @@ func (x *RaftAdminRemoveServerRequest) String() string { func (*RaftAdminRemoveServerRequest) ProtoMessage() {} func (x *RaftAdminRemoveServerRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[35] + mi := &file_service_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2222,7 +2508,7 @@ func (x *RaftAdminRemoveServerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RaftAdminRemoveServerRequest.ProtoReflect.Descriptor instead. func (*RaftAdminRemoveServerRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{35} + return file_service_proto_rawDescGZIP(), []int{37} } func (x *RaftAdminRemoveServerRequest) GetId() string { @@ -2248,7 +2534,7 @@ type RaftAdminConfigurationChangeResponse struct { func (x *RaftAdminConfigurationChangeResponse) Reset() { *x = RaftAdminConfigurationChangeResponse{} - mi := &file_service_proto_msgTypes[36] + mi := &file_service_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2260,7 +2546,7 @@ func (x *RaftAdminConfigurationChangeResponse) String() string { func (*RaftAdminConfigurationChangeResponse) ProtoMessage() {} func (x *RaftAdminConfigurationChangeResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[36] + mi := &file_service_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2273,7 +2559,7 @@ func (x *RaftAdminConfigurationChangeResponse) ProtoReflect() protoreflect.Messa // Deprecated: Use RaftAdminConfigurationChangeResponse.ProtoReflect.Descriptor instead. func (*RaftAdminConfigurationChangeResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{36} + return file_service_proto_rawDescGZIP(), []int{38} } func (x *RaftAdminConfigurationChangeResponse) GetIndex() uint64 { @@ -2296,7 +2582,7 @@ type RaftAdminTransferLeadershipRequest struct { func (x *RaftAdminTransferLeadershipRequest) Reset() { *x = RaftAdminTransferLeadershipRequest{} - mi := &file_service_proto_msgTypes[37] + mi := &file_service_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2308,7 +2594,7 @@ func (x *RaftAdminTransferLeadershipRequest) String() string { func (*RaftAdminTransferLeadershipRequest) ProtoMessage() {} func (x *RaftAdminTransferLeadershipRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[37] + mi := &file_service_proto_msgTypes[39] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2321,7 +2607,7 @@ func (x *RaftAdminTransferLeadershipRequest) ProtoReflect() protoreflect.Message // Deprecated: Use RaftAdminTransferLeadershipRequest.ProtoReflect.Descriptor instead. func (*RaftAdminTransferLeadershipRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{37} + return file_service_proto_rawDescGZIP(), []int{39} } func (x *RaftAdminTransferLeadershipRequest) GetTargetId() string { @@ -2369,7 +2655,7 @@ type TransferTarget struct { func (x *TransferTarget) Reset() { *x = TransferTarget{} - mi := &file_service_proto_msgTypes[38] + mi := &file_service_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2381,7 +2667,7 @@ func (x *TransferTarget) String() string { func (*TransferTarget) ProtoMessage() {} func (x *TransferTarget) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[38] + mi := &file_service_proto_msgTypes[40] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2394,7 +2680,7 @@ func (x *TransferTarget) ProtoReflect() protoreflect.Message { // Deprecated: Use TransferTarget.ProtoReflect.Descriptor instead. func (*TransferTarget) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{38} + return file_service_proto_rawDescGZIP(), []int{40} } func (x *TransferTarget) GetTargetId() string { @@ -2420,7 +2706,7 @@ type FetchChunkBlobRequest struct { func (x *FetchChunkBlobRequest) Reset() { *x = FetchChunkBlobRequest{} - mi := &file_service_proto_msgTypes[39] + mi := &file_service_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2432,7 +2718,7 @@ func (x *FetchChunkBlobRequest) String() string { func (*FetchChunkBlobRequest) ProtoMessage() {} func (x *FetchChunkBlobRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[39] + mi := &file_service_proto_msgTypes[41] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2445,7 +2731,7 @@ func (x *FetchChunkBlobRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use FetchChunkBlobRequest.ProtoReflect.Descriptor instead. func (*FetchChunkBlobRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{39} + return file_service_proto_rawDescGZIP(), []int{41} } func (x *FetchChunkBlobRequest) GetContentSha256() []byte { @@ -2465,7 +2751,7 @@ type FetchChunkBlobResponse struct { func (x *FetchChunkBlobResponse) Reset() { *x = FetchChunkBlobResponse{} - mi := &file_service_proto_msgTypes[40] + mi := &file_service_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2477,7 +2763,7 @@ func (x *FetchChunkBlobResponse) String() string { func (*FetchChunkBlobResponse) ProtoMessage() {} func (x *FetchChunkBlobResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[40] + mi := &file_service_proto_msgTypes[42] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2490,7 +2776,7 @@ func (x *FetchChunkBlobResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use FetchChunkBlobResponse.ProtoReflect.Descriptor instead. func (*FetchChunkBlobResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{40} + return file_service_proto_rawDescGZIP(), []int{42} } func (x *FetchChunkBlobResponse) GetPayload() []byte { @@ -2519,7 +2805,7 @@ type PushChunkBlobRequest struct { func (x *PushChunkBlobRequest) Reset() { *x = PushChunkBlobRequest{} - mi := &file_service_proto_msgTypes[41] + mi := &file_service_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2531,7 +2817,7 @@ func (x *PushChunkBlobRequest) String() string { func (*PushChunkBlobRequest) ProtoMessage() {} func (x *PushChunkBlobRequest) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[41] + mi := &file_service_proto_msgTypes[43] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2544,7 +2830,7 @@ func (x *PushChunkBlobRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use PushChunkBlobRequest.ProtoReflect.Descriptor instead. func (*PushChunkBlobRequest) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{41} + return file_service_proto_rawDescGZIP(), []int{43} } func (x *PushChunkBlobRequest) GetContentSha256() []byte { @@ -2584,7 +2870,7 @@ type PushChunkBlobResponse struct { func (x *PushChunkBlobResponse) Reset() { *x = PushChunkBlobResponse{} - mi := &file_service_proto_msgTypes[42] + mi := &file_service_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2596,7 +2882,7 @@ func (x *PushChunkBlobResponse) String() string { func (*PushChunkBlobResponse) ProtoMessage() {} func (x *PushChunkBlobResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[42] + mi := &file_service_proto_msgTypes[44] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2609,7 +2895,7 @@ func (x *PushChunkBlobResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PushChunkBlobResponse.ProtoReflect.Descriptor instead. func (*PushChunkBlobResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{42} + return file_service_proto_rawDescGZIP(), []int{44} } func (x *PushChunkBlobResponse) GetDurable() bool { @@ -2627,7 +2913,7 @@ type RaftAdminTransferLeadershipResponse struct { func (x *RaftAdminTransferLeadershipResponse) Reset() { *x = RaftAdminTransferLeadershipResponse{} - mi := &file_service_proto_msgTypes[43] + mi := &file_service_proto_msgTypes[45] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2639,7 +2925,7 @@ func (x *RaftAdminTransferLeadershipResponse) String() string { func (*RaftAdminTransferLeadershipResponse) ProtoMessage() {} func (x *RaftAdminTransferLeadershipResponse) ProtoReflect() protoreflect.Message { - mi := &file_service_proto_msgTypes[43] + mi := &file_service_proto_msgTypes[45] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2652,7 +2938,7 @@ func (x *RaftAdminTransferLeadershipResponse) ProtoReflect() protoreflect.Messag // Deprecated: Use RaftAdminTransferLeadershipResponse.ProtoReflect.Descriptor instead. func (*RaftAdminTransferLeadershipResponse) Descriptor() ([]byte, []int) { - return file_service_proto_rawDescGZIP(), []int{43} + return file_service_proto_rawDescGZIP(), []int{45} } var File_service_proto protoreflect.FileDescriptor @@ -2666,16 +2952,20 @@ const file_service_proto_rawDesc = "" + "\foperation_id\x18\x03 \x01(\fR\voperationId\"M\n" + "\x0eRawPutResponse\x12!\n" + "\fcommit_index\x18\x01 \x01(\x04R\vcommitIndex\x12\x18\n" + - "\asuccess\x18\x02 \x01(\bR\asuccess\"z\n" + + "\asuccess\x18\x02 \x01(\bR\asuccess\"\xa0\x01\n" + "\rRawGetRequest\x12\x10\n" + "\x03key\x18\x01 \x01(\fR\x03key\x12\x0e\n" + "\x02ts\x18\x03 \x01(\x04R\x02ts\x12\x19\n" + "\bgroup_id\x18\x04 \x01(\x04R\agroupId\x12,\n" + - "\x12read_route_version\x18\x05 \x01(\x04R\x10readRouteVersion\"b\n" + + "\x12read_route_version\x18\x05 \x01(\x04R\x10readRouteVersion\x12$\n" + + "\x0eneed_commit_ts\x18\x06 \x01(\bR\fneedCommitTs\"\xa8\x01\n" + "\x0eRawGetResponse\x12\"\n" + "\rread_at_index\x18\x01 \x01(\x04R\vreadAtIndex\x12\x14\n" + "\x05value\x18\x02 \x01(\fR\x05value\x12\x16\n" + - "\x06exists\x18\x03 \x01(\bR\x06exists\"G\n" + + "\x06exists\x18\x03 \x01(\bR\x06exists\x12\x1d\n" + + "\tcommit_ts\x18\x04 \x01(\x04H\x00R\bcommitTs\x12\x1a\n" + + "\amissing\x18\x05 \x01(\bH\x00R\amissingB\t\n" + + "\aversion\"G\n" + "\x10RawDeleteRequest\x12\x10\n" + "\x03key\x18\x01 \x01(\fR\x03key\x12!\n" + "\foperation_id\x18\x02 \x01(\fR\voperationId\"P\n" + @@ -2730,13 +3020,25 @@ const file_service_proto_rawDesc = "" + "\x03key\x18\x01 \x01(\fR\x03key\"M\n" + "\x0eDeleteResponse\x12!\n" + "\fcommit_index\x18\x01 \x01(\x04R\vcommitIndex\x12\x18\n" + - "\asuccess\x18\x02 \x01(\bR\asuccess\"\x1e\n" + + "\asuccess\x18\x02 \x01(\bR\asuccess\"D\n" + "\n" + "GetRequest\x12\x10\n" + - "\x03key\x18\x01 \x01(\fR\x03key\"G\n" + + "\x03key\x18\x01 \x01(\fR\x03key\x12$\n" + + "\x0eneed_commit_ts\x18\x02 \x01(\bR\fneedCommitTs\"\x8d\x01\n" + "\vGetResponse\x12\"\n" + "\rread_at_index\x18\x01 \x01(\x04R\vreadAtIndex\x12\x14\n" + - "\x05value\x18\x02 \x01(\fR\x05value\"B\n" + + "\x05value\x18\x02 \x01(\fR\x05value\x12\x1d\n" + + "\tcommit_ts\x18\x03 \x01(\x04H\x00R\bcommitTs\x12\x1a\n" + + "\amissing\x18\x04 \x01(\bH\x00R\amissingB\t\n" + + "\aversion\"m\n" + + "\x15CompareAndSwapRequest\x12\x10\n" + + "\x03key\x18\x01 \x01(\fR\x03key\x12,\n" + + "\x12expected_commit_ts\x18\x02 \x01(\x04R\x10expectedCommitTs\x12\x14\n" + + "\x05value\x18\x03 \x01(\fR\x05value\"f\n" + + "\x16CompareAndSwapResponse\x12$\n" + + "\rnew_commit_ts\x18\x01 \x01(\x04H\x00R\vnewCommitTs\x12\x1c\n" + + "\bmismatch\x18\x02 \x01(\bH\x00R\bmismatchB\b\n" + + "\x06result\"B\n" + "\bKeyError\x12\x18\n" + "\amessage\x18\x01 \x01(\tR\amessage\x12\x1c\n" + "\tretryable\x18\x02 \x01(\bR\tretryable\"M\n" + @@ -2767,7 +3069,7 @@ const file_service_proto_rawDesc = "" + "\bstart_ts\x18\x01 \x01(\x04R\astartTs\",\n" + "\x10RollbackResponse\x12\x18\n" + "\asuccess\x18\x01 \x01(\bR\asuccess\"\x18\n" + - "\x16RaftAdminStatusRequest\"\x83\x04\n" + + "\x16RaftAdminStatusRequest\"\xf8\x05\n" + "\x17RaftAdminStatusResponse\x12%\n" + "\x05state\x18\x01 \x01(\x0e2\x0f.RaftAdminStateR\x05state\x12\x1b\n" + "\tleader_id\x18\x02 \x01(\tR\bleaderId\x12%\n" + @@ -2783,7 +3085,11 @@ const file_service_proto_rawDesc = "" + " \x01(\x04R\bnumPeers\x12,\n" + "\x12last_contact_nanos\x18\v \x01(\x03R\x10lastContactNanos\x12/\n" + "\x13configuration_index\x18\f \x01(\x04R\x12configurationIndex\x12.\n" + - "\x13pending_conf_change\x18\r \x01(\bR\x11pendingConfChange\"\x1f\n" + + "\x13pending_conf_change\x18\r \x01(\bR\x11pendingConfChange\x120\n" + + "\x14supports_version_cas\x18\x0e \x01(\bR\x12supportsVersionCas\x12E\n" + + "\x1fsupports_replicated_catalog_cas\x18\x0f \x01(\bR\x1csupportsReplicatedCatalogCas\x12>\n" + + "\x1bsupports_version_retirement\x18\x10 \x01(\bR\x19supportsVersionRetirement\x12:\n" + + "\x19supports_version_adoption\x18\x11 \x01(\bR\x17supportsVersionAdoption\"\x1f\n" + "\x1dRaftAdminConfigurationRequest\"W\n" + "\x0fRaftAdminMember\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x18\n" + @@ -2842,10 +3148,11 @@ const file_service_proto_rawDesc = "" + "\x06RawGet\x12\x0e.RawGetRequest\x1a\x0f.RawGetResponse\"\x00\x124\n" + "\tRawDelete\x12\x11.RawDeleteRequest\x1a\x12.RawDeleteResponse\"\x00\x12L\n" + "\x11RawLatestCommitTS\x12\x19.RawLatestCommitTSRequest\x1a\x1a.RawLatestCommitTSResponse\"\x00\x124\n" + - "\tRawScanAt\x12\x11.RawScanAtRequest\x1a\x12.RawScanAtResponse\"\x002\xc1\x02\n" + + "\tRawScanAt\x12\x11.RawScanAtRequest\x1a\x12.RawScanAtResponse\"\x002\x86\x03\n" + "\x0fTransactionalKV\x12\"\n" + "\x03Put\x12\v.PutRequest\x1a\f.PutResponse\"\x00\x12\"\n" + - "\x03Get\x12\v.GetRequest\x1a\f.GetResponse\"\x00\x12+\n" + + "\x03Get\x12\v.GetRequest\x1a\f.GetResponse\"\x00\x12C\n" + + "\x0eCompareAndSwap\x12\x16.CompareAndSwapRequest\x1a\x17.CompareAndSwapResponse\"\x00\x12+\n" + "\x06Delete\x12\x0e.DeleteRequest\x1a\x0f.DeleteResponse\"\x00\x12%\n" + "\x04Scan\x12\f.ScanRequest\x1a\r.ScanResponse\"\x00\x122\n" + "\bPreWrite\x12\x10.PreWriteRequest\x1a\x12.PreCommitResponse\"\x00\x12+\n" + @@ -2877,7 +3184,7 @@ func file_service_proto_rawDescGZIP() []byte { } var file_service_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_service_proto_msgTypes = make([]protoimpl.MessageInfo, 44) +var file_service_proto_msgTypes = make([]protoimpl.MessageInfo, 46) var file_service_proto_goTypes = []any{ (RaftAdminState)(0), // 0: RaftAdminState (*RawPutRequest)(nil), // 1: RawPutRequest @@ -2897,44 +3204,46 @@ var file_service_proto_goTypes = []any{ (*DeleteResponse)(nil), // 15: DeleteResponse (*GetRequest)(nil), // 16: GetRequest (*GetResponse)(nil), // 17: GetResponse - (*KeyError)(nil), // 18: KeyError - (*Kv)(nil), // 19: Kv - (*ScanRequest)(nil), // 20: ScanRequest - (*ScanResponse)(nil), // 21: ScanResponse - (*PreWriteRequest)(nil), // 22: PreWriteRequest - (*PreCommitResponse)(nil), // 23: PreCommitResponse - (*CommitRequest)(nil), // 24: CommitRequest - (*CommitResponse)(nil), // 25: CommitResponse - (*RollbackRequest)(nil), // 26: RollbackRequest - (*RollbackResponse)(nil), // 27: RollbackResponse - (*RaftAdminStatusRequest)(nil), // 28: RaftAdminStatusRequest - (*RaftAdminStatusResponse)(nil), // 29: RaftAdminStatusResponse - (*RaftAdminConfigurationRequest)(nil), // 30: RaftAdminConfigurationRequest - (*RaftAdminMember)(nil), // 31: RaftAdminMember - (*RaftAdminConfigurationResponse)(nil), // 32: RaftAdminConfigurationResponse - (*RaftAdminAddVoterRequest)(nil), // 33: RaftAdminAddVoterRequest - (*RaftAdminAddLearnerRequest)(nil), // 34: RaftAdminAddLearnerRequest - (*RaftAdminPromoteLearnerRequest)(nil), // 35: RaftAdminPromoteLearnerRequest - (*RaftAdminRemoveServerRequest)(nil), // 36: RaftAdminRemoveServerRequest - (*RaftAdminConfigurationChangeResponse)(nil), // 37: RaftAdminConfigurationChangeResponse - (*RaftAdminTransferLeadershipRequest)(nil), // 38: RaftAdminTransferLeadershipRequest - (*TransferTarget)(nil), // 39: TransferTarget - (*FetchChunkBlobRequest)(nil), // 40: FetchChunkBlobRequest - (*FetchChunkBlobResponse)(nil), // 41: FetchChunkBlobResponse - (*PushChunkBlobRequest)(nil), // 42: PushChunkBlobRequest - (*PushChunkBlobResponse)(nil), // 43: PushChunkBlobResponse - (*RaftAdminTransferLeadershipResponse)(nil), // 44: RaftAdminTransferLeadershipResponse + (*CompareAndSwapRequest)(nil), // 18: CompareAndSwapRequest + (*CompareAndSwapResponse)(nil), // 19: CompareAndSwapResponse + (*KeyError)(nil), // 20: KeyError + (*Kv)(nil), // 21: Kv + (*ScanRequest)(nil), // 22: ScanRequest + (*ScanResponse)(nil), // 23: ScanResponse + (*PreWriteRequest)(nil), // 24: PreWriteRequest + (*PreCommitResponse)(nil), // 25: PreCommitResponse + (*CommitRequest)(nil), // 26: CommitRequest + (*CommitResponse)(nil), // 27: CommitResponse + (*RollbackRequest)(nil), // 28: RollbackRequest + (*RollbackResponse)(nil), // 29: RollbackResponse + (*RaftAdminStatusRequest)(nil), // 30: RaftAdminStatusRequest + (*RaftAdminStatusResponse)(nil), // 31: RaftAdminStatusResponse + (*RaftAdminConfigurationRequest)(nil), // 32: RaftAdminConfigurationRequest + (*RaftAdminMember)(nil), // 33: RaftAdminMember + (*RaftAdminConfigurationResponse)(nil), // 34: RaftAdminConfigurationResponse + (*RaftAdminAddVoterRequest)(nil), // 35: RaftAdminAddVoterRequest + (*RaftAdminAddLearnerRequest)(nil), // 36: RaftAdminAddLearnerRequest + (*RaftAdminPromoteLearnerRequest)(nil), // 37: RaftAdminPromoteLearnerRequest + (*RaftAdminRemoveServerRequest)(nil), // 38: RaftAdminRemoveServerRequest + (*RaftAdminConfigurationChangeResponse)(nil), // 39: RaftAdminConfigurationChangeResponse + (*RaftAdminTransferLeadershipRequest)(nil), // 40: RaftAdminTransferLeadershipRequest + (*TransferTarget)(nil), // 41: TransferTarget + (*FetchChunkBlobRequest)(nil), // 42: FetchChunkBlobRequest + (*FetchChunkBlobResponse)(nil), // 43: FetchChunkBlobResponse + (*PushChunkBlobRequest)(nil), // 44: PushChunkBlobRequest + (*PushChunkBlobResponse)(nil), // 45: PushChunkBlobResponse + (*RaftAdminTransferLeadershipResponse)(nil), // 46: RaftAdminTransferLeadershipResponse } var file_service_proto_depIdxs = []int32{ 10, // 0: RawScanAtResponse.kv:type_name -> RawKVPair - 18, // 1: Kv.error:type_name -> KeyError - 19, // 2: ScanResponse.kv:type_name -> Kv - 19, // 3: PreWriteRequest.mutations:type_name -> Kv - 18, // 4: PreCommitResponse.errors:type_name -> KeyError - 18, // 5: CommitResponse.errors:type_name -> KeyError + 20, // 1: Kv.error:type_name -> KeyError + 21, // 2: ScanResponse.kv:type_name -> Kv + 21, // 3: PreWriteRequest.mutations:type_name -> Kv + 20, // 4: PreCommitResponse.errors:type_name -> KeyError + 20, // 5: CommitResponse.errors:type_name -> KeyError 0, // 6: RaftAdminStatusResponse.state:type_name -> RaftAdminState - 31, // 7: RaftAdminConfigurationResponse.servers:type_name -> RaftAdminMember - 39, // 8: RaftAdminTransferLeadershipRequest.target_candidates:type_name -> TransferTarget + 33, // 7: RaftAdminConfigurationResponse.servers:type_name -> RaftAdminMember + 41, // 8: RaftAdminTransferLeadershipRequest.target_candidates:type_name -> TransferTarget 1, // 9: RawKV.RawPut:input_type -> RawPutRequest 3, // 10: RawKV.RawGet:input_type -> RawGetRequest 5, // 11: RawKV.RawDelete:input_type -> RawDeleteRequest @@ -2942,43 +3251,45 @@ var file_service_proto_depIdxs = []int32{ 9, // 13: RawKV.RawScanAt:input_type -> RawScanAtRequest 12, // 14: TransactionalKV.Put:input_type -> PutRequest 16, // 15: TransactionalKV.Get:input_type -> GetRequest - 14, // 16: TransactionalKV.Delete:input_type -> DeleteRequest - 20, // 17: TransactionalKV.Scan:input_type -> ScanRequest - 22, // 18: TransactionalKV.PreWrite:input_type -> PreWriteRequest - 24, // 19: TransactionalKV.Commit:input_type -> CommitRequest - 26, // 20: TransactionalKV.Rollback:input_type -> RollbackRequest - 28, // 21: RaftAdmin.Status:input_type -> RaftAdminStatusRequest - 30, // 22: RaftAdmin.Configuration:input_type -> RaftAdminConfigurationRequest - 33, // 23: RaftAdmin.AddVoter:input_type -> RaftAdminAddVoterRequest - 34, // 24: RaftAdmin.AddLearner:input_type -> RaftAdminAddLearnerRequest - 35, // 25: RaftAdmin.PromoteLearner:input_type -> RaftAdminPromoteLearnerRequest - 36, // 26: RaftAdmin.RemoveServer:input_type -> RaftAdminRemoveServerRequest - 38, // 27: RaftAdmin.TransferLeadership:input_type -> RaftAdminTransferLeadershipRequest - 40, // 28: S3BlobFetch.FetchChunkBlob:input_type -> FetchChunkBlobRequest - 42, // 29: S3BlobFetch.PushChunkBlob:input_type -> PushChunkBlobRequest - 2, // 30: RawKV.RawPut:output_type -> RawPutResponse - 4, // 31: RawKV.RawGet:output_type -> RawGetResponse - 6, // 32: RawKV.RawDelete:output_type -> RawDeleteResponse - 8, // 33: RawKV.RawLatestCommitTS:output_type -> RawLatestCommitTSResponse - 11, // 34: RawKV.RawScanAt:output_type -> RawScanAtResponse - 13, // 35: TransactionalKV.Put:output_type -> PutResponse - 17, // 36: TransactionalKV.Get:output_type -> GetResponse - 15, // 37: TransactionalKV.Delete:output_type -> DeleteResponse - 21, // 38: TransactionalKV.Scan:output_type -> ScanResponse - 23, // 39: TransactionalKV.PreWrite:output_type -> PreCommitResponse - 25, // 40: TransactionalKV.Commit:output_type -> CommitResponse - 27, // 41: TransactionalKV.Rollback:output_type -> RollbackResponse - 29, // 42: RaftAdmin.Status:output_type -> RaftAdminStatusResponse - 32, // 43: RaftAdmin.Configuration:output_type -> RaftAdminConfigurationResponse - 37, // 44: RaftAdmin.AddVoter:output_type -> RaftAdminConfigurationChangeResponse - 37, // 45: RaftAdmin.AddLearner:output_type -> RaftAdminConfigurationChangeResponse - 37, // 46: RaftAdmin.PromoteLearner:output_type -> RaftAdminConfigurationChangeResponse - 37, // 47: RaftAdmin.RemoveServer:output_type -> RaftAdminConfigurationChangeResponse - 44, // 48: RaftAdmin.TransferLeadership:output_type -> RaftAdminTransferLeadershipResponse - 41, // 49: S3BlobFetch.FetchChunkBlob:output_type -> FetchChunkBlobResponse - 43, // 50: S3BlobFetch.PushChunkBlob:output_type -> PushChunkBlobResponse - 30, // [30:51] is the sub-list for method output_type - 9, // [9:30] is the sub-list for method input_type + 18, // 16: TransactionalKV.CompareAndSwap:input_type -> CompareAndSwapRequest + 14, // 17: TransactionalKV.Delete:input_type -> DeleteRequest + 22, // 18: TransactionalKV.Scan:input_type -> ScanRequest + 24, // 19: TransactionalKV.PreWrite:input_type -> PreWriteRequest + 26, // 20: TransactionalKV.Commit:input_type -> CommitRequest + 28, // 21: TransactionalKV.Rollback:input_type -> RollbackRequest + 30, // 22: RaftAdmin.Status:input_type -> RaftAdminStatusRequest + 32, // 23: RaftAdmin.Configuration:input_type -> RaftAdminConfigurationRequest + 35, // 24: RaftAdmin.AddVoter:input_type -> RaftAdminAddVoterRequest + 36, // 25: RaftAdmin.AddLearner:input_type -> RaftAdminAddLearnerRequest + 37, // 26: RaftAdmin.PromoteLearner:input_type -> RaftAdminPromoteLearnerRequest + 38, // 27: RaftAdmin.RemoveServer:input_type -> RaftAdminRemoveServerRequest + 40, // 28: RaftAdmin.TransferLeadership:input_type -> RaftAdminTransferLeadershipRequest + 42, // 29: S3BlobFetch.FetchChunkBlob:input_type -> FetchChunkBlobRequest + 44, // 30: S3BlobFetch.PushChunkBlob:input_type -> PushChunkBlobRequest + 2, // 31: RawKV.RawPut:output_type -> RawPutResponse + 4, // 32: RawKV.RawGet:output_type -> RawGetResponse + 6, // 33: RawKV.RawDelete:output_type -> RawDeleteResponse + 8, // 34: RawKV.RawLatestCommitTS:output_type -> RawLatestCommitTSResponse + 11, // 35: RawKV.RawScanAt:output_type -> RawScanAtResponse + 13, // 36: TransactionalKV.Put:output_type -> PutResponse + 17, // 37: TransactionalKV.Get:output_type -> GetResponse + 19, // 38: TransactionalKV.CompareAndSwap:output_type -> CompareAndSwapResponse + 15, // 39: TransactionalKV.Delete:output_type -> DeleteResponse + 23, // 40: TransactionalKV.Scan:output_type -> ScanResponse + 25, // 41: TransactionalKV.PreWrite:output_type -> PreCommitResponse + 27, // 42: TransactionalKV.Commit:output_type -> CommitResponse + 29, // 43: TransactionalKV.Rollback:output_type -> RollbackResponse + 31, // 44: RaftAdmin.Status:output_type -> RaftAdminStatusResponse + 34, // 45: RaftAdmin.Configuration:output_type -> RaftAdminConfigurationResponse + 39, // 46: RaftAdmin.AddVoter:output_type -> RaftAdminConfigurationChangeResponse + 39, // 47: RaftAdmin.AddLearner:output_type -> RaftAdminConfigurationChangeResponse + 39, // 48: RaftAdmin.PromoteLearner:output_type -> RaftAdminConfigurationChangeResponse + 39, // 49: RaftAdmin.RemoveServer:output_type -> RaftAdminConfigurationChangeResponse + 46, // 50: RaftAdmin.TransferLeadership:output_type -> RaftAdminTransferLeadershipResponse + 43, // 51: S3BlobFetch.FetchChunkBlob:output_type -> FetchChunkBlobResponse + 45, // 52: S3BlobFetch.PushChunkBlob:output_type -> PushChunkBlobResponse + 31, // [31:53] is the sub-list for method output_type + 9, // [9:31] is the sub-list for method input_type 9, // [9:9] is the sub-list for extension type_name 9, // [9:9] is the sub-list for extension extendee 0, // [0:9] is the sub-list for field type_name @@ -2989,13 +3300,25 @@ func file_service_proto_init() { if File_service_proto != nil { return } + file_service_proto_msgTypes[3].OneofWrappers = []any{ + (*RawGetResponse_CommitTs)(nil), + (*RawGetResponse_Missing)(nil), + } + file_service_proto_msgTypes[16].OneofWrappers = []any{ + (*GetResponse_CommitTs)(nil), + (*GetResponse_Missing)(nil), + } + file_service_proto_msgTypes[18].OneofWrappers = []any{ + (*CompareAndSwapResponse_NewCommitTs)(nil), + (*CompareAndSwapResponse_Mismatch)(nil), + } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_service_proto_rawDesc), len(file_service_proto_rawDesc)), NumEnums: 1, - NumMessages: 44, + NumMessages: 46, NumExtensions: 0, NumServices: 4, }, diff --git a/proto/service.proto b/proto/service.proto index b40f74f2c..a0f911a16 100644 --- a/proto/service.proto +++ b/proto/service.proto @@ -13,6 +13,7 @@ service RawKV { service TransactionalKV { rpc Put(PutRequest) returns (PutResponse) {} rpc Get(GetRequest) returns (GetResponse) {} + rpc CompareAndSwap(CompareAndSwapRequest) returns (CompareAndSwapResponse) {} rpc Delete(DeleteRequest) returns (DeleteResponse) {} rpc Scan(ScanRequest) returns (ScanResponse) {} @@ -53,12 +54,17 @@ message RawGetRequest { uint64 ts = 3; // optional read timestamp; if zero, server uses current HLC uint64 group_id = 4; // optional explicit Raft group for non-range-owned keyspaces uint64 read_route_version = 5; // stamped by server-side routing for migration read fences + bool need_commit_ts = 6; } message RawGetResponse { uint64 read_at_index = 1; bytes value = 2; bool exists = 3; + oneof version { + uint64 commit_ts = 4; + bool missing = 5; + } } message RawDeleteRequest { @@ -155,11 +161,32 @@ message DeleteResponse { message GetRequest { bytes key = 1; + // Return the commit timestamp of the record that supplied the value. + bool need_commit_ts = 2; } message GetResponse { uint64 read_at_index = 1; bytes value = 2; + // Absent on a legacy response. A live value may have zero bytes. + oneof version { + uint64 commit_ts = 3; + bool missing = 4; + } +} + +message CompareAndSwapRequest { + bytes key = 1; + // A positive commit timestamp previously observed for this live key. + uint64 expected_commit_ts = 2; + bytes value = 3; +} + +message CompareAndSwapResponse { + oneof result { + uint64 new_commit_ts = 1; + bool mismatch = 2; + } } message KeyError { @@ -241,6 +268,10 @@ message RaftAdminStatusResponse { int64 last_contact_nanos = 11; uint64 configuration_index = 12; bool pending_conf_change = 13; + bool supports_version_cas = 14; + bool supports_replicated_catalog_cas = 15; + bool supports_version_retirement = 16; + bool supports_version_adoption = 17; } message RaftAdminConfigurationRequest {} diff --git a/proto/service_grpc.pb.go b/proto/service_grpc.pb.go index 1254bcbf9..d42641bcb 100644 --- a/proto/service_grpc.pb.go +++ b/proto/service_grpc.pb.go @@ -273,13 +273,14 @@ var RawKV_ServiceDesc = grpc.ServiceDesc{ } const ( - TransactionalKV_Put_FullMethodName = "/TransactionalKV/Put" - TransactionalKV_Get_FullMethodName = "/TransactionalKV/Get" - TransactionalKV_Delete_FullMethodName = "/TransactionalKV/Delete" - TransactionalKV_Scan_FullMethodName = "/TransactionalKV/Scan" - TransactionalKV_PreWrite_FullMethodName = "/TransactionalKV/PreWrite" - TransactionalKV_Commit_FullMethodName = "/TransactionalKV/Commit" - TransactionalKV_Rollback_FullMethodName = "/TransactionalKV/Rollback" + TransactionalKV_Put_FullMethodName = "/TransactionalKV/Put" + TransactionalKV_Get_FullMethodName = "/TransactionalKV/Get" + TransactionalKV_CompareAndSwap_FullMethodName = "/TransactionalKV/CompareAndSwap" + TransactionalKV_Delete_FullMethodName = "/TransactionalKV/Delete" + TransactionalKV_Scan_FullMethodName = "/TransactionalKV/Scan" + TransactionalKV_PreWrite_FullMethodName = "/TransactionalKV/PreWrite" + TransactionalKV_Commit_FullMethodName = "/TransactionalKV/Commit" + TransactionalKV_Rollback_FullMethodName = "/TransactionalKV/Rollback" ) // TransactionalKVClient is the client API for TransactionalKV service. @@ -288,6 +289,7 @@ const ( type TransactionalKVClient interface { Put(ctx context.Context, in *PutRequest, opts ...grpc.CallOption) (*PutResponse, error) Get(ctx context.Context, in *GetRequest, opts ...grpc.CallOption) (*GetResponse, error) + CompareAndSwap(ctx context.Context, in *CompareAndSwapRequest, opts ...grpc.CallOption) (*CompareAndSwapResponse, error) Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) Scan(ctx context.Context, in *ScanRequest, opts ...grpc.CallOption) (*ScanResponse, error) PreWrite(ctx context.Context, in *PreWriteRequest, opts ...grpc.CallOption) (*PreCommitResponse, error) @@ -323,6 +325,16 @@ func (c *transactionalKVClient) Get(ctx context.Context, in *GetRequest, opts .. return out, nil } +func (c *transactionalKVClient) CompareAndSwap(ctx context.Context, in *CompareAndSwapRequest, opts ...grpc.CallOption) (*CompareAndSwapResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CompareAndSwapResponse) + err := c.cc.Invoke(ctx, TransactionalKV_CompareAndSwap_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *transactionalKVClient) Delete(ctx context.Context, in *DeleteRequest, opts ...grpc.CallOption) (*DeleteResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(DeleteResponse) @@ -379,6 +391,7 @@ func (c *transactionalKVClient) Rollback(ctx context.Context, in *RollbackReques type TransactionalKVServer interface { Put(context.Context, *PutRequest) (*PutResponse, error) Get(context.Context, *GetRequest) (*GetResponse, error) + CompareAndSwap(context.Context, *CompareAndSwapRequest) (*CompareAndSwapResponse, error) Delete(context.Context, *DeleteRequest) (*DeleteResponse, error) Scan(context.Context, *ScanRequest) (*ScanResponse, error) PreWrite(context.Context, *PreWriteRequest) (*PreCommitResponse, error) @@ -400,6 +413,9 @@ func (UnimplementedTransactionalKVServer) Put(context.Context, *PutRequest) (*Pu func (UnimplementedTransactionalKVServer) Get(context.Context, *GetRequest) (*GetResponse, error) { return nil, status.Error(codes.Unimplemented, "method Get not implemented") } +func (UnimplementedTransactionalKVServer) CompareAndSwap(context.Context, *CompareAndSwapRequest) (*CompareAndSwapResponse, error) { + return nil, status.Error(codes.Unimplemented, "method CompareAndSwap not implemented") +} func (UnimplementedTransactionalKVServer) Delete(context.Context, *DeleteRequest) (*DeleteResponse, error) { return nil, status.Error(codes.Unimplemented, "method Delete not implemented") } @@ -472,6 +488,24 @@ func _TransactionalKV_Get_Handler(srv interface{}, ctx context.Context, dec func return interceptor(ctx, in, info, handler) } +func _TransactionalKV_CompareAndSwap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CompareAndSwapRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactionalKVServer).CompareAndSwap(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: TransactionalKV_CompareAndSwap_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactionalKVServer).CompareAndSwap(ctx, req.(*CompareAndSwapRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _TransactionalKV_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteRequest) if err := dec(in); err != nil { @@ -577,6 +611,10 @@ var TransactionalKV_ServiceDesc = grpc.ServiceDesc{ MethodName: "Get", Handler: _TransactionalKV_Get_Handler, }, + { + MethodName: "CompareAndSwap", + Handler: _TransactionalKV_CompareAndSwap_Handler, + }, { MethodName: "Delete", Handler: _TransactionalKV_Delete_Handler, diff --git a/store/bootstrap_baseline_encryption.go b/store/bootstrap_baseline_encryption.go index 67c378a89..cfd6d5537 100644 --- a/store/bootstrap_baseline_encryption.go +++ b/store/bootstrap_baseline_encryption.go @@ -45,7 +45,7 @@ func (d *OfflineBaselineDecoder) canonicalStoredValue(key, value []byte) ([]byte if err != nil { return nil, errors.Wrap(err, "offline stored-value header") } - if IsRaftControlMetadataKey(key) && (sv.Tombstone || sv.ExpireAt != 0) { + if IsRaftControlMetadataKey(key) && (sv.Tombstone || sv.ExpireAt != 0 || sv.AdoptionEpoch != 0) { return nil, errors.WithStack(ErrBootstrapBaselineInvalid) } // Use the exact runtime AAD/header, rebadging defense and bounded V2 @@ -59,7 +59,7 @@ func (d *OfflineBaselineDecoder) canonicalStoredValue(key, value []byte) ([]byte if err != nil { return nil, errors.Wrap(err, "offline stored-value decompression") } - return encodeValue(plain, sv.Tombstone, sv.ExpireAt, encStateCleartext), nil + return encodeAdoptedValue(plain, sv.Tombstone, sv.ExpireAt, encStateCleartext, sv.AdoptionEpoch), nil } // ProbeBootstrapBaselineSnapshotWithDecoder hashes every authenticated logical diff --git a/store/chunkblob_local.go b/store/chunkblob_local.go index 0d8f5f90f..fb63c1263 100644 --- a/store/chunkblob_local.go +++ b/store/chunkblob_local.go @@ -110,7 +110,7 @@ func (s *pebbleStore) chunkBlobWrittenAtLocked(ctx context.Context, key []byte) if !bytes.Equal(userKey, key) { continue } - _, err := s.readVisibleVersion(it, key, math.MaxUint64) + _, err := s.readVisibleVersion(ctx, it, key, math.MaxUint64, nil) if errors.Is(err, ErrKeyNotFound) { return 0, false, nil } diff --git a/store/encryption_glue.go b/store/encryption_glue.go index c1572b189..1f483e317 100644 --- a/store/encryption_glue.go +++ b/store/encryption_glue.go @@ -1,6 +1,8 @@ package store import ( + "encoding/binary" + "github.com/bootjp/elastickv/internal/encryption" "github.com/cockroachdb/errors" "github.com/cockroachdb/pebble/v2" @@ -390,6 +392,10 @@ func (s *pebbleStore) resolveEnvelopeEmit(gateRegistration bool) (keyID uint32, // in resolveEnvelopeEmit so this function stays within the cyclop // budget. func (s *pebbleStore) encryptForKey(pebbleKey, plaintext []byte, expireAt uint64, gateRegistration bool) ([]byte, byte, error) { + return s.encryptVersionForKey(pebbleKey, plaintext, expireAt, gateRegistration, false, 0) +} + +func (s *pebbleStore) encryptVersionForKey(pebbleKey, plaintext []byte, expireAt uint64, gateRegistration, tombstone bool, adoptionEpoch uint64) ([]byte, byte, error) { keyID, encrypt, err := s.resolveEnvelopeEmit(gateRegistration) if err != nil { return nil, 0, err @@ -410,9 +416,9 @@ func (s *pebbleStore) encryptForKey(pebbleKey, plaintext []byte, expireAt uint64 if envelopeFlag&encryption.FlagCompressed != 0 { envelopeVersion = encryption.EnvelopeVersionV2 } - var hdr [valueHeaderSize]byte - writeValueHeaderBytes(hdr[:], false /*tombstone*/, expireAt, encStateEncrypted) - aad := buildStorageAAD(envelopeVersion, envelopeFlag, keyID, hdr[:], pebbleKey) + var hdr [maxValueHeaderSize]byte + headerSize := writeVersionHeaderBytes(hdr[:], tombstone, expireAt, encStateEncrypted, adoptionEpoch) + aad := buildStorageAAD(envelopeVersion, envelopeFlag, keyID, hdr[:headerSize], pebbleKey) ciphertextAndTag, err := s.cipher.Encrypt(payload, aad, keyID, nonce) if err != nil { return nil, 0, errors.Wrap(err, "store: encrypt value") @@ -503,9 +509,9 @@ func (s *pebbleStore) decryptAuthenticatedForKey(pebbleKey []byte, sv storedValu s.observeDecryptFailure(err) return nil, 0, errors.Wrap(err, "store: decode envelope") } - var hdr [valueHeaderSize]byte - writeValueHeaderBytes(hdr[:], sv.Tombstone, sv.ExpireAt, sv.EncState) - aad := buildStorageAAD(env.Version, env.Flag, env.KeyID, hdr[:], pebbleKey) + var hdr [maxValueHeaderSize]byte + headerSize := writeVersionHeaderBytes(hdr[:], sv.Tombstone, sv.ExpireAt, sv.EncState, sv.AdoptionEpoch) + aad := buildStorageAAD(env.Version, env.Flag, env.KeyID, hdr[:headerSize], pebbleKey) plain, err := s.cipher.Decrypt(env.Body, aad, env.KeyID, env.Nonce[:]) if err != nil { s.observeDecryptFailure(err) @@ -620,9 +626,8 @@ func compressForEncryption(plaintext []byte) ([]byte, byte) { // - version/flag = V1/uncompressed or V2/Snappy-compressed (the two // combinations emitted by the encrypt path; trusting on-disk would // let corrupted format bytes bypass the trial) -// - tombstone = false (the encrypt path never wraps -// tombstones, so any on-disk tombstone bit on an encrypted -// entry is necessarily attacker-supplied) +// - tombstone = false for legacy headers; false/true for adopted headers, +// which can carry an authenticated empty tombstone body // // The remaining AAD inputs come from disk and we enumerate plausible // candidates: @@ -632,6 +637,8 @@ func compressForEncryption(plaintext []byte) ([]byte, byte) { // - expireAt: {on-disk value, 0} (covers both no-flip and the // common "no-TTL write whose expireAt was rewritten by the // attacker" case) +// - adoption epoch: the on-disk tag, including the shifted body prefix if +// the adoption flag was cleared // // The body is sliced at fixed offsets rather than going through // DecodeEnvelope so a corrupted version or flag byte cannot force @@ -642,7 +649,8 @@ func compressForEncryption(plaintext []byte) ([]byte, byte) { // attacker who flips encState=0b01โ†’0b00 and ALSO corrupts a byte the // trial cannot reproduce from canonical inputs โ€” specifically // body[HeaderSize:] (ciphertext / tag) or expireAt when the original -// was a non-zero value the attacker also rewrote โ€” falls through to +// was a non-zero value the attacker also rewrote, or a rewritten adoption +// epoch combined with a cleartext relabel โ€” falls through to // the cleartext branch. The user receives garbage bytes (NOT the // original plaintext: the attacker does not hold the DEK), so the // gap is in integrity observability, not confidentiality. Stage 8 @@ -656,6 +664,22 @@ func (s *pebbleStore) rejectRebadgedEnvelope(pebbleKey []byte, sv storedValue, b if s.cipher == nil { return nil } + if err := s.rejectRebadgedEnvelopeBody(pebbleKey, sv, body); err != nil { + return err + } + // Clearing the adoption flag moves its eight authenticated bytes into the + // apparent body. Try the original framing as well; otherwise a combined + // adoption/encryption relabel could turn an integrity failure into absence. + if sv.AdoptionEpoch == 0 && len(body) >= timestampSize+encryption.EnvelopeOverhead { + sv.AdoptionEpoch = binary.LittleEndian.Uint64(body) + if sv.AdoptionEpoch != 0 { + return s.rejectRebadgedEnvelopeBody(pebbleKey, sv, body[timestampSize:]) + } + } + return nil +} + +func (s *pebbleStore) rejectRebadgedEnvelopeBody(pebbleKey []byte, sv storedValue, body []byte) error { if len(body) < encryption.EnvelopeOverhead { return nil } @@ -667,26 +691,28 @@ func (s *pebbleStore) rejectRebadgedEnvelope(pebbleKey []byte, sv storedValue, b } for _, kid := range s.cipher.LoadedKeyIDs() { for _, candidateExpire := range candidateExpireAts { - for _, candidate := range []struct { - version byte - flag byte - }{ - {version: encryption.EnvelopeVersionV1}, - {version: encryption.EnvelopeVersionV2, flag: encryption.FlagCompressed}, - } { - var hdr [valueHeaderSize]byte - writeValueHeaderBytes(hdr[:], false /*canonical*/, candidateExpire, encStateEncrypted) - aad := buildStorageAAD(candidate.version, candidate.flag, kid, hdr[:], pebbleKey) - // Deliberately NOT reported to - // encryptionObserver: this loop trial-decrypts - // against every loaded DEK, and a tag mismatch - // is the EXPECTED result for genuine cleartext. - // Counting it would increment the paging-grade - // ยง9.2 decrypt_failures counter on essentially - // every cleartext read. - if _, err := s.cipher.Decrypt(ct, aad, kid, nonce); err == nil { - return errors.Wrap(ErrEncryptedReadIntegrity, - "store: cleartext-labelled value verifies as a relabeled envelope under a loaded DEK") + for _, tombstone := range rebadgedEnvelopeTombstones(sv.AdoptionEpoch) { + for _, candidate := range []struct { + version byte + flag byte + }{ + {version: encryption.EnvelopeVersionV1}, + {version: encryption.EnvelopeVersionV2, flag: encryption.FlagCompressed}, + } { + var hdr [maxValueHeaderSize]byte + headerSize := writeVersionHeaderBytes(hdr[:], tombstone, candidateExpire, encStateEncrypted, sv.AdoptionEpoch) + aad := buildStorageAAD(candidate.version, candidate.flag, kid, hdr[:headerSize], pebbleKey) + // Deliberately NOT reported to + // encryptionObserver: this loop trial-decrypts + // against every loaded DEK, and a tag mismatch + // is the EXPECTED result for genuine cleartext. + // Counting it would increment the paging-grade + // ยง9.2 decrypt_failures counter on essentially + // every cleartext read. + if _, err := s.cipher.Decrypt(ct, aad, kid, nonce); err == nil { + return errors.Wrap(ErrEncryptedReadIntegrity, + "store: cleartext-labelled value verifies as a relabeled envelope under a loaded DEK") + } } } } @@ -697,10 +723,17 @@ func (s *pebbleStore) rejectRebadgedEnvelope(pebbleKey []byte, sv storedValue, b return nil } +func rebadgedEnvelopeTombstones(epoch uint64) []bool { + if epoch == 0 { + return []bool{false} + } + return []bool{false, true} +} + // buildStorageAAD composes the ยง4.1 storage-envelope AAD with a // single allocation. Layout: // -// envelope_version โ€– flag โ€– key_id โ€– value_header(9B) โ€– pebble_key +// envelope_version โ€– flag โ€– key_id โ€– value_header(9B or 17B) โ€– pebble_key // // Pre-sizing avoids re-allocation across the two appends below // (AppendHeaderAADBytes + the value-header / pebble-key append). diff --git a/store/internal_record_reclaim_test.go b/store/internal_record_reclaim_test.go index 2e1949e57..736580262 100644 --- a/store/internal_record_reclaim_test.go +++ b/store/internal_record_reclaim_test.go @@ -109,14 +109,21 @@ type internalRecordDiskBytes struct { Allocated int64 } -func runInternalRecordDiskTrial(t *testing.T, count int, reclaim bool) (before, after internalRecordDiskBytes) { +func openInternalRecordTrial(t *testing.T, dir string) *pebbleStore { t.Helper() - ctx := t.Context() - dir := filepath.Join(t.TempDir(), "pebble") opened, err := NewPebbleStore(dir) require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, opened.Close()) }) st, ok := opened.(*pebbleStore) require.True(t, ok) + return st +} + +func runInternalRecordDiskTrial(t *testing.T, count int, reclaim bool) (before, after internalRecordDiskBytes) { + t.Helper() + ctx := t.Context() + dir := filepath.Join(t.TempDir(), "pebble") + st := openInternalRecordTrial(t, dir) keep := []byte("user-key") require.NoError(t, st.PutAt(ctx, keep, []byte("value"), 1, 0)) records := make([]*KVPairMutation, count) @@ -126,7 +133,10 @@ func runInternalRecordDiskTrial(t *testing.T, count int, reclaim bool) (before, } require.NoError(t, st.ApplyMutationsRaftAt(ctx, records, nil, 1, 2, 1)) compactInternalRecordTrial(t, st) - before = measureInternalRecordTrial(t, dir) + require.NoError(t, st.Close()) + before = measureInternalRecordTrial(t, st) + + st = openInternalRecordTrial(t, dir) for _, rec := range records { rec.Op = OpTypeDelete } @@ -141,11 +151,9 @@ func runInternalRecordDiskTrial(t *testing.T, count int, reclaim bool) (before, } compactInternalRecordTrial(t, st) require.NoError(t, st.Close()) - after = measureInternalRecordTrial(t, dir) + after = measureInternalRecordTrial(t, st) - reopened, err := NewPebbleStore(dir) - require.NoError(t, err) - t.Cleanup(func() { require.NoError(t, reopened.Close()) }) + reopened := openInternalRecordTrial(t, dir) val, err := reopened.GetAt(ctx, keep, math.MaxUint64) require.NoError(t, err) require.True(t, bytes.Equal(val, []byte("value"))) @@ -160,10 +168,11 @@ func compactInternalRecordTrial(t *testing.T, st *pebbleStore) { require.NoError(t, st.db.Compact(t.Context(), []byte{0}, []byte{0xff}, false)) } -func measureInternalRecordTrial(t *testing.T, dir string) internalRecordDiskBytes { +func measureInternalRecordTrial(t *testing.T, st *pebbleStore) internalRecordDiskBytes { t.Helper() + require.True(t, st.db == nil && st.lifecycleLock == nil, "close the Pebble store before measuring disk usage") var result internalRecordDiskBytes - require.NoError(t, filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error { + require.NoError(t, filepath.WalkDir(st.dir, func(path string, entry fs.DirEntry, err error) error { if err != nil || entry.IsDir() { return err } diff --git a/store/lsm_migration.go b/store/lsm_migration.go index 9c1c5a7b3..5418422de 100644 --- a/store/lsm_migration.go +++ b/store/lsm_migration.go @@ -17,6 +17,14 @@ func (s *pebbleStore) ExportVersions(ctx context.Context, opts ExportVersionsOpt } func (s *pebbleStore) exportVersionsLocked(ctx context.Context, opts ExportVersionsOptions) (ExportVersionsResult, error) { + return s.exportVersionsFromLocked(ctx, s.db, opts, false) +} + +func (s *pebbleStore) exportVersionsFromLocked(ctx context.Context, reader pebble.Reader, opts ExportVersionsOptions, checkIteratorClose bool) (_ ExportVersionsResult, err error) { + if !opts.includeRetired { + state := s.versionRetirementFor(ctx) + opts.retirement = &state + } opts = normalizeExportVersionsOptions(opts) pos, err := decodeExportCursorForOptions(opts) if err != nil { @@ -29,12 +37,20 @@ func (s *pebbleStore) exportVersionsLocked(ctx context.Context, opts ExportVersi return ExportVersionsResult{}, ErrReadTSCompacted } - iter, err := s.db.NewIter(pebbleExportIterOptions(opts)) + iter, err := reader.NewIter(pebbleExportIterOptions(opts)) if err != nil { return ExportVersionsResult{}, errors.WithStack(err) } - defer iter.Close() + defer func() { + closeErr := iter.Close() + if checkIteratorClose { + err = errors.Join(err, closeErr) + } + }() + return s.scanPebbleExport(ctx, iter, opts, pos) +} +func (s *pebbleStore) scanPebbleExport(ctx context.Context, iter *pebble.Iterator, opts ExportVersionsOptions, pos exportCursorPosition) (ExportVersionsResult, error) { seek, err := pebbleExportSeekKey(opts, pos) if err != nil { return ExportVersionsResult{}, err @@ -292,6 +308,13 @@ func (s *pebbleStore) appendExportedPebbleVersion( if err != nil { return false, false, err } + retained, err := opts.retiredOrReclaimed(version) + if err != nil { + return false, false, err + } + if retained { + return false, true, nil + } if opts.AcceptVersion != nil && !opts.AcceptVersion(version.Key, version.Value) { result.NextCursor = encodeExportCursor(userKey, commitTS, exportCursorTagScanned) if finishExportIfLimited(opts, result) { @@ -333,12 +356,13 @@ func (s *pebbleStore) decodeExportedPebbleVersion(iter *pebble.Iterator, userKey value = nil } return MVCCVersion{ - Key: bytes.Clone(userKey), - CommitTS: commitTS, - Tombstone: sv.Tombstone, - Value: bytes.Clone(value), - KeyFamily: keyFamily, - ExpireAt: sv.ExpireAt, + Key: bytes.Clone(userKey), + CommitTS: commitTS, + Tombstone: sv.Tombstone, + Value: bytes.Clone(value), + KeyFamily: keyFamily, + ExpireAt: sv.ExpireAt, + adoptionEpoch: sv.AdoptionEpoch, }, nil } @@ -434,13 +458,35 @@ func (s *pebbleStore) validatePebbleImportBatch(opts ImportVersionsOptions) (boo return false, nil, nil } +func (s *pebbleStore) planPebbleImportWrites(opts ImportVersionsOptions, gateRegistration bool) ([]MVCCVersion, error) { + opts.Versions = unadoptedImportVersions(opts.Versions) + if err := s.versionRetirement.validateMigrationImport(opts); err != nil { + return nil, err + } + if opts.AllowLegacyVersionOverwrite { + return opts.Versions, nil + } + lookup := s.lookupMigrationHead + if gateRegistration { + lookup = s.lookupMigrationVersion + } + if opts.AllowRetiredStaging { + lookup = s.versionRetirement.retainedMigrationLookup(lookup) + } + return immutableMigrationWrites(opts.Versions, opts.LogicalKey, lookup) +} + func (s *pebbleStore) commitPebbleImportBatch(opts ImportVersionsOptions, batchMax uint64, writeOpts *pebble.WriteOptions, gateRegistration bool) error { + writes, err := s.planPebbleImportWrites(opts, gateRegistration) + if err != nil { + return err + } batch := s.db.NewBatch() defer batch.Close() if err := s.stageOnlineImport(batch, opts); err != nil { return err } - if err := s.applyImportVersionsBatch(batch, opts.Versions, gateRegistration); err != nil { + if err := s.applyImportVersionsBatch(batch, writes, gateRegistration); err != nil { return err } if err := s.stageMigrationImportAck(batch, opts.JobID, opts.BracketID, migrationImportAck{ @@ -499,14 +545,14 @@ func (s *pebbleStore) applyImportVersionsBatch(batch *pebble.Batch, versions []M return err } var encoded []byte - if version.Tombstone { + if version.Tombstone && version.adoptionEpoch == 0 { encoded = encodeValue(nil, true, 0, encStateCleartext) } else { - body, encState, err := s.encryptForKey(k, version.Value, version.ExpireAt, gateRegistration) + body, encState, err := s.encryptVersionForKey(k, version.Value, version.ExpireAt, gateRegistration, version.Tombstone, version.adoptionEpoch) if err != nil { return err } - encoded = encodeValue(body, false, version.ExpireAt, encState) + encoded = encodeAdoptedValue(body, version.Tombstone, version.ExpireAt, encState, version.adoptionEpoch) } if err := batch.Set(k, encoded, nil); err != nil { return errors.WithStack(err) diff --git a/store/lsm_store.go b/store/lsm_store.go index 3dad2a8f7..fbaed8fea 100644 --- a/store/lsm_store.go +++ b/store/lsm_store.go @@ -16,11 +16,13 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "github.com/bootjp/elastickv/internal/encryption" "github.com/cockroachdb/errors" "github.com/cockroachdb/pebble/v2" "github.com/cockroachdb/pebble/v2/vfs" + "go.etcd.io/etcd/client/pkg/v3/fileutil" ) const ( @@ -29,18 +31,20 @@ const ( // First-byte (flags) layout per design ยง4.1: // bit 0 tombstone // bits 1-2 encryption_state (0b00 cleartext, 0b01 encrypted, 0b10/0b11 reserved) - // bits 3-7 reserved (must be zero) + // bit 3 local version adoption epoch follows expireAt + // bits 4-7 reserved (must be zero) encStateMask byte = 0b0000_0110 encStateShift = 1 tombstoneMask byte = 0b0000_0001 encStateCleartext byte = 0b00 encStateEncrypted byte = 0b01 - encStateReservedMask byte = 0b1111_1000 // bits 3-7 must stay zero + encStateReservedMask byte = 0b1111_0000 // bits 4-7 must stay zero snapshotBatchCountLimit = 1000 snapshotBatchByteLimit = 8 << 20 // 8 MiB; balances restore write amplification vs peak memory usage compactionDeleteBatchCountLimit = 128 compactionDeleteBatchByteLimit = 1 << 20 dirPerms = 0755 + storeLifecycleLockPerms = 0o600 metaLastCommitTS = "_meta_last_commit_ts" metaMinRetainedTS = "_meta_min_retained_ts" metaPendingMinRetainedTS = "_meta_pending_min_retained_ts" @@ -243,9 +247,11 @@ var metaAppliedIndexBytes = []byte(metaAppliedIndex) // 4. mtx โ€“ guards the in-memory metadata fields // (lastCommitTS, minRetainedTS, pendingMinRetainedTS, migrationReadinessCache). type pebbleStore struct { + versionRetirement versionRetirementState db *pebble.DB cache *pebble.Cache // owns one ref; Unref on Close / reopen. dbMu sync.RWMutex // guards s.db pointer โ€“ see lock ordering above + ownedSnapshotPins atomic.Int64 // capture holds dbMu.RLock; replacement checks under dbMu.Lock log *slog.Logger lastCommitTS uint64 minRetainedTS uint64 @@ -256,6 +262,7 @@ type pebbleStore struct { applyMu sync.Mutex // serializes ApplyMutations: conflict check โ†’ commit maintenanceMu sync.Mutex dir string + lifecycleLock *fileutil.LockedFile // protects restore recovery and sibling artifacts across DB swaps // sstIngestSnapshots enables the cluster-wide opt-in snapshot format // implemented in snapshot_pebble_sst.go. Receivers always understand the // format; senders keep the legacy stream by default for rolling-upgrade @@ -397,10 +404,24 @@ func processPebbleCacheRef() *pebble.Cache { } // NewPebbleStore creates a new Pebble-backed MVCC store. -func NewPebbleStore(dir string, opts ...PebbleStoreOption) (MVCCStore, error) { +func NewPebbleStore(dir string, opts ...PebbleStoreOption) (_ MVCCStore, retErr error) { + // Restore renames the live directory itself. Resolve a directory symlink + // before choosing either the restore destination or its sibling lock. + dir = filepath.Clean(dir) + if info, err := os.Lstat(dir); err == nil && info.Mode()&os.ModeSymlink != 0 { + dir, err = filepath.EvalSymlinks(dir) + if err != nil { + return nil, errors.WithStack(err) + } + } + lock, err := lockPebbleStoreLifecycle(dir) + if err != nil { + return nil, err + } fsmOpts, fsmLabel := resolveFSMApplyWriteOpts(os.Getenv(fsmSyncModeEnv)) s := &pebbleStore{ - dir: dir, + dir: dir, + lifecycleLock: lock, log: slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelWarn, })), @@ -413,7 +434,12 @@ func NewPebbleStore(dir string, opts ...PebbleStoreOption) (MVCCStore, error) { for _, opt := range opts { opt(s) } - if err := cleanupPebbleSnapshotArtifacts(dir); err != nil { + defer func() { + if retErr != nil { + retErr = errors.Join(retErr, s.closeStoreDB(), lock.Close()) + } + }() + if err := recoverPebbleRestoreBackup(dir); err != nil { return nil, err } @@ -425,40 +451,35 @@ func NewPebbleStore(dir string, opts ...PebbleStoreOption) (MVCCStore, error) { } s.db = db s.cache = cache - - // cleanupOnInitFail closes the just-opened DB and releases this open's - // borrowed cache reference when a metadata scan fails. Also nil out the - // store pointers so a zero-valued pebbleStore does not retain stale refs. - cleanupOnInitFail := func() { - _ = db.Close() - cache.Unref() - s.db = nil - s.cache = nil + if err := s.loadOpenedStoreState(dir); err != nil { + return nil, err } + return s, nil +} +func (s *pebbleStore) loadOpenedStoreState(dir string) error { // Initialize lastCommitTS from the persisted meta key, then validate it // against data versions. Older stores and crash windows can have missing or // stale metadata while MVCC versions remain present; using the lower meta // watermark for OCC would skip conflict scans incorrectly. maxTS, err := s.findMaxCommitTS() if err != nil { - cleanupOnInitFail() - return nil, err + return err } minRetainedTS, err := s.findMinRetainedTS() if err != nil { - cleanupOnInitFail() - return nil, err + return err } pendingMinRetainedTS, err := s.findPendingMinRetainedTS() if err != nil { - cleanupOnInitFail() - return nil, err + return err } readinessStates, err := s.loadMigrationServingMetadata() if err != nil { - cleanupOnInitFail() - return nil, err + return err + } + if err := s.loadVersionRetirements(); err != nil { + return err } s.lastCommitTS = maxTS s.minRetainedTS = minRetainedTS @@ -467,12 +488,27 @@ func NewPebbleStore(dir string, opts ...PebbleStoreOption) (MVCCStore, error) { // A backup is only stale after the live directory has opened and its // metadata has been read successfully. Before this point it is the recovery // source for a process crash between the two restore renames. - if err := cleanupPebbleRestoreBackups(dir); err != nil { - cleanupOnInitFail() - return nil, err + if err := cleanupPebbleSnapshotArtifacts(dir); err != nil { + return err } - return s, nil + return nil +} + +func lockPebbleStoreLifecycle(dir string) (*fileutil.LockedFile, error) { + abs, err := filepath.Abs(dir) + if err != nil { + return nil, errors.WithStack(err) + } + // Keep lock inodes outside both the swappable DB and every scratch + // prefix. File-descriptor locks also exclude another open in this process. + lockDir := filepath.Join(filepath.Dir(abs), ".elastickv-store-locks") + if err := os.MkdirAll(lockDir, dirPerms); err != nil { + return nil, errors.WithStack(err) + } + // Never unlink this file. A concurrent opener must lock the same inode. + lock, err := fileutil.TryLockFile(filepath.Join(lockDir, filepath.Base(abs)), os.O_RDWR|os.O_CREATE, storeLifecycleLockPerms) + return lock, errors.Wrap(err, "lock Pebble store lifecycle") } // Key encoding: UserKey + Separator(0x00) + Timestamp(BigEndian, BitInverted) @@ -583,10 +619,11 @@ func decodeKeyView(k []byte) ([]byte, uint64) { // envelope's AAD so a cut-and-paste / version-substitution attack // rejects on Decrypt; see ยง4.1 case 2/3. type storedValue struct { - Value []byte - Tombstone bool - EncState byte // 0b00 cleartext, 0b01 encrypted; reserved values rejected at decode - ExpireAt uint64 + Value []byte + Tombstone bool + EncState byte // 0b00 cleartext, 0b01 encrypted; reserved values rejected at decode + ExpireAt uint64 + AdoptionEpoch uint64 } // ErrEncryptedValueReservedState indicates decodeValue saw an @@ -630,19 +667,12 @@ func writeValueHeaderBytes(dst []byte, tombstone bool, expireAt uint64, encState } func decodeValue(data []byte) (storedValue, error) { - tombstone, expireAt, encState, err := decodeValueHeader(data) + value, err := decodeValueView(data) if err != nil { return storedValue{}, err } - val := make([]byte, len(data)-valueHeaderSize) - copy(val, data[valueHeaderSize:]) - - return storedValue{ - Value: val, - Tombstone: tombstone, - EncState: encState, - ExpireAt: expireAt, - }, nil + value.Value = bytes.Clone(value.Value) + return value, nil } func decodeValueView(data []byte) (storedValue, error) { @@ -650,11 +680,16 @@ func decodeValueView(data []byte) (storedValue, error) { if err != nil { return storedValue{}, err } + adoptionEpoch, err := decodeValueAdoptionEpoch(data) + if err != nil { + return storedValue{}, err + } return storedValue{ - Value: data[valueHeaderSize:], - Tombstone: tombstone, - EncState: encState, - ExpireAt: expireAt, + Value: data[versionValueHeaderSize(adoptionEpoch):], + Tombstone: tombstone, + EncState: encState, + ExpireAt: expireAt, + AdoptionEpoch: adoptionEpoch, }, nil } @@ -672,6 +707,9 @@ func decodeValueHeader(data []byte) (bool, uint64, byte, error) { return false, 0, 0, errors.Wrapf(ErrEncryptedValueReservedState, "encryption_state=%#x is reserved", encState) } + if _, err := decodeValueAdoptionEpoch(data); err != nil { + return false, 0, 0, err + } return flags&tombstoneMask != 0, binary.LittleEndian.Uint64(data[1:]), encState, nil } @@ -938,8 +976,7 @@ func (s *pebbleStore) LastAppliedIndex() (uint64, bool, error) { // meta key bump from. If we honoured nosync mode here, a crash // between Pebble's deferred flush and SaveSnap's internal fsync // would leave snapshot pointer at X but metaAppliedIndex at Y < X -// forever. The +1 fsync per snapshot persist (rare; default -// SnapshotCount=10000) is negligible vs that risk. +// forever. // // Monotonicity (round-2 P2 fix for PR #915): when persistLocalSnapshot // runs in a background worker, raft apply can continue and the per- @@ -949,7 +986,7 @@ func (s *pebbleStore) LastAppliedIndex() (uint64, bool, error) { // causing the future skip gate to fall back unnecessarily. The // applyMu lock serialises with applyMutationsWithOpts / // deletePrefixAtWithOpts (both hold it across their batch commit), -// and the read-modify-write keeps the meta key strictly monotonic. +// and the read-modify-write keeps the meta key nondecreasing. // // Lock order: applyMu.Lock before dbMu.RLock matches the discipline in // applyMutationsWithOpts (see the lock ordering on pebbleStore). No @@ -960,21 +997,15 @@ func (s *pebbleStore) SetDurableAppliedIndex(idx uint64) error { s.dbMu.RLock() defer s.dbMu.RUnlock() - existing, present, err := s.readAppliedIndexLocked() + existing, _, err := s.readAppliedIndexLocked() if err != nil { return err } - if present && existing >= idx { - // Concurrent apply already advanced the meta key past `idx`; - // no work needed. The skip-invariant still holds because the - // snapshot's claim (LastAppliedIndex >= snap.Metadata.Index) - // is satisfied by existing >= idx >= snap.Metadata.Index. - return nil - } - + // Even an equal or higher value may come from a NoSync data batch. + // Sync the maximum so the preceding data and index survive together. batch := s.db.NewBatch() defer func() { _ = batch.Close() }() - if err := setPebbleUint64InBatch(batch, metaAppliedIndexBytes, idx); err != nil { + if err := setPebbleUint64InBatch(batch, metaAppliedIndexBytes, max(existing, idx)); err != nil { return err } return errors.WithStack(batch.Commit(pebble.Sync)) @@ -1154,9 +1185,9 @@ func (s *pebbleStore) alignCommitTS(commitTS uint64) uint64 { // MVCC Implementation -// getAt is the internal implementation of GetAt. It must be called while the -// caller holds at least s.dbMu.RLock(). -func (s *pebbleStore) getAt(ctx context.Context, key []byte, ts uint64) ([]byte, error) { +// getAt must be called while holding at least s.dbMu.RLock(). A non-nil +// version requests metadata from the same visible record as the returned value. +func (s *pebbleStore) getAt(ctx context.Context, key []byte, ts uint64, version *VersionedValue) ([]byte, error) { if readTSCompacted(ts, s.effectiveMinRetainedTS()) { return nil, ErrReadTSCompacted } @@ -1172,9 +1203,9 @@ func (s *pebbleStore) getAt(ctx context.Context, key []byte, ts uint64) ([]byte, defer iter.Close() if !iter.SeekGE(seekKey) { - return nil, ErrKeyNotFound + return missingIteratorValue(iter) } - return s.readVisibleVersion(iter, key, ts) + return s.readVisibleVersion(ctx, iter, key, ts, version) } // readVisibleVersion examines the iterator's current entry and @@ -1189,12 +1220,12 @@ func (s *pebbleStore) getAt(ctx context.Context, key []byte, ts uint64) ([]byte, // GCM (returns ErrEncryptedReadIntegrity) or matches the original // values, in which case the visibility checks below are operating // on authenticated bytes. -func (s *pebbleStore) readVisibleVersion(iter *pebble.Iterator, key []byte, ts uint64) ([]byte, error) { +func (s *pebbleStore) readVisibleVersion(ctx context.Context, iter *pebble.Iterator, key []byte, ts uint64, version *VersionedValue) ([]byte, error) { if !skipPebbleMetadataForward(iter) { - return nil, ErrKeyNotFound + return missingIteratorValue(iter) } k := iter.Key() - userKey, _ := decodeKeyView(k) + userKey, commitTS := decodeKeyView(k) if !bytes.Equal(userKey, key) { return nil, ErrKeyNotFound } @@ -1206,18 +1237,32 @@ func (s *pebbleStore) readVisibleVersion(iter *pebble.Iterator, key []byte, ts u if err != nil { return nil, err } + if err := s.requireRetainedIteratorEntry(ctx, iter); err != nil { + return nil, err + } if sv.Tombstone { return nil, ErrKeyNotFound } if sv.ExpireAt != 0 && sv.ExpireAt <= ts { return nil, ErrKeyNotFound } + if version != nil { + version.TS = commitTS + version.ExpireAt = sv.ExpireAt + } return finishAuthenticatedValue(plain, flag) } +func missingIteratorValue(iter *pebble.Iterator) ([]byte, error) { + if err := iter.Error(); err != nil { + return nil, errors.WithStack(err) + } + return nil, ErrKeyNotFound +} + func (s *pebbleStore) GetAt(ctx context.Context, key []byte, ts uint64) ([]byte, error) { s.dbMu.RLock() - value, err := s.getAt(ctx, key, ts) + value, err := s.getAt(ctx, key, ts, nil) s.dbMu.RUnlock() if retired := s.txnDecisionReadError(ctx, key, ts, err); retired != nil { return nil, retired @@ -1225,6 +1270,18 @@ func (s *pebbleStore) GetAt(ctx context.Context, key []byte, ts uint64) ([]byte, return value, nil } +func (s *pebbleStore) GetVersionAt(ctx context.Context, key []byte, ts uint64) (VersionedValue, error) { + s.dbMu.RLock() + var version VersionedValue + value, err := s.getAt(ctx, key, ts, &version) + s.dbMu.RUnlock() + if retired := s.txnDecisionReadError(ctx, key, ts, err); retired != nil { + return VersionedValue{}, retired + } + version.Value = value + return version, nil +} + func (s *pebbleStore) VersionExistsAtOrBefore(ctx context.Context, key []byte, ts uint64) (bool, error) { s.dbMu.RLock() defer s.dbMu.RUnlock() @@ -1252,7 +1309,11 @@ func (s *pebbleStore) VersionExistsAtOrBefore(ctx context.Context, key []byte, t return false, nil } userKey, _ := decodeKeyView(iter.Key()) - return bytes.Equal(userKey, key), nil + if !bytes.Equal(userKey, key) { + return false, nil + } + retired, err := s.retiredIteratorEntry(ctx, iter) + return !retired, err } func (s *pebbleStore) GetAtBatch(ctx context.Context, keys [][]byte, ts uint64) (map[string][]byte, error) { @@ -1298,7 +1359,7 @@ func (s *pebbleStore) getAtBatchWithIter(ctx context.Context, iter *pebble.Itera } continue } - value, err := s.readVisibleVersion(iter, key, ts) + value, err := s.readVisibleVersion(ctx, iter, key, ts, nil) if err != nil { if errors.Is(err, ErrKeyNotFound) { continue @@ -1335,7 +1396,7 @@ func (s *pebbleStore) ExistsAt(ctx context.Context, key []byte, ts uint64) (bool defer s.dbMu.RUnlock() // Use internal getAt to avoid a recursive dbMu.RLock() acquisition. - val, err := s.getAt(ctx, key, ts) + val, err := s.getAt(ctx, key, ts, nil) if errors.Is(err, ErrKeyNotFound) { return false, nil } @@ -1368,6 +1429,10 @@ func (s *pebbleStore) ExistsAt(ctx context.Context, key []byte, ts uint64) (bool func (s *pebbleStore) CommittedVersionAt(ctx context.Context, key []byte, commitTS uint64) (bool, error) { s.dbMu.RLock() defer s.dbMu.RUnlock() + state := s.versionRetirementFor(ctx) + if len(state.records) != 0 || state.adoptionEpoch != 0 { + return s.retainedCommittedVersionAt(ctx, key, commitTS) + } return committedVersionAtWith(s.raftEntryReader(ctx), key, commitTS) } @@ -1389,7 +1454,7 @@ func committedVersionAtWith(r pebble.Reader, key []byte, commitTS uint64) (bool, return true, nil } -func (s *pebbleStore) processFoundValue(iter *pebble.Iterator, userKey []byte, ts uint64) (*KVPair, error) { +func (s *pebbleStore) processFoundValue(ctx context.Context, iter *pebble.Iterator, userKey []byte, ts uint64) (*KVPair, error) { valBytes := iter.Value() sv, err := decodeValue(valBytes) if err != nil { @@ -1406,7 +1471,11 @@ func (s *pebbleStore) processFoundValue(iter *pebble.Iterator, userKey []byte, t if err != nil { return nil, err } - if !sv.Tombstone && (sv.ExpireAt == 0 || sv.ExpireAt > ts) { + retired, err := s.retiredIteratorEntry(ctx, iter) + if err != nil { + return nil, err + } + if !retired && !sv.Tombstone && (sv.ExpireAt == 0 || sv.ExpireAt > ts) { value, finishErr := finishAuthenticatedValue(plain, flag) if finishErr != nil { return nil, finishErr @@ -1419,7 +1488,7 @@ func (s *pebbleStore) processFoundValue(iter *pebble.Iterator, userKey []byte, t return nil, nil } -func (s *pebbleStore) foundValueVisible(iter *pebble.Iterator, ts uint64) (bool, error) { +func (s *pebbleStore) foundValueVisible(ctx context.Context, iter *pebble.Iterator, ts uint64) (bool, error) { valBytes := iter.Value() sv, err := decodeValueView(valBytes) if err != nil { @@ -1433,7 +1502,8 @@ func (s *pebbleStore) foundValueVisible(iter *pebble.Iterator, ts uint64) (bool, if err := s.authenticateForKey(iter.Key(), sv, sv.Value); err != nil { return false, err } - return !sv.Tombstone && (sv.ExpireAt == 0 || sv.ExpireAt > ts), nil + retired, err := s.retiredIteratorEntry(ctx, iter) + return !retired && !sv.Tombstone && (sv.ExpireAt == 0 || sv.ExpireAt > ts), err } func (s *pebbleStore) seekToVisibleVersion(iter *pebble.Iterator, userKey []byte, currentVersion, ts uint64) bool { @@ -1560,7 +1630,7 @@ func (s *pebbleStore) collectScanResultsWithPhysicalLimit(ctx context.Context, i } visited++ - kv, advance, err := s.collectForwardScanKV(iter, seen, userKey, version, ts) + kv, advance, err := s.collectForwardScanKV(ctx, iter, seen, userKey, version, ts) if err != nil { return nil, false, err } @@ -1579,7 +1649,7 @@ func forwardScanDone(userKey, end []byte, ok bool) bool { return !ok || pastScanEnd(userKey, end) } -func (s *pebbleStore) collectForwardScanKV(iter *pebble.Iterator, seen map[string]struct{}, userKey []byte, version uint64, ts uint64) (*KVPair, bool, error) { +func (s *pebbleStore) collectForwardScanKV(ctx context.Context, iter *pebble.Iterator, seen map[string]struct{}, userKey []byte, version uint64, ts uint64) (*KVPair, bool, error) { if _, ok := seen[string(userKey)]; ok { return nil, s.skipToNextUserKey(iter, userKey), nil } @@ -1587,7 +1657,7 @@ func (s *pebbleStore) collectForwardScanKV(iter *pebble.Iterator, seen map[strin if !s.seekToVisibleVersion(iter, userKey, version, ts) { return nil, true, nil } - kv, err := s.processFoundValue(iter, userKey, ts) + kv, err := s.processFoundValue(ctx, iter, userKey, ts) if err != nil { return nil, false, err } @@ -1676,7 +1746,7 @@ func (s *pebbleStore) collectVisibleScanKey( var visible bool var err error if version <= ts { - visible, err = s.foundValueVisible(iter, ts) + visible, err = s.foundValueVisible(ctx, iter, ts) } else { visible, err = s.visibleExactKeyAt(ctx, reader, userKey, ts) } @@ -1767,7 +1837,7 @@ func (s *pebbleStore) visibleExactKeyAt(ctx context.Context, reader pebbleIterat if err := ctx.Err(); err != nil { return false, errors.WithStack(err) } - visible, stop, err := s.visibleExactIteratorEntry(iter, key, ts, upperBound != nil) + visible, stop, err := s.visibleExactIteratorEntry(ctx, iter, key, ts, upperBound != nil) if err != nil { return false, err } @@ -1778,7 +1848,7 @@ func (s *pebbleStore) visibleExactKeyAt(ctx context.Context, reader pebbleIterat return false, nil } -func (s *pebbleStore) visibleExactIteratorEntry(iter *pebble.Iterator, key []byte, ts uint64, stopOnPrefixExit bool) (bool, bool, error) { +func (s *pebbleStore) visibleExactIteratorEntry(ctx context.Context, iter *pebble.Iterator, key []byte, ts uint64, stopOnPrefixExit bool) (bool, bool, error) { if isPebbleMetaKey(iter.Key()) { return false, false, nil } @@ -1795,7 +1865,7 @@ func (s *pebbleStore) visibleExactIteratorEntry(iter *pebble.Iterator, key []byt if version > ts { return false, false, nil } - visible, err := s.foundValueVisible(iter, ts) + visible, err := s.foundValueVisible(ctx, iter, ts) if err != nil { return false, true, err } @@ -1902,17 +1972,19 @@ func (s *pebbleStore) ScanKeysAt(ctx context.Context, start []byte, end []byte, } func (s *pebbleStore) collectReverseScanResults( + ctx context.Context, iter *pebble.Iterator, start []byte, end []byte, limit int, ts uint64, ) ([]*KVPair, error) { - result, _, err := s.collectReverseScanResultsWithPhysicalLimit(iter, start, end, limit, 0, ts) + result, _, err := s.collectReverseScanResultsWithPhysicalLimit(ctx, iter, start, end, limit, 0, ts) return result, err } func (s *pebbleStore) collectReverseScanResultsWithPhysicalLimit( + ctx context.Context, iter *pebble.Iterator, start []byte, end []byte, @@ -1928,7 +2000,7 @@ func (s *pebbleStore) collectReverseScanResultsWithPhysicalLimit( if physicalLimit > 0 && visited >= physicalLimit { return result, true, nil } - kv, nextValid, done, err := s.nextReverseScanKV(iter, start, ts) + kv, nextValid, done, err := s.nextReverseScanKV(ctx, iter, start, ts) if err != nil { return nil, false, err } @@ -1953,6 +2025,7 @@ func seekReverseScanStart(iter *pebble.Iterator, end []byte) bool { } func (s *pebbleStore) nextReverseScanKV( + ctx context.Context, iter *pebble.Iterator, start []byte, ts uint64, @@ -1972,7 +2045,7 @@ func (s *pebbleStore) nextReverseScanKV( nextValid := iter.SeekLT(encodeKey(userKey, math.MaxUint64)) return nil, nextValid, false, nil } - kv, err := s.processFoundValue(iter, userKey, ts) + kv, err := s.processFoundValue(ctx, iter, userKey, ts) if err != nil { return nil, false, false, err } @@ -2006,7 +2079,7 @@ func (s *pebbleStore) ReverseScanAt(ctx context.Context, start []byte, end []byt } defer iter.Close() - return s.collectReverseScanResults(iter, start, end, limit, ts) + return s.collectReverseScanResults(ctx, iter, start, end, limit, ts) } func (s *pebbleStore) ReverseScanAtPhysicalLimit(ctx context.Context, start []byte, end []byte, visibleLimit, physicalLimit int, ts uint64) ([]*KVPair, bool, error) { @@ -2038,7 +2111,7 @@ func (s *pebbleStore) ReverseScanAtPhysicalLimit(ctx context.Context, start []by } defer iter.Close() - return s.collectReverseScanResultsWithPhysicalLimit(iter, start, end, visibleLimit, physicalLimit, ts) + return s.collectReverseScanResultsWithPhysicalLimit(ctx, iter, start, end, visibleLimit, physicalLimit, ts) } func (s *pebbleStore) PutAt(ctx context.Context, key []byte, value []byte, commitTS uint64, expireAt uint64) error { @@ -2053,6 +2126,9 @@ func (s *pebbleStore) PutAt(ctx context.Context, key []byte, value []byte, commi } s.dbMu.RLock() defer s.dbMu.RUnlock() + if err := s.versionRetirement.validateWrite(key, value, commitTS); err != nil { + return err + } commitTS = s.alignCommitTS(commitTS) // gateRegistration=true: PutAt is a direct (non-raft) write path. @@ -2080,6 +2156,9 @@ func (s *pebbleStore) DeleteAt(ctx context.Context, key []byte, commitTS uint64) } s.dbMu.RLock() defer s.dbMu.RUnlock() + if err := s.versionRetirement.validateWrite(key, nil, commitTS); err != nil { + return err + } commitTS = s.alignCommitTS(commitTS) v := encodeValue(nil, true, 0, encStateCleartext) @@ -2109,10 +2188,13 @@ func (s *pebbleStore) ExpireAt(ctx context.Context, key []byte, expireAt uint64, // Must read latest value first to preserve it; use internal getAt to // avoid a recursive dbMu.RLock() while we already hold it. - val, err := s.getAt(ctx, key, commitTS) + val, err := s.getAt(ctx, key, commitTS, nil) if err != nil { return err } + if err := s.versionRetirement.validateWrite(key, val, commitTS); err != nil { + return err + } s.alignCommitTS(commitTS) // gateRegistration=true: ExpireAt is a direct (non-raft) write path @@ -2148,6 +2230,10 @@ func (s *pebbleStore) latestCommitTS(ctx context.Context, key []byte) (uint64, b } userKey, version := decodeKeyView(k) if bytes.Equal(userKey, key) { + retired, err := s.retiredIteratorEntry(ctx, iter) + if err != nil || retired { + return 0, false, err + } return version, true, nil } return 0, false, nil @@ -2238,7 +2324,7 @@ func (s *pebbleStore) latestCommitTSWithIter(ctx context.Context, iter *pebble.I if preferNext { ts, exists, decided, err := conflictTSFromCurrentIter(iter, key, linearAdvanceLimit) if err != nil || decided { - return ts, exists, err + return s.retainedConflictResult(ctx, iter, ts, exists, err) } } *seekKey = appendEncodedKey(*seekKey, key, math.MaxUint64) @@ -2246,7 +2332,7 @@ func (s *pebbleStore) latestCommitTSWithIter(ctx context.Context, iter *pebble.I if iter.SeekGEWithLimit(*seekKey, *upperBound) == pebble.IterValid && skipPebbleMetadataForward(iter) { userKey, version := decodeKeyView(iter.Key()) if bytes.Equal(userKey, key) { - return version, true, nil + return s.retainedConflictResult(ctx, iter, version, true, nil) } } if err := iter.Error(); err != nil { @@ -2383,6 +2469,9 @@ type encodedMutation struct { // leaves the batch untouched. A Raft entry scope relies on that: its batch // is shared by every request of the entry. func (s *pebbleStore) encodeMutationsForBatch(mutations []*KVPairMutation, commitTS uint64, gateRegistration bool) ([]encodedMutation, error) { + if err := s.versionRetirement.validateMutations(mutations, commitTS); err != nil { + return nil, err + } encoded := make([]encodedMutation, 0, len(mutations)) for _, mut := range mutations { k, err := encodePebbleUserVersionKey(mut.Key, commitTS) @@ -2670,6 +2759,9 @@ func (s *pebbleStore) applyMutationsWithOpts(ctx context.Context, mutations []*K if fastPathDone { return nil } + if err := s.versionRetirement.validateMutations(mutations, commitTS); err != nil { + return err + } watermark := s.LastCommitTS() if err := checkCommitTSFence(mutations, commitTS, watermark, fenceCommitTS); err != nil { return err @@ -2913,7 +3005,7 @@ func (s *pebbleStore) scanDeletePrefix(iter *pebble.Iterator, batch *pebble.Batc return err } if needsTombstone { - if err := setDeletePrefixTombstone(batch, userKey, commitTS, tombstoneVal); err != nil { + if err := s.stageRetainedPrefixTombstone(batch, userKey, commitTS, tombstoneVal); err != nil { return err } } @@ -2924,6 +3016,13 @@ func (s *pebbleStore) scanDeletePrefix(iter *pebble.Iterator, batch *pebble.Batc return nil } +func (s *pebbleStore) stageRetainedPrefixTombstone(batch *pebble.Batch, key []byte, ts uint64, encoded []byte) error { + if err := s.versionRetirement.validateWrite(key, nil, ts); err != nil { + return err + } + return setDeletePrefixTombstone(batch, key, ts, encoded) +} + func setDeletePrefixTombstone(batch *pebble.Batch, userKey []byte, commitTS uint64, tombstoneVal []byte) error { k, err := encodePebbleUserVersionKey(userKey, commitTS) if err != nil { @@ -2982,7 +3081,8 @@ func (s *pebbleStore) isVisibleLiveKey(iter *pebble.Iterator, userKey []byte, ve if sv.Tombstone || (sv.ExpireAt != 0 && sv.ExpireAt <= commitTS) { return false, nil } - return true, nil + retired, err := s.retiredIteratorEntry(context.Background(), iter) + return !retired, err } type pebbleCompactionStats struct { @@ -3272,7 +3372,7 @@ func readRestoreEntry(r io.Reader, keyBuf *[]byte) (kLen, vLen int, eof bool, er // plaintext but restore rejects the encrypted body with // ErrValueTooLarge. vLen, err = readRestoreFieldLen(r, "snapshot value", - maxSnapshotValueSize+valueHeaderSize+encryption.EnvelopeOverhead) + maxSnapshotValueSize+maxValueHeaderSize+encryption.EnvelopeOverhead) if err != nil { return 0, 0, false, err } @@ -3335,7 +3435,8 @@ func setEncodedVersionInBatch(batch *pebble.Batch, key []byte, version Versioned if err != nil { return err } - deferred := batch.SetDeferred(len(encodedKey), encodedValueLen(len(version.Value))) + headerSize := versionValueHeaderSize(version.adoptionEpoch) + deferred := batch.SetDeferred(len(encodedKey), headerSize+len(version.Value)) copy(deferred.Key, encodedKey) // MVCC snapshot format v2 does not carry encryption_state โ€” Stage 8 of // the encryption rollout (per docs/design/2026_04_29_proposed...) bumps @@ -3344,7 +3445,8 @@ func setEncodedVersionInBatch(batch *pebble.Batch, key []byte, version Versioned // snapshotting/restoring an encrypted dataset must use the native // Pebble snapshot path (snapshot_pebble.go), which ships raw bytes // and thus preserves the on-disk envelope verbatim. - fillEncodedValue(deferred.Value, version.Value, version.Tombstone, version.ExpireAt, encStateCleartext) + writeVersionHeaderBytes(deferred.Value, version.Tombstone, version.ExpireAt, encStateCleartext, version.adoptionEpoch) + copy(deferred.Value[headerSize:], version.Value) return errors.WithStack(deferred.Finish()) } @@ -3419,6 +3521,12 @@ func (s *pebbleStore) restoreSnapshot(r io.Reader, validate func(string) error) // observing a partially swapped or closed database handle. s.dbMu.Lock() defer s.dbMu.Unlock() + if s.db == nil && s.lifecycleLock == nil { + return errors.WithStack(pebble.ErrClosed) + } + if err := s.checkOwnedSnapshotPinsLocked(); err != nil { + return err + } s.mtx.Lock() defer s.mtx.Unlock() @@ -3475,14 +3583,8 @@ func (s *pebbleStore) handleRestorePeekError(err error, header []byte) error { } func (s *pebbleStore) reopenFreshDB() error { - if s.db != nil { - if err := s.db.Close(); err != nil { - return errors.WithStack(err) - } - if s.cache != nil { - s.cache.Unref() - s.cache = nil - } + if err := s.closeStoreDB(); err != nil { + return err } if err := os.RemoveAll(s.dir); err != nil { return errors.WithStack(err) @@ -3597,6 +3699,8 @@ func writeNativeSnapshotToTempDir(r io.Reader, tmpDir string, ts uint64, disable // place after the CRC32 checksum is verified, preserving the existing store // on failure. type streamingMVCCRestoreMetadata struct { + snapshotVersion uint32 + adoptionEpoch uint64 raftControl map[string][]byte controlAppliedIndex uint64 lastCommitTS uint64 @@ -3623,6 +3727,7 @@ func readStreamingMVCCRestoreHeader(r io.Reader) (io.Reader, hash.Hash32, uint32 return nil, nil, 0, streamingMVCCRestoreMetadata{}, err } meta := streamingMVCCRestoreMetadata{ + snapshotVersion: version, raftControl: snapshotMeta.raftControl, controlAppliedIndex: snapshotMeta.controlAppliedIndex, lastCommitTS: lastCommitTS, @@ -3635,6 +3740,10 @@ func readStreamingMVCCRestoreHeader(r io.Reader) (io.Reader, hash.Hash32, uint32 migrationOwnership: snapshotMeta.ownership, migrationPartitions: snapshotMeta.partitions, } + meta.adoptionEpoch, err = snapshotVersionAdoptionEpoch(version, meta.raftControl) + if err != nil { + return nil, nil, 0, streamingMVCCRestoreMetadata{}, err + } return body, hash, expectedChecksum, meta, nil } @@ -3658,7 +3767,7 @@ func writeStreamingMVCCRestoreTempDB(dir string, body io.Reader, hash hash.Hash3 _ = os.RemoveAll(tmpDir) } - if err := writeMVCCEntriesToDB(body, tmpDB); err != nil { + if err := writeMVCCEntriesToDB(body, tmpDB, meta.snapshotVersion, meta.adoptionEpoch); err != nil { cleanupTmp() return "", err } @@ -3695,10 +3804,10 @@ func (s *pebbleStore) restoreFromStreamingMVCC(r io.Reader, validate func(string // writeMVCCEntriesToDB reads MVCC snapshot entries from body and writes them // into the given Pebble database using batched commits. -func writeMVCCEntriesToDB(body io.Reader, db *pebble.DB) error { +func writeMVCCEntriesToDB(body io.Reader, db *pebble.DB, formatVersion uint32, adoptionCeiling uint64) error { batch := db.NewBatch() for { - key, versions, eof, err := readMVCCSnapshotEntry(body) + key, versions, eof, err := readMVCCSnapshotEntry(body, formatVersion, adoptionCeiling) if err != nil { _ = batch.Close() return err @@ -3734,16 +3843,11 @@ func (s *pebbleStore) swapInTempDBWithMetadata(tmpDir string, expected *pebbleSn _ = os.RemoveAll(tmpDir) return err } - if err := s.db.Close(); err != nil { + if err := s.closeStoreDB(); err != nil { _ = os.RemoveAll(tmpDir) _ = os.RemoveAll(backupDir) return errors.WithStack(err) } - if s.cache != nil { - s.cache.Unref() - s.cache = nil - } - s.db = nil if err := os.Rename(s.dir, backupDir); err != nil { _ = os.RemoveAll(tmpDir) _ = os.RemoveAll(backupDir) @@ -3760,7 +3864,7 @@ func (s *pebbleStore) swapInTempDBWithMetadata(tmpDir string, expected *pebbleSn if err != nil { return errors.Join(err, s.restoreSwapBackup(backupDir)) } - readinessStates, err := s.loadMigrationServingMetadata() + readinessStates, err := s.loadMigrationAndRetirementMetadata() if err != nil { return errors.Join(err, s.restoreSwapBackup(backupDir)) } @@ -3787,15 +3891,7 @@ func (s *pebbleStore) reopenStoreDB(dir string) error { } func (s *pebbleStore) restoreSwapBackup(backupDir string) error { - var cleanupErr error - if s.db != nil { - cleanupErr = s.db.Close() - s.db = nil - } - if s.cache != nil { - s.cache.Unref() - s.cache = nil - } + cleanupErr := s.closeStoreDB() removeErr := os.RemoveAll(s.dir) renameErr := os.Rename(backupDir, s.dir) if renameErr != nil { @@ -3830,7 +3926,25 @@ func (s *pebbleStore) Close() error { // before we close the database. Lock ordering: dbMu before mtx. s.dbMu.Lock() defer s.dbMu.Unlock() - err := s.db.Close() + if err := s.checkOwnedSnapshotPinsLocked(); err != nil { + return err + } + err := s.closeStoreDB() + if s.lifecycleLock != nil { + err = errors.Join(err, s.lifecycleLock.Close()) + s.lifecycleLock = nil + } + return err +} + +// Called before publication or with dbMu held exclusively. Restore may replace +// the DB several times while the store retains its lifecycle lock. +func (s *pebbleStore) closeStoreDB() error { + var err error + if s.db != nil { + err = s.db.Close() + s.db = nil + } // Release this store's borrowed block-cache reference after Pebble has // dropped its internal handle. The process base reference keeps the shared // cache alive for other stores; nil prevents a second Close from unrefing @@ -3860,11 +3974,9 @@ func (s *pebbleStore) BlockCacheCapacityBytes() int64 { // return value is a freshly allocated *pebble.Metrics owned by the // caller. // -// Returns nil only before the first Open has installed a DB or after a -// failed Open left s.db unset; callers during an in-flight Restore block -// on dbMu (which Restore holds exclusively) rather than observing nil, -// and Close() does not clear s.db. Callers must still handle nil for the -// pre-Open case. +// Returns nil before the first Open, after Close, or after a failed Open left +// s.db unset. Callers during an in-flight Restore block on dbMu (which Restore +// holds exclusively) rather than observing a partially replaced DB. // // Safe for concurrent use: takes the dbMu read lock to protect against // Restore swapping the DB pointer. diff --git a/store/lsm_store_applied_index_test.go b/store/lsm_store_applied_index_test.go index 458956d2f..be81ec287 100644 --- a/store/lsm_store_applied_index_test.go +++ b/store/lsm_store_applied_index_test.go @@ -490,14 +490,14 @@ func TestRaftApplyMetaWriteOptsSyncsAppliedIndex(t *testing.T) { } // TestSetDurableAppliedIndex_Monotonic guards the round-2 fix for -// codex P2: a background snapshot persist (which is what +// A background snapshot persist (which is what // SetDurableAppliedIndex services) MUST NOT rewind metaAppliedIndex // when a concurrent ApplyMutationsRaftAt has already advanced it // past the snapshot's index. // // The test mirrors the production race in single-threaded form: // 1. ApplyMutationsRaftAt(... appliedIndex=N+k) โ€” meta key = N+k -// 2. SetDurableAppliedIndex(N) โ€” must NO-OP (N < N+k) +// 2. SetDurableAppliedIndex(N) โ€” sync without lowering the value (N < N+k) // // After step 2, LastAppliedIndex must still report N+k. func TestSetDurableAppliedIndex_Monotonic(t *testing.T) { @@ -518,7 +518,7 @@ func TestSetDurableAppliedIndex_Monotonic(t *testing.T) { require.NoError(t, ps.ApplyMutationsRaftAt(ctx, muts, nil, 100, 100, applied)) // Step 2: background SetDurableAppliedIndex(snapIdx) โ€” the per-Apply - // path has already moved past, so this MUST no-op. + // path has already moved past, so the value must not be lowered. require.NoError(t, ps.SetDurableAppliedIndex(snapIdx)) got, present, err := ps.LastAppliedIndex() @@ -539,14 +539,14 @@ func TestSetDurableAppliedIndex_AdvancesOnlyForward(t *testing.T) { require.NoError(t, ps.SetDurableAppliedIndex(50)) require.NoError(t, ps.SetDurableAppliedIndex(100)) // strictly greater โ†’ advances - require.NoError(t, ps.SetDurableAppliedIndex(75)) // strictly less โ†’ no-op - require.NoError(t, ps.SetDurableAppliedIndex(100)) // equal โ†’ no-op + require.NoError(t, ps.SetDurableAppliedIndex(75)) // strictly less: sync the current value + require.NoError(t, ps.SetDurableAppliedIndex(100)) // equal: sync the current value got, present, err := ps.LastAppliedIndex() require.NoError(t, err) require.True(t, present) require.Equal(t, uint64(100), got, - "SetDurableAppliedIndex must advance strictly-greater values and no-op on equal/lesser") + "SetDurableAppliedIndex must never lower the current value") } // TestLastAppliedIndex_CorruptValue exercises the "len(val) < diff --git a/store/migration_cleanup.go b/store/migration_cleanup.go index 6d0d9f202..560f359a5 100644 --- a/store/migration_cleanup.go +++ b/store/migration_cleanup.go @@ -3,6 +3,7 @@ package store import ( "bytes" "context" + "math" "github.com/cockroachdb/errors" "github.com/cockroachdb/pebble/v2" @@ -19,9 +20,30 @@ func cleanupExportOptions(opts CleanupVersionsOptions) ExportVersionsOptions { MaxScannedBytes: opts.MaxScannedBytes, KeyFamily: opts.KeyFamily, AcceptVersion: opts.AcceptVersion, + includeRetired: true, } } +func (state versionRetirementState) cleanupExportOptions(opts CleanupVersionsOptions) (ExportVersionsOptions, error) { + export := cleanupExportOptions(opts) + if state.adoptionEpoch == 0 { + return export, nil + } + epoch := uint64(0) + if opts.Retirement != nil { + updated, record, err := prepareVersionRetirementEpoch(state, *opts.Retirement) + if err != nil { + return ExportVersionsOptions{}, err + } + if _, err := updated.append(record); err != nil { + return ExportVersionsOptions{}, err + } + epoch = record.Epoch + } + export.reclamation = &versionRetirementReclamation{epoch: epoch, current: state.adoptionEpoch} + return export, nil +} + func cleanupResult(exported ExportVersionsResult) CleanupVersionsResult { var deletedBytes uint64 for _, version := range exported.Versions { @@ -44,6 +66,10 @@ func (s *mvccStore) CleanupVersions(ctx context.Context, opts CleanupVersionsOpt s.mtx.Lock() defer s.applyMu.Unlock() defer s.mtx.Unlock() + return s.cleanupMemoryVersionsLocked(ctx, opts) +} + +func (s *mvccStore) cleanupMemoryVersionsLocked(ctx context.Context, opts CleanupVersionsOptions) (CleanupVersionsResult, error) { if _, retired := s.migrationRetired[opts.JobID]; retired { return CleanupVersionsResult{}, errors.WithStack(ErrMigrationRetired) } @@ -51,7 +77,11 @@ func (s *mvccStore) CleanupVersions(ctx context.Context, opts CleanupVersionsOpt return CleanupVersionsResult{Done: true}, nil } - exportOpts := normalizeExportVersionsOptions(cleanupExportOptions(opts)) + exportOpts, err := s.versionRetirement.cleanupExportOptions(opts) + if err != nil { + return CleanupVersionsResult{}, err + } + exportOpts = normalizeExportVersionsOptions(exportOpts) pos, err := decodeExportCursorForOptions(exportOpts) if err != nil { return CleanupVersionsResult{}, err @@ -66,6 +96,58 @@ func (s *mvccStore) CleanupVersions(ctx context.Context, opts CleanupVersionsOpt return cleanupResult(exported), nil } +// StageRaftEntryMigrationCleanup removes a bounded page in the caller's data +// scope. The caller stages progress and authorizes the complete range first. +func StageRaftEntryMigrationCleanup(ctx context.Context, opts CleanupVersionsOptions) (CleanupVersionsResult, error) { + if sc, _ := ctx.Value(raftEntryScopeKey{}).(*raftEntryScope); sc != nil { + return sc.stageMigrationCleanup(ctx, opts) + } + if sc, _ := ctx.Value(memoryEntryKey{}).(*memoryRaftEntry); sc != nil { + if err := sc.allowData(); err != nil { + return CleanupVersionsResult{}, err + } + if err := sc.owner.memoryEntryIndex(ctx, opts.AppliedIndex); err != nil { + return CleanupVersionsResult{}, err + } + return sc.staged.cleanupMemoryVersionsLocked(ctx, opts) + } + return CleanupVersionsResult{}, errors.WithStack(ErrRaftControlScopeRequired) +} + +func (sc *raftEntryScope) stageMigrationCleanup(ctx context.Context, opts CleanupVersionsOptions) (CleanupVersionsResult, error) { + if err := sc.checkDataIndex(opts.AppliedIndex); err != nil { + return CleanupVersionsResult{}, err + } + s := sc.store + s.dbMu.RLock() + defer s.dbMu.RUnlock() + if s.db != sc.db { + return CleanupVersionsResult{}, sc.fail(errors.WithStack(ErrRaftEntryStoreSwapped)) + } + if err := s.checkMigrationNotRetiredLocked(opts.JobID); err != nil { + return CleanupVersionsResult{}, err + } + if opts.MaxVersions <= 0 { + return CleanupVersionsResult{Done: true}, nil + } + exportOpts, err := s.versionRetirementFor(ctx).cleanupExportOptions(opts) + if err != nil { + return CleanupVersionsResult{}, err + } + // Physical cleanup scans whatever remains. MaxCommitTS is a selection + // bound, not a historical read that requires complete retained history. + exportOpts.ReadTS = math.MaxUint64 + exported, err := s.exportVersionsFromLocked(ctx, sc.batch, exportOpts, true) + if err != nil { + return CleanupVersionsResult{}, err + } + if err := stageCleanupVersionDeletes(sc.batch, exported.Versions); err != nil { + return CleanupVersionsResult{}, sc.fail(err) + } + sc.touched = true + return cleanupResult(exported), nil +} + func (s *mvccStore) ClearMigrationState(ctx context.Context, jobID, _ uint64) error { if err := s.rejectMemoryEntry(ctx); err != nil { return err @@ -119,7 +201,11 @@ func (s *pebbleStore) CleanupVersions(ctx context.Context, opts CleanupVersionsO return CleanupVersionsResult{Done: true}, nil } - exported, err := s.exportVersionsLocked(ctx, cleanupExportOptions(opts)) + exportOpts, err := s.versionRetirement.cleanupExportOptions(opts) + if err != nil { + return CleanupVersionsResult{}, err + } + exported, err := s.exportVersionsLocked(ctx, exportOpts) if err != nil { return CleanupVersionsResult{}, err } @@ -128,10 +214,8 @@ func (s *pebbleStore) CleanupVersions(ctx context.Context, opts CleanupVersionsO if err := s.stageOnlineMaintenanceGuard(batch, opts.OnlineGuard, exported.Versions); err != nil { return CleanupVersionsResult{}, err } - for _, version := range exported.Versions { - if err := batch.Delete(encodeKey(version.Key, version.CommitTS), nil); err != nil { - return CleanupVersionsResult{}, errors.WithStack(err) - } + if err := stageCleanupVersionDeletes(batch, exported.Versions); err != nil { + return CleanupVersionsResult{}, err } if opts.AppliedIndex > 0 { if err := setPebbleUint64InBatch(batch, metaAppliedIndexBytes, opts.AppliedIndex); err != nil { @@ -144,6 +228,15 @@ func (s *pebbleStore) CleanupVersions(ctx context.Context, opts CleanupVersionsO return cleanupResult(exported), nil } +func stageCleanupVersionDeletes(batch *pebble.Batch, versions []MVCCVersion) error { + for _, version := range versions { + if err := batch.Delete(encodeKey(version.Key, version.CommitTS), nil); err != nil { + return errors.WithStack(err) + } + } + return nil +} + func (s *pebbleStore) ClearMigrationState(_ context.Context, jobID, appliedIndex uint64) error { if jobID == 0 { return errors.New("migration cleanup job id is required") diff --git a/store/migration_cleanup_test.go b/store/migration_cleanup_test.go new file mode 100644 index 000000000..5e030982b --- /dev/null +++ b/store/migration_cleanup_test.go @@ -0,0 +1,44 @@ +package store + +import ( + "context" + "testing" + + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func TestStageRaftEntryMigrationCleanupRollsBackWithProgress(t *testing.T) { + t.Parallel() + ctx := t.Context() + st, err := NewPebbleStore(t.TempDir()) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, st.Close()) }) + pebble, ok := st.(*pebbleStore) + require.True(t, ok) + key := []byte("a") + require.NoError(t, pebble.PutAt(ctx, key, []byte("live"), 10, 0)) + require.NoError(t, pebble.SetDurableAppliedIndex(1)) + injected := errors.New("abort cleanup entry after staging") + err = pebble.ApplyRaftEntry(ctx, 2, func(ctx context.Context) error { + replayed, err := StageRaftEntryProgress(ctx, 2) + require.NoError(t, err) + require.False(t, replayed) + result, err := StageRaftEntryMigrationCleanup(ctx, CleanupVersionsOptions{ + JobID: 7, AppliedIndex: 2, StartKey: key, EndKey: []byte("b"), MaxVersions: 1, + }) + require.NoError(t, err) + require.Equal(t, uint64(1), result.DeletedRows) + _, err = RaftEntryLatestRecord(ctx, key) + require.ErrorIs(t, err, ErrKeyNotFound) + return injected + }) + require.ErrorIs(t, err, injected) + index, present, err := pebble.LastAppliedIndex() + require.NoError(t, err) + require.True(t, present) + require.Equal(t, uint64(1), index) + row, err := pebble.GetVersionAt(ctx, key, 20) + require.NoError(t, err) + require.Equal(t, VersionedValue{TS: 10, Value: []byte("live")}, row) +} diff --git a/store/migration_ownership_partition_store.go b/store/migration_ownership_partition_store.go index c045a1028..0951acf9e 100644 --- a/store/migration_ownership_partition_store.go +++ b/store/migration_ownership_partition_store.go @@ -57,7 +57,7 @@ func (s *mvccStore) partitionConfigurationLocked() (uint64, error) { } func (s *pebbleStore) partitionConfigurationLocked(ctx context.Context) (uint64, error) { - return partitionConfiguration(s.getAt(ctx, MigrationConfigurationIndexKey(), ^uint64(0))) + return partitionConfiguration(s.getAt(ctx, MigrationConfigurationIndexKey(), ^uint64(0), nil)) } func (s *mvccStore) syncPartitionJobLocked(updated []MigrationOwnershipState, requested MigrationOwnershipState, operation MigrationOwnershipOperation, index uint64) (MigrationOwnershipPartitionState, error) { diff --git a/store/migration_promote.go b/store/migration_promote.go index ac8027198..7988c4c5e 100644 --- a/store/migration_promote.go +++ b/store/migration_promote.go @@ -19,6 +19,14 @@ type promotedVersion struct { target MVCCVersion } +type migrationPromotionPlan struct { + exported ExportVersionsResult + versions []promotedVersion + writes []MVCCVersion + result PromoteVersionsResult + epoch uint64 +} + func validatePromoteVersionsOptions(opts PromoteVersionsOptions) error { if opts.TargetKey == nil { return errors.New("migration promote target key mapper is required") @@ -74,17 +82,29 @@ func (s *mvccStore) PromoteVersions(ctx context.Context, opts PromoteVersionsOpt if opts.MaxVersions <= 0 { return PromoteVersionsResult{Done: true}, nil } + return s.promoteMemoryVersionsLocked(ctx, opts) +} +func (s *mvccStore) promoteMemoryVersionsLocked(ctx context.Context, opts PromoteVersionsOptions) (PromoteVersionsResult, error) { state, cursor := s.promotionStateAndCursorLocked(opts) + if s.versionRetirement.promotionReplayed(opts.AppliedIndex, s.controlAppliedIndex) { + return replayedPromotionResult(state), nil + } if opts.JobID != 0 && state.Done { + epoch, err := s.versionRetirement.promotionEpoch(opts.AppliedIndex) + if err != nil { + return PromoteVersionsResult{}, err + } + s.publishMemoryPromotionEpoch(epoch, opts.AppliedIndex) return PromoteVersionsResult{Done: true, TotalPromotedRows: state.PromotedRows, MaxPromotedTS: state.MaxPromotedTS}, nil } - exported, toPromote, promoted, err := s.planMemoryPromotionLocked(ctx, opts, cursor) + plan, err := s.planMemoryPromotionLocked(ctx, opts, cursor) if err != nil { return PromoteVersionsResult{}, err } - s.applyMemoryPromotionLocked(toPromote) - result, updatedState := finishPromotionResult(opts, state, exported, promoted) + s.applyMemoryPromotionLocked(plan.versions, plan.writes) + s.publishMemoryPromotionEpoch(plan.epoch, opts.AppliedIndex) + result, updatedState := finishPromotionResult(opts, state, plan.exported, plan.result) if result.MaxPromotedTS > s.lastCommitTS { s.lastCommitTS = result.MaxPromotedTS } @@ -94,11 +114,21 @@ func (s *mvccStore) PromoteVersions(ctx context.Context, opts PromoteVersionsOpt return result, nil } +func (s *mvccStore) publishMemoryPromotionEpoch(epoch, index uint64) { + if epoch > s.versionRetirement.adoptionEpoch { + s.raftControl[versionAdoptionMetadataKey] = encodeVersionAdoptionEpoch(epoch) + s.versionRetirement.adoptionEpoch = epoch + } + if epoch != 0 && index > s.controlAppliedIndex { + s.controlAppliedIndex = index + } +} + func (s *mvccStore) planMemoryPromotionLocked( ctx context.Context, opts PromoteVersionsOptions, cursor []byte, -) (ExportVersionsResult, []promotedVersion, PromoteVersionsResult, error) { +) (migrationPromotionPlan, error) { exportOpts := normalizeExportVersionsOptions(ExportVersionsOptions{ StartKey: opts.StartKey, EndKey: opts.EndKey, @@ -109,23 +139,28 @@ func (s *mvccStore) planMemoryPromotionLocked( }) pos, err := decodeExportCursorForOptions(exportOpts) if err != nil { - return ExportVersionsResult{}, nil, PromoteVersionsResult{}, err + return migrationPromotionPlan{}, err } exported, err := s.exportVersionsLocked(ctx, exportOpts, pos) if err != nil { - return ExportVersionsResult{}, nil, PromoteVersionsResult{}, err + return migrationPromotionPlan{}, err } toPromote, promoted, err := promotedVersionsFromStaged(opts, exported.Versions) - return exported, toPromote, promoted, err + if err != nil { + return migrationPromotionPlan{}, err + } + lookup := s.lookupMigrationHead + if opts.AppliedIndex == 0 { + lookup = s.lookupMigrationVersion + } + return s.versionRetirement.planPromotionWrites(opts, exported, toPromote, promoted, lookup) } -func (s *mvccStore) applyMemoryPromotionLocked(toPromote []promotedVersion) { +func (s *mvccStore) applyMemoryPromotionLocked(toPromote []promotedVersion, writes []MVCCVersion) { + for _, version := range writes { + s.putMigratedVersionLocked(version) + } for _, version := range toPromote { - if version.target.Tombstone { - s.deleteVersionLocked(version.target.Key, version.target.CommitTS) - } else { - s.putVersionLocked(version.target.Key, version.target.Value, version.target.CommitTS, version.target.ExpireAt) - } s.removeVersionLocked(version.staged.Key, version.staged.CommitTS) } } @@ -181,8 +216,8 @@ func findVersionIndex(versions []VersionedValue, commitTS uint64) int { func (s *pebbleStore) PromoteVersions(ctx context.Context, opts PromoteVersionsOptions) (PromoteVersionsResult, error) { s.applyMu.Lock() defer s.applyMu.Unlock() - s.dbMu.RLock() - defer s.dbMu.RUnlock() + unlock := s.lockPromotionRetirement() + defer unlock() if err := s.checkMigrationNotRetiredLocked(opts.JobID); err != nil { return PromoteVersionsResult{}, err } @@ -197,29 +232,58 @@ func (s *pebbleStore) PromoteVersions(ctx context.Context, opts PromoteVersionsO if err != nil { return PromoteVersionsResult{}, err } + replayed, err := s.pebblePromotionReplayed(opts.AppliedIndex) + if err != nil { + return PromoteVersionsResult{}, err + } + if replayed { + return replayedPromotionResult(state), nil + } writeOpts := s.promotionWriteOpts(opts.AppliedIndex) if opts.JobID != 0 && state.Done { - result := PromoteVersionsResult{Done: true, TotalPromotedRows: state.PromotedRows, MaxPromotedTS: state.MaxPromotedTS} - return s.finishPebblePromotion(opts.OnlineGuard, nil, opts.JobID, nil, result, opts.AppliedIndex, state.MaxPromotedTS, writeOpts) + return s.finishCompletedPebblePromotion(opts, state, writeOpts) } opts.Cursor = cursor - exported, toPromote, promoted, err := s.planPebblePromotionLocked(ctx, opts) + plan, err := s.planPebblePromotionLocked(ctx, opts) if err != nil { return PromoteVersionsResult{}, err } - result, stateToWrite := finishPromotionResult(opts, state, exported, promoted) + result, stateToWrite := finishPromotionResult(opts, state, plan.exported, plan.result) return s.finishPebblePromotion( opts.OnlineGuard, - toPromote, + plan.versions, + plan.writes, opts.JobID, stateToWrite, result, opts.AppliedIndex, result.MaxPromotedTS, writeOpts, + plan.epoch, ) } +func (s *pebbleStore) finishCompletedPebblePromotion(opts PromoteVersionsOptions, state PromotionState, writeOpts *pebble.WriteOptions) (PromoteVersionsResult, error) { + result := replayedPromotionResult(state) + epoch, err := s.versionRetirement.promotionEpoch(opts.AppliedIndex) + if err != nil { + return PromoteVersionsResult{}, err + } + return s.finishPebblePromotion(opts.OnlineGuard, nil, nil, opts.JobID, nil, result, opts.AppliedIndex, state.MaxPromotedTS, writeOpts, epoch) +} + +func (state versionRetirementState) promotionReplayed(index, persisted uint64) bool { + return state.adoptionEpoch != 0 && index != 0 && index <= persisted +} + +func (s *pebbleStore) pebblePromotionReplayed(index uint64) (bool, error) { + if s.versionRetirement.adoptionEpoch == 0 || index == 0 { + return false, nil + } + persisted, present, err := s.readAppliedIndexLocked() + return present && index <= persisted, err +} + func (s *pebbleStore) promotionWriteOpts(appliedIndex uint64) *pebble.WriteOptions { if appliedIndex > 0 { return s.raftApplyWriteOpts() @@ -230,12 +294,14 @@ func (s *pebbleStore) promotionWriteOpts(appliedIndex uint64) *pebble.WriteOptio func (s *pebbleStore) finishPebblePromotion( guard *OnlineMaintenanceGuard, toPromote []promotedVersion, + targets []MVCCVersion, jobID uint64, stateToWrite *PromotionState, result PromoteVersionsResult, appliedIndex uint64, maxPromotedTS uint64, writeOpts *pebble.WriteOptions, + adoptionEpoch uint64, ) (PromoteVersionsResult, error) { if len(toPromote) == 0 && stateToWrite == nil && appliedIndex == 0 && maxPromotedTS == 0 { return result, nil @@ -243,11 +309,13 @@ func (s *pebbleStore) finishPebblePromotion( if err := s.commitPebblePromoteVersions( guard, toPromote, + targets, jobID, stateToWrite, appliedIndex, maxPromotedTS, writeOpts, + adoptionEpoch, ); err != nil { return PromoteVersionsResult{}, err } @@ -257,7 +325,7 @@ func (s *pebbleStore) finishPebblePromotion( func (s *pebbleStore) planPebblePromotionLocked( ctx context.Context, opts PromoteVersionsOptions, -) (ExportVersionsResult, []promotedVersion, PromoteVersionsResult, error) { +) (migrationPromotionPlan, error) { exported, err := s.exportVersionsLocked(ctx, ExportVersionsOptions{ StartKey: opts.StartKey, EndKey: opts.EndKey, @@ -267,10 +335,17 @@ func (s *pebbleStore) planPebblePromotionLocked( MaxScannedBytes: opts.MaxScannedBytes, }) if err != nil { - return ExportVersionsResult{}, nil, PromoteVersionsResult{}, err + return migrationPromotionPlan{}, err } toPromote, promoted, err := promotedVersionsFromStaged(opts, exported.Versions) - return exported, toPromote, promoted, err + if err != nil { + return migrationPromotionPlan{}, err + } + lookup := s.lookupMigrationHead + if opts.AppliedIndex == 0 { + lookup = s.lookupMigrationVersion + } + return s.versionRetirement.planPromotionWrites(opts, exported, toPromote, promoted, lookup) } func finishPromotionResult( @@ -355,18 +430,16 @@ func (s *pebbleStore) stagePebblePromotionState(batch *pebble.Batch, jobID uint6 func (s *pebbleStore) commitPebblePromoteVersions( guard *OnlineMaintenanceGuard, versions []promotedVersion, + targets []MVCCVersion, jobID uint64, state *PromotionState, appliedIndex uint64, maxPromotedTS uint64, writeOpts *pebble.WriteOptions, + adoptionEpoch uint64, ) error { batch := s.db.NewBatch() defer batch.Close() - targets := make([]MVCCVersion, 0, len(versions)) - for _, version := range versions { - targets = append(targets, version.target) - } if err := s.stageOnlineMaintenanceGuard(batch, guard, targets); err != nil { return err } @@ -380,17 +453,50 @@ func (s *pebbleStore) commitPebblePromoteVersions( return errors.WithStack(err) } } + if err := s.stagePromotionMetadata(batch, jobID, appliedIndex, adoptionEpoch, state); err != nil { + return err + } + writeOpts = s.promotionEpochWriteOpts(writeOpts, adoptionEpoch) + if err := s.commitPebblePromotionBatch(batch, maxPromotedTS, writeOpts); err != nil { + return err + } + if adoptionEpoch > s.versionRetirement.adoptionEpoch { + s.versionRetirement.adoptionEpoch = adoptionEpoch + } + return nil +} + +func (s *pebbleStore) stagePromotionMetadata(batch *pebble.Batch, jobID, index, epoch uint64, state *PromotionState) error { if state != nil { if err := s.stagePebblePromotionState(batch, jobID, *state); err != nil { return err } } - if appliedIndex > 0 { - if err := setPebbleUint64InBatch(batch, metaAppliedIndexBytes, appliedIndex); err != nil { - return err - } + if err := stagePebbleAppliedIndex(batch, index); err != nil { + return err + } + if epoch > s.versionRetirement.adoptionEpoch { + return s.stageVersionAdoptionEpochBatch(batch, epoch) + } + return nil +} + +func (s *pebbleStore) promotionEpochWriteOpts(opts *pebble.WriteOptions, epoch uint64) *pebble.WriteOptions { + if epoch > s.versionRetirement.adoptionEpoch { + return pebble.Sync + } + return opts +} + +func promotionWrites(versions []promotedVersion, allowLegacyOverwrite bool, lookup migrationVersionLookup) ([]MVCCVersion, error) { + targets := make([]MVCCVersion, 0, len(versions)) + for _, version := range versions { + targets = append(targets, version.target) + } + if allowLegacyOverwrite { + return targets, nil } - return s.commitPebblePromotionBatch(batch, maxPromotedTS, writeOpts) + return immutableMigrationWrites(targets, nil, lookup) } func (s *pebbleStore) commitPebblePromotionBatch( diff --git a/store/migration_version_identity.go b/store/migration_version_identity.go new file mode 100644 index 000000000..05893ca4f --- /dev/null +++ b/store/migration_version_identity.go @@ -0,0 +1,151 @@ +package store + +import ( + "bytes" + "math" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2" +) + +// ErrMigrationVersionConflict reports an attempt to assign different contents +// to an existing MVCC version. Expired versions and tombstones retain their +// identity, so this check does not use the public visibility rules. +var ErrMigrationVersionConflict = errors.New("migration MVCC version has different contents") + +type migrationVersionLookup func([]byte, uint64) (VersionedValue, bool, error) + +type migrationVersionID struct { + key string + ts uint64 +} + +func immutableMigrationWrites( + versions []MVCCVersion, + logicalKey func([]byte) []byte, + lookup migrationVersionLookup, +) ([]MVCCVersion, error) { + seen := make(map[migrationVersionID]MVCCVersion, len(versions)) + writes := make([]MVCCVersion, 0, len(versions)) + for _, version := range versions { + key := version.Key + if logicalKey != nil { + key = logicalKey(key) + } + id := migrationVersionID{key: string(key), ts: version.CommitTS} + if previous, ok := seen[id]; ok { + if !sameMigrationVersion(version, previous.Value, previous.ExpireAt, previous.Tombstone) { + return nil, migrationVersionConflict(version) + } + if bytes.Equal(previous.Key, version.Key) { + continue + } + } + seen[id] = version + if !bytes.Equal(key, version.Key) { + if _, err := checkMigrationVersion(lookup, key, version); err != nil { + return nil, err + } + } + present, err := checkMigrationVersion(lookup, version.Key, version) + if err != nil { + return nil, err + } + if !present { + writes = append(writes, version) + } + } + return writes, nil +} + +func checkMigrationVersion(lookup migrationVersionLookup, key []byte, version MVCCVersion) (bool, error) { + existing, present, err := lookup(key, version.CommitTS) + if err != nil || !present { + return false, err + } + if !sameMigrationVersion(version, existing.Value, existing.ExpireAt, existing.Tombstone) { + return false, migrationVersionConflict(version) + } + return true, nil +} + +func sameMigrationVersion(version MVCCVersion, value []byte, expireAt uint64, tombstone bool) bool { + return version.Tombstone == tombstone && version.ExpireAt == expireAt && bytes.Equal(version.Value, value) +} + +func migrationVersionConflict(version MVCCVersion) error { + return errors.Wrapf(ErrMigrationVersionConflict, "key %q, commit timestamp %d", version.Key, version.CommitTS) +} + +func (s *mvccStore) lookupMigrationVersion(key []byte, ts uint64) (VersionedValue, bool, error) { + existing, _ := s.entryTreeGet(key) + versions, _ := existing.([]VersionedValue) + i := findVersionIndex(versions, ts) + if i < 0 { + return VersionedValue{}, false, nil + } + return versions[i], true, nil +} + +// Local compaction can prune different historical versions on different +// voters. Only heads survive on every replica and can satisfy exact CAS. +// Raft conflict verdicts must therefore use heads (plus the batch itself). +// Direct store calls may enforce identity on all retained versions. +func (s *mvccStore) lookupMigrationHead(key []byte, ts uint64) (VersionedValue, bool, error) { + head, ok := s.latestVersionLocked(key) + return head, ok && head.TS == ts, nil +} + +func (s *pebbleStore) lookupMigrationHead(key []byte, ts uint64) (VersionedValue, bool, error) { + iter, err := s.db.NewIter(&pebble.IterOptions{ + LowerBound: encodeKey(key, math.MaxUint64), + UpperBound: keyUpperBound(key), + }) + if err != nil { + return VersionedValue{}, false, errors.WithStack(err) + } + defer iter.Close() + if !iter.First() || !skipPebbleMetadataForward(iter) { + return VersionedValue{}, false, errors.WithStack(iter.Error()) + } + physical := iter.Key() + userKey, latest := decodeKeyView(physical) + if latest != ts || !bytes.Equal(userKey, key) { + return VersionedValue{}, false, nil + } + data, err := iter.ValueAndErr() + if err != nil { + return VersionedValue{}, false, errors.WithStack(err) + } + record, err := s.decodeMigrationVersion(physical, ts, data) + return record, err == nil, err +} + +func (s *pebbleStore) lookupMigrationVersion(key []byte, ts uint64) (VersionedValue, bool, error) { + physical, err := encodePebbleUserVersionKey(key, ts) + if err != nil { + return VersionedValue{}, false, err + } + data, closer, err := s.db.Get(physical) + if errors.Is(err, pebble.ErrNotFound) { + return VersionedValue{}, false, nil + } + if err != nil { + return VersionedValue{}, false, errors.WithStack(err) + } + record, err := s.decodeMigrationVersion(physical, ts, data) + err = errors.Join(err, errors.WithStack(closer.Close())) + return record, err == nil, err +} + +func (s *pebbleStore) decodeMigrationVersion(physical []byte, ts uint64, data []byte) (VersionedValue, error) { + value, err := decodeValueView(data) + if err != nil { + return VersionedValue{}, err + } + plain, err := s.decryptForKey(physical, value, value.Value) + if err != nil { + return VersionedValue{}, err + } + return VersionedValue{Value: bytes.Clone(plain), TS: ts, ExpireAt: value.ExpireAt, Tombstone: value.Tombstone, adoptionEpoch: value.AdoptionEpoch}, nil +} diff --git a/store/migration_version_identity_test.go b/store/migration_version_identity_test.go new file mode 100644 index 000000000..781f961d9 --- /dev/null +++ b/store/migration_version_identity_test.go @@ -0,0 +1,154 @@ +package store + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMigrationVersionIdentityImportIsAtomic(t *testing.T) { + t.Parallel() + runMigrationStoreSuite(t, func(t *testing.T, st MVCCStore) { + ctx := context.Background() + key := []byte("staged") + original := MVCCVersion{Key: key, CommitTS: 10, Value: []byte("observed"), ExpireAt: 20} + opts := ImportVersionsOptions{JobID: 1, BracketID: 1, BatchSeq: 1, Versions: []MVCCVersion{original}} + _, err := st.ImportVersions(ctx, opts) + require.NoError(t, err) + + opts.BatchSeq++ + opts.Cursor = []byte("batch-2") + newRow := MVCCVersion{Key: []byte("unrelated"), CommitTS: 40, Value: []byte("new")} + for _, replacement := range []MVCCVersion{ + {Key: key, CommitTS: 10, Value: []byte("different"), ExpireAt: 20}, + {Key: key, CommitTS: 10, Value: original.Value, ExpireAt: 21}, + {Key: key, CommitTS: 10, Tombstone: true}, + } { + opts.Versions = []MVCCVersion{newRow, replacement} + _, err := st.ImportVersions(ctx, opts) + require.ErrorIs(t, err, ErrMigrationVersionConflict) + require.Equal(t, uint64(10), st.LastCommitTS()) + floor, err := st.MigrationHLCFloor(ctx, opts.JobID) + require.NoError(t, err) + require.Equal(t, uint64(10), floor) + } + + // A conflicting pair for a new physical key is also an overwrite. + opts.Versions = []MVCCVersion{newRow, {Key: newRow.Key, CommitTS: newRow.CommitTS, Tombstone: true}} + _, err = st.ImportVersions(ctx, opts) + require.ErrorIs(t, err, ErrMigrationVersionConflict) + _, err = st.GetAt(ctx, newRow.Key, newRow.CommitTS) + require.ErrorIs(t, err, ErrKeyNotFound) + + // The rejected batch did not advance the acknowledgement. + opts.Versions = []MVCCVersion{original, original, newRow} + result, err := st.ImportVersions(ctx, opts) + require.NoError(t, err) + require.False(t, result.Duplicate) + require.Equal(t, opts.Cursor, result.AckedCursor) + result, err = st.ImportVersions(ctx, opts) + require.NoError(t, err) + require.True(t, result.Duplicate) + + // A retry of an acknowledged sequence cannot replace a version. + opts.Versions = []MVCCVersion{{Key: key, CommitTS: 10, Tombstone: true}} + result, err = st.ImportVersions(ctx, opts) + require.NoError(t, err) + require.True(t, result.Duplicate) + got, err := st.GetAt(ctx, key, 10) + require.NoError(t, err) + require.Equal(t, original.Value, got) + }) +} + +func TestMigrationVersionIdentityRaftVerdictIgnoresPrunedHistory(t *testing.T) { + t.Parallel() + forEachMVCCStore(t, func(t *testing.T, newStore func(*testing.T) MVCCStore) { + ctx := context.Background() + key := []byte("staged") + old := MVCCVersion{Key: key, CommitTS: 10, Value: []byte("previous")} + head := MVCCVersion{Key: key, CommitTS: 20, Value: []byte("current")} + for _, prune := range []bool{false, true} { + st := newStore(t) + opts := ImportVersionsOptions{JobID: 1, BracketID: 1, BatchSeq: 1, Versions: []MVCCVersion{old, head}} + _, err := st.ImportVersionsRaft(ctx, opts) + require.NoError(t, err) + if prune { + require.NoError(t, st.Compact(ctx, 20)) + found, err := st.CommittedVersionAt(ctx, key, 10) + require.NoError(t, err) + require.False(t, found) + } + + opts.BatchSeq++ + opts.Versions = []MVCCVersion{{Key: key, CommitTS: 10, Value: []byte("historical import")}} + _, err = st.ImportVersionsRaft(ctx, opts) + require.NoError(t, err) + + opts.BatchSeq++ + opts.Versions = []MVCCVersion{{Key: key, CommitTS: 20, Tombstone: true}} + _, err = st.ImportVersionsRaft(ctx, opts) + require.ErrorIs(t, err, ErrMigrationVersionConflict) + got, err := st.GetAt(ctx, key, 20) + require.NoError(t, err) + require.Equal(t, head.Value, got) + } + }) +} + +func TestMigrationVersionIdentityIdenticalEncryptedImport(t *testing.T) { + t.Parallel() + ctx := context.Background() + st := newEncryptedStoreFixture(t, 1).mvcc + key := []byte("staged") + value := []byte("plaintext") + version := MVCCVersion{Key: key, CommitTS: 10, Value: value, ExpireAt: 20} + opts := ImportVersionsOptions{JobID: 1, BracketID: 1, BatchSeq: 1, Versions: []MVCCVersion{version}} + _, err := st.ImportVersionsRaft(ctx, opts) + require.NoError(t, err) + opts.BatchSeq++ + result, err := st.ImportVersionsRaft(ctx, opts) + require.NoError(t, err) + require.False(t, result.Duplicate) + + opts.BatchSeq++ + opts.Versions = []MVCCVersion{{Key: key, CommitTS: 10, Value: value, ExpireAt: 19}} + _, err = st.ImportVersionsRaft(ctx, opts) + require.ErrorIs(t, err, ErrMigrationVersionConflict) + got, err := st.GetAt(ctx, key, 19) + require.NoError(t, err) + require.Equal(t, value, got) +} + +func TestMigrationVersionIdentityPromotionConflictIsAtomic(t *testing.T) { + t.Parallel() + runMigrationStoreSuite(t, func(t *testing.T, st MVCCStore) { + ctx := context.Background() + live := []byte("b") + stagedPrefix := []byte("stage/") + firstStaged := []byte("stage/a") + conflictingStaged := []byte("stage/b") + // An empty live value and a tombstone are distinct immutable records. + require.NoError(t, st.PutAt(ctx, live, []byte{}, 10, 0)) + require.NoError(t, st.PutAt(ctx, firstStaged, []byte("first"), 10, 0)) + require.NoError(t, st.DeleteAt(ctx, conflictingStaged, 10)) + promoter, ok := st.(MigrationPromoter) + require.True(t, ok) + _, err := promoter.PromoteVersions(ctx, PromoteVersionsOptions{ + JobID: 1, AppliedIndex: 1, StartKey: stagedPrefix, EndKey: PrefixScanEnd(stagedPrefix), MaxVersions: 16, + TargetKey: func(key []byte) ([]byte, bool) { return key[len(stagedPrefix):], true }, + }) + require.ErrorIs(t, err, ErrMigrationVersionConflict) + _, err = st.GetAt(ctx, live, 10) + require.NoError(t, err) + _, err = st.GetAt(ctx, []byte("a"), 10) + require.ErrorIs(t, err, ErrKeyNotFound) + got, err := st.GetAt(ctx, firstStaged, 10) + require.NoError(t, err) + require.Equal(t, []byte("first"), got) + found, err := st.CommittedVersionAt(ctx, conflictingStaged, 10) + require.NoError(t, err) + require.True(t, found) + }) +} diff --git a/store/migration_versions.go b/store/migration_versions.go index d8e6e2bc1..5cc76575d 100644 --- a/store/migration_versions.go +++ b/store/migration_versions.go @@ -471,6 +471,9 @@ func (s *mvccStore) ExportVersions(ctx context.Context, opts ExportVersionsOptio } func (s *mvccStore) exportVersionsLocked(ctx context.Context, opts ExportVersionsOptions, pos exportCursorPosition) (ExportVersionsResult, error) { + if !opts.includeRetired { + opts.retirement = &s.versionRetirement + } result := newExportVersionsResult(opts.MaxVersions) it := s.entryTreeIterator() if !s.seekMemoryExportStart(&it, opts.StartKey, pos) { @@ -612,12 +615,13 @@ func appendMemoryExportVersion( return exportCursorTagScanned, true } result.Versions = append(result.Versions, MVCCVersion{ - Key: bytes.Clone(key), - CommitTS: version.TS, - Tombstone: version.Tombstone, - Value: bytes.Clone(version.Value), - KeyFamily: opts.KeyFamily, - ExpireAt: version.ExpireAt, + Key: bytes.Clone(key), + CommitTS: version.TS, + Tombstone: version.Tombstone, + Value: bytes.Clone(version.Value), + KeyFamily: opts.KeyFamily, + ExpireAt: version.ExpireAt, + adoptionEpoch: version.adoptionEpoch, }) result.ExportedBytes += versionExportSize(key, len(version.Value)) result.AcceptedRows++ @@ -650,15 +654,31 @@ func exportMemoryVersion( key []byte, version VersionedValue, result *ExportVersionsResult, -) (bool, bool) { +) (bool, bool, error) { if shouldSkipMemoryVersion(cursorCommitTS, version) { - return true, false + return true, false, nil + } + retained, err := opts.reclamation.retain(version.adoptionEpoch) + if err != nil { + return false, false, err + } + if retained { + return finishMemoryExportPosition(opts, key, version, exportCursorTagScanned, result), false, nil + } + if opts.retirement != nil { + retired, err := opts.retirement.retired(key, version.Value, version.TS, version.adoptionEpoch) + if err != nil { + return false, false, err + } + if retired { + return finishMemoryExportPosition(opts, key, version, exportCursorTagScanned, result), false, nil + } } tag, deferred := appendMemoryExportVersion(opts, key, version, result) if deferred { - return false, true + return false, true, nil } - return finishMemoryExportPosition(opts, key, version, tag, result), false + return finishMemoryExportPosition(opts, key, version, tag, result), false, nil } func exportMemoryVersionsForKey( @@ -682,7 +702,10 @@ func exportMemoryVersionsForKey( } return true, nil } - cont, deferred := exportMemoryVersion(opts, cursorCommitTS, key, versions[i], result) + cont, deferred, err := exportMemoryVersion(opts, cursorCommitTS, key, versions[i], result) + if err != nil { + return false, err + } if deferred { // The page is full for this row. The cursor still points at the row // before it, so the next page starts here and carries it alone. @@ -692,9 +715,6 @@ func exportMemoryVersionsForKey( if !cont { return !finishExportIfLimited(opts, result), nil } - if !result.Done && finishExportIfLimited(opts, result) { - return false, nil - } } return true, nil } @@ -703,10 +723,10 @@ func (s *mvccStore) ImportVersions(ctx context.Context, opts ImportVersionsOptio if err := s.rejectMemoryEntry(ctx); err != nil { return ImportVersionsResult{}, err } - return s.importMemoryVersions(opts) + return s.importMemoryVersions(opts, s.lookupMigrationVersion) } -func (s *mvccStore) importMemoryVersions(opts ImportVersionsOptions) (ImportVersionsResult, error) { +func (s *mvccStore) importMemoryVersions(opts ImportVersionsOptions, lookup migrationVersionLookup) (ImportVersionsResult, error) { s.applyMu.Lock() s.mtx.Lock() defer s.applyMu.Unlock() @@ -725,19 +745,9 @@ func (s *mvccStore) importMemoryVersions(opts ImportVersionsOptions) (ImportVers return ImportVersionsResult{AckedCursor: bytes.Clone(existing.cursor), Duplicate: true}, nil } - for _, version := range opts.Versions { - if err := validateImportVersion(version); err != nil { - return ImportVersionsResult{}, err - } - } - for _, version := range opts.Versions { - if version.Tombstone { - s.deleteVersionLocked(version.Key, version.CommitTS) - continue - } - s.putVersionLocked(version.Key, version.Value, version.CommitTS, version.ExpireAt) + if err := s.applyMemoryImportVersionsLocked(opts, lookup); err != nil { + return ImportVersionsResult{}, err } - batchMax := importBatchMaxTS(opts.Versions) if batchMax > s.lastCommitTS { s.lastCommitTS = batchMax @@ -749,8 +759,42 @@ func (s *mvccStore) importMemoryVersions(opts ImportVersionsOptions) (ImportVers return ImportVersionsResult{AckedCursor: bytes.Clone(opts.Cursor), MaxImportedTS: batchMax}, nil } +func (s *mvccStore) applyMemoryImportVersionsLocked(opts ImportVersionsOptions, lookup migrationVersionLookup) error { + opts.Versions = unadoptedImportVersions(opts.Versions) + if err := s.versionRetirement.validateMigrationImport(opts); err != nil { + return err + } + for _, version := range opts.Versions { + if err := validateImportVersion(version); err != nil { + return err + } + } + writes := opts.Versions + if opts.AllowRetiredStaging { + lookup = s.versionRetirement.retainedMigrationLookup(lookup) + } + if !opts.AllowLegacyVersionOverwrite { + var err error + writes, err = immutableMigrationWrites(writes, opts.LogicalKey, lookup) + if err != nil { + return err + } + } + for _, version := range writes { + if version.Tombstone { + s.deleteVersionLocked(version.Key, version.CommitTS) + continue + } + s.putVersionLocked(version.Key, version.Value, version.CommitTS, version.ExpireAt) + } + return nil +} + func (s *mvccStore) ImportVersionsRaft(ctx context.Context, opts ImportVersionsOptions) (ImportVersionsResult, error) { - return s.ImportVersions(ctx, opts) + if err := s.rejectMemoryEntry(ctx); err != nil { + return ImportVersionsResult{}, err + } + return s.importMemoryVersions(opts, s.lookupMigrationHead) } func (s *mvccStore) MigrationHLCFloor(ctx context.Context, jobID uint64) (uint64, error) { diff --git a/store/mvcc_store.go b/store/mvcc_store.go index 9bff114f4..466ecb73a 100644 --- a/store/mvcc_store.go +++ b/store/mvcc_store.go @@ -20,10 +20,11 @@ import ( // VersionedValue represents a single committed version in MVCC storage. type VersionedValue struct { - TS uint64 - Value []byte - Tombstone bool - ExpireAt uint64 // HLC timestamp; 0 means no TTL + TS uint64 + Value []byte + Tombstone bool + ExpireAt uint64 // HLC timestamp; 0 means no TTL + adoptionEpoch uint64 } const ( @@ -35,6 +36,7 @@ const ( mvccSnapshotVersionV6 = uint32(6) mvccSnapshotVersionV7 = uint32(7) mvccSnapshotVersionV8 = uint32(8) + mvccSnapshotVersionV9 = uint32(9) maxSnapshotKeySize = 1 << 20 // 1 MiB per logical key // maxSnapshotInternalKeyEnvelope reserves snapshot headroom for internal // stored-key envelopes such as migration staging. Logical source keys keep @@ -85,6 +87,7 @@ func byteSliceComparator(a, b any) int { // mvccStore is an in-memory MVCC implementation backed by a treemap for // deterministic iteration order and range scans. type mvccStore struct { + versionRetirement versionRetirementState applyMu sync.Mutex raftControl map[string][]byte controlAppliedIndex uint64 @@ -185,23 +188,31 @@ func versionUpperBound(vs []VersionedValue, ts uint64) int { } func visibleValue(vs []VersionedValue, ts uint64) ([]byte, bool) { + version := versionAt(vs, ts) + if version == nil { + return nil, false + } + return version.valueAt(ts) +} + +func versionAt(vs []VersionedValue, ts uint64) *VersionedValue { // Reads at or just behind the head can skip the binary search. const tailChecks = 2 for range tailChecks { if len(vs) == 0 { - return nil, false + return nil } last := len(vs) - 1 if vs[last].TS <= ts { - return vs[last].valueAt(ts) + return &vs[last] } vs = vs[:last] } n := versionUpperBound(vs, ts) if n == 0 { - return nil, false + return nil } - return vs[n-1].valueAt(ts) + return &vs[n-1] } func (v *VersionedValue) valueAt(ts uint64) ([]byte, bool) { @@ -280,6 +291,9 @@ func (s *mvccStore) PutAt(ctx context.Context, key []byte, value []byte, commitT defer s.applyMu.Unlock() defer s.mtx.Unlock() + if err := s.versionRetirement.validateWrite(key, value, commitTS); err != nil { + return err + } commitTS = s.alignCommitTS(commitTS) s.putVersionLocked(key, value, commitTS, expireAt) if s.log.Enabled(ctx, slog.LevelInfo) { @@ -301,6 +315,9 @@ func (s *mvccStore) DeleteAt(ctx context.Context, key []byte, commitTS uint64) e defer s.applyMu.Unlock() defer s.mtx.Unlock() + if err := s.versionRetirement.validateWrite(key, nil, commitTS); err != nil { + return err + } commitTS = s.alignCommitTS(commitTS) s.deleteVersionLocked(key, commitTS) if s.log.Enabled(ctx, slog.LevelInfo) { @@ -344,25 +361,44 @@ func readTSCompacted(ts, minRetainedTS uint64) bool { // ---- MVCCStore methods ---- func (s *mvccStore) GetAt(ctx context.Context, key []byte, ts uint64) ([]byte, error) { + version, err := s.GetVersionAt(ctx, key, ts) + return version.Value, err +} + +func (s *mvccStore) GetVersionAt(ctx context.Context, key []byte, ts uint64) (VersionedValue, error) { if staged := s.memoryEntryStore(ctx); staged != nil { - return staged.GetAt(ctx, key, ts) + return staged.GetVersionAt(ctx, key, ts) } s.mtx.RLock() defer s.mtx.RUnlock() if readTSCompacted(ts, s.minRetainedTS) { - return nil, ErrReadTSCompacted + return VersionedValue{}, ErrReadTSCompacted } v, ok := s.entryTreeGet(key) if !ok { - return nil, ErrKeyNotFound + return VersionedValue{}, ErrKeyNotFound } versions, _ := v.([]VersionedValue) - value, ok := visibleValue(versions, ts) - if !ok { - return nil, ErrKeyNotFound + version := versionAt(versions, ts) + if version == nil { + return VersionedValue{}, ErrKeyNotFound + } + retired, err := s.versionRetirement.retired(key, version.Value, version.TS, version.adoptionEpoch) + if err != nil { + return VersionedValue{}, err + } + if retired { + return VersionedValue{}, ErrKeyNotFound } - return bytes.Clone(value), nil + value, visible := version.valueAt(ts) + if !visible { + return VersionedValue{}, ErrKeyNotFound + } + result := *version + result.Value = bytes.Clone(value) + result.adoptionEpoch = 0 + return result, nil } func (s *mvccStore) ExistsAt(ctx context.Context, key []byte, ts uint64) (bool, error) { @@ -380,8 +416,8 @@ func (s *mvccStore) ExistsAt(ctx context.Context, key []byte, ts uint64) (bool, return false, nil } versions, _ := v.([]VersionedValue) - _, visible := visibleValue(versions, ts) - return visible, nil + _, visible, err := s.visibleRetainedValue(key, versions, ts) + return visible, err } func (s *mvccStore) VersionExistsAtOrBefore(ctx context.Context, key []byte, ts uint64) (bool, error) { @@ -399,7 +435,12 @@ func (s *mvccStore) VersionExistsAtOrBefore(ctx context.Context, key []byte, ts return false, nil } versions, _ := v.([]VersionedValue) - return versionExistsAtOrBefore(versions, ts), nil + version := versionAt(versions, ts) + if version == nil { + return false, nil + } + retired, err := s.versionRetirement.retired(key, version.Value, version.TS, version.adoptionEpoch) + return !retired, err } func computeScanCapHint(treeSize, limit int) int { @@ -414,11 +455,11 @@ func computeScanCapHint(treeSize, limit int) int { } func (s *mvccStore) collectScanResults(ctx context.Context, it *treemap.Iterator, end []byte, limit, capHint int, ts uint64) ([]*KVPair, error) { - result, _, err := collectScanResultsWithPhysicalLimit(ctx, it, end, limit, 0, capHint, ts) + result, _, err := s.collectScanResultsWithPhysicalLimit(ctx, it, end, limit, 0, capHint, ts) return result, err } -func collectScanResultsWithPhysicalLimit(ctx context.Context, it *treemap.Iterator, end []byte, limit, physicalLimit, capHint int, ts uint64) ([]*KVPair, bool, error) { +func (s *mvccStore) collectScanResultsWithPhysicalLimit(ctx context.Context, it *treemap.Iterator, end []byte, limit, physicalLimit, capHint int, ts uint64) ([]*KVPair, bool, error) { result := make([]*KVPair, 0, capHint) visited := 0 for ok := true; ok && len(result) < limit; ok = it.Next() { @@ -437,14 +478,9 @@ func collectScanResultsWithPhysicalLimit(ctx context.Context, it *treemap.Iterat } visited++ versions, _ := it.Value().([]VersionedValue) - val, visible := visibleValue(versions, ts) - if !visible { - continue + if err := s.appendMemoryScanKV(k, versions, ts, &result); err != nil { + return nil, false, err } - result = append(result, &KVPair{ - Key: bytes.Clone(k), - Value: bytes.Clone(val), - }) } return result, false, nil } @@ -463,7 +499,11 @@ func (s *mvccStore) collectScanKeys(ctx context.Context, it *treemap.Iterator, e break } versions, _ := it.Value().([]VersionedValue) - if _, visible := visibleValue(versions, ts); !visible { + _, visible, err := s.visibleRetainedValue(k, versions, ts) + if err != nil { + return nil, err + } + if !visible { continue } result = append(result, bytes.Clone(k)) @@ -523,7 +563,7 @@ func (s *mvccStore) ScanAtPhysicalLimit(ctx context.Context, start []byte, end [ if !seekForwardIteratorStart(&it, start) { return make([]*KVPair, 0, capHint), false, nil } - return collectScanResultsWithPhysicalLimit(ctx, &it, end, visibleLimit, physicalLimit, capHint, ts) + return s.collectScanResultsWithPhysicalLimit(ctx, &it, end, visibleLimit, physicalLimit, capHint, ts) } func (s *mvccStore) ScanKeysAt(ctx context.Context, start []byte, end []byte, limit int, ts uint64) ([][]byte, error) { @@ -594,9 +634,8 @@ func (s *mvccStore) ReverseScanAt(ctx context.Context, start []byte, end []byte, if !seekReverseIteratorStart(&it, end) { return result, nil } - collectReverseVisibleKVs(&it, start, limit, ts, &result) - - return result, nil + _, err := s.collectReverseVisibleKVsWithPhysicalLimit(ctx, &it, start, limit, 0, ts, &result) + return result, err } func (s *mvccStore) ReverseScanAtPhysicalLimit(ctx context.Context, start []byte, end []byte, visibleLimit, physicalLimit int, ts uint64) ([]*KVPair, bool, error) { @@ -630,7 +669,7 @@ func (s *mvccStore) ReverseScanAtPhysicalLimit(ctx context.Context, start []byte if !seekReverseIteratorStart(&it, end) { return result, false, nil } - limitReached, err := collectReverseVisibleKVsWithPhysicalLimit(ctx, &it, start, visibleLimit, physicalLimit, ts, &result) + limitReached, err := s.collectReverseVisibleKVsWithPhysicalLimit(ctx, &it, start, visibleLimit, physicalLimit, ts, &result) return result, limitReached, err } @@ -645,17 +684,7 @@ func seekReverseIteratorStart(it *treemap.Iterator, end []byte) bool { }) } -func collectReverseVisibleKVs( - it *treemap.Iterator, - start []byte, - limit int, - ts uint64, - result *[]*KVPair, -) { - _, _ = collectReverseVisibleKVsWithPhysicalLimit(context.Background(), it, start, limit, 0, ts, result) -} - -func collectReverseVisibleKVsWithPhysicalLimit( +func (s *mvccStore) collectReverseVisibleKVsWithPhysicalLimit( ctx context.Context, it *treemap.Iterator, start []byte, @@ -680,21 +709,27 @@ func collectReverseVisibleKVsWithPhysicalLimit( return true, nil } visited++ - appendVisibleReverseKV(it, k, ts, result) + if err := s.appendVisibleReverseKV(it, k, ts, result); err != nil { + return false, err + } } return false, nil } -func appendVisibleReverseKV(it *treemap.Iterator, key []byte, ts uint64, result *[]*KVPair) { +func (s *mvccStore) appendVisibleReverseKV(it *treemap.Iterator, key []byte, ts uint64, result *[]*KVPair) error { versions, _ := it.Value().([]VersionedValue) - val, visible := visibleValue(versions, ts) + val, visible, err := s.visibleRetainedValue(key, versions, ts) + if err != nil { + return err + } if !visible { - return + return nil } *result = append(*result, &KVPair{ Key: bytes.Clone(key), Value: bytes.Clone(val), }) + return nil } func (s *mvccStore) LatestCommitTS(ctx context.Context, key []byte) (uint64, bool, error) { @@ -708,6 +743,10 @@ func (s *mvccStore) LatestCommitTS(ctx context.Context, key []byte) (uint64, boo if !ok { return 0, false, nil } + retired, err := s.versionRetirement.retired(key, ver.Value, ver.TS, ver.adoptionEpoch) + if err != nil || retired { + return 0, false, err + } return ver.TS, true, nil } @@ -736,7 +775,11 @@ func (s *mvccStore) CommittedVersionAt(ctx context.Context, key []byte, commitTS } vs, _ := v.([]VersionedValue) i := sort.Search(len(vs), func(i int) bool { return vs[i].TS >= commitTS }) - return i < len(vs) && vs[i].TS == commitTS, nil + if i == len(vs) || vs[i].TS != commitTS { + return false, nil + } + retired, err := s.versionRetirement.retired(key, vs[i].Value, commitTS, vs[i].adoptionEpoch) + return !retired, err } // ApplyMutationsRaft is provided to satisfy the MVCCStore interface. The @@ -784,7 +827,7 @@ func (s *mvccStore) applyMutations(ctx context.Context, mutations []*KVPairMutat s.mtx.Lock() defer s.applyMu.Unlock() defer s.mtx.Unlock() - if err := checkCommitTSFence(mutations, commitTS, s.lastCommitTS, fenced); err != nil { + if err := s.validateRetirementAndCommitFence(mutations, commitTS, fenced); err != nil { return err } @@ -822,6 +865,9 @@ func (s *mvccStore) ApplyMutationsPreservingLastCommitTS(ctx context.Context, mu s.mtx.Lock() defer s.applyMu.Unlock() defer s.mtx.Unlock() + if err := s.versionRetirement.validateMutations(mutations, commitTS); err != nil { + return err + } if err := s.checkConflictsLocked(mutations, readKeys, startTS); err != nil { return err @@ -921,15 +967,18 @@ func (s *mvccStore) deletePrefixesAt(deletes []PrefixDelete, commitTS uint64) er defer s.applyMu.Unlock() defer s.mtx.Unlock() - commitTS = s.alignCommitTS(commitTS) - // Collect matching keys first since we cannot modify the tree while iterating. var toDelete [][]byte seen := make(map[string]struct{}) for _, del := range deletes { - toDelete = s.collectDeletePrefixKeysLocked(del, commitTS, seen, toDelete) + var err error + toDelete, err = s.collectDeletePrefixKeysLocked(del, commitTS, seen, toDelete) + if err != nil { + return err + } } + commitTS = s.alignCommitTS(commitTS) for _, k := range toDelete { s.deleteVersionLocked(k, commitTS) } @@ -952,18 +1001,23 @@ func (s *mvccStore) ExpireAt(ctx context.Context, key []byte, expireAt uint64, c defer s.applyMu.Unlock() defer s.mtx.Unlock() - v, ok := s.entryTreeGet(key) + ver, ok := s.latestVersionLocked(key) if !ok { return ErrKeyNotFound } - versions, _ := v.([]VersionedValue) - if len(versions) == 0 { + retired, err := s.versionRetirement.retired(key, ver.Value, ver.TS, ver.adoptionEpoch) + if err != nil { + return err + } + if retired { return ErrKeyNotFound } - ver := versions[len(versions)-1] if ver.Tombstone || (ver.ExpireAt != 0 && ver.ExpireAt <= commitTS) { return ErrKeyNotFound } + if err := s.versionRetirement.validateWrite(key, ver.Value, commitTS); err != nil { + return err + } s.putVersionLocked(key, ver.Value, s.alignCommitTS(commitTS), expireAt) if s.log.Enabled(ctx, slog.LevelInfo) { @@ -1039,6 +1093,9 @@ func (s *mvccStore) writeSnapshotFile(f *os.File) error { if len(s.raftControl) != 0 || s.controlAppliedIndex != 0 { version = mvccSnapshotVersionV8 } + if s.versionRetirement.adoptionEpoch != 0 { + version = mvccSnapshotVersionV9 + } checksumOffset, err := writeMVCCSnapshotHeader(f, version) if err != nil { return err @@ -1129,7 +1186,7 @@ func (s *mvccStore) writeSnapshotBodyLocked(f *os.File, version uint32) (uint32, if !ok { continue } - if err := writeMVCCSnapshotEntry(w, key, versions); err != nil { + if err := writeMVCCSnapshotEntry(w, key, versions, version); err != nil { return 0, err } } @@ -1241,7 +1298,7 @@ func writeMVCCSnapshotBytes(w io.Writer, data []byte) error { return nil } -func writeMVCCSnapshotEntry(w io.Writer, key []byte, versions []VersionedValue) error { +func writeMVCCSnapshotEntry(w io.Writer, key []byte, versions []VersionedValue, formatVersion uint32) error { if err := binary.Write(w, binary.LittleEndian, uint64(len(key))); err != nil { return errors.WithStack(err) } @@ -1252,14 +1309,17 @@ func writeMVCCSnapshotEntry(w io.Writer, key []byte, versions []VersionedValue) return errors.WithStack(err) } for _, version := range versions { - if err := writeMVCCSnapshotVersion(w, version); err != nil { + if err := writeMVCCSnapshotVersion(w, version, formatVersion); err != nil { return err } } return nil } -func writeMVCCSnapshotVersion(w io.Writer, version VersionedValue) error { +func writeMVCCSnapshotVersion(w io.Writer, version VersionedValue, formatVersion uint32) error { + if formatVersion < mvccSnapshotVersionV9 && version.adoptionEpoch != 0 { + return errors.WithStack(ErrVersionRetirementUnavailable) + } if err := binary.Write(w, binary.LittleEndian, version.TS); err != nil { return errors.WithStack(err) } @@ -1269,6 +1329,11 @@ func writeMVCCSnapshotVersion(w io.Writer, version VersionedValue) error { if err := binary.Write(w, binary.LittleEndian, version.ExpireAt); err != nil { return errors.WithStack(err) } + if formatVersion >= mvccSnapshotVersionV9 { + if err := binary.Write(w, binary.LittleEndian, version.adoptionEpoch); err != nil { + return errors.WithStack(err) + } + } if err := binary.Write(w, binary.LittleEndian, uint64(len(version.Value))); err != nil { return errors.WithStack(err) } @@ -1278,7 +1343,7 @@ func writeMVCCSnapshotVersion(w io.Writer, version VersionedValue) error { return nil } -func (s *mvccStore) collectDeletePrefixKeysLocked(del PrefixDelete, commitTS uint64, seen map[string]struct{}, toDelete [][]byte) [][]byte { +func (s *mvccStore) collectDeletePrefixKeysLocked(del PrefixDelete, commitTS uint64, seen map[string]struct{}, toDelete [][]byte) ([][]byte, error) { it := s.entryTreeIterator() var started bool if len(del.Prefix) > 0 { @@ -1291,14 +1356,18 @@ func (s *mvccStore) collectDeletePrefixKeysLocked(del PrefixDelete, commitTS uin if !keyOK { continue } - if len(del.Prefix) > 0 && !bytes.HasPrefix(k, del.Prefix) { + if !bytes.HasPrefix(k, del.Prefix) { break } if len(del.ExcludePrefix) > 0 && bytes.HasPrefix(k, del.ExcludePrefix) { continue } versions, _ := it.Value().([]VersionedValue) - if _, visible := visibleValue(versions, commitTS); !visible { + visible, err := s.prefixDeletableVersion(k, versions, commitTS) + if err != nil { + return nil, err + } + if !visible { continue } dedupeKey := string(k) @@ -1308,7 +1377,15 @@ func (s *mvccStore) collectDeletePrefixKeysLocked(del PrefixDelete, commitTS uin seen[dedupeKey] = struct{}{} toDelete = append(toDelete, bytes.Clone(k)) } - return toDelete + return toDelete, nil +} + +func (s *mvccStore) prefixDeletableVersion(key []byte, versions []VersionedValue, ts uint64) (bool, error) { + _, visible, err := s.visibleRetainedValue(key, versions, ts) + if err != nil || !visible { + return false, err + } + return true, s.versionRetirement.validateWrite(key, nil, ts) } func mvccSnapshotTombstoneByte(tombstone bool) byte { @@ -1340,6 +1417,18 @@ func (s *mvccStore) restoreStreamingSnapshot(r io.Reader, validate func(*treemap return err } } + retirement, err := decodeVersionRetirements(meta.raftControl[versionRetirementMetadataKey], s.versionRetirement.compiler) + if err != nil { + return err + } + epoch, err := decodeVersionAdoptionEpoch(meta.raftControl[versionAdoptionMetadataKey]) + if err != nil { + return err + } + retirement, err = validateVersionRetirementEpochs(retirement, epoch) + if err != nil { + return err + } s.tree = tree s.lastCommitTS = lastCommitTS @@ -1354,6 +1443,7 @@ func (s *mvccStore) restoreStreamingSnapshot(r io.Reader, validate func(*treemap s.migrationAdmission = buildMigrationServingAdmission(meta.ownership, meta.partitions) s.migrationReadinessCache = cloneTargetStagedReadinessStates(meta.readiness) s.raftControl, s.controlAppliedIndex = meta.raftControl, meta.controlAppliedIndex + s.versionRetirement = retirement return nil } @@ -1370,7 +1460,7 @@ func readMVCCSnapshotHeader(r io.Reader) (uint32, uint32, error) { if err := binary.Read(r, binary.LittleEndian, &version); err != nil { return 0, 0, errors.WithStack(err) } - if version < mvccSnapshotVersionV1 || version > mvccSnapshotVersionV8 { + if version < mvccSnapshotVersionV1 || version > mvccSnapshotVersionV9 { return 0, 0, errors.WithStack(errors.Newf("unsupported mvcc snapshot version %d", version)) } @@ -1393,7 +1483,11 @@ func restoreStreamingMVCCSnapshotBody( return nil, 0, 0, mvccSnapshotMigrationMetadata{}, 0, err } - tree, err := readMVCCSnapshotTree(body) + epoch, err := snapshotVersionAdoptionEpoch(version, meta.raftControl) + if err != nil { + return nil, 0, 0, mvccSnapshotMigrationMetadata{}, 0, err + } + tree, err := readMVCCSnapshotTree(body, version, epoch) if err != nil { return nil, 0, 0, mvccSnapshotMigrationMetadata{}, 0, err } @@ -1603,10 +1697,10 @@ func readMVCCSnapshotBytes(r io.Reader, field string) ([]byte, error) { return data, nil } -func readMVCCSnapshotTree(r io.Reader) (*treemap.Map, error) { +func readMVCCSnapshotTree(r io.Reader, formatVersion uint32, adoptionCeiling uint64) (*treemap.Map, error) { tree := treemap.NewWith(byteSliceComparator) for { - key, versions, eof, err := readMVCCSnapshotEntry(r) + key, versions, eof, err := readMVCCSnapshotEntry(r, formatVersion, adoptionCeiling) if err != nil { return nil, err } @@ -1621,7 +1715,7 @@ func readMVCCSnapshotTree(r io.Reader) (*treemap.Map, error) { } } -func readMVCCSnapshotEntry(r io.Reader) ([]byte, []VersionedValue, bool, error) { +func readMVCCSnapshotEntry(r io.Reader, formatVersion uint32, adoptionCeiling uint64) ([]byte, []VersionedValue, bool, error) { var keyLen uint64 if err := binary.Read(r, binary.LittleEndian, &keyLen); err != nil { if errors.Is(err, io.EOF) { @@ -1647,7 +1741,7 @@ func readMVCCSnapshotEntry(r io.Reader) ([]byte, []VersionedValue, bool, error) } versions := make([]VersionedValue, 0, versionCount) for i := uint64(0); i < versionCount; i++ { - version, err := readMVCCSnapshotVersion(r) + version, err := readMVCCSnapshotVersion(r, formatVersion, adoptionCeiling) if err != nil { return nil, nil, false, err } @@ -1659,7 +1753,7 @@ func readMVCCSnapshotEntry(r io.Reader) ([]byte, []VersionedValue, bool, error) return key, versions, false, nil } -func readMVCCSnapshotVersion(r io.Reader) (VersionedValue, error) { +func readMVCCSnapshotVersion(r io.Reader, formatVersion uint32, adoptionCeiling uint64) (VersionedValue, error) { var ts uint64 if err := binary.Read(r, binary.LittleEndian, &ts); err != nil { return VersionedValue{}, errors.WithStack(err) @@ -1674,6 +1768,15 @@ func readMVCCSnapshotVersion(r io.Reader) (VersionedValue, error) { if err := binary.Read(r, binary.LittleEndian, &expireAt); err != nil { return VersionedValue{}, errors.WithStack(err) } + var adoptionEpoch uint64 + if formatVersion >= mvccSnapshotVersionV9 { + if err := binary.Read(r, binary.LittleEndian, &adoptionEpoch); err != nil { + return VersionedValue{}, errors.WithStack(err) + } + if adoptionEpoch > adoptionCeiling { + return VersionedValue{}, errors.WithStack(ErrVersionRetirementConflict) + } + } var valueLen uint64 if err := binary.Read(r, binary.LittleEndian, &valueLen); err != nil { @@ -1689,10 +1792,11 @@ func readMVCCSnapshotVersion(r io.Reader) (VersionedValue, error) { } return VersionedValue{ - TS: ts, - Value: value, - Tombstone: tombstone[0] != 0, - ExpireAt: expireAt, + TS: ts, + Value: value, + Tombstone: tombstone[0] != 0, + ExpireAt: expireAt, + adoptionEpoch: adoptionEpoch, }, nil } diff --git a/store/owned_snapshot.go b/store/owned_snapshot.go new file mode 100644 index 000000000..38f49d930 --- /dev/null +++ b/store/owned_snapshot.go @@ -0,0 +1,100 @@ +package store + +import ( + "io" + "log/slog" + "path/filepath" + "sync" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2" + "github.com/cockroachdb/pebble/v2/sstable" +) + +var _ OwnerSnapshotCapturer = (*pebbleStore)(nil) + +func (s *pebbleStore) CaptureOwnerSnapshot() (Snapshot, error) { + // ApplyRaftEntry can span multiple DB sections. Take the pin between + // entries and keep dbMu only long enough to sample this DB generation. + // The owner retires the pin before replacing or closing that generation. + s.applyMu.Lock() + defer s.applyMu.Unlock() + s.dbMu.RLock() + defer s.dbMu.RUnlock() + s.ownedSnapshotPins.Add(1) + return &ownedPebbleSnapshot{ + newWritable: newTransientSnapshotWritable, + owner: s, + pin: s.db.NewSnapshot(), + format: s.db.TableFormat(), + storeDir: s.dir, + useSST: s.sstIngestSnapshots, + targetFileBytes: s.sstIngestTargetFileBytes, + disableCompression: s.cipher != nil, + log: s.log, + }, nil +} + +type ownedPebbleSnapshot struct { + newWritable snapshotWritableConstructor + mu sync.Mutex // orders serialization and release of the pin + owner *pebbleStore + pin *pebble.Snapshot + format sstable.TableFormat + storeDir string + useSST bool + targetFileBytes uint64 + disableCompression bool + log *slog.Logger + closeErr error +} + +func (s *ownedPebbleSnapshot) WriteTo(w io.Writer) (int64, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.pin == nil { + return 0, errors.New("owned snapshot is closed") + } + if s.useSST { + metadata, err := readPebbleSnapshotMetadata(s.pin) + if err != nil { + return 0, err + } + dir := filepath.Clean(s.storeDir) + bundle, err := buildSnapshotSSTs(s.pin, s.format, filepath.Dir(dir), filepath.Base(dir)+"-sst-ingest-", metadata, s.targetFileBytes, s.disableCompression, s.newWritable) + if err == nil { + defer bundle.Close() + return bundle.WriteTo(w) + } + if s.log != nil { + s.log.Warn("failed to build owned SST ingest snapshot; using legacy stream", "error", err) + } + return (&pebbleSnapshot{snapshot: s.pin, lastCommitTS: metadata.LastCommitTS}).WriteTo(w) + } + lastCommitTS, err := readPebbleSnapshotLastCommitTS(s.pin) + if err != nil { + return 0, err + } + return (&pebbleSnapshot{snapshot: s.pin, lastCommitTS: lastCommitTS}).WriteTo(w) +} + +func (s *ownedPebbleSnapshot) Close() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.pin != nil { + s.closeErr = errors.WithStack(s.pin.Close()) + s.pin = nil + if s.closeErr == nil { + s.owner.ownedSnapshotPins.Add(-1) + s.owner = nil + } + } + return s.closeErr +} + +func (s *pebbleStore) checkOwnedSnapshotPinsLocked() error { + if pins := s.ownedSnapshotPins.Load(); pins != 0 { + return errors.WithStack(errors.Newf("source has %d unreleased owned snapshot pins", pins)) + } + return nil +} diff --git a/store/owned_snapshot_lifetime_test.go b/store/owned_snapshot_lifetime_test.go new file mode 100644 index 000000000..a147f9cbf --- /dev/null +++ b/store/owned_snapshot_lifetime_test.go @@ -0,0 +1,51 @@ +package store + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOwnedSnapshotPreventsSourceReplacement(t *testing.T) { + for _, operation := range []string{"restore", "close"} { + t.Run(operation, func(t *testing.T) { + ps, _, _ := newRaftDataWALSyncStore(t) + snapshot, err := ps.CaptureOwnerSnapshot() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, snapshot.Close()) }) + var image bytes.Buffer + _, err = snapshot.WriteTo(&image) + require.NoError(t, err) + if operation == "restore" { + require.Error(t, ps.Restore(bytes.NewReader(image.Bytes()))) + } else { + require.Error(t, ps.Close()) + } + // Rejection leaves the source and the captured view usable. + _, err = snapshot.WriteTo(&bytes.Buffer{}) + require.NoError(t, err) + require.NoError(t, snapshot.Close()) + if operation == "restore" { + require.NoError(t, ps.Restore(bytes.NewReader(image.Bytes()))) + } + }) + } +} + +func TestOwnedSnapshotPinsReleaseExactlyOnce(t *testing.T) { + ps, _, _ := newRaftDataWALSyncStore(t) + first, err := ps.CaptureOwnerSnapshot() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, first.Close()) }) + second, err := ps.CaptureOwnerSnapshot() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, second.Close()) }) + require.NoError(t, first.Close()) + require.NoError(t, first.Close()) + require.Error(t, ps.Close(), "closing one handle twice must not release the other") + _, err = second.WriteTo(&bytes.Buffer{}) + require.NoError(t, err) + require.NoError(t, second.Close()) + require.Zero(t, ps.ownedSnapshotPins.Load()) +} diff --git a/store/owned_snapshot_test.go b/store/owned_snapshot_test.go new file mode 100644 index 000000000..e57730b06 --- /dev/null +++ b/store/owned_snapshot_test.go @@ -0,0 +1,396 @@ +package store + +import ( + "bytes" + "context" + "errors" + "io" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/bootjp/elastickv/internal/encryption" + "github.com/cockroachdb/pebble/v2" + "github.com/cockroachdb/pebble/v2/objstorage" + "github.com/cockroachdb/pebble/v2/vfs" + "github.com/cockroachdb/pebble/v2/vfs/errorfs" + "github.com/stretchr/testify/require" +) + +func TestOwnerSnapshotCaptureAvoidsCheckpointIO(t *testing.T) { + src, fs, release := newRaftDataWALSyncStore(t) + src.sstIngestSnapshots = true + src.fsmApplyWriteOpts = pebble.NoSync + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "captured"), nil, 10, 10, 7)) + fs.armed.Store(true) + type result struct { + snap Snapshot + err error + } + done := make(chan result, 1) + go func() { + snap, err := src.CaptureOwnerSnapshot() + done <- result{snap, err} + }() + var r result + select { + case <-fs.entered: + release() + r = <-done + t.Error("owner capture reached a blocked WAL sync") + case r = <-done: + } + require.NoError(t, r.err) + defer func() { require.NoError(t, r.snap.Close()) }() + artifacts, err := filepath.Glob(src.dir + "-sst-*") + require.NoError(t, err) + require.Empty(t, artifacts, "owner capture created scratch before materialization") +} + +func captureOwnedForTest(t *testing.T, src *pebbleStore) Snapshot { + t.Helper() + snap, err := src.CaptureOwnerSnapshot() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, snap.Close()) }) + return snap +} + +func TestOwnerSnapshotDoesNotAttemptFailedCheckpoint(t *testing.T) { + dir := t.TempDir() + var armed atomic.Bool + var attempts atomic.Int32 + opts, cache := defaultPebbleOptionsWithCache(false) + opts.FS = errorfs.Wrap(vfs.Default, errorfs.InjectorFunc(func(op errorfs.Op) error { + if armed.Load() && op.Kind == errorfs.OpMkdirAll && strings.HasPrefix(op.Path, dir+"-sst-checkpoint-") { + attempts.Add(1) + return errorfs.ErrInjected + } + return nil + })) + db, err := pebble.Open(dir, opts) + require.NoError(t, err) + src := &pebbleStore{db: db, cache: cache, dir: dir, sstIngestSnapshots: true, fsmApplyWriteOpts: pebble.Sync} + t.Cleanup(func() { require.NoError(t, src.Close()) }) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "cut"), nil, 10, 10, 7)) + armed.Store(true) + snap := captureOwnedForTest(t, src) + require.Zero(t, attempts.Load()) + require.NoError(t, snap.Close()) + // Positive control: the same fault is reached by ordinary capture, which + // still succeeds by returning the native fallback. + ordinary, err := src.Snapshot() + require.NoError(t, err) + defer func() { require.NoError(t, ordinary.Close()) }() + require.Positive(t, attempts.Load()) + require.IsType(t, &pebbleSnapshot{}, ordinary) +} + +func TestOwnerSnapshotEncryptedAdoptedCut(t *testing.T) { + fixture := adoptedEncryptedFixture(t) + src, ok := fixture.mvcc.(*pebbleStore) + require.True(t, ok) + src.sstIngestSnapshots = true + src.sstIngestTargetFileBytes = 64 + ctx := t.Context() + require.NoError(t, src.PutAt(ctx, []byte("history"), []byte("old"), 21, 0)) + require.NoError(t, src.PutAt(ctx, []byte("history"), []byte("cut"), 25, 0)) + require.NoError(t, src.PutAt(ctx, []byte("retired"), []byte("hidden"), 15, 0)) + record := retirementTestRecord() + record.ID, record.JobID = "job/9/retired", 9 + record.StartKey, record.EndKey = []byte("r"), []byte("s") + require.NoError(t, src.ApplyRaftEntry(ctx, 5, func(entry context.Context) error { + if _, err := StageRaftEntryProgress(entry, 5); err != nil { + return err + } + return src.StageVersionRetirement(entry, record) + })) + src.SetMinRetainedTS(2) + started, err := src.beginCompaction(3) + require.NoError(t, err) + require.True(t, started) + // Materialize an independent oracle before later activity. Release this + // reference pin immediately so only the owned pin protects the old rows. + rows := func(st *pebbleStore) []byte { + ref := st.db.NewSnapshot() + defer func() { require.NoError(t, ref.Close()) }() + var b bytes.Buffer + require.NoError(t, writePebbleSnapshotEntries(ref, &b)) + return b.Bytes() + } + wantRows := rows(src) + snap := captureOwnedForTest(t, src) + owned, ok := snap.(*ownedPebbleSnapshot) + require.True(t, ok) + var scratch snapshotScratchFiles + owned.newWritable = scratch.record(owned.newWritable) + require.NoError(t, src.ApplyMutationsRaftAt(ctx, raftEntryPut("history", "future"), nil, 40, 40, 6)) + reclaimed, err := src.ReclaimVersionRetirement(ctx, record.JobID, record.ID) + require.NoError(t, err) + require.EqualValues(t, 1, reclaimed.DeletedRows) + require.NoError(t, src.Compact(ctx, 40)) + require.NoError(t, src.db.Flush()) + require.NoError(t, src.db.Compact(ctx, []byte{0}, []byte{255}, true)) + require.NotEqual(t, wantRows, rows(src)) + + var raw bytes.Buffer + _, err = snap.WriteTo(&raw) + require.NoError(t, err) + require.NoError(t, snap.Close()) + manifest, err := readPebbleSSTIngestManifest(bytes.NewReader(raw.Bytes())) + require.NoError(t, err) + scratch.requireFinished(t, manifest, 0) + artifacts, err := filepath.Glob(src.dir + "-sst-ingest-*") + require.NoError(t, err) + require.Empty(t, artifacts) + require.Equal(t, uint64(25), manifest.LastCommitTS) + require.Equal(t, uint64(2), manifest.MinRetainedTS) + require.Equal(t, uint64(3), manifest.PendingMinRetainedTS) + require.NotNil(t, manifest.AppliedIndex) + require.Equal(t, uint64(5), *manifest.AppliedIndex) + + dir := filepath.Join(t.TempDir(), "restored") + opt := WithEncryption(fixture.cipher, encryption.NewDeterministicNonceFactory(2, 1), func() (uint32, bool) { return fixture.keyID, true }) + dst := openSSTSnapshotTestStore(t, dir, opt) + require.NoError(t, dst.Restore(bytes.NewReader(raw.Bytes()))) + require.NoError(t, dst.Close()) + dst.db = nil // fixture cleanup no longer owns the closed DB + dst = openSSTSnapshotTestStore(t, dir, opt) + require.Equal(t, wantRows, rows(dst)) + retirement := retirementStoreForTest(t, dst) + require.NoError(t, retirement.ConfigureVersionRetirement(retirementTestCompiler)) + require.NoError(t, retirement.VersionAdoptionReady(ctx)) + assertAdoptedRowsForTest(t, dst, 3) + _, err = dst.GetAt(ctx, []byte("retired"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) + reclaimed, err = dst.ReclaimVersionRetirement(ctx, record.JobID, record.ID) + require.NoError(t, err) + require.EqualValues(t, 1, reclaimed.DeletedRows) + v, err := dst.GetAt(ctx, []byte("history"), 21) + require.NoError(t, err) + require.Equal(t, []byte("old"), v) +} + +func TestOwnerSnapshotAppliedIndexPresence(t *testing.T) { + for _, tc := range []struct { + name string + present bool + }{{"absent", false}, {"zero", true}} { + t.Run(tc.name, func(t *testing.T) { + src := openSSTSnapshotTestStore(t, t.TempDir(), WithSSTIngestSnapshots(true)) + if tc.present { + require.NoError(t, src.SetDurableAppliedIndex(0)) + } + snap := captureOwnedForTest(t, src) + require.NoError(t, src.SetDurableAppliedIndex(9)) + var raw bytes.Buffer + _, err := snap.WriteTo(&raw) + require.NoError(t, err) + require.NoError(t, snap.Close()) + manifest, err := readPebbleSSTIngestManifest(bytes.NewReader(raw.Bytes())) + require.NoError(t, err) + require.Equal(t, tc.present, manifest.AppliedIndex != nil) + require.NoError(t, src.Restore(bytes.NewReader(raw.Bytes()))) + idx, present, err := src.LastAppliedIndex() + require.NoError(t, err) + require.Equal(t, tc.present, present) + require.Zero(t, idx) + }) + } +} + +func TestOwnerSnapshotSSTDisabledSkipsScratch(t *testing.T) { + src := openSSTSnapshotTestStore(t, t.TempDir(), WithSSTIngestSnapshots(false)) + writeSSTSnapshotTestData(t, src) + snap, ok := captureOwnedForTest(t, src).(*ownedPebbleSnapshot) + require.True(t, ok) + var scratch snapshotScratchFiles + snap.newWritable = scratch.record(snap.newWritable) + var raw bytes.Buffer + n, err := snap.WriteTo(&raw) + require.NoError(t, err) + require.EqualValues(t, raw.Len(), n) + require.True(t, bytes.HasPrefix(raw.Bytes(), pebbleSnapshotMagic[:])) + require.Empty(t, scratch) +} + +func TestOwnerSnapshotNativeFallbackCut(t *testing.T) { + src := openSSTSnapshotTestStore(t, t.TempDir(), WithSSTIngestSnapshots(true)) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "captured"), nil, 10, 10, 7)) + snap := captureOwnedForTest(t, src) + owned, ok := snap.(*ownedPebbleSnapshot) + require.True(t, ok) + // Give MkdirTemp a missing parent while keeping the real DB and its pin live. + owned.storeDir = filepath.Join(t.TempDir(), "missing", "db") + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "later"), nil, 20, 20, 8)) + var raw bytes.Buffer + _, err := snap.WriteTo(&raw) + require.NoError(t, err) + require.True(t, bytes.HasPrefix(raw.Bytes(), pebbleSnapshotMagic[:])) + require.NoError(t, snap.Close()) + require.NoError(t, src.Restore(bytes.NewReader(raw.Bytes()))) + v, err := src.GetAt(t.Context(), []byte("key"), 20) + require.NoError(t, err) + require.Equal(t, []byte("captured"), v) + idx, present, err := src.LastAppliedIndex() + require.NoError(t, err) + require.True(t, present) + require.Equal(t, uint64(7), idx) +} + +func TestOwnerSnapshotFallbackAfterScratchFinishFailure(t *testing.T) { + src := openSSTSnapshotTestStore(t, t.TempDir(), WithSSTIngestSnapshots(true), withSSTIngestTargetFileBytesForTest(1)) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "cut"), nil, 10, 10, 7)) + snap, ok := captureOwnedForTest(t, src).(*ownedPebbleSnapshot) + require.True(t, ok) + var want bytes.Buffer + native := &pebbleSnapshot{snapshot: snap.pin, lastCommitTS: 10} + _, err := native.WriteTo(&want) + require.NoError(t, err) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "later"), nil, 20, 20, 8)) + + var files snapshotScratchFiles + record := files.record(snap.newWritable) + snap.newWritable = func(f vfs.File) objstorage.Writable { + w := record(f) + if len(files) == 2 { + files[1].closeErr = errors.New("second SST finish") + } + return w + } + var raw bytes.Buffer + n, err := snap.WriteTo(&raw) + require.NoError(t, err) + require.EqualValues(t, want.Len(), n) + require.Equal(t, want.Bytes(), raw.Bytes()) + require.Len(t, files, 2) + for _, f := range files { + require.Positive(t, f.writes) + require.Equal(t, 1, f.closes) + require.Zero(t, f.syncs) + } + artifacts, err := filepath.Glob(src.dir + "-sst-*") + require.NoError(t, err) + require.Empty(t, artifacts) + require.NoError(t, snap.Close()) + require.NoError(t, src.Restore(bytes.NewReader(raw.Bytes()))) + value, err := src.GetAt(t.Context(), []byte("key"), 20) + require.NoError(t, err) + require.Equal(t, "cut", string(value)) +} + +// Stop on the first output byte, with the worker and its bundle still live. +type pausedSnapshotOutput struct { + entered chan struct{} + release chan struct{} + once sync.Once + bytes.Buffer +} + +func (w *pausedSnapshotOutput) Write(p []byte) (int, error) { + w.once.Do(func() { + close(w.entered) + <-w.release + }) + return w.Buffer.Write(p) +} + +func TestOwnerSnapshotApplyDuringWriteAndRetire(t *testing.T) { + src := openSSTSnapshotTestStore(t, t.TempDir(), WithSSTIngestSnapshots(true)) + snap := captureOwnedForTest(t, src) + out := &pausedSnapshotOutput{entered: make(chan struct{}), release: make(chan struct{})} + write := make(chan error, 1) + go func() { + _, err := snap.WriteTo(out) + write <- err + }() + select { + case <-out.entered: + case err := <-write: + t.Fatalf("export finished before streaming: %v", err) + } + closed := make(chan error, 1) + go func() { closed <- snap.Close() }() + err := src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "later"), nil, 20, 20, 8) + select { + case <-closed: + close(out.release) + <-write + t.Fatal("close completed during export") + default: + } + close(out.release) + require.NoError(t, err) + require.NoError(t, <-write) + require.NoError(t, <-closed) + require.Zero(t, src.db.Metrics().Snapshots.Count) + require.NoError(t, snap.Close()) + n, err := snap.WriteTo(io.Discard) + require.Error(t, err) + require.Zero(t, n) +} + +type failingSnapshotOutput struct { + bytes.Buffer + failAfterManifest bool + failed bool +} + +func (w *failingSnapshotOutput) Write(p []byte) (int, error) { + fail := w.Len() == len(pebbleSSTIngestSnapshotMagic) + if w.failAfterManifest { + _, err := readPebbleSSTIngestManifest(bytes.NewReader(w.Bytes())) + fail = err == nil + } + if !w.failed && fail { + w.failed = true + n, _ := w.Buffer.Write(p[:1]) + return n, io.ErrClosedPipe + } + return w.Buffer.Write(p) +} + +func TestOwnerSnapshotAbandonAndPartialWrite(t *testing.T) { + src := openSSTSnapshotTestStore(t, t.TempDir(), WithSSTIngestSnapshots(true)) + abandoned := captureOwnedForTest(t, src) + require.Equal(t, 1, src.db.Metrics().Snapshots.Count) + require.NoError(t, abandoned.Close()) + require.NoError(t, abandoned.Close()) + require.Zero(t, src.db.Metrics().Snapshots.Count) + n, err := abandoned.WriteTo(io.Discard) + require.Error(t, err) + require.Zero(t, n) + + snap := captureOwnedForTest(t, src) + out := &failingSnapshotOutput{} + n, err = snap.WriteTo(out) + require.ErrorIs(t, err, io.ErrClosedPipe) + require.EqualValues(t, len(pebbleSSTIngestSnapshotMagic)+1, n) + require.EqualValues(t, n, out.Len(), "a second stream must never follow partial output") + require.True(t, bytes.HasPrefix(out.Bytes(), pebbleSSTIngestSnapshotMagic[:])) + artifacts, err := filepath.Glob(src.dir + "-sst-*") + require.NoError(t, err) + require.Empty(t, artifacts) +} + +func TestOwnerSnapshotPartialSSTFileWrite(t *testing.T) { + src := openSSTSnapshotTestStore(t, t.TempDir(), WithSSTIngestSnapshots(true)) + writeSSTSnapshotTestData(t, src) + snap := captureOwnedForTest(t, src) + out := &failingSnapshotOutput{failAfterManifest: true} + n, err := snap.WriteTo(out) + require.ErrorIs(t, err, io.ErrClosedPipe) + require.EqualValues(t, out.Len(), n) + r := bytes.NewReader(out.Bytes()) + manifest, err := readPebbleSSTIngestManifest(r) + require.NoError(t, err) + require.NotEmpty(t, manifest.Files) + require.Greater(t, manifest.Files[0].Size, int64(1)) + require.Equal(t, 1, r.Len(), "only the first byte of the first SST was accepted") + artifacts, err := filepath.Glob(src.dir + "-sst-*") + require.NoError(t, err) + require.Empty(t, artifacts) + require.NoError(t, snap.Close()) + require.Zero(t, src.ownedSnapshotPins.Load()) +} diff --git a/store/prepared_mutations.go b/store/prepared_mutations.go index d31605ed2..0cd3ac4c4 100644 --- a/store/prepared_mutations.go +++ b/store/prepared_mutations.go @@ -104,11 +104,11 @@ func (s *mvccStore) applyPreparedMutations(ctx context.Context, mutations []*KVP defer s.applyMu.Unlock() s.mtx.Lock() defer s.mtx.Unlock() - for _, version := range expected { - actual, found := s.latestVersionLocked(version.Key) - if !found || !preparedVersionMatches(version, actual.TS, actual.Tombstone, actual.ExpireAt, actual.Value) { - return NewWriteConflictError(version.Key) - } + if err := s.versionRetirement.validateMutations(mutations, commitTS); err != nil { + return err + } + if err := s.comparePreparedVersionsLocked(expected); err != nil { + return err } if err := s.checkConflictsLocked(conflicts, readKeys, startTS); err != nil { return err @@ -127,3 +127,13 @@ func (s *mvccStore) applyPreparedMutations(ctx context.Context, mutations []*KVP } return nil } + +func (s *mvccStore) comparePreparedVersionsLocked(expected []MVCCVersion) error { + for _, version := range expected { + actual, found := s.latestVersionLocked(version.Key) + if !found || !preparedVersionMatches(version, actual.TS, actual.Tombstone, actual.ExpireAt, actual.Value) { + return NewWriteConflictError(version.Key) + } + } + return nil +} diff --git a/store/raft_control_metadata.go b/store/raft_control_metadata.go index b5bd8459e..dca457e46 100644 --- a/store/raft_control_metadata.go +++ b/store/raft_control_metadata.go @@ -104,6 +104,9 @@ func raftControlKey(key []byte) ([]byte, error) { } func validateRaftControlStage(ctx context.Context, key, value []byte) ([]byte, error) { + if (bytes.Equal(key, []byte(versionRetirementMetadataKey)) || bytes.Equal(key, []byte(versionAdoptionMetadataKey))) && ctx.Value(versionRetirementStageKey{}) != true { + return nil, errors.WithStack(ErrVersionRetirementConflict) + } if err := ctx.Err(); err != nil { return nil, errors.WithStack(err) } @@ -179,7 +182,7 @@ func (s *pebbleStore) decodeRaftControlValue(key, value []byte) ([]byte, error) if err != nil { return nil, err } - if sv.Tombstone || sv.ExpireAt != 0 { + if sv.Tombstone || sv.ExpireAt != 0 || sv.AdoptionEpoch != 0 { return nil, errors.New("store: corrupt raft control metadata value") } plain, flag, err := s.decryptAuthenticatedForKey(key, sv, sv.Value) diff --git a/store/raft_entry.go b/store/raft_entry.go index 3fdfa31dd..a9f50bd53 100644 --- a/store/raft_entry.go +++ b/store/raft_entry.go @@ -51,6 +51,7 @@ func IsApplyVerdict(err error) bool { return errors.Is(err, ErrWriteConflict) || errors.Is(err, ErrUnknownOp) || errors.Is(err, ErrValueTooLarge) || + errors.Is(err, ErrMigrationRetired) || errors.Is(err, errMVCCMetadataKeyCollision) } @@ -84,15 +85,16 @@ type raftEntryScope struct { // lastCommitTS, mirroring the advanceLastCommitTS argument of the // per-request path. advance bool - // touched records that at least one request staged or observed - // something, so an entry whose every request failed validation commits - // nothing, as the per-request path does. - touched bool - dataTouched bool - forceSync bool - controlOnly bool - readiness map[uint64]TargetStagedReadinessState - capture *migrationCaptureCollector + // touched records staged writes, observations, or explicit entry + // progress. A rejection-only entry commits its index when its caller + // stages progress explicitly. + touched bool + dataTouched bool + forceSync bool + controlOnly bool + readiness map[uint64]TargetStagedReadinessState + versionRetirement *versionRetirementState + capture *migrationCaptureCollector // failed is the first staging error; once set, every later staging call // and the commit return it, so a partially staged request can never // land. @@ -235,19 +237,33 @@ func (s *pebbleStore) commitRaftEntryScope(scope *raftEntryScope) error { if !scope.touched { return nil } - s.dbMu.RLock() - defer s.dbMu.RUnlock() + if scope.versionRetirement != nil { + s.dbMu.Lock() + defer s.dbMu.Unlock() + } else { + s.dbMu.RLock() + defer s.dbMu.RUnlock() + } if s.db != scope.db { return errors.WithStack(ErrRaftEntryStoreSwapped) } if err := s.validateRaftControlIndex(scope); err != nil { return err } + // A rejected entry may persist only progress. It changes no readable + // data or watermark, so WAL sync must not hold their publication lock. + if scope.onlyRaftEntryProgress() { + return s.commitRaftEntryProgress(scope) + } watermark := s.LastCommitTS() if scope.canCommitWithoutMetadataLock(watermark) { return s.commitIndexedRaftDataBatch(scope.batch, s.raftApplyWriteOpts(), max(watermark, scope.maxAdvertisedCommitTS), scope.appliedIndex) } + return s.commitRaftEntryMetadata(scope) +} +// The caller holds applyMu and dbMu through the commit and publication. +func (s *pebbleStore) commitRaftEntryMetadata(scope *raftEntryScope) error { s.mtx.Lock() defer s.mtx.Unlock() newLastTS := s.lastCommitTS @@ -268,6 +284,19 @@ func (s *pebbleStore) commitRaftEntryScope(scope *raftEntryScope) error { return nil } +func (sc *raftEntryScope) onlyRaftEntryProgress() bool { + return sc.appliedIndex != 0 && !sc.controlOnly && !sc.advance && + !sc.dataTouched && !sc.forceSync && len(sc.readiness) == 0 && + sc.versionRetirement == nil && sc.batch.Empty() +} + +func (s *pebbleStore) commitRaftEntryProgress(scope *raftEntryScope) error { + if err := stageAppliedIndexInBatch(scope.batch, scope.appliedIndex); err != nil { + return err + } + return errors.WithStack(scope.batch.Commit(s.raftApplyWriteOpts())) +} + func (sc *raftEntryScope) canCommitWithoutMetadataLock(watermark uint64) bool { // A snapshot taken at watermark must exclude every staged version while // Pebble can make the batch visible ahead of WAL sync. @@ -276,6 +305,9 @@ func (sc *raftEntryScope) canCommitWithoutMetadataLock(watermark uint64) bool { } func (s *pebbleStore) publishRaftEntryMirrors(scope *raftEntryScope, newLastTS uint64) { + if scope.versionRetirement != nil { + s.versionRetirement = *scope.versionRetirement + } if scope.advance { s.updateLastCommitTS(newLastTS) } @@ -328,9 +360,9 @@ func (s *pebbleStore) stageMutationsInRaftEntryWithFence(ctx context.Context, sc return scope.fail(errors.WithStack(ErrRaftEntryStoreSwapped)) } - landed, observe, err := s.raftEntryMutationAlreadyLanded(scope, mutations, commitTS, appliedIndex, fenced) + landed, observe, err := s.raftEntryMutationAlreadyLanded(ctx, scope, mutations, commitTS, appliedIndex, fenced) if err != nil { - return scope.fail(err) + return scope.failUnlessVerdict(err) } if landed { if observe { @@ -391,9 +423,9 @@ func (s *pebbleStore) stagePreservingMutationsInRaftEntry(ctx context.Context, s return nil } -func (s *pebbleStore) raftEntryMutationAlreadyLanded(scope *raftEntryScope, mutations []*KVPairMutation, commitTS, appliedIndex uint64, fenced bool) (bool, bool, error) { +func (s *pebbleStore) raftEntryMutationAlreadyLanded(ctx context.Context, scope *raftEntryScope, mutations []*KVPairMutation, commitTS, appliedIndex uint64, fenced bool) (bool, bool, error) { if appliedIndex == 0 { - return false, false, nil + return false, false, s.versionRetirementFor(ctx).validateMutations(mutations, commitTS) } persisted, present, err := s.readAppliedIndexLocked() if err != nil { @@ -402,6 +434,9 @@ func (s *pebbleStore) raftEntryMutationAlreadyLanded(scope *raftEntryScope, muta if present && appliedIndex < persisted { return true, false, nil } + if err := s.versionRetirementFor(ctx).validateMutations(mutations, commitTS); err != nil { + return false, false, err + } if (present && appliedIndex == persisted) || (scope.dataTouched && !fenced) { landed, err := s.raftApplyAlreadyLandedWith(scope.batch, mutations, commitTS) return landed, landed, err diff --git a/store/raft_entry_cas.go b/store/raft_entry_cas.go new file mode 100644 index 000000000..7443eadf0 --- /dev/null +++ b/store/raft_entry_cas.go @@ -0,0 +1,142 @@ +package store + +import ( + "bytes" + "context" + "math" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2" +) + +// StageRaftEntryProgress checks for replay and stages the current entry's +// index even when all of its requests are rejected. Call it before applying +// any requests in the scope. An error from the entry callback discards it. +func StageRaftEntryProgress(ctx context.Context, index uint64) (replayed bool, err error) { + if sc, _ := ctx.Value(raftEntryScopeKey{}).(*raftEntryScope); sc != nil { + return sc.stageProgress(index) + } + if sc, _ := ctx.Value(memoryEntryKey{}).(*memoryRaftEntry); sc != nil { + return sc.stageProgress(index) + } + return false, errors.Wrap(ErrNotSupported, "Raft entry progress requires a data scope") +} + +func (sc *raftEntryScope) stageProgress(index uint64) (bool, error) { + if err := sc.checkDataIndex(index); err != nil { + return false, err + } + if index == 0 { + return false, nil + } + s := sc.store + s.dbMu.RLock() + defer s.dbMu.RUnlock() + if s.db != sc.db { + return false, sc.fail(errors.WithStack(ErrRaftEntryStoreSwapped)) + } + persisted, present, err := s.readAppliedIndexLocked() + if err != nil { + return false, sc.fail(err) + } + if present && index <= persisted { + return true, nil + } + sc.touched = true + return false, nil +} + +func (sc *memoryRaftEntry) stageProgress(index uint64) (bool, error) { + if err := sc.allowData(); err != nil { + return false, err + } + if index != sc.index { + return false, sc.fail(errors.WithStack(ErrRaftEntryIndexMismatch)) + } + if index == 0 { + return false, nil + } + if index <= sc.staged.controlAppliedIndex { + return true, nil + } + sc.staged.controlAppliedIndex = index + return false, nil +} + +// RaftEntryCommitWatermark returns the advertised commit timestamp including +// writes staged earlier in this entry. +func RaftEntryCommitWatermark(ctx context.Context) (uint64, error) { + if sc, _ := ctx.Value(raftEntryScopeKey{}).(*raftEntryScope); sc != nil { + return max(sc.store.LastCommitTS(), sc.maxAdvertisedCommitTS), nil + } + if sc, _ := ctx.Value(memoryEntryKey{}).(*memoryRaftEntry); sc != nil { + return sc.staged.LastCommitTS(), nil + } + return 0, errors.Wrap(ErrNotSupported, "Raft entry watermark requires a data scope") +} + +// RaftEntryLatestRecord reads the version and authenticated visibility +// metadata of the head in the entry view, including tombstones and expired +// records, without returning the previous value. The caller evaluates +// liveness at the replicated write timestamp. +func RaftEntryLatestRecord(ctx context.Context, key []byte) (VersionedValue, error) { + if sc, _ := ctx.Value(raftEntryScopeKey{}).(*raftEntryScope); sc != nil { + return sc.latestRecord(key) + } + if sc, _ := ctx.Value(memoryEntryKey{}).(*memoryRaftEntry); sc != nil { + version, exists := sc.staged.latestVersionLocked(key) + if !exists { + return VersionedValue{}, ErrKeyNotFound + } + version.Value = nil + return version, nil + } + return VersionedValue{}, errors.Wrap(ErrNotSupported, "Raft entry head read requires a data scope") +} + +func (sc *raftEntryScope) latestRecord(key []byte) (VersionedValue, error) { + s := sc.store + s.dbMu.RLock() + defer s.dbMu.RUnlock() + if s.db != sc.db { + return VersionedValue{}, errors.WithStack(ErrRaftEntryStoreSwapped) + } + iter, err := sc.batch.NewIter(&pebble.IterOptions{ + LowerBound: encodeKey(key, math.MaxUint64), + UpperBound: keyUpperBound(key), + }) + if err != nil { + return VersionedValue{}, errors.WithStack(err) + } + record, err := s.readRaftEntryHead(iter, key) + if closeErr := iter.Close(); closeErr != nil { + return VersionedValue{}, errors.Wrap(closeErr, "close Raft entry head iterator") + } + return record, err +} + +func (s *pebbleStore) readRaftEntryHead(iter *pebble.Iterator, key []byte) (VersionedValue, error) { + if !iter.First() || !skipPebbleMetadataForward(iter) { + if err := iter.Error(); err != nil { + return VersionedValue{}, errors.WithStack(err) + } + return VersionedValue{}, ErrKeyNotFound + } + k := iter.Key() + userKey, ts := decodeKeyView(k) + if !bytes.Equal(userKey, key) { + return VersionedValue{}, ErrKeyNotFound + } + raw, err := iter.ValueAndErr() + if err != nil { + return VersionedValue{}, errors.WithStack(err) + } + value, err := decodeValueView(raw) + if err != nil { + return VersionedValue{}, errors.WithStack(err) + } + if _, _, err := s.decryptAuthenticatedForKey(k, value, value.Value); err != nil { + return VersionedValue{}, err + } + return VersionedValue{TS: ts, Tombstone: value.Tombstone, ExpireAt: value.ExpireAt}, nil +} diff --git a/store/raft_entry_memory.go b/store/raft_entry_memory.go index 8a66a9a7e..0671bc338 100644 --- a/store/raft_entry_memory.go +++ b/store/raft_entry_memory.go @@ -146,6 +146,7 @@ func (s *mvccStore) newMemoryEntryOverlayLocked() *mvccStore { dst.migrationReadinessCache = s.migrationReadinessCache dst.controlAppliedIndex = s.controlAppliedIndex dst.raftControl = s.raftControl + dst.versionRetirement = s.versionRetirement return dst } @@ -173,6 +174,7 @@ func (s *mvccStore) publishMemoryEntryLocked(src *mvccStore) { } s.lastCommitTS = src.lastCommitTS s.controlAppliedIndex = src.controlAppliedIndex + s.versionRetirement = src.versionRetirement } type memoryEntryValue struct { diff --git a/store/raft_entry_progress_latency_test.go b/store/raft_entry_progress_latency_test.go new file mode 100644 index 000000000..37db5379e --- /dev/null +++ b/store/raft_entry_progress_latency_test.go @@ -0,0 +1,78 @@ +package store + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type progressReadObservation struct { + ts uint64 + value string + err error +} + +func TestRejectedRaftEntryProgressDoesNotBlockCommittedReads(t *testing.T) { + for _, tc := range []struct { + name string + read func(*pebbleStore) progressReadObservation + wantValue string + }{ + {name: "watermark", read: func(s *pebbleStore) progressReadObservation { + return progressReadObservation{ts: s.LastCommitTS()} + }}, + {name: "versioned", wantValue: "value", read: func(s *pebbleStore) progressReadObservation { + value, err := s.GetVersionAt(t.Context(), []byte("key"), 10) + return progressReadObservation{ts: value.TS, value: string(value.Value), err: err} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s, fs, release := newRaftDataWALSyncStore(t) + require.NoError(t, s.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "value"), nil, 10, 10, 1)) + fs.armed.Store(true) + applied := make(chan error, 1) + go func() { + applied <- s.ApplyRaftEntry(t.Context(), 2, func(ctx context.Context) error { + _, err := StageRaftEntryProgress(ctx, 2) + return err + }) + }() + select { + case <-fs.entered: + case err := <-applied: + t.Fatalf("progress returned before WAL sync: %v", err) + case <-time.After(time.Second): + t.Fatal("progress never reached WAL sync") + } + select { + case err := <-applied: + t.Fatalf("progress acknowledged before WAL sync: %v", err) + default: + } + read := make(chan progressReadObservation, 1) + go func() { read <- tc.read(s) }() + var observed progressReadObservation + blocked := false + select { + case observed = <-read: + case <-time.After(100 * time.Millisecond): + blocked = true + t.Error("rejected entry progress blocked committed read behind WAL sync") + } + release() + require.NoError(t, <-applied) + if blocked { + observed = <-read + } + require.NoError(t, observed.err) + require.Equal(t, uint64(10), observed.ts) + require.Equal(t, tc.wantValue, observed.value) + index, present := raftEntryAppliedIndex(t, s) + require.True(t, present) + require.Equal(t, uint64(2), index) + require.Equal(t, uint64(10), s.LastCommitTS()) + }) + } +} diff --git a/store/redis_fence_gc_test.go b/store/redis_fence_gc_test.go index c26919ed6..40d9e6674 100644 --- a/store/redis_fence_gc_test.go +++ b/store/redis_fence_gc_test.go @@ -64,10 +64,7 @@ func runRedisFenceGCDiskComparison(t *testing.T, gc bool) redisFenceGCDiskCompar t.Helper() ctx := t.Context() dir := filepath.Join(t.TempDir(), "pebble") - opened, err := NewPebbleStore(dir) - require.NoError(t, err) - st, ok := opened.(*pebbleStore) - require.True(t, ok) + st := openInternalRecordTrial(t, dir) keep := []byte("user-key") require.NoError(t, st.PutAt(ctx, keep, []byte("value"), 1, 0)) index := uint64(1) @@ -89,7 +86,7 @@ func runRedisFenceGCDiskComparison(t *testing.T, gc bool) redisFenceGCDiskCompar compactInternalRecordTrial(t, st) require.NoError(t, st.Close()) - report := redisFenceGCDiskComparison{compacted: measureInternalRecordTrial(t, dir)} + report := redisFenceGCDiskComparison{compacted: measureInternalRecordTrial(t, st)} reopened, err := NewPebbleStore(dir) require.NoError(t, err) defer func() { require.NoError(t, reopened.Close()) }() @@ -110,7 +107,10 @@ func runRedisFenceGCDiskComparison(t *testing.T, gc bool) redisFenceGCDiskCompar } else { require.NoError(t, err) } - report.reopened = measureInternalRecordTrial(t, dir) + reopenedPebble, ok := reopened.(*pebbleStore) + require.True(t, ok) + require.NoError(t, reopenedPebble.Close()) + report.reopened = measureInternalRecordTrial(t, reopenedPebble) return report } diff --git a/store/snapshot_artifact_ownership_test.go b/store/snapshot_artifact_ownership_test.go new file mode 100644 index 000000000..6849b3255 --- /dev/null +++ b/store/snapshot_artifact_ownership_test.go @@ -0,0 +1,185 @@ +package store + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/client/pkg/v3/fileutil" +) + +// Run the second open synchronously inside the manifest write, after the +// complete manifest is observable and before the exporter opens its first SST. +type afterManifestWriter struct { + bytes.Buffer + afterManifest func(pebbleSSTIngestManifest) +} + +func (w *afterManifestWriter) Write(p []byte) (int, error) { + n, err := w.Buffer.Write(p) + if w.afterManifest != nil { + manifest, parseErr := readPebbleSSTIngestManifest(bytes.NewReader(w.Bytes())) + if parseErr == nil { + w.afterManifest(manifest) + w.afterManifest = nil + } + } + return n, err +} + +func TestDuplicateStoreOpenPreservesLiveSSTExport(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + src := openSSTSnapshotTestStore(t, dir, WithSSTIngestSnapshots(true)) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("row", "cut"), nil, 1, 2, 11)) + snap := captureOwnedForTest(t, src) + out := &afterManifestWriter{afterManifest: func(manifest pebbleSSTIngestManifest) { + require.NotEmpty(t, manifest.Files) + paths, err := filepath.Glob(dir + "-sst-ingest-*") + require.NoError(t, err) + require.Len(t, paths, 1) + require.FileExists(t, filepath.Join(paths[0], manifest.Files[0].Name)) + other, err := NewPebbleStore(dir) + require.Error(t, err) + require.Nil(t, other) + }} + _, err := snap.WriteTo(out) + require.NoError(t, err) + require.Nil(t, out.afterManifest, "expected an SST stream") + require.NoError(t, snap.Close()) + dst := openSSTSnapshotTestStore(t, filepath.Join(t.TempDir(), "dst")) + require.NoError(t, dst.Restore(bytes.NewReader(out.Bytes()))) + value, err := dst.GetAt(t.Context(), []byte("row"), 2) + require.NoError(t, err) + require.Equal(t, "cut", string(value)) +} + +func TestRawPebbleOwnerPreventsStoreScratchCleanup(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + raw, err := pebble.Open(dir, &pebble.Options{}) + require.NoError(t, err) + scratch, err := os.MkdirTemp(filepath.Dir(dir), "db-sst-ingest-") + require.NoError(t, err) + _, openErr := NewPebbleStore(dir) + require.NoError(t, raw.Close()) + require.Error(t, openErr) + require.DirExists(t, scratch) + openSSTSnapshotTestStore(t, dir) + require.NoDirExists(t, scratch) +} + +func TestStoreOpenDuringRestoreRenameGap(t *testing.T) { + const child = "ELASTICKV_TEST_STORE_RESTORE_GAP" + if os.Getenv(child) == "1" { + _, err := NewPebbleStore("db") + require.ErrorIs(t, err, fileutil.ErrLocked) + return + } + dir := filepath.Join(t.TempDir(), "db") + s := openSSTSnapshotTestStore(t, dir) + require.NoError(t, s.SetDurableAppliedIndex(11)) + // Stop at the on-disk state between the two restore renames. The store + // owner is live, but neither a Pebble handle nor a live directory exists. + require.NoError(t, s.db.Close()) + s.db = nil + s.cache.Unref() + s.cache = nil + backup := dir + "-restore-backup-live" + require.NoError(t, os.Rename(dir, backup)) + other, err := NewPebbleStore(dir) + if err == nil { + require.NoError(t, other.Close()) + t.Fatal("second open recovered a backup belonging to a live restore") + } + executable, err := os.Executable() + require.NoError(t, err) + cmd := exec.CommandContext(t.Context(), executable, "-test.run=^TestStoreOpenDuringRestoreRenameGap$") + cmd.Dir = filepath.Dir(dir) + cmd.Env = append(os.Environ(), child+"=1") + output, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", output) + require.NoDirExists(t, dir) + require.DirExists(t, backup) + require.NoError(t, os.Rename(backup, dir)) + require.NoError(t, s.reopenStoreDB(dir)) + require.NoError(t, s.Close()) + s.db = nil + reopened := openSSTSnapshotTestStore(t, dir) + idx, present := raftEntryAppliedIndex(t, reopened) + require.True(t, present) + require.EqualValues(t, 11, idx) +} + +func TestStoreOpenRecoveryFailureReleasesLock(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + s := openSSTSnapshotTestStore(t, dir) + require.NoError(t, s.SetDurableAppliedIndex(11)) + originalLock, err := s.lifecycleLock.Stat() + require.NoError(t, err) + require.NoError(t, s.Close()) + backup := dir + "-restore-backup-original" + require.NoError(t, os.Rename(dir, backup)) + extra := dir + "-restore-backup-ambiguous" + require.NoError(t, os.Mkdir(extra, dirPerms)) + _, err = NewPebbleStore(dir) + require.ErrorContains(t, err, "2 restore backups") + require.NoDirExists(t, dir) + require.DirExists(t, backup) + require.NoError(t, os.Remove(extra)) + reopened := openSSTSnapshotTestStore(t, dir) + reopenedLock, err := reopened.lifecycleLock.Stat() + require.NoError(t, err) + require.True(t, os.SameFile(originalLock, reopenedLock)) + idx, present := raftEntryAppliedIndex(t, reopened) + require.True(t, present) + require.EqualValues(t, 11, idx) + require.ErrorIs(t, s.Restore(bytes.NewReader(nil)), pebble.ErrClosed) +} + +func TestStoreCloseWithPinRetainsLifecycleLock(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + s := openSSTSnapshotTestStore(t, dir) + snap := captureOwnedForTest(t, s) + require.ErrorContains(t, s.Close(), "unreleased owned snapshot") + alias := filepath.Join(filepath.Dir(dir), "alias") + require.NoError(t, os.Symlink(dir, alias)) + _, err := NewPebbleStore(alias) + require.ErrorIs(t, err, fileutil.ErrLocked) + require.NoError(t, snap.Close()) + require.NoError(t, s.Close()) + openSSTSnapshotTestStore(t, alias) +} + +func TestStoreTerminalCloseErrorReleasesLifecycleLock(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + s := openSSTSnapshotTestStore(t, dir, WithSSTIngestSnapshots(false)) + ordinary, err := s.Snapshot() + require.NoError(t, err) + // Pebble reports a leaked ordinary snapshot after closing the DB. + // The owned-pin refusal above happens before entering Pebble Close. + require.ErrorContains(t, s.Close(), "leaked snapshots") + require.NoError(t, ordinary.Close()) + openSSTSnapshotTestStore(t, dir) +} + +func TestStoreMetadataOpenFailurePreservesRecovery(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + raw, err := pebble.Open(dir, &pebble.Options{}) + require.NoError(t, err) + require.NoError(t, raw.Set(migrationOwnershipMetaKeyBytes, []byte("malformed"), pebble.Sync)) + require.NoError(t, raw.Close()) + backup := dir + "-restore-backup-stale" + require.NoError(t, os.Mkdir(backup, dirPerms)) + _, err = NewPebbleStore(dir) + require.Error(t, err) + require.DirExists(t, backup) + raw, err = pebble.Open(dir, &pebble.Options{}) + require.NoError(t, err) + require.NoError(t, raw.Delete(migrationOwnershipMetaKeyBytes, pebble.Sync)) + require.NoError(t, raw.Close()) + openSSTSnapshotTestStore(t, dir) + require.NoDirExists(t, backup) +} diff --git a/store/snapshot_migration_metadata.go b/store/snapshot_migration_metadata.go index 94f76ce78..c0b0770d7 100644 --- a/store/snapshot_migration_metadata.go +++ b/store/snapshot_migration_metadata.go @@ -7,6 +7,17 @@ import ( "github.com/cockroachdb/pebble/v2" ) +func (s *pebbleStore) loadMigrationAndRetirementMetadata() ([]TargetStagedReadinessState, error) { + states, err := s.loadMigrationServingMetadata() + if err != nil { + return nil, err + } + if err := s.loadVersionRetirements(); err != nil { + return nil, err + } + return states, nil +} + func stageSnapshotServingMetadata(batch *pebble.Batch, meta streamingMVCCRestoreMetadata) error { if err := stageSnapshotOwnership(batch, meta.migrationOwnership); err != nil { return err diff --git a/store/snapshot_pebble_sst.go b/store/snapshot_pebble_sst.go index 97f68542c..ba7db1877 100644 --- a/store/snapshot_pebble_sst.go +++ b/store/snapshot_pebble_sst.go @@ -19,6 +19,7 @@ import ( "github.com/cockroachdb/errors" "github.com/cockroachdb/pebble/v2" + "github.com/cockroachdb/pebble/v2/objstorage" "github.com/cockroachdb/pebble/v2/objstorage/objstorageprovider" "github.com/cockroachdb/pebble/v2/sstable" "github.com/cockroachdb/pebble/v2/vfs" @@ -66,6 +67,7 @@ type pebbleSSTIngestFileMeta struct { } type pebbleSSTIngestSnapshot struct { + newWritable snapshotWritableConstructor checkpointDir string fallback *pebbleSnapshot metadata pebbleSnapshotMetadata @@ -82,8 +84,11 @@ type pebbleSSTIngestBundle struct { manifestJSON []byte } +type snapshotWritableConstructor func(vfs.File) objstorage.Writable + type pebbleSSTExporter struct { - db *pebble.DB + newWritable snapshotWritableConstructor + tableFormat sstable.TableFormat dir string manifest pebbleSSTIngestManifest writer *sstable.Writer @@ -106,13 +111,16 @@ func cleanupPebbleSnapshotArtifacts(dir string) error { clean := filepath.Clean(dir) parent := filepath.Dir(clean) base := filepath.Base(clean) - if err := recoverPebbleRestoreBackup(clean); err != nil { - return err + // The caller holds both the store lifecycle lock and the opened DB. + // Never sweep the recovery source if the live directory is missing. + if _, err := os.Stat(clean); err != nil { + return errors.WithStack(err) } prefixes := []string{ base + "-sst-checkpoint-", base + "-sst-ingest-", base + "-sst-receive-", + base + "-restore-backup-", } for _, prefix := range prefixes { matches, err := siblingPathsWithPrefix(parent, prefix) @@ -168,24 +176,10 @@ func recoverPebbleRestoreBackup(dir string) error { return nil } -func cleanupPebbleRestoreBackups(dir string) error { - clean := filepath.Clean(dir) - backups, err := siblingPathsWithPrefix(filepath.Dir(clean), filepath.Base(clean)+"-restore-backup-") - if err != nil { - return errors.WithStack(err) - } - for _, backup := range backups { - if err := os.RemoveAll(backup); err != nil { - return errors.Wrapf(err, "remove stale Pebble restore backup %s", backup) - } - } - return nil -} - func (s *pebbleStore) newSSTIngestSnapshot() (Snapshot, error) { // Checkpoint must represent the exact state visible when the Raft run loop // calls Snapshot. Block compaction/restore and all commit paths while the - // memtable is flushed and Pebble hard-links the stable checkpoint files. + // WAL is synced and Pebble copies it alongside stable checkpoint files. // applyMu comes before dbMu (see the lock ordering on pebbleStore): an // applier that holds applyMu across several dbMu sections, such as // ApplyRaftEntry, must never find this checkpoint holding dbMu while it @@ -208,14 +202,18 @@ func (s *pebbleStore) newSSTIngestSnapshot() (Snapshot, error) { return snap, nil } - if err := s.db.Flush(); err != nil { - return fallback(errors.Wrap(err, "flush pebble before SST checkpoint")) + // A checkpoint replays its copied WAL when opened for SST export. Forcing + // a memtable flush here would stall the Raft owner on unrelated SST I/O. + // Explicit LogData also rejects WAL-free stores, which need the legacy + // in-memory snapshot rather than an incomplete WAL-based checkpoint. + if err := s.db.LogData(nil, pebble.Sync); err != nil { + return fallback(errors.Wrap(err, "sync pebble WAL before SST checkpoint")) } checkpointDir, err := makeSiblingTempDir(s.dir, "sst-checkpoint") if err != nil { return fallback(err) } - if err := s.db.Checkpoint(checkpointDir, pebble.WithFlushedWAL()); err != nil { + if err := s.db.Checkpoint(checkpointDir); err != nil { _ = os.RemoveAll(checkpointDir) return fallback(errors.Wrap(err, "create pebble SST checkpoint")) } @@ -232,6 +230,7 @@ func (s *pebbleStore) newSSTIngestSnapshot() (Snapshot, error) { targetFileBytes = defaultSSTIngestTargetFileSize } return &pebbleSSTIngestSnapshot{ + newWritable: objstorageprovider.NewFileWritable, checkpointDir: checkpointDir, fallback: &pebbleSnapshot{ snapshot: pebbleSnap, @@ -303,7 +302,7 @@ func (s *pebbleSSTIngestSnapshot) WriteTo(w io.Writer) (int64, error) { if s == nil || s.fallback == nil { return 0, errors.New("snapshot is not available") } - bundle, err := buildPebbleSSTIngestBundle(s.checkpointDir, s.metadata, s.targetFileBytes, s.disableCompression) + bundle, err := buildPebbleSSTIngestBundle(s.checkpointDir, s.metadata, s.targetFileBytes, s.disableCompression, s.newWritable) if err != nil { if s.log != nil { s.log.Warn("failed to build SST ingest snapshot; using legacy stream", "error", err) @@ -333,7 +332,7 @@ func (s *pebbleSSTIngestSnapshot) Close() error { return errors.WithStack(s.err) } -func buildPebbleSSTIngestBundle(checkpointDir string, metadata pebbleSnapshotMetadata, targetFileBytes uint64, disableCompression bool) (*pebbleSSTIngestBundle, error) { +func buildPebbleSSTIngestBundle(checkpointDir string, metadata pebbleSnapshotMetadata, targetFileBytes uint64, disableCompression bool, newWritable snapshotWritableConstructor) (*pebbleSSTIngestBundle, error) { opts, cache := defaultPebbleOptionsWithCache(disableCompression) opts.ReadOnly = true db, err := pebble.Open(checkpointDir, opts) @@ -342,30 +341,34 @@ func buildPebbleSSTIngestBundle(checkpointDir string, metadata pebbleSnapshotMet return nil, errors.WithStack(err) } - exportDir, err := os.MkdirTemp(checkpointDir, "sst-export-") + bundle, err := buildSnapshotSSTs(db, db.TableFormat(), checkpointDir, "sst-export-", metadata, targetFileBytes, disableCompression, newWritable) + closeErr := db.Close() + cache.Unref() if err != nil { - _ = db.Close() - cache.Unref() - return nil, errors.WithStack(err) + return nil, err } - bundle := &pebbleSSTIngestBundle{dir: exportDir} - cleanup := func(err error) (*pebbleSSTIngestBundle, error) { - _ = db.Close() - cache.Unref() + if closeErr != nil { _ = bundle.Close() - return nil, err + return nil, errors.WithStack(closeErr) } + return bundle, nil +} - manifest, err := exportPebbleSnapshotSSTs(db, exportDir, metadata, targetFileBytes, disableCompression) +type pebbleSnapshotIterSource interface { + NewIter(*pebble.IterOptions) (*pebble.Iterator, error) +} + +func buildSnapshotSSTs(src pebbleSnapshotIterSource, format sstable.TableFormat, parent, pattern string, metadata pebbleSnapshotMetadata, targetFileBytes uint64, disableCompression bool, newWritable snapshotWritableConstructor) (*pebbleSSTIngestBundle, error) { + exportDir, err := os.MkdirTemp(parent, pattern) if err != nil { - return cleanup(err) + return nil, errors.WithStack(err) } - if err := db.Close(); err != nil { - cache.Unref() + bundle := &pebbleSSTIngestBundle{dir: exportDir} + manifest, err := exportPebbleSnapshotSSTs(src, format, exportDir, metadata, targetFileBytes, disableCompression, newWritable) + if err != nil { _ = bundle.Close() return nil, errors.WithStack(err) } - cache.Unref() manifestJSON, err := json.Marshal(manifest) if err != nil { @@ -381,12 +384,13 @@ func buildPebbleSSTIngestBundle(checkpointDir string, metadata pebbleSnapshotMet return bundle, nil } -func exportPebbleSnapshotSSTs(db *pebble.DB, exportDir string, metadata pebbleSnapshotMetadata, targetFileBytes uint64, disableCompression bool) (pebbleSSTIngestManifest, error) { +func exportPebbleSnapshotSSTs(src pebbleSnapshotIterSource, format sstable.TableFormat, exportDir string, metadata pebbleSnapshotMetadata, targetFileBytes uint64, disableCompression bool, newWritable snapshotWritableConstructor) (pebbleSSTIngestManifest, error) { if targetFileBytes == 0 { targetFileBytes = defaultSSTIngestTargetFileSize } exporter := pebbleSSTExporter{ - db: db, + newWritable: newWritable, + tableFormat: format, dir: exportDir, targetFileBytes: targetFileBytes, compression: sstExportCompression(disableCompression), @@ -402,7 +406,7 @@ func exportPebbleSnapshotSSTs(db *pebble.DB, exportDir string, metadata pebbleSn exporter.manifest.AppliedIndex = &applied } - iter, err := db.NewIter(nil) + iter, err := src.NewIter(nil) if err != nil { return exporter.manifest, errors.WithStack(err) } @@ -473,9 +477,9 @@ func (e *pebbleSSTExporter) startFile(firstKey []byte) error { if err != nil { return errors.WithStack(err) } - e.writer = sstable.NewWriter(objstorageprovider.NewFileWritable(file), sstable.WriterOptions{ + e.writer = sstable.NewWriter(e.newWritable(file), sstable.WriterOptions{ Comparer: pebble.DefaultComparer, - TableFormat: e.db.TableFormat(), + TableFormat: e.tableFormat, Compression: e.compression, }) e.currentBytes = 0 @@ -488,10 +492,11 @@ func (e *pebbleSSTExporter) finishFile() error { if e.writer == nil { return nil } - if err := e.writer.Close(); err != nil { + writer := e.writer + e.writer = nil // Close consumes the writer even when Finish fails. + if err := writer.Close(); err != nil { return errors.WithStack(err) } - e.writer = nil fileMeta, err := inspectSSTIngestFile(e.currentPath, e.currentName, e.smallest, e.largest) if err != nil { return err diff --git a/store/snapshot_pebble_sst_test.go b/store/snapshot_pebble_sst_test.go index ff23ae88a..13b19cbd1 100644 --- a/store/snapshot_pebble_sst_test.go +++ b/store/snapshot_pebble_sst_test.go @@ -91,6 +91,8 @@ func TestPebbleStoreSSTIngestSnapshotRoundTrip(t *testing.T) { sstSnapshot, ok := snapshot.(*pebbleSSTIngestSnapshot) require.True(t, ok) checkpointDir := sstSnapshot.checkpointDir + var scratch snapshotScratchFiles + sstSnapshot.newWritable = scratch.record(sstSnapshot.newWritable) require.DirExists(t, checkpointDir) // This write happens after the checkpoint and must not leak into the image. @@ -103,7 +105,10 @@ func TestPebbleStoreSSTIngestSnapshotRoundTrip(t *testing.T) { reader := bytes.NewReader(raw.Bytes()) manifest, err := readPebbleSSTIngestManifest(reader) require.NoError(t, err) - require.Greater(t, len(manifest.Files), 1) + scratch.requireFinished(t, manifest, 1) + exports, err := filepath.Glob(filepath.Join(checkpointDir, "sst-export-*")) + require.NoError(t, err) + require.Empty(t, exports) require.GreaterOrEqual(t, manifest.EntryCount, uint64(4)) require.NotNil(t, manifest.AppliedIndex) require.Equal(t, uint64(77), *manifest.AppliedIndex) diff --git a/store/snapshot_pebble_sst_wal_test.go b/store/snapshot_pebble_sst_wal_test.go new file mode 100644 index 000000000..f590a33ce --- /dev/null +++ b/store/snapshot_pebble_sst_wal_test.go @@ -0,0 +1,194 @@ +package store + +import ( + "bytes" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2" + "github.com/cockroachdb/pebble/v2/vfs" + "github.com/stretchr/testify/require" +) + +type pausedSSTCreateFS struct { + vfs.FS + armed atomic.Bool + once sync.Once + entered chan struct{} + release chan struct{} +} + +func (fs *pausedSSTCreateFS) Create(name string, category vfs.DiskWriteCategory) (vfs.File, error) { + if fs.armed.Load() && strings.HasSuffix(name, ".sst") { + fs.once.Do(func() { close(fs.entered) }) + <-fs.release + } + file, err := fs.FS.Create(name, category) + return file, errors.WithStack(err) +} + +func TestSSTCheckpointDoesNotWaitForBlockedSSTFlush(t *testing.T) { + setPebbleCacheBytesForTest(t, 8<<20) + dir := t.TempDir() + fs := &pausedSSTCreateFS{FS: vfs.Default, entered: make(chan struct{}), release: make(chan struct{})} + opts, cache := defaultPebbleOptionsWithCache(false) + opts.FS = fs + db, err := pebble.Open(dir, opts) + require.NoError(t, err) + src := &pebbleStore{db: db, cache: cache, dir: dir, fsmApplyWriteOpts: pebble.Sync, sstIngestSnapshots: true} + t.Cleanup(func() { require.NoError(t, src.Close()) }) + var once sync.Once + release := func() { once.Do(func() { close(fs.release) }) } + t.Cleanup(release) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "captured"), nil, 10, 10, 7)) + fs.armed.Store(true) + flushed := make(chan error, 1) + go func() { flushed <- db.Flush() }() + select { + case <-fs.entered: + case err := <-flushed: + t.Fatalf("flush returned without reaching SST creation: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("flush did not reach SST creation") + } + type captureResult struct { + snapshot Snapshot + err error + } + captured := make(chan captureResult, 1) + go func() { + snapshot, err := src.Snapshot() + captured <- captureResult{snapshot: snapshot, err: err} + }() + var result captureResult + blocked := false + select { + case result = <-captured: + case <-time.After(time.Second): + blocked = true + t.Error("snapshot capture waited for unrelated SST I/O") + } + release() + require.NoError(t, <-flushed) + if blocked { + result = <-captured + } + require.NoError(t, result.err) + t.Cleanup(func() { require.NoError(t, result.snapshot.Close()) }) + var raw bytes.Buffer + _, err = result.snapshot.WriteTo(&raw) + require.NoError(t, err) + require.Equal(t, pebbleSSTIngestSnapshotMagic[:], raw.Bytes()[:len(pebbleSSTIngestSnapshotMagic)]) + dst := openSSTSnapshotTestStore(t, filepath.Join(t.TempDir(), "dst")) + require.NoError(t, dst.Restore(bytes.NewReader(raw.Bytes()))) + value, err := dst.GetVersionAt(t.Context(), []byte("key"), 100) + require.NoError(t, err) + require.Equal(t, uint64(10), value.TS) + require.Equal(t, "captured", string(value.Value)) +} + +func TestSSTCheckpointSyncsWALWithoutFlushingMemtable(t *testing.T) { + setPebbleCacheBytesForTest(t, 8<<20) + src, fs, release := newRaftDataWALSyncStore(t) + src.sstIngestSnapshots = true + src.fsmApplyWriteOpts = pebble.NoSync + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "old"), nil, 5, 5, 6)) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "captured"), nil, 10, 10, 7)) + before := src.db.Metrics().Flush.Count + require.Zero(t, before) + fs.armed.Store(true) + type captureResult struct { + snapshot Snapshot + err error + } + captured := make(chan captureResult, 1) + go func() { + snapshot, err := src.Snapshot() + captured <- captureResult{snapshot: snapshot, err: err} + }() + select { + case <-fs.entered: + case result := <-captured: + if result.snapshot != nil { + _ = result.snapshot.Close() + } + t.Fatalf("checkpoint returned before syncing the WAL: %v", result.err) + case <-time.After(5 * time.Second): + t.Fatal("checkpoint did not reach the WAL sync") + } + select { + case result := <-captured: + if result.snapshot != nil { + _ = result.snapshot.Close() + } + t.Fatalf("checkpoint acknowledged an unfinished WAL sync: %v", result.err) + default: + } + release() + result := <-captured + require.NoError(t, result.err) + t.Cleanup(func() { require.NoError(t, result.snapshot.Close()) }) + require.Equal(t, before, src.db.Metrics().Flush.Count, "capture must not wait for a memtable-to-SST flush") + snapshot, ok := result.snapshot.(*pebbleSSTIngestSnapshot) + require.True(t, ok) + logs, err := filepath.Glob(filepath.Join(snapshot.checkpointDir, "*.log")) + require.NoError(t, err) + require.NotEmpty(t, logs) + tables, err := filepath.Glob(filepath.Join(snapshot.checkpointDir, "*.sst")) + require.NoError(t, err) + require.Empty(t, tables, "this fixture must recover the captured cut from WAL only") + + // Recycle live WAL state and compact later versions before exporting the + // independent checkpoint. Neither later data nor progress may leak back. + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "later"), nil, 20, 20, 8)) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("late", "excluded"), nil, 30, 30, 9)) + require.NoError(t, src.db.Flush()) + require.NoError(t, src.db.Compact(t.Context(), []byte{0}, []byte{255}, true)) + var raw bytes.Buffer + _, err = snapshot.WriteTo(&raw) + require.NoError(t, err) + require.Equal(t, pebbleSSTIngestSnapshotMagic[:], raw.Bytes()[:len(pebbleSSTIngestSnapshotMagic)], "WAL replay must not silently fall back") + dst := openSSTSnapshotTestStore(t, filepath.Join(t.TempDir(), "dst")) + require.NoError(t, dst.Restore(bytes.NewReader(raw.Bytes()))) + latest, err := dst.GetVersionAt(t.Context(), []byte("key"), 100) + require.NoError(t, err) + require.Equal(t, uint64(10), latest.TS) + require.Equal(t, "captured", string(latest.Value)) + historical, err := dst.GetVersionAt(t.Context(), []byte("key"), 5) + require.NoError(t, err) + require.Equal(t, "old", string(historical.Value)) + _, err = dst.GetAt(t.Context(), []byte("late"), 100) + require.ErrorIs(t, err, ErrKeyNotFound) + require.Equal(t, uint64(10), dst.LastCommitTS()) + index, found, err := dst.LastAppliedIndex() + require.NoError(t, err) + require.True(t, found) + require.Equal(t, uint64(7), index) +} + +func TestSSTCheckpointWithoutWALRetainsLegacySnapshot(t *testing.T) { + dir := t.TempDir() + db, err := pebble.Open(dir, &pebble.Options{DisableWAL: true}) + require.NoError(t, err) + src := &pebbleStore{db: db, dir: dir, fsmApplyWriteOpts: pebble.NoSync, sstIngestSnapshots: true} + t.Cleanup(func() { require.NoError(t, db.Close()) }) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("key", "value"), nil, 10, 10, 7)) + snapshot, err := src.Snapshot() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, snapshot.Close()) }) + require.IsType(t, &pebbleSnapshot{}, snapshot, "WAL-free stores cannot use the WAL checkpoint guarantee") + var raw bytes.Buffer + _, err = snapshot.WriteTo(&raw) + require.NoError(t, err) + dst := openSSTSnapshotTestStore(t, filepath.Join(t.TempDir(), "dst")) + require.NoError(t, dst.Restore(bytes.NewReader(raw.Bytes()))) + value, err := dst.GetVersionAt(t.Context(), []byte("key"), 100) + require.NoError(t, err) + require.Equal(t, uint64(10), value.TS) + require.Equal(t, "value", string(value.Value)) +} diff --git a/store/snapshot_source_fence_test.go b/store/snapshot_source_fence_test.go new file mode 100644 index 000000000..0b8e75f3a --- /dev/null +++ b/store/snapshot_source_fence_test.go @@ -0,0 +1,128 @@ +package store + +import ( + "errors" + "os" + "os/exec" + "strings" + "sync/atomic" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/cockroachdb/pebble/v2/vfs" + "github.com/cockroachdb/pebble/v2/vfs/errorfs" + "github.com/stretchr/testify/require" +) + +func openFenceDB(t *testing.T, dir string, opts *pebble.Options, writes *pebble.WriteOptions) *pebbleStore { + t.Helper() + db, err := pebble.Open(dir, opts) + require.NoError(t, err) + s := &pebbleStore{db: db, dir: dir, fsmApplyWriteOpts: writes} + t.Cleanup(func() { require.NoError(t, s.Close()) }) + return s +} + +func TestSnapshotSourceFenceWaitsForWAL(t *testing.T) { + for _, mode := range []string{"sync", "nosync"} { + for name, request := range map[string]uint64{"equal": 11, "ahead": 10} { + t.Run(mode+"/"+name, func(t *testing.T) { + disk := vfs.NewCrashableMem() + gate := &controlSyncFS{FS: disk, entered: make(chan struct{}), release: make(chan struct{})} + writes, _ := resolveFSMApplyWriteOpts(mode) + src := openFenceDB(t, "db", &pebble.Options{FS: gate}, writes) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("row", "one"), nil, 1, 2, 11)) + gate.armed.Store(true) + done := make(chan error, 1) + go func() { done <- src.SetDurableAppliedIndex(request) }() + select { + case err := <-done: + close(gate.release) + t.Fatalf("fence returned before WAL sync: %v", err) + case <-gate.entered: + } + select { + case err := <-done: + close(gate.release) + t.Fatalf("fence returned during blocked WAL sync: %v", err) + default: + } + close(gate.release) + require.NoError(t, <-done) + + // Reopen only the synced filesystem image, before closing the source. + recovered := openFenceDB(t, "db", &pebble.Options{FS: disk.CrashClone(vfs.CrashCloneCfg{}), ErrorIfNotExists: true}, writes) + idx, present := raftEntryAppliedIndex(t, recovered) + require.True(t, present) + require.EqualValues(t, 11, idx) + value, err := recovered.GetAt(t.Context(), []byte("row"), 2) + require.NoError(t, err) + require.Equal(t, "one", string(value)) + }) + } + } +} + +func TestSnapshotSourceFenceRejectsDisabledWAL(t *testing.T) { + src := openFenceDB(t, t.TempDir(), &pebble.Options{DisableWAL: true}, pebble.NoSync) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("row", "one"), nil, 1, 2, 11)) + for _, request := range []uint64{10, 11, 12} { + require.ErrorContains(t, src.SetDurableAppliedIndex(request), "WAL disabled") + idx, present := raftEntryAppliedIndex(t, src) + require.True(t, present) + require.EqualValues(t, 11, idx) + } +} + +func TestSnapshotSourceFenceWALFailure(t *testing.T) { + const phaseEnv = "ELASTICKV_TEST_SNAPSHOT_FENCE_FAILURE" + const failure = "injected snapshot source WAL sync error" + if phase := os.Getenv(phaseEnv); phase != "" { + var armed atomic.Bool + fs := errorfs.Wrap(vfs.Default, errorfs.InjectorFunc(func(op errorfs.Op) error { + if armed.Load() && strings.HasSuffix(op.Path, ".log") && (op.Kind == errorfs.OpFileSync || op.Kind == errorfs.OpFileSyncData) { + return errors.New(failure) + } + return nil + })) + src := openFenceDB(t, ".", &pebble.Options{FS: fs}, pebble.NoSync) + require.NoError(t, src.ApplyMutationsRaftAt(t.Context(), raftEntryPut("row", "one"), nil, 1, 2, 11)) + armed.Store(true) + idx := uint64(11) + if phase == "ahead" { + idx-- + } + err := src.SetDurableAppliedIndex(idx) + armed.Store(false) + t.Fatalf("fence returned from fatal WAL failure: %v", err) + } + for _, phase := range []string{"equal", "ahead"} { + t.Run(phase, func(t *testing.T) { + executable, err := os.Executable() + require.NoError(t, err) + cmd := exec.CommandContext(t.Context(), executable, "-test.run=^TestSnapshotSourceFenceWALFailure$") + cmd.Dir = t.TempDir() + cmd.Env = append(os.Environ(), phaseEnv+"="+phase) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + require.ErrorAs(t, err, &exit) + require.Equal(t, 1, exit.ExitCode()) + require.Contains(t, string(out), failure) + require.NotContains(t, string(out), "fence returned") + }) + } +} + +func BenchmarkSnapshotSourceFenceEqual(b *testing.B) { + st, err := NewPebbleStore(b.TempDir()) + require.NoError(b, err) + defer func() { require.NoError(b, st.Close()) }() + s, ok := st.(*pebbleStore) + require.True(b, ok) + require.NoError(b, s.SetDurableAppliedIndex(11)) + for b.Loop() { + if err := s.SetDurableAppliedIndex(11); err != nil { + b.Fatal(err) + } + } +} diff --git a/store/snapshot_transient_writable.go b/store/snapshot_transient_writable.go new file mode 100644 index 000000000..85e3f5df0 --- /dev/null +++ b/store/snapshot_transient_writable.go @@ -0,0 +1,27 @@ +package store + +import ( + "io" + + "github.com/cockroachdb/pebble/v2/objstorage" + "github.com/cockroachdb/pebble/v2/objstorage/objstorageprovider" + "github.com/cockroachdb/pebble/v2/vfs" +) + +// The owned exporter reopens this private scratch file to hash and stream it. +// Recovery uses the separately persisted snapshot and never reads this file. +func newTransientSnapshotWritable(file vfs.File) objstorage.Writable { + return objstorageprovider.NewFileWritable(transientSnapshotFile{file}) +} + +type transientSnapshotFile struct{ vfs.File } + +func (transientSnapshotFile) Sync() error { return nil } + +func (f transientSnapshotFile) Write(p []byte) (int, error) { + n, err := f.File.Write(p) + if n < len(p) && err == nil { + err = io.ErrShortWrite + } + return n, err +} diff --git a/store/snapshot_transient_writable_test.go b/store/snapshot_transient_writable_test.go new file mode 100644 index 000000000..65fd2d172 --- /dev/null +++ b/store/snapshot_transient_writable_test.go @@ -0,0 +1,219 @@ +package store + +import ( + "bytes" + "errors" + "io" + "os" + "testing" + + "github.com/cockroachdb/pebble/v2/objstorage" + "github.com/cockroachdb/pebble/v2/objstorage/objstorageprovider" + "github.com/cockroachdb/pebble/v2/vfs" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Observe the file below the constructor selected by the real snapshot handle. +type snapshotScratchFile struct { + vfs.File + writes, syncs, closes int + write func([]byte) (int, error) + closeErr error +} + +func (f *snapshotScratchFile) Write(p []byte) (int, error) { + f.writes++ + if f.write != nil { + return f.write(p) + } + return f.File.Write(p) +} + +func (f *snapshotScratchFile) Sync() error { + f.syncs++ + return f.File.Sync() +} + +func (f *snapshotScratchFile) Close() error { + f.closes++ + if err := f.File.Close(); err != nil { + return err + } + return f.closeErr +} + +type snapshotScratchFiles []*snapshotScratchFile + +func (files *snapshotScratchFiles) record(next snapshotWritableConstructor) snapshotWritableConstructor { + return func(file vfs.File) objstorage.Writable { + f := &snapshotScratchFile{File: file} + *files = append(*files, f) + return next(f) + } +} + +func (files snapshotScratchFiles) requireFinished(t *testing.T, manifest pebbleSSTIngestManifest, syncsPerFile int) { + t.Helper() + require.Greater(t, len(manifest.Files), 1) + require.Len(t, files, len(manifest.Files)) + for i, f := range files { + require.Positive(t, f.writes) + require.Equal(t, 1, f.closes) + assert.Equal(t, syncsPerFile, f.syncs, manifest.Files[i].Name) + } +} + +func createSnapshotScratchFile(t *testing.T, fs vfs.FS, name string) *snapshotScratchFile { + t.Helper() + f, err := fs.Create(name, vfs.WriteCategoryUnspecified) + require.NoError(t, err) + return &snapshotScratchFile{File: f} +} + +func readSnapshotScratchFile(t *testing.T, fs vfs.FS, name string) []byte { + t.Helper() + f, err := fs.Open(name) + require.NoError(t, err) + defer func() { require.NoError(t, f.Close()) }() + b, err := io.ReadAll(f) + require.NoError(t, err) + return b +} + +func TestTransientSnapshotWritableFinish(t *testing.T) { + for _, tc := range []struct { + name string + size int + directWrites int + }{ + {"buffered", 8, 0}, + {"direct", 64 << 10, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + fs := vfs.NewMem() + f := createSnapshotScratchFile(t, fs, "scratch") + w := newTransientSnapshotWritable(f) + want := bytes.Repeat([]byte{'x'}, tc.size) + require.NoError(t, w.Write(bytes.Clone(want))) + require.Equal(t, tc.directWrites, f.writes) + require.NoError(t, w.Finish()) + require.Equal(t, 1, f.writes) + require.Zero(t, f.syncs) + require.Equal(t, 1, f.closes) + require.Equal(t, want, readSnapshotScratchFile(t, fs, "scratch")) + }) + } +} + +func TestTransientSnapshotWritableErrors(t *testing.T) { + writeErr := errors.New("scratch write") + closeErr := errors.New("scratch close") + for _, tc := range []struct { + name string + direct bool + shortBy int + writeErr error + closeErr error + wantErr error + }{ + {name: "short direct", direct: true, shortBy: 1, wantErr: io.ErrShortWrite}, + {name: "zero direct", direct: true, shortBy: 64 << 10, wantErr: io.ErrShortWrite}, + {name: "short flush", shortBy: 1, wantErr: io.ErrShortWrite}, + {name: "write before close", direct: true, writeErr: writeErr, closeErr: closeErr, wantErr: writeErr}, + {name: "flush", writeErr: writeErr, wantErr: writeErr}, + {name: "flush before close", writeErr: writeErr, closeErr: closeErr, wantErr: writeErr}, + {name: "close", closeErr: closeErr, wantErr: closeErr}, + } { + t.Run(tc.name, func(t *testing.T) { + f := createSnapshotScratchFile(t, vfs.NewMem(), "scratch") + f.closeErr = tc.closeErr + f.write = func(p []byte) (int, error) { + // Fail promptly even if a zero-progress write is incorrectly retried. + if f.writes > 1 { + return 0, errors.New("unexpected retry") + } + if tc.writeErr != nil { + return 0, tc.writeErr + } + return len(p) - tc.shortBy, nil + } + w := newTransientSnapshotWritable(f) + if tc.direct { + require.ErrorIs(t, w.Write(make([]byte, 64<<10)), tc.wantErr) + require.ErrorIs(t, w.Write([]byte("again")), tc.wantErr) + } else { + require.NoError(t, w.Write([]byte("buffered"))) + require.Zero(t, f.writes) + } + require.ErrorIs(t, w.Finish(), tc.wantErr) + require.Equal(t, 1, f.writes) + require.Zero(t, f.syncs) + require.Equal(t, 1, f.closes) + }) + } +} + +func TestTransientSnapshotWritableAbort(t *testing.T) { + fs := vfs.NewMem() + f := createSnapshotScratchFile(t, fs, "scratch") + f.closeErr = errors.New("discarded close error") + w := newTransientSnapshotWritable(f) + require.NoError(t, w.Write([]byte("buffered"))) + w.Abort() + require.Zero(t, f.writes) + require.Zero(t, f.syncs) + require.Equal(t, 1, f.closes) + require.Empty(t, readSnapshotScratchFile(t, fs, "scratch")) +} + +func TestTransientSnapshotWritableCrashLoss(t *testing.T) { + fs := vfs.NewCrashableMem() + want := []byte("finished SST scratch bytes") + for name, constructor := range map[string]snapshotWritableConstructor{ + "transient": newTransientSnapshotWritable, + "ordinary": objstorageprovider.NewFileWritable, + } { + w := constructor(createSnapshotScratchFile(t, fs, name)) + require.NoError(t, w.Write(bytes.Clone(want))) + require.NoError(t, w.Finish()) + require.Equal(t, want, readSnapshotScratchFile(t, fs, name)) + } + // Persist both names to isolate scratch content loss from name loss. + // This VFS does not model the outer FSM file's OS directory durability. + dir, err := fs.OpenDir(".") + require.NoError(t, err) + require.NoError(t, dir.Sync()) + require.NoError(t, dir.Close()) + crashed := fs.CrashClone(vfs.CrashCloneCfg{}) + require.Empty(t, readSnapshotScratchFile(t, crashed, "transient")) + require.Equal(t, want, readSnapshotScratchFile(t, crashed, "ordinary")) +} + +func TestSnapshotSSTBuilderFailedFinish(t *testing.T) { + src := openSSTSnapshotTestStore(t, t.TempDir(), WithSSTIngestSnapshots(true)) + writeSSTSnapshotTestData(t, src) + snap, ok := captureOwnedForTest(t, src).(*ownedPebbleSnapshot) + require.True(t, ok) + metadata, err := readPebbleSnapshotMetadata(snap.pin) + require.NoError(t, err) + parent := t.TempDir() + closeErr := errors.New("failed scratch close") + var files snapshotScratchFiles + record := files.record(snap.newWritable) + failClose := func(file vfs.File) objstorage.Writable { + w := record(file) + files[len(files)-1].closeErr = closeErr + return w + } + // A large target leaves one real SST writer open for the final Finish. + bundle, err := buildSnapshotSSTs(snap.pin, snap.format, parent, "export-", metadata, 1<<20, false, failClose) + require.ErrorIs(t, err, closeErr) + require.Nil(t, bundle) + require.Len(t, files, 1) + require.Positive(t, files[0].writes) + require.Equal(t, 1, files[0].closes) + entries, err := os.ReadDir(parent) + require.NoError(t, err) + require.Empty(t, entries) +} diff --git a/store/store.go b/store/store.go index 8dbc689d3..527c04934 100644 --- a/store/store.go +++ b/store/store.go @@ -97,12 +97,13 @@ type PrefixDelete struct { // MVCCVersion is a raw committed MVCC version for range migration. // Unlike scan results, it preserves tombstones and TTL expiry metadata. type MVCCVersion struct { - Key []byte - CommitTS uint64 - Tombstone bool - Value []byte - KeyFamily uint32 - ExpireAt uint64 + Key []byte + CommitTS uint64 + Tombstone bool + Value []byte + KeyFamily uint32 + ExpireAt uint64 + adoptionEpoch uint64 } // ExportVersionsOptions selects a raw MVCC-version export window. @@ -120,6 +121,9 @@ type ExportVersionsOptions struct { KeyFamily uint32 AcceptKey func([]byte) bool AcceptVersion func(key []byte, value []byte) bool + includeRetired bool + retirement *versionRetirementState + reclamation *versionRetirementReclamation } // ExportVersionsResult is one resumable chunk of raw MVCC versions. @@ -146,6 +150,13 @@ type ImportVersionsOptions struct { BatchSeq uint64 Versions []MVCCVersion Cursor []byte + // LogicalKey maps a staged key to the public key whose version it carries. + LogicalKey func([]byte) []byte + // Only the typed migration FSM may stage retired versions privately. + AllowRetiredStaging bool + // AllowLegacyVersionOverwrite preserves replay of migration entries that + // preceded replicated version identity protection. + AllowLegacyVersionOverwrite bool } // ImportVersionsResult reports the cursor durably acknowledged by the target. @@ -158,8 +169,9 @@ type ImportVersionsResult struct { // PromoteVersionsOptions atomically copies staged MVCC versions to their // target keys and physically removes the staged versions. type PromoteVersionsOptions struct { - OnlineGuard *OnlineMaintenanceGuard - JobID uint64 + AdoptionAuthority func(MVCCVersion, VersionRetirement) error + OnlineGuard *OnlineMaintenanceGuard + JobID uint64 // AppliedIndex is the optional Raft entry index to bundle with Pebble // promotion batches as metaAppliedIndex. Zero leaves the meta key unchanged. AppliedIndex uint64 @@ -170,6 +182,9 @@ type PromoteVersionsOptions struct { MaxBytes uint64 MaxScannedBytes uint64 TargetKey func(stagedKey []byte) ([]byte, bool) + // AllowLegacyVersionOverwrite preserves replay of migration entries that + // preceded replicated version identity protection. + AllowLegacyVersionOverwrite bool } // PromoteVersionsResult reports one resumable staged-version promotion chunk. @@ -196,6 +211,7 @@ type PromotionState struct { // by the migration bracket filter. It is cursor-resumable and is used only // after ownership has moved or while abandoning an unpublished migration. type CleanupVersionsOptions struct { + Retirement *VersionRetirement OnlineGuard *OnlineMaintenanceGuard JobID uint64 AppliedIndex uint64 @@ -212,6 +228,7 @@ type CleanupVersionsOptions struct { // CleanupVersionsResult reports one bounded physical-delete chunk. type CleanupVersionsResult struct { + RetirementID string NextCursor []byte Done bool DeletedRows uint64 @@ -329,12 +346,36 @@ type Snapshot interface { io.Closer } +// OwnerSnapshotCapturer can pin a view while the Raft owner is at an applied +// cut. The owner must successfully close the handle before Restore or Close +// of the source store, including when it abandons an unmaterialized capture. +type OwnerSnapshotCapturer interface { + CaptureOwnerSnapshot() (Snapshot, error) +} + // VersionPresenceReader reports whether a key has any committed version at or // before a read timestamp, including tombstones and expired values. type VersionPresenceReader interface { VersionExistsAtOrBefore(ctx context.Context, key []byte, ts uint64) (bool, error) } +// VersionedValueReader reads a live record and its commit timestamp together. +type VersionedValueReader interface { + GetVersionAt(ctx context.Context, key []byte, ts uint64) (VersionedValue, error) +} + +// GetVersionAt returns the live record visible at ts. A local engine also +// returns its absolute expiry. Missing, expired and deleted records return +// ErrKeyNotFound. +func GetVersionAt(ctx context.Context, st MVCCStore, key []byte, ts uint64) (VersionedValue, error) { + reader, ok := st.(VersionedValueReader) + if !ok { + return VersionedValue{}, ErrNotSupported + } + record, err := reader.GetVersionAt(ctx, key, ts) + return record, errors.WithStack(err) +} + // MVCCStore extends Store with multi-version concurrency control helpers. // The interface is timestamp-explicit; callers must supply the snapshot or // commit timestamp for every operation. diff --git a/store/txn_decision_gc_test.go b/store/txn_decision_gc_test.go index 824fbf2bb..6d86ccf12 100644 --- a/store/txn_decision_gc_test.go +++ b/store/txn_decision_gc_test.go @@ -100,10 +100,7 @@ func txnDecisionGCDiskTrial(t *testing.T, reclaim bool) txnDecisionGCDiskReport const count, start, decision, reserved = 2048, 100, 200, 201 ctx := t.Context() dir := filepath.Join(t.TempDir(), "pebble") - opened, err := NewPebbleStore(dir) - require.NoError(t, err) - st, ok := opened.(*pebbleStore) - require.True(t, ok) + st := openInternalRecordTrial(t, dir) rows := make([]*KVPairMutation, 0, count+1) for i := range count { @@ -125,7 +122,7 @@ func txnDecisionGCDiskTrial(t *testing.T, reclaim bool) txnDecisionGCDiskReport } compactInternalRecordTrial(t, st) require.NoError(t, st.Close()) - report := txnDecisionGCDiskReport{compacted: measureInternalRecordTrial(t, dir)} + report := txnDecisionGCDiskReport{compacted: measureInternalRecordTrial(t, st)} reopened, err := NewPebbleStore(dir) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, reopened.Close()) }) @@ -135,25 +132,34 @@ func txnDecisionGCDiskTrial(t *testing.T, reclaim bool) txnDecisionGCDiskReport if reclaim { _, err := reopened.GetAt(ctx, rows[count-1].Key, math.MaxUint64) require.ErrorIs(t, err, ErrTxnDecisionRetired) + _, err = GetVersionAt(ctx, reopened, rows[count-1].Key, math.MaxUint64) + require.ErrorIs(t, err, ErrTxnDecisionRetired) } _, err = reopened.GetAt(ctx, keep, math.MaxUint64) require.NoError(t, err) value, err := reopened.GetAt(ctx, []byte("live"), math.MaxUint64) require.NoError(t, err) require.Equal(t, []byte("value"), value) + version, err := GetVersionAt(ctx, reopened, []byte("live"), math.MaxUint64) + require.NoError(t, err) + require.Equal(t, []byte("value"), version.Value) + require.EqualValues(t, decision, version.TS) reopenedPebble, ok := reopened.(*pebbleStore) require.True(t, ok) // A flush can finish before obsolete SST files have been removed. - // Drive the same full-range compactions in both arms, then wait until - // the directory reflects the live table set reported by Pebble. + // Drive the same full-range compactions in both arms. for range 3 { compactInternalRecordTrial(t, reopenedPebble) } require.EventuallyWithT(t, func(c *assert.CollectT) { - report.reopened = measureInternalRecordTrial(t, dir) - live := reopenedPebble.db.Metrics().Total().TablesSize - require.EqualValues(c, live, report.reopened.SST) + m := reopenedPebble.db.Metrics() + require.Zero(c, m.Compact.NumInProgress) + require.Zero(c, m.Table.ObsoleteSize) }, 5*time.Second, 25*time.Millisecond) + live := reopenedPebble.db.Metrics().Total().TablesSize + require.NoError(t, reopenedPebble.Close()) + report.reopened = measureInternalRecordTrial(t, reopenedPebble) + require.EqualValues(t, live, report.reopened.SST) return report } diff --git a/store/version_adoption.go b/store/version_adoption.go new file mode 100644 index 000000000..f452a04cb --- /dev/null +++ b/store/version_adoption.go @@ -0,0 +1,162 @@ +package store + +import ( + "context" + "encoding/binary" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2" +) + +const versionAdoptionMetadataKey = "version-adoption/v1" +const versionAdoptionSchema byte = 1 + +func (s *pebbleStore) VersionAdoptionReady(ctx context.Context) error { + s.dbMu.RLock() + defer s.dbMu.RUnlock() + if s.versionRetirementFor(ctx).adoptionEpoch == 0 { + return errors.WithStack(ErrVersionRetirementUnavailable) + } + return nil +} + +func (s *mvccStore) VersionAdoptionReady(ctx context.Context) error { + if staged := s.memoryEntryStore(ctx); staged != nil { + return staged.VersionAdoptionReady(ctx) + } + s.mtx.RLock() + defer s.mtx.RUnlock() + if s.versionRetirement.adoptionEpoch == 0 { + return errors.WithStack(ErrVersionRetirementUnavailable) + } + return nil +} + +func snapshotVersionAdoptionEpoch(formatVersion uint32, control map[string][]byte) (uint64, error) { + epoch, err := decodeVersionAdoptionEpoch(control[versionAdoptionMetadataKey]) + if err != nil { + return 0, err + } + if (formatVersion >= mvccSnapshotVersionV9) != (epoch != 0) { + return 0, errors.WithStack(ErrVersionRetirementUnavailable) + } + return epoch, nil +} + +func encodeVersionAdoptionEpoch(epoch uint64) []byte { + return binary.BigEndian.AppendUint64([]byte{versionAdoptionSchema}, epoch) +} + +func decodeVersionAdoptionEpoch(data []byte) (uint64, error) { + if len(data) == 0 { + return 0, nil + } + if len(data) != 1+timestampSize || data[0] != versionAdoptionSchema { + return 0, errors.WithStack(ErrVersionRetirementUnavailable) + } + epoch := binary.BigEndian.Uint64(data[1:]) + if epoch == 0 { + return 0, errors.WithStack(ErrVersionRetirementConflict) + } + return epoch, nil +} + +func nextVersionAdoptionEpoch(epoch uint64) (uint64, error) { + if epoch == 0 || epoch == ^uint64(0) { + return 0, errors.WithStack(ErrValueTooLarge) + } + return epoch + 1, nil +} + +func prepareVersionRetirementEpoch(state versionRetirementState, record VersionRetirement) (versionRetirementState, VersionRetirement, error) { + for _, existing := range state.records { + if existing.record.ID == record.ID { + if record.Epoch == 0 { + record.Epoch = existing.record.Epoch + } + return state, record, nil + } + } + if record.Epoch != 0 { + return state, record, errors.WithStack(ErrVersionRetirementConflict) + } + if state.adoptionEpoch != 0 { + epoch, err := nextVersionAdoptionEpoch(state.adoptionEpoch) + if err != nil { + return state, record, err + } + state.adoptionEpoch, record.Epoch = epoch, epoch + } + return state, record, nil +} + +func stageVersionAdoptionEpoch(ctx context.Context, metadata RaftControlMetadataStore, epoch uint64) error { + if epoch == 0 { + return nil + } + ctx = context.WithValue(ctx, versionRetirementStageKey{}, true) + return errors.WithStack(metadata.StageRaftControlMetadata(ctx, []byte(versionAdoptionMetadataKey), encodeVersionAdoptionEpoch(epoch))) +} + +func (s *pebbleStore) StageVersionAdoptionActivation(ctx context.Context) error { + scope := s.raftEntryScopeFrom(ctx) + if scope == nil || scope.appliedIndex == 0 || scope.controlOnly { + return errors.WithStack(ErrRaftControlScopeRequired) + } + s.dbMu.RLock() + state := s.versionRetirementFor(ctx) + s.dbMu.RUnlock() + if state.adoptionEpoch != 0 { + return nil + } + state.adoptionEpoch = 1 + if err := stageVersionAdoptionEpoch(ctx, s, state.adoptionEpoch); err != nil { + return err + } + scope.versionRetirement = &state + return nil +} + +func (s *mvccStore) StageVersionAdoptionActivation(ctx context.Context) error { + scope := s.memoryEntryScope(ctx) + if scope == nil || scope.index == 0 || scope.controlOnly { + return errors.WithStack(ErrRaftControlScopeRequired) + } + if scope.staged.versionRetirement.adoptionEpoch != 0 { + return nil + } + if err := stageVersionAdoptionEpoch(ctx, s, 1); err != nil { + return err + } + scope.staged.versionRetirement.adoptionEpoch = 1 + return nil +} + +func (s *pebbleStore) readVersionAdoptionEpochLocked(reader pebble.Reader) (uint64, error) { + key, err := raftControlKey([]byte(versionAdoptionMetadataKey)) + if err != nil { + return 0, err + } + value, closer, err := reader.Get(key) + if errors.Is(err, pebble.ErrNotFound) { + return 0, nil + } + if err != nil { + return 0, errors.WithStack(err) + } + data, err := s.decodeRaftControlValue(key, value) + if err := errors.Join(err, closer.Close()); err != nil { + return 0, err + } + return decodeVersionAdoptionEpoch(data) +} + +func validateVersionRetirementEpochs(state versionRetirementState, epoch uint64) (versionRetirementState, error) { + for _, record := range state.records { + if record.record.Epoch > epoch { + return versionRetirementState{}, errors.WithStack(ErrVersionRetirementConflict) + } + } + state.adoptionEpoch = epoch + return state, nil +} diff --git a/store/version_adoption_codec.go b/store/version_adoption_codec.go new file mode 100644 index 000000000..5a0953c61 --- /dev/null +++ b/store/version_adoption_codec.go @@ -0,0 +1,52 @@ +package store + +import ( + "encoding/binary" + + "github.com/cockroachdb/errors" +) + +const adoptedVersionMask byte = 1 << 3 +const maxValueHeaderSize = valueHeaderSize + timestampSize + +// Adoption uses a persisted, group-local logical epoch, not a Raft index. +// The epoch survives snapshot-based rebootstrap with a new log index space. +// Import never trusts a source epoch; authorized local promotion assigns it. +func writeVersionHeaderBytes(dst []byte, tombstone bool, expireAt uint64, encState byte, adoptionEpoch uint64) int { + writeValueHeaderBytes(dst, tombstone, expireAt, encState) + if adoptionEpoch == 0 { + return valueHeaderSize + } + dst[0] |= adoptedVersionMask + binary.LittleEndian.PutUint64(dst[valueHeaderSize:], adoptionEpoch) + return maxValueHeaderSize +} + +func decodeValueAdoptionEpoch(data []byte) (uint64, error) { + if data[0]&adoptedVersionMask == 0 { + return 0, nil + } + if len(data) < maxValueHeaderSize { + return 0, errors.New("store: truncated version adoption header") + } + epoch := binary.LittleEndian.Uint64(data[valueHeaderSize:]) + if epoch == 0 { + return 0, errors.New("store: zero version adoption epoch") + } + return epoch, nil +} + +func versionValueHeaderSize(adoptionEpoch uint64) int { + if adoptionEpoch == 0 { + return valueHeaderSize + } + return maxValueHeaderSize +} + +func encodeAdoptedValue(val []byte, tombstone bool, expireAt uint64, encState byte, adoptionEpoch uint64) []byte { + headerSize := versionValueHeaderSize(adoptionEpoch) + buf := make([]byte, headerSize+len(val)) + writeVersionHeaderBytes(buf, tombstone, expireAt, encState, adoptionEpoch) + copy(buf[headerSize:], val) + return buf +} diff --git a/store/version_adoption_encryption_test.go b/store/version_adoption_encryption_test.go new file mode 100644 index 000000000..c6487488e --- /dev/null +++ b/store/version_adoption_encryption_test.go @@ -0,0 +1,119 @@ +package store + +import ( + "bytes" + "context" + "encoding/binary" + "testing" + + "github.com/bootjp/elastickv/internal/encryption" + "github.com/stretchr/testify/require" +) + +func adoptedEncryptedFixture(t *testing.T) *encryptedStoreFixture { + t.Helper() + fixture := newEncryptedStoreFixture(t, 1) + require.NoError(t, retirementStoreForTest(t, fixture.mvcc).ConfigureVersionRetirement(retirementTestCompiler)) + activateVersionAdoptionForTest(t, fixture.mvcc) + applyRetirementForTest(t, fixture.mvcc, 2) + stageAdoptionRowsForTest(t, fixture.mvcc, 8, 3) + adoptRowsForTest(t, fixture.mvcc, 8, 4) + assertAdoptedRowsForTest(t, fixture.mvcc, 3) + return fixture +} + +func TestVersionAdoptionEncryptedReopen(t *testing.T) { + fixture := adoptedEncryptedFixture(t) + fixture.closeIfOpen(t) + fixture.reopen(t) + retirement := retirementStoreForTest(t, fixture.mvcc) + require.NoError(t, retirement.ConfigureVersionRetirement(retirementTestCompiler)) + require.NoError(t, retirement.VersionAdoptionReady(t.Context())) + assertAdoptedRowsForTest(t, fixture.mvcc, 3) + result, err := retirement.ReclaimVersionRetirement(t.Context(), 7, retirementTestRecord().ID) + require.NoError(t, err) + require.Zero(t, result.DeletedRows) + assertAdoptedRowsForTest(t, fixture.mvcc, 3) +} + +func TestVersionAdoptionEncryptedHeaderAuthenticatesBeforeVisibility(t *testing.T) { + cases := map[string]func([]byte) []byte{ + "retired epoch": func(raw []byte) []byte { + binary.LittleEndian.PutUint64(raw[valueHeaderSize:], 2) + return raw + }, + "future epoch": func(raw []byte) []byte { + binary.LittleEndian.PutUint64(raw[valueHeaderSize:], 999) + return raw + }, + "ttl": func(raw []byte) []byte { raw[1] ^= 1; return raw }, + "tombstone": func(raw []byte) []byte { raw[0] ^= tombstoneMask; return raw }, + "removed adoption flag": func(raw []byte) []byte { raw[0] &^= adoptedVersionMask; return raw }, + "cleartext rebadge": func(raw []byte) []byte { raw[0] &^= encStateMask; return raw }, + "removed adoption and encryption flags": func(raw []byte) []byte { + raw[0] &^= encStateMask | adoptedVersionMask + return raw + }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + fixture := adoptedEncryptedFixture(t) + fixture.tamperPebbleValue(t, []byte("n"), 10, mutate) + require.NoError(t, retirementStoreForTest(t, fixture.mvcc).ConfigureVersionRetirement(retirementTestCompiler)) + _, err := fixture.mvcc.GetAt(t.Context(), []byte("n"), 30) + require.Error(t, err) + require.NotErrorIs(t, err, ErrKeyNotFound, "unauthenticated epoch cannot turn corruption into retirement") + _, err = fixture.mvcc.ScanKeysAt(t.Context(), []byte("n"), []byte("o"), 10, 30) + require.Error(t, err) + }) + } +} + +func TestVersionAdoptionEncryptedTombstoneCannotBeRebadged(t *testing.T) { + fixture := adoptedEncryptedFixture(t) + fixture.tamperPebbleValue(t, []byte("n-deleted"), 12, func(raw []byte) []byte { + raw[0] &^= encStateMask | adoptedVersionMask + return raw + }) + require.NoError(t, retirementStoreForTest(t, fixture.mvcc).ConfigureVersionRetirement(retirementTestCompiler)) + _, err := fixture.mvcc.GetAt(t.Context(), []byte("n-deleted"), 30) + require.ErrorIs(t, err, ErrEncryptedReadIntegrity) +} + +func TestVersionAdoptionEncryptedRotationAndSnapshots(t *testing.T) { + fixture := adoptedEncryptedFixture(t) + fixture.closeIfOpen(t) + require.NoError(t, fixture.keystore.Set(2, bytes.Repeat([]byte{2}, encryption.KeySize))) + fixture.keyID = 2 + fixture.reopen(t) + require.NoError(t, retirementStoreForTest(t, fixture.mvcc).ConfigureVersionRetirement(retirementTestCompiler)) + assertAdoptedRowsForTest(t, fixture.mvcc, 3) + require.NoError(t, raftEntryApplier(t, fixture.mvcc).ApplyRaftEntry(t.Context(), 5, func(ctx context.Context) error { + record := retirementTestRecord() + record.ID, record.JobID = "job/9/user", 9 + return retirementStoreForTest(t, fixture.mvcc).StageVersionRetirement(ctx, record) + })) + stageAdoptionRowsForTest(t, fixture.mvcc, 10, 6) + adoptRowsForTest(t, fixture.mvcc, 10, 7) + assertAdoptedRowsForTest(t, fixture.mvcc, 5) + ps, ok := fixture.mvcc.(*pebbleStore) + require.True(t, ok) + for _, sst := range []bool{false, true} { + ps.sstIngestSnapshots = sst + payload := externalTestSnapshot(t, fixture.mvcc) + destination, err := NewPebbleStore(t.TempDir(), WithEncryption(fixture.cipher, + encryption.NewDeterministicNonceFactory(0xBEEF, 1), func() (uint32, bool) { return 2, true })) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, destination.Close()) }) + require.NoError(t, destination.Restore(bytes.NewReader(payload))) + retirement := retirementStoreForTest(t, destination) + require.NoError(t, retirement.ConfigureVersionRetirement(retirementTestCompiler)) + assertAdoptedRowsForTest(t, destination, 5) + for _, record := range []VersionRetirement{retirementTestRecord(), {ID: "job/9/user", JobID: 9}} { + result, err := retirement.ReclaimVersionRetirement(t.Context(), record.JobID, record.ID) + require.NoError(t, err) + require.Zero(t, result.DeletedRows) + } + assertAdoptedRowsForTest(t, destination, 5) + } +} diff --git a/store/version_adoption_epoch_test.go b/store/version_adoption_epoch_test.go new file mode 100644 index 000000000..f61a9bfe7 --- /dev/null +++ b/store/version_adoption_epoch_test.go @@ -0,0 +1,70 @@ +package store + +import ( + "context" + "testing" + + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func adoptionEpochForTest(t *testing.T, st MVCCStore) uint64 { + t.Helper() + metadata, ok := st.(RaftControlMetadataStore) + require.True(t, ok) + data, err := metadata.ReadRaftControlMetadata(t.Context(), []byte(versionAdoptionMetadataKey)) + require.NoError(t, err) + epoch, err := decodeVersionAdoptionEpoch(data) + require.NoError(t, err) + return epoch +} + +func TestVersionAdoptionActivationAndRetirementAreAtomic(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + activateVersionAdoptionForTest(t, st) + require.Equal(t, uint64(1), adoptionEpochForTest(t, st)) + rejected := errors.New("abort the entry") + err := raftEntryApplier(t, st).ApplyRaftEntry(t.Context(), 2, func(ctx context.Context) error { + if err := retirementStoreForTest(t, st).StageVersionRetirement(ctx, retirementTestRecord()); err != nil { + return err + } + return rejected + }) + require.ErrorIs(t, err, rejected) + require.Equal(t, uint64(1), adoptionEpochForTest(t, st)) + applyRetirementForTest(t, st, 2) + require.Equal(t, uint64(2), adoptionEpochForTest(t, st)) + applyRetirementForTest(t, st, 3) + require.Equal(t, uint64(2), adoptionEpochForTest(t, st), "same immutable retirement must reuse its epoch") + stageAdoptionRowsForTest(t, st, 8, 4) + adoptRowsForTest(t, st, 8, 5) + require.Equal(t, uint64(3), adoptionEpochForTest(t, st)) + opts := adoptionPromotionForTest(8, 5) + promoter, ok := st.(MigrationPromoter) + require.True(t, ok) + _, err = promoter.PromoteVersions(t.Context(), opts) + require.NoError(t, err) + require.Equal(t, uint64(3), adoptionEpochForTest(t, st), "replaying a durable index must not allocate again") + }) +} + +func TestVersionAdoptionEpochIsCommandBasedAndBounded(t *testing.T) { + state := versionRetirementState{adoptionEpoch: 7} + for _, pairs := range [][]promotedVersion{nil, {{target: MVCCVersion{Key: []byte("n"), CommitTS: 10}}}} { + _, epoch, err := state.planVersionAdoptions(PromoteVersionsOptions{AppliedIndex: 2}, pairs) + require.NoError(t, err) + require.Equal(t, uint64(8), epoch, "local retention cannot change the replicated epoch count") + } + _, err := nextVersionAdoptionEpoch(^uint64(0)) + require.ErrorIs(t, err, ErrValueTooLarge) + _, err = nextVersionAdoptionEpoch(0) + require.Error(t, err) + for _, data := range [][]byte{{1}, encodeVersionAdoptionEpoch(0), append(encodeVersionAdoptionEpoch(1), 0)} { + _, err := decodeVersionAdoptionEpoch(data) + require.Error(t, err) + } + _, err = snapshotVersionAdoptionEpoch(mvccSnapshotVersionV8, map[string][]byte{versionAdoptionMetadataKey: encodeVersionAdoptionEpoch(1)}) + require.ErrorIs(t, err, ErrVersionRetirementUnavailable) + _, err = snapshotVersionAdoptionEpoch(mvccSnapshotVersionV9, nil) + require.ErrorIs(t, err, ErrVersionRetirementUnavailable) +} diff --git a/store/version_adoption_promotion.go b/store/version_adoption_promotion.go new file mode 100644 index 000000000..e1d06aafc --- /dev/null +++ b/store/version_adoption_promotion.go @@ -0,0 +1,181 @@ +package store + +import ( + "bytes" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2" +) + +func unadoptedImportVersions(versions []MVCCVersion) []MVCCVersion { + for _, version := range versions { + if version.adoptionEpoch != 0 { + versions = append([]MVCCVersion(nil), versions...) + for i := range versions { + versions[i].adoptionEpoch = 0 + } + break + } + } + return versions +} + +func retirementRecordMatches(entry compiledVersionRetirement, key, value []byte, ts uint64) (bool, error) { + record := entry.record + if ts > record.CommitCeiling || bytes.Compare(key, record.StartKey) < 0 || + (len(record.EndKey) != 0 && bytes.Compare(key, record.EndKey) >= 0) { + return false, nil + } + if entry.match == nil { + return false, errors.WithStack(ErrVersionRetirementUnavailable) + } + return entry.match(key, value), nil +} + +func (state versionRetirementState) validateMigrationImport(opts ImportVersionsOptions) error { + if !opts.AllowRetiredStaging { + return state.validateImport(opts.Versions, opts.LogicalKey) + } + if !state.validRetiredStaging(opts) { + return errors.WithStack(ErrMigrationRetired) + } + for _, version := range opts.Versions { + key := opts.LogicalKey(version.Key) + if bytes.Equal(key, version.Key) { + return errors.WithStack(ErrMigrationRetired) + } + for _, record := range state.records { + matched, err := retirementRecordMatches(record, key, version.Value, version.CommitTS) + if err != nil { + return err + } + if matched && record.record.JobID == opts.JobID { + return errors.WithStack(ErrMigrationRetired) + } + } + } + return nil +} + +func (state versionRetirementState) validRetiredStaging(opts ImportVersionsOptions) bool { + return state.adoptionEpoch != 0 && opts.LogicalKey != nil && opts.JobID != 0 +} + +func (state versionRetirementState) retainedMigrationLookup(lookup migrationVersionLookup) migrationVersionLookup { + return func(key []byte, ts uint64) (VersionedValue, bool, error) { + version, found, err := lookup(key, ts) + if err != nil || !found { + return version, found, err + } + retired, err := state.retired(key, version.Value, version.TS, version.adoptionEpoch) + if err != nil || retired { + return VersionedValue{}, false, err + } + return version, true, nil + } +} + +func (state versionRetirementState) authorizeVersionAdoption(opts PromoteVersionsOptions, version MVCCVersion) (bool, error) { + var adopt bool + for _, record := range state.records { + matched, err := retirementRecordMatches(record, version.Key, version.Value, version.CommitTS) + if err != nil { + return false, err + } + if !matched { + continue + } + if opts.AdoptionAuthority == nil || opts.AppliedIndex == 0 || state.adoptionEpoch == 0 || opts.JobID == record.record.JobID { + return false, errors.WithStack(ErrMigrationRetired) + } + if err := opts.AdoptionAuthority(version, record.record); err != nil { + return false, err + } + adopt = true + } + return adopt, nil +} + +func (state versionRetirementState) planVersionAdoptions(opts PromoteVersionsOptions, versions []promotedVersion) ([]promotedVersion, uint64, error) { + epoch, err := state.promotionEpoch(opts.AppliedIndex) + if err != nil { + return nil, 0, err + } + if len(state.records) == 0 { + return versions, epoch, nil + } + versions = append([]promotedVersion(nil), versions...) + for i := range versions { + adopt, err := state.authorizeVersionAdoption(opts, versions[i].target) + if err != nil { + return nil, 0, err + } + if adopt { + versions[i].target.adoptionEpoch = epoch + } + } + return versions, epoch, nil +} + +// Count replicated promotion commands, not locally retained rows. Compaction +// may leave different historical rows on otherwise equivalent replicas. +func (state versionRetirementState) promotionEpoch(appliedIndex uint64) (uint64, error) { + if state.adoptionEpoch == 0 || appliedIndex == 0 { + return state.adoptionEpoch, nil + } + return nextVersionAdoptionEpoch(state.adoptionEpoch) +} + +func replayedPromotionResult(state PromotionState) PromoteVersionsResult { + return PromoteVersionsResult{Done: state.Done, NextCursor: bytes.Clone(state.Cursor), + TotalPromotedRows: state.PromotedRows, MaxPromotedTS: state.MaxPromotedTS} +} + +func (state versionRetirementState) planPromotionWrites(opts PromoteVersionsOptions, exported ExportVersionsResult, versions []promotedVersion, result PromoteVersionsResult, lookup migrationVersionLookup) (migrationPromotionPlan, error) { + versions, epoch, err := state.planVersionAdoptions(opts, versions) + if err != nil { + return migrationPromotionPlan{}, err + } + if opts.AdoptionAuthority != nil { + lookup = state.retainedMigrationLookup(lookup) + } + writes, err := promotionWrites(versions, opts.AllowLegacyVersionOverwrite, lookup) + if err != nil { + return migrationPromotionPlan{}, err + } + return migrationPromotionPlan{exported: exported, versions: versions, writes: writes, result: result, epoch: epoch}, nil +} + +func (s *mvccStore) putMigratedVersionLocked(version MVCCVersion) { + if version.Tombstone { + s.deleteVersionLocked(version.Key, version.CommitTS) + } else { + s.putVersionLocked(version.Key, version.Value, version.CommitTS, version.ExpireAt) + } + existing, _ := s.entryTreeGet(version.Key) + versions, _ := existing.([]VersionedValue) + index := findVersionIndex(versions, version.CommitTS) + versions[index].adoptionEpoch = version.adoptionEpoch +} + +func (s *pebbleStore) stageVersionAdoptionEpochBatch(batch *pebble.Batch, epoch uint64) error { + key, err := raftControlKey([]byte(versionAdoptionMetadataKey)) + if err != nil { + return err + } + body, state, err := s.encryptForKey(key, encodeVersionAdoptionEpoch(epoch), 0, false) + if err != nil { + return err + } + return errors.WithStack(batch.Set(key, encodeValue(body, false, 0, state), nil)) +} + +func (s *pebbleStore) lockPromotionRetirement() func() { + s.dbMu.RLock() + if s.versionRetirement.adoptionEpoch == 0 { + return s.dbMu.RUnlock + } + s.dbMu.RUnlock() + s.dbMu.Lock() + return s.dbMu.Unlock +} diff --git a/store/version_adoption_test.go b/store/version_adoption_test.go new file mode 100644 index 000000000..ef1362a31 --- /dev/null +++ b/store/version_adoption_test.go @@ -0,0 +1,177 @@ +package store + +import ( + "bytes" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func activateVersionAdoptionForTest(t *testing.T, st MVCCStore) { + t.Helper() + require.NoError(t, raftEntryApplier(t, st).ApplyRaftEntry(t.Context(), 1, func(ctx context.Context) error { + if _, err := StageRaftEntryProgress(ctx, 1); err != nil { + return err + } + return retirementStoreForTest(t, st).StageVersionAdoptionActivation(ctx) + })) +} + +func stageAdoptionRowsForTest(t *testing.T, st MVCCStore, jobID, index uint64) { + t.Helper() + _, err := st.ImportVersionsRaft(t.Context(), ImportVersionsOptions{ + JobID: jobID, AppliedIndex: index, BatchSeq: 1, AllowRetiredStaging: true, + LogicalKey: func(key []byte) []byte { return bytes.TrimPrefix(key, []byte("staging/")) }, + Versions: []MVCCVersion{ + {Key: []byte("staging/n"), CommitTS: 10, Value: []byte("unchanged"), ExpireAt: 1000}, + {Key: []byte("staging/n-deleted"), CommitTS: 12, Tombstone: true}, + }, + }) + require.NoError(t, err) +} + +func adoptionPromotionForTest(jobID, index uint64) PromoteVersionsOptions { + return PromoteVersionsOptions{JobID: jobID, AppliedIndex: index, MaxVersions: 10, + StartKey: []byte("staging/"), EndKey: PrefixScanEnd([]byte("staging/")), + TargetKey: func(key []byte) ([]byte, bool) { return bytes.TrimPrefix(key, []byte("staging/")), true }, + } +} + +func adoptRowsForTest(t *testing.T, st MVCCStore, jobID, index uint64) { + t.Helper() + opts := adoptionPromotionForTest(jobID, index) + var authorized int + opts.AdoptionAuthority = func(version MVCCVersion, record VersionRetirement) error { + require.NotEqual(t, jobID, record.JobID) + require.LessOrEqual(t, version.CommitTS, record.CommitCeiling) + authorized++ + return nil + } + promoter, ok := st.(MigrationPromoter) + require.True(t, ok) + result, err := promoter.PromoteVersions(t.Context(), opts) + require.NoError(t, err) + require.True(t, result.Done) + require.Equal(t, uint64(2), result.PromotedRows) + require.Positive(t, authorized) +} + +func assertAdoptedRowsForTest(t *testing.T, st MVCCStore, epoch uint64) { + t.Helper() + value, err := GetVersionAt(t.Context(), st, []byte("n"), 30) + require.NoError(t, err) + require.Equal(t, uint64(10), value.TS) + require.Equal(t, uint64(1000), value.ExpireAt) + require.Equal(t, []byte("unchanged"), value.Value) + _, err = st.GetAt(t.Context(), []byte("n-deleted"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) + rows, err := st.ExportVersions(t.Context(), ExportVersionsOptions{StartKey: []byte("n"), EndKey: []byte("o"), MaxVersions: 10}) + require.NoError(t, err) + require.Len(t, rows.Versions, 2) + for _, row := range rows.Versions { + require.Equal(t, epoch, row.adoptionEpoch) + } +} + +func TestVersionAdoptionRequiresAuthorityAndPreservesOriginalVersion(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + activateVersionAdoptionForTest(t, st) + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("unchanged"), 10, 1000)) + require.NoError(t, st.DeleteAt(t.Context(), []byte("n-deleted"), 12)) + applyRetirementForTest(t, st, 2) + stageAdoptionRowsForTest(t, st, 8, 3) + _, err := st.GetAt(t.Context(), []byte("n"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) + promoter, ok := st.(MigrationPromoter) + require.True(t, ok) + _, err = promoter.PromoteVersions(t.Context(), adoptionPromotionForTest(8, 4)) + require.ErrorIs(t, err, ErrMigrationRetired) + adoptRowsForTest(t, st, 8, 4) + assertAdoptedRowsForTest(t, st, 3) + require.NoError(t, raftEntryApplier(t, st).ApplyRaftEntry(t.Context(), 5, func(ctx context.Context) error { + record := retirementTestRecord() + result, err := StageRaftEntryMigrationCleanup(ctx, CleanupVersionsOptions{ + Retirement: &record, JobID: 7, AppliedIndex: 5, StartKey: []byte("n"), EndKey: []byte("o"), + MaxCommitTS: 20, MaxVersions: 10, + }) + if err == nil { + require.Zero(t, result.DeletedRows, "an old indexed cleanup must preserve the adopted epoch") + } + return err + })) + assertAdoptedRowsForTest(t, st, 3) + require.ErrorIs(t, st.DeletePrefixAt(t.Context(), []byte("n"), nil, 15), ErrMigrationRetired) + require.ErrorIs(t, st.ExpireAt(t.Context(), []byte("n"), 2000, 15), ErrMigrationRetired) + assertAdoptedRowsForTest(t, st, 3) + result, err := retirementStoreForTest(t, st).ReclaimVersionRetirement(t.Context(), 7, retirementTestRecord().ID) + require.NoError(t, err) + require.True(t, result.Done) + require.Zero(t, result.DeletedRows, "old GC cannot delete returned rows at the same MVCC timestamp") + assertAdoptedRowsForTest(t, st, 3) + // A subsequent migration retires the adopted generation, not just legacy rows. + require.NoError(t, raftEntryApplier(t, st).ApplyRaftEntry(t.Context(), 6, func(ctx context.Context) error { + record := retirementTestRecord() + record.ID, record.JobID = "job/9/user", 9 + return retirementStoreForTest(t, st).StageVersionRetirement(ctx, record) + })) + _, err = st.GetAt(t.Context(), []byte("n"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) + result, err = retirementStoreForTest(t, st).ReclaimVersionRetirement(t.Context(), 9, "job/9/user") + require.NoError(t, err) + require.Equal(t, uint64(2), result.DeletedRows) + stageAdoptionRowsForTest(t, st, 10, 7) + adoptRowsForTest(t, st, 10, 8) + assertAdoptedRowsForTest(t, st, 5) + }) +} + +func TestVersionAdoptionSurvivesSnapshotsAndOldGC(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + activateVersionAdoptionForTest(t, st) + applyRetirementForTest(t, st, 2) + stageAdoptionRowsForTest(t, st, 8, 3) + adoptRowsForTest(t, st, 8, 4) + snapshot, err := st.Snapshot() + require.NoError(t, err) + defer func() { require.NoError(t, snapshot.Close()) }() + var payload bytes.Buffer + _, err = snapshot.WriteTo(&payload) + require.NoError(t, err) + destinations := []MVCCStore{openSSTSnapshotTestStore(t, t.TempDir())} + if _, memory := st.(*mvccStore); memory { + dest := NewMVCCStore() + t.Cleanup(func() { require.NoError(t, dest.Close()) }) + destinations = append(destinations, dest) + } + for _, destination := range destinations { + require.NoError(t, destination.Restore(bytes.NewReader(payload.Bytes()))) + retirement := retirementStoreForTest(t, destination) + require.NoError(t, retirement.ConfigureVersionRetirement(retirementTestCompiler)) + require.NoError(t, retirement.VersionAdoptionReady(t.Context())) + assertAdoptedRowsForTest(t, destination, 3) + result, err := retirement.ReclaimVersionRetirement(t.Context(), 7, retirementTestRecord().ID) + require.NoError(t, err) + require.True(t, result.Done) + require.Zero(t, result.DeletedRows) + assertAdoptedRowsForTest(t, destination, 3) + } + }) +} + +func TestVersionAdoptionImportDoesNotTrustForeignEpoch(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + activateVersionAdoptionForTest(t, st) + applyRetirementForTest(t, st, 2) + _, err := st.ImportVersions(t.Context(), ImportVersionsOptions{JobID: 8, BatchSeq: 1, + Versions: []MVCCVersion{{Key: []byte("n"), CommitTS: 10, Value: []byte("forged"), adoptionEpoch: 999}}}) + require.ErrorIs(t, err, ErrMigrationRetired) + _, err = st.ImportVersions(t.Context(), ImportVersionsOptions{JobID: 9, BatchSeq: 1, + Versions: []MVCCVersion{{Key: []byte("outside"), CommitTS: 10, Value: []byte("safe"), adoptionEpoch: 999}}}) + require.NoError(t, err) + rows, err := st.ExportVersions(t.Context(), ExportVersionsOptions{StartKey: []byte("outside"), MaxVersions: 10}) + require.NoError(t, err) + require.Len(t, rows.Versions, 1) + require.Zero(t, rows.Versions[0].adoptionEpoch) + }) +} diff --git a/store/version_retirement.go b/store/version_retirement.go new file mode 100644 index 000000000..2772e68b9 --- /dev/null +++ b/store/version_retirement.go @@ -0,0 +1,505 @@ +package store + +import ( + "bytes" + "context" + "encoding/json" + "io" + "sort" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2" +) + +const versionRetirementMetadataKey = "version-retirement/v1" +const maxVersionRetirementRecords = 4096 +const maxVersionRetirementMetadataBytes = 8 << 20 + +var ErrVersionRetirementUnavailable = errors.New("store: version retirement selector is unavailable") +var ErrVersionRetirementConflict = errors.New("store: version retirement identity conflict") + +// VersionRetirement is an immutable, replicated source-retirement decision. +// Selector is an opaque, versioned description owned by the routing layer. +// Its compiler must be installed before a recovered store can serve the range. +type VersionRetirement struct { + ID string + JobID uint64 + GroupID uint64 + ConfigurationIndex uint64 + Generation string + CommitCeiling uint64 + StartKey []byte + EndKey []byte + Selector []byte + Epoch uint64 `json:",omitempty"` +} + +type VersionRetirementCompiler func([]byte) (func(key, value []byte) bool, error) + +type VersionRetirementStore interface { + ConfigureVersionRetirement(VersionRetirementCompiler) error + ValidateVersionRetirement(context.Context, VersionRetirement) error + StageVersionRetirement(context.Context, VersionRetirement) error + ReclaimVersionRetirement(context.Context, uint64, string) (CleanupVersionsResult, error) + StageVersionAdoptionActivation(context.Context) error + VersionAdoptionReady(context.Context) error +} + +type compiledVersionRetirement struct { + record VersionRetirement + match func(key, value []byte) bool +} + +type versionRetirementState struct { + compiler VersionRetirementCompiler + records []compiledVersionRetirement + // Local, disposable progress. Rebuilt on restore/reopen; never replicated + // or used as a logical visibility decision. + reclamation map[string]CleanupVersionsResult + adoptionEpoch uint64 +} + +type versionRetirementStageKey struct{} + +func encodeVersionRetirements(records []compiledVersionRetirement) ([]byte, error) { + values := make([]VersionRetirement, len(records)) + for i, entry := range records { + values[i] = entry.record + } + data, err := json.Marshal(values) + if err != nil { + return nil, errors.WithStack(err) + } + if len(data) > maxVersionRetirementMetadataBytes { + return nil, errors.WithStack(ErrValueTooLarge) + } + return data, nil +} + +func decodeVersionRetirements(data []byte, compiler VersionRetirementCompiler) (versionRetirementState, error) { + state := versionRetirementState{compiler: compiler} + if len(data) == 0 { + return state, nil + } + if len(data) > maxVersionRetirementMetadataBytes { + return state, errors.WithStack(ErrValueTooLarge) + } + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + var records []VersionRetirement + if err := decoder.Decode(&records); err != nil { + return state, errors.Wrap(err, "decode version retirements") + } + if records == nil { + return state, errors.New("null version retirement metadata") + } + if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) { + return state, errors.New("trailing version retirement data") + } + for _, record := range records { + var err error + state, err = state.append(record) + if err != nil { + return versionRetirementState{}, err + } + } + if len(state.records) != len(records) { + return versionRetirementState{}, errors.WithStack(ErrVersionRetirementConflict) + } + return state, nil +} + +func validVersionRetirement(record VersionRetirement) bool { + return record.ID != "" && record.JobID != 0 && record.GroupID != 0 && + record.ConfigurationIndex != 0 && record.Generation != "" && record.CommitCeiling != 0 && + validVersionRetirementBounds(record) +} + +func validVersionRetirementBounds(record VersionRetirement) bool { + return len(record.ID) <= maxSnapshotKeySize && len(record.Generation) <= maxSnapshotKeySize && + len(record.StartKey) <= maxSnapshotKeySize && len(record.EndKey) <= maxSnapshotKeySize && + len(record.Selector) <= maxVersionRetirementMetadataBytes && + len(record.Selector) != 0 && (len(record.EndKey) == 0 || bytes.Compare(record.StartKey, record.EndKey) < 0) +} + +func (state versionRetirementState) append(record VersionRetirement) (versionRetirementState, error) { + if !validVersionRetirement(record) { + return state, errors.WithStack(ErrVersionRetirementConflict) + } + encoded, err := json.Marshal(record) + if err != nil { + return state, errors.WithStack(err) + } + for _, existing := range state.records { + if existing.record.ID == record.ID { + previous, err := json.Marshal(existing.record) + if err != nil { + return state, errors.WithStack(err) + } + if !bytes.Equal(previous, encoded) { + return state, errors.WithStack(ErrVersionRetirementConflict) + } + return state, nil + } + } + if len(state.records) >= maxVersionRetirementRecords { + return state, errors.WithStack(ErrValueTooLarge) + } + owned := record + owned.StartKey, owned.EndKey = bytes.Clone(record.StartKey), bytes.Clone(record.EndKey) + owned.Selector = bytes.Clone(record.Selector) + entry := compiledVersionRetirement{record: owned} + entry.match, err = compileVersionRetirement(state.compiler, owned.Selector) + if err != nil { + return state, err + } + state.records = append(append([]compiledVersionRetirement(nil), state.records...), entry) + sort.Slice(state.records, func(i, j int) bool { return state.records[i].record.ID < state.records[j].record.ID }) + return state, nil +} + +func compileVersionRetirement(compiler VersionRetirementCompiler, selector []byte) (func([]byte, []byte) bool, error) { + if compiler == nil { + return nil, nil + } + match, err := compiler(bytes.Clone(selector)) + if err != nil { + return nil, err + } + if match == nil { + return nil, errors.WithStack(ErrVersionRetirementUnavailable) + } + return match, nil +} + +func (state versionRetirementState) retired(key, value []byte, commitTS uint64, adoptionEpoch uint64) (bool, error) { + if adoptionEpoch > state.adoptionEpoch { + return false, errors.WithStack(ErrVersionRetirementUnavailable) + } + for _, entry := range state.records { + record := entry.record + if adoptionEpoch > record.Epoch || commitTS > record.CommitCeiling || bytes.Compare(key, record.StartKey) < 0 || + (len(record.EndKey) != 0 && bytes.Compare(key, record.EndKey) >= 0) { + continue + } + if entry.match == nil { + return false, errors.WithStack(ErrVersionRetirementUnavailable) + } + if entry.match(key, value) { + return true, nil + } + } + return false, nil +} + +func (s *pebbleStore) versionRetirementFor(ctx context.Context) versionRetirementState { + if scope := s.raftEntryScopeFrom(ctx); scope != nil && scope.versionRetirement != nil { + return *scope.versionRetirement + } + return s.versionRetirement +} + +func (s *pebbleStore) retiredIteratorEntry(ctx context.Context, iter *pebble.Iterator) (bool, error) { + state := s.versionRetirementFor(ctx) + raw := iter.Value() + if len(state.records) == 0 && (len(raw) == 0 || raw[0]&adoptedVersionMask == 0) { + return false, nil + } + key, timestamp := decodeKeyView(iter.Key()) + value, err := decodeValueView(iter.Value()) + if err != nil { + return false, err + } + plain, flag, err := s.decryptAuthenticatedForKey(iter.Key(), value, value.Value) + if err != nil { + return false, err + } + plain, err = finishAuthenticatedValue(plain, flag) + if err != nil { + return false, err + } + return state.retired(key, plain, timestamp, value.AdoptionEpoch) +} + +func (s *pebbleStore) requireRetainedIteratorEntry(ctx context.Context, iter *pebble.Iterator) error { + retired, err := s.retiredIteratorEntry(ctx, iter) + if err != nil { + return err + } + if retired { + return ErrKeyNotFound + } + return nil +} + +func (s *pebbleStore) retainedConflictResult(ctx context.Context, iter *pebble.Iterator, ts uint64, exists bool, err error) (uint64, bool, error) { + if err != nil || !exists { + return ts, exists, err + } + retired, err := s.retiredIteratorEntry(ctx, iter) + if err != nil || retired { + return 0, false, err + } + return ts, exists, nil +} + +func (s *pebbleStore) retainedCommittedVersionAt(ctx context.Context, key []byte, ts uint64) (bool, error) { + if isPebbleOperationalKey(encodeKey(key, ts)) { + return false, nil + } + iter, err := s.raftEntryReader(ctx).NewIter(&pebble.IterOptions{LowerBound: encodeKey(key, ts), UpperBound: keyUpperBound(key)}) + if err != nil { + return false, errors.WithStack(err) + } + defer iter.Close() + if !iter.First() || !bytes.Equal(iter.Key(), encodeKey(key, ts)) { + return false, errors.WithStack(iter.Error()) + } + retired, err := s.retiredIteratorEntry(ctx, iter) + return !retired, err +} + +func (s *mvccStore) visibleRetainedValue(key []byte, versions []VersionedValue, ts uint64) ([]byte, bool, error) { + version := versionAt(versions, ts) + if version == nil { + return nil, false, nil + } + retired, err := s.versionRetirement.retired(key, version.Value, version.TS, version.adoptionEpoch) + if err != nil || retired { + return nil, false, err + } + value, visible := version.valueAt(ts) + return value, visible, nil +} + +func (s *mvccStore) appendMemoryScanKV(key []byte, versions []VersionedValue, ts uint64, result *[]*KVPair) error { + value, visible, err := s.visibleRetainedValue(key, versions, ts) + if err != nil { + return err + } + if visible { + *result = append(*result, &KVPair{Key: bytes.Clone(key), Value: bytes.Clone(value)}) + } + return nil +} + +func (state versionRetirementState) validateImport(versions []MVCCVersion, logicalKey func([]byte) []byte) error { + if len(state.records) == 0 { + return nil + } + for _, version := range versions { + key := version.Key + if logicalKey != nil { + key = logicalKey(key) + } + retired, err := state.retired(key, version.Value, version.CommitTS, version.adoptionEpoch) + if err != nil { + return err + } + if retired { + return errors.WithStack(ErrMigrationRetired) + } + } + return nil +} + +func (state versionRetirementState) validateWrite(key, value []byte, ts uint64) error { + retired, err := state.retired(key, value, ts, 0) + if err != nil { + return err + } + if retired { + return errors.WithStack(ErrMigrationRetired) + } + return nil +} + +func (state versionRetirementState) validateMutations(mutations []*KVPairMutation, ts uint64) error { + if len(state.records) == 0 { + return nil + } + for _, mutation := range mutations { + if mutation == nil { + continue + } + value := mutation.Value + if mutation.Op == OpTypeDelete { + value = nil + } + if err := state.validateWrite(mutation.Key, value, ts); err != nil { + return err + } + } + return nil +} + +func (s *mvccStore) validateRetirementAndCommitFence(mutations []*KVPairMutation, ts uint64, fenced bool) error { + if err := s.versionRetirement.validateMutations(mutations, ts); err != nil { + return err + } + return checkCommitTSFence(mutations, ts, s.lastCommitTS, fenced) +} + +func (s *pebbleStore) loadVersionRetirements() error { + epoch, err := s.readVersionAdoptionEpochLocked(s.db) + if err != nil { + return err + } + physical, err := raftControlKey([]byte(versionRetirementMetadataKey)) + if err != nil { + return err + } + value, closer, err := s.db.Get(physical) + if errors.Is(err, pebble.ErrNotFound) { + s.versionRetirement = versionRetirementState{compiler: s.versionRetirement.compiler, adoptionEpoch: epoch} + return nil + } + if err != nil { + return errors.WithStack(err) + } + data, decodeErr := s.decodeRaftControlValue(physical, value) + if err := errors.Join(decodeErr, closer.Close()); err != nil { + return err + } + if len(data) == 0 { + return errors.New("empty version retirement metadata") + } + state, err := decodeVersionRetirements(data, s.versionRetirement.compiler) + if err != nil { + return err + } + s.versionRetirement, err = validateVersionRetirementEpochs(state, epoch) + if err != nil { + return err + } + return nil +} + +func (s *pebbleStore) ConfigureVersionRetirement(compiler VersionRetirementCompiler) error { + s.applyMu.Lock() + defer s.applyMu.Unlock() + s.dbMu.Lock() + defer s.dbMu.Unlock() + data, err := encodeVersionRetirements(s.versionRetirement.records) + if err != nil { + return err + } + state, err := decodeVersionRetirements(data, compiler) + if err == nil { + s.versionRetirement, err = validateVersionRetirementEpochs(state, s.versionRetirement.adoptionEpoch) + } + return err +} + +func (s *pebbleStore) StageVersionRetirement(ctx context.Context, record VersionRetirement) error { + scope := s.raftEntryScopeFrom(ctx) + if scope == nil || scope.appliedIndex == 0 || scope.controlOnly { + return errors.WithStack(ErrRaftControlScopeRequired) + } + s.dbMu.RLock() + state := s.versionRetirementFor(ctx) + s.dbMu.RUnlock() + if state.compiler == nil { + return scope.fail(errors.WithStack(ErrVersionRetirementUnavailable)) + } + state, record, err := prepareVersionRetirementEpoch(state, record) + if err != nil { + return scope.fail(err) + } + state, err = state.append(record) + if err != nil { + return scope.fail(err) + } + data, err := encodeVersionRetirements(state.records) + if err != nil { + return scope.fail(err) + } + stageCtx := context.WithValue(ctx, versionRetirementStageKey{}, true) + if err := stageVersionAdoptionEpoch(stageCtx, s, state.adoptionEpoch); err != nil { + return err + } + if err := s.StageRaftControlMetadata(stageCtx, []byte(versionRetirementMetadataKey), data); err != nil { + return err + } + scope.versionRetirement = &state + return nil +} + +func validateVersionRetirementState(state versionRetirementState, record VersionRetirement) error { + if state.compiler == nil { + return errors.WithStack(ErrVersionRetirementUnavailable) + } + state, record, err := prepareVersionRetirementEpoch(state, record) + if err != nil { + return err + } + state, err = state.append(record) + if err != nil { + return err + } + _, err = encodeVersionRetirements(state.records) + return err +} + +func (s *pebbleStore) ValidateVersionRetirement(ctx context.Context, record VersionRetirement) error { + s.dbMu.RLock() + defer s.dbMu.RUnlock() + return validateVersionRetirementState(s.versionRetirementFor(ctx), record) +} + +func (s *mvccStore) ValidateVersionRetirement(ctx context.Context, record VersionRetirement) error { + if staged := s.memoryEntryStore(ctx); staged != nil { + return staged.ValidateVersionRetirement(ctx, record) + } + s.mtx.RLock() + defer s.mtx.RUnlock() + return validateVersionRetirementState(s.versionRetirement, record) +} + +func (s *mvccStore) ConfigureVersionRetirement(compiler VersionRetirementCompiler) error { + s.applyMu.Lock() + defer s.applyMu.Unlock() + s.mtx.Lock() + defer s.mtx.Unlock() + state, err := decodeVersionRetirements(s.raftControl[versionRetirementMetadataKey], compiler) + if err == nil { + epoch, epochErr := decodeVersionAdoptionEpoch(s.raftControl[versionAdoptionMetadataKey]) + if epochErr != nil { + return epochErr + } + s.versionRetirement, err = validateVersionRetirementEpochs(state, epoch) + } + return err +} + +func (s *mvccStore) StageVersionRetirement(ctx context.Context, record VersionRetirement) error { + scope := s.memoryEntryScope(ctx) + if scope == nil || scope.index == 0 || scope.controlOnly { + return errors.WithStack(ErrRaftControlScopeRequired) + } + state := scope.staged.versionRetirement + if state.compiler == nil { + return scope.fail(errors.WithStack(ErrVersionRetirementUnavailable)) + } + state, record, err := prepareVersionRetirementEpoch(state, record) + if err != nil { + return scope.fail(err) + } + state, err = state.append(record) + if err != nil { + return scope.fail(err) + } + data, err := encodeVersionRetirements(state.records) + if err != nil { + return scope.fail(err) + } + stageCtx := context.WithValue(ctx, versionRetirementStageKey{}, true) + if err := stageVersionAdoptionEpoch(stageCtx, s, state.adoptionEpoch); err != nil { + return err + } + if err := s.StageRaftControlMetadata(stageCtx, []byte(versionRetirementMetadataKey), data); err != nil { + return err + } + scope.staged.versionRetirement = state + return nil +} diff --git a/store/version_retirement_reclaim.go b/store/version_retirement_reclaim.go new file mode 100644 index 000000000..acfefffe9 --- /dev/null +++ b/store/version_retirement_reclaim.go @@ -0,0 +1,137 @@ +package store + +import ( + "bytes" + "context" + "math" + + "github.com/cockroachdb/errors" + "github.com/cockroachdb/pebble/v2" +) + +const retirementReclaimPageVersions = 256 +const retirementReclaimPageBytes = 4 << 20 + +type versionRetirementReclamation struct { + epoch uint64 + current uint64 +} + +func (r *versionRetirementReclamation) retain(epoch uint64) (bool, error) { + if r == nil { + return false, nil + } + if epoch > r.current { + return false, errors.WithStack(ErrVersionRetirementUnavailable) + } + return epoch > r.epoch, nil +} + +func (opts ExportVersionsOptions) retiredOrReclaimed(version MVCCVersion) (bool, error) { + retain, err := opts.reclamation.retain(version.adoptionEpoch) + if err != nil || retain { + return retain, err + } + if opts.retirement == nil { + return false, nil + } + return opts.retirement.retired(version.Key, version.Value, version.CommitTS, version.adoptionEpoch) +} + +func (state versionRetirementState) reclamationOptions(jobID uint64, id string) (ExportVersionsOptions, error) { + for _, entry := range state.records { + if entry.record.ID != id || entry.record.JobID != jobID { + continue + } + if entry.match == nil { + return ExportVersionsOptions{}, errors.WithStack(ErrVersionRetirementUnavailable) + } + return ExportVersionsOptions{ + StartKey: entry.record.StartKey, EndKey: entry.record.EndKey, + MaxCommitTSInclusive: entry.record.CommitCeiling, ReadTS: math.MaxUint64, + AcceptVersion: entry.match, includeRetired: true, + reclamation: &versionRetirementReclamation{epoch: entry.record.Epoch, current: state.adoptionEpoch}, + MaxVersions: retirementReclaimPageVersions, MaxBytes: retirementReclaimPageBytes, + MaxScannedBytes: retirementReclaimPageBytes, + Cursor: bytes.Clone(state.reclamation[id].NextCursor), + }, nil + } + return ExportVersionsOptions{}, errors.WithStack(ErrVersionRetirementUnavailable) +} + +func (state *versionRetirementState) recordReclamation(id string, result CleanupVersionsResult) { + if state.reclamation == nil { + state.reclamation = make(map[string]CleanupVersionsResult) + } + result.NextCursor = bytes.Clone(result.NextCursor) + state.reclamation[id] = result +} + +// ReclaimVersionRetirement is local physical GC, not a Raft operation. Its only +// authority is an already committed, immutable retirement. All writers reject +// retired versions. New ownership may adopt a row with a newer epoch, which +// this reclamation must preserve. Reaching the end is monotonic until a restore +// (which discards this disposable progress). Applied indexes are untouched. +func (s *pebbleStore) ReclaimVersionRetirement(ctx context.Context, jobID uint64, id string) (CleanupVersionsResult, error) { + if s.raftEntryScopeFrom(ctx) != nil { + return CleanupVersionsResult{}, errors.WithStack(ErrRaftControlScopeRequired) + } + s.applyMu.Lock() + defer s.applyMu.Unlock() + s.dbMu.Lock() + defer s.dbMu.Unlock() + opts, err := s.versionRetirement.reclamationOptions(jobID, id) + if err != nil { + return CleanupVersionsResult{}, err + } + if s.versionRetirement.reclamation[id].Done { + return CleanupVersionsResult{Done: true}, nil + } + exported, err := s.exportVersionsFromLocked(ctx, s.db, opts, true) + if err != nil { + return CleanupVersionsResult{}, err + } + batch := s.db.NewBatch() + defer batch.Close() + if err := stageCleanupVersionDeletes(batch, exported.Versions); err != nil { + return CleanupVersionsResult{}, err + } + if err := batch.Commit(pebble.Sync); err != nil { + return CleanupVersionsResult{}, errors.WithStack(err) + } + result := cleanupResult(exported) + s.versionRetirement.recordReclamation(id, result) + return result, nil +} + +func (s *mvccStore) ReclaimVersionRetirement(ctx context.Context, jobID uint64, id string) (CleanupVersionsResult, error) { + if s.memoryEntryScope(ctx) != nil { + return CleanupVersionsResult{}, errors.WithStack(ErrRaftControlScopeRequired) + } + s.applyMu.Lock() + defer s.applyMu.Unlock() + s.mtx.Lock() + defer s.mtx.Unlock() + opts, err := s.versionRetirement.reclamationOptions(jobID, id) + if err != nil { + return CleanupVersionsResult{}, err + } + if s.versionRetirement.reclamation[id].Done { + return CleanupVersionsResult{Done: true}, nil + } + opts = normalizeExportVersionsOptions(opts) + pos, err := decodeExportCursorForOptions(opts) + if err != nil { + return CleanupVersionsResult{}, err + } + exported, err := s.exportVersionsLocked(ctx, opts, pos) + if err != nil { + return CleanupVersionsResult{}, err + } + for _, version := range exported.Versions { + s.removeVersionLocked(version.Key, version.CommitTS) + } + result := cleanupResult(exported) + s.versionRetirement.recordReclamation(id, result) + return result, nil +} diff --git a/store/version_retirement_reclaim_test.go b/store/version_retirement_reclaim_test.go new file mode 100644 index 000000000..1d8f44923 --- /dev/null +++ b/store/version_retirement_reclaim_test.go @@ -0,0 +1,66 @@ +package store + +import ( + "bytes" + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestVersionRetirementLocalReclaimIsBoundedAndRequiresCommittedAuthority(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + retirement := retirementStoreForTest(t, st) + _, err := retirement.ReclaimVersionRetirement(t.Context(), 7, "missing") + require.ErrorIs(t, err, ErrVersionRetirementUnavailable) + for i := range 600 { + key := fmt.Appendf(nil, "n%04d", i) + require.NoError(t, st.PutAt(t.Context(), key, []byte("old"), 10, 0)) + require.NoError(t, st.PutAt(t.Context(), key, []byte("new"), 30, 0)) + } + applyRetirementForTest(t, st, 1) + record := retirementTestRecord() + var payload bytes.Buffer + snapshot, err := st.Snapshot() + require.NoError(t, err) + _, err = snapshot.WriteTo(&payload) + require.NoError(t, err) + require.NoError(t, snapshot.Close()) + _, err = retirement.ReclaimVersionRetirement(t.Context(), 8, record.ID) + require.ErrorIs(t, err, ErrVersionRetirementUnavailable) + var deleted uint64 + var completed bool + for range 10 { + result, err := retirement.ReclaimVersionRetirement(t.Context(), record.JobID, record.ID) + require.NoError(t, err) + require.LessOrEqual(t, result.DeletedRows, uint64(retirementReclaimPageVersions)) + deleted += result.DeletedRows + if result.Done { + completed = true + break + } + } + require.True(t, completed) + require.Equal(t, uint64(600), deleted) + rows, err := st.ExportVersions(t.Context(), ExportVersionsOptions{StartKey: []byte("n"), EndKey: []byte("o"), MaxVersions: 1000, includeRetired: true}) + require.NoError(t, err) + require.True(t, rows.Done) + require.Len(t, rows.Versions, 600) + for _, row := range rows.Versions { + require.Equal(t, uint64(30), row.CommitTS) + } + // Snapshot restore discards cached local completion. A snapshot may + // contain retired physical rows that another member already collected. + require.NoError(t, st.Restore(bytes.NewReader(payload.Bytes()))) + result, err := retirement.ReclaimVersionRetirement(t.Context(), record.JobID, record.ID) + require.NoError(t, err) + require.False(t, result.Done) + require.Equal(t, uint64(retirementReclaimPageVersions), result.DeletedRows, "restored physical rows invalidate a cached local completion") + require.NoError(t, raftEntryApplier(t, st).ApplyRaftEntry(t.Context(), 2, func(ctx context.Context) error { + _, err := retirement.ReclaimVersionRetirement(ctx, record.JobID, record.ID) + require.ErrorIs(t, err, ErrRaftControlScopeRequired) + return nil + })) + }) +} diff --git a/store/version_retirement_test.go b/store/version_retirement_test.go new file mode 100644 index 000000000..84e859edd --- /dev/null +++ b/store/version_retirement_test.go @@ -0,0 +1,260 @@ +package store + +import ( + "bytes" + "context" + "testing" + + "github.com/cockroachdb/errors" + "github.com/stretchr/testify/require" +) + +func retirementTestCompiler(selector []byte) (func([]byte, []byte) bool, error) { + if !bytes.Equal(selector, []byte("all/v1")) { + return nil, ErrVersionRetirementUnavailable + } + return func(_, _ []byte) bool { return true }, nil +} + +func retirementTestRecord() VersionRetirement { + return VersionRetirement{ID: "job/7/user", JobID: 7, GroupID: 1, ConfigurationIndex: 9, + Generation: "owner-1", CommitCeiling: 20, StartKey: []byte("n"), EndKey: []byte("o"), Selector: []byte("all/v1")} +} + +func retirementStoreForTest(t *testing.T, st MVCCStore) VersionRetirementStore { + t.Helper() + retirement, ok := st.(VersionRetirementStore) + require.True(t, ok) + return retirement +} + +func forEachRetirementStore(t *testing.T, run func(*testing.T, MVCCStore)) { + t.Helper() + for _, kind := range []string{"memory", "pebble", "sst"} { + t.Run(kind, func(t *testing.T) { + st := NewMVCCStore() + if kind != "memory" { + var err error + st, err = NewPebbleStore(t.TempDir(), WithSSTIngestSnapshots(kind == "sst")) + require.NoError(t, err) + } + t.Cleanup(func() { require.NoError(t, st.Close()) }) + require.NoError(t, retirementStoreForTest(t, st).ConfigureVersionRetirement(retirementTestCompiler)) + run(t, st) + }) + } +} + +func applyRetirementForTest(t *testing.T, st MVCCStore, index uint64) { + t.Helper() + require.NoError(t, raftEntryApplier(t, st).ApplyRaftEntry(t.Context(), index, func(ctx context.Context) error { + if _, err := StageRaftEntryProgress(ctx, index); err != nil { + return err + } + return retirementStoreForTest(t, st).StageVersionRetirement(ctx, retirementTestRecord()) + })) +} + +func TestVersionRetirementPointAndScanVisibility(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + ctx := t.Context() + require.NoError(t, st.PutAt(ctx, []byte("n"), []byte("old"), 10, 0)) + require.NoError(t, st.PutAt(ctx, []byte("n"), []byte("current"), 20, 0)) + require.NoError(t, st.PutAt(ctx, []byte("outside"), []byte("unaffected"), 10, 0)) + applyRetirementForTest(t, st, 1) + for _, ts := range []uint64{10, 20, 30} { + _, err := st.GetAt(ctx, []byte("n"), ts) + require.ErrorIs(t, err, ErrKeyNotFound) + exists, err := st.ExistsAt(ctx, []byte("n"), ts) + require.NoError(t, err) + require.False(t, exists) + forward, err := st.ScanAt(ctx, []byte("n"), []byte("o"), 10, ts) + require.NoError(t, err) + require.Empty(t, forward) + reverse, err := st.ReverseScanAt(ctx, []byte("n"), []byte("o"), 10, ts) + require.NoError(t, err) + require.Empty(t, reverse) + keys, err := st.ScanKeysAt(ctx, []byte("n"), []byte("o"), 10, ts) + require.NoError(t, err) + require.Empty(t, keys) + } + _, found, err := st.LatestCommitTS(ctx, []byte("n")) + require.NoError(t, err) + require.False(t, found) + found, err = st.CommittedVersionAt(ctx, []byte("n"), 20) + require.NoError(t, err) + require.False(t, found) + value, err := st.GetAt(ctx, []byte("outside"), 30) + require.NoError(t, err) + require.Equal(t, []byte("unaffected"), value) + require.NoError(t, st.PutAt(ctx, []byte("n"), []byte("new-generation"), 40, 0)) + row, err := GetVersionAt(ctx, st, []byte("n"), 50) + require.NoError(t, err) + require.Equal(t, uint64(40), row.TS) + require.Equal(t, []byte("new-generation"), row.Value) + }) +} + +func TestVersionRetirementAtomicityAndIdentity(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("live"), 20, 0)) + rejected := errors.New("discard entry") + err := raftEntryApplier(t, st).ApplyRaftEntry(t.Context(), 1, func(ctx context.Context) error { + if err := retirementStoreForTest(t, st).StageVersionRetirement(ctx, retirementTestRecord()); err != nil { + return err + } + return rejected + }) + require.ErrorIs(t, err, rejected) + value, err := st.GetAt(t.Context(), []byte("n"), 30) + require.NoError(t, err) + require.Equal(t, []byte("live"), value) + applyRetirementForTest(t, st, 1) + applyRetirementForTest(t, st, 2) + err = raftEntryApplier(t, st).ApplyRaftEntry(t.Context(), 3, func(ctx context.Context) error { + record := retirementTestRecord() + record.CommitCeiling++ + return retirementStoreForTest(t, st).StageVersionRetirement(ctx, record) + }) + require.ErrorIs(t, err, ErrVersionRetirementConflict) + }) +} + +func TestVersionRetirementSurvivesSnapshotAndRequiresCompiler(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, source MVCCStore) { + require.NoError(t, source.PutAt(t.Context(), []byte("n"), []byte("old"), 10, 0)) + require.NoError(t, source.PutAt(t.Context(), []byte("n"), []byte("head"), 20, 0)) + applyRetirementForTest(t, source, 1) + snapshot, err := source.Snapshot() + require.NoError(t, err) + defer func() { require.NoError(t, snapshot.Close()) }() + var payload bytes.Buffer + _, err = snapshot.WriteTo(&payload) + require.NoError(t, err) + destinations := []MVCCStore{openSSTSnapshotTestStore(t, t.TempDir())} + if _, memory := source.(*mvccStore); memory { + destinations = append(destinations, NewMVCCStore()) + } + for _, destination := range destinations { + require.NoError(t, destination.Restore(bytes.NewReader(payload.Bytes()))) + _, err := destination.GetAt(t.Context(), []byte("n"), 30) + require.ErrorIs(t, err, ErrVersionRetirementUnavailable) + require.NoError(t, retirementStoreForTest(t, destination).ConfigureVersionRetirement(retirementTestCompiler)) + _, err = destination.GetAt(t.Context(), []byte("n"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) + } + }) +} + +func TestVersionRetirementEncryptedReopen(t *testing.T) { + fixture := newEncryptedStoreFixture(t, 1) + require.NoError(t, retirementStoreForTest(t, fixture.mvcc).ConfigureVersionRetirement(retirementTestCompiler)) + require.NoError(t, fixture.mvcc.PutAt(t.Context(), []byte("n"), []byte("old"), 10, 0)) + applyRetirementForTest(t, fixture.mvcc, 1) + fixture.closeIfOpen(t) + fixture.reopen(t) + _, err := fixture.mvcc.GetAt(t.Context(), []byte("n"), 30) + require.ErrorIs(t, err, ErrVersionRetirementUnavailable) + require.NoError(t, retirementStoreForTest(t, fixture.mvcc).ConfigureVersionRetirement(retirementTestCompiler)) + _, err = fixture.mvcc.GetAt(t.Context(), []byte("n"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) +} + +func TestVersionRetirementRejectsStaleImportsAndFiltersExports(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("old"), 10, 0)) + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("head"), 20, 0)) + applyRetirementForTest(t, st, 1) + exported, err := st.ExportVersions(t.Context(), ExportVersionsOptions{ + StartKey: []byte("n"), EndKey: []byte("o"), MaxVersions: 10, + }) + require.NoError(t, err) + require.True(t, exported.Done) + require.Empty(t, exported.Versions) + _, err = st.ImportVersions(t.Context(), ImportVersionsOptions{JobID: 8, BatchSeq: 1, + Versions: []MVCCVersion{{Key: []byte("n"), CommitTS: 20, Value: []byte("head")}}, + }) + require.ErrorIs(t, err, ErrMigrationRetired) + }) +} + +func TestVersionRetirementRejectsStaleWritesBeforeAnyBatchEffects(t *testing.T) { + forEachRetirementStore(t, func(t *testing.T, st MVCCStore) { + ctx := t.Context() + require.NoError(t, st.PutAt(ctx, []byte("n"), []byte("old"), 10, 0)) + applyRetirementForTest(t, st, 1) + mutations := []*KVPairMutation{ + {Op: OpTypePut, Key: []byte("a"), Value: []byte("must-not-land")}, + {Op: OpTypePut, Key: []byte("n"), Value: []byte("retired")}, + } + require.ErrorIs(t, st.PutAt(ctx, []byte("n"), []byte("retired"), 20, 0), ErrMigrationRetired) + require.ErrorIs(t, st.DeleteAt(ctx, []byte("n"), 20), ErrMigrationRetired) + require.ErrorIs(t, st.ApplyMutations(ctx, mutations, nil, 20, 20), ErrMigrationRetired) + prepared, ok := st.(PreparedMutationApplier) + require.True(t, ok) + require.ErrorIs(t, prepared.ApplyPreparedMutationsRaftAt(ctx, mutations, nil, 20, 20, nil, 0), ErrMigrationRetired) + _, err := st.GetAt(ctx, []byte("a"), 40) + require.ErrorIs(t, err, ErrKeyNotFound) + require.ErrorIs(t, st.ExpireAt(ctx, []byte("n"), 50, 30), ErrKeyNotFound) + require.NoError(t, st.DeletePrefixAt(ctx, []byte("n"), nil, 40)) + _, found, err := st.LatestCommitTS(ctx, []byte("n")) + require.NoError(t, err) + require.False(t, found, "prefix delete must not create a new head for a logically absent key") + require.True(t, IsApplyVerdict(ErrMigrationRetired)) + }) +} + +func TestVersionRetirementReclamationAgreesAfterIndependentCompaction(t *testing.T) { + for _, compact := range []bool{false, true} { + t.Run(map[bool]string{false: "uncompacted", true: "compacted"}[compact], func(t *testing.T) { + api, err := NewPebbleStore(t.TempDir()) + require.NoError(t, err) + st, ok := api.(*pebbleStore) + require.True(t, ok) + closed := false + t.Cleanup(func() { + if !closed { + require.NoError(t, st.Close()) + } + }) + require.NoError(t, st.ConfigureVersionRetirement(retirementTestCompiler)) + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("old"), 10, 0)) + require.NoError(t, st.PutAt(t.Context(), []byte("n"), []byte("head"), 20, 0)) + if compact { + require.NoError(t, st.Compact(t.Context(), 21)) + } + applyRetirementForTest(t, st, 1) + var deleted uint64 + var cursor []byte + for index := uint64(2); index < 6; index++ { + _, err := GetVersionAt(t.Context(), st, []byte("n"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) + var result CleanupVersionsResult + require.NoError(t, st.ApplyRaftEntry(t.Context(), index, func(ctx context.Context) error { + if _, err := StageRaftEntryProgress(ctx, index); err != nil { + return err + } + var err error + result, err = StageRaftEntryMigrationCleanup(ctx, CleanupVersionsOptions{JobID: 7, AppliedIndex: index, + StartKey: []byte("n"), EndKey: []byte("o"), MaxCommitTS: 20, MaxVersions: 1, Cursor: cursor}) + return err + })) + deleted += result.DeletedRows + cursor = result.NextCursor + if result.Done { + break + } + } + require.NotZero(t, deleted, "physical reclamation must actually remove rows") + _, err = GetVersionAt(t.Context(), st, []byte("n"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) + dir := st.dir + require.NoError(t, st.Close()) + closed = true + reopened := openSSTSnapshotTestStore(t, dir) + require.NoError(t, reopened.ConfigureVersionRetirement(retirementTestCompiler)) + _, err = GetVersionAt(t.Context(), reopened, []byte("n"), 30) + require.ErrorIs(t, err, ErrKeyNotFound) + }) + } +} diff --git a/store/versioned_read_test.go b/store/versioned_read_test.go new file mode 100644 index 000000000..1fc143774 --- /dev/null +++ b/store/versioned_read_test.go @@ -0,0 +1,99 @@ +package store + +import ( + "bytes" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGetVersionAtVisibility(t *testing.T) { + t.Parallel() + forEachMVCCStore(t, func(t *testing.T, newStore func(*testing.T) MVCCStore) { + ctx := context.Background() + st := newStore(t) + key := []byte("key") + require.NoError(t, st.PutAt(ctx, key, []byte("old"), 10, 0)) + require.NoError(t, st.PutAt(ctx, key, []byte{}, 20, 25)) + require.NoError(t, st.PutAt(ctx, key, []byte("new"), 30, 0)) + require.NoError(t, st.DeleteAt(ctx, key, 40)) + + for _, tc := range []struct { + snapshot uint64 + want VersionedValue + }{ + {9, VersionedValue{}}, + {19, VersionedValue{TS: 10, Value: []byte("old")}}, + {24, VersionedValue{TS: 20, Value: []byte{}, ExpireAt: 25}}, + {25, VersionedValue{}}, + {39, VersionedValue{TS: 30, Value: []byte("new")}}, + {40, VersionedValue{}}, + } { + got, err := GetVersionAt(ctx, st, key, tc.snapshot) + require.Equal(t, tc.want, got, "snapshot %d", tc.snapshot) + if tc.want.TS == 0 { + require.ErrorIs(t, err, ErrKeyNotFound) + } else { + require.NoError(t, err) + } + } + + got, err := GetVersionAt(ctx, st, key, 19) + require.NoError(t, err) + got.Value[0] = 'X' + got, err = GetVersionAt(ctx, st, key, 19) + require.NoError(t, err) + require.Equal(t, []byte("old"), got.Value) + + retention, ok := st.(RetentionController) + require.True(t, ok) + retention.SetMinRetainedTS(20) + _, err = GetVersionAt(ctx, st, key, 19) + require.ErrorIs(t, err, ErrReadTSCompacted) + }) +} + +func TestGetVersionAtEncrypted(t *testing.T) { + t.Parallel() + f := newEncryptedStoreFixture(t, 17) + ctx := context.Background() + key := []byte("encrypted") + value := bytes.Repeat([]byte("compressible"), 100) + require.NoError(t, f.mvcc.PutAt(ctx, key, value, 10, 20)) + got, err := GetVersionAt(ctx, f.mvcc, key, 15) + require.NoError(t, err) + require.Equal(t, VersionedValue{TS: 10, Value: value, ExpireAt: 20}, got) + _, err = GetVersionAt(ctx, f.mvcc, key, 20) + require.ErrorIs(t, err, ErrKeyNotFound) + + f.tamperPebbleValue(t, key, 10, func(raw []byte) []byte { + raw[0] |= 1 // tombstone bit in the authenticated header + return raw + }) + _, err = GetVersionAt(ctx, f.mvcc, key, 20) + require.ErrorIs(t, err, ErrEncryptedReadIntegrity) +} + +func TestGetVersionAtSeesStagedRaftEntry(t *testing.T) { + t.Parallel() + forEachMVCCStore(t, func(t *testing.T, newStore func(*testing.T) MVCCStore) { + ctx := context.Background() + st := newStore(t) + key := []byte("key") + require.NoError(t, st.PutAt(ctx, key, []byte("old"), 10, 0)) + applier, ok := st.(RaftEntryApplier) + require.True(t, ok) + require.NoError(t, applier.ApplyRaftEntry(ctx, 1, func(entryCtx context.Context) error { + mutations := raftEntryPut("key", "staged") + mutations[0].ExpireAt = 30 + if err := st.ApplyMutationsRaftAt(entryCtx, mutations, nil, 20, 20, 1); err != nil { + return err + } + got, err := GetVersionAt(entryCtx, st, key, 25) + require.NoError(t, err) + require.Equal(t, VersionedValue{TS: 20, Value: []byte("staged"), ExpireAt: 30}, got) + return nil + })) + }) +} diff --git a/tla/README.md b/tla/README.md index 101a941d9..8e97a0f74 100644 --- a/tla/README.md +++ b/tla/README.md @@ -7,6 +7,9 @@ Machine-checkable safety models for the four cross-cutting subsystems This directory is **independent of the Go module**; you can navigate and run it without touching anything under the Go source tree. +The [single-key MVCC CAS model](cas/README.md) has a focused +`make tla-cas-check` target and also runs under `make tla-check`. + ## Status | Milestone | Scope | Status | diff --git a/tla/cas/README.md b/tla/cas/README.md new file mode 100644 index 000000000..ccf2a9161 --- /dev/null +++ b/tla/cas/README.md @@ -0,0 +1,85 @@ +# Single-key MVCC CAS safety + +The two [FSM regressions](../../docs/evidence/2026_11_20_single_key_mvcc_cas_review.md#final-pre-pr-review-on-main-2026-11-21) concern one direct byte-range key. Two replicas applying the same CAS at the same index disagreed when one watcher lagged a same-owner split. A bounded cleanup could remove the new head and let a second CAS consume the original token again. + +## Implementation correspondence + +| Model | ElasticKV | +| --- | --- | +| Shared log, indexed apply, durable image, replay | The log is committed by Raft. `applyCASEntry` and `applyVersionIdentityCleanup` stage the result and applied index together. `StageRaftEntryProgress` skips already durable entries. A local apply error aborts the scope and halts at that index. [CAS FSM](../../kv/fsm_cas.go), [cleanup FSM](../../kv/fsm_migration_cleanup.go), [entry progress](../../store/raft_entry_cas.go) | +| Replicated catalog and independent watcher | Public routing selects a candidate group. The frame binds the request to that group and an admitted catalog version. `checkAppliedVersionCASRoute` reads the group's own catalog inside indexed apply and checks the version floor and authority. A same-owner split preserves the write right. A real fence or ownership loss records an indexed route rejection. A missing authoritative catalog or an unmet version floor prevents progress on an injected frame. [CAS routing](../../kv/version_cas_route.go), [CAS FSM](../../kv/fsm_cas.go) | +| Activation, temporary readiness, permanent coverage | The replicated migration version-identity marker turns on the cleanup guard. A cleanup affecting a direct key requires durable evidence covering its entire effective interval. Retirement preserves legacy certificates and partition transitions preserve or expand the covered union. Temporary readiness excludes the key from CAS while armed. Only permanent coverage authorizes protected cleanup of a direct key. The model projects permanent coverage of the effective interval to a boolean for its single key. [Activation and coverage](../../kv/migration_version_identity.go), [CAS routing](../../kv/version_cas_route.go) | +| Exact comparison, versions, bounded cleanup | `compareAndStageCAS` checks the commit watermark, compares the live head with the expected version, and stages the replacement. The model orders rows newest first and selects up to the page limit at or below the ceiling after a cursor. Coverage is checked before scanning, independently of page contents. Legacy cleanup can run before activation. [CAS FSM](../../kv/fsm_cas.go), [cleanup FSM](../../kv/fsm_migration_cleanup.go), [cleanup store](../../store/migration_cleanup.go) | + +## Claims and bounds + +- **Lean 4.** `applied_prefix` proves by induction that a replica's durable image comes from folding the first `applied` entries. `replica_agreement` gives equality of all rows and values, catalog and protection state, and modeled per-entry verdicts at equal applied indices, regardless of watcher progress, restart or replay. `reachable_safe` establishes duplicate-free consumption and proves that a previously consumed token is strictly below the head while the range lacks permanent coverage. `consumed_token_cannot_apply_again` also covers the permanently excluded case, where physical cleanup may expose an older row. The proofs quantify over arbitrary finite committed logs, natural-number versions and cleanup page sizes. +- **TLC.** The configuration explores every commit, apply and watcher schedule for six bounded workloads, with two voters, one key, initial version 1, catalog versions 1โ€“4 and at most eight entries per workload. It permits one leader change and one recorded replay per voter. It checks progress bounds, equal-index agreement, single consumption, no token revival while uncovered, row and version order, and the expected verdicts and halt preconditions. The workloads cover a same-owner split, a real fence, a real ownership loss, readiness versus permanent coverage, pre-activation cleanup with a cursor, stale tokens, reused write timestamps and an injected CAS lacking the required catalog authority or version. +- **Negative controls.** The watcher gap fails `EqualAppliedIndexAgrees` after the same CAS advances both applied indices. Catching up and replaying that index would skip the entry. The cleanup gap fails `SingleConsumption` after a one-row page deletes the new head and the old token succeeds again. Lean contains executable examples of both defects and the modeled fixes. + +The positive agreement proofs assume a common committed prefix and recoverable atomic persistence of each durable image and index in one cluster history. Matching imports and snapshot installs must preserve that history, including the commit watermark, activation marker and durable coverage. The models treat lock-free, live, non-expiring direct keys with valid CAS start timestamps and a pre-existing commit timestamp fence. Other keys and leader timestamp allocation are abstracted into the replicated watermark. Raft, Pebble, interval coverage calculation, WAL recovery, administrative rewind, TTL, locks, and mixed-key transactions sit outside the model. The consumed-token and verdict histories are proof state. The Go store derives the guarantee from exact comparison, increasing versions and protected cleanup. + +## Logical Retirement + +The adaptive request-level precheck and local per-key proposal lanes do not +change these indexed FSM transitions. A pre-submission mismatch is a stuttering +step for the replicated image and has no apply receipt. The models do not +prove the request-owned ReadIndex/pin, capability or forwarding certificate +implementation, nor do they infer a client outcome from a lane release. Go +tests separately cover stale hints, failed fences, locks, route changes, +same-key contenders, local/forwarded sharing, cancellation and leadership retry. + +[`LogicalRetirement.lean`](../../lean/LogicalRetirement.lean) specifies the +visibility boundary implemented by the replacement protocol. Its retirement ceiling is assumed +to be authorized, replicated, durable and restored before reads are admitted. +It proves that removing any subset of rows at or below that ceiling preserves +the visible rows, even if replicas select different pages or deletion counts. +Retiring all previously issued versions produces absence independently of local +retention, while a newer write remains visible. Executable examples retain the +old predecessor-resurrection counterexample and exercise both partial and full +physical collection after retirement. + +`SingleKeyCAS_retirement.cfg` permits independent physical compaction and checks +visible-head agreement after replicated retirement. A separate reachability +configuration requires an actual successful CAS, retirement and completed +physical cleanup on both voters, with a newer surviving row. The old +`SingleKeyCAS_retention_gap.cfg` remains a physical-only negative control. + +The proof does not establish range authorization, capability negotiation, +snapshot pin fencing, storage metadata recovery or enforcement by every Go +read/export/import path. Those remain implementation and acceptance gates. In +particular, the original Go regression still requires real physical deletion +and logical absence on both independently compacted replicas. It is not skipped +or changed into an expected failure. Go tests separately exercise encrypted +reopen, snapshots, bounded local GC, stale-write rejection and learner/configuration +completion barriers. + +## Version Adoption + +[`VersionAdoption.lean`](../../lean/VersionAdoption.lean) proves that epoch-aware +physical collection preserves visible rows, that adoption preserves the original +timestamp/value/TTL, and that a later retirement hides an adopted generation. +Its authorization and monotonic epoch allocation are assumptions, not derived +claims about the RPC protocol. + +`VersionAdoption.cfg` checks two replicas, independent predecessor compaction, +two retire/return cycles, local one-row GC of either old retirement, restart and +replay. Equal applied indexes retain the same visible head and epoch bound. +The timestamp-only collector fails `EqualIndexVisibleHead` in the gap control. +The reachability control must reach both completed returns with the original +timestamp/value/TTL after restart/replay. It models same-lineage persistence, +not snapshot bytes, proof authorization or cryptographic integrity; Go tests +cover those boundaries separately. + +## Run + +From the repository root, run + +```sh +make lean-check +make tla-cas-check +``` + +`make lean-check` uses the version in [lean/lean-toolchain](../../lean/lean-toolchain) when invoked through Elan. Set `LEAN` to use that version's installed binary directly. The TLC targets use the checksum-pinned jar from `make tla-tools`. `make tla-check` includes the CAS suite and the other repository models. The retention-gap scenario still fails `VisibleHeadAgrees` under the old policy; the retirement scenario passes that invariant under the new policy. + +The CAS target fails if the protected model fails, a negative control passes, or a negative control reports a different invariant or tool failure. diff --git a/tla/cas/SingleKeyCAS.cfg b/tla/cas/SingleKeyCAS.cfg new file mode 100644 index 000000000..72f3eab24 --- /dev/null +++ b/tla/cas/SingleKeyCAS.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + UseWatcher = FALSE + UnprotectedCleanup = FALSE + LogicalRetirement = FALSE +INVARIANTS + ProgressBounds + EqualAppliedIndexAgrees + SingleConsumption + NoTokenRevival + VersionOrder + ExpectedVerdicts + ExpectedReadiness +PROPERTY ProducedVersionsAdvance +CHECK_DEADLOCK FALSE diff --git a/tla/cas/SingleKeyCAS.tla b/tla/cas/SingleKeyCAS.tla new file mode 100644 index 000000000..4bfe76fda --- /dev/null +++ b/tla/cas/SingleKeyCAS.tla @@ -0,0 +1,234 @@ +---------------------------- MODULE SingleKeyCAS ---------------------------- +EXTENDS Naturals, Sequences, FiniteSets + +CONSTANTS UseWatcher, UnprotectedCleanup, LogicalRetirement + +Nodes == {1, 2} + +Row(version, value) == [version |-> version, value |-> value] +Catalog(version, owns, fenced) == + [version |-> version, owns |-> owns, fenced |-> fenced] + +Activate == [kind |-> "activate"] +Split == [kind |-> "catalog", route |-> Catalog(2, TRUE, FALSE)] +Fence == [kind |-> "catalog", route |-> Catalog(3, TRUE, TRUE)] +Move == [kind |-> "catalog", route |-> Catalog(4, FALSE, FALSE)] +Arm(armed) == [kind |-> "arm", armed |-> armed] +Certify == [kind |-> "certify"] +Put(version, value) == [kind |-> "put", row |-> Row(version, value)] +CAS(observed, expected, version, value) == + [kind |-> "cas", observed |-> observed, expected |-> expected, + row |-> Row(version, value)] +Cleanup(cursor, ceiling, limit) == + [kind |-> "cleanup", cursor |-> cursor, ceiling |-> ceiling, limit |-> limit] + +Workload(authority, entries, verdicts) == + [authority |-> authority, entries |-> entries, verdicts |-> verdicts] + +\* Each log is shared. Commit, watcher progress, replay, leader change and +\* each replica's apply order interleave independently within each workload. +Workloads == { + Workload(TRUE, + <>, + <<"control", "control", "applied", "cleanupBlocked", "mismatch", "applied">>), + Workload(TRUE, + <>, + <<"control", "control", "applied", "control", "routeFenced", + "control", "routeFenced">>), + Workload(TRUE, + <>, + <<"control", "applied", "control", "cleanupBlocked", "control", + "cleaned", "control", "unavailable">>), + Workload(TRUE, + <>, + <<"written", "written", "cleaned", "control", "mismatch", "timestamp", "applied">>), + Workload(FALSE, + <>, + <<"control", "halt">>), + Workload(TRUE, + <>, + <<"control", "halt">>) +} + +VARIABLES workload, committed, replicas, leader +vars == <> + +Image(authority) == + [route |-> IF authority THEN Catalog(1, TRUE, FALSE) ELSE Catalog(0, FALSE, FALSE), + protection |-> FALSE, armed |-> FALSE, covered |-> FALSE, + rows |-> <>, retiredFloor |-> 0, issued |-> 1, consumed |-> <<>>, verdicts |-> <<>>] + +InitialReplicas == + /\ committed = 0 + /\ leader = 1 + /\ replicas = [n \in Nodes |-> [index |-> 0, watcher |-> 1, replayed |-> FALSE, + image |-> Image(workload.authority)]] + +Init == workload \in Workloads /\ InitialReplicas + +VisibleRows(s) == SelectSeq(s.rows, LAMBDA row: row.version > s.retiredFloor) +HeadVersion(s) == LET rows == VisibleRows(s) IN IF rows = <<>> THEN 0 ELSE rows[1].version +Record(s, verdict) == [s EXCEPT !.verdicts = Append(@, verdict)] +Write(s, row) == [s EXCEPT !.rows = <> \o @, !.issued = row.version] + +CleanRows(rows, e) == + LET eligible == SelectSeq(SubSeq(rows, e.cursor + 1, Len(rows)), + LAMBDA row: row.version <= e.ceiling) + selected == SubSeq(eligible, 1, IF e.limit < Len(eligible) THEN e.limit ELSE Len(eligible)) + IN SelectSeq(rows, LAMBDA row: \A i \in DOMAIN selected: selected[i] # row) + +ApplyCAS(s, watcher, e) == + IF ~s.protection \/ s.route.version = 0 THEN Record(s, "unavailable") + ELSE IF ~s.route.owns \/ s.route.fenced THEN Record(s, "routeFenced") + ELSE IF s.armed \/ s.covered THEN Record(s, "unavailable") + ELSE IF UseWatcher /\ watcher < e.observed THEN Record(s, "missingCatalog") + ELSE IF e.row.version <= s.issued THEN Record(s, "timestamp") + ELSE IF e.expected = 0 \/ e.expected # HeadVersion(s) THEN Record(s, "mismatch") + ELSE Record([Write(s, e.row) EXCEPT !.consumed = Append(@, e.expected)], "applied") + +ApplyEntry(s, watcher, e) == + CASE e.kind = "activate" -> Record([s EXCEPT !.protection = TRUE], "control") + [] e.kind = "catalog" -> + Record(IF s.route.version = 0 THEN s ELSE [s EXCEPT !.route = e.route], "control") + [] e.kind = "arm" -> Record([s EXCEPT !.armed = e.armed], "control") + [] e.kind = "certify" -> Record([s EXCEPT !.covered = TRUE], "control") + [] e.kind = "put" -> + IF e.row.version <= s.issued THEN Record(s, "timestamp") + ELSE Record(Write(s, e.row), "written") + [] e.kind = "cas" -> ApplyCAS(s, watcher, e) + [] e.kind = "cleanup" -> + IF s.protection /\ ~UnprotectedCleanup /\ ~s.covered THEN Record(s, "cleanupBlocked") + ELSE Record([s EXCEPT !.rows = CleanRows(@, e), + !.retiredFloor = IF LogicalRetirement /\ s.protection /\ e.ceiling > @ + THEN e.ceiling ELSE @], "cleaned") + +CanApply(s, e) == + IF e.kind = "cas" + THEN s.protection /\ s.route.version # 0 /\ e.observed <= s.route.version + ELSE TRUE + +Commit(n) == + /\ n = leader + /\ committed < Len(workload.entries) + /\ committed' = committed + 1 + /\ UNCHANGED <> + +CatalogPublished == + 1 + Cardinality({i \in 1..committed: workload.entries[i].kind = "catalog"}) + +Watch(n) == + /\ replicas[n].watcher < CatalogPublished + /\ replicas' = [replicas EXCEPT ![n].watcher = @ + 1] + /\ UNCHANGED <> + +Apply(n) == + LET r == replicas[n] + i == r.index + 1 + IN /\ i <= committed + /\ CanApply(r.image, workload.entries[i]) + /\ replicas' = [replicas EXCEPT ![n].index = i, + ![n].image = ApplyEntry(r.image, r.watcher, workload.entries[i])] + /\ UNCHANGED <> + +Elect == + \* Both voters retain access to the committed log after election. + /\ leader = 1 + /\ leader' = 2 + /\ UNCHANGED <> + +Replay(n) == + \* A restarted/re-elected voter can encounter any already durable entry. + \* Only replayed changes, to make this otherwise stuttering step visible. + /\ leader = 2 + /\ replicas[n].index > 0 + /\ ~replicas[n].replayed + /\ replicas' = [replicas EXCEPT ![n].replayed = TRUE] + /\ UNCHANGED <> + +Next == Elect \/ \E n \in Nodes: Commit(n) \/ Watch(n) \/ Apply(n) \/ Replay(n) +Spec == Init /\ [][Next]_vars + + +\* Independent compaction preserves the visible head and changes no log index. +\* Restrict it to the point after coverage is installed and before cleanup. +CompactCovered(n) == + /\ replicas[n].index = 3 + /\ Len(replicas[n].image.rows) > 1 + /\ replicas' = [replicas EXCEPT ![n].image.rows = SubSeq(@, 1, 1)] + /\ UNCHANGED <> + +RetentionInit == + /\ workload = Workload(TRUE, <>, + <<"control", "applied", "control", "cleaned", "written", "cleaned">>) + /\ InitialReplicas + +RetentionSpec == RetentionInit /\ [][Next \/ (\E n \in Nodes: CompactCovered(n))]_vars + +VisibleHead(s) == LET rows == VisibleRows(s) IN IF rows = <<>> THEN <<>> ELSE <> + +VisibleHeadAgrees == + \A a, b \in Nodes: + replicas[a].index = replicas[b].index => + VisibleHead(replicas[a].image) = VisibleHead(replicas[b].image) + +\* An expected counterexample to this invariant proves a completed execution +\* exists: successful CAS, retirement, reclamation, and a newer surviving row. +RetirementCompletionUnreachable == + ~(\A n \in Nodes: + /\ replicas[n].index = Len(workload.entries) + /\ replicas[n].image.retiredFloor = 2 + /\ replicas[n].image.consumed = <<1>> + /\ replicas[n].image.rows = <>) + +ProgressBounds == + /\ committed \in 0..Len(workload.entries) + /\ \A n \in Nodes: + /\ replicas[n].index \in 0..committed + /\ replicas[n].watcher \in 1..CatalogPublished + /\ Len(replicas[n].image.verdicts) = replicas[n].index + +EqualAppliedIndexAgrees == + \A a, b \in Nodes: + replicas[a].index = replicas[b].index => replicas[a].image = replicas[b].image + +SingleConsumption == + \A n \in Nodes: + LET tokens == replicas[n].image.consumed + IN Len(tokens) = Cardinality({tokens[i]: i \in DOMAIN tokens}) + +NoTokenRevival == + \A n \in Nodes: + LET s == replicas[n].image + IN s.covered \/ \A i \in DOMAIN s.consumed: s.consumed[i] < HeadVersion(s) + +VersionOrder == + \A n \in Nodes: + LET s == replicas[n].image + IN /\ \A i \in DOMAIN s.rows: s.rows[i].version \in 1..s.issued + /\ \A i, j \in DOMAIN s.rows: i < j => s.rows[i].version > s.rows[j].version + /\ \A i \in DOMAIN s.consumed: s.consumed[i] < s.issued + +ProducedVersionsAdvance == + [][\A n \in Nodes: + LET before == replicas[n].image + after == replicas'[n].image + IN /\ before.issued <= after.issued + /\ Len(before.rows) < Len(after.rows) => before.issued < after.issued]_vars + +ExpectedVerdicts == + \A n \in Nodes: + replicas[n].image.verdicts = SubSeq(workload.verdicts, 1, replicas[n].index) + +ExpectedReadiness == + \A n \in Nodes: + LET r == replicas[n] + i == r.index + 1 + IN i <= committed => + (CanApply(r.image, workload.entries[i]) <=> workload.verdicts[i] # "halt") + +============================================================================= diff --git a/tla/cas/SingleKeyCAS_cleanup_gap.cfg b/tla/cas/SingleKeyCAS_cleanup_gap.cfg new file mode 100644 index 000000000..0bf4e403c --- /dev/null +++ b/tla/cas/SingleKeyCAS_cleanup_gap.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS + UseWatcher = FALSE + UnprotectedCleanup = TRUE + LogicalRetirement = FALSE +INVARIANT SingleConsumption +CHECK_DEADLOCK FALSE diff --git a/tla/cas/SingleKeyCAS_retention_gap.cfg b/tla/cas/SingleKeyCAS_retention_gap.cfg new file mode 100644 index 000000000..59374c367 --- /dev/null +++ b/tla/cas/SingleKeyCAS_retention_gap.cfg @@ -0,0 +1,7 @@ +SPECIFICATION RetentionSpec +CONSTANTS + UseWatcher = FALSE + UnprotectedCleanup = FALSE + LogicalRetirement = FALSE +INVARIANT VisibleHeadAgrees +CHECK_DEADLOCK FALSE diff --git a/tla/cas/SingleKeyCAS_retirement.cfg b/tla/cas/SingleKeyCAS_retirement.cfg new file mode 100644 index 000000000..53eef9b29 --- /dev/null +++ b/tla/cas/SingleKeyCAS_retirement.cfg @@ -0,0 +1,11 @@ +SPECIFICATION RetentionSpec +CONSTANTS + UseWatcher = FALSE + UnprotectedCleanup = FALSE + LogicalRetirement = TRUE +INVARIANTS + ProgressBounds + VisibleHeadAgrees + SingleConsumption + VersionOrder +CHECK_DEADLOCK FALSE diff --git a/tla/cas/SingleKeyCAS_retirement_reachable.cfg b/tla/cas/SingleKeyCAS_retirement_reachable.cfg new file mode 100644 index 000000000..b96eee831 --- /dev/null +++ b/tla/cas/SingleKeyCAS_retirement_reachable.cfg @@ -0,0 +1,7 @@ +SPECIFICATION RetentionSpec +CONSTANTS + UseWatcher = FALSE + UnprotectedCleanup = FALSE + LogicalRetirement = TRUE +INVARIANT RetirementCompletionUnreachable +CHECK_DEADLOCK FALSE diff --git a/tla/cas/SingleKeyCAS_watcher_gap.cfg b/tla/cas/SingleKeyCAS_watcher_gap.cfg new file mode 100644 index 000000000..3fd5bfd60 --- /dev/null +++ b/tla/cas/SingleKeyCAS_watcher_gap.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS + UseWatcher = TRUE + UnprotectedCleanup = FALSE + LogicalRetirement = FALSE +INVARIANT EqualAppliedIndexAgrees +CHECK_DEADLOCK FALSE diff --git a/tla/cas/VersionAdoption.cfg b/tla/cas/VersionAdoption.cfg new file mode 100644 index 000000000..e628512a5 --- /dev/null +++ b/tla/cas/VersionAdoption.cfg @@ -0,0 +1,4 @@ +CONSTANT LegacyGC = FALSE +SPECIFICATION Spec +INVARIANTS EqualIndexVisibleHead EpochBound ReturnedVersionPreserved +CHECK_DEADLOCK FALSE diff --git a/tla/cas/VersionAdoption.tla b/tla/cas/VersionAdoption.tla new file mode 100644 index 000000000..41c7952b7 --- /dev/null +++ b/tla/cas/VersionAdoption.tla @@ -0,0 +1,86 @@ +-------------------------- MODULE VersionAdoption -------------------------- +EXTENDS Naturals, Sequences + +CONSTANT LegacyGC +Nodes == {1, 2} +Row(ts, epoch) == [ts |-> ts, value |-> ts, expiry |-> 1000, epoch |-> epoch] +Retirement(ceiling, epoch) == [ceiling |-> ceiling, epoch |-> epoch] +Entries == <<"retire", "return", "retire", "return">> + +VARIABLES committed, replicas +vars == <> + +Init == + /\ committed = 0 + /\ replicas = [n \in Nodes |-> [index |-> 0, counter |-> 1, + rows |-> <>, retirements |-> <<>>, + restarted |-> FALSE, replayed |-> FALSE]] + +Retained(row, r) == row.ts > r.ceiling \/ row.epoch > r.epoch +Visible(s) == SelectSeq(s.rows, LAMBDA row: + \A i \in DOMAIN s.retirements: Retained(row, s.retirements[i])) +VisibleHead(s) == IF Visible(s) = <<>> THEN <<>> ELSE <> + +ApplyEntry(s, kind) == + IF kind = "retire" + THEN [s EXCEPT !.counter = @ + 1, + !.retirements = Append(@, Retirement(20, s.counter + 1))] + ELSE [s EXCEPT !.counter = @ + 1, + !.rows = <> \o SelectSeq(@, LAMBDA row: row.ts # 20)] + +Commit == /\ committed < Len(Entries) + /\ committed' = committed + 1 + /\ UNCHANGED replicas + +Apply(n) == + LET s == replicas[n] + i == s.index + 1 + IN /\ i <= committed + /\ replicas' = [replicas EXCEPT ![n] = [ApplyEntry(s, Entries[i]) EXCEPT !.index = i]] + /\ UNCHANGED committed + +Compact(n) == + /\ replicas[n].index = 0 + /\ Len(replicas[n].rows) = 2 + /\ replicas' = [replicas EXCEPT ![n].rows = SubSeq(@, 1, 1)] + /\ UNCHANGED committed + +Reclaim(n, retirement) == + LET s == replicas[n] + eligible == SelectSeq(s.rows, LAMBDA row: + row.ts <= retirement.ceiling /\ (LegacyGC \/ row.epoch <= retirement.epoch)) + IN /\ eligible # <<>> + /\ replicas' = [replicas EXCEPT ![n].rows = SelectSeq(@, LAMBDA row: row # eligible[1])] + /\ UNCHANGED committed + +Restart(n) == + /\ ~replicas[n].restarted + /\ replicas' = [replicas EXCEPT ![n].restarted = TRUE] + /\ UNCHANGED committed + +Replay(n) == + /\ replicas[n].index > 0 + /\ ~replicas[n].replayed + /\ replicas' = [replicas EXCEPT ![n].replayed = TRUE] + /\ UNCHANGED committed + +Next == Commit \/ \E n \in Nodes: + Apply(n) \/ Compact(n) \/ Restart(n) \/ Replay(n) \/ + (\E i \in DOMAIN replicas[n].retirements: Reclaim(n, replicas[n].retirements[i])) + +Spec == Init /\ [][Next]_vars + +EqualIndexVisibleHead == \A a, b \in Nodes: + replicas[a].index = replicas[b].index => VisibleHead(replicas[a]) = VisibleHead(replicas[b]) + +EpochBound == \A n \in Nodes: + replicas[n].counter = replicas[n].index + 1 /\ + \A i \in DOMAIN replicas[n].rows: replicas[n].rows[i].epoch <= replicas[n].counter + +ReturnedVersionPreserved == \A n \in Nodes: + replicas[n].index \in {2, 4} => VisibleHead(replicas[n]) = <> + +ReturnCompletionUnreachable == ~(\A n \in Nodes: + replicas[n].index = 4 /\ replicas[n].restarted /\ replicas[n].replayed /\ + VisibleHead(replicas[n]) = <>) +============================================================================= diff --git a/tla/cas/VersionAdoption_gap.cfg b/tla/cas/VersionAdoption_gap.cfg new file mode 100644 index 000000000..779fb3be1 --- /dev/null +++ b/tla/cas/VersionAdoption_gap.cfg @@ -0,0 +1,4 @@ +CONSTANT LegacyGC = TRUE +SPECIFICATION Spec +INVARIANTS EqualIndexVisibleHead +CHECK_DEADLOCK FALSE diff --git a/tla/cas/VersionAdoption_reachable.cfg b/tla/cas/VersionAdoption_reachable.cfg new file mode 100644 index 000000000..e340900de --- /dev/null +++ b/tla/cas/VersionAdoption_reachable.cfg @@ -0,0 +1,4 @@ +CONSTANT LegacyGC = FALSE +SPECIFICATION Spec +INVARIANTS ReturnCompletionUnreachable +CHECK_DEADLOCK FALSE diff --git a/tla/cas/check.sh b/tla/cas/check.sh new file mode 100644 index 000000000..249c8375a --- /dev/null +++ b/tla/cas/check.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail + +module_dir="$(cd "$(dirname "$0")" && pwd)" +jar="$1" +scratch="$(mktemp -d "${TMPDIR:-/tmp}/elastickv-cas-tlc.XXXXXX")" +trap 'rm -rf "$scratch"' EXIT + +run_tlc() { + local module="SingleKeyCAS" + if [[ "$1" == VersionAdoption* ]]; then module="VersionAdoption"; fi + java -Xmx512m -XX:+UseParallelGC -cp "$jar" tlc2.TLC -workers 1 \ + -metadir "$scratch/$1-states" -config "$module_dir/$1.cfg" \ + "$module_dir/$module.tla" +} + +expect_counterexample() { + local config="$1" + local invariant="$2" + local log="$scratch/$config.log" + local status + + if run_tlc "$config" >"$log" 2>&1; then + cat "$log" + echo "ERROR: $config passed without violating $invariant" >&2 + return 1 + else + status=$? + fi + cat "$log" + # The pinned TLC exits with 12 for an invariant violation. + if [ "$status" -ne 12 ] || ! grep -Fxq "Error: Invariant $invariant is violated." "$log"; then + echo "ERROR: $config did not produce the expected $invariant counterexample" >&2 + return 1 + fi +} + +run_tlc SingleKeyCAS +run_tlc SingleKeyCAS_retirement +expect_counterexample SingleKeyCAS_watcher_gap EqualAppliedIndexAgrees +expect_counterexample SingleKeyCAS_cleanup_gap SingleConsumption +expect_counterexample SingleKeyCAS_retention_gap VisibleHeadAgrees +expect_counterexample SingleKeyCAS_retirement_reachable RetirementCompletionUnreachable +run_tlc VersionAdoption +expect_counterexample VersionAdoption_gap EqualIndexVisibleHead +expect_counterexample VersionAdoption_reachable ReturnCompletionUnreachable