CodeSampleX

示例

golang.org/x/sync v0.22.0: Handle singleflight duplicate suppression without persistent caching, shared flag propagation to leader and followers, in-flight Forget bypass, and panic propagation

已验证示例 — golang golang.org/x/sync v0.22.0: Handle singleflight duplicate suppression without persistent caching, shared flag propagation to leader and…

sha256:dd194e3340ff4f53b7309dbf639491071c00c853a8c56cc62ab1c74bc5f9f853

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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-16
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 singleflight duplicate suppression without persistent caching, shared flag propagation to leader and followers, in-flight Forget bypass, and panic propagation
包
符号
  • singleflight.Group
  • Group.Do
  • Group.DoChan
  • Group.Forget
环境
go
创建时间
2026-08-16T12:24:20Z

契约

  1. assert singleflight.Group executes sequential calls repeatedly without caching and does not require Forget to invalidate
  2. assert Do returns shared=true to both the leader goroutine and all joining duplicate callers
  3. assert calling Forget during an in-flight execution immediately allows new callers to spawn concurrent work without canceling the original execution
  4. assert a panic in the executed function is captured and re-panics with a panicError across all concurrent waiting callers
  5. assert concurrent callers receive references to the exact same pointer value in memory without deep copy or mutation isolation

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Notes on golang.org/x/sync/singleflight Traps

## 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:fee4a8483e88e2109447b1f697e91dfbe81d19cfec3d5762d0d36b84547e9714` (Goal: "Run concurrent work with a bound and the first error with errgroup").
- **Why this sample is different**: The existing samples in the repository exclusively cover `errgroup`. This sample targets `golang.org/x/sync/singleflight` and proves five distinct traps:
  1. `singleflight.Group` provides transient in-flight deduplication rather than persistent caching; keys are removed immediately when the function returns, so sequential calls always re-execute without `Forget()`.
  2. `Do` returns `shared=true` to all callers (the leader that executed the function as well as all joining followers) whenever duplicate requests overlap.
  3. Calling `Forget(key)` during an active execution removes key suppression immediately, allowing new callers to spawn concurrent executions while the first execution still completes for earlier callers.
  4. Panics inside the executed function are intercepted and re-panicked in all waiting concurrent callers with an error value that preserves the stack trace and unwraps to the original panic cause.
  5. Pointers and reference types returned by `Do` are shared directly in memory without cloning, causing concurrent mutation races if consumers assume exclusive ownership.

## What a Model Would Have Written Instead
A naive model expects `singleflight.Group` to retain computed results like a cache until `Forget` is explicitly called, expects `shared` to be `false` for the leader goroutine that actually ran the task, and expects `Forget` to cancel or reset in-flight work.

## How the Wrong Version Fails
Fails silently with unexpected backend query load when assuming keys are cached across sequential calls, and causes data corruption or race conditions when concurrent callers mutate shared returned pointers under the assumption of unique ownership.
csx.json
{"case":{"believed":"singleflight.Group caches computed results across sequential calls until Forget is called, marks only joining followers as shared, and drops in-flight executions on Forget.","caseId":"case:sha256:15da71c38ed26fb3323ad5c02b66df446c48765362a5eefd2da88ef2eb7906a8","contract":["assert singleflight.Group executes sequential calls repeatedly without caching and does not require Forget to invalidate","assert Do returns shared=true to both the leader goroutine and all joining duplicate callers","assert calling Forget during an in-flight execution immediately allows new callers to spawn concurrent work without canceling the original execution","assert a panic in the executed function is captured and re-panics with a panicError across all concurrent waiting callers","assert concurrent callers receive references to the exact same pointer value in memory without deep copy or mutation isolation"],"goal":"Handle singleflight duplicate suppression without persistent caching, shared flag propagation to leader and followers, in-flight Forget bypass, and panic propagation","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@0.22.0"],"schemaVersion":1,"symbols":["singleflight.Group","Group.Do","Group.DoChan","Group.Forget"]},"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":["singleflight.Group","Group.Do","Group.DoChan","Group.Forget"],"verifierAdapter":"golang@1"}
go.mod
module codesamplex.dev/sample/singleflightapi

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=
singleflight_test.go
package singleflight_test

