Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,29 @@ Resources: 4 created, 0 changed, 0 deleted, 0 unchanged
=== Edit fields inherited through YAML merge keys

=== Detect and save changes
Detected changes in 3 resource(s):
Detected changes in 4 resource(s):

Resource: resources.jobs.my_job
job_clusters[job_cluster_key='derived'].new_cluster.autoscale: add
job_clusters[job_cluster_key='derived'].new_cluster.num_workers: skip (the file does not write it where it is defined)
tasks[task_key='a_task'].timeout_seconds: skip (the mapping it would be added to is shared or inherited through a YAML anchor)
tasks[task_key='b_task'].depends_on[task_key='a_task']: skip (the file does not write it where it is defined)
tasks[task_key='b_task'].depends_on[task_key='prep']: skip (the file does not write it where it is defined)
tasks[task_key='b_task'].max_retries: skip (the file does not write it where it is defined)
tasks[task_key='b_task'].min_retry_interval_millis: add
tasks[task_key='b_task'].notebook_task.base_parameters['added']: add
tasks[task_key='b_task'].notebook_task.base_parameters['input_file_name']: add
tasks[task_key='c_task'].depends_on[task_key='a_task']: skip (the file does not write it where it is defined)
tasks[task_key='c_task'].depends_on[task_key='setup']: skip (the file does not write it where it is defined)
tasks[task_key='c_task'].notebook_task.base_parameters['added']: skip (the mapping it would be added to is shared or inherited through a YAML anchor)
tasks[task_key='prep']: skip (the file does not write it where it is defined)
tasks[task_key='setup']: remove
timeout_seconds: add

Resource: resources.jobs.other_job
max_concurrent_runs: skip (the mapping it would be added to is shared or inherited through a YAML anchor)
tasks[task_key='extra']: skip (the list it would be added to is shared through a YAML anchor)

Resource: resources.jobs.rename_job
tasks[task_key='main']: skip (the file does not write it where it is defined)
tasks[task_key='main2']: skip (the file does not write it where it is defined)
Expand Down Expand Up @@ -62,9 +69,10 @@ Resource: resources.pipelines.my_pipeline
- notebook_path: /Users/{{workspace_user_name}}/setup
- &base_task
task_key: a_task
@@ -84,4 +84,6 @@
@@ -84,4 +84,7 @@
<<: *base_params
extra: b
+ added: b
+ input_file_name: ${var.input_b}
+ min_retry_interval_millis: 5000
- <<: *base_task
Expand All @@ -75,6 +83,13 @@ Resource: resources.pipelines.my_pipeline
=== Effective configuration after the sync
{
"timeout_seconds": 1200,
"max_concurrent_runs": 4,
"task_keys": [
"a_task",
"b_task",
"c_task",
"prep"
],
"b_task": {
"max_retries": 2,
"min_retry_interval_millis": 5000,
Expand All @@ -87,6 +102,15 @@ Resource: resources.pipelines.my_pipeline
}
],
"input_file_name": "other"
},
"c_task": {
"timeout_seconds": null,
"notebook_task": {
"base_parameters": {
"input_file_name": "original"
},
"notebook_path": "/Users/{{workspace_user_name}}/notebook"
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ $CLI bundle deploy
job_id="$(read_id.py my_job)"
pipeline_id="$(read_id.py my_pipeline)"
rename_job_id="$(read_id.py rename_job)"
other_job_id="$(read_id.py other_job)"

title "Edit fields inherited through YAML merge keys"
edit_resource.py jobs $job_id <<EOF2
Expand All @@ -21,8 +22,12 @@ for task in r["tasks"]:
del task["max_retries"]
task["depends_on"] = [d for d in task["depends_on"] if d["task_key"] != "prep"] + [{"task_key": "a_task", "outcome": "true"}]
task["notebook_task"]["base_parameters"]["input_file_name"] = "other"
task["notebook_task"]["base_parameters"]["added"] = "b"
if task["task_key"] == "c_task":
task["depends_on"] = [d for d in task["depends_on"] if d["task_key"] != "setup"] + [{"task_key": "a_task"}]
task["notebook_task"]["base_parameters"]["added"] = "c"
if task["task_key"] == "a_task":
task["timeout_seconds"] = 60
for cluster in r["job_clusters"]:
if cluster["job_cluster_key"] == "derived":
del cluster["new_cluster"]["num_workers"]
Expand All @@ -31,6 +36,10 @@ EOF2
edit_resource.py jobs $rename_job_id <<EOF2
r["tasks"][0]["task_key"] = "main2"
EOF2
edit_resource.py jobs $other_job_id <<EOF2
r["max_concurrent_runs"] = 10
r["tasks"].append({"task_key": "extra", "notebook_task": {"notebook_path": "/Users/{{workspace_user_name}}/extra"}})
EOF2
edit_resource.py pipelines $pipeline_id <<EOF2
del r["clusters"]
EOF2
Expand All @@ -46,7 +55,7 @@ trace diff.py pipeline.yml.backup pipeline.yml
rm databricks.yml.backup pipeline.yml.backup

title "Effective configuration after the sync"
$CLI bundle validate -o json | jq '.resources.jobs.my_job | {timeout_seconds, b_task: (.tasks[] | select(.task_key == "b_task") | {max_retries, min_retry_interval_millis, depends_on, input_file_name: .notebook_task.base_parameters.input_file_name})}'
$CLI bundle validate -o json | jq '.resources.jobs.my_job | {timeout_seconds, max_concurrent_runs, task_keys: [.tasks[].task_key], b_task: (.tasks[] | select(.task_key == "b_task") | {max_retries, min_retry_interval_millis, depends_on, input_file_name: .notebook_task.base_parameters.input_file_name}), c_task: (.tasks[] | select(.task_key == "c_task") | {timeout_seconds, notebook_task})}'

title "Edit inherited fields with and without a target override supplying them"
edit_resource.py jobs $rename_job_id <<EOF2
Expand Down
130 changes: 124 additions & 6 deletions bundle/configsync/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ func ApplyChangesToYAML(ctx context.Context, b *bundle.Bundle, fieldChanges []Fi

// applyChange applies a single field change to the parsed file. Each write path is tried
// in turn; an add that none of them takes is written through the first null ancestor,
// then the first missing one.
// then the first missing one. sourceDocs.addSkipReason follows the same order to tell
// at resolve time where an add lands, so keep the two in step.
func applyChange(ctx context.Context, doc *yaml.Node, fieldChange FieldChange) error {
if len(doc.Content) != 1 {
return errors.New("the file holds no YAML document")
Expand Down Expand Up @@ -316,11 +317,8 @@ func yamlChild(current *yaml.Node, part *structpath.PathNode) (child, keyNode *y
// hold keys inherited through a merge key ('<<: *anchor'): an edit cannot reach those.
type sourceDocs map[string]*yaml.Node

// written reports whether the key is written at either path, and the path whose mapping
// can take the key instead: writePath, unless only altWritePath has such a mapping or
// a key at writePath would not take effect (shadowed), which also discounts one written
// there. An unreadable file counts as written, leaving the outcome to the edit.
func (d sourceDocs) written(file, writePath, altWritePath string, shadowed bool) (key bool, addPath string) {
// doc returns the parsed file, or nil when it cannot be read.
func (d sourceDocs) doc(file string) *yaml.Node {
doc, ok := d[file]
if !ok {
doc = &yaml.Node{}
Expand All @@ -330,6 +328,15 @@ func (d sourceDocs) written(file, writePath, altWritePath string, shadowed bool)
}
d[file] = doc
}
return doc
}

// written reports whether the key is written at either path, and the path whose mapping
// can take the key instead: writePath, unless only altWritePath has such a mapping or
// a key at writePath would not take effect (shadowed), which also discounts one written
// there. An unreadable file counts as written, leaving the outcome to the edit.
func (d sourceDocs) written(file, writePath, altWritePath string, shadowed bool) (key bool, addPath string) {
doc := d.doc(file)
if doc == nil {
return true, ""
}
Expand All @@ -350,6 +357,117 @@ func (d sourceDocs) written(file, writePath, altWritePath string, shadowed bool)
return key || altKey, addPath
}

const sharedAddReason = "the mapping it would be added to is shared or inherited through a YAML anchor"

// addSkipReason says why adding a key the file does not write, at writePath or
// altWritePath, cannot change only that key, or returns "" when it can. The add lands
// where applyChange puts it: in an existing mapping, else through a null, else in
// ancestors it creates. A mapping an alias refers to would change everywhere the alias is
// used, and an ancestor created next to a merge key ('<<: *anchor') that supplies it
// would hide every key inherited under it. An add no path can take, such as one under a
// shared null or a scalar, would fail the edit. An unreadable file gets "", leaving the
// outcome to the edit.
func (d sourceDocs) addSkipReason(file, writePath, altWritePath string) string {
doc := d.doc(file)
if doc == nil {
return ""
}
var landing yamlWalk
var landingPath *structpath.PatternNode
tier := 3
noLanding := sharedAddReason
for _, candidate := range []string{writePath, altWritePath} {
path, err := structpath.ParsePattern(candidate)
if candidate == "" || err != nil {
continue
}
w := walkYAMLPath(doc.Content[0], path)
var t int
switch {
case w.stop == yamlFound && !hasAnchor(w.node), w.stop == yamlMissing && w.depth == path.Len()-1 && w.node.Kind == yaml.MappingNode:
t = 0
case w.stop == yamlNull && !w.shared:
t = 1
case w.stop == yamlMissing:
t = 2
case w.stop == yamlScalar:
noLanding = "the file sets a parent of it to a scalar"
continue
default:
continue
}
if t < tier {
landing, landingPath, tier = w, path, t
}
}
if landingPath == nil {
return noLanding
}
container := landing.depth
if landing.stop == yamlFound {
container--
}
if aliasedAlong(doc.Content[0], landingPath, container) || tier == 2 && mergeSupplies(landing.node, (*structpath.PathNode)(landingPath.AsSlice()[landing.depth])) {
return sharedAddReason
}
return ""
}

// aliased reports whether an alias in the file refers to the node at writePath or to one
// on its path. An unreadable file gets false, leaving the outcome to the edit.
func (d sourceDocs) aliased(file, writePath string) bool {
doc := d.doc(file)
path, err := structpath.ParsePattern(writePath)
if doc == nil || err != nil {
return false
}
return aliasedAlong(doc.Content[0], path, path.Len())
}

// aliasedAlong reports whether an alias in root refers to a node that the first depth
// parts of path lead through, so an add under it shows up wherever the alias is used.
// An anchor that nothing refers to shares nothing.
func aliasedAlong(root *yaml.Node, path *structpath.PatternNode, depth int) bool {
targets := map[*yaml.Node]bool{}
walkYAML(root, func(n *yaml.Node) {
if n.Kind == yaml.AliasNode {
targets[n.Alias] = true
}
})
for _, prefix := range path.AsSlice()[:depth] {
if node := walkYAMLPath(root, prefix).node; node.Kind == yaml.AliasNode || targets[node] {
return true
}
}
return false
}

// mergeSupplies reports whether a merge key of mapping, or of a mapping it merges,
// supplies part.
func mergeSupplies(mapping *yaml.Node, part *structpath.PathNode) bool {
if mapping.Kind != yaml.MappingNode {
return false
}
for i := 0; i+1 < len(mapping.Content); i += 2 {
if mapping.Content[i].ShortTag() != "!!merge" {
continue
}
sources := []*yaml.Node{mapping.Content[i+1]}
if sources[0].Kind == yaml.SequenceNode {
sources = sources[0].Content
}
for _, source := range sources {
if source.Kind == yaml.AliasNode {
source = source.Alias
}
if child, _ := yamlChild(source, part); child != nil || mergeSupplies(source, part) {
return true
}
}
}
return false
}

// keyWrittenAt follows aliases like an edit does, but a parent reached through one, or
// under an anchor, is shared with whatever merges it and is no place to add the key.
func keyWrittenAt(root *yaml.Node, fieldPath string) (key, parent bool) {
Expand Down
52 changes: 52 additions & 0 deletions bundle/configsync/patch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -854,3 +854,55 @@ targets:
assert.True(t, key)
assert.Empty(t, addPath)
}

func TestSourceDocsAddSkipReason(t *testing.T) {
file := filepath.Join(t.TempDir(), "databricks.yml")
require.NoError(t, os.WriteFile(file, []byte(`base: &base
a: 1
nested:
x: 1
alias: *base
merged:
<<: *base
b: 2
anchored: &anchored
<<: *base
chained:
<<: [*anchored]
lonely: &lonely
d: 1
empty:
pinned:
c: &pin null
scalar: ${var.value}
targets:
dev:
merged:
b: 2
`), 0o644))

scalarReason := "the file sets a parent of it to a scalar"
for _, tc := range []struct {
name, path, altPath string
want string
}{
{"own mapping", "merged.c", "", ""},
{"inherited parent", "merged.nested.y", "", sharedAddReason},
{"new parent", "merged.other.y", "", ""},
{"inherited through a merged anchor", "chained.nested.y", "", sharedAddReason},
{"through alias", "alias.c", "", sharedAddReason},
{"under aliased anchor", "anchored.c", "", sharedAddReason},
{"under anchor nothing aliases", "lonely.e", "", ""},
{"null parent", "empty.c", "", ""},
{"alternative over inherited parent", "merged.nested.y", "targets.dev.merged.c", ""},
{"anchored key over shared alternative", "pinned.c", "alias.c", sharedAddReason},
{"anchored null parent", "pinned.c.x", "", sharedAddReason},
{"scalar parent", "scalar.c", "", scalarReason},
} {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.want, sourceDocs{}.addSkipReason(file, tc.path, tc.altPath))
})
}

assert.Empty(t, sourceDocs{}.addSkipReason(filepath.Join(t.TempDir(), "missing.yml"), "a.b", ""))
}
32 changes: 24 additions & 8 deletions bundle/configsync/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,9 @@ func ResolveChanges(ctx context.Context, b *bundle.Bundle, configChanges Changes

// Decided for every destination before any index bookkeeping, so a change
// that cannot be written everywhere is skipped as a whole and shifts nothing.
addPaths, written := writtenDestinations(docs, blocks, targetName, resolved, configChange.Operation, rename.keyField, destinations)
if !written {
leaveUnapplied(ctx, configChange, fullPath, "the file does not write it where it is defined")
addPaths, skipReason := writtenDestinations(docs, blocks, targetName, resolved, configChange.Operation, rename.keyField, b.Config.GetLocationOf(resourcePath).File, destinations)
if skipReason != "" {
leaveUnapplied(ctx, configChange, fullPath, skipReason)
skipped++
if isRename {
skipped++
Expand Down Expand Up @@ -474,9 +474,10 @@ func leaveUnapplied(ctx context.Context, change *ConfigChangeDesc, fullPath, rea
// merged config can locate a key the file does not write at that path, e.g. one
// inherited through a merge key ('<<: *anchor'), which an edit cannot reach. Such a
// replaced key can still be added next to the merge key: addPaths holds where, per
// destination. Anything else unwritten makes written false. renameKey is the key field
// a rename rewrites, empty for any other change.
func writtenDestinations(docs sourceDocs, blocks *blockResolver, target string, resolved resolvedChange, operation OperationType, renameKey string, destinations []routeDestination) (addPaths []string, written bool) {
// destination. Anything else unwritten, or an add that would change more than what it
// adds, returns why the change is skipped instead. renameKey is the key field a rename
// rewrites, empty for any other change. resourceFile is where an unrouted new key is added.
func writtenDestinations(docs sourceDocs, blocks *blockResolver, target string, resolved resolvedChange, operation OperationType, renameKey, resourceFile string, destinations []routeDestination) (addPaths []string, skipReason string) {
addPaths = make([]string, len(destinations))
for i, destination := range destinations {
block := destination.block
Expand All @@ -492,6 +493,17 @@ func writtenDestinations(docs sourceDocs, blocks *blockResolver, target string,
case !isDefinedInConfig && operation == OperationAdd && !addressesKey && block != nil:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A new element in a list shared through an alias lands in the anchor, so each job using it gains it. Should element adds skip too, or is this intended?

// A new element goes into its sequence, which the block has to write.
file = block.file
case !isDefinedInConfig && addressesKey && operation != OperationRemove:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test reaches the replace half of this case: limiting it to adds keeps every test green. Could one cover a replace of an undeclared field under a shared mapping?

// A new key is added, also for a replace of a field the file does not declare.
file = resourceFile
if block != nil {
file = block.file
}
writePath, altWritePath := writeAddress(blocks, block, target, path)
if reason := docs.addSkipReason(file, writePath, altWritePath); reason != "" {
return nil, reason
}
continue
default:
continue
}
Expand All @@ -500,6 +512,10 @@ func writtenDestinations(docs sourceDocs, blocks *blockResolver, target string,
path = path.Parent()
}
writePath, altWritePath := writeAddress(blocks, block, target, path)
if !isDefinedInConfig && !addressesKey && docs.aliased(file, writePath) {
// A new element would show up wherever an alias shares its sequence.
return nil, "the list it would be added to is shared through a YAML anchor"
}
// The target override wins the target merge, so a top-level key it also supplies
// would not take effect.
shadowed := addressesKey && operation == OperationReplace && (block == nil || !block.override) &&
Expand All @@ -519,10 +535,10 @@ func writtenDestinations(docs sourceDocs, blocks *blockResolver, target string,
case addressesKey && operation == OperationReplace && parentPath != "":
addPaths[i] = parentPath
default:
return nil, false
return nil, "the file does not write it where it is defined"
}
}
return addPaths, true
return addPaths, ""
}

// translateWorkspacePaths recursively converts absolute workspace paths to relative
Expand Down
Loading