`ReadAheadCache` harmful on non cloud optimized tiffs

Aperta
#344 4 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
38/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
python, rust

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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

Lingua principale
Rust
Stelle
125
Fork
17
Merge medio
7h 33m
PR unite (30g)
8

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di developmentseed/async-tiff

Tutte le issue di developmentseed/async-tiff

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.