Repository navigation
fix: make the consistent-hash strategy actually consistent (#131) - #271
Merged
Merged
Conversation
selectConsistentHash was `return nodes[:count]` under a comment saying a real
ring belonged there. Its node slice comes from ranging a map, so the same key
reached a different node on each call — the one property consistent hashing
exists to provide, and the one a per-node cache needs in order to hit.
Replaced with a rendezvous (highest-random-weight) ring in
internal/distributed/hashring: score every node against the key, take the
highest, break ties on node ID. Removing a node moves only the keys it owned,
about 1/n, which is asserted with that bound rather than described. Lookup is
O(n) in nodes; the benchmark settles whether that matters at 1555 ns for 100
nodes and 125 ns for 8, zero allocations, three orders of magnitude under the
S3 round trip it precedes.
The issue's plan had a gap: LoadBalancer.SelectNodes never received the
operation key, so nothing behind it could have hashed by key however it was
implemented. It now takes one, which makes the key mandatory at all five call
sites rather than something a strategy could quietly do without.
selectTargetNodes also sorts its alive-node slice. The ring sorts internally,
so removing that sort changes nothing a consistent-hash test can observe —
verified by removing it — but round-robin and the least-load tiebreak index
positionally, and for those the order the map happened to be iterated in *was*
the decision.
The existing test asserted only the returned count, and its own comment
described the defect ("returns the requested number of nodes from the front of
the list") as the intended behavior. A count assertion cannot tell a ring from
a prefix, so it now asserts that permuting the input does not change the
output, which a prefix fails.
Seven mutations, all caught: slice-prefix selection, unsorted alive nodes,
missing hash separator, missing tie-break, no-op Remove, score-ignoring sort,
non-idempotent Add. Two of the seven were caught only after adding tests —
the tie-break is unreachable through the public API since it needs a 64-bit
score collision, so it is asserted on an extracted comparator; and the sort
needed an end-to-end round-robin test, since the ring had been hiding its
absence.
hashring is at 100% coverage with a floor to match, and FuzzLookupIsStable ran
30M executions clean.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #131.
The defect
selectConsistentHashwas:nodesarrives fromselectTargetNodes, which builds it by rangingc.cluster.GetNodes()— a map,whose iteration order Go randomizes per call. So the same key reached a different node on each call.
That is the one property consistent hashing exists to provide, and the one a per-node cache needs in
order to hit at all.
The fix
internal/distributed/hashring: rendezvous (HRW) hashing. Score every node against the key withxxhash(nodeID + "#" + key), take the highest, break ties on node ID. No newgo.modentry —cespare/xxhash/v2was already an indirect dependency.Removing a node moves only the keys that node owned, about 1/n, which is asserted with that bound
rather than described.
Lookupis O(n) in nodes; the benchmark settles whether that matters:Three orders of magnitude below the S3 round trip it precedes, so a sorted ring with virtual nodes
would be complexity spent on nothing.
A prerequisite the issue did not mention
LoadBalancer.SelectNodes(availableNodes []string, count int)never received the operation key, sono implementation behind it could have hashed by key however it was written. It now takes one, which
makes the key mandatory at all five call sites in
selectTargetNodesrather than something astrategy could quietly do without.
selectTargetNodesalso sorts its alive-node slice now. The ring sorts internally, so removing thatsort changes nothing a consistent-hash test can observe — verified by removing it — but round-robin
and the least-load tiebreak index the slice positionally, and for those the order the map happened
to be iterated in was the decision.
A test that could not have caught this
TestLoadBalancer_ConsistentHashasserted only the returned count, and its own doc comment describedthe defect as the intended behavior: "returns the requested number of nodes from the front of the
list." A count assertion passes on
nodes[:count]. It now asserts that permuting the input does notchange the output, plus an end-to-end
selectTargetNodestest that exercises the real randomized mapiteration rather than simulating it.
Verification
Seven mutations, all caught:
TestLoadBalancer_ConsistentHash,TestSelectTargetNodes_IsOrderIndependentTestSelectTargetNodes_SortsAliveNodesTestSeparatorPreventsBoundaryCollisionsTestOutranksBreaksTiesByNodeIDRemovemade a no-opLookupNsorts by node instead of scoreTestLookupAgreesWithLookupNAddmade non-idempotentTestAddIsIdempotentAndSorted,FuzzLookupIsStableTwo of the seven were caught only after adding tests, which is the reason for running them rather
than predicting them:
removing it passed every test in the file.
sort.Sliceis not stable, so on a collision the winnerwithout it is whichever element the sort left first, i.e. the input-order dependence this whole
change removes. Extracted as
outranksso the rule is assertable directly, andLookupnow usesit too, so the two entry points cannot drift apart on a tie.
Gates:
go build·go vet·gofmt -l0 · full suite-racegreen · coverage gate 35 packagesat or above floor,
hashringat 100% with a floor to match ·golangci-lint --new-from-merge-base0 issues · standalonegosecfinds nothing in the new code (the twoG404hits inconsensus.go:856,859are pre-existing and untouched) ·FuzzLookupIsStable30Mexecutions clean.