示例
golang.org/x/sync v0.17.0
已验证示例 — golang golang.org/x/sync v0.17.0. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: errgroup.WithContext cancels derived context and returns…
sha256:40b1bc9bb78b9e8ae757c73bc59d8aba2f7e2ab7f5b64fa61111eee6174d54a9
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
linux 24 · ubuntu · glibc 2.39 x64 go
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | 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.17.0
- 创建时间
- 2026-08-20T02:16:59Z
契约
- 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
文件
- PROMPT.md
- csx.json
- go.mod
- go.sum
- main.go
- spec.json
- test/contract.go
源代码
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.17.0
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/golang.org/x/sync@v0.17.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.
{"case":{"caseId":"case:sha256:82eddf6e18460bad3708d1bfbdbed5b0536adf408a79a9c2c21e64e68faba31c","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.17.0","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@v0.17.0"],"schemaVersion":1},"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.17.0"],"schemaVersion":1,"verifierAdapter":"golang@1"}
module example.com/sample
go 1.26.6
require golang.org/x/sync v0.17.0
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
package main
import (
"context"
"fmt"
"sync/atomic"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
)
// TaskRunner coordinates concurrent tasks with concurrency limits using errgroup.
type TaskRunner struct {
concurrency int
}
// NewTaskRunner creates a TaskRunner with the given concurrency limit.
func NewTaskRunner(concurrency int) *TaskRunner {
return &TaskRunner{concurrency: concurrency}
}
// Run executes tasks concurrently, returning the first error encountered if any.
func (r *TaskRunner) Run(ctx context.Context, tasks []func(context.Context) error) error {
g, gCtx := errgroup.WithContext(ctx)
if r.concurrency > 0 {
g.SetLimit(r.concurrency)
}
for _, task := range tasks {
t := task
g.Go(func() error {
return t(gCtx)
})
}
return g.Wait()
}
// ResourceLimiter manages access to weighted resources using semaphore.Weighted.
type ResourceLimiter struct {
sem *semaphore.Weighted
}
// NewResourceLimiter creates a limiter with max capacity.
func NewResourceLimiter(capacity int64) *ResourceLimiter {
return &ResourceLimiter{sem: semaphore.NewWeighted(capacity)}
}
// Acquire requests weight from the limiter, blocking until available or context canceled.
func (l *ResourceLimiter) Acquire(ctx context.Context, weight int64) error {
return l.sem.Acquire(ctx, weight)
}
// TryAcquire attempts non-blocking acquisition of weight.
func (l *ResourceLimiter) TryAcquire(weight int64) bool {
return l.sem.TryAcquire(weight)
}
// Release returns weight to the limiter.
func (l *ResourceLimiter) Release(weight int64) {
l.sem.Release(weight)
}
// WorkDeduplicator deduplicates concurrent executions for matching keys using singleflight.Group.
type WorkDeduplicator struct {
group singleflight.Group
}
// Do executes fn for the key or awaits an existing in-flight execution.
func (d *WorkDeduplicator) Do(key string, fn func() (any, error)) (any, error, bool) {
return d.group.Do(key, fn)
}
func main() {
runner := NewTaskRunner(3)
var processed int32
err := runner.Run(context.Background(), []func(context.Context) error{
func(ctx context.Context) error {
atomic.AddInt32(&processed, 1)
return nil
},
func(ctx context.Context) error {
atomic.AddInt32(&processed, 1)
return nil
},
})
if err != nil {
fmt.Printf("runner error: %v\n", err)
return
}
limiter := NewResourceLimiter(5)
if limiter.TryAcquire(2) {
fmt.Println("Acquired 2 units")
limiter.Release(2)
}
dedup := &WorkDeduplicator{}
val, _, shared := dedup.Do("item-key", func() (any, error) {
return "computed-result", nil
})
fmt.Printf("Result: %v, Shared: %v, Processed tasks: %d\n", val, shared, processed)
}
{
"schemaVersion": 1,
"goal": "verify pkg:golang/golang.org/x/sync@v0.17.0",
"kind": "HOW",
"packages": [
"pkg:golang/golang.org/x/sync@v0.17.0"
]
}
package main
import (
"context"
"errors"
"fmt"
"os"
"sync"
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
)
func main() {
// Assertion 1: errgroup.WithContext cancels derived context and returns error on first subtask failure
{
expectedErr := errors.New("simulated failure")
g, ctx := errgroup.WithContext(context.Background())
g.Go(func() error {
return expectedErr
})
g.Go(func() error {
select {
case <-ctx.Done():
return nil
case <-time.After(2 * time.Second):
return errors.New("timeout waiting for context cancellation")
}
})
err := g.Wait()
if err == nil || !errors.Is(err, expectedErr) {
fmt.Fprintf(os.Stderr, "FAIL: expected error %v, got %v\n", expectedErr, err)
os.Exit(1)
}
}
// Assertion 2: errgroup.Group with SetLimit limits maximum concurrent task executions
{
var g errgroup.Group
limit := 2
g.SetLimit(limit)
var currentActive int32
var maxActive int32
var completedTasks int32
totalTasks := 6
for i := 0; i < totalTasks; i++ {
g.Go(func() error {
curr := atomic.AddInt32(¤tActive, 1)
for {
max := atomic.LoadInt32(&maxActive)
if curr > max {
if atomic.CompareAndSwapInt32(&maxActive, max, curr) {
break
}
} else {
break
}
}
time.Sleep(10 * time.Millisecond)
atomic.AddInt32(¤tActive, -1)
atomic.AddInt32(&completedTasks, 1)
return nil
})
}
if err := g.Wait(); err != nil {
fmt.Fprintf(os.Stderr, "FAIL: errgroup wait error: %v\n", err)
os.Exit(1)
}
if atomic.LoadInt32(&completedTasks) != int32(totalTasks) {
fmt.Fprintf(os.Stderr, "FAIL: expected %d completed tasks, got %d\n", totalTasks, completedTasks)
os.Exit(1)
}
if atomic.LoadInt32(&maxActive) > int32(limit) {
fmt.Fprintf(os.Stderr, "FAIL: max active goroutines (%d) exceeded limit (%d)\n", maxActive, limit)
os.Exit(1)
}
}
// Assertion 3: semaphore.NewWeighted manages weighted access with TryAcquire, Acquire, and Release
{
sem := semaphore.NewWeighted(3)
if !sem.TryAcquire(2) {
fmt.Fprintf(os.Stderr, "FAIL: TryAcquire(2) failed on empty 3-weight semaphore\n")
os.Exit(1)
}
if sem.TryAcquire(2) {
fmt.Fprintf(os.Stderr, "FAIL: TryAcquire(2) should fail when only 1 weight is available\n")
os.Exit(1)
}
sem.Release(2)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := sem.Acquire(ctx, 3); err != nil {
fmt.Fprintf(os.Stderr, "FAIL: Acquire(3) failed: %v\n", err)
os.Exit(1)
}
sem.Release(3)
}
// Assertion 4: singleflight.Group deduplicates concurrent executions for identical keys
{
var sf singleflight.Group
var callCount int32
var wg sync.WaitGroup
concurrency := 5
results := make([]string, concurrency)
barrier := make(chan struct{})
for i := 0; i < concurrency; i++ {
wg.Add(1)
idx := i
go func() {
defer wg.Done()
<-barrier
v, err, _ := sf.Do("shared-key", func() (any, error) {
atomic.AddInt32(&callCount, 1)
time.Sleep(20 * time.Millisecond)
return "shared-value", nil
})
if err != nil {
return
}
results[idx] = v.(string)
}()
}
close(barrier)
wg.Wait()
calls := atomic.LoadInt32(&callCount)
if calls != 1 {
fmt.Fprintf(os.Stderr, "FAIL: singleflight executed function %d times, expected 1\n", calls)
os.Exit(1)
}
for i, res := range results {
if res != "shared-value" {
fmt.Fprintf(os.Stderr, "FAIL: result[%d] = %q, expected %q\n", i, res, "shared-value")
os.Exit(1)
}
}
}
fmt.Println("PASS: golang.org/x/sync contract passed")
}
原始种子者
匿名