Repository navigation
fix(data): write large values, shapes and zip entries within the download limit #3201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
8a78aff
10bfa84
f33ddb5
a2ae378
9ce3ef9
00fc80d
3e402f8
8052f60
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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 { | ||||||
|
|
@@ -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 | ||||||
|
|
@@ -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 { | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit:
Suggested change
Also for the release quality pass (not anchored here): the Category: quality
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed: |
||||||
| file.shrink_to_fit(); | ||||||
| } | ||||||
| self.release(); | ||||||
| file | ||||||
| } | ||||||
|
|
@@ -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(()) | ||||||
|
|
@@ -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() { | ||||||
|
|
@@ -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] | ||||||
|
|
||||||
There was a problem hiding this comment.
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_withinruns withLimit::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 aVecwhose capacity can be up to about 2× its length.Buffer::reservedoubles, so a 600 MB output can sit in a 1 GB allocation until the caller drops it. Before this change,shrink_to_fitgave that back. On Linux that shrink is usually a cheaprealloc, 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 withcargo xtask memoryand state the multiple in the PR. The doc comment oninto_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
There was a problem hiding this comment.
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_innerto match whichever is chosen.