From 261c534c19f71601492e2205159e6e491b3dc2d0 Mon Sep 17 00:00:00 2001 From: MapleWhiteZZZ <421700801@qq.com> Date: Fri, 20 Nov 2026 11:17:26 +0800 Subject: [PATCH] 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 * 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 * 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 --------- Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com> Co-authored-by: Claude Fable 5.2 Co-authored-by: Chris Lu --- weed/filer/tikv/tikv_store.go | 132 ++++++++++++++++------- weed/filer/tikv/tikv_store_kv.go | 12 +-- weed/filer/tikv/tikv_store_retry_test.go | 85 +++++++++++++++ 3 files changed, 179 insertions(+), 50 deletions(-) create mode 100644 weed/filer/tikv/tikv_store_retry_test.go diff --git a/weed/filer/tikv/tikv_store.go b/weed/filer/tikv/tikv_store.go index 92c34d70d6..9fc2adec91 100644 --- a/weed/filer/tikv/tikv_store.go +++ b/weed/filer/tikv/tikv_store.go @@ -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<