Skip to content

Claude suggestions for performance focus #352

Open

Description

@kylebarron

Given this prompt:

This is a Rust and Python library to efficiently read TIFF files.

I've checked out libtiff in ~/github/libsdl-org/libtifff. Please scan it and create a report of where to invest resources to improve the performance of async-tiff.

Note that async-tiff, as the name suggests, focuses on async reading. While we want to support reading local TIFF files, the primary performance goal is on efficiently reading GeoTIFFs from cloud storage (S3, GCS, Azure, etc). This is why we usually build on top of the Rust object_store library.

Note also that async-geotiff (~/github/developmentseed/async-geotiff) is a Python library that extends async-tiff for parsing GeoTIFFs. For now, we're content with having the GeoTIFF parts managed in Python instead of Rust. Any TIFF performance improvements should ideally also improve GeoTIFF parsing as well.

You aren't limited only to libtiff as a source for where to find improvements for TIFF performance, but if you find improvements from other projects, please cite them.

The most limited resource here is maintainer bandwidth. So please order your suggestions in terms of greatest performance bang for the buck in a ratio to maintainer bandwidth.

We don't want the source code of async-tiff to be vibe coded. It's imperative that a human is carefully checking any source code of async-tiff. That said, for benchmarking and tests, some amount of vibe-coded ness is allowed.

Feel free to scan existing issues/PRs as well if its helps your context gathering.

Run on Fable 5.1 High.

