CodeSampleX

サンプル

golang.org/x/sync v0.12.0

検証済みサンプル — golang golang.org/x/sync v0.12.0. go 1.26 · linux alpine/x64 · docker で contract を実行し、成功しました: errgroup.WithContext cancels derived context and…

sha256:1abe8a8a93ffb43fea88835581e5c9094f2a4c9b57f03dec4f851fe2d4bd42c7

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

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-19

ケース

HOW
ゴール
verify pkg:golang/golang.org/x/sync@v0.12.0
パッケージ
作成日
2026-08-19T20:47:55Z

コントラクト

  1. errgroup.WithContext cancels derived context and returns error on first subtask failure
  2. errgroup.Group with SetLimit limits maximum concurrent task executions
  3. semaphore.NewWeighted manages weighted access with TryAcquire, Acquire, and Release
  4. singleflight.Group deduplicates concurrent executions for identical keys

ファイル

  • 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 pkg:golang/golang.org/x/sync@v0.12.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/sync@v0.12.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:7176a836cdd816ea2abec68867cbd4584da384401ff83ce074193ed2a4c22915","contract":["errgroup.WithContext cancels derived context and returns error on first subtask failure","errgroup.Group with SetLimit limits maximum concurrent task executions","semaphore.NewWeighted manages weighted access with TryAcquire, Acquire, and Release","singleflight.Group deduplicates concurrent executions for identical keys"],"goal":"verify pkg:golang/golang.org/x/sync@v0.12.0","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@v0.12.0"],"schemaVersion":1},"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.12.0"],"schemaVersion":1,"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require golang.org/x/sync v0.12.0
go.sum
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
main.go
package main

