From 568c92b0096b35750eb1bbf0d61d37aa08555610 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sun, 16 Aug 2026 12:21:47 +0200 Subject: [PATCH] load_yaml: Deepcopy cached link expansions The memoisation cache in _expand_links_recursive() stores the expanded value of a link node. A link node that is first reached via another link, and later visited by the normal tree walk, is expanded only once; the cached result object is then returned as-is for the second location. Both places in the output tree end up holding the same dict, so mutating one of them silently mutates the other. Deepcopy the value on every cache read so that each place in the output tree holds an independent object. Add a regression test that mutates one cached location and checks the others stay untouched. Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v0.84.2 Signed-off-by: Jan Lindemann --- src/python/jw/util/load_yaml.py | 8 ++++++-- test/unit/python/jw/util/load_yaml/test.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index ef5292b..ef01d7b 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -235,7 +235,9 @@ def _expand_links_recursive( if link_key in resolving: raise ValueError(f"Cyclic link detected: {link_spec!r}") if link_key in resolved: - base_value: Any = resolved[link_key] + # Deepcopy so that cached results are not aliased into + # multiple places of the output tree + base_value: Any = deepcopy(resolved[link_key]) else: resolving.add(link_key) _, _, target_path, target_value = _resolve_link( @@ -274,7 +276,9 @@ def _expand_links_recursive( if link_key in resolving: raise ValueError(f"Cyclic link detected: {link_spec!r}") if link_key in resolved: - return resolved[link_key] + # Deepcopy so that cached results are not aliased into + # multiple places of the output tree + return deepcopy(resolved[link_key]) resolving.add(link_key) is_named, name, target_path, target_value = _resolve_link( diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index b99240f..1d293d1 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -621,6 +621,22 @@ class TestEdgeCases: assert data['a'] == 'val' assert data['b'] == 'val' + def test_cached_link_expansion_not_aliased(self, yaml_file: Callable) -> None: + """Link results shared via the memoisation cache are independent.""" + data = load_yaml( + yaml_file( + 'target:\n' + ' x: 1\n' + 'link_b:\n' + ' jw.link: target\n' + 'link_a:\n' + ' jw.link: link_b\n' + ) + ) + data['link_a']['x'] = 99 + assert data['link_b']['x'] == 1 + assert data['target']['x'] == 1 + def test_named_link_to_list(self, yaml_file: Callable) -> None: data = load_yaml( yaml_file('target:\n - x\n - y\nlink:\n jw.link: items|target\n')