load_yaml: Reject non-dict include targets

When jw.include specifies a target path, _merge_at_path() walks the
existing document to that path.  If an intermediate key holds a
non-dict value, that value is silently replaced by an empty dict; if
the leaf key holds a non-dict value, it is silently replaced by the
included mapping.  Both cases discard local document data without
warning, and the leaf case even inverts the documented precedence in
which local content wins over included content (which holds for the
dict-versus-dict case).

Make _merge_at_path() raise ValueError when an existing value on or
at the target path is not a mapping, and add regression tests for
both the intermediate and the leaf case.

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:15:47 +02:00
commit 2bd1db5d90
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61

View file

@ -147,18 +147,30 @@ def _merge_at_path(root: dict[str, Any], path: tuple[str, ...],
value: Any) -> dict[str, Any]:
"""Deep-merge *value* into *root* at the given *path*.
Creates intermediate dicts as needed. Returns the modified root.
Creates intermediate dicts as needed. Raises ``ValueError`` when
an existing value on or at the target path is not a mapping.
Returns the modified root.
"""
if not path:
return _deep_merge(root, value)
path_str = '.'.join(path)
current = root
for i, key in enumerate(path[:-1]):
if key not in current or not isinstance(current[key], dict):
if key in current and not isinstance(current[key], dict):
raise ValueError(
f'Include target path {path_str}: value at '
f'{".".join(path[:i + 1])} is not a mapping'
)
if key not in current:
current[key] = {}
current = current[key]
last_key = path[-1]
if (last_key in current and isinstance(current[last_key], dict)
and isinstance(value, dict)):
if last_key in current:
if not isinstance(current[last_key], dict) or not isinstance(value, dict):
raise ValueError(
f'Include target path {path_str}: value at {path_str} '
f'is not a mapping'
)
# root's existing content wins (merge value into root)
current[last_key] = _deep_merge(value, current[last_key])
else: