test(tests): R4.2e browser measurements of the Rust import (module worker page, same perimeter as the TS baseline)

r4-import.mjs runs the 226 baseline files and the hostile classes through a disposable
module worker calling SheetHandle.import_pdf in Chromium 156, Firefox 157 and WebKit 27.2
under the RSS watchdog (not a guaranteed limit); compare-imports.mjs prints TS vs Rust;
serve.mjs gains opt-in mounts (/r4/, /pkg/). Results 2026-10-18-r4-import.json: 666/678
agreements, the 12 others are the 4 declared files; W4 met (max 68 MiB linear); the
1 GiB ceiling traps in every engine.
This commit is contained in:
bchanot committed 2026-10-18 16:58:42 +02:00
1 parent cad485b13c
commit c84186b032
14 files changed
+3135 -17

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>R4 import worker</title>
<link rel="icon" href="data:," />
<script type="module" src="/r4/main.js"></script>
</head>
<body>
<h1>R4 import worker (measurement page)</h1>
<p>
One module worker per import (plan §B.1.5), driven by
scripts/browser/r4-import.mjs through <code>window.r4Import</code>.
</p>
<input id="file" type="file" hidden />
<pre id="status">loading</pre>
</body>
</html>
+293
View File
@@ -0,0 +1,293 @@
// Main thread of the R4 measurement page (R4.2e). Compiles the module once
// (`WebAssembly.compileStreaming`), routes a picked file as HomeRoute does
// (first KiB: PDF magic, JSON object or `.json` name), then runs each import
// in a module worker created for it (plan §B.1.5): the compiled Module
// posted by structured clone (or, when an engine refuses the clone, the
// worker fetches the URL, and the refusal is recorded), the File and the
// sheet bundle text posted on `ready`, `terminate()` in every case.
//
// window.r4Import(fileOrBytes, bundleJson, mode = 'auto' | 'pdf' | 'copy')
// window.r4Proof('ceiling' | 'cap_off', bundleJson, file?)
// window.r4LastResult, window.r4Page (CSP violations, long tasks, compile)
const WASM_URL = '/pkg/faunosteo_wasm_bg.wasm'
const IMPORT_WORKER = '/r4/worker.js'
const PROOFS_WORKER = '/r4/proofs-worker.js'
const MiB = 1024 * 1024
const LIMITS = { pdfBytes: 50 * MiB, copyBytes: 16 * MiB }
const TIMEOUTS = { startMs: 10_000, taskMs: 120_000 }
const SNIFF_BYTES = 1024
const PDF_MAGIC = '%PDF-'
const page = {
csp: [],
longTaskSupported: false,
longTasks: [],
file: null,
changeAt: null,
limits: LIMITS,
timeouts: TIMEOUTS,
}
window.r4Page = page
const now = () => performance.now()
const describe = (error) =>
`${error?.name ?? 'Error'}: ${error?.message ?? error}`
.split('\n')[0]
.slice(0, 200)
function listen() {
document.addEventListener('securitypolicyviolation', (event) =>
page.csp.push(`${event.effectiveDirective} ${event.blockedURI}`),
)
document.getElementById('file').addEventListener('change', (event) => {
page.file = event.target.files?.[0] ?? null
page.changeAt = now()
})
const types = PerformanceObserver.supportedEntryTypes ?? []
if (!types.includes('longtask')) return
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
page.longTasks.push({ start: entry.startTime, ms: entry.duration })
}
}).observe({ type: 'longtask' })
page.longTaskSupported = true
}
async function compileModule() {
const startedAt = now()
try {
const module = await WebAssembly.compileStreaming(fetch(WASM_URL))
return { module, ms: now() - startedAt, error: null }
} catch (error) {
return { module: null, ms: now() - startedAt, error: describe(error) }
}
}
/** HomeRoute: first non-blank byte after an optional UTF-8 BOM. */
function firstContentByte(head) {
const bom = head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf
const blank = [0x20, 0x09, 0x0a, 0x0d]
return head.slice(bom ? 3 : 0).find((b) => !blank.includes(b))
}
/** HomeRoute's routing, from the first KiB only. */
async function routeOf(file) {
const head = new Uint8Array(await file.slice(0, SNIFF_BYTES).arrayBuffer())
const magic = new TextDecoder('latin1').decode(head.slice(0, 5))
if (magic === PDF_MAGIC) return 'pdf'
if (firstContentByte(head) === 0x7b) return 'copy'
const json =
file.name.toLowerCase().endsWith('.json') ||
file.type === 'application/json'
return json ? 'copy' : 'pdf'
}
/** The envelope's facts the comparison needs (never the report itself). */
function summaryOf(value) {
const read = value?.read ?? null
const rebase = value?.rebase ?? null
return {
origin: read?.origin ?? null,
migrated: read?.migrated ?? null,
snapshotRejected: read?.snapshotRejected ?? null,
archive: Boolean(read ? read.archive : value?.archive),
rebased: rebase?.rebased ?? null,
unresolved: rebase
? rebase.unresolvedZones + rebase.unresolvedFindings
: null,
}
}
/** The result message: the envelope parsed here, as the app will parse it. */
function resultOf(message) {
const startedAt = now()
const envelope = JSON.parse(message.out)
const parseMs = now() - startedAt
const head = { parseMs, outChars: message.out.length, diag: message.diag }
if (envelope.ok) {
return { outcome: 'ok', ...head, summary: summaryOf(envelope.value) }
}
const detail = JSON.stringify(envelope.detail ?? null).slice(0, 200)
return { outcome: 'refused', kind: envelope.kind, detail, ...head }
}
/** An `error` event at the Worker: an ErrorEvent, or a bare load failure. */
function errorText(event) {
if (!event.message) return `${event.type} event without message`
const where = event.filename ? ` (${event.filename}:${event.lineno})` : ''
return `${event.message}${where}`.slice(0, 200)
}
/** One worker, one task; the first settlement wins, the worker dies. */
class WorkerRun {
constructor({ url, protocol, module, task }) {
this.url = url
this.protocol = protocol
this.module = module
this.task = task
this.createdAt = now()
this.readyAt = null
this.transfer = null
this.cloneError = null
this.workerCsp = []
this.done = new Promise((resolve) => (this.resolve = resolve))
}
start() {
try {
this.worker = new Worker(this.url, { type: 'module' })
} catch (error) {
return this.settle(this.failure('start', 'worker_unavailable', error))
}
this.worker.onmessage = (event) => this.onMessage(event.data)
this.worker.onerror = (event) =>
this.settle(this.failure(this.phase(), 'worker_error', errorText(event)))
this.worker.onmessageerror = () =>
this.settle(this.failure(this.phase(), 'messageerror', null))
this.arm(TIMEOUTS.startMs, 'start')
this.postInit()
return this.done
}
phase() {
return this.readyAt === null ? 'start' : 'task'
}
failure(phase, kind, error) {
const text = typeof error === 'string' ? error : error && describe(error)
return { outcome: 'failed', phase, kind, error: text ?? null }
}
arm(ms, phase) {
clearTimeout(this.timer)
this.timer = setTimeout(
() => this.settle({ outcome: 'timeout', phase }),
ms,
)
}
/** Import: init (Module clone, else URL), then the task on `ready`. */
postInit() {
if (this.protocol === 'proof') {
this.transfer = 'worker fetch'
this.arm(TIMEOUTS.taskMs, 'task')
return this.post(this.task)
}
if (!this.module) return this.postUrl()
try {
this.worker.postMessage({ v: 1, type: 'init', module: this.module })
this.transfer = 'clone'
} catch (error) {
this.cloneError = describe(error)
this.postUrl()
}
}
postUrl() {
this.transfer = 'fetch'
this.post({ type: 'init', url: WASM_URL })
}
post(message) {
try {
this.worker.postMessage({ v: 1, ...message })
} catch (error) {
this.settle(this.failure(this.phase(), 'post_failed', error))
}
}
onMessage(message) {
if (message?.csp) this.workerCsp = message.csp
if (message?.type === 'clone_failed') {
this.cloneError = 'messageerror in the worker (Module not cloned)'
return this.postUrl()
}
if (message?.type === 'ready') return this.onReady(message)
if (message?.type === 'failed') {
return this.settle({ outcome: 'failed', ...message })
}
if (message?.type === 'proof') {
return this.settle({ outcome: 'proof', value: message.value })
}
if (message?.type === 'result') this.settle(resultOf(message))
}
onReady(message) {
this.readyAt = now()
this.readyLinearBytes = message.linearBytes
this.via = message.via
this.arm(TIMEOUTS.taskMs, 'task')
this.post(this.task)
}
settle(result) {
if (this.settledAt !== undefined) return
this.settledAt = now()
clearTimeout(this.timer)
this.worker?.terminate()
const { v: _v, type: _type, csp: _csp, ...rest } = result
this.resolve({ ...rest, ...this.facts() })
}
facts() {
const started = this.readyAt === null ? null : this.readyAt - this.createdAt
return {
startMs: started,
workerMs: this.settledAt - this.createdAt,
transfer: this.transfer,
via: this.via ?? null,
cloneError: this.cloneError,
readyLinearBytes: this.readyLinearBytes ?? null,
workerCsp: this.workerCsp,
}
}
}
const asFile = (input) =>
input instanceof Blob ? input : new File([input], 'input.pdf')
async function r4Import(input, bundleJson, mode = 'auto') {
const calledAt = now()
const file = asFile(input)
const route = mode === 'auto' ? await routeOf(file) : mode
const { module } = await window.r4Ready.compiled
const task = { type: 'task', route, file, sheet: bundleJson, limits: LIMITS }
const run = new WorkerRun({
url: IMPORT_WORKER,
protocol: 'import',
module,
task,
})
const result = { route, ...(await run.start()) }
result.pageMs = now() - calledAt
window.r4LastResult = result
document.getElementById('status').textContent = JSON.stringify(result)
return result
}
async function r4Proof(name, bundleJson, input = null) {
const calledAt = now()
const file = input && asFile(input)
const task = { type: 'proof', name, sheet: bundleJson, file }
const run = new WorkerRun({
url: PROOFS_WORKER,
protocol: 'proof',
module: null,
task,
})
const result = { name, ...(await run.start()), pageMs: now() - calledAt }
window.r4LastResult = result
return result
}
listen()
const compiled = compileModule()
window.r4Ready = {
compiled,
facts: compiled.then(({ ms, error }) => ({ compileMs: ms, error })),
}
window.r4Import = r4Import
window.r4Proof = r4Proof
compiled.then(({ error }) => {
document.getElementById('status').textContent = error ?? 'ready'
})
@@ -0,0 +1,72 @@
// Memory-protection proofs of the R4 measurement page (R4.2e), on the proofs
// build (packages/core-wasm/pkg-proofs, the R0 and R4.2e test exports): the
// 1 GiB linear ceiling (`allocate_for_test`: 256 MiB returns, 1100 MiB must
// trap) and the cost the OD-3 value cap prevents (`import_pdf_unbounded_
// for_test`, the import with the cap off). The worker fetches and compiles
// the module itself, so the worker's CSP is exercised too.
import init, {
allocate_for_test,
import_pdf_unbounded_for_test,
} from '/pkg-proofs/faunosteo_wasm.js'
const WASM_URL = '/pkg-proofs/faunosteo_wasm_bg.wasm'
const cspViolations = []
let memory = null
self.addEventListener('securitypolicyviolation', (event) => {
cspViolations.push(`${event.effectiveDirective} ${event.blockedURI}`)
})
const linearBytes = () => memory?.buffer.byteLength ?? null
const describe = (error) =>
`${error?.name ?? 'Error'}: ${error?.message ?? error}`
.split('\n')[0]
.slice(0, 200)
/** The call's value, or the throwable's name and message. */
function attempt(work) {
const startedAt = performance.now()
try {
const value = work()
return { returned: value, ms: performance.now() - startedAt }
} catch (error) {
return { threw: describe(error), ms: performance.now() - startedAt }
}
}
function ceiling() {
const first = attempt(() => allocate_for_test(256))
const linearAfterFirst = linearBytes()
const second = attempt(() => allocate_for_test(1100))
return { first, linearAfterFirst, second, linearBytes: linearBytes() }
}
async function capOff({ sheet, file }) {
const bytes = new Uint8Array(await file.arrayBuffer())
const run = attempt(() => import_pdf_unbounded_for_test(sheet, bytes))
return { run, linearBytes: linearBytes() }
}
async function prove(message) {
const exports = await init({ module_or_path: WASM_URL })
memory = exports.memory
const linearAtStart = linearBytes()
const value = message.name === 'ceiling' ? ceiling() : await capOff(message)
return { linearAtStart, ...value }
}
self.onmessage = (event) => {
prove(event.data).then(
(value) =>
self.postMessage({ v: 1, type: 'proof', value, csp: cspViolations }),
(error) =>
self.postMessage({
v: 1,
type: 'failed',
phase: 'start',
kind: 'other',
error: describe(error),
csp: cspViolations,
}),
)
}
+114
View File
@@ -0,0 +1,114 @@
// Import worker of the R4 measurement page (R4.2e), the shape plan §B.1.5
// gives the application at R4.3: a module worker created for one import,
// the glue imported statically, the module received from the main thread
// (structured clone) or fetched from its URL, the File read here, one
// SheetHandle, `import_pdf` or the strict decode then `draft.restore`, one
// result message. The main thread terminates it in every case.
import init, { SheetHandle } from '/pkg/faunosteo_wasm.js'
const cspViolations = []
let memory = null
self.addEventListener('securitypolicyviolation', (event) => {
cspViolations.push(`${event.effectiveDirective} ${event.blockedURI}`)
})
const linearBytes = () => memory?.buffer.byteLength ?? null
function post(message) {
self.postMessage({ v: 1, ...message, csp: cspViolations })
}
function describe(error) {
const text = `${error?.name ?? 'Error'}: ${error?.message ?? error}`
return text.split('\n')[0].slice(0, 200)
}
/** Plan §B.1.5 kinds: a trap, an allocation failure, anything else. */
function kindOf(error) {
const name = error?.name ?? ''
if (name === 'RuntimeError' || name === 'InternalError') return 'trap'
if (name !== 'RangeError') return 'other'
return /memory|alloc|buffer/i.test(error.message) ? 'alloc' : 'trap'
}
function fail(phase, kind, error) {
post({ type: 'failed', phase, kind, error: describe(error) })
}
/** Instantiates once; `module` when the clone arrived, else the URL. */
async function start({ module, url }) {
const exports = await init({ module_or_path: module ?? url })
memory = exports.memory
post({
type: 'ready',
via: module ? 'module' : 'url',
linearBytes: linearBytes(),
})
}
/** A refusal decided here, in the envelope's shape. */
const refusal = (kind, detail) => JSON.stringify({ ok: false, kind, detail })
/** `import_pdf`, or the strict UTF-8 decode then `draft.restore`. */
function runImport(handle, route, bytes) {
if (route === 'pdf') return handle.import_pdf(new Uint8Array(bytes))
let text
try {
text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
} catch {
return refusal('invalid_utf8', 'strict TextDecoder refused the copy')
}
const input = JSON.stringify({ draft: text, archive: null })
return handle.call('draft.restore', input)
}
/** One step whose throwable becomes a `failed` message of its own kind. */
async function step(kind, work) {
try {
return { ok: true, value: await work() }
} catch (error) {
fail('task', kind ?? kindOf(error), error)
return { ok: false }
}
}
async function task({ route, file, sheet, limits }) {
const startedAt = performance.now()
const limit = route === 'copy' ? limits.copyBytes : limits.pdfBytes
if (file.size > limit) {
const out = refusal('file_too_large', `${file.size} > ${limit}`)
return post({ type: 'result', out, diag: { precheck: true } })
}
const bytes = await step('read', () => file.arrayBuffer())
if (!bytes.ok) return
const readAt = performance.now()
const handle = await step('sheet', () => new SheetHandle(sheet))
if (!handle.ok) return
const sheetAt = performance.now()
const linearBeforeRun = linearBytes()
const out = await step(null, () =>
runImport(handle.value, route, bytes.value),
)
if (!out.ok) return
const doneAt = performance.now()
const diag = {
ms: doneAt - startedAt,
readMs: readAt - startedAt,
sheetMs: sheetAt - readAt,
runMs: doneAt - sheetAt,
linearBeforeRun,
linearBytes: linearBytes(),
}
post({ type: 'result', out: out.value, diag })
}
self.onmessage = (event) => {
const message = event.data
const phase = message?.type === 'init' ? 'start' : 'task'
const work = phase === 'start' ? start(message) : task(message)
work.catch((error) => fail(phase, kindOf(error), error))
}
self.onmessageerror = () => post({ type: 'clone_failed' })
self.onunhandledrejection = (event) =>
fail('task', kindOf(event.reason), event.reason)