CodeSampleX

샘플

golang.org/x/sync v0.22.0: Handle semaphore weighted acquisition, FIFO anti-starvation head-of-line blocking, TryAcquire waiter suppression, canceled waiter unblocking, and excess release panics

검증된 샘플 — golang golang.org/x/sync v0.22.0: Handle semaphore weighted acquisition, FIFO anti-starvation head-of-line blocking, TryAcquire waiter suppression…

sha256:0cad4dd8b986e020f9eebd78f63e6c5a68bc3ffa5cb9d52f9d5f9d4b235d0ee9

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 go linux x64 go go gomod

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-17
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18

케이스

HOW
목표
Handle semaphore weighted acquisition, FIFO anti-starvation head-of-line blocking, TryAcquire waiter suppression, canceled waiter unblocking, and excess release panics
패키지
심벌
  • semaphore.NewWeighted
  • Weighted.Acquire
  • Weighted.TryAcquire
  • Weighted.Release
환경
go
생성일
2026-08-17T15:40:26Z

컨트랙트

  1. assert semaphore.Weighted enforces strict FIFO ordering so smaller Acquire requests remain blocked behind a larger head waiter even when sufficient unallocated tokens exist
  2. assert TryAcquire returns false whenever waiters are queued in the wait list even if unallocated capacity is available
  3. assert canceling a blocked head waiter context immediately unblocks subsequent queued waiters without requiring an additional Release
  4. assert calling Acquire with an already-canceled context returns context.Canceled immediately without modifying token capacity
  5. assert calling Release with a weight greater than currently held tokens panics immediately

파일

  • NOTES.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Notes on golang.org/x/sync/semaphore Behaviour

## search_known_solution Result
- **Result**: HIT with sample `sha256:470295d48f5f7621a26432793d4dd80d928dcb80ee6db8a57a43a16edbc4a5c6` (Goal: "Handle errgroup derived context cancellation on successful Wait, first-completion error selection, cooperative sibling cancellation, and TryGo dropping semantics") and sample `sha256:dd194e3340ff4f53b7309dbf639491071c00c853a8c56cc62ab1c74bc5f9f853` (Goal: "Handle singleflight duplicate suppression without persistent caching, shared flag propagation to leader and followers, in-flight Forget bypass, and panic propagation").
- **Why this sample is different**: The existing samples in the repository focus on `errgroup` and `singleflight`. This sample targets `golang.org/x/sync/semaphore` and proves the weighted semaphore implementation:
  1. `Acquire` enforces strict FIFO ordering: when a large request is at the head of the wait queue, smaller subsequent requests remain blocked even when current unallocated tokens could satisfy the small request.
  2. `TryAcquire` returns `false` whenever any waiters are queued in the wait list, preventing non-blocking callers from jumping ahead of blocked waiters.
  3. Canceling a blocked head waiter context removes it from the queue and triggers `notifyWaiters()`, immediately allowing subsequent queued waiters to acquire tokens without requiring an explicit `Release()` call.
  4. `Acquire` with an already-canceled context returns `context.Canceled` immediately without modifying token capacity or queue state.
  5. `Release` panics with `"semaphore: released more than held"` when releasing more tokens than currently held.

## Exact Release Pinned
- `golang.org/x/sync@v0.22.0` in `go.mod` and `go.sum`.

## What a Model Would Have Written Instead
A naive model assumes that a weighted semaphore functions like a raw token pool where any incoming acquire request (or `TryAcquire`) is immediately granted as long as unallocated token capacity is greater than or equal to the requested weight, allowing small requests to jump ahead of earlier queued larger requests.

## How the Wrong Version Fails
Assumptions of out-of-order token allocation lead to unexpected goroutine stalling in production, where small high-throughput background tasks block behind a pending large batch acquisition despite apparent free capacity, and callers assuming `Release` silently caps or ignores excess tokens fail with a runtime panic.
contract_test.go
package contract_test

import (
	"context"
	"errors"
	"strings"
	"testing"
	"time"

	"golang.org/x/sync/semaphore"
)

