fix: Terminate sync immediately when project is deleted (#366)

Signed-off-by: phernandez <paul@basicmachines.co>
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Paul Hernandez
2025-10-16 11:07:12 -05:00
committed by GitHub
parent 434cdf24dd
commit 729a5a3b8d
5 changed files with 143 additions and 1 deletions
@@ -135,7 +135,20 @@ class EntityRepository(Repository[Entity]):
)
return found
except IntegrityError:
except IntegrityError as e:
# Check if this is a FOREIGN KEY constraint failure
error_str = str(e)
if "FOREIGN KEY constraint failed" in error_str:
# Import locally to avoid circular dependency (repository -> services -> repository)
from basic_memory.services.exceptions import SyncFatalError
# Project doesn't exist in database - this is a fatal sync error
raise SyncFatalError(
f"Cannot sync file '{entity.file_path}': "
f"project_id={entity.project_id} does not exist in database. "
f"The project may have been deleted. This sync will be terminated."
) from e
await session.rollback()
# Re-query after rollback to get a fresh, attached entity
+15
View File
@@ -20,3 +20,18 @@ class DirectoryOperationError(Exception):
"""Raised when directory operations fail"""
pass
class SyncFatalError(Exception):
"""Raised when sync encounters a fatal error that prevents continuation.
Fatal errors include:
- Project deleted during sync (FOREIGN KEY constraint)
- Database corruption
- Critical system failures
When this exception is raised, the entire sync operation should be terminated
immediately rather than attempting to continue with remaining files.
"""
pass
+8
View File
@@ -22,6 +22,7 @@ from basic_memory.models import Entity, Project
from basic_memory.repository import EntityRepository, RelationRepository, ObservationRepository
from basic_memory.repository.search_repository import SearchRepository
from basic_memory.services import EntityService, FileService
from basic_memory.services.exceptions import SyncFatalError
from basic_memory.services.link_resolver import LinkResolver
from basic_memory.services.search_service import SearchService
from basic_memory.services.sync_status_service import sync_status_tracker, SyncStatus
@@ -514,6 +515,13 @@ class SyncService:
return entity, checksum
except Exception as e:
# Check if this is a fatal error (or caused by one)
# Fatal errors like project deletion should terminate sync immediately
if isinstance(e, SyncFatalError) or isinstance(e.__cause__, SyncFatalError):
logger.error(f"Fatal sync error encountered, terminating sync: path={path}")
raise
# Otherwise treat as recoverable file-level error
error_msg = str(e)
logger.error(f"Failed to sync file: path={path}, error={error_msg}")