Docs

Monitoring Workers

A Work request runs a job of a registered task in a Web Worker (see Workers). The runtime’s monitor shows what that costs: where each job’s time went, how busy the pool is, what cancellations, timeouts and crashes cost, and how much memory the worker instances hold. It only observes. Turning it on or subscribing to it never changes which job runs when, what it returns or what the app sees.

Everything here is JavaScript run by the page that mounts the app (its index.html, a test harness or a benchmark). The app itself needs nothing.

Turning it on

Every runtime has a monitor, runtime.monitor, and it is always counting. The monitor mount option only sets what it keeps and how loudly it reports:

const runtime = await mountRocEngineApp({
  wasmUrl: "app.wasm",
  root: document.getElementById("app"),
  monitor: {
    history: 128,      // job records kept for snapshot().recent (0 to 1024)
    userTiming: false, // add performance.measure entries for DevTools
    payloads: false,   // copy input and output bytes into events
  },
});

The monitor has three surfaces:

  • runtime.monitor.snapshot() returns plain data you can log, console.table or JSON.stringify.
  • runtime.monitor.subscribe(listener, { turns }) reports lifecycle events as they happen and returns the function that unsubscribes.
  • runtime.monitor.reset() starts a new measurement window.

The timeline of a job

The monitor stamps each job at every step from the request to its applied result, and turns those stamps into spans. The spans add up to the job’s total:

SpanFrom → toWhat it is
heldissued → handed to the poolManual mode or manualWork only: waiting for runEffect
queuehanded to the pool → postedWaiting for a free worker
coldposted → instance readyStarting a worker: its script and its instance. 0 for a warm worker
toWorkerposted → receivedThe message reaching a warm worker (null when cold)
stagereceived (ready, for a cold job) → stagedCopying the input into the worker’s instance and minting handles for the files it names (their bytes are read by the job itself, during compute)
computestaged → returnedThe task itself (work(), or ask() for a preparation’s task), its reads of files included
copyOutreturned → posted backCopying the output out of the instance
fromWorkerposted back → received by the pageThe message coming back
resultWaitreceived → result turn startsThe page was busy with another turn
resultTurnresult turnThe app’s reaction and the DOM it changed

The page receives a worker’s answer at t.answer in the job record. That stamp includes only arrival; resultWait and resultTurn account for delivering it to the engine and applying its commands.

A job’s timeout runs from the moment the request is performed, so it covers queueing and cold start as well as compute. A held job (manual mode, or the manualWork mount option) has no timeout timer: a spec’s time is manual, and expireEffect(id) expires it instead.

held means this on a job everywhere it appears (its span, its phase and the flag on job-issue): the job waits for runEffect. On an instance, held is something else, the name of the preparation whose state the instance keeps.

A job’s inputBytes counts its payload alone, which refers to the files its input holds but does not carry them: the job reads what it needs of them in compute.

firstJobOnInstance marks a worker’s first job. That job’s compute also pays for the browser compiling the task’s code the first time it runs, so compare later jobs when you judge a task’s speed.

Clocks

Every time the monitor reports is the page’s performance.now() in milliseconds. That is the clock User Timing, PerformanceObserver and the DevTools Performance panel use. A worker has its own clock. When its instance is ready it reports its performance.timeOrigin, and the monitor converts its stamps by adding the difference between the two origins.

Browsers coarsen timers: in Chrome to 0.1 ms when the page is not cross-origin isolated. So a span between two threads (toWorker, fromWorker) is good to about ±0.2 ms. Spans are reported raw, never clamped, and one shorter than the resolution may read 0 or even slightly negative. The page reads its clock for posted just before it posts the job, because the worker may receive it before the page’s thread runs again.

The snapshot

