From 60bed4a499c5469f83b06bd1932aec6bff59ba2c Mon Sep 17 00:00:00 2001 From: Pol Michel Date: Tue, 1 Dec 2026 15:10:45 +0100 Subject: [PATCH 1/2] fix(utils): extract the fields of an inline fragment nested in another extract_fields read .name on every child of an inline fragment, so a nested inline fragment raised AttributeError. Infrahub calls it through GraphQLQueryAnalyzer.calculate_depth after it runs an operation, and answered such a query with HTTP 500. An inline fragment now contributes the fields that extract_fields returns for its selection set. A fragment spread inside an inline fragment is skipped, as it already was outside one, instead of being reported as a field named after the fragment. Co-Authored-By: Claude Fable 5.2 --- ...act-fields-nested-inline-fragment.fixed.md | 1 + infrahub_sdk/utils.py | 27 +++++----- tests/unit/sdk/test_query_analyzer.py | 10 ++++ tests/unit/sdk/test_utils.py | 49 +++++++++++++++++++ 4 files changed, 72 insertions(+), 15 deletions(-) create mode 100644 changelog/+extract-fields-nested-inline-fragment.fixed.md diff --git a/changelog/+extract-fields-nested-inline-fragment.fixed.md b/changelog/+extract-fields-nested-inline-fragment.fixed.md new file mode 100644 index 000000000..9c45ec45f --- /dev/null +++ b/changelog/+extract-fields-nested-inline-fragment.fixed.md @@ -0,0 +1 @@ +Fixed `extract_fields` raising `AttributeError: 'InlineFragmentNode' object has no attribute 'name'` for a query that writes an inline fragment inside another inline fragment, such as `query { ... on Query { ... { TestPerson { id } } } }`. `GraphQLQueryAnalyzer.get_fields`, `calculate_depth` and `calculate_height` raised the same error for such a query. The fields of a nested inline fragment are now reported at the level of the enclosing fragment. A fragment spread inside an inline fragment is no longer reported as a field named after the fragment. diff --git a/infrahub_sdk/utils.py b/infrahub_sdk/utils.py index 95da7504d..f31122296 100644 --- a/infrahub_sdk/utils.py +++ b/infrahub_sdk/utils.py @@ -286,28 +286,25 @@ async def extract_fields(selection_set: SelectionSetNode | None) -> dict[str, di if not selection_set: return None - fields = {} + fields: dict[str, Any] = {} for node in selection_set.selections: - sub_selection_set = getattr(node, "selection_set", None) if isinstance(node, FieldNode): - value = await extract_fields(sub_selection_set) - if node.name.value not in fields: - fields[node.name.value] = value - elif isinstance(fields[node.name.value], dict) and isinstance(value, dict): - fields[node.name.value].update(value) - + _merge_extracted_field(fields=fields, name=node.name.value, value=await extract_fields(node.selection_set)) elif isinstance(node, InlineFragmentNode): - for sub_node in node.selection_set.selections: - sub_sub_selection_set = getattr(sub_node, "selection_set", None) - value = await extract_fields(sub_sub_selection_set) - if sub_node.name.value not in fields: - fields[sub_node.name.value] = await extract_fields(sub_sub_selection_set) - elif isinstance(fields[sub_node.name.value], dict) and isinstance(value, dict): - fields[sub_node.name.value].update(value) + # The fields of an inline fragment, and of any inline fragment nested in it, belong to the enclosing level. + for name, value in (await extract_fields(node.selection_set) or {}).items(): + _merge_extracted_field(fields=fields, name=name, value=value) return fields +def _merge_extracted_field(fields: dict[str, Any], name: str, value: dict | None) -> None: + if name not in fields: + fields[name] = value + elif isinstance(fields[name], dict) and isinstance(value, dict): + fields[name].update(value) + + async def extract_fields_first_node(info: GraphQLResolveInfo) -> dict[str, dict]: fields = None if info.field_nodes: diff --git a/tests/unit/sdk/test_query_analyzer.py b/tests/unit/sdk/test_query_analyzer.py index c078b3b3d..214b99db2 100644 --- a/tests/unit/sdk/test_query_analyzer.py +++ b/tests/unit/sdk/test_query_analyzer.py @@ -283,3 +283,13 @@ def test_operations_do_not_repeat_a_diamond_fragment() -> None: ) assert gqa.operations == [MUTATION_OPERATION] + + +async def test_depth_and_height_of_nested_inline_fragments() -> None: + """A query measures the same whether its fields are written plainly or inside nested inline fragments.""" + plain = GraphQLQueryAnalyzer(query="query { TestPerson { name { value } } }") + nested = GraphQLQueryAnalyzer(query="query { ... on Query { ... { TestPerson { name { value } } } } }") + + assert await nested.get_fields() == await plain.get_fields() + assert await nested.calculate_depth() == await plain.calculate_depth() + assert await nested.calculate_height() == await plain.calculate_height() diff --git a/tests/unit/sdk/test_utils.py b/tests/unit/sdk/test_utils.py index 97ea6d27d..b7e38aec8 100644 --- a/tests/unit/sdk/test_utils.py +++ b/tests/unit/sdk/test_utils.py @@ -226,6 +226,55 @@ async def test_extract_fields_fragment(query_02: str) -> None: assert await extract_fields(definition.selection_set) == expected_response +@dataclass +class NestedInlineFragmentCase: + name: str + query: str + expected_fields: dict[str, Any] + + +NESTED_INLINE_FRAGMENT_CASES = [ + NestedInlineFragmentCase( + name="at_the_operation_root", + query="query { ... on Query { ... { TestPerson { name { value } } } } }", + expected_fields={"TestPerson": {"name": {"value": None}}}, + ), + NestedInlineFragmentCase( + name="below_a_field", + query="query { TestCar { ... on TestElectricCar { ... on TestCar { name { value } } nbr_engine { value } } } }", + expected_fields={"TestCar": {"name": {"value": None}, "nbr_engine": {"value": None}}}, + ), + NestedInlineFragmentCase( + name="three_levels", + query="query { ... { ... { ... { TestPerson { id } } } } }", + expected_fields={"TestPerson": {"id": None}}, + ), + NestedInlineFragmentCase( + name="merged_with_the_same_field_of_the_enclosing_fragment", + query="query { ... { TestPerson { id } ... { TestPerson { name { value } } } } }", + expected_fields={"TestPerson": {"id": None, "name": {"value": None}}}, + ), +] + + +@pytest.mark.parametrize("case", NESTED_INLINE_FRAGMENT_CASES, ids=lambda case: case.name) +async def test_extract_fields_nested_inline_fragment(case: NestedInlineFragmentCase) -> None: + """An inline fragment written inside another inline fragment contributes its fields like its parent.""" + definition = parse(case.query).definitions[0] + assert isinstance(definition, OperationDefinitionNode) + assert await extract_fields(definition.selection_set) == case.expected_fields + + +async def test_extract_fields_ignores_fragment_spread_in_inline_fragment() -> None: + """A fragment spread is not a field: inside an inline fragment it is skipped, as it is anywhere else.""" + document = parse( + "query { TestPerson { ... on TestPerson { id ...Names } } } fragment Names on TestPerson { name { value } }" + ) + definition = document.definitions[0] + assert isinstance(definition, OperationDefinitionNode) + assert await extract_fields(definition.selection_set) == {"TestPerson": {"id": None}} + + def test_write_to_file() -> None: tmp_dir = tempfile.TemporaryDirectory() directory = Path(tmp_dir.name) From 393241eddba7dadeb6b76d2bf85275424d1e5680 Mon Sep 17 00:00:00 2001 From: Pol Michel Date: Tue, 1 Dec 2026 16:13:43 +0100 Subject: [PATCH 2/2] fix(utils): keep every sub-field of a field selected twice extract_fields merged two selections of the same field with dict.update, which replaced the nested dictionaries of the first selection. For `cars { edges { node { id } } } cars { edges { node { name } } }` only `name` remained under `node`. A field selected first without sub-fields and then with them kept none. The merge now uses deep_merge_dict, so the selections are combined at every level. Co-Authored-By: Claude Fable 5.2 --- .../+extract-fields-repeated-field.fixed.md | 1 + infrahub_sdk/utils.py | 7 +-- tests/unit/sdk/test_utils.py | 46 +++++++++++++++++++ 3 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 changelog/+extract-fields-repeated-field.fixed.md diff --git a/changelog/+extract-fields-repeated-field.fixed.md b/changelog/+extract-fields-repeated-field.fixed.md new file mode 100644 index 000000000..49f9eb0af --- /dev/null +++ b/changelog/+extract-fields-repeated-field.fixed.md @@ -0,0 +1 @@ +Fixed `extract_fields` dropping sub-fields of a field that a query selects more than once. For `cars { edges { node { id } } } cars { edges { node { name { value } } } }`, only `name` was reported under `node`; both `id` and `name` are now reported. A field selected once without sub-fields and once with them now reports the sub-fields. `GraphQLQueryAnalyzer.get_fields`, `calculate_depth` and `calculate_height` read this result, so the depth and height of such a query can be higher than before. diff --git a/infrahub_sdk/utils.py b/infrahub_sdk/utils.py index f31122296..71857a05b 100644 --- a/infrahub_sdk/utils.py +++ b/infrahub_sdk/utils.py @@ -299,10 +299,11 @@ async def extract_fields(selection_set: SelectionSetNode | None) -> dict[str, di def _merge_extracted_field(fields: dict[str, Any], name: str, value: dict | None) -> None: - if name not in fields: + """Record one selection of a field, keeping the sub-fields of every earlier selection of the same field.""" + if fields.get(name) is None: fields[name] = value - elif isinstance(fields[name], dict) and isinstance(value, dict): - fields[name].update(value) + elif value is not None: + deep_merge_dict(fields[name], value) async def extract_fields_first_node(info: GraphQLResolveInfo) -> dict[str, dict]: diff --git a/tests/unit/sdk/test_utils.py b/tests/unit/sdk/test_utils.py index b7e38aec8..f0eb2ae30 100644 --- a/tests/unit/sdk/test_utils.py +++ b/tests/unit/sdk/test_utils.py @@ -275,6 +275,52 @@ async def test_extract_fields_ignores_fragment_spread_in_inline_fragment() -> No assert await extract_fields(definition.selection_set) == {"TestPerson": {"id": None}} +@dataclass +class RepeatedFieldCase: + name: str + query: str + expected_fields: dict[str, Any] + + +REPEATED_FIELD_CASES = [ + RepeatedFieldCase( + name="two_plain_selections", + query="query { TestPerson { cars { edges { node { id } } } cars { edges { node { name { value } } } } } }", + expected_fields={"TestPerson": {"cars": {"edges": {"node": {"id": None, "name": {"value": None}}}}}}, + ), + RepeatedFieldCase( + name="inline_fragment_then_plain_selection", + query="query { TestPerson { ... on TestPerson { cars { edges { node { id } } } }" + " cars { edges { node { name { value } } } } } }", + expected_fields={"TestPerson": {"cars": {"edges": {"node": {"id": None, "name": {"value": None}}}}}}, + ), + RepeatedFieldCase( + name="two_inline_fragments", + query="query { TestCar { ... on TestElectricCar { owner { node { id } } }" + " ... on TestGazCar { owner { node { name { value } } } } } }", + expected_fields={"TestCar": {"owner": {"node": {"id": None, "name": {"value": None}}}}}, + ), + RepeatedFieldCase( + name="without_then_with_sub_fields", + query="query { TestPerson { cars cars { id } } }", + expected_fields={"TestPerson": {"cars": {"id": None}}}, + ), + RepeatedFieldCase( + name="with_then_without_sub_fields", + query="query { TestPerson { cars { id } cars } }", + expected_fields={"TestPerson": {"cars": {"id": None}}}, + ), +] + + +@pytest.mark.parametrize("case", REPEATED_FIELD_CASES, ids=lambda case: case.name) +async def test_extract_fields_merges_a_field_selected_twice(case: RepeatedFieldCase) -> None: + """A field selected twice reports the sub-fields of both selections, at every level.""" + definition = parse(case.query).definitions[0] + assert isinstance(definition, OperationDefinitionNode) + assert await extract_fields(definition.selection_set) == case.expected_fields + + def test_write_to_file() -> None: tmp_dir = tempfile.TemporaryDirectory() directory = Path(tmp_dir.name)