Skip to content

bug: Executions stuck in 'running' state due to scheduler/backend database split #90

Closed

Description

@vybe

Summary

Scheduled and manual executions silently get stuck in status="running" with claude_session_id=NULL and duration_ms=NULL. The execution record is created in the scheduler's database but never synchronized to the backend's database, so when the backend tries to update the status (on success or failure), the update targets a non-existent record and silently does nothing. The record stays "running" forever.

This affects ~14 out of 15 observed orphaned executions — most orphans are NOT caused by backend restarts but by this silent failure path.

Component

Scheduler / Backend / TaskExecutionService

Priority

P2 — Feature impaired (executions still run, but tracking is broken; requires manual cleanup)

Error

No error is logged. The failure is completely silent:

  • Scheduler creates execution record locally with status="running"
  • Backend receives execution_id but doesn't create a matching record in its own database
  • When execution completes (or fails), backend calls db.update_execution_status(execution_id=...) which silently no-ops
  • Record stays "running" in perpetuity with claude_session_id=NULL, duration_ms=NULL

Location

  • File: src/scheduler/service.py ~line 558 — creates execution in scheduler DB
  • File: src/scheduler/service.py ~line 585 — calls backend with execution_id
  • File: src/backend/services/task_execution_service.py ~line 148-160 — skips record creation when execution_id is provided
  • File: src/backend/services/task_execution_service.py ~line 252-262 — tries to update non-existent backend DB record

Root Cause

The scheduler and backend use separate SQLite databases:

  1. Scheduler (src/scheduler/database.py) creates execution record in its own DB
  2. Scheduler calls backend's /api/internal/execute-task with execution_id
  3. Backend (TaskExecutionService) sees execution_id is provided, so skips creating a record in its own DB (assumes it already exists)
  4. Agent execution proceeds — on completion/failure, backend calls db.update_execution_status() on its own DB
  5. Record doesn't exist in backend DB → update is a silent no-op
  6. Scheduler DB record stays "running" forever
# task_execution_service.py ~line 148
# This skips record creation when scheduler provides execution_id
if not execution_id:
    execution = db.create_task_execution(...)  # Only created when NO id provided
    execution_id = execution.id if execution else None

The same issue affects error handling — when agent container calls fail (e.g., httpx.ConnectError after retries), the exception handler tries to update the backend DB, which also silently fails.

Reproduction Steps

  1. Have a scheduled task configured for any agent
  2. Wait for the scheduler to trigger the task
  3. If the agent container is slow to respond or the execution encounters any issue during launch, the record gets stuck
  4. Query: SELECT * FROM schedule_executions WHERE status = 'running' AND claude_session_id IS NULL
  5. Observe records that will never transition out of "running"

Also reproducible with manual triggers — the scheduler path is used for both.

Suggested Fix

Option A (recommended): Have the scheduler NOT create the execution record. Let the backend's TaskExecutionService create it in the backend database, which is the same database used for status updates:

# scheduler/service.py - DON'T create record here
# Instead, pass schedule details to backend and let it create the record
result = await self._call_backend_execute_task(
    agent_name=schedule.agent_name,
    message=schedule.message,
    schedule_id=schedule.id,
    triggered_by=triggered_by,
    # execution_id=execution.id,  # REMOVE - let backend create it
)
# task_execution_service.py - ALWAYS create record in backend DB
# Remove the `if not execution_id` gate
execution = db.create_task_execution(...)
execution_id = execution.id

Option B: When execution_id is provided, have TaskExecutionService verify the record exists in its DB and create/sync it if missing:

if execution_id:
    existing = db.get_execution(execution_id)
    if not existing:
        # Sync from scheduler - create matching record in backend DB
        execution = db.create_task_execution(
            execution_id=execution_id,  # Use same ID for consistency
            ...
        )

Evidence

Out of 15 orphaned executions observed over 3 weeks:

  • 14 had claude_session_id=NULL AND duration_ms=NULL (silent launch failures)
  • 1 had a session ID (genuine restart orphan)

Affected both scheduled and manual triggers across multiple agents.

Environment

  • Trinity version: e1998fd (fix: Route scheduled tasks through TaskExecutionService for capacity meter visibility)
  • Note: The recent commit e1998fd routed scheduled tasks through TaskExecutionService, which may have introduced or amplified this issue by changing the execution flow

Related

  • src/scheduler/service.py — scheduler execution creation
  • src/scheduler/database.py — scheduler's separate SQLite database
  • src/backend/services/task_execution_service.py — backend execution service
  • src/backend/db/schedules.py — backend execution database layer