const s = runtime.monitor.snapshot();
console.table(s.recent.map((j) => ({ id: j.id, task: j.task, outcome: j.outcome, ...j.ms })));
FieldMeaning
mode"workers", "inline" (the page’s thread) or "unavailable" (no Worker)
poolinstances, spawning, idle, busy (holding a job, starting ones included) and queued, now; their peak; and the time integrals busyMs, aliveMs, queuedMs
jobsCounts by outcome (done, lost, timeout, cancelled, unavailable); inFlight; wastedMs (time on instances by jobs that never delivered output); input and output bytes; lateAnswers (always 0 in a healthy pool); for preparations’ tasks, prepared (jobs that prepared a state), reused (jobs run on a kept state) and prepareMs (total preparation time)
instancesspawns, respawns (spawns beyond the most instances ever live at once), ended by cause (cancel, timeout, fault, executor, unmount, contained, and retired for a worker over maxWorkerBytes), evicted: prepared states let go by cause (replaced by another preparation, released with their file), and the live and retired instances: thread, state, spawn and ready times, instantiation time, jobs served, busy time, linear memory and its peak, the host’s live allocations and bytes, and held, the name of the preparation whose state it keeps (or null)
histHistograms of queue, cold, compute, total, resultTurn and prepare, in fixed 1-2-5 millisecond buckets (edges, counts, n, sum, min, max)
tasksPer task, by name: jobs, outcomes, bytes, and queue, compute and total histograms (job records name their task in task)
recentThe last history job records, with every stamp (t) and span (ms). The record of a preparation’s task’s job says whether it prepared ("prepare") or reused a kept state ("reuse"; null for other tasks), and prepareMs, how long preparing took (also ms.prepare; null when it reused); compute is then the task alone. finished is true for a cancelled job whose task’s on_cancel: Finish let it complete
pageThe page instance’s linear memory, live allocations and bytes, and turns; captureRefused, pointer captures the browser refused; textRefused, events not delivered because their text was not well-formed Unicode
engineThe engine’s effect counters, when the engine’s work record carries them; otherwise null
portsPer port the app used, by name: sent (commands), calls, answered, threw, timedOut, cancelled (stopped by the app or by teardown), subscribed, messages (delivered to the app), coalesced (replaced under Latest before delivery), refusedEmits (emit returned false under Every(n)), tooLarge, closed (ended by the JavaScript), and faults (failures of command handlers and unsubscribe functions, which the app never sees). Counted by the runtime since mount; at most one entry per declared port, so at most 64. Beside the counts, what is outstanding when the snapshot is taken: inFlight (calls awaiting an answer), subscriptions (live subscriptions) and backlog (messages emitted and not yet delivered), so a test can wait until a port is idle

Some useful figures:

  • Utilisation is pool.busyMs / pool.aliveMs.
  • Mean queue length is pool.queuedMs / (s.at - s.since).
  • Overhead is 1 - compute / total. A job whose overhead dominates is too small to send to a worker.

Memory figures are each instance’s linear memory, which only grows, and the host’s allocation counters. The browser’s whole-process memory API needs cross-origin isolation, which the platform does not require, so compiled code and worker threads are not included.

A job refused at the engine’s in-flight cap never reaches the pool, so the pool cannot see it. When engine is present, engine.refused counts it.

Events

const stop = runtime.monitor.subscribe((e) => console.log(e.kind, e));
KindFields
job-issueid, task, inputBytes, timeoutMs, held (true when manual mode holds the job), at (and input with payloads)
job-startid, instance, cold, at
job-endid, task, outcome, at, record (the full job record; and output with payloads)
instance-spawninstance, thread ("worker" or "page"), at
instance-readyinstance, scriptAt, instantiateMs, memBytes, liveAllocs (before any job), at
instance-endinstance, cause, fault ({ class, message } or null), jobs, busyMs, memBytes, at
state-evictinstance, prep (the preparation’s name), cause (replaced, released), at
turnnode, handler, fx (the job id for a job’s result turn), eventMs, applyMs, bytes, at. Only for subscribers that pass { turns: true }
transitionstate (applied, start-rejected, ready-rejected, finished-rejected), at; applied carries cause (callback, timer, queue, none) and typeCount; rejections carry a diagnostic message of at most 1024 characters
pointer-capture-refusedpointer, at
event-text-refusedtype (the event type), at
runtimestate (mounted, poisoned, unmounted), generation, fault, at

What a listener can rely on:

  • Events arrive synchronously as things happen, and at never goes backwards.
  • Each issued job gets exactly one job-end. A job-start, if there is one, comes between the two.
  • Each instance gets instance-spawn, then instance-ready if it ever becomes ready, then exactly one instance-end. No job starts on an instance before it was spawned.
  • A job that delivers a result (done, lost, timeout, unavailable) ends after its result turn has been applied. A cancelled job ends when it is cancelled, with record.phase (held, queued, starting, running) and record.cancelledBy (engine, unmount, contained).
  • A cancelled job whose task says on_cancel: Finish ends at once as cancelled with record.finished, but its instance stays busy until the job completes, or until its timeout (ten minutes when it has none), when the instance ends with cause timeout.
  • When stopping a job terminates its worker (cancel, timeout, fault), the instance-end comes before that job’s job-end.
  • When the page’s runtime is poisoned or unmounted, every job and instance still live ends with that cause, then the runtime event follows. Nothing more is reported until recover() mounts a new generation.

