Repository navigation
fix(deck.gl-raster): destroy tile textures when a raster layer is removed - #728
Conversation
deck.gl's Tileset2D calls onTileUnload only when it evicts a tile. Its finalize clears the cache without calling it, so removing a COGLayer, MultiCOGLayer or other RasterTileLayer left every cached tile's textures to the garbage collector, which GPU memory doesn't trigger. Switching datasets in cog-basic grew luma.gl's live texture count from 8 to 23 over two round trips; with this change it stays at 8. RasterTileset2D now calls onTileUnload for every cached tile in finalize. It also unloads a tile whose data arrives after the tile has left the cache, aborted by finalize or evicted while loading, instead of reporting it as loaded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| * Unloads every cached tile. deck.gl's `Tileset2D.finalize` clears its cache | ||
| * without calling `onTileUnload`, so GPU resources that `getTileData` made | ||
| * for those tiles, like textures, would be freed only by garbage collection. | ||
| * A tile still loading is unloaded again when its data arrives. |
There was a problem hiding this comment.
This is surprising... why would deck.gl not clear its cache? Is that intentional?
There was a problem hiding this comment.
Note
This comment was written by Claude (Claude Code), not by @kylebarron.
deck.gl does clear the cache (finalize calls this._cache.clear()). What it skips is calling onTileUnload for the tiles it drops, so the layer never gets a chance to destroy their textures.
It doesn't look intentional. Three deck.gl PRs, written at different times, never connected:
- Add onTileUnload callback for TileLayer visgl/deck.gl#4936 (2020) added
onTileUnloadand wired it only into cache eviction. The docs say it's "called when a tile is cleared from cache". - Abort Ongoing Tile Requests When New Tileset is Created visgl/deck.gl#5342 (2021) added
finalize(), only to abort requests still in flight. - TileLayer retains cache on data change visgl/deck.gl#6194 (2021) made
finalize()clear the cache and addedreloadAll(), which also deletes tiles.
Neither of the last two mentions unloading anywhere in its discussion. deck.gl's own tile layers never hit this: their getTileData returns CPU data, and their GPU resources belong to sublayers, which deck.gl finalizes. Our layers keep textures in the tile content, so they need every path that drops a tile to call onTileUnload. #733 tracks fixing it upstream.
🤖 Written by Claude Code
There was a problem hiding this comment.
fix submitted upstream in visgl/deck.gl#10883
| /** | ||
| * Unloads a tile whose data arrives after it has left the cache, instead of | ||
| * reporting it as loaded. deck.gl keeps the data that `getTileData` returns | ||
| * for a tile it has aborted or evicted, and nothing else would unload it. | ||
| */ | ||
| override setOptions(opts: Tileset2DProps): void { | ||
| const { onTileLoad } = opts; | ||
| super.setOptions( | ||
| onTileLoad | ||
| ? { | ||
| ...opts, | ||
| onTileLoad: (tile) => { | ||
| // `tiles` is rebuilt from the cache whenever an update or an | ||
| // eviction changes it, and a tile loads only after the update | ||
| // that created it. | ||
| if (this.tiles.includes(tile)) { | ||
| onTileLoad(tile); | ||
| } else { | ||
| this.opts.onTileUnload(tile); | ||
| } | ||
| }, | ||
| } | ||
| : opts, | ||
| ); | ||
| } |
There was a problem hiding this comment.
this looks a little bit less clear than the below change. I don't see why we need to override this. I've never even seen this method before
There was a problem hiding this comment.
Note
This comment was written by Claude (Claude Code), not by @kylebarron.
setOptions is the public Tileset2D method that gives the tileset its options and callbacks. The base constructor calls it, and TileLayer calls it again whenever its props change.
The override handled tiles whose data arrives after they've left the cache: a tile that finalize aborted while its getTileData was still running, or one evicted mid-load. deck.gl keeps that data and still reports the tile as loaded, so nothing ever unloads it. The handler that reports the load is a private field set in the constructor, so wrapping onTileLoad on its way into opts was the only public hook.
It did little for its complexity, so we're dropping it from this PR. finalize will handle tiles still loading when the layer is removed: it waits on tile.data, which is a promise while a tile loads, and unloads each tile once its load finishes. Tiles evicted mid-load stay uncovered until deck.gl fixes this upstream (#733).
🤖 Written by Claude Code
…changes (#731) > [!NOTE] > This PR was written by Claude (Claude Code), not by @kylebarron. Follow-ups to #720's terrain example, from a final review of its camera changes: - **Scene changes reset the exaggeration** to the default 1.5x. Every start view is set for it. At 3x, NAIP's start put the camera inside the terrain in short windows, and jumped back about 1.6 zoom levels in 750 px ones. - **Lowering the exaggeration leaves the camera where it is.** Lowered with the terrain, the camera ended up nearer the ground, and the new `TerrainController`'s first pick could zoom past `maxZoom` and jump back. Raising it still raises the camera with the terrain. - **The camera math uses the window's size.** The view states the controller emits keep a stale size after a resize, until you next move the map. - **Wording:** - The NAIP start view's thresholds are 630 px, and 1760x1100 at the default exaggeration. - The pitch limit of 70 raises deck.gl's default of 60 rather than capping it. - The `naip.ts` comment on cancelled tiles no longer depends on #728. ### Not fixed: the first pick after an exaggeration change The review found that the new `TerrainController`'s first pick can land on the wrong ground, and suggested a new `TerrainLayer` per exaggeration. I tried that, and also waiting for the terrain to load before handing the camera to a `TerrainController`. Neither changed the result. - Raising NAIP from 1.5x to 2x put the target at 6,005 m on terrain beyond the summit. The slope in view is at 8,360 m. - This happened even with every terrain tile loaded. - The pick reports the correct terrain tile, but a point farther along the view ray than the visible surface. - Picks from a view whose target is on the ground come back correct, so this looks like a deck.gl picking issue. The README now describes it: the target eases to the ground as you move, so zooming straight in after raising the exaggeration can take the camera into the slope. Checked in headed Chrome at 1200x750: - 1.5x to 3x one step at a time, and back down to 1x. The zoom never passed 12.2, and the terrain stayed in view. - Scene switches reset the slider, and NAIP's start view lands where it does on first load (zoom 13.58). - No console errors. 🤖 Written by [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
Drop the `setOptions` override, which wrapped `onTileLoad` to unload a tile that finished loading after it had left the cache. `finalize` now covers the tiles still loading when the layer is removed: it waits on `tile.data`, which is a promise while a tile loads, and unloads each tile once its load finishes. Every cached tile gets exactly one `onTileUnload`, including tiles whose load stops at the abort. A tile evicted while loading is no longer unloaded here. That path is left to the upstream deck.gl fix tracked in #733. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s selection changes (#818) > [!NOTE] > This PR was written by Claude (Claude Code), not by @kylebarron. Stage 4c of the Sources design (`dev-docs/specs/2026-10-22-sources-design.md`, decision 24). Closes #797. Layers built on `RasterTileLayer` fetch their tiles again when `updateTriggers.getTileData` or `updateTriggers.all` changes. `ZarrLayer` also does when `selection` changes: ```ts new ZarrLayer({ id: "temperature", source, selection: { time: t }, getTileData, renderTile }); ``` - **The old tiles go at once.** Where new tiles haven't loaded yet, the map shows nothing rather than the old selection's data. - **How:** each refetch gives the inner TileLayer a new id. deck.gl removes the old one, and its tileset aborts the loads in flight and unloads every tile (#728). Subclasses call the new protected `_refetchTiles()`. - **Selections are compared by value,** so an inline `{ time: t }` with the same contents fetches nothing. A change to `updateTriggers.renderTile` still only redraws. - **Not deck.gl's reload:** a `getTileData` trigger on deck.gl's `TileLayer` calls `Tileset2D.reloadAll`. In 9.4 that: - drops the tiles it doesn't need without `onTileUnload`; - leaves those tiles in `tileset.tiles`, still marked visible; - overwrites reloaded tiles' data without `onTileUnload`. Forwarding the triggers, as #797 proposed, would leak textures and draw stale tiles. - **MosaicLayer** builds its own TileLayer. Its part of #797 is #816. ## Migration Apps that put the selection in a ZarrLayer's `id`, or passed `updateTriggers: { renderTile: [selection] }`, can drop both: ```ts // Before new ZarrLayer({ id: `layer-${year}`, selection: { year }, ... }); // After new ZarrLayer({ id: "layer", selection: { year }, ... }); ``` ## Examples and docs - **Examples:** - aef-mosaic and dynamical-zarr-ecmwf drop the selection from their layer `id`. - The experimental `ProjectedCOGLayer` renders its own TileLayer in custom-projection views, and now puts the refetch count in that TileLayer's id too. `_refetchTiles` documents this for subclasses. - **Docs:** - The `getTileData` docs of `RasterTileLayer`, COGLayer and ZarrLayer say how to fetch the tiles again, and that deck.gl compares a trigger's elements with `===`. - ZarrLayer's `selection` docs say that a new selection fetches them again. - **Spec:** records decision 24, and stage 4c as built. ## Tests - **`RasterTileLayer`, in deck.gl's `LayerManager`,** with a real tile grid and viewport: - a changed `updateTriggers.getTileData` aborts every load in flight, unloads every tile, and fetches the visible tiles again; - a changed `updateTriggers.all` does the same; - an equal `getTileData` trigger keeps the tiles, and so does a changed `renderTile` trigger. - **`COGLayer`, in deck.gl's `LayerManager`,** with a COG fixture: a changed `updateTriggers.getTileData` aborts and unloads the loaded tile, and fetches it again. COGLayer inherits this from `RasterTileLayer`, since it overrides neither `updateState` nor `renderLayers`. - **`ZarrLayer`:** a new selection gets a new inner TileLayer; an equal one doesn't. - **`ProjectedCOGLayer`:** a refetch gets a new inner TileLayer. - **Mutation checks:** each of these fails a test: - ignoring `all`; - leaving the count out of the inner id; - not refetching on a trigger, in `RasterTileLayer`'s build, for the COGLayer test; - not refetching on a new selection; - leaving the count out of `ProjectedCOGLayer`'s id. - **In Chrome:** I counted live WebGL textures by wrapping `createTexture` and `deleteTexture`. - **aef-mosaic:** - switching the year removes the old tiles at once; - over 8 switches, two of them 300 ms apart, live textures stayed between 51 and 61, out of 335 created in all. - **dynamical-zarr-ecmwf:** - 250 ms after each forecast-date switch, live textures fall from 56 to 14, which are the basemap's; - they return to between 50 and 56 once the new run loads, over 6 switches; - the lead-time animation changes `renderTile` every 100 ms and creates no textures. 🤖 Written by [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
> [!NOTE] > This PR was written by Claude (Claude Code), not by @kylebarron. `MosaicLayer` passed `renderSource` the signal of the item's open. Both its docs example and the naip-mosaic example passed it on to each COGLayer's `signal`. That signal can't do what passing it suggests, and it can leave an item blank: - **It can't stop a layer's tile loads.** deck.gl doesn't abort a tile once it has loaded, and `renderSource` only draws items whose open has finished. - **It can arrive already aborted.** Say an item's open is aborted while more than `maxRequests` opens are in flight, and its `getSource` finishes anyway. Then deck.gl keeps the source, together with the aborted signal. - naip-mosaic's shared per-URL cache allows that: a later load's abort doesn't reject the promise that an earlier load started. - When the item is drawn again, its COGLayer gets the aborted signal, and every tile load aborts at once. The item stays blank for as long as its mosaic tile stays cached. `renderSource` now gets only `{ source }`. A COGLayer already aborts its loads that leave the view (#809). It aborts the rest when MosaicLayer evicts its item and the layer is finalized (#728). ## Migration Drop `signal` from `renderSource`'s options. 0.10 already changes them from `{ data }` to `{ source }`. ```ts // Before renderSource: (item, { source, signal }) => new COGLayer({ id: item.url, source, signal }), // After renderSource: (item, { source }) => new COGLayer({ id: item.url, source }), ``` ## Tests - **The bug, in deck.gl's `LayerManager`.** The test reproduces it step by step: 1. With `maxRequests: 1`, item A's open is aborted when A leaves the view while F's starts. 2. A's `getSource` finishes anyway. 3. A comes back into view. Before the fix, `renderSource` got an aborted signal. Now it gets `{ source }`. - **A type test:** `renderSource`'s options are exactly `{ source?: SourceT }`. It fails if `signal` is added back. - **The workspace typecheck** passes, naip-mosaic included. - **In Chrome:** naip-mosaic draws as before (924 NAIP items over Denver), with no new console messages. 🤖 Written by [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
…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]>
> [!NOTE] > This PR was written by Claude (Claude Code), not by @kylebarron. Bumps: - `@deck.gl/*` 9.4.0 → [9.4.1](https://github.com/visgl/deck.gl/releases/tag/v9.4.1) - `@developmentseed/{deck.gl-raster,affine,morecantile,raster-reproject}` 0.8.1 → [0.9.0](https://github.com/developmentseed/deck.gl-raster/releases/tag/v0.9.0) → [0.10.0](https://github.com/developmentseed/deck.gl-raster/releases/tag/v0.10.0) The deck.gl overrides in `pnpm-workspace.yaml` go to `^9.4.1` too. Without that, pnpm keeps every overridden deck.gl package at 9.4.0 and only `@deck.gl/react` moves. deck.gl-raster 0.10 now depends on `@developmentseed/range-reader`, so I added it to the commented-out local-checkout overrides. The breaking changes in deck.gl-raster 0.9 and 0.10 are in `deck.gl-geotiff`, `deck.gl-zarr` and `geotiff`, which Lonboard doesn't use. Lonboard only imports `RasterTileLayer`, `TileMatrixSetAdaptor` and `MinimalTileData`, and needs no code changes. Upstream fixes relevant to Lonboard: - deck.gl-raster: tile textures are destroyed when a raster layer is removed (developmentseed/deck.gl-raster#728), and a WebGL vertex array no longer leaks per tile (developmentseed/deck.gl-raster#786). - deck.gl-raster: missing TileMatrixSet bounds are inferred and `extent` is honored (developmentseed/deck.gl-raster#684). The `TMSBoundingBox` step in `examples/raster-titiler.ipynb` (#1327) should no longer be needed. That isn't tested here. - deck.gl: the MapLibre overlay container is removed with the overlay (visgl/deck.gl#10899), and `GlobeController` can zoom past level 12 (visgl/deck.gl#10737). The `beforeId` fix for interleaved MapLibre (visgl/deck.gl#10734) merged after 9.4.1, so the `idle` workaround tracked in #1293 stays. Supersedes Dependabot's #1350, which stops at deck.gl-raster 0.9.0. Closes #1350 ## Testing - `pnpm build`, `pnpm check` and `pnpm test` (12 tests) pass. - `uv run pytest` passes: 367 passed, 1 skipped, including `tests/ui`. - `tsc --noEmit` reports the same 9 errors as `main`, and no new ones. - No test covers `RasterLayer.from_geotiff`, the only path that uses deck.gl-raster's `RasterTileLayer`. I checked it by hand with a throwaway UI test. It opens a 2048×2048 EPSG:32618 COG with 3 overviews and renders it with no basemap. Tiles reach the canvas on this branch and on `main`, and the browser console output is the same on both. 🤖 Written by [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
…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]>
Note
This PR was written by Claude (Claude Code), not by @kylebarron.
Removing a
COGLayer,MultiCOGLayeror otherRasterTileLayernow destroys its cached tile textures, instead of leaving them to the garbage collector.deck.gl's
Tileset2DcallsonTileUnloadonly when it evicts a tile from its cache. When the layer is removed,Tileset2D.finalizeclears the cache without calling it, so the textures thatgetTileDatamade 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.finalizenow callsonTileUnloadfor every cached tile. A tile still loading is unloaded once its load finishes, because deck.gl keeps the data thatgetTileDatareturns after an abort.visgl/deck.gl#10883 makes deck.gl's
Tileset2Ddo this itself. Once a deck.gl release includes it, this override can be removed.The layers already destroy their textures in
onTileUnload:COGLayerandMultiCOGLayerfor their default pipelines, and customgetTileDatasuch as the terrain example's NAIP tiles. They need no changes.Measurements
luma.gl's
Texture MemoryandTextures Activecounters 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:cog-terrain, switching between NAIP (nine COGs) and the Swiss map:Texture memory in
cog-terrainstill grows because of a separate deck.gl leak.TerrainEffectkeeps a drape texture of up to 16 MB for each terrain tile. When the terrain tile goes away,_pruneTerrainCoversremoves itsTerrainCoverfrom a map without callingdelete(). Live framebuffers went from 47 to 132 in both runs.Not covered
These are deck.gl paths, tracked in #733:
onTileUnloadwhen finalizing a TileLayer visgl/deck.gl#10883 fixes this too.Tileset2D.reloadAllremoves unselected tiles from the cache without unloading them.TileLayerreloads only when the update triggers forgetTileDatachange.Tests
raster-tileset-2d-unload.test.tscovers three cases:finalizeunloads every cached tile.finalizeis unloaded once its data arrives, not before.All three fail without this change.
🤖 Written by Claude Code