Skip to content

[confmap] Correctly distinguish between empty and nil slices #12872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .chloggen/mx-psi_nil-empty-slices.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: bug_fix

# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
component: confmap

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Maintain nil values when marshaling or unmarshaling nil slices

# One or more tracking issues or pull requests related to the change
issues: [11882]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext: |
Previously, nil slices were converted to empty lists, which are semantically different
than a nil slice. This change makes this conversion more consistent when encoding
or decoding config, and these values are now maintained.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: []
13 changes: 12 additions & 1 deletion confmap/confmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,12 @@ func sanitizeExpanded(a any, useOriginal bool) any {
}
return c
case []any:
// If the value is nil, return nil.
var newSlice []any
if m == nil {
return newSlice
}
newSlice = make([]any, 0, len(m))
for _, e := range m {
newSlice = append(newSlice, sanitizeExpanded(e, useOriginal))
}
Expand Down Expand Up @@ -555,7 +560,13 @@ type Marshaler interface {
func zeroSliceHookFunc() mapstructure.DecodeHookFuncValue {
return func(from reflect.Value, to reflect.Value) (any, error) {
if to.CanSet() && to.Kind() == reflect.Slice && from.Kind() == reflect.Slice {
to.Set(reflect.MakeSlice(to.Type(), from.Len(), from.Cap()))
if from.IsNil() {
// input slice is nil, set output slice to nil.
to.Set(reflect.Zero(to.Type()))
} else {
// input slice is not nil, set the output slice to a new slice of the same type.
to.Set(reflect.MakeSlice(to.Type(), from.Len(), from.Cap()))
}
}

return from.Interface(), nil
Expand Down
22 changes: 22 additions & 0 deletions confmap/confmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -742,6 +742,28 @@ func TestNilValuesUnchanged(t *testing.T) {
require.Equal(t, confFromStruct.ToStringMap(), nilConf.ToStringMap())
}

func TestEmptySliceUnchanged(t *testing.T) {
type structWithSlices struct {
Strings []string `mapstructure:"strings"`
}

slicesStruct := &structWithSlices{}

nilCfg := map[string]any{
"strings": []any{},
}
nilConf := NewFromStringMap(nilCfg)
err := nilConf.Unmarshal(slicesStruct)
require.NoError(t, err)

confFromStruct := New()
err = confFromStruct.Marshal(slicesStruct)
require.NoError(t, err)

require.Equal(t, nilCfg, nilConf.ToStringMap())
require.Equal(t, nilConf.ToStringMap(), confFromStruct.ToStringMap())
}

type c struct {
Modifiers []string `mapstructure:"modifiers"`
}
Expand Down
3 changes: 1 addition & 2 deletions confmap/confmaptest/configtest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ func TestLoadConf(t *testing.T) {
func TestToStringMapSanitizeEmptySlice(t *testing.T) {
cfg, err := LoadConf(filepath.Join("testdata", "empty-slice.yaml"))
require.NoError(t, err)
var nilSlice []any
assert.Equal(t, map[string]any{"slice": nilSlice}, cfg.ToStringMap())
assert.Equal(t, map[string]any{"slice": []any{}}, cfg.ToStringMap())
}

func TestValidateProviderScheme(t *testing.T) {
Expand Down
5 changes: 5 additions & 0 deletions confmap/internal/mapstructure/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ func (e *Encoder) encodeSlice(value reflect.Value) (any, error) {
Kind: value.Kind(),
}
}

if value.IsNil() {
return []any(nil), nil
}

result := make([]any, value.Len())
for i := 0; i < value.Len(); i++ {
var err error
Expand Down
2 changes: 1 addition & 1 deletion service/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func TestConfmapMarshalConfig(t *testing.T) {
"host": "localhost",
"port": 8888,
"with_resource_constant_labels": map[string]any{
"included": []any(nil),
"included": []any{},
},
"without_scope_info": true,
"without_type_suffix": true,
Expand Down
Loading