Skip to content

bug: Stream Link does not abort #5851

Closed

Description

@enricoros

Provide environment information

  System:
    OS: Windows 11 10.0.22631
    CPU: (32) x64 AMD Ryzen 9 7950X 16-Core Processor
    Memory: 46.84 GB / 63.65 GB
  Binaries:
    Node: 20.13.1 - C:\P\apps\nodejs\node.EXE
    Yarn: 1.22.19 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 10.5.2 - C:\P\apps\nodejs\npm.CMD
  Browsers:
    Edge: Chromium (126.0.2592.81)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    @trpc/client: next => 11.0.0-rc.436+fbb4a2fb4
    @trpc/server: next => 11.0.0-rc.436+fbb4a2fb4
    typescript: ^5.5.0 => 5.5.3

Describe the bug

The AbortController signal seems ignored by Stream Links with async generators.

We'd expect an interruption on the server side, and on the client side, but packets continue to be produced by the async generator, flow to the client, and the client keeps awaiting and receiving them.

I don't know what the correct behavior would be, but right now the signal seems to be completely ignored on both ends.

Link to reproduction

https://github.com/enricoros/trpc-repro-stream-unabort

To reproduce

In summary:

  1. The client creates a Stream Link, and queries with a {signal: ac.signal}, like this (minimal):
const trpc = createTRPCClient<AppRouter>({
  links: [unstable_httpBatchStreamLink({url: 'http://localhost:3000',})],
});

const ac = new AbortController();

const iterable = await trpc.examples.iterable.query(undefined, { signal: ac.signal });
  1. The server implements a procedure with an async generator, like this (minimal):
    iterable: publicProcedure.query(async function* () {
      for (let i = 0; i < 8; i++) {
        await new Promise((resolve) => setTimeout(resolve, 500));
        yield i;
      }
    }),
  1. We would expect both the server and the client to be aborted, but execution continues on both.
    This is the output:
    image

Additional information

No response

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR fixing this bug!

