fix(build): tolerate structured enum fields

Report malformed enum values without hashing them, and use conservative builder fallbacks so one structured field cannot abort a usable extraction.

Refs #5086

Co-authored-by: OpenAI <noreply@openai.com>
(cherry picked from commit 00da7d0155)
This commit is contained in:
sdivyanshu90 authored and safishamsi committed 2026-11-09 16:44:04 +00:00
1 parent 177b35e6a5
commit b327203c30
4 files changed
+67 -3

No files matched your search

+5
View File
@@ -79,6 +79,11 @@ Every extractor returns:
`validate.py` enforces this schema before `build()` consumes it.
Validation reports list/object enum values as schema errors. Graph assembly
repairs structured `file_type` values to `concept` and structured `confidence`
values to `INFERRED`, without fabricating a confidence score, so malformed
semantic fields cannot abort an otherwise usable build.
JS/TS calls through default imports of directly default-exported object literals reuse existing static method nodes.
Members match the imported module path, exact label and source line. Lexically shadowed receivers, constructor calls,
spread, computed keys, accessors, duplicate keys and dynamic aliases are not inferred. These files bypass the per-file
+9 -1
View File
@@ -723,6 +723,10 @@ def _fold_confidence(obj: dict) -> None:
model-drifted string confidences re-warns on every command forever,
identically to the numeric gap above.
Structured JSON values (lists/objects) carry no usable confidence. They
fall back to ``INFERRED`` without inventing a numeric score, just like
an unrecognized nonnumeric string, before validation can hash them.
``confidence_score`` itself is NOT popped in either case: it is a
legitimate companion field the edge loop sanitizes and to_json
round-trips.
@@ -743,6 +747,8 @@ def _fold_confidence(obj: dict) -> None:
except ValueError:
pass
obj["confidence"] = "INFERRED"
elif isinstance(_conf, (list, dict)):
obj["confidence"] = "INFERRED"
if not obj.get("confidence") and obj.get("confidence_score") is not None:
obj["confidence"] = "INFERRED"
@@ -1622,7 +1628,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
if node.get("file_type") in (None, ""):
node["file_type"] = "concept"
ft = node.get("file_type", "")
if ft and ft not in {"code", "document", "paper", "image", "rationale", "concept"}:
if not isinstance(ft, str):
node["file_type"] = "concept"
elif ft and ft not in {"code", "document", "paper", "image", "rationale", "concept"}:
node["file_type"] = _FILE_TYPE_SYNONYMS.get(ft, "concept")
# Canonicalize hyperedge member lists (#1561): producers sometimes key the
+7 -2
View File
@@ -45,7 +45,9 @@ def validate_extraction(data: dict) -> list[str]:
)
else:
node_ids.add(node["id"])
if "file_type" in node and node["file_type"] not in VALID_FILE_TYPES:
if "file_type" in node and (
not isinstance(node["file_type"], str) or node["file_type"] not in VALID_FILE_TYPES
):
errors.append(
f"Node {i} (id={node.get('id', '?')!r}) has invalid file_type "
f"'{node['file_type']}' - must be one of {sorted(VALID_FILE_TYPES)}"
@@ -65,7 +67,10 @@ def validate_extraction(data: dict) -> list[str]:
for field in REQUIRED_EDGE_FIELDS:
if field not in edge:
errors.append(f"Edge {i} missing required field '{field}'")
if "confidence" in edge and edge["confidence"] not in VALID_CONFIDENCES:
if "confidence" in edge and (
not isinstance(edge["confidence"], str)
or edge["confidence"] not in VALID_CONFIDENCES
):
errors.append(
f"Edge {i} has invalid confidence '{edge['confidence']}' "
f"- must be one of {sorted(VALID_CONFIDENCES)}"
+46
View File
@@ -1,4 +1,5 @@
import pytest
from copy import deepcopy
from graphify.validate import validate_extraction, assert_valid
VALID = {
@@ -15,6 +16,51 @@ VALID = {
def test_valid_passes():
assert validate_extraction(VALID) == []
@pytest.mark.parametrize("value", [[], {}, ["code"], {"value": "code"}])
@pytest.mark.parametrize("collection,field", [("nodes", "file_type"), ("edges", "confidence")])
def test_structured_enum_values_reported_not_raised(collection, field, value):
data = deepcopy(VALID)
data[collection][0][field] = value
errors = validate_extraction(data)
assert any(f"invalid {field}" in error for error in errors)
with pytest.raises(ValueError, match=f"invalid {field}"):
assert_valid(data)
@pytest.mark.parametrize("value", [[], {}, ["code"], {"value": "code"}])
@pytest.mark.parametrize("entry_point", ["build", "build_from_json"])
def test_build_repairs_structured_enum_values(entry_point, value):
from graphify.build import build, build_from_json
data = deepcopy(VALID)
data["nodes"][0]["file_type"] = value
data["edges"][0]["confidence"] = value
graph = build([data]) if entry_point == "build" else build_from_json(data)
assert graph.number_of_nodes() == 2
assert graph.number_of_edges() == 1
assert graph.nodes["n1"]["file_type"] == "concept"
assert graph.nodes["n2"]["file_type"] == "document"
edge = next(iter(graph.edges(data=True)))[2]
assert edge["confidence"] == "INFERRED"
assert "confidence_score" not in edge
assert edge["relation"] == "references"
assert edge["source_file"] == "foo.py"
@pytest.mark.parametrize("value", [["EXTRACTED"], {"value": "EXTRACTED"}])
def test_build_repairs_structured_confidence_on_hyperedges(value):
from graphify.build import build_from_json
data = deepcopy(VALID)
data["nodes"].append(
{"id": "n3", "label": "Baz", "file_type": "document", "source_file": "baz.md"}
)
data["hyperedges"] = [{"nodes": ["n1", "n2", "n3"], "confidence": value}]
graph = build_from_json(data)
assert graph.graph["hyperedges"][0]["confidence"] == "INFERRED"
assert set(graph.graph["hyperedges"][0]["nodes"]) == {"n1", "n2", "n3"}
def test_missing_nodes_key():
errors = validate_extraction({"edges": []})
assert any("nodes" in e for e in errors)