Skip to content

Commit e9b73f1

Browse files
otroanclaude
andauthored
adapter/statsclient: read ring buffers incrementally (#387)
* adapter/statsclient: read ring buffers incrementally A ring-buffer stat could only be read whole. CopyEntryData copies every thread's entire ring into a fresh allocation, so the cost of a read is the size of the ring rather than the number of entries produced into it - which is the wrong way round. A ring is sized for burst headroom, so making it big enough to survive a stall makes it too expensive to poll: an 8192-entry ring of 128-byte records is 1 MiB copied and allocated per thread per read, and at the 10 ms cadence a fast producer needs, on eight workers, that is 800 MiB/s of copying and garbage to deliver a few hundred entries. A 16M-entry ring is 2 GiB per thread per read and cannot be polled at all. adapter.RingBufferWindowStat copies only what the producers appended since the previous refresh, into buffers it already owns. On an 8192-entry ring delivering 256 entries: RingBufferStat 483 us, 1 MiB, 5 allocations RingBufferWindowStat 4.1 us, none 118x, and the ratio grows with the ring: ring size no longer appears in the cost of a read. The read cursor is consumer-side state, a field on the RingBufferWindowStat the caller holds rather than anything in the segment, which is mapped read-only. So a window refreshes through UpdateDir like any other prepared entry - the switch in UpdateEntryData already dispatches on the stat's dynamic type. CopyEntryData deliberately never produces one: windowing needs a cursor carried between calls, and only the consumer has anywhere to keep it. Entries are located from the sequence and not from head. The two are congruent - both start at zero and advance together on every commit - but a producer stores head plainly and then publishes the sequence with a release store, so a consumer reading the pair astride a commit sees a head one slot ahead of the sequence that explains it. Positioning off head then delivers the slot a worker is writing and skips the oldest live entry, silently and only under load. The sequence is the only field of the two that carries an ordering guarantee, and it is also the one that publishes the entry bytes. A copy is validated against the producer afterwards. The segment's optimistic lock covers directory changes, not ring data, so a worker is free to overwrite the slots being copied while the copy runs - most easily in the configuration this is for, a large window on a fast producer. Re-reading the sequence after the copy identifies the entries that were overwritten underneath it; they are the oldest of the window, so dropping them from the front leaves exactly the ones that are still whole, and they are counted as lost. Delivering a record that is half one entry and half another while reporting no loss would be worse than losing it, because loss is visible and tearing is not. Lost and Pending are separate. Lost counts entries the producer overwrote before the reader reached them, which are gone; Pending counts entries still in the ring that MaxEntries held back, which the next read delivers. They call for opposite responses - read again now, against the reader is not keeping up - so a single "missed" figure would tell a rate-limited reader it was losing data. PrepareRingBuffer exists because PrepareDir cannot express this: it populates every entry by way of CopyEntryData, so preparing a ring copies it once even if every later read is windowed, and that copy repeats on every epoch change. It is reached through adapter.RingBufferAPI rather than StatsAPI, because serving a window means carrying that cursor between refreshes and a mock or a v1 segment has nowhere to keep one; callers type-assert for it. The three region bounds checks are now in one helper that both the windowed and the whole-ring path use. They are what stands between a racing header and an out-of-bounds read of the mapped segment, so a second copy of them is a second chance to get one subtly wrong; go vet's unsafe.Pointer warnings for this file drop from three to none as a side effect. Tested against the synthetic v2 segment: first-refresh positioning with and without SkipBacklog, delivering only what is new, unwrapping across the ring's seam, exact loss on a lap, the cap and the drain loop that empties it, re-sync on a sequence rewind, per-thread independence, a head published ahead of its sequence, entries overwritten while the copy runs, and that a steady refresh allocates nothing. The last two are reachable only by racing a real producer, so an unexported hook between the copy and its validation stands in for the worker; it is nil in production and costs one nil check per thread per refresh. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * adapter/statsclient: derive the ring metadata stride VPP pads vlib_stats_ring_metadata_t to CLIB_CACHE_LINE_BYTES, and src/cmake/cpu.cmake sets that to 128 on aarch64. The hard-coded 64 read thread 1 and up out of thread 0's padding, so on those builds a window picked its slots from a head and sequence that were not the producer's. The stride is not in the ring header, but a schema-bearing ring states it indirectly: VPP puts the schema immediately after the metadata array and records that offset in every thread's metadata, thread 0's included, which sits at the start of the array whatever the stride is. So the array's size follows from thread 0 alone, and the stride from that. Without a schema there is nothing to derive it from and 64 is assumed. The fake ring took its layout from the same constant, so no test could have caught this; it now takes a stride, and the case runs at both. Also from review: bound each region against the room left in the segment instead of forming its end address, which wrapped on an absurd header and compared as if it fit; log the zero-geometry rejection its neighbours already log; stop aliasing the entry name into ringBufferSchema; and say in the docs what MaxEntries=0 allocates, that a mid-stream geometry change with SkipBacklog drops entries without counting them Lost, and that RingBufferAPI is not reachable through core.StatsConnection. * adapter/statsclient: test the stride derivation and the region bounds The stride fix went in with one end-to-end case and the reshaped bounds check with none. Both are now covered, and each case was checked against the code it guards rather than only against the fix. TestRingBufferMetaStrideDerivation drives ringBufferMetaStride directly: 64 and 128 derived, and every input that must fall back rather than guess - no schema, a schema at or inside the metadata array, an array size indivisible by the thread count, a stride that is neither 64 nor 128, and an array starting past the segment. Disabling the derivation fails the 128 cases; dropping the schema_size guard fails the fallback case. TestRingBufferRejectsOverflowingGeometry covers what the old bounds check could not see. 4 threads of 2^31 entries at 2^31 bytes multiplies to exactly 2^64, so an end address formed from it wraps onto the ring's own base and compares as though it fit; against the previous form the refresh accepts the geometry and dies in makeslice. The single-field cases are plain out-of-range offsets, which never wrapped. TestRingBufferWindowWithoutSchema covers a schemaless ring end to end. It is coverage of a configuration, not a guard: with the schema fields zeroed the offset check rejects them anyway. --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent dcc9074 commit e9b73f1

4 files changed

Lines changed: 1230 additions & 62 deletions

File tree

‎adapter/stats_api.go‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,104 @@ type RingBufferStat struct {
188188
Data [][]byte // per-thread raw ring data
189189
}
190190

191+
// RingBufferAPI is implemented by adapters that can read a ring-buffer stat
192+
// incrementally, and is separate from StatsAPI because not every adapter can:
193+
// serving a window means carrying a read cursor between refreshes. That cursor
194+
// is consumer-side state - the segment itself is mapped read-only - and a mock
195+
// or a v1 segment has nowhere to keep one. Callers type-assert for it.
196+
//
197+
// core.StatsConnection holds its StatsAPI unexported and offers no accessor, so
198+
// this is reached through a *statsclient.StatsClient the caller owns.
199+
type RingBufferAPI interface {
200+
// PrepareRingBuffer resolves one ring-buffer stat by name and returns a
201+
// StatDir holding an incremental reader for it, to be refreshed with
202+
// UpdateDir. maxEntries bounds entries delivered per thread per refresh, zero
203+
// meaning the ring size; skipBacklog starts at the producer's head rather
204+
// than at the oldest entry the ring still holds.
205+
PrepareRingBuffer(name string, maxEntries uint32, skipBacklog bool) (*StatDir, error)
206+
}
207+
208+
// RingBufferWindow is the run of entries one producer thread appended since a
209+
// consumer last read it.
210+
type RingBufferWindow struct {
211+
// Entries holds Count entries of RingBufferConfig.EntrySize bytes each,
212+
// oldest first and already unwrapped, so a consumer indexes it without
213+
// knowing where the ring's seam fell.
214+
//
215+
// It aliases a buffer the stat owns and reuses, so it is only valid until
216+
// the next refresh. Copy anything that must outlive that.
217+
//
218+
// The slice always starts at the buffer's origin and is capped to the entries
219+
// this refresh delivered, so cap(Entries) is the room a refresh has to fill
220+
// and there is no second buffer field to keep in step with it.
221+
Entries []byte
222+
Count uint32
223+
224+
// FirstSeq is the producer sequence of Entries[0], and NextSeq the sequence
225+
// the following read will start from. Both are absolute counts of entries
226+
// this thread has ever written, so they stay meaningful across wraps.
227+
FirstSeq uint64
228+
NextSeq uint64
229+
230+
// Lost counts entries the producer overwrote before this read reached them:
231+
// data that is gone. Pending counts entries still in the ring that this read
232+
// did not return because MaxEntries capped it: data that the next read will
233+
// deliver.
234+
//
235+
// They are separate because they call for opposite responses. Pending means
236+
// read again immediately; Lost means the reader is not keeping up and the
237+
// gap is unrecoverable. A single "missed" figure would conflate a reader
238+
// that is behind with one that is merely rate-limited.
239+
Lost uint64
240+
Pending uint64
241+
}
242+
243+
// RingBufferWindowStat reads a ring buffer incrementally: every refresh copies
244+
// only what the producers appended since the previous one, into buffers the stat
245+
// already owns.
246+
//
247+
// This is the difference between a cost proportional to entries produced and one
248+
// proportional to ring size. RingBufferStat copies the whole ring, for every
249+
// thread, into a fresh allocation on every read - so a ring sized for burst
250+
// headroom rather than for poll latency becomes unreadable long before it
251+
// becomes useful. A 16M-entry ring of 128-byte records is 2 GiB per thread per
252+
// read as a RingBufferStat, and the entries actually produced as this.
253+
//
254+
// Put one in a prepared StatDir entry's Data and refresh it with
255+
// StatsClient.UpdateDir, or let StatsClient.PrepareRingBuffer build both.
256+
// CopyEntryData never produces one: windowing needs a read cursor, and only the
257+
// consumer has it.
258+
//
259+
// The zero value is valid and self-initialising. The first refresh reads the
260+
// geometry, allocates the per-thread buffers, and positions the cursor - at the
261+
// oldest entry the ring still holds, or at the producer's head if SkipBacklog is
262+
// set - and returns no entries. SkipBacklog only decides where that first
263+
// refresh starts and is ignored afterwards; MaxEntries is honoured on every
264+
// refresh.
265+
type RingBufferWindowStat struct {
266+
// MaxEntries bounds how many entries one refresh delivers per thread, and so
267+
// bounds both the buffer this stat allocates and the work one refresh does.
268+
// Zero means the ring size, which is the largest window that can ever be
269+
// available. A consumer draining a fast producer wants this small enough to
270+
// bound a single read and to loop while Pending is non-zero.
271+
//
272+
// It is read on every refresh, so raising or lowering it between refreshes
273+
// takes effect on the next one; the buffers grow to match and are not shrunk.
274+
MaxEntries uint32
275+
276+
// SkipBacklog starts the first read at the producer's head rather than at the
277+
// oldest entry still in the ring, so a consumer that wants only what happens
278+
// from now on does not first have to read and discard a ring of history.
279+
SkipBacklog bool
280+
281+
Config RingBufferConfig
282+
Threads []RingBufferThreadMeta
283+
Schema []byte
284+
285+
// Windows holds one window per producer thread, in thread order.
286+
Windows []RingBufferWindow
287+
}
288+
191289
func (ScalarStat) isStat() {}
192290
func (ErrorStat) isStat() {}
193291
func (SimpleCounterStat) isStat() {}
@@ -198,6 +296,9 @@ func (GaugeStat) isStat() {}
198296
func (HistogramLog2Stat) isStat() {}
199297
func (RingBufferStat) isStat() {}
200298

299+
// Pointer receiver: refreshed in place, so a value must not satisfy Stat.
300+
func (*RingBufferWindowStat) isStat() {}
301+
201302
func (s ScalarStat) IsZero() bool {
202303
return s == 0
203304
}
@@ -352,6 +453,25 @@ func (s RingBufferStat) Type() StatType {
352453
return RingBuffer
353454
}
354455

456+
func (s *RingBufferWindowStat) IsZero() bool {
457+
return s.Config.NThreads == 0 || s.Config.EntrySize == 0
458+
}
459+
460+
func (s *RingBufferWindowStat) Type() StatType {
461+
return RingBuffer
462+
}
463+
464+
func (s *RingBufferWindowStat) String() string {
465+
var b strings.Builder
466+
fmt.Fprintf(&b, "\n config: entry_size=%d, ring_size=%d, threads=%d, schema_version=%d, schema_size=%d",
467+
s.Config.EntrySize, s.Config.RingSize, s.Config.NThreads, s.Config.SchemaVersion, s.Config.SchemaSize)
468+
for i, w := range s.Windows {
469+
fmt.Fprintf(&b, "\n thread[%d]: entries=%d first_seq=%d next_seq=%d lost=%d pending=%d",
470+
i, w.Count, w.FirstSeq, w.NextSeq, w.Lost, w.Pending)
471+
}
472+
return b.String()
473+
}
474+
355475
func (s RingBufferStat) String() string {
356476
var b strings.Builder
357477
fmt.Fprintf(&b, "\n config: entry_size=%d, ring_size=%d, threads=%d, schema_version=%d, schema_size=%d",

‎adapter/statsclient/statsclient.go‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -769,3 +769,82 @@ func symlinkItem(full adapter.Stat, item uint32, dst *adapter.Stat) bool {
769769
}
770770
return false
771771
}
772+
773+
var _ adapter.RingBufferAPI = (*StatsClient)(nil)
774+
775+
// PrepareRingBuffer resolves one ring-buffer stat by name and returns a StatDir
776+
// holding an incremental reader for it, to be refreshed with UpdateDir.
777+
//
778+
// It exists because PrepareDir cannot express this: PrepareDir populates every
779+
// entry it prepares by way of CopyEntryData, which for a ring buffer copies the
780+
// whole ring. On a ring sized for burst headroom that one copy at prepare time is
781+
// the largest allocation the process makes, and it is repeated on every epoch
782+
// change. Here nothing is read but the directory entry itself; the first
783+
// UpdateDir reads the geometry and sizes the reader's buffers from maxEntries.
784+
//
785+
// maxEntries bounds entries per thread per refresh, and so bounds both the
786+
// buffers allocated and the work one refresh does; zero means the ring size. A
787+
// consumer draining a fast producer should set it and loop while any window
788+
// reports Pending. skipBacklog starts at the producer's head rather than at the
789+
// oldest entry still in the ring.
790+
//
791+
// Passing zero therefore makes the first refresh allocate the whole ring per
792+
// thread - RingSize*EntrySize, 1 MiB on an 8192x128 ring - once. The per-read
793+
// saving stands either way, but a bound is what keeps the allocation off the
794+
// ring's size too.
795+
//
796+
// name is matched exactly, not as a pattern: this returns one entry or an error,
797+
// because a caller reading a specific producer's records has nothing sensible to
798+
// do with a second ring that happened to match.
799+
func (sc *StatsClient) PrepareRingBuffer(name string, maxEntries uint32, skipBacklog bool) (*adapter.StatDir, error) {
800+
sc.accessLock.RLock()
801+
defer sc.accessLock.RUnlock()
802+
803+
if !sc.isConnected() {
804+
return nil, adapter.ErrStatsDisconnected
805+
}
806+
807+
accessEpoch := sc.accessStart()
808+
if accessEpoch == 0 {
809+
return nil, adapter.ErrStatsAccessFailed
810+
}
811+
812+
vector := sc.GetDirectoryVector()
813+
if vector == nil {
814+
return nil, fmt.Errorf("failed to prepare ring buffer: directory vector is nil")
815+
}
816+
817+
want := []byte(name)
818+
var entry *adapter.StatEntry
819+
vecLen := *(*uint32)(vectorLen(vector))
820+
for i := uint32(0); i < vecLen; i++ {
821+
// Compared in place: GetStatDirOnIndex clones every name it walks past,
822+
// and on a real directory that is thousands of allocations to find one
823+
// entry.
824+
_, dirType, ok := sc.StatDirOnIndexMatches(vector, i, want)
825+
if !ok {
826+
continue
827+
}
828+
if dirType != adapter.RingBuffer {
829+
return nil, fmt.Errorf("stat %q is %v, not a ring buffer", name, dirType)
830+
}
831+
entry = &adapter.StatEntry{
832+
StatIdentifier: adapter.StatIdentifier{Index: i, Name: want},
833+
Type: adapter.RingBuffer,
834+
Data: &adapter.RingBufferWindowStat{
835+
MaxEntries: maxEntries,
836+
SkipBacklog: skipBacklog,
837+
},
838+
}
839+
break
840+
}
841+
if entry == nil {
842+
return nil, fmt.Errorf("ring buffer stat %q not found", name)
843+
}
844+
845+
if !sc.accessEnd(accessEpoch) {
846+
return nil, adapter.ErrStatsDataBusy
847+
}
848+
849+
return &adapter.StatDir{Epoch: accessEpoch, Entries: []adapter.StatEntry{*entry}}, nil
850+
}

0 commit comments

Comments
 (0)