Skip to content

~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.

fix: remove duplicate download_management and fix critical bugs

LearningCircuit74225bd7afe8
diff --git a/src/local_deep_research/library/download_management/status_tracker.py b/src/local_deep_research/library/download_management/status_tracker.py
index 2f7f42704e..0cf1cf72da 100644
--- a/src/local_deep_research/library/download_management/status_tracker.py
+++ b/src/local_deep_research/library/download_management/status_tracker.py
@@ -87,6 +87,9 @@ class ResourceStatusTracker:
)
# Update retry statistics
+ # Ensure total_retry_count is initialized (handle None from legacy data)
+ if status.total_retry_count is None:
+ status.total_retry_count = 0
status.total_retry_count += 1
status.last_attempt_at = datetime.now(UTC)
@@ -98,6 +101,9 @@ class ResourceStatusTracker:
else None
)
if last_attempt == today:
+ # Ensure today_retry_count is initialized (handle None from legacy data)
+ if status.today_retry_count is None:
+ status.today_retry_count = 0
status.today_retry_count += 1
else:
status.today_retry_count = 1
@@ -166,10 +172,16 @@ class ResourceStatusTracker:
status.status == "temporarily_failed"
and status.retry_after_timestamp
):
- if datetime.now(UTC) < status.retry_after_timestamp:
+ # Ensure retry_after_timestamp is timezone-aware (handle legacy data)
+ retry_timestamp = status.retry_after_timestamp
+ if retry_timestamp.tzinfo is None:
+ # Assume UTC for naive timestamps
+ retry_timestamp = retry_timestamp.replace(tzinfo=UTC)
+
+ if datetime.now(UTC) < retry_timestamp:
return (
False,
- f"Cooldown active, retry available at {status.retry_after_timestamp.strftime('%Y-%m-%d %H:%M:%S')}",
+ f"Cooldown active, retry available at {retry_timestamp.strftime('%Y-%m-%d %H:%M:%S')}",
)
# Check daily retry limit (max 3 retries per day)
diff --git a/src/local_deep_research/research_library/download_management/__init__.py b/src/local_deep_research/research_library/download_management/__init__.py
deleted file mode 100644
index 9167a27f1e..0000000000
--- a/src/local_deep_research/research_library/download_management/__init__.py
+++ /dev/null
@@ -1,24 +0,0 @@
-"""
-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.py
deleted file mode 100644
index acd5db3132..0000000000
--- a/src/local_deep_research/research_library/download_management/failure_classifier.py
+++ /dev/null
@@ -1,208 +0,0 @@
-"""
-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, UTC
-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(UTC)
-
- 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(UTC) >= 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(UTC) < retry_time:
- return retry_time - datetime.now(UTC)
- 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/models/__init__.py b/src/local_deep_research/research_library/download_management/models/__init__.py
deleted file mode 100644
index 1640926436..0000000000
--- a/src/local_deep_research/research_library/download_management/models/__init__.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""
-Database Models for Download Management
-
-Contains ORM models for tracking resource download status and retry logic.
-"""
-
-from datetime import datetime, UTC
-from functools import partial
-from sqlalchemy import Column, Integer, String, Text, DateTime
-from sqlalchemy.ext.declarative import declarative_base
-
-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=partial(datetime.now, UTC))
- updated_at = Column(
- DateTime,
- default=partial(datetime.now, UTC),
- onupdate=partial(datetime.now, UTC),
- )
-
- def __repr__(self):
- return f"<ResourceDownloadStatus(resource_id={self.resource_id}, status='{self.status}', failure_type='{self.failure_type}')>"
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.py
deleted file mode 100644
index 9bb790a728..0000000000
--- a/src/local_deep_research/research_library/download_management/retry_manager.py
+++ /dev/null
@@ -1,279 +0,0 @@
-"""
-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, UTC
-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(UTC)
- 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.py
deleted file mode 100644
index 45826138a1..0000000000
--- a/src/local_deep_research/research_library/download_management/status_tracker.py
+++ /dev/null
@@ -1,281 +0,0 @@
-"""
-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, UTC
-from typing import Optional, Dict, Any
-
-from loguru import logger
-from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker, Session
-
-from .failure_classifier import BaseFailure
-from .models import ResourceDownloadStatus, Base
-
-
-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(UTC)
- 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(UTC)
-
- # Check if retry is today
- today = datetime.now(UTC).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(UTC)
- 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(UTC) < status.retry_after_timestamp:
- 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(UTC) - 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(UTC)
-
- session.commit()
- logger.info(
- f"[STATUS_TRACKER] Cleared {count} old permanent failure records"
- )
- return count
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index 7bf60901d3..8ef82a162a 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -659,34 +659,28 @@ def download_bulk():
return
download_service = DownloadService(username, user_password)
- library_service = LibraryService(username)
+ # Count total pending queue items across all research IDs
total = 0
current = 0
- # Calculate total downloadable items
- for 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:
- 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}"
- )
+ from ...database.session_context import get_user_db_session
+ from ...database.models.library import LibraryDownloadQueue
+
+ with get_user_db_session(username) as session:
+ for research_id in research_ids:
+ count = (
+ session.query(LibraryDownloadQueue)
+ .filter_by(research_id=research_id, status="pending")
+ .count()
+ )
+ total += count
+ logger.debug(
+ f"[PROGRESS_DEBUG] Research {research_id}: {count} pending items in queue"
+ )
- # 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}"
+ f"[PROGRESS_DEBUG] Total pending downloads across all research: {total}"
)
yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': total})}\n\n"
@@ -1058,64 +1052,8 @@ def queue_all_undownloaded():
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)"
)
- # Start processing the queued downloads immediately using the existing session
- if queued_count > 0:
- logger.info(
- f"Starting immediate processing of {queued_count} queued downloads"
- )
- try:
- download_service = DownloadService(username, user_password)
-
- # Get all queued items for this user using the existing session
- queue_items = (
- db_session.query(LibraryDownloadQueue)
- .filter_by(status="pending")
- .order_by(LibraryDownloadQueue.id)
- .limit(queued_count) # Process just what we queued
- .all()
- )
-
- logger.info(
- f"Found {len(queue_items)} queue items to process immediately"
- )
-
- # Process each queued item
- for queue_item in queue_items:
- try:
- logger.info(
- f"Processing download for resource {queue_item.resource_id}"
- )
- success, error_msg = download_service.download_resource(
- queue_item.resource_id
- )
-
- if success:
- logger.info(
- f"Successfully downloaded resource {queue_item.resource_id}"
- )
- queue_item.status = "completed"
- else:
- logger.error(
- f"Failed to download resource {queue_item.resource_id}: {error_msg}"
- )
- queue_item.status = "failed"
- queue_item.error_message = error_msg
-
- except Exception as e:
- logger.exception(
- f"Exception processing resource {queue_item.resource_id}: {e}"
- )
- queue_item.status = "failed"
- queue_item.error_message = str(e)
-
- db_session.commit()
- logger.info(
- f"Completed processing of {len(queue_items)} downloads"
- )
-
- except Exception:
- logger.exception("Failed to process queued downloads")
- # Don't fail the whole request, just log the error
+ # Note: Removed synchronous download processing here to avoid blocking the HTTP request
+ # Downloads will be processed via the SSE streaming endpoint or background tasks
return jsonify(
{