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. contract 在 go 1.26 · linux alpine/x64 …

sha256:b48b87cfb762b19b87a9e14cfa4c246213ffb3bcc3308a534d6e0055f6323576

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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)
}

原始种子者

匿名