CodeSampleX

샘플

golang.org/x/sync v0.22.0: CompareAndSwap and CompareAndDelete on syncmap.Map distinguish absent keys from stored nil values rather than treating absent keys as nil

검증된 샘플 — golang golang.org/x/sync v0.22.0: CompareAndSwap and CompareAndDelete on syncmap.Map distinguish absent keys from stored nil values rather than…

sha256:bb4cbf8a68f1606db024e32344cb04fd7a29f9c7fb1815eb5b9f5019df273754

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 go linux x64 go go gomod

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-17
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18

케이스

HOW
목표
CompareAndSwap and CompareAndDelete on syncmap.Map distinguish absent keys from stored nil values rather than treating absent keys as nil
패키지
심벌
  • syncmap.Map
  • syncmap.Map.CompareAndSwap
  • syncmap.Map.CompareAndDelete
  • syncmap.Map.Swap
  • syncmap.Map.LoadAndDelete
  • syncmap.Map.Load
  • syncmap.Map.Store
환경
go
생성일
2026-08-17T23:39:23Z

컨트랙트

  1. CompareAndSwap on an absent key returns false when old is nil, but succeeds and returns true when the key was explicitly stored with nil
  2. CompareAndDelete returns false on absent keys when old is nil, and returns true only when the key was explicitly stored with nil
  3. Load and LoadAndDelete distinguish absent keys (loaded=false) from keys explicitly stored with nil (loaded=true)
  4. Swap overwrites any existing value and returns whether the key was previously present
  5. Passing an unhashable key type such as a slice panics at runtime with hash of unhashable type
  6. CompareAndDelete and CompareAndSwap panic when comparing against an existing value of identical incomparable slice type, but return false without panic when the stored type differs

파일

  • NOTES.md
  • csx.json
  • go.mod
  • go.sum
  • syncmap_test.go

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# golang.org/x/sync syncmap.Map Semantics (v0.22.0)

A query for `golang.org/x/sync/syncmap.Map` at version 0.22.0 matches sample `sha256:039bfb8238b99b258620baa280a668e86285947c2e249eb1e2d872911fd9b248`, which verified that `syncmap.Map` is a type alias for Go's `sync.Map` rather than a generic type.

This sample explores the exact runtime semantics of `syncmap.Map` conditional atomic operations (`CompareAndSwap`, `CompareAndDelete`, `Swap`, `LoadAndDelete`, and `Load`) regarding absent keys versus explicit `nil` values, as well as runtime comparison invariants.

## Observed Behaviors and Traps

### 1. Absent Keys vs. Stored Nil Values in CompareAndSwap
- **Expectation**: Developers frequently assume `CompareAndSwap(key, nil, newValue)` operates as an "insert if absent" primitive by treating an unassigned key as having a `nil` value (similar to `AtomicReference.compareAndSet(null, v)` in other languages).
- **Reality**: In `syncmap.Map`, an unassigned key is not equal to `nil`. Calling `CompareAndSwap(key, nil, newValue)` on an absent key returns `false` and does not insert the key. It succeeds and returns `true` only if the key was explicitly stored with a value of `nil`.
- **Failure Mode**: Code attempting to use `CompareAndSwap(key, nil, val)` for atomic insertion fails silently by returning `false` without ever writing the entry.

### 2. CompareAndDelete on Absent Keys vs. Nil Values
- `CompareAndDelete(key, nil)` returns `false` on absent keys.
- When `Store(key, nil)` has been called, `CompareAndDelete(key, nil)` succeeds, returns `true`, and deletes the key.

### 3. Disambiguating Absent Keys from Stored Nil
- `Load(key)` returns `(nil, false)` when the key is absent and `(nil, true)` when the key was stored with `nil`.
- `LoadAndDelete(key)` atomically deletes the entry and returns `(nil, false)` when absent and `(nil, true)` when stored with `nil`.

### 4. Atomic Swap
- `Swap(key, newValue)` stores `newValue` and returns `(nil, false)` if the key was previously absent, or `(previousValue, true)` if the key was already present.

### 5. Runtime Panics for Incomparable Keys and Dynamic Values
- **Unhashable Keys**: Passing a non-comparable key type (such as a slice `[]int`) to any method (`Load`, `Store`, `Delete`, `Swap`, `LoadAndDelete`, `CompareAndSwap`, `CompareAndDelete`) panics at runtime with `runtime error: hash of unhashable type`.
- **Incomparable Dynamic Value Comparisons**: In `CompareAndDelete` and `CompareAndSwap`, comparing against an existing value of the same non-comparable type (e.g. `[]int`) panics with `runtime error: comparing uncomparable type`. If the stored value has a different dynamic type (e.g. comparing string against stored slice), Go interface equality rules safely return `false` without panicking.
csx.json
{"case":{"believed":"Calling CompareAndSwap with an old value of nil acts as an insert-if-absent operation by treating unassigned keys as having a nil value.","caseId":"case:sha256:19b02022dac853906df2273678e51a8334c269e85b285a371b5fb8e83367494a","contract":["CompareAndSwap on an absent key returns false when old is nil, but succeeds and returns true when the key was explicitly stored with nil","CompareAndDelete returns false on absent keys when old is nil, and returns true only when the key was explicitly stored with nil","Load and LoadAndDelete distinguish absent keys (loaded=false) from keys explicitly stored with nil (loaded=true)","Swap overwrites any existing value and returns whether the key was previously present","Passing an unhashable key type such as a slice panics at runtime with hash of unhashable type","CompareAndDelete and CompareAndSwap panic when comparing against an existing value of identical incomparable slice type, but return false without panic when the stored type differs"],"goal":"CompareAndSwap and CompareAndDelete on syncmap.Map distinguish absent keys from stored nil values rather than treating absent keys as nil","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@0.22.0"],"schemaVersion":1,"symbols":["syncmap.Map","syncmap.Map.CompareAndSwap","syncmap.Map.CompareAndDelete","syncmap.Map.Swap","syncmap.Map.LoadAndDelete","syncmap.Map.Load","syncmap.Map.Store"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"gomod","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/sync@0.22.0"],"schemaVersion":1,"symbols":["syncmap.Map","syncmap.Map.CompareAndSwap","syncmap.Map.CompareAndDelete","syncmap.Map.Swap","syncmap.Map.LoadAndDelete","syncmap.Map.Load","syncmap.Map.Store"],"verifierAdapter":"golang@1"}
go.mod
module example.com/syncmap-contract

go 1.26.0

require golang.org/x/sync v0.22.0
go.sum
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
syncmap_test.go
package contract_test

import (
	"strings"
	"testing"

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

func TestCompareAndSwapAbsentVsNilValue(t *testing.T) {
	var m syncmap.Map

	// When key is absent, CompareAndSwap with old=nil must return false.
	// An absent key is not considered equal to nil.
	if m.CompareAndSwap("key", nil, "first") {
		t.Fatal("CompareAndSwap on absent key unexpectedly returned true for old=nil")
	}

	if val, ok := m.Load("key"); ok || val != nil {
		t.Fatalf("Load on absent key returned (%v, %v); want (<nil>, false)", val, ok)
	}

	// Explicitly store nil as the value for the key.
	m.Store("key", nil)

	if val, ok := m.Load("key"); !ok || val != nil {
		t.Fatalf("Load on stored nil key returned (%v, %v); want (<nil>, true)", val, ok)
	}

	// Now that key explicitly contains nil, CompareAndSwap with old=nil must succeed.
	if !m.CompareAndSwap("key", nil, "first") {
		t.Fatal("CompareAndSwap on key with stored nil value returned false; want true")
	}

	if val, ok := m.Load("key"); !ok || val != "first" {
		t.Fatalf("Load after successful swap returned (%v, %v); want (first, true)", val, ok)
	}
}

func TestCompareAndDeleteAbsentVsNilValue(t *testing.T) {
	var m syncmap.Map

	// CompareAndDelete on absent key with old=nil returns false.
	if m.CompareAndDelete("key", nil) {
		t.Fatal("CompareAndDelete on absent key returned true for old=nil; want false")
	}

	// Explicitly store nil for key.
	m.Store("key", nil)

	// CompareAndDelete with old=nil must now find the matching nil value and delete the entry.
	if !m.CompareAndDelete("key", nil) {
		t.Fatal("CompareAndDelete on key containing stored nil returned false; want true")
	}

	if val, ok := m.Load("key"); ok || val != nil {
		t.Fatalf("Load after CompareAndDelete returned (%v, %v); want (<nil>, false)", val, ok)
	}
}

func TestLoadAndLoadAndDeleteNilDistinction(t *testing.T) {
	var m syncmap.Map

	// Missing key: Load and LoadAndDelete return loaded=false
	if val, loaded := m.Load("absent"); loaded || val != nil {
		t.Fatalf("Load(absent) returned (%v, %v); want (<nil>, false)", val, loaded)
	}
	if val, loaded := m.LoadAndDelete("absent"); loaded || val != nil {
		t.Fatalf("LoadAndDelete(absent) returned (%v, %v); want (<nil>, false)", val, loaded)
	}

	// Stored nil key: Load and LoadAndDelete return loaded=true
	m.Store("present_nil", nil)
	if val, loaded := m.Load("present_nil"); !loaded || val != nil {
		t.Fatalf("Load(present_nil) returned (%v, %v); want (<nil>, true)", val, loaded)
	}

	if val, loaded := m.LoadAndDelete("present_nil"); !loaded || val != nil {
		t.Fatalf("LoadAndDelete(present_nil) returned (%v, %v); want (<nil>, true)", val, loaded)
	}

	// After deletion, key is absent again
	if val, loaded := m.Load("present_nil"); loaded || val != nil {
		t.Fatalf("Load after LoadAndDelete returned (%v, %v); want (<nil>, false)", val, loaded)
	}
}

func TestSwapAtomicReplacement(t *testing.T) {
	var m syncmap.Map

	// Swap on absent key stores value and returns loaded=false
	if prev, loaded := m.Swap("counter", 1); loaded || prev != nil {
		t.Fatalf("Swap on absent key returned (%v, %v); want (<nil>, false)", prev, loaded)
	}

	// Swap on existing key returns old value and loaded=true
	if prev, loaded := m.Swap("counter", 2); !loaded || prev != 1 {
		t.Fatalf("Swap on existing key returned (%v, %v); want (1, true)", prev, loaded)
	}

	// Swap to nil value
	if prev, loaded := m.Swap("counter", nil); !loaded || prev != 2 {
		t.Fatalf("Swap to nil returned (%v, %v); want (2, true)", prev, loaded)
	}

	if val, ok := m.Load("counter"); !ok || val != nil {
		t.Fatalf("Load after swap to nil returned (%v, %v); want (<nil>, true)", val, ok)
	}
}

func TestUnhashableKeyPanics(t *testing.T) {
	var m syncmap.Map
	unhashableKey := []int{1, 2, 3}

	assertPanics := func(name string, fn func()) {
		t.Helper()
		defer func() {
			r := recover()
			if r == nil {
				t.Fatalf("%s with unhashable key did not panic", name)
			}
			msg := ""
			if err, ok := r.(error); ok {
				msg = err.Error()
			} else if s, ok := r.(string); ok {
				msg = s
			}
			if !strings.Contains(msg, "unhashable") && !strings.Contains(msg, "hash of unhashable type") {
				t.Fatalf("%s panicked with unexpected message: %v", name, r)
			}
		}()
		fn()
	}

	assertPanics("Load", func() { m.Load(unhashableKey) })
	assertPanics("Store", func() { m.Store(unhashableKey, "v") })
	assertPanics("Delete", func() { m.Delete(unhashableKey) })
	assertPanics("Swap", func() { m.Swap(unhashableKey, "v") })
	assertPanics("LoadAndDelete", func() { m.LoadAndDelete(unhashableKey) })
	assertPanics("CompareAndSwap", func() { m.CompareAndSwap(unhashableKey, "old", "new") })
	assertPanics("CompareAndDelete", func() { m.CompareAndDelete(unhashableKey, "old") })
}

func TestIncomparableValueComparison(t *testing.T) {
	var m syncmap.Map
	m.Store("slice_entry", []int{10, 20})

	// Comparing against an old value with a different concrete type does not panic (returns false).
	if m.CompareAndDelete("slice_entry", "string_value") {
		t.Fatal("CompareAndDelete with mismatched dynamic type returned true; want false")
	}

	if m.CompareAndSwap("slice_entry", 999, []int{30}) {
		t.Fatal("CompareAndSwap with mismatched dynamic type returned true; want false")
	}

	// Comparing against an old value of the same incomparable type ([]int) panics at runtime.
	assertIncomparablePanic := func(name string, fn func()) {
		t.Helper()
		defer func() {
			r := recover()
			if r == nil {
				t.Fatalf("%s with incomparable old value did not panic", name)
			}
			msg := ""
			if err, ok := r.(error); ok {
				msg = err.Error()
			} else if s, ok := r.(string); ok {
				msg = s
			}
			if !strings.Contains(msg, "uncomparable") && !strings.Contains(msg, "comparing uncomparable type") {
				t.Fatalf("%s panicked with unexpected message: %v", name, r)
			}
		}()
		fn()
	}

	assertIncomparablePanic("CompareAndDelete", func() {
		m.CompareAndDelete("slice_entry", []int{10, 20})
	})

	assertIncomparablePanic("CompareAndSwap", func() {
		m.CompareAndSwap("slice_entry", []int{10, 20}, []int{30})
	})
}

오리진 시더

csx-seed