Skip to content

feat: Persistent task backlog for async execution (BACKLOG-001) #260

Closed

Description

@vybe

Overview

When async_mode=true is used on POST /api/agents/{name}/task and all parallel slots are full, Trinity currently returns HTTP 429. Instead, tasks should spill into a persistent SQLite-backed backlog and auto-drain when slots free up.

Extends: #157 (Agent Task Backlog spike)

Flow

async_mode=true request arrives
  → slot available? → execute immediately (status: "accepted", HTTP 200)
  → slots full?     → persist to backlog (status: "queued", HTTP 202)
                        → slot freed → auto-drain next → execute
  → slots full + backlog full? → reject (HTTP 429)

Design Decisions

  • Integrated into existing async_mode — not a separate endpoint
  • SQLite persistence — durable across restarts, reuses schedule_executions table with new QUEUED status
  • Callback-based drain — SlotService.release_slot() fires a callback to BacklogService.drain_next()
  • Per-agent configurable depth — max_backlog_depth (default 50, cap 200) on agent_ownership
  • FIFO ordering — priority can come later
  • Safety net — 60s periodic maintenance task catches orphaned QUEUED items and expires stale ones (24h)

Implementation Plan

1. Add QUEUED status to TaskExecutionStatus

File: src/backend/models.py

Add QUEUED = "queued" to the enum, before RUNNING.

2. Database migration

File: src/backend/db/migrations.py

New migration "backlog_support":

  • schedule_executions.queued_at TEXT — ISO timestamp for FIFO ordering
  • schedule_executions.backlog_metadata TEXT — JSON with full request context (model, allowed_tools, system_prompt, timeout_seconds, save_to_session, user_message, chat_session_id, resume_session_id, user_id, user_email, subscription_id, x_source_agent, x_mcp_key_id, x_mcp_key_name, triggered_by, collaboration_activity_id)
  • agent_ownership.max_backlog_depth INTEGER DEFAULT 50
  • Partial index: idx_executions_queued ON schedule_executions(agent_name, queued_at) WHERE status = 'queued'

3. Database query methods

File: src/backend/db/schedules.py

  • update_execution_to_queued(execution_id, backlog_metadata, queued_at) — set status=QUEUED, store metadata
  • claim_next_queued(agent_name) — atomic SELECT oldest QUEUED + UPDATE to RUNNING, returns row or None
  • get_queued_count(agent_name) — COUNT where status=queued
  • cancel_queued_executions(agent_name) — bulk cancel, return count
  • expire_stale_queued(max_age_hours=24) — mark expired QUEUED as FAILED

File: src/backend/db_models.py — Add queued_at, backlog_metadata to ScheduleExecution
File: src/backend/database.py — Delegate new methods + expose get/set_max_backlog_depth()

4. SlotService release callback

File: src/backend/services/slot_service.py

  • Add _on_release_callbacks list to __init__
  • Add register_on_release(callback) method
  • In release_slot(), after removing from ZSET, fire callbacks via asyncio.create_task(cb(agent_name))

5. BacklogService (new file)

File: src/backend/services/backlog_service.py

class BacklogService:
    async def enqueue(...) -> bool       # Check depth, store metadata, set QUEUED
    async def drain_next(agent_name)     # Atomic claim, acquire slot, spawn task
    async def on_slot_released(agent_name)  # Callback → drain_next
    async def get_backlog_depth(agent_name) -> int
    async def cancel_backlog_item(execution_id) -> bool
    async def cancel_all_backlog(agent_name) -> int
    async def expire_stale(max_age_hours=24) -> int

6. Router integration

File: src/backend/routers/chat.py (lines 771-781)

Replace the 429 rejection block: if not slot_acquired, try backlog.enqueue(). If enqueued → return HTTP 202 with status: "queued". If backlog full → HTTP 429.

7. Startup wiring

File: src/backend/main.py

  • Register backlog_service.on_slot_released as SlotService callback
  • Start periodic maintenance task (60s): expire stale, drain orphaned QUEUED items

8. Cancellation support

Update terminate/cancel endpoint to handle status == "queued" (just update DB, no container interaction).

Files Modified/Created

File Change
src/backend/models.py Add QUEUED to TaskExecutionStatus
src/backend/db_models.py Add queued_at, backlog_metadata fields
src/backend/db/migrations.py New migration for backlog columns + index
src/backend/db/schedules.py Backlog query methods
src/backend/database.py Delegate new methods
src/backend/services/slot_service.py Release callback mechanism
src/backend/services/backlog_service.py NEW — core backlog service
src/backend/routers/chat.py Enqueue on capacity instead of 429
src/backend/main.py Wire callback + maintenance task

What Doesn't Change

  • MCP tools: chat_with_agent(async=true) automatically gets backlog behavior. get_execution_result already polls by execution_id — will show status: "queued".
  • UI: Execution list already renders status badges. QUEUED appears as a new badge. No frontend changes for MVP.
  • Sync mode: Unaffected. Only async_mode=true gets backlog.
  • Fan-out: Uses TaskExecutionService directly — no backlog interaction.

Acceptance Criteria

  • Async task at capacity returns HTTP 202 with status: "queued" instead of 429
  • Queued tasks auto-execute when slots free up (FIFO order)
  • GET /api/agents/{name}/executions/{id} shows queued → running → success lifecycle
  • Backlog persists across backend restarts
  • Configurable max_backlog_depth per agent (default 50)
  • True 429 only when backlog is also full
  • Queued items can be cancelled
  • Stale queued items expire after 24h
  • MCP get_execution_result works for queued/backlog items without changes

Verification

  1. Set max_parallel_tasks=1, send 3 async tasks → 1 accepted, 2 queued
  2. Wait for auto-drain chain: task 1 completes → task 2 starts → completes → task 3 starts
  3. Set max_backlog_depth=2, send 4 async tasks → 1 runs, 2 queue, 4th gets 429
  4. Cancel a queued task, verify it doesn't execute
  5. Restart backend with QUEUED items → verify they drain on startup

Activity

  1. added
    priority-p1
    type-feature
    on Apr 3, 2026
  2. added
    status-in-progress
    on Apr 13, 2026
  3. removed
    status-in-progress
    on Apr 17, 2026
  4. added
    complexity-medium
    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-mediumpriority-p1type-feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions