cd /news/ai-tools/crash-telemetry-for-ai-models-that-r… · home › topics › ai-tools › article
[ARTICLE · art-176520] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=↑ positive

Crash Telemetry for AI Models That Run in the Browser: What We Built and What It Caught

A developer at PixVibe, a browser-based image tools suite, built a crash telemetry system for ONNX background-removal models that run client-side via WebGPU or WASM, capturing device, stage, backend, memory and breadcrumb data per failure while sending only the first 16 bytes of a user's image to detect its real format. The system records fallback events where GPU inference fails and CPU succeeds, and in its first month surfaced that the biggest bug was in the team's own code rather than the model or hardware.

recommendation

Instrument client-side model runs with per-incident device snapshots, stage and backend tags, and breadcrumbs, and cap reports per page and per kind so a failure loop cannot flood your endpoint.

more in playbook: Running AI in production
by read16 min views8 publishedNov 26, 2026

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.

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:

InvalidStateError: The source image could not be decoded and 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.failed to allocate on 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. 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 orwasm ), 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.

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 , and the OS took the memory back.

"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')

No error tracker sees this one. The page doesn't throw. It's just gone, and a fresh copy loads.

What we do:

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.pagehide), delete the record.

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.

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

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:

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) },
  }
}

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.

From October 27 to November 26, 2026 we saw 1,581 devices on the tool pages (real users only, bots excluded).

shader-f16. requestAdapter() returned nothing. On Chrome for Windows it was 38%. "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:

std::bad_alloc, or the page gets killed. That isn't bad luck. The device can't do it. 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".

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.

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.

── more in #ai-tools 4 stories · sorted by recency
── more on @pixvibe 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/crash-telemetry-for-…] indexed:0 read:16min 2026-11-26 · —