Skip to content
Source
Sign inSign up
TanStack/charts

feat(spatial): add opt-in grid spatial index #165

Opengreglum(GitHub profile, opens in a new tab)wants to merge 14 commits intomain fromrefs/pull/165/headopened

This adds gridSpatialIndex at @tanstack/charts/spatial/grid-index, an opt-in factory for the existing spatialIndex option. It returns exactly the point the default linear scan returns:

  • smallest squared distance
  • earliest point on a tie
  • the same maxDistance rules
  • the same handling of non-finite anchors

It looks up the nearest point center; it does not hit-test shapes, and the docs say so. Only the default 'nearest' focus mode reaches the hook. The axis and group modes resolve before it.

Default bundles do not change. bundle:check budgets the subpath at 1.2 KiB gzip; it measures 1.01 kB. nearest.ts is untouched, so this should not conflict with #42 or #153. If either changes point-anchor semantics, this index and its tests should follow.

Verification:

  • Seeded property tests compare it with nearestPoint on uniform, lattice, clustered, strip and non-finite layouts, including ties across cells.
  • A cell-visit counter keeps one-column and one-row grids cheap. An earlier version of this branch degraded badly on vertical strips, and this test would catch that.
  • A separate adversarial probe ran 129,600 queries across 16 layouts and many maxDistance values, with zero mismatches against nearestPoint. It was not committed.
  • pnpm performance:pointer checks every index against the linear result before timing.
  • typecheck, test, docs:check, bundle:check and format:check pass.

Benchmark (pnpm performance:pointer, 960×540 plot, radius 48, query medians):

LayoutPointsLinearGrid buildGrid queryQuadtree buildQuadtree query
uniform1k1.8 µs29 µs0.1 µs140 µs0.5 µs
uniform10k16.6 µs113 µs0.3 µs1.04 ms1.2 µs
uniform100k187 µs1.14 ms2.4 µs15.7 ms5.2 µs
vertical strip10k16.0 µs111 µs0.1 µs1.30 ms6.8 µs
vertical strip100k188 µs1.12 ms0.5 µs20.8 ms110 µs
horizontal strip100k182 µs1.11 ms0.6 µs25.2 ms99 µs
clustered100k183 µs1.24 ms2.5 µs16.9 ms3.4 µs
pointer in cluster1k1.7 µs20 µs3.8 µs114 µs0.9 µs
pointer in cluster10k17.6 µs158 µs20.4 µs1.78 ms1.7 µs
pointer in cluster100k214 µs1.29 ms112 µs24.6 ms8.0 µs

The grid keeps about 24 bytes per point. The quadtree keeps about 90 per point on uniform data and about 145 on strips.

These numbers come from one Apple M5 Max running Node 24.18.0 while other work was running (load average 6 to 9), so read them as relative. The worst case is a pointer inside a dense cluster: about 2× slower than linear at 1k points, roughly even at 10k, and 2× faster at 100k. D3 quadtree does better there, and the large-data guide says so.

Includes a minor changeset, a PLAN.md note that the default stays the linear scan, and API-FRICTION entry F-307. That ID will need renumbering if another friction entry lands first.

