Skip to content

Commit 8566492

Browse files
Faisal-Fayazclaude
authored andcommitted
fix(extract): stop walking JSON Schema files as config manifests (#2255)
`_is_config_json()` decides whether a `.json` file is worth AST-walking. It matches by filename first, then falls back to a root-key probe. `$schema` was in that probe's key set -- correctly, since configs legitimately carry it -- but it is also the *defining marker* of a JSON Schema, so every schema document satisfied the probe and got walked in full. That re-opened the keyword-node explosion #1224 closed for data JSON: one 160 KB contract contributed 362 nodes labelled with bare schema keywords (`description` x113, `type` x83, `$ref` x53, ...) plus ~12 schema-only communities, polluting clustering, god-node analysis and GRAPH_REPORT.md. Two changes, both ahead of the existing probe: - Drop `$ref` from the probe keys. A root-level `$ref` is a schema construct and never a config signal. - Return False when the root object carries `$schema` *plus* a schema-definition marker (`$defs`, `definitions`, or `$id`). This is what separates "this file IS a schema" from "this config POINTS AT a schema": the latter points `$schema` at its own tool's schema (biomejs.dev, docs.renovatebot.com) and never carries these markers. The blast radius is smaller than it looks. The filename branches run first, so biome.json / renovate.json / package.json / tsconfig.json never depended on the probe at all; only arbitrarily-named files did. I confirmed this against a control matrix before and after -- every config shape keeps byte-identical node counts. The root keys are now collected once into a set so the schema check and the config probe agree on the same read of the file, rather than walking the root twice. Documented boundary, pinned by a test: a hand-written schema carrying only `$schema` + `properties` (no `$defs`/`definitions`/`$id`) is still walked. Closing that gap needs a keyword-density heuristic, which would risk skipping a real config whose keys overlap schema vocabulary -- the worse error, since it drops structure silently. Left for a deliberate change rather than guessed at. Verified: - uv run pytest tests/test_json_schema_config.py -q (14 passed; 5 fail pre-fix) - uv run pytest tests/ -q -> 28 failed, 6262 passed, 101 skipped - baseline on a clean v0.9.75 checkout: 28 failed, 6248 passed, 101 skipped The 28 failures are byte-identical between the two (missing tree-sitter grammars for erlang/R/solidity/vbnet, plus ollama retry tests) and are diffed test-id-by-test-id, not compared by count. Passing delta is exactly +14. - uv run ruff check . -> clean - uv run pyright -> 636 errors, identical to the clean v0.9.75 baseline Co-Authored-By: Claude <[email protected]> (cherry picked from commit f45ea17)
1 parent 48de615 commit 8566492

2 files changed

Lines changed: 272 additions & 9 deletions

File tree

‎graphify/extractors/json_config.py‎

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,44 +18,80 @@
1818
_CONFIG_JSON_KEYS = frozenset({
1919
"dependencies", "devDependencies", "peerDependencies",
2020
"optionalDependencies", "bundleDependencies", "bundledDependencies",
21-
"extends", "$ref", "$schema", "compilerOptions",
21+
"extends", "$schema", "compilerOptions",
2222
})
2323

24+
# Root-level keys that only a JSON Schema *document* carries. A schema that
25+
# defines anything needs somewhere to put the definitions, and the spec's own
26+
# keywords for that are `$defs` (2020-12) and `definitions` (draft-07/04);
27+
# `$id` names the schema itself. Combined with `$schema` these separate "this
28+
# file IS a schema" from "this config POINTS AT a schema" -- the latter points
29+
# $schema at its own tool's schema (biomejs.dev, docs.renovatebot.com, ...),
30+
# never at the meta-schema, and never carries these markers.
31+
_SCHEMA_DEFINITION_KEYS = frozenset({"$defs", "definitions", "$id"})
32+
33+
2434
def _is_config_json(path: Path, obj_node, source: bytes) -> bool:
2535
"""True if a .json file is a recognized config/manifest worth AST-extracting.
2636
2737
Matches by filename first (cheap), then falls back to a top-level key probe
2838
so arbitrarily-named config files (e.g. ``api.tsconfig.json``,
2939
``foo.eslintrc.json``) are still picked up. Returns False for data JSON so it
30-
is skipped by the structural pass (#1224)."""
40+
is skipped by the structural pass (#1224).
41+
42+
A JSON Schema is *not* a config manifest. `$schema` sits in the probe's key
43+
set because configs legitimately carry it, but it is also the defining marker
44+
of a schema -- so a schema document satisfied the probe and was walked in
45+
full, re-opening the keyword-node explosion #1224 closed (#2255). One 160 KB
46+
contract contributed 362 keyword nodes and ~12 schema-only communities. The
47+
filename branches above run first, so `biome.json`/`renovate.json`/
48+
`package.json` never depended on the probe; the probe only decides the fate
49+
of arbitrarily-named files, which is why narrowing it is low-risk.
50+
51+
Documented boundary: a hand-written schema carrying `$schema` but no
52+
`$defs`/`definitions`/`$id` is still walked. Catching it would need a
53+
keyword-density heuristic, which would risk skipping a real config whose keys
54+
happen to overlap schema vocabulary -- the worse error, since it drops
55+
structure silently (#1224). Pinned by
56+
``tests/test_json_schema_config.py::test_minimal_schema_without_defs_or_id_is_still_walked``.
57+
"""
3158
name = path.name.casefold()
3259
if name in _CONFIG_JSON_NAMES:
3360
return True
3461
# Common compound config names: *.eslintrc.json, *.prettierrc.json, etc.
3562
if name.endswith((".eslintrc.json", ".prettierrc.json", ".babelrc.json",
3663
"tsconfig.json", "jsconfig.json")):
3764
return True
38-
# Top-level key probe: scan the root object's immediate keys (no deep walk).
65+
# Collect the root object's immediate keys once (no deep walk), so the
66+
# schema check below and the config probe agree on the same key set.
67+
root_keys: set[str] = set()
3968
for top_key in obj_node.children:
4069
if top_key.type != "pair":
4170
continue
4271
key_node = top_key.child_by_field_name("key")
4372
if key_node is None:
4473
continue
4574
kc = key_node.child_by_field_name("string_content")
46-
text = _read_text(kc, source) if kc else _read_text(key_node, source).strip('"\'')
47-
if text in _CONFIG_JSON_KEYS:
48-
return True
75+
root_keys.add(_read_text(kc, source) if kc
76+
else _read_text(key_node, source).strip('"\''))
77+
# A file that declares the meta-schema AND defines something IS a schema.
78+
if "$schema" in root_keys and (root_keys & _SCHEMA_DEFINITION_KEYS):
79+
return False
80+
# Top-level key probe. `$ref` is deliberately absent: a root-level `$ref` is
81+
# a schema construct and never a config signal (#2255).
82+
if root_keys & _CONFIG_JSON_KEYS:
83+
return True
4984
return False
5085

5186
def extract_json(path: Path) -> dict:
5287
"""Extract structure and dependency edges from a *config/manifest* .json file.
5388
5489
Data-shaped JSON (eval fixtures, datasets, GeoJSON, API response dumps) is
5590
deliberately skipped — AST-walking it produced hundreds of orphan key-nodes
56-
and duplicate communities that swamped real structure (#1224). Recognition
57-
is by filename (package.json, tsconfig.json, …) or a top-level key probe
58-
(dependencies / extends / $ref / $schema / compilerOptions)."""
91+
and duplicate communities that swamped real structure (#1224). JSON Schema
92+
documents are skipped for the same reason (#2255). Recognition is by filename
93+
(package.json, tsconfig.json, …) or a top-level key probe (dependencies /
94+
extends / $schema / compilerOptions)."""
5995
_JSON_MAX_BYTES = 1_048_576 # 1 MiB — skip large fixture dumps / GeoJSON blobs
6096

6197
try:

‎tests/test_json_schema_config.py‎

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
"""JSON Schema files must not be mistaken for config manifests.
2+
3+
`_is_config_json()` decides whether a `.json` file is worth AST-walking. It
4+
matches by filename first, then falls back to a root-key probe. But `$schema`
5+
was in that probe's key set, and `$schema` is the *defining marker* of a JSON
6+
Schema -- so every schema document satisfied the probe and got walked in full,
7+
re-opening the keyword-node explosion #1224 closed for data JSON.
8+
9+
One 160 KB contract contributed 362 nodes whose labels were bare schema
10+
keywords (`description`, `type`, `$ref`, `required`, `properties`), plus ~12
11+
schema-only communities that polluted clustering, god-node analysis and
12+
`GRAPH_REPORT.md` -- 13% of a 2,725-node graph (#2255).
13+
14+
These tests pin both directions, because the fix removes keys from the probe and
15+
the risk is over-correcting into skipping real configs:
16+
17+
- a file that *is* a schema (`$schema` plus a schema-definition marker) is
18+
skipped, not walked
19+
- a root-level `$ref`, which is a schema construct and never a config signal,
20+
no longer implies config
21+
- every config shape that reaches the probe -- including configs that carry
22+
`$schema` themselves -- is still extracted
23+
24+
The filename branches run before the probe, so `biome.json`/`renovate.json`/
25+
`package.json` never depended on the probe at all; those are pinned explicitly
26+
anyway, because a fix here must not be able to change them.
27+
"""
28+
from pathlib import Path
29+
30+
from graphify.extractors.json_config import extract_json
31+
32+
# A JSON Schema as a contract file actually looks like: `$id` + `$defs`.
33+
SCHEMA_WITH_DEFS = '''\
34+
{
35+
"$schema": "https://json-schema.org/draft/2020-12/schema",
36+
"$id": "https://example.com/events-v1.json",
37+
"title": "Event catalogue",
38+
"$defs": {
39+
"dataClassification": {
40+
"description": "Handling class for the event payload.",
41+
"type": "string",
42+
"enum": ["Public", "Internal", "CUI"]
43+
},
44+
"event": {
45+
"description": "One domain event.",
46+
"type": "object",
47+
"required": ["id", "kind"],
48+
"properties": {
49+
"id": {"description": "Stable id.", "type": "string"},
50+
"kind": {"description": "Event kind.", "type": "string"},
51+
"seq": {"description": "Sequence.", "type": "integer", "minimum": 0},
52+
"tags": {"description": "Tags.", "type": "array",
53+
"items": {"type": "string"}},
54+
"shape": {"description": "One shape.", "oneOf": [{"type": "string"}]}
55+
},
56+
"additionalProperties": false
57+
}
58+
},
59+
"$ref": "#/$defs/event"
60+
}
61+
'''
62+
63+
SCHEMA_WITH_LEGACY_DEFS = '''\
64+
{
65+
"$schema": "http://json-schema.org/draft-07/schema#",
66+
"definitions": {
67+
"point": {"description": "A point.", "type": "object"}
68+
},
69+
"$ref": "#/definitions/point"
70+
}
71+
'''
72+
73+
# A root-level $ref is a schema construct, never a config signal.
74+
SCHEMA_REF_ONLY = '{"$ref": "https://example.com/other.json"}'
75+
76+
# Real configs that carry $schema themselves. These point at their OWN tool's
77+
# schema, not at the JSON Schema meta-schema -- which is exactly why $schema
78+
# cannot be read as "this file is a schema".
79+
BIOME = '''\
80+
{
81+
"$schema": "https://biomejs.dev/schemas/1.7.0/schema.json",
82+
"files": {"include": ["src"]},
83+
"linter": {"enabled": true}
84+
}
85+
'''
86+
87+
RENOVATE = '''\
88+
{
89+
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
90+
"extends": ["config:base"]
91+
}
92+
'''
93+
94+
# Arbitrary filename -> only the root-key probe can catch these.
95+
PROBE_EXTENDS = '{"extends": "./base.json", "rules": {"eqeqeq": "error"}}'
96+
PROBE_COMPILER = '{"compilerOptions": {"strict": true, "target": "es2022"}}'
97+
SUFFIX_TSCONFIG = '{"compilerOptions": {"strict": true}}'
98+
99+
100+
def _write(tmp_path, name, body):
101+
p = Path(tmp_path) / name
102+
p.parent.mkdir(parents=True, exist_ok=True)
103+
p.write_text(body)
104+
return p
105+
106+
107+
def _labels(result):
108+
return [n["label"] for n in result["nodes"]]
109+
110+
111+
def _is_skipped(result):
112+
return result.get("skipped") == "data json (not a config/manifest)"
113+
114+
115+
# --- the schema side: these must stop being walked -------------------------
116+
117+
def test_schema_with_defs_is_skipped_not_walked(tmp_path):
118+
r = extract_json(_write(tmp_path, "events-v1.json", SCHEMA_WITH_DEFS))
119+
assert _is_skipped(r), r
120+
assert r["nodes"] == []
121+
assert r["edges"] == []
122+
123+
124+
def test_schema_with_legacy_definitions_is_skipped(tmp_path):
125+
# draft-07 schemas spell the same thing `definitions`.
126+
r = extract_json(_write(tmp_path, "legacy.json", SCHEMA_WITH_LEGACY_DEFS))
127+
assert _is_skipped(r), r
128+
assert r["nodes"] == []
129+
130+
131+
def test_schema_with_defs_in_subdirectory_is_skipped(tmp_path):
132+
# The reporter's file lived at contracts/events-v1.json, i.e. the filename
133+
# branch could never have matched it -- only the probe could.
134+
r = extract_json(_write(tmp_path, "contracts/events-v1.json", SCHEMA_WITH_DEFS))
135+
assert _is_skipped(r), r
136+
137+
138+
def test_root_level_ref_alone_is_skipped(tmp_path):
139+
r = extract_json(_write(tmp_path, "ref.json", SCHEMA_REF_ONLY))
140+
assert _is_skipped(r), r
141+
assert r["nodes"] == []
142+
143+
144+
def test_schema_produces_no_keyword_nodes(tmp_path):
145+
# The actual symptom: bare schema keywords became graph nodes.
146+
r = extract_json(_write(tmp_path, "events-v1.json", SCHEMA_WITH_DEFS))
147+
keywords = {"description", "type", "properties", "required",
148+
"additionalProperties", "oneOf", "items", "enum"}
149+
assert not keywords & set(_labels(r)), _labels(r)
150+
151+
152+
# --- the config side: the fix must not over-correct ------------------------
153+
154+
def test_biome_json_with_its_own_schema_key_is_still_extracted(tmp_path):
155+
# biome.json points $schema at biome's schema, not at the meta-schema. It is
156+
# filename-matched, so it never depended on the probe -- pinned so this fix
157+
# provably cannot affect it.
158+
r = extract_json(_write(tmp_path, "biome.json", BIOME))
159+
assert not _is_skipped(r), r
160+
assert "linter" in _labels(r)
161+
162+
163+
def test_renovate_json_with_schema_and_extends_is_still_extracted(tmp_path):
164+
r = extract_json(_write(tmp_path, "renovate.json", RENOVATE))
165+
assert not _is_skipped(r), r
166+
assert "extends" in _labels(r)
167+
168+
169+
def test_package_json_is_still_extracted(tmp_path):
170+
r = extract_json(_write(tmp_path, "package.json",
171+
'{"name": "x", "devDependencies": {"jest": "^29"}}'))
172+
assert not _is_skipped(r), r
173+
assert "devDependencies" in _labels(r)
174+
175+
176+
def test_probe_still_recognises_extends_by_arbitrary_filename(tmp_path):
177+
# `extends` stays in the probe; only $ref left.
178+
r = extract_json(_write(tmp_path, "custom.config.json", PROBE_EXTENDS))
179+
assert not _is_skipped(r), r
180+
assert "extends" in _labels(r)
181+
182+
183+
def test_probe_still_recognises_compileroptions_by_arbitrary_filename(tmp_path):
184+
r = extract_json(_write(tmp_path, "weird.json", PROBE_COMPILER))
185+
assert not _is_skipped(r), r
186+
assert "compilerOptions" in _labels(r)
187+
188+
189+
def test_compound_suffix_match_is_unaffected(tmp_path):
190+
r = extract_json(_write(tmp_path, "api.tsconfig.json", SUFFIX_TSCONFIG))
191+
assert not _is_skipped(r), r
192+
assert "compilerOptions" in _labels(r)
193+
194+
195+
def test_dev_dependencies_probe_still_works(tmp_path):
196+
r = extract_json(_write(tmp_path, "deps.json", PROBE_COMPILER))
197+
assert not _is_skipped(r), r
198+
199+
200+
# --- documented boundary, pinned so a future change is deliberate ----------
201+
202+
def test_minimal_schema_without_defs_or_id_is_still_walked(tmp_path):
203+
"""A hand-written schema carrying only `$schema` + `properties` is still walked.
204+
205+
This is a known, accepted residual: catching it needs a keyword-density
206+
heuristic, which would risk the opposite error -- skipping a real config
207+
whose keys happen to overlap schema vocabulary. Pinned here so that closing
208+
the gap later is a deliberate change with a test, not an accident.
209+
210+
`$defs`, `$id` and `definitions` are spec-defined and value-independent, so
211+
they are the markers the fix relies on; this case has none of them.
212+
"""
213+
body = ('{"$schema": "https://json-schema.org/draft/2020-12/schema",'
214+
' "type": "object", "properties": {"a": {"type": "string"}}}')
215+
r = extract_json(_write(tmp_path, "minimal.schema.json", body))
216+
assert not _is_skipped(r), r
217+
assert "properties" in _labels(r)
218+
219+
220+
# --- determinism -----------------------------------------------------------
221+
222+
def test_classification_is_deterministic_across_repeated_calls(tmp_path):
223+
# Extraction must not depend on ordering or ambient state (CONTRIBUTING #3).
224+
p = _write(tmp_path, "events-v1.json", SCHEMA_WITH_DEFS)
225+
first = _labels(extract_json(p))
226+
for _ in range(5):
227+
assert _labels(extract_json(p)) == first

0 commit comments

Comments
 (0)