CodeSampleX

샘플

golang.org/x/sync v0.21.0: singleflight.Group

검증된 샘플 — golang golang.org/x/sync v0.21.0: singleflight.Group. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: singleflight.Group.Do suppresses…

sha256:7c6a5cfdfba88ad3417c14306e9b18089a0d50df90520862271a864b92f632ae

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-19

케이스

HOW
목표
verify golang.org/x/sync/singleflight.Group in pkg:golang/golang.org/x/sync@v0.21.0
패키지
심벌
  • golang.org/x/sync/singleflight.Group
생성일
2026-09-17T19:10:07Z

컨트랙트

  1. singleflight.Group.Do suppresses duplicate concurrent calls for the same key and returns shared result
  2. singleflight.Group.Do returns function error and marks shared true for concurrent callers
  3. singleflight.Group.DoChan returns channel delivering Result struct with Val, Err and Shared flags
  4. singleflight.Group.Forget removes active key so subsequent calls execute function again

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json
  • test/contract.go

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

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify golang.org/x/sync/singleflight.Group in pkg:golang/golang.org/x/sync@v0.21.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/sync@v0.21.0
Demonstrate these symbols/APIs:
  - golang.org/x/sync/singleflight.Group

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:23a096ba01bba7abc98f1285e5751a1140b27ea1dae3a32859682dd91d11144d","contract":["singleflight.Group.Do suppresses duplicate concurrent calls for the same key and returns shared result","singleflight.Group.Do returns function error and marks shared true for concurrent callers","singleflight.Group.DoChan returns channel delivering Result struct with Val, Err and Shared flags","singleflight.Group.Forget removes active key so subsequent calls execute function again"],"goal":"verify golang.org/x/sync/singleflight.Group in pkg:golang/golang.org/x/sync@v0.21.0","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@v0.21.0"],"schemaVersion":1,"symbols":["golang.org/x/sync/singleflight.Group"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/sync@v0.21.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/sync@v0.21.0","symbols":["golang.org/x/sync/singleflight.Group"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.25.0

require golang.org/x/sync v0.21.0
go.sum
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
sample.go
package sample

import (
	"sync/atomic"

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

// GroupCoordinator wraps singleflight.Group to coordinate duplicate execution suppression.
type GroupCoordinator struct {
	group singleflight.Group
	calls atomic.Int64
}

// NewGroupCoordinator returns a new GroupCoordinator instance.
func NewGroupCoordinator() *GroupCoordinator {
	return &GroupCoordinator{}
}

// Group returns the underlying singleflight.Group instance.
func (c *GroupCoordinator) Group() *singleflight.Group {
	return &c.group
}

// Executions returns the total count of executed underlying worker functions.
func (c *GroupCoordinator) Executions() int64 {
	return c.calls.Load()
}

// Do wraps singleflight.Group.Do, tracking execution invocations.
func (c *GroupCoordinator) Do(key string, fn func() (any, error)) (any, error, bool) {
	return c.group.Do(key, func() (any, error) {
		c.calls.Add(1)
		return fn()
	})
}

// DoChan wraps singleflight.Group.DoChan, returning a channel of singleflight.Result.
func (c *GroupCoordinator) DoChan(key string, fn func() (any, error)) <-chan singleflight.Result {
	return c.group.DoChan(key, func() (any, error) {
		c.calls.Add(1)
		return fn()
	})
}

// Forget delegates to singleflight.Group.Forget to invalidate an in-flight key.
func (c *GroupCoordinator) Forget(key string) {
	c.group.Forget(key)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/sync/singleflight.Group in pkg:golang/golang.org/x/sync@v0.21.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/sync@v0.21.0"
  ],
  "symbols": [
    "golang.org/x/sync/singleflight.Group"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"
	"sync"
	"time"

	"sample"
)

func main() {
	coordinator := sample.NewGroupCoordinator()

	// Assertion 1: singleflight.Group.Do suppresses duplicate concurrent calls for the same key and returns shared result
	{
		const callers = 10
		entered := make(chan struct{})
		release := make(chan struct{})
		results := make([]any, callers)
		errs := make([]error, callers)
		shareds := make([]bool, callers)
		var wg sync.WaitGroup

		for i := 0; i < callers; i++ {
			wg.Add(1)
			go func(idx int) {
				defer wg.Done()
				v, err, shared := coordinator.Do("shared-key", func() (any, error) {
					close(entered)
					<-release
					return "computed-data", nil
				})
				results[idx] = v
				errs[idx] = err
				shareds[idx] = shared
			}(i)
		}

		<-entered
		time.Sleep(25 * time.Millisecond)
		close(release)
		wg.Wait()

		for i := 0; i < callers; i++ {
			if results[i] != "computed-data" {
				fmt.Fprintf(os.Stderr, "FAIL: caller %d expected result 'computed-data', got %v\n", i, results[i])
				os.Exit(1)
			}
			if errs[i] != nil {
				fmt.Fprintf(os.Stderr, "FAIL: caller %d expected nil error, got %v\n", i, errs[i])
				os.Exit(1)
			}
		}

		sharedCount := 0
		for _, s := range shareds {
			if s {
				sharedCount++
			}
		}
		if sharedCount == 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected duplicate callers to have shared=true, got 0\n")
			os.Exit(1)
		}

		if coordinator.Executions() != 1 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 1 execution for shared key, got %d\n", coordinator.Executions())
			os.Exit(1)
		}
	}

	// Assertion 2: singleflight.Group.Do returns function error and marks shared true for concurrent callers
	{
		const errCallers = 5
		enteredErr := make(chan struct{})
		releaseErr := make(chan struct{})
		expectedErr := errors.New("simulated upstream failure")
		errs := make([]error, errCallers)
		shareds := make([]bool, errCallers)
		var wg sync.WaitGroup

		for i := 0; i < errCallers; i++ {
			wg.Add(1)
			go func(idx int) {
				defer wg.Done()
				_, err, shared := coordinator.Do("error-key", func() (any, error) {
					close(enteredErr)
					<-releaseErr
					return nil, expectedErr
				})
				errs[idx] = err
				shareds[idx] = shared
			}(i)
		}

		<-enteredErr
		time.Sleep(25 * time.Millisecond)
		close(releaseErr)
		wg.Wait()

		for i := 0; i < errCallers; i++ {
			if !errors.Is(errs[i], expectedErr) {
				fmt.Fprintf(os.Stderr, "FAIL: caller %d expected error %v, got %v\n", i, expectedErr, errs[i])
				os.Exit(1)
			}
		}

		if coordinator.Executions() != 2 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 2 total executions, got %d\n", coordinator.Executions())
			os.Exit(1)
		}
	}

	// Assertion 3: singleflight.Group.DoChan returns channel delivering Result struct with Val, Err and Shared flags
	{
		ch := coordinator.DoChan("chan-key", func() (any, error) {
			return "async-data", nil
		})

		select {
		case res := <-ch:
			if res.Val != "async-data" {
				fmt.Fprintf(os.Stderr, "FAIL: expected Result.Val 'async-data', got %v\n", res.Val)
				os.Exit(1)
			}
			if res.Err != nil {
				fmt.Fprintf(os.Stderr, "FAIL: expected Result.Err nil, got %v\n", res.Err)
				os.Exit(1)
			}
		case <-time.After(2 * time.Second):
			fmt.Fprintf(os.Stderr, "FAIL: timed out waiting on DoChan result channel\n")
			os.Exit(1)
		}

		if coordinator.Executions() != 3 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 3 total executions, got %d\n", coordinator.Executions())
			os.Exit(1)
		}
	}

	// Assertion 4: singleflight.Group.Forget removes active key so subsequent calls execute function again
	{
		enteredForget := make(chan struct{})
		releaseForget1 := make(chan struct{})
		releaseForget2 := make(chan struct{})

		var wg sync.WaitGroup
		wg.Add(1)
		go func() {
			defer wg.Done()
			_, _, _ = coordinator.Do("forget-key", func() (any, error) {
				close(enteredForget)
				<-releaseForget1
				return "first", nil
			})
		}()

		<-enteredForget
		// In-flight call is blocked. Forget active key.
		coordinator.Forget("forget-key")

		secondStarted := make(chan struct{})
		wg.Add(1)
		go func() {
			defer wg.Done()
			_, _, _ = coordinator.Do("forget-key", func() (any, error) {
				close(secondStarted)
				<-releaseForget2
				return "second", nil
			})
		}()

		select {
		case <-secondStarted:
			// Second call started execution independently because the key was forgotten
		case <-time.After(2 * time.Second):
			fmt.Fprintf(os.Stderr, "FAIL: second call did not start independently after Forget\n")
			os.Exit(1)
		}

		close(releaseForget1)
		close(releaseForget2)
		wg.Wait()

		if coordinator.Executions() != 5 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 5 total executions, got %d\n", coordinator.Executions())
			os.Exit(1)
		}
	}

	fmt.Println("PASS: all singleflight.Group contract assertions passed")
}

오리진 시더

익명