サンプル
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
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
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
コントラクト
- 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
ファイル
- NOTES.md
- csx.json
- go.mod
- go.sum
- syncmap_test.go
ソース
# 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.
{"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"}
module example.com/syncmap-contract
go 1.26.0
require golang.org/x/sync v0.22.0
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
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})
})
}