graphql-platform icon indicating copy to clipboard operation
graphql-platform copied to clipboard

Fusion tries to resolve data from subgraph without top-level resolver

Open interad-woergoetter opened this issue 3 years ago • 7 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Product

Hot Chocolate

Describe the bug

Fusion will try to resolve data from the first subgraph that has all (or the most of) the requested data in its schema, regardless of whether that subgraph has a top-level resolver for the type in question. This leads to an error during execution plan creation.

It appears that the query plan generator iterates over all subgraphs in order, i.e. alphabetically, meaning the names of the subgraphs impact the reproducability of this issue.

Steps to reproduce

  1. Set up a Fusion gateway server with the attached gateway package. gateway.fgp.zip
  2. Start the gateway server.
  3. Send the query query { foos { id name nameReversed } } to the gateway.
  4. Confirm that the gateway is able to create a query plan fetching additional data from Subgraph3.
  5. Now send the query query { foos { id name } } to the gateway.
  6. Notice that the gateway is not able to create a query plan.

Relevant log output

{
  "errors": [
    {
      "message": "Unexpected Execution Error",
      "extensions": {
        "message": "There must be a field resolver definition in this context!",
        "stackTrace": "   at HotChocolate.Fusion.Planning.Pipeline.ExecutionStepDiscoveryMiddleware.CreateExecutionSteps(QueryPlanContext context, Queue`1 backlog, ObjectTypeMetadata selectionSetTypeMetadata, IReadOnlyList`1 selections, ISelection parentSelection, SelectionPath parentSelectionPath, Boolean preferBatching)\r\n   at HotChocolate.Fusion.Planning.Pipeline.ExecutionStepDiscoveryMiddleware.Invoke(QueryPlanContext context, QueryPlanDelegate next)\r\n   at HotChocolate.Fusion.Planning.QueryPlanPipelineBuilder.<>c__DisplayClass5_1`1.<Use>b__1(QueryPlanContext context)\r\n   at HotChocolate.Fusion.Planning.QueryPlanner.Plan(IOperation operation)\r\n   at HotChocolate.Fusion.Execution.Pipeline.OperationQueryPlanCompiler.OptimizeOperation(OperationOptimizerContext context)\r\n   at HotChocolate.Execution.Processing.OperationCompiler.CreateOperation(String operationId, OperationDefinitionNode operationDefinition, ObjectType operationType, DocumentNode document, ISchema schema)\r\n   at HotChocolate.Execution.Processing.OperationCompiler.Compile(String operationId, OperationDefinitionNode operationDefinition, ObjectType operationType, DocumentNode document, ISchema schema, IReadOnlyList`1 optimizers, Boolean enableNullBubbling)\r\n   at HotChocolate.Execution.Pipeline.OperationResolverMiddleware.CompileOperation(IRequestContext context, String operationId, OperationDefinitionNode operationDefinition, ObjectType operationType)\r\n   at HotChocolate.Execution.Pipeline.OperationResolverMiddleware.InvokeAsync(IRequestContext context)\r\n   at HotChocolate.Execution.Pipeline.OperationComplexityMiddleware.InvokeAsync(IRequestContext context)\r\n   at HotChocolate.Execution.Pipeline.OperationCacheMiddleware.InvokeAsync(IRequestContext context)\r\n   at HotChocolate.Execution.Pipeline.DocumentValidationMiddleware.InvokeAsync(IRequestContext context)\r\n   at HotChocolate.Execution.Pipeline.DocumentParserMiddleware.InvokeAsync(IRequestContext context)\r\n   at HotChocolate.Execution.Pipeline.DocumentCacheMiddleware.InvokeAsync(IRequestContext context)\r\n   at HotChocolate.Execution.Pipeline.TimeoutMiddleware.InvokeAsync(IRequestContext context)\r\n   at HotChocolate.Execution.Pipeline.ExceptionMiddleware.InvokeAsync(IRequestContext context)"
      }
    }
  ]
}

Additional Context?

No response

Version

13.7.0

interad-woergoetter avatar Nov 27 '23 12:11 interad-woergoetter

Any news regarding this @michaelstaib?

nhuethmayr avatar Dec 18 '23 11:12 nhuethmayr

We've run into the same issue and have opened a PR that should fix it: https://github.com/ChilliCream/graphql-platform/pull/8497 Feel free to take a look, feedback is welcome! Thanks!

dawust avatar Aug 06 '25 12:08 dawust

@dawust @michaelstaib @nloum

I'm having the same issue, and I'm currently on version 15.1.10.

Here's an example:


Subgraph A

schema {
  query: Query
}

type Query {
  item: ProductCatalogItem
}

type ProductCatalogItem {
  # IMPORTANT: interface return type is non-null and only exists here
  price: Price!
}

# Shared interface name across subgraphs
interface Price {
  currency: String
  value: Float
}

# Concrete types ONLY EXIST in this subgraph
type ProductCatalogItemFullPrice implements Price {
  currency: String
  value: Float
  extra: String
}

type ProductCatalogItemSalePrice implements Price {
  currency: String
  value: Float
  discountPercentage: Float
}
Subgraph B

schema {
  query: Query
}

type Query {
  product(id: ID!): Product
}

type Product {
  id: ID!
  variation: Variation
}

type Variation {
  # Same interface name is composed across subgraphs,
  # but no ProductCatalogItem* concrete types here
  price: Price
}

# Same interface name (composed), but different implementations here
interface Price {
  currency: String
  value: Float
}

type FullPrice implements Price {
  currency: String
  value: Float
  tags: [String!]!
}

