Skip to content

script/dom: Implement basic MathML DOM interfaces and bindings - #48631

Merged
TimvdLippe merged 1 commit into
servo:mainfrom
tannal:pr-mathml-dom
Oct 23, 2026
Merged

TimvdLippe merged 1 commit into
servo:mainfrom
tannal:pr-mathml-dom

Conversation

@tannal

@tannal tannal commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Add a new pref, when enabled create MathMLElement for elements in the MathML namespace.

Renamed HTMLOrSVGElement to HTMLOrSVGOrMathMLElement.

Testing: IDL reflection tests and its config updated.

Fixes:
Part of #2165 and #49078, a little :-)

@tannal
tannal requested a review from gterzian as a code owner October 5, 2026 04:24
@servo-highfive servo-highfive added the S-awaiting-review There is new code that needs to be reviewed. label Oct 5, 2026
@TimvdLippe TimvdLippe added the T-linux-wpt Do a try run of the WPT label Oct 5, 2026
@github-actions github-actions Bot removed the T-linux-wpt Do a try run of the WPT label Oct 5, 2026
@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown

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

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown

⚠️ Try run (#37277892852) failed!

@servo-highfive servo-highfive added the S-needs-rebase There are merge conflict errors. label Oct 15, 2026
@servo-highfive servo-highfive removed the S-needs-rebase There are merge conflict errors. label Oct 15, 2026
@tannal

tannal commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

@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.

Only a couple of nits regarding code style and comments. The rest LGTM, thank you for starting the implementation!

Comment thread components/config/prefs.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 16, 2026
@TimvdLippe

Copy link
Copy Markdown
Contributor

Oh and your last commit wasn't signed off. Do make sure all commits are signed off and DCO is green.

@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 20, 2026
@tannal

tannal commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

Removed redundant parse_plain_attribute.

Introduced parse_mathml_attribute_matching to enforce type checking for mathsize.
We should only accept <length-percentage> values but ignore values like small, medium etc for mathsize.

Now we will pass tests like mathml/relations/css-styling/mathsize-attribute-css-keywords.html.

@TimvdLippe TimvdLippe added the T-linux-wpt Do a try run of the WPT label Oct 20, 2026
@github-actions github-actions Bot removed the T-linux-wpt Do a try run of the WPT label Oct 20, 2026
@github-actions

Copy link
Copy Markdown

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

@github-actions

Copy link
Copy Markdown

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

Flaky unexpected result (16)
  • CRASH [expected ERROR] /IndexedDB/idbcursor-update-exception-order.any.serviceworker.html
  • TIMEOUT [expected OK] /content-security-policy/navigation/to-javascript-parent-initiated-parent-csp.html (#46400)
    • TIMEOUT [expected PASS] subtest: Should not have executed the javascript url for area[target=iframe].href

      Test timed out
      

    • NOTRUN [expected PASS] subtest: Should not have executed the javascript url for area[target=otherTab].href
    • NOTRUN [expected PASS] subtest: Should not have executed the javascript url for a[target=otherTab].href
    • NOTRUN [expected PASS] subtest: Should not have executed the javascript url for a[target=iframe].href
  • FAIL [expected PASS] /css/css-backgrounds/background-size-042.html
  • OK /css/css-fonts/variations/at-font-face-font-matching.html (#20684)
    • FAIL [expected PASS] subtest: Matching font-weight: '501' should prefer '503 520' over '500'

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

    • FAIL [expected PASS] subtest: Matching font-style: 'italic' should prefer 'normal' over 'oblique -60deg -30deg'

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

    • FAIL [expected PASS] subtest: Matching font-style: 'oblique 21deg' should prefer 'oblique 20deg' over 'oblique 10deg'

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

  • OK /css/css-overflow/scrollable-overflow-padding-input.html (#47257)
    • FAIL [expected PASS] subtest: .test 1

      assert_equals: 
      &lt;input type="text" value="X" class="test" data-expected-scroll-height="120"&gt;
      scrollHeight expected 120 but got 132
      

    • FAIL [expected PASS] subtest: .test 2

      assert_equals: 
      &lt;input type="number" value="1" class="test" data-expected-scroll-height="120"&gt;
      scrollHeight expected 120 but got 132
      

    • FAIL [expected PASS] subtest: .test 4

      assert_equals: 
      &lt;input type="search" class="test" value="X" data-expected-scroll-height="120"&gt;
      scrollHeight expected 120 but got 133
      

    • FAIL [expected PASS] subtest: .test 5

      assert_equals: 
      &lt;textarea class="test" data-expected-scroll-height="125"&gt;X&lt;/textarea&gt;
      scrollHeight expected 125 but got 142
      

  • OK /css/css-text-decor/parsing/text-decoration-inset-computed.html (#47617)
    • FAIL [expected PASS] subtest: Property text-decoration-inset value '0'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value '0px 0px'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value '0.5em'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value '-1em'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value '-1ch -1ch'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value '1px 2px'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value '1ch -1ch'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value 'calc(1em / 4) calc(-1ch)'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value 'auto'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • FAIL [expected PASS] subtest: Property text-decoration-inset value '10%'

      assert_true: text-decoration-inset doesn't seem to be supported in the computed style expected true got false
      

    • And 5 more unexpected results...
  • OK /dom/nodes/moveBefore/iframe-document-preserve.window.html (#43152)
    • FAIL [expected PASS] subtest: moveBefore(): cross-origin iframe is preserved: remove self via innerHTML

      assert_equals: iframe does not fire a second load event expected 1 but got 0
      

  • OK /html/browsers/browsing-the-web/navigating-across-documents/navigation-unload-same-origin-fragment.html (#20768)
    • PASS [expected FAIL] subtest: Tests that a fragment navigation in the unload handler will not block the initial navigation
  • TIMEOUT /html/browsers/history/the-history-interface/001.html (#12580)
    • PASS [expected FAIL] subtest: traversing history must also traverse hash changes
  • CRASH [expected OK] /html/browsers/history/the-location-interface/assign-replace-from-iframe.html (#47679)
  • CRASH [expected ERROR] /html/semantics/forms/the-select-element/customizable-select/select-appearance-button-after-span.html
  • TIMEOUT [expected OK] /html/user-activation/navigation-state-reset-sameorigin.html (#45151)
    • TIMEOUT [expected FAIL] subtest: Post-navigation state reset.

      Test timed out
      

  • OK /html/webappapis/dynamic-markup-insertion/document-write/iframe_005.html (#43671)
    • PASS [expected FAIL] subtest: document.write external script into iframe write back into parent
  • ERROR [expected TIMEOUT] /performance-timeline/not-restored-reasons/abort-block-bfcache.window.html (#42802)
  • OK /upgrade-insecure-requests/gen/sharedworker-classic-data.meta/upgrade/websocket.https.html
    • FAIL [expected PASS] subtest: Upgrade-Insecure-Requests: Expects allowed for websocket to cross-ws-downgrade origin and no-redirect redirection from https context.

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

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

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

  • OK /webxr/xrSession_features_deviceSupport.https.html (#24357)
    • FAIL [expected PASS] subtest: Immersive XRSession requests with no supported device should reject

      assert_unreached: Should have rejected: undefined Reached unreachable code
      

Stable unexpected results that are known to be intermittent (4)
  • TIMEOUT [expected OK] /html/browsers/browsing-the-web/navigating-across-documents/cross-origin-top-navigation-with-user-activation-in-parent.window.html (#48205)
    • TIMEOUT [expected FAIL] subtest: Cross-origin top navigation is blocked without user activation, even if the parent has user activation

      Test timed out
      

  • TIMEOUT [expected OK] /html/semantics/embedded-content/media-elements/autoplay-allowed-by-permissions-policy.https.sub.html (#46803)
    • TIMEOUT [expected PASS] subtest: Permissions-Policy header: autoplay * allows the top-level document.

      Test timed out
      

    • TIMEOUT [expected PASS] subtest: Permissions-Policy header: autoplay * allows same-origin iframes.

      Test timed out
      

  • OK [expected CRASH] /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 /pointerevents/pointerevent_pointercapture_in_frame.html?pen (#45536)
    • FAIL [expected PASS] subtest: Test penpointer capture in same-origin frame: Pointer down at inner frame and set pointer capture.

      assert_true: Timed out waiting for lostpointercapture expected true got false
      

    • FAIL [expected PASS] subtest: Test penpointer capture in same-origin frame: Pointer down at inner frame and set pointer capture to outer frame should not capture.

      assert_array_equals: Received events: innerFrame received pointerdown,innerFrame received pointermove,innerFrame received pointerup,innerFrame received lostpointercapture lengths differ, expected array ["innerFrame received pointerdown", "innerFrame received pointermove", "innerFrame received pointerup"] length 3, got ["innerFrame received pointerdown", "innerFrame received pointermove", "innerFrame received pointerup", "innerFrame received lostpointercapture"] length 4
      

Stable unexpected results (3)
  • TIMEOUT [expected OK] /_mozilla/mozilla/window-resize-event.html
    • TIMEOUT [expected PASS] subtest: Popup onresize event fires after resizeTo

      Test timed out
      

  • OK /resource-timing/buffer-full-add-then-clear.html
    • PASS [expected FAIL] subtest: Test that if the buffer is cleared after entries were added to the secondary buffer, those entries make it into the primary one
  • OK /resource-timing/test_resource_timing.html
    • PASS [expected FAIL] subtest: PerformanceEntry has correct name, initiatorType, startTime, and duration (xmlhttprequest)

@github-actions

Copy link
Copy Markdown

⚠️ Try run (#39383668383) failed!

@TimvdLippe

Copy link
Copy Markdown
Contributor

You mention that this PR should now pass mathml/relations/css-styling/mathsize-attribute-css-keywords.html, yet the try run shows that the test is still failing. I don't mind it not fully passing just yet, but do let me know if we missed anything in this PR.

@eerii eerii left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks nice! :) I left few questions regarding the preference.

For the tests, as I mentioned via message, tests/wpt/include.ini has skip: true in the toplevel, so each wpt folder needs to be explicitly enabled. We don't seem to be running any MathML tests at the moment.

Comment thread components/config/prefs.rs Resolved
Comment thread components/script/dom/element/create.rs Resolved
@TimvdLippe

Copy link
Copy Markdown
Contributor

Ah of course, that's why CI doesn't see them. For that, please make a separate PR that adds the skip: false so that we have the baseline expectations. Example: #49030

@tannal

tannal commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor Author

I think idlharness.window.html should be enough for this patch so I enabled it only in this PR.
I will enable and rebaseline other tests like mathml/relations/css-styling/mathsize-attribute-css-keywords.html in a separate PR.

Now this patch should be ready to go after ci goes green without being blocked on other tests.
And thanks for all the feedback and help! :-)

@servo-highfive servo-highfive added the S-tests-failed The changes caused existing tests to fail. label Oct 23, 2026
@TimvdLippe
TimvdLippe added this pull request to the merge queue Oct 23, 2026
@servo-highfive servo-highfive added S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. and removed S-tests-failed The changes caused existing tests to fail. labels Oct 23, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 23, 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 23, 2026
@TimvdLippe
TimvdLippe added this pull request to the merge queue Oct 23, 2026
@servo-highfive servo-highfive added S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. and removed S-tests-failed The changes caused existing tests to fail. labels Oct 23, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 23, 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 23, 2026
@TimvdLippe

Copy link
Copy Markdown
Contributor

Loads of unrelated GitHub infrastructure failures on this PR. Another go at it...

@TimvdLippe
TimvdLippe added this pull request to the merge queue Oct 23, 2026
@servo-highfive servo-highfive added S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. and removed S-tests-failed The changes caused existing tests to fail. labels Oct 23, 2026
Merged via the queue into servo:main with commit 64545cb Oct 23, 2026
53 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 23, 2026
@servo-highfive

Copy link
Copy Markdown

Someone thinks this change could be added to the monthly blog post! To help with this, we need someone to answer the following questions: 😄

  1. Who is most impacted by this change: users, Servo developers, embedders, or some other group?
  2. What observable difference does this change make?
  3. What preferences (if any) need to be enabled to observe this difference?
  4. What (if any) specific URLs are affected?

If this change is part of a broader feature/project please make sure the PR description contains a Fixes: #12345 or Part of: #12345 issue reference.

Please add @servo-highfive monthly update answer when answering these questions so the bot notices your answer (or just quote this comment).

Thanks for helping us prepare the monthly blog post! ❤️

@Narfinger

Copy link
Copy Markdown
Contributor

@servo-highfive monthly update answer

  1. Embedders.
  2. Some basics of mathml should work.
  3. mathml_core_enabled
  4. I don't know.

@tannal

tannal commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

@servo-highfive monthly update answer

  1. https://fred-wang.github.io/MathFonts/mozilla_mathml_test/

With mathml_core_enabled I think you can get the MathMLElement object from the dom tree in js.

I guess you can't see any visual difference since we only have dom elements for mathml elements, they are now use what normal html/css algorithms to layout and paint.

We will get to the style/layout system soon!

jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Oct 30, 2026
…r is full

When its player has enough data, a media element cancels a fetch with
range support, to restart it with a Range request once the player needs
data again, and keeps queueing the data of a fetch without range
support, up to 32 MiB, before it cancels it and fetches the resource
from its start again. Every restart costs a request, on HTTP/1.1 a new
connection, and the bytes that were in flight.

Ask net to suspend a fetch that is read from the network instead, and
queue the data that was in flight. Net answers whether it suspended the
fetch. If it did, flow control holds back the server, the download is
suspended (NETWORK_IDLE and suspend, then NETWORK_LOADING once it
resumes, and no progress events meanwhile), and once the player needs
data, the same fetch resumes and the queue drains. If it did not, as
for a cache hit or when two fetches to the origin are suspended
already, the fetch backs off as before; so it does if the answer is
lost, and it is resumed in case net suspended it. Responses that are not read
from the network are handled as before, and the cap on the queue stays
for data that keeps arriving. When a fetch completes, progress, then
NETWORK_IDLE and suspend follow, also if the fetch was suspended.

A fetch with range support that stays suspended for
media_fetch_suspension_timeout_ms (30 s) is cancelled, to restart where
the player stopped once it needs data again, so that an element paused
for long does not hold a connection, which servers would time out
anyway. A fetch without range support stays suspended, since its
restart would fetch the resource from its start again, until net gives
up on it after network_fetch_suspend_timeout_ms (60 s).

Such a server, and net, end the fetch: net with a network error, which
ran the fatal steps (MEDIA_ERR_NETWORK, "If the connection is
interrupted after some media data has been received"), and a closed
connection like a complete body, so the stream ended early. So if a
fetch that was suspended ends with a network error, or with fewer bytes
than its Content-Length, restart it at the byte where the player
stopped, with a Range request, which a server without range support
answers from the start of the resource, whose bytes before that
position are discarded as after a seek: at once if the player accepts
data, or else once it needs data again. A restart past the end of the
resource, which the server answers with 416 or which the length of the
resource tells, ends the stream, as when the server's Content-Length
was too large; so does a restart without range support whose body ends
without an error where the player stopped. Any other restart that ends
early before it delivers data runs the fatal steps: net ends a body
that loses its connection without an error. A restart that delivered
data may be restarted again, so a fetch is only restarted while it
makes progress. The Content-Length of an encoded body is not
the length of the decoded body, so it is not compared.

The state of the suspension in the fetch context grows HTMLVideoElement
from 1264 to 1296 bytes.

Fork note: meant for upstream. Drop once upstream has it.

Testing: no test; a fetch only backs off once the 50 MiB queue of the
GStreamer player is full. See Validation.

Validation: Linux, GStreamer, a 150 MB, 40 s H.264 file in a muted <video preload=metadata> that plays, from a Python server that sends at most 25 MB/s per connection; the base is the parent commit. With range support: 1 request and 149.7 MB sent (base: 3 requests, 149.9 MB); networkState turns NETWORK_IDLE with a suspend event once net confirms the suspension 3.5 s in, and NETWORK_LOADING when the fetch resumes 17.4 s in, with no seeking, stalled or error event. Without range support: 1 request, 149.7 MB, peak RSS 422 MiB (base: 2 requests, 269.9 MB, 419 MiB); paused for 25 s, 1 request, 149.7 MB (base: 2 requests, 269.9 MB). Paused for 40 s with range support: the timeout cancels the fetch 30 s after the suspension, and the restart when playback needs data again plays to the end: 2 requests, 155.4 MB (base: 3 requests, 149.9 MB). Three elements on one origin: net suspends two fetches, which take 1 request each, and the third backs off when net declines its suspension: 4 requests, 449.1 MB (base: 9 requests, 449.8 MB). A suspension costs peak RSS (423 instead of 392 MiB for one element, 738 instead of 683 MiB for three), although only 53 bytes were queued when net confirmed it: once the fetch resumes, net reads at once what the socket buffers held. A server that closes a connection it could not write to for 5 s: the earlier revision of this patch without the restart ended playback after 16.5 s of the media, with no error; with it, the media plays to the end, in 3 requests and 149.7 MB with range support and 2 requests and 238.3 MB without. With network_fetch_suspend_timeout_ms=5000 and playback paused for 40 s, net ends the suspended fetch with a network error, and the media plays to the end after the restart: 3 requests and 156.9 MB with range support, 2 requests and 239.1 MB without, no error event. A server whose Content-Length is 10 MB too large: playback ends normally, as on the base; at 25 MB/s the restart fetches the 10.5 MB that were queued again (2 requests, 160.2 MB) and, without range support, the whole resource again (2 requests, 299.3 MB); at 8 and 12 MB/s the restart starts at the end of the file, which the server answers with 416 (2 requests, 149.7 MB). A server that closes idle connections and closes the restart right after its headers: MEDIA_ERR_NETWORK at the restart, 16.5 s into the media, with and without range support. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` html/semantics/embedded-content/media-elements, the-video-element and html/canvas/element/manual/drawing-images-to-the-canvas with the series: 451 tests, 446 as expected; the other five behave the same on the parent commit of the series when run alone: autoplay-default-permissions-policy.https.sub.html passes where a timeout is expected (3/3 on both), media_fragment_seek.html fails a subtest (3/3 on both), src_object_blob.html times out 1 of 3 runs on both, video_timeupdate_on_seek.html passes a subtest that is expected to time out, and load-removes-queued-error-event.html hangs intermittently because GStreamer never reports the metadata of the 539-byte sound_0.mp3 (3 of 8 runs with the series, 4 of 8 without, alternating). In a later run of media-elements, track-cues-seeking.html timed out, which it does intermittently with and without the series (3 of 39 and 2 of 39 isolated runs, alternating); its 192 KB video never fills the player. `./mach check --ohos` passes at each commit; `./mach test-tidy` reports only the known rustls advisories.
AI-assisted: Yes (agent session; implemented, tested and measured by the agent)
AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the `media_fetch_suspension_timeout_ms` pref where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915), and the patch's +32 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082))
AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: the two early returns for a fetch that ended early pass the fetch listener's global to `submit_timing`, which takes it since upstream 51d1117 (servo#49032))
AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the pref next to upstream's `mathml_core_enabled` (servo#48631), the origin-clean line in upstream's `CorsStatus` form (servo#48748); `HTMLVideoElement` is 1256 bytes, measured at this commit with a compile-time probe, since patch 65 no longer adds a field)
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Oct 30, 2026
Nothing caches media in Servo apart from the backends' own buffers:
every loop, seek back, replay, second element and reload downloads the
resource again, and the media element manages each player's fetch, with
its own backoff, suspension and restarts.

Add the crate servo-media-cache, a process-wide cache that fetches
media resources on behalf of their readers and keeps them in blocks of
64 KiB, as Gecko's MediaCache and Chromium's MultiBuffer do. A resource
is identified by its URL, CORS mode and the origin of the document, is
shared by every reader that opens it, and is reused for 300 s after its
last reader is gone.

Storage: a resource of known length up to 8 MiB keeps its blocks in
memory, all of them together within 32 MiB, beyond which unused ones go
first and then new ones use the file. Every other resource uses slots of
one anonymous temporary file in the directory of the pref
media_cache_directory, or the system temporary directory, so that its
data is page cache that the kernel can reclaim. If the file cannot be
created, read or written, blocks stay in memory within 32 MiB. When the
budget is used up, the block whose next use is predicted latest goes
first, as with Gecko's PredictNextUse; the read-ahead of the readers is
protected, up to half of the budget, and blocks read for metadata go by
their last use.

Fetching: a resource has at most two fetches, started through a Fetcher
that the media element implements, for the readers that still need
them. The main fetch loads 30 s ahead of each reader at its rate, else
8 MiB, is suspended there and resumes below 10 s, else 2 MiB. A reader
that only needs metadata loads 1 MiB ahead, and an idle one nothing. A
read more than 1 MiB from every fetch starts a second fetch at its
block, so that the probe of an index at the end of a file costs one
small request; the last few read positions of a reader keep their
fetches, but only the current one starts fetches. A fetch that reaches
cached data stops unless the next missing byte is within 1 MiB. A
declined suspension cancels a fetch with range support, which restarts
at the first missing byte once it is needed, and so does a suspension
that lasts 30 s; without range support, the fetch keeps loading within
its share of the protected read-ahead, since a restart fetches the
resource from its start again and discards what lies before the read.
Requests after the first carry If-Range. Each response is verified as
HTML's "verify a media response" asks: a CORS-cross-origin response from
another origin than the earlier ones fails the load, and any
CORS-cross-origin response taints the media data. A 200 to a range
request with the same validator and length makes the resource
sequential; a differing validator or length fails the readers with
ResourceChanged instead of splicing two versions of the resource. A
fetch that ends early is restarted where it stopped while it stores new
data, and otherwise the readers fail with a network error; a 416 ends
the resource.

Reading: readers never block. A read returns the cached bytes at a
position, or Pending, and the reader's waker is called once data is
there. An observer hears of the metadata, progress at most every 350
ms, suspension, resumption and completion of the download, and of
errors. The cache queues its calls of fetchers, wakers and observers,
and the user objects it drops, under its lock, and one thread at a time
makes them once the lock is released; file I/O also happens without the
lock, on pinned slots. Time comes from a clock that tests replace. A reader that a player still holds can
be closed, which detaches it as dropping it does and fails its later
reads; a reader also tells whether the resource is tainted, before its
metadata event arrives.

New prefs set the directory, budgets and thresholds:
media_cache_directory, media_cache_file_budget_mb (128 on OpenHarmony
and Android, 512 elsewhere), media_cache_memory_resource_limit_kb,
media_cache_memory_fallback_mb, media_cache_readahead_seconds,
media_cache_resume_seconds, media_cache_suspend_seconds and
media_cache_reuse_seconds. `./mach test-unit -p servo-media-cache` runs
the tests of the crate. Players may read a reader directly through the
new Player::set_data_source, which backends that cannot refuse with
PlayerError::NotSupported.

Fork note: meant for upstream. Drop once upstream has it.

Testing: 54 unit tests with a fake fetcher and a fake clock, which
cover sharing, suspension and resumption, gap and probe fetches,
resources without range support or of unknown length, validators and
200s to range requests, origin verification and taint, recovery from
early ends, 416, eviction, memory and file backing and their I/O
errors, the reuse window, trimming, activities, wakers and observers
called without the lock and dropped from inside callbacks, and readers
on other threads, and closing a reader that a player holds.

Validation: `./mach test-unit -p servo-media-cache` passes ten runs in a row; each of 22 deliberate breaks makes at least one test fail. Two independent reviews of the crate; their findings are fixed. `./mach check`, `cargo clippy -p servo-media-cache --tests` and `./mach fmt` pass.
AI-assisted: Yes (agent session; implemented, reviewed, tested and mutation-checked by agents)
AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the media cache prefs where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915))
AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution, no semantic change: the prefs next to upstream's `mathml_core_enabled` (servo#48631))
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Nov 9, 2026
…r is full

When its player has enough data, a media element cancels a fetch with
range support, to restart it with a Range request once the player needs
data again, and keeps queueing the data of a fetch without range
support, up to 32 MiB, before it cancels it and fetches the resource
from its start again. Every restart costs a request, on HTTP/1.1 a new
connection, and the bytes that were in flight.

Ask net to suspend a fetch that is read from the network instead, and
queue the data that was in flight. Net answers whether it suspended the
fetch. If it did, flow control holds back the server, the download is
suspended (NETWORK_IDLE and suspend, then NETWORK_LOADING once it
resumes, and no progress events meanwhile), and once the player needs
data, the same fetch resumes and the queue drains. If it did not, as
for a cache hit or when two fetches to the origin are suspended
already, the fetch backs off as before; so it does if the answer is
lost, and it is resumed in case net suspended it. Responses that are not read
from the network are handled as before, and the cap on the queue stays
for data that keeps arriving. When a fetch completes, progress, then
NETWORK_IDLE and suspend follow, also if the fetch was suspended.

A fetch with range support that stays suspended for
media_fetch_suspension_timeout_ms (30 s) is cancelled, to restart where
the player stopped once it needs data again, so that an element paused
for long does not hold a connection, which servers would time out
anyway. A fetch without range support stays suspended, since its
restart would fetch the resource from its start again, until net gives
up on it after network_fetch_suspend_timeout_ms (60 s).

Such a server, and net, end the fetch: net with a network error, which
ran the fatal steps (MEDIA_ERR_NETWORK, "If the connection is
interrupted after some media data has been received"), and a closed
connection like a complete body, so the stream ended early. So if a
fetch that was suspended ends with a network error, or with fewer bytes
than its Content-Length, restart it at the byte where the player
stopped, with a Range request, which a server without range support
answers from the start of the resource, whose bytes before that
position are discarded as after a seek: at once if the player accepts
data, or else once it needs data again. A restart past the end of the
resource, which the server answers with 416 or which the length of the
resource tells, ends the stream, as when the server's Content-Length
was too large; so does a restart without range support whose body ends
without an error where the player stopped. Any other restart that ends
early before it delivers data runs the fatal steps: net ends a body
that loses its connection without an error. A restart that delivered
data may be restarted again, so a fetch is only restarted while it
makes progress. The Content-Length of an encoded body is not
the length of the decoded body, so it is not compared.

The state of the suspension in the fetch context grows HTMLVideoElement
from 1264 to 1296 bytes.

Fork note: meant for upstream. Drop once upstream has it.

Testing: no test; a fetch only backs off once the 50 MiB queue of the
GStreamer player is full. See Validation.

Validation: Linux, GStreamer, a 150 MB, 40 s H.264 file in a muted <video preload=metadata> that plays, from a Python server that sends at most 25 MB/s per connection; the base is the parent commit. With range support: 1 request and 149.7 MB sent (base: 3 requests, 149.9 MB); networkState turns NETWORK_IDLE with a suspend event once net confirms the suspension 3.5 s in, and NETWORK_LOADING when the fetch resumes 17.4 s in, with no seeking, stalled or error event. Without range support: 1 request, 149.7 MB, peak RSS 422 MiB (base: 2 requests, 269.9 MB, 419 MiB); paused for 25 s, 1 request, 149.7 MB (base: 2 requests, 269.9 MB). Paused for 40 s with range support: the timeout cancels the fetch 30 s after the suspension, and the restart when playback needs data again plays to the end: 2 requests, 155.4 MB (base: 3 requests, 149.9 MB). Three elements on one origin: net suspends two fetches, which take 1 request each, and the third backs off when net declines its suspension: 4 requests, 449.1 MB (base: 9 requests, 449.8 MB). A suspension costs peak RSS (423 instead of 392 MiB for one element, 738 instead of 683 MiB for three), although only 53 bytes were queued when net confirmed it: once the fetch resumes, net reads at once what the socket buffers held. A server that closes a connection it could not write to for 5 s: the earlier revision of this patch without the restart ended playback after 16.5 s of the media, with no error; with it, the media plays to the end, in 3 requests and 149.7 MB with range support and 2 requests and 238.3 MB without. With network_fetch_suspend_timeout_ms=5000 and playback paused for 40 s, net ends the suspended fetch with a network error, and the media plays to the end after the restart: 3 requests and 156.9 MB with range support, 2 requests and 239.1 MB without, no error event. A server whose Content-Length is 10 MB too large: playback ends normally, as on the base; at 25 MB/s the restart fetches the 10.5 MB that were queued again (2 requests, 160.2 MB) and, without range support, the whole resource again (2 requests, 299.3 MB); at 8 and 12 MB/s the restart starts at the end of the file, which the server answers with 416 (2 requests, 149.7 MB). A server that closes idle connections and closes the restart right after its headers: MEDIA_ERR_NETWORK at the restart, 16.5 s into the media, with and without range support. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` html/semantics/embedded-content/media-elements, the-video-element and html/canvas/element/manual/drawing-images-to-the-canvas with the series: 451 tests, 446 as expected; the other five behave the same on the parent commit of the series when run alone: autoplay-default-permissions-policy.https.sub.html passes where a timeout is expected (3/3 on both), media_fragment_seek.html fails a subtest (3/3 on both), src_object_blob.html times out 1 of 3 runs on both, video_timeupdate_on_seek.html passes a subtest that is expected to time out, and load-removes-queued-error-event.html hangs intermittently because GStreamer never reports the metadata of the 539-byte sound_0.mp3 (3 of 8 runs with the series, 4 of 8 without, alternating). In a later run of media-elements, track-cues-seeking.html timed out, which it does intermittently with and without the series (3 of 39 and 2 of 39 isolated runs, alternating); its 192 KB video never fills the player. `./mach check --ohos` passes at each commit; `./mach test-tidy` reports only the known rustls advisories.
AI-assisted: Yes (agent session; implemented, tested and measured by the agent)
AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the `media_fetch_suspension_timeout_ms` pref where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915), and the patch's +32 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082))
AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: the two early returns for a fetch that ended early pass the fetch listener's global to `submit_timing`, which takes it since upstream 51d1117 (servo#49032))
AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the pref next to upstream's `mathml_core_enabled` (servo#48631), the origin-clean line in upstream's `CorsStatus` form (servo#48748); `HTMLVideoElement` is 1256 bytes, measured at this commit with a compile-time probe, since patch 65 no longer adds a field)
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Nov 9, 2026
Nothing caches media in Servo apart from the backends' own buffers:
every loop, seek back, replay, second element and reload downloads the
resource again, and the media element manages each player's fetch, with
its own backoff, suspension and restarts.

Add the crate servo-media-cache, a process-wide cache that fetches
media resources on behalf of their readers and keeps them in blocks of
64 KiB, as Gecko's MediaCache and Chromium's MultiBuffer do. A resource
is identified by its URL, CORS mode and the origin of the document, is
shared by every reader that opens it, and is reused for 300 s after its
last reader is gone.

Storage: a resource of known length up to 8 MiB keeps its blocks in
memory, all of them together within 32 MiB, beyond which unused ones go
first and then new ones use the file. Every other resource uses slots of
one anonymous temporary file in the directory of the pref
media_cache_directory, or the system temporary directory, so that its
data is page cache that the kernel can reclaim. If the file cannot be
created, read or written, blocks stay in memory within 32 MiB. When the
budget is used up, the block whose next use is predicted latest goes
first, as with Gecko's PredictNextUse; the read-ahead of the readers is
protected, up to half of the budget, and blocks read for metadata go by
their last use.

Fetching: a resource has at most two fetches, started through a Fetcher
that the media element implements, for the readers that still need
them. The main fetch loads 30 s ahead of each reader at its rate, else
8 MiB, is suspended there and resumes below 10 s, else 2 MiB. A reader
that only needs metadata loads 1 MiB ahead, and an idle one nothing. A
read more than 1 MiB from every fetch starts a second fetch at its
block, so that the probe of an index at the end of a file costs one
small request; the last few read positions of a reader keep their
fetches, but only the current one starts fetches. A fetch that reaches
cached data stops unless the next missing byte is within 1 MiB. A
declined suspension cancels a fetch with range support, which restarts
at the first missing byte once it is needed, and so does a suspension
that lasts 30 s; without range support, the fetch keeps loading within
its share of the protected read-ahead, since a restart fetches the
resource from its start again and discards what lies before the read.
Requests after the first carry If-Range. Each response is verified as
HTML's "verify a media response" asks: a CORS-cross-origin response from
another origin than the earlier ones fails the load, and any
CORS-cross-origin response taints the media data. A 200 to a range
request with the same validator and length makes the resource
sequential; a differing validator or length fails the readers with
ResourceChanged instead of splicing two versions of the resource. A
fetch that ends early is restarted where it stopped while it stores new
data, and otherwise the readers fail with a network error; a 416 ends
the resource.

Reading: readers never block. A read returns the cached bytes at a
position, or Pending, and the reader's waker is called once data is
there. An observer hears of the metadata, progress at most every 350
ms, suspension, resumption and completion of the download, and of
errors. The cache queues its calls of fetchers, wakers and observers,
and the user objects it drops, under its lock, and one thread at a time
makes them once the lock is released; file I/O also happens without the
lock, on pinned slots. Time comes from a clock that tests replace. A reader that a player still holds can
be closed, which detaches it as dropping it does and fails its later
reads; a reader also tells whether the resource is tainted, before its
metadata event arrives.

New prefs set the directory, budgets and thresholds:
media_cache_directory, media_cache_file_budget_mb (128 on OpenHarmony
and Android, 512 elsewhere), media_cache_memory_resource_limit_kb,
media_cache_memory_fallback_mb, media_cache_readahead_seconds,
media_cache_resume_seconds, media_cache_suspend_seconds and
media_cache_reuse_seconds. `./mach test-unit -p servo-media-cache` runs
the tests of the crate. Players may read a reader directly through the
new Player::set_data_source, which backends that cannot refuse with
PlayerError::NotSupported.

Fork note: meant for upstream. Drop once upstream has it.

Testing: 54 unit tests with a fake fetcher and a fake clock, which
cover sharing, suspension and resumption, gap and probe fetches,
resources without range support or of unknown length, validators and
200s to range requests, origin verification and taint, recovery from
early ends, 416, eviction, memory and file backing and their I/O
errors, the reuse window, trimming, activities, wakers and observers
called without the lock and dropped from inside callbacks, and readers
on other threads, and closing a reader that a player holds.

Validation: `./mach test-unit -p servo-media-cache` passes ten runs in a row; each of 22 deliberate breaks makes at least one test fail. Two independent reviews of the crate; their findings are fixed. `./mach check`, `cargo clippy -p servo-media-cache --tests` and `./mach fmt` pass.
AI-assisted: Yes (agent session; implemented, reviewed, tested and mutation-checked by agents)
AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the media cache prefs where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915))
AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution, no semantic change: the prefs next to upstream's `mathml_core_enabled` (servo#48631))
AI-assisted: Yes (agent session; 2026-11-09 sync -- the media cache crate joins upstream's 0.8.0 workspace version block (servo#49467), and Cargo.lock gives it that version)
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Nov 10, 2026
…r is full

When its player has enough data, a media element cancels a fetch with
range support, to restart it with a Range request once the player needs
data again, and keeps queueing the data of a fetch without range
support, up to 32 MiB, before it cancels it and fetches the resource
from its start again. Every restart costs a request, on HTTP/1.1 a new
connection, and the bytes that were in flight.

Ask net to suspend a fetch that is read from the network instead, and
queue the data that was in flight. Net answers whether it suspended the
fetch. If it did, flow control holds back the server, the download is
suspended (NETWORK_IDLE and suspend, then NETWORK_LOADING once it
resumes, and no progress events meanwhile), and once the player needs
data, the same fetch resumes and the queue drains. If it did not, as
for a cache hit or when two fetches to the origin are suspended
already, the fetch backs off as before; so it does if the answer is
lost, and it is resumed in case net suspended it. Responses that are not read
from the network are handled as before, and the cap on the queue stays
for data that keeps arriving. When a fetch completes, progress, then
NETWORK_IDLE and suspend follow, also if the fetch was suspended.

A fetch with range support that stays suspended for
media_fetch_suspension_timeout_ms (30 s) is cancelled, to restart where
the player stopped once it needs data again, so that an element paused
for long does not hold a connection, which servers would time out
anyway. A fetch without range support stays suspended, since its
restart would fetch the resource from its start again, until net gives
up on it after network_fetch_suspend_timeout_ms (60 s).

Such a server, and net, end the fetch: net with a network error, which
ran the fatal steps (MEDIA_ERR_NETWORK, "If the connection is
interrupted after some media data has been received"), and a closed
connection like a complete body, so the stream ended early. So if a
fetch that was suspended ends with a network error, or with fewer bytes
than its Content-Length, restart it at the byte where the player
stopped, with a Range request, which a server without range support
answers from the start of the resource, whose bytes before that
position are discarded as after a seek: at once if the player accepts
data, or else once it needs data again. A restart past the end of the
resource, which the server answers with 416 or which the length of the
resource tells, ends the stream, as when the server's Content-Length
was too large; so does a restart without range support whose body ends
without an error where the player stopped. Any other restart that ends
early before it delivers data runs the fatal steps: net ends a body
that loses its connection without an error. A restart that delivered
data may be restarted again, so a fetch is only restarted while it
makes progress. The Content-Length of an encoded body is not
the length of the decoded body, so it is not compared.

The state of the suspension in the fetch context grows HTMLVideoElement
from 1264 to 1296 bytes.

Fork note: meant for upstream. Drop once upstream has it.

Testing: no test; a fetch only backs off once the 50 MiB queue of the
GStreamer player is full. See Validation.

Validation: Linux, GStreamer, a 150 MB, 40 s H.264 file in a muted <video preload=metadata> that plays, from a Python server that sends at most 25 MB/s per connection; the base is the parent commit. With range support: 1 request and 149.7 MB sent (base: 3 requests, 149.9 MB); networkState turns NETWORK_IDLE with a suspend event once net confirms the suspension 3.5 s in, and NETWORK_LOADING when the fetch resumes 17.4 s in, with no seeking, stalled or error event. Without range support: 1 request, 149.7 MB, peak RSS 422 MiB (base: 2 requests, 269.9 MB, 419 MiB); paused for 25 s, 1 request, 149.7 MB (base: 2 requests, 269.9 MB). Paused for 40 s with range support: the timeout cancels the fetch 30 s after the suspension, and the restart when playback needs data again plays to the end: 2 requests, 155.4 MB (base: 3 requests, 149.9 MB). Three elements on one origin: net suspends two fetches, which take 1 request each, and the third backs off when net declines its suspension: 4 requests, 449.1 MB (base: 9 requests, 449.8 MB). A suspension costs peak RSS (423 instead of 392 MiB for one element, 738 instead of 683 MiB for three), although only 53 bytes were queued when net confirmed it: once the fetch resumes, net reads at once what the socket buffers held. A server that closes a connection it could not write to for 5 s: the earlier revision of this patch without the restart ended playback after 16.5 s of the media, with no error; with it, the media plays to the end, in 3 requests and 149.7 MB with range support and 2 requests and 238.3 MB without. With network_fetch_suspend_timeout_ms=5000 and playback paused for 40 s, net ends the suspended fetch with a network error, and the media plays to the end after the restart: 3 requests and 156.9 MB with range support, 2 requests and 239.1 MB without, no error event. A server whose Content-Length is 10 MB too large: playback ends normally, as on the base; at 25 MB/s the restart fetches the 10.5 MB that were queued again (2 requests, 160.2 MB) and, without range support, the whole resource again (2 requests, 299.3 MB); at 8 and 12 MB/s the restart starts at the end of the file, which the server answers with 416 (2 requests, 149.7 MB). A server that closes idle connections and closes the restart right after its headers: MEDIA_ERR_NETWORK at the restart, 16.5 s into the media, with and without range support. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` html/semantics/embedded-content/media-elements, the-video-element and html/canvas/element/manual/drawing-images-to-the-canvas with the series: 451 tests, 446 as expected; the other five behave the same on the parent commit of the series when run alone: autoplay-default-permissions-policy.https.sub.html passes where a timeout is expected (3/3 on both), media_fragment_seek.html fails a subtest (3/3 on both), src_object_blob.html times out 1 of 3 runs on both, video_timeupdate_on_seek.html passes a subtest that is expected to time out, and load-removes-queued-error-event.html hangs intermittently because GStreamer never reports the metadata of the 539-byte sound_0.mp3 (3 of 8 runs with the series, 4 of 8 without, alternating). In a later run of media-elements, track-cues-seeking.html timed out, which it does intermittently with and without the series (3 of 39 and 2 of 39 isolated runs, alternating); its 192 KB video never fills the player. `./mach check --ohos` passes at each commit; `./mach test-tidy` reports only the known rustls advisories.
AI-assisted: Yes (agent session; implemented, tested and measured by the agent)
AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the `media_fetch_suspension_timeout_ms` pref where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915), and the patch's +32 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082))
AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: the two early returns for a fetch that ended early pass the fetch listener's global to `submit_timing`, which takes it since upstream 51d1117 (servo#49032))
AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the pref next to upstream's `mathml_core_enabled` (servo#48631), the origin-clean line in upstream's `CorsStatus` form (servo#48748); `HTMLVideoElement` is 1256 bytes, measured at this commit with a compile-time probe, since patch 65 no longer adds a field)
Signed-off-by: Jonathan Schwender <[email protected]>
jschwe added a commit to openharmony-rs/servo-ohos that referenced this pull request Nov 10, 2026
Nothing caches media in Servo apart from the backends' own buffers:
every loop, seek back, replay, second element and reload downloads the
resource again, and the media element manages each player's fetch, with
its own backoff, suspension and restarts.

Add the crate servo-media-cache, a process-wide cache that fetches
media resources on behalf of their readers and keeps them in blocks of
64 KiB, as Gecko's MediaCache and Chromium's MultiBuffer do. A resource
is identified by its URL, CORS mode and the origin of the document, is
shared by every reader that opens it, and is reused for 300 s after its
last reader is gone.

Storage: a resource of known length up to 8 MiB keeps its blocks in
memory, all of them together within 32 MiB, beyond which unused ones go
first and then new ones use the file. Every other resource uses slots of
one anonymous temporary file in the directory of the pref
media_cache_directory, or the system temporary directory, so that its
data is page cache that the kernel can reclaim. If the file cannot be
created, read or written, blocks stay in memory within 32 MiB. When the
budget is used up, the block whose next use is predicted latest goes
first, as with Gecko's PredictNextUse; the read-ahead of the readers is
protected, up to half of the budget, and blocks read for metadata go by
their last use.

Fetching: a resource has at most two fetches, started through a Fetcher
that the media element implements, for the readers that still need
them. The main fetch loads 30 s ahead of each reader at its rate, else
8 MiB, is suspended there and resumes below 10 s, else 2 MiB. A reader
that only needs metadata loads 1 MiB ahead, and an idle one nothing. A
read more than 1 MiB from every fetch starts a second fetch at its
block, so that the probe of an index at the end of a file costs one
small request; the last few read positions of a reader keep their
fetches, but only the current one starts fetches. A fetch that reaches
cached data stops unless the next missing byte is within 1 MiB. A
declined suspension cancels a fetch with range support, which restarts
at the first missing byte once it is needed, and so does a suspension
that lasts 30 s; without range support, the fetch keeps loading within
its share of the protected read-ahead, since a restart fetches the
resource from its start again and discards what lies before the read.
Requests after the first carry If-Range. Each response is verified as
HTML's "verify a media response" asks: a CORS-cross-origin response from
another origin than the earlier ones fails the load, and any
CORS-cross-origin response taints the media data. A 200 to a range
request with the same validator and length makes the resource
sequential; a differing validator or length fails the readers with
ResourceChanged instead of splicing two versions of the resource. A
fetch that ends early is restarted where it stopped while it stores new
data, and otherwise the readers fail with a network error; a 416 ends
the resource.

Reading: readers never block. A read returns the cached bytes at a
position, or Pending, and the reader's waker is called once data is
there. An observer hears of the metadata, progress at most every 350
ms, suspension, resumption and completion of the download, and of
errors. The cache queues its calls of fetchers, wakers and observers,
and the user objects it drops, under its lock, and one thread at a time
makes them once the lock is released; file I/O also happens without the
lock, on pinned slots. Time comes from a clock that tests replace. A reader that a player still holds can
be closed, which detaches it as dropping it does and fails its later
reads; a reader also tells whether the resource is tainted, before its
metadata event arrives.

New prefs set the directory, budgets and thresholds:
media_cache_directory, media_cache_file_budget_mb (128 on OpenHarmony
and Android, 512 elsewhere), media_cache_memory_resource_limit_kb,
media_cache_memory_fallback_mb, media_cache_readahead_seconds,
media_cache_resume_seconds, media_cache_suspend_seconds and
media_cache_reuse_seconds. `./mach test-unit -p servo-media-cache` runs
the tests of the crate. Players may read a reader directly through the
new Player::set_data_source, which backends that cannot refuse with
PlayerError::NotSupported.

Fork note: meant for upstream. Drop once upstream has it.

Testing: 54 unit tests with a fake fetcher and a fake clock, which
cover sharing, suspension and resumption, gap and probe fetches,
resources without range support or of unknown length, validators and
200s to range requests, origin verification and taint, recovery from
early ends, 416, eviction, memory and file backing and their I/O
errors, the reuse window, trimming, activities, wakers and observers
called without the lock and dropped from inside callbacks, and readers
on other threads, and closing a reader that a player holds.

Validation: `./mach test-unit -p servo-media-cache` passes ten runs in a row; each of 22 deliberate breaks makes at least one test fail. Two independent reviews of the crate; their findings are fixed. `./mach check`, `cargo clippy -p servo-media-cache --tests` and `./mach fmt` pass.
AI-assisted: Yes (agent session; implemented, reviewed, tested and mutation-checked by agents)
AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the media cache prefs where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915))
AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution, no semantic change: the prefs next to upstream's `mathml_core_enabled` (servo#48631))
AI-assisted: Yes (agent session; 2026-11-09 sync -- the media cache crate joins upstream's 0.8.0 workspace version block (servo#49467), and Cargo.lock gives it that version)
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants