mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
filer: retry TiKV store writes on a write conflict (#12798)
* filer: retry TiKV store writes on a write conflict TiKV transactions are optimistic. A commit fails with a write conflict when another transaction committed one of its keys after it began, even for a blind Set or Delete. Outside a filer transaction the TiKV store runs each save and delete in a transaction of its own and returned that error to the caller, so of two requests writing the same entry at the same moment one failed, and a mount reported EIO. A write the store commits itself (InsertEntry, UpdateEntry, DeleteEntry, one batch of DeleteFolderChildren, KvPut, KvDelete) now runs again in a new transaction after a write conflict, up to 5 times, waiting 1-2ms, 2-4ms, ... 16-32ms in between. The failed transaction stored nothing, and the retry lands after the other writer, as if the two had not overlapped. The retries stop when the context is done. A write inside a transaction from BeginTransaction is not retried: the conflict is reported when the caller commits, as before. deleteBatch now goes through RunInTxn like the other writes. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * filer: stop TiKV write retries once the context is done When the context was cancelled while the retry wait was running, the timer case could still win the select and start one more transaction. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: keep a TiKV entry that is no longer expired when listing deletes it The listing decides an entry has expired from its own read, and the delete ran later as a blind delete. Once the delete retries after a write conflict, a live replacement committed in between was removed. Read the entry again in the deleting transaction and delete it only if it is still expired. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
This commit is contained in:
3 files changed
+179
-50
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/tikv/client-go/v2/config"
|
||||
tikverr "github.com/tikv/client-go/v2/error"
|
||||
"github.com/tikv/client-go/v2/txnkv"
|
||||
)
|
||||
|
||||
@@ -87,11 +89,7 @@ func (store *TikvStore) InsertEntry(ctx context.Context, entry *filer.Entry) err
|
||||
if err != nil {
|
||||
return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
|
||||
}
|
||||
txn, err := store.getTxn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = txn.RunInTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
err = store.runTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
return txn.Set(key, value)
|
||||
})
|
||||
if err != nil {
|
||||
@@ -143,12 +141,7 @@ func (store *TikvStore) DeleteEntry(ctx context.Context, path util.FullPath) err
|
||||
dir, name := path.DirAndName()
|
||||
key := store.generateKey(dir, name)
|
||||
|
||||
txn, err := store.getTxn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = txn.RunInTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
err := store.runTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
return txn.Delete(key)
|
||||
})
|
||||
if err != nil {
|
||||
@@ -157,6 +150,34 @@ func (store *TikvStore) DeleteEntry(ctx context.Context, path util.FullPath) err
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteExpiredEntry reads the entry again in the deleting transaction, so a
|
||||
// replacement written since the listing read it is kept.
|
||||
func (store *TikvStore) deleteExpiredEntry(ctx context.Context, path util.FullPath) error {
|
||||
dir, name := path.DirAndName()
|
||||
key := store.generateKey(dir, name)
|
||||
return store.runTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
value, err := txn.Get(ctx, key)
|
||||
if isNotExists(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entry := &filer.Entry{FullPath: path}
|
||||
if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(value)); err != nil {
|
||||
return err
|
||||
}
|
||||
if !isLogicallyExpired(entry) {
|
||||
return nil
|
||||
}
|
||||
return txn.Delete(key)
|
||||
})
|
||||
}
|
||||
|
||||
func isLogicallyExpired(entry *filer.Entry) bool {
|
||||
return entry.TtlSec > 0 && entry.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now())
|
||||
}
|
||||
|
||||
// ~ Entry APIs
|
||||
|
||||
// Directory APIs
|
||||
@@ -216,26 +237,14 @@ func (store *TikvStore) DeleteFolderChildren(ctx context.Context, path util.Full
|
||||
}
|
||||
|
||||
func (store *TikvStore) deleteBatch(ctx context.Context, keys [][]byte) error {
|
||||
deleteTxn, err := store.getTxn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteTxn.inContext {
|
||||
defer func() { _ = deleteTxn.Rollback() }()
|
||||
}
|
||||
|
||||
for _, key := range keys {
|
||||
if err := deleteTxn.Delete(key); err != nil {
|
||||
return err
|
||||
return store.runTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
for _, key := range keys {
|
||||
if err := txn.Delete(key); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !deleteTxn.inContext {
|
||||
return deleteTxn.Commit(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (store *TikvStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (string, error) {
|
||||
@@ -299,17 +308,15 @@ func (store *TikvStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPat
|
||||
}
|
||||
|
||||
// Check TTL expiration before calling eachEntryFunc (similar to Redis stores)
|
||||
if entry.TtlSec > 0 {
|
||||
if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
|
||||
// Entry is expired, delete it and continue without counting toward limit
|
||||
if deleteErr := store.DeleteEntry(ctx, entry.FullPath); deleteErr != nil {
|
||||
glog.V(0).InfofCtx(ctx, "failed to delete expired entry %s: %v", entry.FullPath, deleteErr)
|
||||
}
|
||||
if err := iter.Next(); err != nil {
|
||||
break
|
||||
}
|
||||
continue
|
||||
if isLogicallyExpired(entry) {
|
||||
// Entry is expired, delete it and continue without counting toward limit
|
||||
if deleteErr := store.deleteExpiredEntry(ctx, entry.FullPath); deleteErr != nil {
|
||||
glog.V(0).InfofCtx(ctx, "failed to delete expired entry %s: %v", entry.FullPath, deleteErr)
|
||||
}
|
||||
if err := iter.Next(); err != nil {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Only increment counter for non-expired entries
|
||||
@@ -410,6 +417,51 @@ func (store *TikvStore) getTxn(ctx context.Context) (*TxnWrapper, error) {
|
||||
return &TxnWrapper{txn, false}, nil
|
||||
}
|
||||
|
||||
// writeConflictRetries bounds how many times a write that the store commits
|
||||
// itself is run again after a write conflict.
|
||||
const writeConflictRetries = 5
|
||||
|
||||
// runTxn runs f in the transaction ctx carries, or in a new one that it
|
||||
// commits.
|
||||
//
|
||||
// TiKV transactions are optimistic: a commit fails with a write conflict when
|
||||
// another transaction committed one of its keys after it began, as when two
|
||||
// requests save or delete the same entry at the same moment. A transaction
|
||||
// the store began for this one write has stored nothing when that happens, so
|
||||
// the write is run again in a new transaction, which lands after the other
|
||||
// writer. A transaction carried by ctx is left alone: its owner commits it,
|
||||
// and only the owner can run all of it again.
|
||||
func (store *TikvStore) runTxn(ctx context.Context, f func(txn *txnkv.KVTxn) error) error {
|
||||
return runOwnTxn(ctx, func() (bool, error) {
|
||||
txn, err := store.getTxn(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return txn.inContext, txn.RunInTxn(ctx, f)
|
||||
})
|
||||
}
|
||||
|
||||
// runOwnTxn calls run until it succeeds, fails with anything other than a
|
||||
// write conflict, ran in the caller's transaction, or has been retried
|
||||
// writeConflictRetries times. The wait between runs doubles and is jittered
|
||||
// so that writers that collided do not collide again.
|
||||
func runOwnTxn(ctx context.Context, run func() (inContext bool, err error)) error {
|
||||
for attempt := 0; ; attempt++ {
|
||||
inContext, err := run()
|
||||
if err == nil || inContext || attempt == writeConflictRetries || !tikverr.IsErrWriteConflict(err) {
|
||||
return err
|
||||
}
|
||||
wait := time.Duration(1<<attempt) * time.Millisecond
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(wait + rand.N(wait)):
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ~ Transaction Wrapper
|
||||
|
||||
// Encoding Functions
|
||||
|
||||
@@ -10,11 +10,7 @@ import (
|
||||
)
|
||||
|
||||
func (store *TikvStore) KvPut(ctx context.Context, key []byte, value []byte) error {
|
||||
tw, err := store.getTxn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tw.RunInTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
return store.runTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
return txn.Set(key, value)
|
||||
})
|
||||
}
|
||||
@@ -39,11 +35,7 @@ func (store *TikvStore) KvGet(ctx context.Context, key []byte) ([]byte, error) {
|
||||
}
|
||||
|
||||
func (store *TikvStore) KvDelete(ctx context.Context, key []byte) error {
|
||||
tw, err := store.getTxn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tw.RunInTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
return store.runTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
return txn.Delete(key)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//go:build tikv
|
||||
|
||||
package tikv
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
tikverr "github.com/tikv/client-go/v2/error"
|
||||
)
|
||||
|
||||
func writeConflict() error {
|
||||
return tikverr.NewErrWriteConflictWithArgs(470572673646985949, 470572673646985677, 0, []byte("k"), 0)
|
||||
}
|
||||
|
||||
// A write in a transaction of the store's own runs again after a write
|
||||
// conflict and succeeds once the other writer is done.
|
||||
func TestRunOwnTxnRetriesWriteConflict(t *testing.T) {
|
||||
runs := 0
|
||||
err := runOwnTxn(context.Background(), func() (bool, error) {
|
||||
runs++
|
||||
if runs < 3 {
|
||||
return false, writeConflict()
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
if err != nil || runs != 3 {
|
||||
t.Fatalf("runOwnTxn = %v after %d runs, want nil after 3", err, runs)
|
||||
}
|
||||
}
|
||||
|
||||
// It gives up after writeConflictRetries retries and returns TiKV's error.
|
||||
func TestRunOwnTxnGivesUp(t *testing.T) {
|
||||
runs := 0
|
||||
err := runOwnTxn(context.Background(), func() (bool, error) {
|
||||
runs++
|
||||
return false, writeConflict()
|
||||
})
|
||||
if runs != writeConflictRetries+1 {
|
||||
t.Fatalf("ran %d times, want %d", runs, writeConflictRetries+1)
|
||||
}
|
||||
if !tikverr.IsErrWriteConflict(err) {
|
||||
t.Fatalf("runOwnTxn = %v, want the write conflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
// In the caller's transaction a write runs once: the conflict is reported when
|
||||
// the caller commits, and only the caller can run the whole transaction again.
|
||||
// Errors other than a write conflict are not retried.
|
||||
func TestRunOwnTxnRunsOnceOtherwise(t *testing.T) {
|
||||
other := errors.New("region is unavailable")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
inContext bool
|
||||
err error
|
||||
}{
|
||||
{"in the caller's transaction", true, writeConflict()},
|
||||
{"another error", false, other},
|
||||
{"success", false, nil},
|
||||
} {
|
||||
runs := 0
|
||||
err := runOwnTxn(context.Background(), func() (bool, error) {
|
||||
runs++
|
||||
return tc.inContext, tc.err
|
||||
})
|
||||
if runs != 1 || err != tc.err {
|
||||
t.Errorf("%s: runOwnTxn = %v after %d runs, want %v after 1", tc.name, err, runs, tc.err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A cancelled context stops the retries.
|
||||
func TestRunOwnTxnStopsWithItsContext(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
runs := 0
|
||||
err := runOwnTxn(ctx, func() (bool, error) {
|
||||
runs++
|
||||
return false, writeConflict()
|
||||
})
|
||||
if runs != 1 || !tikverr.IsErrWriteConflict(err) {
|
||||
t.Fatalf("runOwnTxn = %v after %d runs, want the write conflict after 1", err, runs)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user