From 38576bb8e0944c3cdc750bd8f32aba65ef2c21bb Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Tue, 13 Oct 2026 12:06:18 +0000 Subject: [PATCH 1/9] shard: track replicas in ReplicaTracker Extract replica address tracking from ShardSharedinto a new ReplicaTracker class. The state management is a little bit different to the old code but behaviorally there are no significant differences here. Add tests for registry updates and the published snapshots. --- cpp/shard/CMakeLists.txt | 2 +- cpp/shard/ReplicaTracker.cpp | 103 ++++++++++++++++++++++++++++++ cpp/shard/ReplicaTracker.hpp | 53 +++++++++++++++ cpp/shard/Shard.cpp | 44 ++++--------- cpp/tests.sh | 6 +- cpp/tests/CMakeLists.txt | 3 + cpp/tests/replicatrackertests.cpp | 83 ++++++++++++++++++++++++ 7 files changed, 258 insertions(+), 36 deletions(-) create mode 100644 cpp/shard/ReplicaTracker.cpp create mode 100644 cpp/shard/ReplicaTracker.hpp create mode 100644 cpp/tests/replicatrackertests.cpp diff --git a/cpp/shard/CMakeLists.txt b/cpp/shard/CMakeLists.txt index 480392cba..d05d46270 100644 --- a/cpp/shard/CMakeLists.txt +++ b/cpp/shard/CMakeLists.txt @@ -4,7 +4,7 @@ include_directories(${ternfs_SOURCE_DIR}/core) -add_library(shard Shard.cpp Shard.hpp ShardDB.cpp ShardDB.hpp ShardDBData.cpp ShardDBData.hpp BlockServicesCacheDB.hpp BlockServicesCacheDB.cpp BlockServicePicker.hpp BlockServicePicker.cpp) +add_library(shard Shard.cpp Shard.hpp ShardDB.cpp ShardDB.hpp ShardDBData.cpp ShardDBData.hpp BlockServicesCacheDB.hpp BlockServicesCacheDB.cpp BlockServicePicker.hpp BlockServicePicker.cpp ReplicaTracker.hpp ReplicaTracker.cpp) target_link_libraries(shard PRIVATE core crc32c) add_executable(ternshard ternshard.cpp) diff --git a/cpp/shard/ReplicaTracker.cpp b/cpp/shard/ReplicaTracker.cpp new file mode 100644 index 000000000..03f952064 --- /dev/null +++ b/cpp/shard/ReplicaTracker.cpp @@ -0,0 +1,103 @@ +// Copyright 2026 XTX Markets Technologies Limited +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "ReplicaTracker.hpp" + +ReplicaTracker::ReplicaTracker(ShardReplicaId self, uint8_t location, bool isLeader, const AddrsInfo& addrs) + : _self(self), + _location(location), + _localReplicas(std::make_shared()), + _remoteLeaders(std::make_shared()) +{ + _peers.emplace( + ShardReplicaLocationKey(_self, _location), + PeerState{ + .addrs = addrs, + .isLeader = isLeader, + .registryLastSeen = {}, + }); + _publishLocked(); +} + +bool ReplicaTracker::_validReplicaId(ShardReplicaId id) { + return (id.u16 >> 8) < LogsDB::REPLICA_COUNT; +} + +void ReplicaTracker::seedRegistry(const std::vector& replicas) { + std::lock_guard lock(_mutex); + bool changed = false; + + for (const auto& replica : replicas) { + if (!_validReplicaId(replica.id) || + replica.id.shardId() != _self.shardId() || + (replica.id == _self && replica.locationId == _location)) { + continue; + } + + const auto key = ShardReplicaLocationKey(replica.id, replica.locationId); + auto [it, inserted] = _peers.try_emplace( + key, + PeerState{ + .addrs = replica.addrs, + .isLeader = replica.isLeader, + .registryLastSeen = replica.lastSeen, + }); + if (inserted) { + changed = true; + continue; + } + + it->second.registryLastSeen = replica.lastSeen; + if (replica.addrs[0].port != 0 || replica.addrs[1].port != 0) { + it->second.addrs = replica.addrs; + } + it->second.isLeader = replica.isLeader; + changed = true; + } + + if (changed) { + _publishLocked(); + } +} + +std::shared_ptr +ReplicaTracker::localReplicas() const { + return _localReplicas.load(); +} + +std::shared_ptr +ReplicaTracker::remoteLeaders() const { + return _remoteLeaders.load(); +} + +std::optional +ReplicaTracker::peerState(ShardReplicaId id, uint8_t location) const { + std::lock_guard lock(_mutex); + auto it = _peers.find(ShardReplicaLocationKey(id, location)); + if (it == _peers.end()) { + return std::nullopt; + } + return it->second; +} + +void ReplicaTracker::_publishLocked() { + auto local = std::make_shared(); + auto remote = std::make_shared(); + + for (const auto& [key, peer] : _peers) { + const auto id = key.shardReplicaId(); + const auto location = key.locationId(); + + if (location == _location) { + (*local)[id.replicaId().u8] = peer.addrs; + } else if (peer.isLeader && peer.addrs[0].port != 0) { + // A leader without an address, which the registry reports after + // wiping dynamic ports, cannot be waited for or replicated to. + remote->emplace_back(id, peer.isLeader, peer.addrs, peer.registryLastSeen, location); + } + } + + _localReplicas.store(std::move(local)); + _remoteLeaders.store(std::move(remote)); +} diff --git a/cpp/shard/ReplicaTracker.hpp b/cpp/shard/ReplicaTracker.hpp new file mode 100644 index 000000000..000ef6176 --- /dev/null +++ b/cpp/shard/ReplicaTracker.hpp @@ -0,0 +1,53 @@ +// Copyright 2026 XTX Markets Technologies Limited +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "LogsDB.hpp" +#include "MsgsGen.hpp" +#include "Time.hpp" + +// Tracks the replicas of our shard, at every location, as the registry +// describes them. It publishes the addresses of the replicas at our location +// and the leaders at other locations as snapshots that the receive, writer +// and metrics threads read without locking. +class ReplicaTracker { +public: + struct PeerState { + AddrsInfo addrs; + bool isLeader; + TernTime registryLastSeen; // when the registry last heard from the peer + }; + + using LocalReplicas = std::array; + using RemoteLeaders = std::vector; + + ReplicaTracker(ShardReplicaId self, uint8_t location, bool isLeader, const AddrsInfo& addrs); + + // Takes addresses, leadership and last-seen times from the registry. + void seedRegistry(const std::vector& replicas); + + std::shared_ptr localReplicas() const; + std::shared_ptr remoteLeaders() const; + std::optional peerState(ShardReplicaId id, uint8_t location) const; + +private: + const ShardReplicaId _self; + const uint8_t _location; + mutable std::mutex _mutex; + std::unordered_map _peers; + std::atomic> _localReplicas; + std::atomic> _remoteLeaders; + + static bool _validReplicaId(ShardReplicaId id); + void _publishLocked(); +}; diff --git a/cpp/shard/Shard.cpp b/cpp/shard/Shard.cpp index 716852f51..d73ce839e 100644 --- a/cpp/shard/Shard.cpp +++ b/cpp/shard/Shard.cpp @@ -35,6 +35,7 @@ #include "ShardKey.hpp" #include "SharedRocksDB.hpp" #include "RegistryClient.hpp" +#include "ReplicaTracker.hpp" #include "SPSC.hpp" #include "Time.hpp" #include "Timings.hpp" @@ -130,6 +131,9 @@ struct ShardShared { RegistryClient registryClient; + // the replicas of our shard at every location, as the registry describes them + ReplicaTracker replicaTracker; + ShardShared() = delete; ShardShared(const ShardOptions& options_, SharedRocksDB& sharedDB_, BlockServicesCacheDB& blockServicesCache_, ShardDB& shardDB_, LogsDB& logsDB_, UDPSocketPair&& sock, Logger& logger, std::shared_ptr& xmon) : options(options_), @@ -163,8 +167,7 @@ struct ShardShared { isInitiated(false), isBlockServiceCacheInitiated(false), registryClient(logger, xmon, options_.registryClientOptions.host, options_.registryClientOptions.port, options_.registryClientOptions.timeout), - _replicas(nullptr), - _leadersAtOtherLocations(std::make_shared>()) + replicaTracker(options_.shrid(), options_.logsDBOptions.location, options_.isLeader(), socks[0].addr()) { for (uint16_t i = 0; i < options_.numReaders; ++i) { readerRequestsQueues.emplace_back(std::make_unique>(READER_QUEUE_SIZE)); @@ -182,11 +185,7 @@ struct ShardShared { } inline std::shared_ptr> getReplicas() const { - return _replicas.load(); - } - - inline void setReplicas(const std::array&& replicas) { - _replicas.store(std::make_shared>(replicas)); + return replicaTracker.localReplicas(); } inline bool readStale() const { @@ -195,17 +194,8 @@ struct ShardShared { } inline std::shared_ptr> getLeadersAtOtherLocations() const { - return _leadersAtOtherLocations.load(); + return replicaTracker.remoteLeaders(); } - - inline void setLeadersAtOtherLocations(const std::vector&& leadersAtOtherLocations) { - _leadersAtOtherLocations.store(std::make_shared>(leadersAtOtherLocations)); - } - -private: - // replication information - std::atomic>> _replicas; // used for replicating shard within location - std::atomic>> _leadersAtOtherLocations; // used for cross location replication }; static bool bigRequest(ShardMessageKind kind) { @@ -2222,18 +2212,13 @@ struct ShardRegisterer : PeriodicLoop { return false; } - std::vector leadersAtOtherLocations; + _shared.replicaTracker.seedRegistry(allReplicas); + LOG_DEBUG(_env, "Leaders at other locations now %s", *_shared.getLeadersAtOtherLocations()); + std::array localReplicas; for (auto& replica : allReplicas) { - if (replica.id.shardId() != _shrid.shardId()) { - continue; - } - if (replica.locationId == _location) { + if (replica.id.shardId() == _shrid.shardId() && replica.locationId == _location) { localReplicas[replica.id.replicaId().u8] = replica.addrs; - continue; - } - if (replica.isLeader && replica.addrs.addrs[0].port != 0) { - leadersAtOtherLocations.emplace_back(std::move(replica)); } } if (_shared.sock().addr() != localReplicas[_shrid.replicaId().u8]) { @@ -2254,13 +2239,6 @@ struct ShardRegisterer : PeriodicLoop { } } - if (unlikely(!_shared.getReplicas() || *_shared.getReplicas() != localReplicas)) { - LOG_DEBUG(_env, "Updating replicas to %s %s %s %s %s", localReplicas[0], localReplicas[1], localReplicas[2], localReplicas[3], localReplicas[4]); - _shared.setReplicas(std::move(localReplicas)); - } - - LOG_DEBUG(_env, "Updating leaders at other locations to %s", leadersAtOtherLocations); - _shared.setLeadersAtOtherLocations(std::move(leadersAtOtherLocations)); } _env.clearAlert(_alert); diff --git a/cpp/tests.sh b/cpp/tests.sh index e90f1380d..7573f6f69 100755 --- a/cpp/tests.sh +++ b/cpp/tests.sh @@ -10,7 +10,7 @@ cd "$(dirname "$0")" echo "$(tput bold)C++ tests, sanitized$(tput sgr0)" set -x -./build.py sanitized rs/rs-tests crc32c/crc32c-tests tests/tests tests/shardsnapshottests tests/logsdbtests tests/registrydbtests tests/blockservicepickertests tests/blockservicescachedbtests +./build.py sanitized rs/rs-tests crc32c/crc32c-tests tests/tests tests/shardsnapshottests tests/logsdbtests tests/registrydbtests tests/blockservicepickertests tests/blockservicescachedbtests tests/replicatrackertests UBSAN_OPTIONS=print_stacktrace=1 ./build/sanitized/rs/rs-tests UBSAN_OPTIONS=print_stacktrace=1 ./build/sanitized/crc32c/crc32c-tests UBSAN_OPTIONS=print_stacktrace=1 ./build/sanitized/tests/tests @@ -19,6 +19,7 @@ UBSAN_OPTIONS=print_stacktrace=1 ./build/sanitized/tests/logsdbtests UBSAN_OPTIONS=print_stacktrace=1 ./build/sanitized/tests/registrydbtests UBSAN_OPTIONS=print_stacktrace=1 ./build/sanitized/tests/blockservicepickertests UBSAN_OPTIONS=print_stacktrace=1 ./build/sanitized/tests/blockservicescachedbtests +UBSAN_OPTIONS=print_stacktrace=1 ./build/sanitized/tests/replicatrackertests set +x # valgrind doesn't support fnctl F_SET_RW_HINT (1036), and as far as I can @@ -26,7 +27,7 @@ set +x echo "$(tput bold)C++ tests, valgrind$(tput sgr0)" set -x -./build.py valgrind rs/rs-tests crc32c/crc32c-tests tests/tests tests/shardsnapshottests tests/logsdbtests tests/registrydbtests tests/blockservicepickertests tests/blockservicescachedbtests +./build.py valgrind rs/rs-tests crc32c/crc32c-tests tests/tests tests/shardsnapshottests tests/logsdbtests tests/registrydbtests tests/blockservicepickertests tests/blockservicescachedbtests tests/replicatrackertests valgrind --exit-on-first-error=yes -q --error-exitcode=1 ./build/valgrind/rs/rs-tests valgrind --exit-on-first-error=yes -q --error-exitcode=1 ./build/valgrind/crc32c/crc32c-tests valgrind --exit-on-first-error=yes -q --suppressions=valgrind-suppressions --error-exitcode=1 ./build/valgrind/tests/tests 2> >(grep -v "Warning: unimplemented fcntl command: 1036") @@ -36,4 +37,5 @@ valgrind --exit-on-first-error=yes -q --suppressions=valgrind-suppressions --err valgrind --exit-on-first-error=yes -q --suppressions=valgrind-suppressions --error-exitcode=1 ./build/valgrind/tests/registrydbtests 2> >(grep -v "Warning: unimplemented fcntl command: 1036") valgrind --exit-on-first-error=yes -q --suppressions=valgrind-suppressions --error-exitcode=1 ./build/valgrind/tests/blockservicepickertests 2> >(grep -v "Warning: unimplemented fcntl command: 1036") valgrind --exit-on-first-error=yes -q --suppressions=valgrind-suppressions --error-exitcode=1 ./build/valgrind/tests/blockservicescachedbtests 2> >(grep -v "Warning: unimplemented fcntl command: 1036") +valgrind --exit-on-first-error=yes -q --suppressions=valgrind-suppressions --error-exitcode=1 ./build/valgrind/tests/replicatrackertests 2> >(grep -v "Warning: unimplemented fcntl command: 1036") set +x diff --git a/cpp/tests/CMakeLists.txt b/cpp/tests/CMakeLists.txt index cce39bbbf..a8bc58e58 100644 --- a/cpp/tests/CMakeLists.txt +++ b/cpp/tests/CMakeLists.txt @@ -40,5 +40,8 @@ target_link_libraries(registrydbtests PRIVATE core registry) add_executable(blockservicepickertests blockservicepickertests.cpp doctest.h) target_link_libraries(blockservicepickertests PRIVATE core shard) +add_executable(replicatrackertests replicatrackertests.cpp doctest.h) +target_link_libraries(replicatrackertests PRIVATE core shard) + add_executable(blockservicescachedbtests blockservicescachedbtests.cpp doctest.h) target_link_libraries(blockservicescachedbtests PRIVATE core shard) diff --git a/cpp/tests/replicatrackertests.cpp b/cpp/tests/replicatrackertests.cpp new file mode 100644 index 000000000..14db1192d --- /dev/null +++ b/cpp/tests/replicatrackertests.cpp @@ -0,0 +1,83 @@ +// Copyright 2026 XTX Markets Technologies Limited +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "ReplicaTracker.hpp" + +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include "doctest.h" + +static IpPort address(uint8_t lastOctet, uint16_t port) { + IpPort result; + result.ip.data = {127, 0, 0, lastOctet}; + result.port = port; + return result; +} + +static AddrsInfo addresses(uint8_t lastOctet, uint16_t port) { + AddrsInfo result; + result[0] = address(lastOctet, port); + return result; +} + +TEST_CASE("registry seeds local replicas and remote leaders") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + ReplicaTracker tracker(self, 2, true, addresses(1, 10001)); + + std::vector replicas{ + FullShardInfo(self, true, addresses(1, 10001), 0, 2), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(1)), false, addresses(2, 10002), 0, 2), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(0)), true, addresses(3, 10003), TernTime(1'000), 3), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(2)), false, addresses(4, 10004), 0, 3), + FullShardInfo(ShardReplicaId(ShardId(8), ReplicaId(1)), true, addresses(5, 10005), 0, 2), + // A leader at another location whose address the registry has wiped. + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(0)), true, AddrsInfo(), 0, 4), + }; + tracker.seedRegistry(replicas); + + auto local = tracker.localReplicas(); + CHECK((*local)[0] == addresses(1, 10001)); + CHECK((*local)[1] == addresses(2, 10002)); + CHECK((*local)[2][0].port == 0); + + // Only leaders with an address, as the registry path always did. + auto remote = tracker.remoteLeaders(); + REQUIRE(remote->size() == 1); + CHECK(remote->at(0).id == ShardReplicaId(ShardId(7), ReplicaId(0))); + CHECK(remote->at(0).locationId == 3); + CHECK(remote->at(0).addrs == addresses(3, 10003)); + CHECK(remote->at(0).lastSeen == TernTime(1'000)); +} + +TEST_CASE("later registry polls update peers") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + const auto remoteLeader = ShardReplicaId(ShardId(7), ReplicaId(4)); + ReplicaTracker tracker(self, 2, true, addresses(1, 10001)); + + std::vector registry{ + FullShardInfo(peer, false, addresses(2, 10002), TernTime(1'000), 2), + FullShardInfo(remoteLeader, true, addresses(3, 10003), TernTime(1'000), 3), + }; + tracker.seedRegistry(registry); + CHECK((*tracker.localReplicas())[1] == addresses(2, 10002)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + + // The peer moved host, the remote leader was heard from again. + registry[0].addrs = addresses(3, 10003); + registry[1].lastSeen = TernTime(2'000); + tracker.seedRegistry(registry); + CHECK((*tracker.localReplicas())[1] == addresses(3, 10003)); + CHECK(tracker.remoteLeaders()->at(0).lastSeen == TernTime(2'000)); + + // The remote leader stepped down and the peer's address was wiped: the + // leader list empties, the peer keeps its last address. + registry[0].addrs = AddrsInfo(); + registry[1].isLeader = false; + tracker.seedRegistry(registry); + CHECK((*tracker.localReplicas())[1] == addresses(3, 10003)); + CHECK(tracker.remoteLeaders()->empty()); + auto state = tracker.peerState(peer, 2); + REQUIRE(state.has_value()); + CHECK(state->registryLastSeen == TernTime(1'000)); +} From 16bd8c9f60697a9a529970e2569476ba3845aed1 Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Wed, 2 Sep 2026 10:34:02 +0000 Subject: [PATCH 2/9] shard: define replica announcement protocol At the moment, shards find their peers only through the registry. We would like to reduce the time taken for the cluster to observe and respond to partitions, but the overloaded registry is an impediment. This commit introduces new shard replica messages containing identity, location, leadership and address information, signed with the shard key. This will allow one shard shard replica to announce itself to the existing shad replicas immediatley rather than waiting for one full registry poll. --- cpp/core/Msgs.hpp | 2 +- cpp/core/MsgsGen.cpp | 30 +++++++++++++++++ cpp/core/MsgsGen.hpp | 30 +++++++++++++++++ cpp/core/Protocol.hpp | 15 +++++++++ cpp/tests/tests.cpp | 67 +++++++++++++++++++++++++++++++++++++ go/bincodegen/bincodegen.go | 1 + go/msgs/msgs.go | 13 +++++-- go/msgs/msgs_bincode.go | 32 ++++++++++++++++++ 8 files changed, 187 insertions(+), 3 deletions(-) diff --git a/cpp/core/Msgs.hpp b/cpp/core/Msgs.hpp index 14684e0e7..1d8b685b9 100644 --- a/cpp/core/Msgs.hpp +++ b/cpp/core/Msgs.hpp @@ -188,7 +188,7 @@ struct ShardReplicaId { } constexpr bool valid() const { - return replicaId().valid(); + return (u16 >> 8) < 5; } }; diff --git a/cpp/core/MsgsGen.cpp b/cpp/core/MsgsGen.cpp index e0d799f68..d5d6cf474 100644 --- a/cpp/core/MsgsGen.cpp +++ b/cpp/core/MsgsGen.cpp @@ -1579,6 +1579,36 @@ std::ostream& operator<<(std::ostream& out, const FullShardInfo& x) { return out; } +void ShardReplicaAnnouncement::pack(BincodeBuf& buf) const { + shrid.pack(buf); + buf.packScalar(location); + buf.packScalar(isLeader); + addrs.pack(buf); +} +void ShardReplicaAnnouncement::unpack(BincodeBuf& buf) { + shrid.unpack(buf); + location = buf.unpackScalar(); + isLeader = buf.unpackScalar(); + addrs.unpack(buf); +} +void ShardReplicaAnnouncement::clear() { + shrid = ShardReplicaId(); + location = uint8_t(0); + isLeader = bool(0); + addrs.clear(); +} +bool ShardReplicaAnnouncement::operator==(const ShardReplicaAnnouncement& rhs) const { + if ((ShardReplicaId)this->shrid != (ShardReplicaId)rhs.shrid) { return false; }; + if ((uint8_t)this->location != (uint8_t)rhs.location) { return false; }; + if ((bool)this->isLeader != (bool)rhs.isLeader) { return false; }; + if (addrs != rhs.addrs) { return false; }; + return true; +} +std::ostream& operator<<(std::ostream& out, const ShardReplicaAnnouncement& x) { + out << "ShardReplicaAnnouncement(" << "Shrid=" << x.shrid << ", " << "Location=" << (int)x.location << ", " << "IsLeader=" << x.isLeader << ", " << "Addrs=" << x.addrs << ")"; + return out; +} + void RegisterBlockServiceInfo::pack(BincodeBuf& buf) const { id.pack(buf); buf.packScalar(locationId); diff --git a/cpp/core/MsgsGen.hpp b/cpp/core/MsgsGen.hpp index 68b8f6234..4e9cdcb6b 100644 --- a/cpp/core/MsgsGen.hpp +++ b/cpp/core/MsgsGen.hpp @@ -1592,6 +1592,36 @@ struct FullShardInfo { std::ostream& operator<<(std::ostream& out, const FullShardInfo& x); +struct ShardReplicaAnnouncement { + ShardReplicaId shrid; + uint8_t location; + bool isLeader; + AddrsInfo addrs; + + static constexpr uint16_t STATIC_SIZE = 2 + 1 + 1 + AddrsInfo::STATIC_SIZE; // shrid + location + isLeader + addrs + + ShardReplicaAnnouncement() { clear(); } + explicit ShardReplicaAnnouncement(ShardReplicaId shrid_, uint8_t location_, bool isLeader_, AddrsInfo addrs_) : shrid(shrid_), location(location_), isLeader(isLeader_), addrs(addrs_) {} + ShardReplicaAnnouncement(const ShardReplicaAnnouncement&) = default; + ShardReplicaAnnouncement& operator=(const ShardReplicaAnnouncement&) = default; + ShardReplicaAnnouncement(ShardReplicaAnnouncement&&) = default; + ShardReplicaAnnouncement& operator=(ShardReplicaAnnouncement&&) = default; + size_t packedSize() const { + size_t _size = 0; + _size += 2; // shrid + _size += 1; // location + _size += 1; // isLeader + _size += addrs.packedSize(); // addrs + return _size; + } + void pack(BincodeBuf& buf) const; + void unpack(BincodeBuf& buf); + void clear(); + bool operator==(const ShardReplicaAnnouncement&rhs) const; +}; + +std::ostream& operator<<(std::ostream& out, const ShardReplicaAnnouncement& x); + struct RegisterBlockServiceInfo { BlockServiceId id; uint8_t locationId; diff --git a/cpp/core/Protocol.hpp b/cpp/core/Protocol.hpp index 95696ac9e..bc13ef2ea 100644 --- a/cpp/core/Protocol.hpp +++ b/cpp/core/Protocol.hpp @@ -34,6 +34,10 @@ constexpr uint32_t PROXY_SHARD_REQ_PROTOCOL_VERSION = 0x5414853; // '6414853' constexpr uint32_t PROXY_SHARD_RESP_PROTOCOL_VERSION = 0x6414853; +// >>> format(struct.unpack('>> format(struct.unpack('; using ProxyShardReqMsg = SignedProtocolMessage; using ProxyShardRespMsg = SignedProtocolMessage; + +// SignedProtocolMessage includes body.kind() in diagnostics. This fixed-body +// protocol has no discriminator, so provide a diagnostic name around the +// generated wire body. +struct ShardReplicaAnnouncementBody : ShardReplicaAnnouncement { + const char* kind() const { + return "SHARD_REPLICA_ANNOUNCEMENT"; + } +}; + +using ShardReplicaAnnouncementMsg = SignedProtocolMessage; diff --git a/cpp/tests/tests.cpp b/cpp/tests/tests.cpp index 6c2edb739..3ccb08a55 100644 --- a/cpp/tests/tests.cpp +++ b/cpp/tests/tests.cpp @@ -21,6 +21,7 @@ #include "Time.hpp" #include "CDCKey.hpp" #include "Random.hpp" +#include "ShardKey.hpp" #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" @@ -474,6 +475,72 @@ TEST_CASE("CBC MAC") { ); } +TEST_CASE("shard replica announcement protocol") { + AES128Key key; + expandKey(ShardKey, key); + + ShardReplicaAnnouncementMsg announcement; + announcement.id = 42; + announcement.body.shrid = ShardReplicaId(ShardId(17), ReplicaId(3)); + announcement.body.location = 2; + announcement.body.isLeader = true; + announcement.body.addrs[0].ip.data = {127, 0, 0, 1}; + announcement.body.addrs[0].port = 12001; + announcement.body.addrs[1].ip.data = {10, 20, 30, 40}; + announcement.body.addrs[1].port = 12002; + + std::array bytes{}; + BincodeBuf packBuf(bytes.data(), bytes.size()); + announcement.pack(packBuf, key); + CHECK(packBuf.len() == ShardReplicaAnnouncementMsg::STATIC_SIZE); + + ShardReplicaAnnouncementMsg decoded; + BincodeBuf unpackBuf(bytes.data(), packBuf.len()); + decoded.unpack(unpackBuf, key); + CHECK(decoded.id == announcement.id); + CHECK(decoded.body.shrid == announcement.body.shrid); + CHECK(decoded.body.location == announcement.body.location); + CHECK(decoded.body.isLeader == announcement.body.isLeader); + CHECK(decoded.body.addrs == announcement.body.addrs); + + SUBCASE("rejects an invalid MAC") { + bytes[ShardReplicaAnnouncementMsg::STATIC_SIZE - 1] ^= 1; + BincodeBuf buf(bytes.data(), ShardReplicaAnnouncementMsg::STATIC_SIZE); + ShardReplicaAnnouncementMsg invalid; + CHECK_THROWS_AS(invalid.unpack(buf, key), BincodeException); + } + + SUBCASE("rejects the wrong protocol") { + bytes[0] ^= 1; + BincodeBuf buf(bytes.data(), ShardReplicaAnnouncementMsg::STATIC_SIZE); + ShardReplicaAnnouncementMsg invalid; + CHECK_THROWS_AS(invalid.unpack(buf, key), BincodeException); + } + + SUBCASE("rejects a truncated message") { + BincodeBuf buf(bytes.data(), ShardReplicaAnnouncementMsg::STATIC_SIZE - 1); + ShardReplicaAnnouncementMsg invalid; + CHECK_THROWS_AS(invalid.unpack(buf, key), BincodeException); + } + + SUBCASE("rejects an invalid replica identity") { + ShardReplicaAnnouncementMsg invalidIdentity; + invalidIdentity.body.shrid.u16 = (uint16_t(ReplicaId::invalid().u8) << 8) | announcement.body.shrid.shardId().u8; + BincodeBuf invalidPackBuf(bytes.data(), bytes.size()); + invalidIdentity.pack(invalidPackBuf, key); + + BincodeBuf buf(bytes.data(), invalidPackBuf.len()); + ShardReplicaAnnouncementMsg invalid; + CHECK_THROWS_AS(invalid.unpack(buf, key), BincodeException); + } + + SUBCASE("rejects trailing bytes") { + BincodeBuf buf(bytes.data(), bytes.size()); + ShardReplicaAnnouncementMsg invalid; + CHECK_THROWS_AS(invalid.unpack(buf, key), BincodeException); + } +} + struct TempShardDB { std::string dbDir; Logger logger; diff --git a/go/bincodegen/bincodegen.go b/go/bincodegen/bincodegen.go index 94c29e9dd..29b77127a 100644 --- a/go/bincodegen/bincodegen.go +++ b/go/bincodegen/bincodegen.go @@ -2309,6 +2309,7 @@ func main() { reflect.TypeOf(msgs.BlockPolicy{}), reflect.TypeOf(msgs.SnapshotPolicy{}), reflect.TypeOf(msgs.FullShardInfo{}), + reflect.TypeOf(msgs.ShardReplicaAnnouncement{}), reflect.TypeOf(msgs.RegisterBlockServiceInfo{}), reflect.TypeOf(msgs.FullBlockServiceInfo{}), reflect.TypeOf(msgs.BlockServiceSpace{}), diff --git a/go/msgs/msgs.go b/go/msgs/msgs.go index ae00d1ed2..bd504f740 100644 --- a/go/msgs/msgs.go +++ b/go/msgs/msgs.go @@ -11,13 +11,14 @@ import ( "encoding/binary" "encoding/json" "fmt" - "github.com/XTXMarkets/ternfs/go/core/bincode" - "github.com/XTXMarkets/ternfs/go/core/parity" "io" "path" "strconv" "strings" "time" + + "github.com/XTXMarkets/ternfs/go/core/bincode" + "github.com/XTXMarkets/ternfs/go/core/parity" ) //go:generate go run ../bincodegen @@ -2349,6 +2350,14 @@ type FullShardInfo struct { LocationId Location } +// Sent directly between the replicas of a shard, at every location. +type ShardReplicaAnnouncement struct { + Shrid ShardReplicaId + Location Location + IsLeader bool + Addrs AddrsInfo +} + type AllShardsDEPRECATEDResp struct { Shards []FullShardInfo } diff --git a/go/msgs/msgs_bincode.go b/go/msgs/msgs_bincode.go index eab25fbab..2e2a79bf2 100644 --- a/go/msgs/msgs_bincode.go +++ b/go/msgs/msgs_bincode.go @@ -5113,6 +5113,38 @@ func (v *FullShardInfo) Unpack(r io.Reader) error { return nil } +func (v *ShardReplicaAnnouncement) Pack(w io.Writer) error { + if err := bincode.PackScalar(w, uint16(v.Shrid)); err != nil { + return err + } + if err := bincode.PackScalar(w, uint8(v.Location)); err != nil { + return err + } + if err := bincode.PackScalar(w, bool(v.IsLeader)); err != nil { + return err + } + if err := v.Addrs.Pack(w); err != nil { + return err + } + return nil +} + +func (v *ShardReplicaAnnouncement) Unpack(r io.Reader) error { + if err := bincode.UnpackScalar(r, (*uint16)(&v.Shrid)); err != nil { + return err + } + if err := bincode.UnpackScalar(r, (*uint8)(&v.Location)); err != nil { + return err + } + if err := bincode.UnpackScalar(r, (*bool)(&v.IsLeader)); err != nil { + return err + } + if err := v.Addrs.Unpack(r); err != nil { + return err + } + return nil +} + func (v *RegisterBlockServiceInfo) Pack(w io.Writer) error { if err := bincode.PackScalar(w, uint64(v.Id)); err != nil { return err From a6854deb6ecda6142f9c74c87eb97d8433a65da0 Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Tue, 13 Oct 2026 16:25:02 +0000 Subject: [PATCH 3/9] shard: send and receive replica announcements If the new shard flag -replica-announcements is set, then each replica sends an announcement every 100ms to the replicas it knows of at it's last location. Replicas configured to lead also send to the replicas they know of at other locations. The tracker keeps each peer's registry record and last announcement separately. An announcement is used for one minute after we receive it, with its receipt time as the peer's last-seen time. After that the registry record is used, with an unusable registry address filled in from the last announcement. Changes are compared against the last published snapshot, so an expiry that has not been published yet is not missed. At most one leader is published per remote location. Fresh announcements win over registry records, and within a source the most recent wins. --- cpp/shard/ReplicaTracker.cpp | 184 +++++++++++-- cpp/shard/ReplicaTracker.hpp | 45 +++- cpp/shard/Shard.cpp | 82 +++++- cpp/shard/Shard.hpp | 1 + cpp/shard/ternshard.cpp | 7 + cpp/tests/replicatrackertests.cpp | 431 +++++++++++++++++++++++++++++- 6 files changed, 704 insertions(+), 46 deletions(-) diff --git a/cpp/shard/ReplicaTracker.cpp b/cpp/shard/ReplicaTracker.cpp index 03f952064..80265bdb7 100644 --- a/cpp/shard/ReplicaTracker.cpp +++ b/cpp/shard/ReplicaTracker.cpp @@ -4,27 +4,64 @@ #include "ReplicaTracker.hpp" -ReplicaTracker::ReplicaTracker(ShardReplicaId self, uint8_t location, bool isLeader, const AddrsInfo& addrs) - : _self(self), +#include + +#include "Assert.hpp" + +static bool hasAddress(const AddrsInfo& addrs) { + return addrs[0].port != 0 || addrs[1].port != 0; +} + +bool ReplicaTracker::PeerState::hasFreshAnnouncement(TernTime now) const { + return announced.has_value() && now < announced->lastSeen + PEER_EXPIRY; +} + +ReplicaTracker::View ReplicaTracker::PeerState::current(TernTime now) const { + if (hasFreshAnnouncement(now) || !registry.has_value()) { + ALWAYS_ASSERT(announced.has_value()); + return *announced; + } + View view = *registry; + // Wiped registry ports must not discard the only address we know. Keep + // the registry's leadership and timestamp when falling back to it. + if (!hasAddress(view.addrs) && announced.has_value()) { + view.addrs = announced->addrs; + } + return view; +} + +ReplicaTracker::ReplicaTracker(Logger& logger, std::shared_ptr& xmon, ShardReplicaId self, uint8_t location, bool isLeader, const AddrsInfo& addrs) + : _env(logger, xmon, "replica_tracker"), + _self(self), _location(location), + _isLeader(isLeader), _localReplicas(std::make_shared()), - _remoteLeaders(std::make_shared()) + _remoteLeaders(std::make_shared()), + _announcementTargets(std::make_shared()) { _peers.emplace( ShardReplicaLocationKey(_self, _location), PeerState{ - .addrs = addrs, - .isLeader = isLeader, - .registryLastSeen = {}, + .registry = std::nullopt, + .announced = View{.addrs = addrs, .isLeader = isLeader, .lastSeen = {}}, }); - _publishLocked(); + _publishLocked(TernTime{}); } bool ReplicaTracker::_validReplicaId(ShardReplicaId id) { return (id.u16 >> 8) < LogsDB::REPLICA_COUNT; } -void ReplicaTracker::seedRegistry(const std::vector& replicas) { +bool ReplicaTracker::_publishedDiffers(uint8_t location, const View& before, const View& after) const { + if (before.addrs != after.addrs || before.isLeader != after.isLeader) { + return true; + } + // Remote leader timestamps affect leader selection and liveness. + const bool inRemoteLeaders = location != _location && before.isLeader; + return inRemoteLeaders && before.lastSeen != after.lastSeen; +} + +void ReplicaTracker::seedRegistry(const std::vector& replicas, TernTime now) { std::lock_guard lock(_mutex); bool changed = false; @@ -39,25 +76,98 @@ void ReplicaTracker::seedRegistry(const std::vector& replicas) { auto [it, inserted] = _peers.try_emplace( key, PeerState{ - .addrs = replica.addrs, - .isLeader = replica.isLeader, - .registryLastSeen = replica.lastSeen, + .registry = View{.addrs = replica.addrs, .isLeader = replica.isLeader, .lastSeen = replica.lastSeen}, + .announced = std::nullopt, }); if (inserted) { changed = true; continue; } - it->second.registryLastSeen = replica.lastSeen; - if (replica.addrs[0].port != 0 || replica.addrs[1].port != 0) { - it->second.addrs = replica.addrs; + // The registry's view is kept current whichever view we publish, so + // that a peer whose announcements go stale is published at whatever + // address the registry has learnt in the meantime. + auto& peer = it->second; + const View before = peer.current(_publishedAt); + if (!peer.registry.has_value()) { + peer.registry = View{.addrs = replica.addrs, .isLeader = replica.isLeader, .lastSeen = replica.lastSeen}; + changed = true; + } else { + if (hasAddress(replica.addrs)) { + // The registry wipes dynamic ports on restart; keep the last real address. + peer.registry->addrs = replica.addrs; + } + peer.registry->isLeader = replica.isLeader; + peer.registry->lastSeen = replica.lastSeen; } - it->second.isLeader = replica.isLeader; + changed = changed || _publishedDiffers(replica.locationId, before, peer.current(now)); + } + + if (changed) { + _publishLocked(now); + } +} + +void ReplicaTracker::recordAnnouncement(const IpPort& source, const ShardReplicaAnnouncement& announcement, TernTime now) { + if (!_validReplicaId(announcement.shrid)) { + LOG_DEBUG(_env, "Ignoring announcement from %s for invalid replica %s", source, announcement.shrid); + return; + } + if (announcement.shrid.shardId() != _self.shardId()) { + LOG_DEBUG(_env, "Ignoring announcement from %s for shard %s, we are shard %s", source, announcement.shrid.shardId(), _self.shardId()); + return; + } + if (announcement.shrid == _self && announcement.location == _location) { + LOG_DEBUG(_env, "Ignoring announcement from %s claiming to be us", source); + return; + } + if (!announcement.addrs.contains(source)) { + LOG_DEBUG(_env, "Ignoring announcement from %s for %s at location %s, not one of its addresses %s", source, announcement.shrid, (int)announcement.location, announcement.addrs); + return; + } + + std::lock_guard lock(_mutex); + bool changed = false; + const View announced{.addrs = announcement.addrs, .isLeader = announcement.isLeader, .lastSeen = now}; + const auto key = ShardReplicaLocationKey(announcement.shrid, announcement.location); + auto [it, inserted] = _peers.try_emplace(key, PeerState{ + .registry = std::nullopt, + .announced = announced, + }); + if (inserted) { changed = true; + } else { + auto& peer = it->second; + // Expiry may have changed the selected source before the expiry pass + // publishes it. Compare with the view that was actually published. + const View before = peer.current(_publishedAt); + peer.announced = announced; + changed = changed || _publishedDiffers(announcement.location, before, peer.current(now)); + } + if (changed || (announcement.location != _location && announcement.isLeader)) { + _publishLocked(now); + } +} + +void ReplicaTracker::expire(TernTime now) { + std::lock_guard lock(_mutex); + bool changed = false; + + // A peer whose announcements have gone stale since the snapshots were + // built, for example after a restart without -replica-announcements, is + // now published as the registry describes it. + for (const auto& [key, peer] : _peers) { + if (key.shardReplicaId() == _self && key.locationId() == _location) { + continue; + } + changed = changed || _publishedDiffers(key.locationId(), peer.current(_publishedAt), peer.current(now)); + if (key.locationId() != _location && peer.hasFreshAnnouncement(_publishedAt) != peer.hasFreshAnnouncement(now)) { + changed = true; + } } if (changed) { - _publishLocked(); + _publishLocked(now); } } @@ -71,6 +181,11 @@ ReplicaTracker::remoteLeaders() const { return _remoteLeaders.load(); } +std::shared_ptr +ReplicaTracker::announcementTargets() const { + return _announcementTargets.load(); +} + std::optional ReplicaTracker::peerState(ShardReplicaId id, uint8_t location) const { std::lock_guard lock(_mutex); @@ -81,23 +196,52 @@ ReplicaTracker::peerState(ShardReplicaId id, uint8_t location) const { return it->second; } -void ReplicaTracker::_publishLocked() { +void ReplicaTracker::_publishLocked(TernTime now) { + _publishedAt = now; auto local = std::make_shared(); auto remote = std::make_shared(); + auto targets = std::make_shared(); + + // Prefer fresh announcements, then registry records, then announcements + // from peers the registry has never described. Compare timestamps only + // within a source, so registry clock skew cannot override a fresh peer. + auto sourcePriority = [now](const PeerState& peer) { + return peer.hasFreshAnnouncement(now) ? 2 : peer.registry.has_value() ? 1 : 0; + }; for (const auto& [key, peer] : _peers) { const auto id = key.shardReplicaId(); const auto location = key.locationId(); + const bool self = id == _self && location == _location; + const View view = peer.current(now); + if (!self && hasAddress(view.addrs) && (location == _location || _isLeader)) { + targets->push_back(view.addrs); + } if (location == _location) { - (*local)[id.replicaId().u8] = peer.addrs; - } else if (peer.isLeader && peer.addrs[0].port != 0) { + (*local)[id.replicaId().u8] = view.addrs; + } else if (view.isLeader && view.addrs[0].port != 0) { // A leader without an address, which the registry reports after // wiping dynamic ports, cannot be waited for or replicated to. - remote->emplace_back(id, peer.isLeader, peer.addrs, peer.registryLastSeen, location); + auto leader = std::find_if(remote->begin(), remote->end(), [location](const FullShardInfo& info) { + return info.locationId == location; + }); + if (leader == remote->end()) { + remote->emplace_back(id, true, view.addrs, view.lastSeen, location); + continue; + } + const auto& previous = _peers.at(ShardReplicaLocationKey(leader->id, location)); + const int priority = sourcePriority(peer); + const int previousPriority = sourcePriority(previous); + if (priority > previousPriority || + (priority == previousPriority && + (view.lastSeen > leader->lastSeen || (view.lastSeen == leader->lastSeen && id.u16 < leader->id.u16)))) { + *leader = FullShardInfo(id, true, view.addrs, view.lastSeen, location); + } } } _localReplicas.store(std::move(local)); _remoteLeaders.store(std::move(remote)); + _announcementTargets.store(std::move(targets)); } diff --git a/cpp/shard/ReplicaTracker.hpp b/cpp/shard/ReplicaTracker.hpp index 000ef6176..71eeb22a1 100644 --- a/cpp/shard/ReplicaTracker.hpp +++ b/cpp/shard/ReplicaTracker.hpp @@ -12,42 +12,65 @@ #include #include +#include "Env.hpp" #include "LogsDB.hpp" #include "MsgsGen.hpp" #include "Time.hpp" -// Tracks the replicas of our shard, at every location, as the registry -// describes them. It publishes the addresses of the replicas at our location -// and the leaders at other locations as snapshots that the receive, writer -// and metrics threads read without locking. +// Keeps registry records and peer announcements separately. Published snapshots +// use fresh announcements in preference to registry records and contain at most +// one leader per remote location. class ReplicaTracker { public: - struct PeerState { + // How long a peer's announcements stay authoritative after we last heard one. + static constexpr Duration PEER_EXPIRY = 1_mins; + + // One source's description of a peer. + struct View { AddrsInfo addrs; - bool isLeader; - TernTime registryLastSeen; // when the registry last heard from the peer + bool isLeader = false; + // Registry registration time, or local receipt time for an announcement. + TernTime lastSeen; + }; + + struct PeerState { + std::optional registry; // once a registry poll has described the peer + std::optional announced; // once the peer has announced itself + + bool hasFreshAnnouncement(TernTime now) const; + View current(TernTime now) const; }; using LocalReplicas = std::array; using RemoteLeaders = std::vector; + using AnnouncementTargets = std::vector; - ReplicaTracker(ShardReplicaId self, uint8_t location, bool isLeader, const AddrsInfo& addrs); + ReplicaTracker(Logger& logger, std::shared_ptr& xmon, ShardReplicaId self, uint8_t location, bool isLeader, const AddrsInfo& addrs); - // Takes addresses, leadership and last-seen times from the registry. - void seedRegistry(const std::vector& replicas); + void seedRegistry(const std::vector& replicas, TernTime now); + void recordAnnouncement(const IpPort& source, const ShardReplicaAnnouncement& announcement, TernTime now); + void expire(TernTime now); std::shared_ptr localReplicas() const; std::shared_ptr remoteLeaders() const; + std::shared_ptr announcementTargets() const; std::optional peerState(ShardReplicaId id, uint8_t location) const; private: + Env _env; const ShardReplicaId _self; const uint8_t _location; + const bool _isLeader; mutable std::mutex _mutex; std::unordered_map _peers; std::atomic> _localReplicas; std::atomic> _remoteLeaders; + std::atomic> _announcementTargets; + TernTime _publishedAt; // the `now` the snapshots were last built for static bool _validReplicaId(ShardReplicaId id); - void _publishLocked(); + // Whether the snapshots would differ for a peer at `location` described by + // `before` rather than `after`. + bool _publishedDiffers(uint8_t location, const View& before, const View& after) const; + void _publishLocked(TernTime now); }; diff --git a/cpp/shard/Shard.cpp b/cpp/shard/Shard.cpp index d73ce839e..43d5a2e36 100644 --- a/cpp/shard/Shard.cpp +++ b/cpp/shard/Shard.cpp @@ -131,7 +131,6 @@ struct ShardShared { RegistryClient registryClient; - // the replicas of our shard at every location, as the registry describes them ReplicaTracker replicaTracker; ShardShared() = delete; @@ -167,7 +166,7 @@ struct ShardShared { isInitiated(false), isBlockServiceCacheInitiated(false), registryClient(logger, xmon, options_.registryClientOptions.host, options_.registryClientOptions.port, options_.registryClientOptions.timeout), - replicaTracker(options_.shrid(), options_.logsDBOptions.location, options_.isLeader(), socks[0].addr()) + replicaTracker(logger, xmon, options_.shrid(), options_.logsDBOptions.location, options_.isLeader(), socks[0].addr()) { for (uint16_t i = 0; i < options_.numReaders; ++i) { readerRequestsQueues.emplace_back(std::make_unique>(READER_QUEUE_SIZE)); @@ -309,14 +308,15 @@ static void packCheckPointedShardResponse( LOG_DEBUG(env, "will send response for req id %s kind %s to %s", msg.id, reqKind, req.clientAddr); } -static constexpr std::array ShardProtocols = { +static constexpr std::array ShardProtocols = { SHARD_REQ_PROTOCOL_VERSION, SHARD_RESP_PROTOCOL_VERSION, CDC_TO_SHARD_REQ_PROTOCOL_VERSION, LOG_REQ_PROTOCOL_VERSION, LOG_RESP_PROTOCOL_VERSION, PROXY_SHARD_RESP_PROTOCOL_VERSION, - PROXY_SHARD_REQ_PROTOCOL_VERSION}; + PROXY_SHARD_REQ_PROTOCOL_VERSION, + SHARD_REPLICA_ANNOUNCEMENT_PROTOCOL_VERSION}; using ShardChannel = MultiplexedChannel; @@ -367,6 +367,22 @@ struct ShardServer : Loop { virtual ~ShardServer() = default; private: + void _handleReplicaAnnouncement(UDPMessage& msg) { + ShardReplicaAnnouncementMsg announcement; + try { + announcement.unpack(msg.buf, _expandedShardKey); + } catch (const BincodeException& err) { + LOG_ERROR(_env, "Could not parse shard replica announcement from %s: %s", msg.clientAddr, err.what()); + return; + } + + if (!_shared.options.replicaAnnouncements) { + return; + } + + _shared.replicaTracker.recordAnnouncement(msg.clientAddr, announcement.body, ternNow()); + } + void _handleLogsDBResponse(UDPMessage& msg) { LOG_DEBUG(_env, "received LogsDBResponse from %s", msg.clientAddr); @@ -592,7 +608,8 @@ struct ShardServer : Loop { public: virtual void step() override { - if (unlikely(!_shared.isInitiated.load(std::memory_order_acquire) || !_shared.isBlockServiceCacheInitiated.load(std::memory_order_acquire))) { + const bool ready = _shared.isInitiated.load(std::memory_order_acquire) && _shared.isBlockServiceCacheInitiated.load(std::memory_order_acquire); + if (unlikely(!ready && !_shared.options.replicaAnnouncements)) { (100_ms).sleepRetry(); return; } @@ -610,6 +627,14 @@ struct ShardServer : Loop { return; } + for (auto& msg : _channel->protocolMessages(SHARD_REPLICA_ANNOUNCEMENT_PROTOCOL_VERSION)) { + _handleReplicaAnnouncement(msg); + } + + if (unlikely(!ready)) { + return; + } + for (auto& msg : _channel->protocolMessages(LOG_RESP_PROTOCOL_VERSION)) { _handleLogsDBResponse(msg); } @@ -693,6 +718,47 @@ struct ShardServer : Loop { } }; +struct ShardReplicaAnnouncer : Loop { +private: + ShardShared& _shared; + AES128Key _expandedShardKey; + UDPSender _sender; + +public: + ShardReplicaAnnouncer(Logger& logger, std::shared_ptr& xmon, ShardShared& shared) : + Loop(logger, xmon, "announcer"), + _shared(shared) + { + expandKey(ShardKey, _expandedShardKey); + } + + virtual void step() override { + _shared.replicaTracker.expire(ternNow()); + + ShardReplicaAnnouncementMsg announcement; + announcement.body.shrid = _shared.options.shrid(); + announcement.body.location = _shared.options.logsDBOptions.location; + announcement.body.isLeader = _shared.options.isLeader() && (_shared.options.logsDBOptions.noReplication || _shared.isInitiated.load(std::memory_order_acquire)); + announcement.body.addrs = _shared.sock().addr(); + + auto targets = _shared.replicaTracker.announcementTargets(); + for (const auto& target : *targets) { + _sender.prepareOutgoingMessage( + _env, + _shared.sock().addr(), + target, + [&announcement, this](BincodeBuf& buf) { + announcement.pack(buf, _expandedShardKey); + }); + } + _sender.sendMessages(_env, _shared.sock()); + + if (Loop::sleep(100_ms) < 0 && errno != EINTR) { + throw SYSCALL_EXCEPTION("sleep"); + } + } +}; + struct InFlightRequestKey { uint64_t requestId; uint64_t portIp; @@ -2212,7 +2278,7 @@ struct ShardRegisterer : PeriodicLoop { return false; } - _shared.replicaTracker.seedRegistry(allReplicas); + _shared.replicaTracker.seedRegistry(allReplicas, ternNow()); LOG_DEBUG(_env, "Leaders at other locations now %s", *_shared.getLeadersAtOtherLocations()); std::array localReplicas; @@ -2624,6 +2690,7 @@ void runShard(ShardOptions& options) { LOG_INFO(env, " registryPort = %s", options.registryClientOptions.port); LOG_INFO(env, " ownAddres = %s", options.serverOptions.addrs); LOG_INFO(env, " simulateOutgoingPacketDrop = %s", options.serverOptions.simulateOutgoingPacketDrop); + LOG_INFO(env, " replicaAnnouncements = %s", options.replicaAnnouncements); LOG_INFO(env, " syslog = %s", (int)options.logOptions.syslog); LOG_INFO(env, "Using LogsDB with options:"); LOG_INFO(env, " noReplication = '%s'", (int)options.logsDBOptions.noReplication); @@ -2680,6 +2747,9 @@ void runShard(ShardOptions& options) { ShardShared shared(options, sharedDB, blockServicesCache, shardDB, logsDB, UDPSocketPair(env, options.serverOptions.addrs), logger, xmon); threads.emplace_back(LoopThread::Spawn(std::make_unique(logger, xmon, shared))); + if (options.replicaAnnouncements) { + threads.emplace_back(LoopThread::Spawn(std::make_unique(logger, xmon, shared))); + } for (uint16_t i = 0; i < options.numReaders; ++i) { threads.emplace_back(LoopThread::Spawn(std::make_unique(logger, xmon, shared, *shared.readerRequestsQueues[i]))); } diff --git a/cpp/shard/Shard.hpp b/cpp/shard/Shard.hpp index 80331f330..ab4350eee 100644 --- a/cpp/shard/Shard.hpp +++ b/cpp/shard/Shard.hpp @@ -31,6 +31,7 @@ struct ShardOptions { uint64_t hddDriveThroughput = 35'000'000; // bytes/sec per HDD drive uint64_t flashDriveThroughput = 350'000'000; // bytes/sec per flash drive uint64_t minSpaceRequiredForWrite = uint64_t(MAXIMUM_SPAN_SIZE); // min available bytes for a block service to be considered writable + bool replicaAnnouncements = false; // implicit options bool isLeader() const { return !logsDBOptions.avoidBeingLeader; } diff --git a/cpp/shard/ternshard.cpp b/cpp/shard/ternshard.cpp index c21e24903..4468aba6c 100644 --- a/cpp/shard/ternshard.cpp +++ b/cpp/shard/ternshard.cpp @@ -40,6 +40,11 @@ static bool parseShardOptions(CommandLineArgs& args, ShardOptions& options) { } continue; } + if (arg == "-replica-announcements") { + args.next(); + options.replicaAnnouncements = true; + continue; + } if (arg == "-region-staleness-threshold") { options.regionStalenessThreshold = parseDuration(args.next()); continue; @@ -98,6 +103,8 @@ static void printShardOptionsUsage() { fprintf(stderr, " How often the primary leader emits a heartbeat log entry while idle. 0 disables. Default: 1s\n"); fprintf(stderr, " -num-readers\n"); fprintf(stderr, " Number of reader threads. Default: 1\n"); + fprintf(stderr, " -replica-announcements\n"); + fprintf(stderr, " Send and use direct shard replica announcements. Default: false\n"); fprintf(stderr, " -shard\n"); fprintf(stderr, " Which shard we are running as [0-255]\n"); fprintf(stderr, " -transient-deadline-interval\n"); diff --git a/cpp/tests/replicatrackertests.cpp b/cpp/tests/replicatrackertests.cpp index 14db1192d..623520592 100644 --- a/cpp/tests/replicatrackertests.cpp +++ b/cpp/tests/replicatrackertests.cpp @@ -2,11 +2,16 @@ // // SPDX-License-Identifier: GPL-2.0-or-later +#include + #include "ReplicaTracker.hpp" #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" +static Logger logger(LogLevel::LOG_ERROR, STDERR_FILENO, false, false); +static std::shared_ptr xmon; + static IpPort address(uint8_t lastOctet, uint16_t port) { IpPort result; result.ip.data = {127, 0, 0, lastOctet}; @@ -20,20 +25,24 @@ static AddrsInfo addresses(uint8_t lastOctet, uint16_t port) { return result; } +static ShardReplicaAnnouncement announcement(ShardReplicaId id, uint8_t location, bool isLeader, const AddrsInfo& addrs) { + return ShardReplicaAnnouncement(id, location, isLeader, addrs); +} + TEST_CASE("registry seeds local replicas and remote leaders") { const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); - ReplicaTracker tracker(self, 2, true, addresses(1, 10001)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); std::vector replicas{ FullShardInfo(self, true, addresses(1, 10001), 0, 2), FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(1)), false, addresses(2, 10002), 0, 2), - FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(0)), true, addresses(3, 10003), TernTime(1'000), 3), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(0)), true, addresses(3, 10003), 0, 3), FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(2)), false, addresses(4, 10004), 0, 3), FullShardInfo(ShardReplicaId(ShardId(8), ReplicaId(1)), true, addresses(5, 10005), 0, 2), // A leader at another location whose address the registry has wiped. FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(0)), true, AddrsInfo(), 0, 4), }; - tracker.seedRegistry(replicas); + tracker.seedRegistry(replicas, TernTime(10)); auto local = tracker.localReplicas(); CHECK((*local)[0] == addresses(1, 10001)); @@ -46,27 +55,165 @@ TEST_CASE("registry seeds local replicas and remote leaders") { CHECK(remote->at(0).id == ShardReplicaId(ShardId(7), ReplicaId(0))); CHECK(remote->at(0).locationId == 3); CHECK(remote->at(0).addrs == addresses(3, 10003)); - CHECK(remote->at(0).lastSeen == TernTime(1'000)); + + // A leader announces to every replica it knows of with an address. + CHECK(tracker.announcementTargets()->size() == 3); +} + +TEST_CASE("followers announce to their own location only") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(1)); + ReplicaTracker tracker(logger, xmon, self, 2, false, addresses(1, 10001)); + + std::vector replicas{ + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(0)), true, addresses(2, 10002), 0, 2), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(2)), false, addresses(3, 10003), 0, 2), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(0)), true, addresses(4, 10004), 0, 3), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(1)), false, addresses(5, 10005), 0, 3), + }; + tracker.seedRegistry(replicas, TernTime(10)); + + auto targets = tracker.announcementTargets(); + REQUIRE(targets->size() == 2); + CHECK(targets->at(0) != addresses(4, 10004)); + CHECK(targets->at(1) != addresses(4, 10004)); + // Only leaders talk across locations, but the other location's leader is + // still known for routing. + CHECK(tracker.remoteLeaders()->size() == 1); +} + +TEST_CASE("a fresh leader announcement takes precedence over stale registry polls") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(4)); + ReplicaTracker tracker(logger, xmon, self, 0, true, addresses(1, 10001)); + + // The registry says replica 4 leads location 1. + std::vector registry{ + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(4)), true, addresses(2, 10002), TernTime(5), 1), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(3)), false, addresses(3, 10003), TernTime(5), 1), + }; + tracker.seedRegistry(registry, TernTime(10)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == ShardReplicaId(ShardId(7), ReplicaId(4))); + + // Replica 3 announces that it leads now: exactly one leader for location 1. + auto newLeader = announcement(ShardReplicaId(ShardId(7), ReplicaId(3)), 1, true, addresses(3, 10003)); + tracker.recordAnnouncement(address(3, 10003), newLeader, TernTime(20)); + auto remote = tracker.remoteLeaders(); + REQUIRE(remote->size() == 1); + CHECK(remote->at(0).id == ShardReplicaId(ShardId(7), ReplicaId(3))); + CHECK(tracker.peerState(ShardReplicaId(ShardId(7), ReplicaId(4)), 1)->registry->isLeader); + + tracker.seedRegistry(registry, TernTime(30)); + remote = tracker.remoteLeaders(); + REQUIRE(remote->size() == 1); + CHECK(remote->at(0).id == newLeader.shrid); + + tracker.expire(TernTime(20) + ReplicaTracker::PEER_EXPIRY); + remote = tracker.remoteLeaders(); + REQUIRE(remote->size() == 1); + CHECK(remote->at(0).id == registry[0].id); +} + +TEST_CASE("the most recently heard leader wins without changing other peers' records") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(4)); + ReplicaTracker tracker(logger, xmon, self, 0, true, addresses(1, 10001)); + auto first = announcement(ShardReplicaId(ShardId(7), ReplicaId(4)), 1, true, addresses(2, 10002)); + auto second = announcement(ShardReplicaId(ShardId(7), ReplicaId(3)), 1, true, addresses(3, 10003)); + + tracker.recordAnnouncement(address(2, 10002), first, TernTime(10)); + tracker.recordAnnouncement(address(3, 10003), second, TernTime(20)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == second.shrid); + CHECK(tracker.peerState(first.shrid, 1)->announced->isLeader); + + // A delayed packet can temporarily change the winner; the next announcement + // corrects it. Neither packet creates a second published leader. + tracker.recordAnnouncement(address(2, 10002), first, TernTime(30)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == first.shrid); + tracker.recordAnnouncement(address(3, 10003), second, TernTime(40)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == second.shrid); + + second.isLeader = false; + tracker.recordAnnouncement(address(3, 10003), second, TernTime(50)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == first.shrid); +} + +TEST_CASE("leader selection notices expiry even when a peer's registry and announcement agree") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(4)); + ReplicaTracker tracker(logger, xmon, self, 0, true, addresses(1, 10001)); + auto leader = announcement(ShardReplicaId(ShardId(7), ReplicaId(4)), 1, true, addresses(2, 10002)); + std::vector registry{ + FullShardInfo(leader.shrid, true, leader.addrs, TernTime(10), 1), + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(3)), true, addresses(3, 10003), TernTime(20), 1), + }; + tracker.recordAnnouncement(address(2, 10002), leader, TernTime(10)); + tracker.seedRegistry(registry, TernTime(30)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == leader.shrid); + + tracker.expire(TernTime(10) + ReplicaTracker::PEER_EXPIRY); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == registry[1].id); +} + +TEST_CASE("equal leader timestamps have a stable winner") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(4)); + ReplicaTracker tracker(logger, xmon, self, 0, true, addresses(1, 10001)); + auto first = announcement(ShardReplicaId(ShardId(7), ReplicaId(4)), 1, true, addresses(2, 10002)); + auto second = announcement(ShardReplicaId(ShardId(7), ReplicaId(3)), 1, true, addresses(3, 10003)); + tracker.recordAnnouncement(address(2, 10002), first, TernTime(10)); + tracker.recordAnnouncement(address(3, 10003), second, TernTime(10)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == second.shrid); + tracker.recordAnnouncement(address(2, 10002), first, TernTime(10)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).id == second.shrid); +} + +TEST_CASE("announcements that change nothing do not republish") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + + auto body = announcement(peer, 2, false, addresses(2, 10002)); + tracker.recordAnnouncement(address(2, 10002), body, TernTime(20)); + auto local = tracker.localReplicas(); + auto targets = tracker.announcementTargets(); + + // Same announcement again: the peer's last-heard time moves, the + // published snapshots are the same objects. + tracker.recordAnnouncement(address(2, 10002), body, TernTime(21)); + CHECK(tracker.peerState(peer, 2)->announced->lastSeen == TernTime(21)); + CHECK(tracker.localReplicas() == local); + CHECK(tracker.announcementTargets() == targets); + + // A new address republishes. + auto moved = announcement(peer, 2, false, addresses(3, 10003)); + tracker.recordAnnouncement(address(3, 10003), moved, TernTime(22)); + CHECK(tracker.localReplicas() != local); + CHECK((*tracker.localReplicas())[1] == moved.addrs); } TEST_CASE("later registry polls update peers") { const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); const auto remoteLeader = ShardReplicaId(ShardId(7), ReplicaId(4)); - ReplicaTracker tracker(self, 2, true, addresses(1, 10001)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); std::vector registry{ FullShardInfo(peer, false, addresses(2, 10002), TernTime(1'000), 2), FullShardInfo(remoteLeader, true, addresses(3, 10003), TernTime(1'000), 3), }; - tracker.seedRegistry(registry); + tracker.seedRegistry(registry, TernTime(10)); CHECK((*tracker.localReplicas())[1] == addresses(2, 10002)); REQUIRE(tracker.remoteLeaders()->size() == 1); // The peer moved host, the remote leader was heard from again. registry[0].addrs = addresses(3, 10003); registry[1].lastSeen = TernTime(2'000); - tracker.seedRegistry(registry); + tracker.seedRegistry(registry, TernTime(20)); CHECK((*tracker.localReplicas())[1] == addresses(3, 10003)); CHECK(tracker.remoteLeaders()->at(0).lastSeen == TernTime(2'000)); @@ -74,10 +221,276 @@ TEST_CASE("later registry polls update peers") { // leader list empties, the peer keeps its last address. registry[0].addrs = AddrsInfo(); registry[1].isLeader = false; - tracker.seedRegistry(registry); + tracker.seedRegistry(registry, TernTime(30)); CHECK((*tracker.localReplicas())[1] == addresses(3, 10003)); CHECK(tracker.remoteLeaders()->empty()); auto state = tracker.peerState(peer, 2); REQUIRE(state.has_value()); - CHECK(state->registryLastSeen == TernTime(1'000)); + CHECK(state->registry->lastSeen == TernTime(1'000)); +} + +TEST_CASE("direct announcements validate identity and source") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + + auto body = announcement(peer, 2, false, addresses(2, 10002)); + tracker.recordAnnouncement(address(2, 10002), body, TernTime(20)); + CHECK((*tracker.localReplicas())[1] == body.addrs); + + // Not sent from one of the announced addresses. + auto mismatched = announcement(ShardReplicaId(ShardId(7), ReplicaId(2)), 2, false, addresses(3, 10003)); + tracker.recordAnnouncement(address(9, 10009), mismatched, TernTime(21)); + CHECK(!tracker.peerState(mismatched.shrid, mismatched.location).has_value()); + + // Another shard. + auto wrongShard = announcement(ShardReplicaId(ShardId(8), ReplicaId(1)), 2, false, addresses(4, 10004)); + tracker.recordAnnouncement(address(4, 10004), wrongShard, TernTime(22)); + CHECK(!tracker.peerState(wrongShard.shrid, wrongShard.location).has_value()); + + // An invalid replica id. + auto invalid = body; + invalid.shrid.u16 = (uint16_t(LogsDB::REPLICA_COUNT) << 8) | 7; + tracker.recordAnnouncement(address(2, 10002), invalid, TernTime(23)); + CHECK(!tracker.peerState(invalid.shrid, invalid.location).has_value()); + + // Ourselves: our own entry is never updated from the wire. + auto selfBody = announcement(self, 2, true, addresses(5, 10005)); + tracker.recordAnnouncement(address(5, 10005), selfBody, TernTime(24)); + CHECK(tracker.peerState(self, 2)->announced->addrs == addresses(1, 10001)); + CHECK((*tracker.localReplicas())[0] == addresses(1, 10001)); +} + +TEST_CASE("direct announcements replace addresses and leadership") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + + std::vector seed{ + FullShardInfo(peer, false, addresses(2, 10002), 0, 2), + }; + tracker.seedRegistry(seed, TernTime(10)); + + auto first = announcement(peer, 2, false, addresses(3, 10003)); + tracker.recordAnnouncement(address(3, 10003), first, TernTime(20)); + auto state = tracker.peerState(peer, 2); + REQUIRE(state.has_value()); + CHECK(state->current(TernTime(20)).addrs == first.addrs); + CHECK(!state->current(TernTime(20)).isLeader); + CHECK(state->announced->lastSeen == TernTime(20)); + CHECK(state->current(TernTime(20)).lastSeen == TernTime(20)); + + auto restarted = announcement(peer, 2, true, addresses(4, 10004)); + tracker.recordAnnouncement(address(4, 10004), restarted, TernTime(30)); + state = tracker.peerState(peer, 2); + REQUIRE(state.has_value()); + CHECK(state->current(TernTime(30)).addrs == restarted.addrs); + CHECK(state->current(TernTime(30)).isLeader); + CHECK(state->announced->lastSeen == TernTime(30)); + + // Registry polling cannot roll a directly announced address back. + tracker.seedRegistry(seed, TernTime(40)); + CHECK((*tracker.localReplicas())[1] == restarted.addrs); +} + +TEST_CASE("quiet peers fall back to the registry") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + + auto body = announcement(peer, 2, false, addresses(2, 10002)); + const TernTime heardAt(1'000'000'000); + tracker.recordAnnouncement(address(2, 10002), body, heardAt); + + tracker.expire(heardAt + ReplicaTracker::PEER_EXPIRY - 1_ns); + auto state = tracker.peerState(peer, 2); + REQUIRE(state.has_value()); + CHECK(state->current(heardAt + ReplicaTracker::PEER_EXPIRY - 1_ns).lastSeen == heardAt); + + // Quiet for PEER_EXPIRY: the registry would describe the peer now, but it + // never has, so the peer stays published at its last announced address. + tracker.expire(heardAt + ReplicaTracker::PEER_EXPIRY); + CHECK((*tracker.localReplicas())[1] == body.addrs); + state = tracker.peerState(peer, 2); + REQUIRE(state.has_value()); + CHECK(!state->registry.has_value()); + CHECK(state->current(heardAt + ReplicaTracker::PEER_EXPIRY).lastSeen == heardAt); + REQUIRE(tracker.announcementTargets()->size() == 1); + + // Restarted without announcements at a new address: the registry knows. + std::vector registry{ + FullShardInfo(peer, false, addresses(3, 10003), TernTime(5), 2), + }; + tracker.seedRegistry(registry, heardAt + ReplicaTracker::PEER_EXPIRY); + CHECK((*tracker.localReplicas())[1] == addresses(3, 10003)); + CHECK(tracker.announcementTargets()->at(0) == addresses(3, 10003)); + + // Announcing again makes it authoritative again. + auto restarted = announcement(peer, 2, false, addresses(4, 10004)); + tracker.recordAnnouncement( + address(4, 10004), + restarted, + heardAt + ReplicaTracker::PEER_EXPIRY + 1_ns); + CHECK((*tracker.localReplicas())[1] == restarted.addrs); + tracker.seedRegistry(registry, heardAt + ReplicaTracker::PEER_EXPIRY + 2_ns); + CHECK((*tracker.localReplicas())[1] == restarted.addrs); +} + +TEST_CASE("a quiet peer is published at the address the registry learnt meanwhile") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + + std::vector registry{ + FullShardInfo(peer, false, addresses(2, 10002), TernTime(5), 2), + }; + tracker.seedRegistry(registry, TernTime(10)); + auto body = announcement(peer, 2, false, addresses(2, 10002)); + const TernTime heardAt(1'000'000'000); + tracker.recordAnnouncement(address(2, 10002), body, heardAt); + + // The peer restarts at a new address without announcing, and registers + // it. The poll that reports it arrives while its last announcement is + // still fresh: we keep publishing what it announced, but remember what + // the registry said. + registry[0].addrs = addresses(3, 10003); + registry[0].lastSeen = TernTime(6); + tracker.seedRegistry(registry, heardAt + 1_ns); + CHECK((*tracker.localReplicas())[1] == addresses(2, 10002)); + CHECK(tracker.peerState(peer, 2)->registry->addrs == addresses(3, 10003)); + + // Once it has been quiet for PEER_EXPIRY, the registry's address is + // published at once, without waiting for another poll. + tracker.expire(heardAt + ReplicaTracker::PEER_EXPIRY); + CHECK((*tracker.localReplicas())[1] == addresses(3, 10003)); + CHECK(tracker.announcementTargets()->at(0) == addresses(3, 10003)); +} + +TEST_CASE("announcements after expiry update the published local address") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + const TernTime heardAt(1'000'000'000); + auto body = announcement(peer, 2, false, addresses(2, 10002)); + tracker.recordAnnouncement(body.addrs[0], body, heardAt); + + std::vector registry{ + FullShardInfo(peer, false, addresses(3, 10003), heardAt + 1_sec, 2), + }; + tracker.seedRegistry(registry, heardAt + 1_sec); + REQUIRE(tracker.localReplicas()->at(1) == body.addrs); + + const TernTime resumedAt = heardAt + ReplicaTracker::PEER_EXPIRY; + SUBCASE("announcement arrives before the expiry pass") {} + SUBCASE("announcement arrives after the expiry pass") { + tracker.expire(resumedAt); + } + SUBCASE("registry poll arrives before the expiry pass") { + tracker.seedRegistry(registry, resumedAt); + CHECK(tracker.localReplicas()->at(1) == registry[0].addrs); + } + + body.addrs = registry[0].addrs; + tracker.recordAnnouncement(body.addrs[0], body, resumedAt); + CHECK(tracker.localReplicas()->at(1) == body.addrs); + REQUIRE(tracker.announcementTargets()->size() == 1); + CHECK(tracker.announcementTargets()->at(0) == body.addrs); + + registry[0].lastSeen = resumedAt + 1_sec; + tracker.seedRegistry(registry, resumedAt + 1_sec); + tracker.recordAnnouncement(body.addrs[0], body, resumedAt + 1_sec); + tracker.expire(resumedAt + 1_sec); + CHECK(tracker.localReplicas()->at(1) == body.addrs); +} + +TEST_CASE("wiped registry ports preserve the last announced address") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + const TernTime heardAt(1'000'000'000); + auto body = announcement(peer, 2, false, addresses(2, 10002)); + std::vector registry{ + FullShardInfo(peer, false, addresses(2, 0), heardAt, 2), + }; + SUBCASE("registry record arrives first") { + tracker.seedRegistry(registry, heardAt); + tracker.recordAnnouncement(body.addrs[0], body, heardAt + 1_sec); + } + SUBCASE("announcement arrives first") { + tracker.recordAnnouncement(body.addrs[0], body, heardAt); + tracker.seedRegistry(registry, heardAt + 1_sec); + } + + const TernTime expiredAt = heardAt + 1_sec + ReplicaTracker::PEER_EXPIRY; + tracker.expire(expiredAt); + CHECK(tracker.localReplicas()->at(1) == body.addrs); + REQUIRE(tracker.announcementTargets()->size() == 1); + CHECK(tracker.announcementTargets()->at(0) == body.addrs); + CHECK(tracker.peerState(peer, 2)->registry->addrs == registry[0].addrs); + + // A later announcement supplies the new fallback address, even if the + // registry still has no usable address after it expires. + body.addrs = addresses(3, 10003); + tracker.recordAnnouncement(body.addrs[0], body, expiredAt); + registry[0].lastSeen = expiredAt + ReplicaTracker::PEER_EXPIRY; + tracker.seedRegistry(registry, registry[0].lastSeen); + tracker.expire(registry[0].lastSeen); + CHECK(tracker.localReplicas()->at(1) == body.addrs); + REQUIRE(tracker.announcementTargets()->size() == 1); + CHECK(tracker.announcementTargets()->at(0) == body.addrs); + + // A usable registry address still takes precedence over a stale announcement. + registry[0].addrs = addresses(4, 10004); + tracker.seedRegistry(registry, registry[0].lastSeen + 1_ns); + CHECK(tracker.localReplicas()->at(1) == registry[0].addrs); + CHECK(tracker.announcementTargets()->at(0) == registry[0].addrs); +} + +TEST_CASE("an expired announcement supplies only the missing registry address") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto peer = ShardReplicaId(ShardId(7), ReplicaId(1)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + const TernTime heardAt(1'000'000'000); + auto body = announcement(peer, 3, true, addresses(2, 10002)); + tracker.recordAnnouncement(body.addrs[0], body, heardAt); + std::vector registry{ + FullShardInfo(peer, false, addresses(2, 0), heardAt + 1_sec, 3), + }; + tracker.seedRegistry(registry, heardAt + 1_sec); + tracker.expire(heardAt + ReplicaTracker::PEER_EXPIRY); + CHECK(tracker.remoteLeaders()->empty()); + REQUIRE(tracker.announcementTargets()->size() == 1); + CHECK(tracker.announcementTargets()->at(0) == body.addrs); + + registry[0].isLeader = true; + tracker.seedRegistry(registry, heardAt + ReplicaTracker::PEER_EXPIRY + 1_ns); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).addrs == body.addrs); + CHECK(tracker.remoteLeaders()->at(0).lastSeen == registry[0].lastSeen); +} + +TEST_CASE("peers known only from the registry never expire") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(0)); + const auto localPeer = ShardReplicaId(ShardId(7), ReplicaId(1)); + const auto remoteLeader = ShardReplicaId(ShardId(7), ReplicaId(0)); + ReplicaTracker tracker(logger, xmon, self, 2, true, addresses(1, 10001)); + + // For example replicas running without -replica-announcements. + std::vector registry{ + FullShardInfo(localPeer, false, addresses(2, 10002), TernTime(1'000), 2), + FullShardInfo(remoteLeader, true, addresses(3, 10003), TernTime(2'000), 3), + }; + tracker.seedRegistry(registry, TernTime(1'000)); + + tracker.expire(TernTime(1'000) + ReplicaTracker::PEER_EXPIRY * 10); + CHECK((*tracker.localReplicas())[1] == addresses(2, 10002)); + auto remote = tracker.remoteLeaders(); + REQUIRE(remote->size() == 1); + CHECK(remote->at(0).addrs == addresses(3, 10003)); + // Liveness of a peer that doesn't announce is what the registry last saw. + CHECK(remote->at(0).lastSeen == TernTime(2'000)); + + registry[1].lastSeen = TernTime(3'000); + tracker.seedRegistry(registry, TernTime(3'000)); + CHECK(tracker.remoteLeaders()->at(0).lastSeen == TernTime(3'000)); } From 52c395b75b81592e2935e4a59acd0d9ff9be23e5 Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Wed, 2 Sep 2026 09:59:58 +0000 Subject: [PATCH 4/9] shard: allow startup before all replicas are registered Unless it runs with -no-replication, a replica that has not been initiated will not finish starting until the registry has addresses for all five replicas at its location. On an initial start it also asks the registry to hold the fetch until all five are known. One missing replica holds up the others. With replica announcements enabled, drop both requirements. A replica still has to register itself, fetch whatever the registry knows, and find its own address there. A replica that registers later is found through announcements: it gets our address from the registry and announces itself to us. Enable announcements in ternrun and terntests. terntests now starts each shard's followers before its leader. A follower's first fetch can then run before the leader has registered, in which case the follower learns about the leader from the leader's announcements. --- cpp/shard/Shard.cpp | 4 ++-- go/core/managedprocess/managedprocess.go | 4 ++++ go/ternrun/ternrun.go | 1 + go/terntests/terntests.go | 5 ++++- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/cpp/shard/Shard.cpp b/cpp/shard/Shard.cpp index 43d5a2e36..cca9bf07c 100644 --- a/cpp/shard/Shard.cpp +++ b/cpp/shard/Shard.cpp @@ -2263,7 +2263,7 @@ struct ShardRegisterer : PeriodicLoop { { std::vector allReplicas; bool isInitiated = _shared.isInitiated.load(std::memory_order_acquire); - bool needsWait = _shared.options.logsDBOptions.initialStart && !isInitiated && !_noReplication; + bool needsWait = _shared.options.logsDBOptions.initialStart && !isInitiated && !_noReplication && !_shared.options.replicaAnnouncements; uint8_t minKnown = 0; Duration timeout = 10_sec; if (needsWait) { @@ -2299,7 +2299,7 @@ struct ShardRegisterer : PeriodicLoop { ++emptyReplicas; } } - if (emptyReplicas > 0 && !_noReplication) { + if (emptyReplicas > 0 && !_noReplication && !_shared.options.replicaAnnouncements) { _env.updateAlert(_alert, "Didn't get enough replicas with known addresses from registry"); return false; } diff --git a/go/core/managedprocess/managedprocess.go b/go/core/managedprocess/managedprocess.go index 2af96bbab..9faf14f4d 100644 --- a/go/core/managedprocess/managedprocess.go +++ b/go/core/managedprocess/managedprocess.go @@ -698,6 +698,7 @@ type ShardOpts struct { LogsDBFlags []string NumReaders uint16 BlockServiceWritableDelay *time.Duration + ReplicaAnnouncements bool } func (procs *ManagedProcesses) StartShard(ll *log.Logger, repoDir string, opts *ShardOpts) { @@ -727,6 +728,9 @@ func (procs *ManagedProcesses) StartShard(ll *log.Logger, repoDir string, opts * if opts.BlockServiceWritableDelay != nil { args = append(args, "-block-service-writable-delay", fmt.Sprintf("%dns", opts.BlockServiceWritableDelay.Nanoseconds())) } + if opts.ReplicaAnnouncements { + args = append(args, "-replica-announcements") + } if opts.Xmon != "" { args = append(args, "-xmon", opts.Xmon) } diff --git a/go/ternrun/ternrun.go b/go/ternrun/ternrun.go index 0f9041a75..94b844535 100644 --- a/go/ternrun/ternrun.go +++ b/go/ternrun/ternrun.go @@ -327,6 +327,7 @@ func main() { LogsDBFlags: nil, Addr1: "127.0.0.1:0", BlockServiceWritableDelay: &noWritableDelay, + ReplicaAnnouncements: true, } if r == 0 { if *leaderOnly { diff --git a/go/terntests/terntests.go b/go/terntests/terntests.go index 795f63581..702f0947e 100644 --- a/go/terntests/terntests.go +++ b/go/terntests/terntests.go @@ -1528,7 +1528,9 @@ func main() { // Start shards numShards := 256 for i := 0; i < numShards; i++ { - for r := uint8(0); r < replicaCount; r++ { + // Start followers first; their registry fetches may run before the leader registers. + for replicaOffset := uint8(1); replicaOffset <= replicaCount; replicaOffset++ { + r := replicaOffset % replicaCount shrid := msgs.MakeShardReplicaId(msgs.ShardId(i), msgs.ReplicaId(r)) noWritableDelay := time.Duration(0) shopts := managedprocess.ShardOpts{ @@ -1545,6 +1547,7 @@ func main() { TransientDeadlineInterval: &testTransientDeadlineInterval, BlockServiceWritableDelay: &noWritableDelay, LogsDBFlags: nil, + ReplicaAnnouncements: true, } if r == 0 { if *leaderOnly { From 58a6f5180943307561606ae4572829c7fe1aca8a Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Fri, 9 Oct 2026 17:53:01 +0000 Subject: [PATCH 5/9] shard: export replication progress as a metric eggsfs_shard_staleness_lag and the LogsDB reader and follower lag metrics already show how far behind a replica is. They do not show the log index visible to reads, or the backlog relative to the release point the writer knows of. On a secondary that release point can be ahead of what has been released in its local log. Add eggsfs_shard_progress with the last applied index, taken from the snapshot that reads use, the highest release point the writer knows of, and the backlog between them. A follower at a secondary location reports the release point it learnt from its own leader, not the primary's. Co-Authored-By: Claude Opus 5.5 (1M context) --- cpp/shard/Shard.cpp | 20 ++++++++++++++++++++ cpp/shard/ShardDB.cpp | 8 ++++++++ cpp/shard/ShardDB.hpp | 4 ++++ 3 files changed, 32 insertions(+) diff --git a/cpp/shard/Shard.cpp b/cpp/shard/Shard.cpp index cca9bf07c..65a13be22 100644 --- a/cpp/shard/Shard.cpp +++ b/cpp/shard/Shard.cpp @@ -124,6 +124,10 @@ struct ShardShared { std::atomic droppedReadReqs; std::atomic gatedStaleReads; + // Highest release point known to the writer. Secondary followers learn it + // from their local leader. + std::atomic knownLastReleased; + // we should get up to date information from registry before we start serving any requests // this is populated by ShardRegisterer std::atomic isInitiated; @@ -163,6 +167,7 @@ struct ShardShared { droppedProxyWriteResps(0), droppedReadReqs(0), gatedStaleReads(0), + knownLastReleased(0), isInitiated(false), isBlockServiceCacheInitiated(false), registryClient(logger, xmon, options_.registryClientOptions.host, options_.registryClientOptions.port, options_.registryClientOptions.timeout), @@ -1997,6 +2002,8 @@ struct ShardWriter : Loop { _shared.shardDB.flush(true); + _shared.knownLastReleased.store(_knownLastReleased.u64, std::memory_order_relaxed); + for (auto& req : _linkReadRequests) { _processLinkReadRequest(req); } @@ -2600,6 +2607,19 @@ struct ShardMetricsInserter : PeriodicLoop { _metricsBuilder.timestamp(now); } + { + // The backlog is how many entries we still have to apply. On a + // secondary location follower the release point is our own + // leader's, not the primary's. + const auto [lastApplied, lastAppliedTime] = _shared.shardDB.lastAppliedForReads(); + const uint64_t knownLastReleased = _shared.knownLastReleased.load(std::memory_order_relaxed); + newMeassurement("eggsfs_shard_progress"); + _metricsBuilder.fieldU64("last_applied", lastApplied.u64); + _metricsBuilder.fieldU64("known_last_released", knownLastReleased); + _metricsBuilder.fieldU64("backlog", knownLastReleased > lastApplied.u64 ? knownLastReleased - lastApplied.u64 : 0); + _metricsBuilder.timestamp(now); + } + { _rocksDBStats.clear(); _shared.sharedDB.rocksDBMetrics(_rocksDBStats); diff --git a/cpp/shard/ShardDB.cpp b/cpp/shard/ShardDB.cpp index a0a1386fe..9d8889987 100644 --- a/cpp/shard/ShardDB.cpp +++ b/cpp/shard/ShardDB.cpp @@ -4202,6 +4202,14 @@ TernTime ShardDB::lastAppliedEntryTime() const { return impl->_lastAppliedEntryTime(options); } +std::pair ShardDB::lastAppliedForReads() const { + auto* impl = (ShardDBImpl*)_impl; + auto snapshot = impl->_getCurrentReadSnapshot(); + rocksdb::ReadOptions options; + options.snapshot = snapshot.get(); + return {LogIdx(impl->_lastAppliedLogEntry(options)), impl->_lastAppliedEntryTime(options)}; +} + const std::array& ShardDB::secretKey() const { return ((ShardDBImpl*)_impl)->_secretKey; } diff --git a/cpp/shard/ShardDB.hpp b/cpp/shard/ShardDB.hpp index d700457f3..6e888aad2 100644 --- a/cpp/shard/ShardDB.hpp +++ b/cpp/shard/ShardDB.hpp @@ -90,6 +90,10 @@ struct ShardDB { // The time of the last log entry applied to the DB TernTime lastAppliedEntryTime() const; + // The index and time of the last log entry visible to reads, taken from + // the same snapshot. + std::pair lastAppliedForReads() const; + // Applies the log entry at the given index, and fills in the client response. // The log entry index should be the next in line to be applied to the state -- // `lastAppliedLogEntry() + 1`. From bfa42562dd9e30eb9275c6cb29adebc07a9f67f5 Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Fri, 9 Oct 2026 14:18:41 +0000 Subject: [PATCH 6/9] shard: export metrics on cross-location waits The primary leader holds some CDC responses, for the steps of mkdir and rename and for strongly consistent reads, until the leader at each other location confirms it has applied the entry. No metric shows which locations these waits are for, how long they take, or how long responses are held; only debug logs mention them. A secondary that keeps registering but has stopped applying entries still looks live, and the responses it holds do not show up in metrics. Add eggsfs_shard_cross_location_wait, tagged by target location. It counts waits started, skipped because the location looked down, dropped mid-wait and confirmed, with the total time to confirmation, the number outstanding and the age of the oldest. Add eggsfs_shard_cross_location_held with the number of responses delayed and the total time they were held. The wait policy is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- cpp/shard/Shard.cpp | 77 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/cpp/shard/Shard.cpp b/cpp/shard/Shard.cpp index 65a13be22..9cb4c50cb 100644 --- a/cpp/shard/Shard.cpp +++ b/cpp/shard/Shard.cpp @@ -128,6 +128,22 @@ struct ShardShared { // from their local leader. std::atomic knownLastReleased; + // Waits for other locations to apply an entry before we respond, by the + // location waited for. Written by the writer, read by the metrics inserter. + struct CrossLocationWaitStats { + std::atomic started{0}; // waits sent to the location + std::atomic skipped{0}; // not waited for, the location looked down + std::atomic dropped{0}; // given up mid-wait, the location looked down or went missing + std::atomic finished{0}; // the location confirmed it applied the entry + std::atomic finishedNs{0}; // total time until those confirmations + std::atomic inFlight{0}; // waits outstanding now + std::atomic oldestNs{0}; // age of the oldest outstanding wait + }; + std::array crossLocationWaits; + // Responses delayed by cross-location waits, including waits we abandoned. + std::atomic crossLocationHeldResponses{0}; + std::atomic crossLocationHeldNs{0}; + // we should get up to date information from registry before we start serving any requests // this is populated by ShardRegisterer std::atomic isInitiated; @@ -880,6 +896,7 @@ struct ShardWriter : Loop { static constexpr Duration CROSS_REGION_WAIT_RETRY_INTERVAL = 200_ms; Duration _shardDownThreshold; std::unordered_map _crossRegionWaitResponses; // wait req id -> info + std::array _publishedCrossLocationWaits{}; // locations with non-zero wait gauges published std::unordered_map _waitReqIdToResponseId; uint64_t _requestIdCounter; @@ -1024,12 +1041,30 @@ struct ShardWriter : Loop { } } + // Publishes how many waits are outstanding per location and how old the + // oldest is. Locations we published before but have nothing for now go + // back to zero. + void _publishCrossLocationWaitGauges(TernTime now, const std::array& inFlight, const std::array& oldest) { + for (int loc = 0; loc < 256; ++loc) { + if (inFlight[loc] == 0 && !_publishedCrossLocationWaits[loc]) { + continue; + } + auto& stats = _shared.crossLocationWaits[loc]; + stats.inFlight.store(inFlight[loc], std::memory_order_relaxed); + stats.oldestNs.store(inFlight[loc] == 0 ? 0 : (now - oldest[loc]).ns, std::memory_order_relaxed); + _publishedCrossLocationWaits[loc] = inFlight[loc] != 0; + } + } + void _sendCrossRegionWaitResponses() { + auto now = ternNow(); + std::array inFlight{}; + std::array oldest{}; if (_crossRegionWaitResponses.empty()) { + _publishCrossLocationWaitGauges(now, inFlight, oldest); return; } - auto now = ternNow(); auto leadersAtOtherLocations = _shared.getLeadersAtOtherLocations(); for (auto it = _crossRegionWaitResponses.begin(); it != _crossRegionWaitResponses.end(); ) { @@ -1060,11 +1095,17 @@ struct ShardWriter : Loop { } if (!locationFound || locationDown) { + _shared.crossLocationWaits[locationId].dropped.fetch_add(1, std::memory_order_relaxed); _waitReqIdToResponseId.erase(locState.waitReqId); locIt = waitInfo.locationStates.erase(locIt); continue; } + if (inFlight[locationId] == 0 || waitInfo.createdAt < oldest[locationId]) { + oldest[locationId] = waitInfo.createdAt; + } + ++inFlight[locationId]; + auto timeSinceLastSent = now - locState.lastSent; if (timeSinceLastSent >= CROSS_REGION_WAIT_RETRY_INTERVAL) { uint64_t waitReqId = locState.waitReqId; @@ -1101,11 +1142,14 @@ struct ShardWriter : Loop { ALWAYS_ASSERT(_inFlightRequestKeys.erase(InFlightRequestKey{waitInfo.originalRequest.msg.id, waitInfo.originalRequest.clientAddr}) == 1); + _shared.crossLocationHeldResponses.fetch_add(1, std::memory_order_relaxed); + _shared.crossLocationHeldNs.fetch_add((now - waitInfo.createdAt).ns, std::memory_order_relaxed); it = _crossRegionWaitResponses.erase(it); } else { ++it; } } + _publishCrossLocationWaitGauges(now, inFlight, oldest); } void _maybeEmitHeartbeat() { @@ -1307,9 +1351,11 @@ struct ShardWriter : Loop { if (timeSinceLastSeen >= _shardDownThreshold) { LOG_INFO(_env, "Skipping wait for secondary leader at location %s (down for %s)", leader.locationId, timeSinceLastSeen); + _shared.crossLocationWaits[leader.locationId].skipped.fetch_add(1, std::memory_order_relaxed); continue; } shouldWait = true; + _shared.crossLocationWaits[leader.locationId].started.fetch_add(1, std::memory_order_relaxed); uint64_t waitReqId = ++_requestIdCounter; CrossRegionLocationState locState; @@ -1734,9 +1780,11 @@ struct ShardWriter : Loop { if (timeSinceLastSeen >= _shardDownThreshold) { LOG_INFO(_env, "Skipping wait for secondary leader at location %s (down for %s)", leader.locationId, timeSinceLastSeen); + _shared.crossLocationWaits[leader.locationId].skipped.fetch_add(1, std::memory_order_relaxed); continue; } shouldWait = true; + _shared.crossLocationWaits[leader.locationId].started.fetch_add(1, std::memory_order_relaxed); uint64_t waitReqId = ++_requestIdCounter; CrossRegionLocationState locState; @@ -1801,7 +1849,9 @@ struct ShardWriter : Loop { continue; } - auto& locState = locIt->second; + auto& stats = _shared.crossLocationWaits[respondingLocationId]; + stats.finished.fetch_add(1, std::memory_order_relaxed); + stats.finishedNs.fetch_add((now - waitIt->second.createdAt).ns, std::memory_order_relaxed); waitIt->second.locationStates.erase(locIt); LOG_DEBUG(_env, "Received WaitStateAppliedResp for LogIdx %s from location %s, %s locations remaining", waitIt->second.idx.u64, respondingLocationId, @@ -2620,6 +2670,29 @@ struct ShardMetricsInserter : PeriodicLoop { _metricsBuilder.timestamp(now); } + for (int loc = 0; loc < 256; ++loc) { + const auto& stats = _shared.crossLocationWaits[loc]; + uint64_t started = stats.started.load(std::memory_order_relaxed); + uint64_t skipped = stats.skipped.load(std::memory_order_relaxed); + if (started == 0 && skipped == 0) { continue; } + newMeassurement("eggsfs_shard_cross_location_wait"); + _metricsBuilder.tag("target_location", loc); + _metricsBuilder.fieldU64("started", started); + _metricsBuilder.fieldU64("skipped", skipped); + _metricsBuilder.fieldU64("dropped", stats.dropped.load(std::memory_order_relaxed)); + _metricsBuilder.fieldU64("finished", stats.finished.load(std::memory_order_relaxed)); + _metricsBuilder.fieldU64("finished_ns", stats.finishedNs.load(std::memory_order_relaxed)); + _metricsBuilder.fieldU64("in_flight", stats.inFlight.load(std::memory_order_relaxed)); + _metricsBuilder.fieldU64("oldest_ns", stats.oldestNs.load(std::memory_order_relaxed)); + _metricsBuilder.timestamp(now); + } + if (uint64_t held = _shared.crossLocationHeldResponses.load(std::memory_order_relaxed); held > 0) { + newMeassurement("eggsfs_shard_cross_location_held"); + _metricsBuilder.fieldU64("count", held); + _metricsBuilder.fieldU64("ns", _shared.crossLocationHeldNs.load(std::memory_order_relaxed)); + _metricsBuilder.timestamp(now); + } + { _rocksDBStats.clear(); _shared.sharedDB.rocksDBMetrics(_rocksDBStats); From 7391f941df923e4497f2496a346ed6f1a9c4c4d6 Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Fri, 9 Oct 2026 17:54:06 +0000 Subject: [PATCH 7/9] shard: bound cross-location waits with a timeout A wait for a location ends when it confirms, when it drops out of the published leaders, or when the staleness check finds it has not been seen for -region-staleness-threshold (10 minutes by default). A secondary that is still published and keeps registering but has stopped applying entries meets none of these, so each CDC response that waits on it is held indefinitely. Add -region-wait-timeout, default 15s. Once a wait has run that long, stop waiting for the locations that have not confirmed, send the response and count those waits as timed_out. This does not depend on replica announcements. Zero disables the timeout. CDC can now proceed without confirmation that every location has the change. Read gating on the secondary is separate and unchanged, so it can still serve an older namespace, including a mkdir or cross-shard rename that has only partly replicated there. Co-Authored-By: Claude Opus 5.5 (1M context) --- cpp/shard/Shard.cpp | 25 ++++++++++++++++++++----- cpp/shard/Shard.hpp | 5 +++++ cpp/shard/ternshard.cpp | 7 +++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/cpp/shard/Shard.cpp b/cpp/shard/Shard.cpp index 9cb4c50cb..eb933cef5 100644 --- a/cpp/shard/Shard.cpp +++ b/cpp/shard/Shard.cpp @@ -133,6 +133,7 @@ struct ShardShared { struct CrossLocationWaitStats { std::atomic started{0}; // waits sent to the location std::atomic skipped{0}; // not waited for, the location looked down + std::atomic timedOut{0}; // given up mid-wait after -region-wait-timeout std::atomic dropped{0}; // given up mid-wait, the location looked down or went missing std::atomic finished{0}; // the location confirmed it applied the entry std::atomic finishedNs{0}; // total time until those confirmations @@ -895,6 +896,7 @@ struct ShardWriter : Loop { // Cross-region wait tracking for CDC writes static constexpr Duration CROSS_REGION_WAIT_RETRY_INTERVAL = 200_ms; Duration _shardDownThreshold; + Duration _regionWaitTimeout; std::unordered_map _crossRegionWaitResponses; // wait req id -> info std::array _publishedCrossLocationWaits{}; // locations with non-zero wait gauges published std::unordered_map _waitReqIdToResponseId; @@ -932,6 +934,7 @@ struct ShardWriter : Loop { _nextTimeout(0), _catchupWindowIndex(0), _shardDownThreshold(shared.options.regionStalenessThreshold), + _regionWaitTimeout(shared.options.regionWaitTimeout), _requestIdCounter(RandomGenerator().generate64()) { expandKey(ShardKey, _expandedShardKey); @@ -1101,6 +1104,15 @@ struct ShardWriter : Loop { continue; } + if (_regionWaitTimeout != 0 && now - waitInfo.createdAt >= _regionWaitTimeout) { + LOG_DEBUG(_env, "Giving up waiting for location %s to apply LogIdx %s after %s", + locationId, waitInfo.idx.u64, now - waitInfo.createdAt); + _shared.crossLocationWaits[locationId].timedOut.fetch_add(1, std::memory_order_relaxed); + _waitReqIdToResponseId.erase(locState.waitReqId); + locIt = waitInfo.locationStates.erase(locIt); + continue; + } + if (inFlight[locationId] == 0 || waitInfo.createdAt < oldest[locationId]) { oldest[locationId] = waitInfo.createdAt; } @@ -1132,7 +1144,7 @@ struct ShardWriter : Loop { } if (waitInfo.locationStates.empty()) { - LOG_DEBUG(_env, "All secondary locations have applied LogIdx %s, sending response for request %s", + LOG_DEBUG(_env, "Cross-location waits ended for LogIdx %s, sending response for request %s", waitInfo.idx.u64, waitInfo.originalRequest.msg.id); bool dropArtificially = _packetDropRand.generate64() % 10'000 < _outgoingPacketDropProbability; @@ -1319,8 +1331,8 @@ struct ShardWriter : Loop { _shared.shardDB.applyLogEntry(logsDBEntry.idx.u64, shardEntry, resp.body.resp); - // For CDC requests, wait for all secondary leaders to apply - // before sending response + // Delay CDC until the selected locations apply the entry + // or their waits are abandoned. auto now = ternNow(); auto leadersAtOtherLocations = _shared.getLeadersAtOtherLocations(); bool needsCrossLocationWait = false; @@ -1761,8 +1773,8 @@ struct ShardWriter : Loop { resp.body.checkPointIdx = _shared.shardDB.read(req.msg.body, resp.body.resp); resp.id = req.msg.id; - // For CDC requests, wait for all secondary leaders to apply - // before sending response + // Delay CDC until the selected locations reach this checkpoint + // or their waits are abandoned. auto now = ternNow(); auto leadersAtOtherLocations = _shared.getLeadersAtOtherLocations(); bool shouldWait = false; @@ -2680,6 +2692,7 @@ struct ShardMetricsInserter : PeriodicLoop { _metricsBuilder.fieldU64("started", started); _metricsBuilder.fieldU64("skipped", skipped); _metricsBuilder.fieldU64("dropped", stats.dropped.load(std::memory_order_relaxed)); + _metricsBuilder.fieldU64("timed_out", stats.timedOut.load(std::memory_order_relaxed)); _metricsBuilder.fieldU64("finished", stats.finished.load(std::memory_order_relaxed)); _metricsBuilder.fieldU64("finished_ns", stats.finishedNs.load(std::memory_order_relaxed)); _metricsBuilder.fieldU64("in_flight", stats.inFlight.load(std::memory_order_relaxed)); @@ -2785,6 +2798,8 @@ void runShard(ShardOptions& options) { LOG_INFO(env, " simulateOutgoingPacketDrop = %s", options.serverOptions.simulateOutgoingPacketDrop); LOG_INFO(env, " replicaAnnouncements = %s", options.replicaAnnouncements); LOG_INFO(env, " syslog = %s", (int)options.logOptions.syslog); + LOG_INFO(env, " regionStalenessThreshold = %s", options.regionStalenessThreshold); + LOG_INFO(env, " regionWaitTimeout = %s", options.regionWaitTimeout); LOG_INFO(env, "Using LogsDB with options:"); LOG_INFO(env, " noReplication = '%s'", (int)options.logsDBOptions.noReplication); LOG_INFO(env, " avoidBeingLeader = '%s'", (int)options.logsDBOptions.avoidBeingLeader); diff --git a/cpp/shard/Shard.hpp b/cpp/shard/Shard.hpp index ab4350eee..a7d97c04c 100644 --- a/cpp/shard/Shard.hpp +++ b/cpp/shard/Shard.hpp @@ -23,6 +23,11 @@ struct ShardOptions { int32_t rocksdbMaxBackgroundJobs = 4; int32_t rocksdbMaxSubcompactions = 4; Duration regionStalenessThreshold = 10_mins; + // A timeout lets CDC proceed without confirmation from every location. + // Read gating is independent: a secondary can still serve an older namespace, + // including a mkdir or cross-shard rename that has only partly replicated. + // 0 disables this timeout. + Duration regionWaitTimeout = 15_sec; // Stop serving reads when our newest applied log entry is older than this. 0 disables read gating. Duration readStalenessThreshold = 10_sec; // How often the primary leader emits a heartbeat log entry while otherwise idle. 0 disables emission. diff --git a/cpp/shard/ternshard.cpp b/cpp/shard/ternshard.cpp index 4468aba6c..1c9567c79 100644 --- a/cpp/shard/ternshard.cpp +++ b/cpp/shard/ternshard.cpp @@ -49,6 +49,10 @@ static bool parseShardOptions(CommandLineArgs& args, ShardOptions& options) { options.regionStalenessThreshold = parseDuration(args.next()); continue; } + if (arg == "-region-wait-timeout") { + options.regionWaitTimeout = parseDuration(args.next()); + continue; + } if (arg == "-read-staleness-threshold") { options.readStalenessThreshold = parseDuration(args.next()); continue; @@ -97,6 +101,9 @@ static void printShardOptionsUsage() { fprintf(stderr, "ShardOptions:\n"); fprintf(stderr, " -region-staleness-threshold\n"); fprintf(stderr, " Duration after which a cross-region shard is considered down. Default: 10m\n"); + fprintf(stderr, " -region-wait-timeout\n"); + fprintf(stderr, " Stop waiting for a cross-region shard to apply an entry after this long. 0 disables this timeout. Default: 15s\n"); + fprintf(stderr, " \tTimed-out locations may still serve older or partly replicated namespace state.\n"); fprintf(stderr, " -read-staleness-threshold\n"); fprintf(stderr, " Stop serving reads when the newest applied log entry is older than this. 0 disables. Default: 10s\n"); fprintf(stderr, " -heartbeat-emission-interval\n"); From 8cab283995e04410420d9392c9cc92cd531da7b9 Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Mon, 12 Oct 2026 13:25:48 +0000 Subject: [PATCH 8/9] shard: carry replication progress in replica announcements Registrations and announcements both carry on while a secondary's apply loop is stuck, so neither tells the primary whether the secondary is keeping up. Add the last applied index visible to reads, and the time the primary created that entry, to each announcement. The tracker publishes this progress for the selected leader at each remote location, but only while the published address is the one that announced it. Progress is kept when announcements stop, along with when we last heard one, even if the registry reports newer registrations. A registration cannot tell lost announcements apart from a restart at the same address with announcements off, so that restart also looks silent. Add eggsfs_shard_cross_location_view with the age of each leader's last announcement and its reported apply lag, which is receipt time minus entry creation time. Lag is only meaningful on the primary, where both times come from the same clock. Nothing uses this progress for wait decisions yet. Co-Authored-By: Claude Opus 5.5 (1M context) --- cpp/core/MsgsGen.cpp | 10 ++- cpp/core/MsgsGen.hpp | 8 ++- cpp/shard/ReplicaTracker.cpp | 30 ++++++++- cpp/shard/ReplicaTracker.hpp | 15 +++++ cpp/shard/Shard.cpp | 14 ++++ cpp/tests/replicatrackertests.cpp | 104 +++++++++++++++++++++++++++++- go/msgs/msgs.go | 4 ++ go/msgs/msgs_bincode.go | 12 ++++ 8 files changed, 192 insertions(+), 5 deletions(-) diff --git a/cpp/core/MsgsGen.cpp b/cpp/core/MsgsGen.cpp index d5d6cf474..fda6d00d0 100644 --- a/cpp/core/MsgsGen.cpp +++ b/cpp/core/MsgsGen.cpp @@ -1584,28 +1584,36 @@ void ShardReplicaAnnouncement::pack(BincodeBuf& buf) const { buf.packScalar(location); buf.packScalar(isLeader); addrs.pack(buf); + lastApplied.pack(buf); + lastAppliedTime.pack(buf); } void ShardReplicaAnnouncement::unpack(BincodeBuf& buf) { shrid.unpack(buf); location = buf.unpackScalar(); isLeader = buf.unpackScalar(); addrs.unpack(buf); + lastApplied.unpack(buf); + lastAppliedTime.unpack(buf); } void ShardReplicaAnnouncement::clear() { shrid = ShardReplicaId(); location = uint8_t(0); isLeader = bool(0); addrs.clear(); + lastApplied = LogIdx(); + lastAppliedTime = TernTime(); } bool ShardReplicaAnnouncement::operator==(const ShardReplicaAnnouncement& rhs) const { if ((ShardReplicaId)this->shrid != (ShardReplicaId)rhs.shrid) { return false; }; if ((uint8_t)this->location != (uint8_t)rhs.location) { return false; }; if ((bool)this->isLeader != (bool)rhs.isLeader) { return false; }; if (addrs != rhs.addrs) { return false; }; + if ((LogIdx)this->lastApplied != (LogIdx)rhs.lastApplied) { return false; }; + if ((TernTime)this->lastAppliedTime != (TernTime)rhs.lastAppliedTime) { return false; }; return true; } std::ostream& operator<<(std::ostream& out, const ShardReplicaAnnouncement& x) { - out << "ShardReplicaAnnouncement(" << "Shrid=" << x.shrid << ", " << "Location=" << (int)x.location << ", " << "IsLeader=" << x.isLeader << ", " << "Addrs=" << x.addrs << ")"; + out << "ShardReplicaAnnouncement(" << "Shrid=" << x.shrid << ", " << "Location=" << (int)x.location << ", " << "IsLeader=" << x.isLeader << ", " << "Addrs=" << x.addrs << ", " << "LastApplied=" << x.lastApplied << ", " << "LastAppliedTime=" << x.lastAppliedTime << ")"; return out; } diff --git a/cpp/core/MsgsGen.hpp b/cpp/core/MsgsGen.hpp index 4e9cdcb6b..d1842b1cf 100644 --- a/cpp/core/MsgsGen.hpp +++ b/cpp/core/MsgsGen.hpp @@ -1597,11 +1597,13 @@ struct ShardReplicaAnnouncement { uint8_t location; bool isLeader; AddrsInfo addrs; + LogIdx lastApplied; + TernTime lastAppliedTime; - static constexpr uint16_t STATIC_SIZE = 2 + 1 + 1 + AddrsInfo::STATIC_SIZE; // shrid + location + isLeader + addrs + static constexpr uint16_t STATIC_SIZE = 2 + 1 + 1 + AddrsInfo::STATIC_SIZE + 8 + 8; // shrid + location + isLeader + addrs + lastApplied + lastAppliedTime ShardReplicaAnnouncement() { clear(); } - explicit ShardReplicaAnnouncement(ShardReplicaId shrid_, uint8_t location_, bool isLeader_, AddrsInfo addrs_) : shrid(shrid_), location(location_), isLeader(isLeader_), addrs(addrs_) {} + explicit ShardReplicaAnnouncement(ShardReplicaId shrid_, uint8_t location_, bool isLeader_, AddrsInfo addrs_, LogIdx lastApplied_, TernTime lastAppliedTime_) : shrid(shrid_), location(location_), isLeader(isLeader_), addrs(addrs_), lastApplied(lastApplied_), lastAppliedTime(lastAppliedTime_) {} ShardReplicaAnnouncement(const ShardReplicaAnnouncement&) = default; ShardReplicaAnnouncement& operator=(const ShardReplicaAnnouncement&) = default; ShardReplicaAnnouncement(ShardReplicaAnnouncement&&) = default; @@ -1612,6 +1614,8 @@ struct ShardReplicaAnnouncement { _size += 1; // location _size += 1; // isLeader _size += addrs.packedSize(); // addrs + _size += 8; // lastApplied + _size += 8; // lastAppliedTime return _size; } void pack(BincodeBuf& buf) const; diff --git a/cpp/shard/ReplicaTracker.cpp b/cpp/shard/ReplicaTracker.cpp index 80265bdb7..a2490eae6 100644 --- a/cpp/shard/ReplicaTracker.cpp +++ b/cpp/shard/ReplicaTracker.cpp @@ -37,6 +37,7 @@ ReplicaTracker::ReplicaTracker(Logger& logger, std::shared_ptr& xmon, _isLeader(isLeader), _localReplicas(std::make_shared()), _remoteLeaders(std::make_shared()), + _remoteProgress(std::make_shared()), _announcementTargets(std::make_shared()) { _peers.emplace( @@ -44,6 +45,8 @@ ReplicaTracker::ReplicaTracker(Logger& logger, std::shared_ptr& xmon, PeerState{ .registry = std::nullopt, .announced = View{.addrs = addrs, .isLeader = isLeader, .lastSeen = {}}, + .lastApplied = {}, + .lastAppliedTime = {}, }); _publishLocked(TernTime{}); } @@ -56,7 +59,7 @@ bool ReplicaTracker::_publishedDiffers(uint8_t location, const View& before, con if (before.addrs != after.addrs || before.isLeader != after.isLeader) { return true; } - // Remote leader timestamps affect leader selection and liveness. + // Remote leader timestamps affect leader selection, liveness and progress. const bool inRemoteLeaders = location != _location && before.isLeader; return inRemoteLeaders && before.lastSeen != after.lastSeen; } @@ -78,6 +81,8 @@ void ReplicaTracker::seedRegistry(const std::vector& replicas, Te PeerState{ .registry = View{.addrs = replica.addrs, .isLeader = replica.isLeader, .lastSeen = replica.lastSeen}, .announced = std::nullopt, + .lastApplied = {}, + .lastAppliedTime = {}, }); if (inserted) { changed = true; @@ -133,6 +138,8 @@ void ReplicaTracker::recordAnnouncement(const IpPort& source, const ShardReplica auto [it, inserted] = _peers.try_emplace(key, PeerState{ .registry = std::nullopt, .announced = announced, + .lastApplied = announcement.lastApplied, + .lastAppliedTime = announcement.lastAppliedTime, }); if (inserted) { changed = true; @@ -142,6 +149,8 @@ void ReplicaTracker::recordAnnouncement(const IpPort& source, const ShardReplica // publishes it. Compare with the view that was actually published. const View before = peer.current(_publishedAt); peer.announced = announced; + peer.lastApplied = announcement.lastApplied; + peer.lastAppliedTime = announcement.lastAppliedTime; changed = changed || _publishedDiffers(announcement.location, before, peer.current(now)); } if (changed || (announcement.location != _location && announcement.isLeader)) { @@ -181,6 +190,11 @@ ReplicaTracker::remoteLeaders() const { return _remoteLeaders.load(); } +std::shared_ptr +ReplicaTracker::remoteProgress() const { + return _remoteProgress.load(); +} + std::shared_ptr ReplicaTracker::announcementTargets() const { return _announcementTargets.load(); @@ -200,6 +214,7 @@ void ReplicaTracker::_publishLocked(TernTime now) { _publishedAt = now; auto local = std::make_shared(); auto remote = std::make_shared(); + auto progress = std::make_shared(); auto targets = std::make_shared(); // Prefer fresh announcements, then registry records, then announcements @@ -241,7 +256,20 @@ void ReplicaTracker::_publishLocked(TernTime now) { } } + for (const auto& leader : *remote) { + const auto& peer = _peers.at(ShardReplicaLocationKey(leader.id, leader.locationId)); + if (peer.announced.has_value() && peer.announced->addrs == leader.addrs) { + progress->push_back(RemoteLeaderProgress{ + .locationId = leader.locationId, + .lastHeard = peer.announced->lastSeen, + .lastApplied = peer.lastApplied, + .lastAppliedTime = peer.lastAppliedTime, + }); + } + } + _localReplicas.store(std::move(local)); _remoteLeaders.store(std::move(remote)); + _remoteProgress.store(std::move(progress)); _announcementTargets.store(std::move(targets)); } diff --git a/cpp/shard/ReplicaTracker.hpp b/cpp/shard/ReplicaTracker.hpp index 71eeb22a1..2a098d90d 100644 --- a/cpp/shard/ReplicaTracker.hpp +++ b/cpp/shard/ReplicaTracker.hpp @@ -36,11 +36,24 @@ class ReplicaTracker { struct PeerState { std::optional registry; // once a registry poll has described the peer std::optional announced; // once the peer has announced itself + // Progress from `announced`, valid only for the address it advertised. + // Registry registrations do not establish whether announcements stopped. + LogIdx lastApplied; + TernTime lastAppliedTime; bool hasFreshAnnouncement(TernTime now) const; View current(TernTime now) const; }; + // Last announced progress of a published remote leader, retained during silence. + struct RemoteLeaderProgress { + uint8_t locationId; + TernTime lastHeard; // local receipt time + LogIdx lastApplied; + TernTime lastAppliedTime; + }; + using RemoteProgress = std::vector; + using LocalReplicas = std::array; using RemoteLeaders = std::vector; using AnnouncementTargets = std::vector; @@ -53,6 +66,7 @@ class ReplicaTracker { std::shared_ptr localReplicas() const; std::shared_ptr remoteLeaders() const; + std::shared_ptr remoteProgress() const; std::shared_ptr announcementTargets() const; std::optional peerState(ShardReplicaId id, uint8_t location) const; @@ -65,6 +79,7 @@ class ReplicaTracker { std::unordered_map _peers; std::atomic> _localReplicas; std::atomic> _remoteLeaders; + std::atomic> _remoteProgress; std::atomic> _announcementTargets; TernTime _publishedAt; // the `now` the snapshots were last built for diff --git a/cpp/shard/Shard.cpp b/cpp/shard/Shard.cpp index eb933cef5..f14bae575 100644 --- a/cpp/shard/Shard.cpp +++ b/cpp/shard/Shard.cpp @@ -762,6 +762,7 @@ struct ShardReplicaAnnouncer : Loop { announcement.body.location = _shared.options.logsDBOptions.location; announcement.body.isLeader = _shared.options.isLeader() && (_shared.options.logsDBOptions.noReplication || _shared.isInitiated.load(std::memory_order_acquire)); announcement.body.addrs = _shared.sock().addr(); + std::tie(announcement.body.lastApplied, announcement.body.lastAppliedTime) = _shared.shardDB.lastAppliedForReads(); auto targets = _shared.replicaTracker.announcementTargets(); for (const auto& target : *targets) { @@ -2699,6 +2700,19 @@ struct ShardMetricsInserter : PeriodicLoop { _metricsBuilder.fieldU64("oldest_ns", stats.oldestNs.load(std::memory_order_relaxed)); _metricsBuilder.timestamp(now); } + // How far each leader at another location had applied when we last + // heard from it directly. The lag is only meaningful on the primary + // location, where we created the entries ourselves. + // Hold the snapshot for the whole loop: a temporary in the range + // expression would be destroyed before the loop body runs. + auto remoteProgress = _shared.replicaTracker.remoteProgress(); + for (const auto& leader : *remoteProgress) { + newMeassurement("eggsfs_shard_cross_location_view"); + _metricsBuilder.tag("target_location", (int)leader.locationId); + _metricsBuilder.fieldU64("progress_age_ns", now > leader.lastHeard ? (now - leader.lastHeard).ns : 0); + _metricsBuilder.fieldU64("lag_ns", leader.lastHeard > leader.lastAppliedTime ? (leader.lastHeard - leader.lastAppliedTime).ns : 0); + _metricsBuilder.timestamp(now); + } if (uint64_t held = _shared.crossLocationHeldResponses.load(std::memory_order_relaxed); held > 0) { newMeassurement("eggsfs_shard_cross_location_held"); _metricsBuilder.fieldU64("count", held); diff --git a/cpp/tests/replicatrackertests.cpp b/cpp/tests/replicatrackertests.cpp index 623520592..b40cb8d28 100644 --- a/cpp/tests/replicatrackertests.cpp +++ b/cpp/tests/replicatrackertests.cpp @@ -26,7 +26,7 @@ static AddrsInfo addresses(uint8_t lastOctet, uint16_t port) { } static ShardReplicaAnnouncement announcement(ShardReplicaId id, uint8_t location, bool isLeader, const AddrsInfo& addrs) { - return ShardReplicaAnnouncement(id, location, isLeader, addrs); + return ShardReplicaAnnouncement(id, location, isLeader, addrs, LogIdx(), TernTime()); } TEST_CASE("registry seeds local replicas and remote leaders") { @@ -106,11 +106,13 @@ TEST_CASE("a fresh leader announcement takes precedence over stale registry poll remote = tracker.remoteLeaders(); REQUIRE(remote->size() == 1); CHECK(remote->at(0).id == newLeader.shrid); + CHECK(tracker.remoteProgress()->size() == 1); tracker.expire(TernTime(20) + ReplicaTracker::PEER_EXPIRY); remote = tracker.remoteLeaders(); REQUIRE(remote->size() == 1); CHECK(remote->at(0).id == registry[0].id); + CHECK(tracker.remoteProgress()->empty()); } TEST_CASE("the most recently heard leader wins without changing other peers' records") { @@ -118,11 +120,15 @@ TEST_CASE("the most recently heard leader wins without changing other peers' rec ReplicaTracker tracker(logger, xmon, self, 0, true, addresses(1, 10001)); auto first = announcement(ShardReplicaId(ShardId(7), ReplicaId(4)), 1, true, addresses(2, 10002)); auto second = announcement(ShardReplicaId(ShardId(7), ReplicaId(3)), 1, true, addresses(3, 10003)); + first.lastApplied = LogIdx(40); + second.lastApplied = LogIdx(42); tracker.recordAnnouncement(address(2, 10002), first, TernTime(10)); tracker.recordAnnouncement(address(3, 10003), second, TernTime(20)); REQUIRE(tracker.remoteLeaders()->size() == 1); CHECK(tracker.remoteLeaders()->at(0).id == second.shrid); + REQUIRE(tracker.remoteProgress()->size() == 1); + CHECK(tracker.remoteProgress()->at(0).lastApplied == LogIdx(42)); CHECK(tracker.peerState(first.shrid, 1)->announced->isLeader); // A delayed packet can temporarily change the winner; the next announcement @@ -494,3 +500,99 @@ TEST_CASE("peers known only from the registry never expire") { tracker.seedRegistry(registry, TernTime(3'000)); CHECK(tracker.remoteLeaders()->at(0).lastSeen == TernTime(3'000)); } + +TEST_CASE("remote leaders publish the progress they announce") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(4)); + ReplicaTracker tracker(logger, xmon, self, 0, true, addresses(1, 10001)); + + // Known only from the registry: no progress yet. + std::vector seed{ + FullShardInfo(ShardReplicaId(ShardId(7), ReplicaId(4)), true, addresses(3, 10003), 0, 1), + }; + tracker.seedRegistry(seed, TernTime(10)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteProgress()->empty()); + + auto remoteLeader = announcement(ShardReplicaId(ShardId(7), ReplicaId(4)), 1, true, addresses(3, 10003)); + remoteLeader.lastApplied = LogIdx(42); + remoteLeader.lastAppliedTime = TernTime(15); + tracker.recordAnnouncement(address(3, 10003), remoteLeader, TernTime(20)); + + // A follower at that location and a local replica don't count. + auto remoteFollower = announcement(ShardReplicaId(ShardId(7), ReplicaId(1)), 1, false, addresses(4, 10004)); + remoteFollower.lastApplied = LogIdx(40); + tracker.recordAnnouncement(address(4, 10004), remoteFollower, TernTime(21)); + auto localFollower = announcement(ShardReplicaId(ShardId(7), ReplicaId(0)), 0, false, addresses(5, 10005)); + tracker.recordAnnouncement(address(5, 10005), localFollower, TernTime(22)); + + auto progress = tracker.remoteProgress(); + REQUIRE(progress->size() == 1); + CHECK(progress->at(0).locationId == 1); + CHECK(progress->at(0).lastHeard == TernTime(20)); + CHECK(progress->at(0).lastApplied == LogIdx(42)); + CHECK(progress->at(0).lastAppliedTime == TernTime(15)); + + // Registration and announcements run independently. A registration between + // announcements must not discard the progress we just received. + seed[0].lastSeen = TernTime(20) + 10_ms; + tracker.seedRegistry(seed, TernTime(20) + 20_ms); + progress = tracker.remoteProgress(); + REQUIRE(progress->size() == 1); + CHECK(progress->at(0).lastHeard == TernTime(20)); + CHECK(progress->at(0).lastApplied == LogIdx(42)); + + // A quiet leader stays in the progress, with the time we last heard + // from it, so that the primary can see it has gone silent. + tracker.expire(TernTime(20) + ReplicaTracker::PEER_EXPIRY); + progress = tracker.remoteProgress(); + REQUIRE(progress->size() == 1); + CHECK(progress->at(0).lastHeard == TernTime(20)); + + // Another poll with unchanged registration data must preserve silence too. + tracker.seedRegistry(seed, TernTime(20) + ReplicaTracker::PEER_EXPIRY); + CHECK(tracker.remoteProgress()->size() == 1); + + // Registry access can remain healthy while inter-location traffic fails. + seed[0].lastSeen = TernTime(20) + ReplicaTracker::PEER_EXPIRY; + tracker.seedRegistry(seed, seed[0].lastSeen + 1_ns); + progress = tracker.remoteProgress(); + REQUIRE(progress->size() == 1); + CHECK(progress->at(0).lastHeard == TernTime(20)); + CHECK(tracker.remoteLeaders()->size() == 1); + + remoteLeader.lastApplied = LogIdx(100); + remoteLeader.lastAppliedTime = seed[0].lastSeen; + tracker.recordAnnouncement(address(3, 10003), remoteLeader, seed[0].lastSeen + 100_ms); + progress = tracker.remoteProgress(); + REQUIRE(progress->size() == 1); + CHECK(progress->at(0).lastHeard == seed[0].lastSeen + 100_ms); + CHECK(progress->at(0).lastApplied == LogIdx(100)); +} + +TEST_CASE("progress is not transferred to an address learned from the registry") { + const auto self = ShardReplicaId(ShardId(7), ReplicaId(4)); + ReplicaTracker tracker(logger, xmon, self, 0, true, addresses(1, 10001)); + auto leader = announcement(ShardReplicaId(ShardId(7), ReplicaId(4)), 1, true, addresses(2, 10002)); + leader.lastApplied = LogIdx(42); + tracker.recordAnnouncement(address(2, 10002), leader, TernTime(10)); + + std::vector registry{ + FullShardInfo(leader.shrid, true, addresses(3, 10003), TernTime(20), 1), + }; + tracker.seedRegistry(registry, TernTime(30)); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).addrs == leader.addrs); + REQUIRE(tracker.remoteProgress()->size() == 1); + CHECK(tracker.remoteProgress()->at(0).lastApplied == LogIdx(42)); + + tracker.expire(TernTime(10) + ReplicaTracker::PEER_EXPIRY); + REQUIRE(tracker.remoteLeaders()->size() == 1); + CHECK(tracker.remoteLeaders()->at(0).addrs == registry[0].addrs); + CHECK(tracker.remoteProgress()->empty()); + + leader.addrs = registry[0].addrs; + leader.lastApplied = LogIdx(100); + tracker.recordAnnouncement(address(3, 10003), leader, TernTime(10) + ReplicaTracker::PEER_EXPIRY + 1_ns); + REQUIRE(tracker.remoteProgress()->size() == 1); + CHECK(tracker.remoteProgress()->at(0).lastApplied == LogIdx(100)); +} diff --git a/go/msgs/msgs.go b/go/msgs/msgs.go index bd504f740..8de2e0956 100644 --- a/go/msgs/msgs.go +++ b/go/msgs/msgs.go @@ -2356,6 +2356,10 @@ type ShardReplicaAnnouncement struct { Location Location IsLeader bool Addrs AddrsInfo + // The last entry the replica has applied to the state it serves reads + // from, and when the primary leader created that entry. + LastApplied LogIdx + LastAppliedTime TernTime } type AllShardsDEPRECATEDResp struct { diff --git a/go/msgs/msgs_bincode.go b/go/msgs/msgs_bincode.go index 2e2a79bf2..5826c04c4 100644 --- a/go/msgs/msgs_bincode.go +++ b/go/msgs/msgs_bincode.go @@ -5126,6 +5126,12 @@ func (v *ShardReplicaAnnouncement) Pack(w io.Writer) error { if err := v.Addrs.Pack(w); err != nil { return err } + if err := bincode.PackScalar(w, uint64(v.LastApplied)); err != nil { + return err + } + if err := bincode.PackScalar(w, uint64(v.LastAppliedTime)); err != nil { + return err + } return nil } @@ -5142,6 +5148,12 @@ func (v *ShardReplicaAnnouncement) Unpack(r io.Reader) error { if err := v.Addrs.Unpack(r); err != nil { return err } + if err := bincode.UnpackScalar(r, (*uint64)(&v.LastApplied)); err != nil { + return err + } + if err := bincode.UnpackScalar(r, (*uint64)(&v.LastAppliedTime)); err != nil { + return err + } return nil } From 95bde5ec9c23beeb86ca29b10f2100342d2ea283 Mon Sep 17 00:00:00 2001 From: Steve Hodgson Date: Mon, 12 Oct 2026 13:34:56 +0000 Subject: [PATCH 9/9] shard: skip waits for silent or lagging locations The staleness check already skips locations that are missing or look down. A secondary that still looks live is waited for, and if it is not applying entries, each response waiting on it is held for the full 15s timeout. Announced progress lets the primary avoid starting those waits. Before starting a new wait, look at the location leader's last announced progress. Skip the wait if nothing has been heard for 5s (-region-silence-threshold), or if the last announcement showed 15s or more of apply lag (-region-lag-threshold). Lag catches a secondary whose announcer runs but whose apply loop has stalled. The primary's idle heartbeat entries keep a healthy idle secondary's lag low; with -heartbeat-emission-interval 0 it would look behind. Both checks need announcements, each is disabled by zero, and neither affects waits already running. A location with no announced progress for its current address is still waited for, under the timeout. A leader that restarts at the same address with announcements off keeps its old progress and is skipped as silent. Skipped waits are counted as silent or lagging. Like a timeout, a skip lets CDC proceed without confirmation that the secondary has the change. Set the wait, silence and lag limits to zero to turn these early releases off. Co-Authored-By: Claude Opus 5.5 (1M context) --- cpp/shard/Shard.cpp | 45 ++++++++++++++++++++++++++++++++++++++++- cpp/shard/Shard.hpp | 12 +++++++++-- cpp/shard/ternshard.cpp | 16 +++++++++++++-- 3 files changed, 68 insertions(+), 5 deletions(-) diff --git a/cpp/shard/Shard.cpp b/cpp/shard/Shard.cpp index f14bae575..df96c88c6 100644 --- a/cpp/shard/Shard.cpp +++ b/cpp/shard/Shard.cpp @@ -134,6 +134,8 @@ struct ShardShared { std::atomic started{0}; // waits sent to the location std::atomic skipped{0}; // not waited for, the location looked down std::atomic timedOut{0}; // given up mid-wait after -region-wait-timeout + std::atomic silent{0}; // not waited for, no recent announcement received + std::atomic lagging{0}; // not waited for, the location's leader announced being too far behind std::atomic dropped{0}; // given up mid-wait, the location looked down or went missing std::atomic finished{0}; // the location confirmed it applied the entry std::atomic finishedNs{0}; // total time until those confirmations @@ -898,6 +900,8 @@ struct ShardWriter : Loop { static constexpr Duration CROSS_REGION_WAIT_RETRY_INTERVAL = 200_ms; Duration _shardDownThreshold; Duration _regionWaitTimeout; + Duration _regionSilenceThreshold; + Duration _regionLagThreshold; std::unordered_map _crossRegionWaitResponses; // wait req id -> info std::array _publishedCrossLocationWaits{}; // locations with non-zero wait gauges published std::unordered_map _waitReqIdToResponseId; @@ -936,6 +940,8 @@ struct ShardWriter : Loop { _catchupWindowIndex(0), _shardDownThreshold(shared.options.regionStalenessThreshold), _regionWaitTimeout(shared.options.regionWaitTimeout), + _regionSilenceThreshold(shared.options.regionSilenceThreshold), + _regionLagThreshold(shared.options.regionLagThreshold), _requestIdCounter(RandomGenerator().generate64()) { expandKey(ShardKey, _expandedShardKey); @@ -1045,6 +1051,31 @@ struct ShardWriter : Loop { } } + // No progress for the selected address means these checks cannot skip it. + // Previously announced progress is retained when announcements go silent, + // even if the peer keeps registering. + bool _waitForLocation(uint8_t locationId, TernTime now) { + auto remoteProgress = _shared.replicaTracker.remoteProgress(); + for (const auto& leader : *remoteProgress) { + if (leader.locationId != locationId) { + continue; + } + if (_regionSilenceThreshold != 0 && now - leader.lastHeard >= _regionSilenceThreshold) { + LOG_DEBUG(_env, "Skipping wait for location %s, not heard from for %s", locationId, now - leader.lastHeard); + _shared.crossLocationWaits[locationId].silent.fetch_add(1, std::memory_order_relaxed); + return false; + } + Duration lag = leader.lastHeard > leader.lastAppliedTime ? leader.lastHeard - leader.lastAppliedTime : Duration(0); + if (_regionLagThreshold != 0 && lag >= _regionLagThreshold) { + LOG_DEBUG(_env, "Skipping wait for location %s, it announced being %s behind", locationId, lag); + _shared.crossLocationWaits[locationId].lagging.fetch_add(1, std::memory_order_relaxed); + return false; + } + return true; + } + return true; + } + // Publishes how many waits are outstanding per location and how old the // oldest is. Locations we published before but have nothing for now go // back to zero. @@ -1367,6 +1398,9 @@ struct ShardWriter : Loop { _shared.crossLocationWaits[leader.locationId].skipped.fetch_add(1, std::memory_order_relaxed); continue; } + if (!_waitForLocation(leader.locationId, now)) { + continue; + } shouldWait = true; _shared.crossLocationWaits[leader.locationId].started.fetch_add(1, std::memory_order_relaxed); @@ -1796,6 +1830,9 @@ struct ShardWriter : Loop { _shared.crossLocationWaits[leader.locationId].skipped.fetch_add(1, std::memory_order_relaxed); continue; } + if (!_waitForLocation(leader.locationId, now)) { + continue; + } shouldWait = true; _shared.crossLocationWaits[leader.locationId].started.fetch_add(1, std::memory_order_relaxed); @@ -2687,11 +2724,15 @@ struct ShardMetricsInserter : PeriodicLoop { const auto& stats = _shared.crossLocationWaits[loc]; uint64_t started = stats.started.load(std::memory_order_relaxed); uint64_t skipped = stats.skipped.load(std::memory_order_relaxed); - if (started == 0 && skipped == 0) { continue; } + uint64_t silent = stats.silent.load(std::memory_order_relaxed); + uint64_t lagging = stats.lagging.load(std::memory_order_relaxed); + if (started == 0 && skipped == 0 && silent == 0 && lagging == 0) { continue; } newMeassurement("eggsfs_shard_cross_location_wait"); _metricsBuilder.tag("target_location", loc); _metricsBuilder.fieldU64("started", started); _metricsBuilder.fieldU64("skipped", skipped); + _metricsBuilder.fieldU64("silent", silent); + _metricsBuilder.fieldU64("lagging", lagging); _metricsBuilder.fieldU64("dropped", stats.dropped.load(std::memory_order_relaxed)); _metricsBuilder.fieldU64("timed_out", stats.timedOut.load(std::memory_order_relaxed)); _metricsBuilder.fieldU64("finished", stats.finished.load(std::memory_order_relaxed)); @@ -2814,6 +2855,8 @@ void runShard(ShardOptions& options) { LOG_INFO(env, " syslog = %s", (int)options.logOptions.syslog); LOG_INFO(env, " regionStalenessThreshold = %s", options.regionStalenessThreshold); LOG_INFO(env, " regionWaitTimeout = %s", options.regionWaitTimeout); + LOG_INFO(env, " regionSilenceThreshold = %s", options.regionSilenceThreshold); + LOG_INFO(env, " regionLagThreshold = %s", options.regionLagThreshold); LOG_INFO(env, "Using LogsDB with options:"); LOG_INFO(env, " noReplication = '%s'", (int)options.logsDBOptions.noReplication); LOG_INFO(env, " avoidBeingLeader = '%s'", (int)options.logsDBOptions.avoidBeingLeader); diff --git a/cpp/shard/Shard.hpp b/cpp/shard/Shard.hpp index a7d97c04c..22bb3f14d 100644 --- a/cpp/shard/Shard.hpp +++ b/cpp/shard/Shard.hpp @@ -23,11 +23,19 @@ struct ShardOptions { int32_t rocksdbMaxBackgroundJobs = 4; int32_t rocksdbMaxSubcompactions = 4; Duration regionStalenessThreshold = 10_mins; - // A timeout lets CDC proceed without confirmation from every location. + // These limits let CDC proceed without confirmation from every location. // Read gating is independent: a secondary can still serve an older namespace, // including a mkdir or cross-shard rename that has only partly replicated. - // 0 disables this timeout. + // Set all three to 0 to disable these early-release limits. + + // Maximum duration of an individual wait. 0 disables only this timeout. Duration regionWaitTimeout = 15_sec; + // Skip new waits after this long without an announcement. Requires + // -replica-announcements; 0 disables. + Duration regionSilenceThreshold = 5_sec; + // Skip new waits when the last announcement showed this much apply lag. + // Requires -replica-announcements; 0 disables. + Duration regionLagThreshold = 15_sec; // Stop serving reads when our newest applied log entry is older than this. 0 disables read gating. Duration readStalenessThreshold = 10_sec; // How often the primary leader emits a heartbeat log entry while otherwise idle. 0 disables emission. diff --git a/cpp/shard/ternshard.cpp b/cpp/shard/ternshard.cpp index 1c9567c79..b17dabd44 100644 --- a/cpp/shard/ternshard.cpp +++ b/cpp/shard/ternshard.cpp @@ -53,6 +53,14 @@ static bool parseShardOptions(CommandLineArgs& args, ShardOptions& options) { options.regionWaitTimeout = parseDuration(args.next()); continue; } + if (arg == "-region-silence-threshold") { + options.regionSilenceThreshold = parseDuration(args.next()); + continue; + } + if (arg == "-region-lag-threshold") { + options.regionLagThreshold = parseDuration(args.next()); + continue; + } if (arg == "-read-staleness-threshold") { options.readStalenessThreshold = parseDuration(args.next()); continue; @@ -102,8 +110,12 @@ static void printShardOptionsUsage() { fprintf(stderr, " -region-staleness-threshold\n"); fprintf(stderr, " Duration after which a cross-region shard is considered down. Default: 10m\n"); fprintf(stderr, " -region-wait-timeout\n"); - fprintf(stderr, " Stop waiting for a cross-region shard to apply an entry after this long. 0 disables this timeout. Default: 15s\n"); - fprintf(stderr, " \tTimed-out locations may still serve older or partly replicated namespace state.\n"); + fprintf(stderr, " Stop waiting for a cross-region shard to apply an entry after this long. 0 disables only this timeout. Default: 15s\n"); + fprintf(stderr, " Skipped or timed-out locations may still serve older or partly replicated namespace state. Set the wait, silence and lag limits to 0 to disable these limits.\n"); + fprintf(stderr, " -region-silence-threshold\n"); + fprintf(stderr, " Skip new waits for a previously announcing cross-region shard after this long without an announcement. Needs -replica-announcements. 0 disables. Default: 5s\n"); + fprintf(stderr, " -region-lag-threshold\n"); + fprintf(stderr, " Skip new waits for a cross-region shard whose last announcement showed it this far behind. Needs -replica-announcements. 0 disables. Default: 15s\n"); fprintf(stderr, " -read-staleness-threshold\n"); fprintf(stderr, " Stop serving reads when the newest applied log entry is older than this. 0 disables. Default: 10s\n"); fprintf(stderr, " -heartbeat-emission-interval\n");