type SalePrice implements Price {
  currency: String
  value: Float
  discountPercentage: Float
}

Both subgraphs define the same interface name Price. Only Subgraph A (listing) has the concrete types used by the client fragments: ProductCatalogItemFullPrice and ProductCatalogItemSalePrice. Subgraph B has other implementations (FullPrice/SalePrice) that are irrelevant to the query below.

An exception will be thrown if executing the query like this :

query Repro {
  item {
    price {
      __typename
      value
      currency
      ... on ProductCatalogItemFullPrice {
        extra
      }
      ... on ProductCatalogItemSalePrice {
        discountPercentage
      }
    }
  }
}

I believe that somewhere in the code we are getting all the types of that interface and then iterating over them not taking into consideration the current schema. If someone could take a look it would be amazing 😄. I'm could also help fix this issue but I need some guidance 😅 as this is kinda a black box for me. Thanks.

Coelho04 avatar Oct 04 '25 00:10 Coelho04

@Coelho04 I'm going to discuss with the team what the correct behavior should be here. The example you posted works in Fusion v2, but if we slightly modify the query it would break:

{
  item {
    price {
      __typename
      value
      currency
      # This type only exists on Subgraph B and there's no way to transition to it from Subgraph A
      ... on SalePrice {
        discountPercentage
      }
    }
  }
}

Which is understandable, as the planner has no way to resolve SalePrice.discountPercentage, as the type is exclusive to Subgraph B and there's no way to transition from Subgraph A to Subgraph B to resolve it.

I'm wondering whether the planner should just ignore the type refinement in this case as Subgraph A wouldn't be able to produce the concrete type exclusive to Subgraph B in the first place, so we don't even have to attempt to plan for it.

tobias-tengler avatar Oct 04 '25 11:10 tobias-tengler

I'm wondering whether the planner should just ignore the type refinement in this case as Subgraph A wouldn't be able to produce the concrete type exclusive to Subgraph B in the first place, so we don't even have to attempt to plan for it.

@tobias-tengler I believe that's the best approach, but I'm not the right person to say it.

Still, I was able to create a potential fix in version 15.1.10 by doing just that, and the example that I posted and yours work. Here's the code

    private bool CollectNestedSelections(
        QueryPlanContext context,
        Queue<BacklogItem> backlog,
        IOperation operation,
        ISelection parentSelection,
        SelectionPath? rootSelectionPath,
        List<ISelection> path,
        SelectionExecutionStep executionStep,
        bool preferBatching,
        Dictionary<ISelection, ISelection> parentSelectionLookup,
        HashSet<string> subgraphsInContext)
    {
        if (!preferBatching)
        {
            preferBatching = parentSelection.Type.IsListType();
        }

        var overallCouldPlanSelections = false;

        foreach (var possibleType in operation.GetPossibleTypes(parentSelection))
        {
            if (parentSelection.Type.IsInterfaceType() || parentSelection.Type.IsUnionType())
            {
                var declaringType = _config.GetType<ObjectTypeMetadata>(possibleType.Name);
                if (!declaringType.Fields.Any(f =>
                    !f.Name.Equals("__typename") && f.Bindings.ContainsSubgraph(executionStep.SubgraphName)))
                {
                    // The current graph can't resolve this type
                    continue;
                }
            }

            var couldPlanSelections = CollectNestedSelections(
                context,
                backlog,
                operation,
                parentSelection,
                rootSelectionPath,
                path,
                executionStep,
                possibleType,
                preferBatching,
                parentSelectionLookup,
                subgraphsInContext);

            if (couldPlanSelections)
            {
                overallCouldPlanSelections = true;
            }
        }

        return overallCouldPlanSelections;
    }

I excluded the __typename because it was giving me, for instance, both subgraphs; it's a 🔨, but I sincerely don't know a better way to do so.
I'm currently migrating from HC v13 to HC v15, and if it were possible to include something like this or create a new version 15.1.11, I would be immensely grateful, as it would unblock me.

I'm kinda of a noob in these things, but I can try to create a pull request.

Coelho04 avatar Oct 04 '25 23:10 Coelho04

@Coelho04 Yes, we can definitely include a fix for this problem in the next patch version! It would be awesome if you could raise a PR against main-version-15 with the tests and a fix :) I'm going to implement the equivalent for v16/main in the meantime. EDIT: Implemented in https://github.com/ChilliCream/graphql-platform/pull/8762

As for your proposed fix I believe this would be a more direct way to determine whether the type exists on the subgraph we're currently planning against:

if (_config.TryGetType<ObjectTypeMetadata>(possibleType.Name, out var typeMetadata)
    && !typeMetadata.Bindings.ContainsSubgraph(executionStep.SubgraphName))
{
    continue;
}

Also it would be good to have one more test where the only type refinements on the interface are types from Subgraph B, since then we would have no selections to forward to Subgraph A and we'd need to insert __typename to have a valid selection set. I'm talking about this scenario:

{
  # Subgraph A
  item {
    price {
      # This type only exists on Subgraph B
      ... on SalePrice {
        discountPercentage
      }
    }
  }
}

I would hope this would already work without additional changes, but it'd be better to have a test for it. You can create all those tests in src/HotChocolate/Fusion/test/Core.Tests/InterfaceTests.cs.

tobias-tengler avatar Oct 05 '25 09:10 tobias-tengler

The problem reported by @Coelho04 should be resolved with 15.1.11-p.7 🎉

tobias-tengler avatar Oct 06 '25 17:10 tobias-tengler