// TestHeadOfLineBlockingPreventsStarvation proves that semaphore.Weighted enforces strict
// FIFO ordering: when a large Acquire request is queued at the head of the wait list,
// subsequent smaller Acquire requests remain blocked even when sufficient unallocated tokens
// exist to satisfy the smaller requests.
func TestHeadOfLineBlockingPreventsStarvation(t *testing.T) {
	sem := semaphore.NewWeighted(10)
	ctx := context.Background()

	// Step 1: Acquire 8 tokens. 2 tokens remain available.
	if err := sem.Acquire(ctx, 8); err != nil {
		t.Fatalf("failed to acquire initial tokens: %v", err)
	}

	// Step 2: Goroutine A requests 5 tokens. Since 2 < 5, Goroutine A blocks at head of queue.
	headAcquired := make(chan struct{})
	go func() {
		if err := sem.Acquire(ctx, 5); err != nil {
			t.Errorf("head waiter Acquire error: %v", err)
		}
		close(headAcquired)
	}()

	time.Sleep(20 * time.Millisecond)

	// Step 3: Goroutine B requests 1 token. Although 2 tokens are free (2 >= 1),
	// Goroutine B must block behind Goroutine A to prevent starvation of large requests.
	tailAcquired := make(chan struct{})
	go func() {
		if err := sem.Acquire(ctx, 1); err != nil {
			t.Errorf("tail waiter Acquire error: %v", err)
		}
		close(tailAcquired)
	}()

	time.Sleep(20 * time.Millisecond)

	// Verify Goroutine B is blocked despite 2 unallocated tokens
	select {
	case <-tailAcquired:
		t.Fatal("tail waiter acquired 1 token ahead of head waiter, violating FIFO anti-starvation")
	default:
	}

	// Step 4: Release 2 tokens (now 4 unallocated). Head waiter needs 5 (4 < 5), so it remains blocked.
	sem.Release(2)
	time.Sleep(20 * time.Millisecond)

	select {
	case <-headAcquired:
		t.Fatal("head waiter acquired tokens before sufficient capacity was released")
	case <-tailAcquired:
		t.Fatal("tail waiter acquired tokens while head waiter was still blocked")
	default:
	}

	// Step 5: Release 2 more tokens (now 6 unallocated). Head waiter (needs 5) unblocks first,
	// leaving 1 token (6 - 5 = 1), which then allows tail waiter (needs 1) to unblock.
	sem.Release(2)

	select {
	case <-headAcquired:
	case <-time.After(1 * time.Second):
		t.Fatal("timed out waiting for head waiter to acquire tokens")
	}

	select {
	case <-tailAcquired:
	case <-time.After(1 * time.Second):
		t.Fatal("timed out waiting for tail waiter to acquire tokens")
	}

	// Clean up: 4 held by main + 5 held by A + 1 held by B = 10 total
	sem.Release(6) // Release A (5) and B (1)
	sem.Release(4) // Release main (4)
}

// TestTryAcquireBlockedWhenWaitersQueued proves that TryAcquire returns false whenever
// any waiters are queued in the wait list, even if the semaphore has enough unallocated
// capacity to satisfy the TryAcquire call.
func TestTryAcquireBlockedWhenWaitersQueued(t *testing.T) {
	sem := semaphore.NewWeighted(10)
	ctx := context.Background()

	// Acquire 7 tokens (3 tokens remaining)
	if err := sem.Acquire(ctx, 7); err != nil {
		t.Fatalf("unexpected Acquire error: %v", err)
	}

	// Waiter queues for 5 tokens (3 < 5 -> blocked)
	waiterDone := make(chan struct{})
	go func() {
		if err := sem.Acquire(ctx, 5); err != nil {
			t.Errorf("waiter Acquire error: %v", err)
		}
		close(waiterDone)
	}()

	time.Sleep(20 * time.Millisecond)

	// 3 tokens are unallocated, but TryAcquire(1) must return false because a waiter is queued
	if sem.TryAcquire(1) {
		t.Fatal("expected TryAcquire(1) to return false when waiters are queued, but it succeeded")
	}

	// Release 7 tokens to unblock the waiter (takes 5 tokens)
	sem.Release(7)

	select {
	case <-waiterDone:
	case <-time.After(1 * time.Second):
		t.Fatal("waiter did not unblock after tokens were released")
	}

	// After the queue is drained, TryAcquire can succeed with remaining capacity (10 - 5 = 5 tokens)
	if !sem.TryAcquire(5) {
		t.Fatal("expected TryAcquire(5) to succeed once waiter queue was drained")
	}

	sem.Release(5) // Release TryAcquire tokens
	sem.Release(5) // Release waiter tokens
}

