load_yaml: _resolve_link(): Add context to errors

When a link's target path cannot be resolved, the raw KeyError from
_resolve_path() propagates to the caller (or a raw TypeError when a
path segment hits a list), without saying which link or which
document location caused the failure.  The parse-and-resolve
sequence is also duplicated in the jw.link and jw.inplace-link
branches of _expand_links_recursive().

Extract the sequence into _resolve_link() and wrap navigation
failures in ValueError naming the link kind, the spec, and the
location in the document.  Document that path navigation operates on
the unexpanded tree, so intermediate segments must not be link nodes
themselves.  Update the tests that pinned KeyError and add coverage
for the list-navigation case and the error message content.

Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v0.84.2
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-08-16 12:18:22 +02:00
commit 503c620341
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61
2 changed files with 47 additions and 14 deletions

View file

@ -179,6 +179,35 @@ def _merge_at_path(root: dict[str, Any], path: tuple[str, ...],
# -- Link expansion -------------------------------------------------------------
def _resolve_link(
kind: str,
spec: Any,
current_path: tuple[str | int, ...],
root: dict[str, Any],
) -> tuple[bool, str | None, tuple[str, ...], Any]:
"""Parse *spec* and resolve its target path against *root*.
Returns ``(is_named, name, target_path, target_value)``. A missing
or invalid target raises ``ValueError`` naming the link and its
location. Path navigation operates on the unexpanded tree, so
intermediate segments must not be link nodes themselves.
"""
is_named, name, path = _parse_link(spec)
where = '.'.join(str(part) for part in current_path)
if not where:
where = '<root>'
try:
# current_path may contain int indices from list traversal,
# but _resolve_path only uses string keys for navigation
target_path, target_value = _resolve_path(
path, cast('tuple[str, ...]', current_path), root
)
except (KeyError, IndexError, TypeError) as exc:
raise ValueError(
f'{kind} {spec!r} at {where}: cannot resolve target path: {exc}'
) from None
return (is_named, name, target_path, target_value)
def _expand_links_recursive(
node: Any,
root: dict[str, Any],
@ -204,11 +233,8 @@ def _expand_links_recursive(
base_value: dict[str, Any] | Any = resolved[link_key]
else:
resolving.add(link_key)
_, _, path = _parse_link(link_spec)
# current_path may contain int indices from list traversal,
# but _resolve_path only uses string keys for navigation
target_path, target_value = _resolve_path(
path, cast('tuple[str, ...]', current_path), root
_, _, target_path, target_value = _resolve_link(
'jw.inplace-link', link_spec, current_path, root
)
base_value = _expand_links_recursive(
target_value, root, target_path, resolved, resolving
@ -246,11 +272,8 @@ def _expand_links_recursive(
return resolved[link_key]
resolving.add(link_key)
is_named, name, path = _parse_link(link_spec)
# current_path may contain int indices from list traversal,
# but _resolve_path only uses string keys for navigation
target_path, target_value = _resolve_path(
path, cast('tuple[str, ...]', current_path), root
is_named, name, target_path, target_value = _resolve_link(
'jw.link', link_spec, current_path, root
)
expanded_target = _expand_links_recursive(
target_value, root, target_path, resolved, resolving

View file

@ -480,7 +480,7 @@ class TestMissingTargets:
"""Tests for missing link targets."""
def test_missing_absolute_target(self, yaml_file: Callable) -> None:
with pytest.raises(KeyError):
with pytest.raises(ValueError, match = 'cannot resolve target path'):
load_yaml(yaml_file('link:\n jw.link: nonexistent\n'))
def test_missing_relative_target(self, yaml_file: Callable) -> None:
@ -488,17 +488,27 @@ class TestMissingTargets:
load_yaml(yaml_file('link:\n jw.link: ..missing\n'))
def test_missing_deep_target(self, yaml_file: Callable) -> None:
with pytest.raises(KeyError):
with pytest.raises(ValueError, match = 'cannot resolve target path'):
load_yaml(
yaml_file('exists:\n val: ok\nlink:\n jw.link: exists.missing\n')
)
def test_missing_relative_deep_target(self, yaml_file: Callable) -> None:
with pytest.raises(KeyError):
with pytest.raises(ValueError, match = 'cannot resolve target path'):
load_yaml(
yaml_file('a:\n b: val\nnode:\n link:\n jw.link: ..a.missing\n')
)
def test_missing_target_in_list_raises(self, yaml_file: Callable) -> None:
"""Navigating into a list by key name raises with context."""
with pytest.raises(ValueError, match = 'cannot resolve target path'):
load_yaml(yaml_file('items:\n - a\nlink:\n jw.link: items.x\n'))
def test_missing_target_error_names_link(self, yaml_file: Callable) -> None:
"""The error message names the failing link and its location."""
with pytest.raises(ValueError, match = "jw.link 'nope' at link"):
load_yaml(yaml_file('link:\n jw.link: nope\n'))
# -- jw.link expansion - No links (regression) --------------------------------
class TestNoLinksRegression:
@ -619,7 +629,7 @@ class TestEdgeCases:
def test_link_value_with_pipe_in_target_key(self, yaml_file: Callable) -> None:
"""Key with pipe in name — pipe triggers named link parsing."""
with pytest.raises(KeyError):
with pytest.raises(ValueError, match = 'cannot resolve target path'):
load_yaml(yaml_file('my|key: val\nlink:\n jw.link: my|key\n'))
def test_named_link_with_numeric_prefix(self, yaml_file: Callable) -> None: