Skip to content

Inline fragments don't work on fields declared with interface types (v16.2) #2336

Closed

Description

@aleksandarsusnjar

Description
Specifying an inline fragment for a concrete (sub)type of a field declared with that same type seems to work. However, field fetchers aren't even called when the same is done for a field declared using an interface type, whether that declared interface type, concrete object type or any other type in between is used.

For more details see:
#2331

To Reproduce
Create a schema as follows:

interface Base {
    id: ID
}

type Concrete implements Base {
    id: ID
    name: String
}

type Test {
    base: Base
    concrete: Concrete
}

type Query {
    test: Test
}   

Set it up so that you can return/fetch some data. Perhaps return the exact same object/instance for both base and concrete fields of Test to make it more interesting (both need to be of type Concrete anyway). Issue the following query:

query {
    test {
        base {
            __typename
            ... on Base {
                id
            }
            ... on Concrete {
                name
            }
        }
        concrete {
            __typename
            ... on Concrete {
                id
                name
            }
        }
    }
}

Fields base and concrete should include exactly the same sub-fields: __typename, id and name. They do not.

Activity

  1. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    I've been tracing this... in ExecutionStrategy, method:

    protected CompletableFuture<ExecutionResult> completeValueForObject(ExecutionContext executionContext, ExecutionStrategyParameters parameters, GraphQLObjectType resolvedObjectType, Object result) {

    ... line:

    MergedSelectionSet subFields = fieldCollector.collectFields(collectorParameters, parameters.getField());

    yields subFields without field from inline fragments. collectorParameters has:

    1. graphQLSchema: non-null
    2. fragmentsByName: empty, size = 0
    3. variables: empty, size = 0
    4. objectType: correct object type and its fieldDefinitionsByName includes all the fields.

    I can see that fieldCollector has a non-null conditionalNodes reference which has a non-null valuesResolver reference.

  2. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    SelectionSet for the field in question (for which subFields are being determined) prints as:

    SelectionSet{selections=[InlineFragment{typeCondition='TypeName{name='Concrete'}', directives=[], selectionSet=SelectionSet{selections=[Field{name='id', alias='null', arguments=[], directives=[], selectionSet=null}]}}]}
    

    This causes execution to go to:

    private void collectFields(FieldCollectorParameters parameters, SelectionSet selectionSet, Set<String> visitedFragments, Map<String, MergedField> fields)

    ... specifically its case:

                } else if (selection instanceof InlineFragment) {
                    collectInlineFragment(parameters, visitedFragments, fields, (InlineFragment) selection);
                } else
    

    ... that goes into:

        private void collectInlineFragment(FieldCollectorParameters parameters, Set<String> visitedFragments, Map<String, MergedField> fields, InlineFragment inlineFragment) {
            if (!conditionalNodes.shouldInclude(parameters.getVariables(), inlineFragment.getDirectives()) ||
                    !doesFragmentConditionMatch(parameters, inlineFragment)) {
                return;
            }
            collectFields(parameters, inlineFragment.getSelectionSet(), visitedFragments, fields);
        }

    Now, the first part of that condition, specifically:

    conditionalNodes.shouldInclude(parameters.getVariables(), inlineFragment.getDirectives())

    ... evaluates to true as I would have expected (inside skip is false and include is true so !skip && include is true). It is negated so that seems fine. The second condition:

    !doesFragmentConditionMatch(parameters, inlineFragment)

    Seems to figure out the correct conditionType (Concrete) and goes into:

    return checkTypeCondition(parameters, conditionType);

    This is where it gets interesting... I think. After the first line:

    GraphQLObjectType type = parameters.getObjectType();

    ... the type variable and the conditionType parameter are both GraphQLObjectTypes, both for Concrete but are different/separate instances. Not sure why this isn't normalized internally. Their toString() outputs are different. Equality check at the top of the method evaluates to false (not equal). It appears that equals method is not implemented on GraphQLObjectType so this falls back on the default implementation from Object that uses ==.

    These are different internally. conditionType has replacedInterfaces non-null and type has it null.

    In then comes to this code:

            if (conditionType instanceof GraphQLInterfaceType) {
                List<GraphQLObjectType> implementations = parameters.getGraphQLSchema().getImplementations((GraphQLInterfaceType) conditionType);
                return implementations.contains(type);
            } else if (conditionType instanceof GraphQLUnionType) {
                return ((GraphQLUnionType) conditionType).getTypes().contains(type);
            }
            return false;

    Since conditionType isn't an interface or a union type in this case (but Concrete object type), this will fall through to that final return false;.

    It appears that equals(Object that) method needs to be implemented on all types - object types to cover this case and interface types to cover exact matches too, which also fail. I am wondering if it can't be simply implemented to say that they are equal if they match the following conditions:

    1. Are of the same Java class (this.class == that.class)
    2. Belong to the same schema (although I don't see a readily available reference to it)
    3. If wrapped, compare unwrapped (recursively), otherwise compare names.

    I am willing to contribute this change if reasoning seems correct. Please respond.

  3. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    This isn't going to be so easy. I cloned the repo and implemented the unit tests (commit 1) and then equals(Object) and hashCode() method (commit 2). The new unit tests are passing but 526 other fail with many occurrences of:

    Internal error: should never happen: This schema is not forming an Directed Acyclic Graph : GraphQLObjectType{name='__Type', description='null', fieldDefinitionsByName=[kind, name, description, fields, interfaces, possibleTypes, enumValues, inputFields, ofType, specifiedByUrl], interfaces=[]} has already has a temporary mark
    

    See: https://github.com/aleksandarsusnjar/graphql-java/pull/new/issue-2336-inline-fragments

  4. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    Alternative is to make doesFragmentConditionMatch() not use equals() (only).

  5. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    @andimarek:

    What should be done here:

    1. type and conditionType should really be == if they are for the same actual type - that should be fixed.
    2. Not [1] but type.equals(another) must return true if the actual types are the same even when !=. This is my change. 526 unit test failures indicate incompatible expectations that would need to be fixed.
    3. Neither [1] or [2]. FieldCollector.checkTypeCondition(FieldCollectorParameters, GraphQLType) must not rely (only) on equals(Object) but also account for this. My change could be modified to implement an alternate method instead of modifying equals(Object), then use that method instead.
  6. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    I have two sets of changes.

    [2] https://github.com/aleksandarsusnjar/graphql-java/pull/new/issue-2336-inline-fragments

    • (Re)implements equals(Object) and hashCode()
    • Fails 526 old unit tests.

    [3] https://github.com/aleksandarsusnjar/graphql-java/pull/new/issue-2336-alt-equality

    • Adds new isEquivalentTo(GraphQLType) to GraphQLType
    • Adds default implementation of isEquivalentTo(GraphQLType) for GraphQLNamedType
    • Adds default implementation of isEquivalentTo(GraphQLType) for GraphQLModifiedType
    • Adds the same for a nested class MyGraphQLObjectType inside SchemaPrinterTest
    • Modifies FieldCollector.checkTypeCondition(FieldCollectorParameters, GraphQLType) to use isEquivalentTo(GraphQLType) instead of equals(Object).
    • Wanted to test but didn't ... I need Long scalars and I made the changes to the newest code, not 16.2. They will be commonly needed in Java world. Note: GraphQL clients are neither solely JavaScript nor is JavaScript disadvantaged in this case any more - see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt ... and custom scalars are supported.
  7. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    I have tested a 16.2 variant of [3] inside what I am working on (see #2331) and can confirm that it works:

    https://github.com/aleksandarsusnjar/graphql-java/pull/new/v16.2-issue-2336

    I feel that [1] should be the right approach but I don't want to mess with that myself. @andimarek ?

  8. andimarek commented on May 14, 2021

    @andimarek
    Member

    GraphQLObjectTypes, both for Concrete but are different/separate instances

    This sounds wrong: we are making sure that every Type is unique inside a Schema: you will never have two different types with the same name. Can you elaborate on that? Does that mean you have two GraphQLObjectType instances with the same name?
    If so: how do you create you schema?

  9. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    Yes, exactly that:

    Does that mean you have two GraphQLObjectType instances with the same name?

    Re:

    If so: how do you create you schema?

    Programmatically .... using the schema builder. It is not reporting duplicate or redefined types.

  10. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    @andimarek: I cannot share that code but we can have a Zoom session if you're up to it... Would need to send you the details privately.

  11. andimarek commented on May 14, 2021

    @andimarek
    Member

    Programmatically .... using the schema builder. It is not reporting duplicate or redefined types.

    I would recommend that you try to dig deeper into that: Have a look at GraphQLTypeCollectingVisitor.assertTypeUniqueness: this should normally throw an exception at schema build time if you have multiple types with the same name.

  12. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    OK ... will do now.
    Breakpoint there.... restarting to regenerate schema.

  13. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    Put a breakpoint on the throw new ... (as shown below) ... and did NOT land on it.

        private void assertTypeUniqueness(GraphQLNamedType type, Map<String, GraphQLNamedType> result) {
            GraphQLType existingType = result.get(type.getName());
            // do we have an existing definition
            if (existingType != null) {
                // type references are ok
                if (!(existingType instanceof GraphQLTypeReference || type instanceof GraphQLTypeReference))
                    // object comparison here is deliberate
                    if (existingType != type) {
                        throw new AssertException(format("All types within a GraphQL schema must have unique names. No two provided types may have the same name.\n" +
                                        "No provided type may have a name which conflicts with any built in types (including Scalar and Introspection types).\n" +
                                        "You have redefined the type '%s' from being a '%s' to a '%s'",
                                type.getName(), existingType.getClass().getSimpleName(), type.getClass().getSimpleName()));
                    }
            }
        }
  14. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    Not landing on:

    if (!(existingType instanceof GraphQLTypeReference || type instanceof GraphQLTypeReference))

    either...

  15. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    Method is getting called. It is landing on that first if.

  16. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    I put a conditional breakpoint on it to trigger only when my type "in question" is being checked. Breakpoint is not triggered at all - like the method isn't called for it. I can see it being called for scalars (built-in and my custom ones) and enums (again, built-in and custom ones) but not once for either an object or interface type (didn't check others).

  17. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    Notice this:

        @Override
        public TraversalControl visitGraphQLObjectType(GraphQLObjectType node, TraverserContext<GraphQLSchemaElement> context) {
            if (isTypeReference(node.getName())) {
                assertTypeUniqueness(node, result);
            } else {
                save(node.getName(), node);
            }
            return super.visitGraphQLObjectType(node, context);
        }

    That will only call the assertion method for type references, which are ignored by the assertion. Is it meant to negate that condition:

            if (!isTypeReference(node.getName())) { // <--- NEGATED condition
  18. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    Same thing applies to visiting input and interface types. Union types are asserted always. You already have an extra comment there for that isTypeReference method:

        // TODO: eh? Isn't it similar to assertTypeUniqueness?
        private boolean isTypeReference(String name) {
            return result.containsKey(name) && !(result.get(name) instanceof GraphQLTypeReference);
        }
  19. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    However, this alone does not answer the main challenge. All calls to schemaBuilder.additionalType(type) in my code go through a single method of mine and I added double checking that names are distinct for all named output types. They are all distinct.

  20. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    However, that visitGraphQLObjectType() method IS called TWICE for my object type in question.

    The first time it is my code building it. Relevant part of the stack trace is:

    visitGraphQLObjectType:40, GraphQLTypeCollectingVisitor (graphql.schema)
    accept:207, GraphQLObjectType (graphql.schema)
    enter:72, SchemaTraverser$TraverserDelegateVisitor (graphql.schema)
    traverse:144, Traverser (graphql.util)
    doTraverse:59, SchemaTraverser (graphql.schema)
    depthFirst:51, SchemaTraverser (graphql.schema)
    depthFirst:38, SchemaTraverser (graphql.schema)
    allTypes:50, SchemaUtil (graphql.schema)
    <init>:124, GraphQLSchema (graphql.schema)
    <init>:47, GraphQLSchema (graphql.schema)
    buildImpl:640, GraphQLSchema$Builder (graphql.schema)
    build:622, GraphQLSchema$Builder (graphql.schema)
    

    The second time it seems to be building another copy of it, as triggered by me setting up the GraphQL (kickstart servlet) configuration, from that line .with(getSchema()) in the code below:

        private synchronized GraphQLSchema getSchema() {
            return schema;
        }
    
        private synchronized void setSchema(final GraphQLSchema schema) {
            this.schema = schema;
    
            configuration.set(GraphQLConfiguration
                .with(getSchema())
                .with(ContextSetting.PER_REQUEST_WITHOUT_INSTRUMENTATION)
                .with(GraphQLQueryInvoker.newBuilder()
                    .with(Collections.singletonList(ExecutionInstrumentation.singleton()))
                    .build()
                )
                .build()
            );

    Relevant part of the stack trace is:

    visitGraphQLObjectType:40, GraphQLTypeCollectingVisitor (graphql.schema)
    accept:207, GraphQLObjectType (graphql.schema)
    enter:72, SchemaTraverser$TraverserDelegateVisitor (graphql.schema)
    traverse:144, Traverser (graphql.util)
    doTraverse:59, SchemaTraverser (graphql.schema)
    depthFirst:51, SchemaTraverser (graphql.schema)
    depthFirst:38, SchemaTraverser (graphql.schema)
    allTypes:50, SchemaUtil (graphql.schema)
    <init>:124, GraphQLSchema (graphql.schema)
    <init>:47, GraphQLSchema (graphql.schema)
    buildImpl:640, GraphQLSchema$Builder (graphql.schema)
    build:622, GraphQLSchema$Builder (graphql.schema)
    copyReadOnly:11, GraphQLSchemaProvider (graphql.kickstart.execution.config)
    <init>:14, DefaultGraphQLSchemaProvider (graphql.kickstart.execution.config)
    <init>:15, DefaultGraphQLSchemaServletProvider (graphql.kickstart.servlet.config)
    with:57, GraphQLConfiguration (graphql.kickstart.servlet)
    
  21. andimarek commented on May 14, 2021

    @andimarek
    Member

    I am strongly suspecting that something is messing with your Schema. Please remember that GraphQL Java is just the engine and we can't comment on libraries build on top of it (like the Kickstarter ones).

    If this is really a GraphQL Java issue we need a standalone example in pure GraphQL Java code. Thanks

  22. aleksandarsusnjar commented on May 14, 2021

    @aleksandarsusnjar
    Author

    I get it. I am now puzzled as to why does kickstart configuration make a copy of the schema and also why would that be a problem either.

  23. aleksandarsusnjar commented on May 15, 2021

    @aleksandarsusnjar
    Author

    OK ... I found the issue... however, you should look at the calls to that assertion.

    What was the issue? It was in my code and undetected by graphql-java. I invoked the build() method of the same GraphQLObjectType.Builder twice accidentally. Only the result of the second one was passed on to the schema builder additionalType(). The result of the first invocation, however, may have found its way of being used directly / instead of a type reference from something else, such as the field type or as some kind of relation of another type. Schema (builder) accepted this just fine but got confused by it later...

    After making sure that I build and reuse a single instance only things started working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions