CodeSampleX

샘플

golang.org/x/sync v0.21.0: singleflight.Result

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

sha256:72cfbc6fb7b88af58ced7f2c820c2db09e6adfcf4eda0d1891b0922e200b82f2

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

케이스

HOW
목표
verify golang.org/x/sync/singleflight.Result in pkg:golang/golang.org/x/sync@v0.21.0
패키지
심벌
  • golang.org/x/sync/singleflight.Result
환경
go 1.26.6
생성일
2026-10-13T02:38:15Z

컨트랙트

  1. singleflight.Result struct has accessible Val, Err, and Shared fields and can be directly instantiated
  2. singleflight.Group.DoChan returns a channel delivering a singleflight.Result with Val and nil Err when fn succeeds
  3. singleflight.Group.DoChan delivers a singleflight.Result with non-nil Err when fn returns an error
  4. singleflight.Result.Shared is false for an unshared execution and true when multiple callers share execution
  5. singleflight.Group.DoChan delivers identical singleflight.Result values to multiple concurrent callers without interfering

파일

  • 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/singleflight.Result 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/singleflight.Result

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:a539cbb3da54b8fbcb6eaa3e092c10ba1b080d86f5b9f659f4a6491aa09059e5","contract":["singleflight.Result struct has accessible Val, Err, and Shared fields and can be directly instantiated","singleflight.Group.DoChan returns a channel delivering a singleflight.Result with Val and nil Err when fn succeeds","singleflight.Group.DoChan delivers a singleflight.Result with non-nil Err when fn returns an error","singleflight.Result.Shared is false for an unshared execution and true when multiple callers share execution","singleflight.Group.DoChan delivers identical singleflight.Result values to multiple concurrent callers without interfering"],"goal":"verify golang.org/x/sync/singleflight.Result 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/singleflight.Result"]},"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/singleflight.Result"],"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 (
	"fmt"
	"sync"
	"time"

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

func fetchData(id int) (string, error) {
	time.Sleep(50 * time.Millisecond)
	return fmt.Sprintf("payload-for-item-%d", id), nil
}

func main() {
	var g singleflight.Group

	// 1. Direct Result construction and field inspection
	localResult := singleflight.Result{
		Val:    "initial-value",
		Err:    nil,
		Shared: false,
	}
	fmt.Printf("Direct Result: Val=%v, Err=%v, Shared=%t\n", localResult.Val, localResult.Err, localResult.Shared)

	// 2. Asynchronous execution with DoChan returning <-chan singleflight.Result
	resultChan := g.DoChan("item:100", func() (any, error) {
		return fetchData(100)
	})

	res := <-resultChan
	fmt.Printf("DoChan Result: Val=%v, Err=%v, Shared=%t\n", res.Val, res.Err, res.Shared)

	// 3. Concurrent callers sharing execution and observing Result.Shared = true
	var wg sync.WaitGroup
	const callers = 3
	wg.Add(callers)

	for i := 0; i < callers; i++ {
		callerID := i + 1
		go func() {
			defer wg.Done()
			ch := g.DoChan("shared-item:200", func() (any, error) {
				return fetchData(200)
			})
			r := <-ch
			fmt.Printf("Caller %d received Result: Val=%v, Shared=%t\n", callerID, r.Val, r.Shared)
		}()
	}

	wg.Wait()
	fmt.Println("golang.org/x/sync/singleflight.Result demonstrated successfully.")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/sync/singleflight.Result 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/singleflight.Result"
  ]
}
test/contract.go
package main

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

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

func main() {
	// Assertion 1: singleflight.Result struct has accessible Val, Err, and Shared fields and can be directly instantiated
	{
		r := singleflight.Result{
			Val:    "test-val",
			Err:    nil,
			Shared: true,
		}
		if r.Val != "test-val" || r.Err != nil || !r.Shared {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: direct instantiation fields mismatch: %+v\n", r)
			os.Exit(1)
		}

		var zero singleflight.Result
		if zero.Val != nil || zero.Err != nil || zero.Shared != false {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: zero value fields mismatch: %+v\n", zero)
			os.Exit(1)
		}
	}

	// Assertion 2: singleflight.Group.DoChan returns a channel delivering a singleflight.Result with Val and nil Err when fn succeeds
	{
		var g singleflight.Group
		ch := g.DoChan("key-success", func() (interface{}, error) {
			return 12345, nil
		})
		if ch == nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: DoChan returned nil channel\n")
			os.Exit(1)
		}

		res := <-ch
		if res.Val != 12345 {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected Val 12345, got %v\n", res.Val)
			os.Exit(1)
		}
		if res.Err != nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected nil Err, got %v\n", res.Err)
			os.Exit(1)
		}
	}

	// Assertion 3: singleflight.Group.DoChan delivers a singleflight.Result with non-nil Err when fn returns an error
	{
		var g singleflight.Group
		expectedErr := errors.New("simulated failure")
		ch := g.DoChan("key-error", func() (interface{}, error) {
			return nil, expectedErr
		})

		res := <-ch
		if res.Val != nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected nil Val on error, got %v\n", res.Val)
			os.Exit(1)
		}
		if !errors.Is(res.Err, expectedErr) {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected %v, got %v\n", expectedErr, res.Err)
			os.Exit(1)
		}
	}

	// Assertion 4: singleflight.Result.Shared is false for an unshared execution and true when multiple callers share execution
	{
		var g singleflight.Group

		// Unshared case:
		chSolo := g.DoChan("key-solo", func() (interface{}, error) {
			return "solo", nil
		})
		resSolo := <-chSolo
		if resSolo.Shared {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected Shared=false for solo caller\n")
			os.Exit(1)
		}

		// Shared case:
		started := make(chan struct{})
		release := make(chan struct{})

		ch1 := g.DoChan("key-shared", func() (interface{}, error) {
			close(started)
			<-release
			return "shared", nil
		})

		<-started
		ch2 := g.DoChan("key-shared", func() (interface{}, error) {
			return "unreached", nil
		})

		close(release)

		res1 := <-ch1
		res2 := <-ch2

		if !res1.Shared || !res2.Shared {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected Shared=true for both callers, got res1=%t, res2=%t\n", res1.Shared, res2.Shared)
			os.Exit(1)
		}
	}

	// Assertion 5: singleflight.Group.DoChan delivers identical singleflight.Result values to multiple concurrent callers without interfering
	{
		var g singleflight.Group
		var execCount int32
		started := make(chan struct{})
		release := make(chan struct{})

		const numCallers = 4
		channels := make([]<-chan singleflight.Result, numCallers)

		channels[0] = g.DoChan("key-multi", func() (interface{}, error) {
			atomic.AddInt32(&execCount, 1)
			close(started)
			<-release
			return "consistent-payload", nil
		})

		<-started
		for i := 1; i < numCallers; i++ {
			channels[i] = g.DoChan("key-multi", func() (interface{}, error) {
				atomic.AddInt32(&execCount, 1)
				return "unexpected", nil
			})
		}

		close(release)

		for i, ch := range channels {
			r := <-ch
			if r.Val != "consistent-payload" || r.Err != nil || !r.Shared {
				fmt.Fprintf(os.Stderr, "assertion 5 failed: caller %d got inconsistent Result: %+v\n", i, r)
				os.Exit(1)
			}
		}

		if got := atomic.LoadInt32(&execCount); got != 1 {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected exactly 1 execution, got %d\n", got)
			os.Exit(1)
		}
	}

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

오리진 시더

익명