feat(spatial): add opt-in grid spatial index #165
main fromrefs/pull/165/head·opened 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
maxDistancerules - 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
nearestPointon 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
maxDistancevalues, with zero mismatches againstnearestPoint. It was not committed. pnpm performance:pointerchecks every index against the linear result before timing.typecheck,test,docs:check,bundle:checkandformat:checkpass.
Benchmark (pnpm performance:pointer, 960×540 plot, radius 48, query medians):
| Layout | Points | Linear | Grid build | Grid query | Quadtree build | Quadtree query |
|---|---|---|---|---|---|---|
| uniform | 1k | 1.8 µs | 29 µs | 0.1 µs | 140 µs | 0.5 µs |
| uniform | 10k | 16.6 µs | 113 µs | 0.3 µs | 1.04 ms | 1.2 µs |
| uniform | 100k | 187 µs | 1.14 ms | 2.4 µs | 15.7 ms | 5.2 µs |
| vertical strip | 10k | 16.0 µs | 111 µs | 0.1 µs | 1.30 ms | 6.8 µs |
| vertical strip | 100k | 188 µs | 1.12 ms | 0.5 µs | 20.8 ms | 110 µs |
| horizontal strip | 100k | 182 µs | 1.11 ms | 0.6 µs | 25.2 ms | 99 µs |
| clustered | 100k | 183 µs | 1.24 ms | 2.5 µs | 16.9 ms | 3.4 µs |
| pointer in cluster | 1k | 1.7 µs | 20 µs | 3.8 µs | 114 µs | 0.9 µs |
| pointer in cluster | 10k | 17.6 µs | 158 µs | 20.4 µs | 1.78 ms | 1.7 µs |
| pointer in cluster | 100k | 214 µs | 1.29 ms | 112 µs | 24.6 ms | 8.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
Thanks @greglum, the opt-in boundary and strip-query coverage are useful. I reproduced one remaining numeric edge case at
277cd05b536334f71bee4c2992187094933e187din an isolated Chromium context.With two finite anchors at
(-1e308, 0)and(1e308, 0), querying either exact anchor withmaxDistance: 0returnsnull. The linear scan returns the matching point. The same failure occurs for the equivalent vertical and diagonal layouts.maxX - minXoverflows toInfinity. The grid calculation then reachesInfinity / InfinityorInfinity * 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.
Thanks @greglum, the numeric fix at
a94e0e4ea9a2d7c00956d2c412b458895310ed69resolves 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.
🦋 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
Name Type @tanstack/charts Minor @tanstack/alpine-charts Minor @tanstack/angular-charts Minor @tanstack/lit-charts Minor @tanstack/octane-charts Minor @tanstack/preact-charts Minor @tanstack/react-charts Minor @tanstack/react-native-charts Minor @tanstack/solid-charts Minor @tanstack/svelte-charts Minor @tanstack/vue-charts Minor @tanstack/charts-scales Minor 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
Thanks @greglum, I found an optional improvement to the clustered-point case at
7d8c7708107ed7ed677cf5fc05bf6fc9fb8870e1.Inlining the distance comparison inside
visitCell, instead of callingvisitfor 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.
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.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 main3f2c82e2after #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.
No actionable comments were generated in the recent review.
6a94a91a-4d94-4d9a-9a7c-8f5d0d97834dReviewing files that changed from the base of the PR and between 6af7b786c523c4ef6ce7a9740c7de080364d27ff and fe337abc010174b153a4c622a81f07ebb45211c4.
benchmarks/conformance/previews/manifest.jsonIncluded 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
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.mjsgridSpatialIndexthrough@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.packages/charts-core/src/spatial-grid-index.test.ts,benchmarks/entries/charts-spatial-grid-index.ts,benchmarks/interaction/nearest.ts,benchmarks/interaction/README.md.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/*benchmarks/comparison/bundle-baseline.json,benchmarks/conformance/previews/manifest.json,docs/comparison.md,packages/charts-core/docs/comparison.mdEstimated code review effort: 3 (Moderate) | ~25 minutes
Change: Feature
Possibly related issues
Suggested reviewers:
ryansolidMerge Risk:
Minimal · up to
fe337No merge-blocking issue was found in the reviewed change.
Security architecture risk:
Low · up to
277cdThe 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
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
Pre-merge checks:
5
gridSpatialIndexat@tanstack/charts/spatial/grid-indexas an opt-in factory for the existing `sp…Full details: Title check
Explanation
The title "feat(spatial): add opt-in grid spatial index" names the main change. The changeset adds
gridSpatialIndexat@tanstack/charts/spatial/grid-indexas an opt-in factory for the existingspatialIndexoption. 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)
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