Activity

  1. KATT commented on Jul 2, 2024

    @KATT
    Member

    I think if you stop consuming the result and break in your for await it'll do what you expect

  2. enricoros commented on Jul 3, 2024

    @enricoros
    ContributorAuthor

    Tried this, and it stops the client, but the server keeps producing (yielding).

    For a client only solution I would not need the AbortController, but the assumption is that by passing the signal there will be some effect, but right now I don't see any effect on it.

    Pushed a branch variant-client-quit, with this commit, but the output shows that the server keeps producing as if abort was never called.

    image

  3. KATT commented on Jul 3, 2024

    @KATT
    Member

    Interesting. Feels like we should address this indeed.

    The code is a bit involved - this link handles streaming and batching requests so one abort shouldn't necessarily abort everything unless all requests are aborted.

    It'll likely take me some hours to debug this and think of a good solution, client side cancellation slipped my mind when doing the implementation.

    If you need this solved, consider adding a bounty.

  4. enricoros commented on Jul 3, 2024

    @enricoros
    ContributorAuthor

    Thanks, I understand it's not easy - this is very advanced. For my usage I don't need the batching part, I don't know if there could be a simplification where abort() terminated all the connections of the batch.

    The other issue is that after throwing on the server side, the connection seems to stay open (while it closes without throwing) -- maybe it's related to batching too.

    I've added a bounty using polar. I understand it's not much, but it's basically my GitHub income for the month (and beats the issues with no bounty! :).

  5. KATT commented on Jul 5, 2024

    @KATT
    Member

    The PR has been released as a tmp release, you can use it straight away using the @tmp-tag of tRPC

    Update your package.json to use the tmp version of tRPC:

    -    "@trpc/client": "^x.y.z",
    -    "@trpc/next": "^x.y.z",
    -    "@trpc/react-query": "^x.y.z",
    -    "@trpc/server": "^x.y.z",
    +    "@trpc/client": "tmp",
    +    "@trpc/next": "tmp",
    +    "@trpc/react-query": "tmp",
    +    "@trpc/server": "tmp",

    Then run npm install or similar. Let me now how it works. It's not a great hack.

  6. KATT commented on Jul 5, 2024

    @KATT
    Member

    Both

    1. returning in the for await , and
    2. using an abort signal

    should work, please try verifying both with a real usecase 🙏

  7. enricoros commented on Jul 5, 2024

    @enricoros
    ContributorAuthor

    Thanks! What a code change - Impressive. Testing in progress... ⌛

  8. KATT commented on Jul 5, 2024

    @KATT
    Member

    Thanks! What a code change - Impressive. Testing in progress... ⌛

    I hated how I did it so I ended up spending 2-3 hours refactoring after 😬

  9. enricoros commented on Jul 6, 2024

    @enricoros
    ContributorAuthor

    This is working incredibly well. I am VERY glad I am basing this AI stack on tRPC, as this is working wonders already.
    (update: updated pledge too - it's a lot of great work!)

    Evaluation below - in short, this is great and looks like magic to me - only 1 question below.

    • Abort on the Client-side (rRPC API call / for await ...):

      • This is unbelievable and looks like magic to me
      • Works by passing the signal to the tRPC Api call (code below)
      • Client side stops correctly and instantaneously at the for await ....
      • Socket closed
      • love this pattern (or catching at higher levels):
        const stream = await aixApi.lowlevel.chatGenerateContentStream.mutate({ ... }, { signal: abortSignal });
        try {
          for await (const update of stream) {
            // use the update object here...
          }
        } catch (error) {
          console.error('Client Catch', error);
        }
      • Note on the 'error' object contents: see 'misc note 1.'
    • Abort on the Server-side (tRPC procedure):

      • the client->server socket seems to close, exactly like fetch calls
      • there's no exception thrown or signal catchable on the server-side, but it's probably okay as execution seems to stall
      • Question: on the server-side, I do open a connection to OpenAI/Anthropic/etc., and could pass an abort signal to that upstream fetch, to terminate it alonside the tRPC procedure - is this possible?
        • I tested and the upstream request (from the procedure to OpenAI/etc) does not get aborted (so tokens are still generated), despite the procedure itself not continuing (it's stopped at the first yield, while the downstream socket to the frontend seems closed)
        • This is with nextjs in dev or prod (built) mode
    • Throwing from the server-side raises a TRPCClientError on the client side:

      {
        data: { code: "INTERNAL_SERVER_ERROR", httpStatus: 500, path: _the full name of the procedure,_ ... },
        message: _the message thrown on the server side_,
        name: "TRPCClientError",
        cause: undefined,
        ...
      }
      • throwing a TRPCError on the server side allows to also to change code/status (and cause) in addition to the message
      • the HTTP code stays the same (200) which is ok
      • Socket is closed (before this change the connection remained open - fixed!)

    Misc. notes:

      1. The exception raised on the client side seems to be a DOMException, with a 'cause.name' set to 'AbortError':
        image
      • The typical AbortError has error.name = 'AbortError', as per this MDN note
      • I would advise to set the name of the error thrown as 'AbortError', so that it's compatible with existing catching code
      1. Somehow with Chrome dev tools I cannot see the Preview/Response for the request once done - not a big deal

    Thanks again for this great work; would love to hear on the server-side question (are there events/signals to catch or pass on to the upstream OpenAI connection).

  10. KATT commented on Jul 6, 2024

    @KATT
    Member

    Question: on the server-side, I do open a connection to OpenAI/Anthropic/etc., and could pass an abort signal to that upstream fetch, to terminate it alonside the tRPC procedure - is this possible?

    If you pass the req from createContext down you should be able to do this:

    function myFn(opts: { ctx: Context }) {
      const ac = new AbortController();
      opts.ctx.req.once('aborted', () => {
        ac.abort();
      });
      const res = await fetch({
        // [...]
       signal: ac.signal
      })
      // [...]
    }

    We could potentially add a signal in opts.ctx.info.signal or something too, wdyt?

    Edit: did that in #5872 as it was just a few lines

  11. enricoros commented on Jul 6, 2024

    @enricoros
    ContributorAuthor

    I'm watching the branch and the commits pouring in, while at the same time I tried to debug it myself (got stuck inside some 'undici' - this is way too unknown for me). I am eager to try this out - looks amazing.

  12. enricoros commented on Jul 6, 2024

    @enricoros
    ContributorAuthor

    Update: Testing ⌛complete.

    Works perfectly. I confirm that the signal passed from the context request.signal works really well.
    image

    As an example, I started 4 OpenAI Generations and interrupted them right at the beginning, and the servers show the following stats:
    image

    This shows that the signal is really used from the request, passed to the fetch which terminates the upstream connection, and the user saves tokens - input (context) tokens >> output (generated) tokens.

    As of now, the client and server work great. I don't see any other improvement (I didn't check if error.name = 'AbortError', but it can be worked around too).

    Thanks, and glad to honor the pledge.

  13. KATT commented on Jul 10, 2024

    @KATT
    Member

    Merged this now and we appreciate the pledge - if you want to do a real dent in longevity of tRPC, please consider to sponsor [or get your employer to sponsor] on a monthly basis 🙏

  14. enricoros commented on Jul 11, 2024

    @enricoros
    ContributorAuthor

    @KATT thanks, this is huge news! When my startup gets funding I'll pay it forward and sponsor the project.

    So far, I'm incredibly happy with Streaming via tRPC, especially because it induces correctness upstream via generators/async generators. The new API is so clean, and have infinite room for scalability, which I'm still early in exploring. Cannot wait to remove all my old stream transformation code and manual endpoints. Streaming is such a great tRPC use case because of the flexibility of return types; it's not one .output(), but many object types generated on the fly with no cost.

    I wish I had the time to make my tRPC AI library a bit more independent from the rest of the App, because it's a more flexible alternative to the Vercel AI sdk (multi-modal, multi-part, dynamic upstream streaming, 14 vendors, etc.)

  15. KATT commented on Jul 11, 2024

    @KATT
    Member

    Thank you @enricoros, this whole interaction with you has been 10/10

  16. github-actions commented on Jul 13, 2024

    @github-actions
    Contributor

    This issue has been locked because we are very unlikely to see comments on closed issues. If you are running into a similar issue, please create a new issue. Thank you.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions