`ReadAheadCache` harmful on non cloud optimized tiffs

Open
#344 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
38/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
python, rust

Research direction

Start with src/metadata/cache.rs at the linked lines, then run the self-contained Python repro to observe the range requests made while opening scattered directories. Compare the cache behavior with the proposed configurable or multiblock approaches; done means scattered-IFD TIFFs no longer require fetching the intervening image data while cloud-optimized TIFF behavior remains supported.

Written by the indexing model from the issue text.

Description

Problem

Opening a tiff where the IFDs are scattered throughout the file results in downloading the entire file to read the metadata, due to how the ReadAheadMetadataCache always starts from byte zero and only grows from there.

This is something I encountered using virutal-tiff on some bio tiffs.

https://github.com/developmentseed/async-tiff/blob/19ddfcd4a60e837d0120a1149d1548a67d58beb8/src/metadata/cache.rs#L15-L23

This works well for cloud optimized tiffs where the metadata is all at the start of the file (or so is my understanding). But is resulting in my having to download effectively the entire file(!!) just to parse the metadata.

I ran into this on this file s3://camelyon-dataset/CAMELYON16/images/tumor_001.tif (public us-west-2)

which is an 11-directory BigTIFF, containing a 10-level JPEG pyramid (512×512 tiles) plus a macro image. Each level's directory are placed right after that level's tiles. The first tile is at byte 16, and directory 0 is at byte 2,421,903,632

Starts at Size
header 0 16 B
level 0 tiles 16 2.42 GB
directory 0 + tag values 2,421,903,632 (74.2%) 2.31 MB
level 1 tiles 2,424,209,385 629 MB
directory 1 + tag values 3,052,970,432 (93.5%) 333 KB
… levels 2–9, each directory after its tiles …
directory 10 (macro) 3,264,778,576 938 B

So Tiff.Open has to download 2.42 GB to get directory 0.

Another example is this single image file that has the IFD at the end, s3://cellpainting-gallery/cpg0000-jump-pilot/source_4/images/2020_11_04_CPJUMP1/images/BR00116991__2020-11-05T19_51_35-Measurement1/Images/r01c01f01p01-ch1sk1fk1fl1.tiff (us-east-1)

Starts at Size
header 0 8 B
pixels (one LZW strip) 8 2,471,697 B
IFD 0 (23 entries, next = 0) 2,471,706 (96.7%) 282 B
out-of-line tag values 2,471,988 83,742 B
end of file 2,555,730

For repros using those real files it would end up downloading the whole file, so here is a self contained repro with a synthetic tiff with two directories.

# /// script
# dependencies = ["async-tiff", "tifffile", "numpy"]
# ///
"""async-tiff fetches every byte before a TIFF's second directory to open it."""

import asyncio
import io

import numpy as np
import tifffile
from async_tiff import TIFF

buf = io.BytesIO()
with tifffile.TiffWriter(buf) as tw:
    tw.write(np.zeros((2048, 2048), np.uint8))
    tw.write(np.zeros((16, 16), np.uint8))
data = buf.getvalue()
print(f"file: {len(data):,} bytes, directories at {[p.offset for p in tifffile.TiffFile(io.BytesIO(data)).pages]}")


class LoggingStore:
    def __init__(self, blob):
        self.blob, self.requests = blob, []

    async def get_range_async(self, path, *, start, end=None, length=None):
        end = start + length if end is None else end
        self.requests.append((start, end))
        return self.blob[start:end]

    async def get_ranges_async(self, path, *, starts, ends=None, lengths=None):
        raise NotImplementedError("only tile reads use this")


async def main():
    await TIFF.open("x.tif", store=store)


store = LoggingStore(data)
asyncio.run(main())
for start, end in store.requests:
    print(f"  requested {start:>10,} .. {end:>10,}")
fetched = sum(len(data[s:e]) for s, e in store.requests)
print(f"fetched {fetched:,} of {len(data):,} bytes to read two directories")

Gives

file: 4,195,056 bytes, directories at [8, 4194560]
  requested          0 ..     32,768
  requested     32,768 ..  4,194,562
  requested  4,194,562 .. 12,583,686
fetched 4,195,056 of 4,195,056 bytes to read two directories

Solution(s)

I think there may be a few layers here

  1. Allow configurable caching layer - i.e. opt out of the readaheadcache

Ideally I could pass a different caching object from python that is tuned to my objects layout. This seems like the only way to properly scale to all possible tiff variants

  1. Make default cache more flexible

Make it a multiblock cache where blcoks dont have to start from zero.

  • A read that misses just past the end of a cached block extends that block, as today's cache does.
  • A far miss starts a new block at the read, sized from 32 KiB and growing within that block only.

Maybe change the default sizing of these, or expose it to python

  1. Add more specialized caches for the common tiff layouts

Not sure if this makes sense, but I bet we could have a caching layer that does this better

Dominant language
Rust
Stars
125
Forks
17
Avg merge
7h 33m
Merged PRs (30d)
8

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from developmentseed/async-tiff

All issues in developmentseed/async-tiff

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.