Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

chore(server): add slow-path timing logs for /tasks/claim (#1376)

LinYushencf74327aa662
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 8d29bca60d..ed7ed49e37 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -10,6 +10,7 @@ import (
"sort"
"strconv"
"strings"
+ "time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -496,18 +497,56 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
+// logClaimEndpointSlow emits one structured log when the /tasks/claim endpoint
+// exceeds 500ms, splitting auth / claim / response-build phases so the prod
+// tail can be diagnosed without flooding logs at normal poll rates.
+func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, claimMs, buildMs int64) {
+ totalMs := time.Since(start).Milliseconds()
+ if totalMs < 500 {
+ return
+ }
+ slog.Info("claim_endpoint slow",
+ "runtime_id", runtimeID,
+ "outcome", outcome,
+ "total_ms", totalMs,
+ "auth_ms", authMs,
+ "claim_ms", claimMs,
+ "build_ms", buildMs,
+ )
+}
+
// ClaimTaskByRuntime atomically claims the next queued task for a runtime.
// The response includes the agent's name and skills, fetched fresh from the DB.
func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
+ start := time.Now()
+
+ var (
+ outcome = "unauth"
+ authMs, claimMs, buildMs int64
+ buildStart time.Time
+ )
+ defer func() {
+ // Emit at function exit so error / unauth paths also carry timing.
+ // build_ms is computed from buildStart only when we entered the
+ // response-build phase (otherwise stays 0).
+ if !buildStart.IsZero() {
+ buildMs = time.Since(buildStart).Milliseconds()
+ }
+ logClaimEndpointSlow(runtimeID, outcome, start, authMs, claimMs, buildMs)
+ }()
// Verify the caller owns this runtime's workspace.
if _, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID); !ok {
return
}
+ authMs = time.Since(start).Milliseconds()
+ claimStart := time.Now()
task, err := h.TaskService.ClaimTaskForRuntime(r.Context(), parseUUID(runtimeID))
+ claimMs = time.Since(claimStart).Milliseconds()
if err != nil {
+ outcome = "error_claim"
writeError(w, http.StatusInternalServerError, "failed to claim task: "+err.Error())
return
}
@@ -515,9 +554,13 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
if task == nil {
slog.Debug("no task to claim", "runtime_id", runtimeID)
writeJSON(w, http.StatusOK, map[string]any{"task": nil})
+ outcome = "no_task"
return
}
+ outcome = "claimed"
+ buildStart = time.Now()
+
// Build response with fresh agent data (name + skills + custom_env + custom_args).
resp := taskToResponse(*task)
if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 5151e91d74..e7625192a8 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -8,6 +8,7 @@ import (
"log/slog"
"strconv"
+ "time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -173,66 +174,155 @@ func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.A
// ClaimTask atomically claims the next queued task for an agent,
// respecting max_concurrent_tasks.
func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.AgentTaskQueue, error) {
+ start := time.Now()
+ var (
+ outcome = "unknown"
+ getAgentMs, countRunningMs, claimAgentMs, updateStatusMs, dispatchMs int64
+ )
+ defer func() {
+ s.maybeLogClaimSlow(agentID, outcome, start, getAgentMs, countRunningMs, claimAgentMs, updateStatusMs, dispatchMs)
+ }()
+
+ t0 := start
agent, err := s.Queries.GetAgent(ctx, agentID)
+ getAgentMs = time.Since(t0).Milliseconds()
if err != nil {
+ outcome = "error_get_agent"
return nil, fmt.Errorf("agent not found: %w", err)
}
+ t0 = time.Now()
running, err := s.Queries.CountRunningTasks(ctx, agentID)
+ countRunningMs = time.Since(t0).Milliseconds()
if err != nil {
+ outcome = "error_count_running"
return nil, fmt.Errorf("count running tasks: %w", err)
}
if running >= int64(agent.MaxConcurrentTasks) {
slog.Debug("task claim: no capacity", "agent_id", util.UUIDToString(agentID), "running", running, "max", agent.MaxConcurrentTasks)
+ outcome = "no_capacity"
return nil, nil // No capacity
}
+ t0 = time.Now()
task, err := s.Queries.ClaimAgentTask(ctx, agentID)
+ claimAgentMs = time.Since(t0).Milliseconds()
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
slog.Debug("task claim: no tasks available", "agent_id", util.UUIDToString(agentID))
+ outcome = "no_tasks"
return nil, nil // No tasks available
}
+ outcome = "error_claim"
return nil, fmt.Errorf("claim task: %w", err)
}
slog.Info("task claimed", "task_id", util.UUIDToString(task.ID), "agent_id", util.UUIDToString(agentID))
- // Update agent status to working
+ // Update agent status to working. Hits the DB and may publish events,
+ // so it must be inside the timed window.
+ t0 = time.Now()
s.updateAgentStatus(ctx, agentID, "working")
+ updateStatusMs = time.Since(t0).Milliseconds()
- // Broadcast task:dispatch
+ // Broadcast task:dispatch. ResolveTaskWorkspaceID inside this path can
+ // re-query issue/chat_session/autopilot_run, so it can also be a real
+ // contributor to claim latency.
+ t0 = time.Now()
s.broadcastTaskDispatch(ctx, task)
+ dispatchMs = time.Since(t0).Milliseconds()
+ outcome = "claimed"
return &task, nil
}
// ClaimTaskForRuntime claims the next runnable task for a runtime while
// still respecting each agent's max_concurrent_tasks limit.
func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.UUID) (*db.AgentTaskQueue, error) {
+ start := time.Now()
+ var (
+ outcome = "no_task"
+ listMs, loopMs int64
+ listCount, tried int
+ claimedFlag bool
+ )
+ defer func() {
+ totalMs := time.Since(start).Milliseconds()
+ if totalMs < 300 {
+ return
+ }
+ slog.Info("claim_for_runtime slow",
+ "runtime_id", util.UUIDToString(runtimeID),
+ "outcome", outcome,
+ "total_ms", totalMs,
+ "list_pending_ms", listMs,
+ "list_pending_count", listCount,
+ "agents_tried", tried,
+ "claim_loop_ms", loopMs,
+ "claimed", claimedFlag,
+ )
+ }()
+
+ t0 := start
tasks, err := s.Queries.ListPendingTasksByRuntime(ctx, runtimeID)
+ listMs = time.Since(t0).Milliseconds()
+ listCount = len(tasks)
if err != nil {
+ outcome = "error_list"
return nil, fmt.Errorf("list pending tasks: %w", err)
}
+ loopStart := time.Now()
triedAgents := map[string]struct{}{}
+ var claimed *db.AgentTaskQueue
for _, candidate := range tasks {
agentKey := util.UUIDToString(candidate.AgentID)
if _, seen := triedAgents[agentKey]; seen {
continue
}
triedAgents[agentKey] = struct{}{}
+ tried++
task, err := s.ClaimTask(ctx, candidate.AgentID)
if err != nil {
+ loopMs = time.Since(loopStart).Milliseconds()
+ outcome = "error_claim"
return nil, err
}
if task != nil && task.RuntimeID == runtimeID {
- return task, nil
+ claimed = task
+ break
}
}
+ loopMs = time.Since(loopStart).Milliseconds()
+ if claimed != nil {
+ claimedFlag = true
+ outcome = "claimed"
+ }
+
+ return claimed, nil
+}
- return nil, nil
+// maybeLogClaimSlow emits one structured log per ClaimTask call when its total
+// latency exceeds 300ms, so the prod tail can be diagnosed without flooding
+// logs at normal poll rates. Called via defer so it captures the full path
+// including post-claim updateAgentStatus / broadcastTaskDispatch (both of
+// which can hit the DB) and any error exit.
+func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, start time.Time, getAgentMs, countRunningMs, claimAgentMs, updateStatusMs, dispatchMs int64) {
+ totalMs := time.Since(start).Milliseconds()
+ if totalMs < 300 {
+ return
+ }
+ slog.Info("claim_task slow",
+ "agent_id", util.UUIDToString(agentID),
+ "outcome", outcome,
+ "total_ms", totalMs,
+ "get_agent_ms", getAgentMs,
+ "count_running_ms", countRunningMs,
+ "claim_agent_ms", claimAgentMs,
+ "update_status_ms", updateStatusMs,
+ "dispatch_ms", dispatchMs,
+ )
}
// StartTask transitions a dispatched task to running.