PixVibe 如何為瀏覽器端 AI 模型建立崩潰遙測並定位故障
Crash Telemetry for AI Models That Run in the Browser: What We Built and What It Caught
PixVibe 為瀏覽器端背景移除模型建立崩潰遙測,記錄故障階段、裝置狀態與錯誤資訊,同時不會上傳圖片像素。失敗工作或頁面遭終止時,系統會傳送檔案首 16 bytes 以辨認實際格式。作者把無進度看門狗限於模型下載和載入,並為推理設 5 分鐘前景時間上限;修正後四週未再收到這類報告。
I run PixVibe, a set of image tools. Background removal runs an ONNX model directly in the user's browser: WebGPU when it works, WASM when it doesn't. Run that way, the photo is never uploaded. We never see it. (There's also a server-side option that does upload the photo. Users pick it themselves.)
That also means when it breaks, it breaks on a machine I can't see.
I found this out watching Microsoft Clarity recordings. I saw people upload a photo, wait, and leave. Some got an error. Some just watched the page reload itself. Our error logs had almost nothing. I didn't know if it was the model, the GPU, the phone, or our code.
So we built crash telemetry for the model runs. It records what was going on when a run failed, but it never uploads the image. The only bytes of the file it sends are the first 16, to detect the real format. Below is how it works, with simplified code, and what it found in the first month. The biggest bug it found was ours.
Why window.onerror wasn't enough
A normal error tracker catches exceptions and sends a stack trace. With a model running in the browser, most of what went wrong for us never showed up there:
- The page gets killed. A phone runs out of memory while loading a 90 MB model, and the OS reloads the tab. Nothing throws. Your code never runs again.
- The GPU fails quietly. WebGPU times out, the code falls back to the CPU, the job finishes several times slower. Nothing broke, so nothing got reported.
-
The error you show isn't the error that happened. We catch
InvalidStateError: The source image could not be decodedand show "We couldn't read this image". If you report the friendly text, the real cause is gone. With four UI languages it's worse: one bug becomes four. -
The error alone tells you almost nothing. The same
failed to allocateon a 2 GB Android phone and on a 32 GB desktop are two different problems. You need to know what the device looked like at that moment.
What goes into one incident
We call one failure an incident. Our rule: collect more than you think you need. Every time I sat down to dig into a problem, I wanted some detail we hadn't captured, and you can't go back for it later. The limit is privacy, which I cover at the end.
Each incident has:
| Group | Fields |
|---|---|
| What failed | incident kind, the original error name and message, first 10 lines of the stack |
| Where | stage (decode, model download, model init, inference, encode), backend (webgpu or wasm), model |
| The file | size, MIME type, extension, dimensions; for failed jobs and killed pages also the first 16 bytes and the real format detected from them. Never the file name, and nothing of the file beyond those 16 bytes |
| The moment | JS heap used, tab visible or hidden, online or not, time since page load |
| The device | browser and OS, cores, memory, GPU, WebGPU status, screen, network, cross-origin isolation |
| The history | the last 50 breadcrumbs |
We keep a separate device profile table too, but every incident carries its own copy of the device snapshot. One row has the whole picture, no joins.
An incident is also broader than an error. If the GPU fails and the CPU fallback succeeds, the user sees nothing wrong, and we still record it. That fallback is where the speed goes.
The reporter, simplified:
const API = '/api/incident'
const MAX_BODY = 60 * 1024
const MAX_PER_PAGE = 40
const MAX_PER_KIND = 10
const sent = { total: 0, byKind: new Map<string, number>() }
export function reportIncident(input: IncidentInput): void {
try {
// A real failure doesn't produce 40 reports. A loop does.
if (sent.total >= MAX_PER_PAGE) return
const n = (sent.byKind.get(input.kind) ?? 0) + 1
if (n > MAX_PER_KIND) return
sent.byKind.set(input.kind, n)
sent.total++
const err = describeError(input.error)
const run = currentRun()
// Capture the moment synchronously. After the first await
// the state has already moved on.
const body = {
kind: input.kind,
stage: input.stage ?? run?.stage ?? 'unknown',
backend: input.backend ?? run?.backend ?? '',
errorName: err.name,
errorMessage: err.message,
errorStack: err.stack,
memUsedMB: usedHeapMB(),
visible: document.visibilityState === 'visible',
online: navigator.onLine,
uptimeMs: Math.round(performance.now()),
breadcrumbs: recentCrumbs(50),
env: deviceSnapshot(),
extra: { ...err.fields, ...input.extra },
fileBytes: input.file?.size ?? 0,
fileType: input.file?.type ?? '',
fileMagic: '',
}
if (input.file && input.sniff) { // failed jobs and killed pages only
sniffHeader(input.file) // reads only the first 16 bytes
.then((magic) => { body.fileMagic = magic })
.finally(() => send(body))
} else {
send(body)
}
} catch {
// Telemetry must never break the page.
}
}
async function send(body: Record<string, unknown>) {
try {
let json = JSON.stringify(body)
// Too big? Drop the least useful parts first.
if (json.length > MAX_BODY) { body.errorStack = ''; json = JSON.stringify(body) }
if (json.length > MAX_BODY) { body.breadcrumbs = (body.breadcrumbs as unknown[]).slice(-20); json = JSON.stringify(body) }
if (json.length > MAX_BODY) { body.extra = {}; json = JSON.stringify(body) }
await fetch(API, {
method: 'POST',
keepalive: true, // finishes even if the tab is closing
headers: { 'Content-Type': 'application/json' },
body: json,
})
} catch { /* silent */ }
}
keepalive matters more than it looks. Without it, the report you send right before the tab closes is the one you lose, and that's often the interesting one. The function returns nothing and never throws, so you can drop it into any catch without thinking.
Breadcrumbs
The error tells you what failed. Breadcrumbs tell you what the user was doing. Each one is tiny: upload, option changed, start, stage changed, fell back to CPU, done, failed, tab hidden, tab visible. A ring buffer keeps the last 50:
export type Crumb = { t: number; k: string; d?: Record<string, string | number | boolean> }
const MAX = 50
const buf: Crumb[] = []
export function crumb(k: string, d?: Record<string, unknown>): void {
const c: Crumb = { t: Math.round(performance.now()), k }
if (d) c.d = shortData(d) // short scalars only: max 8 keys, strings cut at 64 chars
buf.push(c)
if (buf.length > MAX) buf.splice(0, buf.length - MAX)
}
export function recentCrumbs(n = MAX): Crumb[] {
return buf.slice(-n).map((c) => ({ ...c, d: c.d && { ...c.d } }))
}
document.addEventListener('visibilitychange', () =>
crumb('visibility', { state: document.visibilityState }))
window.addEventListener('pagehide', () => crumb('nav', { v: 'pagehide' }))
The visibility crumb turned out to be the most useful line in the whole system. On phones, the last thing before a dead page is very often "tab hidden". The user switched to another app while the model was loading, and the OS took the memory back.
Stages
"Background removal failed" is useless. "Failed during model init on the WASM backend" tells you where to look.
The engine reports which stage it's in. It doesn't know or care which tool it's running for. The tool shell registers that once when a job starts:
export type RunStage =
'upload' | 'decode' | 'model_download' | 'model_init' | 'infer' | 'encode' | 'unknown'
type RunState = { tool: string; seq: number; stage: RunStage; backend?: string; model?: string; mem?: number; crumbs: Crumb[] }
let current: RunState | null = null
const listeners = new Set<(s: RunState | null) => void>()
export function runStart(tool: string, seq: number) {
current = { tool, seq, stage: 'unknown', crumbs: [] }
crumb('start', { tool, seq })
emit()
}
export function stage(s: RunStage, extra?: { backend?: string; model?: string }) {
crumb('stage', { s, ...extra })
if (!current) return
current.stage = s
if (extra?.backend) current.backend = extra.backend
if (extra?.model) current.model = extra.model
current.mem = usedHeapMB()
current.crumbs = recentCrumbs(15)
emit()
}
export function runEnd() { current = null; emit() }
export const currentRun = () => current
export const onRunChange = (cb: (s: RunState | null) => void) => { listeners.add(cb); return () => listeners.delete(cb) }
function emit() { for (const cb of listeners) { try { cb(current) } catch {} } }
In the engine it's one line per step:
stage('model_download', { model: 'isnet' })
const session = await loadModel()
stage('infer', { backend: session.backend })
const mask = await session.run(input)
stage('encode')
A flight recorder for pages the browser killed
No error tracker sees this one. The page doesn't throw. It's just gone, and a fresh copy loads.
What we do:
- When a job starts, write a small record to
localStorage(tool, file name and dimensions, run number, options) and put the original image in IndexedDB, in the user's own browser. Nothing here is sent anywhere. - On every stage change, rewrite the record: stage, backend, memory, last 15 breadcrumbs. A few hundred bytes.
- When the job ends, or the page leaves normally (
pagehide), delete the record. - When the tool page opens, look for records left by other tabs. If one is there and its tab doesn't answer, that tab died mid-job.
const PREFIX = 'run:'
const TAB = crypto.randomUUID()
const keyOf = (tool: string, tab = TAB) => `${PREFIX}${tool}:${tab}`
const channel = new BroadcastChannel('run-guard')
const active = new Set<string>()
channel.onmessage = (e) => {
if (e.data?.type === 'ping' && active.has(e.data.tool)) {
channel.postMessage({ type: 'pong', tool: e.data.tool, tab: TAB })
}
}
// Leaving normally is not a crash.
window.addEventListener('pagehide', () => {
for (const tool of active) localStorage.removeItem(keyOf(tool))
})
onRunChange((s) => {
if (!s || !active.has(s.tool)) return
const prev = JSON.parse(localStorage.getItem(keyOf(s.tool)) || '{}')
localStorage.setItem(keyOf(s.tool), JSON.stringify({ ...prev, ...s }))
})
export function beginRun(tool: string, info: { seq: number }, file: File) {
active.add(tool)
localStorage.setItem(keyOf(tool), JSON.stringify({ ...info, ts: Date.now() }))
saveImage(`crash:${tool}`, file) // IndexedDB; if this fails, fine
runStart(tool, info.seq)
}
export function endRun(tool: string) {
active.delete(tool)
runEnd()
localStorage.removeItem(keyOf(tool))
deleteImage(`crash:${tool}`) // don't leave the user's image on disk
}
export async function takeCrashedRun(tool: string) {
const foreign = Object.keys(localStorage)
.filter((k) => k.startsWith(`${PREFIX}${tool}:`) && k !== keyOf(tool))
if (!foreign.length) return null
// Ask the other tabs if they're still working.
const alive = new Set<string>()
const onPong = (e: MessageEvent) => {
if (e.data?.type === 'pong' && e.data.tool === tool) alive.add(keyOf(tool, e.data.tab))
}
channel.addEventListener('message', onPong)
channel.postMessage({ type: 'ping', tool })
await new Promise((r) => setTimeout(r, 400))
channel.removeEventListener('message', onPong)
let hit = null
for (const k of foreign) {
if (alive.has(k)) continue
const v = JSON.parse(localStorage.getItem(k) || 'null')
if (v && (!hit || v.ts > hit.ts)) hit = v
localStorage.removeItem(k) // read once, then delete
}
if (!hit) return null
const file = await takeImage(`crash:${tool}`) // also deletes it
return { ...hit, file }
}
On page load the tool calls takeCrashedRun(). If it gets something back, we send a page_killed incident with the stage, backend, model, memory and breadcrumbs from the record, and we put the user's image back in the workspace with a short explanation.
We don't rerun the job. On a phone that just ran out of memory, a rerun will most likely crash again, and now the user is stuck in a reload loop. Instead, the device gets a mark for seven days: the next upload doesn't start the local model automatically, it asks first (try again here, or use the server-side option). One successful local run clears the mark.
Two things bit us here. Without the BroadcastChannel ping, a second open tab looks exactly like a crashed one; 400 ms is plenty for a live tab to answer. And older browsers don't have BroadcastChannel at all, so there we only treat records older than two minutes as crashes. I'd rather miss a crash than invent one.
Signatures
Raw incidents are noisy. The same bug shows up with different buffer sizes, addresses and URLs. Two rules turned hundreds of reports into a list I can actually read.
First, keep the original error. When you turn a browser error into a friendly message, attach the original as cause:
try {
bitmap = await createImageBitmap(blob)
} catch (e) {
throw new Error(t('errors.cannotRead'), { cause: e })
}
The reporter unwraps it. The original message is what gets grouped; the friendly one is kept on the side:
function describeError(e: unknown) {
const out = { name: '', message: '', stack: '', fields: {} as Record<string, unknown> }
if (e == null) return out
const cause = (e as { cause?: unknown }).cause
if (cause != null && typeof e === 'object') {
const inner = describeError(cause)
if (inner.message) {
inner.fields.userMessage = String((e as Error).message).slice(0, 200)
return inner
}
}
if (typeof e !== 'object') { out.message = String(e).slice(0, 500); return out }
const o = e as Record<string, unknown>
out.name = typeof o.name === 'string' ? o.name : ''
out.message = typeof o.message === 'string' ? o.message.slice(0, 500) : String(e)
out.stack = typeof o.stack === 'string' ? o.stack.split('\n').slice(0, 10).join('\n') : ''
// Keep other short fields too: code, errorCode, DOMException codes
for (const [k, v] of Object.entries(o)) {
if (['name', 'message', 'stack'].includes(k)) continue
if (typeof v === 'string') out.fields[`err_${k}`] = v.slice(0, 120)
else if (typeof v === 'number' || typeof v === 'boolean') out.fields[`err_${k}`] = v
}
return out
}
Second, normalize before hashing. On the server (Go), we clean the message and hash it together with kind, tool, stage, backend and model:
var (
sigURLRe = regexp.MustCompile(`https?://\S+`)
sigHexRe = regexp.MustCompile(`\b[0-9a-f]{6,}\b`)
sigNumRe = regexp.MustCompile(`\d+`)
sigSpaceRe = regexp.MustCompile(`\s+`)
)
func NormalizeErrorMessage(m string) string {
m = strings.ToLower(strings.TrimSpace(m))
m = sigURLRe.ReplaceAllString(m, "<url>")
// Only hex with a digit in it is an address. "facade" stays.
m = sigHexRe.ReplaceAllStringFunc(m, func(h string) string {
if strings.ContainsAny(h, "0123456789") {
return "#"
}
return h
})
m = sigNumRe.ReplaceAllString(m, "#")
m = sigSpaceRe.ReplaceAllString(m, " ")
if len(m) > 160 {
m = m[:160]
}
return m
}
func IncidentSignature(kind, tool, stage, backend, model, message string) string {
key := strings.Join([]string{kind, tool, stage, backend, model, NormalizeErrorMessage(message)}, "|")
sum := sha256.Sum256([]byte(key))
return hex.EncodeToString(sum[:8])
}
Now failed to allocate a buffer of size 90447799 and ... of size 88123456 are one signature. Stage and backend are in the key on purpose: a timeout while downloading the model and a timeout during inference are different problems with different fixes.
We only alert (a Telegram bot) when a signature hasn't been seen in 30 days. Few alerts means somebody actually reads them.
The first week: the bug was our own timeout
We turned this on October 23, 2026. In the first week, background removal had 382 successful runs and 39 failures, about 9%.
The biggest group of failures had one message: removebg timed out (no progress). 50 reports from 15 visitors in six days. That's reports, not failures. Each of these failures was reported twice (more on that bug below), so it was about 25 actual failures.
That message came from our own code. The worker pool had a watchdog: no message from the worker for 150 seconds, kill it and fail the job. It was meant to catch hung workers. But a WASM inference call is one long synchronous call. It sends nothing until it's done. On a slow CPU, a model that was working fine got killed for being quiet. The breadcrumbs showed it plainly: device after device, the gap between stage: infer and fail was almost exactly 150 seconds.
The GPU path was worse. WebGPU timed out at 120 seconds, fell back to the CPU, then hit the 150-second watchdog. Those users waited four to seven minutes and still got an error. And the timer kept running while the tab was in the background, so a phone user who switched to reply to a message came back to a failure.
What we changed on October 29:
- The "no message" watchdog only covers model download and load, where there is real progress to watch. During inference there's just a safety ceiling: 5 minutes of foreground time.
- Every timer counts foreground time only. Background time doesn't count:
export function startVisibleClock() {
let vis = 0, hid = 0
let since = performance.now()
let visible = document.visibilityState !== 'hidden'
const flush = () => {
const now = performance.now()
if (visible) vis += now - since; else hid += now - since
since = now
}
const onChange = () => { flush(); visible = document.visibilityState !== 'hidden' }
document.addEventListener('visibilitychange', onChange)
return {
visibleMs: () => { flush(); return Math.round(vis) },
hiddenMs: () => { flush(); return Math.round(hid) },
stop: () => { flush(); document.removeEventListener('visibilitychange', onChange) },
}
}
- After a GPU timeout we no longer start a full CPU run silently. The user picks: keep going on this device, or use the server-side option.
- If a device was slow last time, we say so up front instead of letting them find out after two minutes.
Result: zero no progress reports in the four weeks since the fix went out, on the evening of October 29 (UTC).
A note on the timing, because it looks better than it is. The last report came in on October 28 at 23:14 UTC, about 19 hours before the fix. Those 19 hours were just quiet: the old watchdog was still live, 20 CPU runs finished in that window, and none of them happened to hit it. Quiet stretches happened before too. October 27 had only 2 reports. So the 19 hours prove nothing; the four weeks do.
We started logging pure inference time on November 8, and since then three CPU runs took longer than 150 seconds of inference and finished fine. The slowest took 4 minutes 38 seconds. Every one of those would have been killed and reported as a failure before.
The same week also showed a bug in the telemetry itself. 149 reports were really 101 incidents. When a job failed, the engine reported it with stage and backend, then the tool shell caught the same error and reported it again with stage unknown. One failure, two signatures. Now the lowest layer that knows the most owns the report, and the layers above only report what it can't see.
A month of real devices
From October 27 to November 26, 2026 we saw 1,581 devices on the tool pages (real users only, bots excluded).
- 72% got a WebGPU adapter. 64% had
shader-f16. - 25% had the WebGPU API but
requestAdapter()returned nothing. On Chrome for Windows it was 38%. - 0 were cross-origin isolated, so 0 could use multi-threaded WASM. Every CPU run was single-threaded.
- 63% of successful background removals ran on the GPU.
"Supports WebGPU" and "you get a GPU" are not the same thing. And getting an adapter isn't the end either. Safari on iOS returns one 88% of the time, but we run iOS on the CPU on purpose: in our tests, WebKit didn't release GPU memory between inference runs, 400 to 500 MB more per image, and a batch would crash the tab.
Failure rates as the user sees them (failed runs plus killed pages), same 30 days:
| Platform | Failure rate | Users who never got one result |
|---|---|---|
| Desktop, integrated GPU | 2.6% | 3.2% |
| Desktop, discrete GPU | 3.2% | 1 of 104 |
| Mac, Apple silicon | 6.0% | 1 of 48 |
| Desktop, software rendering (no GPU acceleration) | 23.2% | 16.7% |
| Android | 19.3% | 12.1% |
| iOS / iPadOS | 25.0% | 21.4% |
Desktops are fine. Phones and low-end machines are where it hurts, and the telemetry says why:
- Devices reporting 2 GB of memory or less: 16 attempts from 9 people, zero successes. Building the session for a 90 MB model fails with
std::bad_alloc, or the page gets killed. That isn't bad luck. The device can't do it. - Desktop "software rendering" machines mostly fail because the browser has no WASM SIMD, so the CPU path can't start either. Today they download the model first and then fail. They should be told before the download.
- On iOS it isn't big images. Pages killed during CPU inference had images of 2.2 megapixels on average. Separately, 14 model downloads on iOS were interrupted, and 8 of those happened while the page was in the background.
I'm now deciding whether to skip local inference entirely on those first two groups. Without the device snapshot in each incident, I'd only know that "some phones fail".
Where the privacy line is
The point of running the model locally is that the user's image never gets uploaded. That's the line. Error and usage data does get sent, because without it we're guessing.
- Never in a report: file names, pixels, any part of the file beyond its first 16 bytes, URL parameter values, IP addresses.
- Collected: for failed jobs and killed pages, the first 16 bytes of the file. That's the format header, enough to tell a real JPEG from a renamed HEIC, and no image data. Also extension, MIME type, dimensions, size, device capabilities, browser language and time zone, error messages, breadcrumbs with short values only.
- The IP address isn't stored with the incident or the device profile. Our backend uses it for one thing: an hourly rate limit on the report endpoint, a counter in Redis that expires after two hours. Like every request to the site, the report also shows up in the web server's access log.
- The device ID is the first 16 hex characters of a SHA-256 over the stable parts of the device configuration. It's the key of the device profile table, and incidents and usage events carry it, so I can count by device: that's where "1,581 devices" and the failure rates above come from. Identical devices share an ID and a browser update changes it, so those counts are close, not exact. Every visitor gets a random ID in a cookie; for signed-in users we also store the user ID, never an email or a name. Country is the two-letter code from the CDN's request header, filled in by the server; if the header is missing, it's left empty. The server trims every field, strips control characters, and caps JSON depth and size.
- The image saved for crash recovery stays in the user's own IndexedDB, with its file name. We don't ask first; it never leaves the browser. Files over 50 MB aren't saved at all. It's deleted a moment after the job ends (1.5 seconds, so a multi-page PDF isn't rewritten for every page) or, as a best effort, when the page closes normally. After a crash, it's deleted as soon as the tool page reads it back. If the user never opens that tool again, any PixVibe page they open after seven days deletes it. If they never come back at all, it stays in their browser until they clear site data.
If you're building this
What I'd do first, in order: put a device snapshot in every incident, keep the original error with { cause }, and write the flight-recorder record on every stage change. Those three found almost everything above. And look hard at any timeout you wrote for work that can't report progress. Ours was the single biggest source of failures, and no user could have told us.
I used AI tools to help draft and edit this post. The code is simplified from our production code, and every number comes from our own production data.
來源:DEV Community · dev.to