From ff9f68a60938f03946a9a8258c68ea29124d67f6 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Tue, 10 Nov 2026 16:51:33 +0100 Subject: [PATCH 01/16] feat(pushsync): remember first hop results per neighborhood --- pkg/pushsync/export_test.go | 56 ++- pkg/pushsync/hopmemory.go | 197 +++++++++++ pkg/pushsync/hopmemory_origin_test.go | 486 ++++++++++++++++++++++++++ pkg/pushsync/hopmemory_test.go | 344 ++++++++++++++++++ pkg/pushsync/metrics.go | 57 +-- pkg/pushsync/pushsync.go | 133 ++++++- 6 files changed, 1246 insertions(+), 27 deletions(-) create mode 100644 pkg/pushsync/hopmemory.go create mode 100644 pkg/pushsync/hopmemory_origin_test.go create mode 100644 pkg/pushsync/hopmemory_test.go diff --git a/pkg/pushsync/export_test.go b/pkg/pushsync/export_test.go index 0a9fdebdf07..d582c1b5ed2 100644 --- a/pkg/pushsync/export_test.go +++ b/pkg/pushsync/export_test.go @@ -4,7 +4,14 @@ package pushsync -import "github.com/ethersphere/bee/v2/pkg/pushsync/pb" +import ( + "time" + + "github.com/ethersphere/bee/v2/pkg/pushsync/pb" + "github.com/ethersphere/bee/v2/pkg/swarm" + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" +) var ( ProtocolName = protocolName @@ -15,6 +22,51 @@ var ( // CheckReceipt exposes the unexported receipt verification (signature recovery, // overlay derivation, proximity and shallow-receipt logic) for fuzzing. func (ps *PushSync) CheckReceipt(receipt *pb.Receipt) error { - _, err := ps.checkReceipt(receipt) + _, err := ps.checkReceipt(receipt, swarm.ZeroAddress) return err } + +type HopMemory = hopMemory + +func NewHopMemory(now func() time.Time) *HopMemory { return newHopMemory(now) } + +func (m *hopMemory) RecordValid(rad uint8, chunk, peer swarm.Address) { + m.recordValid(rad, chunk, peer) +} + +func (m *hopMemory) RecordShallow(rad uint8, chunk, peer swarm.Address) { + m.recordShallow(rad, chunk, peer) +} +func (m *hopMemory) Forget(rad uint8, chunk, peer swarm.Address) { m.forget(rad, chunk, peer) } +func (m *hopMemory) MarkProbe(rad uint8, chunk swarm.Address) { m.markProbe(rad, chunk) } +func (m *hopMemory) Len() int { return m.len() } + +func (m *hopMemory) View(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { + return m.view(rad, chunk) +} + +// SetHopClock replaces the clock of the first-hop memory. +func (ps *PushSync) SetHopClock(now func() time.Time) { + ps.hops.mtx.Lock() + defer ps.hops.mtx.Unlock() + ps.hops.now = now +} + +// HopRecords returns the number of first-hop records. +func (ps *PushSync) HopRecords() int { return ps.hops.len() } + +func (ps *PushSync) FirstHopCount(source, result string) float64 { + return counterValue(ps.metrics.FirstHop.WithLabelValues(source, result)) +} + +func (ps *PushSync) NeighborhoodKnownShallowCount() float64 { + return counterValue(ps.metrics.NeighborhoodKnownShallow) +} + +func counterValue(c prometheus.Counter) float64 { + var m dto.Metric + if err := c.Write(&m); err != nil { + return -1 + } + return m.GetCounter().GetValue() +} diff --git a/pkg/pushsync/hopmemory.go b/pkg/pushsync/hopmemory.go new file mode 100644 index 00000000000..0887a5a2fb2 --- /dev/null +++ b/pkg/pushsync/hopmemory.go @@ -0,0 +1,197 @@ +// Copyright 2026 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pushsync + +import ( + "sync" + "time" + + "github.com/ethersphere/bee/v2/pkg/swarm" +) + +const ( + // hopShallowPause is the time a first hop is left out for a neighborhood + // after one shallow receipt. It doubles with each shallow receipt in a row. + hopShallowPause = time.Minute + // hopShallowMaxPause is the longest pause of a first hop. + hopShallowMaxPause = 30 * time.Minute + // hopProbeInterval is the shortest time between two probes of one neighborhood. + hopProbeInterval = 30 * time.Second + // hopValidIdle is the time after which a valid record without a new result is removed. + hopValidIdle = 30 * time.Minute +) + +// hopRecord is the last result of one first hop for one neighborhood. +type hopRecord struct { + peer swarm.Address + valid bool + at time.Time + shallow int // shallow receipts in a row +} + +// blockedUntil returns the end of the pause of a shallow record. +func (r *hopRecord) blockedUntil() time.Time { + pause := hopShallowPause + for i := 1; i < r.shallow && pause < hopShallowMaxPause; i++ { + pause *= 2 + } + return r.at.Add(min(pause, hopShallowMaxPause)) +} + +type hopHood struct { + peers map[string]*hopRecord + lastProbe time.Time +} + +// hopMemory remembers, per neighborhood, which first hops gave a valid and +// which gave a shallow receipt, so that an origin does not pay again for a +// result it has already seen. A neighborhood is the set of chunk addresses +// that share the first radius bits. +type hopMemory struct { + mtx sync.Mutex + now func() time.Time + radius uint8 + hoods map[string]*hopHood +} + +func newHopMemory(now func() time.Time) *hopMemory { + return &hopMemory{ + now: now, + hoods: make(map[string]*hopHood), + } +} + +// hoodKey returns the first rad bits of the chunk address. +func hoodKey(rad uint8, chunk swarm.Address) string { + b := chunk.Bytes() + if int(rad) >= len(b)*8 { + return string(b) + } + n, rem := int(rad/8), rad%8 + if rem == 0 { + return string(b[:n]) + } + key := make([]byte, n+1) + copy(key, b[:n]) + key[n] = b[n] & (0xff << (8 - rem)) + return string(key) +} + +// hood returns the neighborhood of the chunk. Records made for another +// radius describe other neighborhoods, so they are dropped first. +// Must be called with the lock held. +func (m *hopMemory) hood(rad uint8, chunk swarm.Address, create bool) *hopHood { + if rad != m.radius { + m.radius = rad + clear(m.hoods) + } + key := hoodKey(rad, chunk) + h := m.hoods[key] + if h == nil && create { + h = &hopHood{peers: make(map[string]*hopRecord)} + m.hoods[key] = h + } + return h +} + +// recordValid notes that the peer gave a valid receipt for the neighborhood of the chunk. +func (m *hopMemory) recordValid(rad uint8, chunk, peer swarm.Address) { + m.mtx.Lock() + defer m.mtx.Unlock() + + m.hood(rad, chunk, true).peers[peer.ByteString()] = &hopRecord{peer: peer, valid: true, at: m.now()} +} + +// recordShallow notes that the peer gave a shallow receipt for the neighborhood of the chunk. +// A shallow receipt that comes while the pause of the peer runs belongs to a +// push that was sent before the pause began, so it does not make the pause longer. +func (m *hopMemory) recordShallow(rad uint8, chunk, peer swarm.Address) { + m.mtx.Lock() + defer m.mtx.Unlock() + + now := m.now() + h := m.hood(rad, chunk, true) + r := h.peers[peer.ByteString()] + if r == nil { + r = &hopRecord{peer: peer} + h.peers[peer.ByteString()] = r + } + if !r.valid && r.shallow > 0 && now.Before(r.blockedUntil()) { + return + } + r.valid = false + r.shallow++ + r.at = now +} + +// forget removes the record of the peer for the neighborhood of the chunk. +// A shallow record whose pause still runs stays: the error belongs to a push +// that was sent before the pause began. +func (m *hopMemory) forget(rad uint8, chunk, peer swarm.Address) { + m.mtx.Lock() + defer m.mtx.Unlock() + + h := m.hood(rad, chunk, false) + if h == nil { + return + } + if r := h.peers[peer.ByteString()]; r != nil && !r.valid && m.now().Before(r.blockedUntil()) { + return + } + delete(h.peers, peer.ByteString()) + if len(h.peers) == 0 { + delete(m.hoods, hoodKey(rad, chunk)) + } +} + +// view returns, for the neighborhood of the chunk, the peers with a usable +// valid record, the peers whose shallow pause still runs, and whether a probe +// of the neighborhood is due. +func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { + m.mtx.Lock() + defer m.mtx.Unlock() + + h := m.hood(rad, chunk, false) + if h == nil { + return nil, nil, true + } + + now := m.now() + for key, r := range h.peers { + switch { + case r.valid && now.Sub(r.at) >= hopValidIdle: + delete(h.peers, key) + case r.valid: + valid = append(valid, r.peer) + case now.Before(r.blockedUntil()): + blocked = append(blocked, r.peer) + } + } + if len(h.peers) == 0 { + delete(m.hoods, hoodKey(rad, chunk)) + } + + return valid, blocked, h.lastProbe.IsZero() || now.Sub(h.lastProbe) >= hopProbeInterval +} + +// markProbe notes that a probe of the neighborhood of the chunk was sent now. +func (m *hopMemory) markProbe(rad uint8, chunk swarm.Address) { + m.mtx.Lock() + defer m.mtx.Unlock() + + m.hood(rad, chunk, true).lastProbe = m.now() +} + +// len returns the number of records. +func (m *hopMemory) len() int { + m.mtx.Lock() + defer m.mtx.Unlock() + + var n int + for _, h := range m.hoods { + n += len(h.peers) + } + return n +} diff --git a/pkg/pushsync/hopmemory_origin_test.go b/pkg/pushsync/hopmemory_origin_test.go new file mode 100644 index 00000000000..105ae209895 --- /dev/null +++ b/pkg/pushsync/hopmemory_origin_test.go @@ -0,0 +1,486 @@ +// Copyright 2026 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pushsync_test + +import ( + "context" + "errors" + "testing" + "time" + + accountingmock "github.com/ethersphere/bee/v2/pkg/accounting/mock" + "github.com/ethersphere/bee/v2/pkg/crypto" + "github.com/ethersphere/bee/v2/pkg/log" + "github.com/ethersphere/bee/v2/pkg/p2p" + "github.com/ethersphere/bee/v2/pkg/p2p/streamtest" + pricermock "github.com/ethersphere/bee/v2/pkg/pricer/mock" + "github.com/ethersphere/bee/v2/pkg/pushsync" + "github.com/ethersphere/bee/v2/pkg/soc" + stabilmock "github.com/ethersphere/bee/v2/pkg/stabilization/mock" + testingc "github.com/ethersphere/bee/v2/pkg/storage/testing" + "github.com/ethersphere/bee/v2/pkg/swarm" + "github.com/ethersphere/bee/v2/pkg/topology" + "github.com/ethersphere/bee/v2/pkg/topology/mock" +) + +const hopRadius = 2 + +// hopNet is an origin with first hops whose receipts the test controls. +// +// The origin knows a first hop by an address that is outside the +// neighborhood of the chunks, so it never sends in parallel, and the order +// of the first hops is the same for every chunk of the neighborhood. The +// node behind a first hop has its own address inside the neighborhood, so it +// stores the chunk and signs a receipt. A receipt is valid when the key of +// that node has an overlay inside the neighborhood, and shallow when not. +type hopNet struct { + t *testing.T + anchor swarm.Address // an address inside the neighborhood of the chunks + topo interface{ Disconnected(p2p.Peer) } + hops []swarm.Address // first hops as the origin knows them, closest first + origin *pushsync.PushSync + recorder *streamtest.Recorder + handlers map[string]p2p.ProtocolSpec + clock *testClock + nodes byte +} + +// flipBits returns a copy of the address with the given bits flipped. +func flipBits(a swarm.Address, bits ...int) swarm.Address { + b := a.Clone().Bytes() + for _, i := range bits { + b[i/8] ^= 0x80 >> (i % 8) + } + return swarm.NewAddress(b) +} + +// hopSigner returns a signer whose overlay is inside (near) or far outside +// the neighborhood of the anchor. +func hopSigner(t *testing.T, anchor swarm.Address, near bool) crypto.Signer { + t.Helper() + + for { + key, err := crypto.GenerateSecp256k1Key() + if err != nil { + t.Fatal(err) + } + signer := crypto.NewDefaultSigner(key) + pubKey, err := signer.PublicKey() + if err != nil { + t.Fatal(err) + } + overlay, err := crypto.NewOverlayAddress(*pubKey, 1, blockHash.Bytes()) + if err != nil { + t.Fatal(err) + } + po := swarm.Proximity(overlay.Bytes(), anchor.Bytes()) + if (near && po > hopRadius) || (!near && po == 0) { + return signer + } + } +} + +// newHopNet makes an origin that knows the given number of first hops. +// A first hop with a lower index is closer to every chunk of the +// neighborhood. insideAOR puts the origin itself inside the neighborhood. +func newHopNet(t *testing.T, insideAOR bool, hops int) *hopNet { + t.Helper() + + n := &hopNet{ + t: t, + anchor: swarm.RandAddress(t), + handlers: make(map[string]p2p.ProtocolSpec), + clock: newTestClock(), + } + + // all first hops differ from the neighborhood in bit 0; the next bits + // set their order + for _, bits := range [][]int{{0}, {0, 2}, {0, 1}}[:hops] { + n.hops = append(n.hops, flipBits(n.anchor, bits...)) + } + + originAddr := flipBits(n.anchor, 0, 255) + if insideAOR { + originAddr = flipBits(n.anchor, 255) + } + + topo := mock.NewTopologyDriver(mock.WithPeers(n.hops...)) + n.topo = topo + + n.recorder = streamtest.New(streamtest.WithPeerProtocols(n.handlers), streamtest.WithBaseAddr(originAddr)) + n.origin = pushsync.New( + originAddr, 1, blockHash.Bytes(), + streamtest.NewRecorderDisconnecter(n.recorder), + &testStorer{chunksPut: make(map[string]swarm.Chunk), chunksReported: make(map[string]int)}, + func() (uint8, error) { return hopRadius, nil }, + topo, true, + func(swarm.Chunk) {}, func(*soc.SOC) {}, + func(ch swarm.Chunk) (swarm.Chunk, error) { return ch, nil }, + log.Noop, accountingmock.NewAccounting(), + pricermock.NewMockService(defaultPrices.price, defaultPrices.peerPrice), + nil, nil, stabilmock.NewSubscriber(true), + ) + t.Cleanup(func() { n.origin.Close() }) + n.origin.SetHopClock(n.clock.Now) + + return n +} + +// setReceipt makes the first hop answer with a valid or a shallow receipt. +func (n *hopNet) setReceipt(hop swarm.Address, valid bool) { + n.t.Helper() + + n.nodes++ + self := n.anchor.Clone().Bytes() + self[swarm.HashSize-1] ^= n.nodes + + node, _ := createPushSyncNodeWithRadius(n.t, swarm.NewAddress(self), defaultPrices, nil, nil, hopSigner(n.t, n.anchor, valid), hopRadius, mock.WithClosestPeerErr(topology.ErrWantSelf)) + n.handlers[hop.String()] = node.Protocol() +} + +// setGone makes every push to the first hop return an error. +func (n *hopNet) setGone(hop swarm.Address) { + delete(n.handlers, hop.String()) +} + +func (n *hopNet) chunk() swarm.Chunk { + n.t.Helper() + return testingc.GenerateValidRandomChunkAt(n.t, n.anchor, hopRadius) +} + +// streams returns the number of pushes the origin sent to the first hop. +func (n *hopNet) streams(hop swarm.Address) int { + recs, _ := n.recorder.Records(hop, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName) + return len(recs) +} + +func (n *hopNet) wantStreams(hop swarm.Address, want int) { + n.t.Helper() + if got := n.streams(hop); got != want { + n.t.Fatalf("first hop %s: got %d pushes, want %d", hop.String()[:4], got, want) + } +} + +func (n *hopNet) wantFirstHop(source, result string, want float64) { + n.t.Helper() + if got := n.origin.FirstHopCount(source, result); got != want { + n.t.Fatalf("first hop metric %s/%s: got %v, want %v", source, result, got, want) + } +} + +func (n *hopNet) push() error { + _, err := n.origin.PushChunkToClosest(context.Background(), n.chunk()) + return err +} + +func (n *hopNet) pushValid() { + n.t.Helper() + if err := n.push(); err != nil { + n.t.Fatalf("got %v, want a valid receipt", err) + } +} + +func (n *hopNet) pushShallow() { + n.t.Helper() + if err := n.push(); !errors.Is(err, pushsync.ErrShallowReceipt) { + n.t.Fatalf("got %v, want %v", err, pushsync.ErrShallowReceipt) + } +} + +// TestOriginPrefersKnownValidPeer checks that the second chunk of a +// neighborhood goes straight to the first hop that gave a valid receipt and +// not to a closer first hop that gave a shallow one. +func TestOriginPrefersKnownValidPeer(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 2) + shallow, valid := n.hops[0], n.hops[1] + n.setReceipt(shallow, false) + n.setReceipt(valid, true) + + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(valid, 1) + + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(valid, 2) + + n.wantFirstHop("unknown", "shallow", 1) + n.wantFirstHop("unknown", "valid", 1) + n.wantFirstHop("known_valid", "valid", 1) +} + +// TestOriginShallowPauseDoubles checks that a first hop that gave a shallow +// receipt is left out for 60s, and for 2 minutes after the next one. +func TestOriginShallowPauseDoubles(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 1) + shallow := n.hops[0] + n.setReceipt(shallow, false) + + n.pushShallow() + n.wantStreams(shallow, 1) + + n.clock.Add(59 * time.Second) + n.pushShallow() + n.wantStreams(shallow, 1) + + n.clock.Add(time.Second) + n.pushShallow() + n.wantStreams(shallow, 2) + + n.clock.Add(119 * time.Second) + n.pushShallow() + n.wantStreams(shallow, 2) + + n.clock.Add(time.Second) + n.pushShallow() + n.wantStreams(shallow, 3) +} + +// TestOriginOtherNeighborhoodNotAffected checks that a shallow receipt for +// one neighborhood does not leave the first hop out for another one. +func TestOriginOtherNeighborhoodNotAffected(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 1) + shallow := n.hops[0] + n.setReceipt(shallow, false) + + n.pushShallow() + n.wantStreams(shallow, 1) + + // a chunk that differs from the neighborhood in bit 1 + other := testingc.GenerateValidRandomChunkAt(t, flipBits(n.anchor, 1), hopRadius) + _, _ = n.origin.PushChunkToClosest(context.Background(), other) + n.wantStreams(shallow, 2) +} + +// TestOriginAllPeersBlocked checks that a chunk ends without a paid send +// when every first hop gave a shallow receipt for its neighborhood a short +// time ago. +func TestOriginAllPeersBlocked(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 2) + n.setReceipt(n.hops[0], false) + n.setReceipt(n.hops[1], false) + + n.pushShallow() + n.wantStreams(n.hops[0], 1) + n.wantStreams(n.hops[1], 1) + + receipt, err := n.origin.PushChunkToClosest(context.Background(), n.chunk()) + if !errors.Is(err, pushsync.ErrShallowReceipt) { + t.Fatalf("got %v, want %v", err, pushsync.ErrShallowReceipt) + } + if receipt != nil { + t.Fatalf("got receipt %v, want none", receipt) + } + n.wantStreams(n.hops[0], 1) + n.wantStreams(n.hops[1], 1) + + if got := n.origin.NeighborhoodKnownShallowCount(); got != 1 { + t.Fatalf("got %v pushes ended without a send, want 1", got) + } +} + +// TestOriginAllBlockedInsideAOR checks that an origin inside the +// neighborhood of the chunk still stores the chunk itself when every first +// hop is left out. +func TestOriginAllBlockedInsideAOR(t *testing.T) { + t.Parallel() + + n := newHopNet(t, true, 1) + n.setReceipt(n.hops[0], false) + + n.pushShallow() + n.wantStreams(n.hops[0], 1) + + if err := n.push(); !errors.Is(err, topology.ErrWantSelf) { + t.Fatalf("got %v, want %v", err, topology.ErrWantSelf) + } + n.wantStreams(n.hops[0], 1) +} + +// TestOriginValidPeerError checks that a first hop with a valid record that +// fails loses the record, and that the chunk still gets a valid receipt +// through another first hop in the same call. +func TestOriginValidPeerError(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 2) + first, second := n.hops[0], n.hops[1] + n.setReceipt(first, true) + n.setReceipt(second, true) + + n.pushValid() + n.wantStreams(first, 1) + n.wantStreams(second, 0) + + n.setGone(first) + + n.pushValid() + n.wantStreams(second, 1) + n.wantFirstHop("known_valid", "error", 1) + n.wantFirstHop("unknown", "valid", 2) + if got := n.origin.HopRecords(); got != 1 { + t.Fatalf("got %d records, want 1", got) + } +} + +// TestOriginSkipsDisconnectedValidPeer checks that a first hop with a valid +// record that is no longer connected is not picked, and that its record is +// removed. +func TestOriginSkipsDisconnectedValidPeer(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 2) + valid, shallow := n.hops[0], n.hops[1] + n.setReceipt(valid, true) + n.setReceipt(shallow, false) + + n.pushValid() + n.wantStreams(valid, 1) + n.wantStreams(shallow, 0) + + n.topo.Disconnected(p2p.Peer{Address: valid}) + + n.pushShallow() + n.wantStreams(valid, 1) + n.wantStreams(shallow, 1) + if got := n.origin.HopRecords(); got != 1 { + t.Fatalf("got %d records, want 1", got) + } +} + +// TestOriginProbe checks that a closer first hop gets one new try after its +// pause, and that the chunk still ends with the valid receipt of the known +// first hop when the try gives a shallow receipt again. +func TestOriginProbe(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 2) + shallow, valid := n.hops[0], n.hops[1] + n.setReceipt(shallow, false) + n.setReceipt(valid, true) + + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(valid, 1) + + // the pause of the closer first hop is not over: no probe + n.clock.Add(59 * time.Second) + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(valid, 2) + + n.clock.Add(time.Second) + n.pushValid() + n.wantStreams(shallow, 2) + n.wantStreams(valid, 3) + n.wantFirstHop("probe", "shallow", 1) + + // the second shallow receipt in a row doubles the pause + n.clock.Add(119 * time.Second) + n.pushValid() + n.wantStreams(shallow, 2) + n.wantStreams(valid, 4) +} + +// TestOriginProbeInterval checks that one neighborhood gets at most one +// probe per 30s, also when more than one closer first hop can be tried. +func TestOriginProbeInterval(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 3) + n.setReceipt(n.hops[0], false) + n.setReceipt(n.hops[1], false) + n.setReceipt(n.hops[2], true) + + n.pushValid() + n.wantStreams(n.hops[0], 1) + n.wantStreams(n.hops[1], 1) + n.wantStreams(n.hops[2], 1) + + // both pauses are over: the first chunk probes the closest first hop + n.clock.Add(time.Minute) + n.pushValid() + n.wantStreams(n.hops[0], 2) + n.wantStreams(n.hops[1], 1) + + // the next chunk comes before the end of the probe interval + n.clock.Add(29 * time.Second) + n.pushValid() + n.wantStreams(n.hops[1], 1) + + n.clock.Add(time.Second) + n.pushValid() + n.wantStreams(n.hops[0], 2) + n.wantStreams(n.hops[1], 2) + n.wantFirstHop("probe", "shallow", 2) + n.wantStreams(n.hops[2], 4) +} + +// TestOriginProbeBecomesValid checks that a closer first hop that gives a +// valid receipt on a probe is used first from then on. +func TestOriginProbeBecomesValid(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 2) + closer, valid := n.hops[0], n.hops[1] + n.setReceipt(closer, false) + n.setReceipt(valid, true) + + n.pushValid() + n.wantStreams(closer, 1) + n.wantStreams(valid, 1) + + n.setReceipt(closer, true) + n.clock.Add(time.Minute) + + n.pushValid() + n.wantStreams(closer, 2) + n.wantStreams(valid, 1) + n.wantFirstHop("probe", "valid", 1) + + n.pushValid() + n.wantStreams(closer, 3) + n.wantStreams(valid, 1) +} + +// TestForwarderDoesNotUseHopMemory checks that only an origin keeps +// first-hop records. +func TestForwarderDoesNotUseHopMemory(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 1) + storer := flipBits(n.anchor, 254) + + storerNode, _ := createPushSyncNodeWithRadius(t, storer, defaultPrices, nil, nil, hopSigner(t, n.anchor, true), hopRadius, mock.WithClosestPeerErr(topology.ErrWantSelf)) + + // the forwarder is outside the neighborhood and knows the storer + forwarderAddr := flipBits(n.anchor, 0, 254) + forwarderRecorder := streamtest.New(streamtest.WithProtocols(storerNode.Protocol()), streamtest.WithBaseAddr(forwarderAddr)) + forwarder, _ := createPushSyncNodeWithRadius(t, forwarderAddr, defaultPrices, forwarderRecorder, nil, nil, hopRadius, mock.WithPeers(storer)) + n.handlers[n.hops[0].String()] = forwarder.Protocol() + + n.pushValid() + + if got := n.streams(n.hops[0]); got != 1 { + t.Fatalf("got %d pushes to the forwarder, want 1", got) + } + if recs, _ := forwarderRecorder.Records(storer, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName); len(recs) != 1 { + t.Fatalf("got %d pushes to the storer, want 1", len(recs)) + } + if got := forwarder.HopRecords(); got != 0 { + t.Fatalf("forwarder has %d first-hop records, want 0", got) + } + if got := n.origin.HopRecords(); got != 1 { + t.Fatalf("origin has %d first-hop records, want 1", got) + } +} diff --git a/pkg/pushsync/hopmemory_test.go b/pkg/pushsync/hopmemory_test.go new file mode 100644 index 00000000000..6eb338db77c --- /dev/null +++ b/pkg/pushsync/hopmemory_test.go @@ -0,0 +1,344 @@ +// Copyright 2026 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pushsync_test + +import ( + "math/rand" + "sync" + "testing" + "time" + + "github.com/ethersphere/bee/v2/pkg/pushsync" + "github.com/ethersphere/bee/v2/pkg/swarm" +) + +// testClock is a clock that a test moves forward by hand. +type testClock struct { + mtx sync.Mutex + t time.Time +} + +func newTestClock() *testClock { + return &testClock{t: time.Unix(1_700_000_000, 0)} +} + +func (c *testClock) Now() time.Time { + c.mtx.Lock() + defer c.mtx.Unlock() + return c.t +} + +func (c *testClock) Add(d time.Duration) { + c.mtx.Lock() + defer c.mtx.Unlock() + c.t = c.t.Add(d) +} + +// hopAddr returns an address that starts with the given bytes. +func hopAddr(prefix ...byte) swarm.Address { + b := make([]byte, swarm.HashSize) + copy(b, prefix) + return swarm.NewAddress(b) +} + +func hasAddr(addrs []swarm.Address, a swarm.Address) bool { + return swarm.ContainsAddress(addrs, a) +} + +func TestHopMemoryRecord(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + ) + + m.RecordValid(10, chunk, peer) + valid, blocked, _ := m.View(10, chunk) + if !hasAddr(valid, peer) || len(blocked) != 0 { + t.Fatalf("after a valid receipt: valid %v blocked %v", valid, blocked) + } + + m.RecordShallow(10, chunk, peer) + valid, blocked, _ = m.View(10, chunk) + if len(valid) != 0 || !hasAddr(blocked, peer) { + t.Fatalf("after a shallow receipt: valid %v blocked %v", valid, blocked) + } + + m.RecordValid(10, chunk, peer) + m.Forget(10, chunk, peer) + valid, blocked, _ = m.View(10, chunk) + if len(valid) != 0 || len(blocked) != 0 { + t.Fatalf("after forget: valid %v blocked %v", valid, blocked) + } + if got := m.Len(); got != 0 { + t.Fatalf("got %d records, want 0", got) + } +} + +// TestHopMemoryShallowDuringPause checks that shallow receipts of pushes that +// were sent before the pause began do not make the pause longer. +func TestHopMemoryShallowDuringPause(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + ) + + // results of pushes that ran in parallel + m.RecordShallow(10, chunk, peer) + m.RecordShallow(10, chunk, peer) + clock.Add(30 * time.Second) + m.RecordShallow(10, chunk, peer) + + clock.Add(30 * time.Second) + if _, blocked, _ := m.View(10, chunk); len(blocked) != 0 { + t.Fatal("peer is blocked 60s after the first shallow receipt") + } +} + +// TestHopMemoryForgetKeepsPause checks that an error of another push does not +// end a pause that still runs. +func TestHopMemoryForgetKeepsPause(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + ) + + m.RecordShallow(10, chunk, peer) + m.Forget(10, chunk, peer) + if _, blocked, _ := m.View(10, chunk); !hasAddr(blocked, peer) { + t.Fatal("forget ended a pause that still runs") + } + + clock.Add(time.Minute) + m.Forget(10, chunk, peer) + if got := m.Len(); got != 0 { + t.Fatalf("got %d records after the pause, want 0", got) + } +} + +func TestHopMemoryPauseDoubles(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + ) + + isBlocked := func() bool { + _, blocked, _ := m.View(10, chunk) + return hasAddr(blocked, peer) + } + + // each step records one more shallow receipt in a row and checks the + // pause that follows it + for i, pause := range []time.Duration{ + time.Minute, + 2 * time.Minute, + 4 * time.Minute, + 8 * time.Minute, + 16 * time.Minute, + 30 * time.Minute, + 30 * time.Minute, + } { + m.RecordShallow(10, chunk, peer) + clock.Add(pause - time.Second) + if !isBlocked() { + t.Fatalf("shallow receipt %d: peer is free one second before the end of a %s pause", i+1, pause) + } + clock.Add(time.Second) + if isBlocked() { + t.Fatalf("shallow receipt %d: peer is blocked after a %s pause", i+1, pause) + } + } + + // a valid receipt starts the count again + m.RecordValid(10, chunk, peer) + m.RecordShallow(10, chunk, peer) + clock.Add(time.Minute) + if isBlocked() { + t.Fatal("peer is blocked 60s after the first shallow receipt that follows a valid one") + } +} + +func TestHopMemoryValidIdle(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + ) + + m.RecordValid(10, chunk, peer) + + clock.Add(29 * time.Minute) + if valid, _, _ := m.View(10, chunk); !hasAddr(valid, peer) { + t.Fatal("valid record is gone after 29 minutes") + } + + clock.Add(time.Minute) + if valid, _, _ := m.View(10, chunk); len(valid) != 0 { + t.Fatal("valid record is still used after 30 minutes without a result") + } + if got := m.Len(); got != 0 { + t.Fatalf("got %d records, want 0", got) + } +} + +func TestHopMemoryProbe(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + other = hopAddr(0x1c, 0x00) + peer = hopAddr(0x10) + ) + + m.RecordValid(10, chunk, peer) + m.RecordValid(10, other, peer) + + if _, _, due := m.View(10, chunk); !due { + t.Fatal("probe is not due for a neighborhood that was never probed") + } + + m.MarkProbe(10, chunk) + if _, _, due := m.View(10, chunk); due { + t.Fatal("probe is due right after a probe") + } + if _, _, due := m.View(10, other); !due { + t.Fatal("probe of one neighborhood changed another neighborhood") + } + + clock.Add(29 * time.Second) + if _, _, due := m.View(10, chunk); due { + t.Fatal("probe is due 29s after a probe") + } + clock.Add(time.Second) + if _, _, due := m.View(10, chunk); !due { + t.Fatal("probe is not due 30s after a probe") + } +} + +func TestHopMemoryNeighborhoodKey(t *testing.T) { + t.Parallel() + + peer := hopAddr(0x10) + + t.Run("radius 10", func(t *testing.T) { + t.Parallel() + + m := pushsync.NewHopMemory(newTestClock().Now) + m.RecordValid(10, hopAddr(0x6b, 0x00), peer) + + // 0x6b3f shares the first 10 bits with 0x6b00, 0x6b40 does not + if valid, _, _ := m.View(10, hopAddr(0x6b, 0x3f, 0xff)); !hasAddr(valid, peer) { + t.Fatal("chunk of the same neighborhood does not see the record") + } + if valid, _, _ := m.View(10, hopAddr(0x6b, 0x40)); len(valid) != 0 { + t.Fatal("chunk of another neighborhood sees the record") + } + if valid, _, _ := m.View(10, hopAddr(0x6a, 0x00)); len(valid) != 0 { + t.Fatal("chunk of another neighborhood sees the record") + } + }) + + t.Run("radius 8", func(t *testing.T) { + t.Parallel() + + m := pushsync.NewHopMemory(newTestClock().Now) + m.RecordValid(8, hopAddr(0x6b, 0x00), peer) + + if valid, _, _ := m.View(8, hopAddr(0x6b, 0xff)); !hasAddr(valid, peer) { + t.Fatal("chunk of the same neighborhood does not see the record") + } + if valid, _, _ := m.View(8, hopAddr(0x6a, 0x00)); len(valid) != 0 { + t.Fatal("chunk of another neighborhood sees the record") + } + }) + + t.Run("radius 0", func(t *testing.T) { + t.Parallel() + + m := pushsync.NewHopMemory(newTestClock().Now) + m.RecordValid(0, hopAddr(0x6b), peer) + + if valid, _, _ := m.View(0, hopAddr(0xff, 0xff)); !hasAddr(valid, peer) { + t.Fatal("at radius 0 every chunk is in one neighborhood") + } + }) +} + +func TestHopMemoryRadiusChange(t *testing.T) { + t.Parallel() + + var ( + m = pushsync.NewHopMemory(newTestClock().Now) + chunk = hopAddr(0x6b, 0x00) + ) + + m.RecordValid(9, chunk, hopAddr(0x10)) + m.RecordShallow(9, chunk, hopAddr(0x20)) + + valid, blocked, _ := m.View(10, chunk) + if len(valid) != 0 || len(blocked) != 0 { + t.Fatalf("records of radius 9 are used at radius 10: valid %v blocked %v", valid, blocked) + } + if got := m.Len(); got != 0 { + t.Fatalf("got %d records, want 0", got) + } +} + +func TestHopMemoryConcurrent(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + wg sync.WaitGroup + ) + + for i := range 64 { + wg.Go(func() { + r := rand.New(rand.NewSource(int64(i))) + for range 200 { + chunk := hopAddr(byte(r.Intn(4)), byte(r.Intn(256))) + peer := hopAddr(byte(r.Intn(8))) + switch r.Intn(6) { + case 0: + m.RecordValid(10, chunk, peer) + case 1: + m.RecordShallow(10, chunk, peer) + case 2: + m.Forget(10, chunk, peer) + case 3: + m.MarkProbe(10, chunk) + case 4: + clock.Add(time.Second) + default: + m.View(10, chunk) + } + } + }) + } + wg.Wait() + + _ = m.Len() +} diff --git a/pkg/pushsync/metrics.go b/pkg/pushsync/metrics.go index 20e1054f76c..0770465fbf3 100644 --- a/pkg/pushsync/metrics.go +++ b/pkg/pushsync/metrics.go @@ -12,26 +12,28 @@ import ( const statusLabel = "status" type metrics struct { - TotalSent prometheus.Counter - TotalReceived prometheus.Counter - TotalHandlerErrors prometheus.Counter - TotalRequests prometheus.Counter - TotalSendAttempts prometheus.Counter - TotalFailedSendAttempts prometheus.Counter - TotalOutgoing prometheus.Counter - TotalOutgoingErrors prometheus.Counter - InvalidStampErrors prometheus.Counter - StampValidationTime *prometheus.HistogramVec - Forwarder prometheus.Counter - Storer prometheus.Counter - TotalHandlerTime *prometheus.HistogramVec - PushToPeerTime *prometheus.HistogramVec - ReceiptDepth *prometheus.CounterVec - ShallowReceiptDepth *prometheus.CounterVec - ShallowReceipt prometheus.Counter - OverdraftRefresh prometheus.Counter - OutOfDepthStoring prometheus.Counter - OriginNoPeersLeft prometheus.Counter + TotalSent prometheus.Counter + TotalReceived prometheus.Counter + TotalHandlerErrors prometheus.Counter + TotalRequests prometheus.Counter + TotalSendAttempts prometheus.Counter + TotalFailedSendAttempts prometheus.Counter + TotalOutgoing prometheus.Counter + TotalOutgoingErrors prometheus.Counter + InvalidStampErrors prometheus.Counter + StampValidationTime *prometheus.HistogramVec + Forwarder prometheus.Counter + Storer prometheus.Counter + TotalHandlerTime *prometheus.HistogramVec + PushToPeerTime *prometheus.HistogramVec + ReceiptDepth *prometheus.CounterVec + ShallowReceiptDepth *prometheus.CounterVec + ShallowReceipt prometheus.Counter + OverdraftRefresh prometheus.Counter + OutOfDepthStoring prometheus.Counter + OriginNoPeersLeft prometheus.Counter + FirstHop *prometheus.CounterVec + NeighborhoodKnownShallow prometheus.Counter } func newMetrics() metrics { @@ -168,6 +170,21 @@ func newMetrics() metrics { Name: "origin_no_peers_left", Help: "Total number of pushes given up by an origin outside the chunk's neighborhood because every peer was already tried or skipped.", }), + FirstHop: prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: m.Namespace, + Subsystem: subsystem, + Name: "first_hop_total", + Help: "Results of origin pushes by the reason the first hop was picked (probe, known_valid, unknown) and the result (valid, shallow, error).", + }, + []string{"source", "result"}, + ), + NeighborhoodKnownShallow: prometheus.NewCounter(prometheus.CounterOpts{ + Namespace: m.Namespace, + Subsystem: subsystem, + Name: "neighborhood_known_shallow", + Help: "Total number of origin pushes that ended without a send because every peer left gave a shallow receipt for the neighborhood a short time ago.", + }), } } diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index df80179ad6b..e14f6a2ef6d 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -97,6 +97,7 @@ type PushSync struct { signer crypto.Signer fullNode bool errSkip *skippeers.List + hops *hopMemory stabilizer stabilization.Subscriber overDraftRefreshLimiter *rate.Limiter } @@ -145,6 +146,7 @@ func New( tracer: tracer, signer: signer, errSkip: skippeers.NewList(time.Minute), + hops: newHopMemory(time.Now), stabilizer: stabilizer, overDraftRefreshLimiter: rate.NewLimiter(rate.Every(time.Second), 1), } @@ -337,6 +339,10 @@ func (ps *PushSync) PushChunkToClosest(ctx context.Context, ch swarm.Chunk) (*Re ps.metrics.TotalOutgoing.Inc() r, err := ps.pushToClosest(ctx, ch, true) if errors.Is(err, ErrShallowReceipt) { + // no receipt when every peer is in a shallow pause and nothing was sent + if r == nil { + return nil, err + } return &Receipt{ Address: swarm.NewAddress(r.Address), Signature: r.Signature, @@ -372,6 +378,8 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo parallelForwards = maxMultiplexForwards shallowReceiptResult *pb.Receipt shallowReceiptPO uint8 + probed bool + hopSources = make(map[string]hopSource) ) if origin { @@ -421,7 +429,18 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo // Non-origin peers store the chunk if the chunk is within depth. // For non-origin peers, if the chunk is not within depth, they may store the chunk if they are the closest peer to the chunk. fullSkip := append(skip.ChunkPeers(idAddress), ps.errSkip.ChunkPeers(idAddress)...) - peer, err := ps.closestPeer(ch.Address(), origin, fullSkip) + + var ( + peer swarm.Address + err error + source hopSource + blockedOnly bool + ) + if origin { + peer, source, blockedOnly, err = ps.originPeer(ch.Address(), rad, fullSkip, &probed) + } else { + peer, err = ps.closestPeer(ch.Address(), origin, fullSkip) + } // ErrWantSelf on a forwarder can mean closer peers exist but are // overdraft-skipped; wait for refresh before falling back to self. @@ -460,6 +479,13 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo if !origin || swarm.Proximity(ps.address.Bytes(), ch.Address().Bytes()) >= rad { return nil, topology.ErrWantSelf } + // Every peer that is left gave a shallow receipt for + // this neighborhood a short time ago: do not pay for + // the same result again. + if blockedOnly { + ps.metrics.NeighborhoodKnownShallow.Inc() + return nil, ErrShallowReceipt + } // Peers were tried and none of them took the chunk, // or they are all skipped for now: retrying right away // cannot succeed, unlike the case of a node that has @@ -472,6 +498,10 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo if shallowReceiptResult != nil { return shallowReceiptResult, ErrShallowReceipt } + if blockedOnly { + ps.metrics.NeighborhoodKnownShallow.Inc() + return nil, ErrShallowReceipt + } ps.logger.Debug("no peers left", "chunk_address", ch.Address(), "error", err) return nil, err } @@ -503,6 +533,9 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo continue } skip.Forever(idAddress, peer) + if origin { + hopSources[peer.ByteString()] = source + } ps.metrics.TotalSendAttempts.Inc() inflight++ @@ -524,10 +557,14 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo // Cache the best (highest-PO) shallow receipt and exhaust the // budget; surface ErrShallowReceipt only when nothing better lands. - switch po, err := ps.checkReceipt(result.receipt); { + switch po, err := ps.checkReceipt(result.receipt, result.peer); { case err == nil: + ps.hops.recordValid(rad, ch.Address(), result.peer) + ps.metrics.FirstHop.WithLabelValues(string(hopSources[result.peer.ByteString()]), "valid").Inc() return result.receipt, nil case errors.Is(err, ErrShallowReceipt): + ps.hops.recordShallow(rad, ch.Address(), result.peer) + ps.metrics.FirstHop.WithLabelValues(string(hopSources[result.peer.ByteString()]), "shallow").Inc() if shallowReceiptResult == nil || po > shallowReceiptPO { shallowReceiptResult = result.receipt shallowReceiptPO = po @@ -538,6 +575,13 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo } } + // A first hop that fails in another way than a shallow receipt + // says nothing about the neighborhood: it is an unknown peer again. + if origin && !errors.Is(result.err, ErrShallowReceipt) { + ps.hops.forget(rad, ch.Address(), result.peer) + ps.metrics.FirstHop.WithLabelValues(string(hopSources[result.peer.ByteString()]), "error").Inc() + } + ps.metrics.TotalFailedSendAttempts.Inc() ps.logger.Debug("could not push to peer", "chunk_address", ch.Address(), "id_address", idAddress, "peer_address", result.peer, "error", result.err) @@ -554,6 +598,85 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo return nil, ErrNoPush } +// hopSource says why an origin picked a first hop. +type hopSource string + +const ( + hopSourceProbe hopSource = "probe" + hopSourceValid hopSource = "known_valid" + hopSourceUnknown hopSource = "unknown" +) + +// originPeer picks the next first hop for an origin. It uses what earlier +// chunks of the same neighborhood showed: +// 1. at most once per call and per hopProbeInterval, a peer that is closer to +// the chunk than every peer with a valid record gets a new try; +// 2. otherwise the closest peer that gave a valid receipt is used; +// 3. otherwise the closest peer that is not in a shallow pause. +// +// blockedOnly is true when the error is topology.ErrNotFound only because of +// peers in a shallow pause. +func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip []swarm.Address, probed *bool) (peer swarm.Address, source hopSource, blockedOnly bool, err error) { + valid, blocked, probeDue := ps.hops.view(rad, chunkAddress) + + // A valid record does not say that the peer is still connected. A peer + // that left is not picked, and its record is removed. + if len(valid) > 0 { + var connected []swarm.Address + _ = ps.topologyDriver.EachConnectedPeer(func(p swarm.Address, _ uint8) (bool, bool, error) { + if swarm.ContainsAddress(valid, p) { + connected = append(connected, p) + } + return false, false, nil + }, topology.Select{}) + for _, p := range valid { + if !swarm.ContainsAddress(connected, p) { + ps.hops.forget(rad, chunkAddress, p) + } + } + valid = connected + } + + best := swarm.ZeroAddress + for _, p := range valid { + if swarm.ContainsAddress(fullSkip, p) { + continue + } + if best.IsZero() { + best = p + continue + } + if closer, _ := p.Closer(chunkAddress, best); closer { + best = p + } + } + + notBlocked := append(append([]swarm.Address{}, fullSkip...), blocked...) + + if !best.IsZero() { + if probeDue && !*probed { + candidate, err := ps.closestPeer(chunkAddress, true, append(notBlocked, valid...)) + if err == nil { + if closer, _ := candidate.Closer(chunkAddress, best); closer { + *probed = true + ps.hops.markProbe(rad, chunkAddress) + return candidate, hopSourceProbe, false, nil + } + } + } + return best, hopSourceValid, false, nil + } + + peer, err = ps.closestPeer(chunkAddress, true, notBlocked) + if errors.Is(err, topology.ErrNotFound) && len(blocked) > 0 { + if _, err := ps.closestPeer(chunkAddress, true, fullSkip); err == nil { + blockedOnly = true + } + } + + return peer, hopSourceUnknown, blockedOnly, err +} + func (ps *PushSync) closestPeer(chunkAddress swarm.Address, origin bool, skipList []swarm.Address) (swarm.Address, error) { includeSelf := ps.fullNode && !origin @@ -623,7 +746,7 @@ func (ps *PushSync) push(parentCtx context.Context, resultChan chan<- receiptRes // checkReceipt validates the receipt and returns the storer-to-chunk PO so // callers can rank shallow receipts; PO is zero on signature errors. Strict // po >= rad: a chunk is not synced until it lands within the AOR. -func (ps *PushSync) checkReceipt(receipt *pb.Receipt) (uint8, error) { +func (ps *PushSync) checkReceipt(receipt *pb.Receipt, firstHop swarm.Address) (uint8, error) { addr := swarm.NewAddress(receipt.Address) publicKey, err := crypto.Recover(receipt.Signature, addr.Bytes()) @@ -646,12 +769,12 @@ func (ps *PushSync) checkReceipt(receipt *pb.Receipt) (uint8, error) { if po < r || uint32(po) < receipt.StorageRadius { ps.metrics.ShallowReceiptDepth.WithLabelValues(strconv.Itoa(int(po))).Inc() ps.metrics.ShallowReceipt.Inc() - ps.logger.Debug("shallow receipt", "chunk_address", addr, "peer_address", peer, "proximity_order", po, "peer_radius", receipt.StorageRadius, "self_radius", r) + ps.logger.Debug("shallow receipt", "chunk_address", addr, "peer_address", peer, "proximity_order", po, "peer_radius", receipt.StorageRadius, "self_radius", r, "first_hop", firstHop) return po, ErrShallowReceipt } ps.metrics.ReceiptDepth.WithLabelValues(strconv.Itoa(int(po))).Inc() - ps.logger.Debug("chunk pushed", "chunk_address", addr, "peer_address", peer, "proximity_order", po) + ps.logger.Debug("chunk pushed", "chunk_address", addr, "peer_address", peer, "proximity_order", po, "first_hop", firstHop) return po, nil } From 27c37ecc9f32ee2867b300c49a3c00825ed93ad3 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Mon, 16 Nov 2026 13:22:16 +0100 Subject: [PATCH 02/16] fix(pushsync): expire idle shallow records and wait when all peers are paused --- pkg/pushsync/hopmemory.go | 11 +++++ pkg/pushsync/hopmemory_origin_test.go | 26 ++++++++++-- pkg/pushsync/hopmemory_test.go | 61 +++++++++++++++++++++++++++ pkg/pushsync/pushsync.go | 14 +++--- 4 files changed, 102 insertions(+), 10 deletions(-) diff --git a/pkg/pushsync/hopmemory.go b/pkg/pushsync/hopmemory.go index 0887a5a2fb2..8b3b6b3c2d5 100644 --- a/pkg/pushsync/hopmemory.go +++ b/pkg/pushsync/hopmemory.go @@ -21,6 +21,11 @@ const ( hopProbeInterval = 30 * time.Second // hopValidIdle is the time after which a valid record without a new result is removed. hopValidIdle = 30 * time.Minute + // hopShallowIdle is the time after which a shallow record without a new + // shallow receipt is removed. It is longer than the longest pause, so + // that a shallow receipt that comes right after a pause still counts as + // one more in a row. + hopShallowIdle = 2 * hopShallowMaxPause ) // hopRecord is the last result of one first hop for one neighborhood. @@ -121,6 +126,10 @@ func (m *hopMemory) recordShallow(rad uint8, chunk, peer swarm.Address) { if !r.valid && r.shallow > 0 && now.Before(r.blockedUntil()) { return } + // a record that view did not remove yet + if !r.valid && now.Sub(r.at) >= hopShallowIdle { + r.shallow = 0 + } r.valid = false r.shallow++ r.at = now @@ -167,6 +176,8 @@ func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm valid = append(valid, r.peer) case now.Before(r.blockedUntil()): blocked = append(blocked, r.peer) + case now.Sub(r.at) >= hopShallowIdle: + delete(h.peers, key) } } if len(h.peers) == 0 { diff --git a/pkg/pushsync/hopmemory_origin_test.go b/pkg/pushsync/hopmemory_origin_test.go index 105ae209895..fd2185d05f5 100644 --- a/pkg/pushsync/hopmemory_origin_test.go +++ b/pkg/pushsync/hopmemory_origin_test.go @@ -189,6 +189,15 @@ func (n *hopNet) pushShallow() { } } +// pushPaused pushes a chunk and wants the result of an origin that sent +// nothing because every first hop is in a shallow pause. +func (n *hopNet) pushPaused() { + n.t.Helper() + if err := n.push(); !errors.Is(err, pushsync.ErrNeighborhoodShallow) { + n.t.Fatalf("got %v, want %v", err, pushsync.ErrNeighborhoodShallow) + } +} + // TestOriginPrefersKnownValidPeer checks that the second chunk of a // neighborhood goes straight to the first hop that gave a valid receipt and // not to a closer first hop that gave a shallow one. @@ -226,7 +235,7 @@ func TestOriginShallowPauseDoubles(t *testing.T) { n.wantStreams(shallow, 1) n.clock.Add(59 * time.Second) - n.pushShallow() + n.pushPaused() n.wantStreams(shallow, 1) n.clock.Add(time.Second) @@ -234,7 +243,7 @@ func TestOriginShallowPauseDoubles(t *testing.T) { n.wantStreams(shallow, 2) n.clock.Add(119 * time.Second) - n.pushShallow() + n.pushPaused() n.wantStreams(shallow, 2) n.clock.Add(time.Second) @@ -274,9 +283,18 @@ func TestOriginAllPeersBlocked(t *testing.T) { n.wantStreams(n.hops[0], 1) n.wantStreams(n.hops[1], 1) + // nothing is sent, so the result must not look like a shallow receipt: + // the pusher counts those against the retry budget of the chunk. It + // must look like "no peer for now", which the callers wait out. receipt, err := n.origin.PushChunkToClosest(context.Background(), n.chunk()) - if !errors.Is(err, pushsync.ErrShallowReceipt) { - t.Fatalf("got %v, want %v", err, pushsync.ErrShallowReceipt) + if !errors.Is(err, pushsync.ErrNeighborhoodShallow) { + t.Fatalf("got %v, want %v", err, pushsync.ErrNeighborhoodShallow) + } + if errors.Is(err, pushsync.ErrShallowReceipt) { + t.Fatalf("got %v, which is a shallow receipt error", err) + } + if !errors.Is(err, topology.ErrNotFound) { + t.Fatalf("got %v, which is not %v", err, topology.ErrNotFound) } if receipt != nil { t.Fatalf("got receipt %v, want none", receipt) diff --git a/pkg/pushsync/hopmemory_test.go b/pkg/pushsync/hopmemory_test.go index 6eb338db77c..1b2bc15059e 100644 --- a/pkg/pushsync/hopmemory_test.go +++ b/pkg/pushsync/hopmemory_test.go @@ -175,6 +175,67 @@ func TestHopMemoryPauseDoubles(t *testing.T) { } } +// TestHopMemoryShallowIdle checks that a shallow record is removed one hour +// after its last shallow receipt, so that records of peers that are no longer +// picked do not stay in the memory. +func TestHopMemoryShallowIdle(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + ) + + for i := range 50 { + m.RecordShallow(10, chunk, hopAddr(0x10, byte(i))) + } + + clock.Add(time.Hour - time.Second) + m.View(10, chunk) + if got := m.Len(); got != 50 { + t.Fatalf("got %d records one second before the end of the idle time, want 50", got) + } + + clock.Add(time.Second) + m.View(10, chunk) + if got := m.Len(); got != 0 { + t.Fatalf("got %d records after the idle time, want 0", got) + } +} + +// TestHopMemoryShallowCountRestarts checks that a shallow receipt that comes +// more than one hour after the last one starts the count again, also when +// nothing read the neighborhood in between. +func TestHopMemoryShallowCountRestarts(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + ) + + isBlocked := func() bool { + _, blocked, _ := m.View(10, chunk) + return hasAddr(blocked, peer) + } + + m.RecordShallow(10, chunk, peer) + clock.Add(time.Hour) + m.RecordShallow(10, chunk, peer) + + clock.Add(time.Minute - time.Second) + if !isBlocked() { + t.Fatal("peer is free one second before the end of a 1m0s pause") + } + clock.Add(time.Second) + if isBlocked() { + t.Fatal("peer is blocked after a 1m0s pause: the count did not start again") + } +} + func TestHopMemoryValidIdle(t *testing.T) { t.Parallel() diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index e14f6a2ef6d..b50d3b70105 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -61,6 +61,12 @@ var ( ErrOutOfDepthStoring = errors.New("storing outside of the neighborhood") ErrWarmup = errors.New("node warmup time not complete") ErrShallowReceipt = errors.New("shallow receipt") + // ErrNeighborhoodShallow is returned by an origin that did not send the + // chunk because every peer that is left gave a shallow receipt for the + // neighborhood a short time ago. It wraps topology.ErrNotFound: for the + // caller there is no peer for the chunk for now, and it must wait and + // try again, without counting the try against the chunk. + ErrNeighborhoodShallow = fmt.Errorf("every peer is in a shallow pause for the neighborhood: %w", topology.ErrNotFound) ) type PushSyncer interface { @@ -339,10 +345,6 @@ func (ps *PushSync) PushChunkToClosest(ctx context.Context, ch swarm.Chunk) (*Re ps.metrics.TotalOutgoing.Inc() r, err := ps.pushToClosest(ctx, ch, true) if errors.Is(err, ErrShallowReceipt) { - // no receipt when every peer is in a shallow pause and nothing was sent - if r == nil { - return nil, err - } return &Receipt{ Address: swarm.NewAddress(r.Address), Signature: r.Signature, @@ -484,7 +486,7 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo // the same result again. if blockedOnly { ps.metrics.NeighborhoodKnownShallow.Inc() - return nil, ErrShallowReceipt + return nil, ErrNeighborhoodShallow } // Peers were tried and none of them took the chunk, // or they are all skipped for now: retrying right away @@ -500,7 +502,7 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo } if blockedOnly { ps.metrics.NeighborhoodKnownShallow.Inc() - return nil, ErrShallowReceipt + return nil, ErrNeighborhoodShallow } ps.logger.Debug("no peers left", "chunk_address", ch.Address(), "error", err) return nil, err From 85f1d65c5cf0351be57fb2b167524bf6ecd3aa11 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Mon, 16 Nov 2026 21:32:06 +0100 Subject: [PATCH 03/16] fix(retrieval): ask closer peers before far healthy peers at the origin --- pkg/retrieval/retrieval.go | 7 ++++ pkg/retrieval/retrieval_test.go | 64 +++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/pkg/retrieval/retrieval.go b/pkg/retrieval/retrieval.go index 046fff39086..e04d973cbec 100644 --- a/pkg/retrieval/retrieval.go +++ b/pkg/retrieval/retrieval.go @@ -404,6 +404,13 @@ func (s *Service) closestPeer(addr swarm.Address, skipPeers []swarm.Address, all } if allowUpstream { + // The origin has many attempts, and a healthy peer that is far from the + // chunk must not use them before a peer of a higher proximity order is + // asked. Health decides only between peers of the same proximity order. + nearest, err := s.peerSuggester.ClosestPeer(addr, false, topology.Select{Reachable: true}, skipPeers...) + if err == nil && swarm.Proximity(nearest.Bytes(), addr.Bytes()) > swarm.Proximity(closest.Bytes(), addr.Bytes()) { + return nearest, nil + } return closest, nil } diff --git a/pkg/retrieval/retrieval_test.go b/pkg/retrieval/retrieval_test.go index 436b9e97b1a..f43f38ba850 100644 --- a/pkg/retrieval/retrieval_test.go +++ b/pkg/retrieval/retrieval_test.go @@ -719,3 +719,67 @@ func createRetrieval( t.Cleanup(func() { ret.Close() }) return ret } + +// TestClosestPeerOriginProximityBeforeHealth checks that the origin does not +// ask a healthy peer before a peer of a higher proximity order to the chunk +// that is not healthy. +func TestClosestPeerOriginProximityBeforeHealth(t *testing.T) { + t.Parallel() + + var ( + base = swarm.MustParseHexAddress("ff00000000000000000000000000000000000000000000000000000000000000") + chunk = swarm.MustParseHexAddress("0100000000000000000000000000000000000000000000000000000000000000") + closer = swarm.MustParseHexAddress("0300000000000000000000000000000000000000000000000000000000000000") // PO 6, not healthy + samePO = swarm.MustParseHexAddress("0200000000000000000000000000000000000000000000000000000000000000") // PO 6, healthy + far = swarm.MustParseHexAddress("8000000000000000000000000000000000000000000000000000000000000000") // PO 0, healthy + unhealthy = map[string]bool{closer.ByteString(): true} + ) + + driver := func(peers ...swarm.Address) topology.ClosestPeerer { + return topologymock.NewTopologyDriver(topologymock.WithClosestPeerFunc( + func(addr swarm.Address, _ bool, filter topology.Select, skip ...swarm.Address) (swarm.Address, error) { + best := swarm.ZeroAddress + for _, p := range peers { + if (filter.Healthy && unhealthy[p.ByteString()]) || swarm.ContainsAddress(skip, p) { + continue + } + if best.IsZero() { + best = p + continue + } + if ok, _ := p.Closer(addr, best); ok { + best = p + } + } + if best.IsZero() { + return swarm.ZeroAddress, topology.ErrNotFound + } + return best, nil + })) + } + + for _, tc := range []struct { + name string + peers []swarm.Address + origin bool + want swarm.Address + }{ + {name: "origin, closer peer is not healthy", peers: []swarm.Address{far, closer}, origin: true, want: closer}, + {name: "origin, same proximity order", peers: []swarm.Address{samePO, closer}, origin: true, want: samePO}, + {name: "forwarder, closer peer is not healthy", peers: []swarm.Address{far, closer}, origin: false, want: far}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + ret := createRetrieval(t, base, nil, nil, driver(tc.peers...), log.Noop, nil, nil, nil, false) + + got, err := ret.ClosestPeer(chunk, nil, tc.origin) + if err != nil { + t.Fatal(err) + } + if !got.Equal(tc.want) { + t.Fatalf("want %s, got %s", tc.want, got) + } + }) + } +} From 19b84d4dee7c8ad06ab1f13b41b802666a60905f Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Wed, 18 Nov 2026 09:59:57 +0100 Subject: [PATCH 04/16] fix(retrieval): ask closer peers before far healthy peers at forwarders --- pkg/retrieval/retrieval.go | 15 ++++++++------- pkg/retrieval/retrieval_test.go | 28 +++++++++++++++++++++------- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/pkg/retrieval/retrieval.go b/pkg/retrieval/retrieval.go index e04d973cbec..9dd910ea685 100644 --- a/pkg/retrieval/retrieval.go +++ b/pkg/retrieval/retrieval.go @@ -403,14 +403,15 @@ func (s *Service) closestPeer(addr swarm.Address, skipPeers []swarm.Address, all return swarm.Address{}, err } + // A healthy peer that is far from the chunk must not be asked before a + // peer of a higher proximity order. Health decides only between peers of + // the same proximity order. + nearest, err := s.peerSuggester.ClosestPeer(addr, false, topology.Select{Reachable: true}, skipPeers...) + if err == nil && swarm.Proximity(nearest.Bytes(), addr.Bytes()) > swarm.Proximity(closest.Bytes(), addr.Bytes()) { + closest = nearest + } + if allowUpstream { - // The origin has many attempts, and a healthy peer that is far from the - // chunk must not use them before a peer of a higher proximity order is - // asked. Health decides only between peers of the same proximity order. - nearest, err := s.peerSuggester.ClosestPeer(addr, false, topology.Select{Reachable: true}, skipPeers...) - if err == nil && swarm.Proximity(nearest.Bytes(), addr.Bytes()) > swarm.Proximity(closest.Bytes(), addr.Bytes()) { - return nearest, nil - } return closest, nil } diff --git a/pkg/retrieval/retrieval_test.go b/pkg/retrieval/retrieval_test.go index f43f38ba850..5441a091fa2 100644 --- a/pkg/retrieval/retrieval_test.go +++ b/pkg/retrieval/retrieval_test.go @@ -720,14 +720,15 @@ func createRetrieval( return ret } -// TestClosestPeerOriginProximityBeforeHealth checks that the origin does not -// ask a healthy peer before a peer of a higher proximity order to the chunk -// that is not healthy. -func TestClosestPeerOriginProximityBeforeHealth(t *testing.T) { +// TestClosestPeerProximityBeforeHealth checks that neither the origin nor a +// forwarder asks a healthy peer before a peer of a higher proximity order to +// the chunk that is not healthy. +func TestClosestPeerProximityBeforeHealth(t *testing.T) { t.Parallel() var ( base = swarm.MustParseHexAddress("ff00000000000000000000000000000000000000000000000000000000000000") + nearBase = swarm.MustParseHexAddress("0180000000000000000000000000000000000000000000000000000000000000") // PO 8 chunk = swarm.MustParseHexAddress("0100000000000000000000000000000000000000000000000000000000000000") closer = swarm.MustParseHexAddress("0300000000000000000000000000000000000000000000000000000000000000") // PO 6, not healthy samePO = swarm.MustParseHexAddress("0200000000000000000000000000000000000000000000000000000000000000") // PO 6, healthy @@ -760,20 +761,33 @@ func TestClosestPeerOriginProximityBeforeHealth(t *testing.T) { for _, tc := range []struct { name string + base swarm.Address peers []swarm.Address origin bool - want swarm.Address + want swarm.Address // zero when no peer is expected }{ {name: "origin, closer peer is not healthy", peers: []swarm.Address{far, closer}, origin: true, want: closer}, {name: "origin, same proximity order", peers: []swarm.Address{samePO, closer}, origin: true, want: samePO}, - {name: "forwarder, closer peer is not healthy", peers: []swarm.Address{far, closer}, origin: false, want: far}, + {name: "forwarder, closer peer is not healthy", peers: []swarm.Address{far, closer}, origin: false, want: closer}, + {name: "forwarder, same proximity order", peers: []swarm.Address{samePO, closer}, origin: false, want: samePO}, + {name: "forwarder, closer to the chunk than every peer", base: nearBase, peers: []swarm.Address{far, closer}, origin: false}, + {name: "origin, closer to the chunk than every peer", base: nearBase, peers: []swarm.Address{far, closer}, origin: true, want: closer}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - ret := createRetrieval(t, base, nil, nil, driver(tc.peers...), log.Noop, nil, nil, nil, false) + if tc.base.IsZero() { + tc.base = base + } + ret := createRetrieval(t, tc.base, nil, nil, driver(tc.peers...), log.Noop, nil, nil, nil, false) got, err := ret.ClosestPeer(chunk, nil, tc.origin) + if tc.want.IsZero() { + if !errors.Is(err, topology.ErrNotFound) { + t.Fatalf("want %v, got peer %s, error %v", topology.ErrNotFound, got, err) + } + return + } if err != nil { t.Fatal(err) } From ff11ee88850fde1c90650f2e2ae464d8c408afab Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Wed, 18 Nov 2026 13:58:05 +0100 Subject: [PATCH 05/16] chore(pushsync): shorten comments --- pkg/pushsync/hopmemory.go | 50 ++++++++++-------------- pkg/pushsync/hopmemory_origin_test.go | 56 +++++++++++---------------- pkg/pushsync/hopmemory_test.go | 18 ++++----- pkg/pushsync/pushsync.go | 32 ++++++--------- pkg/retrieval/retrieval.go | 5 +-- pkg/retrieval/retrieval_test.go | 5 +-- 6 files changed, 65 insertions(+), 101 deletions(-) diff --git a/pkg/pushsync/hopmemory.go b/pkg/pushsync/hopmemory.go index 8b3b6b3c2d5..0bcced1250f 100644 --- a/pkg/pushsync/hopmemory.go +++ b/pkg/pushsync/hopmemory.go @@ -12,19 +12,15 @@ import ( ) const ( - // hopShallowPause is the time a first hop is left out for a neighborhood - // after one shallow receipt. It doubles with each shallow receipt in a row. - hopShallowPause = time.Minute - // hopShallowMaxPause is the longest pause of a first hop. + // hopShallowPause is the pause of a first hop after a shallow receipt. + // It doubles with each shallow receipt in a row, up to hopShallowMaxPause. + hopShallowPause = time.Minute hopShallowMaxPause = 30 * time.Minute - // hopProbeInterval is the shortest time between two probes of one neighborhood. + // hopProbeInterval is the shortest time between two probes of a neighborhood. hopProbeInterval = 30 * time.Second - // hopValidIdle is the time after which a valid record without a new result is removed. - hopValidIdle = 30 * time.Minute - // hopShallowIdle is the time after which a shallow record without a new - // shallow receipt is removed. It is longer than the longest pause, so - // that a shallow receipt that comes right after a pause still counts as - // one more in a row. + // hopValidIdle and hopShallowIdle are the times after which a record + // without a new result is removed. + hopValidIdle = 30 * time.Minute hopShallowIdle = 2 * hopShallowMaxPause ) @@ -50,10 +46,8 @@ type hopHood struct { lastProbe time.Time } -// hopMemory remembers, per neighborhood, which first hops gave a valid and -// which gave a shallow receipt, so that an origin does not pay again for a -// result it has already seen. A neighborhood is the set of chunk addresses -// that share the first radius bits. +// hopMemory keeps the last receipt result of each first hop per neighborhood +// (the chunk addresses that share the first radius bits). type hopMemory struct { mtx sync.Mutex now func() time.Time @@ -84,9 +78,8 @@ func hoodKey(rad uint8, chunk swarm.Address) string { return string(key) } -// hood returns the neighborhood of the chunk. Records made for another -// radius describe other neighborhoods, so they are dropped first. -// Must be called with the lock held. +// hood returns the neighborhood of the chunk. A radius change drops all +// records. Must be called with the lock held. func (m *hopMemory) hood(rad uint8, chunk swarm.Address, create bool) *hopHood { if rad != m.radius { m.radius = rad @@ -101,7 +94,7 @@ func (m *hopMemory) hood(rad uint8, chunk swarm.Address, create bool) *hopHood { return h } -// recordValid notes that the peer gave a valid receipt for the neighborhood of the chunk. +// recordValid stores a valid receipt of the peer. func (m *hopMemory) recordValid(rad uint8, chunk, peer swarm.Address) { m.mtx.Lock() defer m.mtx.Unlock() @@ -109,9 +102,8 @@ func (m *hopMemory) recordValid(rad uint8, chunk, peer swarm.Address) { m.hood(rad, chunk, true).peers[peer.ByteString()] = &hopRecord{peer: peer, valid: true, at: m.now()} } -// recordShallow notes that the peer gave a shallow receipt for the neighborhood of the chunk. -// A shallow receipt that comes while the pause of the peer runs belongs to a -// push that was sent before the pause began, so it does not make the pause longer. +// recordShallow stores a shallow receipt of the peer. A receipt that comes +// during the pause of the peer does not make the pause longer. func (m *hopMemory) recordShallow(rad uint8, chunk, peer swarm.Address) { m.mtx.Lock() defer m.mtx.Unlock() @@ -126,7 +118,7 @@ func (m *hopMemory) recordShallow(rad uint8, chunk, peer swarm.Address) { if !r.valid && r.shallow > 0 && now.Before(r.blockedUntil()) { return } - // a record that view did not remove yet + // idle record that view did not remove yet if !r.valid && now.Sub(r.at) >= hopShallowIdle { r.shallow = 0 } @@ -135,9 +127,8 @@ func (m *hopMemory) recordShallow(rad uint8, chunk, peer swarm.Address) { r.at = now } -// forget removes the record of the peer for the neighborhood of the chunk. -// A shallow record whose pause still runs stays: the error belongs to a push -// that was sent before the pause began. +// forget removes the record of the peer, except a shallow record whose +// pause still runs. func (m *hopMemory) forget(rad uint8, chunk, peer swarm.Address) { m.mtx.Lock() defer m.mtx.Unlock() @@ -155,9 +146,8 @@ func (m *hopMemory) forget(rad uint8, chunk, peer swarm.Address) { } } -// view returns, for the neighborhood of the chunk, the peers with a usable -// valid record, the peers whose shallow pause still runs, and whether a probe -// of the neighborhood is due. +// view returns the peers with a valid record, the peers in a shallow pause, +// and whether a probe of the neighborhood is due. func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { m.mtx.Lock() defer m.mtx.Unlock() @@ -187,7 +177,7 @@ func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm return valid, blocked, h.lastProbe.IsZero() || now.Sub(h.lastProbe) >= hopProbeInterval } -// markProbe notes that a probe of the neighborhood of the chunk was sent now. +// markProbe stores the time of a probe of the neighborhood. func (m *hopMemory) markProbe(rad uint8, chunk swarm.Address) { m.mtx.Lock() defer m.mtx.Unlock() diff --git a/pkg/pushsync/hopmemory_origin_test.go b/pkg/pushsync/hopmemory_origin_test.go index fd2185d05f5..232c7ae1a53 100644 --- a/pkg/pushsync/hopmemory_origin_test.go +++ b/pkg/pushsync/hopmemory_origin_test.go @@ -28,13 +28,10 @@ import ( const hopRadius = 2 // hopNet is an origin with first hops whose receipts the test controls. -// -// The origin knows a first hop by an address that is outside the -// neighborhood of the chunks, so it never sends in parallel, and the order -// of the first hops is the same for every chunk of the neighborhood. The -// node behind a first hop has its own address inside the neighborhood, so it -// stores the chunk and signs a receipt. A receipt is valid when the key of -// that node has an overlay inside the neighborhood, and shallow when not. +// The origin knows each first hop by an address outside the neighborhood, so +// the order of the first hops is the same for every chunk. The node behind a +// first hop signs with a key whose overlay is inside the neighborhood (valid +// receipt) or outside of it (shallow receipt). type hopNet struct { t *testing.T anchor swarm.Address // an address inside the neighborhood of the chunks @@ -82,9 +79,8 @@ func hopSigner(t *testing.T, anchor swarm.Address, near bool) crypto.Signer { } } -// newHopNet makes an origin that knows the given number of first hops. -// A first hop with a lower index is closer to every chunk of the -// neighborhood. insideAOR puts the origin itself inside the neighborhood. +// newHopNet makes an origin with n first hops; a lower index is closer to +// the chunks. insideAOR puts the origin inside the neighborhood. func newHopNet(t *testing.T, insideAOR bool, hops int) *hopNet { t.Helper() @@ -189,8 +185,7 @@ func (n *hopNet) pushShallow() { } } -// pushPaused pushes a chunk and wants the result of an origin that sent -// nothing because every first hop is in a shallow pause. +// pushPaused pushes a chunk and wants ErrNeighborhoodShallow. func (n *hopNet) pushPaused() { n.t.Helper() if err := n.push(); !errors.Is(err, pushsync.ErrNeighborhoodShallow) { @@ -198,9 +193,8 @@ func (n *hopNet) pushPaused() { } } -// TestOriginPrefersKnownValidPeer checks that the second chunk of a -// neighborhood goes straight to the first hop that gave a valid receipt and -// not to a closer first hop that gave a shallow one. +// TestOriginPrefersKnownValidPeer checks that the next chunk goes to the +// first hop with a valid record, not to a closer one that gave a shallow receipt. func TestOriginPrefersKnownValidPeer(t *testing.T) { t.Parallel() @@ -269,9 +263,8 @@ func TestOriginOtherNeighborhoodNotAffected(t *testing.T) { n.wantStreams(shallow, 2) } -// TestOriginAllPeersBlocked checks that a chunk ends without a paid send -// when every first hop gave a shallow receipt for its neighborhood a short -// time ago. +// TestOriginAllPeersBlocked checks that nothing is sent when every first +// hop is in a shallow pause. func TestOriginAllPeersBlocked(t *testing.T) { t.Parallel() @@ -283,9 +276,8 @@ func TestOriginAllPeersBlocked(t *testing.T) { n.wantStreams(n.hops[0], 1) n.wantStreams(n.hops[1], 1) - // nothing is sent, so the result must not look like a shallow receipt: - // the pusher counts those against the retry budget of the chunk. It - // must look like "no peer for now", which the callers wait out. + // the result must be "no peer for now", not a shallow receipt, which + // the pusher counts against the retry budget of the chunk receipt, err := n.origin.PushChunkToClosest(context.Background(), n.chunk()) if !errors.Is(err, pushsync.ErrNeighborhoodShallow) { t.Fatalf("got %v, want %v", err, pushsync.ErrNeighborhoodShallow) @@ -308,8 +300,7 @@ func TestOriginAllPeersBlocked(t *testing.T) { } // TestOriginAllBlockedInsideAOR checks that an origin inside the -// neighborhood of the chunk still stores the chunk itself when every first -// hop is left out. +// neighborhood stores the chunk itself when every first hop is paused. func TestOriginAllBlockedInsideAOR(t *testing.T) { t.Parallel() @@ -325,9 +316,8 @@ func TestOriginAllBlockedInsideAOR(t *testing.T) { n.wantStreams(n.hops[0], 1) } -// TestOriginValidPeerError checks that a first hop with a valid record that -// fails loses the record, and that the chunk still gets a valid receipt -// through another first hop in the same call. +// TestOriginValidPeerError checks that an error removes a valid record and +// that the chunk gets a valid receipt from another first hop in the same call. func TestOriginValidPeerError(t *testing.T) { t.Parallel() @@ -351,9 +341,8 @@ func TestOriginValidPeerError(t *testing.T) { } } -// TestOriginSkipsDisconnectedValidPeer checks that a first hop with a valid -// record that is no longer connected is not picked, and that its record is -// removed. +// TestOriginSkipsDisconnectedValidPeer checks that a disconnected first hop +// with a valid record is not picked and loses the record. func TestOriginSkipsDisconnectedValidPeer(t *testing.T) { t.Parallel() @@ -376,9 +365,8 @@ func TestOriginSkipsDisconnectedValidPeer(t *testing.T) { } } -// TestOriginProbe checks that a closer first hop gets one new try after its -// pause, and that the chunk still ends with the valid receipt of the known -// first hop when the try gives a shallow receipt again. +// TestOriginProbe checks that a closer first hop is probed after its pause +// and that the chunk still gets the valid receipt of the known first hop. func TestOriginProbe(t *testing.T) { t.Parallel() @@ -410,8 +398,8 @@ func TestOriginProbe(t *testing.T) { n.wantStreams(valid, 4) } -// TestOriginProbeInterval checks that one neighborhood gets at most one -// probe per 30s, also when more than one closer first hop can be tried. +// TestOriginProbeInterval checks that a neighborhood gets at most one probe +// per 30s. func TestOriginProbeInterval(t *testing.T) { t.Parallel() diff --git a/pkg/pushsync/hopmemory_test.go b/pkg/pushsync/hopmemory_test.go index 1b2bc15059e..2c2f0100e5b 100644 --- a/pkg/pushsync/hopmemory_test.go +++ b/pkg/pushsync/hopmemory_test.go @@ -80,8 +80,8 @@ func TestHopMemoryRecord(t *testing.T) { } } -// TestHopMemoryShallowDuringPause checks that shallow receipts of pushes that -// were sent before the pause began do not make the pause longer. +// TestHopMemoryShallowDuringPause checks that a shallow receipt during a +// pause does not make the pause longer. func TestHopMemoryShallowDuringPause(t *testing.T) { t.Parallel() @@ -104,8 +104,7 @@ func TestHopMemoryShallowDuringPause(t *testing.T) { } } -// TestHopMemoryForgetKeepsPause checks that an error of another push does not -// end a pause that still runs. +// TestHopMemoryForgetKeepsPause checks that forget does not end a pause. func TestHopMemoryForgetKeepsPause(t *testing.T) { t.Parallel() @@ -144,8 +143,7 @@ func TestHopMemoryPauseDoubles(t *testing.T) { return hasAddr(blocked, peer) } - // each step records one more shallow receipt in a row and checks the - // pause that follows it + // each step adds one shallow receipt in a row for i, pause := range []time.Duration{ time.Minute, 2 * time.Minute, @@ -176,8 +174,7 @@ func TestHopMemoryPauseDoubles(t *testing.T) { } // TestHopMemoryShallowIdle checks that a shallow record is removed one hour -// after its last shallow receipt, so that records of peers that are no longer -// picked do not stay in the memory. +// after its last shallow receipt. func TestHopMemoryShallowIdle(t *testing.T) { t.Parallel() @@ -204,9 +201,8 @@ func TestHopMemoryShallowIdle(t *testing.T) { } } -// TestHopMemoryShallowCountRestarts checks that a shallow receipt that comes -// more than one hour after the last one starts the count again, also when -// nothing read the neighborhood in between. +// TestHopMemoryShallowCountRestarts checks that the count starts again after +// one hour without a shallow receipt, also when view was not called. func TestHopMemoryShallowCountRestarts(t *testing.T) { t.Parallel() diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index b50d3b70105..90bc4abe37e 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -61,11 +61,9 @@ var ( ErrOutOfDepthStoring = errors.New("storing outside of the neighborhood") ErrWarmup = errors.New("node warmup time not complete") ErrShallowReceipt = errors.New("shallow receipt") - // ErrNeighborhoodShallow is returned by an origin that did not send the - // chunk because every peer that is left gave a shallow receipt for the - // neighborhood a short time ago. It wraps topology.ErrNotFound: for the - // caller there is no peer for the chunk for now, and it must wait and - // try again, without counting the try against the chunk. + // ErrNeighborhoodShallow is returned by an origin that sent nothing + // because every peer left is in a shallow pause for the neighborhood. + // It wraps topology.ErrNotFound so that callers wait and try again. ErrNeighborhoodShallow = fmt.Errorf("every peer is in a shallow pause for the neighborhood: %w", topology.ErrNotFound) ) @@ -481,9 +479,7 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo if !origin || swarm.Proximity(ps.address.Bytes(), ch.Address().Bytes()) >= rad { return nil, topology.ErrWantSelf } - // Every peer that is left gave a shallow receipt for - // this neighborhood a short time ago: do not pay for - // the same result again. + // Every peer left is in a shallow pause. if blockedOnly { ps.metrics.NeighborhoodKnownShallow.Inc() return nil, ErrNeighborhoodShallow @@ -577,8 +573,7 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo } } - // A first hop that fails in another way than a shallow receipt - // says nothing about the neighborhood: it is an unknown peer again. + // An error other than a shallow receipt removes the record. if origin && !errors.Is(result.err, ErrShallowReceipt) { ps.hops.forget(rad, ch.Address(), result.peer) ps.metrics.FirstHop.WithLabelValues(string(hopSources[result.peer.ByteString()]), "error").Inc() @@ -609,20 +604,17 @@ const ( hopSourceUnknown hopSource = "unknown" ) -// originPeer picks the next first hop for an origin. It uses what earlier -// chunks of the same neighborhood showed: -// 1. at most once per call and per hopProbeInterval, a peer that is closer to -// the chunk than every peer with a valid record gets a new try; -// 2. otherwise the closest peer that gave a valid receipt is used; -// 3. otherwise the closest peer that is not in a shallow pause. +// originPeer picks the next first hop for an origin: +// 1. a probe, at most once per call and per hopProbeInterval: a peer closer +// to the chunk than every peer with a valid record; +// 2. the closest peer with a valid record; +// 3. the closest peer that is not in a shallow pause. // -// blockedOnly is true when the error is topology.ErrNotFound only because of -// peers in a shallow pause. +// blockedOnly is true when no peer is found only because of shallow pauses. func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip []swarm.Address, probed *bool) (peer swarm.Address, source hopSource, blockedOnly bool, err error) { valid, blocked, probeDue := ps.hops.view(rad, chunkAddress) - // A valid record does not say that the peer is still connected. A peer - // that left is not picked, and its record is removed. + // Remove the valid records of peers that are no longer connected. if len(valid) > 0 { var connected []swarm.Address _ = ps.topologyDriver.EachConnectedPeer(func(p swarm.Address, _ uint8) (bool, bool, error) { diff --git a/pkg/retrieval/retrieval.go b/pkg/retrieval/retrieval.go index 9dd910ea685..21f2d8d8edf 100644 --- a/pkg/retrieval/retrieval.go +++ b/pkg/retrieval/retrieval.go @@ -403,9 +403,8 @@ func (s *Service) closestPeer(addr swarm.Address, skipPeers []swarm.Address, all return swarm.Address{}, err } - // A healthy peer that is far from the chunk must not be asked before a - // peer of a higher proximity order. Health decides only between peers of - // the same proximity order. + // Proximity order comes before health: prefer a closer peer that is + // not healthy to a healthy peer of a lower proximity order. nearest, err := s.peerSuggester.ClosestPeer(addr, false, topology.Select{Reachable: true}, skipPeers...) if err == nil && swarm.Proximity(nearest.Bytes(), addr.Bytes()) > swarm.Proximity(closest.Bytes(), addr.Bytes()) { closest = nearest diff --git a/pkg/retrieval/retrieval_test.go b/pkg/retrieval/retrieval_test.go index 5441a091fa2..3c50971a993 100644 --- a/pkg/retrieval/retrieval_test.go +++ b/pkg/retrieval/retrieval_test.go @@ -720,9 +720,8 @@ func createRetrieval( return ret } -// TestClosestPeerProximityBeforeHealth checks that neither the origin nor a -// forwarder asks a healthy peer before a peer of a higher proximity order to -// the chunk that is not healthy. +// TestClosestPeerProximityBeforeHealth checks that a peer of a higher +// proximity order is asked before a healthy peer, at origin and forwarder. func TestClosestPeerProximityBeforeHealth(t *testing.T) { t.Parallel() From 649c1bc7727a359abcdfbe49b63280a271af7e9f Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Thu, 19 Nov 2026 08:19:50 +0100 Subject: [PATCH 06/16] fix(pushsync): send through a paused first hop and ignore late results --- pkg/pushsync/export_test.go | 11 ++- pkg/pushsync/hopmemory.go | 70 +++++++++++--- pkg/pushsync/hopmemory_origin_test.go | 109 ++++++++++------------ pkg/pushsync/hopmemory_test.go | 129 +++++++++++++++++++++++++- pkg/pushsync/metrics.go | 51 +++++----- pkg/pushsync/pushsync.go | 60 ++++++------ 6 files changed, 293 insertions(+), 137 deletions(-) diff --git a/pkg/pushsync/export_test.go b/pkg/pushsync/export_test.go index d582c1b5ed2..83ee3161fe7 100644 --- a/pkg/pushsync/export_test.go +++ b/pkg/pushsync/export_test.go @@ -38,8 +38,10 @@ func (m *hopMemory) RecordShallow(rad uint8, chunk, peer swarm.Address) { m.recordShallow(rad, chunk, peer) } func (m *hopMemory) Forget(rad uint8, chunk, peer swarm.Address) { m.forget(rad, chunk, peer) } -func (m *hopMemory) MarkProbe(rad uint8, chunk swarm.Address) { m.markProbe(rad, chunk) } -func (m *hopMemory) Len() int { return m.len() } +func (m *hopMemory) ClaimProbe(rad uint8, chunk swarm.Address) bool { + return m.claimProbe(rad, chunk) +} +func (m *hopMemory) Len() int { return m.len() } func (m *hopMemory) View(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { return m.view(rad, chunk) @@ -59,9 +61,8 @@ func (ps *PushSync) FirstHopCount(source, result string) float64 { return counterValue(ps.metrics.FirstHop.WithLabelValues(source, result)) } -func (ps *PushSync) NeighborhoodKnownShallowCount() float64 { - return counterValue(ps.metrics.NeighborhoodKnownShallow) -} +// Hops returns the first-hop memory. +func (ps *PushSync) Hops() *HopMemory { return ps.hops } func counterValue(c prometheus.Counter) float64 { var m dto.Metric diff --git a/pkg/pushsync/hopmemory.go b/pkg/pushsync/hopmemory.go index 0bcced1250f..4d8eac0fb96 100644 --- a/pkg/pushsync/hopmemory.go +++ b/pkg/pushsync/hopmemory.go @@ -5,6 +5,7 @@ package pushsync import ( + "slices" "sync" "time" @@ -78,13 +79,25 @@ func hoodKey(rad uint8, chunk swarm.Address) string { return string(key) } -// hood returns the neighborhood of the chunk. A radius change drops all -// records. Must be called with the lock held. -func (m *hopMemory) hood(rad uint8, chunk swarm.Address, create bool) *hopHood { - if rad != m.radius { - m.radius = rad - clear(m.hoods) +// useRadius reports whether the memory holds records of the radius. Only a +// selection (change is true) drops the records of another radius, so that a +// late result of a push that began at the old radius is ignored. +// Must be called with the lock held. +func (m *hopMemory) useRadius(rad uint8, change bool) bool { + if rad == m.radius { + return true + } + if !change && len(m.hoods) > 0 { + return false } + m.radius = rad + clear(m.hoods) + return true +} + +// hood returns the neighborhood of the chunk. +// Must be called with the lock held. +func (m *hopMemory) hood(rad uint8, chunk swarm.Address, create bool) *hopHood { key := hoodKey(rad, chunk) h := m.hoods[key] if h == nil && create { @@ -99,6 +112,9 @@ func (m *hopMemory) recordValid(rad uint8, chunk, peer swarm.Address) { m.mtx.Lock() defer m.mtx.Unlock() + if !m.useRadius(rad, false) { + return + } m.hood(rad, chunk, true).peers[peer.ByteString()] = &hopRecord{peer: peer, valid: true, at: m.now()} } @@ -108,6 +124,9 @@ func (m *hopMemory) recordShallow(rad uint8, chunk, peer swarm.Address) { m.mtx.Lock() defer m.mtx.Unlock() + if !m.useRadius(rad, false) { + return + } now := m.now() h := m.hood(rad, chunk, true) r := h.peers[peer.ByteString()] @@ -133,6 +152,9 @@ func (m *hopMemory) forget(rad uint8, chunk, peer swarm.Address) { m.mtx.Lock() defer m.mtx.Unlock() + if !m.useRadius(rad, false) { + return + } h := m.hood(rad, chunk, false) if h == nil { return @@ -146,18 +168,21 @@ func (m *hopMemory) forget(rad uint8, chunk, peer swarm.Address) { } } -// view returns the peers with a valid record, the peers in a shallow pause, -// and whether a probe of the neighborhood is due. +// view returns the peers with a valid record, the peers in a shallow pause +// (the pause that ends first comes first), and whether a probe of the +// neighborhood is due. func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { m.mtx.Lock() defer m.mtx.Unlock() + m.useRadius(rad, true) h := m.hood(rad, chunk, false) if h == nil { return nil, nil, true } now := m.now() + var paused []*hopRecord for key, r := range h.peers { switch { case r.valid && now.Sub(r.at) >= hopValidIdle: @@ -165,11 +190,21 @@ func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm case r.valid: valid = append(valid, r.peer) case now.Before(r.blockedUntil()): - blocked = append(blocked, r.peer) + paused = append(paused, r) case now.Sub(r.at) >= hopShallowIdle: delete(h.peers, key) } } + slices.SortFunc(paused, func(a, b *hopRecord) int { + if c := a.blockedUntil().Compare(b.blockedUntil()); c != 0 { + return c + } + c, _ := swarm.DistanceCmp(chunk, b.peer, a.peer) + return c + }) + for _, r := range paused { + blocked = append(blocked, r.peer) + } if len(h.peers) == 0 { delete(m.hoods, hoodKey(rad, chunk)) } @@ -177,12 +212,23 @@ func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm return valid, blocked, h.lastProbe.IsZero() || now.Sub(h.lastProbe) >= hopProbeInterval } -// markProbe stores the time of a probe of the neighborhood. -func (m *hopMemory) markProbe(rad uint8, chunk swarm.Address) { +// claimProbe reports whether a probe of the neighborhood is due, and stores +// the time of the probe when it is. Of the callers that run at the same time, +// only one gets true. +func (m *hopMemory) claimProbe(rad uint8, chunk swarm.Address) bool { m.mtx.Lock() defer m.mtx.Unlock() - m.hood(rad, chunk, true).lastProbe = m.now() + if !m.useRadius(rad, false) { + return false + } + now := m.now() + h := m.hood(rad, chunk, true) + if !h.lastProbe.IsZero() && now.Sub(h.lastProbe) < hopProbeInterval { + return false + } + h.lastProbe = now + return true } // len returns the number of records. diff --git a/pkg/pushsync/hopmemory_origin_test.go b/pkg/pushsync/hopmemory_origin_test.go index 232c7ae1a53..f417795698a 100644 --- a/pkg/pushsync/hopmemory_origin_test.go +++ b/pkg/pushsync/hopmemory_origin_test.go @@ -185,14 +185,6 @@ func (n *hopNet) pushShallow() { } } -// pushPaused pushes a chunk and wants ErrNeighborhoodShallow. -func (n *hopNet) pushPaused() { - n.t.Helper() - if err := n.push(); !errors.Is(err, pushsync.ErrNeighborhoodShallow) { - n.t.Fatalf("got %v, want %v", err, pushsync.ErrNeighborhoodShallow) - } -} - // TestOriginPrefersKnownValidPeer checks that the next chunk goes to the // first hop with a valid record, not to a closer one that gave a shallow receipt. func TestOriginPrefersKnownValidPeer(t *testing.T) { @@ -216,33 +208,27 @@ func TestOriginPrefersKnownValidPeer(t *testing.T) { n.wantFirstHop("known_valid", "valid", 1) } -// TestOriginShallowPauseDoubles checks that a first hop that gave a shallow -// receipt is left out for 60s, and for 2 minutes after the next one. -func TestOriginShallowPauseDoubles(t *testing.T) { +// TestOriginPausedPeerLast checks that a first hop in a shallow pause is not +// used while another first hop is left. +func TestOriginPausedPeerLast(t *testing.T) { t.Parallel() - n := newHopNet(t, false, 1) - shallow := n.hops[0] + n := newHopNet(t, false, 2) + shallow, other := n.hops[0], n.hops[1] n.setReceipt(shallow, false) + // the farther first hop gives an error, so it gets no record n.pushShallow() n.wantStreams(shallow, 1) + n.wantFirstHop("unknown", "error", 1) + n.setReceipt(other, true) n.clock.Add(59 * time.Second) - n.pushPaused() + n.pushValid() n.wantStreams(shallow, 1) - - n.clock.Add(time.Second) - n.pushShallow() - n.wantStreams(shallow, 2) - - n.clock.Add(119 * time.Second) - n.pushPaused() - n.wantStreams(shallow, 2) - - n.clock.Add(time.Second) - n.pushShallow() - n.wantStreams(shallow, 3) + n.wantStreams(other, 1) + n.wantFirstHop("unknown", "valid", 1) + n.wantFirstHop("paused", "shallow", 0) } // TestOriginOtherNeighborhoodNotAffected checks that a shallow receipt for @@ -263,9 +249,10 @@ func TestOriginOtherNeighborhoodNotAffected(t *testing.T) { n.wantStreams(shallow, 2) } -// TestOriginAllPeersBlocked checks that nothing is sent when every first -// hop is in a shallow pause. -func TestOriginAllPeersBlocked(t *testing.T) { +// TestOriginAllPeersPaused checks that the origin sends through the first +// hops in a shallow pause when no other first hop is left, and that these +// sends do not make the pauses longer. +func TestOriginAllPeersPaused(t *testing.T) { t.Parallel() n := newHopNet(t, false, 2) @@ -276,27 +263,20 @@ func TestOriginAllPeersBlocked(t *testing.T) { n.wantStreams(n.hops[0], 1) n.wantStreams(n.hops[1], 1) - // the result must be "no peer for now", not a shallow receipt, which - // the pusher counts against the retry budget of the chunk - receipt, err := n.origin.PushChunkToClosest(context.Background(), n.chunk()) - if !errors.Is(err, pushsync.ErrNeighborhoodShallow) { - t.Fatalf("got %v, want %v", err, pushsync.ErrNeighborhoodShallow) - } - if errors.Is(err, pushsync.ErrShallowReceipt) { - t.Fatalf("got %v, which is a shallow receipt error", err) - } - if !errors.Is(err, topology.ErrNotFound) { - t.Fatalf("got %v, which is not %v", err, topology.ErrNotFound) - } - if receipt != nil { - t.Fatalf("got receipt %v, want none", receipt) - } - n.wantStreams(n.hops[0], 1) - n.wantStreams(n.hops[1], 1) + n.clock.Add(30 * time.Second) + n.pushShallow() + n.wantStreams(n.hops[0], 2) + n.wantStreams(n.hops[1], 2) + n.wantFirstHop("paused", "shallow", 2) - if got := n.origin.NeighborhoodKnownShallowCount(); got != 1 { - t.Fatalf("got %v pushes ended without a send, want 1", got) - } + // the pauses still end 60s after the first shallow receipts + n.setReceipt(n.hops[1], true) + n.clock.Add(30 * time.Second) + n.pushValid() + n.wantStreams(n.hops[0], 3) + n.wantStreams(n.hops[1], 3) + n.wantFirstHop("unknown", "shallow", 3) + n.wantFirstHop("unknown", "valid", 1) } // TestOriginAllBlockedInsideAOR checks that an origin inside the @@ -459,8 +439,8 @@ func TestOriginProbeBecomesValid(t *testing.T) { n.wantStreams(valid, 1) } -// TestForwarderDoesNotUseHopMemory checks that only an origin keeps -// first-hop records. +// TestForwarderDoesNotUseHopMemory checks that a forwarder neither reads +// nor writes first-hop records. func TestForwarderDoesNotUseHopMemory(t *testing.T) { t.Parallel() @@ -469,22 +449,35 @@ func TestForwarderDoesNotUseHopMemory(t *testing.T) { storerNode, _ := createPushSyncNodeWithRadius(t, storer, defaultPrices, nil, nil, hopSigner(t, n.anchor, true), hopRadius, mock.WithClosestPeerErr(topology.ErrWantSelf)) - // the forwarder is outside the neighborhood and knows the storer + // the forwarder and its two peers are outside the neighborhood; every + // push of the forwarder gets to the storer forwarderAddr := flipBits(n.anchor, 0, 254) + closer, farther := flipBits(n.anchor, 1), flipBits(n.anchor, 0, 2) forwarderRecorder := streamtest.New(streamtest.WithProtocols(storerNode.Protocol()), streamtest.WithBaseAddr(forwarderAddr)) - forwarder, _ := createPushSyncNodeWithRadius(t, forwarderAddr, defaultPrices, forwarderRecorder, nil, nil, hopRadius, mock.WithPeers(storer)) + forwarder, _ := createPushSyncNodeWithRadius(t, forwarderAddr, defaultPrices, forwarderRecorder, nil, nil, hopRadius, mock.WithPeers(closer, farther)) n.handlers[n.hops[0].String()] = forwarder.Protocol() - n.pushValid() + // an origin with these records sends to the farther peer first + chunk := n.chunk() + forwarder.Hops().View(hopRadius, chunk.Address()) + forwarder.Hops().RecordValid(hopRadius, chunk.Address(), farther) + forwarder.Hops().ClaimProbe(hopRadius, chunk.Address()) + + if _, err := n.origin.PushChunkToClosest(context.Background(), chunk); err != nil { + t.Fatalf("got %v, want a valid receipt", err) + } if got := n.streams(n.hops[0]); got != 1 { t.Fatalf("got %d pushes to the forwarder, want 1", got) } - if recs, _ := forwarderRecorder.Records(storer, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName); len(recs) != 1 { - t.Fatalf("got %d pushes to the storer, want 1", len(recs)) + if recs, _ := forwarderRecorder.Records(closer, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName); len(recs) != 1 { + t.Fatalf("got %d pushes to the closest peer, want 1", len(recs)) + } + if recs, _ := forwarderRecorder.Records(farther, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName); len(recs) != 0 { + t.Fatalf("got %d pushes to the peer with a valid record, want 0", len(recs)) } - if got := forwarder.HopRecords(); got != 0 { - t.Fatalf("forwarder has %d first-hop records, want 0", got) + if got := forwarder.HopRecords(); got != 1 { + t.Fatalf("forwarder has %d first-hop records, want the 1 that the test made", got) } if got := n.origin.HopRecords(); got != 1 { t.Fatalf("origin has %d first-hop records, want 1", got) diff --git a/pkg/pushsync/hopmemory_test.go b/pkg/pushsync/hopmemory_test.go index 2c2f0100e5b..8e17c21cd79 100644 --- a/pkg/pushsync/hopmemory_test.go +++ b/pkg/pushsync/hopmemory_test.go @@ -7,6 +7,7 @@ package pushsync_test import ( "math/rand" "sync" + "sync/atomic" "testing" "time" @@ -276,7 +277,12 @@ func TestHopMemoryProbe(t *testing.T) { t.Fatal("probe is not due for a neighborhood that was never probed") } - m.MarkProbe(10, chunk) + if !m.ClaimProbe(10, chunk) { + t.Fatal("probe that is due was not given") + } + if m.ClaimProbe(10, chunk) { + t.Fatal("second probe was given right after a probe") + } if _, _, due := m.View(10, chunk); due { t.Fatal("probe is due right after a probe") } @@ -363,6 +369,104 @@ func TestHopMemoryRadiusChange(t *testing.T) { } } +// TestHopMemoryLateResult checks that a result of a push that began at +// another radius does not remove the records of the current radius. +func TestHopMemoryLateResult(t *testing.T) { + t.Parallel() + + var ( + m = pushsync.NewHopMemory(newTestClock().Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + late = hopAddr(0x20) + ) + + m.View(10, chunk) + m.RecordValid(10, chunk, peer) + + m.RecordValid(9, chunk, late) + m.RecordShallow(9, chunk, late) + m.Forget(9, chunk, peer) + if m.ClaimProbe(9, chunk) { + t.Fatal("probe was given for another radius") + } + + valid, blocked, _ := m.View(10, chunk) + if len(valid) != 1 || !hasAddr(valid, peer) || len(blocked) != 0 { + t.Fatalf("got valid %v blocked %v, want only the record of radius 10", valid, blocked) + } +} + +// TestHopMemoryBlockedOrder checks that the peers in a pause are returned in +// the order in which their pauses end. +func TestHopMemoryBlockedOrder(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + long = hopAddr(0x6a) + first = hopAddr(0x10) + last = hopAddr(0x20) + ) + + // two shallow receipts in a row: the pause of this peer ends at 3m + m.RecordShallow(10, chunk, long) + clock.Add(time.Minute) + m.RecordShallow(10, chunk, long) + // these pauses end at 2m10s and 2m20s + clock.Add(10 * time.Second) + m.RecordShallow(10, chunk, first) + clock.Add(10 * time.Second) + m.RecordShallow(10, chunk, last) + + _, blocked, _ := m.View(10, chunk) + want := []swarm.Address{first, last, long} + if len(blocked) != len(want) { + t.Fatalf("got %d peers in a pause, want %d", len(blocked), len(want)) + } + for i := range want { + if !blocked[i].Equal(want[i]) { + t.Fatalf("position %d: got %s, want %s", i, blocked[i], want[i]) + } + } +} + +// TestHopMemoryClaimProbeOnce checks that only one of the callers that run +// at the same time gets the probe of a neighborhood. +func TestHopMemoryClaimProbeOnce(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + ) + m.RecordValid(10, chunk, hopAddr(0x10)) + + for round := range 3 { + var ( + wg sync.WaitGroup + given atomic.Int32 + ) + for range 64 { + wg.Go(func() { + if m.ClaimProbe(10, chunk) { + given.Add(1) + } + }) + } + wg.Wait() + if got := given.Load(); got != 1 { + t.Fatalf("round %d: got %d probes, want 1", round, got) + } + clock.Add(30 * time.Second) + } +} + +// TestHopMemoryConcurrent runs all operations at the same time and checks +// that the memory stays consistent. func TestHopMemoryConcurrent(t *testing.T) { t.Parallel() @@ -386,7 +490,7 @@ func TestHopMemoryConcurrent(t *testing.T) { case 2: m.Forget(10, chunk, peer) case 3: - m.MarkProbe(10, chunk) + m.ClaimProbe(10, chunk) case 4: clock.Add(time.Second) default: @@ -397,5 +501,24 @@ func TestHopMemoryConcurrent(t *testing.T) { } wg.Wait() - _ = m.Len() + // 4 values of the first byte and 4 of the next two bits give at most + // 16 neighborhoods at radius 10, each with at most 8 peers + if got := m.Len(); got > 16*8 { + t.Fatalf("got %d records, want at most %d", got, 16*8) + } + var seen int + for a := range 4 { + for b := range 4 { + valid, blocked, _ := m.View(10, hopAddr(byte(a), byte(b<<6))) + for _, p := range valid { + if hasAddr(blocked, p) { + t.Fatalf("peer %s is valid and in a pause", p) + } + } + seen += len(valid) + len(blocked) + } + } + if got := m.Len(); seen > got { + t.Fatalf("views returned %d peers, the memory has %d records", seen, got) + } } diff --git a/pkg/pushsync/metrics.go b/pkg/pushsync/metrics.go index 0770465fbf3..dfeaf07497d 100644 --- a/pkg/pushsync/metrics.go +++ b/pkg/pushsync/metrics.go @@ -12,28 +12,27 @@ import ( const statusLabel = "status" type metrics struct { - TotalSent prometheus.Counter - TotalReceived prometheus.Counter - TotalHandlerErrors prometheus.Counter - TotalRequests prometheus.Counter - TotalSendAttempts prometheus.Counter - TotalFailedSendAttempts prometheus.Counter - TotalOutgoing prometheus.Counter - TotalOutgoingErrors prometheus.Counter - InvalidStampErrors prometheus.Counter - StampValidationTime *prometheus.HistogramVec - Forwarder prometheus.Counter - Storer prometheus.Counter - TotalHandlerTime *prometheus.HistogramVec - PushToPeerTime *prometheus.HistogramVec - ReceiptDepth *prometheus.CounterVec - ShallowReceiptDepth *prometheus.CounterVec - ShallowReceipt prometheus.Counter - OverdraftRefresh prometheus.Counter - OutOfDepthStoring prometheus.Counter - OriginNoPeersLeft prometheus.Counter - FirstHop *prometheus.CounterVec - NeighborhoodKnownShallow prometheus.Counter + TotalSent prometheus.Counter + TotalReceived prometheus.Counter + TotalHandlerErrors prometheus.Counter + TotalRequests prometheus.Counter + TotalSendAttempts prometheus.Counter + TotalFailedSendAttempts prometheus.Counter + TotalOutgoing prometheus.Counter + TotalOutgoingErrors prometheus.Counter + InvalidStampErrors prometheus.Counter + StampValidationTime *prometheus.HistogramVec + Forwarder prometheus.Counter + Storer prometheus.Counter + TotalHandlerTime *prometheus.HistogramVec + PushToPeerTime *prometheus.HistogramVec + ReceiptDepth *prometheus.CounterVec + ShallowReceiptDepth *prometheus.CounterVec + ShallowReceipt prometheus.Counter + OverdraftRefresh prometheus.Counter + OutOfDepthStoring prometheus.Counter + OriginNoPeersLeft prometheus.Counter + FirstHop *prometheus.CounterVec } func newMetrics() metrics { @@ -175,16 +174,10 @@ func newMetrics() metrics { Namespace: m.Namespace, Subsystem: subsystem, Name: "first_hop_total", - Help: "Results of origin pushes by the reason the first hop was picked (probe, known_valid, unknown) and the result (valid, shallow, error).", + Help: "Results of origin pushes by the reason the first hop was picked (probe, known_valid, unknown, paused) and the result (valid, shallow, error).", }, []string{"source", "result"}, ), - NeighborhoodKnownShallow: prometheus.NewCounter(prometheus.CounterOpts{ - Namespace: m.Namespace, - Subsystem: subsystem, - Name: "neighborhood_known_shallow", - Help: "Total number of origin pushes that ended without a send because every peer left gave a shallow receipt for the neighborhood a short time ago.", - }), } } diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index 90bc4abe37e..d5ee28d71fb 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -61,10 +61,6 @@ var ( ErrOutOfDepthStoring = errors.New("storing outside of the neighborhood") ErrWarmup = errors.New("node warmup time not complete") ErrShallowReceipt = errors.New("shallow receipt") - // ErrNeighborhoodShallow is returned by an origin that sent nothing - // because every peer left is in a shallow pause for the neighborhood. - // It wraps topology.ErrNotFound so that callers wait and try again. - ErrNeighborhoodShallow = fmt.Errorf("every peer is in a shallow pause for the neighborhood: %w", topology.ErrNotFound) ) type PushSyncer interface { @@ -431,13 +427,12 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo fullSkip := append(skip.ChunkPeers(idAddress), ps.errSkip.ChunkPeers(idAddress)...) var ( - peer swarm.Address - err error - source hopSource - blockedOnly bool + peer swarm.Address + err error + source hopSource ) if origin { - peer, source, blockedOnly, err = ps.originPeer(ch.Address(), rad, fullSkip, &probed) + peer, source, err = ps.originPeer(ch.Address(), rad, fullSkip, &probed) } else { peer, err = ps.closestPeer(ch.Address(), origin, fullSkip) } @@ -479,11 +474,6 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo if !origin || swarm.Proximity(ps.address.Bytes(), ch.Address().Bytes()) >= rad { return nil, topology.ErrWantSelf } - // Every peer left is in a shallow pause. - if blockedOnly { - ps.metrics.NeighborhoodKnownShallow.Inc() - return nil, ErrNeighborhoodShallow - } // Peers were tried and none of them took the chunk, // or they are all skipped for now: retrying right away // cannot succeed, unlike the case of a node that has @@ -496,10 +486,6 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo if shallowReceiptResult != nil { return shallowReceiptResult, ErrShallowReceipt } - if blockedOnly { - ps.metrics.NeighborhoodKnownShallow.Inc() - return nil, ErrNeighborhoodShallow - } ps.logger.Debug("no peers left", "chunk_address", ch.Address(), "error", err) return nil, err } @@ -602,16 +588,17 @@ const ( hopSourceProbe hopSource = "probe" hopSourceValid hopSource = "known_valid" hopSourceUnknown hopSource = "unknown" + hopSourcePaused hopSource = "paused" ) // originPeer picks the next first hop for an origin: // 1. a probe, at most once per call and per hopProbeInterval: a peer closer // to the chunk than every peer with a valid record; // 2. the closest peer with a valid record; -// 3. the closest peer that is not in a shallow pause. -// -// blockedOnly is true when no peer is found only because of shallow pauses. -func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip []swarm.Address, probed *bool) (peer swarm.Address, source hopSource, blockedOnly bool, err error) { +// 3. the closest peer that is not in a shallow pause; +// 4. the peer whose shallow pause ends first, unless the origin can store +// the chunk itself. +func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip []swarm.Address, probed *bool) (peer swarm.Address, source hopSource, err error) { valid, blocked, probeDue := ps.hops.view(rad, chunkAddress) // Remove the valid records of peers that are no longer connected. @@ -651,24 +638,37 @@ func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip [ if probeDue && !*probed { candidate, err := ps.closestPeer(chunkAddress, true, append(notBlocked, valid...)) if err == nil { - if closer, _ := candidate.Closer(chunkAddress, best); closer { + if closer, _ := candidate.Closer(chunkAddress, best); closer && ps.hops.claimProbe(rad, chunkAddress) { *probed = true - ps.hops.markProbe(rad, chunkAddress) - return candidate, hopSourceProbe, false, nil + return candidate, hopSourceProbe, nil } } } - return best, hopSourceValid, false, nil + return best, hopSourceValid, nil } peer, err = ps.closestPeer(chunkAddress, true, notBlocked) - if errors.Is(err, topology.ErrNotFound) && len(blocked) > 0 { - if _, err := ps.closestPeer(chunkAddress, true, fullSkip); err == nil { - blockedOnly = true + if !errors.Is(err, topology.ErrNotFound) || len(blocked) == 0 { + return peer, hopSourceUnknown, err + } + if ps.fullNode && swarm.Proximity(ps.address.Bytes(), chunkAddress.Bytes()) >= rad { + return peer, hopSourceUnknown, err + } + + // Every peer left is in a shallow pause. Waiting would hold a push slot + // of the pusher, so send through the peer whose pause ends first. + for i, p := range blocked { + if swarm.ContainsAddress(fullSkip, p) { + continue + } + others := append(append([]swarm.Address{}, fullSkip...), blocked[:i]...) + others = append(others, blocked[i+1:]...) + if found, err := ps.closestPeer(chunkAddress, true, others); err == nil && found.Equal(p) { + return p, hopSourcePaused, nil } } - return peer, hopSourceUnknown, blockedOnly, err + return peer, hopSourceUnknown, err } func (ps *PushSync) closestPeer(chunkAddress swarm.Address, origin bool, skipList []swarm.Address) (swarm.Address, error) { From b3e76f35de7867d04105fcd96ce0c6ff30ddf545 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Thu, 19 Nov 2026 08:03:34 +0100 Subject: [PATCH 07/16] fix(retrieval): select the closest reachable peer without the health mark --- pkg/retrieval/retrieval.go | 16 ++++------------ pkg/retrieval/retrieval_test.go | 18 +++++++++++------- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/pkg/retrieval/retrieval.go b/pkg/retrieval/retrieval.go index 21f2d8d8edf..dc9ab4fa10b 100644 --- a/pkg/retrieval/retrieval.go +++ b/pkg/retrieval/retrieval.go @@ -391,25 +391,17 @@ func (s *Service) closestPeer(addr swarm.Address, skipPeers []swarm.Address, all err error ) - closest, err = s.peerSuggester.ClosestPeer(addr, false, topology.Select{Reachable: true, Healthy: true}, skipPeers...) + // The health mark is not used: a healthy peer that is far from the chunk + // must not be asked before a closer peer. + closest, err = s.peerSuggester.ClosestPeer(addr, false, topology.Select{Reachable: true}, skipPeers...) if errors.Is(err, topology.ErrNotFound) { - closest, err = s.peerSuggester.ClosestPeer(addr, false, topology.Select{Reachable: true}, skipPeers...) - if errors.Is(err, topology.ErrNotFound) { - closest, err = s.peerSuggester.ClosestPeer(addr, false, topology.Select{}, skipPeers...) - } + closest, err = s.peerSuggester.ClosestPeer(addr, false, topology.Select{}, skipPeers...) } if err != nil { return swarm.Address{}, err } - // Proximity order comes before health: prefer a closer peer that is - // not healthy to a healthy peer of a lower proximity order. - nearest, err := s.peerSuggester.ClosestPeer(addr, false, topology.Select{Reachable: true}, skipPeers...) - if err == nil && swarm.Proximity(nearest.Bytes(), addr.Bytes()) > swarm.Proximity(closest.Bytes(), addr.Bytes()) { - closest = nearest - } - if allowUpstream { return closest, nil } diff --git a/pkg/retrieval/retrieval_test.go b/pkg/retrieval/retrieval_test.go index 3c50971a993..63e4fab6dd4 100644 --- a/pkg/retrieval/retrieval_test.go +++ b/pkg/retrieval/retrieval_test.go @@ -720,9 +720,9 @@ func createRetrieval( return ret } -// TestClosestPeerProximityBeforeHealth checks that a peer of a higher -// proximity order is asked before a healthy peer, at origin and forwarder. -func TestClosestPeerProximityBeforeHealth(t *testing.T) { +// TestClosestPeerIgnoresHealth checks that the origin and a forwarder ask the +// closest reachable peer, also when it is not healthy. +func TestClosestPeerIgnoresHealth(t *testing.T) { t.Parallel() var ( @@ -730,8 +730,9 @@ func TestClosestPeerProximityBeforeHealth(t *testing.T) { nearBase = swarm.MustParseHexAddress("0180000000000000000000000000000000000000000000000000000000000000") // PO 8 chunk = swarm.MustParseHexAddress("0100000000000000000000000000000000000000000000000000000000000000") closer = swarm.MustParseHexAddress("0300000000000000000000000000000000000000000000000000000000000000") // PO 6, not healthy - samePO = swarm.MustParseHexAddress("0200000000000000000000000000000000000000000000000000000000000000") // PO 6, healthy + samePO = swarm.MustParseHexAddress("0200000000000000000000000000000000000000000000000000000000000000") // PO 6, healthy, farther than closer far = swarm.MustParseHexAddress("8000000000000000000000000000000000000000000000000000000000000000") // PO 0, healthy + private = swarm.MustParseHexAddress("0100000000000000000000000000000000000000000000000000000000000001") // PO 255, not reachable unhealthy = map[string]bool{closer.ByteString(): true} ) @@ -740,7 +741,7 @@ func TestClosestPeerProximityBeforeHealth(t *testing.T) { func(addr swarm.Address, _ bool, filter topology.Select, skip ...swarm.Address) (swarm.Address, error) { best := swarm.ZeroAddress for _, p := range peers { - if (filter.Healthy && unhealthy[p.ByteString()]) || swarm.ContainsAddress(skip, p) { + if (filter.Healthy && unhealthy[p.ByteString()]) || (filter.Reachable && p.Equal(private)) || swarm.ContainsAddress(skip, p) { continue } if best.IsZero() { @@ -766,11 +767,14 @@ func TestClosestPeerProximityBeforeHealth(t *testing.T) { want swarm.Address // zero when no peer is expected }{ {name: "origin, closer peer is not healthy", peers: []swarm.Address{far, closer}, origin: true, want: closer}, - {name: "origin, same proximity order", peers: []swarm.Address{samePO, closer}, origin: true, want: samePO}, + {name: "origin, same proximity order", peers: []swarm.Address{samePO, closer}, origin: true, want: closer}, {name: "forwarder, closer peer is not healthy", peers: []swarm.Address{far, closer}, origin: false, want: closer}, - {name: "forwarder, same proximity order", peers: []swarm.Address{samePO, closer}, origin: false, want: samePO}, + {name: "forwarder, same proximity order", peers: []swarm.Address{samePO, closer}, origin: false, want: closer}, {name: "forwarder, closer to the chunk than every peer", base: nearBase, peers: []swarm.Address{far, closer}, origin: false}, {name: "origin, closer to the chunk than every peer", base: nearBase, peers: []swarm.Address{far, closer}, origin: true, want: closer}, + {name: "origin, a reachable peer comes before a closer peer that is not reachable", peers: []swarm.Address{far, private}, origin: true, want: far}, + {name: "origin, no reachable peer", peers: []swarm.Address{private}, origin: true, want: private}, + {name: "forwarder, no reachable peer", peers: []swarm.Address{private}, origin: false, want: private}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() From 180495a1618d472dc3f4625ee125ad7e63a33069 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Thu, 19 Nov 2026 11:39:23 +0100 Subject: [PATCH 08/16] fix(pushsync): remove idle first-hop records of unused neighborhoods --- pkg/pushsync/export_test.go | 23 ++++++++++- pkg/pushsync/hopmemory.go | 75 ++++++++++++++++++++++------------ pkg/pushsync/hopmemory_test.go | 68 ++++++++++++++++++++++++++++++ pkg/pushsync/pushsync.go | 5 ++- 4 files changed, 141 insertions(+), 30 deletions(-) diff --git a/pkg/pushsync/export_test.go b/pkg/pushsync/export_test.go index 83ee3161fe7..e841db118d2 100644 --- a/pkg/pushsync/export_test.go +++ b/pkg/pushsync/export_test.go @@ -41,7 +41,26 @@ func (m *hopMemory) Forget(rad uint8, chunk, peer swarm.Address) { m.forget(rad, func (m *hopMemory) ClaimProbe(rad uint8, chunk swarm.Address) bool { return m.claimProbe(rad, chunk) } -func (m *hopMemory) Len() int { return m.len() } + +// Len returns the number of records. +func (m *hopMemory) Len() int { + m.mtx.Lock() + defer m.mtx.Unlock() + + var n int + for _, h := range m.hoods { + n += len(h.peers) + } + return n +} + +// Hoods returns the number of neighborhoods. +func (m *hopMemory) Hoods() int { + m.mtx.Lock() + defer m.mtx.Unlock() + + return len(m.hoods) +} func (m *hopMemory) View(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { return m.view(rad, chunk) @@ -55,7 +74,7 @@ func (ps *PushSync) SetHopClock(now func() time.Time) { } // HopRecords returns the number of first-hop records. -func (ps *PushSync) HopRecords() int { return ps.hops.len() } +func (ps *PushSync) HopRecords() int { return ps.hops.Len() } func (ps *PushSync) FirstHopCount(source, result string) float64 { return counterValue(ps.metrics.FirstHop.WithLabelValues(source, result)) diff --git a/pkg/pushsync/hopmemory.go b/pkg/pushsync/hopmemory.go index 4d8eac0fb96..cda24be51ad 100644 --- a/pkg/pushsync/hopmemory.go +++ b/pkg/pushsync/hopmemory.go @@ -23,6 +23,9 @@ const ( // without a new result is removed. hopValidIdle = 30 * time.Minute hopShallowIdle = 2 * hopShallowMaxPause + // hopSweepInterval is the shortest time between two removals of idle + // records in all neighborhoods. + hopSweepInterval = hopValidIdle ) // hopRecord is the last result of one first hop for one neighborhood. @@ -42,6 +45,14 @@ func (r *hopRecord) blockedUntil() time.Time { return r.at.Add(min(pause, hopShallowMaxPause)) } +// idle reports whether the record had no new result for long enough to be removed. +func (r *hopRecord) idle(now time.Time) bool { + if r.valid { + return now.Sub(r.at) >= hopValidIdle + } + return now.Sub(r.at) >= hopShallowIdle +} + type hopHood struct { peers map[string]*hopRecord lastProbe time.Time @@ -50,10 +61,11 @@ type hopHood struct { // hopMemory keeps the last receipt result of each first hop per neighborhood // (the chunk addresses that share the first radius bits). type hopMemory struct { - mtx sync.Mutex - now func() time.Time - radius uint8 - hoods map[string]*hopHood + mtx sync.Mutex + now func() time.Time + radius uint8 + hoods map[string]*hopHood + lastSweep time.Time } func newHopMemory(now func() time.Time) *hopMemory { @@ -107,6 +119,34 @@ func (m *hopMemory) hood(rad uint8, chunk swarm.Address, create bool) *hopHood { return h } +// dropEmpty removes the neighborhood when it has no records and its last +// probe no longer limits the next one. +// Must be called with the lock held. +func (m *hopMemory) dropEmpty(key string, h *hopHood, now time.Time) { + if len(h.peers) == 0 && now.Sub(h.lastProbe) >= hopProbeInterval { + delete(m.hoods, key) + } +} + +// sweep removes the idle records of all neighborhoods, at most once per +// hopSweepInterval. Without it the records of a neighborhood that gets no +// more chunks would stay until the radius changes. +// Must be called with the lock held. +func (m *hopMemory) sweep(now time.Time) { + if now.Sub(m.lastSweep) < hopSweepInterval { + return + } + m.lastSweep = now + for key, h := range m.hoods { + for peer, r := range h.peers { + if r.idle(now) { + delete(h.peers, peer) + } + } + m.dropEmpty(key, h, now) + } +} + // recordValid stores a valid receipt of the peer. func (m *hopMemory) recordValid(rad uint8, chunk, peer swarm.Address) { m.mtx.Lock() @@ -163,9 +203,7 @@ func (m *hopMemory) forget(rad uint8, chunk, peer swarm.Address) { return } delete(h.peers, peer.ByteString()) - if len(h.peers) == 0 { - delete(m.hoods, hoodKey(rad, chunk)) - } + m.dropEmpty(hoodKey(rad, chunk), h, m.now()) } // view returns the peers with a valid record, the peers in a shallow pause @@ -176,23 +214,22 @@ func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm defer m.mtx.Unlock() m.useRadius(rad, true) + now := m.now() + m.sweep(now) h := m.hood(rad, chunk, false) if h == nil { return nil, nil, true } - now := m.now() var paused []*hopRecord for key, r := range h.peers { switch { - case r.valid && now.Sub(r.at) >= hopValidIdle: + case r.idle(now): delete(h.peers, key) case r.valid: valid = append(valid, r.peer) case now.Before(r.blockedUntil()): paused = append(paused, r) - case now.Sub(r.at) >= hopShallowIdle: - delete(h.peers, key) } } slices.SortFunc(paused, func(a, b *hopRecord) int { @@ -205,9 +242,7 @@ func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm for _, r := range paused { blocked = append(blocked, r.peer) } - if len(h.peers) == 0 { - delete(m.hoods, hoodKey(rad, chunk)) - } + m.dropEmpty(hoodKey(rad, chunk), h, now) return valid, blocked, h.lastProbe.IsZero() || now.Sub(h.lastProbe) >= hopProbeInterval } @@ -230,15 +265,3 @@ func (m *hopMemory) claimProbe(rad uint8, chunk swarm.Address) bool { h.lastProbe = now return true } - -// len returns the number of records. -func (m *hopMemory) len() int { - m.mtx.Lock() - defer m.mtx.Unlock() - - var n int - for _, h := range m.hoods { - n += len(h.peers) - } - return n -} diff --git a/pkg/pushsync/hopmemory_test.go b/pkg/pushsync/hopmemory_test.go index 8e17c21cd79..815cf5e60da 100644 --- a/pkg/pushsync/hopmemory_test.go +++ b/pkg/pushsync/hopmemory_test.go @@ -259,6 +259,74 @@ func TestHopMemoryValidIdle(t *testing.T) { } } +// TestHopMemorySweep checks that the idle records of a neighborhood that gets +// no more chunks are removed when another neighborhood is used. +func TestHopMemorySweep(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + other = hopAddr(0x1c, 0x00) + peer = hopAddr(0x10) + bad = hopAddr(0x20) + ) + + m.View(10, chunk) // the first sweep + m.RecordValid(10, chunk, peer) + m.RecordShallow(10, chunk, bad) + + clock.Add(30 * time.Minute) + m.View(10, other) + if got := m.Len(); got != 1 { + t.Fatalf("got %d records after 30 minutes, want 1 (the shallow record)", got) + } + + clock.Add(30 * time.Minute) + m.View(10, other) + if got := m.Len(); got != 0 { + t.Fatalf("got %d records after 60 minutes, want 0", got) + } + if got := m.Hoods(); got != 0 { + t.Fatalf("got %d neighborhoods after 60 minutes, want 0", got) + } +} + +// TestHopMemoryProbeTimeKept checks that the removal of the last record of a +// neighborhood does not make the next probe due before the interval ends. +func TestHopMemoryProbeTimeKept(t *testing.T) { + t.Parallel() + + var ( + clock = newTestClock() + m = pushsync.NewHopMemory(clock.Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + ) + + m.RecordValid(10, chunk, peer) + if !m.ClaimProbe(10, chunk) { + t.Fatal("probe that is due was not given") + } + m.Forget(10, chunk, peer) + + m.RecordValid(10, chunk, peer) + if _, _, due := m.View(10, chunk); due { + t.Fatal("probe is due right after a probe") + } + if m.ClaimProbe(10, chunk) { + t.Fatal("second probe was given before the interval ended") + } + + m.Forget(10, chunk, peer) + clock.Add(30 * time.Second) + m.View(10, chunk) + if got := m.Hoods(); got != 0 { + t.Fatalf("got %d neighborhoods after the interval, want 0", got) + } +} + func TestHopMemoryProbe(t *testing.T) { t.Parallel() diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index d5ee28d71fb..7ec67b46ab7 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -375,10 +375,11 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo shallowReceiptResult *pb.Receipt shallowReceiptPO uint8 probed bool - hopSources = make(map[string]hopSource) + hopSources map[string]hopSource // first hops of an origin ) if origin { + hopSources = make(map[string]hopSource) ticker := time.NewTicker(preemptiveInterval) defer ticker.Stop() preemptiveTicker = ticker.C @@ -608,7 +609,7 @@ func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip [ if swarm.ContainsAddress(valid, p) { connected = append(connected, p) } - return false, false, nil + return len(connected) == len(valid), false, nil }, topology.Select{}) for _, p := range valid { if !swarm.ContainsAddress(connected, p) { From f81c59566196eaedcd48b4e1295a316521beeb08 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Fri, 20 Nov 2026 20:10:04 +0100 Subject: [PATCH 09/16] fix(pushsync): use one radius per attempt and ignore late results after a radius change --- pkg/pushsync/export_test.go | 6 +++- pkg/pushsync/hopmemory.go | 10 ++++--- pkg/pushsync/hopmemory_origin_test.go | 41 ++++++++++++++++++++++++++- pkg/pushsync/hopmemory_test.go | 36 +++++++++++++++++++++++ pkg/pushsync/pushsync.go | 22 ++++++++------ 5 files changed, 101 insertions(+), 14 deletions(-) diff --git a/pkg/pushsync/export_test.go b/pkg/pushsync/export_test.go index e841db118d2..c3b43fecf63 100644 --- a/pkg/pushsync/export_test.go +++ b/pkg/pushsync/export_test.go @@ -22,7 +22,11 @@ var ( // CheckReceipt exposes the unexported receipt verification (signature recovery, // overlay derivation, proximity and shallow-receipt logic) for fuzzing. func (ps *PushSync) CheckReceipt(receipt *pb.Receipt) error { - _, err := ps.checkReceipt(receipt, swarm.ZeroAddress) + rad, err := ps.radius() + if err != nil { + return err + } + _, err = ps.checkReceipt(receipt, swarm.ZeroAddress, rad) return err } diff --git a/pkg/pushsync/hopmemory.go b/pkg/pushsync/hopmemory.go index cda24be51ad..d3f5615a615 100644 --- a/pkg/pushsync/hopmemory.go +++ b/pkg/pushsync/hopmemory.go @@ -64,6 +64,7 @@ type hopMemory struct { mtx sync.Mutex now func() time.Time radius uint8 + radiusSet bool // false until the first use of the memory hoods map[string]*hopHood lastSweep time.Time } @@ -93,16 +94,17 @@ func hoodKey(rad uint8, chunk swarm.Address) string { // useRadius reports whether the memory holds records of the radius. Only a // selection (change is true) drops the records of another radius, so that a -// late result of a push that began at the old radius is ignored. +// late result of a push that began at the old radius is ignored, also when +// the memory has no records. // Must be called with the lock held. func (m *hopMemory) useRadius(rad uint8, change bool) bool { - if rad == m.radius { + if m.radiusSet && rad == m.radius { return true } - if !change && len(m.hoods) > 0 { + if m.radiusSet && !change { return false } - m.radius = rad + m.radius, m.radiusSet = rad, true clear(m.hoods) return true } diff --git a/pkg/pushsync/hopmemory_origin_test.go b/pkg/pushsync/hopmemory_origin_test.go index f417795698a..66493bf6ab7 100644 --- a/pkg/pushsync/hopmemory_origin_test.go +++ b/pkg/pushsync/hopmemory_origin_test.go @@ -7,6 +7,7 @@ package pushsync_test import ( "context" "errors" + "sync/atomic" "testing" "time" @@ -42,6 +43,7 @@ type hopNet struct { handlers map[string]p2p.ProtocolSpec clock *testClock nodes byte + radius atomic.Uint32 // storage radius of the origin } // flipBits returns a copy of the address with the given bits flipped. @@ -90,6 +92,7 @@ func newHopNet(t *testing.T, insideAOR bool, hops int) *hopNet { handlers: make(map[string]p2p.ProtocolSpec), clock: newTestClock(), } + n.radius.Store(hopRadius) // all first hops differ from the neighborhood in bit 0; the next bits // set their order @@ -110,7 +113,7 @@ func newHopNet(t *testing.T, insideAOR bool, hops int) *hopNet { originAddr, 1, blockHash.Bytes(), streamtest.NewRecorderDisconnecter(n.recorder), &testStorer{chunksPut: make(map[string]swarm.Chunk), chunksReported: make(map[string]int)}, - func() (uint8, error) { return hopRadius, nil }, + func() (uint8, error) { return uint8(n.radius.Load()), nil }, topo, true, func(swarm.Chunk) {}, func(*soc.SOC) {}, func(ch swarm.Chunk) (swarm.Chunk, error) { return ch, nil }, @@ -439,6 +442,42 @@ func TestOriginProbeBecomesValid(t *testing.T) { n.wantStreams(valid, 1) } +// TestOriginRadiusChangeDuringPush checks that a push whose radius changes +// between two attempts selects the next first hop and records its result at +// the new radius. +func TestOriginRadiusChangeDuringPush(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 2) + n.setReceipt(n.hops[0], false) + n.setReceipt(n.hops[1], true) + + // the radius of the origin grows while the first attempt is on its way + spec := n.handlers[n.hops[0].String()] + handler := spec.StreamSpecs[0].Handler + spec.StreamSpecs = []p2p.StreamSpec{spec.StreamSpecs[0]} + spec.StreamSpecs[0].Handler = func(ctx context.Context, p p2p.Peer, s p2p.Stream) error { + n.radius.Store(hopRadius + 1) + return handler(ctx, p, s) + } + n.handlers[n.hops[0].String()] = spec + + ch := testingc.GenerateValidRandomChunkAt(t, n.anchor, hopRadius+1) + if _, err := n.origin.PushChunkToClosest(context.Background(), ch); err != nil { + t.Fatalf("got %v, want a valid receipt", err) + } + n.wantStreams(n.hops[0], 1) + n.wantStreams(n.hops[1], 1) + + if got := n.origin.HopRecords(); got != 1 { + t.Fatalf("got %d records, want 1", got) + } + valid, blocked, _ := n.origin.Hops().View(hopRadius+1, ch.Address()) + if len(valid) != 1 || !valid[0].Equal(n.hops[1]) || len(blocked) != 0 { + t.Fatalf("got valid %v blocked %v, want the valid record of the second first hop at the new radius", valid, blocked) + } +} + // TestForwarderDoesNotUseHopMemory checks that a forwarder neither reads // nor writes first-hop records. func TestForwarderDoesNotUseHopMemory(t *testing.T) { diff --git a/pkg/pushsync/hopmemory_test.go b/pkg/pushsync/hopmemory_test.go index 815cf5e60da..4310228ac5c 100644 --- a/pkg/pushsync/hopmemory_test.go +++ b/pkg/pushsync/hopmemory_test.go @@ -465,6 +465,42 @@ func TestHopMemoryLateResult(t *testing.T) { } } +// TestHopMemoryLateResultEmptyMemory checks that a result of a push that began +// at the old radius is ignored when the memory has no records, which is the +// state right after a radius change. +func TestHopMemoryLateResultEmptyMemory(t *testing.T) { + t.Parallel() + + var ( + m = pushsync.NewHopMemory(newTestClock().Now) + chunk = hopAddr(0x6b, 0x00) + peer = hopAddr(0x10) + late = hopAddr(0x20) + ) + + m.View(9, chunk) + m.RecordValid(9, chunk, late) + m.View(10, chunk) + if got := m.Len(); got != 0 { + t.Fatalf("got %d records after the radius change, want 0", got) + } + + m.RecordValid(9, chunk, late) + m.RecordShallow(9, chunk, late) + if m.ClaimProbe(9, chunk) { + t.Fatal("probe was given for another radius") + } + if got := m.Len(); got != 0 { + t.Fatalf("got %d records of the old radius, want 0", got) + } + + m.RecordValid(10, chunk, peer) + valid, blocked, _ := m.View(10, chunk) + if len(valid) != 1 || !hasAddr(valid, peer) || len(blocked) != 0 { + t.Fatalf("got valid %v blocked %v, want only the record of radius 10", valid, blocked) + } +} + // TestHopMemoryBlockedOrder checks that the peers in a pause are returned in // the order in which their pauses end. func TestHopMemoryBlockedOrder(t *testing.T) { diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index 7ec67b46ab7..e20a515bf65 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -420,6 +420,10 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo case <-preemptiveTicker: retry() case <-retryC: + // The radius can change between two attempts of one push. + if rad, err = ps.radius(); err != nil { + return nil, fmt.Errorf("pushsync: storage radius: %w", err) + } // Origin peers should not store the chunk initially so that the chunk is always forwarded into the network. // If no peer can be found from an origin peer, the origin peer may store the chunk. @@ -534,6 +538,13 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo ps.measurePushPeer(result.pushTime, result.err) + // The receipt is checked and recorded at the same radius. + if origin { + if rad, err = ps.radius(); err != nil { + return nil, fmt.Errorf("pushsync: storage radius: %w", err) + } + } + if result.err == nil { if !origin { // forwarder nodes do not need to check the receipt @@ -542,7 +553,7 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo // Cache the best (highest-PO) shallow receipt and exhaust the // budget; surface ErrShallowReceipt only when nothing better lands. - switch po, err := ps.checkReceipt(result.receipt, result.peer); { + switch po, err := ps.checkReceipt(result.receipt, result.peer, rad); { case err == nil: ps.hops.recordValid(rad, ch.Address(), result.peer) ps.metrics.FirstHop.WithLabelValues(string(hopSources[result.peer.ByteString()]), "valid").Inc() @@ -740,8 +751,8 @@ func (ps *PushSync) push(parentCtx context.Context, resultChan chan<- receiptRes // checkReceipt validates the receipt and returns the storer-to-chunk PO so // callers can rank shallow receipts; PO is zero on signature errors. Strict -// po >= rad: a chunk is not synced until it lands within the AOR. -func (ps *PushSync) checkReceipt(receipt *pb.Receipt, firstHop swarm.Address) (uint8, error) { +// po >= r: a chunk is not synced until it lands within the AOR. +func (ps *PushSync) checkReceipt(receipt *pb.Receipt, firstHop swarm.Address, r uint8) (uint8, error) { addr := swarm.NewAddress(receipt.Address) publicKey, err := crypto.Recover(receipt.Signature, addr.Bytes()) @@ -756,11 +767,6 @@ func (ps *PushSync) checkReceipt(receipt *pb.Receipt, firstHop swarm.Address) (u po := swarm.Proximity(addr.Bytes(), peer.Bytes()) - r, err := ps.radius() - if err != nil { - return po, fmt.Errorf("pushsync: storage radius: %w", err) - } - if po < r || uint32(po) < receipt.StorageRadius { ps.metrics.ShallowReceiptDepth.WithLabelValues(strconv.Itoa(int(po))).Inc() ps.metrics.ShallowReceipt.Inc() From b9ed8cf4e6d4284ac098a3334ed3ca76a51c946e Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Fri, 20 Nov 2026 20:25:14 +0100 Subject: [PATCH 10/16] refactor(pushsync): select the paused first hop in one pass over connected peers --- pkg/pushsync/hopmemory_origin_test.go | 27 ++++++++++++++++++++++ pkg/pushsync/pushsync.go | 33 +++++++++++++++------------ 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/pkg/pushsync/hopmemory_origin_test.go b/pkg/pushsync/hopmemory_origin_test.go index 66493bf6ab7..2073d232d83 100644 --- a/pkg/pushsync/hopmemory_origin_test.go +++ b/pkg/pushsync/hopmemory_origin_test.go @@ -7,6 +7,7 @@ package pushsync_test import ( "context" "errors" + "slices" "sync/atomic" "testing" "time" @@ -282,6 +283,32 @@ func TestOriginAllPeersPaused(t *testing.T) { n.wantFirstHop("unknown", "valid", 1) } +// TestOriginPausedPeerDisconnected checks that, when every first hop is in a +// shallow pause, the origin sends only through the ones that are connected. +func TestOriginPausedPeerDisconnected(t *testing.T) { + t.Parallel() + + n := newHopNet(t, false, 3) + for _, hop := range n.hops { + n.setReceipt(hop, false) + } + + n.pushShallow() + for _, hop := range n.hops { + n.wantStreams(hop, 1) + } + + // the topology mock removes a peer from the slice that n.hops shares + hops := slices.Clone(n.hops) + n.topo.Disconnected(p2p.Peer{Address: hops[0]}) + n.topo.Disconnected(p2p.Peer{Address: hops[2]}) + n.pushShallow() + n.wantStreams(hops[0], 1) + n.wantStreams(hops[1], 2) + n.wantStreams(hops[2], 1) + n.wantFirstHop("paused", "shallow", 1) +} + // TestOriginAllBlockedInsideAOR checks that an origin inside the // neighborhood stores the chunk itself when every first hop is paused. func TestOriginAllBlockedInsideAOR(t *testing.T) { diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index e20a515bf65..d76d2aa6822 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -615,13 +615,7 @@ func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip [ // Remove the valid records of peers that are no longer connected. if len(valid) > 0 { - var connected []swarm.Address - _ = ps.topologyDriver.EachConnectedPeer(func(p swarm.Address, _ uint8) (bool, bool, error) { - if swarm.ContainsAddress(valid, p) { - connected = append(connected, p) - } - return len(connected) == len(valid), false, nil - }, topology.Select{}) + connected := ps.connectedOf(valid) for _, p := range valid { if !swarm.ContainsAddress(connected, p) { ps.hops.forget(rad, chunkAddress, p) @@ -668,14 +662,10 @@ func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip [ } // Every peer left is in a shallow pause. Waiting would hold a push slot - // of the pusher, so send through the peer whose pause ends first. - for i, p := range blocked { - if swarm.ContainsAddress(fullSkip, p) { - continue - } - others := append(append([]swarm.Address{}, fullSkip...), blocked[:i]...) - others = append(others, blocked[i+1:]...) - if found, err := ps.closestPeer(chunkAddress, true, others); err == nil && found.Equal(p) { + // of the pusher, so send through the connected peer whose pause ends first. + connected := ps.connectedOf(blocked) + for _, p := range blocked { + if swarm.ContainsAddress(connected, p) && !swarm.ContainsAddress(fullSkip, p) { return p, hopSourcePaused, nil } } @@ -683,6 +673,19 @@ func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip [ return peer, hopSourceUnknown, err } +// connectedOf returns the peers that are connected, in one pass over the +// connected peers. +func (ps *PushSync) connectedOf(peers []swarm.Address) []swarm.Address { + var connected []swarm.Address + _ = ps.topologyDriver.EachConnectedPeer(func(p swarm.Address, _ uint8) (bool, bool, error) { + if swarm.ContainsAddress(peers, p) { + connected = append(connected, p) + } + return len(connected) == len(peers), false, nil + }, topology.Select{}) + return connected +} + func (ps *PushSync) closestPeer(chunkAddress swarm.Address, origin bool, skipList []swarm.Address) (swarm.Address, error) { includeSelf := ps.fullNode && !origin From 1c0bc9aaa0e3b59b0de57c39c464dcfa2f50b15a Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Fri, 20 Nov 2026 20:27:46 +0100 Subject: [PATCH 11/16] refactor(pushsync): build the first-hop skip list only where it is used --- pkg/pushsync/pushsync.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index d76d2aa6822..178c4f3d0b1 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -10,6 +10,7 @@ import ( "context" "errors" "fmt" + "slices" "strconv" "time" @@ -638,11 +639,9 @@ func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip [ } } - notBlocked := append(append([]swarm.Address{}, fullSkip...), blocked...) - if !best.IsZero() { if probeDue && !*probed { - candidate, err := ps.closestPeer(chunkAddress, true, append(notBlocked, valid...)) + candidate, err := ps.closestPeer(chunkAddress, true, slices.Concat(fullSkip, blocked, valid)) if err == nil { if closer, _ := candidate.Closer(chunkAddress, best); closer && ps.hops.claimProbe(rad, chunkAddress) { *probed = true @@ -653,7 +652,7 @@ func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip [ return best, hopSourceValid, nil } - peer, err = ps.closestPeer(chunkAddress, true, notBlocked) + peer, err = ps.closestPeer(chunkAddress, true, slices.Concat(fullSkip, blocked)) if !errors.Is(err, topology.ErrNotFound) || len(blocked) == 0 { return peer, hopSourceUnknown, err } From 397701552bff10f2b2bc4577ccdf87bdd747edbc Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Fri, 20 Nov 2026 20:36:24 +0100 Subject: [PATCH 12/16] feat(pushsync): add gauges for the size of the first-hop memory --- pkg/pushsync/export_test.go | 16 ++++------------ pkg/pushsync/hopmemory.go | 11 +++++++++++ pkg/pushsync/metrics.go | 22 +++++++++++++++++++++- pkg/pushsync/pushsync.go | 5 +++-- 4 files changed, 39 insertions(+), 15 deletions(-) diff --git a/pkg/pushsync/export_test.go b/pkg/pushsync/export_test.go index c3b43fecf63..62679bae90f 100644 --- a/pkg/pushsync/export_test.go +++ b/pkg/pushsync/export_test.go @@ -48,22 +48,14 @@ func (m *hopMemory) ClaimProbe(rad uint8, chunk swarm.Address) bool { // Len returns the number of records. func (m *hopMemory) Len() int { - m.mtx.Lock() - defer m.mtx.Unlock() - - var n int - for _, h := range m.hoods { - n += len(h.peers) - } - return n + _, records := m.size() + return records } // Hoods returns the number of neighborhoods. func (m *hopMemory) Hoods() int { - m.mtx.Lock() - defer m.mtx.Unlock() - - return len(m.hoods) + hoods, _ := m.size() + return hoods } func (m *hopMemory) View(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { diff --git a/pkg/pushsync/hopmemory.go b/pkg/pushsync/hopmemory.go index d3f5615a615..98144c63d01 100644 --- a/pkg/pushsync/hopmemory.go +++ b/pkg/pushsync/hopmemory.go @@ -149,6 +149,17 @@ func (m *hopMemory) sweep(now time.Time) { } } +// size returns the number of neighborhoods and the number of records. +func (m *hopMemory) size() (hoods, records int) { + m.mtx.Lock() + defer m.mtx.Unlock() + + for _, h := range m.hoods { + records += len(h.peers) + } + return len(m.hoods), records +} + // recordValid stores a valid receipt of the peer. func (m *hopMemory) recordValid(rad uint8, chunk, peer swarm.Address) { m.mtx.Lock() diff --git a/pkg/pushsync/metrics.go b/pkg/pushsync/metrics.go index dfeaf07497d..5e08ff79ed0 100644 --- a/pkg/pushsync/metrics.go +++ b/pkg/pushsync/metrics.go @@ -33,9 +33,11 @@ type metrics struct { OutOfDepthStoring prometheus.Counter OriginNoPeersLeft prometheus.Counter FirstHop *prometheus.CounterVec + FirstHopRecords prometheus.GaugeFunc + FirstHopNeighborhoods prometheus.GaugeFunc } -func newMetrics() metrics { +func newMetrics(hops *hopMemory) metrics { subsystem := "pushsync" return metrics{ @@ -178,6 +180,24 @@ func newMetrics() metrics { }, []string{"source", "result"}, ), + FirstHopRecords: prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + Namespace: m.Namespace, + Subsystem: subsystem, + Name: "first_hop_records", + Help: "Number of records in the first-hop memory of an origin.", + }, func() float64 { + _, records := hops.size() + return float64(records) + }), + FirstHopNeighborhoods: prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + Namespace: m.Namespace, + Subsystem: subsystem, + Name: "first_hop_neighborhoods", + Help: "Number of neighborhoods in the first-hop memory of an origin.", + }, func() float64 { + hoods, _ := hops.size() + return float64(hoods) + }), } } diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index 178c4f3d0b1..d4e5f67ec92 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -129,6 +129,7 @@ func New( tracer *tracing.Tracer, stabilizer stabilization.Subscriber, ) *PushSync { + hops := newHopMemory(time.Now) ps := &PushSync{ address: address, radius: radius, @@ -143,11 +144,11 @@ func New( logger: logger.WithName(loggerName).Register(), accounting: accounting, pricer: pricer, - metrics: newMetrics(), + metrics: newMetrics(hops), tracer: tracer, signer: signer, errSkip: skippeers.NewList(time.Minute), - hops: newHopMemory(time.Now), + hops: hops, stabilizer: stabilizer, overDraftRefreshLimiter: rate.NewLimiter(rate.Every(time.Second), 1), } From a7e73645e98d89ebca42e7388bf9a79251e58fc6 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Fri, 20 Nov 2026 20:36:46 +0100 Subject: [PATCH 13/16] test(pushsync): remove the paused first hop test that passes without the change --- pkg/pushsync/hopmemory_origin_test.go | 27 --------------------------- 1 file changed, 27 deletions(-) diff --git a/pkg/pushsync/hopmemory_origin_test.go b/pkg/pushsync/hopmemory_origin_test.go index 2073d232d83..66493bf6ab7 100644 --- a/pkg/pushsync/hopmemory_origin_test.go +++ b/pkg/pushsync/hopmemory_origin_test.go @@ -7,7 +7,6 @@ package pushsync_test import ( "context" "errors" - "slices" "sync/atomic" "testing" "time" @@ -283,32 +282,6 @@ func TestOriginAllPeersPaused(t *testing.T) { n.wantFirstHop("unknown", "valid", 1) } -// TestOriginPausedPeerDisconnected checks that, when every first hop is in a -// shallow pause, the origin sends only through the ones that are connected. -func TestOriginPausedPeerDisconnected(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 3) - for _, hop := range n.hops { - n.setReceipt(hop, false) - } - - n.pushShallow() - for _, hop := range n.hops { - n.wantStreams(hop, 1) - } - - // the topology mock removes a peer from the slice that n.hops shares - hops := slices.Clone(n.hops) - n.topo.Disconnected(p2p.Peer{Address: hops[0]}) - n.topo.Disconnected(p2p.Peer{Address: hops[2]}) - n.pushShallow() - n.wantStreams(hops[0], 1) - n.wantStreams(hops[1], 2) - n.wantStreams(hops[2], 1) - n.wantFirstHop("paused", "shallow", 1) -} - // TestOriginAllBlockedInsideAOR checks that an origin inside the // neighborhood stores the chunk itself when every first hop is paused. func TestOriginAllBlockedInsideAOR(t *testing.T) { From 40cf109a0a4a97c2ea8aeb044e2922828d4cf1f1 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Sun, 22 Nov 2026 20:45:05 +0100 Subject: [PATCH 14/16] refactor(pushsync): add the internal firsthop package for the first-hop memory --- pkg/pushsync/internal/firsthop/memory.go | 328 +++++++++++++ pkg/pushsync/internal/firsthop/memory_test.go | 433 ++++++++++++++++++ 2 files changed, 761 insertions(+) create mode 100644 pkg/pushsync/internal/firsthop/memory.go create mode 100644 pkg/pushsync/internal/firsthop/memory_test.go diff --git a/pkg/pushsync/internal/firsthop/memory.go b/pkg/pushsync/internal/firsthop/memory.go new file mode 100644 index 00000000000..4d73fbe6c0a --- /dev/null +++ b/pkg/pushsync/internal/firsthop/memory.go @@ -0,0 +1,328 @@ +// Copyright 2026 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package firsthop keeps the receipt results of the first hops of an origin. +// +// An origin sends a chunk to one of its peers, the first hop, and gets back a +// receipt that is valid (the chunk was stored inside its neighborhood) or +// shallow (it was stored outside of it). The Memory keeps the last result of +// each first hop per neighborhood, so that the next chunk of the neighborhood +// goes to a first hop that gave a valid receipt and not to one that gave a +// shallow receipt. +package firsthop + +import ( + "slices" + "sync" + "time" + + "github.com/ethersphere/bee/v2/pkg/swarm" +) + +const ( + // shallowPause is the pause of a first hop after a shallow receipt. + // It doubles with each shallow receipt in a row, up to maxShallowPause. + shallowPause = time.Minute + maxShallowPause = 30 * time.Minute + // probeInterval is the shortest time between two probes of a neighborhood. + probeInterval = 30 * time.Second + // validIdle and shallowIdle are the times after which a record without a + // new result is removed. + validIdle = 30 * time.Minute + shallowIdle = 2 * maxShallowPause + // sweepInterval is the shortest time between two removals of idle records + // in all neighborhoods. + sweepInterval = validIdle +) + +// record is the last result of one first hop for one neighborhood. +type record struct { + peer swarm.Address + valid bool + at time.Time + shallow int // shallow receipts in a row +} + +// pausedUntil returns the end of the pause of a shallow record. +func (r *record) pausedUntil() time.Time { + pause := shallowPause + for i := 1; i < r.shallow && pause < maxShallowPause; i++ { + pause *= 2 + } + return r.at.Add(min(pause, maxShallowPause)) +} + +// paused reports whether the record is shallow and its pause still runs. +func (r *record) paused(now time.Time) bool { + return !r.valid && now.Before(r.pausedUntil()) +} + +// idle reports whether the record had no new result for long enough to be removed. +func (r *record) idle(now time.Time) bool { + if r.valid { + return now.Sub(r.at) >= validIdle + } + return now.Sub(r.at) >= shallowIdle +} + +// neighborhood holds the records of the chunk addresses that share the first +// radius bits. +type neighborhood struct { + peers map[string]*record + lastProbe time.Time +} + +// probeDue reports whether the last probe no longer limits the next one. +func (n *neighborhood) probeDue(now time.Time) bool { + return n.lastProbe.IsZero() || now.Sub(n.lastProbe) >= probeInterval +} + +// Memory keeps the last receipt result of each first hop per neighborhood. +// It holds the records of one radius at a time. It is safe for concurrent use. +type Memory struct { + now func() time.Time + + mtx sync.Mutex // guards the fields below + radius uint8 + radiusSet bool // false until the first use of the memory + neighborhoods map[string]*neighborhood + lastSweep time.Time +} + +// New returns an empty memory that reads the time from now. +func New(now func() time.Time) *Memory { + return &Memory{ + now: now, + neighborhoods: make(map[string]*neighborhood), + } +} + +// View is what the memory holds about the first hops of one neighborhood. +type View struct { + // Valid are the peers whose last receipt was valid. + Valid []swarm.Address + // Paused are the peers in a shallow pause; the pause that ends first + // comes first. + Paused []swarm.Address + // ProbeDue is true when the neighborhood had no probe for the probe interval. + ProbeDue bool +} + +// View returns the records of the neighborhood of the chunk. The radius of +// the call becomes the radius of the memory: the records of another radius +// are removed. +func (m *Memory) View(radius uint8, chunk swarm.Address) View { + m.mtx.Lock() + defer m.mtx.Unlock() + + now := m.now() + m.setRadius(radius) + m.sweep(now) + + key := neighborhoodKey(radius, chunk) + n := m.neighborhoods[key] + if n == nil { + return View{ProbeDue: true} + } + + var ( + view View + paused []*record + ) + for peer, r := range n.peers { + switch { + case r.idle(now): + delete(n.peers, peer) + case r.valid: + view.Valid = append(view.Valid, r.peer) + case r.paused(now): + paused = append(paused, r) + } + } + slices.SortFunc(paused, func(a, b *record) int { + if c := a.pausedUntil().Compare(b.pausedUntil()); c != 0 { + return c + } + c, _ := swarm.DistanceCmp(chunk, b.peer, a.peer) + return c + }) + for _, r := range paused { + view.Paused = append(view.Paused, r.peer) + } + view.ProbeDue = n.probeDue(now) + m.dropEmpty(key, n, now) + + return view +} + +// Valid stores a valid receipt of the peer. +func (m *Memory) Valid(radius uint8, chunk, peer swarm.Address) { + m.mtx.Lock() + defer m.mtx.Unlock() + + if !m.holdsRadius(radius) { + return + } + n := m.neighborhood(neighborhoodKey(radius, chunk)) + n.peers[peer.ByteString()] = &record{peer: peer, valid: true, at: m.now()} +} + +// Shallow stores a shallow receipt of the peer. A receipt that comes during +// the pause of the peer does not make the pause longer. +func (m *Memory) Shallow(radius uint8, chunk, peer swarm.Address) { + m.mtx.Lock() + defer m.mtx.Unlock() + + if !m.holdsRadius(radius) { + return + } + now := m.now() + n := m.neighborhood(neighborhoodKey(radius, chunk)) + r := n.peers[peer.ByteString()] + if r == nil { + r = &record{peer: peer} + n.peers[peer.ByteString()] = r + } + if r.paused(now) { + return + } + // idle record that View did not remove yet + if !r.valid && r.idle(now) { + r.shallow = 0 + } + r.valid = false + r.shallow++ + r.at = now +} + +// Forget removes the record of the peer, except a shallow record whose pause +// still runs. +func (m *Memory) Forget(radius uint8, chunk, peer swarm.Address) { + m.mtx.Lock() + defer m.mtx.Unlock() + + if !m.holdsRadius(radius) { + return + } + key := neighborhoodKey(radius, chunk) + n := m.neighborhoods[key] + if n == nil { + return + } + now := m.now() + if r := n.peers[peer.ByteString()]; r != nil && r.paused(now) { + return + } + delete(n.peers, peer.ByteString()) + m.dropEmpty(key, n, now) +} + +// ClaimProbe reports whether a probe of the neighborhood of the chunk is due, +// and stores the time of the probe when it is. Of the callers that run at the +// same time, only one gets true. +func (m *Memory) ClaimProbe(radius uint8, chunk swarm.Address) bool { + m.mtx.Lock() + defer m.mtx.Unlock() + + if !m.holdsRadius(radius) { + return false + } + now := m.now() + n := m.neighborhood(neighborhoodKey(radius, chunk)) + if !n.probeDue(now) { + return false + } + n.lastProbe = now + return true +} + +// Size returns the number of neighborhoods and the number of records. +func (m *Memory) Size() (neighborhoods, records int) { + m.mtx.Lock() + defer m.mtx.Unlock() + + for _, n := range m.neighborhoods { + records += len(n.peers) + } + return len(m.neighborhoods), records +} + +// setRadius makes radius the radius of the memory and removes the records of +// another radius. +// Must be called with the lock held. +func (m *Memory) setRadius(radius uint8) { + if m.radiusSet && radius == m.radius { + return + } + m.radius, m.radiusSet = radius, true + clear(m.neighborhoods) +} + +// holdsRadius reports whether the memory holds the records of the radius. +// A result does not change the radius of a memory that has one, so that a +// late result of a push that began at the old radius is ignored, also when +// the memory has no records. +// Must be called with the lock held. +func (m *Memory) holdsRadius(radius uint8) bool { + if !m.radiusSet { + m.setRadius(radius) + } + return radius == m.radius +} + +// neighborhood returns the neighborhood of the key and makes it when the +// memory does not have it. +// Must be called with the lock held. +func (m *Memory) neighborhood(key string) *neighborhood { + n := m.neighborhoods[key] + if n == nil { + n = &neighborhood{peers: make(map[string]*record)} + m.neighborhoods[key] = n + } + return n +} + +// dropEmpty removes the neighborhood when it has no records and its last +// probe no longer limits the next one. +// Must be called with the lock held. +func (m *Memory) dropEmpty(key string, n *neighborhood, now time.Time) { + if len(n.peers) == 0 && n.probeDue(now) { + delete(m.neighborhoods, key) + } +} + +// sweep removes the idle records of all neighborhoods, at most once per +// sweepInterval. Without it the records of a neighborhood that gets no more +// chunks would stay until the radius changes. +// Must be called with the lock held. +func (m *Memory) sweep(now time.Time) { + if now.Sub(m.lastSweep) < sweepInterval { + return + } + m.lastSweep = now + for key, n := range m.neighborhoods { + for peer, r := range n.peers { + if r.idle(now) { + delete(n.peers, peer) + } + } + m.dropEmpty(key, n, now) + } +} + +// neighborhoodKey returns the first radius bits of the chunk address. +func neighborhoodKey(radius uint8, chunk swarm.Address) string { + b := chunk.Bytes() + if int(radius) >= len(b)*8 { + return string(b) + } + n, rem := int(radius/8), radius%8 + if rem == 0 { + return string(b[:n]) + } + key := make([]byte, n+1) + copy(key, b[:n]) + key[n] = b[n] & (0xff << (8 - rem)) + return string(key) +} diff --git a/pkg/pushsync/internal/firsthop/memory_test.go b/pkg/pushsync/internal/firsthop/memory_test.go new file mode 100644 index 00000000000..cf13e55dc92 --- /dev/null +++ b/pkg/pushsync/internal/firsthop/memory_test.go @@ -0,0 +1,433 @@ +// Copyright 2026 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package firsthop_test + +import ( + "math/rand" + "sync" + "testing" + "time" + + "github.com/ethersphere/bee/v2/pkg/pushsync/internal/firsthop" + "github.com/ethersphere/bee/v2/pkg/swarm" +) + +const radius = 10 + +// testClock is a clock that a test moves forward by hand. +type testClock struct { + mtx sync.Mutex + t time.Time +} + +func (c *testClock) Now() time.Time { + c.mtx.Lock() + defer c.mtx.Unlock() + return c.t +} + +func (c *testClock) Add(d time.Duration) { + c.mtx.Lock() + defer c.mtx.Unlock() + c.t = c.t.Add(d) +} + +func newMemory() (*firsthop.Memory, *testClock) { + clock := &testClock{t: time.Unix(1_700_000_000, 0)} + return firsthop.New(clock.Now), clock +} + +// addr returns an address that starts with the given bytes. +func addr(prefix ...byte) swarm.Address { + b := make([]byte, swarm.HashSize) + copy(b, prefix) + return swarm.NewAddress(b) +} + +func has(addrs []swarm.Address, a swarm.Address) bool { + return swarm.ContainsAddress(addrs, a) +} + +func records(m *firsthop.Memory) int { + _, n := m.Size() + return n +} + +// TestRecord checks that the last result of a peer decides where View puts it. +func TestRecord(t *testing.T) { + t.Parallel() + + var ( + m, clock = newMemory() + chunk = addr(0x6b, 0x00) + peer = addr(0x10) + ) + + m.Valid(radius, chunk, peer) + if v := m.View(radius, chunk); !has(v.Valid, peer) || len(v.Paused) != 0 { + t.Fatalf("after a valid receipt: valid %v paused %v", v.Valid, v.Paused) + } + + m.Shallow(radius, chunk, peer) + if v := m.View(radius, chunk); len(v.Valid) != 0 || !has(v.Paused, peer) { + t.Fatalf("after a shallow receipt: valid %v paused %v", v.Valid, v.Paused) + } + + m.Forget(radius, chunk, peer) + if v := m.View(radius, chunk); !has(v.Paused, peer) { + t.Fatal("forget ended a pause that still runs") + } + + clock.Add(time.Minute) + m.Forget(radius, chunk, peer) + if got := records(m); got != 0 { + t.Fatalf("got %d records after forget that follows the pause, want 0", got) + } + + m.Valid(radius, chunk, peer) + m.Forget(radius, chunk, peer) + if neighborhoods, records := m.Size(); neighborhoods != 0 || records != 0 { + t.Fatalf("after forget of a valid record: got %d neighborhoods and %d records, want 0", neighborhoods, records) + } +} + +// TestShallowPause checks the length of the pause that follows a shallow receipt. +func TestShallowPause(t *testing.T) { + t.Parallel() + + var ( + chunk = addr(0x6b, 0x00) + peer = addr(0x10) + ) + + // wantPause checks that the pause of the peer ends after d and not + // one second before. + wantPause := func(t *testing.T, m *firsthop.Memory, clock *testClock, d time.Duration) { + t.Helper() + + clock.Add(d - time.Second) + if !has(m.View(radius, chunk).Paused, peer) { + t.Fatalf("peer is not paused one second before the end of a %s pause", d) + } + clock.Add(time.Second) + if has(m.View(radius, chunk).Paused, peer) { + t.Fatalf("peer is paused after a %s pause", d) + } + } + + for _, tc := range []struct { + name string + // before runs after the first shallow receipt of the peer + before func(m *firsthop.Memory, clock *testClock) + // pauses are the pauses of the shallow receipts that follow, in a row + pauses []time.Duration + }{ + { + name: "doubles up to the maximum", + before: func(_ *firsthop.Memory, clock *testClock) { clock.Add(time.Minute) }, + pauses: []time.Duration{2 * time.Minute, 4 * time.Minute, 8 * time.Minute, 16 * time.Minute, 30 * time.Minute, 30 * time.Minute}, + }, + { + name: "valid receipt starts the count again", + before: func(m *firsthop.Memory, clock *testClock) { + clock.Add(time.Minute) + m.Valid(radius, chunk, peer) + }, + pauses: []time.Duration{time.Minute}, + }, + { + // one hour without a shallow receipt, also when View was not called + name: "idle time starts the count again", + before: func(_ *firsthop.Memory, clock *testClock) { clock.Add(time.Hour) }, + pauses: []time.Duration{time.Minute}, + }, + { + // results of pushes that ran in parallel + name: "receipt during a pause does not make it longer", + before: func(m *firsthop.Memory, clock *testClock) { + m.Shallow(radius, chunk, peer) + clock.Add(30 * time.Second) + }, + pauses: []time.Duration{30 * time.Second}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + m, clock := newMemory() + m.Shallow(radius, chunk, peer) + tc.before(m, clock) + for _, pause := range tc.pauses { + m.Shallow(radius, chunk, peer) + wantPause(t, m, clock, pause) + } + }) + } +} + +// TestIdle checks that a record without a new result is removed: a valid +// record after 30 minutes, a shallow record after one hour. +func TestIdle(t *testing.T) { + t.Parallel() + + var ( + chunk = addr(0x6b, 0x00) + peer = addr(0x10) + ) + + for _, tc := range []struct { + name string + record func(m *firsthop.Memory) + idle time.Duration + }{ + {"valid", func(m *firsthop.Memory) { m.Valid(radius, chunk, peer) }, 30 * time.Minute}, + {"shallow", func(m *firsthop.Memory) { m.Shallow(radius, chunk, peer) }, time.Hour}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + m, clock := newMemory() + tc.record(m) + + clock.Add(tc.idle - time.Second) + m.View(radius, chunk) + if got := records(m); got != 1 { + t.Fatalf("got %d records one second before the end of the idle time, want 1", got) + } + + clock.Add(time.Second) + if v := m.View(radius, chunk); len(v.Valid) != 0 || len(v.Paused) != 0 { + t.Fatalf("idle record is used: valid %v paused %v", v.Valid, v.Paused) + } + if got := records(m); got != 0 { + t.Fatalf("got %d records after the idle time, want 0", got) + } + }) + } +} + +// TestSweep checks that the idle records of a neighborhood that gets no more +// chunks are removed when another neighborhood is used. +func TestSweep(t *testing.T) { + t.Parallel() + + var ( + m, clock = newMemory() + chunk = addr(0x6b, 0x00) + other = addr(0x1c, 0x00) + ) + + m.View(radius, chunk) // the first sweep + m.Valid(radius, chunk, addr(0x10)) + m.Shallow(radius, chunk, addr(0x20)) + + clock.Add(30 * time.Minute) + m.View(radius, other) + if got := records(m); got != 1 { + t.Fatalf("got %d records after 30 minutes, want 1 (the shallow record)", got) + } + + clock.Add(30 * time.Minute) + m.View(radius, other) + if neighborhoods, records := m.Size(); neighborhoods != 0 || records != 0 { + t.Fatalf("after 60 minutes: got %d neighborhoods and %d records, want 0", neighborhoods, records) + } +} + +// TestProbe checks that a neighborhood gets at most one probe per 30 seconds. +func TestProbe(t *testing.T) { + t.Parallel() + + var ( + m, clock = newMemory() + chunk = addr(0x6b, 0x00) + other = addr(0x1c, 0x00) + peer = addr(0x10) + ) + + m.Valid(radius, chunk, peer) + m.Valid(radius, other, peer) + + if !m.View(radius, chunk).ProbeDue { + t.Fatal("probe is not due for a neighborhood that was never probed") + } + if !m.ClaimProbe(radius, chunk) { + t.Fatal("probe that is due was not given") + } + if m.ClaimProbe(radius, chunk) { + t.Fatal("second probe was given right after a probe") + } + if !m.View(radius, other).ProbeDue { + t.Fatal("probe of one neighborhood changed another neighborhood") + } + + // the removal of the last record does not make the next probe due + m.Forget(radius, chunk, peer) + m.Valid(radius, chunk, peer) + + clock.Add(29 * time.Second) + if m.View(radius, chunk).ProbeDue { + t.Fatal("probe is due 29s after a probe") + } + clock.Add(time.Second) + if !m.View(radius, chunk).ProbeDue { + t.Fatal("probe is not due 30s after a probe") + } + + // a neighborhood without records is removed when the interval ends + m.Forget(radius, chunk, peer) + m.Forget(radius, other, peer) + if neighborhoods, _ := m.Size(); neighborhoods != 0 { + t.Fatalf("got %d neighborhoods after the interval, want 0", neighborhoods) + } +} + +// TestNeighborhood checks that the chunks that share the first radius bits +// share the records. +func TestNeighborhood(t *testing.T) { + t.Parallel() + + peer := addr(0x10) + + for _, tc := range []struct { + name string + radius uint8 + chunk swarm.Address + same bool + }{ + // 0x6b3f shares the first 10 bits with 0x6b00, 0x6b40 does not + {"radius 10, same 10 bits", 10, addr(0x6b, 0x3f, 0xff), true}, + {"radius 10, bit 10 differs", 10, addr(0x6b, 0x40), false}, + {"radius 10, bit 8 differs", 10, addr(0x6a, 0x00), false}, + {"radius 8, same byte", 8, addr(0x6b, 0xff), true}, + {"radius 8, bit 8 differs", 8, addr(0x6a, 0x00), false}, + {"radius 0", 0, addr(0xff, 0xff), true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + m, _ := newMemory() + m.Valid(tc.radius, addr(0x6b, 0x00), peer) + + if got := has(m.View(tc.radius, tc.chunk).Valid, peer); got != tc.same { + t.Fatalf("chunk sees the record: got %v, want %v", got, tc.same) + } + }) + } +} + +// TestRadiusChange checks that View at a new radius removes the records of +// the old radius, and that a result of a push that began at the old radius +// is ignored from then on, also when the memory has no records. +func TestRadiusChange(t *testing.T) { + t.Parallel() + + var ( + m, _ = newMemory() + chunk = addr(0x6b, 0x00) + peer = addr(0x10) + late = addr(0x20) + ) + + m.Valid(9, chunk, peer) + m.Shallow(9, chunk, late) + + if v := m.View(10, chunk); len(v.Valid) != 0 || len(v.Paused) != 0 { + t.Fatalf("records of radius 9 are used at radius 10: valid %v paused %v", v.Valid, v.Paused) + } + + lateResults := func() { + t.Helper() + + m.Valid(9, chunk, late) + m.Shallow(9, chunk, late) + m.Forget(9, chunk, peer) + if m.ClaimProbe(9, chunk) { + t.Fatal("probe was given for another radius") + } + } + + lateResults() + if got := records(m); got != 0 { + t.Fatalf("got %d records of the old radius in an empty memory, want 0", got) + } + + m.Valid(10, chunk, peer) + lateResults() + if v := m.View(10, chunk); len(v.Valid) != 1 || !has(v.Valid, peer) || len(v.Paused) != 0 { + t.Fatalf("got valid %v paused %v, want only the record of radius 10", v.Valid, v.Paused) + } +} + +// TestPausedOrder checks that the peers in a pause are returned in the order +// in which their pauses end. +func TestPausedOrder(t *testing.T) { + t.Parallel() + + var ( + m, clock = newMemory() + chunk = addr(0x6b, 0x00) + long = addr(0x6a) + first = addr(0x10) + last = addr(0x20) + ) + + // two shallow receipts in a row: the pause of this peer ends at 3m + m.Shallow(radius, chunk, long) + clock.Add(time.Minute) + m.Shallow(radius, chunk, long) + // these pauses end at 2m10s and 2m20s + clock.Add(10 * time.Second) + m.Shallow(radius, chunk, first) + clock.Add(10 * time.Second) + m.Shallow(radius, chunk, last) + + paused := m.View(radius, chunk).Paused + want := []swarm.Address{first, last, long} + if len(paused) != len(want) { + t.Fatalf("got %d peers in a pause, want %d", len(paused), len(want)) + } + for i := range want { + if !paused[i].Equal(want[i]) { + t.Fatalf("position %d: got %s, want %s", i, paused[i], want[i]) + } + } +} + +// TestConcurrent runs all operations at the same time, for the race detector. +func TestConcurrent(t *testing.T) { + t.Parallel() + + var ( + m, clock = newMemory() + wg sync.WaitGroup + ) + + for i := range 16 { + wg.Go(func() { + r := rand.New(rand.NewSource(int64(i))) + for range 200 { + chunk := addr(byte(r.Intn(4)), byte(r.Intn(256))) + peer := addr(byte(r.Intn(8))) + switch r.Intn(6) { + case 0: + m.Valid(radius, chunk, peer) + case 1: + m.Shallow(radius, chunk, peer) + case 2: + m.Forget(radius, chunk, peer) + case 3: + m.ClaimProbe(radius, chunk) + case 4: + clock.Add(time.Second) + default: + m.View(radius, chunk) + m.Size() + } + } + }) + } + wg.Wait() +} From 788a276d8b47566ddf577ceaeceb4981c5e46d81 Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Sun, 22 Nov 2026 20:45:05 +0100 Subject: [PATCH 15/16] refactor(pushsync): use the firsthop package and move the first hop selection to originPush --- pkg/pushsync/export_test.go | 49 +- pkg/pushsync/firsthop.go | 159 +++++++ pkg/pushsync/firsthop_test.go | 588 ++++++++++++++++++++++++ pkg/pushsync/hopmemory.go | 280 ------------ pkg/pushsync/hopmemory_origin_test.go | 524 --------------------- pkg/pushsync/hopmemory_test.go | 628 -------------------------- pkg/pushsync/metrics.go | 10 +- pkg/pushsync/pushsync.go | 129 +----- 8 files changed, 771 insertions(+), 1596 deletions(-) create mode 100644 pkg/pushsync/firsthop.go create mode 100644 pkg/pushsync/firsthop_test.go delete mode 100644 pkg/pushsync/hopmemory.go delete mode 100644 pkg/pushsync/hopmemory_origin_test.go delete mode 100644 pkg/pushsync/hopmemory_test.go diff --git a/pkg/pushsync/export_test.go b/pkg/pushsync/export_test.go index 62679bae90f..ce4fda3b7e8 100644 --- a/pkg/pushsync/export_test.go +++ b/pkg/pushsync/export_test.go @@ -5,8 +5,7 @@ package pushsync import ( - "time" - + "github.com/ethersphere/bee/v2/pkg/pushsync/internal/firsthop" "github.com/ethersphere/bee/v2/pkg/pushsync/pb" "github.com/ethersphere/bee/v2/pkg/swarm" "github.com/prometheus/client_golang/prometheus" @@ -30,55 +29,13 @@ func (ps *PushSync) CheckReceipt(receipt *pb.Receipt) error { return err } -type HopMemory = hopMemory - -func NewHopMemory(now func() time.Time) *HopMemory { return newHopMemory(now) } - -func (m *hopMemory) RecordValid(rad uint8, chunk, peer swarm.Address) { - m.recordValid(rad, chunk, peer) -} - -func (m *hopMemory) RecordShallow(rad uint8, chunk, peer swarm.Address) { - m.recordShallow(rad, chunk, peer) -} -func (m *hopMemory) Forget(rad uint8, chunk, peer swarm.Address) { m.forget(rad, chunk, peer) } -func (m *hopMemory) ClaimProbe(rad uint8, chunk swarm.Address) bool { - return m.claimProbe(rad, chunk) -} - -// Len returns the number of records. -func (m *hopMemory) Len() int { - _, records := m.size() - return records -} - -// Hoods returns the number of neighborhoods. -func (m *hopMemory) Hoods() int { - hoods, _ := m.size() - return hoods -} - -func (m *hopMemory) View(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { - return m.view(rad, chunk) -} - -// SetHopClock replaces the clock of the first-hop memory. -func (ps *PushSync) SetHopClock(now func() time.Time) { - ps.hops.mtx.Lock() - defer ps.hops.mtx.Unlock() - ps.hops.now = now -} - -// HopRecords returns the number of first-hop records. -func (ps *PushSync) HopRecords() int { return ps.hops.Len() } +// FirstHops returns the first-hop memory. +func (ps *PushSync) FirstHops() *firsthop.Memory { return ps.firstHops } func (ps *PushSync) FirstHopCount(source, result string) float64 { return counterValue(ps.metrics.FirstHop.WithLabelValues(source, result)) } -// Hops returns the first-hop memory. -func (ps *PushSync) Hops() *HopMemory { return ps.hops } - func counterValue(c prometheus.Counter) float64 { var m dto.Metric if err := c.Write(&m); err != nil { diff --git a/pkg/pushsync/firsthop.go b/pkg/pushsync/firsthop.go new file mode 100644 index 00000000000..11d42b8a188 --- /dev/null +++ b/pkg/pushsync/firsthop.go @@ -0,0 +1,159 @@ +// Copyright 2026 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pushsync + +import ( + "errors" + "slices" + + "github.com/ethersphere/bee/v2/pkg/swarm" + "github.com/ethersphere/bee/v2/pkg/topology" +) + +// firstHopSource says why an origin picked a first hop. +type firstHopSource string + +const ( + firstHopSourceProbe firstHopSource = "probe" + firstHopSourceValid firstHopSource = "known_valid" + firstHopSourceUnknown firstHopSource = "unknown" + firstHopSourcePaused firstHopSource = "paused" +) + +// originPush picks the first hops of one push of an origin and records +// their results in the first-hop memory. +type originPush struct { + ps *PushSync + chunk swarm.Address + probed bool // the push made its probe + sources map[string]firstHopSource // why each first hop was picked +} + +func (ps *PushSync) newOriginPush(chunk swarm.Address) *originPush { + return &originPush{ + ps: ps, + chunk: chunk, + sources: make(map[string]firstHopSource), + } +} + +// next picks the next first hop that is not in skip: +// 1. a probe, at most once per push and per probe interval of the +// neighborhood: a peer closer to the chunk than every peer with a valid +// record; +// 2. the closest peer with a valid record; +// 3. the closest peer that is not in a shallow pause; +// 4. the peer whose shallow pause ends first, unless the origin can store +// the chunk itself. +func (o *originPush) next(radius uint8, skip []swarm.Address) (swarm.Address, error) { + peer, source, err := o.pick(radius, skip) + if err != nil { + return swarm.ZeroAddress, err + } + o.probed = o.probed || source == firstHopSourceProbe + o.sources[peer.ByteString()] = source + return peer, nil +} + +func (o *originPush) pick(radius uint8, skip []swarm.Address) (swarm.Address, firstHopSource, error) { + ps := o.ps + view := ps.firstHops.View(radius, o.chunk) + + valid := o.connectedValid(radius, view.Valid) + if known := closestOf(o.chunk, valid, skip); !known.IsZero() { + if view.ProbeDue && !o.probed { + candidate, err := ps.closestPeer(o.chunk, true, slices.Concat(skip, view.Paused, valid)) + if err == nil { + if closer, _ := candidate.Closer(o.chunk, known); closer && ps.firstHops.ClaimProbe(radius, o.chunk) { + return candidate, firstHopSourceProbe, nil + } + } + } + return known, firstHopSourceValid, nil + } + + peer, err := ps.closestPeer(o.chunk, true, slices.Concat(skip, view.Paused)) + if !errors.Is(err, topology.ErrNotFound) || len(view.Paused) == 0 { + return peer, firstHopSourceUnknown, err + } + if ps.fullNode && swarm.Proximity(ps.address.Bytes(), o.chunk.Bytes()) >= radius { + return peer, firstHopSourceUnknown, err + } + + // Every peer left is in a shallow pause. Waiting would hold a push slot + // of the pusher, so send through the connected peer whose pause ends first. + connected := ps.connectedOf(view.Paused) + for _, p := range view.Paused { + if swarm.ContainsAddress(connected, p) && !swarm.ContainsAddress(skip, p) { + return p, firstHopSourcePaused, nil + } + } + + return peer, firstHopSourceUnknown, err +} + +// connectedValid returns the peers with a valid record that are connected, +// and removes the valid records of the others. +func (o *originPush) connectedValid(radius uint8, valid []swarm.Address) []swarm.Address { + if len(valid) == 0 { + return nil + } + connected := o.ps.connectedOf(valid) + for _, p := range valid { + if !swarm.ContainsAddress(connected, p) { + o.ps.firstHops.Forget(radius, o.chunk, p) + } + } + return connected +} + +// closestOf returns the peer closest to the chunk among the peers that are +// not in skip, or the zero address. +func closestOf(chunk swarm.Address, peers, skip []swarm.Address) swarm.Address { + closest := swarm.ZeroAddress + for _, p := range peers { + if swarm.ContainsAddress(skip, p) { + continue + } + if closest.IsZero() { + closest = p + continue + } + if closer, _ := p.Closer(chunk, closest); closer { + closest = p + } + } + return closest +} + +// record stores the result of a push to a first hop: a valid receipt (err is +// nil), a shallow receipt, or an error, which removes the record of the peer. +func (o *originPush) record(radius uint8, peer swarm.Address, err error) { + result := "error" + switch { + case err == nil: + result = "valid" + o.ps.firstHops.Valid(radius, o.chunk, peer) + case errors.Is(err, ErrShallowReceipt): + result = "shallow" + o.ps.firstHops.Shallow(radius, o.chunk, peer) + default: + o.ps.firstHops.Forget(radius, o.chunk, peer) + } + o.ps.metrics.FirstHop.WithLabelValues(string(o.sources[peer.ByteString()]), result).Inc() +} + +// connectedOf returns the peers that are connected, in one pass over the +// connected peers. +func (ps *PushSync) connectedOf(peers []swarm.Address) []swarm.Address { + var connected []swarm.Address + _ = ps.topologyDriver.EachConnectedPeer(func(p swarm.Address, _ uint8) (bool, bool, error) { + if swarm.ContainsAddress(peers, p) { + connected = append(connected, p) + } + return len(connected) == len(peers), false, nil + }, topology.Select{}) + return connected +} diff --git a/pkg/pushsync/firsthop_test.go b/pkg/pushsync/firsthop_test.go new file mode 100644 index 00000000000..8366fa54505 --- /dev/null +++ b/pkg/pushsync/firsthop_test.go @@ -0,0 +1,588 @@ +// Copyright 2026 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pushsync_test + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + accountingmock "github.com/ethersphere/bee/v2/pkg/accounting/mock" + "github.com/ethersphere/bee/v2/pkg/crypto" + "github.com/ethersphere/bee/v2/pkg/log" + "github.com/ethersphere/bee/v2/pkg/p2p" + "github.com/ethersphere/bee/v2/pkg/p2p/streamtest" + pricermock "github.com/ethersphere/bee/v2/pkg/pricer/mock" + "github.com/ethersphere/bee/v2/pkg/pushsync" + "github.com/ethersphere/bee/v2/pkg/soc" + stabilmock "github.com/ethersphere/bee/v2/pkg/stabilization/mock" + testingc "github.com/ethersphere/bee/v2/pkg/storage/testing" + "github.com/ethersphere/bee/v2/pkg/swarm" + "github.com/ethersphere/bee/v2/pkg/topology" + "github.com/ethersphere/bee/v2/pkg/topology/mock" +) + +const hopRadius = 2 + +// hopNet is an origin with first hops whose receipts the test controls. +// The origin knows each first hop by an address outside the neighborhood, so +// the order of the first hops is the same for every chunk. The node behind a +// first hop signs with a key whose overlay is inside the neighborhood (valid +// receipt) or outside of it (shallow receipt). +type hopNet struct { + t *testing.T + anchor swarm.Address // an address inside the neighborhood of the chunks + topo interface{ Disconnected(p2p.Peer) } + hops []swarm.Address // first hops as the origin knows them, closest first + origin *pushsync.PushSync + recorder *streamtest.Recorder + handlers map[string]p2p.ProtocolSpec + nodes byte + radius atomic.Uint32 // storage radius of the origin +} + +// flipBits returns a copy of the address with the given bits flipped. +func flipBits(a swarm.Address, bits ...int) swarm.Address { + b := a.Clone().Bytes() + for _, i := range bits { + b[i/8] ^= 0x80 >> (i % 8) + } + return swarm.NewAddress(b) +} + +// hopSigner returns a signer whose overlay is inside (near) or far outside +// the neighborhood of the anchor. +func hopSigner(t *testing.T, anchor swarm.Address, near bool) crypto.Signer { + t.Helper() + + for { + key, err := crypto.GenerateSecp256k1Key() + if err != nil { + t.Fatal(err) + } + signer := crypto.NewDefaultSigner(key) + pubKey, err := signer.PublicKey() + if err != nil { + t.Fatal(err) + } + overlay, err := crypto.NewOverlayAddress(*pubKey, 1, blockHash.Bytes()) + if err != nil { + t.Fatal(err) + } + po := swarm.Proximity(overlay.Bytes(), anchor.Bytes()) + if (near && po > hopRadius) || (!near && po == 0) { + return signer + } + } +} + +// newHopNet makes an origin with n first hops; a lower index is closer to +// the chunks. insideAOR puts the origin inside the neighborhood. +func newHopNet(t *testing.T, insideAOR bool, hops int) *hopNet { + t.Helper() + + n := &hopNet{ + t: t, + anchor: swarm.RandAddress(t), + handlers: make(map[string]p2p.ProtocolSpec), + } + n.radius.Store(hopRadius) + + // all first hops differ from the neighborhood in bit 0; the next bits + // set their order + for _, bits := range [][]int{{0}, {0, 2}, {0, 1}}[:hops] { + n.hops = append(n.hops, flipBits(n.anchor, bits...)) + } + + originAddr := flipBits(n.anchor, 0, 255) + if insideAOR { + originAddr = flipBits(n.anchor, 255) + } + + topo := mock.NewTopologyDriver(mock.WithPeers(n.hops...)) + n.topo = topo + + n.recorder = streamtest.New(streamtest.WithPeerProtocols(n.handlers), streamtest.WithBaseAddr(originAddr)) + n.origin = pushsync.New( + originAddr, 1, blockHash.Bytes(), + streamtest.NewRecorderDisconnecter(n.recorder), + &testStorer{chunksPut: make(map[string]swarm.Chunk), chunksReported: make(map[string]int)}, + func() (uint8, error) { return uint8(n.radius.Load()), nil }, + topo, true, + func(swarm.Chunk) {}, func(*soc.SOC) {}, + func(ch swarm.Chunk) (swarm.Chunk, error) { return ch, nil }, + log.Noop, accountingmock.NewAccounting(), + pricermock.NewMockService(defaultPrices.price, defaultPrices.peerPrice), + nil, nil, stabilmock.NewSubscriber(true), + ) + t.Cleanup(func() { n.origin.Close() }) + + return n +} + +// setReceipt makes the first hop answer with a valid or a shallow receipt. +func (n *hopNet) setReceipt(hop swarm.Address, valid bool) { + n.t.Helper() + + n.nodes++ + self := n.anchor.Clone().Bytes() + self[swarm.HashSize-1] ^= n.nodes + + node, _ := createPushSyncNodeWithRadius(n.t, swarm.NewAddress(self), defaultPrices, nil, nil, hopSigner(n.t, n.anchor, valid), hopRadius, mock.WithClosestPeerErr(topology.ErrWantSelf)) + n.handlers[hop.String()] = node.Protocol() +} + +// setGone makes every push to the first hop return an error. +func (n *hopNet) setGone(hop swarm.Address) { + delete(n.handlers, hop.String()) +} + +// beforeReceipt runs f at the first hop before it handles each push. +func (n *hopNet) beforeReceipt(hop swarm.Address, f func()) { + spec := n.handlers[hop.String()] + handler := spec.StreamSpecs[0].Handler + spec.StreamSpecs = []p2p.StreamSpec{spec.StreamSpecs[0]} + spec.StreamSpecs[0].Handler = func(ctx context.Context, p p2p.Peer, s p2p.Stream) error { + f() + return handler(ctx, p, s) + } + n.handlers[hop.String()] = spec +} + +func (n *hopNet) chunk() swarm.Chunk { + n.t.Helper() + return testingc.GenerateValidRandomChunkAt(n.t, n.anchor, hopRadius) +} + +// streams returns the number of pushes the origin sent to the first hop. +func (n *hopNet) streams(hop swarm.Address) int { + recs, _ := n.recorder.Records(hop, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName) + return len(recs) +} + +func (n *hopNet) wantStreams(hop swarm.Address, want int) { + n.t.Helper() + if got := n.streams(hop); got != want { + n.t.Fatalf("first hop %s: got %d pushes, want %d", hop.String()[:4], got, want) + } +} + +func (n *hopNet) wantFirstHop(source, result string, want float64) { + n.t.Helper() + if got := n.origin.FirstHopCount(source, result); got != want { + n.t.Fatalf("first hop metric %s/%s: got %v, want %v", source, result, got, want) + } +} + +func (n *hopNet) push() error { + _, err := n.origin.PushChunkToClosest(context.Background(), n.chunk()) + return err +} + +func (n *hopNet) pushValid() { + n.t.Helper() + if err := n.push(); err != nil { + n.t.Fatalf("got %v, want a valid receipt", err) + } +} + +func (n *hopNet) pushShallow() { + n.t.Helper() + if err := n.push(); !errors.Is(err, pushsync.ErrShallowReceipt) { + n.t.Fatalf("got %v, want %v", err, pushsync.ErrShallowReceipt) + } +} + +// hopRecords returns the number of records in the first-hop memory of the node. +func hopRecords(ps *pushsync.PushSync) int { + _, records := ps.FirstHops().Size() + return records +} + +// TestOriginPrefersKnownValidPeer checks that the next chunk goes to the +// first hop with a valid record, not to a closer one that gave a shallow receipt. +func TestOriginPrefersKnownValidPeer(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 2) + shallow, valid := n.hops[0], n.hops[1] + n.setReceipt(shallow, false) + n.setReceipt(valid, true) + + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(valid, 1) + + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(valid, 2) + + n.wantFirstHop("unknown", "shallow", 1) + n.wantFirstHop("unknown", "valid", 1) + n.wantFirstHop("known_valid", "valid", 1) + }) +} + +// TestOriginPausedPeerLast checks that a first hop in a shallow pause is not +// used while another first hop is left. +func TestOriginPausedPeerLast(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 2) + shallow, other := n.hops[0], n.hops[1] + n.setReceipt(shallow, false) + + // the farther first hop gives an error, so it gets no record + n.pushShallow() + n.wantStreams(shallow, 1) + n.wantFirstHop("unknown", "error", 1) + + n.setReceipt(other, true) + time.Sleep(59 * time.Second) + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(other, 1) + n.wantFirstHop("unknown", "valid", 1) + n.wantFirstHop("paused", "shallow", 0) + }) +} + +// TestOriginAllPeersPaused checks that the origin sends through the first +// hops in a shallow pause when no other first hop is left, and that these +// sends do not make the pauses longer. +func TestOriginAllPeersPaused(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 2) + n.setReceipt(n.hops[0], false) + n.setReceipt(n.hops[1], false) + + n.pushShallow() + n.wantStreams(n.hops[0], 1) + n.wantStreams(n.hops[1], 1) + + time.Sleep(30 * time.Second) + n.pushShallow() + n.wantStreams(n.hops[0], 2) + n.wantStreams(n.hops[1], 2) + n.wantFirstHop("paused", "shallow", 2) + + // the pauses still end 60s after the first shallow receipts + n.setReceipt(n.hops[1], true) + time.Sleep(30 * time.Second) + n.pushValid() + n.wantStreams(n.hops[0], 3) + n.wantStreams(n.hops[1], 3) + n.wantFirstHop("unknown", "shallow", 3) + n.wantFirstHop("unknown", "valid", 1) + }) +} + +// TestOriginAllPausedInsideAOR checks that an origin inside the +// neighborhood stores the chunk itself when every first hop is paused. +func TestOriginAllPausedInsideAOR(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, true, 1) + n.setReceipt(n.hops[0], false) + + n.pushShallow() + n.wantStreams(n.hops[0], 1) + + if err := n.push(); !errors.Is(err, topology.ErrWantSelf) { + t.Fatalf("got %v, want %v", err, topology.ErrWantSelf) + } + n.wantStreams(n.hops[0], 1) + }) +} + +// TestOriginValidPeerError checks that an error removes a valid record and +// that the chunk gets a valid receipt from another first hop in the same call. +func TestOriginValidPeerError(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 2) + first, second := n.hops[0], n.hops[1] + n.setReceipt(first, true) + n.setReceipt(second, true) + + n.pushValid() + n.wantStreams(first, 1) + n.wantStreams(second, 0) + + n.setGone(first) + + n.pushValid() + n.wantStreams(second, 1) + n.wantFirstHop("known_valid", "error", 1) + n.wantFirstHop("unknown", "valid", 2) + if got := hopRecords(n.origin); got != 1 { + t.Fatalf("got %d records, want 1", got) + } + }) +} + +// TestOriginSkipsDisconnectedValidPeer checks that a disconnected first hop +// with a valid record is not picked and loses the record. +func TestOriginSkipsDisconnectedValidPeer(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 2) + valid, shallow := n.hops[0], n.hops[1] + n.setReceipt(valid, true) + n.setReceipt(shallow, false) + + n.pushValid() + n.wantStreams(valid, 1) + n.wantStreams(shallow, 0) + + n.topo.Disconnected(p2p.Peer{Address: valid}) + + n.pushShallow() + n.wantStreams(valid, 1) + n.wantStreams(shallow, 1) + if got := hopRecords(n.origin); got != 1 { + t.Fatalf("got %d records, want 1", got) + } + }) +} + +// TestOriginSkipsValidPeerInFlight checks that a push that waits for a first +// hop with a valid record sends to another first hop, not to the same one again. +func TestOriginSkipsValidPeerInFlight(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 2) + slow, other := n.hops[0], n.hops[1] + n.setReceipt(slow, true) + n.setReceipt(other, true) + + n.pushValid() + n.wantStreams(slow, 1) + + // the answer takes longer than the time to the next attempt + n.beforeReceipt(slow, func() { time.Sleep(6 * time.Second) }) + + n.pushValid() + n.wantStreams(slow, 2) + n.wantStreams(other, 1) + }) +} + +// TestOriginProbe checks that a closer first hop is probed after its pause, +// that the chunk still gets the valid receipt of the known first hop, and +// that a closer first hop that gives a valid receipt on a probe is used first +// from then on. +func TestOriginProbe(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 2) + shallow, valid := n.hops[0], n.hops[1] + n.setReceipt(shallow, false) + n.setReceipt(valid, true) + + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(valid, 1) + + // the pause of the closer first hop is not over: no probe + time.Sleep(59 * time.Second) + n.pushValid() + n.wantStreams(shallow, 1) + n.wantStreams(valid, 2) + + time.Sleep(time.Second) + n.pushValid() + n.wantStreams(shallow, 2) + n.wantStreams(valid, 3) + n.wantFirstHop("probe", "shallow", 1) + + // the second shallow receipt in a row doubles the pause + time.Sleep(119 * time.Second) + n.pushValid() + n.wantStreams(shallow, 2) + n.wantStreams(valid, 4) + + // a valid receipt on a probe: the closer first hop is used first + // from then on + n.setReceipt(shallow, true) + time.Sleep(time.Second) + n.pushValid() + n.wantStreams(shallow, 3) + n.wantStreams(valid, 4) + n.wantFirstHop("probe", "valid", 1) + + n.pushValid() + n.wantStreams(shallow, 4) + n.wantStreams(valid, 4) + }) +} + +// TestOriginProbeInterval checks that a neighborhood gets at most one probe +// per 30s. +func TestOriginProbeInterval(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 3) + n.setReceipt(n.hops[0], false) + n.setReceipt(n.hops[1], false) + n.setReceipt(n.hops[2], true) + + n.pushValid() + n.wantStreams(n.hops[0], 1) + n.wantStreams(n.hops[1], 1) + n.wantStreams(n.hops[2], 1) + + // both pauses are over: the first chunk probes the closest first hop + time.Sleep(time.Minute) + n.pushValid() + n.wantStreams(n.hops[0], 2) + n.wantStreams(n.hops[1], 1) + + // the next chunk comes before the end of the probe interval + time.Sleep(29 * time.Second) + n.pushValid() + n.wantStreams(n.hops[1], 1) + + time.Sleep(time.Second) + n.pushValid() + n.wantStreams(n.hops[0], 2) + n.wantStreams(n.hops[1], 2) + n.wantFirstHop("probe", "shallow", 2) + n.wantStreams(n.hops[2], 4) + }) +} + +// TestOriginRadiusChangeBeforeNextAttempt checks that an attempt that starts +// without a result of the attempt before it selects its first hop at the +// radius of that moment, so that its result is recorded at the new radius. +func TestOriginRadiusChangeBeforeNextAttempt(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 2) + slow, other := n.hops[0], n.hops[1] + n.setReceipt(slow, true) + n.setReceipt(other, true) + + // the radius of the origin grows while the first attempt is on its + // way, and the answer takes longer than the time to the next attempt + n.beforeReceipt(slow, func() { + n.radius.Store(hopRadius + 1) + time.Sleep(6 * time.Second) + }) + + ch := testingc.GenerateValidRandomChunkAt(t, n.anchor, hopRadius+1) + if _, err := n.origin.PushChunkToClosest(context.Background(), ch); err != nil { + t.Fatalf("got %v, want a valid receipt", err) + } + n.wantStreams(slow, 1) + n.wantStreams(other, 1) + + if got := hopRecords(n.origin); got != 1 { + t.Fatalf("got %d records, want 1", got) + } + view := n.origin.FirstHops().View(hopRadius+1, ch.Address()) + if len(view.Valid) != 1 || !view.Valid[0].Equal(other) || len(view.Paused) != 0 { + t.Fatalf("got valid %v paused %v, want the valid record of the second first hop at the new radius", view.Valid, view.Paused) + } + }) +} + +// TestOriginRadiusChangeBeforeResult checks that a result is recorded at the +// radius of the moment it arrives: a result of an attempt that began at the +// old radius is not recorded at it, and the next push records at the new radius. +func TestOriginRadiusChangeBeforeResult(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 1) + hop := n.hops[0] + n.setReceipt(hop, true) + + // the radius of the origin grows while the only attempt is on its way + n.beforeReceipt(hop, func() { n.radius.Store(hopRadius + 1) }) + + ch := testingc.GenerateValidRandomChunkAt(t, n.anchor, hopRadius+1) + if _, err := n.origin.PushChunkToClosest(context.Background(), ch); err != nil { + t.Fatalf("got %v, want a valid receipt", err) + } + n.wantStreams(hop, 1) + if got := hopRecords(n.origin); got != 0 { + t.Fatalf("got %d records of a push that began at the old radius, want 0", got) + } + + if _, err := n.origin.PushChunkToClosest(context.Background(), ch); err != nil { + t.Fatalf("got %v, want a valid receipt", err) + } + n.wantStreams(hop, 2) + if got := hopRecords(n.origin); got != 1 { + t.Fatalf("got %d records, want 1", got) + } + view := n.origin.FirstHops().View(hopRadius+1, ch.Address()) + if len(view.Valid) != 1 || !view.Valid[0].Equal(hop) || len(view.Paused) != 0 { + t.Fatalf("got valid %v paused %v, want the valid record of the first hop at the new radius", view.Valid, view.Paused) + } + }) +} + +// TestForwarderDoesNotUseHopMemory checks that a forwarder neither reads +// nor writes first-hop records. +func TestForwarderDoesNotUseHopMemory(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + n := newHopNet(t, false, 1) + storer := flipBits(n.anchor, 254) + + storerNode, _ := createPushSyncNodeWithRadius(t, storer, defaultPrices, nil, nil, hopSigner(t, n.anchor, true), hopRadius, mock.WithClosestPeerErr(topology.ErrWantSelf)) + + // the forwarder and its two peers are outside the neighborhood; every + // push of the forwarder gets to the storer + forwarderAddr := flipBits(n.anchor, 0, 254) + closer, farther := flipBits(n.anchor, 1), flipBits(n.anchor, 0, 2) + forwarderRecorder := streamtest.New(streamtest.WithProtocols(storerNode.Protocol()), streamtest.WithBaseAddr(forwarderAddr)) + forwarder, _ := createPushSyncNodeWithRadius(t, forwarderAddr, defaultPrices, forwarderRecorder, nil, nil, hopRadius, mock.WithPeers(closer, farther)) + n.handlers[n.hops[0].String()] = forwarder.Protocol() + + // an origin with these records sends to the farther peer first + chunk := n.chunk() + forwarder.FirstHops().View(hopRadius, chunk.Address()) + forwarder.FirstHops().Valid(hopRadius, chunk.Address(), farther) + forwarder.FirstHops().ClaimProbe(hopRadius, chunk.Address()) + + if _, err := n.origin.PushChunkToClosest(context.Background(), chunk); err != nil { + t.Fatalf("got %v, want a valid receipt", err) + } + + if got := n.streams(n.hops[0]); got != 1 { + t.Fatalf("got %d pushes to the forwarder, want 1", got) + } + if recs, _ := forwarderRecorder.Records(closer, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName); len(recs) != 1 { + t.Fatalf("got %d pushes to the closest peer, want 1", len(recs)) + } + if recs, _ := forwarderRecorder.Records(farther, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName); len(recs) != 0 { + t.Fatalf("got %d pushes to the peer with a valid record, want 0", len(recs)) + } + if got := hopRecords(forwarder); got != 1 { + t.Fatalf("forwarder has %d first-hop records, want the 1 that the test made", got) + } + if got := hopRecords(n.origin); got != 1 { + t.Fatalf("origin has %d first-hop records, want 1", got) + } + }) +} diff --git a/pkg/pushsync/hopmemory.go b/pkg/pushsync/hopmemory.go deleted file mode 100644 index 98144c63d01..00000000000 --- a/pkg/pushsync/hopmemory.go +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright 2026 The Swarm Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pushsync - -import ( - "slices" - "sync" - "time" - - "github.com/ethersphere/bee/v2/pkg/swarm" -) - -const ( - // hopShallowPause is the pause of a first hop after a shallow receipt. - // It doubles with each shallow receipt in a row, up to hopShallowMaxPause. - hopShallowPause = time.Minute - hopShallowMaxPause = 30 * time.Minute - // hopProbeInterval is the shortest time between two probes of a neighborhood. - hopProbeInterval = 30 * time.Second - // hopValidIdle and hopShallowIdle are the times after which a record - // without a new result is removed. - hopValidIdle = 30 * time.Minute - hopShallowIdle = 2 * hopShallowMaxPause - // hopSweepInterval is the shortest time between two removals of idle - // records in all neighborhoods. - hopSweepInterval = hopValidIdle -) - -// hopRecord is the last result of one first hop for one neighborhood. -type hopRecord struct { - peer swarm.Address - valid bool - at time.Time - shallow int // shallow receipts in a row -} - -// blockedUntil returns the end of the pause of a shallow record. -func (r *hopRecord) blockedUntil() time.Time { - pause := hopShallowPause - for i := 1; i < r.shallow && pause < hopShallowMaxPause; i++ { - pause *= 2 - } - return r.at.Add(min(pause, hopShallowMaxPause)) -} - -// idle reports whether the record had no new result for long enough to be removed. -func (r *hopRecord) idle(now time.Time) bool { - if r.valid { - return now.Sub(r.at) >= hopValidIdle - } - return now.Sub(r.at) >= hopShallowIdle -} - -type hopHood struct { - peers map[string]*hopRecord - lastProbe time.Time -} - -// hopMemory keeps the last receipt result of each first hop per neighborhood -// (the chunk addresses that share the first radius bits). -type hopMemory struct { - mtx sync.Mutex - now func() time.Time - radius uint8 - radiusSet bool // false until the first use of the memory - hoods map[string]*hopHood - lastSweep time.Time -} - -func newHopMemory(now func() time.Time) *hopMemory { - return &hopMemory{ - now: now, - hoods: make(map[string]*hopHood), - } -} - -// hoodKey returns the first rad bits of the chunk address. -func hoodKey(rad uint8, chunk swarm.Address) string { - b := chunk.Bytes() - if int(rad) >= len(b)*8 { - return string(b) - } - n, rem := int(rad/8), rad%8 - if rem == 0 { - return string(b[:n]) - } - key := make([]byte, n+1) - copy(key, b[:n]) - key[n] = b[n] & (0xff << (8 - rem)) - return string(key) -} - -// useRadius reports whether the memory holds records of the radius. Only a -// selection (change is true) drops the records of another radius, so that a -// late result of a push that began at the old radius is ignored, also when -// the memory has no records. -// Must be called with the lock held. -func (m *hopMemory) useRadius(rad uint8, change bool) bool { - if m.radiusSet && rad == m.radius { - return true - } - if m.radiusSet && !change { - return false - } - m.radius, m.radiusSet = rad, true - clear(m.hoods) - return true -} - -// hood returns the neighborhood of the chunk. -// Must be called with the lock held. -func (m *hopMemory) hood(rad uint8, chunk swarm.Address, create bool) *hopHood { - key := hoodKey(rad, chunk) - h := m.hoods[key] - if h == nil && create { - h = &hopHood{peers: make(map[string]*hopRecord)} - m.hoods[key] = h - } - return h -} - -// dropEmpty removes the neighborhood when it has no records and its last -// probe no longer limits the next one. -// Must be called with the lock held. -func (m *hopMemory) dropEmpty(key string, h *hopHood, now time.Time) { - if len(h.peers) == 0 && now.Sub(h.lastProbe) >= hopProbeInterval { - delete(m.hoods, key) - } -} - -// sweep removes the idle records of all neighborhoods, at most once per -// hopSweepInterval. Without it the records of a neighborhood that gets no -// more chunks would stay until the radius changes. -// Must be called with the lock held. -func (m *hopMemory) sweep(now time.Time) { - if now.Sub(m.lastSweep) < hopSweepInterval { - return - } - m.lastSweep = now - for key, h := range m.hoods { - for peer, r := range h.peers { - if r.idle(now) { - delete(h.peers, peer) - } - } - m.dropEmpty(key, h, now) - } -} - -// size returns the number of neighborhoods and the number of records. -func (m *hopMemory) size() (hoods, records int) { - m.mtx.Lock() - defer m.mtx.Unlock() - - for _, h := range m.hoods { - records += len(h.peers) - } - return len(m.hoods), records -} - -// recordValid stores a valid receipt of the peer. -func (m *hopMemory) recordValid(rad uint8, chunk, peer swarm.Address) { - m.mtx.Lock() - defer m.mtx.Unlock() - - if !m.useRadius(rad, false) { - return - } - m.hood(rad, chunk, true).peers[peer.ByteString()] = &hopRecord{peer: peer, valid: true, at: m.now()} -} - -// recordShallow stores a shallow receipt of the peer. A receipt that comes -// during the pause of the peer does not make the pause longer. -func (m *hopMemory) recordShallow(rad uint8, chunk, peer swarm.Address) { - m.mtx.Lock() - defer m.mtx.Unlock() - - if !m.useRadius(rad, false) { - return - } - now := m.now() - h := m.hood(rad, chunk, true) - r := h.peers[peer.ByteString()] - if r == nil { - r = &hopRecord{peer: peer} - h.peers[peer.ByteString()] = r - } - if !r.valid && r.shallow > 0 && now.Before(r.blockedUntil()) { - return - } - // idle record that view did not remove yet - if !r.valid && now.Sub(r.at) >= hopShallowIdle { - r.shallow = 0 - } - r.valid = false - r.shallow++ - r.at = now -} - -// forget removes the record of the peer, except a shallow record whose -// pause still runs. -func (m *hopMemory) forget(rad uint8, chunk, peer swarm.Address) { - m.mtx.Lock() - defer m.mtx.Unlock() - - if !m.useRadius(rad, false) { - return - } - h := m.hood(rad, chunk, false) - if h == nil { - return - } - if r := h.peers[peer.ByteString()]; r != nil && !r.valid && m.now().Before(r.blockedUntil()) { - return - } - delete(h.peers, peer.ByteString()) - m.dropEmpty(hoodKey(rad, chunk), h, m.now()) -} - -// view returns the peers with a valid record, the peers in a shallow pause -// (the pause that ends first comes first), and whether a probe of the -// neighborhood is due. -func (m *hopMemory) view(rad uint8, chunk swarm.Address) (valid, blocked []swarm.Address, probeDue bool) { - m.mtx.Lock() - defer m.mtx.Unlock() - - m.useRadius(rad, true) - now := m.now() - m.sweep(now) - h := m.hood(rad, chunk, false) - if h == nil { - return nil, nil, true - } - - var paused []*hopRecord - for key, r := range h.peers { - switch { - case r.idle(now): - delete(h.peers, key) - case r.valid: - valid = append(valid, r.peer) - case now.Before(r.blockedUntil()): - paused = append(paused, r) - } - } - slices.SortFunc(paused, func(a, b *hopRecord) int { - if c := a.blockedUntil().Compare(b.blockedUntil()); c != 0 { - return c - } - c, _ := swarm.DistanceCmp(chunk, b.peer, a.peer) - return c - }) - for _, r := range paused { - blocked = append(blocked, r.peer) - } - m.dropEmpty(hoodKey(rad, chunk), h, now) - - return valid, blocked, h.lastProbe.IsZero() || now.Sub(h.lastProbe) >= hopProbeInterval -} - -// claimProbe reports whether a probe of the neighborhood is due, and stores -// the time of the probe when it is. Of the callers that run at the same time, -// only one gets true. -func (m *hopMemory) claimProbe(rad uint8, chunk swarm.Address) bool { - m.mtx.Lock() - defer m.mtx.Unlock() - - if !m.useRadius(rad, false) { - return false - } - now := m.now() - h := m.hood(rad, chunk, true) - if !h.lastProbe.IsZero() && now.Sub(h.lastProbe) < hopProbeInterval { - return false - } - h.lastProbe = now - return true -} diff --git a/pkg/pushsync/hopmemory_origin_test.go b/pkg/pushsync/hopmemory_origin_test.go deleted file mode 100644 index 66493bf6ab7..00000000000 --- a/pkg/pushsync/hopmemory_origin_test.go +++ /dev/null @@ -1,524 +0,0 @@ -// Copyright 2026 The Swarm Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pushsync_test - -import ( - "context" - "errors" - "sync/atomic" - "testing" - "time" - - accountingmock "github.com/ethersphere/bee/v2/pkg/accounting/mock" - "github.com/ethersphere/bee/v2/pkg/crypto" - "github.com/ethersphere/bee/v2/pkg/log" - "github.com/ethersphere/bee/v2/pkg/p2p" - "github.com/ethersphere/bee/v2/pkg/p2p/streamtest" - pricermock "github.com/ethersphere/bee/v2/pkg/pricer/mock" - "github.com/ethersphere/bee/v2/pkg/pushsync" - "github.com/ethersphere/bee/v2/pkg/soc" - stabilmock "github.com/ethersphere/bee/v2/pkg/stabilization/mock" - testingc "github.com/ethersphere/bee/v2/pkg/storage/testing" - "github.com/ethersphere/bee/v2/pkg/swarm" - "github.com/ethersphere/bee/v2/pkg/topology" - "github.com/ethersphere/bee/v2/pkg/topology/mock" -) - -const hopRadius = 2 - -// hopNet is an origin with first hops whose receipts the test controls. -// The origin knows each first hop by an address outside the neighborhood, so -// the order of the first hops is the same for every chunk. The node behind a -// first hop signs with a key whose overlay is inside the neighborhood (valid -// receipt) or outside of it (shallow receipt). -type hopNet struct { - t *testing.T - anchor swarm.Address // an address inside the neighborhood of the chunks - topo interface{ Disconnected(p2p.Peer) } - hops []swarm.Address // first hops as the origin knows them, closest first - origin *pushsync.PushSync - recorder *streamtest.Recorder - handlers map[string]p2p.ProtocolSpec - clock *testClock - nodes byte - radius atomic.Uint32 // storage radius of the origin -} - -// flipBits returns a copy of the address with the given bits flipped. -func flipBits(a swarm.Address, bits ...int) swarm.Address { - b := a.Clone().Bytes() - for _, i := range bits { - b[i/8] ^= 0x80 >> (i % 8) - } - return swarm.NewAddress(b) -} - -// hopSigner returns a signer whose overlay is inside (near) or far outside -// the neighborhood of the anchor. -func hopSigner(t *testing.T, anchor swarm.Address, near bool) crypto.Signer { - t.Helper() - - for { - key, err := crypto.GenerateSecp256k1Key() - if err != nil { - t.Fatal(err) - } - signer := crypto.NewDefaultSigner(key) - pubKey, err := signer.PublicKey() - if err != nil { - t.Fatal(err) - } - overlay, err := crypto.NewOverlayAddress(*pubKey, 1, blockHash.Bytes()) - if err != nil { - t.Fatal(err) - } - po := swarm.Proximity(overlay.Bytes(), anchor.Bytes()) - if (near && po > hopRadius) || (!near && po == 0) { - return signer - } - } -} - -// newHopNet makes an origin with n first hops; a lower index is closer to -// the chunks. insideAOR puts the origin inside the neighborhood. -func newHopNet(t *testing.T, insideAOR bool, hops int) *hopNet { - t.Helper() - - n := &hopNet{ - t: t, - anchor: swarm.RandAddress(t), - handlers: make(map[string]p2p.ProtocolSpec), - clock: newTestClock(), - } - n.radius.Store(hopRadius) - - // all first hops differ from the neighborhood in bit 0; the next bits - // set their order - for _, bits := range [][]int{{0}, {0, 2}, {0, 1}}[:hops] { - n.hops = append(n.hops, flipBits(n.anchor, bits...)) - } - - originAddr := flipBits(n.anchor, 0, 255) - if insideAOR { - originAddr = flipBits(n.anchor, 255) - } - - topo := mock.NewTopologyDriver(mock.WithPeers(n.hops...)) - n.topo = topo - - n.recorder = streamtest.New(streamtest.WithPeerProtocols(n.handlers), streamtest.WithBaseAddr(originAddr)) - n.origin = pushsync.New( - originAddr, 1, blockHash.Bytes(), - streamtest.NewRecorderDisconnecter(n.recorder), - &testStorer{chunksPut: make(map[string]swarm.Chunk), chunksReported: make(map[string]int)}, - func() (uint8, error) { return uint8(n.radius.Load()), nil }, - topo, true, - func(swarm.Chunk) {}, func(*soc.SOC) {}, - func(ch swarm.Chunk) (swarm.Chunk, error) { return ch, nil }, - log.Noop, accountingmock.NewAccounting(), - pricermock.NewMockService(defaultPrices.price, defaultPrices.peerPrice), - nil, nil, stabilmock.NewSubscriber(true), - ) - t.Cleanup(func() { n.origin.Close() }) - n.origin.SetHopClock(n.clock.Now) - - return n -} - -// setReceipt makes the first hop answer with a valid or a shallow receipt. -func (n *hopNet) setReceipt(hop swarm.Address, valid bool) { - n.t.Helper() - - n.nodes++ - self := n.anchor.Clone().Bytes() - self[swarm.HashSize-1] ^= n.nodes - - node, _ := createPushSyncNodeWithRadius(n.t, swarm.NewAddress(self), defaultPrices, nil, nil, hopSigner(n.t, n.anchor, valid), hopRadius, mock.WithClosestPeerErr(topology.ErrWantSelf)) - n.handlers[hop.String()] = node.Protocol() -} - -// setGone makes every push to the first hop return an error. -func (n *hopNet) setGone(hop swarm.Address) { - delete(n.handlers, hop.String()) -} - -func (n *hopNet) chunk() swarm.Chunk { - n.t.Helper() - return testingc.GenerateValidRandomChunkAt(n.t, n.anchor, hopRadius) -} - -// streams returns the number of pushes the origin sent to the first hop. -func (n *hopNet) streams(hop swarm.Address) int { - recs, _ := n.recorder.Records(hop, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName) - return len(recs) -} - -func (n *hopNet) wantStreams(hop swarm.Address, want int) { - n.t.Helper() - if got := n.streams(hop); got != want { - n.t.Fatalf("first hop %s: got %d pushes, want %d", hop.String()[:4], got, want) - } -} - -func (n *hopNet) wantFirstHop(source, result string, want float64) { - n.t.Helper() - if got := n.origin.FirstHopCount(source, result); got != want { - n.t.Fatalf("first hop metric %s/%s: got %v, want %v", source, result, got, want) - } -} - -func (n *hopNet) push() error { - _, err := n.origin.PushChunkToClosest(context.Background(), n.chunk()) - return err -} - -func (n *hopNet) pushValid() { - n.t.Helper() - if err := n.push(); err != nil { - n.t.Fatalf("got %v, want a valid receipt", err) - } -} - -func (n *hopNet) pushShallow() { - n.t.Helper() - if err := n.push(); !errors.Is(err, pushsync.ErrShallowReceipt) { - n.t.Fatalf("got %v, want %v", err, pushsync.ErrShallowReceipt) - } -} - -// TestOriginPrefersKnownValidPeer checks that the next chunk goes to the -// first hop with a valid record, not to a closer one that gave a shallow receipt. -func TestOriginPrefersKnownValidPeer(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 2) - shallow, valid := n.hops[0], n.hops[1] - n.setReceipt(shallow, false) - n.setReceipt(valid, true) - - n.pushValid() - n.wantStreams(shallow, 1) - n.wantStreams(valid, 1) - - n.pushValid() - n.wantStreams(shallow, 1) - n.wantStreams(valid, 2) - - n.wantFirstHop("unknown", "shallow", 1) - n.wantFirstHop("unknown", "valid", 1) - n.wantFirstHop("known_valid", "valid", 1) -} - -// TestOriginPausedPeerLast checks that a first hop in a shallow pause is not -// used while another first hop is left. -func TestOriginPausedPeerLast(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 2) - shallow, other := n.hops[0], n.hops[1] - n.setReceipt(shallow, false) - - // the farther first hop gives an error, so it gets no record - n.pushShallow() - n.wantStreams(shallow, 1) - n.wantFirstHop("unknown", "error", 1) - - n.setReceipt(other, true) - n.clock.Add(59 * time.Second) - n.pushValid() - n.wantStreams(shallow, 1) - n.wantStreams(other, 1) - n.wantFirstHop("unknown", "valid", 1) - n.wantFirstHop("paused", "shallow", 0) -} - -// TestOriginOtherNeighborhoodNotAffected checks that a shallow receipt for -// one neighborhood does not leave the first hop out for another one. -func TestOriginOtherNeighborhoodNotAffected(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 1) - shallow := n.hops[0] - n.setReceipt(shallow, false) - - n.pushShallow() - n.wantStreams(shallow, 1) - - // a chunk that differs from the neighborhood in bit 1 - other := testingc.GenerateValidRandomChunkAt(t, flipBits(n.anchor, 1), hopRadius) - _, _ = n.origin.PushChunkToClosest(context.Background(), other) - n.wantStreams(shallow, 2) -} - -// TestOriginAllPeersPaused checks that the origin sends through the first -// hops in a shallow pause when no other first hop is left, and that these -// sends do not make the pauses longer. -func TestOriginAllPeersPaused(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 2) - n.setReceipt(n.hops[0], false) - n.setReceipt(n.hops[1], false) - - n.pushShallow() - n.wantStreams(n.hops[0], 1) - n.wantStreams(n.hops[1], 1) - - n.clock.Add(30 * time.Second) - n.pushShallow() - n.wantStreams(n.hops[0], 2) - n.wantStreams(n.hops[1], 2) - n.wantFirstHop("paused", "shallow", 2) - - // the pauses still end 60s after the first shallow receipts - n.setReceipt(n.hops[1], true) - n.clock.Add(30 * time.Second) - n.pushValid() - n.wantStreams(n.hops[0], 3) - n.wantStreams(n.hops[1], 3) - n.wantFirstHop("unknown", "shallow", 3) - n.wantFirstHop("unknown", "valid", 1) -} - -// TestOriginAllBlockedInsideAOR checks that an origin inside the -// neighborhood stores the chunk itself when every first hop is paused. -func TestOriginAllBlockedInsideAOR(t *testing.T) { - t.Parallel() - - n := newHopNet(t, true, 1) - n.setReceipt(n.hops[0], false) - - n.pushShallow() - n.wantStreams(n.hops[0], 1) - - if err := n.push(); !errors.Is(err, topology.ErrWantSelf) { - t.Fatalf("got %v, want %v", err, topology.ErrWantSelf) - } - n.wantStreams(n.hops[0], 1) -} - -// TestOriginValidPeerError checks that an error removes a valid record and -// that the chunk gets a valid receipt from another first hop in the same call. -func TestOriginValidPeerError(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 2) - first, second := n.hops[0], n.hops[1] - n.setReceipt(first, true) - n.setReceipt(second, true) - - n.pushValid() - n.wantStreams(first, 1) - n.wantStreams(second, 0) - - n.setGone(first) - - n.pushValid() - n.wantStreams(second, 1) - n.wantFirstHop("known_valid", "error", 1) - n.wantFirstHop("unknown", "valid", 2) - if got := n.origin.HopRecords(); got != 1 { - t.Fatalf("got %d records, want 1", got) - } -} - -// TestOriginSkipsDisconnectedValidPeer checks that a disconnected first hop -// with a valid record is not picked and loses the record. -func TestOriginSkipsDisconnectedValidPeer(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 2) - valid, shallow := n.hops[0], n.hops[1] - n.setReceipt(valid, true) - n.setReceipt(shallow, false) - - n.pushValid() - n.wantStreams(valid, 1) - n.wantStreams(shallow, 0) - - n.topo.Disconnected(p2p.Peer{Address: valid}) - - n.pushShallow() - n.wantStreams(valid, 1) - n.wantStreams(shallow, 1) - if got := n.origin.HopRecords(); got != 1 { - t.Fatalf("got %d records, want 1", got) - } -} - -// TestOriginProbe checks that a closer first hop is probed after its pause -// and that the chunk still gets the valid receipt of the known first hop. -func TestOriginProbe(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 2) - shallow, valid := n.hops[0], n.hops[1] - n.setReceipt(shallow, false) - n.setReceipt(valid, true) - - n.pushValid() - n.wantStreams(shallow, 1) - n.wantStreams(valid, 1) - - // the pause of the closer first hop is not over: no probe - n.clock.Add(59 * time.Second) - n.pushValid() - n.wantStreams(shallow, 1) - n.wantStreams(valid, 2) - - n.clock.Add(time.Second) - n.pushValid() - n.wantStreams(shallow, 2) - n.wantStreams(valid, 3) - n.wantFirstHop("probe", "shallow", 1) - - // the second shallow receipt in a row doubles the pause - n.clock.Add(119 * time.Second) - n.pushValid() - n.wantStreams(shallow, 2) - n.wantStreams(valid, 4) -} - -// TestOriginProbeInterval checks that a neighborhood gets at most one probe -// per 30s. -func TestOriginProbeInterval(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 3) - n.setReceipt(n.hops[0], false) - n.setReceipt(n.hops[1], false) - n.setReceipt(n.hops[2], true) - - n.pushValid() - n.wantStreams(n.hops[0], 1) - n.wantStreams(n.hops[1], 1) - n.wantStreams(n.hops[2], 1) - - // both pauses are over: the first chunk probes the closest first hop - n.clock.Add(time.Minute) - n.pushValid() - n.wantStreams(n.hops[0], 2) - n.wantStreams(n.hops[1], 1) - - // the next chunk comes before the end of the probe interval - n.clock.Add(29 * time.Second) - n.pushValid() - n.wantStreams(n.hops[1], 1) - - n.clock.Add(time.Second) - n.pushValid() - n.wantStreams(n.hops[0], 2) - n.wantStreams(n.hops[1], 2) - n.wantFirstHop("probe", "shallow", 2) - n.wantStreams(n.hops[2], 4) -} - -// TestOriginProbeBecomesValid checks that a closer first hop that gives a -// valid receipt on a probe is used first from then on. -func TestOriginProbeBecomesValid(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 2) - closer, valid := n.hops[0], n.hops[1] - n.setReceipt(closer, false) - n.setReceipt(valid, true) - - n.pushValid() - n.wantStreams(closer, 1) - n.wantStreams(valid, 1) - - n.setReceipt(closer, true) - n.clock.Add(time.Minute) - - n.pushValid() - n.wantStreams(closer, 2) - n.wantStreams(valid, 1) - n.wantFirstHop("probe", "valid", 1) - - n.pushValid() - n.wantStreams(closer, 3) - n.wantStreams(valid, 1) -} - -// TestOriginRadiusChangeDuringPush checks that a push whose radius changes -// between two attempts selects the next first hop and records its result at -// the new radius. -func TestOriginRadiusChangeDuringPush(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 2) - n.setReceipt(n.hops[0], false) - n.setReceipt(n.hops[1], true) - - // the radius of the origin grows while the first attempt is on its way - spec := n.handlers[n.hops[0].String()] - handler := spec.StreamSpecs[0].Handler - spec.StreamSpecs = []p2p.StreamSpec{spec.StreamSpecs[0]} - spec.StreamSpecs[0].Handler = func(ctx context.Context, p p2p.Peer, s p2p.Stream) error { - n.radius.Store(hopRadius + 1) - return handler(ctx, p, s) - } - n.handlers[n.hops[0].String()] = spec - - ch := testingc.GenerateValidRandomChunkAt(t, n.anchor, hopRadius+1) - if _, err := n.origin.PushChunkToClosest(context.Background(), ch); err != nil { - t.Fatalf("got %v, want a valid receipt", err) - } - n.wantStreams(n.hops[0], 1) - n.wantStreams(n.hops[1], 1) - - if got := n.origin.HopRecords(); got != 1 { - t.Fatalf("got %d records, want 1", got) - } - valid, blocked, _ := n.origin.Hops().View(hopRadius+1, ch.Address()) - if len(valid) != 1 || !valid[0].Equal(n.hops[1]) || len(blocked) != 0 { - t.Fatalf("got valid %v blocked %v, want the valid record of the second first hop at the new radius", valid, blocked) - } -} - -// TestForwarderDoesNotUseHopMemory checks that a forwarder neither reads -// nor writes first-hop records. -func TestForwarderDoesNotUseHopMemory(t *testing.T) { - t.Parallel() - - n := newHopNet(t, false, 1) - storer := flipBits(n.anchor, 254) - - storerNode, _ := createPushSyncNodeWithRadius(t, storer, defaultPrices, nil, nil, hopSigner(t, n.anchor, true), hopRadius, mock.WithClosestPeerErr(topology.ErrWantSelf)) - - // the forwarder and its two peers are outside the neighborhood; every - // push of the forwarder gets to the storer - forwarderAddr := flipBits(n.anchor, 0, 254) - closer, farther := flipBits(n.anchor, 1), flipBits(n.anchor, 0, 2) - forwarderRecorder := streamtest.New(streamtest.WithProtocols(storerNode.Protocol()), streamtest.WithBaseAddr(forwarderAddr)) - forwarder, _ := createPushSyncNodeWithRadius(t, forwarderAddr, defaultPrices, forwarderRecorder, nil, nil, hopRadius, mock.WithPeers(closer, farther)) - n.handlers[n.hops[0].String()] = forwarder.Protocol() - - // an origin with these records sends to the farther peer first - chunk := n.chunk() - forwarder.Hops().View(hopRadius, chunk.Address()) - forwarder.Hops().RecordValid(hopRadius, chunk.Address(), farther) - forwarder.Hops().ClaimProbe(hopRadius, chunk.Address()) - - if _, err := n.origin.PushChunkToClosest(context.Background(), chunk); err != nil { - t.Fatalf("got %v, want a valid receipt", err) - } - - if got := n.streams(n.hops[0]); got != 1 { - t.Fatalf("got %d pushes to the forwarder, want 1", got) - } - if recs, _ := forwarderRecorder.Records(closer, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName); len(recs) != 1 { - t.Fatalf("got %d pushes to the closest peer, want 1", len(recs)) - } - if recs, _ := forwarderRecorder.Records(farther, pushsync.ProtocolName, pushsync.ProtocolVersion, pushsync.StreamName); len(recs) != 0 { - t.Fatalf("got %d pushes to the peer with a valid record, want 0", len(recs)) - } - if got := forwarder.HopRecords(); got != 1 { - t.Fatalf("forwarder has %d first-hop records, want the 1 that the test made", got) - } - if got := n.origin.HopRecords(); got != 1 { - t.Fatalf("origin has %d first-hop records, want 1", got) - } -} diff --git a/pkg/pushsync/hopmemory_test.go b/pkg/pushsync/hopmemory_test.go deleted file mode 100644 index 4310228ac5c..00000000000 --- a/pkg/pushsync/hopmemory_test.go +++ /dev/null @@ -1,628 +0,0 @@ -// Copyright 2026 The Swarm Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pushsync_test - -import ( - "math/rand" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/ethersphere/bee/v2/pkg/pushsync" - "github.com/ethersphere/bee/v2/pkg/swarm" -) - -// testClock is a clock that a test moves forward by hand. -type testClock struct { - mtx sync.Mutex - t time.Time -} - -func newTestClock() *testClock { - return &testClock{t: time.Unix(1_700_000_000, 0)} -} - -func (c *testClock) Now() time.Time { - c.mtx.Lock() - defer c.mtx.Unlock() - return c.t -} - -func (c *testClock) Add(d time.Duration) { - c.mtx.Lock() - defer c.mtx.Unlock() - c.t = c.t.Add(d) -} - -// hopAddr returns an address that starts with the given bytes. -func hopAddr(prefix ...byte) swarm.Address { - b := make([]byte, swarm.HashSize) - copy(b, prefix) - return swarm.NewAddress(b) -} - -func hasAddr(addrs []swarm.Address, a swarm.Address) bool { - return swarm.ContainsAddress(addrs, a) -} - -func TestHopMemoryRecord(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - ) - - m.RecordValid(10, chunk, peer) - valid, blocked, _ := m.View(10, chunk) - if !hasAddr(valid, peer) || len(blocked) != 0 { - t.Fatalf("after a valid receipt: valid %v blocked %v", valid, blocked) - } - - m.RecordShallow(10, chunk, peer) - valid, blocked, _ = m.View(10, chunk) - if len(valid) != 0 || !hasAddr(blocked, peer) { - t.Fatalf("after a shallow receipt: valid %v blocked %v", valid, blocked) - } - - m.RecordValid(10, chunk, peer) - m.Forget(10, chunk, peer) - valid, blocked, _ = m.View(10, chunk) - if len(valid) != 0 || len(blocked) != 0 { - t.Fatalf("after forget: valid %v blocked %v", valid, blocked) - } - if got := m.Len(); got != 0 { - t.Fatalf("got %d records, want 0", got) - } -} - -// TestHopMemoryShallowDuringPause checks that a shallow receipt during a -// pause does not make the pause longer. -func TestHopMemoryShallowDuringPause(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - ) - - // results of pushes that ran in parallel - m.RecordShallow(10, chunk, peer) - m.RecordShallow(10, chunk, peer) - clock.Add(30 * time.Second) - m.RecordShallow(10, chunk, peer) - - clock.Add(30 * time.Second) - if _, blocked, _ := m.View(10, chunk); len(blocked) != 0 { - t.Fatal("peer is blocked 60s after the first shallow receipt") - } -} - -// TestHopMemoryForgetKeepsPause checks that forget does not end a pause. -func TestHopMemoryForgetKeepsPause(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - ) - - m.RecordShallow(10, chunk, peer) - m.Forget(10, chunk, peer) - if _, blocked, _ := m.View(10, chunk); !hasAddr(blocked, peer) { - t.Fatal("forget ended a pause that still runs") - } - - clock.Add(time.Minute) - m.Forget(10, chunk, peer) - if got := m.Len(); got != 0 { - t.Fatalf("got %d records after the pause, want 0", got) - } -} - -func TestHopMemoryPauseDoubles(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - ) - - isBlocked := func() bool { - _, blocked, _ := m.View(10, chunk) - return hasAddr(blocked, peer) - } - - // each step adds one shallow receipt in a row - for i, pause := range []time.Duration{ - time.Minute, - 2 * time.Minute, - 4 * time.Minute, - 8 * time.Minute, - 16 * time.Minute, - 30 * time.Minute, - 30 * time.Minute, - } { - m.RecordShallow(10, chunk, peer) - clock.Add(pause - time.Second) - if !isBlocked() { - t.Fatalf("shallow receipt %d: peer is free one second before the end of a %s pause", i+1, pause) - } - clock.Add(time.Second) - if isBlocked() { - t.Fatalf("shallow receipt %d: peer is blocked after a %s pause", i+1, pause) - } - } - - // a valid receipt starts the count again - m.RecordValid(10, chunk, peer) - m.RecordShallow(10, chunk, peer) - clock.Add(time.Minute) - if isBlocked() { - t.Fatal("peer is blocked 60s after the first shallow receipt that follows a valid one") - } -} - -// TestHopMemoryShallowIdle checks that a shallow record is removed one hour -// after its last shallow receipt. -func TestHopMemoryShallowIdle(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - ) - - for i := range 50 { - m.RecordShallow(10, chunk, hopAddr(0x10, byte(i))) - } - - clock.Add(time.Hour - time.Second) - m.View(10, chunk) - if got := m.Len(); got != 50 { - t.Fatalf("got %d records one second before the end of the idle time, want 50", got) - } - - clock.Add(time.Second) - m.View(10, chunk) - if got := m.Len(); got != 0 { - t.Fatalf("got %d records after the idle time, want 0", got) - } -} - -// TestHopMemoryShallowCountRestarts checks that the count starts again after -// one hour without a shallow receipt, also when view was not called. -func TestHopMemoryShallowCountRestarts(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - ) - - isBlocked := func() bool { - _, blocked, _ := m.View(10, chunk) - return hasAddr(blocked, peer) - } - - m.RecordShallow(10, chunk, peer) - clock.Add(time.Hour) - m.RecordShallow(10, chunk, peer) - - clock.Add(time.Minute - time.Second) - if !isBlocked() { - t.Fatal("peer is free one second before the end of a 1m0s pause") - } - clock.Add(time.Second) - if isBlocked() { - t.Fatal("peer is blocked after a 1m0s pause: the count did not start again") - } -} - -func TestHopMemoryValidIdle(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - ) - - m.RecordValid(10, chunk, peer) - - clock.Add(29 * time.Minute) - if valid, _, _ := m.View(10, chunk); !hasAddr(valid, peer) { - t.Fatal("valid record is gone after 29 minutes") - } - - clock.Add(time.Minute) - if valid, _, _ := m.View(10, chunk); len(valid) != 0 { - t.Fatal("valid record is still used after 30 minutes without a result") - } - if got := m.Len(); got != 0 { - t.Fatalf("got %d records, want 0", got) - } -} - -// TestHopMemorySweep checks that the idle records of a neighborhood that gets -// no more chunks are removed when another neighborhood is used. -func TestHopMemorySweep(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - other = hopAddr(0x1c, 0x00) - peer = hopAddr(0x10) - bad = hopAddr(0x20) - ) - - m.View(10, chunk) // the first sweep - m.RecordValid(10, chunk, peer) - m.RecordShallow(10, chunk, bad) - - clock.Add(30 * time.Minute) - m.View(10, other) - if got := m.Len(); got != 1 { - t.Fatalf("got %d records after 30 minutes, want 1 (the shallow record)", got) - } - - clock.Add(30 * time.Minute) - m.View(10, other) - if got := m.Len(); got != 0 { - t.Fatalf("got %d records after 60 minutes, want 0", got) - } - if got := m.Hoods(); got != 0 { - t.Fatalf("got %d neighborhoods after 60 minutes, want 0", got) - } -} - -// TestHopMemoryProbeTimeKept checks that the removal of the last record of a -// neighborhood does not make the next probe due before the interval ends. -func TestHopMemoryProbeTimeKept(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - ) - - m.RecordValid(10, chunk, peer) - if !m.ClaimProbe(10, chunk) { - t.Fatal("probe that is due was not given") - } - m.Forget(10, chunk, peer) - - m.RecordValid(10, chunk, peer) - if _, _, due := m.View(10, chunk); due { - t.Fatal("probe is due right after a probe") - } - if m.ClaimProbe(10, chunk) { - t.Fatal("second probe was given before the interval ended") - } - - m.Forget(10, chunk, peer) - clock.Add(30 * time.Second) - m.View(10, chunk) - if got := m.Hoods(); got != 0 { - t.Fatalf("got %d neighborhoods after the interval, want 0", got) - } -} - -func TestHopMemoryProbe(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - other = hopAddr(0x1c, 0x00) - peer = hopAddr(0x10) - ) - - m.RecordValid(10, chunk, peer) - m.RecordValid(10, other, peer) - - if _, _, due := m.View(10, chunk); !due { - t.Fatal("probe is not due for a neighborhood that was never probed") - } - - if !m.ClaimProbe(10, chunk) { - t.Fatal("probe that is due was not given") - } - if m.ClaimProbe(10, chunk) { - t.Fatal("second probe was given right after a probe") - } - if _, _, due := m.View(10, chunk); due { - t.Fatal("probe is due right after a probe") - } - if _, _, due := m.View(10, other); !due { - t.Fatal("probe of one neighborhood changed another neighborhood") - } - - clock.Add(29 * time.Second) - if _, _, due := m.View(10, chunk); due { - t.Fatal("probe is due 29s after a probe") - } - clock.Add(time.Second) - if _, _, due := m.View(10, chunk); !due { - t.Fatal("probe is not due 30s after a probe") - } -} - -func TestHopMemoryNeighborhoodKey(t *testing.T) { - t.Parallel() - - peer := hopAddr(0x10) - - t.Run("radius 10", func(t *testing.T) { - t.Parallel() - - m := pushsync.NewHopMemory(newTestClock().Now) - m.RecordValid(10, hopAddr(0x6b, 0x00), peer) - - // 0x6b3f shares the first 10 bits with 0x6b00, 0x6b40 does not - if valid, _, _ := m.View(10, hopAddr(0x6b, 0x3f, 0xff)); !hasAddr(valid, peer) { - t.Fatal("chunk of the same neighborhood does not see the record") - } - if valid, _, _ := m.View(10, hopAddr(0x6b, 0x40)); len(valid) != 0 { - t.Fatal("chunk of another neighborhood sees the record") - } - if valid, _, _ := m.View(10, hopAddr(0x6a, 0x00)); len(valid) != 0 { - t.Fatal("chunk of another neighborhood sees the record") - } - }) - - t.Run("radius 8", func(t *testing.T) { - t.Parallel() - - m := pushsync.NewHopMemory(newTestClock().Now) - m.RecordValid(8, hopAddr(0x6b, 0x00), peer) - - if valid, _, _ := m.View(8, hopAddr(0x6b, 0xff)); !hasAddr(valid, peer) { - t.Fatal("chunk of the same neighborhood does not see the record") - } - if valid, _, _ := m.View(8, hopAddr(0x6a, 0x00)); len(valid) != 0 { - t.Fatal("chunk of another neighborhood sees the record") - } - }) - - t.Run("radius 0", func(t *testing.T) { - t.Parallel() - - m := pushsync.NewHopMemory(newTestClock().Now) - m.RecordValid(0, hopAddr(0x6b), peer) - - if valid, _, _ := m.View(0, hopAddr(0xff, 0xff)); !hasAddr(valid, peer) { - t.Fatal("at radius 0 every chunk is in one neighborhood") - } - }) -} - -func TestHopMemoryRadiusChange(t *testing.T) { - t.Parallel() - - var ( - m = pushsync.NewHopMemory(newTestClock().Now) - chunk = hopAddr(0x6b, 0x00) - ) - - m.RecordValid(9, chunk, hopAddr(0x10)) - m.RecordShallow(9, chunk, hopAddr(0x20)) - - valid, blocked, _ := m.View(10, chunk) - if len(valid) != 0 || len(blocked) != 0 { - t.Fatalf("records of radius 9 are used at radius 10: valid %v blocked %v", valid, blocked) - } - if got := m.Len(); got != 0 { - t.Fatalf("got %d records, want 0", got) - } -} - -// TestHopMemoryLateResult checks that a result of a push that began at -// another radius does not remove the records of the current radius. -func TestHopMemoryLateResult(t *testing.T) { - t.Parallel() - - var ( - m = pushsync.NewHopMemory(newTestClock().Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - late = hopAddr(0x20) - ) - - m.View(10, chunk) - m.RecordValid(10, chunk, peer) - - m.RecordValid(9, chunk, late) - m.RecordShallow(9, chunk, late) - m.Forget(9, chunk, peer) - if m.ClaimProbe(9, chunk) { - t.Fatal("probe was given for another radius") - } - - valid, blocked, _ := m.View(10, chunk) - if len(valid) != 1 || !hasAddr(valid, peer) || len(blocked) != 0 { - t.Fatalf("got valid %v blocked %v, want only the record of radius 10", valid, blocked) - } -} - -// TestHopMemoryLateResultEmptyMemory checks that a result of a push that began -// at the old radius is ignored when the memory has no records, which is the -// state right after a radius change. -func TestHopMemoryLateResultEmptyMemory(t *testing.T) { - t.Parallel() - - var ( - m = pushsync.NewHopMemory(newTestClock().Now) - chunk = hopAddr(0x6b, 0x00) - peer = hopAddr(0x10) - late = hopAddr(0x20) - ) - - m.View(9, chunk) - m.RecordValid(9, chunk, late) - m.View(10, chunk) - if got := m.Len(); got != 0 { - t.Fatalf("got %d records after the radius change, want 0", got) - } - - m.RecordValid(9, chunk, late) - m.RecordShallow(9, chunk, late) - if m.ClaimProbe(9, chunk) { - t.Fatal("probe was given for another radius") - } - if got := m.Len(); got != 0 { - t.Fatalf("got %d records of the old radius, want 0", got) - } - - m.RecordValid(10, chunk, peer) - valid, blocked, _ := m.View(10, chunk) - if len(valid) != 1 || !hasAddr(valid, peer) || len(blocked) != 0 { - t.Fatalf("got valid %v blocked %v, want only the record of radius 10", valid, blocked) - } -} - -// TestHopMemoryBlockedOrder checks that the peers in a pause are returned in -// the order in which their pauses end. -func TestHopMemoryBlockedOrder(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - long = hopAddr(0x6a) - first = hopAddr(0x10) - last = hopAddr(0x20) - ) - - // two shallow receipts in a row: the pause of this peer ends at 3m - m.RecordShallow(10, chunk, long) - clock.Add(time.Minute) - m.RecordShallow(10, chunk, long) - // these pauses end at 2m10s and 2m20s - clock.Add(10 * time.Second) - m.RecordShallow(10, chunk, first) - clock.Add(10 * time.Second) - m.RecordShallow(10, chunk, last) - - _, blocked, _ := m.View(10, chunk) - want := []swarm.Address{first, last, long} - if len(blocked) != len(want) { - t.Fatalf("got %d peers in a pause, want %d", len(blocked), len(want)) - } - for i := range want { - if !blocked[i].Equal(want[i]) { - t.Fatalf("position %d: got %s, want %s", i, blocked[i], want[i]) - } - } -} - -// TestHopMemoryClaimProbeOnce checks that only one of the callers that run -// at the same time gets the probe of a neighborhood. -func TestHopMemoryClaimProbeOnce(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - chunk = hopAddr(0x6b, 0x00) - ) - m.RecordValid(10, chunk, hopAddr(0x10)) - - for round := range 3 { - var ( - wg sync.WaitGroup - given atomic.Int32 - ) - for range 64 { - wg.Go(func() { - if m.ClaimProbe(10, chunk) { - given.Add(1) - } - }) - } - wg.Wait() - if got := given.Load(); got != 1 { - t.Fatalf("round %d: got %d probes, want 1", round, got) - } - clock.Add(30 * time.Second) - } -} - -// TestHopMemoryConcurrent runs all operations at the same time and checks -// that the memory stays consistent. -func TestHopMemoryConcurrent(t *testing.T) { - t.Parallel() - - var ( - clock = newTestClock() - m = pushsync.NewHopMemory(clock.Now) - wg sync.WaitGroup - ) - - for i := range 64 { - wg.Go(func() { - r := rand.New(rand.NewSource(int64(i))) - for range 200 { - chunk := hopAddr(byte(r.Intn(4)), byte(r.Intn(256))) - peer := hopAddr(byte(r.Intn(8))) - switch r.Intn(6) { - case 0: - m.RecordValid(10, chunk, peer) - case 1: - m.RecordShallow(10, chunk, peer) - case 2: - m.Forget(10, chunk, peer) - case 3: - m.ClaimProbe(10, chunk) - case 4: - clock.Add(time.Second) - default: - m.View(10, chunk) - } - } - }) - } - wg.Wait() - - // 4 values of the first byte and 4 of the next two bits give at most - // 16 neighborhoods at radius 10, each with at most 8 peers - if got := m.Len(); got > 16*8 { - t.Fatalf("got %d records, want at most %d", got, 16*8) - } - var seen int - for a := range 4 { - for b := range 4 { - valid, blocked, _ := m.View(10, hopAddr(byte(a), byte(b<<6))) - for _, p := range valid { - if hasAddr(blocked, p) { - t.Fatalf("peer %s is valid and in a pause", p) - } - } - seen += len(valid) + len(blocked) - } - } - if got := m.Len(); seen > got { - t.Fatalf("views returned %d peers, the memory has %d records", seen, got) - } -} diff --git a/pkg/pushsync/metrics.go b/pkg/pushsync/metrics.go index 5e08ff79ed0..2240e6354fb 100644 --- a/pkg/pushsync/metrics.go +++ b/pkg/pushsync/metrics.go @@ -37,7 +37,9 @@ type metrics struct { FirstHopNeighborhoods prometheus.GaugeFunc } -func newMetrics(hops *hopMemory) metrics { +// newMetrics takes the function that returns the number of neighborhoods and +// the number of records of the first-hop memory. +func newMetrics(firstHopSize func() (neighborhoods, records int)) metrics { subsystem := "pushsync" return metrics{ @@ -186,7 +188,7 @@ func newMetrics(hops *hopMemory) metrics { Name: "first_hop_records", Help: "Number of records in the first-hop memory of an origin.", }, func() float64 { - _, records := hops.size() + _, records := firstHopSize() return float64(records) }), FirstHopNeighborhoods: prometheus.NewGaugeFunc(prometheus.GaugeOpts{ @@ -195,8 +197,8 @@ func newMetrics(hops *hopMemory) metrics { Name: "first_hop_neighborhoods", Help: "Number of neighborhoods in the first-hop memory of an origin.", }, func() float64 { - hoods, _ := hops.size() - return float64(hoods) + neighborhoods, _ := firstHopSize() + return float64(neighborhoods) }), } } diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index d4e5f67ec92..d0d00458ca4 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -10,7 +10,6 @@ import ( "context" "errors" "fmt" - "slices" "strconv" "time" @@ -22,6 +21,7 @@ import ( "github.com/ethersphere/bee/v2/pkg/p2p/protobuf" "github.com/ethersphere/bee/v2/pkg/postage" "github.com/ethersphere/bee/v2/pkg/pricer" + "github.com/ethersphere/bee/v2/pkg/pushsync/internal/firsthop" "github.com/ethersphere/bee/v2/pkg/pushsync/pb" "github.com/ethersphere/bee/v2/pkg/safe" "github.com/ethersphere/bee/v2/pkg/skippeers" @@ -98,7 +98,7 @@ type PushSync struct { signer crypto.Signer fullNode bool errSkip *skippeers.List - hops *hopMemory + firstHops *firsthop.Memory // receipt results of the first hops of an origin stabilizer stabilization.Subscriber overDraftRefreshLimiter *rate.Limiter } @@ -129,7 +129,7 @@ func New( tracer *tracing.Tracer, stabilizer stabilization.Subscriber, ) *PushSync { - hops := newHopMemory(time.Now) + firstHops := firsthop.New(time.Now) ps := &PushSync{ address: address, radius: radius, @@ -144,11 +144,11 @@ func New( logger: logger.WithName(loggerName).Register(), accounting: accounting, pricer: pricer, - metrics: newMetrics(hops), + metrics: newMetrics(firstHops.Size), tracer: tracer, signer: signer, errSkip: skippeers.NewList(time.Minute), - hops: hops, + firstHops: firstHops, stabilizer: stabilizer, overDraftRefreshLimiter: rate.NewLimiter(rate.Every(time.Second), 1), } @@ -376,12 +376,11 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo parallelForwards = maxMultiplexForwards shallowReceiptResult *pb.Receipt shallowReceiptPO uint8 - probed bool - hopSources map[string]hopSource // first hops of an origin + op *originPush // first hops of an origin ) if origin { - hopSources = make(map[string]hopSource) + op = ps.newOriginPush(ch.Address()) ticker := time.NewTicker(preemptiveInterval) defer ticker.Stop() preemptiveTicker = ticker.C @@ -434,12 +433,11 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo fullSkip := append(skip.ChunkPeers(idAddress), ps.errSkip.ChunkPeers(idAddress)...) var ( - peer swarm.Address - err error - source hopSource + peer swarm.Address + err error ) if origin { - peer, source, err = ps.originPeer(ch.Address(), rad, fullSkip, &probed) + peer, err = op.next(rad, fullSkip) } else { peer, err = ps.closestPeer(ch.Address(), origin, fullSkip) } @@ -524,9 +522,6 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo continue } skip.Forever(idAddress, peer) - if origin { - hopSources[peer.ByteString()] = source - } ps.metrics.TotalSendAttempts.Inc() inflight++ @@ -557,12 +552,9 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo // budget; surface ErrShallowReceipt only when nothing better lands. switch po, err := ps.checkReceipt(result.receipt, result.peer, rad); { case err == nil: - ps.hops.recordValid(rad, ch.Address(), result.peer) - ps.metrics.FirstHop.WithLabelValues(string(hopSources[result.peer.ByteString()]), "valid").Inc() + op.record(rad, result.peer, nil) return result.receipt, nil case errors.Is(err, ErrShallowReceipt): - ps.hops.recordShallow(rad, ch.Address(), result.peer) - ps.metrics.FirstHop.WithLabelValues(string(hopSources[result.peer.ByteString()]), "shallow").Inc() if shallowReceiptResult == nil || po > shallowReceiptPO { shallowReceiptResult = result.receipt shallowReceiptPO = po @@ -573,10 +565,10 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo } } - // An error other than a shallow receipt removes the record. - if origin && !errors.Is(result.err, ErrShallowReceipt) { - ps.hops.forget(rad, ch.Address(), result.peer) - ps.metrics.FirstHop.WithLabelValues(string(hopSources[result.peer.ByteString()]), "error").Inc() + // A shallow receipt starts a pause of the first hop; another + // error removes its record. + if origin { + op.record(rad, result.peer, result.err) } ps.metrics.TotalFailedSendAttempts.Inc() @@ -595,97 +587,6 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo return nil, ErrNoPush } -// hopSource says why an origin picked a first hop. -type hopSource string - -const ( - hopSourceProbe hopSource = "probe" - hopSourceValid hopSource = "known_valid" - hopSourceUnknown hopSource = "unknown" - hopSourcePaused hopSource = "paused" -) - -// originPeer picks the next first hop for an origin: -// 1. a probe, at most once per call and per hopProbeInterval: a peer closer -// to the chunk than every peer with a valid record; -// 2. the closest peer with a valid record; -// 3. the closest peer that is not in a shallow pause; -// 4. the peer whose shallow pause ends first, unless the origin can store -// the chunk itself. -func (ps *PushSync) originPeer(chunkAddress swarm.Address, rad uint8, fullSkip []swarm.Address, probed *bool) (peer swarm.Address, source hopSource, err error) { - valid, blocked, probeDue := ps.hops.view(rad, chunkAddress) - - // Remove the valid records of peers that are no longer connected. - if len(valid) > 0 { - connected := ps.connectedOf(valid) - for _, p := range valid { - if !swarm.ContainsAddress(connected, p) { - ps.hops.forget(rad, chunkAddress, p) - } - } - valid = connected - } - - best := swarm.ZeroAddress - for _, p := range valid { - if swarm.ContainsAddress(fullSkip, p) { - continue - } - if best.IsZero() { - best = p - continue - } - if closer, _ := p.Closer(chunkAddress, best); closer { - best = p - } - } - - if !best.IsZero() { - if probeDue && !*probed { - candidate, err := ps.closestPeer(chunkAddress, true, slices.Concat(fullSkip, blocked, valid)) - if err == nil { - if closer, _ := candidate.Closer(chunkAddress, best); closer && ps.hops.claimProbe(rad, chunkAddress) { - *probed = true - return candidate, hopSourceProbe, nil - } - } - } - return best, hopSourceValid, nil - } - - peer, err = ps.closestPeer(chunkAddress, true, slices.Concat(fullSkip, blocked)) - if !errors.Is(err, topology.ErrNotFound) || len(blocked) == 0 { - return peer, hopSourceUnknown, err - } - if ps.fullNode && swarm.Proximity(ps.address.Bytes(), chunkAddress.Bytes()) >= rad { - return peer, hopSourceUnknown, err - } - - // Every peer left is in a shallow pause. Waiting would hold a push slot - // of the pusher, so send through the connected peer whose pause ends first. - connected := ps.connectedOf(blocked) - for _, p := range blocked { - if swarm.ContainsAddress(connected, p) && !swarm.ContainsAddress(fullSkip, p) { - return p, hopSourcePaused, nil - } - } - - return peer, hopSourceUnknown, err -} - -// connectedOf returns the peers that are connected, in one pass over the -// connected peers. -func (ps *PushSync) connectedOf(peers []swarm.Address) []swarm.Address { - var connected []swarm.Address - _ = ps.topologyDriver.EachConnectedPeer(func(p swarm.Address, _ uint8) (bool, bool, error) { - if swarm.ContainsAddress(peers, p) { - connected = append(connected, p) - } - return len(connected) == len(peers), false, nil - }, topology.Select{}) - return connected -} - func (ps *PushSync) closestPeer(chunkAddress swarm.Address, origin bool, skipList []swarm.Address) (swarm.Address, error) { includeSelf := ps.fullNode && !origin From 52c3c285c4ab676a3014d1a54a83e737011c04ac Mon Sep 17 00:00:00 2001 From: Ljubisa Gacevic Date: Sun, 22 Nov 2026 20:45:31 +0100 Subject: [PATCH 16/16] feat(pushsync): limit the first-hop memory to 14 address bits per neighborhood --- pkg/pushsync/internal/firsthop/memory.go | 11 +++++++++-- pkg/pushsync/internal/firsthop/memory_test.go | 5 +++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/pkg/pushsync/internal/firsthop/memory.go b/pkg/pushsync/internal/firsthop/memory.go index 4d73fbe6c0a..a0f0f1ddb60 100644 --- a/pkg/pushsync/internal/firsthop/memory.go +++ b/pkg/pushsync/internal/firsthop/memory.go @@ -34,6 +34,11 @@ const ( // sweepInterval is the shortest time between two removals of idle records // in all neighborhoods. sweepInterval = validIdle + // maxKeyBits is the largest number of address bits that tell two + // neighborhoods apart. It limits the memory to 1<= len(b)*8 { return string(b) diff --git a/pkg/pushsync/internal/firsthop/memory_test.go b/pkg/pushsync/internal/firsthop/memory_test.go index cf13e55dc92..b222740a747 100644 --- a/pkg/pushsync/internal/firsthop/memory_test.go +++ b/pkg/pushsync/internal/firsthop/memory_test.go @@ -304,6 +304,11 @@ func TestNeighborhood(t *testing.T) { {"radius 8, same byte", 8, addr(0x6b, 0xff), true}, {"radius 8, bit 8 differs", 8, addr(0x6a, 0x00), false}, {"radius 0", 0, addr(0xff, 0xff), true}, + // the key has at most 14 bits + {"radius 14, bit 14 differs", 14, addr(0x6b, 0x04), false}, + {"radius 16, bit 14 differs", 16, addr(0x6b, 0x04), false}, + {"radius 16, bit 15 differs", 16, addr(0x6b, 0x02), true}, + {"radius 16, bit 16 differs", 16, addr(0x6b, 0x01), true}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel()