Files
seaweedfs/weed/command/filer_remote_sync_gone.go
T
ec1032d642 filer.remote.sync: a source chunk gone for good no longer wedges the write-back (#13220)
* filer.remote.sync: a source chunk gone for good no longer wedges the write-back

An entry whose chunk the volume servers answer 404 for, even with
readDeleted=true, can never be uploaded: the bytes no longer exist in the
cluster. A volume lost with its disk leaves such entries behind (for
example a filer restored from a metadata backup onto a new volume server
while some chunks had not been written back yet). filer.remote.sync
retried the create event forever, every ~2 s, and since a failing event
holds the directory's processed watermark, no later change under the
mount was ever written back again. We hit this in production: one photo's
chunk answered 404 for hours and more than 11,000 later changes waited
behind it.

Now, once the filer confirms the entry is still the one the event
described (the existing supersession check), the upload ends with
errSourceGone when:

- every location answered 404 for sourceGoneGrace (5 min) over
  sourceGoneMinAnswers (3) attempts in a row, or
- the master cannot locate the chunk's volume at all ("failed to locate",
  the whole volume lost with its disk) for sourceGoneLookupGrace (30 min,
  the filer deletion retry's figure for "volume not found").

It logs one ERROR line naming the path, the chunk's fid and the
destination, with a per-process count, and every caller treats the event
as handled so the offset advances. A path found gone is remembered with
its fid (bounded to 10,000), so later events of the same entry are skipped
at once; any other outcome (success, superseded, another error, a failed
supersession lookup) forgets it and starts the grace again, so a volume
server that has not loaded its volume yet, or a stale location, is not
mistaken for lost data.

Only the source decides. The upload body is wrapped in a recorder that
keeps the first error the chunk reader returned, because remote clients
wrap a body read failure in their own errors (the AWS SDK's RequestError
has no Unwrap). The recorder forwards ReadAt and Seek, so s3manager keeps
reading parts in place. A 404, 5xx, timeout or any other error from the
remote itself never reaches the recorder and keeps retrying as before.

A rename of an entry that was written back now deletes the old key only
after the new one is written: when the entry's local data is gone, the old
key keeps the last remote copy (logged) instead of being deleted before an
upload that can never succeed. The gateway's rename path, which deletes
first, does not acknowledge errSourceGone and keeps failing visibly.

util/http:
- GetAuthenticated (the encrypted chunk read) reports a 404 as ErrNotFound,
  as the unencrypted read paths already do, with the same error text;
  readEncryptedUrl wraps with %w instead of %v and treats a 404 as
  retryable, like the plain read, so it tries the other locations.
- A chunk read is ErrNotFound only when no location of the pass failed
  differently (NotFoundEverywhere): a 404 from one replica while another is
  down, answers 5xx or is throttled does not mean the chunk is gone. This
  is applied once in hedgedChunkPass (both RetriedFetchChunkData paths) and
  in the manifest's retriedStreamFetchChunkData loop.

Tests:
- filer_remote_sync_gone_test.go: a plain and an encrypted chunk served 404
  by a test volume server end in errSourceGone on the third attempt and are
  counted once; a remote that answers 404 with readable chunks never does;
  the tracker's grace, answer count, reset, fid change and remembered path;
  the lookup-miss grace; ReaderAt kept by the recorder; a rename keeps the
  old key when the entry is gone and deletes it after the write otherwise.
- TestGetAuthenticatedNotFound; TestRetriedFetchChunkDataNotFoundEverywhere
  (plain direct, plain stream, encrypted; a 404 and a 503 in either order
  is not ErrNotFound).
- Mutation checks: each fails with readEncryptedUrl back on %v, with the
  write error classified instead of the body's read error, with
  NotFoundEverywhere dropped from hedgedChunkPass, with the old key deleted
  first, and with the recorder hiding ReadAt.
- go vet and go test of weed/util/http, weed/command, weed/filer and
  weed/replication/... pass; weed/util/http also with -race.

* filer.remote.sync: renames keep the old key until the new one holds the content; gone is per entry; missing volumes opt-in

- A sighting is counted per entry content (the sorted chunk file ids),
  not per failing chunk. An uploader reads the parts of a ReaderAt body in
  parallel, so the chunk that fails first changes between attempts; keyed
  on it, the grace restarted every time and a large file missing several
  chunks held the offset forever. The tracker's `seen` map is bounded, and
  the log names the first chunk "and N more" instead of every fid.
- On every rename the old key is deleted only after the new one holds the
  content: also when the event's old entry carries no stamp (an upload
  whose stamp a rename in between refused leaves an unstamped copy), and
  in the superseded branch, where the old key is what uploadCurrentEntry
  copies a remote-only entry from. uploadCurrentEntry reports when the
  current entry's data is gone, and the old key stays then. A multipart or
  system path whose old key cannot be deleted no longer skips the stamp.
