Skip to content

fix(overlay): expand YAML aliases before actions apply - #740

Open
daveshanley wants to merge 2 commits into
mainfrom
fix/overlay-alias-expansion
Open

daveshanley wants to merge 2 commits into
mainfrom
fix/overlay-alias-expansion

Conversation

@daveshanley

@daveshanley daveshanley commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

The fault

An overlay failed on a document that uses YAML anchors:

paths:
  /admin/a:
    get:
      responses:
        '200':
          description: ok
          content: &shared
            application/json:
              schema: {type: string}
  /b:
    get:
      responses:
        '200':
          description: ok
          content: *shared
actions:
  - target: $.paths['/admin/a']
    remove: true

The remove action deleted the node that defines &shared. The alias under /b stayed, so the output had an alias with no anchor and did not parse: yaml: unknown anchor 'shared' referenced.

The same sharing caused a second fault. An action that reached a node through an alias changed every place that shared the node, because an alias and its anchor are one yaml.Node.

The fix

An overlay addresses the JSON data model, where each value belongs to one place. The engine now makes the document a plain tree before it applies an action (overlay/aliases.go):

  • each alias gets its own copy of the node it names, with the comments at the alias;
  • merge keys (<<) are applied, with the same precedence as utils.ResolveMergeNodes. {<<: {}} becomes {};
  • anchor names are removed.

An update value that has an alias, an anchor or a merge key gets the same treatment, on a copy. The caller's overlay does not change.

A document with no alias, anchor or merge key keeps every node it has. The cost for it is one walk of the tree.

The expansion follows the rules of go-yaml:

  • It uses the default alias limit of go-yaml, the same limit the index uses. The alias node counts as a node. The engine counts each copy against the limit before it allocates the copy. A document built to expand without end fails with ErrExcessiveAliases.
  • Alias copies can add at most 64 MiB of text (values and comments). More also fails with ErrExcessiveAliases.
  • An anchor that contains itself, or a named tree that holds a nil node, fails with ErrInvalidAlias.
  • An alias key that names << is a literal key, not a merge key.
  • A merge value must be a mapping or a list of mappings. Other values fail with ErrInvalidMergeKey.

go-yaml keeps the head and line comment at the start of a block mapping or sequence on its first entry. So a block copy moves the comments of its alias there. A copy does not keep a head comment on the first key inside an anchored block mapping, because go-yaml puts the comment of the anchor's place there too.

Behaviour changes

  • A document that has anchors comes out of an overlay with the anchors expanded, also where no action touches them.
  • A cyclic alias in the target now fails with ErrInvalidAlias, not ErrIncompatibleUpdate. TestApply_RejectCyclicAliasMerge is changed to match.
  • A merge value that is not a mapping or a list of mappings now fails with the new ErrInvalidMergeKey. Before, the overlay kept it unchanged in the output.

Tests

  • New overlay/aliases_test.go: remove the anchor owner (one alias, several aliases, a merge key), remove and update through an alias, update the anchor owner, copy the anchor owner, an update value that has an alias, the alias limit, a cycle.
  • Review fixes: the limit check before the copy (by allocation count), the text limit, a flat list of 2,048 aliases, an alias key that names <<, {<<: {}}, invalid merge values, a valid list merge, a nil node, and the comments at the alias. Each test failed before the fix. Where go-yaml can read the input, the tests compare the result with go-yaml.
  • First commit: go test ./... passes. Review fixes: go test ./overlay/ . passes (the root package is the only one that imports overlay).
  • The overlay package is at 100.0% of statements. go test -race ./overlay/ passes. go vet and gofmt are clean.
  • Alias expansion of a large document with no aliases is not slower: −2.8% (p=0.026, n=15, old and new runs in turn).

🤖 Generated with Claude Code

An overlay addresses the JSON data model, where each value belongs to
one place. A YAML anchor shares one node between all the aliases and
merge keys that name it. This caused two failures:

- A remove action that deleted the node that defines an anchor left
  the aliases with no anchor. The output did not parse ("unknown
  anchor").
- An action that reached a node through an alias changed every place
  that shared the node.

The engine now expands the target document before it applies an
action. Each alias gets its own copy of the node it names, merge keys
are applied, and anchor names are removed. An update value that has an
alias, an anchor or a merge key is copied and expanded in the same
way. The caller's overlay does not change. The expansion uses the
default alias limit of go-yaml and finds cycles.

Behaviour changes:

- A document that has anchors comes out with the anchors expanded.
- A cyclic alias in the target now fails with ErrInvalidAlias, not
  ErrIncompatibleUpdate.

New errors: ErrInvalidAlias and ErrExcessiveAliases.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (ef96408) to head (04337f7).

Additional details and impacted files
@@            Coverage Diff             @@
##              main      #740    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files          316       317     +1     
  Lines        40239     40375   +136     
==========================================
+ Hits         40239     40375   +136     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@daveshanley daveshanley left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The full Go suite and overlay race tests passed. I found seven issues in alias expansion.

Comment thread overlay/aliases.go Outdated
return err
}
node.Content[i] = e.copyOf(child.Alias)
if err := aliasLimits.CheckAlias(e.aliasNodes, e.nodes); err != nil {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Check the node limit before copyOf allocates the subtree. Also bound expanded scalar bytes before marshaling, since node count alone cannot limit output size.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 04337f7. copyAlias measures the named tree once (measureTree, kept in sizes) and counts the full copy against the node limit before copyTree allocates it. The alias ratio only increases while a copy adds nodes, so one check of the full copy gives the same result as one check for each node.

Alias copies can also add at most 64 MiB of text (values and comments). More fails with ErrExcessiveAliases.

  • TestExpandAliases_LimitCheckedBeforeCopy: an alias to a tree of 10,000 nodes over the limit makes fewer than 100 allocations.
  • TestApply_ExcessiveAliasText: 65 aliases to a 1 MiB scalar are in the count limit, and fail on the text limit.

Comment thread overlay/aliases.go Outdated
}
// The named node is expanded once, in place. Every alias then takes a
// copy of a tree that has no alias left in it.
if err := e.expand(child.Alias, true); err != nil {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Count the alias itself in e.nodes before visiting its target. A flat list of 2,048 scalar aliases passes go-yaml and fails here with ErrExcessiveAliases.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 04337f7. The alias counts in e.nodes before its target is visited, as in go-yaml. TestApply_FlatAliasList has 2,048 aliases to one scalar. It checks that go-yaml accepts the list, and that the overlay result holds all 2,048 values.

Comment thread overlay/aliases.go Outdated
if err := e.expand(child.Alias, true); err != nil {
return err
}
node.Content[i] = e.copyOf(child.Alias)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

When an alias supplies the literal mapping key <<, emit it as a quoted string. Copying its tag turns it into a merge directive and can break JSON conversion.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 04337f7. A copy in a key position that is the scalar << gets the tag !!str and the double-quoted style. TestApply_AliasKeyIsLiteralMergeText has *key : literal next to a real merge key. It compares the result with go-yaml's own reading of the source: {"<<": "literal", "merged": true}.

Also, only a key can start merge resolution now. Before, a << value also did.

Comment thread overlay/aliases.go Outdated
}
}
if merges && node.Kind == yaml.MappingNode {
node.Content = utils.ResolveMergeNodes(node).Content

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ResolveMergeNodes leaves {<<: {}} intact. Normalize it to {} so a wildcard action matches zero properties.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 04337f7. When ResolveMergeNodes returns the mapping unchanged (the merge gives no entry), the mapping gets no content. TestApply_EmptyMerge_HasNoProperties updates $['x-empty'].*. The result is x-empty: {}, and the update matches nothing.

A remove action did not show this fault: it removed the << entry together with the {} that it matched.

Comment thread overlay/aliases.go Outdated
}
}
if merges && node.Kind == yaml.MappingNode {
node.Content = utils.ResolveMergeNodes(node).Content

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reject scalar merge sources before resolving the mapping. For {<<: name, enabled: true}, this silently drops the invalid directive and returns success.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 04337f7. resolveMerges checks each merge value before it resolves the mapping. A value that is not a mapping or a list of mappings fails with the new ErrInvalidMergeKey, with the line of the merge key.

  • TestApply_MergeValueNotMapping: a scalar, a null, a list with a scalar, and an alias to a scalar. Each case also checks that go-yaml rejects the same document.
  • TestApply_MergeKeyList: a valid list merge gives the same mapping as go-yaml.

Comment thread overlay/aliases.go Outdated
if len(node.Content) > 0 {
copied.Content = make([]*yaml.Node, len(node.Content))
for i, child := range node.Content {
copied.Content[i] = e.copyOf(child)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A nil child in a caller-built aliased sequence reaches copyOf(nil) and panics. Return an error and cover this case in TestPlainUpdate_NilChild.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 04337f7. measureTree runs before the copy and finds a nil node at any depth. copyAlias then returns ErrInvalidAlias. TestPlainUpdate_NilChild now has a nil node one level below the named node. A nil child that no alias names stays as it is, as before.

Comment thread overlay/aliases.go Outdated
if err := e.expand(child.Alias, true); err != nil {
return err
}
node.Content[i] = e.copyOf(child.Alias)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A title-only update replaced # staging deployment on the alias with the anchor’s comment. Preserve the comment at the alias site.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 04337f7. A copy takes the head, line and foot comments of its alias. go-yaml keeps the head and line comment at the start of a block mapping or sequence on its first entry. So in a block copy, the first entry loses the comments of the anchor and gets the line comment of the alias. Flow collections and scalars keep their comments on the node. TestApply_AliasKeepsItsComments checks the exact output for block mappings, block sequences, flow mappings and scalars.

One limit: a copy does not keep a head comment on the first key inside an anchored block mapping, because go-yaml puts the comment of the anchor's place there too. The original keeps it.

Fixes from the review of the alias expansion:

- The engine checks the node limit before it makes a copy. It measures
  each named tree once, and it counts the full copy before it allocates.
- Alias copies can add at most 64 MiB of text (values and comments). The
  node limit cannot limit the size of the output, because a copy shares
  its strings with the node that it copies.
- The alias node counts as a node, as in go-yaml. A flat list of 2,048
  aliases to one scalar does not fail with ErrExcessiveAliases now.
- An alias key that names "<<" stays a literal key, as go-yaml reads it.
  The copy is a quoted string, so it is not a merge key.
- {<<: {}} becomes {}, so a wildcard target matches no property.
- A merge value that is not a mapping or a list of mappings fails with
  the new ErrInvalidMergeKey, as in go-yaml. Before, the engine removed
  the merge key and did not report an error.
- A nil node in a tree that an alias names fails with ErrInvalidAlias.
  Before, it caused a panic.
- A copy keeps the comments at its alias, not the comments at the
  anchor. go-yaml keeps the head and line comment of a block mapping or
  sequence on its first entry, so the copy moves the comments there too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant