Files

153 lines
6.5 KiB
TypeScript

/**
* R3 thresholds (plan rev 2 §5 item 4) on the shipped module: every hostile SVG of the
* corpus, plus generated floods at the caps, loaded as a sheet drawing and composed through
* `view.canvas`, answers a closed outcome with no trap (the instance stays the same), within
* 150 ms and 32 MiB of linear memory growth per case (each case in a fresh instance: the
* application loads one sheet per page; sessions never freed in one instance would add up
* their drawings, an artefact of the loop); the product drawing composes within 15 ms warm. Numbers printed for docs/development/RUST.md §9.
*/
import { readFileSync, readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { CoreRuntime, type GlueModule } from '../src/index'
import { nodeCoreSource } from '../src/node'
const ROOT = '../../../'
const SEED = `${ROOT}supabase/seed/anatomical-sheets/equine/draft/`
const HOSTILE = `${ROOT}crates/core/tests/fixtures/svg/hostile/`
const HORSE_ID = '7f767f74-3b36-51a7-8465-52dd7e2ead4a'
const path = (p: string) => fileURLToPath(new URL(p, import.meta.url))
const read = (p: string) => readFileSync(path(p), 'utf8')
const document = JSON.parse(read(`${SEED}document.json`))
const migrationMap = JSON.parse(read(`${SEED}report-migration-map.json`))
function bundle(horse: string): string {
return JSON.stringify({
status: 'draft',
ref: {
sheet_id: 'sheet',
version_id: null,
document_sha256: '0'.repeat(64),
schema_version: 2,
species_id: 'equine',
},
document,
migrationMap,
assets: { [HORSE_ID]: horse },
assetHashes: { [HORSE_ID]: '0'.repeat(64) },
})
}
const OPEN = '<svg xmlns="http://www.w3.org/2000/svg">'
/** Floods at and past the caps: nesting, nodes, markup, attributes, size, references. */
function floods(): Record<string, string> {
const attrs = (n: number) =>
Array.from({ length: n }, (_, i) => ` a${i}="${i}"`).join('')
let chain = '<path id="l0" d="M0 0h1"/>'
for (let level = 1; level <= 12; level++) {
chain += `<g id="l${level}">${`<use href="#l${level - 1}"/>`.repeat(20)}</g>`
}
return {
'deep 99,000 levels': `${OPEN}${'<g>'.repeat(99_000)}`,
'deep 65 levels': `${OPEN}${'<g>'.repeat(64)}${'</g>'.repeat(64)}</svg>`,
'nodes 20,001': `${OPEN}${'<path/>'.repeat(20_000)}</svg>`,
'brackets in a comment': `${OPEN}<!--${'<'.repeat(150_000)}--></svg>`,
'attributes 257 on one element': `${OPEN}<path${attrs(257)}/></svg>`,
'bytes 2 MiB + 1': `${OPEN}<!--${'x'.repeat(2 * 1024 * 1024)}--></svg>`,
'use chain 12 x 20': `${OPEN}${chain}</svg>`,
'text 1.9 MiB of >': `${OPEN}<title>${'>'.repeat(1_900_000)}</title></svg>`,
}
}
function corpus(): Record<string, string> {
const files = readdirSync(path(HOSTILE)).filter((f) => f.endsWith('.svg'))
return {
...Object.fromEntries(files.map((f) => [f, read(`${HOSTILE}${f}`)])),
...floods(),
}
}
async function measuredRuntime() {
let memory: WebAssembly.Memory | undefined
const source = nodeCoreSource('pkg')
const runtime = new CoreRuntime({
compile: source.compile,
importGlue: async (n) => {
const glue = await source.importGlue(n)
return {
...glue,
default: async (input: { module_or_path: WebAssembly.Module }) => {
const exports = (await glue.default(input)) as { memory?: WebAssembly.Memory }
memory = exports.memory
return exports
},
} as GlueModule
},
})
expect(await runtime.ready()).toBe(true)
return { runtime, memoryMiB: () => (memory?.buffer.byteLength ?? 0) / 1024 / 1024 }
}
describe('R3 anatomy on the shipped module', () => {
it('answers every hostile drawing with a closed outcome, no trap, within the budgets', async () => {
let slowest = { name: '', ms: 0 }
let largest = { name: '', mib: 0 }
const kinds: Record<string, string> = {}
for (const [name, text] of Object.entries(corpus())) {
const { runtime, memoryMiB } = await measuredRuntime()
const generation = runtime.generation
const before = memoryMiB()
const started = performance.now()
const session = runtime.sheet(bundle(text))
const outcome = session.call<{ svg: string }>('view.canvas', '{"viewId":"main"}')
const ms = performance.now() - started
if (ms > slowest.ms) slowest = { name, ms }
kinds[name] = outcome.ok ? 'ok' : `${outcome.kind}:${outcome.detail}`
expect(['ok', 'svg_rejected'], name).toContain(outcome.ok ? 'ok' : outcome.kind)
expect(ms, name).toBeLessThan(150)
expect(runtime.generation, name).toBe(generation)
expect(runtime.status, name).toBe('ready')
const growth = memoryMiB() - before
if (growth > largest.mib) largest = { name, mib: growth }
expect(growth, name).toBeLessThan(32)
}
console.info(
`[core-wasm] R3 hostile corpus: ${Object.keys(kinds).length} cases, slowest ${slowest.name} ` +
`${slowest.ms.toFixed(1)} ms, largest linear memory growth ${largest.name} ${largest.mib.toFixed(1)} MiB`,
)
expect(kinds['deep 99,000 levels']).toBe('svg_rejected:too_deep')
expect(kinds['use chain 12 x 20']).toBe('svg_rejected:too_complex')
// A closer overlapping its opener (`<!-->`) must not hide nesting from the prescan.
expect(kinds['comment-desync-depth.svg']).toBe('svg_rejected:too_deep')
expect(kinds['comment-desync-attributes.svg']).toBe('svg_rejected:too_complex')
})
it('composes the product drawing within budget', async () => {
const { runtime, memoryMiB } = await measuredRuntime()
let started = performance.now()
const session = runtime.sheet(bundle(read(`${SEED}assets/horse.svg`)))
expect(session.open()).toEqual({ ok: true, value: null })
const loadMs = performance.now() - started
started = performance.now()
const first = session.call<{ svg: string }>('view.canvas', '{"viewId":"main"}')
const firstMs = performance.now() - started
expect(first.ok).toBe(true)
const times: number[] = []
for (let i = 0; i < 20; i++) {
const t = performance.now()
session.call('view.canvas', '{"viewId":"head"}')
times.push(performance.now() - t)
}
times.sort((a, b) => a - b)
const warm = times[10]!
console.info(
`[core-wasm] R3 sheet handle with the drawing ${loadMs.toFixed(1)} ms, view.canvas main first ` +
`${firstMs.toFixed(1)} ms, head warm median ${warm.toFixed(2)} ms, ` +
`${first.ok ? (first.value.svg.length / 1024).toFixed(0) : '?'} KiB, linear memory ${memoryMiB().toFixed(1)} MiB`,
)
expect(warm).toBeLessThan(15)
})
})