← Back to Pull requests

perf(rio): write a copy from its source as it is written #797

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 10, 2026 16:45 UTC
Author

Closes #730.

terrio.rio.shutil.copy writes a COG from its source as the file is written, a row of the COG's tiles at a time, its overviews computed as the rows come, instead of first copying the source's pixels into the dataset it creates, which held them until it closed. The copy no longer holds its source's image: copying the issue's 4096 x 4096 RGB GeoTIFF to a Deflate COG grew the process's peak by 296 to 322 MiB, and grows it by 197 to 206 MiB (268 to 283, and 145 to 166, with TERRIO_CACHEMAX=0), for the same file byte for byte. A GeoTIFF larger than TERRIO_RIO_IN_MEMORY_LIMIT is copied the same way, without the temporary file that held its pixels. A copy whose source has a dataset mask or overviews the COG copies, a COG compressed with JPEG, WebP, LERC or JPEG XL, and a smaller GeoTIFF still hold the source's pixels until they are written.

Behaviour

  • A copy written in rows reads its source as it writes. When the file a copy writes is written in rows, shutil.copy gives the dataset it creates the source, and the dataset reads it while it writes the file: a COG a row of its tiles at a time (BLOCKSIZE rows, 512 by default), a GeoTIFF larger than TERRIO_RIO_IN_MEMORY_LIMIT in the rows of about 16 MB it is written in. The dataset holds no array of the source's pixels, and no temporary file of them.

  • Which files are written in rows. The same as before: a COG without a mask, without overviews of its source to copy (a GeoTIFF or COG source with overviews, and OVERVIEWS AUTO or FORCE_USE_EXISTING), and compressed with NONE, LZW, DEFLATE, ZIP, ZSTD or PACKBITS; and a GeoTIFF larger than TERRIO_RIO_IN_MEMORY_LIMIT. A source with a dataset mask is copied as before, whatever the format, since its mask is written into the dataset.

  • The same file. The metadata go through the same dataset and the same writer as before; only where the rows come from changes. The file is the one the copy holding the pixels writes, byte for byte.

  • From any source. A path, an open dataset, a MemoryFile or a VRT.

  • Not changed. Other copies (a GeoTIFF below the in-memory limit, the COGs not written in rows, other formats) hold the source's pixels until they are written, as before.

  • The issue's first proposal, terrio.translate, is not used. Writing the issue's image to a COG, terrio.translate grew the peak by 258 to 265 MiB on this machine (249 to 255 with TERRIO_CACHEMAX=0), more than the copy now needs: it returns its output as a Raster, held whole. Its streaming form, the command line's, writes other bytes than the copy for 6 of the 11 kinds of source below to a Deflate COG (overviews, Float32 with nodata and band metadata, paletted, masked and RGBA GeoTIFFs, a JPEG file), 7 uncompressed (band-interleaved UInt16 too), so a copy through it would not keep its file.

  • Docs. docs/rasterio.md (Writing) and the docstring of shutil.copy say so.
  • Before and after

    The issue's reproduction as filed, three fresh processes for each figure, peak growth in MiB, alone on the machine. main is e1f2908; this branch changes Python files only, so both run over the same extension, built from e1f2908:

    main:
    rgb.tif  TERRIO_CACHEMAX=default  peak growth (MiB), 3 runs: shutil.copy [301, 322, 296], translate [266, 262, 263]; outputs byte-identical: True
    rgb.tif  TERRIO_CACHEMAX=0        peak growth (MiB), 3 runs: shutil.copy [275, 268, 283], translate [260, 257, 257]; outputs byte-identical: True
    rgb.jpg  TERRIO_CACHEMAX=default  peak growth (MiB), 3 runs: shutil.copy [307, 300, 307], translate [220, 213, 215]; outputs byte-identical: False
    rgb.jpg  TERRIO_CACHEMAX=0        peak growth (MiB), 3 runs: shutil.copy [286, 283, 302], translate [217, 217, 218]; outputs byte-identical: False
    this branch:
    rgb.tif  TERRIO_CACHEMAX=default  peak growth (MiB), 3 runs: shutil.copy [206, 201, 197], translate [258, 264, 265]; outputs byte-identical: True
    rgb.tif  TERRIO_CACHEMAX=0        peak growth (MiB), 3 runs: shutil.copy [145, 154, 166], translate [255, 251, 249]; outputs byte-identical: True
    rgb.jpg  TERRIO_CACHEMAX=default  peak growth (MiB), 3 runs: shutil.copy [231, 225, 223], translate [217, 217, 215]; outputs byte-identical: False
    rgb.jpg  TERRIO_CACHEMAX=0        peak growth (MiB), 3 runs: shutil.copy [221, 222, 242], translate [219, 213, 215]; outputs byte-identical: False
    

    The JPEG source's copy and translation differ on main too; the copy's file is main's on both sources.

    Every surface, from the issue's image, TERRIO_CACHEMAX=0, three fresh processes each, peak growth in MiB; each output is main's byte for byte:

    | shutil.copy | Written in rows | main | this branch |
    | --- | --- | --- | --- |
    | A GeoTIFF file to a Deflate COG | yes | 276.4 to 288.4 | 154.6 to 157.8 |
    | An open dataset of it | yes | 286.5 to 295.4 | 156.3 to 161.1 |
    | A MemoryFile of it | yes | 268.4 to 298.7 | 152.6 to 157.6 |
    | A VRT of it | yes | 285.4 to 312.9 | 223.0 to 227.4 |
    | A JPEG file | yes | 295.3 to 320.5 | 217.0 to 233.1 |
    | A GeoTIFF file to an uncompressed COG | yes | 272.2 to 284.9 | 166.1 to 170.3 |
    | A GeoTIFF with overviews of 2, 4 and 8, which the COG copies | no | 211.7 to 214.3 | 211.9 to 214.6 |
    | The same with overviews="NONE" | yes | 210.7 to 215.4 | 85.0 to 91.1 |
    | A GeoTIFF with a dataset mask | no | 400.8 to 407.4 | 403.1 to 406.1 |
    | A GeoTIFF to a JPEG-compressed COG | no | 279.6 to 289.7 | 276.3 to 283.7 |
    | A GeoTIFF to a tiled Deflate GeoTIFF | no | 185.5 to 189.8 | 186.6 to 187.8 |
    | The same over the in-memory limit (TERRIO_RIO_IN_MEMORY_LIMIT=1) | yes | 138.1 to 143.7 | 93.8 to 94.6 |

    Small sources of every kind the copy treats apart (RGB, overviews, Float32 with nodata and band metadata, paletted, masked, RGBA, band-interleaved UInt16, GCPs only, JPEG, paletted PNG, VRT), copied to COG and to GTiff, compressed or not, with the in-memory limit as it is and at 1 byte, from a path, an open dataset and a MemoryFile: 256 copies, each main's byte for byte.

    Tests and mutations

    python/tests/test_rio_copy_streams.py, on a 3,000 x 1,024 RGB GeoTIFF (9,216,000 bytes; five rows of 512 x 512 tiles and part of a sixth):

  • test_a_cog_copy_allocates_no_array_of_the_whole_image[path, dataset, memoryfile, vrt]: during a COG copy, Python and NumPy allocate under half the image's bytes (tracemalloc), and the copy has the source's pixels.

  • test_a_copy_written_in_rows_reads_its_source_a_row_at_a_time[cog-512, cog-256, gtiff-over-the-limit]: the source is read in rows of 512, or of 256 with blocksize=256, the last of 440 or 184; a GeoTIFF over the in-memory limit in one read of 3,000 rows. No other file is in the directory while it is read.

  • test_a_copy_written_from_its_source_is_the_one_written_from_its_pixels: the copy's file is the one _copy_dataset(..., from_source=False) writes, holding the pixels, byte for byte. Its cases are RGB Deflate; Float32 with nodata, tags, a description, a unit, a scale and an offset in ZSTD with predictor 3; band-interleaved UInt16 without compression; a paletted COG; a GeoTIFF over the limit; and, not written in rows, a JPEG-compressed COG and a GeoTIFF below the limit.

  • test_a_copy_keeps_its_source_s_dataset_mask, test_a_copy_keeps_its_source_s_overviews: the copies not written in rows keep them.

  • test_a_copy_s_writer_given_a_mask_after_all_writes_its_source_whole: a writer given a source and then a mask, which is no longer written in rows, reads its source whole.
  • On main, 15 of the 17 fail: the peak is 9,230,727 bytes or more, the reads are rows of 2,730 and 270, and _copy_dataset takes no from_source. The mask and overview tests pass there, and guard what is not written in rows.

    Each mutation was applied alone, run against the test file, and restored. MA9 was also run against the whole Python suite:

    | Mutation | Caught by | First message |
    | --- | --- | --- |
    | A copy never written from its source | allocates_no_array… (4 cases), reads_its_source_a_row_at_a_time (3) | 9,296,162 bytes at the peak for an image of 9,216,000 |
    | The source read at the wrong rows | allocates_no_array… (4), reads_its_source…[cog-512, cog-256], …is_the_one_written_from_its_pixels (the 4 COGs written in rows) | the pixels and the files differ |
    | A copy whose source has a dataset mask written from its source | test_a_copy_keeps_its_source_s_dataset_mask | the mask differs |
    | A COG copy read in 16 MB slabs, not rows of tiles | reads_its_source_a_row_at_a_time[cog-512, cog-256] | [(0, 3000)] for [(0, 512), …, (2560, 440)] |
    | A GeoTIFF copy given its source not counted as written in rows when written | reads_its_source…[gtiff-over-the-limit], …[gtiff-over-the-in-memory-limit] | [None] (one whole read) for [(0, 3000)] |
    | A source's overviews not excluded: computed, not copied | test_a_copy_keeps_its_source_s_overviews | a COG copying a source's overviews needs the whole raster |
    | The writer's whole read of a source no longer written in rows removed | test_a_copy_s_writer_given_a_mask_after_all_writes_its_source_whole | the array is empty |
    | A copy written from its source allocating its pixels all the same | allocates_no_array… (4), reads_its_source…[gtiff-over-the-limit] | 9,293,224 bytes at the peak …; the temporary file in the directory |
    | A JPEG-compressed COG written in rows | none, here or in the whole suite (6,575 passed) | — |
    | A GeoTIFF below the in-memory limit written from its source | …is_the_one_written_from_its_pixels[gtiff-below-the-in-memory-limit] | the files differ |
    | A copy from a VRT not written from its source | allocates_no_array…[vrt] | 9,230,631 bytes at the peak … |
    | A copy from a MemoryFile not written from its source | allocates_no_array…[memoryfile] | 9,232,162 bytes at the peak … |
    | A copy of an open dataset not written from its source | allocates_no_array…[dataset, memoryfile], reads_its_source… (3) | 9,232,180 bytes at the peak … |

    The JPEG mutation changes the condition _flush writes a COG in rows by, which this change moves into _streams_on_flush without changing it: no test says which compressions the COG writer takes in rows, and a test that a copy holds its pixels would pin a limitation.

    Checks run

    This branch changes Python files and docs/rasterio.md only, so the Rust gates do not apply. Its tests ran with the branch's Python files over an extension built from e1f2908, whose Rust code is the branch's:

  • pytest on the whole Python suite: 6,575 passed, 945 skipped, 4 xfailed, 2 xpassed, 0 failed. Two earlier runs failed 12 cases of a CRS test, the PROJJSON of EPSG codes, which pass alone and with the new tests in either order; they fail or pass with the files an xdist worker runs before them, as they did once on another branch.

  • pre-commit run --files on the changed files.

  • scripts/compare_rio_with_rasterio.py with the real data, on main and on this branch: 190 checks on both, 178 identical, 7 within tolerance and 5 known differences, and every check keeps its status.

  • 13 mutations, in the table above.
  • Limitations

  • What a COG's writer holds. A copy written in rows still needs the rows of tiles its COG writer compresses at once, the overview levels it builds, and the source's reader: about 155 MiB for the issue's GeoTIFF, more for a JPEG file or a VRT, whose reads hold more.

  • Copies not written in rows hold the source's pixels as before: a source with a dataset mask (about 400 MiB for the issue's image), overviews a COG copies, a COG compressed with JPEG, WebP, LERC or JPEG XL, and a GeoTIFF below the in-memory limit.

  • A GeoTIFF below the limit is not written from its source, though it could be: in rows, the GeoTIFF writer writes other bytes than it does whole, for every source tried here, so this would change those files.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: github-actions[bot] Review duration: 6m
    All Vouch review confidence checks passed
    Residual risk 0.38 = Change Risk (0.52) × (1 − Review Confidence (0.27)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 40% · Reviewer familiarity: 35%
    27%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #797"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: medium confidence: 27.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 27.3% · Lower = rushed or shallow review
    27.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 37.8% · Moderate risk
    37.8%