Files
DeepTutor/deeptutor/api/utils/task_id_manager.py
Antonio-Faure 63ef9b7c2c chore: remove dead Python modules and helpers (#2253)
* chore: remove dead Python modules and helpers

Delete unreferenced P0 code identified by the dead-code audit:
- services/llm/registry.py and its test-only coverage
- logging/adapters package (LlamaIndex log forwarding)
- textbook_struct.chapter_rebuild.detect_frames
- load_config_with_main_async and its async file helper
- memory.trace.iter_by_ids / latest_ts
- TokenTracker.format_summary
- WeixinChannel._api_get
- ArxivSearchTool.extract_arxiv_id_from_url
- FileLibraryStore migration scaffolding (_run_migrations et al.)
- eight small dead helpers in services, api/utils, and knowledge
- redundant runtime C2CMessage import in the QQ channel

* chore: drop the prompt-language shim and a dead storage helper

The book agents were the last in-tree users of blocks/_language.py, which
only re-exported services.prompt.language. Import the real module and
delete the shim. storage._storage_path_from_version_entry had no caller.

Verified: ruff F401/F811/F841/F821 on changed files; py_compile.

---------

Co-authored-by: Antonio-Faure <209759495+Antonio-Faure@users.noreply.github.com>
2026-12-02 10:50:16 +08:00

116 lines
4.3 KiB
Python

"""
Task ID Manager - Assigns unique IDs to each background task
"""
from datetime import datetime, timedelta
import logging
import threading
from typing import Optional
import uuid
logger = logging.getLogger(__name__)
class TaskIDManager:
"""Singleton class for managing task IDs"""
_MAX_COMPLETED_TASKS = 256
_instance: Optional["TaskIDManager"] = None
_lock = threading.Lock()
_task_ids: dict[str, str] = {} # task_key -> task_id
_task_metadata: dict[str, dict] = {} # task_id -> metadata
@classmethod
def get_instance(cls) -> "TaskIDManager":
"""Get singleton instance"""
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = cls()
return cls._instance
def generate_task_id(self, task_type: str, task_key: str) -> str:
"""
Generate unique ID for task
Args:
task_type: Task type (e.g., 'kb_init', 'kb_upload', 'question_gen', 'solve', 'research')
task_key: Task unique identifier (e.g., knowledge base name, question ID, etc.)
Returns:
Task ID (format: {task_type}_{timestamp}_{uuid})
"""
self.cleanup_old_tasks()
with self._lock:
# If task already exists, return existing ID
if task_key in self._task_ids:
return self._task_ids[task_key]
# Generate new ID
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
unique_id = str(uuid.uuid4())[:8]
task_id = f"{task_type}_{timestamp}_{unique_id}"
# Save mapping and metadata
self._task_ids[task_key] = task_id
self._task_metadata[task_id] = {
"task_type": task_type,
"task_key": task_key,
"created_at": datetime.now().isoformat(),
"status": "running",
}
return task_id
def update_task_status(self, task_id: str, status: str, **kwargs):
"""Update task status"""
with self._lock:
if task_id in self._task_metadata:
self._task_metadata[task_id]["status"] = status
self._task_metadata[task_id].update(kwargs)
if status in ["completed", "error", "cancelled"]:
self._task_metadata[task_id]["finished_at"] = datetime.now().isoformat()
def get_task_metadata(self, task_id: str) -> dict | None:
"""Get task metadata"""
with self._lock:
return self._task_metadata.get(task_id, {}).copy()
def cleanup_old_tasks(self, max_age_hours: int = 24):
"""Clean up old tasks (completed tasks older than specified hours)"""
with self._lock:
cutoff = datetime.now() - timedelta(hours=max_age_hours)
to_remove = []
for task_id, metadata in self._task_metadata.items():
if metadata.get("status") in ["completed", "error", "cancelled"]:
finished_at = metadata.get("finished_at")
if finished_at:
try:
finished_time = datetime.fromisoformat(finished_at)
if finished_time < cutoff:
to_remove.append(task_id)
except Exception:
logger.warning("Failed to parse finished_at for task %s", task_id)
for task_id in to_remove:
metadata = self._task_metadata.pop(task_id, {})
task_key = metadata.get("task_key")
if task_key:
self._task_ids.pop(task_key, None)
completed = sorted(
(
(str(metadata.get("finished_at") or ""), task_id)
for task_id, metadata in self._task_metadata.items()
if metadata.get("status") in ["completed", "error", "cancelled"]
)
)
overflow = len(completed) - self._MAX_COMPLETED_TASKS
for _, task_id in completed[: max(0, overflow)]:
metadata = self._task_metadata.pop(task_id, {})
task_key = metadata.get("task_key")
if task_key:
self._task_ids.pop(task_key, None)