Integration: TIFF memory check only for sizes main refused, cgroup page cache, bounded conversion (#8536)

- The free-memory check ran for every flat TIFF on Linux with a 512 MiB
  reserve, so small TIFFs that open on main were refused on a small VM or
  in a container: it now runs only for sizes the whole-image decode
  refused (over 2^30 px or its byte budget).
- In a cgroup, memory.current counts page cache the kernel reclaims
  before memory.max is hit; its inactive_file part now counts as free.
  A `docker --memory=2g` batch whose cache filled up refused every TIFF.
- A single-strip TIFF is one group, the whole image, and every converted
  piece of it was held at once: conversion now runs in rounds of at most
  32 MiB of source rows per core.
- TiffBands::open reported no ExtraSamplesDropped/OverLimit warnings on
  32-bit targets (wasm); both decoders now share prepared_warnings, and
  Truncated goes before MorePages by position.
- Drops the ar.tsv rows of "Fix CI after merging upstream": main added the
  same two keys (#10173), so the merged catalogue had duplicates and
  i18n::tests::bundled_catalogs_are_consistent failed.
- Doc comments: the swap cap is every cgroup's above too (the ancestor
  walk FredApps asked for); a cut-off strip decodes as zeros.

Co-authored-by: Khawar Zamman Wani <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
committed 2026-10-29 21:00:43 +01:00
1 parent 995f2b5b2d
commit c62c987000
6 files changed
+204 -45

No files matched your search

+1 -1
View File
@@ -221,7 +221,7 @@ fn decode_band(
if lay.direct() && pref.len == band.len() && stride == out_row {
match dec.read_chunk_bytes(chunk, band) {
Ok(()) => tally.decoded += 1,
// The rows read before the end stay in `band`: a missing strip is zeros.
// Rows read before the end would survive: a missing strip is zeros.
Err(e) if is_eof(&e) => {
band.fill(0);
tally.missing += 1;
+49 -10
View File
@@ -90,7 +90,10 @@ impl<'a> TiffBands<'a> {
let mut icc = None;
let meta = metadata(&file, &dir, &mut icc);
let stored = ifd::orientation_of(&file, &dir);
Ok(TiffBands { b: bytes, p, stored, turn: 1, cap: limits.max_alloc, icc, meta, warnings: more.into_iter().collect() })
// Extra samples are dropped here only on 32-bit targets, where the whole image counts.
let mut warnings = prepared_warnings(&p);
warnings.extend(more);
Ok(TiffBands { b: bytes, p, stored, turn: 1, cap: limits.max_alloc, icc, meta, warnings })
}
/// The bands turned upright for the page's Orientation tag, as [`Image::oriented`] turns a
@@ -203,8 +206,10 @@ impl<'a> TiffBands<'a> {
return Err(err("the image data is missing (cut off or past the end of the file)").into());
}
if tally.missing > 0 {
// Before `MorePages`, as the whole-image decode orders them.
self.warnings.insert(0, DecodeWarning::Truncated { format: F });
// After the extra-sample warnings and before `MorePages`, as the whole-image decode
// orders them.
let at = self.warnings.iter().position(|w| matches!(w, DecodeWarning::MorePages { .. })).unwrap_or(self.warnings.len());
self.warnings.insert(at, DecodeWarning::Truncated { format: F });
}
Ok(())
}
@@ -575,19 +580,27 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
};
img.meta.extra_samples = split_extra_samples(&extra_data, p.w as usize, p.h as usize, &p.lay.extra_at, p.lay.out, kind_of)?;
}
if p.extras_over_limit > 0 {
let count = u32::try_from(p.extras_over_limit).unwrap_or(u32::MAX);
img.warnings.push(DecodeWarning::ExtraSamplesOverLimit { format: F, count });
}
if p.extras_dropped > 0 {
img.warnings.push(DecodeWarning::ExtraSamplesDropped { format: F, count: p.extras_dropped });
}
img.warnings.extend(prepared_warnings(&p));
if tally.missing > 0 {
img.warnings.push(DecodeWarning::Truncated { format: F });
}
Ok(img)
}
/// What [`prepare`] left out of the image: extra samples past the supported count, then extra
/// samples over the allocation budget. Both decoders report them, in this order.
fn prepared_warnings(p: &Prepared) -> Vec<DecodeWarning> {
let mut warnings = Vec::new();
if p.extras_over_limit > 0 {
let count = u32::try_from(p.extras_over_limit).unwrap_or(u32::MAX);
warnings.push(DecodeWarning::ExtraSamplesOverLimit { format: F, count });
}
if p.extras_dropped > 0 {
warnings.push(DecodeWarning::ExtraSamplesDropped { format: F, count: p.extras_dropped });
}
warnings
}
/// Checks one directory and lays it out for decoding. `whole`: the image is decoded into one
/// buffer, which `limits.max_alloc` bounds; otherwise only its size is checked here.
fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prepared, CodecError> {
@@ -807,3 +820,29 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
extras_dropped,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{EncodeOptions, ExtraSample, Format};
/// `TiffBands::open` drops extra samples over the budget only on 32-bit targets (wasm32),
/// so it reports them through the same function as the whole-image decode.
#[test]
fn extra_samples_over_the_budget_are_reported_by_both_decoders() {
// Several strips (about 1 MB each), so one strip of all four samples fits the image's budget.
let (w, h) = (1024u32, 1024u32);
let n = (w * h) as usize;
let mut img = Image::from_raw(w, h, ChannelLayout::Rgb, SampleType::U8, vec![90; 3 * n]).unwrap();
img.meta.extra_samples = vec![ExtraSample { kind: 0, data: vec![7; n] }];
let bytes = crate::encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
let (file, dir, _) = open_page(&bytes, None).unwrap();
let tight = Limits { max_alloc: 3 * n as u64, ..Limits::default() };
let p = prepare(&file, &dir, &tight, true).unwrap();
assert_eq!(prepared_warnings(&p), vec![DecodeWarning::ExtraSamplesDropped { format: F, count: 1 }]);
assert!(prepared_warnings(&prepare(&file, &dir, &tight, false).unwrap()).is_empty(), "banded: only the band counts");
assert!(prepared_warnings(&prepare(&file, &dir, &Limits::default(), true).unwrap()).is_empty());
let whole = decode(&bytes, &tight).unwrap();
assert_eq!(whole.warnings, prepared_warnings(&p));
}
}
+109 -20
View File
@@ -238,7 +238,7 @@ pub fn import_tiff_page(name: &str, bytes: &[u8], page: Option<usize>) -> Result
drop(bands);
return import_tiff_whole(name, bytes, page);
}
tiff_to_document(name, bands.upright())
tiff_to_document(name, bands.upright(), crate::memory::available, BAND_BYTES)
}
/// A layered TIFF, or a flat one with extra samples, decoded whole: the layers are built from the
@@ -262,22 +262,26 @@ fn import_tiff_whole(name: &str, bytes: &[u8], page: Option<usize>) -> Result<Im
}
/// A flat TIFF page as a single-layer document, decoded a group of rows at a time into the
/// layer's tiles: only one group exists beside the document.
fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>) -> Result<ImportResult, IoError> {
/// layer's tiles: only one group exists beside the document. `available`: the memory this
/// process can still use (see [`crate::memory::available`]); `budget`: the source bytes per core
/// converted at a time ([`BAND_BYTES`]).
fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: impl FnOnce() -> Option<u64>, budget: usize) -> Result<ImportResult, IoError> {
let (w, h) = bands.dimensions();
let (layout, sample) = (bands.layout(), bands.sample_type());
let f = document_format(layout, sample);
let fmt = PixelFormat::new(f.mode, f.depth, true);
// The layer's tiles, plus a group as decoded, turned upright, converted and read into a
// worker's scratch buffer. Linux overcommits, so the tiles below are allocated even when they
// can't be backed, and writing them would have the process killed: refuse first.
let bpp = fmt.bytes_per_pixel() as u64;
let tiles = |n: u32| u64::from(n).div_ceil(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64);
let layer = tiles(w).saturating_mul(tiles(h)).saturating_mul(bpp);
let group = bands.group_bytes()? as u64;
let group_px = group / (layout.channels() as u64 * sample.bytes() as u64).max(1);
let needed = layer.saturating_add(group.saturating_mul(3)).saturating_add(group_px.saturating_mul(bpp));
crate::memory::check_fits(w, h, needed, crate::memory::available())?;
if needs_memory_check(w, h, layout, sample) {
// The layer's tiles, plus a group as decoded, turned upright, converted and read into a
// worker's scratch buffer. Linux overcommits, so the tiles below are allocated even when
// they can't be backed, and writing them would have the process killed: refuse first.
let tiles = |n: u32| u64::from(n).div_ceil(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64);
let layer = tiles(w).saturating_mul(tiles(h)).saturating_mul(bpp);
let group = bands.group_bytes()? as u64;
let group_px = group / (layout.channels() as u64 * sample.bytes() as u64).max(1);
let needed = layer.saturating_add(group.saturating_mul(3)).saturating_add(group_px.saturating_mul(bpp));
crate::memory::check_fits(w, h, needed, available())?;
}
let mut s = Surface::new(fmt);
let out_of_memory = |e: photocraft_raster::AllocationError| {
let gb = (u64::from(w) * u64::from(h)).saturating_mul(bpp) as f64 / 1e9;
@@ -290,15 +294,19 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>) -> Result<Impo
if layout == f.layout && sample == f.sample {
return s.try_write_interleaved(rect(&(0..gh as usize)), group.data()).map_err(out_of_memory);
}
// Converted in pieces of rows on all cores, then each piece written (on all cores too).
// Converted in pieces of rows on all cores, then each piece written (on all cores too), a
// round of at most `BAND_BYTES` of source rows per core at a time: a single-strip file is
// one group, the whole image, and converting it at once would hold it converted beside it.
let row = group.data().len() / (gh.max(1) as usize);
let pieces = crate::pixels::par_map(crate::pixels::bands(gh as usize), |rows| {
let part = group.data().get(rows.start * row..rows.end * row).unwrap_or_default().to_vec();
Image::from_raw(gw, rows.len() as u32, layout, sample, part).map(|p| (rows, p.convert(f.layout, f.sample)))
});
for piece in pieces {
let (rows, part) = piece?;
s.try_write_interleaved(rect(&rows), part.data()).map_err(out_of_memory)?;
for round in conversion_rounds(gh as usize, row, budget) {
let pieces = crate::pixels::par_map(round, |rows| {
let part = group.data().get(rows.start * row..rows.end * row).unwrap_or_default().to_vec();
Image::from_raw(gw, rows.len() as u32, layout, sample, part).map(|p| (rows, p.convert(f.layout, f.sample)))
});
for piece in pieces {
let (rows, part) = piece?;
s.try_write_interleaved(rect(&rows), part.data()).map_err(out_of_memory)?;
}
}
Ok(())
})?;
@@ -309,6 +317,26 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>) -> Result<Impo
Ok(single_layer_document(name, (w, h), f, layout.has_alpha(), s, bands.icc.take(), meta, warnings))
}
/// Whether a `w` × `h` flat TIFF is checked against free memory before it opens: only the sizes
/// the whole-image decode refused, which only the banded decode opens. Every image that opened
/// before opens as it did, also on a small machine or in a container whose page cache fills.
fn needs_memory_check(w: u32, h: u32, layout: ChannelLayout, sample: CSample) -> bool {
codecs::Limits::default().check(w, h, layout, sample).is_err()
}
/// `0..rows` of `row` bytes each, split into rounds of about one piece per core, each piece at
/// most about `budget` bytes, in order.
fn conversion_rounds(rows: usize, row: usize, budget: usize) -> Vec<Vec<std::ops::Range<usize>>> {
let round = (budget / row.max(1)).max(1).saturating_mul(crate::pixels::bands(rows).len()).max(1);
(0..rows)
.step_by(round)
.map(|start| {
let end = start.saturating_add(round).min(rows);
crate::pixels::bands(end - start).into_iter().map(|r| start + r.start..start + r.end).collect()
})
.collect()
}
/// How a decoded image's pixels are kept in a document.
struct DocumentFormat {
mode: ColorMode,
@@ -1159,3 +1187,64 @@ mod cmyk_band_tests {
assert_eq!(first[3], 255);
}
}
#[cfg(test)]
mod tiff_banded_tests {
use super::*;
#[test]
fn a_tiff_main_opened_opens_without_a_memory_check() {
// With no free memory reported, an ordinary small TIFF was refused ("not enough memory"):
// on a small machine or in a container whose page cache filled up.
let img = Image::from_raw(64, 64, ChannelLayout::Rgb, CSample::U8, vec![77; 64 * 64 * 3]).unwrap();
let bytes = codecs::encode(&img, Format::Tiff, &codecs::EncodeOptions::default()).unwrap();
let bands = codecs::TiffBands::open(&bytes, None, &codecs::Limits::banded()).unwrap();
let r = tiff_to_document("small.tif", bands.upright(), || Some(0), BAND_BYTES).unwrap();
assert_eq!((r.document.size.width, r.document.size.height), (64, 64));
}
#[test]
fn a_group_converted_in_many_rounds_is_the_whole_image_converted() {
// A budget of a few rows splits each group into many rounds: every row lands where the
// one-shot conversion put it, at every depth the convert branch takes.
for (layout, sample) in [(ChannelLayout::Rgb, CSample::U8), (ChannelLayout::Rgb, CSample::U16), (ChannelLayout::Gray, CSample::F32)] {
let (w, h) = (37u32, 101u32);
let n = (w * h) as usize * layout.channels();
let px: Vec<f32> = (0..n).map(|i| ((i * 37 + i / 7) % 251) as f32 / 250.0).collect();
let img = Image::from_normalized(w, h, layout, sample, &px).unwrap();
let bytes = codecs::encode(&img, Format::Tiff, &codecs::EncodeOptions::default()).unwrap();
let bands = codecs::TiffBands::open(&bytes, None, &codecs::Limits::banded()).unwrap();
let row = w as usize * layout.channels() * sample.bytes();
let r = tiff_to_document("rounds.tif", bands, || None, 3 * row).unwrap();
let f = document_format(layout, sample);
let want = codecs::decode(&bytes).unwrap().convert(f.layout, f.sample);
let LayerContent::Raster(s) = &r.document.layers[0].content else { panic!("not a raster layer") };
assert!(s.to_interleaved(r.document.bounds()) == want.data(), "{layout:?} {sample:?}");
}
}
#[test]
fn only_sizes_the_whole_image_decode_refused_are_checked() {
use {CSample as S, ChannelLayout as L};
assert!(!needs_memory_check(6000, 4000, L::Rgb, S::U8));
assert!(!needs_memory_check(20_000, 20_000, L::Rgba, S::U16));
assert!(needs_memory_check(40_000, 30_000, L::Rgb, S::U8), "over 2^30 px");
assert!(needs_memory_check(300_000, 300_000, L::Rgb, S::U8));
}
#[test]
fn conversion_rounds_cover_every_row_in_order_within_the_budget() {
let workers = crate::pixels::bands(usize::MAX >> 8).len();
for (rows, row, budget) in [(0, 30, 100), (1, 30, 100), (1000, 30, 100), (997, 7, 50), (10, 1000, 1), (5000, 3, 1 << 20)] {
let rounds = conversion_rounds(rows, row, budget);
let pieces: Vec<_> = rounds.iter().flatten().cloned().collect();
assert_eq!(pieces.iter().map(|r| r.len()).sum::<usize>(), rows, "{rows} rows");
assert!(pieces.windows(2).all(|p| p[0].end == p[1].start), "contiguous and in order: {pieces:?}");
assert!(pieces.first().is_none_or(|p| p.start == 0));
let most = (budget / row).max(1);
assert!(pieces.iter().all(|p| p.len() <= most), "{rows} x {row} B, budget {budget}: {pieces:?}");
assert!(rounds.iter().all(|r| r.len() <= workers));
}
assert_eq!(conversion_rounds(5000, 3, 1 << 20).len(), 1, "a group under the budget is one round");
}
}
+22 -8
View File
@@ -10,7 +10,7 @@ pub const RESERVE: u64 = 512 << 20;
/// Bytes this process can still use without running out, or `None` where that isn't known. On
/// Linux: the free RAM the kernel can hand out (`MemAvailable`, capped by the process's cgroup
/// v2 `memory.max` and those above it) plus free swap (capped by the cgroup's `memory.swap.max`).
/// v2 `memory.max` and those above it) plus free swap (capped by the cgroup's `memory.swap.max` and those above it).
/// Elsewhere `None`: Windows refuses an allocation past its commit limit, which the importers
/// already report as an error, and macOS pages to disk as it needs.
pub fn available() -> Option<u64> {
@@ -66,17 +66,25 @@ mod linux {
}
/// Memory and swap left under the limits of `dir` and every cgroup above it (`None`: no
/// limit). Both limits apply hierarchically.
/// limit). Both limits apply hierarchically. `memory.current` includes page cache, which the
/// kernel reclaims before a cgroup hits `memory.max`, so its inactive part counts as free.
pub(super) fn cgroup_room(dir: &Path) -> (Option<u64>, Option<u64>) {
let room = |d: &Path, max: &str, current: &str| -> Option<u64> {
let max = std::fs::read_to_string(d.join(max)).ok()?.trim().parse::<u64>().ok()?;
let current = std::fs::read_to_string(d.join(current)).ok().and_then(|c| c.trim().parse::<u64>().ok()).unwrap_or(0);
Some(max.saturating_sub(current))
let read = |d: &Path, f: &str| std::fs::read_to_string(d.join(f)).ok();
let room = |d: &Path, max: &str, current: &str, reclaimable: u64| -> Option<u64> {
let max = read(d, max)?.trim().parse::<u64>().ok()?;
let current = read(d, current).and_then(|c| c.trim().parse::<u64>().ok()).unwrap_or(0);
Some(max.saturating_sub(current.saturating_sub(reclaimable)))
};
let swap = dir.ancestors().take(64).filter_map(|d| room(d, "memory.swap.max", "memory.swap.current")).min();
let ram = dir.ancestors().take(64).filter_map(|d| room(d, "memory.max", "memory.current")).min();
let inactive_file = |d: &Path| read(d, "memory.stat").and_then(|s| stat(&s, "inactive_file")).unwrap_or(0);
let swap = dir.ancestors().take(64).filter_map(|d| room(d, "memory.swap.max", "memory.swap.current", 0)).min();
let ram = dir.ancestors().take(64).filter_map(|d| room(d, "memory.max", "memory.current", inactive_file(d))).min();
(ram, swap)
}
/// A `memory.stat` field (`<name> <bytes>` per line).
fn stat(stat: &str, field: &str) -> Option<u64> {
stat.lines().find_map(|l| l.strip_prefix(field)?.strip_prefix(' '))?.trim().parse().ok()
}
}
#[cfg(test)]
@@ -126,6 +134,12 @@ mod tests {
assert_eq!(linux::cgroup_room(&leaf).1, Some(128 << 20), "the tighter leaf swap limit wins");
write(&leaf, "memory.max", "1610612736\n");
assert_eq!(linux::cgroup_room(&leaf).0, Some(512 << 20), "the tighter limit wins");
write(&leaf, "memory.max", "2147483648\n");
write(&leaf, "memory.current", "2147483648\n");
write(&leaf, "memory.stat", "anon 268435456\nfile 1879048192\ninactive_file_x 1\ninactive_file 1610612736\n");
assert_eq!(linux::cgroup_room(&leaf).0, Some(1610612736), "inactive page cache is reclaimed before the limit");
write(&leaf, "memory.stat", "anon 268435456\n");
assert_eq!(linux::cgroup_room(&leaf).0, Some(0), "no inactive_file: memory.current is all in use");
std::fs::remove_dir_all(&root).unwrap();
assert!(available().is_some());
}
+23 -2
View File
@@ -61,6 +61,26 @@ fn every_layout_opens_as_the_whole_image_decode_does() {
}
}
/// A file stored as one strip is one group, the whole image, converted to the layer in rounds of
/// rows: the document is the one the whole-image decode gives (#8536 review).
#[test]
fn a_single_strip_tiff_opens_as_the_whole_image_decode_does() {
use flate2::{Compression, write::ZlibEncoder};
use std::io::Write;
let (w, h) = (1531, 2049);
let img = pattern(w, h, ChannelLayout::Rgb, SampleType::U8);
let mut z = ZlibEncoder::new(Vec::new(), Compression::fast());
z.write_all(img.data()).unwrap();
let strip = z.finish().unwrap();
let mut f = b"II*\0\0\0\0\0".to_vec();
f.extend_from_slice(&strip);
let bytes = rgb_tiff_directory(f, w, h, h, &[8], &[strip.len() as u32]);
let r = photocraft_io::import("one-strip.tif", &bytes).unwrap();
let decoded = codecs::decode(&bytes).unwrap();
assert_eq!(decoded.data(), img.data());
assert!(layer_bytes(&r) == decoded.convert(ChannelLayout::Rgba, SampleType::U8).data(), "pixels");
}
/// Peak resident memory of this process so far (Linux), in bytes.
fn peak_rss() -> Option<u64> {
let status = std::fs::read_to_string("/proc/self/status").ok()?;
@@ -133,10 +153,11 @@ fn rgb_tiff_directory(mut f: Vec<u8>, w: u32, h: u32, rows: u32, offsets: &[u32]
(258, 3, 3, bits_at),
(259, 3, 1, 8),
(262, 3, 1, 2),
(273, 4, n, arrays_at),
// A single strip's offset and count fit in the entry itself.
(273, 4, n, if let [o] = offsets { *o } else { arrays_at }),
(277, 3, 1, 3),
(278, 4, 1, rows),
(279, 4, n, arrays_at + 4 * n),
(279, 4, n, if let [c] = counts { *c } else { arrays_at + 4 * n }),
(284, 3, 1, 1),
];
f.extend_from_slice(&(entries.len() as u16).to_le_bytes());
-4
View File
@@ -3550,7 +3550,3 @@ curves Smooth تنعيم
Update and Restart التحديث وإعادة التشغيل
X X
Y Y
# Select and Mask workspace closure reasons
Select and Mask was closed: its document is no longer the active one أُغلقت مساحة التحديد والقناع: لم يعد المستند الخاص بها نشطًا
Select and Mask was closed: another layer was selected أُغلقت مساحة التحديد والقناع: تم تحديد طبقة أخرى
Can't render this file because it contains an unexpected character in line 6 and column 47.