diff --git a/packages/common/store/src/sqlite/blob.rs b/packages/common/store/src/sqlite/blob.rs index 37fe231b53..3ee45763fc 100644 --- a/packages/common/store/src/sqlite/blob.rs +++ b/packages/common/store/src/sqlite/blob.rs @@ -28,15 +28,19 @@ impl SqliteDocStorage { } /// Insert or replace a blob and clear any previous soft-delete timestamp. + /// + /// The owned fields move into the query arguments. A borrowed bind would copy the payload. pub async fn set_blob(&self, blob: SetBlob) -> StoreResult<()> { + let SetBlob { key, data, mime } = blob; + let size = data.len() as i64; sqlx::query( "INSERT INTO blobs (key, data, mime, size) VALUES ($1, $2, $3, $4) \ ON CONFLICT(key) DO UPDATE SET data = $2, mime = $3, size = $4, deleted_at = NULL;", ) - .bind(&blob.key) - .bind(&blob.data) - .bind(&blob.mime) - .bind(blob.data.len() as i64) + .bind(key) + .bind(data) + .bind(mime) + .bind(size) .execute(&self.pool) .await?; diff --git a/packages/common/store/tests/sqlite_set_blob_alloc.rs b/packages/common/store/tests/sqlite_set_blob_alloc.rs new file mode 100644 index 0000000000..8cd1372028 --- /dev/null +++ b/packages/common/store/tests/sqlite_set_blob_alloc.rs @@ -0,0 +1,126 @@ +//! Single-test binary for `SqliteDocStorage::set_blob`: upsert semantics and Rust heap +//! allocation accounting. The counting global allocator sees every thread of this process, so +//! this file holds exactly one test to keep the counters free of parallel test noise. + +#![cfg(not(target_family = "wasm"))] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use affine_store::sqlite::{SetBlob, SqliteDocStorage}; + +const LARGE_ALLOC_BYTES: usize = 1024 * 1024; +const PAYLOAD_BYTES: usize = 8 * 1024 * 1024; +const MAX_SET_BLOB_HEAP_BYTES: usize = 64 * 1024; + +struct CountingAlloc; + +static REQUESTED_BYTES: AtomicUsize = AtomicUsize::new(0); +static LARGE_ALLOCS: AtomicUsize = AtomicUsize::new(0); + +fn record(size: usize) { + REQUESTED_BYTES.fetch_add(size, Ordering::Relaxed); + if size >= LARGE_ALLOC_BYTES { + LARGE_ALLOCS.fetch_add(1, Ordering::Relaxed); + } +} + +// SAFETY: Every call forwards to `System` with the same arguments. The counters only use +// atomics and never allocate. +unsafe impl GlobalAlloc for CountingAlloc { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + record(layout.size()); + // SAFETY: The caller upholds the `GlobalAlloc::alloc` contract. + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + record(layout.size()); + // SAFETY: The caller upholds the `GlobalAlloc::alloc_zeroed` contract. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + record(new_size); + // SAFETY: The caller upholds the `GlobalAlloc::realloc` contract. + unsafe { System.realloc(ptr, layout, new_size) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: The caller upholds the `GlobalAlloc::dealloc` contract. + unsafe { System.dealloc(ptr, layout) } + } +} + +#[global_allocator] +static GLOBAL: CountingAlloc = CountingAlloc; + +fn patterned(len: usize, seed: u8) -> Vec { + (0..len).map(|i| (i % 251) as u8 ^ seed).collect() +} + +async fn assert_visible(storage: &SqliteDocStorage, key: &str, data: &[u8], mime: &str) { + let record = storage + .get_blob(key) + .await + .unwrap() + .expect("blob is visible"); + assert_eq!(record.key, key); + assert_eq!(record.mime, mime); + assert_eq!(record.size, data.len() as i64); + assert!(record.data == data, "blob bytes differ for {key}"); +} + +#[tokio::test] +async fn set_blob_upserts_revives_and_moves_8_mib_payload_without_heap_copy() { + let storage = SqliteDocStorage::new(":memory:"); + storage.connect().await.unwrap(); + + // Insert, overwrite with a new length and mime, soft-delete, then revive. + let steps: [(&[u8], &str, bool); 4] = [ + (&[10, 20, 30], "image/png", false), + (&[1, 2, 3, 4, 5, 6, 7], "text/plain", false), + (&[1, 2, 3, 4, 5, 6, 7], "text/plain", true), + (&[42; 5], "image/jpeg", false), + ]; + for (data, mime, soft_delete) in steps { + if soft_delete { + storage.delete_blob("k", false, 1_000).await.unwrap(); + assert!(storage.get_blob("k").await.unwrap().is_none()); + continue; + } + storage + .set_blob(SetBlob { + key: "k".into(), + data: data.to_vec(), + mime: mime.into(), + }) + .await + .unwrap(); + assert_visible(&storage, "k", data, mime).await; + } + assert_eq!(storage.list_blobs().await.unwrap().len(), 1); + + let expected = patterned(PAYLOAD_BYTES, 0x5a); + let blob = SetBlob { + key: "large".into(), + data: expected.clone(), + mime: "application/octet-stream".into(), + }; + + REQUESTED_BYTES.store(0, Ordering::SeqCst); + LARGE_ALLOCS.store(0, Ordering::SeqCst); + storage.set_blob(blob).await.unwrap(); + let requested = REQUESTED_BYTES.load(Ordering::SeqCst); + let large = LARGE_ALLOCS.load(Ordering::SeqCst); + println!( + "set_blob {PAYLOAD_BYTES} B payload: requested {requested} B, {large} allocations >= {LARGE_ALLOC_BYTES} B" + ); + + assert_eq!(large, 0, "set_blob made a large heap allocation"); + assert!( + requested < MAX_SET_BLOB_HEAP_BYTES, + "set_blob requested {requested} B of Rust heap" + ); + assert_visible(&storage, "large", &expected, "application/octet-stream").await; +}