Transition events are passive: a rejected browser animation does not poison the app or change the applied DOM. They retain no animation history in the monitor. A turn event’s applyMs measures synchronous work after the call, including a marked batch’s first read and early effects; it does not include the wait for the browser callback or its later DOM update. Manual replay keeps its separate bounded transition observations (Testing).

A listener must only observe: it may call snapshot(), but not drive the runtime. A listener that throws is reported on the console and unsubscribed. At most 16 listeners can subscribe.

DevTools and User Timing

With userTiming: true the monitor adds performance.measure entries, so jobs show up in the DevTools Performance panel and in any PerformanceObserver, with no custom tooling:

  • roc:work <task>: a job from issue to its applied result. Its detail carries the id, instance, outcome and byte sizes.
  • roc:work.queue, roc:work.cold, roc:work.run (posted until the answer arrives) and roc:work.result: the job’s phases.
  • roc:work.prepare: the preparation of a preparation’s task’s job, drawn with the length the worker measured, ending where the task’s own call starts. The job’s own files are staged between the two, so the entry is drawn that much late.
  • roc:worker <n> spawn: a worker starting.
  • roc:work.compute <task>: added by the worker itself, on its own thread.

Each entry’s detail.devtools asks Chrome to draw it on a “roc workers” track group.

new PerformanceObserver((list) => {
  for (const m of list.getEntries()) if (m.name.startsWith("roc:work ")) console.log(m.name, m.duration.toFixed(1), m.detail.outcome);
}).observe({ type: "measure" });

Each thread keeps at most 1024 of the monitor’s entries in its performance timeline and clears them when it reaches that. Observers and recorded traces have already received them by then.

Bounds and cost

Everything the monitor keeps has a bound:

KeptBoundAt the bound
Job recordshistory (default 128, at most 1024)Oldest overwritten, counted in recentDropped
Retired instances16Oldest overwritten, counted in retiredDropped
Tasks64, the catalogue’s boundFurther names counted under "*"
Live jobs and instancesThe in-flight cap and maxWorkers—
Subscribers16subscribe throws
Timeline entries1024 per threadCleared

When nobody is looking:

  • A job costs eight clock reads on the page and five in its worker, plus a few counter and histogram updates.
  • An unmarked turn that delivers no job result reads no clock at all. A marked batch reads the clock for each passive transition event.

When someone is looking:

  • Each event is one object and one call per subscriber.
  • { turns: true } adds three clock reads to every turn.
  • User Timing adds roughly five measures per job.

Diagnosing a slow job

A search box sends its filter to a worker. Results feel slow, so the page logs the last few jobs:

console.table(runtime.monitor.snapshot().recent.map((j) => ({ id: j.id, total: j.ms.total, queue: j.ms.queue, cold: j.ms.cold, compute: j.ms.compute, resultWait: j.ms.resultWait })));

The rows show a total of about 120 ms, of which compute is 8 ms and queue 96 ms. cold is 0, and resultWait and resultTurn are a few milliseconds. The jobs are not slow; they wait. The pool confirms it:

const { pool, maxWorkers } = runtime.monitor.snapshot();
// maxWorkers 2, pool.peak.busy 2, pool.peak.queued 7, busyMs / aliveMs ≈ 0.97

Both workers are busy almost all the time, and up to seven jobs wait behind them. Each keystroke issues several jobs at once. There are two fixes:

  • Issue less: one job per query, or debounce the input.
  • Allow more concurrency: raise maxWorkers.

After the change, hist.queue should collapse into its lowest buckets.

The same table can tell a different story. Suppose cold dominates instead, instances.respawns keeps climbing and instances.ended.cancel grows with it. Then jobs are being cancelled while they run: each cancel terminates a worker, and the next job pays to start a new one. Work is scoped to the site that issued it, so this means the issuing site is disposed and re-created, for example inside a when that toggles. Issue the work from a site in a longer-lived scope.