Skip to content

Commit fc96fff

Browse files
denikIsaac
andcommitted
Fix codex review findings
- configsync: compare int and int64 values as equal when restoring variable references (variables decode as int, remote fields are int64). - schema annotations: merge object/sequence defaults as documented; accept an empty annotations file. - python mutator: use ResourceKeySet.AddPattern instead of a duplicate helper. - structvar.Set: don't rewrite an unchanged leaf location node (avoids cloning every ancestor per write). - ResolveConfigAgainstState: resolve all references in one call so lookups are shared. Co-authored-by: Isaac <no-reply@databricks.com>
1 parent a6077a6 commit fc96fff

9 files changed

Lines changed: 128 additions & 37 deletions

File tree

‎bundle/config/mutator/python/apply_python_output.go‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,6 @@ func applyPythonOutput(root, output structvar.View) (*structvar.OverridePlan, ap
3333
return plan, result, nil
3434
}
3535

36-
// addResourceKeys adds the keys of the resources in root that match pattern.
37-
func addResourceKeys(set resourcemutator.ResourceKeySet, pattern *structpath.PatternNode, root structvar.View) error {
38-
return structvar.ForEach(root, pattern, func(np *structpath.PathNode, _ structvar.View) error {
39-
set.AddResourceKey(resourcemutator.ResourceKey{Type: np.KeyAt(1), Name: np.KeyAt(2)})
40-
return nil
41-
})
42-
}
43-
4436
func createOverrideVisitor(leftRoot, rightRoot structvar.View) (applyPythonOutputResult, structvar.OverrideVisitor) {
4537
resourcesPath := structpath.MustParsePath("resources")
4638
deleted := resourcemutator.NewResourceKeySet()
@@ -66,7 +58,7 @@ func createOverrideVisitor(leftRoot, rightRoot structvar.View) (applyPythonOutpu
6658
// leftRoot: {"bundle": ..., "resources": ...},
6759
// rightRoot: {"bundle": ...}
6860

69-
return addResourceKeys(deleted,
61+
return deleted.AddPattern(
7062
structpath.MustParsePattern("resources.*.*"),
7163
leftRoot,
7264
)
@@ -77,7 +69,7 @@ func createOverrideVisitor(leftRoot, rightRoot structvar.View) (applyPythonOutpu
7769
// leftRoot: {"resources": { "jobs": ..., "pipeline": ...}}},
7870
// rightRoot: {"resources": { "jobs": ...}}},
7971

80-
return addResourceKeys(deleted,
72+
return deleted.AddPattern(
8173
structpath.NewPatternDotStar(structpath.NewPatternStringKey(structpath.MustParsePattern("resources"), np.KeyAt(1))),
8274
leftRoot,
8375
)
@@ -109,7 +101,7 @@ func createOverrideVisitor(leftRoot, rightRoot structvar.View) (applyPythonOutpu
109101
// leftRoot: {"bundle": ..., }
110102
// rightRoot: {"bundle": ..., "resources": {...} }
111103

112-
return addResourceKeys(added,
104+
return added.AddPattern(
113105
structpath.MustParsePattern("resources.*.*"),
114106
rightRoot,
115107
)
@@ -120,7 +112,7 @@ func createOverrideVisitor(leftRoot, rightRoot structvar.View) (applyPythonOutpu
120112
// leftRoot: {"resources": { }}
121113
// rightRoot: {"resources": { "jobs": {...} }}
122114

123-
return addResourceKeys(added,
115+
return added.AddPattern(
124116
structpath.NewPatternDotStar(structpath.NewPatternStringKey(structpath.MustParsePattern("resources"), np.KeyAt(1))),
125117
rightRoot,
126118
)
@@ -156,7 +148,7 @@ func createOverrideVisitor(leftRoot, rightRoot structvar.View) (applyPythonOutpu
156148
// leftRoot: {"bundle": ..., "resources": null }
157149
// rightRoot: {"bundle": ..., "resources": {...} }
158150

159-
return addResourceKeys(added,
151+
return added.AddPattern(
160152
structpath.MustParsePattern("resources.*.*"),
161153
rightRoot,
162154
)
@@ -167,7 +159,7 @@ func createOverrideVisitor(leftRoot, rightRoot structvar.View) (applyPythonOutpu
167159
// leftRoot: {"resources": { "jobs": null }}
168160
// rightRoot: {"resources": { "jobs": {...} }}
169161

170-
return addResourceKeys(added,
162+
return added.AddPattern(
171163
structpath.NewPatternDotStar(structpath.NewPatternStringKey(structpath.MustParsePattern("resources"), np.KeyAt(1))),
172164
rightRoot,
173165
)

‎bundle/configsync/variables.go‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package configsync
33
import (
44
"context"
55
"errors"
6+
"reflect"
67
"strings"
78

89
"github.com/databricks/cli/bundle"
@@ -297,7 +298,7 @@ func restoreFromSiblingsAt(value any, siblings []structvar.View, resolved resolv
297298
if !found {
298299
continue
299300
}
300-
if rv == value {
301+
if equalValues(rv, value) {
301302
refs[s] = struct{}{}
302303
}
303304
} else if isStr && structvar.ContainsVariableReference(s) {
@@ -360,7 +361,7 @@ func matchAnyVariable(remoteValue any, resolved resolvedConfig) (string, bool) {
360361
v := variable.Get("value")
361362
switch v.Kind() {
362363
case structvar.KindString, structvar.KindInt, structvar.KindBool:
363-
if v.AsAny() == remoteValue {
364+
if equalValues(v.AsAny(), remoteValue) {
364365
match = pathToRef(structpath.NewStringKey(varPrefix, name))
365366
count++
366367
}
@@ -400,7 +401,7 @@ func matchOriginalRef(remoteValue any, preResolved structvar.View, resolved reso
400401
return "", false
401402
}
402403

403-
if resolvedV == remoteValue {
404+
if equalValues(resolvedV, remoteValue) {
404405
return s, true
405406
}
406407
return "", false
@@ -580,3 +581,25 @@ func sequenceSiblings(preResolved structvar.View, fieldPath string) ([]structvar
580581
}
581582
return seq, true
582583
}
584+
585+
// equalValues reports whether two configuration values are equal, treating integers of
586+
// different Go types as equal: variables decoded from YAML hold int, while typed
587+
// fields of the remote resource hold int64.
588+
func equalValues(a, b any) bool {
589+
ai, aok := asInt64(a)
590+
bi, bok := asInt64(b)
591+
if aok || bok {
592+
return aok && bok && ai == bi
593+
}
594+
return a == b
595+
}
596+
597+
func asInt64(v any) (int64, bool) {
598+
rv := reflect.ValueOf(v)
599+
switch rv.Kind() {
600+
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
601+
return rv.Int(), true
602+
default:
603+
return 0, false
604+
}
605+
}

‎bundle/configsync/variables_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,15 @@ func TestRestoreFromSiblings_ValueMatchesVariableButDifferentPath(t *testing.T)
8585
// TestRestoreFromSiblings_AmbiguousAcrossSiblings fences the multi-variable
8686
// same-value rule: when two siblings use different variables at the same
8787
// relative path that both resolve to the same value, restoration is skipped.
88+
func TestRestoreFromSiblings_IntVariableMatchesInt64Field(t *testing.T) {
89+
// The variable decodes from YAML as int; the remote field is a typed int64.
90+
siblings := tasksView(t, `task_key: main, max_retries: "${var.retry_count}"`)
91+
resolved := variablesConfig(t, map[string]any{"retry_count": 5})
92+
value := map[string]any{"task_key": "other", "max_retries": int64(5)}
93+
result := restoreFromSiblings(value, siblings, resolved, &RestoreStats{}).(map[string]any)
94+
assert.Equal(t, "${var.retry_count}", result["max_retries"])
95+
}
96+
8897
func TestRestoreFromSiblings_AmbiguousAcrossSiblings(t *testing.T) {
8998
siblings := tasksView(t, `task_key: "${var.landing_schema}"`, `task_key: "${var.curated_schema}"`)
9099
resolved := variablesConfig(t, map[string]any{"landing_schema": "raw_data", "curated_schema": "raw_data"})

‎bundle/direct/resolve_config.go‎

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package direct
22

33
import (
44
"fmt"
5+
"maps"
6+
"slices"
57

68
"github.com/databricks/cli/bundle/config"
79
"github.com/databricks/cli/libs/structs/structaccess"
@@ -32,13 +34,10 @@ func (b *DeploymentBundle) ResolveConfigAgainstState(cfg *config.Root, target *s
3234
return fmt.Errorf("resource %s not found in configuration", target)
3335
}
3436

35-
// Each string is resolved on its own (references only point at other paths), then
36-
// written back; collect first because writing changes the view.
37-
type update struct {
38-
path *structpath.PathNode
39-
value any
40-
}
41-
var updates []update
37+
// Collect every reference string first: resolving them in one call shares the
38+
// lookups, and writing back changes the view.
39+
templates := map[string]structvar.Template{}
40+
paths := map[string]*structpath.PathNode{}
4241

4342
lookup := func(path *structpath.PathNode) (structvar.View, error) {
4443
if !path.HasPrefix(resourcesPrefix) {
@@ -67,22 +66,28 @@ func (b *DeploymentBundle) ResolveConfigAgainstState(cfg *config.Root, target *s
6766
return nil
6867
}
6968
key := p.String()
70-
out, err := structvar.Resolve(map[string]structvar.Template{key: {Value: s}}, lookup)
71-
if err != nil {
72-
return err
73-
}
74-
if resolved, ok := out[key]; ok {
75-
updates = append(updates, update{structpath.Join(target, p.AsSlice()...), resolved.AsAny()})
76-
}
69+
templates[key] = structvar.Template{Value: s}
70+
paths[key] = structpath.Join(target, p.AsSlice()...)
7771
return nil
7872
})
7973
if err != nil {
8074
return err
8175
}
8276

83-
for _, u := range updates {
77+
resolved, err := structvar.Resolve(templates, lookup)
78+
if err != nil {
79+
return err
80+
}
81+
82+
// Snapshot all values before writing: a resolved view may point into the configuration.
83+
values := map[string]any{}
84+
for key, v := range resolved {
85+
values[key] = v.AsAny()
86+
}
87+
for _, key := range slices.Sorted(maps.Keys(values)) {
88+
value := values[key]
8489
// Decode converts like loading did, e.g. a string id into an int job_id.
85-
diags, err := cfg.Decode(u.path, structvar.NewView(&u.value, nil, nil))
90+
diags, err := cfg.Decode(paths[key], structvar.NewView(&value, nil, nil))
8691
if err != nil {
8792
return err
8893
}

‎bundle/internal/schema/annotations.go‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ package main
22

33
import (
44
"fmt"
5+
"maps"
56
"reflect"
67
"regexp"
8+
"slices"
79
"strings"
810

911
"github.com/databricks/cli/bundle/internal/annotation"
@@ -95,6 +97,8 @@ func mergeDescriptor(a, b annotation.Descriptor) annotation.Descriptor {
9597
case g.IsZero():
9698
case f.Kind() == reflect.Slice:
9799
f.Set(reflect.AppendSlice(reflect.AppendSlice(reflect.Zero(f.Type()), f), g))
100+
case f.Kind() == reflect.Interface:
101+
f.Set(reflect.ValueOf(mergeAny(f.Interface(), g.Interface())))
98102
case f.Kind() == reflect.Map:
99103
m := reflect.MakeMap(f.Type())
100104
for _, v := range []reflect.Value{f, g} {
@@ -110,6 +114,28 @@ func mergeDescriptor(a, b annotation.Descriptor) annotation.Descriptor {
110114
return a
111115
}
112116

117+
// mergeAny merges b over a like mergeDescriptor merges fields: maps merge by key
118+
// (recursively), sequences concatenate and other values are replaced.
119+
func mergeAny(a, b any) any {
120+
switch bv := b.(type) {
121+
case map[string]any:
122+
av, ok := a.(map[string]any)
123+
if !ok {
124+
return b
125+
}
126+
out := maps.Clone(av)
127+
for k, v := range bv {
128+
out[k] = mergeAny(av[k], v)
129+
}
130+
return out
131+
case []any:
132+
if av, ok := a.([]any); ok {
133+
return slices.Concat(av, bv)
134+
}
135+
}
136+
return b
137+
}
138+
113139
func (d *annotationHandler) addAnnotations(typ reflect.Type, s jsonschema.Schema) jsonschema.Schema {
114140
refPath := getPath(typ)
115141
shouldHandle := strings.HasPrefix(refPath, "github.com")

‎bundle/internal/schema/annotations_file.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,10 @@ func loadAnnotationsFile(path string, g *typeGraph) (annotation.File, []string,
153153
if err != nil {
154154
return nil, nil, err
155155
}
156+
if v == nil {
157+
// An empty document has no annotations.
158+
return annotation.File{}, nil, nil
159+
}
156160

157161
l := &fileLoader{graph: g, data: annotation.File{}}
158162
err = l.block(v, g.root, "")

‎bundle/internal/schema/annotations_file_test.go‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,15 @@ func TestAnnotationsFileDetachedEntries(t *testing.T) {
167167
"github.com/databricks/cli/no/such.Type: field",
168168
}, detached)
169169
}
170+
171+
func TestAnnotationsFileEmpty(t *testing.T) {
172+
g, err := newTypeGraph(reflect.TypeFor[tgRoot]())
173+
require.NoError(t, err)
174+
path := filepath.Join(t.TempDir(), "annotations.yml")
175+
require.NoError(t, os.WriteFile(path, []byte("# no annotations yet\n"), 0o644))
176+
177+
data, unknown, err := loadAnnotationsFile(path, g)
178+
require.NoError(t, err)
179+
assert.Empty(t, data)
180+
assert.Empty(t, unknown)
181+
}

‎bundle/internal/schema/annotations_test.go‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,3 +270,16 @@ func TestBuildEnumDescriptions(t *testing.T) {
270270
assert.Equal(t, []string{"[Public Preview]", "", "[Beta]"}, got)
271271
})
272272
}
273+
274+
func TestMergeAnnotationFilesMergesDefaults(t *testing.T) {
275+
a := annotation.File{}
276+
a.SetField("t", "f", annotation.Descriptor{Default: map[string]any{"a": 1, "nested": map[string]any{"x": 1}}})
277+
a.SetField("t", "g", annotation.Descriptor{Default: []any{1}})
278+
b := annotation.File{}
279+
b.SetField("t", "f", annotation.Descriptor{Default: map[string]any{"b": 2, "nested": map[string]any{"y": 2}}})
280+
b.SetField("t", "g", annotation.Descriptor{Default: []any{2}})
281+
282+
merged := mergeAnnotationFiles(a, b)
283+
assert.Equal(t, map[string]any{"a": 1, "b": 2, "nested": map[string]any{"x": 1, "y": 2}}, merged["t"].Fields["f"].Default)
284+
assert.Equal(t, []any{1, 2}, merged["t"].Fields["g"].Default)
285+
}

‎libs/structs/structvar/write.go‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,18 @@ func (sv *StructVar) Set(path *structpath.PathNode, value any) error {
3636
}
3737
sv.Refs = withoutRefs(sv.Refs, path)
3838
// The node marks the value as present even if it is zero (e.g. an empty struct).
39-
var locs *Locations
40-
if value != nil {
41-
locs = (*Locations)(nil).WithLocations(sv.Locations.At(path))
39+
// A leaf node is already what we would write; skip rewriting the tree, which clones
40+
// every ancestor (e.g. the map of all jobs).
41+
cur := sv.Locations.Sub(path)
42+
if value == nil {
43+
if cur != nil {
44+
sv.Locations = sv.Locations.With(path, nil)
45+
}
46+
return nil
47+
}
48+
if cur == nil || len(cur.keys) > 0 || len(cur.elems) > 0 {
49+
sv.Locations = sv.Locations.With(path, (*Locations)(nil).WithLocations(cur.Get()))
4250
}
43-
sv.Locations = sv.Locations.With(path, locs)
4451
return nil
4552
}
4653

0 commit comments

Comments
 (0)