seaweed-volume, storage: a shard the master places nowhere is not a known location (#12898)

* seaweed-volume: a shard the master places nowhere is not a known location

The master answers LookupEcVolume with every shard slot it tracks, so a
shard whose holders are all down comes back with no locations. The cache
kept those entries. They overwrote the cached address of a holder that
was only restarting, counted toward the reply's data-shard guard, which
therefore always passed, and made the map look neither short nor
complete, so it was re-checked only every 7 minutes. Nothing marked it
stale meanwhile: a read never tries a shard with no address.

A shard with no location is now left out of the reply, as Go's
cachedLookupEcShardLocations does.

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

* storage: count only placed shards toward an EC lookup's completeness

The master answers every shard slot, so len(ShardIdLocations) is 32
whatever is up, and the guard that should keep a partial reply from
replacing a complete cache never fired. A reply placing fewer than the
data shards now fails the lookup and leaves the cache as it was, as the
Rust server does.

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

* storage: fill a cold EC location cache from a partial lookup

A reply placing fewer than the data shards no longer reaches the cache
at all, so a cold cache stays empty and a read cannot go straight to a
shard whose holder is up, as it could before the guard counted placed
shards. Take the holders it names for shards the cache does not know,
without touching known shards or the refresh time.

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

* seaweed-volume: fill a cold EC location cache from a partial lookup

write_back_shard_locations refused a reply placing fewer than the data
shards before writing anything, so a read on a cold cache kept an empty
map and could not fetch a shard directly from a holder the master did
name. A partial now fills only the shards the cache does not know,
leaves the refresh time alone and marks the map stale, as Go does. The
scrub still refuses a partial reply.

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

* storage: a partial EC lookup puts the holders it names first

A partial reply only filled shards the cache did not know, so a shard
that moved while the replies stayed partial kept its old address: a
failed direct read marked the map stale, the next partial reply skipped
the shard again, and the read fell back to a reconstruction that the
partial outage could not serve. A partial reply now puts the holders it
names ahead of the cached ones, which stay as fallback. Other shards and
the refresh time stay as they were.

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

* seaweed-volume: drop a shard the master places nowhere from the location cache

Leaving shards with no location out of the reply let a complete reply
keep a former holder's cached address for a shard the master now places
nowhere. An EC delete tried that address first: an offline peer failed
the delete without the fallback to other shard holders, and a peer that
had unmounted the volume acknowledged it without writing a tombstone.

The reply now keeps every slot and only located shards count toward its
completeness. A complete reply drops a shard it places nowhere, as Go's
delete-then-append does, and a partial reply's empty slots add nothing.

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

* seaweed-volume: a partial EC lookup puts the holders it names first

fill_shard_location_gaps took a partial reply's holders only for shards
the cache did not know, so a shard that moved while the replies stayed
partial kept its old address and a read could not reach it directly.
merge_partial_shard_locations puts the holders the reply names ahead of
the cached ones, which stay as fallback, as Go does.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-11-22 11:29:41 -08:00
1 parent a2df801e6d
commit c46dea9b6a
4 files changed
+288 -26

No files matched your search

+60 -19
View File
@@ -158,7 +158,7 @@ pub async fn read_ec_shard_needle_or_miss(
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => {
// A complete reply merges into the cache; an incomplete one
// (< data_shards) is left unwritten — keep the prior cache.
// (< data_shards) only puts the holders it names first.
match write_back_shard_locations(
state,
vid,
@@ -167,8 +167,6 @@ pub async fn read_ec_shard_needle_or_miss(
snapshot.encode_ts_ns,
) {
Some(merged) => shard_locations = merged,
// An incomplete reply leaves the cache unwritten and its refresh
// time unadvanced, so the mark this refresh consumed goes back.
None => mark_shard_locations_stale(state, vid),
}
}
@@ -714,8 +712,10 @@ pub async fn scrub_ec_volume_distributed(
) {
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => {
let partial = located_shard_count(&fresh) < data_shards;
if write_back_shard_locations(state, vid, fresh, data_shards, expected_encode_ts_ns)
.is_none()
|| partial
{
mark_shard_locations_stale(state, vid);
return (
@@ -1232,35 +1232,44 @@ async fn cached_lookup_ec_shard_locations(
.lookup_ec_volume(Request::new(LookupEcVolumeRequest { volume_id: vid.0 }))
.await
.map_err(|e| io::Error::other(format!("lookup_ec_volume: {}", e)))?;
let resp = resp.into_inner();
Ok(shard_locations_from_reply(resp.into_inner()))
}
/// The shard slots of a `LookupEcVolume` reply. The master answers every slot
/// it tracks, so a shard whose holders are all down comes back with no
/// addresses: it does not count toward the reply's completeness, and a complete
/// reply drops it from the cache, as Go's `cachedLookupEcShardLocations` does.
fn shard_locations_from_reply(
resp: master_pb::LookupEcVolumeResponse,
) -> HashMap<ShardId, Vec<String>> {
let mut out = HashMap::new();
for entry in resp.shard_id_locations {
let Ok(sid) = shard_id_try_from(entry.shard_id) else {
continue;
};
let addrs: Vec<String> = entry
.locations
.iter()
.map(format_location_as_server_address)
.collect();
// Defensive: skip out-of-range shard ids from the master instead of
// truncating (256 would alias 0). Valid replies are unaffected.
let Ok(sid) = shard_id_try_from(entry.shard_id) else {
continue;
};
out.insert(sid, addrs);
}
Ok(out)
out
}
fn located_shard_count(locations: &HashMap<ShardId, Vec<String>>) -> usize {
locations.values().filter(|addrs| !addrs.is_empty()).count()
}
/// Merge a fresh `LookupEcVolume` reply into the per-EcVolume shard-location
/// cache. Returns the merged map on success, or `None` when the reply is
/// incomplete (and was therefore NOT written) or the volume is gone.
/// cache. Returns the resulting map, or `None` when the volume is gone.
///
/// Completeness guard (mirrors Go's `cachedLookupEcShardLocations`): a reply
/// carrying fewer than `data_shards` shard locations is a master-mid-recovery
/// partial, not ground truth — Go aborts the lookup with a retryable error and
/// leaves the cache + refresh time untouched. Returning `None` without writing
/// does the same, so a previously-complete cache is never clobbered with a
/// partial map. On a complete reply the write is a per-shard MERGE (see
/// partial, not ground truth. It only puts the holders it names ahead of the
/// cached ones, and leaves the refresh time unadvanced with the map marked
/// stale, so a previously-complete cache is never clobbered with a partial map.
/// On a complete reply the write is a per-shard MERGE (see
/// `merge_shard_locations`), not a full replace.
fn write_back_shard_locations(
state: &Arc<VolumeServerState>,
@@ -1269,11 +1278,11 @@ fn write_back_shard_locations(
data_shards: usize,
expected_encode_ts_ns: i64,
) -> Option<HashMap<ShardId, Vec<String>>> {
if locations.len() < data_shards {
return None;
}
let store = state.store.read().unwrap();
let ecv = find_ec_volume_for_scrub(&store, vid, expected_encode_ts_ns)?;
if located_shard_count(&locations) < data_shards {
return Some(ecv.merge_partial_shard_locations(locations));
}
Some(ecv.merge_shard_locations(locations))
}
@@ -2782,6 +2791,38 @@ mod tests {
assert!(search(&shards, &metas, &n, dat_offset).is_none());
}
// The master answers all 32 shard slots, located or not. While 7 of a 10+4
// volume's shards have a holder up, the reply must count as 7 shards, short
// of the data shards.
#[test]
fn a_lookup_reply_counts_only_located_shards() {
use master_pb::lookup_ec_volume_response::EcShardIdLocation;
let located = [0u32, 3, 4, 6, 7, 9, 12];
let reply = master_pb::LookupEcVolumeResponse {
volume_id: 136,
shard_id_locations: (0..32u32)
.map(|sid| EcShardIdLocation {
shard_id: sid,
locations: if located.contains(&sid) {
vec![master_pb::Location {
url: "10.0.0.5:8180".to_string(),
grpc_port: 18180,
..Default::default()
}]
} else {
Vec::new()
},
..Default::default()
})
.collect(),
};
let got = shard_locations_from_reply(reply);
assert_eq!(got.len(), 32);
assert_eq!(located_shard_count(&got), 7);
assert!(got[&1].is_empty());
assert_eq!(got[&3], vec!["10.0.0.5:8180.18180".to_string()]);
}
fn locations(count: usize) -> HashMap<ShardId, Vec<String>> {
(0..count)
.map(|sid| (sid as ShardId, vec!["127.0.0.1:8080".to_string()]))
@@ -1726,10 +1726,11 @@ impl EcVolume {
/// stamp the refresh time, returning a clone of the resulting map.
///
/// Per-shard upsert (mirrors Go's `cachedLookupEcShardLocations`): each shard
/// id present in the reply overwrites its cached entry, while shard ids absent
/// from the reply keep their previously-cached locations — so a reply that
/// passes the data-shard completeness guard but omits a shard already in cache
/// does not drop that shard's known location (unlike a full replace).
/// id present in the reply overwrites its cached entry, and one the reply
/// places nowhere is dropped, while shard ids absent from the reply keep
/// their previously-cached locations — so a reply that passes the data-shard
/// completeness guard but omits a shard already in cache does not drop that
/// shard's known location (unlike a full replace).
///
/// Map and refresh time advance in one write section, so no reader can pair
/// the merged map with the previous lookup's timestamp.
@@ -1739,12 +1740,43 @@ impl EcVolume {
) -> HashMap<ShardId, Vec<String>> {
let mut cache = self.shard_locations.write().unwrap();
for (shard_id, addrs) in locations {
cache.locations.insert(shard_id, addrs);
if addrs.is_empty() {
cache.locations.remove(&shard_id);
} else {
cache.locations.insert(shard_id, addrs);
}
}
cache.refreshed_at = Some(Instant::now());
cache.locations.clone()
}
/// Put a partial reply's holders ahead of the cached ones for each shard it
/// places, keeping the cached addresses as fallback and every other shard
/// and the refresh time alone. A partial is not the volume's map, but a read
/// can still go straight to a shard it names; the map stays marked so the
/// next read looks it up again.
pub(crate) fn merge_partial_shard_locations(
&self,
locations: HashMap<ShardId, Vec<String>>,
) -> HashMap<ShardId, Vec<String>> {
let mut cache = self.shard_locations.write().unwrap();
for (shard_id, mut addrs) in locations {
if addrs.is_empty() {
continue;
}
if let Some(known) = cache.locations.get(&shard_id) {
for addr in known {
if !addrs.contains(addr) {
addrs.push(addr.clone());
}
}
}
cache.locations.insert(shard_id, addrs);
}
cache.stale = true;
cache.locations.clone()
}
/// The cached map and the time it was learned, read in one section. Both
/// halves describe the same refresh, which is what the freshness heuristic
/// assumes when it ages the map against the timestamp.
@@ -5448,6 +5480,47 @@ mod tests {
later.unwrap() >= before,
"the second merge re-stamped the refresh time"
);
// A shard the master places nowhere is dropped, not kept at an address
// a delete would trust.
let merged = vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
assert_eq!(merged, HashMap::from([(1, vec!["c:3".to_string()])]));
}
#[test]
fn merge_partial_shard_locations_keeps_known_holders_and_refresh_time() {
let tmp = TempDir::new().unwrap();
let vol = mount_bare_ec_volume(tmp.path().to_str().unwrap());
let filled =
vol.merge_partial_shard_locations(HashMap::from([(0, vec!["a:1".to_string()])]));
assert_eq!(filled.get(&0), Some(&vec!["a:1".to_string()]));
assert!(
vol.shard_locations_snapshot().1.is_none(),
"a partial reply is not a refresh"
);
vol.merge_shard_locations(HashMap::from([(1, vec!["b:2".to_string()])]));
let stamped = vol.shard_locations_snapshot().1;
vol.claim_shard_locations_refresh(|_| true);
let filled = vol.merge_partial_shard_locations(HashMap::from([
(1, vec!["c:3".to_string()]),
(2, vec!["d:4".to_string()]),
(3, Vec::new()),
]));
assert_eq!(
filled.get(&1),
Some(&vec!["c:3".to_string(), "b:2".to_string()]),
"a holder the partial names goes first, the cached one stays as fallback"
);
assert_eq!(filled.get(&0), Some(&vec!["a:1".to_string()]));
assert_eq!(filled.get(&2), Some(&vec!["d:4".to_string()]));
assert!(!filled.contains_key(&3), "a partial reply's empty slot adds nothing");
assert_eq!(vol.shard_locations_snapshot().1, stamped);
assert!(
vol.claim_shard_locations_refresh(|stale| stale),
"the partial leaves the map marked for the next lookup"
);
}
/// The stale mark is consumed by the refresh that acts on it, exactly once:
+31 -2
View File
@@ -1182,8 +1182,37 @@ func (s *Store) cachedLookupEcShardLocations(ecVolume *erasure_coding.EcVolume)
if err != nil {
return fmt.Errorf("lookup ec volume %d: %v", ecVolume.VolumeId, err)
}
if len(resp.ShardIdLocations) < ecCtx.DataShards {
return fmt.Errorf("only %d shards found but %d required", len(resp.ShardIdLocations), ecCtx.DataShards)
// The master answers every shard slot it tracks; only the shards it
// places on a server count toward a usable map.
located := 0
for _, shardIdLocations := range resp.ShardIdLocations {
if len(shardIdLocations.Locations) > 0 {
located++
}
}
if located < ecCtx.DataShards {
// Too few to trust as the volume's map, but a read can still go
// straight to a shard it names: put those holders first, keep the
// cached ones as fallback, and leave the refresh time alone.
ecVolume.ShardLocationsLock.Lock()
for _, shardIdLocations := range resp.ShardIdLocations {
if len(shardIdLocations.Locations) == 0 {
continue
}
shardId := erasure_coding.ShardId(shardIdLocations.ShardId)
var holders []pb.ServerAddress
for _, loc := range shardIdLocations.Locations {
holders = append(holders, pb.NewServerAddressFromLocation(loc))
}
for _, known := range ecVolume.ShardLocations[shardId] {
if !slices.Contains(holders, known) {
holders = append(holders, known)
}
}
ecVolume.ShardLocations[shardId] = holders
}
ecVolume.ShardLocationsLock.Unlock()
return fmt.Errorf("only %d shards found but %d required", located, ecCtx.DataShards)
}
ecVolume.ShardLocationsLock.Lock()
@@ -3,8 +3,10 @@ package storage
import (
"bytes"
"context"
"fmt"
"net"
"os"
"slices"
"sync/atomic"
"testing"
"time"
@@ -30,6 +32,22 @@ type countingMaster struct {
onLookup func()
// failLookup answers with an error instead of a shard map.
failLookup atomic.Bool
// located, when set, answers every shard slot as the master does but
// places only the first located shards on a server.
located atomic.Int64
// partialPort is the port of the server those shards are placed on; 0 is 1.
partialPort atomic.Int64
}
func partialLocation(port int64) *master_pb.Location {
if port == 0 {
port = 1
}
return &master_pb.Location{Url: fmt.Sprintf("127.0.0.1:%d", port), GrpcPort: 2}
}
func partialHolder(port int64) pb.ServerAddress {
return pb.NewServerAddressFromLocation(partialLocation(port))
}
func (m *countingMaster) LookupEcVolume(_ context.Context, req *master_pb.LookupEcVolumeRequest) (*master_pb.LookupEcVolumeResponse, error) {
@@ -41,6 +59,16 @@ func (m *countingMaster) LookupEcVolume(_ context.Context, req *master_pb.Lookup
return nil, status.Error(codes.Unavailable, "master is having a moment")
}
resp := &master_pb.LookupEcVolumeResponse{VolumeId: req.VolumeId}
if located := int(m.located.Load()); located > 0 {
for shardId := 0; shardId < erasure_coding.MaxShardCount; shardId++ {
entry := &master_pb.LookupEcVolumeResponse_EcShardIdLocation{ShardId: uint32(shardId)}
if shardId < located {
entry.Locations = []*master_pb.Location{partialLocation(m.partialPort.Load())}
}
resp.ShardIdLocations = append(resp.ShardIdLocations, entry)
}
return resp, nil
}
for shardId := 0; shardId < erasure_coding.TotalShardsCount; shardId++ {
resp.ShardIdLocations = append(resp.ShardIdLocations, &master_pb.LookupEcVolumeResponse_EcShardIdLocation{
ShardId: uint32(shardId),
@@ -152,6 +180,97 @@ func TestCachedLookupEcShardLocationsSettlesAfterRefresh(t *testing.T) {
}
}
// The master answers every shard slot, so a reply naming 32 shards can still
// place fewer than the data shards on a server, as while several holders are
// down. That reply is a partial and must leave a complete cache as it was.
func TestCachedLookupEcShardLocationsRefusesAReplyWithFewLocatedShards(t *testing.T) {
master, masterAddr := startCountingMaster(t)
store := &Store{
MasterFn: func() pb.ServerAddress { return masterAddr },
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
ecVolume := &erasure_coding.EcVolume{
VolumeId: 9,
ShardLocations: make(map[erasure_coding.ShardId][]pb.ServerAddress),
}
if err := store.cachedLookupEcShardLocations(ecVolume); err != nil {
t.Fatalf("first lookup: %v", err)
}
master.located.Store(7)
master.partialPort.Store(3)
rewindShardLocationsRefresh(ecVolume, 12*time.Second)
ecVolume.ShardLocationsLock.Lock()
ecVolume.ShardLocationsStale = true
refreshedAt := ecVolume.ShardLocationsRefreshTime
ecVolume.ShardLocationsLock.Unlock()
if err := store.cachedLookupEcShardLocations(ecVolume); err == nil {
t.Error("a reply placing 7 of 14 shards was accepted")
}
ecVolume.ShardLocationsLock.RLock()
cached := len(ecVolume.ShardLocations)
named := ecVolume.ShardLocations[0]
unnamed := ecVolume.ShardLocations[7]
refreshed := ecVolume.ShardLocationsRefreshTime
ecVolume.ShardLocationsLock.RUnlock()
if cached != erasure_coding.TotalShardsCount {
t.Errorf("the cache holds %d shards after the partial reply, want all %d kept", cached, erasure_coding.TotalShardsCount)
}
if want := []pb.ServerAddress{partialHolder(3), partialHolder(1)}; !slices.Equal(named, want) {
t.Errorf("a shard the partial reply places holds %v, want its new holder first and the cached one kept: %v", named, want)
}
if want := []pb.ServerAddress{partialHolder(1)}; !slices.Equal(unnamed, want) {
t.Errorf("a shard the partial reply places nowhere holds %v, want its cached %v", unnamed, want)
}
if !refreshed.Equal(refreshedAt) {
t.Errorf("the partial reply moved the refresh time from %v to %v", refreshedAt, refreshed)
}
}
// A partial reply is no map to trust, but the cache takes the holders it names,
// so a read can still go straight to a shard whose holder is up, including one
// that moved while the replies stayed partial.
func TestCachedLookupEcShardLocationsFillsAColdCacheFromAPartialReply(t *testing.T) {
master, masterAddr := startCountingMaster(t)
master.located.Store(7)
store := &Store{
MasterFn: func() pb.ServerAddress { return masterAddr },
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
ecVolume := &erasure_coding.EcVolume{
VolumeId: 9,
ShardLocations: make(map[erasure_coding.ShardId][]pb.ServerAddress),
}
if err := store.cachedLookupEcShardLocations(ecVolume); err == nil {
t.Error("a reply placing 7 of 14 shards was accepted")
}
ecVolume.ShardLocationsLock.RLock()
cached := len(ecVolume.ShardLocations)
refreshed := !ecVolume.ShardLocationsRefreshTime.IsZero()
stale := ecVolume.ShardLocationsStale
ecVolume.ShardLocationsLock.RUnlock()
if cached != 7 {
t.Errorf("the cold cache holds %d shards after the partial reply, want the 7 it placed", cached)
}
if refreshed || !stale {
t.Errorf("a partial reply must leave the map due a lookup: refreshed=%v stale=%v", refreshed, stale)
}
master.partialPort.Store(4)
if err := store.cachedLookupEcShardLocations(ecVolume); err == nil {
t.Error("a second reply placing 7 of 14 shards was accepted")
}
if got := master.lookups.Load(); got != 2 {
t.Fatalf("asked the master %d times, want 2: a partial reply leaves the map due", got)
}
ecVolume.ShardLocationsLock.RLock()
moved := ecVolume.ShardLocations[0]
ecVolume.ShardLocationsLock.RUnlock()
if want := []pb.ServerAddress{partialHolder(4), partialHolder(1)}; !slices.Equal(moved, want) {
t.Errorf("after the shard moved, the cache holds %v, want %v", moved, want)
}
}
func TestEcShardLocationsTTL(t *testing.T) {
ecCtx := erasure_coding.NewDefaultECContext("", 1)
for _, tc := range []struct {