CodeSampleX

샘플

sigs.k8s.io/yaml v1.4.0: Preserve 64-bit integer precision and decode untyped YAML numbers in sigs.k8s.io/yaml using JSONOpt UseNumber

검증된 샘플 — golang sigs.k8s.io/yaml v1.4.0: Preserve 64-bit integer precision and decode untyped YAML numbers in sigs.k8s.io/yaml using JSONOpt UseNumber. go…

sha256:b26c17ad7a69e13b5a7bcb2b075acafb7bf6062ad327a7370e9eea24f586f98e

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
3
빌드한 서명 키
3
선언된 환경 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-16
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
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-09-08

케이스

HOW
목표
Preserve 64-bit integer precision and decode untyped YAML numbers in sigs.k8s.io/yaml using JSONOpt UseNumber
패키지
심벌
  • sigs.k8s.io/yaml.Unmarshal
  • sigs.k8s.io/yaml.JSONOpt
환경
go
생성일
2026-08-16T13:22:35Z

컨트랙트

  1. assert default Unmarshal silently truncates integers above 2^53 into float64 whereas JSONOpt UseNumber preserves exact int64 values as json.Number
  2. assert types implementing yaml.Unmarshaler are ignored while json.Unmarshaler and encoding.TextUnmarshaler are executed
  3. assert YAML numbers and booleans are coerced to strings when target struct fields are string type
  4. assert unmarshaling into map[interface{}]interface{} fails with JSON unmarshal error unlike standard YAML decoders

파일

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

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

소스

NOTES.md
# Notes: sigs.k8s.io/yaml JSONOpt Configuration and Interface Traps

## Prior Solution Search
`search_known_solution` returned candidate sample sha256:03d14e2883c81e3c8dd5a947bbd6bf84b0c7682b5e2b5e0adf9b88c3287d4652 which covers JSON struct tag precedence and duplicate key rejection under UnmarshalStrict.

This sample addresses a different set of traps:
1. Untyped 64-bit integer precision loss (> 2^53) during standard `Unmarshal` and its remedy using the `JSONOpt` `UseNumber` decoder option.
2. Silent omission of the standard `yaml.Unmarshaler` interface (`UnmarshalYAML`) in favor of `json.Unmarshaler` and `encoding.TextUnmarshaler`.
3. Automatic string coercion for primitive numbers and booleans on struct fields.
4. Failure to decode into untyped `map[interface{}]interface{}`.

## How the wrong version fails
It fails silently with a green build: unmarshaling 64-bit integers > 2^53 into untyped maps silently truncates and corrupts numeric precision via float64 conversion, and implementing yaml.Unmarshaler is silently skipped without error.
csx.json
{"case":{"believed":"sigs.k8s.io/yaml.Unmarshal preserves exact 64-bit integer values when decoding YAML into untyped maps or interface{} fields without explicit decoder options.","caseId":"case:sha256:b68086867fa6604e2c9bf8c24d71af0fdade250835f6ef51bfc10eb159bde46e","contract":["assert default Unmarshal silently truncates integers above 2^53 into float64 whereas JSONOpt UseNumber preserves exact int64 values as json.Number","assert types implementing yaml.Unmarshaler are ignored while json.Unmarshaler and encoding.TextUnmarshaler are executed","assert YAML numbers and booleans are coerced to strings when target struct fields are string type","assert unmarshaling into map[interface{}]interface{} fails with JSON unmarshal error unlike standard YAML decoders"],"goal":"Preserve 64-bit integer precision and decode untyped YAML numbers in sigs.k8s.io/yaml using JSONOpt UseNumber","kind":"HOW","packages":["pkg:golang/sigs.k8s.io/yaml@v1.4.0"],"schemaVersion":1,"symbols":["sigs.k8s.io/yaml.Unmarshal","sigs.k8s.io/yaml.JSONOpt"]},"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/sigs.k8s.io/yaml@v1.4.0"],"schemaVersion":1,"symbols":["sigs.k8s.io/yaml.Unmarshal","sigs.k8s.io/yaml.JSONOpt"],"verifierAdapter":"golang@1"}
go.mod
module testyaml

