-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathprune_core.py
More file actions
2426 lines (2032 loc) · 94.4 KB
/
Copy pathprune_core.py
File metadata and controls
2426 lines (2032 loc) · 94.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Core Prune Classes and Vector Database Cleaners
This module contains all the core classes from backend/open_webui/routers/prune.py,
including the abstract vector database cleaner and its implementations.
"""
import logging
import json
import uuid
import os
import re
import shutil
import sqlite3
from datetime import datetime, timedelta
from pathlib import Path
from typing import Generator, Optional, Set, Tuple
from abc import ABC, abstractmethod
# Optional database-specific imports
try:
from sqlalchemy import text, bindparam
except ImportError:
text = None
try:
from pymilvus import utility, Collection
except ImportError:
utility = None
Collection = None
try:
from qdrant_client.models import models as qdrant_models
except ImportError:
qdrant_models = None
log = logging.getLogger(__name__)
class PruneLock:
"""
Simple file-based locking mechanism to prevent concurrent prune operations.
This uses a lock file with timestamp to prevent multiple admins from running
prune simultaneously, which could cause race conditions and data corruption.
"""
LOCK_FILE = None # Will be set by init
LOCK_TIMEOUT = timedelta(hours=2) # Safety timeout
@classmethod
def init(cls, cache_dir: Path):
"""Initialize lock file path with cache directory."""
cls.LOCK_FILE = Path(cache_dir) / ".prune.lock"
@classmethod
def acquire(cls) -> bool:
"""
Try to acquire the lock. Returns True if acquired, False if already locked.
If lock file exists but is stale (older than timeout), automatically
removes it and acquires a new lock.
"""
if cls.LOCK_FILE is None:
raise RuntimeError(
"PruneLock not initialized. Call PruneLock.init() first."
)
try:
# Check if lock file exists
if cls.LOCK_FILE.exists():
# Read lock file to check if it's stale
try:
with open(cls.LOCK_FILE, "r") as f:
lock_data = json.load(f)
lock_time = datetime.fromisoformat(lock_data["timestamp"])
operation_id = lock_data.get("operation_id", "unknown")
# Check if lock is stale
if datetime.utcnow() - lock_time > cls.LOCK_TIMEOUT:
log.warning(
f"Found stale lock from {lock_time} (operation {operation_id}), removing"
)
cls.LOCK_FILE.unlink()
else:
# Lock is still valid
log.warning(
f"Prune operation already in progress (started {lock_time}, operation {operation_id})"
)
return False
except (json.JSONDecodeError, KeyError, ValueError) as e:
# Corrupt lock file, remove it
log.warning(f"Found corrupt lock file, removing: {e}")
cls.LOCK_FILE.unlink()
# Create lock file
operation_id = str(uuid.uuid4())[:8]
lock_data = {
"timestamp": datetime.utcnow().isoformat(),
"operation_id": operation_id,
"pid": os.getpid(),
}
# Ensure parent directory exists
cls.LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(cls.LOCK_FILE, "w") as f:
json.dump(lock_data, f)
log.info(f"Acquired prune lock (operation {operation_id})")
return True
except Exception as e:
log.error(f"Error acquiring prune lock: {e}")
return False
@classmethod
def release(cls) -> None:
"""Release the lock by removing the lock file."""
if cls.LOCK_FILE is None:
return
try:
if cls.LOCK_FILE.exists():
cls.LOCK_FILE.unlink()
log.info("Released prune lock")
except Exception as e:
log.error(f"Error releasing prune lock: {e}")
class JSONFileIDExtractor:
"""
Utility for extracting and validating file IDs from JSON content.
Replaces duplicated regex compilation and validation logic used throughout
the file scanning functions. Compiles patterns once for better performance.
"""
# Compile patterns once at class level for performance
_FILE_ID_PATTERN = re.compile(
r'"id":\s*"([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})"'
)
_URL_PATTERN = re.compile(
r"/api/v1/files/([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})"
)
@classmethod
def extract_file_ids(cls, json_string: str) -> Set[str]:
"""
Extract file IDs from JSON string WITHOUT database validation.
Args:
json_string: JSON content as string (or any string to scan)
Returns:
Set of extracted file IDs (not validated against database)
Note:
Use this method when you have a preloaded set of valid file IDs
to validate against, avoiding N database queries.
"""
potential_ids = []
potential_ids.extend(cls._FILE_ID_PATTERN.findall(json_string))
potential_ids.extend(cls._URL_PATTERN.findall(json_string))
return set(potential_ids)
# UUID pattern for direct dict traversal (Phase 1.5 optimization)
UUID_PATTERN = re.compile(
r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
)
# URL-style file references: legacy generated images are stored in chat JSON as
# {"type": "image", "url": "/api/v1/files/{id}/content"} with no "id" key, so
# id-field matching alone misses them and live chats would lose their images.
URL_FILE_REF_PATTERN = re.compile(
r"/api/v1/files/([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})"
)
def collect_file_ids_from_dict(
obj, out: Set[str], valid_ids: Set[str], _depth: int = 0
) -> None:
"""
Recursively traverse dict/list structures and collect file IDs.
This function replaces json.dumps() + regex approach with direct dict traversal,
reducing memory usage by ~75% on large chat databases.
Args:
obj: Dict, list, or any value to traverse
out: Set to accumulate found file IDs into
valid_ids: Set of known valid file IDs (for O(1) validation)
_depth: Current recursion depth (safety limit)
Patterns detected:
- {"id": "uuid"}
- {"file_id": "uuid"}
- {"fileId": "uuid"}
- {"file_ids": ["uuid1", "uuid2"]}
- {"fileIds": ["uuid1", "uuid2"]}
"""
# Safety: Prevent excessive recursion
if _depth > 100:
return
if isinstance(obj, dict):
# Check individual file ID fields
# valid_ids only contains real UUIDs from the database, so set lookup
# alone is sufficient — no need for regex pre-validation
for field_name in ["id", "file_id", "fileId"]:
fid = obj.get(field_name)
if isinstance(fid, str) and fid in valid_ids:
out.add(fid)
# Check file ID array fields
for field_name in ["file_ids", "fileIds"]:
fid_array = obj.get(field_name)
if isinstance(fid_array, list):
for fid in fid_array:
if isinstance(fid, str) and fid in valid_ids:
out.add(fid)
# Check URL-style references (legacy generated images carry only a url)
for field_name in ["url", "src"]:
url_val = obj.get(field_name)
if isinstance(url_val, str) and "/api/v1/files/" in url_val:
for match in URL_FILE_REF_PATTERN.findall(url_val):
if match in valid_ids:
out.add(match)
# Recurse into all dict values
for value in obj.values():
collect_file_ids_from_dict(value, out, valid_ids, _depth + 1)
elif isinstance(obj, list):
# Recurse into all list items
for item in obj:
collect_file_ids_from_dict(item, out, valid_ids, _depth + 1)
# Primitives (str, int, None, etc.) - do nothing
# Open WebUI stores one metadata embedding per knowledge base (its name +
# description) in this shared collection, used for semantic search across KBs.
# Separate from each KB's own {kb_id} collection that holds file/chunk vectors.
KNOWLEDGE_BASES_COLLECTION = "knowledge-bases"
class VectorDatabaseCleaner(ABC):
"""
Abstract base class for vector database cleanup operations.
This interface defines the contract that all vector database implementations
must follow. Community contributors can implement support for new vector
databases by extending this class.
Supported operations:
- Count orphaned collections (for dry-run preview)
- Cleanup orphaned collections (actual deletion)
- Delete individual collections by name
"""
@abstractmethod
def count_orphaned_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> int:
"""
Count how many orphaned vector collections would be deleted.
Args:
active_file_ids: Set of file IDs that are still referenced
active_kb_ids: Set of knowledge base IDs that are still active
active_user_ids: Set of user IDs that are still active (optional, for multitenancy)
Returns:
Number of orphaned collections that would be deleted
"""
pass
@abstractmethod
def cleanup_orphaned_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> tuple[int, Optional[str]]:
"""
Actually delete orphaned vector collections.
Args:
active_file_ids: Set of file IDs that are still referenced
active_kb_ids: Set of knowledge base IDs that are still active
active_user_ids: Set of user IDs that are still active (optional, for multitenancy)
Returns:
Tuple of (deleted_count, error_message)
- deleted_count: Number of collections that were deleted
- error_message: None on success, error description on failure
"""
pass
@abstractmethod
def delete_collection(self, collection_name: str) -> bool:
"""
Delete a specific vector collection by name.
Args:
collection_name: Name of the collection to delete
Returns:
True if deletion was successful, False otherwise
"""
pass
def iter_orphaned_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> Generator[Tuple[str, str], None, None]:
"""
Yield (orphaned_id, context) for each orphaned vector item.
Used by the export feature to list individual orphaned items.
Default implementation yields nothing. Subclasses override to
provide actual iteration.
Args:
active_file_ids: Set of file IDs that are still referenced
active_kb_ids: Set of knowledge base IDs that are still active
active_user_ids: Set of user IDs that are still active
Yields:
(orphaned_id, context_string) — e.g. ("file-abc-123", "chromadb")
"""
return
yield # pragma: no cover — makes this a generator
# ── Knowledge base metadata embeddings (shared 'knowledge-bases' collection) ──
#
# These default implementations work for any backend whose client follows
# Open WebUI's unified VectorDBBase interface (get/delete/has_collection),
# so individual cleaners do not need to override them. Backends without a
# client (e.g. NoOp) fall through to a safe no-op via getattr.
def _kb_metadata_ids(self) -> Optional[Set[str]]:
"""Return the KB ids present in the shared metadata collection.
Returns None when the collection or client is unavailable (so callers
can distinguish "nothing to do" from "empty"). Best-effort.
"""
client = getattr(self, "vector_db_client", None)
if client is None:
return None
try:
if not client.has_collection(KNOWLEDGE_BASES_COLLECTION):
return None
result = client.get(KNOWLEDGE_BASES_COLLECTION)
except Exception as e:
log.debug(f"Could not read {KNOWLEDGE_BASES_COLLECTION} collection: {e}")
return None
ids: Set[str] = set()
raw = getattr(result, "ids", None) if result is not None else None
for entry in raw or []:
# GetResult.ids is List[List[str]] but some backends return a flat
# list — handle both.
if isinstance(entry, (list, tuple)):
ids.update(str(i) for i in entry if i)
elif entry:
ids.add(str(entry))
return ids
def delete_kb_metadata(self, kb_ids) -> int:
"""Remove specific KB ids from the shared metadata collection.
Mirrors Open WebUI's remove_knowledge_base_metadata_embedding. Used when
a KB is deleted (by age or as orphaned) so no ghost remains in KB search.
Best-effort; returns the number of ids requested for deletion.
"""
client = getattr(self, "vector_db_client", None)
ids = [str(i) for i in (kb_ids or []) if i]
if client is None or not ids:
return 0
try:
if not client.has_collection(KNOWLEDGE_BASES_COLLECTION):
return 0
client.delete(collection_name=KNOWLEDGE_BASES_COLLECTION, ids=ids)
return len(ids)
except Exception as e:
log.debug(f"Failed to delete KB metadata embeddings: {e}")
return 0
def count_orphaned_kb_metadata(self, active_kb_ids: Set[str]) -> int:
"""Count KB metadata entries whose knowledge base no longer exists."""
present = self._kb_metadata_ids()
if not present:
return 0
return sum(1 for kb_id in present if kb_id not in active_kb_ids)
def cleanup_orphaned_kb_metadata(self, active_kb_ids: Set[str]) -> int:
"""Delete KB metadata entries whose knowledge base no longer exists."""
present = self._kb_metadata_ids()
if not present:
return 0
orphaned = [kb_id for kb_id in present if kb_id not in active_kb_ids]
if not orphaned:
return 0
deleted = self.delete_kb_metadata(orphaned)
if deleted:
log.info(f"Deleted {deleted} orphaned knowledge base metadata embeddings")
return deleted
def iter_orphaned_kb_metadata(
self, active_kb_ids: Set[str]
) -> Generator[Tuple[str, str], None, None]:
"""Yield (kb_id, context) for each orphaned KB metadata entry."""
present = self._kb_metadata_ids() or set()
for kb_id in present:
if kb_id not in active_kb_ids:
yield (kb_id, KNOWLEDGE_BASES_COLLECTION)
# ── Memories (per-user 'user-memory-{uid}' collections) ──
#
# Open WebUI stores one vector point per memory, keyed by memory.id. When a
# user deletes an individual memory the point can be left behind, so these
# methods reconcile each active user's memory collection against the memory
# ids still in the database. Generic over the unified client; NoOp-safe.
def _collection_point_ids(self, collection_name: str) -> Optional[Set[str]]:
"""Return the point ids present in a collection, or None if unavailable."""
client = getattr(self, "vector_db_client", None)
if client is None:
return None
try:
if not client.has_collection(collection_name):
return None
result = client.get(collection_name)
except Exception as e:
log.debug(f"Could not read collection {collection_name}: {e}")
return None
ids: Set[str] = set()
raw = getattr(result, "ids", None) if result is not None else None
for entry in raw or []:
if isinstance(entry, (list, tuple)):
ids.update(str(i) for i in entry if i)
elif entry:
ids.add(str(entry))
return ids
def count_orphaned_memories(self, valid_ids_by_user: dict) -> int:
"""Count memories whose database row no longer exists, per active user."""
total = 0
for uid, valid in (valid_ids_by_user or {}).items():
present = self._collection_point_ids(f"user-memory-{uid}")
if not present:
continue
total += sum(1 for pid in present if pid not in valid)
return total
def cleanup_orphaned_memories(self, valid_ids_by_user: dict) -> int:
"""Delete memories whose database row no longer exists, per active user."""
client = getattr(self, "vector_db_client", None)
if client is None:
return 0
deleted = 0
for uid, valid in (valid_ids_by_user or {}).items():
collection = f"user-memory-{uid}"
present = self._collection_point_ids(collection)
if not present:
continue
orphans = [pid for pid in present if pid not in valid]
if not orphans:
continue
try:
client.delete(collection_name=collection, ids=orphans)
deleted += len(orphans)
except Exception as e:
log.debug(f"Failed to delete orphaned memories for {uid}: {e}")
if deleted:
log.info(f"Deleted {deleted} orphaned memories")
return deleted
def iter_orphaned_memories(
self, valid_ids_by_user: dict
) -> Generator[Tuple[str, str], None, None]:
"""Yield (point_id, context) for each orphaned memory."""
for uid, valid in (valid_ids_by_user or {}).items():
present = self._collection_point_ids(f"user-memory-{uid}") or set()
for pid in present:
if pid not in valid:
yield (pid, f"user-memory-{uid}")
class ChromaDatabaseCleaner(VectorDatabaseCleaner):
"""
ChromaDB-specific implementation of vector database cleanup.
Handles ChromaDB's specific storage structure including:
- SQLite metadata database (chroma.sqlite3)
- Physical vector storage directories
- Collection name to UUID mapping
- Segment-based storage architecture
"""
def __init__(self, vector_db_client, cache_dir: Path):
"""Initialize ChromaDB cleaner with paths."""
self.vector_db_client = vector_db_client
self.vector_dir = Path(cache_dir).parent / "vector_db"
self.chroma_db_path = self.vector_dir / "chroma.sqlite3"
def count_orphaned_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> int:
"""Count orphaned ChromaDB collections for preview."""
if not self.chroma_db_path.exists():
return 0
expected_collections = self._build_expected_collections(
active_file_ids, active_kb_ids, active_user_ids
)
uuid_to_collection = self._get_collection_mappings()
count = 0
try:
for collection_dir in self.vector_dir.iterdir():
if not collection_dir.is_dir() or collection_dir.name.startswith("."):
continue
dir_uuid = collection_dir.name
collection_name = uuid_to_collection.get(dir_uuid)
if (
collection_name is None
or collection_name not in expected_collections
):
count += 1
except Exception as e:
log.debug(f"Error counting orphaned ChromaDB collections: {e}")
return count
def iter_orphaned_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> Generator[Tuple[str, str], None, None]:
"""Yield (collection_name, context) for each orphaned ChromaDB collection."""
if not self.chroma_db_path.exists():
return
expected_collections = self._build_expected_collections(
active_file_ids, active_kb_ids, active_user_ids
)
uuid_to_collection = self._get_collection_mappings()
try:
for collection_dir in self.vector_dir.iterdir():
if not collection_dir.is_dir() or collection_dir.name.startswith("."):
continue
dir_uuid = collection_dir.name
collection_name = uuid_to_collection.get(dir_uuid)
if (
collection_name is None
or collection_name not in expected_collections
):
yield (collection_name or dir_uuid, "chromadb")
except Exception as e:
log.debug(f"Error iterating orphaned ChromaDB collections: {e}")
def cleanup_orphaned_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> tuple[int, Optional[str]]:
"""Actually delete orphaned ChromaDB collections and database records."""
if not self.chroma_db_path.exists():
return (0, None)
expected_collections = self._build_expected_collections(
active_file_ids, active_kb_ids, active_user_ids
)
uuid_to_collection = self._get_collection_mappings()
deleted_count = 0
errors = []
# First, clean up orphaned database records
try:
deleted_count += self._cleanup_orphaned_database_records()
except Exception as e:
error_msg = f"ChromaDB database cleanup failed: {e}"
log.error(error_msg)
errors.append(error_msg)
# Then clean up physical directories
try:
for collection_dir in self.vector_dir.iterdir():
if not collection_dir.is_dir() or collection_dir.name.startswith("."):
continue
dir_uuid = collection_dir.name
collection_name = uuid_to_collection.get(dir_uuid)
# Delete if no corresponding collection name or collection is not expected
if collection_name is None:
try:
shutil.rmtree(collection_dir)
deleted_count += 1
log.info(
f"Deleted orphaned ChromaDB directory (no mapping): {dir_uuid}"
)
except Exception as e:
error_msg = (
f"Failed to delete orphaned directory {dir_uuid}: {e}"
)
log.error(error_msg)
errors.append(error_msg)
elif collection_name not in expected_collections:
try:
shutil.rmtree(collection_dir)
deleted_count += 1
log.info(
f"Deleted orphaned ChromaDB collection directory: {collection_name} ({dir_uuid})"
)
except Exception as e:
error_msg = (
f"Failed to delete collection directory {dir_uuid}: {e}"
)
log.error(error_msg)
errors.append(error_msg)
else:
log.debug(
f"Keeping expected collection: {collection_name} ({dir_uuid})"
)
except Exception as e:
error_msg = f"ChromaDB directory cleanup failed: {e}"
log.error(error_msg)
errors.append(error_msg)
if deleted_count > 0:
log.info(f"Deleted {deleted_count} orphaned ChromaDB collections")
# Return error if any critical failures occurred
if errors:
return (deleted_count, "; ".join(errors))
return (deleted_count, None)
def delete_collection(self, collection_name: str) -> bool:
"""Delete a specific ChromaDB collection by name."""
try:
# Attempt to delete via ChromaDB client first
try:
self.vector_db_client.delete_collection(collection_name=collection_name)
log.debug(f"Deleted ChromaDB collection via client: {collection_name}")
except Exception as e:
log.debug(
f"Collection {collection_name} may not exist in ChromaDB: {e}"
)
# Also clean up physical directory if it exists
# Note: ChromaDB uses UUID directories, so we'd need to map collection name to UUID
# For now, let the cleanup_orphaned_collections method handle physical cleanup
return True
except Exception as e:
log.error(f"Error deleting ChromaDB collection {collection_name}: {e}")
return False
def _build_expected_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> Set[str]:
"""Build set of collection names that should exist."""
expected_collections = set()
# File collections use "file-{id}" pattern
for file_id in active_file_ids:
expected_collections.add(f"file-{file_id}")
# Knowledge base collections use the KB ID directly
for kb_id in active_kb_ids:
expected_collections.add(kb_id)
# Preserve active users' memory collections (user-memory-{id}); only a
# deleted user's memory collection should be treated as orphaned.
for user_id in active_user_ids or set():
expected_collections.add(f"user-memory-{user_id}")
# Shared KB-metadata collection is pruned per-entry, never wholesale.
expected_collections.add(KNOWLEDGE_BASES_COLLECTION)
return expected_collections
def _get_collection_mappings(self) -> dict:
"""Get mapping from ChromaDB directory UUID to collection name."""
uuid_to_collection = {}
try:
with sqlite3.connect(str(self.chroma_db_path)) as conn:
# First, get collection ID to name mapping
collection_id_to_name = {}
cursor = conn.execute("SELECT id, name FROM collections")
for collection_id, collection_name in cursor.fetchall():
collection_id_to_name[collection_id] = collection_name
# Then, get segment ID to collection mapping (segments are the directory UUIDs)
cursor = conn.execute(
"SELECT id, collection FROM segments WHERE scope = 'VECTOR'"
)
for segment_id, collection_id in cursor.fetchall():
if collection_id in collection_id_to_name:
collection_name = collection_id_to_name[collection_id]
uuid_to_collection[segment_id] = collection_name
log.debug(f"Found {len(uuid_to_collection)} ChromaDB vector segments")
except Exception as e:
log.error(f"Error reading ChromaDB metadata: {e}")
return uuid_to_collection
def _cleanup_orphaned_database_records(self) -> int:
"""
Clean up orphaned database records that ChromaDB's delete_collection() method leaves behind.
This is the key fix for the file size issue - ChromaDB doesn't properly cascade
deletions, leaving orphaned embeddings, metadata, and FTS data that prevent
VACUUM from reclaiming space.
Returns:
Number of orphaned records cleaned up
"""
cleaned_records = 0
try:
with sqlite3.connect(str(self.chroma_db_path)) as conn:
# Count orphaned records before cleanup
cursor = conn.execute(
"""
SELECT COUNT(*) FROM embeddings
WHERE segment_id NOT IN (SELECT id FROM segments)
"""
)
orphaned_embeddings = cursor.fetchone()[0]
if orphaned_embeddings == 0:
log.debug("No orphaned ChromaDB embeddings found")
return 0
log.info(
f"Cleaning up {orphaned_embeddings} orphaned ChromaDB embeddings and related data"
)
# Delete orphaned embedding_metadata first (child records)
cursor = conn.execute(
"""
DELETE FROM embedding_metadata
WHERE id IN (
SELECT id FROM embeddings
WHERE segment_id NOT IN (SELECT id FROM segments)
)
"""
)
metadata_deleted = cursor.rowcount
cleaned_records += metadata_deleted
# Delete orphaned embeddings
cursor = conn.execute(
"""
DELETE FROM embeddings
WHERE segment_id NOT IN (SELECT id FROM segments)
"""
)
embeddings_deleted = cursor.rowcount
cleaned_records += embeddings_deleted
# Selectively clean FTS while preserving active content
fts_cleaned = self._cleanup_fts_selectively(conn)
log.info(f"FTS cleanup: preserved {fts_cleaned} valid text entries")
# Clean up orphaned collection and segment metadata
cursor = conn.execute(
"""
DELETE FROM collection_metadata
WHERE collection_id NOT IN (SELECT id FROM collections)
"""
)
collection_meta_deleted = cursor.rowcount
cleaned_records += collection_meta_deleted
cursor = conn.execute(
"""
DELETE FROM segment_metadata
WHERE segment_id NOT IN (SELECT id FROM segments)
"""
)
segment_meta_deleted = cursor.rowcount
cleaned_records += segment_meta_deleted
# Clean up orphaned max_seq_id records
cursor = conn.execute(
"""
DELETE FROM max_seq_id
WHERE segment_id NOT IN (SELECT id FROM segments)
"""
)
seq_id_deleted = cursor.rowcount
cleaned_records += seq_id_deleted
# Force FTS index rebuild - this is crucial for VACUUM to work properly
conn.execute(
"INSERT INTO embedding_fulltext_search(embedding_fulltext_search) VALUES('rebuild')"
)
# Commit changes
conn.commit()
log.info(
f"ChromaDB cleanup: {embeddings_deleted} embeddings, {metadata_deleted} metadata, "
f"{collection_meta_deleted} collection metadata, {segment_meta_deleted} segment metadata, "
f"{seq_id_deleted} sequence IDs"
)
# Log database size before VACUUM for diagnostic purposes
db_size_mb = self.chroma_db_path.stat().st_size / (1024 * 1024)
log.info(
f"ChromaDB size after cleanup, before VACUUM: {db_size_mb:.1f}MB (VACUUM needed to reclaim space)"
)
except Exception as e:
log.error(f"Error cleaning orphaned ChromaDB database records: {e}")
raise
return cleaned_records
def _cleanup_fts_selectively(self, conn) -> int:
"""
Selectively clean FTS content with atomic operations, preserving only data from active embeddings.
This method prevents destroying valid search data by:
1. Creating and validating temporary table with valid content
2. Using atomic transactions for DELETE/INSERT operations
3. Rolling back on failure to preserve existing data
4. Conservative fallback: skip FTS cleanup if validation fails
Returns:
Number of valid FTS entries preserved, or -1 if FTS cleanup was skipped
"""
try:
# Step 1: Create temporary table with valid content
conn.execute(
"""
CREATE TEMPORARY TABLE temp_valid_fts AS
SELECT DISTINCT em.string_value
FROM embedding_metadata em
JOIN embeddings e ON em.id = e.id
JOIN segments s ON e.segment_id = s.id
WHERE em.string_value IS NOT NULL
AND em.string_value != ''
"""
)
# Step 2: Validate temp table creation and count records
cursor = conn.execute("SELECT COUNT(*) FROM temp_valid_fts")
valid_count = cursor.fetchone()[0]
# Step 3: Validate temp table is accessible
try:
conn.execute("SELECT 1 FROM temp_valid_fts LIMIT 1")
temp_table_ok = True
except Exception:
temp_table_ok = False
# Step 4: Only proceed if validation passed
if not temp_table_ok:
log.warning(
"FTS temp table validation failed, skipping FTS cleanup for safety"
)
conn.execute("DROP TABLE IF EXISTS temp_valid_fts")
return -1 # Signal FTS cleanup was skipped
# Step 5: FTS cleanup operation (already in transaction)
try:
# Delete all FTS content
conn.execute("DELETE FROM embedding_fulltext_search")
# Re-insert only valid content if any exists
if valid_count > 0:
conn.execute(
"""
INSERT INTO embedding_fulltext_search(string_value)
SELECT string_value FROM temp_valid_fts
"""
)
log.debug(f"Preserved {valid_count} valid FTS entries")
else:
log.debug("No valid FTS content found, cleared all entries")
# Rebuild FTS index
conn.execute(
"INSERT INTO embedding_fulltext_search(embedding_fulltext_search) VALUES('rebuild')"
)
except Exception as e:
log.error(f"FTS cleanup failed: {e}")
conn.execute("DROP TABLE IF EXISTS temp_valid_fts")
return -1 # Signal FTS cleanup failed
# Step 6: Clean up temporary table
conn.execute("DROP TABLE IF EXISTS temp_valid_fts")
return valid_count
except Exception as e:
log.error(f"FTS cleanup validation failed, leaving FTS untouched: {e}")
# Conservative approach: don't touch FTS if anything goes wrong
try:
conn.execute("DROP TABLE IF EXISTS temp_valid_fts")
except Exception:
pass
return -1 # Signal FTS cleanup was skipped
class PGVectorDatabaseCleaner(VectorDatabaseCleaner):
"""
PGVector database cleanup implementation.
Leverages the existing PGVector client's delete() method for simple,
reliable collection cleanup while maintaining comprehensive error handling
and safety features.
"""
def __init__(self, vector_db_client):
"""Initialize PGVector cleaner with client."""
self.vector_db_client = vector_db_client
# Validate that we can access the PGVector client
try:
if hasattr(vector_db_client, "session") and vector_db_client.session:
self.session = vector_db_client.session
log.debug("PGVector cleaner initialized successfully")
else:
raise Exception("PGVector client session not available")
except Exception as e:
log.error(f"Failed to initialize PGVector client for cleanup: {e}")
self.session = None
def count_orphaned_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> int:
"""Count orphaned PGVector collections for preview."""
if not self.session:
log.warning(
"PGVector session not available for counting orphaned collections"
)
return 0
try:
orphaned_collections = self._get_orphaned_collections(
active_file_ids, active_kb_ids, active_user_ids
)
self.session.rollback() # Read-only transaction
return len(orphaned_collections)
except Exception as e:
if self.session:
self.session.rollback()
log.error(f"Error counting orphaned PGVector collections: {e}")
return 0
def iter_orphaned_collections(
self,
active_file_ids: Set[str],
active_kb_ids: Set[str],
active_user_ids: Optional[Set[str]] = None,
) -> Generator[Tuple[str, str], None, None]:
"""Yield (collection_name, context) for each orphaned PGVector collection."""
if not self.session:
return
try: