Skip to content

Concurrency issue: GraphQL query randomly returns wrong result #5108

Closed

Description

@ikenox

Link to reproduction

https://github.com/ikenox/payload/tree/wrong-graphql-query-result

Describe the Bug

Payload server randomly returns wrong result for specific GraphQL query

Example

Collections: https://github.com/ikenox/payload/blob/wrong-graphql-query-result/test/wrong-graphql-query-result/collections.ts
Initial data: https://github.com/ikenox/payload/blob/wrong-graphql-query-result/test/wrong-graphql-query-result/config.ts#L12-L23

Query:

query {
  Shops {
    docs {
      name
      items {
        name
      }
    }
  }
  Items {
    docs {
      name
      itemTags {
        name
      }
    }
  }
}

Expected response is below:

{
  "data": {
    "Shops": {
      "docs": [
        {
          "name": "shop1",
          "items": [
            {
              "name": "item1"
            }
          ]
        }
      ]
    },
    "Items": {
      "docs": [
        {
          "name": "item1",
          "itemTags": [
            {
              "name": "tag1"
            }
          ]
        }
      ]
    }
  }
}

But randomly, about one out of every two times, wrong result are returned that has no items on Shops.docs.items field.

{
  "data": {
    "Shops": {
      "docs": [
        {
          "name": "shop1",
          "items": []
        }
      ]
    },
    "Items": {
      "docs": [
        {
          "name": "item1",
          "itemTags": [
            {
              "name": "tag1"
            }
          ]
        }
      ]
    }
  }
}

To Reproduce

I created a failing test.
Please execute pnpm test:int:postgres wrong-graphql-query-result on my reproducible example code https://github.com/ikenox/payload/tree/wrong-graphql-query-result .

Or you can test the query manually.

pnpm dev:postgres wrong-graphql-query-result
open http://localhost:3000/api/graphql-playground

Payload Version

2.11.1

Adapters and Plugins

db-postgres

Activity

  1. added
    status: needs-triage
    on Feb 18, 2024
  2. changed the title [-]GraphQL query returns wrong result[/-] [+]GraphQL query randomly returns wrong result[/+] on Feb 18, 2024
  3. ikenox commented on Feb 18, 2024

    @ikenox
    Author

    I've investigated the detailed behaviour.

    1. To obtain hasMany relationship data, dataloader is called with current req.transactionID (usually the value is null)

      const result = await context.req.payloadDataLoader.load(
      JSON.stringify([
      context.req.transactionID,
      collectionSlug,
      id,
      0,
      0,
      locale,
      fallbackLocale,
      false,
      false,
      ]),
      )

    2. payload.find is called in dataloader

      const result = await payload.find({

    3. initTransaction is called in find operation function.

      const shouldCommit = await initTransaction(args.req)

    4. If any other concurrent task in the same request is trying to issue transaction, just wait it and return false.

      if (transactionIDPromise) {
      // wait for whoever else is already creating the transaction
      await transactionIDPromise
      return false
      }

      • Important: I could see the req.transactionID is changed before and after this line, perhaps by other concurrent dataloader task. At this point, the req.transactionID is no longer null.
    5. The returned false is assigned to shouldCommit, so req.transactionID is not deleted at the end of find operation.

      if (shouldCommit) await commitTransaction(req)

    6. As a result, transactionID of docKey is not null while that of keys is null. It causes docIndex=-1

      const docKey = JSON.stringify([
      req.transactionID,
      collection,
      doc.id,
      depth,
      currentDepth,
      locale,
      fallbackLocale,
      overrideAccess,
      showHiddenFields,
      ])
      const docsIndex = keys.findIndex((key) => key === docKey)

  4. changed the title [-]GraphQL query randomly returns wrong result[/-] [+]Concurrency issue: GraphQL query randomly returns wrong result[/+] on Feb 18, 2024
  5. ikenox commented on Feb 18, 2024

    @ikenox
    Author

    Moving req.transactionID = transactionID after payload.find(...) statement superficially resolves the problem, but I'm not confident that it is the right solution.

    req.transactionID = transactionID
    const result = await payload.find({
    collection,
    currentDepth,
    depth,
    disableErrors: true,
    fallbackLocale,
    locale,
    overrideAccess: Boolean(overrideAccess),
    pagination: false,
    req,
    showHiddenFields: Boolean(showHiddenFields),
    where: {
    id: {
    in: ids,
    },
    },
    })

  6. SimYunSup commented on May 31, 2024

    @SimYunSup
    Contributor

    Bump because latest payload has same problem.

    • payload: 2.18.3
      • @payloadcms/db-postgres: 0.8.4
    • payload: beta (in my computer)

    I think that first payload.find must have req.transactionID to equalize transactionID(This is my guess, so I could be wrong).

    So How about change first value in docKeys to transactionID?

    Expected:

     const docKey = JSON.stringify([ 
       transactionID, 
       collection, 
       doc.id, 
       depth, 
       currentDepth, 
       locale, 
       fallbackLocale, 
       overrideAccess, 
       showHiddenFields, 
     ]) 
     const docsIndex = keys.findIndex((key) => key === docKey) 
  7. SimYunSup commented on Jun 8, 2024

    @SimYunSup
    Contributor

    Addtional:

    Moving req.transactionID = transactionID after payload.find(...) cause randomly nested null return 😢 .

  8. self-assigned this
    on Jun 9, 2024
  9. removed
    status: needs-triage
    on Jun 9, 2024
  10. added
    status: needs-triage
    and removed
    status: needs-triage
    on Jun 9, 2024
  11. ikenox commented on Jun 18, 2024

    @ikenox
    Author

    Maybe #6821 fixes this issue.

  12. SimYunSup commented on Jun 18, 2024

    @SimYunSup
    Contributor

    Unfortunately, I think this patch is a workaround.

    It's possible to fix the above issue by NOT using req.transactionID in the computed batch key, but presumably the intention here was to re-use open transactions. The behavior we're seeing here is that sometimes our relationship batch fetch will happen in its own transaction and sometimes it won't if we don't reuse the transaction id from the batch key.

    As written above, as @tychedelia said in #6800, this patch appears to solve the problem by accepting the req.transactionID cleared by payload.find, but it's not the way the payloadCMS team intended to handle GraphQL's loader in a single transaction. I don't know how @DanRibbens solves this, but I think there needs to be logic to not commit in payload.find when given a parent transactionId.

    In addition to, it doesn't find the key in the doc (and I don't know where it would show up as a bug).

    const docsIndex = keys.findIndex((key) => key === docKey)
    if (docsIndex > -1) {
    docs[docsIndex] = doc
    }
    })

  13. tychedelia commented on Jun 18, 2024

    @tychedelia

    It's possible that the transaction id simply needs to be removed from the cache key. However, as it stands, the existing logic contains a race condition that triggers the bug described in #6800.

  14. SimYunSup commented on Jun 19, 2024

    @SimYunSup
    Contributor

    Sorry, I misunderstood your code. I didn't see that if the req passed to find has a transactionId, it doesn't commitTransaction.

    @tychedelia I think the error is due to the req.transactionId being tainted and not finding the key in the above part of the code, but it looks like #6821 doesn't really decontaminate the req.transactionID, and it seems necessary to pass the transactionId so that it can be rolled back or killed if given.

    However, when I pass the req to isolateObjectProperty, the transactionId is not passed, so it is not easy to rollback or kill. So instead of using isolateObjectProperty, I think it is correct to use transactionID instead of req.transactionID when creating a docKey like the code in this comment.

    I'm still not fixing the bug in #6821 where the relationship filter in the where clause doesn't include the results because of a different transactionId than the docKey I created above due to a tainted req.transactionId. I won't create a reproduction right now, but I'll try to do so as soon as I can.

  15. added a commit that references this issue on Jun 19, 2024
  16. added a commit that references this issue on Jun 25, 2024
  17. jmikrut commented on Jun 25, 2024

    @jmikrut
    Member

    Closed by #6857

    THANK YOU EVERYONE for the reconnaissance, the reproductions, and the thinking!

  18. github-actions commented on Sep 7, 2024

    @github-actions
    Contributor

    This issue has been automatically locked.
    Please open a new issue if this issue persists with any additional detail.

  19. locked as resolved and limited conversation to collaborators on Sep 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

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