Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

20.3 KB
Raw Blame
//! Tiered RAM / LZ4 / Scratch Disk Memory Manager.
//!
//! Enforces configured RAM budgets across all open documents using a 4-tier frustum-aware LRU
//! eviction policy:
//! 1. **L2 Demotion (Raw -> LZ4 RAM):** Cold tiles are LZ4-compressed in place via `lz4_flex`,
//!    reclaiming 5–20× memory with zero disk I/O.
//! 2. **L3 Eviction (LZ4/Raw -> Scratch Disk):** When compressed RAM still exceeds the budget,
//!    lowest-priority tiles are written directly in-process to [`ScratchBackend`].

use super::scratch::ScratchBackend;
use crate::tiles::{pixel_to_tile_coord, TileCoord, TileData, TileKind, TileStorage};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// Viewport bounding box in document pixel coordinates for frustum-aware eviction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ViewportFrustum {
    pub min_x: i32,
    pub min_y: i32,
    pub max_x: i32,
    pub max_y: i32,
}

/// Runtime memory and history budget configuration mirrored from `performanceManager`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryBudgetConfig {
    /// Hard CPU RAM budget for tile data across all open documents (default 1024 MB).
    pub ram_budget_bytes: u64,
    /// Target L1 GPU VRAM tile atlas budget (default 512 MB = 1024 `Rgba16Float` slots).
    pub vram_budget_bytes: u64,
    /// Maximum history steps retained per document (clamped 10..=200, default 50).
    pub max_history_steps: usize,
    /// Whether inactive document tabs should eagerly compress to L2/L3 on tab switch.
    pub offload_inactive_tabs: bool,
}

impl Default for MemoryBudgetConfig {
    fn default() -> Self {
        Self {
            ram_budget_bytes: 1024 * 1024 * 1024,
            vram_budget_bytes: 512 * 1024 * 1024,
            max_history_steps: 50,
            offload_inactive_tabs: true,
        }
    }
}

/// Live tiered memory statistics surfaced to React's Performance settings & HUD.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryStats {
    pub ram_raw_bytes: u64,
    pub ram_lz4_bytes: u64,
    pub ram_total_bytes: u64,
    pub ram_budget_bytes: u64,
    pub disk_paged_tiles: u64,
    pub disk_paged_logical_bytes: u64,
    pub vram_used_bytes: u64,
    pub vram_budget_bytes: u64,
    pub vram_slots_used: u32,
    pub vram_slots_capacity: u32,
    pub solid_tile_count: u64,
    pub raw_tile_count: u64,
    pub lz4_tile_count: u64,
    pub total_tile_count: u64,
    pub history_entry_count: u64,
    pub open_document_count: u32,
}

/// Snapshot of active document/layer/frustum state used to prioritize tile eviction.
#[derive(Debug, Clone, Default)]
pub struct EvictionContext {
    pub active_doc_id: Option<String>,
    pub active_layer_id: Option<String>,
    pub frustum: Option<ViewportFrustum>,
    pub hidden_layers: HashSet<(String, String)>, // (doc_id, layer_id)
}

/// Mutable tile reference item passed into [`TieredMemoryManager::enforce_budget`].
pub struct ManagedTileSlot<'a> {
    pub doc_id: &'a str,
    pub layer_id: &'a str,
    pub kind: TileKind,
    pub coord: TileCoord,
    pub tile: &'a mut Arc<TileData>,
    /// True when this slot belongs to an Undo/Redo history snapshot rather than a live layer grid.
    pub is_history: bool,
}

/// Coordinates L2 LZ4 RAM compression and L3 Scratch Disk paging.
pub struct TieredMemoryManager {
    pub config: MemoryBudgetConfig,
    scratch: Arc<dyn ScratchBackend>,
}

impl TieredMemoryManager {
    pub fn new(config: MemoryBudgetConfig, scratch: Arc<dyn ScratchBackend>) -> Self {
        Self { config, scratch }
    }

    pub fn scratch(&self) -> &Arc<dyn ScratchBackend> {
        &self.scratch
    }

