Repository navigation
feat(discovery): limit discv4 routing-table entries per subnet #16416
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 6 commits
02641de
5e85ec1
a0d63ce
1744bb8
f40a3e2
41e1c11
b0178c6
61c3c23
56bb582
38fc60d
e603dae
4547c30
7b8366b
6d5b8cf
33e2574
337f676
bc270a4
e2843c0
4d35ad0
7173ec9
a9bffc6
502a80e
948edaf
7ddaf92
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,5 +7,6 @@ public enum BucketAddResult | |
| { | ||
| Added, | ||
| Refreshed, | ||
| Full | ||
| Full, | ||
| Rejected | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited | ||
| // SPDX-License-Identifier: LGPL-3.0-only | ||
|
|
||
| namespace Nethermind.Kademlia; | ||
|
|
||
| /// <summary> | ||
| /// Admission policy for nodes entering the routing table. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Lock order is routing-table lock, then limiter lock. <see cref="TryAdmit"/> is called under the routing-table | ||
| /// lock, so an implementation must not call back into the table. The bucket scan receives the bucket's cached array, | ||
| /// which allocates only when the bucket size exceeds the replacement cache size. | ||
| /// </remarks> | ||
| public interface IRoutingTableNodeLimiter<TNode> | ||
| { | ||
| /// <summary>Admits <paramref name="node"/> to the bucket whose active entries are <paramref name="bucketNodes"/>.</summary> | ||
| /// <remarks>Called under the routing-table lock. Must not call back into the table. An exempt verdict releases | ||
| /// any charge the node previously held, so a node that gains an exemption stops consuming its subnet slot.</remarks> | ||
| bool TryAdmit(TNode node, ReadOnlySpan<TNode> bucketNodes); | ||
|
|
||
| /// <summary>Releases the slot held by <paramref name="node"/>, if any. Idempotent.</summary> | ||
| void Release(TNode node); | ||
|
|
||
| /// <summary>Table-wide probe: whether <see cref="TryAdmit"/> would find a table slot. Does not reserve.</summary> | ||
| bool WouldAdmit(TNode node); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -56,21 +56,32 @@ public BucketAddResult TryAddOrRefresh(in TKadKey hash, TNode item, out TNode? t | |
|
|
||
| internal int CopyAllWithHash((TKadKey Hash, TNode Node)[] destination) => _items.CopyAllWithKey(destination); | ||
|
|
||
| public bool RemoveAndReplace(in TKadKey hash) | ||
| public bool Remove(in TKadKey hash) | ||
| { | ||
| if (!_items.Remove(hash)) return false; | ||
|
|
||
| if (_replacement.TryPopHead(out TKadKey replacementHash, out TNode? replacement)) | ||
| { | ||
| _items.AddOrRefresh(replacementHash, replacement!); | ||
| } | ||
| UpdateCachedArray(); | ||
| return true; | ||
| } | ||
|
|
||
| if (_cacheItems) | ||
| /// <summary> | ||
| /// Promotes the most recently cached replacement that <paramref name="canPromote"/> accepts, discarding the | ||
| /// candidates it rejects. | ||
| /// </summary> | ||
| /// <param name="canPromote">Admission predicate for a candidate, or <see langword="null"/> to accept the first.</param> | ||
| /// <returns><see langword="true"/> when a replacement was promoted.</returns> | ||
| public bool TryPromote(Func<TNode, bool>? canPromote) | ||
| { | ||
| while (_replacement.TryPopHead(out TKadKey replacementHash, out TNode? replacement)) | ||
| { | ||
| _cachedArray = _items.GetAll(); | ||
| if (canPromote is not null && !canPromote(replacement!)) continue; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rejected candidates are dropped from the cache here. I'd keep them, one removal can drain the whole replacement cache when their subnet sits at the cap
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 7b8366b. TryPromote now iterates _replacement.GetAllWithKey() head-first (same ordering as the old TryPopHead loop) and removes only the candidate that passes re-admission; rejected candidates stay cached, so a subnet at cap no longer drains the replacement cache. UpdateCachedArray still runs on promote. |
||
|
|
||
| _items.AddOrRefresh(replacementHash, replacement!); | ||
| UpdateCachedArray(); | ||
| return true; | ||
| } | ||
|
|
||
| return true; | ||
| return false; | ||
| } | ||
|
|
||
| public void Clear() | ||
|
|
@@ -87,6 +98,11 @@ public void Clear() | |
| internal bool TryGetStored(in TKadKey hash, [MaybeNullWhen(false)] out TNode node) | ||
| => _items.TryGetValue(hash, out node) || _replacement.TryGetValue(hash, out node); | ||
|
|
||
| private void UpdateCachedArray() | ||
| { | ||
| if (_cacheItems) _cachedArray = _items.GetAll(); | ||
| } | ||
|
|
||
| private static bool ShouldUpdateCachedArray(TNode? previous, TNode item) | ||
| => previous is not null && | ||
| (typeof(TNode).IsValueType | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -30,6 +30,7 @@ private class TreeNode(int k, TKadKey prefix) | |
| private readonly TKadKey _currentNodeHash; | ||
| private readonly IKademliaDistance<TKadKey> _distance; | ||
| private readonly Func<TNode, TNode, TNode>? _mergeOnRefresh; | ||
| private readonly IRoutingTableNodeLimiter<TNode>? _limiter; | ||
| private readonly ILogger _logger; | ||
|
|
||
| private readonly Lock _lock = new(); | ||
|
|
@@ -54,6 +55,7 @@ public KBucketTree( | |
| _distance = distance; | ||
| _currentNodeHash = nodeHashProvider.GetHash(config.CurrentNodeId); | ||
| _mergeOnRefresh = config.MergeOnRefresh; | ||
| _limiter = config.NodeLimiter; | ||
| _root = new TreeNode(config.KSize, distance.Zero); | ||
| _logger = loggerFactory.CreateLogger<KBucketTree<TNode, TKadKey>>(); | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Initialized KBucketTree with k={_k}, currentNodeId={_currentNodeHash}"); | ||
|
|
@@ -81,7 +83,23 @@ public BucketAddResult TryAddOrRefresh(in TKadKey nodeHash, TNode node, out TNod | |
| } | ||
| } | ||
|
|
||
| IRoutingTableNodeLimiter<TNode>? limiter = _limiter; | ||
| if (limiter is not null && !limiter.TryAdmit(nodeToStore, bucket.GetAllCached())) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [possible issue] Low — Probe: The effect lasts only until a node from another subnet splits the bucket. Fix: run the limiter on the leaf the node actually lands in, e.g. from the leaf branch of 🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 56bb582. |
||
| { | ||
| if (_logger.IsEnabled(LogLevel.Trace)) _logger.LogTrace($"Subnet limiter rejected node {nodeToStore}"); | ||
| toRefresh = default; | ||
| fireAdded = false; | ||
| return BucketAddResult.Rejected; | ||
| } | ||
|
|
||
| resp = TryAddOrRefreshLocked(nodeHash, nodeToStore, out toRefresh, out fireAdded); | ||
| if (resp == BucketAddResult.Full) | ||
| { | ||
| // The node landed in the replacement cache, not the table: release the | ||
| // charge so only active entries count. Full implies the key was absent | ||
| // from the active set, so this cannot release a live slot. | ||
| limiter?.Release(nodeToStore); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P3] A replacement-cache insertion can make NodeSource drop an eligible candidate even though active subnet occupancy stays at nine. In a full unsplittable leaf, TryAdmit publishes the tenth charge and unlocks the limiter before the bucket returns Full and the tree releases the charge. The candidate consumer takes only the limiter lock, so an already queued, uncharged candidate can be filtered in that interval. Its identity remains reserved in RecentNodeFilter after the drop. Check eligibility without charging an absent key in a full unsplittable leaf, and charge it when promoted.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in a9bffc6. A full unsplittable leaf now uses ProbeAdmit (DiscoveryNodeLimiter.cs:151-159) — a pure check under the limiter lock with no mutation and no charge — and parks the candidate uncharged; the charge happens only when promotion admits it. The consumer's WouldAdmit window can no longer observe a phantom tenth charge. |
||
| } | ||
| } | ||
|
|
||
| if (fireAdded) OnNodeAdded?.Invoke(this, nodeToStore); | ||
|
|
@@ -199,7 +217,12 @@ public bool Remove(in TKadKey nodeHash) | |
|
|
||
| KBucket<TNode, TKadKey> bucket = GetBucketForHash(nodeHash); | ||
| removedNode = bucket.GetByHash(nodeHash); | ||
| removed = bucket.RemoveAndReplace(nodeHash); | ||
| removed = bucket.Remove(nodeHash); | ||
| if (removed) | ||
| { | ||
| if (removedNode is not null) _limiter?.Release(removedNode); | ||
| bucket.TryPromote(node => _limiter is null || _limiter.TryAdmit(node, bucket.GetAllCached())); | ||
| } | ||
| } | ||
|
|
||
| if (removed && removedNode is not null) OnNodeRemoved?.Invoke(this, removedNode); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited | ||
| // SPDX-License-Identifier: LGPL-3.0-only | ||
|
|
||
| using Nethermind.Core.Crypto; | ||
|
|
||
| namespace Nethermind.Network; | ||
|
|
||
| /// <summary> | ||
| /// Live lookup for nodes exempt from discovery subnet limits (managed static/trusted entries). | ||
| /// Implemented by the full client; absent in slim hosts such as the bootnode. | ||
| /// </summary> | ||
| public interface IDiscoveryNodeExemptions | ||
| { | ||
| /// <summary>Returns <see langword="true"/> when a managed static or trusted node has <paramref name="nodeId"/> as its identity.</summary> | ||
| bool IsExempt(PublicKey nodeId); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] A rejected endpoint change can cancel the liveness check for the endpoint the table retains. While a probe to incumbent A is pending, the same identity can complete a separate discv4 bond at B. NodeHealthTracker.OnIncomingMessageFrom clears the pending refresh by identity before the new Rejected result leaves A in the table, then clears the failure count too. If A times out, RefreshAsync skips removal because B already cleared the marker. Lookups keep returning A and its subnet charge remains occupied. Clear liveness state only when the update is accepted or the message proves liveness at the retained endpoint.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 337f676. NodeHealthTracker.OnIncomingMessageFrom (NodeHealthTracker.cs:128-135) clears _isRefreshing and _peerFailures only when addResult != Rejected — a refused endpoint change at B leaves the pending refresh and failure count for retained A intact, so A's timeout still evicts it and frees the slot and charge