Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add unused favicon cleanup check to Rust vault pruner (#1991)

Leendert de Borstef53078f051f
diff --git a/apps/browser-extension/src/utils/VaultMergeService.ts b/apps/browser-extension/src/utils/VaultMergeService.ts
index 26c8ce624..c429e06d9 100644
--- a/apps/browser-extension/src/utils/VaultMergeService.ts
+++ b/apps/browser-extension/src/utils/VaultMergeService.ts
@@ -269,7 +269,7 @@ export class VaultMergeService {
try {
// Tables needed for pruning
- const tableNames = ['Items', 'FieldValues', 'Attachments', 'TotpCodes', 'Passkeys'];
+ const tableNames = ['Items', 'FieldValues', 'Attachments', 'TotpCodes', 'Passkeys', 'Logos'];
// Read tables as JSON
const tables: TableData[] = tableNames.map(name => ({
diff --git a/apps/browser-extension/src/utils/db/queries/ItemQueries.ts b/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
index b42998f88..415dfa128 100644
--- a/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
+++ b/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
@@ -216,12 +216,6 @@ export class ItemQueries {
UpdatedAt = ?
WHERE Id = ?`;
- /**
- * Get LogoId for an item.
- */
- public static readonly GET_LOGO_ID = `
- SELECT LogoId FROM Items WHERE Id = ?`;
-
/**
* Get all unique email addresses from field values.
*/
diff --git a/apps/browser-extension/src/utils/db/queries/LogoQueries.ts b/apps/browser-extension/src/utils/db/queries/LogoQueries.ts
index 2455cc0d9..86c55ad5b 100644
--- a/apps/browser-extension/src/utils/db/queries/LogoQueries.ts
+++ b/apps/browser-extension/src/utils/db/queries/LogoQueries.ts
@@ -17,17 +17,4 @@ export class LogoQueries {
public static readonly INSERT = `
INSERT INTO Logos (Id, Source, FileData, CreatedAt, UpdatedAt, IsDeleted)
VALUES (?, ?, ?, ?, ?, ?)`;
-
- /**
- * Count items using a logo.
- */
- public static readonly COUNT_USAGE = `
- SELECT COUNT(*) as count FROM Items
- WHERE LogoId = ? AND IsDeleted = 0`;
-
- /**
- * Hard delete logo.
- */
- public static readonly HARD_DELETE = `
- DELETE FROM Logos WHERE Id = ?`;
}
diff --git a/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts b/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts
index b5f40d892..041daa1fe 100644
--- a/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts
+++ b/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts
@@ -311,13 +311,6 @@ export class ItemRepository extends BaseRepository {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- // Get the LogoId before we clear it
- const logoResult = this.client.executeQuery<{ LogoId: string | null }>(
- ItemQueries.GET_LOGO_ID,
- [itemId]
- );
- const logoId = logoResult.length > 0 ? logoResult[0].LogoId : null;
-
// Hard delete all related entities
this.hardDeleteByForeignKey('FieldValues', 'ItemId', itemId);
this.hardDeleteByForeignKey('FieldHistories', 'ItemId', itemId);
@@ -326,18 +319,11 @@ export class ItemRepository extends BaseRepository {
this.hardDeleteByForeignKey('Attachments', 'ItemId', itemId);
this.hardDeleteByForeignKey('ItemTags', 'ItemId', itemId);
- // Convert item to tombstone
- const result = this.client.executeUpdate(ItemQueries.TOMBSTONE_ITEM, [
+ // Convert item to tombstone.
+ return this.client.executeUpdate(ItemQueries.TOMBSTONE_ITEM, [
currentDateTime,
itemId
]);
-
- // Clean up orphaned logo
- if (logoId) {
- this.logoRepository.cleanupOrphanedLogo(logoId);
- }
-
- return result;
});
}
diff --git a/apps/browser-extension/src/utils/db/repositories/LogoRepository.ts b/apps/browser-extension/src/utils/db/repositories/LogoRepository.ts
index c2677c11d..91ad9e39c 100644
--- a/apps/browser-extension/src/utils/db/repositories/LogoRepository.ts
+++ b/apps/browser-extension/src/utils/db/repositories/LogoRepository.ts
@@ -61,23 +61,6 @@ export class LogoRepository extends BaseRepository {
return logoId;
}
- /**
- * Clean up orphaned logo if no items reference it.
- * @param logoId - The ID of the logo to potentially clean up
- */
- public cleanupOrphanedLogo(logoId: string): void {
- const usageResult = this.client.executeQuery<{ count: number }>(
- LogoQueries.COUNT_USAGE,
- [logoId]
- );
- const usageCount = usageResult.length > 0 ? usageResult[0].count : 0;
-
- if (usageCount === 0) {
- this.client.executeUpdate(LogoQueries.HARD_DELETE, [logoId]);
- console.debug(`[LogoRepository] Deleted orphaned logo: ${logoId}`);
- }
- }
-
/**
* Extract and normalize source domain from a URL string.
* Uses lowercase and removes www. prefix for case-insensitive matching.
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore/VaultMergeService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore/VaultMergeService.kt
index bc7cd7dd1..33e9e328e 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore/VaultMergeService.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/rustcore/VaultMergeService.kt
@@ -221,7 +221,7 @@ object VaultMergeService {
try {
// Read tables needed for pruning
- val pruneTableNames = listOf("Items", "FieldValues", "Attachments", "TotpCodes", "Passkeys")
+ val pruneTableNames = listOf("Items", "FieldValues", "Attachments", "TotpCodes", "Passkeys", "Logos")
val tables = JSONArray()
for (tableName in pruneTableNames) {
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt
index 92e94ed0d..58a78238e 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultMutate.kt
@@ -3,7 +3,9 @@ package net.aliasvault.app.vaultstore
import android.util.Log
import net.aliasvault.app.exceptions.SerializationException
import net.aliasvault.app.exceptions.VaultOperationException
+import net.aliasvault.app.rustcore.VaultMergeService
import net.aliasvault.app.vaultstore.repositories.ItemRepository
+import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
import org.json.JSONArray
import org.json.JSONObject
@@ -14,9 +16,18 @@ class VaultMutate(
private val database: VaultDatabase,
private val itemRepository: ItemRepository,
private val metadata: VaultMetadataManager,
+ private val crypto: VaultCrypto,
+ private val auth: VaultAuth,
+ private val storageProvider: StorageProvider,
) {
companion object {
private const val TAG = "VaultMutate"
+
+ // Trash retention. Soft-deleted items stay in the recycle bin for this many
+ // days before the Rust pruner permanently removes them on the next upload.
+ // This value is declared in other places as well, make sure to update them
+ // when updating this value.
+ private const val TRASH_RETENTION_DAYS = 30
}
// region Vault Mutation
@@ -29,6 +40,9 @@ class VaultMutate(
// Capture mutation sequence for race detection
val mutationSeqAtStart = metadata.getMutationSequence()
+ // Prune expired trash items and cleanup orphaned logos
+ pruneLocalVault()
+
try {
val vault = prepareVault()
@@ -91,6 +105,9 @@ class VaultMutate(
suspend fun uploadVault(webApiService: net.aliasvault.app.webapi.WebApiService): VaultUploadResult {
val mutationSeqAtStart = metadata.getMutationSequence()
+ // Prune expired trash items and cleanup orphaned logos
+ pruneLocalVault()
+
return try {
val vault = prepareVault()
@@ -238,6 +255,33 @@ class VaultMutate(
)
}
+ /**
+ * Run the Rust vault pruner against the locally-stored encrypted vault and,
+ * if any rows were pruned, persist the cleaned version and reload the
+ * in-memory database so subsequent reads see the pruned state.
+ *
+ * All errors are swallowed: pruning is best-effort and must never block
+ * the surrounding upload.
+ */
+ private fun pruneLocalVault() {
+ val encryptionKey = crypto.encryptionKey ?: return
+
+ try {
+ val (prunedBase64, prunedCount) = VaultMergeService.pruneVault(
+ vaultBase64 = database.getEncryptedDatabase(),
+ retentionDays = TRASH_RETENTION_DAYS,
+ encryptionKey = encryptionKey,
+ tempDir = storageProvider.getCacheDir(),
+ )
+ if (prunedCount == 0) return
+
+ database.storeEncryptedDatabase(prunedBase64)
+ database.unlockVault(auth.getAuthMethods())
+ } catch (e: Exception) {
+ Log.w(TAG, "Vault prune failed, continuing with upload", e)
+ }
+ }
+
// endregion
// region Data Models
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index c79733f04..7e030d840 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -81,7 +81,7 @@ class VaultStore(
internal val metadata = VaultMetadataManager(storageProvider)
private val auth = VaultAuth(storageProvider) { cache.clearCache() }
private val sync = VaultSync(database, metadata, crypto, storageProvider, itemRepository)
- private val mutate = VaultMutate(database, itemRepository, metadata)
+ private val mutate = VaultMutate(database, itemRepository, metadata, crypto, auth, storageProvider)
private val cache = VaultCache(crypto, database, keystoreProvider, storageProvider)
private val passkey = VaultPasskey(database)
private val pin by lazy {
diff --git a/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift b/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
index 7b66fde5f..0c8fbad5b 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
@@ -24,4 +24,10 @@ public struct VaultConstants {
static let isSyncingKey = "aliasvault_is_syncing"
static let defaultAutoLockTimeout: Int = 3600 // 1 hour in seconds
+
+ // Trash retention. Soft-deleted items stay in the recycle bin for this many
+ // days before the Rust pruner permanently removes them on the next sync.
+ // This value is declared in other places as well, make sure to update them
+ // when updating this value.
+ static let trashRetentionDays: Int = 30
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultMergeService.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultMergeService.swift
index 7f0056c3f..f84a03e08 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultMergeService.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultMergeService.swift
@@ -155,7 +155,7 @@ public class VaultMergeService {
defer { sqlite3_close(db) }
// Read tables needed for pruning
- let pruneTableNames = ["Items", "FieldValues", "Attachments", "TotpCodes", "Passkeys"]
+ let pruneTableNames = ["Items", "FieldValues", "Attachments", "TotpCodes", "Passkeys", "Logos"]
var tables: [[String: Any]] = []
for tableName in pruneTableNames {
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift
index bbaf6d67b..8953aab9f 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Mutate.swift
@@ -116,6 +116,9 @@ extension VaultStore {
// Capture mutation sequence for race detection
let mutationSeqAtStart = getMutationSequence()
+ // Prune expired trash items and cleanup orphaned logos
+ pruneLocalVault()
+
// Prepare vault for upload
let vault = try prepareVault()
@@ -220,6 +223,9 @@ extension VaultStore {
public func uploadVault(using webApiService: WebApiService) async throws -> VaultUploadResult {
let mutationSeqAtStart = getMutationSequence()
+ // Prune expired trash items and cleanup orphaned logos
+ pruneLocalVault()
+
// Prepare vault for upload
let vault = try prepareVault()
@@ -341,4 +347,29 @@ extension VaultStore {
print("VaultStore: Could not extract version from migration ID '\(migrationId)', returning default")
return "0.0.0"
}
+
+ /// Run the Rust vault pruner against the locally-stored encrypted vault and,
+ /// if any rows were pruned, persist the cleaned version and reload the
+ /// in-memory database so the UI reflects the change.
+ ///
+ /// All errors are swallowed: pruning is best-effort and must never block
+ /// the surrounding upload.
+ private func pruneLocalVault() {
+ do {
+ guard let encryptedVault = getEncryptedDatabase() else { return }
+ let encryptionKey = try getEncryptionKey()
+
+ let result = try VaultMergeService.shared.pruneVault(
+ vaultBase64: encryptedVault,
+ retentionDays: VaultConstants.trashRetentionDays,
+ encryptionKey: encryptionKey
+ )
+ guard result.prunedCount > 0 else { return }
+
+ try storeEncryptedDatabase(result.vaultBase64)
+ try unlockVault()
+ } catch {
+ print("VaultStore: Vault prune failed, continuing with upload: \(error)")
+ }
+ }
}
diff --git a/apps/server/AliasVault.Client/Services/Database/DbService.cs b/apps/server/AliasVault.Client/Services/Database/DbService.cs
index dd60aced4..0026d91be 100644
--- a/apps/server/AliasVault.Client/Services/Database/DbService.cs
+++ b/apps/server/AliasVault.Client/Services/Database/DbService.cs
@@ -977,7 +977,7 @@ public sealed class DbService : IDisposable
try
{
// Read table data for prune operation
- var tableNames = new[] { "Items", "FieldValues", "Attachments", "TotpCodes", "Passkeys" };
+ var tableNames = new[] { "Items", "FieldValues", "Attachments", "TotpCodes", "Passkeys", "Logos" };
var tables = await ReadTablesAsJsonAsync(_sqlConnection!, tableNames);
var pruneInput = new JsInterop.RustCore.PruneInput
diff --git a/core/rust/src/vault_pruner/mod.rs b/core/rust/src/vault_pruner/mod.rs
index b7c4c6bca..0ecd4796f 100644
--- a/core/rust/src/vault_pruner/mod.rs
+++ b/core/rust/src/vault_pruner/mod.rs
@@ -66,6 +66,9 @@ pub struct PruneStats {
pub totp_codes_pruned: u32,
/// Number of passkeys permanently deleted
pub passkeys_pruned: u32,
+ /// Number of orphan logos soft-deleted (no remaining active item references them)
+ #[serde(default)]
+ pub logos_pruned: u32,
}
/// Output of the prune operation.
@@ -99,23 +102,25 @@ pub fn prune_vault(input: PruneInput) -> VaultResult<PruneOutput> {
.ok_or_else(|| crate::error::VaultError::General(
format!("Invalid current_time format: {}", input.current_time)
))?;
+ let now_str = now.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
- // Calculate cutoff date
+ // Calculate cutoff date for trash retention
let cutoff_date = now - Duration::days(input.retention_days as i64);
- // Find Items table
- let items_table = input.tables.iter().find(|t| t.name == "Items");
- if items_table.is_none() {
- return Ok(PruneOutput {
- success: true,
- statements: vec![],
- stats,
- });
- }
-
- let items = &items_table.unwrap().records;
+ // Items table is required for both passes (trash purge + logo orphan check).
+ let items_table = match input.tables.iter().find(|t| t.name == "Items") {
+ Some(t) => t,
+ None => {
+ return Ok(PruneOutput {
+ success: true,
+ statements,
+ stats,
+ });
+ }
+ };
+ let items = &items_table.records;
- // Find items that are in trash (DeletedAt set) and older than retention period
+ // Pass 1 — find items in trash older than retention period.
let mut expired_item_ids: Vec<String> = Vec::new();
for item in items {
@@ -144,18 +149,7 @@ pub fn prune_vault(input: PruneInput) -> VaultResult<PruneOutput> {
}
}
- // If no expired items, return early
- if expired_item_ids.is_empty() {
- return Ok(PruneOutput {
- success: true,
- statements: vec![],
- stats,
- });
- }
-
- // Generate SQL statements to permanently delete the expired items and related entities
- let now_str = now.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
-
+ // Pass 1 — generate SQL for expired items + related entities.
for item_id in &expired_item_ids {
// Mark item as permanently deleted
statements.push(SqlStatement {
@@ -228,6 +222,55 @@ pub fn prune_vault(input: PruneInput) -> VaultResult<PruneOutput> {
}
}
+ // Pass 2 — orphan logo cleanup. A Logo is orphan when no Item with
+ // IsDeleted=0 references it. Items being purged in Pass 1 are treated
+ // as effectively deleted so logos they referenced can be reclaimed in
+ // the same call.
+ if let Some(logos_table) = input.tables.iter().find(|t| t.name == "Logos") {
+ let expired_set: std::collections::HashSet<&str> =
+ expired_item_ids.iter().map(|s| s.as_str()).collect();
+
+ let mut referenced_logo_ids: std::collections::HashSet<String> =
+ std::collections::HashSet::new();
+ for item in items {
+ let is_deleted = item.get("IsDeleted")
+ .map(|v| v.as_i64() == Some(1) || v.as_bool() == Some(true))
+ .unwrap_or(false);
+ if is_deleted {
+ continue;
+ }
+ let item_id = item.get("Id").and_then(|v| v.as_str()).unwrap_or("");
+ if expired_set.contains(item_id) {
+ continue;
+ }
+ if let Some(logo_id) = item.get("LogoId").and_then(|v| v.as_str()) {
+ referenced_logo_ids.insert(logo_id.to_string());
+ }
+ }
+
+ for logo in &logos_table.records {
+ let is_deleted = logo.get("IsDeleted")
+ .map(|v| v.as_i64() == Some(1) || v.as_bool() == Some(true))
+ .unwrap_or(false);
+ if is_deleted {
+ continue;
+ }
+
+ if let Some(logo_id) = logo.get("Id").and_then(|v| v.as_str()) {
+ if !referenced_logo_ids.contains(logo_id) {
+ statements.push(SqlStatement {
+ sql: "UPDATE Logos SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ?".to_string(),
+ params: vec![
+ serde_json::json!(now_str),
+ serde_json::json!(logo_id),
+ ],
+ });
+ stats.logos_pruned += 1;
+ }
+ }
+ }
+ }
+
Ok(PruneOutput {
success: true,
statements,
@@ -305,6 +348,29 @@ mod tests {
record
}
+ fn make_item_with_logo(
+ id: &str,
+ logo_id: Option<&str>,
+ deleted_at: Option<&str>,
+ is_deleted: bool,
+ ) -> Record {
+ let mut record = make_item_record(id, deleted_at, is_deleted);
+ match logo_id {
+ Some(lid) => record.insert("LogoId".to_string(), serde_json::json!(lid)),
+ None => record.insert("LogoId".to_string(), serde_json::Value::Null),
+ };
+ record
+ }
+
+ fn make_logo_record(id: &str, is_deleted: bool) -> Record {
+ let mut record = HashMap::new();
+ record.insert("Id".to_string(), serde_json::json!(id));
+ record.insert("Source".to_string(), serde_json::json!("example.com"));
+ record.insert("UpdatedAt".to_string(), serde_json::json!("2024-01-01T00:00:00Z"));
+ record.insert("IsDeleted".to_string(), serde_json::json!(if is_deleted { 1 } else { 0 }));
+ record
+ }
+
#[test]
fn test_prune_expired_items() {
let now = Utc::now();
@@ -433,4 +499,184 @@ mod tests {
assert!(output.success);
assert_eq!(output.stats.items_pruned, 1);
}
+
+ fn logo_update_count(output: &PruneOutput) -> usize {
+ output.statements.iter()
+ .filter(|s| s.sql.starts_with("UPDATE Logos"))
+ .count()
+ }
+
+ #[test]
+ fn test_orphan_logo_with_no_referencing_items_is_pruned() {
+ let now_str = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ let input = PruneInput {
+ tables: vec![
+ TableData {
+ name: "Items".to_string(),
+ records: vec![],
+ },
+ TableData {
+ name: "Logos".to_string(),
+ records: vec![make_logo_record("logo-orphan", false)],
+ },
+ ],
+ retention_days: 30,
+ current_time: now_str,
+ };
+
+ let output = prune_vault(input).unwrap();
+
+ assert!(output.success);
+ assert_eq!(output.stats.logos_pruned, 1);
+ assert_eq!(logo_update_count(&output), 1);
+ }
+
+ #[test]
+ fn test_logo_referenced_by_active_item_is_kept() {
+ let now_str = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ let input = PruneInput {
+ tables: vec![
+ TableData {
+ name: "Items".to_string(),
+ records: vec![make_item_with_logo("item-1", Some("logo-1"), None, false)],
+ },
+ TableData {
+ name: "Logos".to_string(),
+ records: vec![make_logo_record("logo-1", false)],
+ },
+ ],
+ retention_days: 30,
+ current_time: now_str,
+ };
+
+ let output = prune_vault(input).unwrap();
+
+ assert!(output.success);
+ assert_eq!(output.stats.logos_pruned, 0);
+ assert_eq!(logo_update_count(&output), 0);
+ }
+
+ #[test]
+ fn test_logo_referenced_only_by_tombstoned_item_is_pruned() {
+ let now_str = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ // The tombstoned item (IsDeleted=1) still has LogoId set; the logo
+ // should be considered orphan since no active item references it.
+ let input = PruneInput {
+ tables: vec![
+ TableData {
+ name: "Items".to_string(),
+ records: vec![make_item_with_logo("item-1", Some("logo-1"), None, true)],
+ },
+ TableData {
+ name: "Logos".to_string(),
+ records: vec![make_logo_record("logo-1", false)],
+ },
+ ],
+ retention_days: 30,
+ current_time: now_str,
+ };
+
+ let output = prune_vault(input).unwrap();
+
+ assert_eq!(output.stats.logos_pruned, 1);
+ }
+
+ #[test]
+ fn test_logo_referenced_only_by_item_being_purged_is_pruned() {
+ let now = Utc::now();
+ let now_str = now.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ // Item is in trash older than retention — Pass 1 will tombstone it,
+ // Pass 2 should reclaim its logo in the same call.
+ let old_date = (now - Duration::days(60)).format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ let input = PruneInput {
+ tables: vec![
+ TableData {
+ name: "Items".to_string(),
+ records: vec![make_item_with_logo("item-1", Some("logo-1"), Some(&old_date), false)],
+ },
+ TableData {
+ name: "Logos".to_string(),
+ records: vec![make_logo_record("logo-1", false)],
+ },
+ ],
+ retention_days: 30,
+ current_time: now_str,
+ };
+
+ let output = prune_vault(input).unwrap();
+
+ assert_eq!(output.stats.items_pruned, 1);
+ assert_eq!(output.stats.logos_pruned, 1);
+ }
+
+ #[test]
+ fn test_logo_referenced_by_item_in_recent_trash_is_kept() {
+ let now = Utc::now();
+ let now_str = now.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ // Item is in trash but within retention — could still be restored,
+ // so its logo must be preserved.
+ let recent_date = (now - Duration::days(10)).format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ let input = PruneInput {
+ tables: vec![
+ TableData {
+ name: "Items".to_string(),
+ records: vec![make_item_with_logo("item-1", Some("logo-1"), Some(&recent_date), false)],
+ },
+ TableData {
+ name: "Logos".to_string(),
+ records: vec![make_logo_record("logo-1", false)],
+ },
+ ],
+ retention_days: 30,
+ current_time: now_str,
+ };
+
+ let output = prune_vault(input).unwrap();
+
+ assert_eq!(output.stats.items_pruned, 0);
+ assert_eq!(output.stats.logos_pruned, 0);
+ }
+
+ #[test]
+ fn test_already_soft_deleted_logo_is_not_re_pruned() {
+ let now_str = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ let input = PruneInput {
+ tables: vec![
+ TableData {
+ name: "Items".to_string(),
+ records: vec![],
+ },
+ TableData {
+ name: "Logos".to_string(),
+ records: vec![make_logo_record("logo-1", true)],
+ },
+ ],
+ retention_days: 30,
+ current_time: now_str,
+ };
+
+ let output = prune_vault(input).unwrap();
+
+ assert_eq!(output.stats.logos_pruned, 0);
+ }
+
+ #[test]
+ fn test_logo_pruning_skipped_when_logos_table_absent() {
+ let now_str = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
+ let input = PruneInput {
+ tables: vec![
+ TableData {
+ name: "Items".to_string(),
+ records: vec![make_item_with_logo("item-1", Some("logo-1"), None, false)],
+ },
+ ],
+ retention_days: 30,
+ current_time: now_str,
+ };
+
+ let output = prune_vault(input).unwrap();
+
+ assert_eq!(output.stats.logos_pruned, 0);
+ assert_eq!(logo_update_count(&output), 0);
+ }
}