Introducing a new way to review your PRs.

Read the announcement

reflex-dev / xy

Ultra-fast and customizable Python charts

View on GitHub

20 documents · Updated Nov 18, 2026

docs / browser-worker-and-kernels

Browser worker and compute kernels

The browser worker and compute-kernel paths keep large chart data responsive while preserving a clear view of what the user sees. JavaScript owns view state and display changes. The native kernel computes exact points or screen-sized aggregates when a kernel connection exists. A standalone export uses a browser worker for zoom refinement. See the browser rendering runtime for the wider client lifecycle. Related display behavior is described in WebGL rendering resources, browser interaction and animation, and level of detail and streaming.

Runtime coordination

The runtime turns a pan or zoom into a bounded compute request. It keeps the current image visible while work runs, then accepts only the result that still belongs to the current view.

Browser and kernel roles

The JavaScript client is the coordinator. It reads the current viewport, schedules a debounced request, and applies the returned geometry or density grid to the renderer. The Python interaction layer validates the request and chooses the representation. Native Rust code performs the data scan and returns typed buffers rather than a large JSON record.

The browser has two compute paths:

PathData sourceMain resultUse
Kernel-attachedCanonical data in the Python processExact points or a density grid for the requested windowInteractive charts with a live backend
StandaloneA retained sample embedded in the exportA worker-built density grid for a zoomed viewKernel-less HTML exports

This split keeps the browser responsive without making the standalone chart treat its sample as the full data set.

References: js/…/54_kernel.ts• L20-153 python/…/interaction.py• L882-899 js/…/46_worker.ts• L19-21

View request flow

The following flow shows how a view change reaches either the native kernel or the browser worker and returns a display-ready result.

sequenceDiagram
    participant User
    participant Client as JavaScript client
    alt Kernel attached
        participant Python as Python interaction layer
        participant Rust as Native Rust kernel
        User->>Client: Pan or zoom
        Client->>Python: density_view(view, screen size)
        Python->>Rust: Validate and aggregate or select points
        Rust-->>Python: Typed result buffers
        Python-->>Client: density_update or points update
    else Standalone export
        participant Worker as Browser re-bin worker
        User->>Client: Zoom in
        Client->>Worker: rebin(view, sequence)
        Worker-->>Client: Grid buffers
    end
    Client->>Client: Check sequence and update the view

The sequence number belongs to the client view request. A result that arrives after a newer view is active is ignored. The client also suppresses a request when an identical density window is already answered or still in flight. This avoids replacing a valid result with duplicate work while keeping a new request possible after data or filter state changes.

References: js/…/54_kernel.ts• L41-153 js/…/54_kernel.ts• L156-235 js/…/54_kernel.ts• L730-847

View-dependent computation

The level-of-detail decision is a property of one trace in one viewport. It uses the visible count and a direct-point budget rather than the total data size alone.

Tier selection

The LOD planner first makes the viewport safe. It orders reversed bounds, rejects non-finite values, and clamps screen dimensions. It then chooses exact points when the visible count fits the budget. Otherwise it chooses a density representation and records the reduction in the update.

Once a trace is showing exact points, a small amount of count growth does not immediately force it back to density. This hysteresis prevents rapid changes at the threshold. The same rule is mirrored by the browser and the Python side so both sides agree about the meaning of an update.

View conditionBrowser representationMeaning
Visible rows fit the direct budgetReal points with channelsExact marks for the window
Visible rows exceed the budgetScreen-sized density gridAn aggregate view with a recorded reduction
Standalone zoom-in with no kernelRe-binned retained sampleA sample-based refinement, not full-data exactness

References: python/…/lod.py• L47-119 python/…/lod.py• L139-242 python/…/interaction.py• L882-917 js/…/45_lod.ts• L282-302

Density aggregation

Density computation maps visible points into a grid sized for the screen. The count grid keeps the result bounded by the output size, while invalid or out-of-window points do not contribute.

For traces with a varying color, the aggregate also carries the mean of the colors that the points actually draw. The mean uses alpha weighting and linear-light color space. A constant-color trace can use the count grid with a client-side tint instead.

The update records facts such as the visible count, reduction, served data window, density encoding, and any color aggregation. These facts allow the client to show an honest reduction state instead of inferring one from the pixels.

References: python/…/interaction.py• L918-929 python/…/interaction.py• L1084-1134 src/kernels.rs• L3040-3052 src/kernels.rs• L3598-3607

Exact point handoff

When a deep view can show real points, the kernel sends the point subset and its per-point channels. Coordinates use an offset and scale so large values such as timestamps keep useful precision in browser-friendly floating-point buffers. The update also carries a drill sequence, which identifies the subset used by later picks and selections.

The client can keep exact windows for nearby pans and zooms. A view inside a known exact window can render locally. A view outside that window asks for a new representation. This reduces repeated work while preserving the rule that an exact point response must match the data window it claims to cover.

References: python/…/interaction.py• L1137-1230 python/…/lod.py• L720-755 python/…/lod.py• L901-938 js/…/54_kernel.ts• L983-1005

Standalone worker computation

The standalone path uses the first-paint density grid for broad views and retains a small deterministic sample for later refinement. A worker re-bins that sample away from the main browser thread when the user zooms in.

Worker input and output

The client initializes one worker data set per trace with decoded x and y values. For a channel-colored trace it also sends the resolved point colors. Each re-bin message names the trace, sequence, view bounds, and output size. The worker returns a grid, its maximum count, the served range, and an optional RGBA color plane through transferable buffers.

The client applies a returned grid through the same density path used by a kernel reply. It checks the sequence before upload, so a worker result cannot replace a newer view. The retained sample remains available for the point overlay, while the re-binned grid supplies the aggregate surface for the current zoom.

References: js/…/54_kernel.ts• L237-388 js/…/46_worker.ts• L35-89

Worker fallback

Worker creation uses a bundled script and a Blob URL. If the browser does not support workers or the page policy blocks Blob workers, the client keeps the original overview behavior. The chart still renders, but a zoom can stretch the overview instead of computing a new sample grid.

References: js/…/46_worker.ts• L19-21 js/…/46_worker.ts• L92-103 js/…/54_kernel.ts• L291-298

JavaScript and kernel interface

The interface separates small control metadata from bulk numeric data. This lets the client route an update by its mode and trace while the buffers carry points, channels, or grid values efficiently.

Request and reply contract

The client sends a view request with normalized bounds and screen dimensions. A density request also names the trace. The kernel reply identifies the trace representation and describes the served window.

Contract fieldRole
seqIdentifies the current view request and rejects stale replies
mode, tier, reductionStates whether the result is exact points or an aggregate
visibleGives the count used for the tier decision
x_range, y_rangeStates the data window covered by the result
Buffer referencesPoint coordinates, channels, density counts, or colors
drill_seqVersions an exact point subset for picks and selection masks

The Python side builds the metadata and typed buffers. The JavaScript side decodes those buffers and creates the GPU resources needed by the active renderer. Filter state is also part of density reply admission. A reply computed for another hidden-category set is ignored.

References: python/…/lod.py• L800-825 python/…/interaction.py• L1102-1134 python/…/interaction.py• L1201-1230 js/…/54_kernel.ts• L792-847

Native execution boundary

The Python kernel module exposes the compiled Rust core as the only compute backend. It does not silently replace native work with a Python implementation when the native module is unavailable. The Rust functions cover the chart preparation work needed here, including grid binning, mean-color aggregation, local density values, sampling, and precision-safe coordinate encoding.

The native calls are synchronous from the Python interface. Rust may split large independent scans across CPU threads inside a call, then merges the result before returning. This keeps the browser protocol simple while the expensive data work stays outside the browser main thread.

References: python/…/kernels.py• L1-27 python/…/kernels.py• L39-75 src/kernels.rs• L3177-3210 src/kernels.rs• L5241-5282

Streaming append coordination

Streaming append handling updates the chart with fresh data while preserving the user's position. The client applies a complete bounded payload, then schedules a short follow-up request when the current view can benefit from sharper decimation or density.

At the home view, the chart follows the new data domain. A zoomed view follows the live edge only when its right edge was pinned to that edge. A user who inspects history stays on that history. Direct scatter and line data can use an in-place tail update when its encoding and style remain compatible; otherwise the client rebuilds the affected trace.

The follow-up work is coalesced during a continuous stream. If the append payload already covers the home view at the needed pixel width, the client skips redundant decimation work and refreshes only density traces that still need it.

References: js/…/54_kernel.ts• L406-513 js/…/54_kernel.ts• L515-727

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the mode, tier, visible, and reduction metadata aligned with the representation that the client draws.
  • Keep seq checks consistent across debounced sends, worker replies, and kernel replies. A new request must invalidate older work.
  • Keep duplicate-request suppression tied to both the density window and the hidden-category filter state.
  • Keep drill_seq tied to the shipped point subset. Picks and selection masks must not use indices from another subset.
  • Keep density count and color grids on the same viewport and cell layout so their occupied cells and visual meaning stay aligned.
  • Keep coordinate offset and scale metadata paired with every encoded point buffer. A buffer without its decode metadata cannot preserve deep-zoom precision.
  • Keep the standalone worker's sample color rule aligned with the native mean-color aggregate when channel colors are present.
  • Keep append fast-path checks tied to the actual GPU encoding and style. An incompatible payload must rebuild rather than extend buffers with a different meaning.
  • Keep worker fallback behavior visible in product expectations. Browsers without worker or Blob support still need a valid overview render.

Important failure modes

TriggerConsequenceGuard
A stale kernel or worker result passes through after a newer viewThe chart shows an older windowCompare the result sequence with the current view sequence before applying it
A duplicate density request is treated as answered after its filter state changesThe chart keeps an aggregate built from hidden categories that are no longer activeInclude the canonical filter key in request identity and reply admission
An exact point reply is used with the wrong drill subset versionPicks or highlights can refer to the wrong source rowCheck drill_seq and drop unmatched index buffers
A density grid and color plane use different bounds or cell shapeColors no longer describe the counts beneath themBuild both planes from the same validated window and dimensions
A non-finite or degenerate viewport reaches a kernelThe tier decision or native scan can fail before a valid update existsValidate bounds and screen shape before changing drill state
An append extends buffers after their encoding or style changedNew marks use the wrong coordinates or visual channelsUse the in-place path only for prefix-compatible data and rebuild otherwise
Worker or Blob support is unavailableStandalone zoom refinement is not availableKeep the overview grid and use the documented stretched-overview fallback
The native Rust module cannot loadPython compute cannot provide the chart kernel contractFail loudly with install or build guidance instead of silently changing backend

Key files

FileWhy to read it
js/…/54_kernel.tsMain client coordinator for view requests, worker re-binning, append refresh, and inbound kernel messages
js/…/46_worker.tsBrowser-side sample re-bin protocol and worker fallback
js/…/45_lod.tsClient rules for exact windows, density caches, drill transitions, and stale-safe local reuse
python/…/interaction.pyBackend-facing density_view contract and the choice between density grids and exact points
python/…/lod.pyShared viewport validation, tier planning, stable sampling, and encoded-buffer rules
python/…/kernels.pyNative backend boundary and the public compute-kernel surface
src/kernels.rsAccelerated Rust operations for binning, color aggregation, local density, and typed numeric preparation
tests/test_lod.pyGuarantees for tier planning, stable sampling, validation, and shared wire metadata
tests/test_kernels.pyGuarantees for native precision, density binning, sampling, and invalid-input handling