Summary by CodeRabbit

  • New Features
    • Added an optional spatial index for nearest-point lookups in dense charts. It returns results consistent with linear search, including tie-breaking and distance limits, and searches point centers rather than chart shapes. Charts remain unchanged unless the index is explicitly used.
  • Documentation
    • Added guidance on index behavior, limitations, and rebuild requirements, along with performance comparisons across different chart sizes and point distributions.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      No actionable comments were generated in the recent review.

      Recent review info
      Run configuration
      • Source mode: Auto
      • Repository: Unavailable
      • Branch: Unavailable
      • File: No configuration file from this repository applied
      • Commit: Unavailable
      • Layers: defaults
      • Review profile: CHILL
      • Plan: Advanced
      • Run ID: 6a94a91a-4d94-4d9a-9a7c-8f5d0d97834d
      Commits

      Reviewing files that changed from the base of the PR and between 6af7b786c523c4ef6ce7a9740c7de080364d27ff and fe337abc010174b153a4c622a81f07ebb45211c4.

      Files selected for processing: 1
      • benchmarks/conformance/previews/manifest.json

      Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

      Walkthrough

      The package adds an opt-in grid spatial index for nearest point-anchor lookup. It publishes the factory through a dedicated subpath, tests it against a linear scan, measures its scaling, and documents its behavior and limitations.

      Changes: Grid spatial index

      Layer / File(s)Summary
      Grid implementation and package export
      packages/charts-core/src/spatial-grid-index*, packages/charts-core/package.json, packages/charts-core/src/exports.test.ts, scripts/check-packed-consumers.mjs, scripts/measure-bundles.mjs
      Adds the grid index and exposes gridSpatialIndex through @tanstack/charts/spatial/grid-index. Bundle checks set boundaries for retaining the index. A bundle measurement applies a 1.2 KiB gzip budget to the subpath.
      Correctness and scaling validation
      packages/charts-core/src/spatial-grid-index.test.ts, benchmarks/entries/charts-spatial-grid-index.ts, benchmarks/interaction/nearest.ts, benchmarks/interaction/README.md
      Tests compare results with a linear scan across point layouts and query conditions. Benchmarks compare the grid index with linear scans and D3 quadtrees across point counts and distributions.
      Usage documentation and release notes
      .changeset/grid-spatial-index.md, API-FRICTION.md, PLAN.md, docs/guides/large-data.md, docs/reference/*, packages/charts-core/docs/guides/large-data.md, packages/charts-core/docs/reference/*
      Documents the opt-in API, nearest-anchor behavior, distance limits, tie handling, non-finite anchors, and shape-hit-testing limitations. The changeset records a minor release entry.
      Benchmark and comparison metadata
      benchmarks/comparison/bundle-baseline.json, benchmarks/conformance/previews/manifest.json, docs/comparison.md, packages/charts-core/docs/comparison.md
      Updates the measured workspace revision and source hashes in benchmark metadata and comparison pages.

      Estimated code review effort: 3 (Moderate) | ~25 minutes

      Change: Feature

      Possibly related issues

      • Pointer-move point rebuilding and focus resolution performance: this PR adds an opt-in spatial index for nearest-point resolution, but does not address CTM caching or early input.

      Suggested reviewers: ryansolid

      Merge Risk: Minimal · up to fe337

      No merge-blocking issue was found in the reviewed change.

      Security architecture risk: Low · up to 277cd

      The explicit opt-in import limits exposure to consumers that choose the index. No added credential, permission, or cross-service access was identified. Numeric edge cases, input-lifetime assumptions, and incomplete security coverage prevent a minimal-risk assessment.

      Retained concerns No architecture-level concerns identified.

      Security review details

      Security Blast Radius

      • inferred — The demonstrated exposure is confined to point selection and local computation in consumers opting into the factory. No cross-tenant, credential, data-store, or service authority expansion was established by the inspected call path.

      Trust Boundaries and Controls

      • observed — Index use remains controlled by application configuration and scene identity. Presentation-point lookup bypasses the index. Viewport filtering restricts clipped points when configured, but does not universally bound coordinates.

      Resilience and Maintainability Implications

      • observed — Query selection state is local to each invocation, and the grid owns no external resource requiring disposal. Scene replacement precedes factory completion, so a throwing factory can leave the previous index installed; that ordering also exists on main and is not a newly introduced lifecycle change.

      Hardening Proposals

      • proposed — Consider documenting stable point-array and point-identity ownership for the index lifetime, and falling back to linear lookup when grid dimensions are non-finite. These are contract-hardening proposals, not verified security findings.
      Pre-merge checks: Passed 5
      Check nameStatusExplanation
      Description CheckPassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      Title checkPassedThe title "feat(spatial): add opt-in grid spatial index" names the main change. The changeset adds gridSpatialIndex at @tanstack/charts/spatial/grid-index as an opt-in factory for the existing `sp…
      Docstring CoveragePassedDocstring coverage is inconclusive: files from earlier reviews still need to be rechecked within the check's analysis limits. Not blocking.
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Full details: Title check

      Explanation

      The title "feat(spatial): add opt-in grid spatial index" names the main change. The changeset adds gridSpatialIndex at @tanstack/charts/spatial/grid-index as an opt-in factory for the existing spatialIndex option. The implementation files, package export, tests, benchmarks, and docs all support this change. The title is short, specific, and uses the conventional commit form. It does not describe the default bundle, the benchmark, or the clustered-data caveat, but those are secondary details.

      Finishing Touches
      Generate unit tests (beta)
      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      Share
    2. Thanks @greglum, the opt-in boundary and strip-query coverage are useful. I reproduced one remaining numeric edge case at 277cd05b536334f71bee4c2992187094933e187d in an isolated Chromium context.

      With two finite anchors at (-1e308, 0) and (1e308, 0), querying either exact anchor with maxDistance: 0 returns null. The linear scan returns the matching point. The same failure occurs for the equivalent vertical and diagonal layouts.

      maxX - minX overflows to Infinity. The grid calculation then reaches Infinity / Infinity or Infinity * 0, producing a non-finite cell count or cell coordinate, so the points never become searchable grid members. Ordinary coordinates and the [0, 1e200] control passed.

      Please handle non-finite derived grid dimensions and add these exact-anchor regressions before merging. The public promise is equivalence to the linear scan, including finite input coordinates whose extent overflows. This is a correctness edge case, not a measured security issue. I have not completed the full PR validation yet.

    3. Thanks @greglum, the numeric fix at a94e0e4ea9a2d7c00956d2c412b458895310ed69 resolves the exact-anchor failure I reported above.

      I checked 22,056 queries against the linear scan in an isolated Chromium context, including overflowing extents, tiny coordinates, zero-width axes, duplicate points, empty inputs and distance limits. They all matched. The standalone production ESM build measures 1.076 kB gzip and 0.970 kB Brotli, below this new entry's 1.2288 kB gzip ceiling.

      The performance tradeoff is worth keeping in the docs: for 256 queries over 10,000 tightly clustered points, my seven-trial median was 4.3 ms for the grid versus 2.1 ms for the linear scan. Uniform points at the same count were below 0.1 ms for the grid versus 1.9 ms for the scan. This stays opt-in, so it does not replace the default scan.

      Full repository and packed-consumer validation are still pending. The two GitHub workflows currently require approval, so this is confirmation of the numeric fix, not a merge-ready claim.

    4. changeset-bot[bot](GitHub profile, opens in a new tab)commented

      🦋 Changeset detected

      Latest commit: fe337abc010174b153a4c622a81f07ebb45211c4

      The changes in this PR will be included in the next version bump.

      This PR includes changesets to release 12 packages
      NameType
      @tanstack/chartsMinor
      @tanstack/alpine-chartsMinor
      @tanstack/angular-chartsMinor
      @tanstack/lit-chartsMinor
      @tanstack/octane-chartsMinor
      @tanstack/preact-chartsMinor
      @tanstack/react-chartsMinor
      @tanstack/react-native-chartsMinor
      @tanstack/solid-chartsMinor
      @tanstack/svelte-chartsMinor
      @tanstack/vue-chartsMinor
      @tanstack/charts-scalesMinor

      Not sure what this means? Click here to learn what changesets are.

      Click here if you're a maintainer who wants to add another changeset to this PR

    5. Thanks @greglum, I found an optional improvement to the clustered-point case at 7d8c7708107ed7ed677cf5fc05bf6fc9fb8870e1.

      Inlining the distance comparison inside visitCell, instead of calling visit for each member, improved my isolated query tests without changing the grid search or adding a density heuristic:

      const index = members[slot]!
      const dx = xs[index]! - x
      const dy = ys[index]! - y
      const distance = dx * dx + dy * dy
      if (
        distance < bestDistance ||
        (distance === bestDistance && (best < 0 || index < best))
      ) {
        best = index
        bestDistance = distance
      }

      For 4,096 queries over 100,000 points, with half the points in a 2-pixel cluster, seven paired trial medians were 135.9 → 46.2 ms in Chromium, 192 → 57 ms in Firefox, and 58 → 42 ms in WebKit. Queries mixed near-cluster and uniform positions. These are lookup-only measurements, not chart frame times.

      The prototype matched the linear scan on 22,056 edge-case queries in each browser. I also checked multiple cluster densities and positions, plus radii 0, 1, 48 and Infinity. The standalone production ESM entry changes from 1.076 to 1.110 kB gzip and 0.970 to 0.989 kB Brotli, still below the proposed new-entry gzip ceiling. Existing-entry isolation and full repository validation are not covered by this prototype.

      This is a suggestion, not another correctness blocker. The documented clustered-data caveat should stay, and CI approval and full packed-consumer validation are still pending.

    6. Thanks @greglum, the full isolated checkout now passes all 2,245 DOM tests, the six additional framework targets, TypeScript, docs and bundle checks. The full packed-package gate also passes, including bare React Native, Expo, seven adapters and the final unified artifact.

      I checked the grid export from that final tarball against a linear scan for 112 edge-case queries, including ties, overflowing extents, tiny coordinates and distance limits. A deliberately broken lookup fails the verifier. This adds packed-package evidence to the earlier browser checks, without changing the optional performance suggestion above. Required CI and the proposed new-entry budget remain separate merge gates.

      Verified head: 7d8c7708107ed7ed677cf5fc05bf6fc9fb8870e1.

    7. tannerlinsleycommented

      Thanks @greglum, this is updated to current main and ready for CI again. The optional grid implementation and your commit history are preserved.

      AI review notes: The reconciliation resolves documentation and generated-metadata conflicts, without changing the grid implementation or existing bundle limits. Independent current-base checks passed: 2,282 DOM tests, 23 tests across six other framework targets, TypeScript, native types, docs, catalogs, formatting, conformance build and all 147 bundle checks. Every existing consumer's compiled output is byte-identical to main. The separate grid entry measures 1.078 decimal kB gzip, below its 1.2288 kB ceiling. All 189 canonical preview assets are unchanged. The packed-package checks cover bare React Native, Expo, seven adapters and the final unified artifact. Contributor execution used an isolated environment without credentials, unrelated files or network access. The earlier browser correctness evidence still applies to the unchanged grid implementation. The optional clustered-query optimization remains a suggestion, with the documented clustered-data caveat retained. This update is not a published release; GitHub checks and review still need to finish on the new head.

      The final public grid export also passed 112 packed edge-case queries, and the deliberately broken lookup failed as expected. After package verification, only comparison source metadata and its documentation references changed; comparison and docs checks passed on those final inputs. Updated head: 6af7b786c523c4ef6ce7a9740c7de080364d27ff.

      Update at fe337abc010174b153a4c622a81f07ebb45211c4: merged main 3f2c82e2 after #245. The only conflict was the preview manifest source hash. The grid implementation and all runtime/test source are unchanged. Fresh frozen install, all 147 bundle checks, the full native/Expo/seven-adapter/unified package gate, 112 packed grid queries, canonical preview generation/check and changed-file formatting pass. All 189 preview asset records remain identical. The earlier DOM/framework evidence is reused for the unchanged runtime/test tree. Existing comparison provenance remains valid, with no baseline edits. Replacement workflows 41533468782 and 41533470740 require approval; the earlier workflow IDs are superseded.

Sign in to join this conversation.