CodeSampleX

サンプル

golang.org/x/sync v0.22.0: errgroup.WithContext, errgroup.Group.SetLimit, semaphore.NewWeighted

検証済みサンプル — golang golang.org/x/sync v0.22.0: errgroup.WithContext, errgroup.Group.SetLimit, semaphore.NewWeighted. go 1.26 · linux alpine/x64 · docker で…

sha256:b48b87cfb762b19b87a9e14cfa4c246213ffb3bcc3308a534d6e0055f6323576

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-20

ケース

HOW
ゴール
verify pkg:golang/golang.org/x/sync@v0.22.0
パッケージ
シンボル
  • errgroup.WithContext
  • errgroup.Group.SetLimit
  • semaphore.NewWeighted
  • singleflight.Group
作成日
2026-08-20T20:40:28Z

コントラクト

  1. errgroup.WithContext cancels derived context and returns error on first subtask failure
  2. errgroup.Group with SetLimit limits maximum concurrent task executions
  3. semaphore.NewWeighted manages weighted access with TryAcquire, Acquire, and Release
  4. singleflight.Group deduplicates concurrent executions for identical keys

ファイル

  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • sync_sample.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 pkg:golang/golang.org/x/sync@v0.22.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/sync@v0.22.0

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.
contract_test.go
package sample

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

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

func TestErrgroupWithContextCancellation(t *testing.T) {
	ctx := context.Background()
	expectedErr := errors.New("subtask failure")

	var canceledObserved int32
	tasks := []func(ctx context.Context) error{
		func(ctx context.Context) error {
			time.Sleep(20 * time.Millisecond)
			return expectedErr
		},
		func(ctx context.Context) error {
			select {
			case <-ctx.Done():
				atomic.StoreInt32(&canceledObserved, 1)
				return ctx.Err()
			case <-time.After(500 * time.Millisecond):
				return nil
			}
		},
	}

	err := RunTaskGroup(ctx, tasks)
	if !errors.Is(err, expectedErr) && (err == nil || err.Error() != expectedErr.Error()) {
		t.Fatalf("expected error %v, got %v", expectedErr, err)
	}

	if atomic.LoadInt32(&canceledObserved) != 1 {
		t.Fatal("expected derived context to be canceled on subtask failure")
	}

	// Direct verification with errgroup.WithContext
	g, gCtx := errgroup.WithContext(context.Background())
	g.Go(func() error {
		return errors.New("direct fail")
	})
	if err := g.Wait(); err == nil {
		t.Fatal("expected error from direct errgroup.WithContext")
	}
	if gCtx.Err() == nil {
		t.Fatal("expected direct group context to be canceled")
	}
}

func TestErrgroupSetLimitConcurrency(t *testing.T) {
	limit := 2
	totalTasks := 8
	var tc TrackConcurrency

	tasks := make([]func() error, totalTasks)
	for i := 0; i < totalTasks; i++ {
		tasks[i] = func() error {
			tc.Enter()
			defer tc.Leave()
			time.Sleep(20 * time.Millisecond)
			return nil
		}
	}

	if err := RunBoundedTasks(limit, tasks); err != nil {
		t.Fatalf("RunBoundedTasks failed: %v", err)
	}

	peak := tc.Peak()
	if peak > int64(limit) {
		t.Fatalf("expected peak concurrency <= %d, observed %d", limit, peak)
	}
	if peak < 2 {
		t.Fatalf("expected peak concurrency to reach %d, observed %d", limit, peak)
	}

	// Direct verification of errgroup.Group SetLimit
	var directGroup errgroup.Group
	directGroup.SetLimit(1)
	var directExecs int32
	directGroup.Go(func() error {
		atomic.AddInt32(&directExecs, 1)
		return nil
	})
	if err := directGroup.Wait(); err != nil {
		t.Fatalf("directGroup failed: %v", err)
	}
	if atomic.LoadInt32(&directExecs) != 1 {
		t.Fatal("expected directGroup to execute task")
	}
}

func TestSemaphoreWeightedAccess(t *testing.T) {
	mgr := NewResourceManager(2)

	// TryAcquire max tokens
	if !mgr.TryAcquire(2) {
		t.Fatal("expected TryAcquire(2) to succeed on fresh semaphore")
	}

	// TryAcquire should fail when no tokens are available
	if mgr.TryAcquire(1) {
		t.Fatal("expected TryAcquire(1) to fail when capacity is exhausted")
	}

	// Release 2 tokens
	mgr.Release(2)

	// Acquire 1 token with context
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	if err := mgr.Acquire(ctx, 1); err != nil {
		t.Fatalf("expected Acquire(1) to succeed: %v", err)
	}

	// TryAcquire remaining 1 token
	if !mgr.TryAcquire(1) {
		t.Fatal("expected TryAcquire(1) to succeed for remaining capacity")
	}

	// Release both tokens
	mgr.Release(2)

	// Direct semaphore.NewWeighted verification
	sem := semaphore.NewWeighted(1)
	if !sem.TryAcquire(1) {
		t.Fatal("expected semaphore.NewWeighted TryAcquire(1) to succeed")
	}
	sem.Release(1)
}