// TestCanceledHeadWaiterUnblocksSubsequentWaiters proves that canceling a blocked waiter
// at the front of the queue removes it and unblocks the next waiter if available tokens suffice,
// without requiring any external Release call.
func TestCanceledHeadWaiterUnblocksSubsequentWaiters(t *testing.T) {
	sem := semaphore.NewWeighted(6)
	ctx := context.Background()

	// Acquire 4 tokens (2 tokens available)
	if err := sem.Acquire(ctx, 4); err != nil {
		t.Fatalf("unexpected Acquire error: %v", err)
	}

	ctxHead, cancelHead := context.WithCancel(ctx)
	headErrCh := make(chan error, 1)

	// Head waiter requests 4 tokens (blocked because 2 < 4)
	go func() {
		headErrCh <- sem.Acquire(ctxHead, 4)
	}()

	time.Sleep(20 * time.Millisecond)

	// Next waiter requests 2 tokens (blocked behind head waiter despite 2 available)
	nextAcquired := make(chan struct{})
	go func() {
		if err := sem.Acquire(ctx, 2); err != nil {
			t.Errorf("next waiter Acquire error: %v", err)
		}
		close(nextAcquired)
	}()

	time.Sleep(20 * time.Millisecond)

	// Verify next waiter is blocked behind head waiter
	select {
	case <-nextAcquired:
		t.Fatal("next waiter acquired tokens prematurely")
	default:
	}

	// Cancel the head waiter
	cancelHead()

	err := <-headErrCh
	if !errors.Is(err, context.Canceled) {
		t.Fatalf("expected context.Canceled for head waiter, got: %v", err)
	}

	// Next waiter should be unblocked automatically since 2 tokens are available and head was removed
	select {
	case <-nextAcquired:
	case <-time.After(1 * time.Second):
		t.Fatal("next waiter failed to unblock after head waiter cancellation")
	}

	// Clean up: release tokens held by main (4) and next waiter (2)
	sem.Release(4)
	sem.Release(2)
}

// TestPreCanceledContextFailsImmediately proves that Acquire on an already-canceled
// context returns ctx.Err() immediately and leaves token capacity and waiters untouched.
func TestPreCanceledContextFailsImmediately(t *testing.T) {
	sem := semaphore.NewWeighted(5)
	ctx, cancel := context.WithCancel(context.Background())
	cancel() // cancel beforehand

	err := sem.Acquire(ctx, 3)
	if !errors.Is(err, context.Canceled) {
		t.Fatalf("expected context.Canceled, got: %v", err)
	}

	// All 5 tokens must remain available
	if !sem.TryAcquire(5) {
		t.Fatal("expected full capacity (5) to be available after failed pre-canceled Acquire")
	}
	sem.Release(5)
}

// TestReleaseMoreThanHeldPanics proves that calling Release with a weight greater
// than currently acquired tokens panics with "semaphore: released more than held".
func TestReleaseMoreThanHeldPanics(t *testing.T) {
	sem := semaphore.NewWeighted(5)

	// Acquire 2 tokens
	if !sem.TryAcquire(2) {
		t.Fatal("failed to TryAcquire 2 tokens")
	}

	var panicVal any
	func() {
		defer func() {
			panicVal = recover()
		}()
		sem.Release(3) // Releasing 3 when only 2 are held
	}()

	if panicVal == nil {
		t.Fatal("expected Release(3) to panic when only 2 tokens were held")
	}

	msg, ok := panicVal.(string)
	if !ok || !strings.Contains(msg, "released more than held") {
		t.Fatalf("expected 'released more than held' panic message, got: %v", panicVal)
	}
}
csx.json
{"case":{"believed":"a weighted semaphore grants available capacity to incoming requests whenever unallocated tokens suffice, allowing small requests to bypass earlier larger queued waiters.","caseId":"case:sha256:0b4b6249bee40392df5cededca6b354df20a7fc616d93bc4e4c0300fe7ec5372","contract":["assert semaphore.Weighted enforces strict FIFO ordering so smaller Acquire requests remain blocked behind a larger head waiter even when sufficient unallocated tokens exist","assert TryAcquire returns false whenever waiters are queued in the wait list even if unallocated capacity is available","assert canceling a blocked head waiter context immediately unblocks subsequent queued waiters without requiring an additional Release","assert calling Acquire with an already-canceled context returns context.Canceled immediately without modifying token capacity","assert calling Release with a weight greater than currently held tokens panics immediately"],"goal":"Handle semaphore weighted acquisition, FIFO anti-starvation head-of-line blocking, TryAcquire waiter suppression, canceled waiter unblocking, and excess release panics","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@0.22.0"],"schemaVersion":1,"symbols":["semaphore.NewWeighted","Weighted.Acquire","Weighted.TryAcquire","Weighted.Release"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"gomod","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/sync@0.22.0"],"schemaVersion":1,"symbols":["semaphore.NewWeighted","Weighted.Acquire","Weighted.TryAcquire","Weighted.Release"],"verifierAdapter":"golang@1"}
go.mod
module codesamplex.dev/sample/semaphoreapi

go 1.26.5

require golang.org/x/sync v0.22.0
go.sum
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=

오리진 시더

csx-seed