From 03a6b19cc614432a2c8db694cf15746466a52b2d Mon Sep 17 00:00:00 2001 From: WitteShadovv Date: Fri, 16 Oct 2026 13:32:49 +0200 Subject: [PATCH] fix(config): make flattening deterministic for duplicate keys When a config file defines the same option both nested and flattened, e.g. {"core": {"devMode": true}, "core/devMode": false}, flattenMap iterated over the map in random order, so the value in use changed between restarts. Iterate over the keys in sorted order. A flattened key sorts after its nested parent ("core" < "core/devMode"), so the flattened spelling consistently takes precedence. --- base/config/persistence.go | 10 +++++++++- base/config/persistence_test.go | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/base/config/persistence.go b/base/config/persistence.go index 87fd9e91c..8fd2de97d 100644 --- a/base/config/persistence.go +++ b/base/config/persistence.go @@ -3,8 +3,10 @@ package config import ( "encoding/json" "fmt" + "maps" "os" "path" + "slices" "strings" "sync" @@ -114,8 +116,14 @@ func Flatten(config map[string]interface{}) (flattenedConfig map[string]interfac return flattenedConfig } +// flattenMap adds all values of subMap to rootMap, joining nested keys with +// "/" and prefixing them with subKey. Keys are processed in sorted order to get +// a deterministic result when the same option is defined both nested and +// flattened, e.g. {"a": {"b": 1}, "a/b": 2}. A flattened key sorts after its +// nested parent and therefore takes precedence. func flattenMap(rootMap, subMap map[string]interface{}, subKey string) { - for key, entry := range subMap { + for _, key := range slices.Sorted(maps.Keys(subMap)) { + entry := subMap[key] // get next level key subbedKey := path.Join(subKey, key) diff --git a/base/config/persistence_test.go b/base/config/persistence_test.go index 982835c3f..752e0c40d 100644 --- a/base/config/persistence_test.go +++ b/base/config/persistence_test.go @@ -95,3 +95,20 @@ func TestConfigCleaning(t *testing.T) { t.Errorf("should be empty: %+v", configHier) } } + +// TestFlattenDuplicateKeys checks that an option defined both nested and +// flattened always resolves to the same value, independent of the random map +// iteration order. +func TestFlattenDuplicateKeys(t *testing.T) { + t.Parallel() + + for range 100 { + configFlat, err := JSONToMap([]byte(`{"core": {"devMode": false}, "core/devMode": true}`)) + if err != nil { + t.Fatal(err) + } + if value := configFlat["core/devMode"]; value != true { + t.Fatalf("flattened key should take precedence over nested key, got %v", value) + } + } +}