func TestSingleflightDeduplication(t *testing.T) {
	var fetcher CachedFetcher
	var calls int32
	concurrentCallers := 5

	var wg sync.WaitGroup
	results := make([]string, concurrentCallers)
	sharedResults := make([]bool, concurrentCallers)
	errs := make([]error, concurrentCallers)

	for i := 0; i < concurrentCallers; i++ {
		wg.Add(1)
		idx := i
		go func() {
			defer wg.Done()
			res, err, shared := fetcher.Fetch("resource-key", func() (string, error) {
				atomic.AddInt32(&calls, 1)
				time.Sleep(50 * time.Millisecond)
				return "computed-data", nil
			})
			results[idx] = res
			sharedResults[idx] = shared
			errs[idx] = err
		}()
	}

	wg.Wait()

	for i := 0; i < concurrentCallers; i++ {
		if errs[i] != nil {
			t.Fatalf("caller %d got error: %v", i, errs[i])
		}
		if results[i] != "computed-data" {
			t.Fatalf("caller %d got unexpected result: %s", i, results[i])
		}
	}

	totalCalls := atomic.LoadInt32(&calls)
	if totalCalls != 1 {
		t.Fatalf("expected underlying fetch function to be called exactly once, called %d times", totalCalls)
	}

	// Direct singleflight.Group verification
	var directGroup singleflight.Group
	val, err, _ := directGroup.Do("test-direct", func() (interface{}, error) {
		return "ok", nil
	})
	if err != nil || val != "ok" {
		t.Fatalf("expected direct singleflight to return ok, got %v, err=%v", val, err)
	}
}
csx.json
{"case":{"caseId":"case:sha256:aa8fc042bc449ea2f5a7ae628f2002259513cbf0d0c484e1728b23e9089f533c","contract":["errgroup.WithContext cancels derived context and returns error on first subtask failure","errgroup.Group with SetLimit limits maximum concurrent task executions","semaphore.NewWeighted manages weighted access with TryAcquire, Acquire, and Release","singleflight.Group deduplicates concurrent executions for identical keys"],"goal":"verify pkg:golang/golang.org/x/sync@v0.22.0","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@v0.22.0"],"schemaVersion":1,"symbols":["errgroup.WithContext","errgroup.Group.SetLimit","semaphore.NewWeighted","singleflight.Group"]},"contractCommand":["go","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.22.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/sync@v0.22.0","symbols":["errgroup.WithContext","errgroup.Group.SetLimit","semaphore.NewWeighted","singleflight.Group"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/golang.org/x/sync@v0.22.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/sync@v0.22.0"
  ]
}
sync_sample.go
package sample

import (
	"context"
	"errors"
	"fmt"
	"sync/atomic"

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

// RunTaskGroup executes tasks concurrently, canceling all tasks on first failure.
func RunTaskGroup(ctx context.Context, tasks []func(ctx context.Context) error) error {
	g, groupCtx := errgroup.WithContext(ctx)
	for _, task := range tasks {
		t := task
		g.Go(func() error {
			return t(groupCtx)
		})
	}
	return g.Wait()
}

// RunBoundedTasks executes tasks with bounded concurrency.
func RunBoundedTasks(limit int, tasks []func() error) error {
	if limit <= 0 {
		return errors.New("limit must be greater than 0")
	}
	var g errgroup.Group
	g.SetLimit(limit)

	for _, task := range tasks {
		t := task
		g.Go(func() error {
			return t()
		})
	}
	return g.Wait()
}

// ResourceManager manages resource concurrency using a weighted semaphore.
type ResourceManager struct {
	sem *semaphore.Weighted
}

// NewResourceManager creates a manager with max tokens.
func NewResourceManager(tokens int64) *ResourceManager {
	return &ResourceManager{
		sem: semaphore.NewWeighted(tokens),
	}
}

// TryAcquire attempts to acquire n tokens without blocking.
func (r *ResourceManager) TryAcquire(n int64) bool {
	return r.sem.TryAcquire(n)
}

// Acquire acquires n tokens with context.
func (r *ResourceManager) Acquire(ctx context.Context, n int64) error {
	return r.sem.Acquire(ctx, n)
}

// Release releases n tokens.
func (r *ResourceManager) Release(n int64) {
	r.sem.Release(n)
}

// CachedFetcher deduplicates concurrent fetch calls using singleflight.
type CachedFetcher struct {
	group singleflight.Group
}

// Fetch executes fn deduplicated by key.
func (c *CachedFetcher) Fetch(key string, fn func() (string, error)) (string, error, bool) {
	v, err, shared := c.group.Do(key, func() (interface{}, error) {
		res, err := fn()
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return "", err, shared
	}
	resStr, ok := v.(string)
	if !ok {
		return "", fmt.Errorf("unexpected value type %T", v), shared
	}
	return resStr, nil, shared
}

// TrackConcurrency tracks active workers and maximum observed concurrency.
type TrackConcurrency struct {
	current int64
	peak    int64
}

// Enter records a worker starting.
func (tc *TrackConcurrency) Enter() {
	cur := atomic.AddInt64(&tc.current, 1)
	for {
		peak := atomic.LoadInt64(&tc.peak)
		if cur <= peak || atomic.CompareAndSwapInt64(&tc.peak, peak, cur) {
			break
		}
	}
}

// Leave records a worker finishing.
func (tc *TrackConcurrency) Leave() {
	atomic.AddInt64(&tc.current, -1)
}

// Peak returns the maximum concurrent workers observed.
func (tc *TrackConcurrency) Peak() int64 {
	return atomic.LoadInt64(&tc.peak)
}

オリジンシーダー

匿名