    pub fn scratch_ref(&self) -> &dyn ScratchBackend {
        self.scratch.as_ref()
    }

    pub fn set_budget(&mut self, config: MemoryBudgetConfig) {
        self.config = config;
    }

    /// Computes live memory statistics across a slice of tile references (deduplicating shared CoW `Arc`s
    /// by pointer address so Copy-on-Write snapshots are never double-counted!).
    pub fn compute_stats<'a, I>(
        &self,
        tiles: I,
        history_entry_count: u64,
        open_document_count: u32,
    ) -> MemoryStats
    where
        I: IntoIterator<Item = &'a Arc<TileData>>,
    {
        let mut seen_ptrs: HashSet<*const TileData> = HashSet::new();
        let mut stats = MemoryStats {
            ram_budget_bytes: self.config.ram_budget_bytes,
            vram_budget_bytes: self.config.vram_budget_bytes,
            history_entry_count,
            open_document_count,
            ..Default::default()
        };

        for arc in tiles {
            let ptr = Arc::as_ptr(arc);
            if !seen_ptrs.insert(ptr) {
                continue;
            }
            stats.total_tile_count += 1;
            match &arc.storage {
                TileStorage::SolidColor { .. } => {
                    stats.solid_tile_count += 1;
                }
                TileStorage::Raw(v) => {
                    stats.raw_tile_count += 1;
                    stats.ram_raw_bytes += v.len() as u64;
                }
                TileStorage::CompressedLz4 { compressed, .. } => {
                    stats.lz4_tile_count += 1;
                    stats.ram_lz4_bytes += compressed.len() as u64;
                }
                TileStorage::PagedToDisk {
                    uncompressed_len, ..
                } => {
                    stats.disk_paged_tiles += 1;
                    stats.disk_paged_logical_bytes += *uncompressed_len as u64;
                }
            }
        }
        stats.ram_total_bytes = stats.ram_raw_bytes + stats.ram_lz4_bytes;
        stats
    }

    /// Enforces `ram_budget_bytes` across all supplied tiles:
    /// - Deduplicates CoW-shared `Arc<TileData>` handles by `Arc::as_ptr` so shared tiles are
    ///   never CoW-cloned via `Arc::make_mut` while another holder retains the original raw buffer.
    /// - Only demotes a tile group when `Arc::strong_count == group.len()` (every holder is
    ///   present in `slots` and updated atomically to the compressed/paged `Arc`, genuinely
    ///   dropping the old raw buffer). External holders with `strong_count > group.len()` are
    ///   skipped so RAM can NEVER increase.
    /// - Pass 1 (L2): Compresses lowest-priority `Raw` tiles to `CompressedLz4` (or `SolidColor`)
    ///   when total RAM exceeds `soft_target` (80% of budget).
    /// - Pass 2 (L3): Pages lowest-priority remaining `Raw` / `CompressedLz4` tiles to scratch disk
    ///   when total RAM still exceeds `ram_budget_bytes` (down to 90% of budget).
    ///
    /// Returns `(lz4_compressed_count, disk_paged_count, bytes_freed)`.
    pub fn enforce_budget(
        &self,
        mut slots: Vec<ManagedTileSlot<'_>>,
        ctx: &EvictionContext,
    ) -> Result<(usize, usize, u64), String> {
        let budget = self.config.ram_budget_bytes.max(1);
        let soft_limit = (budget * 4) / 5; // 80% triggers fast L2 LZ4 compression
        let target_after_evict = (budget * 9) / 10; // 90% target after L3 paging

        let initial_ram = Self::unique_ram_bytes(&slots);
        let mut total_ram = initial_ram;
        if total_ram <= soft_limit {
            return Ok((0, 0, 0));
        }

        // Deduplicate CoW-shared Arcs by pointer so all holders of the same Arc are managed as one unit.
        // Group priority = highest (hardest-to-evict) priority among all holders in the group.
        struct TileGroup {
            indices: Vec<usize>,
            tier: u8,
            dist: i64,
            last_access_seq: u64,
        }

        let mut ptr_to_group: HashMap<*const TileData, usize> = HashMap::with_capacity(slots.len());
        let mut groups: Vec<TileGroup> = Vec::with_capacity(slots.len());

        for (idx, s) in slots.iter().enumerate() {
            if s.tile.ram_bytes() == 0 {
                continue;
            }
            let ptr = Arc::as_ptr(s.tile);
            let (tier, dist) = Self::score_slot(s, ctx);
            if let Some(&g_idx) = ptr_to_group.get(&ptr) {
                let g = &mut groups[g_idx];
                g.indices.push(idx);
                // Keep the highest retention priority among all holders (higher tier / closer dist)
                if tier > g.tier || (tier == g.tier && dist < g.dist) {
                    g.tier = tier;
                    g.dist = dist;
                }
                g.last_access_seq = g.last_access_seq.max(s.tile.last_access_seq);
            } else {
                let g_idx = groups.len();
                ptr_to_group.insert(ptr, g_idx);
                groups.push(TileGroup {
                    indices: vec![idx],
                    tier,
                    dist,
                    last_access_seq: s.tile.last_access_seq,
                });
            }
        }

        groups.sort_by(|a, b| {
            a.tier
                .cmp(&b.tier)
                .then_with(|| b.dist.cmp(&a.dist)) // Farthest outside frustum first
                .then_with(|| a.last_access_seq.cmp(&b.last_access_seq)) // Oldest access sequence first
        });

        let mut lz4_count = 0usize;
        let mut disk_count = 0usize;

        // Pass 1: Demote Raw -> L2 LZ4 RAM (fast, zero disk I/O)
        for group in &groups {
            if total_ram <= soft_limit {
                break;
            }
            let lead_idx = group.indices[0];
            if !matches!(slots[lead_idx].tile.storage, TileStorage::Raw(_)) {
                continue;
            }
            // Safety invariant: only demote when EVERY strong reference to this Arc is in `group`.
            // Otherwise an external holder would keep the old Raw buffer alive and cloning would INCREASE RAM!
            let strong = Arc::strong_count(slots[lead_idx].tile);
            if strong > group.indices.len() {
                continue;
            }
            if strong == 1 && group.indices.len() == 1 {
                let td = Arc::make_mut(slots[lead_idx].tile);
                let freed = td.demote_to_lz4() as u64;
                if freed > 0 {
                    lz4_count += 1;
                    total_ram = total_ram.saturating_sub(freed);
                }
            } else if let Some((new_td, freed)) = slots[lead_idx].tile.to_demoted_lz4() {
                let new_arc = Arc::new(new_td);
                for &idx in &group.indices {
                    *slots[idx].tile = Arc::clone(&new_arc);
                }
                if freed > 0 {
                    lz4_count += 1;
                    total_ram = total_ram.saturating_sub(freed as u64);
                }
            }
        }

        total_ram = Self::unique_ram_bytes(&slots);
        if total_ram <= budget {
            let actual_freed = initial_ram.saturating_sub(total_ram);
            return Ok((lz4_count, disk_count, actual_freed));
        }

        // Pass 2: Demote L2/Raw -> L3 Scratch Disk (in-process zero-IPC write!)
        let mut to_page: Vec<usize> = Vec::new();
        let mut projected = total_ram;
        for (g_idx, group) in groups.iter().enumerate() {
            if projected <= target_after_evict {
                break;
            }
            let lead_idx = group.indices[0];
            let ram = slots[lead_idx].tile.ram_bytes() as u64;
            if ram == 0 {
                continue;
            }
            if Arc::strong_count(slots[lead_idx].tile) > group.indices.len() {
                continue;
            }
            to_page.push(g_idx);
            projected = projected.saturating_sub(ram);
        }

        if !to_page.is_empty() {
            let mut initialized_sessions: HashSet<&str> = HashSet::new();
            for g_idx in to_page {
                let group = &groups[g_idx];
                let lead_idx = group.indices[0];
                let strong = Arc::strong_count(slots[lead_idx].tile);
                if strong > group.indices.len() {
                    continue;
                }
                let doc_id = slots[lead_idx].doc_id;
                let layer_id = slots[lead_idx].layer_id;
                let kind = slots[lead_idx].kind;
                let coord = slots[lead_idx].coord;
                if initialized_sessions.insert(doc_id) {
                    self.scratch.init_session(doc_id)?;
                }
                let layer_key = match kind {
                    TileKind::Raster => format!("{layer_id}__v{}", slots[lead_idx].tile.version),
                    TileKind::Mask => {
                        format!("{layer_id}__mask__v{}", slots[lead_idx].tile.version)
                    }
                    TileKind::ImpastoHeight => {
                        format!("{layer_id}__impasto__v{}", slots[lead_idx].tile.version)
                    }
                };

                if strong == 1 && group.indices.len() == 1 {
                    let td = Arc::make_mut(slots[lead_idx].tile);
                    let freed = td.demote_to_disk(
                        doc_id,
                        &layer_key,
                        coord,
                        self.scratch.as_ref(),
                    )? as u64;
                    if freed > 0 {
                        disk_count += 1;
                    }
                } else if let Some((new_td, freed)) = slots[lead_idx].tile.to_demoted_disk(
                    doc_id,
                    &layer_key,
                    coord,
                    self.scratch.as_ref(),
                )? {
                    let new_arc = Arc::new(new_td);
                    for &idx in &group.indices {
                        *slots[idx].tile = Arc::clone(&new_arc);
                    }
                    if freed > 0 {
                        disk_count += 1;
                    }
                }
            }
        }

        let final_ram = Self::unique_ram_bytes(&slots);
        let actual_freed = initial_ram.saturating_sub(final_ram);
        Ok((lz4_count, disk_count, actual_freed))
    }

    /// Compresses all eligible `Raw` tiles in `slots` to L2 LZ4 RAM (e.g. when switching away from a tab),
    /// deduplicating CoW-shared `Arc`s and skipping any `Arc` with external holders so RAM never grows.
    pub fn compress_all_to_lz4(&self, mut slots: Vec<ManagedTileSlot<'_>>) -> (usize, u64) {
        let initial_ram = Self::unique_ram_bytes(&slots);
        let mut ptr_to_indices: HashMap<*const TileData, Vec<usize>> =
            HashMap::with_capacity(slots.len());
        for (idx, s) in slots.iter().enumerate() {
            if matches!(s.tile.storage, TileStorage::Raw(_)) {
                ptr_to_indices
                    .entry(Arc::as_ptr(s.tile))
                    .or_default()
                    .push(idx);
            }
        }
        let mut count = 0usize;
        for indices in ptr_to_indices.values() {
            let lead = indices[0];
            let strong = Arc::strong_count(slots[lead].tile);
            if strong > indices.len() {
                continue;
            }
            if strong == 1 && indices.len() == 1 {
                let td = Arc::make_mut(slots[lead].tile);
                if td.demote_to_lz4() > 0 {
                    count += 1;
                }
            } else if let Some((new_td, freed)) = slots[lead].tile.to_demoted_lz4() {
                let new_arc = Arc::new(new_td);
                for &idx in indices {
                    *slots[idx].tile = Arc::clone(&new_arc);
                }
                if freed > 0 {
                    count += 1;
                }
            }
        }
        let final_ram = Self::unique_ram_bytes(&slots);
        (count, initial_ram.saturating_sub(final_ram))
    }

    /// Pages all eligible tiles in `slots` to L3 Scratch Disk (explicit memory purge / tab offload),
    /// deduplicating CoW-shared `Arc`s and skipping any `Arc` with external holders so RAM never grows.
    pub fn evict_all_to_disk(
        &self,
        mut slots: Vec<ManagedTileSlot<'_>>,
    ) -> Result<(usize, u64), String> {
        let initial_ram = Self::unique_ram_bytes(&slots);
        let mut ptr_to_indices: HashMap<*const TileData, Vec<usize>> =
            HashMap::with_capacity(slots.len());
        for (idx, s) in slots.iter().enumerate() {
            if s.tile.ram_bytes() > 0 {
                ptr_to_indices
                    .entry(Arc::as_ptr(s.tile))
                    .or_default()
                    .push(idx);
            }
        }
        let mut count = 0usize;
        let mut initialized: HashSet<String> = HashSet::new();
        for indices in ptr_to_indices.values() {
            let lead = indices[0];
            let strong = Arc::strong_count(slots[lead].tile);
            if strong > indices.len() {
                continue;
            }
            let doc_id = slots[lead].doc_id;
            let layer_id = slots[lead].layer_id;
            let kind = slots[lead].kind;
            let coord = slots[lead].coord;
            if initialized.insert(doc_id.to_string()) {
                self.scratch.init_session(doc_id)?;
            }
            let layer_key = match kind {
                TileKind::Raster => format!("{layer_id}__v{}", slots[lead].tile.version),
                TileKind::Mask => format!("{layer_id}__mask__v{}", slots[lead].tile.version),
                TileKind::ImpastoHeight => {
                    format!("{layer_id}__impasto__v{}", slots[lead].tile.version)
                }
            };
            if strong == 1 && indices.len() == 1 {
                let td = Arc::make_mut(slots[lead].tile);
                if td.demote_to_disk(doc_id, &layer_key, coord, self.scratch.as_ref())? > 0 {
                    count += 1;
                }
            } else if let Some((new_td, freed)) =
                slots[lead]
                    .tile
                    .to_demoted_disk(doc_id, &layer_key, coord, self.scratch.as_ref())?
            {
                let new_arc = Arc::new(new_td);
                for &idx in indices {
                    *slots[idx].tile = Arc::clone(&new_arc);
                }
                if freed > 0 {
                    count += 1;
                }
            }
        }
        let final_ram = Self::unique_ram_bytes(&slots);
        Ok((count, initial_ram.saturating_sub(final_ram)))
    }

    fn unique_ram_bytes(slots: &[ManagedTileSlot<'_>]) -> u64 {
        let mut seen: HashMap<*const TileData, usize> = HashMap::with_capacity(slots.len());
        for s in slots {
            seen.entry(Arc::as_ptr(s.tile))
                .or_insert_with(|| s.tile.ram_bytes());
        }
        seen.values().map(|&b| b as u64).sum()
    }

    fn score_slot(slot: &ManagedTileSlot<'_>, ctx: &EvictionContext) -> (u8, i64) {
        if slot.is_history {
            // Cold undo/redo history snapshots are lowest retention priority (evict before live canvas tiles)
            return (0, i64::MAX / 4);
        }
        let is_active_doc = ctx
            .active_doc_id
            .as_deref()
            .map(|id| id == slot.doc_id)
            .unwrap_or(true);
        if !is_active_doc {
            return (0, i64::MAX / 2);
        }
        let is_hidden = ctx
            .hidden_layers
            .contains(&(slot.doc_id.to_string(), slot.layer_id.to_string()));
        if is_hidden {
            return (0, 0);
        }

        let frustum_dist = if let Some(f) = ctx.frustum {
            let min_tx = pixel_to_tile_coord(f.min_x, 0);
            let max_tx = pixel_to_tile_coord(f.max_x, 0);
            let min_ty = pixel_to_tile_coord(f.min_y, 0);
            let max_ty = pixel_to_tile_coord(f.max_y, 0);
            let dx = if slot.coord.tx < min_tx {
                (min_tx - slot.coord.tx) as i64
            } else if slot.coord.tx > max_tx {
                (slot.coord.tx - max_tx) as i64
            } else {
                0
            };
            let dy = if slot.coord.ty < min_ty {
                (min_ty - slot.coord.ty) as i64
            } else if slot.coord.ty > max_ty {
                (slot.coord.ty - max_ty) as i64
            } else {
                0
            };
            dx * dx + dy * dy
        } else {
            0
        };

        if frustum_dist > 0 {
            return (1, frustum_dist);
        }

        let is_active_layer = ctx
            .active_layer_id
            .as_deref()
            .map(|id| id == slot.layer_id)
            .unwrap_or(false);
        if is_active_layer {
            (3, 0)
        } else {
            (2, 0)
        }
    }
}