Skip to content

net, script: Partition CORS preflight cache by top-level site - #49252

Merged
TimvdLippe merged 1 commit into
servo:mainfrom
sabbCodes:issue-49228
Oct 26, 2026
Merged

TimvdLippe merged 1 commit into
servo:mainfrom
sabbCodes:issue-49228

Conversation

@sabbCodes

Copy link
Copy Markdown
Contributor

Partitioned the CORS preflight cache by the top-level site network
partition key according to the Fetch specification.

Testing: ./mach test-wpt tests/wpt/tests/cors/preflight-cache-partitioning.sub.window.js (passes: 1/1 subtests OK).
./mach test-wpt tests/wpt/tests/cors/preflight-cache.htm (passes: 5/6 expected subtests OK).
All other checks were normal
Fixes: #49228

@sabbCodes
sabbCodes requested a review from gterzian as a code owner October 25, 2026 05:31
@servo-highfive servo-highfive added the S-awaiting-review There is new code that needs to be reviewed. label Oct 25, 2026
Comment thread components/net/fetch/cors_cache.rs Resolved
Comment thread components/net/fetch/cors_cache.rs Resolved
Comment thread components/net/fetch/cors_cache.rs Resolved
Comment thread components/net/fetch/cors_cache.rs Resolved
Comment thread components/shared/net/pub_domains.rs Resolved
@servo-highfive servo-highfive added S-needs-code-changes Changes have not yet been made that were requested by a reviewer. and removed S-awaiting-review There is new code that needs to be reviewed. labels Oct 25, 2026
@sabbCodes

Copy link
Copy Markdown
Contributor Author

Kind of expect these, I've been cracking my brain on this since yesterday, knew there has to be corrections 😅

Love the challenge anyway.
Will look into it, ser.

@TimvdLippe

Copy link
Copy Markdown
Contributor

Don't feel disheartened by the amount of comments. This work is great and I am looking forward to it! Only helping you out with landing it 😄

@sabbCodes

Copy link
Copy Markdown
Contributor Author

Ah, no.

I'm actually learning a lot from these.
It's my pleasure 😄

@servo-highfive servo-highfive added S-awaiting-review There is new code that needs to be reviewed. and removed S-needs-code-changes Changes have not yet been made that were requested by a reviewer. labels Oct 25, 2026

@TimvdLippe TimvdLippe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Last couple of nits, the rest LGTM. Thanks!

Comment thread components/shared/net/pub_domains.rs Resolved
@servo-highfive servo-highfive removed the S-awaiting-review There is new code that needs to be reviewed. label Oct 25, 2026
@servo-highfive servo-highfive added the S-awaiting-review There is new code that needs to be reviewed. label Oct 25, 2026

@TimvdLippe TimvdLippe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One last nit. Let's run the test as well after that assert to ensure we covered everything

@servo-highfive servo-highfive removed the S-awaiting-review There is new code that needs to be reviewed. label Oct 25, 2026
@sabbCodes

Copy link
Copy Markdown
Contributor Author

One last nit. Let's run the test as well after that assert to ensure we covered everything

Alright ser

@sabbCodes

sabbCodes commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Tests are still passing

@servo-highfive servo-highfive added the S-awaiting-review There is new code that needs to be reviewed. label Oct 25, 2026
@TimvdLippe
TimvdLippe added this pull request to the merge queue Oct 25, 2026
@servo-highfive servo-highfive added the S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. label Oct 25, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 26, 2026
@servo-highfive servo-highfive added S-tests-failed The changes caused existing tests to fail. and removed S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. labels Oct 26, 2026
@jdm

jdm commented Oct 26, 2026

Copy link
Copy Markdown
Member
CRASH [expected OK] /content-security-policy/sandbox/iframe-self-all-directives.sub.html
TIMEOUT [expected PASS] /css/css-position/position-absolute-iframe-print-002.sub.html
TIMEOUT [expected PASS] /domparsing/createContextualFragment-in-detached-xml-document-crash.html
CRASH [expected OK] /fetch/api/request/multi-globals/construct-in-detached-frame.window.html
TIMEOUT [expected OK] /focus/activeelement-after-calling-window-focus.sub.html
TIMEOUT [expected OK] /html/browsers/history/the-location-interface/location-ancestor-origins.sub.html
CRASH [expected OK] /html/browsers/origin/origin-keyed-agent-clusters/data-frame-child.https.sub.html
TIMEOUT [expected OK] /html/interaction/focus/the-autofocus-attribute/same-origin-autofocus.html
TIMEOUT [expected PASS] /html/semantics/embedded-content/the-img-element/document-destroyed-crash.html
CRASH [expected PASS] /html/semantics/forms/the-input-element/input-importNode-to-detached-document-crash.html
CRASH [expected PASS] /html/semantics/scripting-1/the-template-element/template-element/template-set-inner-html-in-inactive-document-crash.html
TIMEOUT [expected OK] /html/user-activation/consumption-crossorigin.sub.html
TIMEOUT [expected OK] /html/user-activation/propagation-crossorigin.sub.html
CRASH [expected OK] /html/webappapis/dynamic-markup-insertion/opening-the-input-stream/active.window.html
CRASH [expected OK] /html/webappapis/dynamic-markup-insertion/opening-the-input-stream/event-listeners.window.html
CRASH [expected OK] /html/webappapis/dynamic-markup-insertion/opening-the-input-stream/url.window.html
TIMEOUT [expected OK] /intersection-observer/scroll-margin-propagation.html
TIMEOUT [expected PASS] /svg/styling/svg-filter-render-same-origin-frame-in-cross-origin-frame.tentative.sub.https.html
CRASH [expected OK] /xhr/open-url-multi-window-3.htm

@sabbCodes

Copy link
Copy Markdown
Contributor Author

Thank you

@servo-highfive servo-highfive removed the S-tests-failed The changes caused existing tests to fail. label Oct 26, 2026
@jdm jdm added the T-linux-wpt Do a try run of the WPT label Oct 26, 2026
@github-actions github-actions Bot removed the T-linux-wpt Do a try run of the WPT label Oct 26, 2026
@github-actions

Copy link
Copy Markdown

