Skip to content

fix(demo): read fragmented HTTP responses until EOF - #1340

Merged
Lorenzobattistela merged 3 commits into
bendlang:mainfrom
oxura:fix/http-fetch-eof
Oct 5, 2026
Merged

Lorenzobattistela merged 3 commits into
bendlang:mainfrom
oxura:fix/http-fetch-eof

Conversation

@oxura

@oxura oxura commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1309.

The HTTP fetch demo called TCP.recv twice and closed, so a Connection: close response that arrived in three or more pieces was cut short. It now reads until EOF (an empty receive), then closes and prints the body.

  • Reads bytes, bounded in bytes. The reader uses TCP.recv_bytes and caps the response at 65536 bytes, headers included. Each receive asks for at most what is left of the budget (8192 at most). At exactly the limit, a one-byte receive must return EOF, otherwise the fetch fails with HTTP response exceeds 65536 bytes. A Nat fuel of 65536 keeps the loop structurally recursive.
  • Decodes UTF-8 once, at the end. Decoding each receive separately split multibyte characters at chunk boundaries (café came out as caf��). Base has no bytes-to-text conversion, so the demo carries a small decoder (utf8) that follows the same replacement policy as the TCP text codec, including an incomplete final character.
  • Closes on every path. EOF, the limit, and send/receive failures all close the socket once. Failures keep their original code and message.
  • Joins chunks without deep recursion. Chunks are kept newest-first and folded once with List.foldl.

Tests (tests/io/):

  • http_fetch_eof.bend: a real loopback listener sends the header separator, the body and a two-byte é across separate writes; also a response of exactly 65536 bytes whose last character's bytes arrive separately, an empty response, and one with no header separator. The test carries its own copy of the demo's reader, since tests import only from tests/.
  • http_fetch_limit.bend: one byte over the limit fails with exit 1.

Verified locally:

  • Both tests print their #| lines on the interpreted, JS and C lanes, each in about 1 s.
  • Against a local TCP server on Bun JS and native C: fragmented headers and body print ABC (main prints an empty body), and split café and x€😀ñy sent one byte per write decode correctly.
  • The utf8 decoder matches TextDecoder on 433 byte strings (overlong, surrogate, above U+10FFFF, truncated, stray continuation, plus random), on C, JS and the interpreter.
  • Repo gate: PASS 50 / 50. No changes to gates/, Base or the compiler.
  • Cluster gates not run.

🤖 Generated with Claude Code

@oxura

oxura commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Joint local verification of #1337–#1341 against main 565d7fd, including the constructor-model correction in #1338:

  • Combined repository gate: PASS 50 / 50; original caps/core-language/gates unchanged.
  • Actual Lean 4.34.0 BendTT kernel accepts all six positive new proof fixtures, existing vec_safe_lookup, Base's Type-model control and compact 9000 Nat control. The 4097 regression uses an independent 2^12+1 structural value oracle.
  • User-defined parameterized/def Unit remains explicitly out of elaboration scope (no model for idt~A), not a claimed kernel success.
  • Versioned kernel cache works with no Lean on PATH. The earlier incompatible 4.32/source-only-cache and explicit BENDTT controls were also exercised.
  • Combined emitted HTTP JS retains ABC across fragmented headers and six receives. Individual HTTP smoke additionally used actual TCP under Bun/native C and an exact 65536-character response split into 65536 one-character receives.
  • Combined generated CUDA C reports cuInit(0) failed: CUDA_ERROR_UNKNOWN when forced under fault injection; automatic CPU fallback prints 2147450880 without diagnostics.
  • Code changes merge automatically. Only additive Unreleased CHANGELOG entries needed combining in the local integration checkout.

No physical GPU, macOS/Metal runtime, or mini-cluster gate was exercised. Separate PR source branches remain independent; the integration branch is local verification only.

@Lorenzobattistela Lorenzobattistela self-assigned this Oct 5, 2026

@Lorenzobattistela Lorenzobattistela left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this. The loop does fix #1309: over a real loopback socket, with the header separator and the body split across six writes, main prints an empty body and this branch prints ABC, on both the Bun JS and native C backends. Four things need fixing before merge, though.

1. A response that fits the limit is rejected.
The limit counts decoded characters, but each read is sized in bytes, and TCP.recv decodes every read on its own. Near the end of the budget, U32.max(U32.min(left, 8192), 1) asks for reads of 1 to 3 bytes, and those can cut a multibyte character in half.

To reproduce, run a local server that sends a 65536-character response: the headers plus ASCII up to 65535 characters, a short pause, then é (2 bytes), then close. Point the demo at it. With left == 1, recv(1) returns the first byte of é, which decodes to U+FFFD, so left drops to 0. The final 1-byte read then returns the second byte, which is also U+FFFD and not empty. Both backends exit 1 with HTTP response exceeds 65536 characters. If the last character is ASCII e instead, the same response is accepted and all 65498 body characters print.

The same per-read decoding also corrupts text away from the limit. If the server writes caf\xC3 and then \xA9, the demo prints caf��. This happens on main too, but reading until EOF means more reads and therefore more places to split. The fix is to bound the response in bytes and decode it once: read with TCP.recv_bytes, cap the total byte count, and decode UTF-8 at the end. That fixes both problems, and the "decoded characters, not wire bytes" caveat goes away. If you'd rather keep TCP.recv, the minimum change is to never request fewer than 4 bytes and to make the limit check unable to reject a response that is exactly at the limit. But the corruption above would remain.

2. A regression test is needed.
The issue asks for a test that splits the separator and the body across at least three receives. Nothing in gates/test.ts runs demos, so right now the fix is covered only by local smoke runs. Please add a test under tests/io/ that sets up a loopback listener, the way tcp_short_recv.bend / tcp_loopback.bend do. Have it send a response split across several writes, and end it with the #| lines it should print. A case at the limit, as in point 1, would also cover the limit logic.
limit, as in point 1, would also cover the limit logic.

3. Remove the duplicated branches.
The Fail arm (close, then IO.die) and the EOF arm (close, then fold the chunks) appear in both fetch_read and fetch_end, and the Fail arm a third time in fetch_sent. Move each into one helper. Also drop the cap: Bool parameter, since it is always U32.is_zero(remaining). A demo should be the shortest correct version.

4. Remove the CHANGELOG entry.
Release notes are written when a release is cut, so please leave CHANGELOG.md out of this PR.

How I reproduced it: the PR head is 5507220. I made a copy of the demo with TCP.connect("127.0.0.1", PORT) and ran it against a Bun Bun.listen server that writes chosen byte pieces with 400 ms pauses between them. I ran it both with bend file.bend (JS) and as a binary built with -o (native C).

scenario main this PR (JS / C)
separator and A/B/C over 6 writes `` (empty) ABC / ABC
65536 chars, ASCII at the end not run accepted / accepted
65536 chars, é at the end, its 2 bytes arriving in separate reads not run exit 1, "exceeds 65536" / same
café, é split across 2 writes caf�� caf�� / caf��

oxura and others added 2 commits October 5, 2026 22:10
The test imported demos/io_http_fetch/main.bend, which needed a
special case in gates/_lib.ts pack() and still broke gates/safe.ts,
whose tarball holds tests/ only. Copy the demo's reader into the test
and drop the gate change.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Lorenzobattistela
Lorenzobattistela merged commit b003a4e into bendlang:main Oct 5, 2026
1 check passed
@oxura

oxura commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Checked the merged byte reader in both Bun and native C with the committed real-loopback fixture: both print AéBC, 65516, é, empty:True and malformed:True. This exercises split UTF-8, the exact byte limit and EOF, in addition to the fragmented header/body case. The reader now decodes after collecting bytes and shares the failure/EOF helpers; the release note was removed. Thanks for identifying the character-vs-byte boundary error and adding permanent coverage.

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.

Demo bug: HTTP fetch truncates responses after two TCP reads

2 participants