Count embedded smart object contents toward the history budget

History counted a document's pixel tiles but not the file bytes a
smart object embeds (SmartSource::Embedded). A document of large
embedded sources was far over its memory budget without trimming
ever noticing, and every Replace Contents kept the old bytes alive in
the undo states unaccounted.

The four counters (add, remove, bytes_with and the uncounted walk)
now visit one shared list of blocks: the tiles as before plus each
embedded source's Arc, keyed by address. States, snapshots and
duplicated layers that share an Arc count it once, and trimming the
last state that holds an old source releases it.
This commit is contained in:
Khawar Zamman Wani committed 2026-10-29 10:03:25 +05:30
1 parent e96386fe47
commit b779bd8f02
4 files changed
+151 -38

No files matched your search

+1 -1
View File
@@ -67,7 +67,7 @@ impl DocState {
}
/// Pixel bytes of the document, the tiles only its history holds and the tiles only its
/// History panel snapshots hold.
/// History panel snapshots hold; embedded smart object contents count too.
pub fn memory_bytes(&self) -> usize {
let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect();
self.history.pixel_bytes(&self.doc).saturating_add(self.history.extra_bytes(&self.doc, &snaps))
+12 -13
View File
@@ -6,7 +6,8 @@
//! same approach Photoshop's History panel exposes to users (one state per step).
//!
//! Memory is bounded by `max_states` plus an approximate byte budget. The current document's
//! tiles and tiles only history holds count against it, including selection masks.
//! tiles and tiles only history holds count against it, including selection masks, and so do the
//! embedded contents of smart objects (shared `Arc` bytes, counted once however many states hold them).
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -48,8 +49,8 @@ pub struct History {
/// Lazily initialized when a byte budget is used; unlimited histories pay no counting cost.
tiles: Option<tiles::Tiles>,
pub max_states: usize,
/// Pixel memory budget in bytes for the current document plus the tiles only history holds
/// (0 = unlimited). [`History::trim`] drops the oldest states beyond it.
/// Pixel memory budget in bytes for the current document plus the tiles (and embedded smart
/// object contents) only history holds (0 = unlimited). [`History::trim`] drops the oldest states beyond it.
pub max_bytes: usize,
/// Label of the step that produced the current document.
current_label: String,
@@ -534,8 +535,8 @@ impl History {
self.held_states().map(|s| tile_bytes(&s.doc, &mut seen)).sum()
}
/// Pixel bytes of `current` plus the tiles only history holds (what [`History::trim`]
/// bounds by [`History::max_bytes`]).
/// Pixel bytes of `current` plus the tiles only history holds, embedded smart object contents
/// included (what [`History::trim`] bounds by [`History::max_bytes`]).
pub fn pixel_bytes(&self, current: &Document) -> usize {
if let Some(tiles) = &self.tiles {
return usize::try_from(tiles.bytes_with(current)).unwrap_or(usize::MAX);
@@ -571,7 +572,7 @@ impl History {
}
/// Keep pixel memory within [`History::max_bytes`]: the current document's tiles plus the
/// tiles only history holds (newest states first). The oldest undo states that don't fit are
/// tiles only history holds (newest states first), both with embedded smart object contents. The oldest undo states that don't fit are
/// dropped; the most recent one is always kept so the last step can be undone. The History
/// Brush's source state ([`History::set_brush_source`]) is never dropped: its unique tiles are
/// counted first, and the newest states fill what remains. Returns how many states were
@@ -580,7 +581,7 @@ impl History {
self.trim_with(current, &[])
}
/// [`History::trim`] counting the tiles only `pinned` documents hold (History panel
/// [`History::trim`] counting the tiles (and embedded smart object contents) only `pinned` documents hold (History panel
/// snapshots, which outlive the states) against the budget too, so they can't take memory
/// beyond it unseen (#4530). The most recent state is still always kept.
pub fn trim_with(&mut self, current: &Document, pinned: &[&Document]) -> usize {
@@ -666,14 +667,12 @@ fn merge_ids(into: &mut Vec<LayerId>, from: &[LayerId]) {
}
}
/// Bytes of the pixel tiles of `doc` (layers, masks, fill caches, smart filter masks, alpha channels, selection) not already in `seen`.
/// Bytes of the pixel tiles of `doc` (layers, masks, fill caches, smart filter masks, alpha channels, selection) and the embedded contents of its smart objects not already in `seen`.
fn tile_bytes(doc: &Document, seen: &mut HashSet<usize>) -> usize {
let mut n = 0usize;
tiles::surfaces(doc, |surface| {
for (_, tile) in surface.tiles() {
if seen.insert(Arc::as_ptr(tile) as usize) {
n = n.saturating_add(tile.bytes().len());
}
tiles::blocks(doc, |ptr, len| {
if seen.insert(ptr) {
n = n.saturating_add(len);
}
});
n
+104
View File
@@ -655,6 +655,110 @@ fn fill_caches_and_smart_filter_masks_count_toward_history_bytes() {
assert_counter(&h, &cur);
}
const TILE: usize = 256 * 256 * 4;
const SOURCE: usize = 1_000_000;
fn embedded(len: usize) -> photocraft_doc::SmartSource {
photocraft_doc::SmartSource::Embedded { file_name: "source.pcraft".into(), bytes: Arc::new(vec![7; len]) }
}
/// `base()` with one smart object holding `source`; returns the document and the layer's id.
fn smart_document(source: photocraft_doc::SmartSource) -> (Document, photocraft_doc::LayerId) {
use photocraft_doc::{Affine, LayerContent, SmartObject};
let mut doc = base();
let layer = Layer::new("Smart", LayerContent::Smart(SmartObject::new(source, Affine::IDENTITY, None)));
let id = layer.id;
doc.insert_above(None, layer);
(doc, id)
}
fn replace_source(doc: &mut Document, id: photocraft_doc::LayerId, source: photocraft_doc::SmartSource) {
if let Some(photocraft_doc::LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) {
sm.source = source;
}
}
#[test]
fn embedded_smart_object_contents_count_toward_history_bytes() {
let (with, _) = smart_document(embedded(SOURCE));
let without = base();
let mut h = History::default();
assert_eq!(h.pixel_bytes(&with), h.pixel_bytes(&without) + SOURCE, "uncounted history walks the document");
assert_eq!(h.pixel_bytes(&without), TILE);
// With a budget the counter keeps the figure incrementally.
let mut cur = Arc::new(with.clone());
h.max_bytes = usize::MAX;
edit(&mut h, &mut cur, "Rename", |d| d.name = "renamed".into());
edit(&mut h, &mut cur, "Rename again", |d| d.name = "renamed again".into());
h.trim(&cur);
assert_eq!(h.pixel_bytes(&cur), TILE + SOURCE);
assert_counter(&h, &cur);
// A linked source holds no bytes of its own.
let (linked, _) = smart_document(photocraft_doc::SmartSource::Linked { path: "a.png".into() });
assert_eq!(History::default().pixel_bytes(&linked), TILE);
}
#[test]
fn states_sharing_one_embedded_source_count_it_once() {
let (doc, _) = smart_document(embedded(SOURCE));
let mut cur = Arc::new(doc);
let mut h = History { max_bytes: usize::MAX, ..History::default() };
for i in 0..10 {
edit(&mut h, &mut cur, &format!("Rename {i}"), |d| d.name = format!("renamed {i}"));
}
h.trim(&cur);
assert_eq!(h.past_len(), 10);
assert_eq!(h.pixel_bytes(&cur), TILE + SOURCE);
assert_eq!(h.unique_bytes(&cur), 0);
assert_counter(&h, &cur);
// A duplicated layer shares the same bytes too.
edit(&mut h, &mut cur, "Duplicate", |d| {
if let Some(copy) = d.layers.last().cloned() {
d.insert_above(None, copy);
}
});
h.trim(&cur);
assert_eq!(h.pixel_bytes(&cur), TILE + SOURCE);
assert_counter(&h, &cur);
}
#[test]
fn a_replaced_embedded_source_counts_until_the_state_holding_it_is_trimmed() {
const REPLACED: usize = 400_000;
let (doc, id) = smart_document(embedded(SOURCE));
let mut cur = Arc::new(doc);
let mut h = History { max_bytes: usize::MAX, ..History::default() };
edit(&mut h, &mut cur, "Replace Contents", |d| replace_source(d, id, embedded(REPLACED)));
assert_eq!(h.pixel_bytes(&cur), TILE + SOURCE + REPLACED, "the state before still holds the old contents");
assert_eq!(h.unique_bytes(&cur), SOURCE);
edit(&mut h, &mut cur, "Rename", |d| d.name = "renamed".into());
h.trim(&cur);
assert_counter(&h, &cur);
h.max_bytes = TILE + REPLACED;
assert_eq!(h.trim(&cur), 1, "dropping the oldest state releases the old contents");
assert_eq!(h.pixel_bytes(&cur), TILE + REPLACED);
assert_counter(&h, &cur);
}
#[test]
fn embedded_contents_push_old_states_out_of_the_budget() {
let (doc, id) = smart_document(embedded(SOURCE));
let mut cur = Arc::new(doc);
let mut h = History::new(50);
for i in 0..5 {
// Each step swaps in contents of its own; only the tile is shared between states.
edit(&mut h, &mut cur, &format!("Replace {i}"), |d| replace_source(d, id, embedded(SOURCE)));
}
assert_eq!(h.trim(&cur), 0, "unlimited by default");
assert_eq!(h.pixel_bytes(&cur), TILE + 6 * SOURCE);
// The current contents and the two newest states fit.
h.max_bytes = TILE + 3 * SOURCE;
assert_eq!(h.trim(&cur), 3);
assert_eq!(h.past_len(), 2);
assert_eq!(h.pixel_bytes(&cur), TILE + 3 * SOURCE);
assert_counter(&h, &cur);
}
#[test]
fn selection_tiles_count_current_and_history_without_double_counting() {
use photocraft_doc::{PixelFormat, Surface};
+34 -24
View File
@@ -1,7 +1,7 @@
//! Tile references owned by history snapshots. The snapshots keep these addresses alive;
//! COW edits cannot change a retained tile in place. Count occurrences (including aliases
//! within one document), so removing a state releases a tile only after its last reference.
use photocraft_doc::{Document, LayerContent, Surface};
use photocraft_doc::{Document, LayerContent, SmartSource, Surface};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -47,29 +47,42 @@ pub(crate) fn surfaces(doc: &Document, mut visit: impl FnMut(&Surface)) {
}
}
/// Every shared allocation `doc` holds that history can retain, as `visit(address, length)`:
/// the tiles of [`surfaces`] and the embedded contents of smart objects (an `Arc` that undo
/// states and duplicated layers share, replaced by Replace Contents).
pub(crate) fn blocks(doc: &Document, mut visit: impl FnMut(usize, usize)) {
surfaces(doc, |surface| {
for (_, tile) in surface.tiles() {
visit(Arc::as_ptr(tile) as usize, tile.bytes().len());
}
});
for (_, _, layer) in doc.walk() {
if let LayerContent::Smart(smart) = &layer.content
&& let SmartSource::Embedded { bytes, .. } = &smart.source
{
visit(Arc::as_ptr(bytes) as usize, bytes.len());
}
}
}
impl Tiles {
pub(crate) fn add(&mut self, doc: &Document) {
surfaces(doc, |surface| {
for (_, tile) in surface.tiles() {
let count = self.refs.entry(Arc::as_ptr(tile) as usize).or_insert_with(|| {
self.bytes += tile.bytes().len() as u128;
(0, tile.bytes().len())
});
count.0 += 1;
}
blocks(doc, |ptr, len| {
let count = self.refs.entry(ptr).or_insert_with(|| {
self.bytes += len as u128;
(0, len)
});
count.0 += 1;
});
}
pub(crate) fn remove(&mut self, doc: &Document) {
surfaces(doc, |surface| {
for (_, tile) in surface.tiles() {
let key = Arc::as_ptr(tile) as usize;
if let Some(count) = self.refs.get_mut(&key) {
count.0 -= 1;
if count.0 == 0 {
self.bytes -= count.1 as u128;
self.refs.remove(&key);
}
blocks(doc, |ptr, _| {
if let Some(count) = self.refs.get_mut(&ptr) {
count.0 -= 1;
if count.0 == 0 {
self.bytes -= count.1 as u128;
self.refs.remove(&ptr);
}
}
});
@@ -85,12 +98,9 @@ impl Tiles {
pub(crate) fn bytes_with(&self, current: &Document) -> u128 {
let mut total = self.bytes;
let mut seen = HashSet::new();
surfaces(current, |surface| {
for (_, tile) in surface.tiles() {
let key = Arc::as_ptr(tile) as usize;
if !self.refs.contains_key(&key) && seen.insert(key) {
total += tile.bytes().len() as u128;
}
blocks(current, |ptr, len| {
if !self.refs.contains_key(&ptr) && seen.insert(ptr) {
total += len as u128;
}
});
total