import (
	"errors"
	"sync"
	"sync/atomic"
	"testing"
	"time"

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

type resource struct {
	ID    string
	Count int
}

// TestSequentialCallsNotCached proves that singleflight.Group only suppresses
// concurrent executions and immediately deletes the key on completion.
// Subsequent sequential calls execute fn again without requiring Forget().
func TestSequentialCallsNotCached(t *testing.T) {
	var g singleflight.Group
	var execCount int32

	fn := func() (any, error) {
		atomic.AddInt32(&execCount, 1)
		return "data", nil
	}

	// First call executes fn
	v1, err, shared1 := g.Do("key1", fn)
	if err != nil || v1 != "data" {
		t.Fatalf("call 1 failed: v=%v, err=%v", v1, err)
	}
	if shared1 {
		t.Fatalf("expected shared=false on isolated call, got true")
	}
	if got := atomic.LoadInt32(&execCount); got != 1 {
		t.Fatalf("expected execCount=1, got %d", got)
	}

	// Second call without Forget() also executes fn because key was already removed
	v2, err, shared2 := g.Do("key1", fn)
	if err != nil || v2 != "data" {
		t.Fatalf("call 2 failed: v=%v, err=%v", v2, err)
	}
	if shared2 {
		t.Fatalf("expected shared=false on second sequential call, got true")
	}
	if got := atomic.LoadInt32(&execCount); got != 2 {
		t.Fatalf("expected execCount=2 for sequential call, got %d", got)
	}
}

// TestSharedReturnedToLeaderAndFollowers proves that when concurrent callers join,
// Do returns shared=true to ALL callers including the leader that executed fn.
func TestSharedReturnedToLeaderAndFollowers(t *testing.T) {
	var g singleflight.Group
	var execCount int32

	fnStarted := make(chan struct{})
	unblockFn := make(chan struct{})

	fn := func() (any, error) {
		atomic.AddInt32(&execCount, 1)
		close(fnStarted)
		<-unblockFn
		return "shared-val", nil
	}

	var leaderShared bool
	var leaderErr error
	var leaderVal any

	var followerShared bool
	var followerErr error
	var followerVal any

	var wg sync.WaitGroup
	wg.Add(2)

	// Leader
	go func() {
		defer wg.Done()
		leaderVal, leaderErr, leaderShared = g.Do("concurrent-key", fn)
	}()

	// Wait until leader starts executing fn
	<-fnStarted

	// Follower
	go func() {
		defer wg.Done()
		followerVal, followerErr, followerShared = g.Do("concurrent-key", fn)
	}()

	// Give follower time to enter g.Do and register as duplicate
	time.Sleep(50 * time.Millisecond)
	close(unblockFn)

	wg.Wait()

	if leaderErr != nil || followerErr != nil {
		t.Fatalf("unexpected errors: leaderErr=%v, followerErr=%v", leaderErr, followerErr)
	}
	if leaderVal != "shared-val" || followerVal != "shared-val" {
		t.Fatalf("unexpected values: leaderVal=%v, followerVal=%v", leaderVal, followerVal)
	}

	// Trap: both leader and follower receive shared=true
	if !leaderShared {
		t.Fatalf("expected leader to receive shared=true when duplicate joined, got false")
	}
	if !followerShared {
		t.Fatalf("expected follower to receive shared=true, got false")
	}
	if got := atomic.LoadInt32(&execCount); got != 1 {
		t.Fatalf("expected exactly 1 execution, got %d", got)
	}
}

// TestInFlightForgetAllowsConcurrentExecution proves that calling Forget(key) while
// fn is running removes key suppression immediately, allowing new callers to start
// a second execution concurrently while the first execution still completes for original callers.
func TestInFlightForgetAllowsConcurrentExecution(t *testing.T) {
	var g singleflight.Group
	var execCount int32

	firstStarted := make(chan struct{})
	unblockFirst := make(chan struct{})

	firstFn := func() (any, error) {
		atomic.AddInt32(&execCount, 1)
		close(firstStarted)
		<-unblockFirst
		return "first-result", nil
	}

	var firstVal any
	var firstErr error
	var wg sync.WaitGroup
	wg.Add(1)

	go func() {
		defer wg.Done()
		firstVal, firstErr, _ = g.Do("forget-key", firstFn)
	}()

	<-firstStarted

	// Call Forget while first execution is in flight
	g.Forget("forget-key")

	// Subsequent caller now starts a NEW execution instead of joining the in-flight one
	secondFn := func() (any, error) {
		atomic.AddInt32(&execCount, 1)
		return "second-result", nil
	}

	secondVal, secondErr, secondShared := g.Do("forget-key", secondFn)
	if secondErr != nil || secondVal != "second-result" {
		t.Fatalf("second call failed: v=%v, err=%v", secondVal, secondErr)
	}
	if secondShared {
		t.Fatalf("expected second call to not be shared, got shared=true")
	}

	// Unblock and wait for first caller
	close(unblockFirst)
	wg.Wait()

	if firstErr != nil || firstVal != "first-result" {
		t.Fatalf("first call failed: v=%v, err=%v", firstVal, firstErr)
	}
	if got := atomic.LoadInt32(&execCount); got != 2 {
		t.Fatalf("expected 2 executions due to in-flight Forget, got %d", got)
	}
}

// TestPanicPropagatedToAllCallers proves that if fn panics, Do intercepts the panic
// and re-panics in all waiting concurrent callers with an error that implements Unwrap().
func TestPanicPropagatedToAllCallers(t *testing.T) {
	var g singleflight.Group

	fnStarted := make(chan struct{})
	unblockFn := make(chan struct{})
	customErr := errors.New("underlying failure")

	fn := func() (any, error) {
		close(fnStarted)
		<-unblockFn
		panic(customErr)
	}

	var leaderPanicked, followerPanicked bool
	var leaderPanicVal, followerPanicVal any

	var wg sync.WaitGroup
	wg.Add(2)

	// Leader
	go func() {
		defer wg.Done()
		defer func() {
			if r := recover(); r != nil {
				leaderPanicked = true
				leaderPanicVal = r
			}
		}()
		g.Do("panic-key", fn)
	}()

	<-fnStarted

	// Follower
	go func() {
		defer wg.Done()
		defer func() {
			if r := recover(); r != nil {
				followerPanicked = true
				followerPanicVal = r
			}
		}()
		g.Do("panic-key", fn)
	}()

	time.Sleep(50 * time.Millisecond)
	close(unblockFn)
	wg.Wait()

	if !leaderPanicked {
		t.Fatal("expected leader to panic")
	}
	if !followerPanicked {
		t.Fatal("expected follower to panic when leader panicked")
	}

	// Panic values wrap the original error and can be unwrapped
	lErr, ok := leaderPanicVal.(interface{ Unwrap() error })
	if !ok || !errors.Is(lErr.Unwrap(), customErr) {
		t.Fatalf("expected leader panic value to unwrap to customErr, got %v", leaderPanicVal)
	}
	fErr, ok := followerPanicVal.(interface{ Unwrap() error })
	if !ok || !errors.Is(fErr.Unwrap(), customErr) {
		t.Fatalf("expected follower panic value to unwrap to customErr, got %v", followerPanicVal)
	}
}

// TestReturnedPointerSharedWithoutCopying proves that concurrent callers receive the exact
// same pointer value in memory without cloning, meaning mutations by one caller affect all.
func TestReturnedPointerSharedWithoutCopying(t *testing.T) {
	var g singleflight.Group

	fnStarted := make(chan struct{})
	unblockFn := make(chan struct{})

	fn := func() (any, error) {
		close(fnStarted)
		<-unblockFn
		return &resource{ID: "res-1", Count: 10}, nil
	}

	var res1, res2 *resource
	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		defer wg.Done()
		v, _, _ := g.Do("pointer-key", fn)
		res1 = v.(*resource)
	}()

	<-fnStarted

	go func() {
		defer wg.Done()
		v, _, _ := g.Do("pointer-key", fn)
		res2 = v.(*resource)
	}()

	time.Sleep(50 * time.Millisecond)
	close(unblockFn)
	wg.Wait()

	if res1 == nil || res2 == nil {
		t.Fatal("expected non-nil resources")
	}
	if res1 != res2 {
		t.Fatalf("expected identical pointer addresses, got %p vs %p", res1, res2)
	}

	// Modifying via res1 modifies res2 directly because memory is shared
	res1.Count = 99
	if res2.Count != 99 {
		t.Fatalf("expected res2.Count to reflect mutation (99), got %d", res2.Count)
	}
}

原始种子者

csx-seed