Activity

  1. kylebarron commented on Oct 13, 2026

    @kylebarron
    MemberAuthor

    Note

    This comment was written by Claude (Claude Code), not by @kylebarron. It synthesizes four parallel research passes: a scan of libtiff (libsdl-org/libtiff at d232499), a code audit plus scratch benchmarks of async-tiff main (9a0ebac), a sweep of the async-tiff / async-geotiff issue trackers, and a survey of GDAL, tifffile, aiocogeo, geotiff.js, @cogeotiff/core, image-tiff and the Rust codec ecosystem. Numbers below come from a throwaway harness on an Apple Silicon laptop (aarch64, single thread, local files) and should be treated as directional, not authoritative.

    TL;DR: ranked by payoff per maintainer-hour

    # Change Effort Expected payoff Where
    1 Rewrite predictor loops with per-channel register accumulators S 3.4-6.3x on predictor stage; 1.5-2x end-to-end decode for LZW/zstd + predictor=2 and float32 + predictor=3 tiles src/predictor.rs
    2 Switch flate2 to the zlib-rs backend S (Cargo change) 38-47% faster inflate on tiles; ~25% faster whole-file deflate decode Cargo.toml
    3 Fix TokioReader (always returns EOF) and give ReqwestReader a real get_byte_ranges S Correctness + removes fully serial tile fetching over plain HTTP src/reader.rs
    4 Cap merged-range size and fetch chunks concurrently in ObjectReader::get_byte_ranges M Largest cloud win: today a window of contiguous tiles becomes one unbounded GET on a single TCP stream src/reader.rs
    5 Metadata cache that can start at an arbitrary offset (not prefix-only) M Stops whole-file downloads for non-COG TIFFs (#344); needed for SubIFDs (#328) anyway src/metadata/cache.rs
    6 Replace jpeg-decoder with zune-jpeg M 3.7-4x JPEG decode on aarch64 (jpeg-decoder has no stable NEON path); smaller but real on x86 src/decoder.rs
    7 Give decoders the expected output size via a context struct (#203), and return typed output (#234) M (public API) Enables preallocation, zstd bulk decode, removes a per-tile copy; unlocks several smaller wins at once src/decoder.rs, src/tile.rs, src/array.rs
    8 Let callers fetch byte ranges across IFDs in one call so async-geotiff can coalesce data + mask S/M Halves requests for masked COGs src/ifd.rs, async-geotiff _fetch.py
    9 Read out-of-line tag arrays in one fetch and parse into typed vectors S/M Hygiene: 20k awaits → ~40 for a 7k-tile file, 4x less metadata memory; only ms-level today src/metadata/reader.rs
    10 Benchmark infrastructure (vibe-coding allowed) S Makes 1-9 measurable and keeps them from regressing benches/, python tests

    Deferred / not recommended right now: explicit SIMD intrinsics for the predictor (item 1 gets most of it with safe Rust), a custom LZW decoder (weezl already does ~630 MB/s and has Wuffs-style 8-byte writes), libdeflate FFI (#270) before trying zlib-rs, lazy per-element TileOffsets loading (#305) before item 5 exists, GDAL ghost-area parsing (#201) as a first step, and anything mmap-based from libtiff.

    Where time actually goes today

    Single-thread decode of a 10980x10980 Sentinel-2 TCI converted to 512px tiles (output MB/s, including the predictor pass):

    Codec Decode MB/s Decoder stage per tile Predictor stage per tile
    Deflate u8 + pred2 (miniz_oxide) 460-490 7.6 ms (1024px tile) 2.8-3.6 ms
    LZW u8 + pred2 (weezl) 556 1.25 ms 0.71-0.90 ms
    Zstd u8 + pred2 720-770 0.36 ms 0.7-0.97 ms
    Deflate f32 + pred3 570 1.9 ms 3.6-3.8 ms (65% of tile time)
    JPEG YCbCr (jpeg-decoder) 350-500 1.64-1.75 ms n/a

    Three observations drive the ranking above:

    • The predictor is the biggest CPU hotspot on predictor files, not the codec. For zstd and LZW it costs more than decompression; for float32 it is two thirds of the tile. This matches weiji14's FOSS4G 2025 slides (slides.md) where async-tiff at 16 threads was 0.45 s vs LiberTIFF 0.26 s on LZW + predictor=2, with "faster decompressors and SIMD predictor" as the stated gap.
    • Opening a COG is already one request (32 KiB readahead covers every COG header tested; header_byte_size from feat: expose TIFF.header_byte_size for prefetch sizing #302 makes re-opens exact). Header work is in good shape for COGs and poor for non-COGs (ReadAheadCache harmful on non cloud optimized tiffs #344).
    • Tile fetching is already coalesced (fetch_tiles → one get_ranges, PR Tile request coalescing #11), but it inherits object_store policy wholesale, which has a 1 MiB gap and 10-way parallelism but no cap on merged request size (object_store util.rs merge_ranges).

    Details per item

    1. Register-accumulator predictors (S)

    rev_hpredict_row does row[i] = row[i] + row[i - samples], which reloads the just-written previous sample from memory on every element; the store-to-load dependency caps it at ~0.9 GB/s (u8) and ~2.3 GB/s (u16). Keeping one accumulator per channel in registers and iterating chunks_exact_mut(spp) with a const-generic channel count removes the dependency and lets LLVM unroll per channel. Measured on the harness (re-run twice):

    Case Current Accumulators Speedup
    u8, spp=3, 512px 0.90 ms 0.16 ms 5.6x
    u8, spp=3, 1024px 3.65 ms 0.58 ms 6.3x
    u16, spp=1 0.68 ms 0.20 ms 3.4x
    f32, spp=3, pred=3 3.79 ms 0.89 ms 4.3x

    For the float predictor the win comes from doing the byte-delta pass with accumulators and then interleaving the four planes with a single zipped loop over as_chunks_mut::<4>() instead of a per-element gather. This is the same trick as image-tiff main's one_byte_predict::<N> (comment there: "Without this, LLVM emits a scalar byte-at-a-time loop for N=3") and libtiff's stride-1/3/4 specializations in horAcc8. libtiff's fpAcc uses an SSE2 transpose for the 4-byte case; not needed as a first step.

    Two things to carry over from libtiff while touching this file: swap bytes before accumulating for non-native 16/32/64-bit data (libtiff's swabHorAcc*) so it is one pass instead of two, and avoid the fresh allocation unpredict_float makes per tile. All safe Rust, fully covered by existing predictor fixtures. The harness did not assert equality against the current implementation, so the real change must be validated against the predictor2/predictor3 fixtures.

    2. flate2 zlib-rs backend (S)

    The lockfile pins flate2 1.1.9 on miniz_oxide. flate2 documents zlib-rs as its fastest backend (docs.rs); Trifecta's benchmark has it ahead of zlib-ng at every chunk size above 16 bytes (blog), and an independent four-way inflate benchmark puts miniz_oxide at 416 MB/s vs zlib-rs 527 MB/s on Apple M4 and 533 vs 722 on Zen 4 (flate2 PR #545). Measured here on 3 MB tiles: 7.61 ms → 4.03 ms (u8), 2.07 → 1.29 ms (u16); whole-file TCI 460 → 573 MB/s.

    Gotcha: default-features = false silently drops runtime_detection, so use features = ["zlib-rs", "runtime_detection"] (flate2 issue #570). It is pure Rust, so it should not break the Pyodide recipe in dev-docs/specs, but that needs a check. libdeflate (#270, via libdeflater) is a further 1.3-1.8x step (Wuffs benchmarks) and is exactly what libtiff does for whole striles (tif_zip.c), but it adds a C dependency and needs item 7's output size, so try zlib-rs first.

    3. TokioReader bug and ReqwestReader::get_byte_ranges (S)

    TokioReader::make_range_request does Vec::with_capacity(n) then file.read(&mut buffer), which reads into a zero-length slice; the harness confirms every call returns EndOfFile(n, 0). Fix is vec![0; n] plus read_exact, with a test (there are none for TokioReader).

    ReqwestReader does not override get_byte_ranges, so it gets the sequential default: fetch_tiles over plain HTTP is N serial requests with no coalescing. Reusing object_store::coalesce_ranges with the reqwest fetch closure is a few lines.

    4. Cap merged-range size and parallelize (M)

    Because merge_ranges has no size limit, fetch_tiles on a run of contiguous tiles produces one range (measured: 121 tiles of TCI → 1 request of ~55 MB). On S3 that is one connection at roughly 50-90 MB/s (dvassallo/s3-benchmark: ~93 MB/s per thread, ~20 ms p90 TTFB) while object_store's 10-way parallelism sits idle. AWS's older guidance was 8-16 MB range requests, one per 85-90 MB/s of desired throughput (2021 archive); Arrow C++ caps merged ranges at 32 MiB and derives the hole size from bandwidth × TTFB (caching.h); GDAL caps its raw block prefetch at 10 MiB.

    Proposal: in ObjectReader::get_byte_ranges, run your own merge (gap and max-chunk configurable, defaults ~1 MiB gap / ~8-16 MiB chunk), then futures::stream::iter(...).buffered(n) over store.get_range. This also resolves #6 without waiting on object_store. Keep the current behaviour for LocalFileSystem.

    5. Non-prefix metadata cache (M)

    ReadaheadMetadataCache can only extend a prefix from byte 0. For a file with overviews appended after the pixel data (the classic libtiff layout, and every bio-imaging TIFF in #344) the harness measured 3 requests totalling 242 MB to read the metadata of an 81 MB file (32 KiB, then max(2x, needed) = 80.8 MB, then 161 MB past EOF). A cache of independent blocks keyed by offset (fetch a window of initial bytes starting at the requested offset when it is outside any cached block, grow on sequential misses) fixes #344 and is what #328 needs for SubIFDs. GDAL's /vsicurl/ does this with 16 KiB chunks that double up to 2 MiB on sequential reads (cpl_vsil_curl.cpp); geotiff.js uses 64 KiB blocks in an LRU (blockedsource.js). Expose the cache choice from Python as Rust-side classes as discussed in #344.

    Once this exists, libtiff's on-demand strile loading becomes a natural follow-up for #305: _TIFFPartialReadStripArray reads a 4 KiB page around the requested index and decodes every entry in the window. A network reader would use larger windows and fetch the offsets and bytecounts windows concurrently. But only files with ~10^5+ tiles per IFD benefit, so it ranks below the items above.

    6. zune-jpeg (M)

    jpeg-decoder 0.3 is in maintenance mode (README), reads the entropy stream byte-by-byte through a dyn Read, and only has NEON behind a nightly feature, so IDCT and colour conversion are scalar on Apple Silicon and Graviton. Measured on 512px YCbCr tiles: jpeg-decoder 1.64-1.75 ms vs zune-jpeg 0.40-0.46 ms. image 0.25 (CHANGES.md) and image-tiff (PR #268) already made this switch. Caveats to verify against the JPEG fixtures: zune-jpeg wants a single contiguous buffer (concatenate JPEGTables minus EOI with the tile minus SOI, which is cheap), output colourspace mapping for RGB/YCbCr/CMYK/grayscale, and non-strict mode for abbreviated streams. Neither decoder supports 12-bit lossy JPEG, so there is no regression there; lossless JPEG is unsupported by zune-jpeg, which matters only for DNG-style files.

    7. Decoder context + typed output (M, public API)

    The Decoder trait receives no expected output size, so every decoder grows a Vec from empty, zstd allocates a ~128 KiB streaming BufReader per tile, and the typed array step always copies. Doing #203 once (a DecodeContext/TileInfo struct with width, height, spp, bps, data type, expected byte length, photometric, tables, LERC params) unlocks, in one API break:

    • preallocated output (miniz 7.6 → 5.0 ms with decompress_vec; zlib-rs 4.03 → 3.84 ms),
    • zstd::bulk::decompress with a reused Decompressor (0.359 → 0.308 ms),
    • typed output buffers so TypedArray::try_new stops copying. #166 always goes the slow path for most types #234 is correct: bytemuck::try_cast_vec::<u8, u16> returns AlignmentMismatch unconditionally (bytemuck allocation.rs), so the fallback copy runs for every non-8-bit tile. It measured only ~2% (42 µs for a 1.5 MB u16 tile, 68 µs for 3 MB f32), which is why it is folded in here instead of standing alone.
    • a fix for the latent panic in the JPEG2000 decoder, which calls cast_vec::<u16, u8> and will hit the same alignment check on any 16-bit tile.

    libtiff's equivalent is the caller-supplied buffer in TIFFReadEncodedTile / TIFFReadFromUserBuffer (tif_read.c), and WebP decodes straight into it when sizes match (tif_webp.c). feefladder's #87/#103 sketch was this idea; it stalled on PR size, so scoping it as "context struct in, typed buffer out, nothing else" is the way to land it.

    8. Cross-IFD range fetching for data + mask (S/M)

    async-geotiff fetches a window's data tiles and mask tiles as two independent fetch_tiles calls (_fetch.py), so two get_ranges round trips per read, even though GDAL writes the mask tile right after its imagery tile (MASK_INTERLEAVED_WITH_IMAGERY=YES, COG driver docs) and GDAL reads both in one request (gtiffdataset_read.cpp). tiles_byte_ranges already exists (#261); adding a fetch_byte_ranges(ranges) -> Vec<Bytes> on TIFF (or accepting pre-computed ranges plus the IFD to build Tiles from) lets async-geotiff submit one coalesced request. No ghost-area parsing needed: coalescing by offset does the right thing automatically when the layout is interleaved.

    9. Typed, single-fetch tag array reads (S/M)

    read_tag_value reads out-of-line arrays one element per awaited fetch() (each a mutex lock and a Bytes slice), into Vec<TagValue> (32 bytes per element) that from_tags converts again into Vec<u64>. Measured: 20,194 fetch calls for a 7,396-tile IFD, ~1.6 ms in-memory, ~3 ms through the cache. Small today, but it is 4x the memory and scales linearly for the 10^5-10^6-tile IFDs that motivate #305. One fetch(count * size) per tag plus a typed fast path for SHORT/LONG/LONG8 arrays is a contained change, and it is the layer #305 would build on. Also worth copying from libtiff while here: reject IFDs with more than 4096 entries and tag data over 2 GiB before allocating (tif_dirread.c).

    10. Benchmarks (S, vibe-coding fine)

    The one Rust bench depends on a TCI_lzw.tif that must be made with GDAL and is not present, rebuilds the tokio runtime and rayon pool inside the timed closure, and per #254 nobody looks at the CodSpeed output. Cheap, high-leverage additions:

    • Decode-only criterion benches per codec and per predictor on a fixture generated in the bench setup (rasterio or GDAL via pixi, as fixtures/geotiff-test-data already does), so items 1, 2, 6 and 7 have before/after numbers.
    • A request-counting AsyncFileReader wrapper in tests that asserts request count and total bytes for "open COG", "open IFD-at-end TIFF", "fetch a 4x4 window", "fetch window + mask". This is deterministic, runs offline, and catches regressions like ReadAheadCache harmful on non cloud optimized tiffs #344 and the unbounded-merge behaviour directly.
    • A Python-level GeoTIFF.read() benchmark in async-geotiff (none exists); the Python-side costs the audit found (assemble_tiles always copies, see async-geotiff added predictors #86; two serial gather phases for data then mask; transform recomputed per tile) are invisible without one.

    Smaller items found along the way

    • Tile.decode_sync decodes while holding the GIL (python/src/tile.rs); wrap in py.detach.
    • The LZW decoder uses expect(...) on decode failure and panics on corrupt tiles (decoder.rs).
    • lerc_parameters is a Vec<u32> cloned per tile; Arc<[u32]> like colormap. LERC also pays two extra copies (outer wrapper to Vec, then cast_slice().to_vec()), fixed by item 7. lerc-rs 0.7 (pure Rust, released 2026-10-13) could remove the bindgen/libclang wheel-build constraint, which is a maintainer-bandwidth win rather than a speed win, once it is mature.
    • ImageFileDirectory.tile_offsets builds a fresh Python list[int] on every attribute access; expose via the buffer protocol like Colormap if anyone loops over it.
    • Correction to a claim in the tracker: obstore stores are passed to Rust as native object_store instances (python/src/reader.rs), so they do not round-trip through Python per request; only non-obstore obspec backends do.

    Things that look fine and should not be re-litigated

    Single-request COG open with the 32 KiB readahead and header_byte_size; fetch_tiles as one get_ranges including flattened planar bands; compressed Bytes never copied before the decoder; decode on rayon with the GIL released and zero-copy numpy export via the buffer protocol; jpeg-decoder's rayon feature disabled in favour of tile-level parallelism; fix_endianness a vectorized no-op on native files.

    Sources

    libtiff: tif_dirread.c, tif_predict.c, tif_zip.c, tif_lzw.c, tif_read.c, TIFFOpen 'D'/'O' flags. GDAL: cpl_vsil_curl.cpp, gtiffdataset_read.cpp, COG driver, virtual file systems. Others: object_store util.rs, Arrow C++ caching.h, tifffile read_segments, aiocogeo partial_reads.py, geotiff.js BlockedSource, @cogeotiff/core leader-based tile sizing, image-tiff main predictor, zlib-rs benchmark, flate2 inflate comparison, zune-jpeg, weezl changelog, AWS S3 performance, FOSS4G 2025 slides. Tracker: #6, #70, #82, #87, #89, #103, #140, #201, #203, #234, #254, #261, #270, #301, #305, #328, #344; async-geotiff #66, #78, #86.

    🤖 Written by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions