From c967ba4a7abcba1fe5b385f694cf95fb5f4899ff Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Sun, 22 Nov 2026 12:28:45 -0800 Subject: [PATCH] storage, seaweed-volume: ask a delisted EC shard holder before rebuilding the shard (#12899) * storage: ask a delisted EC shard holder before rebuilding the shard A complete lookup that places a shard nowhere drops its holder from the map deletes route by. That holder may still answer, and may be the one that journaled a needle's delete, which the other shards cannot know. Keep it as a read hint that reads try before reconstructing and drop once it fails. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: ask a delisted EC shard holder before rebuilding the shard Mirrors Go: a complete lookup that places a shard nowhere moves its cached holders to read hints, which fetch_one_interval tries before reconstructing and drops once they fail. Deletes and recovery keep using only the placed locations. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: test reads asking a delisted EC shard holder Mirrors the Go read-path tests: a delisted holder that journaled the delete answers before the local shards rebuild the needle, and an unreachable one is dropped while the read rebuilds. Co-Authored-By: Claude Opus 5.5 * storage: take only a deleted answer from a delisted EC shard holder A delete made after the delisting is journaled on a listed holder, so the delisted one still answers live. Returning its bytes skipped the reconstruction that asks the listed holders and finds that delete. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: take only a deleted answer from a delisted EC shard holder Mirrors Go: a live answer from a read hint may predate a delete that went to a listed holder, so fetch_one_interval goes on to the direct read and reconstruction instead of returning it. Co-Authored-By: Claude Opus 5.5 * storage: bound the read asking a delisted EC shard holder A delisted holder may have stopped answering, and the hint read had no deadline over its stream. Only its deleted answer is used, so ask for one byte under a short deadline; a timeout drops the hint like any other failure. Co-Authored-By: Claude Opus 5.5 * storage: drop only the read hint a failed EC read used A lookup can replace a shard's hint while a read of the old one is in flight; that read's failure then dropped the new hint. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: bound the read asking a delisted EC shard holder Mirrors Go: ask the hint for one byte under EC_READ_HINT_TIMEOUT, since only its deleted answer is used; a timeout drops the hint like any other failure. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: drop only the read hint a failed EC read used Mirrors Go: a lookup can replace a shard's hint while a read of the old one is in flight, and that read's failure dropped the new hint. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: keep fetch_one_interval's doc comment on the function Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- seaweed-volume/src/server/grpc_server.rs | 141 ++++++++++-- seaweed-volume/src/server/store_ec.rs | 56 +++++ .../src/storage/erasure_coding/ec_volume.rs | 47 +++- weed/storage/erasure_coding/ec_volume.go | 5 + weed/storage/store_ec.go | 43 +++- weed/storage/store_ec_location_cache_test.go | 214 ++++++++++++++++++ weed/storage/store_ec_quarantine_test.go | 3 +- weed/storage/store_ec_scrub.go | 3 +- 8 files changed, 489 insertions(+), 23 deletions(-) diff --git a/seaweed-volume/src/server/grpc_server.rs b/seaweed-volume/src/server/grpc_server.rs index f7f8a8563a..916b35460c 100644 --- a/seaweed-volume/src/server/grpc_server.rs +++ b/seaweed-volume/src/server/grpc_server.rs @@ -14027,17 +14027,13 @@ mod tests { .unwrap(); } - /// Leaves `service` holding `local_shards` of EC volume 1, with shard 0 (the - /// one with needle 11's bytes) also served by a peer; `peer_deletes` - /// journals the needle's delete on the peer alone. - async fn put_ec_1_needle_shard_on_a_peer( - service: &VolumeGrpcService, + /// Serves `shard_ids` of the EC volume 1 generated in `tmp` from a new peer; + /// `deletes` journals needle 11's delete on that peer alone. + async fn serve_ec_1_shards_from_a_peer( tmp: &TempDir, - local_shards: Vec, - peer_deletes: bool, - ) -> (TempDir, tokio::sync::oneshot::Sender<()>) { - generate_and_mount_ec_1(service, local_shards).await; - + shard_ids: Vec, + deletes: bool, + ) -> (String, TempDir, tokio::sync::oneshot::Sender<()>) { let (peer, peer_tmp) = make_local_service_with_volume("", None); peer.state .store @@ -14051,8 +14047,8 @@ mod tests { std::fs::copy(tmp.path().join(&name), peer_tmp.path().join(&name)).unwrap(); } } - mount_ec_1(&peer, vec![0]).await; - if peer_deletes { + mount_ec_1(&peer, shard_ids).await; + if deletes { peer.state .store .write() @@ -14063,6 +14059,21 @@ mod tests { .unwrap(); } let (port, shutdown) = serve_source(peer).await; + (format!("127.0.0.1:{port}.{port}"), peer_tmp, shutdown) + } + + /// Leaves `service` holding `local_shards` of EC volume 1, with shard 0 (the + /// one with needle 11's bytes) also served by a peer; `peer_deletes` + /// journals the needle's delete on the peer alone. + async fn put_ec_1_needle_shard_on_a_peer( + service: &VolumeGrpcService, + tmp: &TempDir, + local_shards: Vec, + peer_deletes: bool, + ) -> (TempDir, tokio::sync::oneshot::Sender<()>) { + generate_and_mount_ec_1(service, local_shards).await; + let (peer_addr, peer_tmp, shutdown) = + serve_ec_1_shards_from_a_peer(tmp, vec![0], peer_deletes).await; { let mut store = service.state.store.write().unwrap(); @@ -14074,7 +14085,7 @@ mod tests { (0u8..14) .map(|sid| { let addr = if sid == 0 { - format!("127.0.0.1:{port}.{port}") + peer_addr.clone() } else { "127.0.0.1:255.1".to_string() }; @@ -14112,6 +14123,110 @@ mod tests { assert_eq!(err.message(), "already deleted"); } + /// A complete lookup places shard 0 nowhere and every other shard on an + /// unreachable holder. + fn delist_ec_1_shard_0(service: &VolumeGrpcService) { + service + .state + .store + .read() + .unwrap() + .find_ec_volume(VolumeId(1)) + .unwrap() + .merge_shard_locations( + (0u8..14) + .map(|sid| { + let addrs = if sid == 0 { + Vec::new() + } else { + vec!["127.0.0.1:255.1".to_string()] + }; + (sid, addrs) + }) + .collect(), + ); + } + + /// The local shards could rebuild needle 11, but the delisted holder of + /// shard 0 still answers and journaled its delete. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn test_ec_read_asks_a_delisted_holder_before_rebuilding() { + let (service, tmp) = make_local_service_with_volume("", None); + let _peer = put_ec_1_needle_shard_on_a_peer(&service, &tmp, (1..14).collect(), true).await; + delist_ec_1_shard_0(&service); + + let err = needle_status(&service, 11).await.unwrap_err(); + assert_eq!(err.message(), "already deleted", "{err}"); + } + + /// A delete made after the delisting went to a listed holder, so the + /// delisted holder still answers live; the read must not take that answer + /// over the reconstruction that asks the listed holder. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn test_ec_read_does_not_take_a_live_answer_from_a_delisted_holder() { + let (service, tmp) = make_local_service_with_volume("", None); + generate_and_mount_ec_1(&service, (1..10).collect()).await; + let (delisted, _delisted_tmp, _delisted_stop) = + serve_ec_1_shards_from_a_peer(&tmp, vec![0], false).await; + let (journaled, _journaled_tmp, _journaled_stop) = + serve_ec_1_shards_from_a_peer(&tmp, vec![10], true).await; + { + let mut store = service.state.store.write().unwrap(); + store.unmount_volume(VolumeId(1)).unwrap(); + let ecv = store.find_ec_volume(VolumeId(1)).unwrap(); + ecv.merge_shard_locations(std::collections::HashMap::from([(0, vec![delisted])])); + ecv.merge_shard_locations(std::collections::HashMap::from([ + (0, Vec::new()), + (10, vec![journaled]), + ])); + } + + let err = needle_status(&service, 11).await.unwrap_err(); + assert_eq!(err.message(), "already deleted", "{err}"); + let store = service.state.store.read().unwrap(); + assert!( + store + .find_ec_volume(VolumeId(1)) + .unwrap() + .shard_read_hints(0) + .is_some(), + "a read hint that answered was dropped" + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn test_ec_read_drops_an_unreachable_read_hint_and_rebuilds() { + let (service, _tmp) = make_local_service_with_volume("", None); + let want = needle_status(&service, 11).await.unwrap(); + generate_and_mount_ec_1(&service, (1..14).collect()).await; + { + let mut store = service.state.store.write().unwrap(); + store.unmount_volume(VolumeId(1)).unwrap(); + store + .find_ec_volume(VolumeId(1)) + .unwrap() + .merge_shard_locations( + (0u8..14) + .map(|sid| (sid, vec!["127.0.0.1:255.1".to_string()])) + .collect(), + ); + } + delist_ec_1_shard_0(&service); + + let got = needle_status(&service, 11) + .await + .expect("the local shards rebuild shard 0"); + assert_eq!(got, want); + let store = service.state.store.read().unwrap(); + assert_eq!( + store + .find_ec_volume(VolumeId(1)) + .unwrap() + .shard_read_hints(0), + None + ); + } + fn quarantine_ec_1(service: &VolumeGrpcService) { service .state diff --git a/seaweed-volume/src/server/store_ec.rs b/seaweed-volume/src/server/store_ec.rs index b8485371ae..fa3c7b2829 100644 --- a/seaweed-volume/src/server/store_ec.rs +++ b/seaweed-volume/src/server/store_ec.rs @@ -1345,6 +1345,10 @@ struct EcShardMap<'a> { parity_shards: usize, } +/// Bounds asking a delisted holder, which may have stopped answering, before +/// the read reconstructs the shard (Go's `ecReadHintTimeout`). +const EC_READ_HINT_TIMEOUT: Duration = Duration::from_secs(5); + /// Try direct peer read; on failure, reconstruct via Reed-Solomon /// from the other shards. Mirrors `readOneEcShardInterval`'s tail. async fn fetch_one_interval( @@ -1353,6 +1357,37 @@ async fn fetch_one_interval( map: EcShardMap<'_>, ) -> io::Result<(Vec, bool)> { let EcInterval { vid, shard_id, .. } = iv; + if map.locations.get(&shard_id).is_none_or(Vec::is_empty) + && let Some(hints) = shard_read_hints(state, vid, shard_id) + { + // Only a deleted answer is taken from a hint, so one byte is enough. + let probe = EcInterval { size: 1, ..iv }; + let read = tokio::time::timeout( + EC_READ_HINT_TIMEOUT, + read_remote_ec_shard_interval(state, &hints, probe), + ) + .await + .unwrap_or_else(|_| { + Err(io::Error::new( + io::ErrorKind::TimedOut, + "read hint timed out", + )) + }); + match read { + Ok((buf, true)) => return Ok((buf, true)), + Ok(_) => {} + Err(e) => { + tracing::debug!( + "read ec shard {}.{} from delisted holders {:?} failed: {}", + vid.0, + shard_id, + hints, + e + ); + forget_shard_read_hints(state, vid, shard_id, &hints); + } + } + } // Direct peer read against the cached locations for this shard. if let Some(sources) = map.locations.get(&shard_id) && !sources.is_empty() @@ -1837,6 +1872,27 @@ async fn recover_one_remote_ec_shard_interval( } } +fn shard_read_hints( + state: &Arc, + vid: VolumeId, + shard_id: ShardId, +) -> Option> { + let store = state.store.read().unwrap(); + store.find_ec_volume(vid)?.shard_read_hints(shard_id) +} + +fn forget_shard_read_hints( + state: &Arc, + vid: VolumeId, + shard_id: ShardId, + used: &[String], +) { + let store = state.store.read().unwrap(); + if let Some(ecv) = store.find_ec_volume(vid) { + ecv.forget_shard_read_hints(shard_id, used); + } +} + /// Drop a confirmed-corrupt shard's cached location so later reads go straight /// to reconstruction — Go's `forgetShardId` reached through the volume. fn forget_shard_location(state: &Arc, vid: VolumeId, shard_id: ShardId) { diff --git a/seaweed-volume/src/storage/erasure_coding/ec_volume.rs b/seaweed-volume/src/storage/erasure_coding/ec_volume.rs index 3f856e3262..61dfeafb14 100644 --- a/seaweed-volume/src/storage/erasure_coding/ec_volume.rs +++ b/seaweed-volume/src/storage/erasure_coding/ec_volume.rs @@ -31,6 +31,12 @@ pub(crate) struct ShardLocationCache { /// Maps shard ID -> list of server addresses where that shard exists. /// Used for distributed EC reads across the cluster. locations: HashMap>, + /// Holders a complete lookup stopped placing a shard on (Go's + /// `ShardReadHints`). Reads ask them before reconstructing, for a delete only + /// such a holder journaled, but take nothing else from them: a delete made + /// since went to a listed holder, which reconstruction asks. Deletes never + /// use them. + read_hints: HashMap>, /// Wall-clock timestamp of the most recent successful `LookupEcVolume` /// refresh of `locations`. `None` until the first refresh. Drives the /// staleness heuristic in `cached_lookup_ec_shard_locations` (mirrors Go's @@ -1741,8 +1747,13 @@ impl EcVolume { let mut cache = self.shard_locations.write().unwrap(); for (shard_id, addrs) in locations { if addrs.is_empty() { - cache.locations.remove(&shard_id); + if let Some(known) = cache.locations.remove(&shard_id) + && !known.is_empty() + { + cache.read_hints.insert(shard_id, known); + } } else { + cache.read_hints.remove(&shard_id); cache.locations.insert(shard_id, addrs); } } @@ -1787,6 +1798,20 @@ impl EcVolume { (cache.locations.clone(), cache.refreshed_at) } + pub(crate) fn shard_read_hints(&self, shard_id: ShardId) -> Option> { + let cache = self.shard_locations.read().unwrap(); + cache.read_hints.get(&shard_id).cloned() + } + + /// Drops the shard's hint only if it is still `used`: a lookup may have + /// replaced it while the read that failed was in flight. + pub(crate) fn forget_shard_read_hints(&self, shard_id: ShardId, used: &[String]) { + let mut cache = self.shard_locations.write().unwrap(); + if cache.read_hints.get(&shard_id).is_some_and(|h| h == used) { + cache.read_hints.remove(&shard_id); + } + } + /// Mark the cached map for a prompt re-check after a read failed against one /// of its locations. pub(crate) fn mark_shard_locations_stale(&self) { @@ -5482,9 +5507,27 @@ mod tests { ); // A shard the master places nowhere is dropped, not kept at an address - // a delete would trust. + // a delete would trust; its holder stays a place a read can ask first. let merged = vol.merge_shard_locations(HashMap::from([(0, Vec::new())])); assert_eq!(merged, HashMap::from([(1, vec!["c:3".to_string()])])); + assert_eq!(vol.shard_read_hints(0), Some(vec!["a:1".to_string()])); + vol.merge_shard_locations(HashMap::from([(0, Vec::new())])); + assert_eq!( + vol.shard_read_hints(0), + Some(vec!["a:1".to_string()]), + "a later reply placing the shard nowhere keeps the hint" + ); + vol.merge_shard_locations(HashMap::from([(0, vec!["d:4".to_string()])])); + assert_eq!(vol.shard_read_hints(0), None); + vol.merge_shard_locations(HashMap::from([(0, Vec::new())])); + vol.forget_shard_read_hints(0, &["a:1".to_string()]); + assert_eq!( + vol.shard_read_hints(0), + Some(vec!["d:4".to_string()]), + "a failed read of an older hint keeps its replacement" + ); + vol.forget_shard_read_hints(0, &["d:4".to_string()]); + assert_eq!(vol.shard_read_hints(0), None); } #[test] diff --git a/weed/storage/erasure_coding/ec_volume.go b/weed/storage/erasure_coding/ec_volume.go index 5c780d886f..2c2c034c81 100644 --- a/weed/storage/erasure_coding/ec_volume.go +++ b/weed/storage/erasure_coding/ec_volume.go @@ -61,6 +61,11 @@ type EcVolume struct { Shards []*EcVolumeShard ShardLocations map[ShardId][]pb.ServerAddress ShardLocationsRefreshTime time.Time + // ShardReadHints keeps the holders a complete lookup stopped placing a shard + // on. Reads ask them before reconstructing, for a delete only such a holder + // journaled, but take nothing else from them: a delete made since went to a + // listed holder, which reconstruction asks. Deletes never use them. + ShardReadHints map[ShardId][]pb.ServerAddress // ShardLocationsStale marks the map for a prompt re-check: a read that failed // against a cached location has disproved what the map claims, and the normal // freshness window is far too long to serve from a map known to be wrong. diff --git a/weed/storage/store_ec.go b/weed/storage/store_ec.go index 1469d674fd..4cb5d8f62c 100644 --- a/weed/storage/store_ec.go +++ b/weed/storage/store_ec.go @@ -722,11 +722,30 @@ func (s *Store) readOneEcShardInterval(needleId types.NeedleId, ecVolume *erasur ecVolume.ShardLocationsLock.RLock() sourceDataNodes, hasShardIdLocation := ecVolume.ShardLocations[shardId] + readHints := ecVolume.ShardReadHints[shardId] ecVolume.ShardLocationsLock.RUnlock() + if !hasShardIdLocation && len(readHints) > 0 { + // Only a deleted answer is taken from a hint, so one byte is enough. + ctx, cancel := context.WithTimeout(context.Background(), ecReadHintTimeout) + _, is_deleted, err = s.readRemoteEcShardInterval(ctx, readHints, needleId, ecVolume.VolumeId, shardId, data[:1], actualOffset, ecVolume.EncodeTsNs) + cancel() + if err == nil && is_deleted { + return + } + if err != nil { + glog.V(1).Infof("read ec shard %d.%d from delisted holders %v: %v", ecVolume.VolumeId, shardId, readHints, err) + ecVolume.ShardLocationsLock.Lock() + if slices.Equal(ecVolume.ShardReadHints[shardId], readHints) { + delete(ecVolume.ShardReadHints, shardId) + } + ecVolume.ShardLocationsLock.Unlock() + } + } + // try reading directly if hasShardIdLocation { - _, is_deleted, err = s.readRemoteEcShardInterval(sourceDataNodes, needleId, ecVolume.VolumeId, shardId, data, actualOffset, ecVolume.EncodeTsNs) + _, is_deleted, err = s.readRemoteEcShardInterval(context.Background(), sourceDataNodes, needleId, ecVolume.VolumeId, shardId, data, actualOffset, ecVolume.EncodeTsNs) if err == nil { return } @@ -1218,6 +1237,14 @@ func (s *Store) cachedLookupEcShardLocations(ecVolume *erasure_coding.EcVolume) ecVolume.ShardLocationsLock.Lock() for _, shardIdLocations := range resp.ShardIdLocations { shardId := erasure_coding.ShardId(shardIdLocations.ShardId) + if len(shardIdLocations.Locations) > 0 { + delete(ecVolume.ShardReadHints, shardId) + } else if known := ecVolume.ShardLocations[shardId]; len(known) > 0 { + if ecVolume.ShardReadHints == nil { + ecVolume.ShardReadHints = make(map[erasure_coding.ShardId][]pb.ServerAddress) + } + ecVolume.ShardReadHints[shardId] = known + } delete(ecVolume.ShardLocations, shardId) for _, loc := range shardIdLocations.Locations { ecVolume.ShardLocations[shardId] = append(ecVolume.ShardLocations[shardId], pb.NewServerAddressFromLocation(loc)) @@ -1244,6 +1271,10 @@ func (s *Store) cachedLookupEcShardLocations(ecVolume *erasure_coding.EcVolume) // to peers or reconstruction first. var errShardQuarantined = fmt.Errorf("ec shard on a quarantined disk: %w", errShardNotLocal) +// ecReadHintTimeout bounds asking a delisted holder, which may have stopped +// answering, before the read reconstructs the shard. +var ecReadHintTimeout = 5 * time.Second + // readLocalEcShardInterval refuses a shard whose disk is quarantined unless // allowQuarantined is set. func (s *Store) readLocalEcShardInterval(ecVolume *erasure_coding.EcVolume, shardId erasure_coding.ShardId, buf []byte, offset int64, allowQuarantined bool) error { @@ -1278,7 +1309,7 @@ func (s *Store) readLocalEcShardInterval(ecVolume *erasure_coding.EcVolume, shar return nil } -func (s *Store) readRemoteEcShardInterval(sourceDataNodes []pb.ServerAddress, needleId types.NeedleId, vid needle.VolumeId, shardId erasure_coding.ShardId, buf []byte, offset int64, expectedEncodeTsNs int64) (n int, is_deleted bool, err error) { +func (s *Store) readRemoteEcShardInterval(ctx context.Context, sourceDataNodes []pb.ServerAddress, needleId types.NeedleId, vid needle.VolumeId, shardId erasure_coding.ShardId, buf []byte, offset int64, expectedEncodeTsNs int64) (n int, is_deleted bool, err error) { if len(sourceDataNodes) == 0 { return 0, false, fmt.Errorf("failed to find ec shard %d.%d", vid, shardId) @@ -1286,7 +1317,7 @@ func (s *Store) readRemoteEcShardInterval(sourceDataNodes []pb.ServerAddress, ne for _, sourceDataNode := range sourceDataNodes { glog.V(3).Infof("read remote ec shard %d.%d from %s", vid, shardId, sourceDataNode) - n, is_deleted, err = s.doReadRemoteEcShardInterval(sourceDataNode, needleId, vid, shardId, buf, offset, expectedEncodeTsNs) + n, is_deleted, err = s.doReadRemoteEcShardInterval(ctx, sourceDataNode, needleId, vid, shardId, buf, offset, expectedEncodeTsNs) if err == nil { return } @@ -1296,12 +1327,12 @@ func (s *Store) readRemoteEcShardInterval(sourceDataNodes []pb.ServerAddress, ne return } -func (s *Store) doReadRemoteEcShardInterval(sourceDataNode pb.ServerAddress, needleId types.NeedleId, vid needle.VolumeId, shardId erasure_coding.ShardId, buf []byte, offset int64, expectedEncodeTsNs int64) (n int, is_deleted bool, err error) { +func (s *Store) doReadRemoteEcShardInterval(ctx context.Context, sourceDataNode pb.ServerAddress, needleId types.NeedleId, vid needle.VolumeId, shardId erasure_coding.ShardId, buf []byte, offset int64, expectedEncodeTsNs int64) (n int, is_deleted bool, err error) { err = operation.WithVolumeServerClient(false, sourceDataNode, s.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error { // copy data slice - shardReadClient, err := client.VolumeEcShardRead(context.Background(), &volume_server_pb.VolumeEcShardReadRequest{ + shardReadClient, err := client.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{ VolumeId: uint32(vid), ShardId: uint32(shardId), Offset: offset, @@ -1423,7 +1454,7 @@ func (s *Store) gatherEcShardIntervals(needleId types.NeedleId, ecVolume *erasur go func() { defer wg.Done() data := make([]byte, size) - nRead, isDeleted, readErr := s.readRemoteEcShardInterval(locations, needleId, ecVolume.VolumeId, shardId, data, offset, ecVolume.EncodeTsNs) + nRead, isDeleted, readErr := s.readRemoteEcShardInterval(context.Background(), locations, needleId, ecVolume.VolumeId, shardId, data, offset, ecVolume.EncodeTsNs) if readErr != nil { glog.V(3).Infof("recover: readRemoteEcShardInterval %d.%d %d bytes from %+v: %v", ecVolume.VolumeId, shardId, nRead, locations, readErr) forgetShardId(ecVolume, shardId) diff --git a/weed/storage/store_ec_location_cache_test.go b/weed/storage/store_ec_location_cache_test.go index 9af7372dc3..4d4a81d3d2 100644 --- a/weed/storage/store_ec_location_cache_test.go +++ b/weed/storage/store_ec_location_cache_test.go @@ -3,7 +3,9 @@ package storage import ( "bytes" "context" + "errors" "fmt" + "maps" "net" "os" "slices" @@ -447,3 +449,215 @@ func TestCachedLookupEcShardLocationsKeepsTheMarkWhenTheLookupFails(t *testing.T t.Errorf("asked the master %d times, want 3: a failed lookup must not leave the disproved map trusted", got) } } + +// A complete reply that places a shard nowhere takes it out of the map a delete +// routes by, but its former holder stays a place a read can ask first. +func TestCachedLookupEcShardLocationsKeepsADelistedHolderForReads(t *testing.T) { + const delisted = erasure_coding.ShardId(13) + master, masterAddr := startCountingMaster(t) + master.located.Store(13) + store := &Store{ + MasterFn: func() pb.ServerAddress { return masterAddr }, + grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + } + ecVolume := &erasure_coding.EcVolume{ + VolumeId: 9, + ShardLocations: map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {partialHolder(5)}}, + } + if err := store.cachedLookupEcShardLocations(ecVolume); err != nil { + t.Fatalf("lookup: %v", err) + } + ecVolume.ShardLocationsLock.RLock() + _, listed := ecVolume.ShardLocations[delisted] + hints := maps.Clone(ecVolume.ShardReadHints) + ecVolume.ShardLocationsLock.RUnlock() + if listed { + t.Error("shard 13 is still in the map after the master placed it nowhere") + } + if want := map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {partialHolder(5)}}; !maps.EqualFunc(hints, want, slices.Equal) { + t.Errorf("read hints %v, want %v", hints, want) + } + if err := store.doDeleteNeedleFromRemoteEcShardServers(delisted, ecVolume, 1); !errors.Is(err, errEcShardMissing) { + t.Errorf("a delete for shard 13 got %v, want it routed elsewhere", err) + } + + master.located.Store(14) + rewindShardLocationsRefresh(ecVolume, time.Hour) + if err := store.cachedLookupEcShardLocations(ecVolume); err != nil { + t.Fatalf("second lookup: %v", err) + } + ecVolume.ShardLocationsLock.RLock() + _, hinted := ecVolume.ShardReadHints[delisted] + ecVolume.ShardLocationsLock.RUnlock() + if hinted { + t.Error("the read hint outlived the master placing shard 13 again") + } +} + +// deletedNeedlePeer answers every shard read as the holder that journaled the +// needle's delete. +type deletedNeedlePeer struct { + volume_server_pb.UnimplementedVolumeServerServer +} + +func (deletedNeedlePeer) VolumeEcShardRead(req *volume_server_pb.VolumeEcShardReadRequest, stream volume_server_pb.VolumeServer_VolumeEcShardReadServer) error { + return stream.Send(&volume_server_pb.VolumeEcShardReadResponse{IsDeleted: true, EncodeTsNs: req.EncodeTsNs}) +} + +// The other shards rebuild a delisted shard's bytes but know nothing of a delete +// its holder journaled, so a read asks that holder before rebuilding. +func TestReadOneEcShardIntervalAsksADelistedHolderBeforeRebuilding(t *testing.T) { + const delisted = erasure_coding.ShardId(3) + baseFileName, n := writeEcVolumeFiles(t, t.TempDir(), 7) + others := startEcShardPeer(t, &oneBadShardPeer{baseFileName: baseFileName, badShard: delisted}) + journaled := startEcShardPeer(t, deletedNeedlePeer{}) + + store := &Store{grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())} + ecVolume := &erasure_coding.EcVolume{ + VolumeId: 7, + ShardLocations: make(map[erasure_coding.ShardId][]pb.ServerAddress), + } + seedShardLocations(ecVolume, others) + delete(ecVolume.ShardLocations, delisted) + ecVolume.ShardReadHints = map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {journaled}} + + interval := erasure_coding.Interval{BlockIndex: int(delisted), Size: 4096, IsLargeBlock: true} + got := make([]byte, interval.Size) + isDeleted, err := store.readOneEcShardInterval(n.Id, ecVolume, interval, got) + if err != nil || !isDeleted { + t.Fatalf("read interval: deleted=%v err=%v, want the delisted holder's delete", isDeleted, err) + } + + // A hint that no longer answers is dropped, and the read rebuilds the shard. + ecVolume.ShardReadHints[delisted] = []pb.ServerAddress{others} + isDeleted, err = store.readOneEcShardInterval(n.Id, ecVolume, interval, got) + if err != nil || isDeleted { + t.Fatalf("read interval: deleted=%v err=%v, want it rebuilt", isDeleted, err) + } + ecVolume.ShardLocationsLock.RLock() + _, hinted := ecVolume.ShardReadHints[delisted] + ecVolume.ShardLocationsLock.RUnlock() + if hinted { + t.Error("a read hint that failed is still kept") + } + want := make([]byte, len(got)) + f, err := os.Open(baseFileName + erasure_coding.ToExt(int(delisted))) + if err != nil { + t.Fatalf("open shard %d: %v", delisted, err) + } + defer f.Close() + if _, err := f.ReadAt(want, 0); err != nil { + t.Fatalf("read shard %d: %v", delisted, err) + } + if !bytes.Equal(got, want) { + t.Error("the rebuilt interval does not match the shard on disk") + } +} + +// A delete made after the delisting went to a listed holder, so the delisted +// holder still answers live; the read must not take that answer over the +// reconstruction that asks the listed holders. +func TestReadOneEcShardIntervalDoesNotTakeALiveAnswerFromADelistedHolder(t *testing.T) { + const delisted = erasure_coding.ShardId(3) + baseFileName, n := writeEcVolumeFiles(t, t.TempDir(), 7) + live := startEcShardPeer(t, &oneBadShardPeer{baseFileName: baseFileName, badShard: 13}) + journaled := startEcShardPeer(t, deletedNeedlePeer{}) + + store := &Store{grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())} + ecVolume := &erasure_coding.EcVolume{ + VolumeId: 7, + ShardLocations: map[erasure_coding.ShardId][]pb.ServerAddress{0: {journaled}}, + ShardReadHints: map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {live}}, + } + for shardId := erasure_coding.ShardId(4); shardId < 13; shardId++ { + ecVolume.ShardLocations[shardId] = []pb.ServerAddress{live} + } + ecVolume.ShardLocationsRefreshTime = time.Now() + + interval := erasure_coding.Interval{BlockIndex: int(delisted), Size: 4096, IsLargeBlock: true} + isDeleted, err := store.readOneEcShardInterval(n.Id, ecVolume, interval, make([]byte, interval.Size)) + if !isDeleted { + t.Fatalf("read interval: deleted=%v err=%v, want the listed holder's delete", isDeleted, err) + } + ecVolume.ShardLocationsLock.RLock() + _, hinted := ecVolume.ShardReadHints[delisted] + ecVolume.ShardLocationsLock.RUnlock() + if !hinted { + t.Error("a read hint that answered was dropped") + } +} + +// stalledPeer accepts a shard read and never answers it. +type stalledPeer struct { + volume_server_pb.UnimplementedVolumeServerServer +} + +func (stalledPeer) VolumeEcShardRead(req *volume_server_pb.VolumeEcShardReadRequest, stream volume_server_pb.VolumeServer_VolumeEcShardReadServer) error { + <-stream.Context().Done() + return stream.Context().Err() +} + +// hintReplacingPeer fails a read after a lookup has replaced the hint it used. +type hintReplacingPeer struct { + volume_server_pb.UnimplementedVolumeServerServer + replace func() +} + +func (p hintReplacingPeer) VolumeEcShardRead(req *volume_server_pb.VolumeEcShardReadRequest, stream volume_server_pb.VolumeServer_VolumeEcShardReadServer) error { + p.replace() + return status.Error(codes.Unavailable, "holder went away") +} + +// A delisted holder that stops answering costs a read only the hint's deadline, +// and a failed hinted read drops only the hint it used. +func TestReadOneEcShardIntervalBoundsAndScopesAFailedReadHint(t *testing.T) { + const delisted = erasure_coding.ShardId(3) + baseFileName, n := writeEcVolumeFiles(t, t.TempDir(), 7) + others := startEcShardPeer(t, &oneBadShardPeer{baseFileName: baseFileName, badShard: delisted}) + stalled := startEcShardPeer(t, stalledPeer{}) + + store := &Store{grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())} + ecVolume := &erasure_coding.EcVolume{ + VolumeId: 7, + ShardLocations: make(map[erasure_coding.ShardId][]pb.ServerAddress), + } + seedShardLocations(ecVolume, others) + delete(ecVolume.ShardLocations, delisted) + ecVolume.ShardReadHints = map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {stalled}} + defer func(old time.Duration) { ecReadHintTimeout = old }(ecReadHintTimeout) + ecReadHintTimeout = 200 * time.Millisecond + + interval := erasure_coding.Interval{BlockIndex: int(delisted), Size: 4096, IsLargeBlock: true} + read := func() { + t.Helper() + if isDeleted, err := store.readOneEcShardInterval(n.Id, ecVolume, interval, make([]byte, interval.Size)); err != nil || isDeleted { + t.Fatalf("read interval: deleted=%v err=%v, want it rebuilt", isDeleted, err) + } + } + hint := func() []pb.ServerAddress { + ecVolume.ShardLocationsLock.RLock() + defer ecVolume.ShardLocationsLock.RUnlock() + return ecVolume.ShardReadHints[delisted] + } + + start := time.Now() + read() + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Errorf("the read waited %v on a holder that never answers", elapsed) + } + if got := hint(); got != nil { + t.Errorf("a hint that timed out is still kept: %v", got) + } + + replacement := []pb.ServerAddress{others} + replacing := startEcShardPeer(t, hintReplacingPeer{replace: func() { + ecVolume.ShardLocationsLock.Lock() + ecVolume.ShardReadHints[delisted] = replacement + ecVolume.ShardLocationsLock.Unlock() + }}) + ecVolume.ShardReadHints[delisted] = []pb.ServerAddress{replacing} + read() + if got := hint(); !slices.Equal(got, replacement) { + t.Errorf("read hint %v, want the replacement %v kept", got, replacement) + } +} diff --git a/weed/storage/store_ec_quarantine_test.go b/weed/storage/store_ec_quarantine_test.go index c40948888e..fd7f54193a 100644 --- a/weed/storage/store_ec_quarantine_test.go +++ b/weed/storage/store_ec_quarantine_test.go @@ -2,6 +2,7 @@ package storage import ( "bytes" + "context" "fmt" "net" "os" @@ -133,7 +134,7 @@ func TestReadRemoteEcShardIntervalKeepsDeletionWhenTheStreamFails(t *testing.T) startEcShardPeer(t, &volume_server_pb.UnimplementedVolumeServerServer{}), } - _, isDeleted, err := store.readRemoteEcShardInterval(sources, 42, 7, 0, make([]byte, 64), 0, 0) + _, isDeleted, err := store.readRemoteEcShardInterval(context.Background(), sources, 42, 7, 0, make([]byte, 64), 0, 0) if err != nil || !isDeleted { t.Errorf("read got deleted=%v err=%v, want deleted and no error", isDeleted, err) } diff --git a/weed/storage/store_ec_scrub.go b/weed/storage/store_ec_scrub.go index 293827982c..96820c0c05 100644 --- a/weed/storage/store_ec_scrub.go +++ b/weed/storage/store_ec_scrub.go @@ -1,6 +1,7 @@ package storage import ( + "context" "errors" "fmt" "slices" @@ -112,7 +113,7 @@ func (s *Store) scrubEcVolumeWalk(ecv *erasure_coding.EcVolume, mode volume_serv ecv.ShardLocationsLock.RUnlock() readErr := errors.New("no known shard locations") if ok { - if _, _, readErr = s.readRemoteEcShardInterval(sourceDataNodes, id, ecv.VolumeId, shardId, chunk, offset, ecv.EncodeTsNs); readErr == nil { + if _, _, readErr = s.readRemoteEcShardInterval(context.Background(), sourceDataNodes, id, ecv.VolumeId, shardId, chunk, offset, ecv.EncodeTsNs); readErr == nil { data = append(data, chunk...) continue }