Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ The format follows Keep a Changelog and the package uses semantic versioning.

## Unreleased

- Initiated best-effort cancellation of discarded HTTP object and bundle
response bodies. Missing/fallback/error outcomes, successful consumption,
conditional reads and request policy are preserved. Cancellation promises
are not awaited, and cleanup failures do not replace the status outcome.
Custom fetch implementations must treat their responses as reader-owned.
This adds no body-size limit, timeout, retry or connection-reuse guarantee.

- Fixed collection-keyed browser layout/index and engine index options reading
inherited properties as settings. Legal names such as `constructor` and
`__proto__` now use the existing defaults when no own entry exists.
Expand Down
4 changes: 4 additions & 0 deletions benchmarks/discarded-response-bodies/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.gitattributes text eol=lf
*.mjs text eol=lf
results/*.svg text eol=lf
results/native-*.json -text -diff
244 changes: 244 additions & 0 deletions benchmarks/discarded-response-bodies/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
# Discarded HTTP response bodies

## Decision

Merge-worthiness: 93/100. Recommend the scoped change after full CI and CodeQL
pass on the current pull request head and the required review is complete.
Every mandatory gate remains required regardless of score.

HTTP readers previously returned missing/error/fallback outcomes while leaving
their response bodies unread and uncancelled. The candidate initiates
best-effort cancellation before returning or throwing those same outcomes.
It preserves successful and conditional reads and does not await an
underlying cancellation promise.

All 54 candidate trials satisfy the desired ownership/status contracts,
compared with 18/54 historically. Every public result/error is unchanged;
the corrected contract is explicit discarded-body ownership, not completion
of previously failed application reads. All 18 ordinary controls retain
complete measured work. This is not a performance comparison.

## Scope and compatibility

| Boundary | Revision |
| --- | --- |
| Historical main, including merged P23 | `b99213de9b7e065f8e9bee7e1e2d6db158e83168` |
| Prospective protocol published before edits | `295b76d968a4bf717049674ee37210651d9de57a` |
| Frozen implementation, fixtures, collector, verifier and tests | `722dc35dd75347d625824ba7c8a91584a95e77bc` |

Production changes are 12 added lines in `src/browser/remote-reader.ts`:
four calls and one private helper. `HttpByteObjectReader` cancels discarded
missing/error bodies; `HttpJsonObjectReader` inherits this through delegation.
`HttpPointReadBundleReader` cancels discarded fallback/error bodies.

Object 404 remains missing; bundle 404/409/413 remain fallback. Other
unsuccessful statuses retain `HttpObjectReadError` name, status, key and
message. Successful bodies, payloads, byte accounting, ETags, conditional
object 304 handling, URLs, headers, fetch receiver, credentials and cache
options are unchanged.

Cancellation promises are not awaited. Synchronous custom-hook throws and
promise rejection do not replace the original status outcome. Pending
underlying cleanup can retain promise references; a synchronous hook still
runs synchronously. A locked stream cannot be forcibly cancelled. This
does not guarantee completed cleanup, immediate network abort or low latency.

The reader owns the Response supplied by its fetch implementation. Code
retaining that same response after a discarded outcome can now observe a
disturbed body or cancellation hook call. Custom fetch implementations must
not depend on those bodies staying readable. Shared-response ownership is a
poor fit for this API, whose successful path already consumes the body.

No public API, option/default, retry, timeout, body-size policy, storage or
encryption format changes. Package exports and starter interfaces are unchanged.
P24, P22, P19 and P7 remain parked and are not requalified.

## Method and evidence

The [prospective protocol](protocol.json) fixes three readers, four discard
statuses and four body forms. Open bodies have one queued UTF-8 chunk and
no close. Underlying cancellation succeeds, rejects with `cancel-failed`,
or remains pending until explicit driver release. Null bodies cover bodyless
responses. Each reader adds a valid closed success and a null 304 control.
Total: 54 trials per arm, 108 original rows and 18 complete controls.

Fixtures exercise actual public reader classes with native
Response/Headers/ReadableStream implementations and an injected
receiver-sensitive fetch. They record request arguments, complete
payload/bytes, public outcome/error, stream construction, source body-method
and cancellation calls, underlying-source hooks, return-time disturbed/locked
state, unhandled rejections and final driver cleanup.
This is controlled stream/interface evidence, not an actual HTTP transfer.

The sole scored comparison ran from detached frozen source, from
23:58:46.276Z to 23:58:53.835Z on 4 December 2026. Environment: Windows x64
10.0.26300, Node 22.22.2, bundled Undici 6.24.1, TypeScript 5.9.3,
esbuild 0.28.2 and Playwright 1.63.0. Timestamps are provenance, not latency
samples.

Independent verification checks 172 frozen inputs, including all tracked
source/tests and relevant configuration; rebuilds both complete 19-module
exact-Git API graphs and the complete one-module fixture graph; and exactly
replays all 108 observations. All 18 controls match complete measured work.
Every CSV cell and both graphs' counts, labels and bar geometry are checked.
Only global event sequence/interleaving is normalised; phase, operation,
reason, request, payload, outcome, error and state remain.

The driver uses saved real timers for five-second liveness bounds and two
task drains, outside source accounting. Pending cancellation is released
only after the public operation settles, so waiting for it would fail.
Owned unread streams are cleaned up and rejection listeners removed in
`finally`. No time distribution, CPU, heap or garbage-collection data is
collected.

| Artifact | Contents |
| --- | --- |
| [Scored capture](results/local-2026-12-04.json) | All 108 original rows, payloads, requests, states and all three complete executable graphs |
| [Per-trial CSV](results/local-2026-12-04-trials.csv) | Every contract, ownership state and phase cost |
| [Desired-contract graph](results/local-2026-12-04-success.svg) | All reader paths |
| [Source cancellation graph](results/local-2026-12-04-cancel.svg) | Explicit requests before public status settlement, not completed underlying cleanup |
| [Original native capture](results/native-2026-12-04.json) | One zero-retry invocation and all 324 original inline attachments |
| [Qualification manifest](results/qualification-2026-12-04.json) | Frozen/artifact/original-log identities, exact test results and attachment digests |

## Results

Each reader has 18 trials per arm: twelve discarded non-null bodies and six
null/success/conditional controls.

| Reader | Historical desired contracts | Candidate desired contracts | Historical/candidate source cancellations |
| --- | ---: | ---: | ---: |
| Bytes | 6/18 | 18/18 | 0/12 |
| JSON | 6/18 | 18/18 | 0/12 |
| Bundle | 6/18 | 18/18 | 0/12 |
| Total | 18/54 | 54/54 | 0/36 |

![Desired controlled response-body ownership contracts](results/local-2026-12-04-success.svg)

All 36 historical discarded non-null bodies remain undisturbed until driver
cleanup. The candidate starts one cancellation request and underlying hook
for each, without reading that payload or changing the public outcome.
Twelve candidate hooks reject without an unhandled rejection. Twelve others
are still pending when the public operation returns and are released by
the driver afterwards. Disturbance is not proof of completed underlying
resource release.

![Source cancellation requests for discarded bodies](results/local-2026-12-04-cancel.svg)

### Complete measured work

Values are historical/candidate. Counts include setup, the public read and
explicit driver cleanup for all 54 trials per arm. Native stream internals,
buffered/retained bytes, scheduling, allocations and transport operations
are not counted.

| Phase | Fetches | Array-buffer calls | Text calls | Cancel requests | Underlying hooks | Releases | Events |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| Setup | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 57/57 |
| Exercise | 54/54 | 2/2 | 1/1 | 0/36 | 0/36 | 0/0 | 111/183 |
| Cleanup | 0/0 | 0/0 | 0/0 | 36/0 | 36/0 | 12/12 | 96/12 |
| All | 54/54 | 2/2 | 1/1 | 36/36 | 36/36 | 12/12 | 264/252 |

Cancellation moves from driver cleanup to source ownership. Total calls are
36/36 after driver cleanup; this is not a reduction in cancellation work.
The twelve-event difference is the baseline driver's rejection records:
the candidate's best-effort handler observes those failures internally.
It is not a reduction in failed underlying cancellations or resource work.

Source execution now adds cancellation and rejection-handler work on those
discarded paths. Custom hooks can run synchronously or remain pending.
Physical memory, CPU, latency, TCP/connection reuse, provider behaviour and
production incidence remain unmeasured.

## Native qualification

One invocation passes 162 paired tests, with zero failures, retries, flakes
or skips. All 324 original observations pass independent per-arm validation
and exact Node correspondence. All 54 same-runtime control pairs match.
Every observation's own `__proto__` data sentinel survives JSON text transport.

| Engine | Version | Pairs | Historical desired contracts | Candidate desired contracts | Controls |
| --- | --- | ---: | ---: | ---: | ---: |
| Chromium | 153.0.8010.12 | 54 | 18/54 | 54/54 | 18/18 |
| Firefox | 155.0 | 54 | 18/54 | 54/54 | 18/18 |
| Windows WebKit | 26.6 | 54 | 18/54 | 54/54 | 18/18 |
| Total | | 162 | 54/162 | 162/162 | 54/54 |

The native harness routes the fixture document and three retained ESM
bundles at `http://p25.invalid`, aborting every other page request. Its
experiment-specific config has no web server. No authority helper, listening
port or persistent test secret is needed. The run exercises native Response
and stream interfaces, not an actual network server.

The native invocation starts on 5 December 2026 UTC, with a reporter duration
of 25,298.76 ms. This is provenance, not a latency sample. Filenames retain
the experiment's 4 December label. All inline attachment bytes are retained
in the original JSON; private output directories and the run record are also
retained.

This does not qualify Apple Safari, actual HTTP/TCP cancellation, background
behaviour, production browser populations or Cloudflare Worker runtime
behaviour. Windows WebKit is not Safari on Apple hardware.

## Other checks and limits

Preparation passes 71 focused cases. Exact historical substitution passes
28 and fails the 43 targeted cases. Additional focused coverage includes
locked bodies, synchronous custom cancellation throws, read failures,
already-consumed malformed JSON/bundles, missing ETags, bodyless 204 results
and repeat requests with fresh responses.

The related run passes 1,025 cases in 27 files, covering reader/envelope,
browser lifecycle/connection/cache, bundle/HEAD, layout, ownership, query
and engine controls. Repository, Studio, Worker and explicit fixture/native
types pass. Package build, isolated packed consumers/browser isolation and
all 54 complete built-entrypoint observations pass.

The candidate-only preparation and standard-API capability probes are
labelled separately from the sole scored comparison/native invocation.
All original preparation output and the derived output-layout audit
diagnostic are retained. The reporter stores attachment bodies inline, not
as per-test filesystem copies; recognising that layout changed no original,
frozen verifier, fixture, protocol or scored result.

This change does not replace application-specific body limits, request
deadlines or abort policy. It cannot forcibly release a locked stream or
guarantee a failing/hung cancellation hook releases its resources. Successful,
bodyless or already-consumed responses have no demonstrated ownership benefit.
No heap, throughput, latency, socket-reuse or production-frequency improvement
is established.

| Component | Score | Basis |
| --- | ---: | --- |
| Correctness and fit | 37/40 | Explicit ownership correction with preserved status outcomes; production incidence and transport effects unproven |
| Compatibility and work | 23/25 | Complete controls and contained failures; custom fetch hooks and discarded-body state intentionally change |
| Reproduction | 19/20 | Frozen graphs/172 inputs, complete replays, native originals and built probes; no real HTTP/TCP campaign |
| Simplicity | 14/15 | One production module, four calls and one private helper; pending rejection-handler retention remains possible |
| Total | 93/100 | Recommend only with every mandatory gate and required review |

## Reproduction

Use the frozen source and existing lockfile/dependencies. Evidence paths are
write-once; do not overwrite originals or substitute another native attempt.

```powershell
npx --no-install tsx benchmarks\discarded-response-bodies\run.mjs --preflight
npx --no-install tsx benchmarks\discarded-response-bodies\verify.mjs benchmarks\discarded-response-bodies\results\local-2026-12-04.json benchmarks\discarded-response-bodies\results\native-2026-12-04.json
npx --no-install vitest run tests\discarded-response-bodies.test.ts
```

The verifier rebuilds both exact-Git API graphs and the exact fixture graph,
replays all local observations and checks the original native attachments,
controls, CSV and graphs. A new measured campaign needs separately labelled
prospective qualification rather than replacing these observations.

## Research basis

- [Undici response-body garbage-collection guidance](https://github.com/nodejs/undici/blob/25e65a1af44afaa2e1d4c616a5f66b0ed758145f/README.md#garbage-collection),
checked 4 December 2026: consume or cancel unused bodies rather than relying
on nondeterministic garbage collection for connection resources.
- [MDN ReadableStream.cancel](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/cancel),
checked 4 December 2026: cancellation discards queued data and returns a
promise; locked streams reject and underlying cleanup may fail or wait.

These references motivate explicit ownership. They do not prove a ThimbleDB
connection, memory or performance benefit.
10 changes: 10 additions & 0 deletions benchmarks/discarded-response-bodies/baseline-vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {execFileSync} from "node:child_process";
import {readFileSync} from "node:fs";
import path from "node:path";
import {fileURLToPath} from "node:url";
import {defineConfig} from "vitest/config";
const root=fileURLToPath(new URL("../../",import.meta.url));
const {baseline}=JSON.parse(readFileSync(new URL("./protocol.json",import.meta.url),"utf8")) as {baseline:string};
const file=path.join(root,"src","browser","remote-reader.ts").replaceAll("\\","/");
const source=execFileSync("git",["show",`${baseline}:src/browser/remote-reader.ts`],{cwd:root,encoding:"utf8"});
export default defineConfig({root,plugins:[{name:"exact-response-baseline",enforce:"pre",load(id){return id.replaceAll("\\","/").split("?")[0]===file?source:null}}],test:{include:["tests/discarded-response-bodies.test.ts"]}});
Loading