🔨 Triggering try run (#40314367854) for Linux (WPT)

@github-actions

Copy link
Copy Markdown

Test results for linux-wpt from try job (#40314367854):

Flaky unexpected result (18)
  • CRASH [expected ERROR] /IndexedDB/idbfactory_deleteDatabase.any.serviceworker.html
  • OK /IndexedDB/idbtransaction-oncomplete.any.sharedworker.html (#45911)
    • FAIL [expected PASS] subtest: IDBTransaction - complete event

      assert_array_equals: lengths differ, expected array ["upgradeneeded", "complete", "success", "opencursor"] length 4, got ["upgradeneeded", "complete", "success"] length 3
      

  • TIMEOUT [expected OK] /content-security-policy/inheritance/document-write-iframe.html (#47620)
    • TIMEOUT [expected PASS] subtest: document.open() keeps inherited CSPs on transient about:blank.

      Test timed out
      

  • OK /css/CSS2/linebox/inline-negative-margin-001.html (#43763)
    • FAIL [expected PASS] subtest: [data-expected-height] 3

      assert_equals: 
      <div class="w4" data-expected-height="10">123 <span style="margin-left: -4ch">1234 </span></div>
      height expected 10 but got 20
      

    • FAIL [expected PASS] subtest: [data-expected-height] 4

      assert_equals: 
      <div class="w4" data-expected-height="10">123 <span style="margin-left: -4ch">123 </span></div>
      height expected 10 but got 20
      

    • FAIL [expected PASS] subtest: [data-expected-height] 5

      assert_equals: 
      <div class="w4" data-expected-height="10"><img class="w4"><span style="margin-left: -4ch">123</span></div>
      height expected 10 but got 20
      

    • FAIL [expected PASS] subtest: [data-expected-height] 6

      assert_equals: 
      <div class="w4" data-expected-height="10"><img class="w5"><span style="margin-left: -5ch">123</span></div>
      height expected 10 but got 20
      

    • FAIL [expected PASS] subtest: [data-expected-height] 8

      assert_equals: 
      <div class="w4" data-expected-height="10"><img class="w4"><img class="w1" style="margin-left: -1ch"></div>
      height expected 10 but got 20
      

    • FAIL [expected PASS] subtest: [data-expected-height] 10

      assert_equals: 
      <div class="w4" data-expected-height="10"><img class="w5"><img class="w1" style="margin-left: -2ch"></div>
      height expected 10 but got 20
      

  • FAIL [expected PASS] /css/css-backgrounds/background-size-042.html
  • TIMEOUT [expected PASS] /dom/nodes/moveBefore/moveBefore-range-iframe-crash.html
  • OK [expected ERROR] /focus/focus-event-after-switching-iframes.sub.html (#40368)
  • OK /html/browsers/browsing-the-web/navigating-across-documents/navigation-unload-same-origin-fragment.html (#20768)
    • FAIL [expected PASS] subtest: Tests that a fragment navigation in the unload handler will not block the initial navigation

      assert_equals: expected "" but got "#fragment"
      

  • OK /html/browsers/browsing-the-web/navigating-across-documents/navigation-unload-same-origin.window.html (#29049)
    • PASS [expected FAIL] subtest: Same-origin navigation started from unload handler must be ignored
  • OK /html/browsers/browsing-the-web/navigating-across-documents/refresh/same-document-refresh.html (#34597)
    • FAIL [expected PASS] subtest: Same-Document Referrer from Refresh

      assert_equals: original page loads expected "http://web-platform.test:8000/html/browsers/browsing-the-web/navigating-across-documents/refresh/resources/refresh-with-section.sub.html?url=%23section" but got "http://web-platform.test:8000/html/browsers/browsing-the-web/navigating-across-documents/refresh/resources/refresh-with-section.sub.html?url=%23section#section"
      

  • OK /html/semantics/forms/form-submission-0/jsurl-form-submit.tentative.html (#36489)
    • PASS [expected FAIL] subtest: Verifies that form submissions scheduled inside javascript: urls take precedence over the javascript: url's return value.
  • TIMEOUT [expected OK] /html/user-activation/navigation-state-reset-sameorigin.html (#45151)
    • TIMEOUT [expected FAIL] subtest: Post-navigation state reset.

      Test timed out
      

  • OK /infrastructure/testdriver/click_window.html (#47303)
    • FAIL [expected PASS] subtest: TestDriver click method in window

      Unhandled rejection: assert_unreached: click failed Reached unreachable code
      

  • FAIL [expected PASS] /mathml/presentation-markup/operators/mo-lspace-rspace-dynamic.html (#49168)
  • PASS [expected FAIL] /mathml/presentation-markup/operators/mo-single-char-and-children.html
  • TIMEOUT [expected OK] /pointerevents/compat/pointerevent_touch-action_two-finger_interaction.html
    • NOTRUN [expected PASS] subtest: touch two-finger pan on 'touch-action: pan-x pan-y'
    • NOTRUN [expected FAIL] subtest: touch two-finger pan on 'touch-action: pinch-zoom'
  • OK /upgrade-insecure-requests/gen/sharedworker-module-data.meta/unset/fetch.https.html
    • FAIL [expected PASS] subtest: Upgrade-Insecure-Requests: Expects blocked for fetch to cross-http-downgrade origin and downgrade redirection from https context.

      assert_equals: The resource request should be 'blocked'. expected "blocked" but got "allowed"
      

    • FAIL [expected PASS] subtest: Upgrade-Insecure-Requests: Expects blocked for fetch to cross-http-downgrade origin and no-redirect redirection from https context.

      assert_equals: The resource request should be 'blocked'. expected "blocked" but got "allowed"
      

    • FAIL [expected PASS] subtest: Upgrade-Insecure-Requests: Expects blocked for fetch to cross-https origin and downgrade redirection from https context.

      assert_equals: The resource request should be 'blocked'. expected "blocked" but got "allowed"
      

    • FAIL [expected PASS] subtest: Upgrade-Insecure-Requests: Expects blocked for fetch to same-http-downgrade origin and downgrade redirection from https context.

      assert_equals: The resource request should be 'blocked'. expected "blocked" but got "allowed"
      

    • FAIL [expected PASS] subtest: Upgrade-Insecure-Requests: Expects blocked for fetch to same-http-downgrade origin and no-redirect redirection from https context.

      assert_equals: The resource request should be 'blocked'. expected "blocked" but got "allowed"
      

    • FAIL [expected PASS] subtest: Upgrade-Insecure-Requests: Expects blocked for fetch to same-https origin and downgrade redirection from https context.

      assert_equals: The resource request should be 'blocked'. expected "blocked" but got "allowed"
      

  • OK /wasm/webapi/abort.any.html (#39966)
    • FAIL [expected PASS] subtest: instantiateStreaming() asynchronously racing with abort should succeed or reject with AbortError

      assert_equals: expected "AbortError" but got "CompileError"
      

Stable unexpected results that are known to be intermittent (12)
  • OK /beacon/beacon-basic.https.window.html (#41723)
    • FAIL [expected PASS] subtest: Payload size restriction should be accumulated: type = blob

      assert_false: expected false got true
      

  • OK /css/css-fonts/variations/at-font-face-font-matching.html (#20684)
    • FAIL [expected PASS] subtest: Matching font-stretch: '110%' should prefer '115% 116%' over '105%'

      assert_equals: Unexpected font on test element expected 487 but got 532
      

  • CRASH [expected OK] /html/browsers/browsing-the-web/navigating-across-documents/005.html (#27062)
  • OK [expected TIMEOUT] /html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit.html (#44028)
  • CRASH [expected OK] /html/browsers/history/the-location-interface/assign-replace-from-iframe.html (#47679)
  • TIMEOUT /html/browsers/sandboxing/sandbox-window-open-srcdoc.html (#48863)
    • TIMEOUT [expected PASS] subtest: window.open('about:srcdoc') from sandboxed srcdoc doesn't crash.

      Test timed out
      

    • NOTRUN [expected PASS] subtest: popup is isolated from an isolated iframe
  • OK [expected TIMEOUT] /html/semantics/embedded-content/media-elements/autoplay-default-permissions-policy.https.sub.html (#46805)
    • PASS [expected TIMEOUT] subtest: Default "autoplay" feature policy ["self"] allows the top-level document.
    • PASS [expected TIMEOUT] subtest: Default "autoplay" feature policy ["self"] allows same-origin iframes.
  • OK /html/semantics/embedded-content/media-elements/media_fragment_seek.html (#24114)
    • PASS [expected FAIL] subtest: Video should seek to time specified in media fragment syntax
  • OK /html/semantics/forms/form-submission-0/form-submit-iframe-then-location-navigate.html (#29634)
    • FAIL [expected PASS] subtest: Verifies that location navigations take precedence when following form submissions.

      assert_equals: expected "/html/semantics/forms/form-submission-0/resources/location.html" but got "/html/semantics/forms/form-submission-0/resources/form.html"
      

  • OK /html/webappapis/user-prompts/print-during-unload.html (#35944)
    • FAIL [expected PASS] subtest: print() during unload

      assert_array_equals: expected property 1 to be "destination" but got "error: window.print is not a function" (expected array ["start", "destination"] got ["start", "error: window.print is not a function"])
      

  • OK /mathml/relations/text-and-math/basic-mathematical-alphanumeric-symbols-with-default-font.html (#49181)
    • FAIL [expected PASS] subtest: Bold mathematical alphanumeric symbol with the default font

      assert_greater_than: Width of 'U+1D416 MATHEMATICAL BOLD CAPITAL W' is much larger than 'U+1D529 MATHEMATICAL FRAKTUR SMALL L' expected a number greater than 60 but got 60
      

    • FAIL [expected PASS] subtest: Bold-italic mathematical alphanumeric symbol with the default font

      assert_greater_than: Width of 'U+1D47E MATHEMATICAL BOLD ITALIC CAPITAL' is much larger than 'U+1D529 MATHEMATICAL FRAKTUR SMALL L' expected a number greater than 60 but got 60
      

  • OK /mixed-content/tentative/autoupgrades/video-upgrade.https.sub.html (#41135)
    • FAIL [expected PASS] subtest: Video of other host autoupgraded

      assert_equals: Length. Other host expected 1 but got Infinity
      

@github-actions

Copy link
Copy Markdown

✨ Try run (#40314367854) succeeded.

@TimvdLippe
TimvdLippe added this pull request to the merge queue Oct 26, 2026
@servo-highfive servo-highfive added the S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. label Oct 26, 2026
Merged via the queue into servo:main with commit 600d5df Oct 26, 2026
76 checks passed
@servo-highfive servo-highfive removed the S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. label Oct 26, 2026
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Oct 30, 2026
The HTTP cache kept every stored body as a `Vec<u8>` in the net process,
shared with the response handed to the consumer, so net also kept the
decoded body of every response until its fetch ended. Its RFC 9111
rules were hand-written for RFC 7234.

The rules now come from the `http-cache-rules` crate: storability, the
stored and updated header fields, freshness (with `max-age`, `Expires`,
the heuristic, `Age` and `Date`), `Vary`, `stale-while-revalidate`,
`immutable`, the request directives, the validation request and the
merge of a 304. The crate decides and stores nothing; its requirements
are traced to the RFC text and tested, model checked and fuzzed in its
own repository. `http_cache::policy` configures it as a private cache
that stores 206 responses and their bodies encoded.

Servo keeps what belongs to the fetch layer: the cache modes, background
revalidation (only for requests with a client), invalidation after
unsafe methods, ranges, and its own refusals on top of the crate: `Vary:
*`, entries over the store's size limit, 206 without `Content-Range`,
and the storage rule for audio and video of patch 79.

Storage moves behind `CacheStore`, which streams bodies in and out:

  * `TeeBody` copies each frame into the store below the content
    decoder, so the stored body is what came off the wire, and the copy
    is a reference count, not a second allocation. The store's bounded
    queue back-pressures the network.
  * A hit streams the entry through the decoder in chunks.
  * `ResponseBody::Streamed` marks a body delivered to the consumer and
    kept nowhere. Only subresource integrity and preloads still keep the
    whole decoded body (`retains_whole_body`), so net no longer keeps
    media bodies, which patch 79 had to arrange separately.
  * An entry is visible only once its decoded body ended cleanly, so a
    failed, cancelled or truncated body never becomes an entry, which
    patch 80 had to arrange separately. The fetch commits it through a
    `TeeCommit`, not `TeeBody` at the end of the network body: the
    decoder stops reading at the end of a gzip or brotli stream.
  * Every entry carries a random stamp, and the store opens, updates
    and removes an entry only for the stamp it was looked up with, since
    a later entry of the key may reuse its id.
  * `http_cache::inflight` lets one fetch write a key. Once its headers
    show a fresh response, others wait for it and read the committed
    entry, or go to the network if it aborts or, as patch 92 requires,
    while it is suspended. Before that, or if the response needs
    validation, they go to the network as with the old cache, so a slow
    or long-polled response holds up no other fetch. Once the whole body
    has arrived, they wait for any response while the store commits it,
    so a fetch right after another one finds its entry. A fetch does
    not wait for a response that varies on a field in which its own
    request differs, or whose body outgrows what the store accepts. It
    stops waiting when it is cancelled, and goes on from there like any
    cancelled fetch, and it waits 5 s at most.
  * `MemoryStore` is the only store in this patch: byte-bounded, LRU,
    for private browsing, temporary storage, no cache directory, and
    the tests. The SQLite cache goes, and `rusqlite`, `sea-query` and
    `quick_cache` leave `components/net`.

Fixes over the cache of the `http-cache-v2` branch, which this replaces:
a 304 no longer collapses repeated stored fields (a two-line CSP lost a
line) nor freshens on a weak or mismatching strong validator, `Age`
takes `Date` and the request time into account, the RFC 850 and asctime
date formats are understood, and `Vary` compares all field lines. That
branch also never stored a compressed response but stored a gzip body
cut short under clean framing, let a late 304 freshen or remove the
entry that had replaced its own, and made a fetch wait for the whole
body of another fetch's response even when it could not use it, and
wrote the URL's credentials into every entry: the key now leaves them
and the fragment out, and a stored response is served with the
request's URL. An
invalidation through `Location` or `Content-Location` reaches only URIs
of the target's origin (RFC 9111 4.4). Of several matching stored
responses the most recent is used (RFC 9111 4). When a 304 is about
another response than the stored one, the request is made again without
preconditions, and that response is stored.

Prefs: `network_http_cache_size` (an entry count) and
`network_http_disk_cache` (a path) are replaced by
`network_http_memory_cache_size` and `network_http_cache_max_entry_size`,
in bytes; `network_http_disk_cache_size` gains 0 = automatic.

`apply_algorithm_to_response` returned through `unreachable!()` when
the body was not `Done`, which a null body status makes it, and a
streamed body would reach reliably. It now returns a digest that cannot
match, so the fetch fails as `response-null-body.any.js` expects.

`preload/prefetch-document.html`: "different-site document prefetch with
'as=document' should not be consumed" now also fails at times, like its
two siblings. Servo has no HTTP cache partition (servo#33616), so the fresh
response of a cross-site prefetch answers the later navigation, unless
the navigation starts before the prefetch's response headers arrive and
goes to the network. With `network_http_cache_disabled=true` the subtest
passes and the "same origin ... should be consumed" sibling fails
instead.

Fork note: supersedes patches 79 and 80 (their cache code goes; their
fetch tests stay), and moves the cache side of patch 92 into
`http_cache::inflight`. 79 and 80 stayed on the stack at the 2026-10-22
sync: patch 92 builds on both (it calls 79's `may_store_media_response`
and sets 80's abort flag), so dropping them means reworking 92. Uses
`http-cache-rules` 0.1.0 from crates.io.

Testing: tests/http_cache.rs covers storability, Vary, freshness,
stale-while-revalidate with and without a client, partial entries and
ranges (with the five range tests of the `http-cache-range` branch),
the encoded body, the media storage rule, same-origin invalidation and
the most recent variant. tests/fetch.rs covers a 304 with another strong
validator, a 304 resetting Age, and a 304 with no-store.
tests/http_loader.rs covers a compressed response answered from the
cache, a compressed body cut short, and fetches that do not wait for the
headers of another fetch, a response that needs validation, a variant
of another request or a body too large to store, and that stop waiting
when cancelled or after a while; tests/http_cache.rs also a URL with
credentials and a fragment; tests/cache_store.rs an id reused by another
entry. The fetch tests of
patches 79, 80 and 92 are adapted to entries that appear on commit.

Validation: `./mach test-unit -p servo-net`: 435 tests pass. Negative controls, each run once: without the origin check, the most-recent selection, the 304 exception in `tee` or the suspended-producer wait, `test_invalidation_only_reaches_the_same_origin`, `test_the_most_recent_matching_response_is_used`, `test_a_304_for_another_response_makes_the_request_again_without_preconditions` and `test_fetch_waiting_for_a_suspended_response_uses_the_network` fail. Without the commit on the decoded end, the stamps and the waiting rule, `test_compressed_response_is_answered_from_cache`, `test_compressed_response_cut_short_is_not_stored`, `a_reused_id_is_not_touched_on_behalf_of_its_old_entry` (memory and disk store) and `test_fetch_does_not_wait_for_a_response_that_needs_validation` fail; with waiters waiting from the writer's registration on, `test_fetch_does_not_wait_for_the_headers_of_another_fetch` fails as well, and with waiters waiting for any response the validation one does. With patches 121 to 123: `./mach test-unit --profile checked-release` (1212 tests) and `--doc` pass; `./mach clippy --locked -- -- --deny warnings`, the crown `checked-release` build and the OHOS `checked-release` build with `RUSTFLAGS="-D warnings"` are clean, as is `./mach test-tidy`. WPT, `checked-release`, 8 processes, fetch/http-cache, fetch/range, fetch/stale-while-revalidate, fetch/api, cors, xhr, preload, html/semantics/embedded-content/media-elements and html/semantics/scripting-1, 2140 tests: 2134 as expected, and "Response with Cache-Control: max-age=2592000, public and Pragma: no-cache should not be cached" now passes (expectation removed; the crate's deviation D-2). The other six behave the same alone on ohos-main 091e100215c: src_object_blob.html times out 3 of 8 runs (2 of 8 there), load-removes-queued-error-event.html crashes 5 of 8 (4 of 8 there), media_fragment_seek.html fails and autoplay-default-permissions-policy.https.sub.html passes every time on both, and seek-to-max-value.htm and track-remove-by-setting-innerHTML.html pass 3 of 3 on both. Full WPT, `checked-release`, 12 processes, on the build before the waiting rule was fixed: 58273 of 58348 tests as expected. The other 75 were run again serially, those still unexpected on ohos-main 091e100215c too, and the 12 that differed 3 times alone on both: async_003.htm, async_004.htm and async_005.htm failed every time on the branch only (their script's headers are delayed, and a second fetch of it waited for them), and pass 3 of 3 with the fix; the other 9 behave the same on both. The focused set without scripting-1 on QuickJS (`--js-engine quickjs`), before the review fixes: 1540 of 1545 as expected, three of the same media tests, and two track-element timeouts that pass 3 of 3 alone on both builds. On ohos-main deaca97 with `http-cache-rules` 0.1.0 from crates.io (the same files as the path dependency tested above): `./mach test-unit -p servo-net` passes, 435 tests here and 472 with patch 121, and the CI-parity checks above pass again at patch 123, except `indexeddb::engines::sqlite::tests::test_async_operations` of servo-storage, which timed out once and passes 3 of 3 alone. `test_response_cache_status_is_validated` failed 5 of 320 runs, 32 at a time, while the commit of the first response was not waited for, and 0 of 960 after. WPT fetch/http-cache, fetch/range, fetch/stale-while-revalidate, preload and html/semantics/scripting-1, 756 tests: as expected but for execution-timing/077.html, which passes 3 of 3 alone here and fails 1 of 3 alone on ohos-main 091e100215c, and the prefetch-document subtest above, which passed 2 of 3 runs alone; its expectation now allows both. Review fixes (the wait ends on cancellation, does not start for another variant or a body too large to store, and times out; the key leaves out the credentials and fragment of the URL): 440 tests pass here, and 481 with patch 121. Negative controls, each run once: without the cancellation of the wait, `test_a_waiting_fetch_stops_waiting_when_it_is_cancelled` fails; without the `Vary` check, the cap in `TeeBody`, the timeout or the password left out of the key, `test_fetch_does_not_wait_for_a_response_that_varies_from_its_request`, `test_fetch_does_not_wait_for_a_response_too_large_to_store`, `test_a_waiting_fetch_goes_to_the_network_after_a_while` and `test_url_credentials_and_fragment_are_not_part_of_the_key` fail. At patch 123 the CI-parity checks pass again (`test-unit --profile checked-release`: 1221 tests), and WPT fetch/http-cache, fetch/range, fetch/stale-while-revalidate, fetch/api, preload, html/semantics/scripting-1 and html/semantics/embedded-content/media-elements, 1679 tests, run as expected but for four of the media tests above and seek-to-currentTime.html, which passes 3 of 3 alone on both builds. A first version also returned a network error from step 9 of HTTP-network-or-cache fetch for any fetch cancelled before it reached the network. PR CI caught that: requests sent while a document unloads were dropped, and fetch/fetch-later/send-on-discard/send-multiple, both sandbox-top-navigation-child-delivered tests, navigation-timing/nested-unload-timing and navigation-timing/prefetch-transfer-size-executor failed in both attempts of that CI run and in a serial local run. Without it they run as expected in 2 of 2 serial local runs; of the other stable unexpected results of that CI run, window-resize-event.html times out alone on ohos-main 091e100215c too, and test_resource_timing and media-loading-pseudo-classes-in-has.sub.html behave the same alone on both builds and are flaky upstream.
AI-assisted: Yes (agent session; the agent ported the storage half of the http-cache-v2 branch, wrote the glue over http-cache-rules and the merge with patches 79, 80 and 92, and wrote and ran the tests)
AI-assisted: Yes (agent session; 2026-10-22 sync -- conflict resolution: `http_cache.rs` deleted as before, which drops upstream's edits to it (servo#48927 most recent matching response and replacement of matching responses, servo#48842); this cache uses the most recent matching response already and makes the request again when a 304 is about another response. The old cache steps of HTTP-network-or-cache fetch and `block_for_cache_ready` go as before, with upstream's edits to them (servo#48927, servo#48867); `obtain_response` keeps upstream's new `FetchParams` signature (servo#49040) and returns the body below the decoder as before; test imports merged. `./mach test-unit -p servo-net` at this commit: 440 tests pass)
AI-assisted: Yes (agent session; 2026-10-22 sync -- the fork note says why patches 79 and 80 were not dropped)
AI-assisted: Yes (agent session; 2026-10-29 sync -- test compile fix: `request_with_client()` sets the new `RequestClient::network_partition_key` (servo#49252))
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Oct 30, 2026
A response body was held twice: as a state in a shared
`Arc<Mutex<ResponseBody>>`, and as a `done_chan` that every fetch function
passed along and had to reset whenever it replaced the response. Keeping
the two paired by convention went wrong in several ways:

- A fetch cancelled right after its headers returned a network error while
  `done_chan` still held a sender, so `wait_for_response` waited forever
  and the fetch never ended.
- A response replaced by a network error, after a failed CORS check or a
  CORP, CSP, nosniff, MIME type or mixed content block, kept its channel,
  so its body was still delivered to the consumer.
- Step 22 of main fetch (null body status, HEAD) blanked the state, but not
  the chunks already queued in the channel.
- A navigation through a `web+` protocol handler returned a response whose
  body an inner fetch had already handed to `DiscardFetch`.
- Producers had to know whether a consumer inside net (subresource
  integrity, preloads) needed the whole body, and `file:` and `blob:`
  bodies were kept whole in net in any case. An in-memory `blob:` body was
  never kept, so its integrity check always failed.

`ResponseBody` is now `Null`, `Bytes`, or a `Stream` of the body stream
type added in the previous patch, and the response owns it.
`wait_for_response` is the one place that hands a body over, and it keeps
the body as `Bytes` for preloads and for subresource integrity. A body whose
producer goes away without finishing ends as failed instead of hanging. The
body of a redirect, or of a response replaced after a 401 or 407, is
discarded instead of being queued while the next request runs; readers of
files and of the cache stop when nobody reads their body.
`ProtocolHandler::load` loses its `done_chan` parameter, and
`servo::protocol_handler` exports the body stream. `Response` is no longer
`Clone`: `try_clone` copies a response whose body is not a stream. The page
content protocol handler runs main fetch recursively, so the outer fetch
hands the handler URL's body over.

Otherwise behaviour does not change: a body cut short by the connection
still ends as aborted with a successful end of file, a discarded network
body is still read to its end so that its connection can be reused and the
cache can store it, and subresource integrity still forwards the body
before checking it. One exception: a preload whose body is cut short is
now kept without a body instead of with the bytes that arrived; both are
wrong, and a later patch makes it a network error.

Validation: `./mach test-unit -p servo-net`: 490 tests pass, 7 of them new. On ohos-main 67173a4, `test_fetch_cancelled_while_its_headers_are_held_ends` fails with "the fetch did not end", `test_body_of_a_response_that_fails_the_cors_check_is_not_delivered` with all 19 body bytes delivered, `test_body_of_a_response_blocked_by_nosniff_is_not_delivered` with all 12, and `test_navigation_through_a_page_content_protocol_handler_delivers_the_body` with none. Negative controls on this patch: without applying step 22's null body, `test_body_of_a_null_body_status_is_not_delivered` gets 7 bytes; with a test producer that keeps its sender alive, `test_body_whose_producer_stops_without_finishing_ends_the_fetch` does not end; without keeping preloaded bodies, `test_fetch_of_a_preload_keeps_its_body` finds no body. `./mach check`, `./mach clippy --locked -- -- --deny warnings` and `./mach test-tidy` pass. 2026-10-29 sync (CORS cache now in the fetch context): `./mach test-unit --profile checked-release -p servo-net` at this commit, 490 tests pass.
AI-assisted: Yes (agent session; the agent wrote this patch and its tests following docs/fetch-body-stream-plan-2026-10-22.md in the workspace, found the cancellation hang, the delivery of blocked bodies and the protocol handler regression, and applied an independent review's findings)
AI-assisted: Yes (agent session; 2026-10-29 sync -- conflict resolution, no semantic change: upstream moved the CORS preflight cache into the fetch context (servo#49055, servo#49252), so `main_fetch`, `scheme_fetch`, `http_fetch` and `http_redirect_fetch` lose both the cache and `done_chan`, and the page content protocol handler's inner main fetch no longer passes a fresh cache; the preflight fetch keeps upstream's devtools reporting (servo#49151); `to_filtered` takes the headers out of the internal response before its body-less copy, as upstream now does (servo#49313))
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Nov 9, 2026
The HTTP cache kept every stored body as a `Vec<u8>` in the net process,
shared with the response handed to the consumer, so net also kept the
decoded body of every response until its fetch ended. Its RFC 9111
rules were hand-written for RFC 7234.

The rules now come from the `http-cache-rules` crate: storability, the
stored and updated header fields, freshness (with `max-age`, `Expires`,
the heuristic, `Age` and `Date`), `Vary`, `stale-while-revalidate`,
`immutable`, the request directives, the validation request and the
merge of a 304. The crate decides and stores nothing; its requirements
are traced to the RFC text and tested, model checked and fuzzed in its
own repository. `http_cache::policy` configures it as a private cache
that stores 206 responses and their bodies encoded.

Servo keeps what belongs to the fetch layer: the cache modes, background
revalidation (only for requests with a client), invalidation after
unsafe methods, ranges, and its own refusals on top of the crate: `Vary:
*`, entries over the store's size limit, 206 without `Content-Range`,
and the storage rule for audio and video of patch 79.

Storage moves behind `CacheStore`, which streams bodies in and out:

  * `TeeBody` copies each frame into the store below the content
    decoder, so the stored body is what came off the wire, and the copy
    is a reference count, not a second allocation. The store's bounded
    queue back-pressures the network.
  * A hit streams the entry through the decoder in chunks.
  * `ResponseBody::Streamed` marks a body delivered to the consumer and
    kept nowhere. Only subresource integrity and preloads still keep the
    whole decoded body (`retains_whole_body`), so net no longer keeps
    media bodies, which patch 79 had to arrange separately.
  * An entry is visible only once its decoded body ended cleanly, so a
    failed, cancelled or truncated body never becomes an entry, which
    patch 80 had to arrange separately. The fetch commits it through a
    `TeeCommit`, not `TeeBody` at the end of the network body: the
    decoder stops reading at the end of a gzip or brotli stream.
  * Every entry carries a random stamp, and the store opens, updates
    and removes an entry only for the stamp it was looked up with, since
    a later entry of the key may reuse its id.
  * `http_cache::inflight` lets one fetch write a key. Once its headers
    show a fresh response, others wait for it and read the committed
    entry, or go to the network if it aborts or, as patch 92 requires,
    while it is suspended. Before that, or if the response needs
    validation, they go to the network as with the old cache, so a slow
    or long-polled response holds up no other fetch. Once the whole body
    has arrived, they wait for any response while the store commits it,
    so a fetch right after another one finds its entry. A fetch does
    not wait for a response that varies on a field in which its own
    request differs, or whose body outgrows what the store accepts. It
    stops waiting when it is cancelled, and goes on from there like any
    cancelled fetch, and it waits 5 s at most.
  * `MemoryStore` is the only store in this patch: byte-bounded, LRU,
    for private browsing, temporary storage, no cache directory, and
    the tests. The SQLite cache goes, and `rusqlite`, `sea-query` and
    `quick_cache` leave `components/net`.

Fixes over the cache of the `http-cache-v2` branch, which this replaces:
a 304 no longer collapses repeated stored fields (a two-line CSP lost a
line) nor freshens on a weak or mismatching strong validator, `Age`
takes `Date` and the request time into account, the RFC 850 and asctime
date formats are understood, and `Vary` compares all field lines. That
branch also never stored a compressed response but stored a gzip body
cut short under clean framing, let a late 304 freshen or remove the
entry that had replaced its own, and made a fetch wait for the whole
body of another fetch's response even when it could not use it, and
wrote the URL's credentials into every entry: the key now leaves them
and the fragment out, and a stored response is served with the
request's URL. An
invalidation through `Location` or `Content-Location` reaches only URIs
of the target's origin (RFC 9111 4.4). Of several matching stored
responses the most recent is used (RFC 9111 4). When a 304 is about
another response than the stored one, the request is made again without
preconditions, and that response is stored.

Prefs: `network_http_cache_size` (an entry count) and
`network_http_disk_cache` (a path) are replaced by
`network_http_memory_cache_size` and `network_http_cache_max_entry_size`,
in bytes; `network_http_disk_cache_size` gains 0 = automatic.

`apply_algorithm_to_response` returned through `unreachable!()` when
the body was not `Done`, which a null body status makes it, and a
streamed body would reach reliably. It now returns a digest that cannot
match, so the fetch fails as `response-null-body.any.js` expects.

`preload/prefetch-document.html`: "different-site document prefetch with
'as=document' should not be consumed" now also fails at times, like its
two siblings. Servo has no HTTP cache partition (servo#33616), so the fresh
response of a cross-site prefetch answers the later navigation, unless
the navigation starts before the prefetch's response headers arrive and
goes to the network. With `network_http_cache_disabled=true` the subtest
passes and the "same origin ... should be consumed" sibling fails
instead.

Fork note: supersedes patches 79 and 80 (their cache code goes; their
fetch tests stay), and moves the cache side of patch 92 into
`http_cache::inflight`. 79 and 80 stayed on the stack at the 2026-10-22
sync: patch 92 builds on both (it calls 79's `may_store_media_response`
and sets 80's abort flag), so dropping them means reworking 92. Uses
`http-cache-rules` 0.1.0 from crates.io.

Testing: tests/http_cache.rs covers storability, Vary, freshness,
stale-while-revalidate with and without a client, partial entries and
ranges (with the five range tests of the `http-cache-range` branch),
the encoded body, the media storage rule, same-origin invalidation and
the most recent variant. tests/fetch.rs covers a 304 with another strong
validator, a 304 resetting Age, and a 304 with no-store.
tests/http_loader.rs covers a compressed response answered from the
cache, a compressed body cut short, and fetches that do not wait for the
headers of another fetch, a response that needs validation, a variant
of another request or a body too large to store, and that stop waiting
when cancelled or after a while; tests/http_cache.rs also a URL with
credentials and a fragment; tests/cache_store.rs an id reused by another
entry. The fetch tests of
patches 79, 80 and 92 are adapted to entries that appear on commit.

Validation: `./mach test-unit -p servo-net`: 435 tests pass. Negative controls, each run once: without the origin check, the most-recent selection, the 304 exception in `tee` or the suspended-producer wait, `test_invalidation_only_reaches_the_same_origin`, `test_the_most_recent_matching_response_is_used`, `test_a_304_for_another_response_makes_the_request_again_without_preconditions` and `test_fetch_waiting_for_a_suspended_response_uses_the_network` fail. Without the commit on the decoded end, the stamps and the waiting rule, `test_compressed_response_is_answered_from_cache`, `test_compressed_response_cut_short_is_not_stored`, `a_reused_id_is_not_touched_on_behalf_of_its_old_entry` (memory and disk store) and `test_fetch_does_not_wait_for_a_response_that_needs_validation` fail; with waiters waiting from the writer's registration on, `test_fetch_does_not_wait_for_the_headers_of_another_fetch` fails as well, and with waiters waiting for any response the validation one does. With patches 121 to 123: `./mach test-unit --profile checked-release` (1212 tests) and `--doc` pass; `./mach clippy --locked -- -- --deny warnings`, the crown `checked-release` build and the OHOS `checked-release` build with `RUSTFLAGS="-D warnings"` are clean, as is `./mach test-tidy`. WPT, `checked-release`, 8 processes, fetch/http-cache, fetch/range, fetch/stale-while-revalidate, fetch/api, cors, xhr, preload, html/semantics/embedded-content/media-elements and html/semantics/scripting-1, 2140 tests: 2134 as expected, and "Response with Cache-Control: max-age=2592000, public and Pragma: no-cache should not be cached" now passes (expectation removed; the crate's deviation D-2). The other six behave the same alone on ohos-main 091e100215c: src_object_blob.html times out 3 of 8 runs (2 of 8 there), load-removes-queued-error-event.html crashes 5 of 8 (4 of 8 there), media_fragment_seek.html fails and autoplay-default-permissions-policy.https.sub.html passes every time on both, and seek-to-max-value.htm and track-remove-by-setting-innerHTML.html pass 3 of 3 on both. Full WPT, `checked-release`, 12 processes, on the build before the waiting rule was fixed: 58273 of 58348 tests as expected. The other 75 were run again serially, those still unexpected on ohos-main 091e100215c too, and the 12 that differed 3 times alone on both: async_003.htm, async_004.htm and async_005.htm failed every time on the branch only (their script's headers are delayed, and a second fetch of it waited for them), and pass 3 of 3 with the fix; the other 9 behave the same on both. The focused set without scripting-1 on QuickJS (`--js-engine quickjs`), before the review fixes: 1540 of 1545 as expected, three of the same media tests, and two track-element timeouts that pass 3 of 3 alone on both builds. On ohos-main deaca97 with `http-cache-rules` 0.1.0 from crates.io (the same files as the path dependency tested above): `./mach test-unit -p servo-net` passes, 435 tests here and 472 with patch 121, and the CI-parity checks above pass again at patch 123, except `indexeddb::engines::sqlite::tests::test_async_operations` of servo-storage, which timed out once and passes 3 of 3 alone. `test_response_cache_status_is_validated` failed 5 of 320 runs, 32 at a time, while the commit of the first response was not waited for, and 0 of 960 after. WPT fetch/http-cache, fetch/range, fetch/stale-while-revalidate, preload and html/semantics/scripting-1, 756 tests: as expected but for execution-timing/077.html, which passes 3 of 3 alone here and fails 1 of 3 alone on ohos-main 091e100215c, and the prefetch-document subtest above, which passed 2 of 3 runs alone; its expectation now allows both. Review fixes (the wait ends on cancellation, does not start for another variant or a body too large to store, and times out; the key leaves out the credentials and fragment of the URL): 440 tests pass here, and 481 with patch 121. Negative controls, each run once: without the cancellation of the wait, `test_a_waiting_fetch_stops_waiting_when_it_is_cancelled` fails; without the `Vary` check, the cap in `TeeBody`, the timeout or the password left out of the key, `test_fetch_does_not_wait_for_a_response_that_varies_from_its_request`, `test_fetch_does_not_wait_for_a_response_too_large_to_store`, `test_a_waiting_fetch_goes_to_the_network_after_a_while` and `test_url_credentials_and_fragment_are_not_part_of_the_key` fail. At patch 123 the CI-parity checks pass again (`test-unit --profile checked-release`: 1221 tests), and WPT fetch/http-cache, fetch/range, fetch/stale-while-revalidate, fetch/api, preload, html/semantics/scripting-1 and html/semantics/embedded-content/media-elements, 1679 tests, run as expected but for four of the media tests above and seek-to-currentTime.html, which passes 3 of 3 alone on both builds. A first version also returned a network error from step 9 of HTTP-network-or-cache fetch for any fetch cancelled before it reached the network. PR CI caught that: requests sent while a document unloads were dropped, and fetch/fetch-later/send-on-discard/send-multiple, both sandbox-top-navigation-child-delivered tests, navigation-timing/nested-unload-timing and navigation-timing/prefetch-transfer-size-executor failed in both attempts of that CI run and in a serial local run. Without it they run as expected in 2 of 2 serial local runs; of the other stable unexpected results of that CI run, window-resize-event.html times out alone on ohos-main 091e100215c too, and test_resource_timing and media-loading-pseudo-classes-in-has.sub.html behave the same alone on both builds and are flaky upstream.
AI-assisted: Yes (agent session; the agent ported the storage half of the http-cache-v2 branch, wrote the glue over http-cache-rules and the merge with patches 79, 80 and 92, and wrote and ran the tests)
AI-assisted: Yes (agent session; 2026-10-22 sync -- conflict resolution: `http_cache.rs` deleted as before, which drops upstream's edits to it (servo#48927 most recent matching response and replacement of matching responses, servo#48842); this cache uses the most recent matching response already and makes the request again when a 304 is about another response. The old cache steps of HTTP-network-or-cache fetch and `block_for_cache_ready` go as before, with upstream's edits to them (servo#48927, servo#48867); `obtain_response` keeps upstream's new `FetchParams` signature (servo#49040) and returns the body below the decoder as before; test imports merged. `./mach test-unit -p servo-net` at this commit: 440 tests pass)
AI-assisted: Yes (agent session; 2026-10-22 sync -- the fork note says why patches 79 and 80 were not dropped)
AI-assisted: Yes (agent session; 2026-10-29 sync -- test compile fix: `request_with_client()` sets the new `RequestClient::network_partition_key` (servo#49252))
AI-assisted: Yes (agent session; 2026-11-09 sync -- components/net/http_cache.rs stays deleted; upstream's cleanup of it (servo#49434) has no counterpart in the new cache)
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Nov 9, 2026
A response body was held twice: as a state in a shared
`Arc<Mutex<ResponseBody>>`, and as a `done_chan` that every fetch function
passed along and had to reset whenever it replaced the response. Keeping
the two paired by convention went wrong in several ways:

- A fetch cancelled right after its headers returned a network error while
  `done_chan` still held a sender, so `wait_for_response` waited forever
  and the fetch never ended.
- A response replaced by a network error, after a failed CORS check or a
  CORP, CSP, nosniff, MIME type or mixed content block, kept its channel,
  so its body was still delivered to the consumer.
- Step 22 of main fetch (null body status, HEAD) blanked the state, but not
  the chunks already queued in the channel.
- A navigation through a `web+` protocol handler returned a response whose
  body an inner fetch had already handed to `DiscardFetch`.
- Producers had to know whether a consumer inside net (subresource
  integrity, preloads) needed the whole body, and `file:` and `blob:`
  bodies were kept whole in net in any case. An in-memory `blob:` body was
  never kept, so its integrity check always failed.

`ResponseBody` is now `Null`, `Bytes`, or a `Stream` of the body stream
type added in the previous patch, and the response owns it.
`wait_for_response` is the one place that hands a body over, and it keeps
the body as `Bytes` for preloads and for subresource integrity. A body whose
producer goes away without finishing ends as failed instead of hanging. The
body of a redirect, or of a response replaced after a 401 or 407, is
discarded instead of being queued while the next request runs; readers of
files and of the cache stop when nobody reads their body.
`ProtocolHandler::load` loses its `done_chan` parameter, and
`servo::protocol_handler` exports the body stream. `Response` is no longer
`Clone`: `try_clone` copies a response whose body is not a stream. The page
content protocol handler runs main fetch recursively, so the outer fetch
hands the handler URL's body over.

Otherwise behaviour does not change: a body cut short by the connection
still ends as aborted with a successful end of file, a discarded network
body is still read to its end so that its connection can be reused and the
cache can store it, and subresource integrity still forwards the body
before checking it. One exception: a preload whose body is cut short is
now kept without a body instead of with the bytes that arrived; both are
wrong, and a later patch makes it a network error.

Validation: `./mach test-unit -p servo-net`: 490 tests pass, 7 of them new. On ohos-main 67173a4, `test_fetch_cancelled_while_its_headers_are_held_ends` fails with "the fetch did not end", `test_body_of_a_response_that_fails_the_cors_check_is_not_delivered` with all 19 body bytes delivered, `test_body_of_a_response_blocked_by_nosniff_is_not_delivered` with all 12, and `test_navigation_through_a_page_content_protocol_handler_delivers_the_body` with none. Negative controls on this patch: without applying step 22's null body, `test_body_of_a_null_body_status_is_not_delivered` gets 7 bytes; with a test producer that keeps its sender alive, `test_body_whose_producer_stops_without_finishing_ends_the_fetch` does not end; without keeping preloaded bodies, `test_fetch_of_a_preload_keeps_its_body` finds no body. `./mach check`, `./mach clippy --locked -- -- --deny warnings` and `./mach test-tidy` pass. 2026-10-29 sync (CORS cache now in the fetch context): `./mach test-unit --profile checked-release -p servo-net` at this commit, 490 tests pass.
AI-assisted: Yes (agent session; the agent wrote this patch and its tests following docs/fetch-body-stream-plan-2026-10-22.md in the workspace, found the cancellation hang, the delivery of blocked bodies and the protocol handler regression, and applied an independent review's findings)
AI-assisted: Yes (agent session; 2026-10-29 sync -- conflict resolution, no semantic change: upstream moved the CORS preflight cache into the fetch context (servo#49055, servo#49252), so `main_fetch`, `scheme_fetch`, `http_fetch` and `http_redirect_fetch` lose both the cache and `done_chan`, and the page content protocol handler's inner main fetch no longer passes a fresh cache; the preflight fetch keeps upstream's devtools reporting (servo#49151); `to_filtered` takes the headers out of the internal response before its body-less copy, as upstream now does (servo#49313))
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Nov 10, 2026
The HTTP cache kept every stored body as a `Vec<u8>` in the net process,
shared with the response handed to the consumer, so net also kept the
decoded body of every response until its fetch ended. Its RFC 9111
rules were hand-written for RFC 7234.

The rules now come from the `http-cache-rules` crate: storability, the
stored and updated header fields, freshness (with `max-age`, `Expires`,
the heuristic, `Age` and `Date`), `Vary`, `stale-while-revalidate`,
`immutable`, the request directives, the validation request and the
merge of a 304. The crate decides and stores nothing; its requirements
are traced to the RFC text and tested, model checked and fuzzed in its
own repository. `http_cache::policy` configures it as a private cache
that stores 206 responses and their bodies encoded.

Servo keeps what belongs to the fetch layer: the cache modes, background
revalidation (only for requests with a client), invalidation after
unsafe methods, ranges, and its own refusals on top of the crate: `Vary:
*`, entries over the store's size limit, 206 without `Content-Range`,
and the storage rule for audio and video of patch 79.

Storage moves behind `CacheStore`, which streams bodies in and out:

  * `TeeBody` copies each frame into the store below the content
    decoder, so the stored body is what came off the wire, and the copy
    is a reference count, not a second allocation. The store's bounded
    queue back-pressures the network.
  * A hit streams the entry through the decoder in chunks.
  * `ResponseBody::Streamed` marks a body delivered to the consumer and
    kept nowhere. Only subresource integrity and preloads still keep the
    whole decoded body (`retains_whole_body`), so net no longer keeps
    media bodies, which patch 79 had to arrange separately.
  * An entry is visible only once its decoded body ended cleanly, so a
    failed, cancelled or truncated body never becomes an entry, which
    patch 80 had to arrange separately. The fetch commits it through a
    `TeeCommit`, not `TeeBody` at the end of the network body: the
    decoder stops reading at the end of a gzip or brotli stream.
  * Every entry carries a random stamp, and the store opens, updates
    and removes an entry only for the stamp it was looked up with, since
    a later entry of the key may reuse its id.
  * `http_cache::inflight` lets one fetch write a key. Once its headers
    show a fresh response, others wait for it and read the committed
    entry, or go to the network if it aborts or, as patch 92 requires,
    while it is suspended. Before that, or if the response needs
    validation, they go to the network as with the old cache, so a slow
    or long-polled response holds up no other fetch. Once the whole body
    has arrived, they wait for any response while the store commits it,
    so a fetch right after another one finds its entry. A fetch does
    not wait for a response that varies on a field in which its own
    request differs, or whose body outgrows what the store accepts. It
    stops waiting when it is cancelled, and goes on from there like any
    cancelled fetch, and it waits 5 s at most.
  * `MemoryStore` is the only store in this patch: byte-bounded, LRU,
    for private browsing, temporary storage, no cache directory, and
    the tests. The SQLite cache goes, and `rusqlite`, `sea-query` and
    `quick_cache` leave `components/net`.

Fixes over the cache of the `http-cache-v2` branch, which this replaces:
a 304 no longer collapses repeated stored fields (a two-line CSP lost a
line) nor freshens on a weak or mismatching strong validator, `Age`
takes `Date` and the request time into account, the RFC 850 and asctime
date formats are understood, and `Vary` compares all field lines. That
branch also never stored a compressed response but stored a gzip body
cut short under clean framing, let a late 304 freshen or remove the
entry that had replaced its own, and made a fetch wait for the whole
body of another fetch's response even when it could not use it, and
wrote the URL's credentials into every entry: the key now leaves them
and the fragment out, and a stored response is served with the
request's URL. An
invalidation through `Location` or `Content-Location` reaches only URIs
of the target's origin (RFC 9111 4.4). Of several matching stored
responses the most recent is used (RFC 9111 4). When a 304 is about
another response than the stored one, the request is made again without
preconditions, and that response is stored.

Prefs: `network_http_cache_size` (an entry count) and
`network_http_disk_cache` (a path) are replaced by
`network_http_memory_cache_size` and `network_http_cache_max_entry_size`,
in bytes; `network_http_disk_cache_size` gains 0 = automatic.

`apply_algorithm_to_response` returned through `unreachable!()` when
the body was not `Done`, which a null body status makes it, and a
streamed body would reach reliably. It now returns a digest that cannot
match, so the fetch fails as `response-null-body.any.js` expects.

`preload/prefetch-document.html`: "different-site document prefetch with
'as=document' should not be consumed" now also fails at times, like its
two siblings. Servo has no HTTP cache partition (servo#33616), so the fresh
response of a cross-site prefetch answers the later navigation, unless
the navigation starts before the prefetch's response headers arrive and
goes to the network. With `network_http_cache_disabled=true` the subtest
passes and the "same origin ... should be consumed" sibling fails
instead.

Fork note: supersedes patches 79 and 80 (their cache code goes; their
fetch tests stay), and moves the cache side of patch 92 into
`http_cache::inflight`. 79 and 80 stayed on the stack at the 2026-10-22
sync: patch 92 builds on both (it calls 79's `may_store_media_response`
and sets 80's abort flag), so dropping them means reworking 92. Uses
`http-cache-rules` 0.1.0 from crates.io.

Testing: tests/http_cache.rs covers storability, Vary, freshness,
stale-while-revalidate with and without a client, partial entries and
ranges (with the five range tests of the `http-cache-range` branch),
the encoded body, the media storage rule, same-origin invalidation and
the most recent variant. tests/fetch.rs covers a 304 with another strong
validator, a 304 resetting Age, and a 304 with no-store.
tests/http_loader.rs covers a compressed response answered from the
cache, a compressed body cut short, and fetches that do not wait for the
headers of another fetch, a response that needs validation, a variant
of another request or a body too large to store, and that stop waiting
when cancelled or after a while; tests/http_cache.rs also a URL with
credentials and a fragment; tests/cache_store.rs an id reused by another
entry. The fetch tests of
patches 79, 80 and 92 are adapted to entries that appear on commit.

Validation: `./mach test-unit -p servo-net`: 435 tests pass. Negative controls, each run once: without the origin check, the most-recent selection, the 304 exception in `tee` or the suspended-producer wait, `test_invalidation_only_reaches_the_same_origin`, `test_the_most_recent_matching_response_is_used`, `test_a_304_for_another_response_makes_the_request_again_without_preconditions` and `test_fetch_waiting_for_a_suspended_response_uses_the_network` fail. Without the commit on the decoded end, the stamps and the waiting rule, `test_compressed_response_is_answered_from_cache`, `test_compressed_response_cut_short_is_not_stored`, `a_reused_id_is_not_touched_on_behalf_of_its_old_entry` (memory and disk store) and `test_fetch_does_not_wait_for_a_response_that_needs_validation` fail; with waiters waiting from the writer's registration on, `test_fetch_does_not_wait_for_the_headers_of_another_fetch` fails as well, and with waiters waiting for any response the validation one does. With patches 121 to 123: `./mach test-unit --profile checked-release` (1212 tests) and `--doc` pass; `./mach clippy --locked -- -- --deny warnings`, the crown `checked-release` build and the OHOS `checked-release` build with `RUSTFLAGS="-D warnings"` are clean, as is `./mach test-tidy`. WPT, `checked-release`, 8 processes, fetch/http-cache, fetch/range, fetch/stale-while-revalidate, fetch/api, cors, xhr, preload, html/semantics/embedded-content/media-elements and html/semantics/scripting-1, 2140 tests: 2134 as expected, and "Response with Cache-Control: max-age=2592000, public and Pragma: no-cache should not be cached" now passes (expectation removed; the crate's deviation D-2). The other six behave the same alone on ohos-main 091e100215c: src_object_blob.html times out 3 of 8 runs (2 of 8 there), load-removes-queued-error-event.html crashes 5 of 8 (4 of 8 there), media_fragment_seek.html fails and autoplay-default-permissions-policy.https.sub.html passes every time on both, and seek-to-max-value.htm and track-remove-by-setting-innerHTML.html pass 3 of 3 on both. Full WPT, `checked-release`, 12 processes, on the build before the waiting rule was fixed: 58273 of 58348 tests as expected. The other 75 were run again serially, those still unexpected on ohos-main 091e100215c too, and the 12 that differed 3 times alone on both: async_003.htm, async_004.htm and async_005.htm failed every time on the branch only (their script's headers are delayed, and a second fetch of it waited for them), and pass 3 of 3 with the fix; the other 9 behave the same on both. The focused set without scripting-1 on QuickJS (`--js-engine quickjs`), before the review fixes: 1540 of 1545 as expected, three of the same media tests, and two track-element timeouts that pass 3 of 3 alone on both builds. On ohos-main deaca97 with `http-cache-rules` 0.1.0 from crates.io (the same files as the path dependency tested above): `./mach test-unit -p servo-net` passes, 435 tests here and 472 with patch 121, and the CI-parity checks above pass again at patch 123, except `indexeddb::engines::sqlite::tests::test_async_operations` of servo-storage, which timed out once and passes 3 of 3 alone. `test_response_cache_status_is_validated` failed 5 of 320 runs, 32 at a time, while the commit of the first response was not waited for, and 0 of 960 after. WPT fetch/http-cache, fetch/range, fetch/stale-while-revalidate, preload and html/semantics/scripting-1, 756 tests: as expected but for execution-timing/077.html, which passes 3 of 3 alone here and fails 1 of 3 alone on ohos-main 091e100215c, and the prefetch-document subtest above, which passed 2 of 3 runs alone; its expectation now allows both. Review fixes (the wait ends on cancellation, does not start for another variant or a body too large to store, and times out; the key leaves out the credentials and fragment of the URL): 440 tests pass here, and 481 with patch 121. Negative controls, each run once: without the cancellation of the wait, `test_a_waiting_fetch_stops_waiting_when_it_is_cancelled` fails; without the `Vary` check, the cap in `TeeBody`, the timeout or the password left out of the key, `test_fetch_does_not_wait_for_a_response_that_varies_from_its_request`, `test_fetch_does_not_wait_for_a_response_too_large_to_store`, `test_a_waiting_fetch_goes_to_the_network_after_a_while` and `test_url_credentials_and_fragment_are_not_part_of_the_key` fail. At patch 123 the CI-parity checks pass again (`test-unit --profile checked-release`: 1221 tests), and WPT fetch/http-cache, fetch/range, fetch/stale-while-revalidate, fetch/api, preload, html/semantics/scripting-1 and html/semantics/embedded-content/media-elements, 1679 tests, run as expected but for four of the media tests above and seek-to-currentTime.html, which passes 3 of 3 alone on both builds. A first version also returned a network error from step 9 of HTTP-network-or-cache fetch for any fetch cancelled before it reached the network. PR CI caught that: requests sent while a document unloads were dropped, and fetch/fetch-later/send-on-discard/send-multiple, both sandbox-top-navigation-child-delivered tests, navigation-timing/nested-unload-timing and navigation-timing/prefetch-transfer-size-executor failed in both attempts of that CI run and in a serial local run. Without it they run as expected in 2 of 2 serial local runs; of the other stable unexpected results of that CI run, window-resize-event.html times out alone on ohos-main 091e100215c too, and test_resource_timing and media-loading-pseudo-classes-in-has.sub.html behave the same alone on both builds and are flaky upstream.
AI-assisted: Yes (agent session; the agent ported the storage half of the http-cache-v2 branch, wrote the glue over http-cache-rules and the merge with patches 79, 80 and 92, and wrote and ran the tests)
AI-assisted: Yes (agent session; 2026-10-22 sync -- conflict resolution: `http_cache.rs` deleted as before, which drops upstream's edits to it (servo#48927 most recent matching response and replacement of matching responses, servo#48842); this cache uses the most recent matching response already and makes the request again when a 304 is about another response. The old cache steps of HTTP-network-or-cache fetch and `block_for_cache_ready` go as before, with upstream's edits to them (servo#48927, servo#48867); `obtain_response` keeps upstream's new `FetchParams` signature (servo#49040) and returns the body below the decoder as before; test imports merged. `./mach test-unit -p servo-net` at this commit: 440 tests pass)
AI-assisted: Yes (agent session; 2026-10-22 sync -- the fork note says why patches 79 and 80 were not dropped)
AI-assisted: Yes (agent session; 2026-10-29 sync -- test compile fix: `request_with_client()` sets the new `RequestClient::network_partition_key` (servo#49252))
AI-assisted: Yes (agent session; 2026-11-09 sync -- components/net/http_cache.rs stays deleted; upstream's cleanup of it (servo#49434) has no counterpart in the new cache)
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Nov 10, 2026
A response body was held twice: as a state in a shared
`Arc<Mutex<ResponseBody>>`, and as a `done_chan` that every fetch function
passed along and had to reset whenever it replaced the response. Keeping
the two paired by convention went wrong in several ways:

- A fetch cancelled right after its headers returned a network error while
  `done_chan` still held a sender, so `wait_for_response` waited forever
  and the fetch never ended.
- A response replaced by a network error, after a failed CORS check or a
  CORP, CSP, nosniff, MIME type or mixed content block, kept its channel,
  so its body was still delivered to the consumer.
- Step 22 of main fetch (null body status, HEAD) blanked the state, but not
  the chunks already queued in the channel.
- A navigation through a `web+` protocol handler returned a response whose
  body an inner fetch had already handed to `DiscardFetch`.
- Producers had to know whether a consumer inside net (subresource
  integrity, preloads) needed the whole body, and `file:` and `blob:`
  bodies were kept whole in net in any case. An in-memory `blob:` body was
  never kept, so its integrity check always failed.

`ResponseBody` is now `Null`, `Bytes`, or a `Stream` of the body stream
type added in the previous patch, and the response owns it.
`wait_for_response` is the one place that hands a body over, and it keeps
the body as `Bytes` for preloads and for subresource integrity. A body whose
producer goes away without finishing ends as failed instead of hanging. The
body of a redirect, or of a response replaced after a 401 or 407, is
discarded instead of being queued while the next request runs; readers of
files and of the cache stop when nobody reads their body.
`ProtocolHandler::load` loses its `done_chan` parameter, and
`servo::protocol_handler` exports the body stream. `Response` is no longer
`Clone`: `try_clone` copies a response whose body is not a stream. The page
content protocol handler runs main fetch recursively, so the outer fetch
hands the handler URL's body over.

Otherwise behaviour does not change: a body cut short by the connection
still ends as aborted with a successful end of file, a discarded network
body is still read to its end so that its connection can be reused and the
cache can store it, and subresource integrity still forwards the body
before checking it. One exception: a preload whose body is cut short is
now kept without a body instead of with the bytes that arrived; both are
wrong, and a later patch makes it a network error.

Validation: `./mach test-unit -p servo-net`: 490 tests pass, 7 of them new. On ohos-main 67173a4, `test_fetch_cancelled_while_its_headers_are_held_ends` fails with "the fetch did not end", `test_body_of_a_response_that_fails_the_cors_check_is_not_delivered` with all 19 body bytes delivered, `test_body_of_a_response_blocked_by_nosniff_is_not_delivered` with all 12, and `test_navigation_through_a_page_content_protocol_handler_delivers_the_body` with none. Negative controls on this patch: without applying step 22's null body, `test_body_of_a_null_body_status_is_not_delivered` gets 7 bytes; with a test producer that keeps its sender alive, `test_body_whose_producer_stops_without_finishing_ends_the_fetch` does not end; without keeping preloaded bodies, `test_fetch_of_a_preload_keeps_its_body` finds no body. `./mach check`, `./mach clippy --locked -- -- --deny warnings` and `./mach test-tidy` pass. 2026-10-29 sync (CORS cache now in the fetch context): `./mach test-unit --profile checked-release -p servo-net` at this commit, 490 tests pass.
AI-assisted: Yes (agent session; the agent wrote this patch and its tests following docs/fetch-body-stream-plan-2026-10-22.md in the workspace, found the cancellation hang, the delivery of blocked bodies and the protocol handler regression, and applied an independent review's findings)
AI-assisted: Yes (agent session; 2026-10-29 sync -- conflict resolution, no semantic change: upstream moved the CORS preflight cache into the fetch context (servo#49055, servo#49252), so `main_fetch`, `scheme_fetch`, `http_fetch` and `http_redirect_fetch` lose both the cache and `done_chan`, and the page content protocol handler's inner main fetch no longer passes a fresh cache; the preflight fetch keeps upstream's devtools reporting (servo#49151); `to_filtered` takes the headers out of the internal response before its body-less copy, as upstream now does (servo#49313))
Signed-off-by: Jonathan Schwender <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-awaiting-review There is new code that needs to be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

net: Partition CORS preflight cache by network partition key

4 participants