diff --git a/pkg/pushsync/export_test.go b/pkg/pushsync/export_test.go index 0a9fdebdf07..ce4fda3b7e8 100644 --- a/pkg/pushsync/export_test.go +++ b/pkg/pushsync/export_test.go @@ -4,7 +4,13 @@ package pushsync -import "github.com/ethersphere/bee/v2/pkg/pushsync/pb" +import ( + "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" + dto "github.com/prometheus/client_model/go" +) var ( ProtocolName = protocolName @@ -15,6 +21,25 @@ 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) + rad, err := ps.radius() + if err != nil { + return err + } + _, err = ps.checkReceipt(receipt, swarm.ZeroAddress, rad) return err } + +// 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)) +} + +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/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/internal/firsthop/memory.go b/pkg/pushsync/internal/firsthop/memory.go new file mode 100644 index 00000000000..a0f0f1ddb60 --- /dev/null +++ b/pkg/pushsync/internal/firsthop/memory.go @@ -0,0 +1,335 @@ +// 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 + // maxKeyBits is the largest number of address bits that tell two + // neighborhoods apart. It limits the memory to 1<= validIdle + } + return now.Sub(r.at) >= shallowIdle +} + +// neighborhood holds the records of the chunk addresses that share the first +// radius bits, at most maxKeyBits. +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, at most +// maxKeyBits. +func neighborhoodKey(radius uint8, chunk swarm.Address) string { + radius = min(radius, maxKeyBits) + 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..b222740a747 --- /dev/null +++ b/pkg/pushsync/internal/firsthop/memory_test.go @@ -0,0 +1,438 @@ +// 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}, + // 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() + + 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() +} diff --git a/pkg/pushsync/metrics.go b/pkg/pushsync/metrics.go index 20e1054f76c..2240e6354fb 100644 --- a/pkg/pushsync/metrics.go +++ b/pkg/pushsync/metrics.go @@ -32,9 +32,14 @@ type metrics struct { OverdraftRefresh prometheus.Counter OutOfDepthStoring prometheus.Counter OriginNoPeersLeft prometheus.Counter + FirstHop *prometheus.CounterVec + FirstHopRecords prometheus.GaugeFunc + FirstHopNeighborhoods prometheus.GaugeFunc } -func newMetrics() 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{ @@ -168,6 +173,33 @@ 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, paused) and the result (valid, shallow, error).", + }, + []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 := firstHopSize() + 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 { + neighborhoods, _ := firstHopSize() + return float64(neighborhoods) + }), } } diff --git a/pkg/pushsync/pushsync.go b/pkg/pushsync/pushsync.go index df80179ad6b..d0d00458ca4 100644 --- a/pkg/pushsync/pushsync.go +++ b/pkg/pushsync/pushsync.go @@ -21,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" @@ -97,6 +98,7 @@ type PushSync struct { signer crypto.Signer fullNode bool errSkip *skippeers.List + firstHops *firsthop.Memory // receipt results of the first hops of an origin stabilizer stabilization.Subscriber overDraftRefreshLimiter *rate.Limiter } @@ -127,6 +129,7 @@ func New( tracer *tracing.Tracer, stabilizer stabilization.Subscriber, ) *PushSync { + firstHops := firsthop.New(time.Now) ps := &PushSync{ address: address, radius: radius, @@ -141,10 +144,11 @@ func New( logger: logger.WithName(loggerName).Register(), accounting: accounting, pricer: pricer, - metrics: newMetrics(), + metrics: newMetrics(firstHops.Size), tracer: tracer, signer: signer, errSkip: skippeers.NewList(time.Minute), + firstHops: firstHops, stabilizer: stabilizer, overDraftRefreshLimiter: rate.NewLimiter(rate.Every(time.Second), 1), } @@ -372,9 +376,11 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo parallelForwards = maxMultiplexForwards shallowReceiptResult *pb.Receipt shallowReceiptPO uint8 + op *originPush // first hops of an origin ) if origin { + op = ps.newOriginPush(ch.Address()) ticker := time.NewTicker(preemptiveInterval) defer ticker.Stop() preemptiveTicker = ticker.C @@ -415,13 +421,26 @@ 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. // 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 + ) + if origin { + peer, err = op.next(rad, fullSkip) + } 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. @@ -516,6 +535,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 @@ -524,8 +550,9 @@ 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, rad); { case err == nil: + op.record(rad, result.peer, nil) return result.receipt, nil case errors.Is(err, ErrShallowReceipt): if shallowReceiptResult == nil || po > shallowReceiptPO { @@ -538,6 +565,12 @@ func (ps *PushSync) pushToClosest(ctx context.Context, ch swarm.Chunk, origin bo } } + // 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() ps.logger.Debug("could not push to peer", "chunk_address", ch.Address(), "id_address", idAddress, "peer_address", result.peer, "error", result.err) @@ -622,8 +655,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) (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()) @@ -638,20 +671,15 @@ func (ps *PushSync) checkReceipt(receipt *pb.Receipt) (uint8, error) { 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() - 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 } diff --git a/pkg/retrieval/retrieval.go b/pkg/retrieval/retrieval.go index 046fff39086..dc9ab4fa10b 100644 --- a/pkg/retrieval/retrieval.go +++ b/pkg/retrieval/retrieval.go @@ -391,12 +391,11 @@ 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 { diff --git a/pkg/retrieval/retrieval_test.go b/pkg/retrieval/retrieval_test.go index 436b9e97b1a..63e4fab6dd4 100644 --- a/pkg/retrieval/retrieval_test.go +++ b/pkg/retrieval/retrieval_test.go @@ -719,3 +719,84 @@ func createRetrieval( t.Cleanup(func() { ret.Close() }) return ret } + +// 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 ( + 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, 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} + ) + + 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()]) || (filter.Reachable && p.Equal(private)) || 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 + base swarm.Address + peers []swarm.Address + origin bool + 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: 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: 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() + + 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) + } + if !got.Equal(tc.want) { + t.Fatalf("want %s, got %s", tc.want, got) + } + }) + } +}