CodeSampleX

샘플

golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208: errgroup.WithContext, semaphore.NewWeighted, singleflight.Group

검증된 샘플 — golang golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208: errgroup.WithContext, semaphore.NewWeighted, singleflight.Group. go 1.26 · linux…

sha256:d48e276c03842e8a6da32f092b9a7571aff8ded8b4f79451c4054a6671710406

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

케이스

HOW
목표
verify pkg:golang/golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208
패키지
심벌
  • errgroup.WithContext
  • semaphore.NewWeighted
  • singleflight.Group
  • syncmap.Map
생성일
2026-10-16T10:21: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 while returning their previous value via LoadAndDelete

파일

  • 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-20200625203802-6e8e738ad208
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208

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:6b09bad2c0fdb23344231776cdcd03723e7d837572b29cbde8263fdb2a89b36f","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 while returning their previous value via LoadAndDelete"],"goal":"verify pkg:golang/golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208"],"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-20200625203802-6e8e738ad208"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208","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-20200625203802-6e8e738ad208
go.sum
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA=
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208"
  ]
}
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 := runContract(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func runContract() error {
	// 1. errgroup.WithContext cancels derived context on first non-nil error and returns that first error
	baseCtx := context.Background()
	g, gctx := errgroup.WithContext(baseCtx)
	sentinelErr := errors.New("task failed")
	g.Go(func() error {
		return sentinelErr
	})
	g.Go(func() error {
		<-gctx.Done()
		return nil
	})
	if err := g.Wait(); !errors.Is(err, sentinelErr) {
		return fmt.Errorf("expected sentinel error from errgroup.Wait, got %v", err)
	}
	if gctx.Err() == nil {
		return fmt.Errorf("expected errgroup derived context to be canceled after Wait")
	}

	// 2. errgroup.WithContext also cancels derived context when all goroutines succeed and Wait returns nil
	g2, gctx2 := errgroup.WithContext(baseCtx)
	g2.Go(func() error {
		return nil
	})
	if err := g2.Wait(); err != nil {
		return fmt.Errorf("expected nil error from successful errgroup.Wait, got %v", err)
	}
	if !errors.Is(gctx2.Err(), context.Canceled) {
		return fmt.Errorf("expected errgroup derived context to be Canceled after Wait returns, got %v", gctx2.Err())
	}

	// 3. singleflight.Group deduplicates concurrent Do calls for the same key andForget allows re-execution
	var sf singleflight.Group
	var calls int32
	started := make(chan struct{})
	release := make(chan struct{})

	ch1 := sf.DoChan("key-a", func() (interface{}, error) {
		atomic.AddInt32(&calls, 1)
		close(started)
		<-release
		return "computed-value", nil
	})
	<-started
	ch2 := sf.DoChan("key-a", func() (interface{}, error) {
		atomic.AddInt32(&calls, 1)
		return "second-value", nil
	})
	close(release)

	res1 := <-ch1
	res2 := <-ch2
	if atomic.LoadInt32(&calls) != 1 {
		return fmt.Errorf("expected singleflight function to execute once, got %d", calls)
	}
	if res1.Val != "computed-value" || res2.Val != "computed-value" {
		return fmt.Errorf("unexpected singleflight results: %v, %v", res1.Val, res2.Val)
	}
	if !res1.Shared || !res2.Shared {
		return fmt.Errorf("expected Shared=true when two callers share in-flight execution")
	}

	// Forget Eviction
	started2 := make(chan struct{})
	release2 := make(chan struct{})
	ch3 := sf.DoChan("key-b", func() (interface{}, error) {
		atomic.AddInt32(&calls, 1)
		close(started2)
		<-release2
		return "first-b", nil
	})
	<-started2
	sf.Forget("key-b")
	v, err, shared := sf.Do("key-b", func() (interface{}, error) {
		atomic.AddInt32(&calls, 1)
		return "second-b", nil
	})
	close(release2)
	res3 := <-ch3
	if err != nil || v != "second-b" || shared {
		return fmt.Errorf("expected fresh execution after Forget, got v=%v err=%v shared=%v", v, err, shared)
	}
	if res3.Val != "first-b" {
		return fmt.Errorf("expected first in-flight caller to still receive first-b, got %v", res3.Val)
	}

	// 4. semaphore.NewWeighted enforces FIFO waiter ordering and blocks TryAcquire while waiters are queued
	sem := semaphore.NewWeighted(3)
	if !sem.TryAcquire(2) {
		return fmt.Errorf("expected initial TryAcquire(2) on capacity 3 to succeed")
	}
	// Remaining capacity is 1. Queue an Acquire(2) waiter which must block.
	waiterCtx, cancelWaiter := context.WithTimeout(baseCtx, 5*time.Second)
	defer cancelWaiter()
	waiterDone := make(chan error, 1)
	go func() {
		waiterDone <- sem.Acquire(waiterCtx, 2)
	}()

	// Wait until waiter is enqueued by polling TryAcquire(1) which turns false once a waiter is queued
	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 enter semaphore wait list")
		}
		time.Sleep(time.Millisecond)
	}
	// With waiter(2) at head of queue and 1 token free, TryAcquire(1) must return false due to FIFO fairness
	if sem.TryAcquire(1) {
		return fmt.Errorf("expected TryAcquire(1) to return false while larger waiter is queued")
	}
	sem.Release(2)
	if err := <-waiterDone; err != nil {
		return fmt.Errorf("expected queued Acquire(2) to succeed after Release(2), got %v", err)
	}
	sem.Release(2)

	// 5. syncmap.Map LoadOrStore, LoadAndDelete, and Range operations
	var sm syncmap.Map
	actual, loaded := sm.LoadOrStore("alpha", 100)
	if loaded || actual != 100 {
		return fmt.Errorf("expected first LoadOrStore to store 100 with loaded=false")
	}
	actual, loaded = sm.LoadOrStore("alpha", 200)
	if !loaded || actual != 100 {
		return fmt.Errorf("expected second LoadOrStore to return existing 100 with loaded=true")
	}
	deletedVal, deletedOk := sm.LoadAndDelete("alpha")
	if !deletedOk || deletedVal != 100 {
		return fmt.Errorf("expected LoadAndDelete to return 100, true; got %v, %v", deletedVal, deletedOk)
	}
	if _, ok := sm.Load("alpha"); ok {
		return fmt.Errorf("expected key alpha to be absent after LoadAndDelete")
	}

	return nil
}

오리진 시더

익명