OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

Task JSON files accumulate on disk indefinitely - _evict_expired() only cleans memory cache, never calls store.delete()

Open livechenjt-prog opened this issue 3 months ago • 1 comments

Summary

TaskTracker._evict_expired() evicts expired tasks from the in-memory cache (self._tasks dict) but never calls self._store.delete() to remove the corresponding JSON files from disk. Over time, task JSON files accumulate indefinitely with no cleanup mechanism, causing disk bloat, inode exhaustion, and indirect memory pressure (kernel dentry/inode cache + AGFS metadata).

Environment

  • OpenViking server v0.4.12, single-node deployment
  • Linux (Alibaba Cloud), 1.8 GB RAM
  • AGFS local backend, LevelDB vector backend
  • Embedding/VLM/Rerank: remote API (no local model memory)

Root Cause

In openviking/service/task_tracker.py, the _evict_expired() method (around L256-277):

async def _evict_expired(self) -> None:
    """Remove expired tasks and enforce MAX_TASKS."""
    now = time.time()
    async with self._async_lock:
        with self._lock:
            expired_ids = []
            for tid, t in self._tasks.items():
                if t.status in (TaskStatus.COMPLETED, TaskStatus.CANCELLED) and (
                    now - t.updated_at
                ) > self.TTL_COMPLETED:
                    expired_ids.append(tid)
                elif t.status == TaskStatus.FAILED and (now - t.updated_at) > self.TTL_FAILED:
                    expired_ids.append(tid)

            for tid in expired_ids:
                self._tasks.pop(tid, None)  # ← Only removes from memory dict

            if len(self._tasks) > self.MAX_TASKS:
                sorted_tasks = sorted(self._tasks.items(), key=lambda x: x[1].created_at)
                excess = len(self._tasks) - self.MAX_TASKS
                for tid, _ in sorted_tasks[:excess]:
                    self._tasks.pop(tid, None)  # ← Same: memory only

PersistentTaskStore (in task_store.py) does have a delete() method:

async def delete(self, task_id: str, *, account_id: str, user_id: Optional[str] = None) -> None:
    if not user_id:
        return
    await self._agfs.rm(self._task_path(account_id, user_id, task_id), force=True)

But _evict_expired() never calls it. The task API also has no DELETE endpoint — only GET /tasks/{id}, POST /tasks/{id}/cancel, and GET /tasks.

Impact

On our production deployment over 47 days:

Metric Value
Total task JSON files on disk 136,271 (543 MB)
Status breakdown completed: 131,928 / running (zombie): 4,257 / failed: 86
Files older than 7 days 131,275
Daily growth rate ~2,900 files/day
openviking-server RSS 973 MB (50% of 1.8 GB RAM)
Swap usage 1.0 GB / 2.0 GB (50%)

The 4,257 "running" tasks are zombies — they were in progress when the server restarted and will never transition to a terminal state, so they're never evicted even from the in-memory cache (the TTL check only covers COMPLETED/CANCELLED/FAILED).

Memory pressure chain:

  1. Kernel dentry/inode cache — 136K files consume significant slab memory
  2. AGFS metadata — RAGFS in-process binding maintains filesystem metadata for all files
  3. PersistentTaskStore.list() — iterates all JSON files in the directory, reads and json.loads() each one. Any API call to GET /tasks with specific filters triggers a full directory scan

Suggested Fix

1. Call store.delete() in _evict_expired():

for tid in expired_ids:
    task = self._tasks.pop(tid, None)
    if task and self._store:
        try:
            await self._store.delete(
                tid,
                account_id=task.account_id,
                user_id=task.user_id,
            )
        except Exception:
            logger.warning("[TaskTracker] Failed to delete task file %s", tid)

2. Handle zombie "running" tasks

Tasks stuck in PENDING/RUNNING/CANCELLING that haven't been updated for longer than TTL_FAILED (7 days) should also be evicted and their disk files removed. These are tasks orphaned by server restarts.

# Add to _evict_expired():
elif t.status in _ACTIVE_STATUSES and (now - t.updated_at) > self.TTL_FAILED:
    expired_ids.append(tid)

3. Optional: configurable retention

Add a task.retention_days config option in ov.conf so operators can tune the cleanup window.

Workaround

Until this is fixed, operators can manually clean old task files. The following Python script safely removes terminal tasks older than 7 days:

import json, os, time

task_dir = '/path/to/data/viking/default/_system/tasks/hermes/'
cutoff = time.time() - 7 * 86400

for fname in os.listdir(task_dir):
    if not fname.endswith('.json'):
        continue
    fpath = os.path.join(task_dir, fname)
    with open(fpath) as fh:
        d = json.load(fh)
    if d.get('updated_at', 0) < cutoff and d.get('status') in ('completed', 'failed', 'cancelled', 'running', 'pending'):
        os.remove(fpath)

OV's PersistentTaskStore.get() handles missing files gracefully (AGFSNotFoundError → returns None), so deletion is safe.

Additional Context

  • No existing issue or PR addresses this (searched task cleanup disk files in the repo)
  • The FAQ's "Performance issues" section does not mention task file cleanup
  • No ov.conf configuration option exists for task retention
  • The ov CLI has no task purge or task cleanup subcommand

livechenjt-prog avatar Aug 09 '26 07:08 livechenjt-prog

I’d like to work on this with a narrowly scoped fix. I’ll delete persisted records for TTL-expired terminal tasks under the existing per-task lock, and remove the cache entry only after the store deletion succeeds so failures can retry on the next cleanup cycle. The MAX_TASKS path will remain cache-only to avoid deleting active tasks, and zombie-task/configurable-retention behavior will stay out of scope. I’ll add regression coverage for both successful persistent cleanup and deletion failure.

AaronZ345 avatar Aug 10 '26 05:08 AaronZ345