CodeSampleX

샘플

golang.org/x/sync v0.21.0: errgroup.WithContext

검증된 샘플 — golang golang.org/x/sync v0.21.0: errgroup.WithContext. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: errgroup.WithContext returns a…

sha256:5e5772d6a2cbc25ab6d3919c6df5b7bed3877ee1b5f68409d85eb5560afd8559

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

검증 실행 환경

환경 컨트랙트 단계 실행일
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-09-19

케이스

HOW
목표
verify golang.org/x/sync/errgroup.WithContext in pkg:golang/golang.org/x/sync@v0.21.0
패키지
심벌
  • golang.org/x/sync/errgroup.WithContext
환경
go 1.26.6
생성일
2026-09-17T17:33:57Z

컨트랙트

  1. errgroup.WithContext returns a new Group and a non-nil derived Context from the parent context
  2. errgroup.WithContext coordinates concurrent tasks with g.Go and returns nil from g.Wait when all succeed
  3. errgroup.WithContext cancels the derived context when any goroutine returns a non-nil error
  4. g.Wait returns the first non-nil error returned by any goroutine
  5. Parent context cancellation propagates to the derived context returned by errgroup.WithContext

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • 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 golang.org/x/sync/errgroup.WithContext in pkg:golang/golang.org/x/sync@v0.21.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/sync@v0.21.0
Demonstrate these symbols/APIs:
  - golang.org/x/sync/errgroup.WithContext

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:d5b8db8f1dda75cf21cfec3906ccfefd1d4be10f85b7614b88401b810a0bd7d4","contract":["errgroup.WithContext returns a new Group and a non-nil derived Context from the parent context","errgroup.WithContext coordinates concurrent tasks with g.Go and returns nil from g.Wait when all succeed","errgroup.WithContext cancels the derived context when any goroutine returns a non-nil error","g.Wait returns the first non-nil error returned by any goroutine","Parent context cancellation propagates to the derived context returned by errgroup.WithContext"],"goal":"verify golang.org/x/sync/errgroup.WithContext in pkg:golang/golang.org/x/sync@v0.21.0","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@v0.21.0"],"schemaVersion":1,"symbols":["golang.org/x/sync/errgroup.WithContext"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/sync@v0.21.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/sync@v0.21.0","symbols":["golang.org/x/sync/errgroup.WithContext"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require golang.org/x/sync v0.21.0
go.sum
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
main.go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"

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

func fetchResource(ctx context.Context, id int) (string, error) {
	select {
	case <-ctx.Done():
		return "", ctx.Err()
	case <-time.After(10 * time.Millisecond):
		if id == 3 {
			return "", errors.New("resource 3 simulated failure")
		}
		return fmt.Sprintf("result-%d", id), nil
	}
}

func main() {
	// Example 1: Successful concurrent execution with errgroup.WithContext
	ctx := context.Background()
	g, gCtx := errgroup.WithContext(ctx)

	results := make([]string, 3)
	for i := 0; i < 3; i++ {
		index := i
		g.Go(func() error {
			select {
			case <-gCtx.Done():
				return gCtx.Err()
			case <-time.After(5 * time.Millisecond):
				results[index] = fmt.Sprintf("data-%d", index)
				return nil
			}
		})
	}

	if err := g.Wait(); err != nil {
		fmt.Printf("Unexpected error in successful run: %v\n", err)
	} else {
		fmt.Printf("Successful run completed with results: %v\n", results)
	}

	// Example 2: Error propagation and context cancellation across goroutines
	gErr, gErrCtx := errgroup.WithContext(ctx)
	for i := 1; i <= 4; i++ {
		id := i
		gErr.Go(func() error {
			_, err := fetchResource(gErrCtx, id)
			return err
		})
	}

	if err := gErr.Wait(); err != nil {
		fmt.Printf("Error group caught failure as expected: %v\n", err)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/sync/errgroup.WithContext in pkg:golang/golang.org/x/sync@v0.21.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/sync@v0.21.0"
  ],
  "symbols": [
    "golang.org/x/sync/errgroup.WithContext"
  ]
}
test/contract.go
package main

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

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

func main() {
	// Assertion 1: errgroup.WithContext returns a new Group and a non-nil derived Context from the parent context
	{
		parentCtx, cancel := context.WithCancel(context.Background())
		defer cancel()

		g, gCtx := errgroup.WithContext(parentCtx)
		if g == nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: Group should not be nil\n")
			os.Exit(1)
		}
		if gCtx == nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: derived context should not be nil\n")
			os.Exit(1)
		}
		if gCtx.Err() != nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: derived context should not be canceled initially\n")
			os.Exit(1)
		}
	}

	// Assertion 2: errgroup.WithContext coordinates concurrent tasks with g.Go and returns nil from g.Wait when all succeed
	{
		g, _ := errgroup.WithContext(context.Background())
		var count atomic.Int32
		const numTasks = 5

		for i := 0; i < numTasks; i++ {
			g.Go(func() error {
				count.Add(1)
				return nil
			})
		}

		if err := g.Wait(); err != nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: Wait returned unexpected error: %v\n", err)
			os.Exit(1)
		}
		if count.Load() != numTasks {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected count %d, got %d\n", numTasks, count.Load())
			os.Exit(1)
		}
	}

	// Assertion 3: errgroup.WithContext cancels the derived context when any goroutine returns a non-nil error
	{
		g, gCtx := errgroup.WithContext(context.Background())
		expectedErr := errors.New("simulated error")

		g.Go(func() error {
			return expectedErr
		})

		g.Go(func() error {
			select {
			case <-gCtx.Done():
				return nil
			case <-time.After(2 * time.Second):
				return errors.New("timeout waiting for context cancellation")
			}
		})

		err := g.Wait()
		if !errors.Is(err, expectedErr) {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected %v, got %v\n", expectedErr, err)
			os.Exit(1)
		}
		if !errors.Is(gCtx.Err(), context.Canceled) {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: context should be canceled, got %v\n", gCtx.Err())
			os.Exit(1)
		}
	}

	// Assertion 4: g.Wait returns the first non-nil error returned by any goroutine
	{
		g, gCtx := errgroup.WithContext(context.Background())
		firstErr := errors.New("first failure")
		secondErr := errors.New("second failure")

		g.Go(func() error {
			return firstErr
		})

		g.Go(func() error {
			<-gCtx.Done()
			return secondErr
		})

		err := g.Wait()
		if !errors.Is(err, firstErr) {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected first error %v, got %v\n", firstErr, err)
			os.Exit(1)
		}
	}

	// Assertion 5: Parent context cancellation propagates to the derived context returned by errgroup.WithContext
	{
		parentCtx, cancelParent := context.WithCancel(context.Background())
		_, gCtx := errgroup.WithContext(parentCtx)

		cancelParent()

		select {
		case <-gCtx.Done():
			if !errors.Is(gCtx.Err(), context.Canceled) {
				fmt.Fprintf(os.Stderr, "assertion 5 failed: expected context.Canceled, got %v\n", gCtx.Err())
				os.Exit(1)
			}
		case <-time.After(2 * time.Second):
			fmt.Fprintf(os.Stderr, "assertion 5 failed: derived context was not canceled after parent cancellation\n")
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed successfully.")
}

오리진 시더

익명