import (
	"context"
	"fmt"
	"sync/atomic"

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

// TaskRunner manages task execution with concurrency limits and error handling using errgroup.
type TaskRunner struct {
	limit int
}

// NewTaskRunner creates a new TaskRunner with the given concurrency limit.
func NewTaskRunner(limit int) *TaskRunner {
	return &TaskRunner{limit: limit}
}

// RunTasks executes the provided tasks concurrently up to the configured limit.
func (r *TaskRunner) RunTasks(ctx context.Context, tasks []func(context.Context) error) error {
	g, gCtx := errgroup.WithContext(ctx)
	if r.limit > 0 {
		g.SetLimit(r.limit)
	}

	for _, task := range tasks {
		t := task
		g.Go(func() error {
			return t(gCtx)
		})
	}

	return g.Wait()
}

// ResourcePool manages weighted resource access using semaphore.Weighted.
type ResourcePool struct {
	sem *semaphore.Weighted
}

// NewResourcePool creates a ResourcePool with the specified maximum token capacity.
func NewResourcePool(capacity int64) *ResourcePool {
	return &ResourcePool{sem: semaphore.NewWeighted(capacity)}
}

// AcquireTokens blocks until n tokens can be acquired or context is cancelled.
func (p *ResourcePool) AcquireTokens(ctx context.Context, n int64) error {
	return p.sem.Acquire(ctx, n)
}

// TryAcquireTokens attempts to acquire n tokens non-blockingly.
func (p *ResourcePool) TryAcquireTokens(n int64) bool {
	return p.sem.TryAcquire(n)
}

// ReleaseTokens releases n tokens back to the pool.
func (p *ResourcePool) ReleaseTokens(n int64) {
	p.sem.Release(n)
}

// QueryDeduplicator deduplicates concurrent executions with the same key using singleflight.Group.
type QueryDeduplicator struct {
	group singleflight.Group
}

// Execute runs fn for key, deduplicating concurrent calls.
func (q *QueryDeduplicator) Execute(key string, fn func() (any, error)) (any, error, bool) {
	return q.group.Do(key, fn)
}

func main() {
	runner := NewTaskRunner(2)
	var count int32

	err := runner.RunTasks(context.Background(), []func(context.Context) error{
		func(ctx context.Context) error {
			atomic.AddInt32(&count, 1)
			return nil
		},
		func(ctx context.Context) error {
			atomic.AddInt32(&count, 1)
			return nil
		},
	})

	if err != nil {
		fmt.Printf("Task execution error: %v\n", err)
		return
	}

	pool := NewResourcePool(4)
	if pool.TryAcquireTokens(2) {
		fmt.Println("Acquired 2 tokens")
		pool.ReleaseTokens(2)
	}

	dedup := &QueryDeduplicator{}
	val, _, shared := dedup.Execute("item-1", func() (any, error) {
		return "data", nil
	})

	fmt.Printf("Result: %v, Shared: %v, Tasks completed: %d\n", val, shared, count)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/golang.org/x/sync@v0.12.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/sync@v0.12.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

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

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

func main() {
	// Assertion 1: errgroup.WithContext cancels derived context and returns error on first subtask failure
	{
		expectedErr := errors.New("simulated failure")
		g, ctx := errgroup.WithContext(context.Background())

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

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

		err := g.Wait()
		if err == nil || !errors.Is(err, expectedErr) {
			fmt.Fprintf(os.Stderr, "FAIL: expected error %v, got %v\n", expectedErr, err)
			os.Exit(1)
		}
	}

	// Assertion 2: errgroup.Group with SetLimit limits maximum concurrent task executions
	{
		var g errgroup.Group
		limit := 2
		g.SetLimit(limit)

		var currentActive int32
		var maxActive int32
		var completedTasks int32
		totalTasks := 6

		for i := 0; i < totalTasks; i++ {
			g.Go(func() error {
				curr := atomic.AddInt32(&currentActive, 1)
				for {
					max := atomic.LoadInt32(&maxActive)
					if curr > max {
						if atomic.CompareAndSwapInt32(&maxActive, max, curr) {
							break
						}
					} else {
						break
					}
				}

				time.Sleep(10 * time.Millisecond)
				atomic.AddInt32(&currentActive, -1)
				atomic.AddInt32(&completedTasks, 1)
				return nil
			})
		}

		if err := g.Wait(); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: errgroup wait error: %v\n", err)
			os.Exit(1)
		}

		if atomic.LoadInt32(&completedTasks) != int32(totalTasks) {
			fmt.Fprintf(os.Stderr, "FAIL: expected %d completed tasks, got %d\n", totalTasks, completedTasks)
			os.Exit(1)
		}

		if atomic.LoadInt32(&maxActive) > int32(limit) {
			fmt.Fprintf(os.Stderr, "FAIL: max active goroutines (%d) exceeded limit (%d)\n", maxActive, limit)
			os.Exit(1)
		}
	}

	// Assertion 3: semaphore.NewWeighted manages weighted access with TryAcquire, Acquire, and Release
	{
		sem := semaphore.NewWeighted(3)

		if !sem.TryAcquire(2) {
			fmt.Fprintf(os.Stderr, "FAIL: TryAcquire(2) failed on empty 3-weight semaphore\n")
			os.Exit(1)
		}

		if sem.TryAcquire(2) {
			fmt.Fprintf(os.Stderr, "FAIL: TryAcquire(2) should fail when only 1 weight is available\n")
			os.Exit(1)
		}

		sem.Release(2)

		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		defer cancel()

		if err := sem.Acquire(ctx, 3); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Acquire(3) failed: %v\n", err)
			os.Exit(1)
		}
		sem.Release(3)
	}

	// Assertion 4: singleflight.Group deduplicates concurrent executions for identical keys
	{
		var sf singleflight.Group
		var callCount int32
		var wg sync.WaitGroup
		concurrency := 5
		results := make([]string, concurrency)

		barrier := make(chan struct{})

		for i := 0; i < concurrency; i++ {
			wg.Add(1)
			idx := i
			go func() {
				defer wg.Done()
				<-barrier
				v, err, _ := sf.Do("shared-key", func() (any, error) {
					atomic.AddInt32(&callCount, 1)
					time.Sleep(20 * time.Millisecond)
					return "shared-value", nil
				})
				if err != nil {
					return
				}
				results[idx] = v.(string)
			}()
		}

		close(barrier)
		wg.Wait()

		calls := atomic.LoadInt32(&callCount)
		if calls != 1 {
			fmt.Fprintf(os.Stderr, "FAIL: singleflight executed function %d times, expected 1\n", calls)
			os.Exit(1)
		}

		for i, res := range results {
			if res != "shared-value" {
				fmt.Fprintf(os.Stderr, "FAIL: result[%d] = %q, expected %q\n", i, res, "shared-value")
				os.Exit(1)
			}
		}
	}

	fmt.Println("PASS: golang.org/x/sync contract passed")
}

オリジンシーダー

匿名