Activity

  1. vybe commented on Mar 11, 2026

    @vybe
    ContributorAuthor

    Investigation Results — Root Cause Clarification

    The bug is confirmed real, but the "separate databases" framing in the description is incorrect. Here's what's actually happening.

    Both services share the same SQLite file

    • Backend: TRINITY_DB_PATH=/data/trinity.db (src/backend/db/connection.py:12)
    • Scheduler: DATABASE_PATH=/data/trinity.db (src/scheduler/config.py:17)
    • Both mount the same Docker volume: trinity-data:/data (docker-compose.yml:55,169)

    So this is NOT a two-database problem. It's a concurrent SQLite access problem.

    Actual root cause: dual-write without WAL mode

    Neither the backend nor the scheduler enables WAL mode — both use SQLite's default DELETE journal mode (src/backend/db/connection.py:18, src/scheduler/database.py:37). DELETE mode uses exclusive file locks for writes.

    The failure sequence:

    1. Scheduler (service.py:558) calls self.db.create_execution() → INSERTs row, commits, closes connection.
    2. Scheduler (service.py:585) calls backend's POST /api/internal/execute-task with execution_id.
    3. Backend TaskExecutionService (task_execution_service.py:148) sees execution_id is provided → skips creating a record.
    4. Agent runs. On completion, backend calls db.update_execution_status() (task_execution_service.py:252).
    5. Backend's update_execution_status() (db/schedules.py:591) runs SELECT started_at FROM schedule_executions WHERE id = ?.

    Under normal conditions, step 5 finds the row. But with two separate processes doing short-lived sqlite3.connect() calls against the same file via a Docker volume mount (no persistent connection, no WAL), there are visibility windows where:

    • The scheduler's commit hasn't fully flushed through the Docker volume layer
    • The backend opens a connection that sees a stale filesystem state
    • SQLite's file-level locking creates contention under concurrent access

    Compounding issue: silent failure

    db.update_execution_status() returns False when the row isn't found (db/schedules.py:593), but TaskExecutionService never checks this return value — at lines 252, 295, 329, and 352 the return value is discarded. So the failure is completely silent: no log, no error, no retry.

    Same problem in error paths

    When the backend call itself fails (e.g., agent container unreachable), the scheduler catches the exception and calls its own self.db.update_execution_status() (service.py:649). This writes to the same file, but the backend's TaskExecutionService has already attempted (and silently failed) its own status update within the failed HTTP call. The two processes race to update the same row.

    Confirmed fix: Option A from the issue

    Stop the scheduler from creating execution records. Let TaskExecutionService always create the record in its own transaction:

    1. Scheduler: Remove self.db.create_execution() call. Pass schedule_id, agent_name, message, triggered_by, model to the backend. Don't pass execution_id.
    2. Backend InternalTaskExecutionRequest: Add schedule_id field.
    3. TaskExecutionService: Always create the record (remove the if not execution_id gate). Pass schedule_id through to db.create_task_execution().
    4. Backend response: Return execution_id to the scheduler so it can use it for WebSocket events and run-time updates.
    5. Scheduler error handler (service.py:649): Remove self.db.update_execution_status() — the backend owns all execution record lifecycle.
    6. Bonus: Add WAL mode to both connection helpers to prevent future concurrent access issues.

    This eliminates the dual-write entirely — only the backend writes execution records, and its updates always target rows it created.

  2. vybe commented on Mar 12, 2026

    @vybe
    ContributorAuthor

    Fix Implemented

    The bug has been fixed in this commit. However, the root cause analysis in the issue was incorrect.

    Corrected Root Cause

    There is NO database split. Both the scheduler and backend use the same SQLite database (/data/trinity.db):

    • Scheduler: database_path = os.getenv("DATABASE_PATH", "/data/trinity.db") (src/scheduler/config.py:18)
    • Backend: DB_PATH = Path(os.environ.get("TRINITY_DB_PATH", "/data/trinity.db")) (src/backend/db/connection.py:8)

    The actual bug was in TaskExecutionService.execute_task():

    1. When execution_id is provided (scheduler case), the service correctly skips creating a new record since it already exists
    2. The problem: The try block that caught exceptions and updated execution status to FAILED only started after slot acquisition (step 4)
    3. If an exception occurred during db.get_max_parallel_tasks() or slot_service.acquire_slot() (steps 2-3), the exception propagated up without updating the execution record
    4. Result: execution stuck in 'running' forever with NULL claude_session_id and duration_ms

    Fix

    src/backend/services/task_execution_service.py:

    • Wrapped the entire execution flow (from slot acquisition onwards) in a try block starting at line 166
    • Added slot_acquired = False flag to track state
    • Changed finally block to only release slot if acquired: if slot_acquired: slot_service.release_slot(...)

    src/backend/routers/internal.py:

    • Added defensive error handling to _execute_task_internal_background()
    • If an exception escapes TaskExecutionService, the handler now updates execution status to FAILED (prevents stuck executions from async dispatch)

    Modified Files

    • src/backend/services/task_execution_service.py
    • src/backend/routers/internal.py
    • docs/memory/changelog.md
    • docs/memory/feature-flows/task-execution-service.md
  3. added
    complexity-low
    on Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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