go 1.26.5

require sigs.k8s.io/yaml v1.4.0
go.sum
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=
sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=
yaml_config_test.go
package testyaml

import (
	"encoding/json"
	"fmt"
	"strings"
	"testing"

	k8syaml "sigs.k8s.io/yaml"
)

// SnowflakeID > 2^53 (9007199254740992) where float64 loses precision.
const testInt64Value int64 = 9007199254740993

type YamlCustomObject struct {
	Value  string `json:"value"`
	Called bool   `json:"-"`
}

func (y *YamlCustomObject) UnmarshalYAML(unmarshal func(interface{}) error) error {
	y.Called = true
	var raw struct {
		Value string `yaml:"value"`
	}
	if err := unmarshal(&raw); err != nil {
		return err
	}
	y.Value = "custom_yaml:" + raw.Value
	return nil
}

type JsonUnmarshalerType struct {
	Called bool
	Value  string
}

func (j *JsonUnmarshalerType) UnmarshalJSON(data []byte) error {
	j.Called = true
	var raw struct {
		Value string `json:"value"`
	}
	if err := json.Unmarshal(data, &raw); err != nil {
		return err
	}
	j.Value = "json:" + raw.Value
	return nil
}

type TextUnmarshalerType struct {
	Called bool
	Value  string
}

func (t *TextUnmarshalerType) UnmarshalText(text []byte) error {
	t.Called = true
	t.Value = "text:" + string(text)
	return nil
}

type CoercionConfig struct {
	Port    string `json:"port"`
	Enabled string `json:"enabled"`
	Score   string `json:"score"`
}

func TestUntypedLargeIntegerPrecisionAndUseNumber(t *testing.T) {
	// A naive model assumes sigs.k8s.io/yaml preserves exact integer values
	// when decoding untyped YAML numbers into map[string]any or any.
	// In reality, sigs.k8s.io/yaml unmarshals through encoding/json, which
	// decodes untyped numbers as float64, causing silent loss of precision
	// for 64-bit integers > 2^53 (9007199254740992).
	yamlInput := []byte(fmt.Sprintf("id: %d\n", testInt64Value))

	// Case 1: Default Unmarshal without options
	var defaultMap map[string]any
	if err := k8syaml.Unmarshal(yamlInput, &defaultMap); err != nil {
		t.Fatalf("unexpected unmarshal error: %v", err)
	}

	val, ok := defaultMap["id"]
	if !ok {
		t.Fatal("expected 'id' key in unmarshaled map")
	}

	floatVal, isFloat := val.(float64)
	if !isFloat {
		t.Fatalf("expected default unmarshaled number to be float64, got %T", val)
	}

	// 9007199254740993 rounds to 9007199254740992 in float64
	if int64(floatVal) == testInt64Value {
		t.Fatalf("expected float64 to lose precision for %d, but got exact match", testInt64Value)
	}
	if int64(floatVal) != 9007199254740992 {
		t.Fatalf("expected corrupted float64 value 9007199254740992, got %d", int64(floatVal))
	}

	// Case 2: Unmarshal with JSONOpt UseNumber setting
	useNumberOpt := func(d *json.Decoder) *json.Decoder {
		d.UseNumber()
		return d
	}

	var optMap map[string]any
	if err := k8syaml.Unmarshal(yamlInput, &optMap, useNumberOpt); err != nil {
		t.Fatalf("unexpected unmarshal error with UseNumber: %v", err)
	}

	numVal, isNumber := optMap["id"].(json.Number)
	if !isNumber {
		t.Fatalf("expected json.Number when UseNumber option is provided, got %T", optMap["id"])
	}

	parsedInt64, err := numVal.Int64()
	if err != nil {
		t.Fatalf("failed to parse json.Number as int64: %v", err)
	}
	if parsedInt64 != testInt64Value {
		t.Fatalf("expected preserved int64 %d, got %d", testInt64Value, parsedInt64)
	}
}

func TestUnmarshalerInterfacePrecedence(t *testing.T) {
	// A naive developer expects UnmarshalYAML to be called by a YAML unmarshaler.
	// However, sigs.k8s.io/yaml converts YAML to JSON first and calls json.Unmarshal,
	// so yaml.Unmarshaler is completely ignored while json.Unmarshaler and
	// encoding.TextUnmarshaler are executed.

	type Container struct {
		YamlCustom YamlCustomObject    `json:"yaml_custom"`
		JsonCustom JsonUnmarshalerType `json:"json_custom"`
		TextCustom TextUnmarshalerType `json:"text_custom"`
	}

	yamlInput := []byte("yaml_custom:\n  value: hello\njson_custom:\n  value: world\ntext_custom: textval\n")
	var c Container
	if err := k8syaml.Unmarshal(yamlInput, &c); err != nil {
		t.Fatalf("unmarshal error: %v", err)
	}

	// yaml.Unmarshaler is NOT called; default JSON unmarshaling was used
	if c.YamlCustom.Called {
		t.Fatal("expected YamlCustomObject.UnmarshalYAML to NOT be called by sigs.k8s.io/yaml")
	}
	if c.YamlCustom.Value != "hello" {
		t.Fatalf("expected raw json unmarshaled value 'hello', got %q", c.YamlCustom.Value)
	}

	// json.Unmarshaler IS called
	if !c.JsonCustom.Called {
		t.Fatal("expected JsonUnmarshalerType.UnmarshalJSON to be called")
	}
	if c.JsonCustom.Value != "json:world" {
		t.Fatalf("expected 'json:world', got %q", c.JsonCustom.Value)
	}

	// encoding.TextUnmarshaler IS called
	if !c.TextCustom.Called {
		t.Fatal("expected TextUnmarshalerType.UnmarshalText to be called")
	}
	if c.TextCustom.Value != "text:textval" {
		t.Fatalf("expected 'text:textval', got %q", c.TextCustom.Value)
	}
}

func TestSilentPrimitiveToStringCoercion(t *testing.T) {
	// Unlike standard JSON/YAML unmarshalers that return type errors when unmarshaling
	// primitives into string fields, sigs.k8s.io/yaml automatically coerces numbers
	// and booleans into strings when the destination struct field is a string.
	yamlInput := []byte("port: 8080\nenabled: true\nscore: 98.5\n")

	var cfg CoercionConfig
	if err := k8syaml.Unmarshal(yamlInput, &cfg); err != nil {
		t.Fatalf("unexpected unmarshal error: %v", err)
	}

	if cfg.Port != "8080" {
		t.Fatalf("expected coerced string '8080', got %q", cfg.Port)
	}
	if cfg.Enabled != "true" {
		t.Fatalf("expected coerced string 'true', got %q", cfg.Enabled)
	}
	if cfg.Score != "98.5" {
		t.Fatalf("expected coerced string '98.5', got %q", cfg.Score)
	}
}

func TestMapInterfaceInterfaceRejected(t *testing.T) {
	// Standard yaml decoders (yaml.v2 / yaml.v3) decode maps into map[interface{}]interface{}.
	// sigs.k8s.io/yaml fails because encoding/json cannot unmarshal JSON objects into map[interface{}]interface{}.
	yamlInput := []byte("host: server.example.com\n")

	var m map[interface{}]interface{}
	err := k8syaml.Unmarshal(yamlInput, &m)
	if err == nil {
		t.Fatal("expected Unmarshal into map[interface{}]interface{} to fail")
	}
	if !strings.Contains(err.Error(), "map[interface {}]interface {}") {
		t.Fatalf("expected map[interface{}]interface{} error, got: %v", err)
	}
}

오리진 시더

csx-seed