CodeSampleX

示例

golang.org/x/sync v0.0.0-20190423024810-112230192c58: errgroup.WithContext, semaphore.NewWeighted, singleflight.Group

已验证示例 — golang golang.org/x/sync v0.0.0-20190423024810-112230192c58: errgroup.WithContext, semaphore.NewWeighted, singleflight.Group. contract 在 go 1.26 …

sha256:d3d8d2d0d5c0c97d4c3fa773e129e299e655d9251ecf277e73afd7378136867c

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

案例

HOW
目标
verify pkg:golang/golang.org/x/sync@v0.0.0-20190423024810-112230192c58
包
符号
  • errgroup.WithContext
  • semaphore.NewWeighted
  • singleflight.Group
  • syncmap.Map
创建时间
2026-10-18T20:40:46Z

契约

  1. assert errgroup.WithContext cancels its derived context upon the first non-nil goroutine error or upon Wait returning and returns the first non-nil error
  2. assert singleflight.Group deduplicates concurrent in-flight DoChan calls for the same key with Shared=true and Forget evicts the active key so subsequent callers execute freshly
  3. assert semaphore.NewWeighted enforces strict FIFO waiter ordering where TryAcquire returns false for smaller weights while a larger waiter is queued at the head
  4. assert syncmap.Map atomically stores or returns existing entries via LoadOrStore and removes entries via Delete

文件

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • 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 pkg:golang/golang.org/x/sync@v0.0.0-20190423024810-112230192c58
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/sync@v0.0.0-20190423024810-112230192c58

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:ea418acfa67612205fa58618fc1d0bc365671e59ab420b727a19aaeff84abdd2","contract":["assert errgroup.WithContext cancels its derived context upon the first non-nil goroutine error or upon Wait returning and returns the first non-nil error","assert singleflight.Group deduplicates concurrent in-flight DoChan calls for the same key with Shared=true and Forget evicts the active key so subsequent callers execute freshly","assert semaphore.NewWeighted enforces strict FIFO waiter ordering where TryAcquire returns false for smaller weights while a larger waiter is queued at the head","assert syncmap.Map atomically stores or returns existing entries via LoadOrStore and removes entries via Delete"],"goal":"verify pkg:golang/golang.org/x/sync@v0.0.0-20190423024810-112230192c58","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@v0.0.0-20190423024810-112230192c58"],"schemaVersion":1,"symbols":["errgroup.WithContext","semaphore.NewWeighted","singleflight.Group","syncmap.Map"]},"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.0.0-20190423024810-112230192c58"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/sync@v0.0.0-20190423024810-112230192c58","symbols":["errgroup.WithContext","semaphore.NewWeighted","singleflight.Group","syncmap.Map"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.18

require golang.org/x/sync v0.0.0-20190423024810-112230192c58
go.sum
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/golang.org/x/sync@v0.0.0-20190423024810-112230192c58",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/sync@v0.0.0-20190423024810-112230192c58"
  ]
}
test/contract.go
package main

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

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

