Skip to content

Truly independent web browser

LibJS+LibWeb: Test reuse of compiled scripts across realms

Andreas Kling585eb19baeb8
diff --git a/Libraries/LibJS/Rust/src/embedding/function.rs b/Libraries/LibJS/Rust/src/embedding/function.rs
index bdb684f864d..fa8aa0ba6d2 100644
--- a/Libraries/LibJS/Rust/src/embedding/function.rs
+++ b/Libraries/LibJS/Rust/src/embedding/function.rs
@@ -16,6 +16,7 @@
use core::ffi::{c_char, c_void};
use core::mem::offset_of;
use core::ptr::NonNull;
+use std::sync::Arc;
use crate::embedding::abi_types::{
JSOwnedUtf16String, JSRealm, JSUtf16View, cell_from_abi, completion_from_abi, completion_into_abi, object_into_abi,
@@ -29,7 +30,7 @@ use crate::gc::foreign::ForeignCellSlot;
use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
-use crate::layout::function_object::EcmascriptFunctionObject;
+use crate::layout::function_object::{EcmascriptFunctionObject, FunctionObject};
use crate::layout::host_class::{JSCompletion, JSObject, JSPropertyKey, JSVM, JSValue};
use crate::layout::value::Value;
use crate::layout_forward::{RawNativeFunctionPointer, RawNativeFunctionResult};
@@ -424,6 +425,24 @@ pub unsafe extern "C" fn js_function_compile_dynamic(
}
}
+/// functions_share_code(vm, a, b): whether two ECMAScript functions run the same compiled code, which compiles them if
+/// they did not run yet. Main thread only.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn js_function_shares_code(vm: *mut JSVM, a: *mut JSObject, b: *mut JSObject) -> bool {
+ // SAFETY: See the module documentation.
+ let (vm, a, b) = unsafe { (vm_from_abi(vm), function_from_abi(a), function_from_abi(b)) };
+ let compiled_executable = |function: Gc<FunctionObject>| {
+ function
+ .downcast::<EcmascriptFunctionObject>()?
+ .compiled_executable(vm)
+ .ok()
+ };
+ match (compiled_executable(a), compiled_executable(b)) {
+ (Some(a), Some(b)) => Arc::ptr_eq(a.code(), b.code()),
+ _ => false,
+ }
+}
+
/// OrdinaryFunctionCreate over code js_function_compile_dynamic() compiled: a function of the realm with the default
/// prototype for its kind, which closes over the scope and the private environment (null for none), and whose
/// [[ScriptOrModule]] is `script_or_module`, as an execution context holds it. Returns an unrooted function. Main
diff --git a/Libraries/LibJS/ScriptCompilation.cpp b/Libraries/LibJS/ScriptCompilation.cpp
index d1bd076b926..5b2fb057b9f 100644
--- a/Libraries/LibJS/ScriptCompilation.cpp
+++ b/Libraries/LibJS/ScriptCompilation.cpp
@@ -87,6 +87,11 @@ Vector<Position> breakpoint_positions_for_source(SourceCode const& source_code,
return positions;
}
+bool functions_share_code(VM& vm, FunctionObject const& a, FunctionObject const& b)
+{
+ return js_function_shares_code(vm_to_abi(vm), object_to_abi(a), object_to_abi(b));
+}
+
ParsedProgram::ParsedProgram(FFI::ParsedProgram* program)
: m_program(program)
{
@@ -222,7 +227,6 @@ Result<GC::Ref<SourceTextModule>, Vector<ParserError>> create_module(CompiledPro
return module_from_abi<SourceTextModule>(module);
}
-// The host's callbacks, which the runtime shares between the main thread and the workers until it releases them.
RefPtr<SourceCode const> top_level_source_code(Script const& script)
{
return source_code_from_abi(js_compile_top_level_source_code_of_script(script_to_abi(script)));
diff --git a/Libraries/LibJS/ScriptCompilation.h b/Libraries/LibJS/ScriptCompilation.h
index 30b27893585..5367305ad4e 100644
--- a/Libraries/LibJS/ScriptCompilation.h
+++ b/Libraries/LibJS/ScriptCompilation.h
@@ -67,6 +67,9 @@ private:
// compiled yet. This compiles a private copy of the source without touching the VM or the GC heap.
JS_API Vector<Position> breakpoint_positions_for_source(SourceCode const&, ProgramType, size_t line_number_offset);
+// Whether two functions run the same compiled code, which compiles them if they did not run yet. Only for tests.
+JS_API bool functions_share_code(VM&, FunctionObject const&, FunctionObject const&);
+
class ParsedProgram;
class CompiledProgram;
@@ -77,8 +80,8 @@ JS_API Result<GC::Ref<Script>, Vector<ParserError>> create_script(CompiledProgra
JS_API Result<GC::Ref<SourceTextModule>, Vector<ParserError>> create_module(ParsedProgram, NonnullRefPtr<SourceCode const>, Realm&, StringView filename, GC::Ptr<GC::Cell>);
JS_API Result<GC::Ref<SourceTextModule>, Vector<ParserError>> create_module(CompiledProgram, NonnullRefPtr<SourceCode const>, Realm&, StringView filename, GC::Ptr<GC::Cell>);
-// ParsedProgram and CompiledProgram hold a program outside of the VM and the GC heap. Parsing, compiling, serializing
-// and destroying them is thread-safe, so a host can do that work on a worker thread.
+// ParsedProgram and CompiledProgram hold a program outside of the VM and the GC heap. Parsing, compiling and destroying
+// them is thread-safe, so a host can do that work on a worker thread.
class JS_API ParsedProgram {
AK_MAKE_NONCOPYABLE(ParsedProgram);
@@ -93,8 +96,6 @@ public:
explicit operator bool() const { return m_program; }
bool has_errors() const;
- // Only for a program without errors. The copy compiles independently of the original.
-
private:
friend class CompiledProgram;
friend JS_API Result<GC::Ref<Script>, Vector<ParserError>> create_script(ParsedProgram, NonnullRefPtr<SourceCode const>, Realm&, StringView filename, GC::Ptr<GC::Cell>);
diff --git a/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h
index b961771263b..3afbf86c558 100644
--- a/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h
+++ b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h
@@ -39,6 +39,8 @@ public:
// From here on, the program keeps the functions that get compiled for it. Replaces what the key held before.
void store(CompiledScriptCacheKey, Utf16String source_text, JS::CompiledProgram const&);
+ bool contains(CompiledScriptCacheKey const& key) const { return m_entries.contains(key); }
+
void clear();
private:
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index e7348f7d260..8906cf2e3f3 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -21,6 +21,7 @@
#include <LibGC/Heap.h>
#include <LibGC/RootVector.h>
#include <LibGfx/Cursor.h>
+#include <LibHTTP/Cache/Utilities.h>
#include <LibHTTP/HSTS/ParsedHSTSPolicy.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Array.h>
@@ -89,6 +90,7 @@
#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/Navigable.h>
#include <LibWeb/HTML/Parser/HTMLParser.h>
+#include <LibWeb/HTML/Scripting/CompiledScriptCache.h>
#include <LibWeb/HTML/Scripting/ConsoleInputCompletion.h>
#include <LibWeb/HTML/Scripting/DevToolsObjectTable.h>
#include <LibWeb/HTML/Scripting/Environments.h>
@@ -1412,6 +1414,32 @@ bool Internals::set_http_memory_cache_enabled(bool enabled)
return was_enabled;
}
+bool Internals::functions_share_code(JS::Value a, JS::Value b)
+{
+ if (!a.is_function() || !b.is_function())
+ return false;
+ return JS::functions_share_code(vm(), a.as_function(), b.as_function());
+}
+
+bool Internals::compiled_script_cache_contains(Utf16String const& url)
+{
+ auto parsed_url = DOMURL::parse(url);
+ if (!parsed_url.has_value())
+ return false;
+
+ auto key = Fetch::Infrastructure::determine_the_network_partition_key(window().associated_document().relevant_settings_object());
+ auto partition = key.has_value() ? key->disk_cache_partition() : OptionalNone {};
+ if (!partition.has_value())
+ return false;
+
+ return HTML::CompiledScriptCache::the().contains({
+ .partition = partition.release_value(),
+ .url_without_fragment = HTTP::serialize_url_for_cache_storage(*parsed_url),
+ .program_type = JS::ProgramType::Script,
+ .line_number_offset = 1,
+ });
+}
+
bool Internals::set_disk_cache_enabled_for_navigations(bool enabled)
{
auto was_enabled = Web::Fetch::Fetching::disk_cache_enabled_for_navigations_for_testing();
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index 5f812f50774..91e6ee82604 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -177,6 +177,8 @@ public:
WebIDL::ExceptionOr<bool> has_cookie_for_url(Utf16String const& url, String const& name, String const& value);
bool set_http_memory_cache_enabled(bool enabled);
+ bool functions_share_code(JS::Value a, JS::Value b);
+ bool compiled_script_cache_contains(Utf16String const& url);
bool set_disk_cache_enabled_for_navigations(bool enabled);
void simulate_request_server_connection_loss();
void simulate_worker_request_server_connection_loss();
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index b245ee45141..aa09ba083cb 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -177,6 +177,10 @@ interface Internals {
boolean hasCookieForURL(DOMString url, ByteString name, ByteString value);
boolean setHttpMemoryCacheEnabled(boolean enabled);
+ // Whether two functions run the same compiled code, which compiles them if they did not run yet.
+ boolean functionsShareCode(any a, any b);
+ // Whether a classic script from the given URL is in the compiled script cache for this window's partition.
+ boolean compiledScriptCacheContains(DOMString url);
boolean setDiskCacheEnabledForNavigations(boolean enabled);
undefined simulateRequestServerConnectionLoss();
undefined simulateWorkerRequestServerConnectionLoss();
diff --git a/Tests/LibWeb/Text/expected/Cache/compiled-script-reuse.txt b/Tests/LibWeb/Text/expected/Cache/compiled-script-reuse.txt
new file mode 100644
index 00000000000..aeec6ff57e4
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Cache/compiled-script-reuse.txt
@@ -0,0 +1,40 @@
+Function called in the first realm: true
+Function called in neither realm: true
+Nested function: true
+Function of an immediately invoked function: true
+Different functions: false
+Second realm runs: 10
+Realm-bound code is shared: true
+Top-level object literal prototype is per realm: true
+Template object is stable in a realm: true
+Template objects differ across realms: true
+Top-level template objects differ across realms: true
+Second load in one realm is shared: true
+Template objects differ across loads in one realm: true
+Top-level template objects differ across loads in one realm: true
+toString is shared: true
+toString of a function: true
+toString of a class: class C { method ( ) { } }
+Redirected loads are shared: true
+Stack names the request URL: true
+Stack does not name the redirect target: true
+Stack of the direct load names the target: true
+Loads with other fragments are shared: true
+Stack names the fragment of its load: true
+Muted load is shared: true
+CORS load reports the error: true
+No-CORS load mutes the error: Script error.
+Later CORS load reports the error: true
+Charsets decode to: 1, 2
+Other charset is shared: false
+Back to the first charset: 1
+Loaded as: false, true, true, false
+Classic and module are shared: false
+Modules are shared: true
+Classic scripts are shared: true
+Changed bytes run: 1, 2
+Changed bytes are shared: false
+A no-store response is shared: false
+Stored in this partition: true
+Found from another partition: false
+Stored for the other partition once it loaded: true
diff --git a/Tests/LibWeb/Text/input/Cache/compiled-script-reuse.html b/Tests/LibWeb/Text/input/Cache/compiled-script-reuse.html
new file mode 100644
index 00000000000..d78fb832f7c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Cache/compiled-script-reuse.html
@@ -0,0 +1,275 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ const CACHEABLE = { "Content-Type": "text/javascript", "Cache-Control": "max-age=60" };
+
+ function newFrame() {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ return iframe.contentWindow;
+ }
+
+ function loadScript(frame, url, attributes = {}) {
+ return new Promise((resolve, reject) => {
+ const script = frame.document.createElement("script");
+ Object.assign(script, attributes);
+ script.src = url;
+ script.onload = resolve;
+ script.onerror = reject;
+ frame.document.body.appendChild(script);
+ });
+ }
+
+ async function loadInNewFrame(url, attributes) {
+ const frame = newFrame();
+ await loadScript(frame, url, attributes);
+ return frame;
+ }
+
+ function waitForMessage(source) {
+ return new Promise(resolve => {
+ window.addEventListener("message", function listener(event) {
+ if (event.source !== source)
+ return;
+ window.removeEventListener("message", listener);
+ resolve(event.data);
+ });
+ });
+ }
+
+ async function testHitsAcrossRealms(server) {
+ const url = await server.createEcho("GET", "/compiled-script-reuse/hit", {
+ status: 200,
+ headers: CACHEABLE,
+ body: `globalThis.calledFirst = function () { return 1; };
+ globalThis.neverCalledBefore = function () { return 2; };
+ globalThis.outer = function () { return function inner() { return 3; }; };
+ globalThis.iife = (function () { return function () { return 4; }; })();`,
+ });
+
+ const first = await loadInNewFrame(url);
+ first.calledFirst();
+ const innerOfFirst = first.outer();
+
+ const second = await loadInNewFrame(url);
+ println(`Function called in the first realm: ${internals.functionsShareCode(first.calledFirst, second.calledFirst)}`);
+ println(`Function called in neither realm: ${internals.functionsShareCode(first.neverCalledBefore, second.neverCalledBefore)}`);
+ println(`Nested function: ${internals.functionsShareCode(innerOfFirst, second.outer())}`);
+ println(`Function of an immediately invoked function: ${internals.functionsShareCode(first.iife, second.iife)}`);
+ println(`Different functions: ${internals.functionsShareCode(first.calledFirst, second.neverCalledBefore)}`);
+
+ println(`Second realm runs: ${second.calledFirst() + second.neverCalledBefore() + second.outer()() + second.iife()}`);
+ }
+
+ async function testRealmBoundState(server) {
+ const url = await server.createEcho("GET", "/compiled-script-reuse/realm-bound", {
+ status: 200,
+ headers: CACHEABLE,
+ body: `function tag(strings) { return strings; }
+ globalThis.template = function () { return tag\`a\${1}b\`; };
+ globalThis.objectLiteral = function () { return { a: 1 }; };
+ globalThis.topLevelTemplate = tag\`c\`;
+ globalThis.topLevelObjectLiteral = { b: 2 };`,
+ });
+
+ const first = await loadInNewFrame(url);
+ const second = await loadInNewFrame(url);
+ println(`Realm-bound code is shared: ${internals.functionsShareCode(first.objectLiteral, second.objectLiteral)}`);
+
+ // Run the code in both realms in turn, so that each sees caches the other would have filled if they were shared.
+ for (let i = 0; i < 3; ++i) {
+ for (const frame of [first, second]) {
+ const objectPrototypeIsOwn = Object.getPrototypeOf(frame.objectLiteral()) === frame.Object.prototype;
+ const templatePrototypeIsOwn = Object.getPrototypeOf(frame.template()) === frame.Array.prototype;
+ if (!objectPrototypeIsOwn || !templatePrototypeIsOwn)
+ println(`FAIL: Prototypes of another realm, round ${i}`);
+ }
+ }
+ println(`Top-level object literal prototype is per realm: ${Object.getPrototypeOf(second.topLevelObjectLiteral) === second.Object.prototype}`);
+ println(`Template object is stable in a realm: ${first.template() === first.template()}`);
+ println(`Template objects differ across realms: ${first.template() !== second.template()}`);
+ println(`Top-level template objects differ across realms: ${first.topLevelTemplate !== second.topLevelTemplate}`);
+
+ const firstLoad = first.template;
+ const firstLoadTemplate = firstLoad();
+ const firstTopLevelTemplate = first.topLevelTemplate;
+ await loadScript(first, url);
+ println(`Second load in one realm is shared: ${internals.functionsShareCode(firstLoad, first.template)}`);
+ println(`Template objects differ across loads in one realm: ${firstLoadTemplate !== first.template()}`);
+ println(`Top-level template objects differ across loads in one realm: ${firstTopLevelTemplate !== first.topLevelTemplate}`);
+ }
+
+ async function testToString(server) {
+ const source = "function spaced ( a ,b ) { /* comment */ return a+b; }";
+ const url = await server.createEcho("GET", "/compiled-script-reuse/to-string", {
+ status: 200,
+ headers: CACHEABLE,
+ body: `globalThis.spaced = ${source};\nclass C { method ( ) { } }\nglobalThis.C = C;`,
+ });
+
+ const first = await loadInNewFrame(url);
+ first.spaced(1, 2);
+ const second = await loadInNewFrame(url);
+ println(`toString is shared: ${internals.functionsShareCode(first.spaced, second.spaced)}`);
+ println(`toString of a function: ${second.spaced.toString() === source}`);
+ println(`toString of a class: ${second.C.toString()}`);
+ }
+
+ async function testFilenames(server) {
+ const body = `globalThis.stackOf = function () { return new Error("x").stack; };`;
+ const target = await server.createEcho("GET", "/compiled-script-reuse/target", {
+ status: 200,
+ headers: CACHEABLE,
+ body,
+ });
+ const redirect = await server.createEcho("GET", "/compiled-script-reuse/redirect", {
+ status: 302,
+ headers: { Location: target, "Cache-Control": "no-store" },
+ });
+
+ const firstRedirected = await loadInNewFrame(redirect);
+ const secondRedirected = await loadInNewFrame(redirect);
+ const direct = await loadInNewFrame(target);
+ println(`Redirected loads are shared: ${internals.functionsShareCode(firstRedirected.stackOf, secondRedirected.stackOf)}`);
+ println(`Stack names the request URL: ${secondRedirected.stackOf().includes(redirect)}`);
+ println(`Stack does not name the redirect target: ${!secondRedirected.stackOf().includes(target)}`);
+ println(`Stack of the direct load names the target: ${direct.stackOf().includes(target)}`);
+
+ const firstFragment = await loadInNewFrame(`${target}#one`);
+ const secondFragment = await loadInNewFrame(`${target}#two`);
+ println(`Loads with other fragments are shared: ${internals.functionsShareCode(firstFragment.stackOf, secondFragment.stackOf)}`);
+ println(`Stack names the fragment of its load: ${firstFragment.stackOf().includes("#one") && secondFragment.stackOf().includes("#two")}`);
+ }
+
+ async function testMutedErrors(server) {
+ const echo = await server.createEcho("GET", "/compiled-script-reuse/muted", {
+ status: 200,
+ headers: { ...CACHEABLE, "Access-Control-Allow-Origin": "*" },
+ body: `globalThis.fn = function () {}; throw new Error("secret");`,
+ });
+ const crossOrigin = new URL(echo);
+ crossOrigin.hostname = uniqueLocalhostHostname("muted");
+
+ async function messageOfError(attributes) {
+ const frame = newFrame();
+ const message = new Promise(resolve => {
+ frame.onerror = message => {
+ resolve(message);
+ return true;
+ };
+ });
+ await loadScript(frame, crossOrigin.href, attributes);
+ return { frame, message: await message };
+ }
+
+ const unmuted = await messageOfError({ crossOrigin: "anonymous" });
+ const muted = await messageOfError({});
+ const unmutedAgain = await messageOfError({ crossOrigin: "anonymous" });
+ println(`Muted load is shared: ${internals.functionsShareCode(unmuted.frame.fn, muted.frame.fn)}`);
+ println(`CORS load reports the error: ${unmuted.message.includes("secret")}`);
+ println(`No-CORS load mutes the error: ${muted.message}`);
+ println(`Later CORS load reports the error: ${unmutedAgain.message.includes("secret")}`);
+ }
+
+ async function testCharset(server) {
+ const url = await server.createEcho("GET", "/compiled-script-reuse/charset", {
+ status: 200,
+ headers: CACHEABLE,
+ body: `globalThis.length = "é".length; globalThis.fn = function () {};`,
+ });
+
+ const utf8 = await loadInNewFrame(url, { charset: "utf-8" });
+ const latin1 = await loadInNewFrame(url, { charset: "windows-1252" });
+ const utf8Again = await loadInNewFrame(url, { charset: "utf-8" });
+ println(`Charsets decode to: ${utf8.length}, ${latin1.length}`);
+ println(`Other charset is shared: ${internals.functionsShareCode(utf8.fn, latin1.fn)}`);
+ println(`Back to the first charset: ${utf8Again.length}`);
+ }
+
+ async function testClassicAndModule(server) {
+ const url = await server.createEcho("GET", "/compiled-script-reuse/classic-and-module", {
+ status: 200,
+ headers: { ...CACHEABLE, "Access-Control-Allow-Origin": "*" },
+ body: `globalThis.isModule = this === undefined; globalThis.fn = function () {};`,
+ });
+
+ const classic = await loadInNewFrame(url);
+ const module = await loadInNewFrame(url, { type: "module" });
+ const moduleAgain = await loadInNewFrame(url, { type: "module" });
+ const classicAgain = await loadInNewFrame(url);
+ println(`Loaded as: ${classic.isModule}, ${module.isModule}, ${moduleAgain.isModule}, ${classicAgain.isModule}`);
+ println(`Classic and module are shared: ${internals.functionsShareCode(classic.fn, module.fn)}`);
+ println(`Modules are shared: ${internals.functionsShareCode(module.fn, moduleAgain.fn)}`);
+ println(`Classic scripts are shared: ${internals.functionsShareCode(classic.fn, classicAgain.fn)}`);
+ }
+
+ async function testChangedBytes(server) {
+ const url = `${server.getStaticURL("Text/input/Cache/resources/compiled-script-changing-bytes.py")}?token=${crypto.randomUUID()}`;
+ const before = await loadInNewFrame(url);
+ const after = await loadInNewFrame(url);
+ println(`Changed bytes run: ${before.value()}, ${after.value()}`);
+ println(`Changed bytes are shared: ${internals.functionsShareCode(before.value, after.value)}`);
+ }
+
+ async function testNoStore(server) {
+ const url = await server.createEcho("GET", "/compiled-script-reuse/no-store", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript", "Cache-Control": "no-store" },
+ body: "globalThis.fn = function () {};",
+ });
+ const first = await loadInNewFrame(url);
+ const second = await loadInNewFrame(url);
+ println(`A no-store response is shared: ${internals.functionsShareCode(first.fn, second.fn)}`);
+ }
+
+ async function testPartitions(server) {
+ const url = await server.createEcho("GET", "/compiled-script-reuse/partition", {
+ status: 200,
+ headers: CACHEABLE,
+ body: "globalThis.fn = function () {};",
+ });
+ await loadInNewFrame(url);
+ println(`Stored in this partition: ${internals.compiledScriptCacheContains(url)}`);
+
+ const frameEchoURL = await server.createEcho("GET", "/compiled-script-reuse/partition-frame.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html", "Cache-Control": "no-store" },
+ body: `<!DOCTYPE html><script>
+ const before = internals.compiledScriptCacheContains(${JSON.stringify(url)});
+ const script = document.createElement("script");
+ script.src = ${JSON.stringify(url)};
+ script.onload = () => parent.postMessage({ before, after: internals.compiledScriptCacheContains(${JSON.stringify(url)}) }, "*");
+ document.head.appendChild(script);
+ <\/script>`,
+ });
+ const frameURL = new URL(frameEchoURL);
+ frameURL.hostname = uniqueLocalhostHostname("partition");
+
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const message = waitForMessage(iframe.contentWindow);
+ iframe.src = frameURL.href;
+ const { before, after } = await message;
+ println(`Found from another partition: ${before}`);
+ println(`Stored for the other partition once it loaded: ${after}`);
+ }
+
+ asyncTest(async done => {
+ const httpMemoryCacheWasEnabled = internals.setHttpMemoryCacheEnabled(true);
+ const server = httpTestServer();
+
+ await testHitsAcrossRealms(server);
+ await testRealmBoundState(server);
+ await testToString(server);
+ await testFilenames(server);
+ await testMutedErrors(server);
+ await testCharset(server);
+ await testClassicAndModule(server);
+ await testChangedBytes(server);
+ await testNoStore(server);
+ await testPartitions(server);
+
+ internals.setHttpMemoryCacheEnabled(httpMemoryCacheWasEnabled);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Cache/resources/compiled-script-changing-bytes.py b/Tests/LibWeb/Text/input/Cache/resources/compiled-script-changing-bytes.py
new file mode 100644
index 00000000000..1110c3ae5ac
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Cache/resources/compiled-script-changing-bytes.py
@@ -0,0 +1,13 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+
+def main(request, response):
+ token = request.GET.first(b"token")
+ load_count = (request.server.stash.take(token) or 0) + 1
+ request.server.stash.put(token, load_count)
+
+ response.headers.set(b"Content-Type", b"text/javascript")
+ response.headers.set(b"Cache-Control", b"no-cache")
+ return f"globalThis.value = function () {{ return {load_count}; }};".encode()