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
@@ -0,0 +1,36 @@
bundle:
name: test-bundle-$UNIQUE_NAME

resources:
jobs:
my_job:
job_clusters:
- job_cluster_key: main
new_cluster: &cluster
spark_version: $DEFAULT_SPARK_VERSION
node_type_id: $NODE_TYPE_ID
num_workers: 1
- job_cluster_key: large
new_cluster: *cluster
tasks:
- task_key: setup
job_cluster_key: main
notebook_task:
notebook_path: /Users/{{workspace_user_name}}/setup
libraries: &common_libs
- pypi:
package: requests
- task_key: ingest
job_cluster_key: main
notebook_task:
notebook_path: /Users/{{workspace_user_name}}/ingest
libraries: *common_libs
- task_key: transform
job_cluster_key: main
notebook_task:
notebook_path: /Users/{{workspace_user_name}}/transform
libraries: *common_libs

targets:
default:
mode: development
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Cloud = true
GOOS.windows = false
EnvMatrix.DMS = ["", "true"]
62 changes: 62 additions & 0 deletions acceptance/bundle/config-remote-sync/yaml_anchors/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle-[UNIQUE_NAME]/default/files...
Created jobs.my_job
Files: 2 uploaded, 0 deleted
Resources: 1 created, 0 changed, 0 deleted, 0 unchanged

=== Remove the libraries of the task that defines the anchor, change the library of one aliased task and move another to the large cluster

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

Resource: resources.jobs.my_job
tasks[task_key='ingest'].libraries[0].pypi.package: replace
tasks[task_key='setup'].libraries: remove
tasks[task_key='transform'].job_cluster_key: replace



=== Configuration changes

>>> diff.py databricks.yml.backup databricks.yml
--- databricks.yml.backup
+++ databricks.yml
@@ -18,17 +18,18 @@
notebook_task:
notebook_path: /Users/{{workspace_user_name}}/setup
- libraries: &common_libs
- - pypi:
- package: requests
- task_key: ingest
job_cluster_key: main
notebook_task:
notebook_path: /Users/{{workspace_user_name}}/ingest
- libraries: *common_libs
+ libraries:
+ - pypi:
+ package: httpx
- task_key: transform
- job_cluster_key: main
+ job_cluster_key: large
notebook_task:
notebook_path: /Users/{{workspace_user_name}}/transform
- libraries: *common_libs
+ libraries: &common_libs
+ - pypi:
+ package: requests

targets:

=== Only the changed tasks differ

>>> [CLI] bundle validate -o json
{"task_key":"ingest","job_cluster_key":"main","libraries":[{"pypi":{"package":"httpx"}}]}
{"task_key":"setup","job_cluster_key":"main","libraries":null}
{"task_key":"transform","job_cluster_key":"large","libraries":[{"pypi":{"package":"requests"}}]}

>>> [CLI] bundle destroy --auto-approve
The following resources will be deleted:
delete resources.jobs.my_job

All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/test-bundle-[UNIQUE_NAME]/default

Destroy: 1 deleted
33 changes: 33 additions & 0 deletions acceptance/bundle/config-remote-sync/yaml_anchors/script
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#!/bin/bash

envsubst < databricks.yml.tmpl > databricks.yml

cleanup() {
trace $CLI bundle destroy --auto-approve
}
trap cleanup EXIT

$CLI bundle deploy
job_id="$(read_id.py my_job)"

title "Remove the libraries of the task that defines the anchor, change the library of one aliased task and move another to the large cluster"
edit_resource.py jobs $job_id <<EOF
for task in r["tasks"]:
if task["task_key"] == "setup":
del task["libraries"]
if task["task_key"] == "ingest":
task["libraries"][0]["pypi"]["package"] = "httpx"
if task["task_key"] == "transform":
task["job_cluster_key"] = "large"
EOF

title "Detect and save changes"
cp databricks.yml databricks.yml.backup
$CLI bundle config-remote-sync --save

title "Configuration changes"
trace diff.py databricks.yml.backup databricks.yml
rm databricks.yml.backup

title "Only the changed tasks differ"
trace $CLI bundle validate -o json | jq -c '.resources.jobs.my_job.tasks[] | {task_key, job_cluster_key, libraries}'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nit] .agents/rules/testing.md asks for the acceptance/bin/ helpers instead of inline jq pipelines. Could this use gron.py | grep on the task fields (task_key, job_cluster_key, libraries) instead of the hand-written jq -c projection?

6 changes: 6 additions & 0 deletions acceptance/bundle/config-remote-sync/yaml_anchors/test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Cloud = true

RecordRequests = false
Ignore = [".databricks", "databricks.yml", "databricks.yml.backup"]

Env.DATABRICKS_BUNDLE_ENABLE_EXPERIMENTAL_YAML_SYNC = "true"
137 changes: 132 additions & 5 deletions bundle/configsync/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ func ApplyChangesToYAML(ctx context.Context, b *bundle.Bundle, fieldChanges []Fi
type parentNode struct {
path yamlpatch.Path
missingPath yamlpatch.Path
source []byte
}

// applyChange applies a single field change to YAML content.
Expand All @@ -92,24 +93,29 @@ func applyChange(ctx context.Context, content []byte, fieldChange FieldChange) (
return nil, fmt.Errorf("failed to parse JSON Pointer %s: %w", jsonPointer, err)
}

source, err := isolateAnchors(content, fieldPathCandidate, fieldChange.Change.Operation)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nice to have] The isolated source goes to the patcher and the parent-path retry, but the fallback at line 151 still calls addThroughNullAncestor(content, ...) on the original content. That function bails on any anchored ancestor (line 215), and yamlChild can't follow an AliasNode. So other: &shared null\nparent: *shared with an add at parent.key still fails with scalar can not be a container, and so does parent: &shared {tags: null}\nother: *shared at parent.tags.key, even though after isolation both are plain nulls the fallback could fill in. Could the fallback run on the isolated source for each candidate? Then the anchor guard in addThroughNullAncestor could go, and those TestApplyChangeScalarParents cases would show the fix instead of pinning the error.

if err != nil {
return nil, err
}

patcher := gopkgv3yamlpatcher.New(gopkgv3yamlpatcher.IndentSpaces(2))
var modifiedContent []byte
var patchErr error

switch fieldChange.Change.Operation {
case OperationRemove:
modifiedContent, patchErr = patcher.Apply(content, yamlpatch.Patch{yamlpatch.Operation{
modifiedContent, patchErr = patcher.Apply(source, yamlpatch.Patch{yamlpatch.Operation{
Type: yamlpatch.OperationRemove,
Path: path,
}})
case OperationReplace:
modifiedContent, patchErr = patcher.Apply(content, yamlpatch.Patch{yamlpatch.Operation{
modifiedContent, patchErr = patcher.Apply(source, yamlpatch.Patch{yamlpatch.Operation{
Type: yamlpatch.OperationReplace,
Path: path,
Value: fieldChange.Change.Value,
}})
case OperationAdd:
modifiedContent, patchErr = patcher.Apply(content, yamlpatch.Patch{yamlpatch.Operation{
modifiedContent, patchErr = patcher.Apply(source, yamlpatch.Patch{yamlpatch.Operation{
Type: yamlpatch.OperationAdd,
Path: path,
Value: fieldChange.Change.Value,
Expand All @@ -118,7 +124,7 @@ func applyChange(ctx context.Context, content []byte, fieldChange FieldChange) (
// Collect parent path errors for later retry
if patchErr != nil && isParentPathError(patchErr) {
if missingPath, extractErr := extractMissingPath(patchErr); extractErr == nil {
parentNodesToCreate = append(parentNodesToCreate, parentNode{path, missingPath})
parentNodesToCreate = append(parentNodesToCreate, parentNode{path, missingPath, source})
}
}
default:
Expand Down Expand Up @@ -159,7 +165,7 @@ func applyChange(ctx context.Context, content []byte, fieldChange FieldChange) (
nestedValue := buildNestedMaps(errInfo.path, errInfo.missingPath, fieldChange.Change.Value)

patcher := gopkgv3yamlpatcher.New(gopkgv3yamlpatcher.IndentSpaces(2))
modifiedContent, patchErr := patcher.Apply(content, yamlpatch.Patch{yamlpatch.Operation{
modifiedContent, patchErr := patcher.Apply(errInfo.source, yamlpatch.Patch{yamlpatch.Operation{

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[nice to have] Switching this retry from content to errInfo.source is part of the fix, but none of the TestApplyChangeKeepsAnchors cases reach it. For example, a: &x\n k: 1\nb: *x\n with an add at b.m.n fails first with a missing /b/m parent, so it goes through this retry. Can you add that case and assert that a stays {k: 1} and only b gains m: {n: 2}?

Type: yamlpatch.OperationAdd,
Path: errInfo.missingPath,
Value: nestedValue,
Expand Down Expand Up @@ -249,6 +255,127 @@ func addThroughNullAncestor(content []byte, fieldPath string, value any) ([]byte
return nil, nil
}

// isolateAnchors rewrites content so that a change at fieldPath affects only that field.
// An alias on the path becomes a copy of its anchored node. An anchored node that the
// change edits or drops hands its anchor to its first alias elsewhere, which becomes a
// copy of the old value, so the aliases after it keep that value.
func isolateAnchors(content []byte, fieldPath string, operation OperationType) ([]byte, error) {
var doc yaml.Node
if err := yaml.Unmarshal(content, &doc); err != nil {
return nil, err
}
if len(doc.Content) != 1 {
return content, nil
}
pattern, err := structpath.ParsePattern(fieldPath)
if err != nil {
return nil, err
}

changed := false
anchors := map[*yaml.Node]bool{}
node, key := doc.Content[0], (*yaml.Node)(nil)
for _, part := range pattern.AsSlice() {
if node.Kind == yaml.AliasNode {
replaceYAMLNode(node, key, inlineYAMLNode(node.Alias))
changed = true
}
if node.Anchor != "" {
anchors[node] = true
}
node, key = yamlChild(node, (*structpath.PathNode)(part))
if node == nil {
break
}
}

var dropped *yaml.Node
if node != nil && (operation == OperationRemove || operation == OperationReplace) {
dropped = node
walkYAML(dropped, func(n *yaml.Node) {
if n.Anchor != "" {
anchors[n] = true
}
})
if operation == OperationRemove && key != nil && key.Anchor != "" {
anchors[key] = true
}
}

var visit func(node, key *yaml.Node)
visit = func(node, key *yaml.Node) {
if node == dropped {
return
}
if node.Kind == yaml.AliasNode && anchors[node.Alias] {
anchored := node.Alias
delete(anchors, anchored)
replacement := inlineYAMLNode(anchored)
replacement.Anchor = anchored.Anchor
anchored.Anchor = ""
replaceYAMLNode(node, key, replacement)
changed = true
return
}
if node.Kind == yaml.MappingNode {
for i := 0; i+1 < len(node.Content); i += 2 {
visit(node.Content[i], nil)
visit(node.Content[i+1], node.Content[i])
}
return
}
for _, child := range node.Content {
visit(child, nil)
}
}
visit(&doc, nil)
if !changed {
return content, nil
}
return encodeYAML(&doc)
}

func walkYAML(node *yaml.Node, fn func(*yaml.Node)) {
fn(node)
for _, child := range node.Content {
walkYAML(child, fn)
}
}

// inlineYAMLNode copies node with its aliases expanded and its anchors dropped, so the
// copy cannot rebind an anchor name for the aliases that follow it.
func inlineYAMLNode(node *yaml.Node) *yaml.Node {
if node.Kind == yaml.AliasNode {
return inlineYAMLNode(node.Alias)
}
c := *node
c.Anchor = ""
c.Content = make([]*yaml.Node, len(node.Content))
for i, child := range node.Content {
c.Content[i] = inlineYAMLNode(child)
}
return &c
}

// replaceYAMLNode replaces an alias in place and keeps its comments.
func replaceYAMLNode(alias, key, replacement *yaml.Node) {
replacement.HeadComment = alias.HeadComment
replacement.LineComment = ""
replacement.FootComment = alias.FootComment
// A block container would pass the alias's inline comment on to the next line, and
// yaml.v3 cannot encode an anchored one after a key's inline comment, so it goes above.
switch {
case alias.LineComment == "":
case replacement.Kind == yaml.ScalarNode || replacement.Style&yaml.FlowStyle != 0:
replacement.LineComment = alias.LineComment
case key != nil:
key.HeadComment = strings.TrimSpace(key.HeadComment + "\n" + alias.LineComment)
default:
replacement.HeadComment = strings.TrimSpace(replacement.HeadComment + "\n" + alias.LineComment)
}
*alias = *replacement
}

// isParentPathError checks if error indicates missing parent path.
func isParentPathError(err error) bool {
if err == nil {
Expand Down
Loading
Loading