Skip to content

Commit 5bc0fee

Browse files
otroanclaude
andcommitted
adapter/statsclient: compare entry names in place on refresh
updateStatOnIndex confirms a prepared entry is still the one it prepared by comparing its name against the directory. It did that through GetStatDirOnIndex, which clones the name out of the shared memory region - correct for callers that retain it, wasteful here, where the copy is compared and dropped on the next line. UpdateDir runs this once per prepared entry per tick. With the previous commit reading each symlink target once, that clone became the dominant remaining cost of a refresh: a prepared dir over a real box's ~3900 entries cloned ~3900 names every tick. Add StatDirOnIndexMatches, which compares in place and reports whether the name at an index equals the caller's, and use it here. GetStatDirOnIndex keeps cloning, since its callers do retain the name. Refreshing 128 symlinks goes from 142 allocations to 14. Both segment versions implement it. The v1 path had no coverage at all - the fake segment harness is v2-only - so the test builds a directory vector directly for each version and checks that a prefix, an extension, a different name of equal length and an empty name are all rejected, and that a mismatch reports adapter.Unknown rather than a plausible type. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 3cbab7e commit 5bc0fee

5 files changed

Lines changed: 193 additions & 6 deletions

File tree

‎adapter/statsclient/stat_segment_api.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,17 @@ type statSegment interface {
8484
// the same memory address as the argument.
8585
GetStatDirOnIndex(v dirVector, index uint32) (dirSegment, dirName, adapter.StatType)
8686

87+
// StatDirOnIndexMatches is GetStatDirOnIndex for callers that only need to
88+
// confirm an entry is still the one they prepared. It compares the name in
89+
// place instead of copying it out, which matters on a refresh path: UpdateDir
90+
// runs it once per prepared entry per tick, and cloning a name to compare it
91+
// is an allocation per entry for a value discarded immediately afterwards.
92+
//
93+
// ok reports whether the name at index equals want. The segment pointer is
94+
// returned either way; the StatType is meaningful only when ok is true, and
95+
// is adapter.Unknown otherwise.
96+
StatDirOnIndexMatches(v dirVector, index uint32, want []byte) (dirSegment, adapter.StatType, bool)
97+
8798
// GetEpoch re-loads stats header and returns current epoch
8899
//and 'inProgress' value
89100
GetEpoch() (int64, bool)

‎adapter/statsclient/statsclient.go‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package statsclient
1818

1919
import (
20-
"bytes"
2120
"fmt"
2221
"net"
2322
"os"
@@ -661,10 +660,12 @@ func (sc *StatsClient) updateStatOnIndex(entry *adapter.StatEntry, vector dirVec
661660
if entry.Index >= dirLen {
662661
return ref, false, fmt.Errorf("stat entry index %d out of dir vector length (%d)", entry.Index, dirLen)
663662
}
664-
dirPtr, dirName, dirType := sc.GetStatDirOnIndex(vector, entry.Index)
665-
// Identity is the name; if it no longer matches, the directory changed under us
666-
// (the epoch check in UpdateDir normally catches this first).
667-
if len(dirName) == 0 || !bytes.Equal(dirName, entry.Name) || entry.Data == nil {
663+
// Identity is the name; if it no longer matches, the directory changed under
664+
// us (the epoch check in UpdateDir normally catches this first). Compared in
665+
// place: this runs once per prepared entry per tick, and cloning the name to
666+
// compare it would allocate per entry for a value discarded immediately after.
667+
dirPtr, dirType, match := sc.StatDirOnIndexMatches(vector, entry.Index, entry.Name)
668+
if !match || entry.Data == nil {
668669
return ref, false, nil
669670
}
670671
if dirType == adapter.Symlink {
@@ -684,7 +685,7 @@ func (sc *StatsClient) updateStatOnIndex(entry *adapter.StatEntry, vector dirVec
684685
return ref, false, nil
685686
}
686687
if err := sc.UpdateEntryData(dirPtr, &entry.Data); err != nil {
687-
return ref, false, fmt.Errorf("updating stat data for entry %s failed: %v", dirName, err)
688+
return ref, false, fmt.Errorf("updating stat data for entry %s failed: %v", entry.Name, err)
688689
}
689690
return ref, false, nil
690691
}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
// Copyright (c) 2026 Meter, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at:
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package statsclient
16+
17+
import (
18+
"testing"
19+
"unsafe"
20+
21+
"go.fd.io/govpp/adapter"
22+
)
23+
24+
// dirEntryBuf lays out a directory vector holding the given names, for both
25+
// segment versions. The vector is preceded by its length, as VPP lays it out.
26+
func dirEntryBufV1(t *testing.T, names []string) (dirVector, func()) {
27+
t.Helper()
28+
sz := int(unsafe.Sizeof(statSegDirectoryEntryV1{}))
29+
buf := make([]byte, 8+sz*len(names))
30+
*(*uint32)(unsafe.Pointer(&buf[0])) = uint32(len(names))
31+
base := unsafe.Pointer(&buf[8])
32+
for i, n := range names {
33+
e := (*statSegDirectoryEntryV1)(unsafe.Add(base, i*sz))
34+
copy(e.name[:], n)
35+
e.name[len(n)] = 0
36+
e.directoryType = 2 // SimpleCounterVector
37+
}
38+
return dirVector(base), func() { runtimeKeepAlive(buf) }
39+
}
40+
41+
func dirEntryBufV2(t *testing.T, names []string) (dirVector, func()) {
42+
t.Helper()
43+
sz := int(unsafe.Sizeof(statSegDirectoryEntryV2{}))
44+
buf := make([]byte, 8+sz*len(names))
45+
*(*uint32)(unsafe.Pointer(&buf[0])) = uint32(len(names))
46+
base := unsafe.Pointer(&buf[8])
47+
for i, n := range names {
48+
e := (*statSegDirectoryEntryV2)(unsafe.Add(base, i*sz))
49+
copy(e.name[:], n)
50+
e.name[len(n)] = 0
51+
e.directoryType = 2 // SimpleCounterVector
52+
}
53+
return dirVector(base), func() { runtimeKeepAlive(buf) }
54+
}
55+
56+
func runtimeKeepAlive(b []byte) { _ = b }
57+
58+
// TestStatDirOnIndexMatches covers both segment versions. v1 is easy to leave
59+
// untested - the fake segment harness is v2-only - and it is exactly where a
60+
// regression would go unnoticed.
61+
func TestStatDirOnIndexMatches(t *testing.T) {
62+
names := []string{"/if/rx", "/node/errors", "/sys/heartbeat"}
63+
64+
for _, tc := range []struct {
65+
version string
66+
build func(*testing.T, []string) (dirVector, func())
67+
seg statSegment
68+
}{
69+
{"v1", dirEntryBufV1, &statSegmentV1{}},
70+
{"v2", dirEntryBufV2, &statSegmentV2{sharedHeader: make([]byte, 1<<12)}},
71+
} {
72+
t.Run(tc.version, func(t *testing.T) {
73+
v, keep := tc.build(t, names)
74+
defer keep()
75+
76+
for i, n := range names {
77+
_, typ, ok := tc.seg.StatDirOnIndexMatches(v, uint32(i), []byte(n))
78+
if !ok {
79+
t.Errorf("index %d (%q): reported no match", i, n)
80+
}
81+
if typ == adapter.Unknown {
82+
t.Errorf("index %d (%q): matched but type is Unknown", i, n)
83+
}
84+
}
85+
86+
// A name that is a prefix of the stored one must NOT match: the
87+
// length check is what stops /if/rx matching /if/rx-unicast.
88+
if _, _, ok := tc.seg.StatDirOnIndexMatches(v, 0, []byte("/if/r")); ok {
89+
t.Error("a prefix of the stored name matched")
90+
}
91+
// Nor an extension of it.
92+
if _, _, ok := tc.seg.StatDirOnIndexMatches(v, 0, []byte("/if/rx-unicast")); ok {
93+
t.Error("an extension of the stored name matched")
94+
}
95+
// Wrong entry at the right length.
96+
if _, _, ok := tc.seg.StatDirOnIndexMatches(v, 0, []byte("/if/tx")); ok {
97+
t.Error("a different name of equal length matched")
98+
}
99+
// Empty want against a non-empty entry.
100+
if _, _, ok := tc.seg.StatDirOnIndexMatches(v, 0, nil); ok {
101+
t.Error("an empty name matched a populated entry")
102+
}
103+
// A mismatch must report Unknown rather than a plausible type.
104+
if _, typ, _ := tc.seg.StatDirOnIndexMatches(v, 0, []byte("/if/tx")); typ != adapter.Unknown {
105+
t.Errorf("mismatch reported type %v, want Unknown", typ)
106+
}
107+
})
108+
}
109+
}
110+
111+
// TestStatDirOnIndexMatchesAgreesWithGet pins the two accessors together: the
112+
// in-place comparison must accept exactly the names GetStatDirOnIndex reports.
113+
func TestStatDirOnIndexMatchesAgreesWithGet(t *testing.T) {
114+
f := newFakeSegment(t, fakeGroupValues(8))
115+
sc := f.client()
116+
v := sc.GetDirectoryVector()
117+
if v == nil {
118+
t.Fatal("nil directory vector")
119+
}
120+
for i := uint32(0); i < 10; i++ {
121+
_, name, typ := sc.GetStatDirOnIndex(v, i)
122+
if len(name) == 0 {
123+
continue
124+
}
125+
_, mTyp, ok := sc.StatDirOnIndexMatches(v, i, name)
126+
if !ok {
127+
t.Errorf("index %d: GetStatDirOnIndex says %q, Matches disagrees", i, name)
128+
}
129+
if mTyp != typ {
130+
t.Errorf("index %d (%q): type %v vs %v", i, name, mTyp, typ)
131+
}
132+
}
133+
}

‎adapter/statsclient/statseg_v1.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,27 @@ func (ss *statSegmentV1) GetStatDirOnIndex(v dirVector, index uint32) (dirSegmen
8888
return statSegDir, name, getStatType(dir.directoryType, true)
8989
}
9090

91+
// StatDirOnIndexMatches compares the entry name in place - see the interface.
92+
func (ss *statSegmentV1) StatDirOnIndexMatches(v dirVector, index uint32, want []byte) (dirSegment, adapter.StatType, bool) {
93+
statSegDir := dirSegment(uintptr(v) + uintptr(index)*unsafe.Sizeof(statSegDirectoryEntryV1{}))
94+
dir := (*statSegDirectoryEntryV1)(statSegDir)
95+
n := 0
96+
for ; n < len(dir.name); n++ {
97+
if dir.name[n] == 0 {
98+
break
99+
}
100+
}
101+
if n == 0 || n != len(want) {
102+
return statSegDir, adapter.Unknown, false
103+
}
104+
for i := 0; i < n; i++ {
105+
if dir.name[i] != want[i] {
106+
return statSegDir, adapter.Unknown, false
107+
}
108+
}
109+
return statSegDir, getStatType(dir.directoryType, true), true
110+
}
111+
91112
func (ss *statSegmentV1) GetEpoch() (int64, bool) {
92113
sh := ss.loadSharedHeader(ss.sharedHeader)
93114
return sh.epoch, sh.inProgress != 0

‎adapter/statsclient/statseg_v2.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,27 @@ func (ss *statSegmentV2) GetStatDirOnIndex(v dirVector, index uint32) (dirSegmen
8888
return statSegDir, name, getStatType(dir.directoryType, ss.getErrorVector() != nil)
8989
}
9090

91+
// StatDirOnIndexMatches compares the entry name in place - see the interface.
92+
func (ss *statSegmentV2) StatDirOnIndexMatches(v dirVector, index uint32, want []byte) (dirSegment, adapter.StatType, bool) {
93+
statSegDir := dirSegment(uintptr(v) + uintptr(index)*unsafe.Sizeof(statSegDirectoryEntryV2{}))
94+
dir := (*statSegDirectoryEntryV2)(statSegDir)
95+
n := 0
96+
for ; n < len(dir.name); n++ {
97+
if dir.name[n] == 0 {
98+
break
99+
}
100+
}
101+
if n == 0 || n != len(want) {
102+
return statSegDir, adapter.Unknown, false
103+
}
104+
for i := 0; i < n; i++ {
105+
if dir.name[i] != want[i] {
106+
return statSegDir, adapter.Unknown, false
107+
}
108+
}
109+
return statSegDir, getStatType(dir.directoryType, ss.getErrorVector() != nil), true
110+
}
111+
91112
func (ss *statSegmentV2) GetEpoch() (int64, bool) {
92113
sh := ss.loadSharedHeader(ss.sharedHeader)
93114
return sh.epoch, sh.inProgress != 0

0 commit comments

Comments
 (0)