Skip to content
Merged
150 changes: 148 additions & 2 deletions crates/data/src/capped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

use crate::{DataError, Result};

/// The most bytes of one value or zip entry a writer hands its output at once, so a capped one
/// refuses a large value without being offered it whole.
pub(crate) const PIECE: usize = 8 << 10;

/// `bytes` written to `out`, [`PIECE`] at a time.
pub(crate) fn write_pieces(out: &mut (impl Write + ?Sized), bytes: &[u8]) -> std::io::Result<()> {
bytes.chunks(PIECE).try_for_each(|piece| out.write_all(piece))
}

/// The most bytes the buffers a file is made in may hold in all (a Shapefile's parts share one).
#[derive(Debug)]
pub struct Limit {
Expand All @@ -30,9 +39,37 @@ impl Limit {
self.passed.load(Ordering::Relaxed)
}

/// Whether there is a limit to pass: false for [`Limit::none`].
pub(crate) fn bounded(&self) -> bool {
self.max != usize::MAX
}

/// Refuses, and notes the limit passed, when files that come to `bytes` can't be held: for a
/// writer to ask before it builds a large piece of them that would then be refused.
pub(crate) fn fits(&self, bytes: usize) -> Result<()> {
if bytes <= self.max {
return Ok(());
}
self.passed.store(true, Ordering::Relaxed);
self.whole(Ok(()))
}

/// Refuses as [`Limit::fits`] does when `more` bytes can't be held beside what is counted now.
pub(crate) fn fits_more(&self, more: usize) -> Result<()> {
self.fits(self.held.load(Ordering::Relaxed).saturating_add(more))
}

/// An empty buffer counted against this limit.
pub(crate) fn buffer(&self) -> Buffer<'_> {
Buffer { file: Vec::new(), at: 0, limit: self, charged: 0 }
Buffer { file: Vec::new(), at: 0, limit: self, charged: 0, room: None }
}

/// [`Limit::buffer`], which also keeps `room` at the bytes counted for it as it grows: for a
/// caller to ask while a writer has the buffer.
pub(crate) fn watched_buffer<'a>(&'a self, room: &'a AtomicUsize) -> Buffer<'a> {
let mut buffer = self.buffer();
buffer.room = Some(room);
buffer
}

/// Counts `bytes` held apart from the buffers (files made in them and taken out, while an
Expand Down Expand Up @@ -88,13 +125,19 @@ pub(crate) struct Buffer<'a> {
limit: &'a Limit,
/// The allocation counted against the limit: what the system holds, not the file's length.
charged: usize,
/// Told `charged` as it grows ([`Limit::watched_buffer`]).
room: Option<&'a AtomicUsize>,
}

