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 / level-of-detail-and-streaming

Level of detail, density, and streaming

XY keeps the source data available while choosing a smaller view representation for large or changing datasets. The level-of-detail (LOD) system limits rendered work to what the current view can show, moves between exact marks and aggregates as the view changes, and refreshes live charts without sending the full history on every update.

Representation policy

The LOD policy maps a trace and its current viewport to a representation. A viewport is the visible x/y window and screen size. The policy uses the number of visible rows rather than only the total dataset size, so a zoomed region can return to exact marks even when the full chart needs an aggregate.

Data situationRepresentationProduct effect
Small point viewDirect pointsEach finite visible row can remain an individual mark.
Long ordered line or areaM4 decimationThe view keeps a bounded set of extrema that preserves the shape of the series.
Dense scatter overviewDensity surfaceCounts are combined into screen-sized cells instead of drawing every point.
Affordable deep scatter viewExact point windowThe system returns real points for the local window and restores point channels.
Very large or disk-backed scatterPyramid or indexed windowPrebuilt summaries serve broad views. A spatial index can provide sharp local detail when its read limit allows it.

The public density choice controls the initial scatter policy. None lets the chart choose automatically. True asks for a density overview. False keeps direct points and accepts the cost of a large direct payload. The active choice is recorded in the payload as tier and reduction information rather than being hidden from the client. See Python chart API and figure model and Chart families, facets, and layout for the chart-level context.

Tier decisions

The shared LOD policy validates the viewport before it changes state. It orders reversed bounds, rejects non-finite values, and clamps screen dimensions to a safe range. It then compares the visible count with a direct-point budget and applies hysteresis. Hysteresis means that an exact view does not switch back to an aggregate at the first small count increase, which prevents rapid mode changes near the boundary (python/…/lod.py• L47-118, python/…/lod.py• L139-242).

Every reduced update states its mode, semantic tier, visible count, and reduction. This lets the client and downstream features distinguish exact marks from density, decimation, or another aggregate. A reduction changes the rendered view, not the canonical rows used for exact readout and selection (python/…/lod.py• L91-118, python/…/_payload.py• L257-269).

References: python/…/lod.py• L47-118 python/…/lod.py• L139-242 python/…/_payload.py• L257-269

Density and raster paths

The density path turns point positions into a bounded two-dimensional grid. The grid is sized from the viewport and screen, so transport and GPU texture size follow the display rather than the row count. The grid is encoded in compact log-scaled bytes for the wire. The client decodes it into a texture and can use either smooth filtering for an aggregate or nearest-neighbour filtering for exact deep-zoom bins (python/…/_payload.py• L1260-1361, python/…/interaction.py• L882-942, js/…/45_lod.ts• L38-138).

The surface remains tied to the meaning of the source marks. A constant-color trace keeps its color. A trace with a color channel carries a per-cell mean color. A channel with no honest cell summary is reported as dropped. These facts travel with the density metadata so a client does not mistake an aggregate for a set of individual rows (python/…/_payload.py• L1361-1411, src/tiles.rs• L99-172).

Static raster output uses the same bounded density grid but does not draw the browser-only sample overlay. The omission is recorded as static_raster, while the grid itself stays unchanged. This keeps PNG and other raster output stable without adding a point layer that the raster path does not consume (python/…/_payload.py• L82-112, python/…/_payload.py• L289-295, python/…/_raster.py• L925-1085). See Export and static rendering for the wider export model.

Density transitions

The client keeps a covering aggregate while a refined response is in flight. It crossfades between representations instead of clearing the plot, and it keeps the aggregate below point marks while the transition is active. Mean-color surfaces preserve the color and overplot intensity of the points they summarize. Count-only surfaces use a gradual intensity handoff (js/…/45_lod.ts• L113-205, js/…/45_lod.ts• L1080-1140).

This diagram shows how a large scatter view moves from an overview surface to exact local marks and back without a blank frame.

flowchart LR
    A[Canonical rows] --> B[Viewport count]
    B -->|Above direct budget| C[Density grid]
    B -->|At or below direct budget| D[Exact point window]
    C --> E[Cached covering surface]
    D --> F[Cached exact window]
    E -->|Zoom toward resolvable window| D
    F -->|Zoom or pan outside window| C
    E -. crossfade .-> D
    D -. fade back .-> C

References: python/…/interaction.py• L882-1134 python/…/_payload.py• L1205-1434 js/…/45_lod.ts• L113-205 js/…/45_lod.ts• L1080-1271 python/…/_raster.py• L925-1085

Out-of-core data

Out-of-core data is canonical chart data kept on disk while the chart reads only the parts needed for summaries or a view. A disk-backed NumPy memory map can enter the normal column store without copying the full column into RAM. Range checks, density scans, and pyramid builds read through the operating system page cache, so resident memory can stay below the raw dataset size (python/…/_ooc.py• L1-26, python/…/_ooc.py• L42-105).

For large scatter traces, a multiresolution pyramid is built lazily after the trace reaches the large-data range. It stores count summaries at several scales and can also store mean-color summaries. Broad views compose a grid from the suitable level rather than scanning all rows for each interaction. Counts remain conserved across levels, and the chosen representation is recorded in the update (python/…/interaction.py• L607-650, src/tiles.rs• L59-172, src/tiles.rs• L315-478).

When a normal in-memory trace zooms past the finest useful pyramid level, the system can perform an exact local re-bin. For a very large or memory-mapped trace, it avoids repeated full scans and serves the finest summary with bounded upsampling. If an out-of-core trace has a spatial index, the system can read only overlapping cells. It returns exact points for a small local result or a full-screen exact grid for a larger local result. Position-only indexed points cannot restore per-row channels or exact source-row identity, so channel-bearing traces keep the truthful colored aggregate instead (python/…/config.py• L232-260, python/…/interaction.py• L930-1057).

The memory report separates mapped canonical bytes from resident canonical bytes and reports pyramid memory. This distinction helps an engineer tell the cost of keeping a large dataset available from the cost of the active rendered summaries (tests/test_ooc.py• L65-125, tests/test_streaming.py• L413-422).

References: python/…/_ooc.py• L1-26 python/…/_ooc.py• L42-150 python/…/interaction.py• L607-650 python/…/interaction.py• L930-1057 src/tiles.rs• L59-172 src/tiles.rs• L315-478 tests/test_ooc.py• L65-125

Request economy

Request economy keeps view changes from sending expensive updates that cannot improve the displayed result. The client reuses the smallest cached density surface that covers the view and keeps a broad fallback when no refined surface covers it. It does not stack overlapping density textures because their alpha would count the same area more than once (js/…/45_lod.ts• L345-367).

Aggregate refinement follows a small aligned ladder instead of issuing a new grid for every pan or zoom. A view inside the current ladder step sends no request. A request near the point range uses the raw view so the kernel can make the exact-versus-aggregate decision with real counts. Probe replies can update the count facts without replacing a surface that already covers the view (js/…/45_lod.ts• L369-460, js/…/45_lod.ts• L497-526, js/…/45_lod.ts• L1144-1227).

Exact point windows are padded and aligned when possible. The padding lets nearby views reuse the same window. The client keeps a bounded cache of retired exact windows and can promote one without a new request. A view inside an exact window also suppresses a request until the window no longer covers it or the encoded coordinates need a new precision center (python/…/interaction.py• L747-796, js/…/45_lod.ts• L551-800).

The request path also suppresses duplicate windows that differ by less than half an output texel. Debouncing coalesces rapid gestures. Sequence numbers reject stale replies, and a pending hold keeps the current representation visible for a bounded time while refinement is in flight (js/…/54_kernel.ts• L25-153, js/…/54_kernel.ts• L156-184).

References: js/…/45_lod.ts• L345-460 js/…/45_lod.ts• L497-526 js/…/45_lod.ts• L551-800 js/…/54_kernel.ts• L25-184 python/…/interaction.py• L747-796

Incremental and streaming updates

Streaming append extends an existing scatter or line trace while preserving the figure structure. Python validates the new rows and channel tails before mutation. It then updates canonical columns and emits a fresh screen-bounded payload for the affected trace. The payload includes an append sequence and affected trace IDs so widget hosts can apply the coherent spec and buffer pair (python/…/interaction.py• L1233-1273, python/…/interaction.py• L1275-1454).

An append follows the current view policy. A chart at home follows the new data extent. A zoomed chart whose right edge was pinned follows the new tail at the same width. A chart that is inspecting history stays in place. The browser applies direct scatter or line tails in place when the encoding and style contract is unchanged. Other cases rebuild the affected trace from the new bounded payload (js/…/54_kernel.ts• L406-494, js/…/54_kernel.ts• L515-727).

The append payload paints the new state at once. A delayed, coalesced refresh can then sharpen the current density or decimated window. A continuous stream therefore avoids one expensive refinement request per tick while still allowing the settled view to catch up (js/…/54_kernel.ts• L11-18, js/…/54_kernel.ts• L496-513).

Pyramid updates are incremental when new finite points remain inside the original domain and the pyramid has no color plane that needs new channel data. Domain growth or a colored pyramid invalidates the cached summary and lets the next density view rebuild it lazily. Any active exact drill and its old row mapping are cleared after an append because their indices describe the prior canonical data (src/tiles.rs• L175-217, python/…/interaction.py• L1429-1444).

This diagram shows the relationship between an append, canonical state, the bounded refresh, and the later refinement pass.

sequenceDiagram
    participant App as Python application
    participant Store as Canonical store
    participant Host as Widget or browser host
    participant View as Chart view
    participant Kernel as View kernel

    App->>Store: Validate and append rows
    Store-->>App: Update columns and summaries
    App->>Host: Send append sequence and bounded payload
    Host->>View: Apply coherent spec and buffers
    View-->>Host: Paint new state
    View->>Kernel: Coalesced current-view refinement
    Kernel-->>View: Density or decimation update
    View-->>Host: Replace or retain the refined representation

References: python/…/interaction.py• L1233-1454 src/tiles.rs• L175-217 js/…/54_kernel.ts• L406-513 js/…/54_kernel.ts• L515-727 js/…/60_entries.ts• L18-62 tests/test_streaming.py• L89-245

Cross-system contracts

LOD sits between canonical data, interaction, payload transport, and rendering. The main contract is that each layer can tell whether it is handling exact rows, a summary, or a sample. This protects hover, selection, legends, exports, and streamed updates from treating reduced geometry as source truth. See Data ingestion and payload construction, Styling, themes, and annotations, and Interaction and view state for the neighboring contracts.

The following rules are the most important relationships to preserve:

  • Canonical rows remain the source for exact readout. Rendered buffers can be reduced or encoded for transport.
  • LOD metadata describes every reduction. A changed channel must be named as aggregated or dropped.
  • A subset shipped for exact points has its own sequence. A stale pick must be dropped rather than translated as a different row.
  • Append data invalidates old exact subsets and any derived state that no longer describes the current columns.
  • Density cache entries and point-window entries are bounded rebuildable views. They must not become a second unbounded copy of the dataset.

References: python/…/interaction.py• L175-213 python/…/lod.py• L720-764 python/…/_payload.py• L1361-1411 js/…/54_kernel.ts• L792-847 docs/…/real-time-and-streaming-data.md• L63-72

Change checklist

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

  • If a tier or reduction name changes, update the Python plan, payload metadata, browser admission logic, and any UI that reports the reduction.
  • If density grid encoding or filtering changes, keep the Python wire writer, browser texture upload, native raster path, and pyramid composition contract aligned.
  • If viewport thresholds or hysteresis change, review request gating, exact-window padding, cache reuse, and the point-versus-density transition together.
  • If append payload shape changes, preserve append sequence handling and coherent spec/buffer application for widget hosts.
  • If canonical column domains or channel normalization change, review pyramid validity and the conditions for in-place browser tail updates.
  • If an indexed out-of-core path changes, preserve the distinction between position-only indexed data and channel-bearing canonical rows.

Important failure modes

TriggerConsequenceGuard
Non-finite or zero-area viewportA kernel or cache could receive an invalid request and corrupt the active tier state.Validate through ViewportRequest before any tier or drill mutation.
Density reply arrives for a stale sequence or filter stateAn old aggregate can replace the view for a newer gesture or legend state.Compare request sequence and filter identity before applying the reply.
Aggregate request sent for every small pan or zoomLarge grids are resent even when the displayed picture does not improve.Use aligned ladder steps, cache coverage, debounce, and sub-texel duplicate suppression.
Exact point window is reused after an appendPicks and selections can map to rows from the old canonical data.Exit the drill and clear drill history when data changes.
Colored pyramid is incremented without new color factsExisting cells can show incorrect colors after an append or domain change.Invalidate and lazily rebuild colored pyramids.
Out-of-core indexed points carry per-row channelsThe chart could show positions with invented or missing channel values.Skip the position-only exact tier for channel-bearing traces and keep the colored aggregate.
Widget receives spec and buffers in different change eventsA torn append can be applied with mismatched column data.Check payload coherence and wait for the matching pair before consuming the append sequence.

Key files

FileWhy to read it
python/…/lod.pyShared viewport validation, tier planning, stable sampling, exact-window encoding, and reduction metadata.
python/…/interaction.pyKernel-side density decisions, pyramid use, spatial-index detail, drill windows, and append effects.
python/…/_payload.pyInitial density, sample, decimation, and raster payload policy.
python/…/_ooc.pyDisk-backed canonical columns and their normal chart-ingest boundary.
python/…/_figure.pyPublic append entry point and the figure-level streaming lifecycle.
src/tiles.rsNative multiresolution summaries, composition, count conservation, and incremental pyramid rules.
js/…/45_lod.tsBrowser cache, request reuse, density textures, exact-window revival, and visual transitions.
js/…/54_kernel.tsView request scheduling, reply admission, append application, and coalesced refinement.
js/…/60_entries.tsWidget-side coherent application of append spec and buffer updates.
tests/test_density_request_economy.pyExecutable contract for ladder steps, facts-only replies, duplicate suppression, and one-texture drawing.
tests/test_ooc.pyContract for memory-mapped ingest, memory accounting, and screen-bounded density rendering.
tests/test_streaming.pyContract for append validation, follow behavior, pyramid updates, and payload prefix stability.