Introducing a new way to review your PRs.

Read the announcement

maplibre / martin

Blazing fast and lightweight PostGIS, MBtiles and PMtiles tile server, tile generation, and mbtiles tooling.

View on GitHub

22 documents · Updated Nov 23, 2026

docs / cog-backends-and-python-bindings

COG backends and Python bindings

The COG backends give local files, memory buffers, and object stores one byte-range reading model. The Python extension uses this model to expose single COGs, file mosaics, tile indexes, and STAC-backed sources through sync and async tile and raster access. See COG raster tiles for the higher-level tile behavior and file and remote tile sources for the wider source model.

Backend model

The backend layer separates where a COG lives from how the COG reader reads TIFF pages and tile data. Each backend reports a safe display location, the source size, and async byte-range reads, so one reader can serve tiles from different storage types.

Byte-range contract

The AsyncBackend contract is the common boundary for COG input. It validates ranges and adapts them to the TIFF reader. A backend can also combine nearby ranges when its storage system can read them efficiently.

References: cog-tiles/…/mod.rs• L1-92

Local file backend

The FileBackend reads a local COG by byte position. It suits files on the host because concurrent tile requests share the opened source without sharing a mutable file cursor.

References: cog-tiles/…/file.rs• L1-69

Memory backend

The MemoryBackend treats an existing byte buffer as a COG source. It gives Rust callers and tests the same range-read contract without storage or network work. It is a Rust library backend rather than a Python location type.

References: cog-tiles/…/memory.rs• L1-43 cog-tiles/…/lib.rs• L19-27

Object-store backend

The ObjectStoreBackend reads one object through the shared object-store interface. Opening an object records its size and version information. Later range reads use that identity so a replacement cannot silently combine bytes from two object versions.

The object-store layer supports S3, Google Cloud Storage, Azure Blob Storage, and HTTP. It can coalesce nearby ranges to reduce requests when one tile needs several close byte ranges.

References: cog-tiles/…/object_store.rs• L1-89 cog-tiles/Cargo.toml• L17-32

Python extension

The Python package is a native extension named cog_tiles. It presents one source interface for a COG or a collection of COGs. It turns Rust results into encoded bytes, NumPy arrays, and raster objects for Python applications.

Python module surface

The module provides sync and async opening functions for four source types: one COG, a file-name mosaic, a gdaltindex tile index, and a STAC search. All opened sources share TileSource operations for encoded tiles, decoded tile pixels, tile iteration, and stitched reads. This common surface lets an application change how it finds imagery without changing how it consumes tiles or rasters.

The extension is a Python-loadable native library. Its module registration defines the runtime objects and exceptions. The generated stub file describes the same surface to editors and type checkers.

References: cog-tiles-py/…/lib.rs• L1-38 cog-tiles-py/…/py.rs• L35-40 cog-tiles-py/…/py.rs• L280-330 cog-tiles-py/…/py.rs• L427-516 cog-tiles-py/cog_tiles.pyi• L10-29 cog-tiles-py/Cargo.toml• L13-18 cog-tiles-py/pyproject.toml• L1-29

Location resolution

Python locations resolve to either a local path or an object-store source before a COG is opened. Local paths and file:// URLs use the file backend. s3://, gs://, az://, and HTTP(S) URLs use object stores with credentials from the normal environment and per-call options as overrides.

Mosaic locations split into a storage root and a file-name template. Tile-index and STAC file references use the same resolver. This lets one indexed source use local paths and supported remote URLs while keeping credentials and query settings separate from the display location in errors.

References: cog-tiles-py/…/location.rs• L20-90 cog-tiles-py/…/location.rs• L94-139 cog-tiles-py/…/py.rs• L365-373 cog-tiles-py/…/py.rs• L441-457 cog-tiles-py/…/py.rs• L549-594 cog-tiles-py/cog_tiles.pyi• L270-284

Source dispatch

The Python source layer maps a resolved location to a file reader, an object-store reader, or a file mosaic. Tile indexes and STAC searches become indexed mosaics after they resolve their listed or found COGs. After opening, every source exposes common layout data such as zoom range, tile size, format, and bounds.

Area reads and tile iteration add bounded concurrency around source calls. Area reads paste decoded tile pixels into one raster. Tile iteration returns encoded tiles as they arrive and stops pending work when the iterator is dropped.

References: cog-tiles-py/…/source.rs• L18-32 cog-tiles-py/…/source.rs• L43-126 cog-tiles-py/…/source.rs• L128-155 cog-tiles-py/…/source.rs• L168-228 cog-tiles-py/…/py.rs• L132-243

Tile encoding

The Python API can return source tiles as stored or re-encode every tile as PNG, WebP, or JPEG. Re-encoding gives all source types one output contract. tile_pixels and read continue to expose decoded pixels. JPEG uses a background color for transparent pixels. WebP can use lossless output.

References: cog-tiles-py/…/py.rs• L139-145 cog-tiles-py/…/py.rs• L1458-1528 cog-tiles-py/cog_tiles.pyi• L209-239 cog-tiles-py/…/test_format.py• L18-53

Runtime boundary

The extension owns a multi-thread Tokio runtime for storage I/O and decoding. Sync Python calls wait on that runtime with the GIL released and check Python signals during long waits. Async calls submit work to the same runtime, so the Python event loop waits for results instead of running fetch or decode work.

The runtime is recreated after a process fork because worker threads do not survive the fork. Dropping an async operation or iterator aborts its pending work. This lets cancellation and early iterator exit stop outstanding fetches.

References: cog-tiles-py/…/runtime.rs• L1-75 cog-tiles-py/…/py.rs• L91-124 cog-tiles-py/…/py.rs• L177-182 cog-tiles-py/…/source.rs• L177-228

Python contract

The Python contract keeps storage concerns behind TileSource and gives callers encoded and decoded result forms. Encoded tile methods suit tile serving or storage. Pixel and area-read methods provide uint8 arrays with EPSG:3857 placement data for raster work.

Synchronous and asynchronous calls

Each operation that can wait has a matching async form, including opening indexed and STAC sources. Both forms use the same source and return the same tile or raster meaning. The async form is for asyncio services and supports task cancellation.

The API reports invalid arguments as ValueError, missing sources as FileNotFoundError, unsupported COG layouts as UnsupportedCogError, and other read failures as CogTilesError. The same mapping covers invalid STAC filters, band choices, and tile-index settings.

References: cog-tiles-py/…/error.rs• L1-57 cog-tiles-py/…/py.rs• L96-243 cog-tiles-py/…/py.rs• L969-1288 cog-tiles-py/cog_tiles.pyi• L163-291

Stub generation

The Python type surface comes from Rust binding declarations. Stub annotations describe Python classes, functions, return types, and literal values. The stub-gen tool writes cog_tiles.pyi, which includes the COG, mosaic, tile-index, and STAC entry points and their shared result types.

The stub file is part of the package's typed interface. A change to a Python-visible class, function, signature, or exception needs a new generated stub. The package build marks the distribution as typed and exposes the native module as cog_tiles.

References: cog-tiles-py/…/py.rs• L19-20 cog-tiles-py/…/lib.rs• L9-38 cog-tiles-py/…/stub_gen.rs• L1-13 cog-tiles-py/cog_tiles.pyi• L1-29 cog-tiles-py/pyproject.toml• L5-30 cog-tiles-py/README.md• L142-151

Source flow

The following flow shows how a Python open or read request moves from a public source description to storage or index discovery and then to a tile or raster result.

flowchart LR
    A[Python open or read] --> B[Source resolution]
    B -->|local path| C[File backend]
    B -->|object URL| D[Object-store backend]
    B -->|tile index or STAC| E[Indexed mosaic]
    C --> F[COG reader or mosaic]
    D --> F
    E --> F
    F --> G[Encoded tile]
    F --> H[Decoded pixels]
    H --> I[NumPy raster]

References: cog-tiles-py/…/location.rs• L20-90 cog-tiles-py/…/source.rs• L26-78 cog-tiles-py/…/py.rs• L441-457 cog-tiles-py/…/py.rs• L549-594 cog-tiles/…/mod.rs• L26-49

Change checklist

When these files or sections are changed, remember to consider these:

  • When a backend changes, keep its range checks, source identity in errors, and AsyncBackend bridge behavior aligned with the COG reader.
  • When a URL scheme or object-store option changes, update location parsing and the credential or option path used by single COGs, mosaics, tile indexes, and STAC assets.
  • When a Python-visible binding changes, update module registration, sync and async counterparts, generated annotations, pickle restore paths, and cog_tiles.pyi together.
  • When tile-index or STAC discovery changes, keep file-reference resolution, band selection, bounds, cache settings, and the shared TileSource layout aligned.
  • When tile output encoding changes, apply the format, quality, and transparency rules to every source-opening function and preserve the decoded-pixel contract.
  • When runtime or cancellation behavior changes, check both blocking Python calls and asyncio calls, including iterator drop and process-fork behavior.
  • When source layout or result types change, keep file readers, object-store readers, mosaics, NumPy arrays, and raster placement data on the same contract.

Important failure modes

TriggerConsequenceGuard
A requested range is empty or outside the sourceThe backend rejects the read instead of returning misleading bytesCentral range validation in the backend contract
An object changes after it is openedA later range request fails rather than mixing old and new object dataObject-store reads use the opened ETag or version
A TIFF is not a supported tile-aligned COGOpening fails with UnsupportedCogErrorValidate the COG layout before serving tiles
A mosaic tile request has no bounding boxThe Python call cannot determine which files to readRequire a bbox when the mosaic has no known whole-source bounds
A tile-index or STAC source has invalid bands, zooms, filters, or source linksOpening or a later tile read fails instead of producing an incomplete mosaicValidate source settings and resolve listed or found files through the shared source rules
A requested re-encoding uses an invalid format, quality, or backgroundThe source cannot open with the requested output contractValidate encoding options before the first read
A Python binding changes without stub regenerationRuntime behavior and static type information disagreeGenerate cog_tiles.pyi from the binding declarations

Key files

FileWhy to read it
cog-tiles/…/mod.rsDefines the byte-range backend boundary shared by storage types
cog-tiles/…/file.rsShows the local-file source model
cog-tiles/…/memory.rsShows the in-memory source model used for small inputs and tests
cog-tiles/…/object_store.rsShows remote object reads and version protection
cog-tiles-py/…/location.rsExplains how Python paths, URLs, and indexed file references select storage
cog-tiles-py/…/source.rsConnects locations and backends to COG, mosaic, tile, and raster operations
cog-tiles-py/…/runtime.rsDefines the sync and async boundary around Rust I/O
cog-tiles-py/…/py.rsDefines the Python-facing source, result, encoding, index, and STAC contracts
cog-tiles-py/…/lib.rsRegisters the native module and its public names
cog-tiles-py/…/stub_gen.rsDefines how the checked-in Python stubs are produced
cog-tiles-py/cog_tiles.pyiShows the typed Python API consumed by tools and editors
cog-tiles-py/…/test_format.pyShows the shared output-encoding contract across source types
cog-tiles-py/…/test_tile_index.pyShows indexed source bounds, bands, remote references, and shared tile access
cog-tiles-py/…/test_stac.pyShows STAC search, item ordering, band selection, caching, and async access