- A volume the master cannot locate counts only with
  -sourceGoneVolumeMissing=<duration> (default 0: never): a volume server
  that is down or in maintenance looks the same, and an entry written off
  is not retried. It suits a deployment whose master and volume server run
  as one process.
- filer.remote.gateway's rename writes the new key first, deletes the old
  object after, and keeps it when the source data is gone.

Tests: TestRetriedWriteFileSourceGoneAcrossChunks (two lost chunks read in
turn), TestSupersededRenameUploadsCurrentEntry "uncached between the check
and the upload" and "current entry's chunks gone: the old key stays",
TestRenameOfGoneEntryKeepsTheOldKey "old entry unstamped",
TestSourceGoneGraceFor (lookup miss off by default, on with the flag);
each fails with its fix undone. The test remote's DeleteFile removes the
object, as a real remote does.

* filer.remote.sync: evidence kinds apart, a gone entry counted once, the copy owns its source's cleanup; gateway keeps the old object on a superseded rename

- Lookup misses and 404s no longer share one run of sightings
  (sightingKey = content + grace): with -sourceGoneVolumeMissing set, a few
  minutes of "failed to locate" followed by one 404 met the 404 grace with
  the misses' start and answers.
- observe reports whether this call found the entry gone; a replayed event
  of an entry already gone is skipped without another log line or count.
- A superseded rename whose current entry is remote-only leaves the old key
  to completeRemoteOnlyRename, which removes its source only while it is
  the object the stamp describes; an unconditional delete after it could
  remove a replacement.
- filer.remote.gateway: a superseded rename keeps the old object (logged)
  instead of deleting it before the superseding event has written the new
  key.

Tests: TestSourceGoneTrackerCountsOnceAndKeepsEvidenceApart,
TestSupersededRenameUploadsCurrentEntry "the old key replaced during the
copy"; each fails with its fix undone. The gateway change has no test of its
own (its rename path needs a reachable filer).

* filer.remote.sync: drop -sourceGoneVolumeMissing, a lookup miss keeps retrying

A volume the master cannot locate looks the same whether it was lost or
its server is down, so no default can write such an entry off safely, and
a flag for the one-process layout is not worth carrying. Only a 404 from
every location counts as gone; a lookup miss retries as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.remote.gateway: a superseded rename settles its old object

A rename the filer has moved past kept the renamed-from object for good,
so every rename followed by a delete or a rewrite before the gateway
reached it left an orphan on the remote. Settle it the way
filer.remote.sync's uploadCurrentEntry does: copy from it when the entry
has become remote-only, and otherwise delete it, since it no longer holds
the entry's content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.remote.sync, filer.remote.gateway: a superseded rename copied from a later rename's source settles its own old key

When the entry became remote-only through another rename onto it, the copy
reads that rename's source and removes it, and nothing read or removed the
event's own old key any more. Delete it then, in both commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.remote.gateway: reset cached remote clients after the superseded-rename test

A cached client kept the previous run's recorder, so the test failed under
-count above one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:15:37 -08:00

239 lines
7.3 KiB
Go

package command
import (
"errors"
"fmt"
"hash/fnv"
"io"
"regexp"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// errSourceGone marks an upload whose source data no longer exists in this
// cluster: a volume server answered 404 for one of the entry's chunks (read
// with readDeleted=true, so not even a deleted needle is left), the filer
// still holds the entry as the event described it, and that held for
// sourceGoneGrace over sourceGoneMinAnswers attempts in a row. Retrying
// cannot produce the bytes: the write-back reports the path once and moves
// past the event instead of holding the directory's offset on it forever.
// A volume lost with its disk (a server restored from a metadata-only
// backup) leaves entries like this behind.
var errSourceGone = errors.New("source data gone")
// A 404 can also come from a volume server that has not loaded the volume
// yet, or from a stale location right after a move; neither lasts. Only a
// 404 that persists this long, over this many attempts with nothing else in
// between, counts as gone. A volume the master cannot locate at all is also
// what a volume server that is down looks like, so it never counts.
var (
sourceGoneGrace = 5 * time.Minute
sourceGoneMinAnswers = 3
)
// sourceGoneRemembered bounds how many paths a process keeps, both those with
// sightings in a row and those found gone.
const sourceGoneRemembered = 10000
// sourceGoneCount is how many entries this process left unwritten because
// their source data was gone.
var sourceGoneCount atomic.Int64
// sourceReadRecorder keeps the first error the upload body's reader returned.
// Remote clients wrap a body read failure in their own errors (the AWS SDK's
// RequestError has no Unwrap), so the write error cannot say whether the
// source or the remote failed; the recorder can, and a 404 from the remote
// itself never reaches it.
type sourceReadRecorder struct {
r io.Reader
mu sync.Mutex
err error
}
func (s *sourceReadRecorder) Read(p []byte) (int, error) {
n, err := s.r.Read(p)
s.record(err)
return n, err
}
// sourceReadAtRecorder keeps an io.ReaderAt + io.Seeker body one: an S3
// uploader reads the parts of such a body in place and in parallel, where a
// plain io.Reader is copied into a buffer per part.
type sourceReadAtRecorder struct {
*sourceReadRecorder
ra io.ReaderAt
sk io.Seeker
}
func (s *sourceReadAtRecorder) ReadAt(p []byte, off int64) (int, error) {
n, err := s.ra.ReadAt(p, off)
s.record(err)
return n, err
}
func (s *sourceReadAtRecorder) Seek(offset int64, whence int) (int64, error) {
return s.sk.Seek(offset, whence)
}
// newSourceReadRecorder wraps an upload body, keeping the shape the remote
// client sees.
func newSourceReadRecorder(r io.Reader) (io.Reader, *sourceReadRecorder) {
rec := &sourceReadRecorder{r: r}
ra, okAt := r.(io.ReaderAt)
sk, okSeek := r.(io.Seeker)
if okAt && okSeek {
return &sourceReadAtRecorder{sourceReadRecorder: rec, ra: ra, sk: sk}, rec
}
return rec, rec
}
func (s *sourceReadRecorder) record(err error) {
if err == nil || err == io.EOF {
return
}
s.mu.Lock()
if s.err == nil {
s.err = err
}
s.mu.Unlock()
}
func (s *sourceReadRecorder) readErr() error {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
return s.err
}
// isSourceGone reports whether a read of the entry's own chunks says the data
// may be gone: every location of a chunk answered 404
// (util_http.NotFoundEverywhere). Only errors from the source side are passed
// here: the upload body's reader or the chunk view resolution.
func isSourceGone(sourceErr error) bool {
return errors.Is(sourceErr, util_http.ErrNotFound)
}
var fidInURL = regexp.MustCompile(`/(\d+,[0-9a-fA-F]+)(?:[?:/\s"]|$)`)
// goneFid names the chunk the sighting was for, for the log: the file id in
// the URL the error carries, else the entry's first chunk and how many more
// it has.
func goneFid(sourceErr error, entry *filer_pb.Entry) string {
if m := fidInURL.FindStringSubmatch(sourceErr.Error()); m != nil {
return m[1]
}
chunks := entry.GetChunks()
switch len(chunks) {
case 0:
return "unknown"
case 1:
return chunks[0].GetFileIdString()
}
return fmt.Sprintf("%s and %d more", chunks[0].GetFileIdString(), len(chunks)-1)
}
// chunkSetKey identifies the content a sighting is about: the entry's chunk
// file ids, in any order. The chunk that fails first can differ from one
// attempt to the next (an uploader reads parts in parallel), so sightings in
// a row are counted per content, not per failing chunk.
func chunkSetKey(entry *filer_pb.Entry) string {
fids := make([]string, 0, len(entry.GetChunks()))
for _, c := range entry.GetChunks() {
fids = append(fids, c.GetFileIdString())
}
sort.Strings(fids)
h := fnv.New64a()
for _, f := range fids {
h.Write([]byte(f))
h.Write([]byte{0})
}
return fmt.Sprintf("%d:%016x", len(fids), h.Sum64())
}
type goneSighting struct {
key string
first time.Time
last time.Time
answers int
}
// sourceGoneTracker holds, per path, the sightings seen in a row. Any other
// outcome for the path forgets them, so the grace starts again. A path found
// gone is remembered with its content key: a later event of the same entry (a
// metadata update, a replay) is skipped at once instead of holding the
// directory's offset for another grace.
type sourceGoneTracker struct {
mu sync.Mutex
seen map[string]*goneSighting
gone map[string]string
}
func newSourceGoneTracker() *sourceGoneTracker {
return &sourceGoneTracker{seen: map[string]*goneSighting{}, gone: map[string]string{}}
}
var sourceGone = newSourceGoneTracker()
// observe records a sighting for path under key (chunkSetKey) and reports
// whether it has now held for sourceGoneGrace over sourceGoneMinAnswers
// attempts, and whether this call is the one that found it gone (a path
// already known gone reports gone, not new).
func (t *sourceGoneTracker) observe(path, key string, now time.Time) (gone, isNew bool) {
t.mu.Lock()
defer t.mu.Unlock()
if g, ok := t.gone[path]; ok && g == key {
return true, false
}
s := t.seen[path]
if s == nil || s.key != key {
if s == nil && len(t.seen) >= sourceGoneRemembered {
t.pruneSeen(now)
}
s = &goneSighting{key: key, first: now}
t.seen[path] = s
}
s.answers++
s.last = now
if s.answers >= sourceGoneMinAnswers && now.Sub(s.first) >= sourceGoneGrace {
delete(t.seen, path)
if len(t.gone) >= sourceGoneRemembered {
t.gone = map[string]string{}
}
t.gone[path] = key
return true, true
}
return false, false
}
// pruneSeen drops sightings of paths no attempt has reached for longer than
// the grace (the entry was deleted, or the subscription moved past it), and
// every sighting if the map is still full. Dropping one only restarts that
// path's grace.
func (t *sourceGoneTracker) pruneSeen(now time.Time) {
stale := 2 * sourceGoneGrace
for p, s := range t.seen {
if now.Sub(s.last) > stale {
delete(t.seen, p)
}
}
if len(t.seen) >= sourceGoneRemembered {
t.seen = map[string]*goneSighting{}
}
}
// forget drops path's sightings, and its gone mark: the entry was written
// back, superseded, or failed some other way.
func (t *sourceGoneTracker) forget(path string) {
t.mu.Lock()
delete(t.seen, path)
delete(t.gone, path)
t.mu.Unlock()
}