Skip to content

Introduce fast path for buffered ReadableStream - #13704

Merged
Jarred-Sumner merged 25 commits into
mainfrom
jarred/fast-path
Sep 4, 2024
Merged

Jarred-Sumner merged 25 commits into
mainfrom
jarred/fast-path

Conversation

@Jarred-Sumner

@Jarred-Sumner Jarred-Sumner commented Sep 3, 2024 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes #13678

This introduces a fast path for consuming streaming request bodies where previously the developer accessed the ReadableStream. This also fixes a memory leak when doing that.

Previously, the following code would be unnecessarily slow:

Bun.serve({
  async fetch(req) {
    if (req.body) { 
       await req.json();
    }

    // previously, the fast path only worked if you didn't access req.body.
  }
});

This would cause us to:

  1. Buffer the contents of the stream in JavaScript (slow)
  2. High water mark of around 16 KB because we didn't implement the drain function for it.

TODO:

  • Fix FormData issue
  • Fix other test failures
  • benchmark once CI finishes

How did you verify your code works?

There are some new tests, and also I modified some existing tests to also cover this case.

There's a lot of room for mistakes here. So let's be very confident this works properly when we merge it.

Bun.gc(true);

const rss = (process.memoryUsage.rss() / 1024 / 1024) | 0;
expect(rss).toBeLessThan(baseline * 4);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test was not failing when it should've been failing. The test itself shouldn't use a ton of memory so I think a hardcoded value is fine here.

@@ -0,0 +1,16 @@
const buildTypeFlag = process.argv.find(argv => {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't mean to commit this

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can this be removed so do not cause confusion in the future?

};
readable.ptr.Bytes.onData(
.{
.temporary_and_done = bun.ByteList.initConst(chunk),

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

subtle change

Comment thread src/bun.js/bindings/Uint8Array.cpp Resolved

@cirospaciari cirospaciari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM just the uneeded file that I think we should remove so we not associate with this PR in the future

@cirospaciari
cirospaciari self-requested a review September 4, 2024 00:48

@cirospaciari cirospaciari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Failing leak memory test.

@Jarred-Sumner
Jarred-Sumner merged commit a9cf463 into main Sep 4, 2024
@Jarred-Sumner
Jarred-Sumner deleted the jarred/fast-path branch September 4, 2024 11:16
@mshameti

mshameti commented Sep 4, 2024

Copy link
Copy Markdown

thank you for your hard work on this @Jarred-Sumner! the incredibly low turnaround time of issue to fix and enhancement is understated

dylan-conway pushed a commit that referenced this pull request Jul 13, 2026
…iles (#34081)

## Failure

`test/js/bun/http/bun-serve-static.test.ts` timed out at the 180s file
wall on `:ubuntu: 25.04 x64` in [build
#72253](https://buildkite.com/bun/bun/builds/72253#019f56c3-b041-43b4-85b8-4db05b51eb3d),
four retries in a row. No individual test failed; the process was killed
seven `/big` stress tests into eight:

```
Start RSS 422
RSS Growth 87
Final RSS 458
Delta RSS 36
.main process killed by undefined but no core file found
```

Per-test timestamps from that job put each `/big` stress test at 17-30s
(≈195s for all eight), against ~6s locally. The runner was a noisy AWS
box; the rest of its shard ran at normal speed.

## Why not shrink `/big`

#34047 dropped the body to 512KB. That is not equivalent:
`StaticRoute::do_render_blob` only enters the `to_async` + `on_writable`
backpressure loop when the first `send()` short-writes, which is driven
by the kernel send buffer. On loopback 512KB can drain in one write; 4MB
reliably cannot. So the 4MB body is part of the test surface and stays.

## Change

Move the stress loop into two new files (one per `res.body`-access
variant) that share the route table and loop body via
`bun-serve-static-helpers.ts`. Each file gets its own per-file wall
clock while running the exact same work: 4MB body, 64 concurrent × 24
iterations, all four body readers, `toStrictEqual` on every response,
the RSS ceiling check. 110,616 `expect()` calls across the two stress
files matches the original count.

Two latent bugs in the moved code are fixed in the helper:

- `byteSize` was `static_responses[path][method]?.size`, which is always
`undefined` (the value is a Blob method, not a Blob), so the `48/10`
branch never executed. The loop has always been 64×12; the dead
conditional is removed.
- `buf[i] = randomAnyCaseLetter()` assigned a one-char string, which
coerces to `NaN` → `0`, so `/big` has been 4MB of NUL bytes since
#13704. Now `charCodeAt()`, so the body is printable ASCII as intended
(no timing impact).

`expected-durations.json` is seeded for the new files so the LPT shard
packer places them sensibly instead of at the 58ms median.

## Verification

| file | release | debug+asan |
|---|---|---|
| `bun-serve-static.test.ts` | 0.19s, 17/17 | 2.47s, 17/17 |
| `bun-serve-static-stress-access-body.test.ts` | 24.0s, 12/12 | 93.6s,
12/12 |
| `bun-serve-static-stress-no-body.test.ts` | 25.0s, 12/12 | 88.4s,
12/12 |

At the ≈4× slowdown observed in build 72253 each stress file would
finish in ~100s (release, 180s budget) or ~250s (asan, 360s budget).

Supersedes #34047.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 1 · Platform-specific test-only change;
deferring to CI.

<!-- robobun:evidence:end -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Memory leak if accessing body of fetch() response before consuming the stream

4 participants