impl Buffer<'_> {
/// The file made, its spare room given back, no longer counted against the limit.
pub(crate) fn into_inner(mut self) -> Vec<u8> {
let mut file = std::mem::take(&mut self.file);
file.shrink_to_fit();
// Only a file held to a limit (a download, which waits counted by what it holds) gives
// back its spare room: a file to be written isn't reallocated for it.
if self.limit.max != usize::MAX {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes every unlimited buffer keep its spare capacity, not only the limited ones. projected_bytes_within runs with Limit::none() on the desktop (write_bytes_noted → write_bytes_noted_within(…, &Limit::none())), so a GeoJSON, CSV, KML, GPX, Shapefile zip or KMZ made in memory now comes back as a Vec whose capacity can be up to about 2× its length. Buffer::reserve doubles, so a 600 MB output can sit in a 1 GB allocation until the caller drops it. Before this change, shrink_to_fit gave that back. On Linux that shrink is usually a cheap realloc, not a copy, so the stated reason for skipping it ("isn't reallocated") does not cover the memory it keeps.

The PR's memory numbers only measure the limited case, and AGENTS.md ("Size for real data") asks for the multiple of the layer that a change holds. Either restore the unconditional shrink_to_fit, or measure the unlimited export with cargo xtask memory and state the multiple in the PR. The doc comment on into_inner (line 118) also says "its spare room given back", which no longer holds for unlimited buffers.

Confidence: medium. The 2× bound follows from reserve's doubling. I did not measure the real overhead.

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two reviews pull opposite ways here: #3124's asked not to trim a desktop file (a shrink can copy it on an allocator that can't shrink in place), this one notes an untrimmed file can keep up to twice its length until it is dropped. A desktop file made in memory is written and dropped straight after, so either cost is brief, and which is cheaper depends on the allocator. Left for the release quality pass, with the doc comment on into_inner to match whichever is chosen.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Limit::bounded() was added in this change for exactly this check, so using it here keeps the two in step.

Suggested change
if self.limit.max != usize::MAX {
if self.limit.bounded() {

Also for the release quality pass (not anchored here): the csv_stopped doc at crates/data/src/io.rs:3861 reads "used after a write of its failed", and the shapefile_record_bytes doc at crates/data/src/io.rs:6638 breaks mid-sentence ("counted from" then a new line).

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: bounded() is the check to use there, and both doc lines need their wording fixed. Left for the release quality pass.

file.shrink_to_fit();
}
self.release();
file
}
Expand All @@ -117,6 +160,9 @@ impl Buffer<'_> {
let room = old.saturating_mul(2).max(end).min(old.saturating_add(left)).max(end);
self.limit.take(room - old)?;
self.charged += room - old;
if let Some(told) = self.room {
told.store(self.charged, Ordering::Relaxed);
}
// For bytes, `try_reserve_exact` allocates what is asked.
self.file.try_reserve_exact(room - self.file.len()).map_err(|_| Error::from(ErrorKind::OutOfMemory))?;
Ok(())
Expand Down Expand Up @@ -179,6 +225,26 @@ mod tests {
use crate::raster::{ColorHint, Crs, GeoTransform, Raster, cogwrite, geotiff};
use crate::{Dataset, Field, FieldType, Geometry, GeometryType, Value};

/// A file made under no limit (one to be written) keeps its allocation when finished, so it
/// isn't reallocated; one held to a limit gives its spare room back.
#[test]
fn only_a_limited_file_is_trimmed_when_finished() {
// Five bytes, then one more: the allocation doubles to ten for six.
let unlimited = Limit::none();
let mut b = unlimited.buffer();
b.write_all(&[1; 5]).unwrap();
b.write_all(&[1]).unwrap();
assert_eq!(b.file.capacity(), 10);
assert_eq!(b.into_inner().capacity(), 10);
let limit = Limit::new(1000);
let mut b = limit.buffer();
b.write_all(&[1; 5]).unwrap();
b.write_all(&[1]).unwrap();
assert_eq!(b.file.capacity(), 10);
let file = b.into_inner();
assert_eq!((file.len(), file.capacity()), (6, 6));
}

/// A request past the limit, however large, is refused without changing what is counted.
#[test]
fn a_request_past_the_limit_leaves_the_count_as_it_was() {
Expand Down Expand Up @@ -320,6 +386,86 @@ mod tests {
}
}

impl Seek for Pieces<'_> {
fn seek(&mut self, to: SeekFrom) -> std::io::Result<u64> {
self.to.seek(to)
}
}

/// One value or zip entry that alone passes the limit is handed over a piece at a time: KML
/// and GPX text, a CSV or WKT cell, guarded or not, and an entry deflated or stored.
#[test]
fn one_large_value_stops_at_the_limit_without_it_offered_whole() {
const MAX: usize = 40_000;
let long = "a long \"value\" & more, ".repeat(20_000);
let formula = format!("={long}");
let at = crate::Coord::new(1.0, 2.0);
let layer = |geometry: Geometry, field: &str, value: &str| {
let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new(field, FieldType::Text)]);
ds.push(Some(geometry), vec![Value::Text(value.to_string())]);
ds
};
// Bytes with no pattern to deflate, which are stored as they are.
let mut state = 7u32;
let noise: Vec<u8> = std::iter::repeat_with(|| {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(state >> 24) as u8
})
.take(500_000)
.collect();
// Deflated to well past a piece, yet smaller than they are.
let halves: Vec<u8> = noise.iter().map(|b| b & 0x0f).collect();
type Make<'a> = Box<dyn Fn(&mut Pieces<'_>) -> Result<()> + 'a>;
let zipped = |data: &[u8]| -> Make<'_> {
let entries = vec![("e".to_string(), data.to_vec())];
Box::new(move |out| crate::zip::write_to(&entries, out).map_err(crate::DataError::Format))
};
let point = || Geometry::Point(at);
let mut cases: Vec<(&str, Make<'_>)> = Vec::new();
for (name, field, value) in [("KML description", "description", &long), ("KML attribute", "note", &long)] {
let ds = layer(point(), field, value);
cases.push((name, Box::new(move |out| crate::interop::write_kml(&ds, None, out))));
}
for (name, geometry) in [
("GPX waypoint name", point()),
("GPX multipoint name", Geometry::MultiPoint(vec![at, at])),
("GPX track name", Geometry::Line(vec![vec![at, at]])),
] {
let ds = layer(geometry, "note", &long);
cases.push((name, Box::new(move |out| crate::interop::write_gpx(&ds, Some(0), out))));
}
for (name, value) in [("WKT cell", &long), ("WKT guarded cell", &formula)] {
let ds = layer(point(), "note", value);
cases.push((name, Box::new(move |out| crate::interop::write_wkt_csv(&ds, out))));
}
for (name, value) in [("CSV cell", &long), ("CSV guarded cell", &formula)] {
let ds = layer(point(), "note", value);
cases.push((
name,
Box::new(move |out| {
let mut w = crate::io::CsvWriter::new(out, &ds.fields, ds.geometry_type, Crs::LonLat)?;
w.write(&ds.features)?;
w.finish().map(drop)
}),
));
}
cases.push(("deflated entry", zipped(&halves)));
cases.push(("stored entry", zipped(&noise)));
let mut failed = Vec::new();
for (name, make) in cases {
let limit = Limit::new(MAX);
let mut out = Pieces { to: limit.buffer(), largest: 0 };
let made = make(&mut out);
let (largest, held) = (out.largest, out.to.file.capacity());
if largest > PIECE || held > MAX {
failed.push(format!("{name}: a piece of {largest} bytes, {held} held"));
}
let e = limit.whole(made).unwrap_err().to_string();
assert!(limit.passed() && e.contains("passes the 40000 bytes"), "{name}: {e}");
}
assert!(failed.is_empty(), "{failed:#?}");
}

/// A buffer dropped without being handed over, as a refused write or a writer's error leaves
/// one, no longer counts against the limit, and a file handed over is released only once.
#[test]
Expand Down
Loading
Loading