Skip to content

fix: stop SpscRingBuffer.Count reporting a count the buffer never held [patch] - #92

Merged
matt-edmondson merged 1 commit into
mainfrom
claude/containers-81-spsc-count-snapshot
Sep 29, 2026
Merged

matt-edmondson merged 1 commit into
mainfrom
claude/containers-81-spsc-count-snapshot

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #81

What was wrong

SpscRingBuffer<T>.Count read tail and then head, and returned (tail - head) & mask. Suppose a diagnostics thread, which is neither the producer nor the consumer, reads Count. Between its two reads, the producer and consumer can both move on, so head passes the stale tail. The negative difference then wraps to a value near Capacity. The result is a count the buffer never held, which breaks metering and back-pressure heuristics built on it.

Change

Count now reads head, then tail, then head again. It retries until head stays the same across both reads. The tail it uses was therefore observed while head held that value, so the difference is a count the buffer really had. Masking already bounds the result to [0, Capacity], so no extra clamp is needed. The retry only affects the thread reading Count: TryEnqueue and TryDequeue are unchanged and remain wait-free.

Tests

Count_ReadFromThirdThread_NeverExceedsTrueCount is the stress test from the issue. The producer only enqueues into an empty buffer, so the true count is always 0 or 1, and a third thread polls Count for 2 seconds.

  • Fix reverted: the test fails, because the observer sees counts far above 1.
  • Fix in place: it passed in 4 separate runs.
  • Full suite: passes (dotnet test: 419 passed, 0 failed), and Containers.csproj builds with 0 warnings.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EdrcmpMTNHSnACRgnNGs8v


Generated by Claude Code

…d [patch]

Count read tail and then head. A thread that was neither producer nor
consumer could see the consumer move head past the stale tail between the two
reads, and the masked difference then wrapped to a value near Capacity on an
idle buffer.

Count now reads head, then tail, then head again, and retries until head did
not move, so the tail it uses was observed while head held that value.

Fixes #81

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EdrcmpMTNHSnACRgnNGs8v
@sonarqubecloud

Copy link
Copy Markdown

@matt-edmondson
matt-edmondson merged commit 3fb346c into main Sep 29, 2026
12 checks passed
@matt-edmondson
matt-edmondson deleted the claude/containers-81-spsc-count-snapshot branch September 29, 2026 01:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SpscRingBuffer.Count read from a third thread can report a nearly full buffer (up to Capacity) when it is actually empty

2 participants