func main() {
	if err := verifyContract(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func verifyContract() error {
	ctx := context.Background()

	// 1. errgroup.WithContext cancels derived context upon the first non-nil goroutine error or upon Wait returning and returns the first non-nil error
	g, gctx := errgroup.WithContext(ctx)
	errFail := errors.New("subtask failed")
	g.Go(func() error {
		return errFail
	})
	g.Go(func() error {
		<-gctx.Done()
		return nil
	})
	if err := g.Wait(); !errors.Is(err, errFail) {
		return fmt.Errorf("expected errFail from errgroup.Wait, got %v", err)
	}
	if gctx.Err() == nil {
		return fmt.Errorf("expected derived context to be canceled after error")
	}

	gOk, gctxOk := errgroup.WithContext(ctx)
	gOk.Go(func() error {
		return nil
	})
	if err := gOk.Wait(); err != nil {
		return fmt.Errorf("expected nil error from gOk.Wait, got %v", err)
	}
	if !errors.Is(gctxOk.Err(), context.Canceled) {
		return fmt.Errorf("expected derived context to be Canceled after Wait returns, got %v", gctxOk.Err())
	}

	// 2. singleflight.Group deduplicates concurrent in-flight DoChan calls for the same key with Shared=true and Forget evicts the active key so subsequent callers execute freshly
	var sf singleflight.Group
	var execCount int32
	started := make(chan struct{})
	gate := make(chan struct{})

	ch1 := sf.DoChan("k1", func() (interface{}, error) {
		atomic.AddInt32(&execCount, 1)
		close(started)
		<-gate
		return "v1", nil
	})
	<-started
	ch2 := sf.DoChan("k1", func() (interface{}, error) {
		atomic.AddInt32(&execCount, 1)
		return "v2", nil
	})
	close(gate)

	r1 := <-ch1
	r2 := <-ch2
	if atomic.LoadInt32(&execCount) != 1 {
		return fmt.Errorf("expected singleflight function to run once, got %d", execCount)
	}
	if r1.Val != "v1" || r2.Val != "v1" || !r1.Shared || !r2.Shared {
		return fmt.Errorf("unexpected singleflight results: r1=%+v r2=%+v", r1, r2)
	}

	started2 := make(chan struct{})
	gate2 := make(chan struct{})
	ch3 := sf.DoChan("k2", func() (interface{}, error) {
		atomic.AddInt32(&execCount, 1)
		close(started2)
		<-gate2
		return "old", nil
	})
	<-started2
	sf.Forget("k2")
	val, err, shared := sf.Do("k2", func() (interface{}, error) {
		atomic.AddInt32(&execCount, 1)
		return "fresh", nil
	})
	close(gate2)
	r3 := <-ch3
	if err != nil || val != "fresh" || shared || r3.Val != "old" {
		return fmt.Errorf("unexpected Forget behavior: val=%v err=%v shared=%v r3=%+v", val, err, shared, r3)
	}

	// 3. semaphore.NewWeighted enforces strict FIFO waiter ordering where TryAcquire returns false for smaller weights while a larger waiter is queued at the head
	sem := semaphore.NewWeighted(3)
	if !sem.TryAcquire(2) {
		return fmt.Errorf("expected TryAcquire(2) on capacity 3 to succeed")
	}
	wCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	acquired := make(chan error, 1)
	go func() {
		acquired <- sem.Acquire(wCtx, 2)
	}()

	deadline := time.Now().Add(2 * time.Second)
	for sem.TryAcquire(1) {
		sem.Release(1)
		if time.Now().After(deadline) {
			return fmt.Errorf("timed out waiting for Acquire(2) to queue")
		}
		time.Sleep(time.Millisecond)
	}
	if sem.TryAcquire(1) {
		return fmt.Errorf("expected TryAcquire(1) to fail while weight-2 waiter is at head of queue")
	}
	sem.Release(2)
	if err := <-acquired; err != nil {
		return fmt.Errorf("expected queued Acquire(2) to succeed, got %v", err)
	}
	sem.Release(2)

	// 4. syncmap.Map atomically stores or returns existing entries via LoadOrStore and removes entries via Delete
	var sm syncmap.Map
	v, loaded := sm.LoadOrStore("item", 42)
	if loaded || v != 42 {
		return fmt.Errorf("expected initial LoadOrStore to return 42, false; got %v, %v", v, loaded)
	}
	v, loaded = sm.LoadOrStore("item", 99)
	if !loaded || v != 42 {
		return fmt.Errorf("expected second LoadOrStore to return 42, true; got %v, %v", v, loaded)
	}
	sm.Delete("item")
	if _, ok := sm.Load("item"); ok {
		return fmt.Errorf("expected item to be removed after Delete")
	}

	return nil
}

原始种子者

匿名