Skip to content

fix(geo-layers) call onTileUnload when finalizing a TileLayer - #10883

Merged
chrisgervang merged 4 commits into
visgl:masterfrom
kylebarron:kyle/tileset-2d-unload
Nov 2, 2026
Merged

chrisgervang merged 4 commits into
visgl:masterfrom
kylebarron:kyle/tileset-2d-unload

Conversation

@kylebarron

@kylebarron kylebarron commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #

Background

Currently, onTileUnload is not called when a TileLayer is finalized. This means that any resources created in getTileData don't have an explicit place to be disposed of.

In the case of deck.gl-raster, one of the primary suggested uses is to create luma.gl Texture objects inside of getTileData, so that texture objects don't have to be created each render.

But in this case, when TileLayer.finalize is called, the user has no way to destroy those GPU textures manually.

Change List

  • Call onTileUnload for each loaded tile when finalizing a TileLayer
  • Call onTileUnload whenever a tile finished loading after it has already left the cache
  • Docs update to onTileUnload.

Note

Medium Risk
Changes tile lifecycle callbacks in ways apps may rely on for cleanup; behavior is intentional but late-load paths now fire unload instead of load.

Overview
Tileset2D (used by TileLayer) now treats onTileUnload as the lifecycle hook for tearing down per-tile resources created in getTileData, including on layer teardown and for late-arriving tile data.

On finalize(), every cached tile triggers onTileUnload (after aborting in-flight loads), so GPU textures and similar assets can be disposed when the layer is removed. When a tile’s load completes after it was already evicted or the cache was cleared, onTileLoad is skipped and onTileUnload runs instead (possibly a second time once content is set). Tile layer docs describe this onTileUnload behavior; unit tests cover finalize, delayed loads, and cache eviction while loading.

Reviewed by Cursor Bugbot for commit 8c0da5c. Bugbot is set up for automated code reviews on this repo. Configure here.

kylebarron added a commit to developmentseed/deck.gl-raster that referenced this pull request Oct 21, 2026
…oved (#728)

> [!NOTE]
> This PR was written by Claude (Claude Code), not by @kylebarron.

Removing a `COGLayer`, `MultiCOGLayer` or other `RasterTileLayer` now
destroys its cached tile textures, instead of leaving them to the
garbage collector.

deck.gl's `Tileset2D` calls `onTileUnload` only when it evicts a tile
from its cache. When the layer is removed, `Tileset2D.finalize` clears
the cache without calling it, so the textures that `getTileData` made
for those tiles were never destroyed. The browser frees a WebGL texture
only when garbage collection collects it, and GPU memory doesn't trigger
garbage collection.

`RasterTileset2D.finalize` now calls `onTileUnload` for every cached
tile. A tile still loading is unloaded once its load finishes, because
deck.gl keeps the data that `getTileData` returns after an abort.

visgl/deck.gl#10883 makes deck.gl's `Tileset2D` do this itself. Once a
deck.gl release includes it, this override can be removed.

The layers already destroy their textures in `onTileUnload`: `COGLayer`
and `MultiCOGLayer` for their default pipelines, and custom
`getTileData` such as the terrain example's NAIP tiles. They need no
changes.

### Measurements

luma.gl's `Texture Memory` and `Textures Active` counters drop only when
a texture is destroyed. Measured in headed Chrome at 1200x750, DPR 1, 15
s after each switch.

`cog-basic`, switching between Sentinel-2 (New York) and EOxCloudless:

| | Before | After |
|---|---|---|
| Sentinel-2 | 1.8 MB, 8 textures | 1.8 MB, 8 textures |
| EOxCloudless | 4.3 MB, 10 | 3.5 MB, 8 |
| Sentinel-2 | 6.1 MB, 15 | 1.8 MB, 8 |
| EOxCloudless | 9.6 MB, 19 | 3.5 MB, 8 |
| Sentinel-2 | 11.4 MB, 23 | 1.8 MB, 8 |

`cog-terrain`, switching between NAIP (nine COGs) and the Swiss map:

| | Before | After |
|---|---|---|
| NAIP | 291 MB, 270 textures | 292 MB, 272 textures |
| Swiss map | 516 MB, 313 | 472 MB, 246 |
| NAIP | 727 MB, 500 | 650 MB, 396 |
| Swiss map | 952 MB, 547 | 832 MB, 378 |

Texture memory in `cog-terrain` still grows because of a separate
deck.gl leak. `TerrainEffect` keeps a drape texture of up to 16 MB for
each terrain tile. When the terrain tile goes away,
`_pruneTerrainCovers` removes its `TerrainCover` from a map without
calling `delete()`. Live framebuffers went from 47 to 132 in both runs.

### Not covered

These are deck.gl paths, tracked in #733:

- A tile evicted while it's still loading is reported as loaded when its
data arrives, and nothing unloads it. visgl/deck.gl#10883 fixes this
too.
- `Tileset2D.reloadAll` removes unselected tiles from the cache without
unloading them. `TileLayer` reloads only when the update triggers for
`getTileData` change.
- A reload replaces a tile's content without unloading the old content.

### Tests

`raster-tileset-2d-unload.test.ts` covers three cases:

- `finalize` unloads every cached tile.
- A tile still loading at `finalize` is unloaded once its data arrives,
not before.
- A tile whose load stops at the abort is still unloaded.

All three fail without this change.

🤖 Written by [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@greptile-apps

greptile-apps Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with only the earlier non-blocking test timing concern remaining.

Findings

  1. P2 Late-load tests depend on timing ▶

Summary

Tileset2D now calls onTileUnload for cached tiles during finalize() and for data that arrives after a tile leaves the cache.

  • Removing a TileLayer calls the unload callback for every cached tile.
  • Tiles that finish after leaving the cache go to the unload callback.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  F["finalize()"] --> A["Abort pending requests"]
  A --> U["Call onTileUnload for cached tiles"]
  U --> C["Clear cache"]
  L["Tile data arrives"] --> Q{"Same tile still cached?"}
  Q -->|Yes| N["Call onTileLoad and count bytes"]
  Q -->|No| D["Call onTileUnload without counting bytes"]
Loading

Reviews (2) · Last reviewed commit: "Merge branch 'master' into kyle/tileset-..." · Reviewed by Greptile

let tileLoadCalled = 0;
const unloaded: {id: string; content: unknown}[] = [];
// getTileData ignores the abort and returns data anyway
const tileDataPending = sleep(50).then(() => ({byteLength: 1}));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Late-load tests depend on timing

Both new late-load tests let tileDataPending resolve after 50 ms instead of keeping it pending until after finalize() or eviction. If setup or a pause takes long enough, the data can arrive first and the tests fail even when cleanup works correctly. Use a promise the test resolves explicitly: wait until getTileData starts, finalize or evict, then resolve the data.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@coveralls

coveralls commented Oct 21, 2026 •

Copy link
Copy Markdown

Coverage Status

No base build to compare — kylebarron:kyle/tileset-2d-unload into visgl:master

@charlieforward9 charlieforward9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

solves an issue I was having as well. Thanks!

@chrisgervang chrisgervang mentioned this pull request Oct 29, 2026
29 of 30 tasks
kylebarron added a commit to developmentseed/deck.gl-raster that referenced this pull request Oct 30, 2026
kylebarron added a commit to developmentseed/deck.gl-raster that referenced this pull request Oct 30, 2026
…urces when it's removed (#823)

> [!NOTE]
> This PR was written by Claude (Claude Code), not by @kylebarron.

When a MosaicLayer is removed, `onSourceUnload` now fires for every
source the layer still holds.

deck.gl's `Tileset2D.finalize` clears its cache without calling
`onTileUnload`, so MosaicLayer never reported those sources.
`MosaicTileset2D` now unloads every cached item on finalize, as
`RasterTileset2D` does for tiles (#728). An item still opening is
unloaded once its open finishes, since deck.gl keeps what an aborted
open returns anyway.

This is the first step toward #816. Re-opening sources through
`updateTriggers` will replace MosaicLayer's inner TileLayer, which drops
its cache the same way.

The override repeats `RasterTileset2D.finalize`. visgl/deck.gl#10883
would make deck.gl do this itself, and then both could go.

Ref #816

## Tests

These run in deck.gl's `LayerManager`, and both failed before the fix:
- removing the layer passes each loaded item's source to
`onSourceUnload`;
- an item still opening at removal is passed to it once its source
arrives. Unloading the item right away instead fails this test.

🤖 Written by [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@chrisgervang chrisgervang added this to the v9.4 patch releases milestone Nov 2, 2026
@chrisgervang chrisgervang changed the title Call onTileUnload when finalizing a TileLayer fix(geo-layers) call onTileUnload when finalizing a TileLayer Nov 2, 2026
@chrisgervang
chrisgervang merged commit 79c8a7b into visgl:master Nov 2, 2026
9 checks passed
chrisgervang pushed a commit that referenced this pull request Nov 3, 2026
kylebarron added a commit to developmentseed/deck.gl-raster that referenced this pull request Nov 11, 2026
<img width="1280" height="800" alt="01-similarity"
src="https://github.com/user-attachments/assets/595b09b6-8720-43db-b973-b19a71a246fc"
/>

<img width="1280" height="800" alt="02-clusters"
src="https://github.com/user-attachments/assets/ae6a2efa-7caf-4dc9-bb9f-15687c90b20e"
/>
<img width="1280" height="800" alt="03-classifier"
src="https://github.com/user-attachments/assets/40b19db6-28e2-4b09-888f-eb0112286640"
/>

> [!NOTE]
> This PR was written by Claude (Claude Code) on behalf of @kylebarron,
not by @kylebarron.

An experimental example that runs small ONNX models over AlphaEarth
embeddings in the browser. It reads the same GeoZarr mosaic as
`aef-mosaic` (64-band int8 embeddings) with `ZarrLayer`, and uses [ONNX
Runtime Web](https://onnxruntime.ai/docs/tutorials/web/) on WebGPU to
compute a result per pixel for every loaded tile, drawn through
deck.gl-raster's WebGL2 pipeline.

## What it does

- **Similarity.** Every loaded tile shows its cosine similarity to one
pixel's embedding. It starts with the pixel in the middle of the map;
click another to search again. Changing the query re-runs the resident
tiles in place, with no refetch.
- **Clusters.** k-means runs in JavaScript on pixels sampled from the
loaded tiles; a model assigns every pixel to its nearest centroid.
- **Classifier.** Click positive and negative points, a logistic
regression is fitted in JavaScript on their embeddings, and a model
draws the probability map. Its learning rate, number of steps and L2
penalty are controls in the panel. Until there is at least one positive
and one negative point, a notice at the bottom of the map says which is
still missing.
- **RGB.** The three-band composite from `aef-mosaic`, as its own mode.

A "Show embeddings underneath" checkbox, on by default, draws the RGB
composite dimmed under the model modes' results, as a cue for where data
has loaded. With it off, results draw over the plain basemap, pixels
below the threshold are not drawn, and a mode with nothing to show yet
draws nothing.

In a browser without WebGPU, a dialog says that the models need it and
offers the RGB mode, which draws without a model.

## How it works

- The models are about a kilobyte each. Each is a Python function in
`models/make_models.py` that
[onnxscript](https://github.com/microsoft/onnxscript) translates to
ONNX, committed under `public/models/`. `uv run models/make_models.py
public/models` rebuilds them and checks them against NumPy. The query
vector, the centroids and the classifier weights are model inputs, so
they change per run without a new model. The models use opset 23, the
highest at which ONNX Runtime Web 1.31 keeps the int8 conversion on
WebGPU.
- ONNX Runtime owns its own WebGPU device, separate from deck.gl's
WebGL2 context, so results come back to the CPU and are uploaded as
textures. All runs go through one queue, because two `session.run` calls
in flight on one session never resolve.
- The models take the raw int8 tile and dequantize it on WebGPU, with a
`DequantizeLinear` node. Every session disables ONNX Runtime's CPU
fallback, so every node of every model runs on WebGPU.

## Numbers

Measured on an M2 Pro in headless Chromium; tiles are 256 x 256 x 64
int8.

| | Time |
|---|---|
| One model run on one tile, nothing else on the page | **3.3 ms** |
| One query change over 15 tiles, in the app | 65 to 120 ms |

Each loaded tile holds 4 MiB of int8 embeddings on the CPU and a 4 MiB
texture for the RGB composite. An earlier version could also keep a
float32 copy of each tile on ONNX Runtime's GPU device. That made a run
about three times faster but cost 16 MiB of GPU memory per tile, so it
was removed.

The in-app times vary that much from run to run. `NOTES.md` has every
measurement.

The ONNX Runtime WebAssembly file is 28.7 MB, 7.3 MB gzipped, loaded
when the first model runs.

## Things to decide before this is more than a draft

- **It is not listed on the docs examples page** and has no card image.
The docs workflow builds every example directory, so on merge it would
still be published at `/examples/onnx-embeddings/`, including the 28.7
MB WebAssembly file.
- **`NOTES.md`** is a findings log: the design, a friction log for ONNX
Runtime Web, and measurements. It is useful background but unusual for
an example directory, and can be dropped.
- **Correction: there is no texture leak on a year change.** An earlier
version of this description said `aef-mosaic` might leak textures when
the year changes. That was wrong: `RasterTileset2D.finalize()` calls
`onTileUnload` for every cached tile when the inner TileLayer is
replaced, and ten year changes in `aef-mosaic` left no orphaned
textures. This example's own cleanup on a year change was therefore
freeing tiles twice, and is removed. The leak that does exist is the
known one for tiles evicted while still loading (#876,
visgl/deck.gl#10883), which `maxCacheSize: 10` makes common in both
examples.

## Test plan

- [x] The example's `typecheck` passes, `biome ci` passes on its
directory, and `vite build` produces a site that serves the WebAssembly
file locally.
- [x] Checked in headless Chromium with a real GPU: each mode draws
(screenshots above), also after the models were regenerated with
onnxscript.
- [x] After the review changes: all three models load with the CPU
fallback disabled, and each mode and each classifier setting was
re-checked in headless Chromium with no console errors.
- [x] Without WebGPU, both with no `navigator.gpu` and with no adapter,
a dialog explains that the models need it and offers the RGB mode. No
errors are logged.
- [ ] Not checked: other GPUs and browsers, load time over a real
network.

🤖 Written by [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
kylebarron added a commit to developmentseed/deck.gl-raster that referenced this pull request Nov 16, 2026
…nloaded (#878)

> [!NOTE]
> This PR was written by Claude (Claude Code) on behalf of @kylebarron,
not by @kylebarron.

Closes #876

### Problem

A tile that is unloaded while it is still loading can leak its textures:

1. deck.gl 9.4.1 evicts tiles that are still loading when its cache is
over the limit, and calls `onTileUnload` while their `content` is still
`null`. `RasterTileset2D`'s own wrapper does the same when it aborts an
unwanted load.
2. If the load still returns data, because `getTileData` doesn't stop at
the abort or was never aborted, deck.gl keeps the result as the tile's
content.
3. The tile has already left the cache, so `onTileUnload` never runs for
it again, and whatever `getTileData` created is never freed.

#876 describes this for a `COGLayer` tile aborted mid-decode. It also
happens with no abort at all: `ZarrLayer` doesn't abort unwanted loads,
and `aef-mosaic` sets `maxCacheSize: 10` with about 15 tiles in view, so
short pans evict tiles mid-load.

### Fix

`RasterTileset2D` remembers the tiles it has passed to `onTileUnload`,
in a `WeakSet`. When one of them finishes loading, it calls
`onTileUnload` again, now with content, instead of `onTileLoad`. This is
the "unload late results centrally" option from #876, so custom
`getTileData` pipelines are covered too.

#728 knowingly left this case to the upstream fix. This brings a guard
back for the interval before that fix is published. visgl/deck.gl#10883
makes the same change in deck.gl's own load handler, due in 9.4.2.
There, deck.gl unloads the late tile and returns before it calls
`onTileLoad`, so this guard is never reached and nothing is unloaded
twice. The guard can go when the overrides in #863 go.

### Measured

`aef-mosaic` on `main` with deck.gl 9.4.1, headless Chromium at 1280 x
800: 16 round trips of a 300 px pan, then a wait until no loads were
left. An orphaned texture is a tile texture that no live tile holds and
that was never destroyed.

| Build | Orphaned tile textures | `Texture Memory` | `Textures Active`
|
|---|---|---|---|
| `main`, run 1 | **11** | **122 MB** | 47 |
| `main`, run 2 | **8** | **109 MB** | 44 |
| This PR | **0** | 76 MB | 36 |

With this PR, 15 tiles finished loading after they had been unloaded
empty, and all 15 were freed.

### Not covered

- **The wasted work.** A tile aborted after its bytes arrive is still
decoded and uploaded, and then freed. #876 lists two changes that would
skip that: checking `signal` before `device.createTexture` in the
default `getTileData`, and passing `signal` into `pool.decode`. They are
not in this PR; #879 tracks them.
- **`MosaicTileset2D`** extends deck.gl's `Tileset2D` directly, so it
doesn't get this guard. I didn't check whether a mosaic item evicted
mid-load leaks its source.

### Test plan

- [x] A new unit test evicts tiles that are still loading, then lets
their data arrive. It fails on `main`, where the tiles are never
unloaded, and passes here. It runs with `abortUnwantedLoads` both off
and on.
- [x] The package's 262 tests pass, and `typecheck` and `biome ci` pass.
- [x] The pan measurement above, run with and without the change.
- [ ] Not checked in a browser: the `COGLayer` mid-decode case from
#876. The unit test with `abortUnwantedLoads` on follows the same path.

🤖 Written by [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5.2 <[email protected]>
@chrisgervang

Copy link
Copy Markdown
Collaborator

Released in deck.gl 9.4.2. Thanks @kylebarron!

kylebarron added a commit to developmentseed/deck.gl-raster that referenced this pull request Nov 24, 2026
…s redundant (#886)

> [!NOTE]
> This PR was written by Claude (Claude Code) on behalf of @kylebarron,
not by @kylebarron.

Closes #863

### Problem

deck.gl [9.4.2](https://github.com/visgl/deck.gl/releases/tag/v9.4.2)
includes visgl/deck.gl#10883:
- `Tileset2D.finalize` calls `onTileUnload` for every cached tile.
- A tile whose load finishes after it left the cache is unloaded instead
of reported loaded.

Our workarounds for 9.4.1 do the same thing. On 9.4.2, they unloaded
every tile twice. That destroyed default-pipeline textures twice and ran
user `onTileUnload` / `onSourceUnload` callbacks twice (#863). With the
lockfile moved to 9.4.2, five tests failed this way before this change.

### Change

This is option 2 from #863:
- Every `@deck.gl/*` spec, including peer deps, pnpm overrides and
examples, now requires `^9.4.2`. The lockfile moves only deck.gl.
- `RasterTileset2D`: removes the `finalize` override and the late-load
guard from #878. The `abortUnwantedLoads` wrapper of `onTileUnload`
stays.
- `MosaicTileset2D`: removes the `finalize` override. `reloadAll` stays,
because deck.gl's `reloadAll` still drops items without unloading them.
It now calls deck.gl's `finalize`.
- `custom-projection` example: removes its `finalize` override.
- `MosaicLayer.onSourceUnload` docs: an item that is still opening is
unloaded with no source, then again with its source once the open
finishes.
- `onnx-embeddings/NOTES.md`: no longer says the mid-load eviction leak
applies.

### Test plan

- [x] `deck.gl-raster` (263), `deck.gl-geotiff` (224) and `deck.gl-zarr`
(81) tests pass on 9.4.2.
- [x] One test encoded 9.4.1 behavior, with no unload at `finalize` for
a loading tile. It now expects an unload right away with no content,
then another once the data arrives.
- [x] `biome ci` passes.
- [ ] Not checked in a browser.

Follow-up: switch the examples to `@deck.gl/maplibre` (#661), which
visgl/deck.gl#10734 in 9.4.2 unblocks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_011cLtCQHxJfGKqmXPYrjSPA

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants