go-ethereum/trie/bintrie/hashed_node_test.go
CPerezz b6d415c88d
trie/bintrie: replace BinaryNode interface with GC-free NodeRef arena (#34055)
## Summary

Replace the `BinaryNode` interface with `NodeRef uint32` indices into
typed arena pools, eliminating GC-scanned pointers from binary trie
nodes.

Inspired by [fjl's
observation](https://github.com/ethereum/go-ethereum/pull/34034#issuecomment-4075176446):
> *"if the binary trie produces such a large graph, it should probably
be changed so that the trie node type does not contain pointers. The
runtime does not scan objects that do not contain pointers, so it can
really help with the performance to build it this way."*

### The problem

CPU profiling of the binary trie (EIP-7864) showed **44% of CPU time in
garbage collection**. Each `InternalNode` held two `BinaryNode`
interface values (2 pointer-words each), and the GC scanned every one.
With ~25K `InternalNode`s in memory during block processing, this
created enormous GC pressure.

### The solution

`NodeRef` is a compact `uint32` (2-bit kind tag + 30-bit pool index).
`NodeStore` manages chunked typed pools per node kind:
- **InternalNode pool**: ZERO Go pointers (children are `NodeRef`, hash
is `[32]byte`) → noscan spans
- **HashedNode pool**: ZERO Go pointers → noscan spans
- **StemNode pool**: retains `Values [][]byte` (matching existing
format)

The serialization format is unchanged — flat InternalNode
`[type][leftHash][rightHash]` = 65 bytes.

## Benchmark: Apple M4 Pro (`--benchtime=10s --count=3`, on top of
#34021)

| Metric | Baseline | Arena | Delta |
|--------|----------|-------|-------|
| Approve (Mgas/s) | 374 | 382 | **+2.1%** |
| BalanceOf (Mgas/s) | 885 | 901 | **+1.8%** |
| Approve allocs/op | 775K | **607K** | **-21.7%** |
| BalanceOf allocs/op | 265K | **228K** | **-14.0%** |

## Benchmark: AMD EPYC 48-core (50GB state, execution-specs ERC-20, on
top of #34021 + #34032)

| Benchmark | Baseline | Arena | Delta |
|-----------|----------|-------|-------|
| erc20_approve (write) | 22.4 Mgas/s | **27.0 Mgas/s** | **+20.5%** |
| mixed_sload_sstore | 62.9 Mgas/s | **97.3 Mgas/s** | **+54.7%** |
| erc20_balanceof (read) | 180.8 Mgas/s | 167.6 Mgas/s | -7.3% (cold
cache variance) |

The arena benefit scales with heap size — the EPYC (larger heap, more GC
pressure) shows much larger gains than the M4 Pro (efficient unified
memory). The mixed workload baseline was unstable (62.9 vs 16.3 Mgas/s
between runs due to GC-induced throughput collapse); the arena
eliminates this entirely (95-97 Mgas/s, stable).

## Dependencies

Benchmarked with #34021 (H01 N+1 fix) + #34032 (R14 parallel hashing).
No code dependency — applies independently to master.

All test suites pass (`trie/bintrie` with `-race`, `core/state`,
`triedb/pathdb`, `cmd/geth`).

---------

Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com>
2026-04-20 14:08:30 +02:00

154 lines
4.8 KiB
Go

// Copyright 2025 go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package bintrie
import (
"bytes"
"errors"
"testing"
"github.com/ethereum/go-ethereum/common"
)
// TestHashedNodeHash tests the Hash method via nodeStore.
func TestHashedNodeHash(t *testing.T) {
hash := common.HexToHash("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef")
s := newNodeStore()
ref := s.newHashedRef(hash)
if s.computeHash(ref) != hash {
t.Errorf("Hash mismatch: expected %x, got %x", hash, s.computeHash(ref))
}
}
// TestHashedNodeCopy tests the Copy method via nodeStore.
func TestHashedNodeCopy(t *testing.T) {
hash := common.HexToHash("0xabcdef")
s := newNodeStore()
ref := s.newHashedRef(hash)
s.root = ref
ns := s.Copy()
copiedHash := ns.computeHash(ns.root)
if copiedHash != hash {
t.Errorf("Hash mismatch after copy: expected %x, got %x", hash, copiedHash)
}
}
// TestHashedNodeInsertValuesAtStem tests InsertValuesAtStem resolution via nodeStore.
func TestHashedNodeInsertValuesAtStem(t *testing.T) {
// Test 1: nil resolver should return an error
s := newNodeStore()
hashedRef := s.newHashedRef(common.HexToHash("0x1234"))
s.root = hashedRef
stem := make([]byte, StemSize)
values := make([][]byte, StemNodeWidth)
err := s.InsertValuesAtStem(stem, values, nil)
if err == nil {
t.Fatal("Expected error for InsertValuesAtStem with nil resolver")
}
// Test 2: mock resolver returning invalid data should return deserialization error
mockResolver := func(path []byte, hash common.Hash) ([]byte, error) {
return []byte{0xff, 0xff, 0xff}, nil
}
s2 := newNodeStore()
hashedRef2 := s2.newHashedRef(common.HexToHash("0x1234"))
s2.root = hashedRef2
err = s2.InsertValuesAtStem(stem, values, mockResolver)
if err == nil {
t.Fatal("Expected error for InsertValuesAtStem with invalid resolver data")
}
// Test 3: mock resolver returning valid serialized node should succeed
stem = make([]byte, StemSize)
stem[0] = 0xaa
originalValues := make([][]byte, StemNodeWidth)
originalValues[0] = common.HexToHash("0x1111111111111111111111111111111111111111111111111111111111111111").Bytes()
originalValues[1] = common.HexToHash("0x2222222222222222222222222222222222222222222222222222222222222222").Bytes()
// Build the serialized node
rs := newNodeStore()
ref := rs.newStemRef(stem, 0)
sn := rs.getStem(ref.Index())
for i, v := range originalValues {
if v != nil {
sn.setValue(byte(i), v)
}
}
serialized := rs.serializeNode(ref)
validResolver := func(path []byte, hash common.Hash) ([]byte, error) {
return serialized, nil
}
s3 := newNodeStore()
hashedRef3 := s3.newHashedRef(common.HexToHash("0x1234"))
s3.root = hashedRef3
newValues := make([][]byte, StemNodeWidth)
newValues[2] = common.HexToHash("0x3333333333333333333333333333333333333333333333333333333333333333").Bytes()
err = s3.InsertValuesAtStem(stem, newValues, validResolver)
if err != nil {
t.Fatalf("Expected successful resolution and insertion, got error: %v", err)
}
// Verify original values are preserved
retrieved, err := s3.GetValuesAtStem(stem, nil)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(retrieved[0], originalValues[0]) {
t.Errorf("Original value at index 0 not preserved")
}
if !bytes.Equal(retrieved[1], originalValues[1]) {
t.Errorf("Original value at index 1 not preserved")
}
if !bytes.Equal(retrieved[2], newValues[2]) {
t.Errorf("New value at index 2 not inserted correctly")
}
}
// TestHashedNodeGetError tests that getting through an unresolved HashedNode root returns error.
func TestHashedNodeGetError(t *testing.T) {
s := newNodeStore()
// Create root as hashed, then try to resolve through InternalNode parent
rootRef := s.newInternalRef(0)
rootNode := s.getInternal(rootRef.Index())
hashedLeft := s.newHashedRef(common.HexToHash("0x1234"))
rootNode.left = hashedLeft
rootNode.right = emptyRef
s.root = rootRef
key := make([]byte, 32) // goes left
key[31] = 5
resolver := func(path []byte, hash common.Hash) ([]byte, error) {
return nil, errors.New("node not found")
}
_, err := s.Get(key, resolver)
if err == nil {
t.Fatal("Expected error when resolver fails")
}
}