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 を実行し、成功しました.

sha256:5e5772d6a2cbc25ab6d3919c6df5b7bed3877ee1b5f68409d85eb5560afd8559

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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.")
}

オリジンシーダー

匿名