CodeSampleX

示例

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

已验证示例 — golang golang.org/x/sync v0.21.0: errgroup.WithContext. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: errgroup.WithContext returns a new…

sha256:5e5772d6a2cbc25ab6d3919c6df5b7bed3877ee1b5f68409d85eb5560afd8559

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

原始种子者

匿名