Skip to content

bug: Cleanup service misses no-session running executions and doesn't terminal-state skipped executions #137

Closed

Description

@vybe

Summary

The cleanup service fails to clean up two categories of orphaned executions: (1) running executions with no claude_session_id that should be caught by the 60-second no-session check, and (2) skipped executions that are never moved to a terminal state. This causes stale records to accumulate in the database and hold agent capacity slots in Redis, requiring manual cleanup.

Component

Backend / Cleanup Service

Priority

P2

Evidence

Cleanup service status at 02:03 UTC reported all zeros:

{
  "last_run_at": "2026-03-16T02:03:12.349715Z",
  "last_report": {
    "stale_executions": 0,
    "no_session_executions": 0,
    "orphaned_skipped": 0,
    "stale_activities": 0,
    "stale_slots": 0,
    "total": 0
  }
}

Yet these executions were present in the database at that time:

cornelius-m      running    started=2026-03-16T01:59:00  (no session)
oracle-7-ai-semi running    started=2026-03-16T02:00:00  (no session)
oracle-2         running    started=2026-03-16T02:00:00  (no session)
oracle-2         skipped    started=2026-03-15T18:00:00  (no session)

The cornelius-m execution was 4+ minutes old with no session at the 02:03 cleanup cycle — well past the 60-second no-session threshold. All three running executions should have been caught.

The previous cycle at 02:00:54 caught 1 stale activity but 0 no-session executions, even though cornelius-m (started 01:59:00) was ~114 seconds old with no session at that point.

Each stuck execution also held a Redis capacity slot (agent:slots:{name}), preventing the agent from using its full parallel capacity.

Location

  • File: src/backend/db/schedules.py
  • Lines: ~1015-1058 (no-session check), ~1060-1082 (skipped check)
  • File: src/backend/services/cleanup_service.py

Root Cause

Issue 1: No-session check not matching rows

The no-session query uses:

WHERE status = 'running'
AND claude_session_id IS NULL
AND started_at < datetime('now', '-60 seconds')

Possible causes for the miss:

  • Timezone mismatch: If started_at values are stored in a different timezone than SQLite's datetime('now') returns, the comparison will be wrong. Python's datetime.utcnow() vs SQLite's datetime('now') (which returns UTC) should match, but if execution records are written with local time or an offset, the 60-second window could be ineffective.
  • claude_session_id is empty string vs NULL: If the field is set to "" instead of NULL, IS NULL won't match.

Issue 2: Skipped executions not terminalized

The orphaned skipped cleanup only adds completed_at to skipped records — it does NOT change the status. So skipped executions remain as skipped forever, which is not in the set of terminal states (completed, failed, cancelled, success). They show up as stuck in any query filtering for non-terminal states.

Reproduction Steps

  1. Create a scheduled task that runs every few minutes
  2. Restart the backend while the scheduler is dispatching executions
  3. Wait for the cleanup service to run (5-minute interval)
  4. Query schedule_executions for non-terminal states
  5. Observe that running (no session) and skipped records persist

Suggested Fix

Fix 1: Debug the no-session query

Add logging to the no-session cleanup to see what it queries vs what exists:

# In cleanup cycle, before the no-session update:
cursor.execute("""
    SELECT id, agent_name, status, claude_session_id, started_at,
           typeof(claude_session_id) as sid_type,
           datetime('now', '-60 seconds') as threshold
    FROM schedule_executions
    WHERE status = 'running'
""")
rows = cursor.fetchall()
logger.info(f"[Cleanup] Running executions: {len(rows)}")
for row in rows:
    logger.info(f"[Cleanup]   {row}")

This will reveal whether the issue is timezone, NULL vs empty string, or something else.

Fix 2: Treat skipped as terminal OR change status during cleanup

Option A — Mark skipped as failed during cleanup:

cursor.execute("""
    UPDATE schedule_executions
    SET status = 'failed',
        completed_at = COALESCE(started_at, ?),
        duration_ms = 0,
        error = 'Finalized by cleanup: skipped execution'
    WHERE status = 'skipped'
    AND completed_at IS NULL
""", (now,))

Option B — Add skipped to the terminal states set everywhere it's checked.

Fix 3: Also check for empty string session IDs

WHERE status = 'running'
AND (claude_session_id IS NULL OR claude_session_id = '')
AND started_at < datetime('now', '-60 seconds')

Environment

  • Trinity version: fb8b9c6
  • Cleanup service interval: 300s (5 minutes)
  • Agent timeout: default (900s)

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    complexity-lowpriority-p2type-bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions