Repository navigation
Description
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_executionstable with newQUEUEDstatus - Callback-based drain —
SlotService.release_slot()fires a callback toBacklogService.drain_next() - Per-agent configurable depth —
max_backlog_depth(default 50, cap 200) onagent_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 orderingschedule_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 metadataclaim_next_queued(agent_name)— atomic SELECT oldest QUEUED + UPDATE to RUNNING, returns row or Noneget_queued_count(agent_name)— COUNT where status=queuedcancel_queued_executions(agent_name)— bulk cancel, return countexpire_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_callbackslist to__init__ - Add
register_on_release(callback)method - In
release_slot(), after removing from ZSET, fire callbacks viaasyncio.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) -> int6. 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_releasedas 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_resultalready polls by execution_id — will showstatus: "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=truegets backlog. - Fan-out: Uses
TaskExecutionServicedirectly — 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}showsqueued → running → successlifecycle - Backlog persists across backend restarts
- Configurable
max_backlog_depthper 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_resultworks for queued/backlog items without changes
Verification
- Set
max_parallel_tasks=1, send 3 async tasks → 1 accepted, 2 queued - Wait for auto-drain chain: task 1 completes → task 2 starts → completes → task 3 starts
- Set
max_backlog_depth=2, send 4 async tasks → 1 runs, 2 queue, 4th gets 429 - Cancel a queued task, verify it doesn't execute
- Restart backend with QUEUED items → verify they drain on startup
Activity
feat(backlog): persistent async task backlog (BACKLOG-001, #260)
docs: update orchestration plan progress + add retry tests (#271 foll…
feat(backlog): persistent async task backlog (BACKLOG-001, #260) (#316)
fix(backlog): repair drain spawn — lazy-import target after #95 (#496) (
docs(planning): #408 dissolution gated on #428, not #306 (re-audit) (#…
docs(feature-flows): clean up #95 drift missed by #500 (#496) (#503)
Release: v0.5.0 (#608)