fix(yaml): handle multi-document streams, gate data YAML, bump cache schema (#4706)
Three fixes on top of #4706's YAML extractor: - Multi-document YAML (`---` separators) returned zero nodes because it used yaml.safe_load, which accepts only one document; k8s manifests, Helm output, and CI pipelines (the headline use cases) were silently empty. Use safe_load_all and give each document a distinct node (labelled by kind+name for k8s) so two docs in one file do not merge their keys. - Add a _is_config_yaml gate mirroring extract_json's _is_config_json: a top-level data array, an OpenAPI/Swagger spec, a JSON-schema-in-YAML, and a flat all-scalar bundle (i18n) are skipped as data instead of minting up to 500 orphan nodes. A mapping with any nested value, a recognized config name, or a .github/workflows path is still walked. - Bump _AST_CACHE_SCHEMA 22 -> 23 (the PR reclassifies .yaml/.yml and adds a new extractor, so cached YAML must re-extract). - Tests: multi-doc, data/OpenAPI/array skip, the safe_load ACE guard, and caps. - Clearer missing-PyYAML hint (pip install pyyaml). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
9c5d56f28f
commit
1834b3e703
3 files changed
+167
-14
No files matched your search
+1
-1
@@ -37,7 +37,7 @@ except Exception:
|
||||
_EXTRACTOR_VERSION = "unknown"
|
||||
|
||||
# Bump when AST cache-key semantics change independently of the package version.
|
||||
_AST_CACHE_SCHEMA = 22 # SQL labels drop T-SQL brackets and routine bodies emit `reads_from`/`writes_to` (#4635), and a `GO` batch separator ends a statement (#4651), so cached `.sql` extractions re-run; prior (21): a CommonJS `const X = require('./m')` binding no longer mints a module-scope node that shadows the class the required file exports, so `new X()` resolves to the required declaration (#4621); prior (20): Obsidian `[[wikilink]]` targets that start with the scan root's own folder names now resolve to the real page (#4559), so cached markdown extractions re-run; prior (19): Dart `typedef` declarations are extracted as aliases (not variables of type `typedef`); C++ Metal/CUDA GPU qualifiers no longer mint sourceless god nodes (#4550); a `.h` header containing `extern "C"` routes to the C++ extractor; prior (18): Kotlin `typealias` (#4553), C# `delegate` (#4552), and Swift `macro` declarations (#4551) are now extracted so references stop minting sourceless stubs; Rust `use` rooted at a `mod` declared in the same scope carries `_rust_use_name` (#4564); prior (17): Python pytest-fixture markers (`_py_fixture`/`_python_fixture_param`, #4332) and module-level class-id collision salting (#2810); TS `this.field` typed from any method incl. static (#4473); Solidity callables carry `metadata.arity` + inherited-call/`super`/modifier raw calls (#4379); Go type-decl and Rust file-item case-distinct node ids (#4444); prior (16): Rust `use` edges carry the imported name as written (`_rust_use_name`, #4439); (15): Go generic receiver types normalized (`Box[T]` -> `Box`) so methods attach to the type node; prior (14): C# receiver resolution for nameless/`new X()`/`foreach` receivers (defer + receiver-chain markers) and `_`/case-distinct node ids (underscore-salted); prior (13): Kotlin/Scala/C++/Swift generic & template type params no longer mint sourceless stubs; Objective-C NS_ENUM/NS_OPTIONS extraction and `_callable`/`_callable_class` markers; Go and PHP receiver-typed member calls park cross-repo (`go_type_table`/`php_type_table`, receiver fields); prior (12): Java inherited-supertype (`receiver_unbound`) and chained/new/cast receiver typing (`java_receiver_chain`, `_java_ret`); C/C++ quoted cross-directory include provenance (`include_kind`); JS external imports anchored to the package, not the path leaf; prior (11): Python property-accessor decorators / `Self`, Swift `Self`, Go generic type params, Python forward type-hint file node, PowerShell dot-source, C# verbatim-interpolated string recovery; (10): C# partial types carry `type_path`; (9): Python property-read raw calls and `_py_property` nodes; (8): Rust `use`-group per-binding edges; (7): Python opaque-base/super(args) markers + nested-class enclosing ids.
|
||||
_AST_CACHE_SCHEMA = 23 # `.yaml`/`.yml` files are structurally extracted (keys as nodes, config-vs-data gated) and reclassified from document to code (#2214), so cached YAML re-extracts; prior (22): SQL labels drop T-SQL brackets and routine bodies emit `reads_from`/`writes_to` (#4635), and a `GO` batch separator ends a statement (#4651), so cached `.sql` extractions re-run; prior (21): a CommonJS `const X = require('./m')` binding no longer mints a module-scope node that shadows the class the required file exports, so `new X()` resolves to the required declaration (#4621); prior (20): Obsidian `[[wikilink]]` targets that start with the scan root's own folder names now resolve to the real page (#4559), so cached markdown extractions re-run; prior (19): Dart `typedef` declarations are extracted as aliases (not variables of type `typedef`); C++ Metal/CUDA GPU qualifiers no longer mint sourceless god nodes (#4550); a `.h` header containing `extern "C"` routes to the C++ extractor; prior (18): Kotlin `typealias` (#4553), C# `delegate` (#4552), and Swift `macro` declarations (#4551) are now extracted so references stop minting sourceless stubs; Rust `use` rooted at a `mod` declared in the same scope carries `_rust_use_name` (#4564); prior (17): Python pytest-fixture markers (`_py_fixture`/`_python_fixture_param`, #4332) and module-level class-id collision salting (#2810); TS `this.field` typed from any method incl. static (#4473); Solidity callables carry `metadata.arity` + inherited-call/`super`/modifier raw calls (#4379); Go type-decl and Rust file-item case-distinct node ids (#4444); prior (16): Rust `use` edges carry the imported name as written (`_rust_use_name`, #4439); (15): Go generic receiver types normalized (`Box[T]` -> `Box`) so methods attach to the type node; prior (14): C# receiver resolution for nameless/`new X()`/`foreach` receivers (defer + receiver-chain markers) and `_`/case-distinct node ids (underscore-salted); prior (13): Kotlin/Scala/C++/Swift generic & template type params no longer mint sourceless stubs; Objective-C NS_ENUM/NS_OPTIONS extraction and `_callable`/`_callable_class` markers; Go and PHP receiver-typed member calls park cross-repo (`go_type_table`/`php_type_table`, receiver fields); prior (12): Java inherited-supertype (`receiver_unbound`) and chained/new/cast receiver typing (`java_receiver_chain`, `_java_ret`); C/C++ quoted cross-directory include provenance (`include_kind`); JS external imports anchored to the package, not the path leaf; prior (11): Python property-accessor decorators / `Self`, Swift `Self`, Go generic type params, Python forward type-hint file node, PowerShell dot-source, C# verbatim-interpolated string recovery; (10): C# partial types carry `type_path`; (9): Python property-read raw calls and `_py_property` nodes; (8): Rust `use`-group per-binding edges; (7): Python opaque-base/super(args) markers + nested-class enclosing ids.
|
||||
|
||||
|
||||
# Per-process memo: distributions() scans site-packages metadata, which is
|
||||
|
||||
@@ -7,7 +7,10 @@ being skipped entirely (#2214).
|
||||
|
||||
Mirrors ``extract_json`` in shape: a file node plus ``contains`` edges to
|
||||
top-level (and nested) keys, with a pair/depth cap to keep data-heavy YAML from
|
||||
exploding into orphan nodes.
|
||||
exploding into orphan nodes. Like ``extract_json``'s ``_is_config_json`` gate,
|
||||
data-shaped YAML (a top-level data array, an OpenAPI/Swagger spec, a flat
|
||||
key:value data bundle) is skipped so it does not mint up to 500 orphan nodes
|
||||
(the #1224/#2255 class of problem).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,19 +21,93 @@ from typing import Any
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
from graphify.ids import normalize_id
|
||||
|
||||
_YAML_MAX_BYTES = 1_048_576 # 1 MiB
|
||||
_MAX_PAIRS = 500
|
||||
_MAX_DEPTH = 6
|
||||
|
||||
# Config/manifest filenames worth structural extraction regardless of shape.
|
||||
_CONFIG_YAML_NAMES = frozenset({
|
||||
"values.yaml", "values.yml", "chart.yaml", "chart.yml",
|
||||
"docker-compose.yaml", "docker-compose.yml", "compose.yaml", "compose.yml",
|
||||
"kustomization.yaml", "kustomization.yml", "skaffold.yaml", "skaffold.yml",
|
||||
"serverless.yaml", "serverless.yml", "mkdocs.yaml", "mkdocs.yml",
|
||||
".gitlab-ci.yml", ".gitlab-ci.yaml", ".pre-commit-config.yaml",
|
||||
"cloudbuild.yaml", "cloudbuild.yml", "pubspec.yaml", "environment.yml",
|
||||
"action.yml", "action.yaml", "catalog-info.yaml", ".travis.yml",
|
||||
"appveyor.yml", "azure-pipelines.yml",
|
||||
})
|
||||
# Top-level keys that signal a config/manifest (k8s, CI, compose, ansible, helm).
|
||||
_CONFIG_YAML_KEYS = frozenset({
|
||||
"apiversion", "kind", "metadata", "spec", # k8s
|
||||
"services", "volumes", "networks", # compose
|
||||
"jobs", "steps", "stages", "on", "workflows", "pipeline", # CI
|
||||
"hosts", "tasks", "roles", # ansible
|
||||
"name", "version", "dependencies", "scripts", # generic
|
||||
"resources", "provider", "functions", # serverless
|
||||
})
|
||||
|
||||
|
||||
def _is_config_yaml(path: Path, data: Any) -> bool:
|
||||
"""True if a YAML document is a recognized config/manifest worth extracting.
|
||||
|
||||
Matches by filename first, then a ``.github/workflows`` path, then a
|
||||
top-level key probe. Skips clear data: a plain data array, an OpenAPI/Swagger
|
||||
spec, a JSON-Schema-in-YAML, and a flat all-scalar mapping with no config
|
||||
key (for example an i18n string bundle). Errs toward extracting (a mapping
|
||||
with any nested value is treated as config) so an arbitrarily-named real
|
||||
config is not silently dropped.
|
||||
"""
|
||||
name = path.name.casefold()
|
||||
if name in _CONFIG_YAML_NAMES:
|
||||
return True
|
||||
if "/.github/workflows/" in path.as_posix().casefold():
|
||||
return True
|
||||
if isinstance(data, list):
|
||||
# A top-level sequence is config only when it is an ansible-style list of
|
||||
# plays/tasks; a plain data array is not.
|
||||
return any(
|
||||
isinstance(item, dict)
|
||||
and ({"hosts", "tasks", "roles"} & {str(k).casefold() for k in item})
|
||||
for item in data
|
||||
)
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
keys = {str(k).casefold() for k in data.keys()}
|
||||
if ("openapi" in keys or "swagger" in keys) and "paths" in keys:
|
||||
return False # an API spec is data-heavy, not a config to walk (#2255-style)
|
||||
if "$schema" in keys and ({"$defs", "definitions", "$id"} & keys):
|
||||
return False # a JSON schema in YAML clothing
|
||||
if keys & _CONFIG_YAML_KEYS:
|
||||
return True
|
||||
# A mapping with at least one nested value is config-like; a flat all-scalar
|
||||
# mapping with no config key is treated as a data bundle and skipped.
|
||||
return any(isinstance(v, (dict, list)) for v in data.values())
|
||||
|
||||
|
||||
def _doc_label(doc: Any, index: int) -> str:
|
||||
"""A stable label for one document of a multi-document YAML stream."""
|
||||
if isinstance(doc, dict):
|
||||
kind = doc.get("kind")
|
||||
if isinstance(kind, str) and kind:
|
||||
meta = doc.get("metadata")
|
||||
nm = meta.get("name") if isinstance(meta, dict) else None
|
||||
return f"{kind} {nm}" if isinstance(nm, str) and nm else kind
|
||||
return f"doc {index}"
|
||||
|
||||
|
||||
def extract_yaml(path: Path) -> dict:
|
||||
"""Extract structural nodes/edges from a ``.yaml``/``.yml`` file.
|
||||
|
||||
Uses PyYAML (``yaml.safe_load``) when available; returns an error payload
|
||||
otherwise so callers degrade gracefully instead of crashing.
|
||||
Uses PyYAML ``safe_load_all`` (never ``load``; a ``!!python/...`` tag raises
|
||||
rather than executing) and walks every document in a multi-document stream.
|
||||
Returns an error payload when PyYAML is missing so callers degrade
|
||||
gracefully instead of crashing.
|
||||
"""
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "pyyaml not installed"}
|
||||
|
||||
_YAML_MAX_BYTES = 1_048_576 # 1 MiB
|
||||
return {"nodes": [], "edges": [],
|
||||
"error": "pyyaml not installed; install with `pip install pyyaml`"}
|
||||
|
||||
try:
|
||||
with path.open("rb") as _f:
|
||||
@@ -38,13 +115,16 @@ def extract_yaml(path: Path) -> dict:
|
||||
if len(raw) > _YAML_MAX_BYTES:
|
||||
return {"nodes": [], "edges": [], "error": "yaml file too large to index"}
|
||||
text = raw.decode("utf-8", errors="ignore")
|
||||
data = yaml.safe_load(text)
|
||||
docs = list(yaml.safe_load_all(text))
|
||||
except Exception as exc: # noqa: BLE001 - surface any parse failure to caller
|
||||
return {"nodes": [], "edges": [], "error": str(exc)}
|
||||
|
||||
if not isinstance(data, (dict, list)):
|
||||
# A scalar document carries no structure worth graphing.
|
||||
structured = [d for d in docs if isinstance(d, (dict, list))]
|
||||
if not structured:
|
||||
return {"nodes": [], "edges": [], "skipped": "scalar yaml"}
|
||||
config_docs = [d for d in structured if _is_config_yaml(path, d)]
|
||||
if not config_docs:
|
||||
return {"nodes": [], "edges": [], "skipped": "data yaml (not a config/manifest)"}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
@@ -77,11 +157,11 @@ def extract_yaml(path: Path) -> dict:
|
||||
pair_count = [0]
|
||||
|
||||
def walk(obj: Any, parent_nid: str, parent_key: str | None, depth: int) -> None:
|
||||
if depth > 6:
|
||||
if depth > _MAX_DEPTH:
|
||||
return
|
||||
if isinstance(obj, dict):
|
||||
for key, val in obj.items():
|
||||
if pair_count[0] >= 500:
|
||||
if pair_count[0] >= _MAX_PAIRS:
|
||||
return
|
||||
pair_count[0] += 1
|
||||
key_str = str(key)
|
||||
@@ -101,5 +181,19 @@ def extract_yaml(path: Path) -> dict:
|
||||
if isinstance(item, (dict, list)):
|
||||
walk(item, parent_nid, parent_key, depth + 1)
|
||||
|
||||
walk(data, file_nid, None, 0)
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
multi = len(config_docs) > 1
|
||||
for index, doc in enumerate(config_docs):
|
||||
if multi:
|
||||
# Keep each document of a multi-document stream distinct (a k8s file
|
||||
# holding a Deployment and a Service must not merge their metadata).
|
||||
label = _doc_label(doc, index)
|
||||
doc_nid = _make_id(stem, f"doc{index}", label) or _make_id(stem, f"doc{index}")
|
||||
if not doc_nid:
|
||||
continue
|
||||
add_node(doc_nid, label)
|
||||
add_edge(file_nid, doc_nid, "contains")
|
||||
walk(doc, doc_nid, label, 1)
|
||||
else:
|
||||
walk(doc, file_nid, None, 0)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -61,3 +61,62 @@ def test_extract_yaml_scalar_document_is_skipped(tmp_path):
|
||||
def test_extract_yaml_empty_document(tmp_path):
|
||||
result = extract_yaml(_write(tmp_path / "empty.yaml", ""))
|
||||
assert result.get("skipped") == "scalar yaml"
|
||||
|
||||
|
||||
def test_multi_document_yaml_extracts_each_document(tmp_path):
|
||||
"""A k8s-style multi-document stream (`---` separators) is the headline use
|
||||
case; each document must contribute distinct nodes rather than returning
|
||||
zero (safe_load_all, not safe_load)."""
|
||||
path = _write(
|
||||
tmp_path / "manifests.yaml",
|
||||
"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: web\n"
|
||||
"---\n"
|
||||
"apiVersion: v1\nkind: Service\nmetadata:\n name: web-svc\n",
|
||||
)
|
||||
result = extract_yaml(path)
|
||||
assert "error" not in result and "skipped" not in result, result
|
||||
labels = {n["label"] for n in result["nodes"]}
|
||||
# both documents are present and kept distinct, labelled by kind + name
|
||||
assert "Deployment web" in labels
|
||||
assert "Service web-svc" in labels
|
||||
|
||||
|
||||
def test_data_yaml_is_skipped(tmp_path):
|
||||
"""A flat all-scalar data bundle with no config key (an i18n-style file) is
|
||||
skipped rather than minting orphan nodes, mirroring extract_json's gate."""
|
||||
result = extract_yaml(_write(
|
||||
tmp_path / "strings.yaml", "greeting: hello\nfarewell: goodbye\nthanks: cheers\n"))
|
||||
assert result.get("skipped") == "data yaml (not a config/manifest)"
|
||||
|
||||
|
||||
def test_openapi_spec_yaml_is_skipped(tmp_path):
|
||||
"""An OpenAPI/Swagger spec is data-heavy API description, not a config to walk."""
|
||||
result = extract_yaml(_write(
|
||||
tmp_path / "api.yaml",
|
||||
"openapi: 3.0.0\npaths:\n /x:\n get:\n responses:\n '200':\n description: ok\n"))
|
||||
assert result.get("skipped") == "data yaml (not a config/manifest)"
|
||||
|
||||
|
||||
def test_top_level_data_array_is_skipped(tmp_path):
|
||||
result = extract_yaml(_write(tmp_path / "list.yaml", "- one\n- two\n- three\n"))
|
||||
assert result.get("skipped") == "data yaml (not a config/manifest)"
|
||||
|
||||
|
||||
def test_unsafe_yaml_tag_does_not_execute(tmp_path):
|
||||
"""extract_yaml must use safe_load (never load): a `!!python/...` tag raises
|
||||
instead of executing arbitrary code on an untrusted repo."""
|
||||
marker = tmp_path / "pwned"
|
||||
path = _write(
|
||||
tmp_path / "evil.yaml",
|
||||
f"danger: !!python/object/apply:os.system ['touch {marker}']\n",
|
||||
)
|
||||
result = extract_yaml(path)
|
||||
assert "error" in result
|
||||
assert not marker.exists(), "safe_load must not execute the python tag"
|
||||
|
||||
|
||||
def test_extract_yaml_caps_bound_output(tmp_path):
|
||||
"""A config-named YAML with thousands of keys is bounded by the 500-pair cap."""
|
||||
body = "root:\n" + "".join(f" k{i}: {i}\n" for i in range(2000))
|
||||
result = extract_yaml(_write(tmp_path / "values.yaml", body))
|
||||
assert len(result["nodes"]) <= 502 # file node + root key + at most 500 pairs
|
||||
Reference in new issue
Block a user