Skip to content

Fix HillshadingTileDataSource caching corrupt tiles and reporting failed renders as success - #1317

Open
jhotadhari wants to merge 1 commit into
mapsforge:masterfrom
jhotadhari:fix/hillshading-cache-corruption
Open

jhotadhari wants to merge 1 commit into
mapsforge:masterfrom
jhotadhari:fix/hillshading-cache-corruption

Conversation

@jhotadhari

Copy link
Copy Markdown

Summary

createTile reported QueryResult.SUCCESS in four cases where the tile had
not rendered or had not been written correctly. One of them committed a
truncated PNG to the on-disk tile cache, producing a permanent rendering
artifact served from disk thereafter.

This is a deliberate behaviour change, not an opt-in addition: renders and
cache writes that previously passed silently as successes are now reported as
failures.

Fixes #1316

Motivation

See the issue for the full analysis. In short, on a hillshading layer with a
tile cache configured:

  • getPngEncodedData() was called on the tile bitmap after
    setTileImage() had handed it to the tile loader, which races with the
    loader recycling it — IllegalStateException: Can't compress a recycled bitmap, 21 times in a few minutes of panning on device;
  • an IOException during the cache write was swallowed and the tile was still
    reported SUCCESS and committed, writing a truncated PNG that was then
    served from disk forever;
  • a shading strip that threw returned true anyway, and createTile discarded
    the result, so a half-shaded tile was displayed and cached as a success;
  • a shading strip walks one shading cell per ShadingLatStep, and each cell's
    tile load was wrapped in a try whose catch was swallowed, so a load that
    threw was indistinguishable from the legitimate no-data case (ocean, or a
    missing .hgt file) at the following shadingTile == null check — the cell
    was skipped as if there were simply no data there, the strip still returned
    true, and the tile was displayed and cached with a hole in it.

What changed

All in vtm-hillshading/src/org/oscim/tiling/source/hills/HillshadingTileDataSource.java.

  • createTile(MapTile, ITileDataSink, ITileCache)
    • New local boolean cacheOk = false.
    • The PNG encode for the cache is moved before sink.setTileImage(...),
      into its own try/catch (Throwable). On failure it logs and leaves
      pngBytes == null; the tile still renders and is still reported
      SUCCESS. A cache-encode failure must not cost the tile.
    • The cache write block runs only when pngBytes != null, and sets
      cacheOk = true only after outputStream.write(...) returns normally.
      The catch (IOException) now logs the tile and does not set cacheOk.
    • finally: cacheWriter.complete(ok && cacheOk) instead of
      complete(ok). complete() is still called unconditionally whenever a
      writer was obtained, since that is what returns the pooled
      ByteArrayOutputStream to TileCache.
    • The strip drain now collects results:
      boolean allStripsOk = true;
      while (!deque.isEmpty()) {
          if (!Boolean.TRUE.equals(deque.pollFirst().get())) {
              allStripsOk = false;
          }
      }
      if (!allStripsOk) {
          // leave res = FAILED
          return;
      }
      The whole deque is always drained, so no task is left pending, and
      SilentFutureTask.get() returning null (its behaviour when the task
      threw) is treated as a failure.
  • renderLatStrip(...)'s Callable<Boolean>
    • catch (Throwable t) now logs with the stack trace
      (log.log(Level.SEVERE, tile + " ...", t) rather than
      log.severe(t.toString())) and returns false instead of falling through
      to return true.
  • renderLatStrip(...), shading-tile load (lines 225-235)
    • The catch (Exception e) around
      mHillsRenderConfig.getShadingTile(...) now logs with the stack trace and
      the tile, and returns false, so the strip drain above reports
      QueryResult.FAILED for the tile.
    • The shadingTile == null / continue path is unchanged on purpose:
      that is the legitimate no-data case (ocean, or a missing .hgt file),
      where skipping that cell is correct and unshaded sea is the desired result.
      A failure here leaves a hole, not wrong shading.

Behaviour change (not a pure addition)

Unlike the other changes in this series, this is a bug fix with a deliberate
behaviour change: renders and cache writes that previously passed silently as
successes are now reported as failures.

  • On QueryResult.FAILED, TileManager.JobCompletedEvent clears the tile to
    NONE and TileManager.addTile re-queues it on the next POSITION_EVENT /
    CLEAR_EVENT. The area shows the parent proxy tile until then.
  • There is no permanent-failure marking or backoff in TileManager, so a tile
    that failed consistently would be retried on each position change while the
    map is moving. In practice these failures are races and the retry succeeds;
    after the fixes for 1–3 the failure path stopped being hit at all (see
    below). Flagging it as a known property of vtm's retry model rather than
    something this PR introduces.
  • A failed cache write no longer fails the tile — only the cache entry is
    skipped. That is a deliberate asymmetry: the rendered tile is fine.

Testing notes

Verified on a Pixel 6 Pro (LineageOS 20), SRTM3 DEM, AdaptiveClasyHillShading,
hillshading layer with a 50 MB SQLite tile cache, release build.

Before the fix, in a few minutes of panning:

Can't compress a recycled bitmap : 21

plus a hard, geo-anchored vertical seam in the hillshading, reproducible at the
same tile-column boundary across sessions and surviving a full cache wipe.

After the fixes for defects 1–3, same scenario (cache wiped, two app starts,
extensive panning):

Can't compress a recycled bitmap : 0
cache write failed               : 0
png encode for cache failed      : 0
shading strip failed             : 0

and no seams. The cache also now behaves correctly, which is the clearest
evidence that defect 1 was starving it:

first start   opened ... rows=0    totalBytes=0
after restart opened ... rows=176  totalBytes=25760546

176 tiles persisted across a restart, then the cache filled to the configured
budget and trimmed normally.

Those measurements cover fixes 1 and 2, which have had several days of
real-world use.

Note: the failure paths for defects 3 and 4 were not observed firing —
they are fixed as defence-in-depth against the same class of bug as 1 and 2,
not because they were the observed cause.

For defect 4 I tried to exercise it deliberately, by replacing an .hgt file
with a zip whose central directory advertises the correct uncompressed size
(so it passes HgtCache.indexFile's perfect-square length check and is indexed
at axisLen = 1201) but whose deflate stream is corrupted. The read does fail
— java.util.zip.ZipException: invalid stored block lengths, ten times over
two runs — but the exception never reaches createTile: mapsforge's
AThreadedHillShading catches it internally and logs it at WARNING, so
getShadingTile simply yields no bitmap, which is indistinguishable from
genuine no-data. So this fix guards a path that mapsforge does not expose for
I/O failures; it still matters for anything that does escape
getShadingTile, but I could not demonstrate it firing and am not claiming it
handles corrupt DEM data.

That experiment did, however, reproduce the underlying symptom: with a freshly
emptied tile cache, the corrupt DEM produced a silently unshaded area and 128
tiles were committed to the cache four seconds after the first read failure.

  • Based on current upstream master (52cf6569 at time of writing).
  • No new unit tests. createTile needs a tile loader, a DEM and a graphics
    backend, so a meaningful test would be an instrumentation test; happy to add
    one if maintainers want it.

Checklist

  • Targets master (based on 52cf6569, single squashed commit, one file)
  • Builds for Android (vtm-hillshading:compileJava, clean rerun)
  • Manually verified on device (see testing notes)
  • Behaviour change acknowledged and documented above
  • 4-space indent, no tabs, UTF-8
  • Instrumentation test — happy to add one if you would like it (see note above)

createTile reported QueryResult.SUCCESS in four situations where the tile
had not rendered or had not been written correctly. One of them committed
a truncated PNG to the tile cache, which was then served from disk on
every later visit -- a permanent, tile-aligned rendering artifact that
survived app restarts and cache clears.

- The tile bitmap was handed to the sink via setTileImage() and only then
  PNG-encoded for the cache. The loader may consume and recycle the
  bitmap in between, so the encode raced and threw "Can't compress a
  recycled bitmap". Encode before handing over; a failure there now costs
  only the cache entry, never the tile.

- An IOException during the cache write was logged and swallowed, and the
  tile was then reported SUCCESS and committed, writing a truncated PNG.
  Track the write and commit only on full success. complete() still
  always runs, since that is what returns the pooled buffer.

- Each longitude strip is a Callable<Boolean> that caught Throwable and
  returned true regardless, and createTile discarded the result, so a
  strip that threw yielded a half-shaded tile presented and cached as a
  success. Strips now report failure and createTile drains them all,
  leaving no task pending, then reports FAILED so the tile is dropped and
  re-queued.

- A getShadingTile failure was swallowed, after which it was
  indistinguishable from the legitimate "no DEM data here" case, so the
  cell was skipped and the tile cached with a hole. The skip is correct
  for genuine no-data and is unchanged; only the exception path now
  reports failure.

Exception logging now includes the stack trace and the tile.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

HillshadingTileDataSource caches corrupt tiles and reports failed renders as success

1 participant