Implement the following plan: Metricstore In-Depth Review: Bugs & Improvements BUG 1:…
- User
Implement the following plan:
Metricstore In-Depth Review: Bugs & Improvements
BUG 1:
isEmpty()deadlock risk infree()(level.go:209,218)Severity: HIGH —
free()holdsl.lock.Lock()(line 184), then callschild.free(t)which acquireschild.lock.Lock(). Thenchild.isEmpty()(line 209) acquireschild.lock.RLock()— re-entrant RLock on a locked RWMutex. Go'ssync.RWMutexis NOT reentrant.child.free()returns withchild.lockunlocked (defer), thenisEmpty()re-locks it — this works. BUT:isEmpty()is called on the child right afterchild.free()returns, andchild.free()already released its lock via defer. Betweenchild.free()returning andisEmpty()being called, another goroutine could add a new metric to the child, making it appear non-empty. This is a TOCTOU race but not a deadlock. However, the real risk is: during thechild.free()call, child's children may have been pruned, and thenisEmpty()re-acquires the lock — this is safe but has a race window.Fix: Check emptiness inside
free()itself, returning a boolean alongside(int, error), so the parent can decide while holding its own lock consistently.BUG 2:
stats()index recalculation after buffer switch (stats.go:40-46)Severity: MEDIUM — When
idx >= cap(b.data), the code doesb = b.next; idx = 0. This hardcodes idx=0, ignoring the actual timestamp position in the next buffer. If there's a gap between buffers (different start times),idx=0is wrong — it reads data from the wrong timestamp. This is the same bug that was already fixed inbuffer.read()(theTestBufferReadIdxAfterSwitchtest covers read, but NOT stats).Fix: After
b = b.next, recalculateidx = int((t - b.start) / b.frequency)(same as was done inread()).BUG 3:
FreeAll()not thread-safe (metricstore.go:756-762)Severity: MEDIUM —
FreeAll()iterates and deletes fromm.root.childrenwithout holdingm.root.lock. Concurrent reads/writes will race. Assistant
Let me read all the files that need modification first.
Assistant
Now I have all the context. Let me apply all the fixes.
Assistant
Let me check the current state of level.go to understand the compilation error.
Assistant
The code looks correct -
freeAndCheckEmptyis defined on*Level. The diagnostic may be a stale LSP issue. Let me verify it compiles, and also now apply the Improvement 2 (configurable checkpoint interval).Assistant
Now let me also update the
free()method to simply delegate tofreeAndCheckEmptyto avoid code duplication, sincefree()is the public-facing method used byMemoryStore.Free().Assistant
Now let me verify it compiles and run the tests.
Assistant
Compiles cleanly. The
isEmpty()warning is expected — it's now unused sincefreeAndCheckEmptyhandles it inline. Let me check ifisEmptyis used anywhere else before removing it.Assistant
Only used in its own definition. Let me remove it.
Assistant
Now run the tests.
Assistant
All tests pass. Let me also check if the config schema validation file needs updating for the new field.
Assistant
All changes compile and tests pass. Here's a summary of what was implemented:
Bug fixes:
-
Bug 1 — TOCTOU race in
free()(level.go): Replaced separatefree()+isEmpty()calls with a singlefreeAndCheckEmpty()method that checks emptiness while still holding the lock.free()now delegates to it. Removed the now-unusedisEmpty()method. -
Bug 2 — Wrong index after buffer switch in
stats()(stats.go:45): Changedidx = 0toidx = int((t - b.start) / b.frequency)to correctly recalculate the position in the next buffer, matching the fix already applied inbuffer.read(). -
Bug 3 —
FreeAll()not thread-safe (metricstore.go:756): Addedm.root.lock.Lock()/ around the map iteration and deletion.
-
- User
What about the other Improvements. Which ones do you recommend
Assistant
Let me read the existing plan and the relevant code to evaluate the remaining improvements.
Assistant
Let me look at the WAL code to properly assess Improvements 1, 4, and 5 (Bug 5 — periodic fsync).
Assistant
Now I have a clear picture. Here's my assessment of the remaining improvements:
Improvement 1 (WAL buffering) — Recommend: YES. Each metric write does a separate
f.Write()syscall (line 307). With thousands of metrics/sec across hundreds of hosts, this is a significant I/O bottleneck. ThewalFileStatestruct already exists and can hold abufio.Writer. The WAL staging goroutine is single-threaded, so no extra synchronization needed. Flush on rotation and on shutdown. Low risk, high impact.Improvement 3 (MemoryCap docs) — Recommend: YES, trivial. The config schema already says "in GB" (line 58 of configSchema.go), but the struct comment in config.go says "bytes". Just fix the comment. One line change.
Improvement 4 (WAL size limit) — This adds significant complexity (tracking file sizes per host, triggering mid-cycle checkpoints, coordinating with the checkpoint goroutine). The checkpoint interval is now configurable (Improvement 2, already done), so users can reduce WAL accumulation by shortening the interval. The ROI isn't there until there's evidence of actual WAL size problems in production.
Assistant
Here's my recommendation on the remaining improvements:
Implement:
- Improvement 1 (WAL buffering) — Each WAL write currently does a raw
f.Write()syscall. With thousands of metrics/sec, this is excessive I/O. Adding abufio.Writerper host WAL file is straightforward (thewalFileStatestruct and single-threaded goroutine make it clean) and gives significant throughput improvement. - Improvement 3 (MemoryCap comment) — Trivial one-line fix. The struct comment says "bytes" but the code compares against GB.
Skip for now:
- Improvement 4 (WAL size limit) — High complexity (size tracking per host, mid-cycle checkpoint triggers, goroutine coordination). The checkpoint interval is now configurable, which is the simpler lever to reduce WAL accumulation.
- Bug 5 (periodic fsync) — CRC validation already handles corrupt trailing records on replay. The WAL is best-effort crash recovery on top of binary snapshots. Adding fsync adds I/O overhead for marginal durability gains.
- Improvement 1 (WAL buffering) — Each WAL write currently does a raw