~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix: resolve download failures and integrate encrypted database system
LearningCircuit65ebe6bd5221
diff --git a/src/local_deep_research/library/download_management/__init__.py b/src/local_deep_research/library/download_management/__init__.pynew file mode 100644index 0000000000..cff5a4506e--- /dev/null+++ b/src/local_deep_research/library/download_management/__init__.py@@ -0,0 +1,37 @@+"""+Download Management Module++Smart retry management for downloaded resources with failure classification,+cooldown handling, and permanent failure tracking to prevent endless retry loops.+"""++from .retry_manager import (+ RetryManager,+ RetryDecision,+ ResourceFilterResult,+ FilterSummary,+)+from .failure_classifier import (+ BaseFailure,+ PermanentFailure,+ TemporaryFailure,+ RateLimitFailure,+ FailureClassifier,+)+from .status_tracker import ResourceStatusTracker, ResourceDownloadStatus+from .filters.resource_filter import ResourceFilter++__all__ = [+ "RetryManager",+ "RetryDecision",+ "ResourceFilterResult",+ "FilterSummary",+ "BaseFailure",+ "PermanentFailure",+ "TemporaryFailure",+ "RateLimitFailure",+ "FailureClassifier",+ "ResourceStatusTracker",+ "ResourceDownloadStatus",+ "ResourceFilter",+]diff --git a/src/local_deep_research/library/download_management/database_init.py b/src/local_deep_research/library/download_management/database_init.pynew file mode 100644index 0000000000..6e0a08b173--- /dev/null+++ b/src/local_deep_research/library/download_management/database_init.py@@ -0,0 +1,67 @@+"""+Database Initialization for Download Management++Creates the necessary database tables for tracking download status and retry logic.+"""++from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime+from sqlalchemy.ext.declarative import declarative_base+from loguru import logger++Base = declarative_base()+++class ResourceDownloadStatus(Base):+ """Database model for tracking resource download status"""++ __tablename__ = "resource_download_status"++ id = Column(Integer, primary_key=True)+ resource_id = Column(Integer, unique=True, nullable=False, index=True)+ status = Column(String(50), nullable=False, default="available")+ failure_type = Column(String(100))+ failure_message = Column(Text)+ retry_after_timestamp = Column(DateTime)+ last_attempt_at = Column(DateTime)+ total_retry_count = Column(Integer, default=0)+ today_retry_count = Column(Integer, default=0)+ created_at = Column(DateTime)+ updated_at = Column(DateTime)++ def __repr__(self):+ return f"<ResourceDownloadStatus(resource_id={self.resource_id}, status='{self.status}')>"+++def init_database():+ """Initialize the database with required tables"""++ # Create engine - use same path as research_library module+ engine = create_engine("sqlite:///data/research_library.db")++ # Create tables+ Base.metadata.create_all(engine)++ logger.info("Download management database tables initialized successfully")+ return engine+++def verify_table_exists():+ """Verify that the required tables exist"""++ engine = create_engine("sqlite:///data/research_library.db")++ # Check if table exists+ inspector = engine.dialect.get_table_names(engine)++ if "resource_download_status" in inspector:+ logger.info("✓ resource_download_status table exists")+ return True+ else:+ logger.warning("✗ resource_download_status table missing")+ return False+++if __name__ == "__main__":+ # Initialize database when run directly+ init_database()+ verify_table_exists()diff --git a/src/local_deep_research/library/download_management/failure_classifier.py b/src/local_deep_research/library/download_management/failure_classifier.pynew file mode 100644index 0000000000..ed7899bf37--- /dev/null+++ b/src/local_deep_research/library/download_management/failure_classifier.py@@ -0,0 +1,211 @@+"""+Failure Classification System with Inheritance++Provides base classes and specific failure types for download attempts.+Uses inheritance to organize different failure categories and their retry behavior.+"""++from abc import ABC+from datetime import datetime, timedelta+from typing import Optional+from urllib.parse import urlparse++from loguru import logger+++class BaseFailure(ABC):+ """Base class for all failure types with common functionality"""++ def __init__(+ self,+ error_type: str,+ message: str,+ retry_after: Optional[timedelta] = None,+ ):+ """+ Initialize a failure classification.++ Args:+ error_type: Machine-readable error identifier+ message: Human-readable error description+ retry_after: When this failure can be retried (None = permanent)+ """+ self.error_type = error_type+ self.message = message+ self.retry_after = retry_after+ self.created_at = datetime.now()++ logger.debug(+ f"[FAILURE_CLASSIFIER] Created {self.__class__.__name__}: {error_type} - {message}"+ )++ def is_permanent(self) -> bool:+ """Check if this is a permanent failure (never retry)"""+ return self.retry_after is None++ def can_retry_now(self) -> bool:+ """Check if this resource can be retried right now"""+ if self.is_permanent():+ return False+ return datetime.now() >= self.created_at + self.retry_after++ def get_cooldown_remaining(self) -> Optional[timedelta]:+ """Get remaining cooldown time, or None if no cooldown"""+ if self.is_permanent():+ return None++ retry_time = self.created_at + self.retry_after+ if datetime.now() < retry_time:+ return retry_time - datetime.now()+ return None++ def to_dict(self) -> dict:+ """Convert to dictionary for database storage"""+ return {+ "error_type": self.error_type,+ "message": self.message,+ "retry_after_timestamp": self.created_at + self.retry_after+ if self.retry_after+ else None,+ "is_permanent": self.is_permanent(),+ "created_at": self.created_at,+ }+++class PermanentFailure(BaseFailure):+ """Resources that should never be retried"""++ def __init__(self, error_type: str, message: str):+ super().__init__(error_type, message, retry_after=None)+++class TemporaryFailure(BaseFailure):+ """Resources that can be retried after cooldown"""++ def __init__(self, error_type: str, message: str, cooldown: timedelta):+ super().__init__(error_type, message, retry_after=cooldown)+++class RateLimitFailure(TemporaryFailure):+ """Domain-specific rate limit handling with longer cooldowns"""++ def __init__(self, domain: str, details: str = ""):+ # Domain-specific cooldown periods+ domain_cooldowns = {+ "arxiv.org": timedelta(+ hours=6+ ), # General arXiv rate limiting (reCAPTCHA handled separately)+ "pubmed.ncbi.nlm.nih.gov": timedelta(hours=2), # PubMed rate limits+ "biorxiv.org": timedelta(hours=6), # BioRxiv rate limits+ "semanticscholar.org": timedelta(+ hours=4+ ), # Semantic Scholar rate limits+ "researchgate.net": timedelta(hours=12), # ResearchGate rate limits+ "default": timedelta(+ hours=1+ ), # Default cooldown for unknown domains+ }++ cooldown = domain_cooldowns.get(domain, domain_cooldowns["default"])+ message = f"Rate limited by {domain}"+ if details:+ message += f" - {details}"++ super().__init__("rate_limited", message, cooldown)+ self.domain = domain+++class FailureClassifier:+ """Classifies download failures into appropriate types based on error patterns"""++ def classify_failure(+ self,+ error_type: str,+ status_code: Optional[int] = None,+ url: str = "",+ details: str = "",+ ) -> BaseFailure:+ """+ Classify a download failure based on error information.++ Args:+ error_type: Error type identifier+ status_code: HTTP status code if available+ url: URL that failed+ details: Additional error details++ Returns:+ Appropriate failure classification+ """+ # HTTP Status Code classifications+ if status_code:+ if status_code == 404:+ return PermanentFailure("not_found", "Resource not found (404)")+ elif status_code == 403:+ return PermanentFailure("forbidden", "Access forbidden (403)")+ elif status_code == 410:+ return PermanentFailure(+ "gone", "Resource permanently removed (410)"+ )+ elif status_code == 429:+ domain = urlparse(url).netloc if url else "unknown"+ return RateLimitFailure(domain, details)+ elif status_code == 503:+ return TemporaryFailure(+ "server_error",+ "Service temporarily unavailable (503)",+ timedelta(hours=1),+ )++ # Error message pattern classifications+ error_lower = error_type.lower()+ details_lower = details.lower()++ # arXiv specific patterns+ if "arxiv" in error_lower or "arxiv" in details_lower:+ if "recaptcha" in details_lower or "captcha" in details_lower:+ return TemporaryFailure(+ "recaptcha_protection",+ "Anti-bot protection active, retry after 3 days",+ timedelta(days=3),+ )+ if "not a pdf file" in details_lower:+ return PermanentFailure(+ "incompatible_format", "Content is not a PDF file"+ )+ if (+ "html" in details_lower+ and "application/pdf" not in details_lower+ ):+ return PermanentFailure(+ "incompatible_format",+ "Content returned HTML instead of PDF",+ )++ # Common timeout and network errors+ if "timeout" in error_lower:+ return TemporaryFailure(+ "timeout", "Request timed out", timedelta(minutes=30)+ )+ if "connection" in error_lower or "network" in error_lower:+ return TemporaryFailure(+ "network_error",+ "Network connectivity issue",+ timedelta(minutes=5),+ )++ # Default to temporary failure with 1-hour cooldown+ logger.warning(+ f"[FAILURE_CLASSIFIER] Unclassified error: {error_type} - {details}"+ )+ return TemporaryFailure(+ "unknown_error", f"Unknown error: {error_type}", timedelta(hours=1)+ )++ def classify_from_exception(+ self, exception: Exception, url: str = ""+ ) -> BaseFailure:+ """Classify failure from exception object"""+ error_type = type(exception).__name__+ details = str(exception)+ return self.classify_failure(error_type, details=details, url=url)diff --git a/src/local_deep_research/library/download_management/filters/__init__.py b/src/local_deep_research/library/download_management/filters/__init__.pynew file mode 100644index 0000000000..bd2fffe833--- /dev/null+++ b/src/local_deep_research/library/download_management/filters/__init__.py@@ -0,0 +1,12 @@+"""+Filters Submodule++Provides smart filtering logic for downloadable resources based on+failure history, cooldowns, and retry policies.+"""++from .resource_filter import ResourceFilter++__all__ = [+ "ResourceFilter",+]diff --git a/src/local_deep_research/library/download_management/filters/resource_filter.py b/src/local_deep_research/library/download_management/filters/resource_filter.pynew file mode 100644index 0000000000..e85134281c--- /dev/null+++ b/src/local_deep_research/library/download_management/filters/resource_filter.py@@ -0,0 +1,164 @@+"""+Resource Filter++Smart filtering logic for downloadable resources based on failure history,+cooldowns, and retry policies. Replaces simple file existence checks with+intelligent retry management.+"""++from typing import List, Optional++from loguru import logger++from ..retry_manager import RetryManager, ResourceFilterResult, FilterSummary+++class ResourceFilter:+ """Filter resources for download based on history and policies"""++ def __init__(self, username: str, password: Optional[str] = None):+ """+ Initialize the resource filter.++ Args:+ username: Username for database access+ password: Optional password for encrypted database+ """+ self.username = username+ self.retry_manager = RetryManager(username, password)+ logger.info(f"[RESOURCE_FILTER] Initialized for user: {username}")++ def filter_downloadable_resources(+ self, resources: List, check_files: bool = True+ ) -> List[ResourceFilterResult]:+ """+ Filter resources that are available for download.++ Args:+ resources: List of ResearchResource objects to filter+ check_files: Whether to also check for existing text files (legacy behavior)++ Returns:+ List of ResourceFilterResult objects with retry decisions+ """+ logger.info(f"[RESOURCE_FILTER] Filtering {len(resources)} resources")++ # Use retry manager to filter based on failure history+ results = self.retry_manager.filter_resources(resources)++ # Optional legacy file existence check+ if check_files:+ results = self._apply_legacy_file_check(results)++ return results++ def _apply_legacy_file_check(+ self, results: List[ResourceFilterResult]+ ) -> List[ResourceFilterResult]:+ """+ Apply legacy file existence checking to filter results.++ Args:+ results: Existing filter results to modify++ Returns:+ Updated filter results with file existence check+ """+ # This would get the download service instance to check for existing files+ # For now, we'll skip this as the retry manager handles the main logic+ return results++ def get_filter_summary(+ self, resources: List, check_files: bool = True+ ) -> FilterSummary:+ """+ Get a summary of filtering results.++ Args:+ resources: List of resources that were filtered+ check_files: Whether file existence checking was applied++ Returns:+ FilterSummary object with detailed counts+ """+ results = self.filter_downloadable_resources(resources, check_files)+ return self.retry_manager.get_filter_summary(results)++ def get_skipped_resources_info(self, resources: List) -> dict:+ """+ Get detailed information about skipped resources for UI display.++ Args:+ resources: List of all resources++ Returns:+ Dictionary with detailed skip information+ """+ results = self.filter_downloadable_resources(resources)++ skipped_resources = []+ for result in results:+ if not result.can_retry:+ status_info = (+ self.retry_manager.status_tracker.get_resource_status(+ result.resource_id+ )+ )+ skipped_resources.append(+ {+ "resource_id": result.resource_id,+ "status": result.status,+ "reason": result.reason,+ "estimated_wait_minutes": result.estimated_wait.total_seconds()+ // 60+ if result.estimated_wait+ else None,+ "status_info": status_info,+ }+ )++ return {+ "total_skipped": len(skipped_resources),+ "permanently_failed": [+ r+ for r in skipped_resources+ if r["status"] == "permanently_failed"+ ],+ "temporarily_failed": [+ r+ for r in skipped_resources+ if r["status"] == "temporarily_failed"+ ],+ "other_skipped": [+ r+ for r in skipped_resources+ if r["status"]+ not in ["permanently_failed", "temporarily_failed"]+ ],+ "skipped_resources": skipped_resources,+ }++ def should_skip_resource(self, resource_id: int) -> tuple[bool, str]:+ """+ Quick check if a specific resource should be skipped.++ Args:+ resource_id: Resource identifier++ Returns:+ Tuple of (should_skip, reason)+ """+ decision = self.retry_manager.should_retry_resource(resource_id)+ return (+ not decision.can_retry,+ decision.reason or "Resource not available for retry",+ )++ def get_retry_statistics(self) -> dict:+ """+ Get retry statistics for monitoring and debugging.++ Returns:+ Dictionary with retry statistics+ """+ return self.retry_manager.get_retry_statistics()diff --git a/src/local_deep_research/library/download_management/retry_manager.py b/src/local_deep_research/library/download_management/retry_manager.pynew file mode 100644index 0000000000..f1b40c341d--- /dev/null+++ b/src/local_deep_research/library/download_management/retry_manager.py@@ -0,0 +1,278 @@+"""+Retry Manager++Core retry logic and cooldown management for download attempts.+Prevents endless retry loops and implements intelligent retry strategies.+"""++from dataclasses import dataclass+from datetime import datetime, timedelta+from typing import List, Optional, Tuple++from loguru import logger+from .failure_classifier import FailureClassifier+from .status_tracker import ResourceStatusTracker+++@dataclass+class RetryDecision:+ """Decision about whether to retry a resource"""++ can_retry: bool+ reason: Optional[str] = None+ estimated_wait_time: Optional[timedelta] = None+++class ResourceFilterResult:+ """Result of filtering a resource"""++ def __init__(+ self,+ resource_id: int,+ can_retry: bool,+ status: str,+ reason: str = "",+ estimated_wait: Optional[timedelta] = None,+ ):+ self.resource_id = resource_id+ self.can_retry = can_retry+ self.status = status+ self.reason = reason+ self.estimated_wait = estimated_wait+++class FilterSummary:+ """Summary of filtering results"""++ def __init__(self):+ self.total_count = 0+ self.downloadable_count = 0+ self.permanently_failed_count = 0+ self.temporarily_failed_count = 0+ self.available_count = 0+ self.failure_type_counts = {}++ def add_result(self, result: ResourceFilterResult):+ """Add a filtering result to the summary"""+ self.total_count += 1++ if result.can_retry:+ self.downloadable_count += 1+ elif result.status == "permanently_failed":+ self.permanently_failed_count += 1+ elif result.status == "temporarily_failed":+ self.temporarily_failed_count += 1+ else:+ self.available_count += 1++ def to_dict(self) -> dict:+ """Convert to dictionary"""+ return {+ "total_count": self.total_count,+ "downloadable_count": self.downloadable_count,+ "permanently_failed_count": self.permanently_failed_count,+ "temporarily_failed_count": self.temporarily_failed_count,+ "available_count": self.available_count,+ "failure_type_counts": self.failure_type_counts,+ }+++class RetryManager:+ """Manage retry logic and prevent endless loops"""++ def __init__(self, username: str, password: Optional[str] = None):+ """+ Initialize the retry manager.++ Args:+ username: Username for database access+ password: Optional password for encrypted database+ """+ self.username = username+ self.failure_classifier = FailureClassifier()+ self.status_tracker = ResourceStatusTracker(username, password)++ logger.info(f"[RETRY_MANAGER] Initialized for user: {username}")++ def should_retry_resource(self, resource_id: int) -> RetryDecision:+ """+ Determine if a resource should be retried based on history.++ Args:+ resource_id: Resource identifier++ Returns:+ RetryDecision with can_retry flag and reasoning+ """+ can_retry, reason = self.status_tracker.can_retry(resource_id)+ return RetryDecision(can_retry=can_retry, reason=reason)++ def record_attempt(+ self,+ resource_id: int,+ result: Tuple[bool, Optional[str]],+ status_code: Optional[int] = None,+ url: str = "",+ details: str = "",+ ) -> None:+ """+ Record a download attempt result.++ Args:+ resource_id: Resource identifier+ result: Tuple of (success, error_message)+ status_code: HTTP status code if available+ url: URL that was attempted+ details: Additional error details+ """+ success, error_message = result++ if success:+ # Successful download+ self.status_tracker.mark_success(resource_id)+ logger.info(+ f"[RETRY_MANAGER] Resource {resource_id} marked as successful"+ )+ else:+ # Failed download - classify the failure+ failure = self.failure_classifier.classify_failure(+ error_type=type(error_message).__name__+ if error_message+ else "unknown",+ status_code=status_code,+ url=url,+ details=details or (error_message or "Unknown error"),+ )++ self.status_tracker.mark_failure(resource_id, failure)+ logger.info(+ f"[RETRY_MANAGER] Resource {resource_id} marked as failed: {failure.error_type}"+ )++ def filter_resources(self, resources: List) -> List[ResourceFilterResult]:+ """+ Filter resources based on their retry eligibility.++ Args:+ resources: List of resources to filter++ Returns:+ List of ResourceFilterResult objects+ """+ results = []++ for resource in resources:+ if not hasattr(resource, "id"):+ # Skip resources without ID+ continue++ can_retry, reason = self.status_tracker.can_retry(resource.id)+ status = self._get_resource_status(can_retry, reason)++ # Get estimated wait time if temporarily failed+ estimated_wait = None+ if not can_retry and reason and "cooldown" in reason.lower():+ try:+ status_info = self.status_tracker.get_resource_status(+ resource.id+ )+ if status_info and status_info["retry_after_timestamp"]:+ retry_time = datetime.fromisoformat(+ status_info["retry_after_timestamp"]+ )+ estimated_wait = retry_time - datetime.now()+ except Exception as e:+ logger.debug(+ f"[RETRY_MANAGER] Error calculating wait time: {e}"+ )++ result = ResourceFilterResult(+ resource_id=resource.id,+ can_retry=can_retry,+ status=status,+ reason=reason or "",+ estimated_wait=estimated_wait,+ )+ results.append(result)++ logger.info(+ f"[RETRY_MANAGER] Filtered {len(results)} resources: "+ f"{sum(1 for r in results if r.can_retry)} downloadable, "+ f"{sum(1 for r in results if r.status == 'permanently_failed')} permanently failed"+ )++ return results++ def get_filter_summary(+ self, results: List[ResourceFilterResult]+ ) -> FilterSummary:+ """+ Generate a summary of filtering results.++ Args:+ results: List of ResourceFilterResult objects++ Returns:+ FilterSummary object with counts+ """+ summary = FilterSummary()+ for result in results:+ summary.add_result(result)+ return summary++ def _get_resource_status(+ self, can_retry: bool, reason: Optional[str]+ ) -> str:+ """Get status string based on retry decision"""+ if not can_retry:+ if reason and "permanently failed" in reason:+ return "permanently_failed"+ elif reason and "cooldown" in reason:+ return "temporarily_failed"+ else:+ return "unavailable"+ return "available"++ def get_retry_statistics(self) -> dict:+ """+ Get retry statistics for monitoring.++ Returns:+ Dictionary with retry statistics+ """+ failure_counts = self.status_tracker.get_failed_resources_count()++ return {+ "total_permanent_failures": sum(+ count for count in failure_counts.values()+ ),+ "total_temporary_failures": sum(+ count for count in failure_counts.values()+ ),+ "failure_type_breakdown": failure_counts,+ }++ def reset_daily_retry_counters(self) -> int:+ """+ Reset daily retry counters (call this at midnight).++ Returns:+ Number of resources that had their daily counter reset+ """+ # This would be called by a daily cron job+ logger.info(+ "[RETRY_MANAGER] Daily retry counter reset would be called here"+ )+ return 0 # Implementation would reset today_retry_count in database++ def clear_old_permanent_failures(self, days: int = 30) -> int:+ """+ Clear old permanent failure records.++ Args:+ days: Clear failures older than this many days++ Returns:+ Number of records cleared+ """+ return self.status_tracker.clear_permanent_failures(days)diff --git a/src/local_deep_research/library/download_management/status_tracker.py b/src/local_deep_research/library/download_management/status_tracker.pynew file mode 100644index 0000000000..29459e4ffc--- /dev/null+++ b/src/local_deep_research/library/download_management/status_tracker.py@@ -0,0 +1,321 @@+"""+Resource Status Tracker++Tracks download attempts, failures, and cooldowns in the database.+Provides persistent storage for failure classifications and retry eligibility.+"""++from datetime import datetime, timedelta+from typing import Optional, Dict, Any++from loguru import logger+from sqlalchemy import Column, Integer, String, Text, DateTime+from sqlalchemy.ext.declarative import declarative_base+from sqlalchemy.orm import sessionmaker, Session++Base = declarative_base()+++class ResourceDownloadStatus(Base):+ """Database model for tracking resource download status"""++ __tablename__ = "resource_download_status"++ id = Column(Integer, primary_key=True)+ resource_id = Column(Integer, unique=True, nullable=False, index=True)++ # Status tracking+ status = Column(+ String(50), nullable=False, default="available"+ ) # available, temporarily_failed, permanently_failed+ failure_type = Column(String(100)) # not_found, rate_limited, timeout, etc.+ failure_message = Column(Text)++ # Retry timing+ retry_after_timestamp = Column(+ DateTime+ ) # When this can be retried (NULL = permanent)+ last_attempt_at = Column(DateTime)+ permanent_failure_at = Column(DateTime) # When permanently failed++ # Statistics+ total_retry_count = Column(Integer, default=0)+ today_retry_count = Column(Integer, default=0)++ # Timestamps+ created_at = Column(DateTime, default=datetime.now)+ updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)++ def __repr__(self):+ return f"<ResourceDownloadStatus(resource_id={self.resource_id}, status='{self.status}', failure_type='{self.failure_type}')>"+++class ResourceStatusTracker:+ """Track download attempts, failures, and cooldowns in database"""++ def __init__(self, username: str, password: Optional[str] = None):+ """+ Initialize the status tracker for a user.++ Args:+ username: Username for database access+ password: Optional password for encrypted database+ """+ self.username = username+ self.password = password++ # Use the same encrypted database system as the main application+ from ...database.encrypted_db import DatabaseManager++ self.db_manager = DatabaseManager()+ self.engine = self.db_manager.create_user_database(username, password)+ self.Session = sessionmaker(bind=self.engine)++ # Create tables if they don't exist+ Base.metadata.create_all(self.engine)+ logger.info(+ f"[STATUS_TRACKER] Initialized for user: {username} with encrypted database"+ )++ def _get_session(self) -> Session:+ """Get a database session"""+ return self.Session()++ def mark_failure(self, resource_id: int, failure) -> None:+ """+ Mark a resource as failed with classification.++ Args:+ resource_id: Resource identifier+ failure: Classified failure object+ """+ with self._get_session() as session:+ # Get or create status record+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if not status:+ status = ResourceDownloadStatus(resource_id=resource_id)+ session.add(status)++ # Update status information+ if failure.is_permanent():+ status.status = "permanently_failed"+ status.retry_after_timestamp = None+ status.failure_type = failure.error_type+ status.failure_message = failure.message+ status.permanent_failure_at = datetime.now()+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as permanently failed: {failure.error_type}"+ )+ else:+ status.status = "temporarily_failed"+ status.retry_after_timestamp = (+ failure.created_at + failure.retry_after+ )+ status.failure_type = failure.error_type+ status.failure_message = failure.message+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as temporarily failed: {failure.error_type}, retry after: {failure.retry_after}"+ )++ # Update retry statistics+ status.total_retry_count += 1+ status.last_attempt_at = datetime.now()++ # Check if retry is today+ today = datetime.now().date()+ last_attempt = (+ status.last_attempt_at.date()+ if status.last_attempt_at+ else None+ )+ if last_attempt == today:+ status.today_retry_count += 1+ else:+ status.today_retry_count = 1++ session.commit()+ logger.debug(+ f"[STATUS_TRACKER] Updated failure status for resource {resource_id}"+ )++ def mark_success(self, resource_id: int) -> None:+ """+ Mark a resource as successfully downloaded.++ Args:+ resource_id: Resource identifier+ """+ with self._get_session() as session:+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if status:+ status.status = "completed"+ status.failure_type = None+ status.failure_message = None+ status.retry_after_timestamp = None+ status.updated_at = datetime.now()+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as successfully completed"+ )++ session.commit()++ def can_retry(self, resource_id: int) -> tuple[bool, Optional[str]]:+ """+ Check if a resource can be retried right now.++ Args:+ resource_id: Resource identifier++ Returns:+ Tuple of (can_retry, reason_if_not)+ """+ with self._get_session() as session:+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if not status:+ # No status record, can retry+ return True, None++ # Check if permanently failed+ if status.status == "permanently_failed":+ return (+ False,+ f"Permanently failed: {status.failure_message or status.failure_type}",+ )++ # Check if temporarily failed and cooldown not expired+ if (+ status.status == "temporarily_failed"+ and status.retry_after_timestamp+ ):+ if datetime.now() < status.retry_after_timestamp:+ remaining = status.retry_after_timestamp - datetime.now()+ return (+ False,+ f"Cooldown active, retry available at {status.retry_after_timestamp.strftime('%Y-%m-%d %H:%M:%S')}",+ )++ # Check daily retry limit (max 3 retries per day)+ if status.today_retry_count >= 3:+ return (+ False,+ f"Daily retry limit exceeded ({status.today_retry_count}/3). Retry available tomorrow.",+ )++ # Can retry+ return True, None++ def get_resource_status(self, resource_id: int) -> Optional[Dict[str, Any]]:+ """+ Get the current status of a resource.++ Args:+ resource_id: Resource identifier++ Returns:+ Status information dictionary or None if not found+ """+ with self._get_session() as session:+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if not status:+ return None++ return {+ "resource_id": status.resource_id,+ "status": status.status,+ "failure_type": status.failure_type,+ "failure_message": status.failure_message,+ "retry_after_timestamp": status.retry_after_timestamp.isoformat()+ if status.retry_after_timestamp+ else None,+ "last_attempt_at": status.last_attempt_at.isoformat()+ if status.last_attempt_at+ else None,+ "total_retry_count": status.total_retry_count,+ "today_retry_count": status.today_retry_count,+ "created_at": status.created_at.isoformat(),+ "updated_at": status.updated_at.isoformat(),+ }++ def get_failed_resources_count(self) -> Dict[str, int]:+ """+ Get counts of resources by failure type.++ Returns:+ Dictionary mapping failure types to counts+ """+ with self._get_session() as session:+ failed_resources = (+ session.query(ResourceDownloadStatus)+ .filter(+ ResourceDownloadStatus.status.in_(+ ["temporarily_failed", "permanently_failed"]+ )+ )+ .all()+ )++ counts = {}+ for resource in failed_resources:+ failure_type = resource.failure_type or "unknown"+ counts[failure_type] = counts.get(failure_type, 0) + 1++ return counts++ def clear_permanent_failures(self, older_than_days: int = 30) -> int:+ """+ Clear permanent failure statuses for old records.++ Args:+ older_than_days: Clear failures older than this many days++ Returns:+ Number of records cleared+ """+ cutoff_date = datetime.now() - timedelta(days=older_than_days)++ with self._get_session() as session:+ old_failures = (+ session.query(ResourceDownloadStatus)+ .filter(+ ResourceDownloadStatus.status == "permanently_failed",+ ResourceDownloadStatus.created_at < cutoff_date,+ )+ .all()+ )++ count = len(old_failures)+ for failure in old_failures:+ failure.status = "available"+ failure.failure_type = None+ failure.failure_message = None+ failure.retry_after_timestamp = None+ failure.permanent_failure_at = None+ failure.total_retry_count = 0+ failure.today_retry_count = 0+ failure.updated_at = datetime.now()++ session.commit()+ logger.info(+ f"[STATUS_TRACKER] Cleared {count} old permanent failure records"+ )+ return countdiff --git a/src/local_deep_research/research_library/download_management/__init__.py b/src/local_deep_research/research_library/download_management/__init__.pynew file mode 100644index 0000000000..9167a27f1e--- /dev/null+++ b/src/local_deep_research/research_library/download_management/__init__.py@@ -0,0 +1,24 @@+"""+Download Management Module++Provides intelligent retry management and failure classification for resource downloads.+Prevents endless retry loops and implements cooldown strategies for different failure types.+"""++from .failure_classifier import (+ BaseFailure,+ PermanentFailure,+ TemporaryFailure,+ RateLimitFailure,+)+from .retry_manager import RetryManager+from .status_tracker import ResourceStatusTracker++__all__ = [+ "BaseFailure",+ "PermanentFailure",+ "TemporaryFailure",+ "RateLimitFailure",+ "RetryManager",+ "ResourceStatusTracker",+]diff --git a/src/local_deep_research/research_library/download_management/failure_classifier.py b/src/local_deep_research/research_library/download_management/failure_classifier.pynew file mode 100644index 0000000000..97c8876128--- /dev/null+++ b/src/local_deep_research/research_library/download_management/failure_classifier.py@@ -0,0 +1,208 @@+"""+Failure Classification System with Inheritance++Provides base classes and specific failure types for download attempts.+Uses inheritance to organize different failure categories and their retry behavior.+"""++from abc import ABC+from datetime import datetime, timedelta+from typing import Optional+from urllib.parse import urlparse++from loguru import logger+++class BaseFailure(ABC):+ """Base class for all failure types with common functionality"""++ def __init__(+ self,+ error_type: str,+ message: str,+ retry_after: Optional[timedelta] = None,+ ):+ """+ Initialize a failure classification.++ Args:+ error_type: Machine-readable error identifier+ message: Human-readable error description+ retry_after: When this failure can be retried (None = permanent)+ """+ self.error_type = error_type+ self.message = message+ self.retry_after = retry_after+ self.created_at = datetime.now()++ logger.debug(+ f"[FAILURE_CLASSIFIER] Created {self.__class__.__name__}: {error_type} - {message}"+ )++ def is_permanent(self) -> bool:+ """Check if this is a permanent failure (never retry)"""+ return self.retry_after is None++ def can_retry_now(self) -> bool:+ """Check if this resource can be retried right now"""+ if self.is_permanent():+ return False+ return datetime.now() >= self.created_at + self.retry_after++ def get_cooldown_remaining(self) -> Optional[timedelta]:+ """Get remaining cooldown time, or None if no cooldown"""+ if self.is_permanent():+ return None++ retry_time = self.created_at + self.retry_after+ if datetime.now() < retry_time:+ return retry_time - datetime.now()+ return None++ def to_dict(self) -> dict:+ """Convert to dictionary for database storage"""+ return {+ "error_type": self.error_type,+ "message": self.message,+ "retry_after_timestamp": self.created_at + self.retry_after+ if self.retry_after+ else None,+ "is_permanent": self.is_permanent(),+ "created_at": self.created_at,+ }+++class PermanentFailure(BaseFailure):+ """Resources that should never be retried"""++ def __init__(self, error_type: str, message: str):+ super().__init__(error_type, message, retry_after=None)+++class TemporaryFailure(BaseFailure):+ """Resources that can be retried after cooldown"""++ def __init__(self, error_type: str, message: str, cooldown: timedelta):+ super().__init__(error_type, message, retry_after=cooldown)+++class RateLimitFailure(TemporaryFailure):+ """Domain-specific rate limit handling with longer cooldowns"""++ def __init__(self, domain: str, details: str = ""):+ # Domain-specific cooldown periods+ domain_cooldowns = {+ "arxiv.org": timedelta(hours=24), # reCAPTCHA issues+ "pubmed.ncbi.nlm.nih.gov": timedelta(hours=2), # PubMed rate limits+ "biorxiv.org": timedelta(hours=6), # BioRxiv rate limits+ "semanticscholar.org": timedelta(+ hours=4+ ), # Semantic Scholar rate limits+ "researchgate.net": timedelta(hours=12), # ResearchGate rate limits+ "default": timedelta(+ hours=1+ ), # Default cooldown for unknown domains+ }++ cooldown = domain_cooldowns.get(domain, domain_cooldowns["default"])+ message = f"Rate limited by {domain}"+ if details:+ message += f" - {details}"++ super().__init__("rate_limited", message, cooldown)+ self.domain = domain+++class FailureClassifier:+ """Classifies download failures into appropriate types based on error patterns"""++ def classify_failure(+ self,+ error_type: str,+ status_code: Optional[int] = None,+ url: str = "",+ details: str = "",+ ) -> BaseFailure:+ """+ Classify a download failure based on error information.++ Args:+ error_type: Error type identifier+ status_code: HTTP status code if available+ url: URL that failed+ details: Additional error details++ Returns:+ Appropriate failure classification+ """+ # HTTP Status Code classifications+ if status_code:+ if status_code == 404:+ return PermanentFailure("not_found", "Resource not found (404)")+ elif status_code == 403:+ return PermanentFailure("forbidden", "Access forbidden (403)")+ elif status_code == 410:+ return PermanentFailure(+ "gone", "Resource permanently removed (410)"+ )+ elif status_code == 429:+ domain = urlparse(url).netloc if url else "unknown"+ return RateLimitFailure(domain, details)+ elif status_code == 503:+ return TemporaryFailure(+ "server_error",+ "Service temporarily unavailable (503)",+ timedelta(hours=1),+ )++ # Error message pattern classifications+ error_lower = error_type.lower()+ details_lower = details.lower()++ # arXiv specific patterns+ if "arxiv" in error_lower or "arxiv" in details_lower:+ if "recaptcha" in details_lower or "captcha" in details_lower:+ return PermanentFailure(+ "no_public_pdf",+ "Anti-bot protection active, no direct PDF access",+ )+ if "not a pdf file" in details_lower:+ return PermanentFailure(+ "incompatible_format", "Content is not a PDF file"+ )+ if (+ "html" in details_lower+ and "application/pdf" not in details_lower+ ):+ return PermanentFailure(+ "incompatible_format",+ "Content returned HTML instead of PDF",+ )++ # Common timeout and network errors+ if "timeout" in error_lower:+ return TemporaryFailure(+ "timeout", "Request timed out", timedelta(minutes=30)+ )+ if "connection" in error_lower or "network" in error_lower:+ return TemporaryFailure(+ "network_error",+ "Network connectivity issue",+ timedelta(minutes=5),+ )++ # Default to temporary failure with 1-hour cooldown+ logger.warning(+ f"[FAILURE_CLASSIFIER] Unclassified error: {error_type} - {details}"+ )+ return TemporaryFailure(+ "unknown_error", f"Unknown error: {error_type}", timedelta(hours=1)+ )++ def classify_from_exception(+ self, exception: Exception, url: str = ""+ ) -> BaseFailure:+ """Classify failure from exception object"""+ error_type = type(exception).__name__+ details = str(exception)+ return self.classify_failure(error_type, details=details, url=url)diff --git a/src/local_deep_research/research_library/download_management/retry_manager.py b/src/local_deep_research/research_library/download_management/retry_manager.pynew file mode 100644index 0000000000..09421d28de--- /dev/null+++ b/src/local_deep_research/research_library/download_management/retry_manager.py@@ -0,0 +1,279 @@+"""+Retry Manager++Core retry logic and cooldown management for download attempts.+Prevents endless retry loops and implements intelligent retry strategies.+"""++from dataclasses import dataclass+from datetime import datetime, timedelta+from typing import List, Optional, Tuple++from loguru import logger++from .failure_classifier import FailureClassifier+from .status_tracker import ResourceStatusTracker+++@dataclass+class RetryDecision:+ """Decision about whether to retry a resource"""++ can_retry: bool+ reason: Optional[str] = None+ estimated_wait_time: Optional[timedelta] = None+++class ResourceFilterResult:+ """Result of filtering a resource"""++ def __init__(+ self,+ resource_id: int,+ can_retry: bool,+ status: str,+ reason: str = "",+ estimated_wait: Optional[timedelta] = None,+ ):+ self.resource_id = resource_id+ self.can_retry = can_retry+ self.status = status+ self.reason = reason+ self.estimated_wait = estimated_wait+++class FilterSummary:+ """Summary of filtering results"""++ def __init__(self):+ self.total_count = 0+ self.downloadable_count = 0+ self.permanently_failed_count = 0+ self.temporarily_failed_count = 0+ self.available_count = 0+ self.failure_type_counts = {}++ def add_result(self, result: ResourceFilterResult):+ """Add a filtering result to the summary"""+ self.total_count += 1++ if result.can_retry:+ self.downloadable_count += 1+ elif result.status == "permanently_failed":+ self.permanently_failed_count += 1+ elif result.status == "temporarily_failed":+ self.temporarily_failed_count += 1+ else:+ self.available_count += 1++ def to_dict(self) -> dict:+ """Convert to dictionary"""+ return {+ "total_count": self.total_count,+ "downloadable_count": self.downloadable_count,+ "permanently_failed_count": self.permanently_failed_count,+ "temporarily_failed_count": self.temporarily_failed_count,+ "available_count": self.available_count,+ "failure_type_counts": self.failure_type_counts,+ }+++class RetryManager:+ """Manage retry logic and prevent endless loops"""++ def __init__(self, username: str, password: Optional[str] = None):+ """+ Initialize the retry manager.++ Args:+ username: Username for database access+ password: Optional password for encrypted database+ """+ self.username = username+ self.failure_classifier = FailureClassifier()+ self.status_tracker = ResourceStatusTracker(username, password)++ logger.info(f"[RETRY_MANAGER] Initialized for user: {username}")++ def should_retry_resource(self, resource_id: int) -> RetryDecision:+ """+ Determine if a resource should be retried based on history.++ Args:+ resource_id: Resource identifier++ Returns:+ RetryDecision with can_retry flag and reasoning+ """+ can_retry, reason = self.status_tracker.can_retry(resource_id)+ return RetryDecision(can_retry=can_retry, reason=reason)++ def record_attempt(+ self,+ resource_id: int,+ result: Tuple[bool, Optional[str]],+ status_code: Optional[int] = None,+ url: str = "",+ details: str = "",+ ) -> None:+ """+ Record a download attempt result.++ Args:+ resource_id: Resource identifier+ result: Tuple of (success, error_message)+ status_code: HTTP status code if available+ url: URL that was attempted+ details: Additional error details+ """+ success, error_message = result++ if success:+ # Successful download+ self.status_tracker.mark_success(resource_id)+ logger.info(+ f"[RETRY_MANAGER] Resource {resource_id} marked as successful"+ )+ else:+ # Failed download - classify the failure+ failure = self.failure_classifier.classify_failure(+ error_type=type(error_message).__name__+ if error_message+ else "unknown",+ status_code=status_code,+ url=url,+ details=details or (error_message or "Unknown error"),+ )++ self.status_tracker.mark_failure(resource_id, failure)+ logger.info(+ f"[RETRY_MANAGER] Resource {resource_id} marked as failed: {failure.error_type}"+ )++ def filter_resources(self, resources: List) -> List[ResourceFilterResult]:+ """+ Filter resources based on their retry eligibility.++ Args:+ resources: List of resources to filter++ Returns:+ List of ResourceFilterResult objects+ """+ results = []++ for resource in resources:+ if not hasattr(resource, "id"):+ # Skip resources without ID+ continue++ can_retry, reason = self.status_tracker.can_retry(resource.id)+ status = self._get_resource_status(can_retry, reason)++ # Get estimated wait time if temporarily failed+ estimated_wait = None+ if not can_retry and reason and "cooldown" in reason.lower():+ try:+ status_info = self.status_tracker.get_resource_status(+ resource.id+ )+ if status_info and status_info["retry_after_timestamp"]:+ retry_time = datetime.fromisoformat(+ status_info["retry_after_timestamp"]+ )+ estimated_wait = retry_time - datetime.now()+ except Exception as e:+ logger.debug(+ f"[RETRY_MANAGER] Error calculating wait time: {e}"+ )++ result = ResourceFilterResult(+ resource_id=resource.id,+ can_retry=can_retry,+ status=status,+ reason=reason or "",+ estimated_wait=estimated_wait,+ )+ results.append(result)++ logger.info(+ f"[RETRY_MANAGER] Filtered {len(results)} resources: "+ f"{sum(1 for r in results if r.can_retry)} downloadable, "+ f"{sum(1 for r in results if r.status == 'permanently_failed')} permanently failed"+ )++ return results++ def get_filter_summary(+ self, results: List[ResourceFilterResult]+ ) -> FilterSummary:+ """+ Generate a summary of filtering results.++ Args:+ results: List of ResourceFilterResult objects++ Returns:+ FilterSummary object with counts+ """+ summary = FilterSummary()+ for result in results:+ summary.add_result(result)+ return summary++ def _get_resource_status(+ self, can_retry: bool, reason: Optional[str]+ ) -> str:+ """Get status string based on retry decision"""+ if not can_retry:+ if reason and "permanently failed" in reason:+ return "permanently_failed"+ elif reason and "cooldown" in reason:+ return "temporarily_failed"+ else:+ return "unavailable"+ return "available"++ def get_retry_statistics(self) -> dict:+ """+ Get retry statistics for monitoring.++ Returns:+ Dictionary with retry statistics+ """+ failure_counts = self.status_tracker.get_failed_resources_count()++ return {+ "total_permanent_failures": sum(+ count for count in failure_counts.values()+ ),+ "total_temporary_failures": sum(+ count for count in failure_counts.values()+ ),+ "failure_type_breakdown": failure_counts,+ }++ def reset_daily_retry_counters(self) -> int:+ """+ Reset daily retry counters (call this at midnight).++ Returns:+ Number of resources that had their daily counter reset+ """+ # This would be called by a daily cron job+ logger.info(+ "[RETRY_MANAGER] Daily retry counter reset would be called here"+ )+ return 0 # Implementation would reset today_retry_count in database++ def clear_old_permanent_failures(self, days: int = 30) -> int:+ """+ Clear old permanent failure records.++ Args:+ days: Clear failures older than this many days++ Returns:+ Number of records cleared+ """+ return self.status_tracker.clear_permanent_failures(days)diff --git a/src/local_deep_research/research_library/download_management/status_tracker.py b/src/local_deep_research/research_library/download_management/status_tracker.pynew file mode 100644index 0000000000..1564093e16--- /dev/null+++ b/src/local_deep_research/research_library/download_management/status_tracker.py@@ -0,0 +1,317 @@+"""+Resource Status Tracker++Tracks download attempts, failures, and cooldowns in the database.+Provides persistent storage for failure classifications and retry eligibility.+"""++from datetime import datetime, timedelta+from typing import Optional, Dict, Any++from loguru import logger+from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime+from sqlalchemy.ext.declarative import declarative_base+from sqlalchemy.orm import sessionmaker, Session++from .failure_classifier import BaseFailure++Base = declarative_base()+++class ResourceDownloadStatus(Base):+ """Database model for tracking resource download status"""++ __tablename__ = "resource_download_status"++ id = Column(Integer, primary_key=True)+ resource_id = Column(Integer, unique=True, nullable=False, index=True)++ # Status tracking+ status = Column(+ String(50), nullable=False, default="available"+ ) # available, temporarily_failed, permanently_failed+ failure_type = Column(String(100)) # not_found, rate_limited, timeout, etc.+ failure_message = Column(Text)++ # Retry timing+ retry_after_timestamp = Column(+ DateTime+ ) # When this can be retried (NULL = permanent)+ last_attempt_at = Column(DateTime)++ # Statistics+ total_retry_count = Column(Integer, default=0)+ today_retry_count = Column(Integer, default=0)++ # Timestamps+ created_at = Column(DateTime, default=datetime.now)+ updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)++ def __repr__(self):+ return f"<ResourceDownloadStatus(resource_id={self.resource_id}, status='{self.status}', failure_type='{self.failure_type}')>"+++class ResourceStatusTracker:+ """Track download attempts, failures, and cooldowns in database"""++ def __init__(self, username: str, password: Optional[str] = None):+ """+ Initialize the status tracker for a user.++ Args:+ username: Username for database access+ password: Optional password for encrypted database+ """+ self.username = username+ self.password = password++ # Initialize database session+ self.engine = create_engine("sqlite:///data/research_library.db")+ self.Session = sessionmaker(bind=self.engine)++ # Create tables if they don't exist+ Base.metadata.create_all(self.engine)+ logger.info(f"[STATUS_TRACKER] Initialized for user: {username}")++ def _get_session(self) -> Session:+ """Get a database session"""+ return self.Session()++ def mark_failure(self, resource_id: int, failure: BaseFailure) -> None:+ """+ Mark a resource as failed with classification.++ Args:+ resource_id: Resource identifier+ failure: Classified failure object+ """+ with self._get_session() as session:+ # Get or create status record+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if not status:+ status = ResourceDownloadStatus(resource_id=resource_id)+ session.add(status)++ # Update status information+ if failure.is_permanent():+ status.status = "permanently_failed"+ status.retry_after_timestamp = None+ status.failure_type = failure.error_type+ status.failure_message = failure.message+ status.permanent_failure_at = datetime.now()+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as permanently failed: {failure.error_type}"+ )+ else:+ status.status = "temporarily_failed"+ status.retry_after_timestamp = (+ failure.created_at + failure.retry_after+ )+ status.failure_type = failure.error_type+ status.failure_message = failure.message+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as temporarily failed: {failure.error_type}, retry after: {failure.retry_after}"+ )++ # Update retry statistics+ status.total_retry_count += 1+ status.last_attempt_at = datetime.now()++ # Check if retry is today+ today = datetime.now().date()+ last_attempt = (+ status.last_attempt_at.date()+ if status.last_attempt_at+ else None+ )+ if last_attempt == today:+ status.today_retry_count += 1+ else:+ status.today_retry_count = 1++ session.commit()+ logger.debug(+ f"[STATUS_TRACKER] Updated failure status for resource {resource_id}"+ )++ def mark_success(self, resource_id: int) -> None:+ """+ Mark a resource as successfully downloaded.++ Args:+ resource_id: Resource identifier+ """+ with self._get_session() as session:+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if status:+ status.status = "completed"+ status.failure_type = None+ status.failure_message = None+ status.retry_after_timestamp = None+ status.updated_at = datetime.now()+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as successfully completed"+ )++ session.commit()++ def can_retry(self, resource_id: int) -> tuple[bool, Optional[str]]:+ """+ Check if a resource can be retried right now.++ Args:+ resource_id: Resource identifier++ Returns:+ Tuple of (can_retry, reason_if_not)+ """+ with self._get_session() as session:+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if not status:+ # No status record, can retry+ return True, None++ # Check if permanently failed+ if status.status == "permanently_failed":+ return (+ False,+ f"Permanently failed: {status.failure_message or status.failure_type}",+ )++ # Check if temporarily failed and cooldown not expired+ if (+ status.status == "temporarily_failed"+ and status.retry_after_timestamp+ ):+ if datetime.now() < status.retry_after_timestamp:+ remaining = status.retry_after_timestamp - datetime.now()+ return (+ False,+ f"Cooldown active, retry available at {status.retry_after_timestamp.strftime('%Y-%m-%d %H:%M:%S')}",+ )++ # Check daily retry limit (max 3 retries per day)+ if status.today_retry_count >= 3:+ return (+ False,+ f"Daily retry limit exceeded ({status.today_retry_count}/3). Retry available tomorrow.",+ )++ # Can retry+ return True, None++ def get_resource_status(self, resource_id: int) -> Optional[Dict[str, Any]]:+ """+ Get the current status of a resource.++ Args:+ resource_id: Resource identifier++ Returns:+ Status information dictionary or None if not found+ """+ with self._get_session() as session:+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if not status:+ return None++ return {+ "resource_id": status.resource_id,+ "status": status.status,+ "failure_type": status.failure_type,+ "failure_message": status.failure_message,+ "retry_after_timestamp": status.retry_after_timestamp.isoformat()+ if status.retry_after_timestamp+ else None,+ "last_attempt_at": status.last_attempt_at.isoformat()+ if status.last_attempt_at+ else None,+ "total_retry_count": status.total_retry_count,+ "today_retry_count": status.today_retry_count,+ "created_at": status.created_at.isoformat(),+ "updated_at": status.updated_at.isoformat(),+ }++ def get_failed_resources_count(self) -> Dict[str, int]:+ """+ Get counts of resources by failure type.++ Returns:+ Dictionary mapping failure types to counts+ """+ with self._get_session() as session:+ failed_resources = (+ session.query(ResourceDownloadStatus)+ .filter(+ ResourceDownloadStatus.status.in_(+ ["temporarily_failed", "permanently_failed"]+ )+ )+ .all()+ )++ counts = {}+ for resource in failed_resources:+ failure_type = resource.failure_type or "unknown"+ counts[failure_type] = counts.get(failure_type, 0) + 1++ return counts++ def clear_permanent_failures(self, older_than_days: int = 30) -> int:+ """+ Clear permanent failure statuses for old records.++ Args:+ older_than_days: Clear failures older than this many days++ Returns:+ Number of records cleared+ """+ cutoff_date = datetime.now() - timedelta(days=older_than_days)++ with self._get_session() as session:+ old_failures = (+ session.query(ResourceDownloadStatus)+ .filter(+ ResourceDownloadStatus.status == "permanently_failed",+ ResourceDownloadStatus.created_at < cutoff_date,+ )+ .all()+ )++ count = len(old_failures)+ for failure in old_failures:+ failure.status = "available"+ failure.failure_type = None+ failure.failure_message = None+ failure.retry_after_timestamp = None+ failure.permanent_failure_at = None+ failure.total_retry_count = 0+ failure.today_retry_count = 0+ failure.updated_at = datetime.now()++ session.commit()+ logger.info(+ f"[STATUS_TRACKER] Cleared {count} old permanent failure records"+ )+ return countdiff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex 550506a6c7..2b78b4e23b 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -26,6 +26,7 @@ from ...web.utils.templates import render_template_with_defaultsfrom ...database.session_context import get_user_db_sessionfrom ...database.models.research import ResearchResourcefrom ...database.models.library import LibraryDocument, LibraryDownloadQueue+from ...library.download_management import ResourceFilterfrom ..services.download_service import DownloadServicefrom ..services.library_service import LibraryServicefrom ..utils import open_file_location@@ -626,7 +627,7 @@ def download_bulk():def generate():"""Generate progress updates as Server-Sent Events."""- download_service = DownloadService(username)+ download_service = DownloadService(username, user_password)library_service = LibraryService(username)total = 0@@ -635,12 +636,27 @@ def download_bulk():# Calculate total downloadable itemsfor research_id in research_ids:research_data = library_service.get_research_list_with_stats()+ logger.debug(+ f"[PROGRESS_DEBUG] Research {research_id}: got {len(research_data)} research items"+ )for r in research_data:if r["id"] == research_id:- total += r.get("downloadable_count", 0) - r.get(- "downloaded_count", 0+ downloadable = r.get("downloadable_count", 0) or 0+ downloaded = r.get("downloaded_count", 0) or 0+ old_total = total+ total += downloadable - downloaded+ logger.debug(+ f"[PROGRESS_DEBUG] Research {research_id}: downloadable={downloadable}, downloaded={downloaded}, total changed from {old_total} to {total}")+ # Ensure total is not negative+ logger.debug(+ f"[PROGRESS_DEBUG] Final total before max(0): {total} (type: {type(total)})"+ )+ total = max(0, total)+ logger.info(+ f"[PROGRESS_DEBUG] Final total after processing all research: {total}"+ )yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': total})}\n\n"# Process each research@@ -681,10 +697,27 @@ def download_bulk():# Process each queued itemfor queue_item in queue_items:+ logger.debug(+ f"[PROGRESS_DEBUG] Before increment: current={current} (type: {type(current)}), total={total} (type: {type(total)})"+ )current += 1+ logger.debug(+ f"[PROGRESS_DEBUG] After increment: current={current} (type: {type(current)})"+ )++ # Check for division issues+ if total is None:+ logger.error(+ "[PROGRESS_DEBUG] ERROR: total is None! Setting to 0 to avoid crash"+ )+ total = 0+progress = (int((current / total) * 100) if total > 0 else 100)+ logger.debug(+ f"[PROGRESS_DEBUG] Calculated progress: {progress}%"+ )# Get resource inforesource = session.query(ResearchResource).get(@@ -859,11 +892,76 @@ def queue_all_undownloaded():logger.info(f"Found {len(undownloaded)} total undownloaded resources")+ # Get user password from session password store for encrypted database access+ from ...database.session_passwords import session_password_store++ try:+ user_password = session_password_store.get_session_password(+ username, session.get("_id")+ )+ logger.info(+ f"[LIBRARY_ROUTES] Retrieved user password from session store: {'***' if user_password else 'None'} for user {username}"+ )+ except Exception as e:+ logger.error(f"[LIBRARY_ROUTES] Failed to get user password: {e}")+ user_password = None++ # Fallback to g.user_password (set by middleware if temp_auth was used)+ if not user_password:+ user_password = getattr(g, "user_password", None)+ logger.info(+ f"[LIBRARY_ROUTES] Retrieved user password from g.user_password fallback: {'***' if user_password else 'None'} for user {username}"+ )++ # Use smart filtering to decide which resources should be retried+ if user_password is None:+ logger.error(+ f"[LIBRARY_ROUTES] Cannot proceed with downloads: no password available for user {username}"+ )+ return (+ jsonify(+ {+ "status": "error",+ "message": "Authentication required: Please refresh the page and log in again to access encrypted database features.",+ }+ ),+ 401,+ )++ resource_filter = ResourceFilter(username, user_password)+ filter_results = resource_filter.filter_downloadable_resources(+ undownloaded+ )++ # Get detailed filtering summary+ filter_summary = resource_filter.get_filter_summary(undownloaded)+ skipped_info = resource_filter.get_skipped_resources_info(undownloaded)++ logger.info(f"Filter results: {filter_summary.to_dict()}")+queued_count = 0research_ids = set()skipped_count = 0for resource in undownloaded:+ # Check if resource passed the smart filter+ filter_result = next(+ (r for r in filter_results if r.resource_id == resource.id),+ None,+ )++ if not filter_result or not filter_result.can_retry:+ skipped_count += 1+ if filter_result:+ logger.debug(+ f"Skipping resource {resource.id} due to retry policy: {filter_result.reason}"+ )+ else:+ logger.debug(+ f"Skipping resource {resource.id} - no filter result available"+ )+ continue+# Check if it's downloadable using proper URL parsingif not resource.url:skipped_count += 1@@ -924,7 +1022,7 @@ def queue_all_undownloaded():db_session.commit()logger.info(- f"Queued {queued_count} articles for download, skipped {skipped_count} non-downloadable URLs"+ f"Queued {queued_count} articles for download, skipped {skipped_count} resources (including {filter_summary.permanently_failed_count} permanently failed and {filter_summary.temporarily_failed_count} temporarily failed)")return jsonify(@@ -934,6 +1032,8 @@ def queue_all_undownloaded():"research_ids": list(research_ids),"total_undownloaded": len(undownloaded),"skipped": skipped_count,+ "filter_summary": filter_summary.to_dict(),+ "skipped_details": skipped_info,})diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 90894bf536..2b38237902 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -36,6 +36,7 @@ from ...database.models.research import ResearchResourcefrom ...database.session_context import get_user_db_sessionfrom ...utilities.db_utils import get_settings_managerfrom ...security.path_validator import PathValidator+from ...library.download_management import RetryManagerfrom ..utils import (get_url_hash,get_absolute_path_from_settings,@@ -64,7 +65,7 @@ class DownloadService:"""self.username = usernameself.password = password- self.settings = get_settings_manager()+ self.settings = get_settings_manager(user_id=username)# Debug settings manager and user contextlogger.info(@@ -104,6 +105,12 @@ class DownloadService:GenericDownloader(timeout=30), # Generic should be last (fallback)]+ # Initialize retry manager for smart failure tracking+ self.retry_manager = RetryManager(username, password)+ logger.info(+ f"[DOWNLOAD_SERVICE] Initialized retry manager for user: {username}"+ )+def _setup_directories(self):"""Create library directory structure."""# Only create the root and pdfs folder - flat structure@@ -359,6 +366,17 @@ class DownloadService:if last_attempt and hasattr(last_attempt, "error_message"):skip_reason = last_attempt.error_message+ # Record attempt with retry manager for smart failure tracking+ self.retry_manager.record_attempt(+ resource_id=resource.id,+ result=(success, skip_reason),+ url=resource.url,+ details=skip_reason+ or (+ "Successfully downloaded" if success else "Download failed"+ ),+ )+# Update queue status if existsqueue_entry = (session.query(LibraryDownloadQueue)@@ -945,10 +963,35 @@ class DownloadService:# Verify it's a PDFcontent_type = response.headers.get("Content-Type", "")+ logger.debug(+ f"[TEXT_EXTRACTION] Response content type: {content_type}"+ )+ logger.debug(+ f"[TEXT_EXTRACTION] Response headers: {dict(response.headers)}"+ )+ logger.debug(+ f"[TEXT_EXTRACTION] Response status: {response.status_code}"+ )+ logger.debug(f"[TEXT_EXTRACTION] Response URL: {response.url}")+if not content_type.startswith("application/pdf"):logger.warning(- f"[TEXT_EXTRACTION] URL didn't return PDF content: {content_type}"+ f"[TEXT_EXTRACTION] URL didn't return PDF content: {content_type}, status: {response.status_code}, final URL: {response.url}")+ # Check if we got redirected to an HTML page+ if "text/html" in content_type:+ logger.warning(+ "[TEXT_EXTRACTION] Got HTML instead of PDF - likely arXiv abstract page"+ )+ # Log first few characters of content for debugging+ content_preview = (+ response.text[:200]+ if hasattr(response, "text")+ else str(response.content[:200])+ )+ logger.debug(+ f"[TEXT_EXTRACTION] Content preview: {content_preview}"+ )raise Exception("Not a PDF file")# Extract text from PDF in memorydiff --git a/src/local_deep_research/security/file_write_verifier.py b/src/local_deep_research/security/file_write_verifier.pyindex 5d16c19477..5db32f1b51 100644--- a/src/local_deep_research/security/file_write_verifier.py+++ b/src/local_deep_research/security/file_write_verifier.py@@ -71,12 +71,21 @@ def write_file_verified()if settings_manager:- actual_value = settings_manager.get_setting(setting_name, None)- logger.warning(- f"[SECURITY_CHECK] Setting '{setting_name}': retrieved_value={actual_value}, required_value={required_value}"- )+ try:+ actual_value = settings_manager.get_setting(setting_name, None)+ logger.warning(+ f"[SECURITY_CHECK] Setting '{setting_name}': retrieved_value={actual_value} (type: {type(actual_value)}), required_value={required_value} (type: {type(required_value)})"+ )+ except Exception as e:+ logger.warning(+ f"[SECURITY_CHECK] Exception getting setting '{setting_name}': {e}"+ )+ actual_value = Noneelse:actual_value = None+ logger.warning(+ f"[SECURITY_CHECK] No settings manager available for '{setting_name}', actual_value set to None"+ )if actual_value != required_value:logger.warning(