Skip to content

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

Go

MUL-6941 feat(daemon): record task phase latency (#7890)

eveningb123cc758a74e149
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 198d8ede40..8623b8cb8f 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5399,6 +5399,10 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// a millisecond timestamp that only advances every ~65s, so concurrent
// tasks routinely share one (#7326).
taskLog := d.logger.With("task", task.ID)
+ phaseRecorder := newTaskPhaseRecorder(taskLog.With("task_id", task.ID, "runtime_id", task.RuntimeID), time.Now)
+ ctx = withTaskPhaseRecorder(ctx, phaseRecorder)
+ phaseRecorder.Mark(taskPhaseClaimed)
+ defer phaseRecorder.Mark(taskPhaseFinished)
agentName := "agent"
if task.Agent != nil {
agentName = task.Agent.Name
@@ -7243,6 +7247,8 @@ func qualifyTaskModel(
}
func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot int, taskLog *slog.Logger) (taskResult TaskResult, returnErr error) {
+ phaseRecorder := taskPhaseRecorderFromContext(ctx)
+ phaseRecorder.Mark(taskPhasePrepareStarted)
// A claim carries the task-row agent id both at the top level and inside
// the expanded agent configuration. The top-level id is authoritative
// because it is also bound into the task-scoped token. Never prepare or
@@ -7337,6 +7343,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if err := d.ensureTaskSkillBundles(prepareCtx, &task); err != nil {
return TaskResult{}, err
}
+ phaseRecorder.Mark(taskPhaseSkillsReady)
agentName := "agent"
var skills []SkillData
@@ -7814,6 +7821,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
}
}
+ phaseRecorder.Mark(taskPhaseEnvironmentReady)
// Belt-and-suspenders: also mark whatever root we ended up with, in case
// future changes diverge from ResolveRootDir.
if env.RootDir != resolvedRoot && env.RootDir != "" {
@@ -8409,6 +8417,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// than being relabeled resumable by a benign-looking second error.
result, tools = reconcileFreshRetryResult(firstResult, firstUsage, firstTools, retryResult, retryTools, retryErr)
}
+ phaseRecorder.Mark(taskPhaseTurnCompleted)
elapsed := time.Since(taskStart).Round(time.Second)
taskLog.Info("agent finished",
@@ -8847,6 +8856,7 @@ func freshSessionMayHelp(errText string) bool {
// sequence instead of restarting at 1 — the server orders the transcript by
// seq alone, and duplicate seqs would interleave the two attempts' rows.
func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prompt string, opts agent.ExecOptions, taskLog *slog.Logger, taskID, codexHome string, msgSeq *atomic.Int32) (agent.Result, int32, error) {
+ phaseRecorder := taskPhaseRecorderFromContext(ctx)
// Wrap the caller's ctx so the idle watchdog (below) can interrupt both
// the agent subprocess (via the ctx passed to backend.Execute) AND the
// drain loop with a single cancel. Without this layer the backend would
@@ -8869,6 +8879,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
// boundary, not at the earlier server-side StartTask transition.
d.runningTasks.Add(1)
defer d.runningTasks.Add(-1)
+ phaseRecorder.Mark(taskPhaseRuntimeStarted)
taskLog.Debug("backend started, draining messages")
// Bound the drain loop only when there is a wall-clock cap. With a positive
@@ -9019,6 +9030,12 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
if !ok {
goto drainDone
}
+ if isTaskOutputReceived(msg) {
+ phaseRecorder.Mark(taskPhaseFirstOutputReceived)
+ }
+ if isTaskToolUse(msg) {
+ phaseRecorder.Mark(taskPhaseFirstToolUse)
+ }
// Stamp activity as soon as a message lands. The idle
// watchdog reads this to decide whether the backend has
// gone silent — stamping before processing makes sure a
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index eace8bab72..16d3356999 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2548,7 +2548,9 @@ func TestExecuteAndDrain_ResumeFailureFallback(t *testing.T) {
t.Parallel()
d := newTestDaemon(t)
- ctx := context.Background()
+ capture := newTaskPhaseCaptureHandler()
+ recorder := newTaskPhaseRecorder(slog.New(capture), time.Now)
+ ctx := withTaskPhaseRecorder(context.Background(), recorder)
taskLog := slog.Default()
fb := &fakeBackend{
@@ -2572,6 +2574,9 @@ func TestExecuteAndDrain_ResumeFailureFallback(t *testing.T) {
if result.Status != "failed" || result.SessionID != "" {
t.Fatalf("expected failed result with empty SessionID, got %+v", result)
}
+ if slices.Contains(capture.phasesSnapshot(), taskPhaseTurnCompleted) {
+ t.Fatal("turn_completed was recorded for the discarded resume attempt")
+ }
// Mirrors the retry in runTask, gated on the same production predicate.
if shouldRetryWithFreshSession(result, opts.ResumeSessionID, tools, "claude") {
@@ -2599,6 +2604,13 @@ func TestExecuteAndDrain_ResumeFailureFallback(t *testing.T) {
if fb.calls[1].ResumeSessionID != "" {
t.Fatal("retry should not have ResumeSessionID")
}
+ if slices.Contains(capture.phasesSnapshot(), taskPhaseTurnCompleted) {
+ t.Fatal("executeAndDrain recorded turn_completed before runTask reconciled the final attempt")
+ }
+ recorder.Mark(taskPhaseTurnCompleted) // Mirrors runTask after fresh-retry reconciliation.
+ if got, want := capture.phasesSnapshot(), []taskPhase{taskPhaseRuntimeStarted, taskPhaseTurnCompleted}; !slices.Equal(got, want) {
+ t.Fatalf("task phases = %v, want %v", got, want)
+ }
}
// transcriptBackend emits a tool_use and a text message before returning its
diff --git a/server/internal/daemon/task_phase_timing.go b/server/internal/daemon/task_phase_timing.go
new file mode 100644
index 0000000000..d776c8b2b0
--- /dev/null
+++ b/server/internal/daemon/task_phase_timing.go
@@ -0,0 +1,116 @@
+package daemon
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+type taskPhase string
+
+const (
+ taskPhaseClaimed taskPhase = "claimed"
+ taskPhasePrepareStarted taskPhase = "prepare_started"
+ taskPhaseSkillsReady taskPhase = "skills_ready"
+ taskPhaseEnvironmentReady taskPhase = "environment_ready"
+ taskPhaseRuntimeStarted taskPhase = "runtime_started"
+ taskPhaseFirstOutputReceived taskPhase = "first_output_received"
+ taskPhaseFirstToolUse taskPhase = "first_tool_use"
+ taskPhaseTurnCompleted taskPhase = "turn_completed"
+ taskPhaseFinished taskPhase = "finished"
+)
+
+type taskPhaseSample struct {
+ Phase taskPhase
+ PhaseElapsed time.Duration
+ TotalElapsed time.Duration
+}
+
+// taskPhaseRecorder records daemon-local task lifecycle timing. It is
+// diagnostic-only: Mark has no error path and callers must not use it to make
+// task-state decisions.
+type taskPhaseRecorder struct {
+ logger *slog.Logger
+ now func() time.Time
+
+ mu sync.Mutex
+ started time.Time
+ previous time.Time
+ marked map[taskPhase]struct{}
+}
+
+func newTaskPhaseRecorder(logger *slog.Logger, now func() time.Time) *taskPhaseRecorder {
+ if now == nil {
+ now = time.Now
+ }
+ started := now()
+ return &taskPhaseRecorder{
+ logger: logger,
+ now: now,
+ started: started,
+ previous: started,
+ marked: make(map[taskPhase]struct{}),
+ }
+}
+
+// Mark records and logs a phase only once. PhaseElapsed is the time since the
+// previous recorded phase, not the duration of the named phase itself; skipped
+// phases therefore widen the next recorded interval. A duplicate mark returns
+// a zero sample and does not consume the injected clock.
+func (r *taskPhaseRecorder) Mark(phase taskPhase) taskPhaseSample {
+ if r == nil {
+ return taskPhaseSample{}
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if _, ok := r.marked[phase]; ok {
+ return taskPhaseSample{}
+ }
+
+ now := r.now()
+ sample := taskPhaseSample{
+ Phase: phase,
+ PhaseElapsed: now.Sub(r.previous),
+ TotalElapsed: now.Sub(r.started),
+ }
+ r.marked[phase] = struct{}{}
+ r.previous = now
+ if r.logger != nil {
+ r.logger.Info("task phase recorded",
+ "task_phase", phase,
+ "phase_elapsed_ms", sample.PhaseElapsed.Milliseconds(),
+ "total_elapsed_ms", sample.TotalElapsed.Milliseconds(),
+ )
+ }
+ return sample
+}
+
+type taskPhaseRecorderContextKey struct{}
+
+func withTaskPhaseRecorder(ctx context.Context, recorder *taskPhaseRecorder) context.Context {
+ return context.WithValue(ctx, taskPhaseRecorderContextKey{}, recorder)
+}
+
+func taskPhaseRecorderFromContext(ctx context.Context) *taskPhaseRecorder {
+ recorder, _ := ctx.Value(taskPhaseRecorderContextKey{}).(*taskPhaseRecorder)
+ return recorder
+}
+
+func isTaskOutputReceived(msg agent.Message) bool {
+ switch msg.Type {
+ case agent.MessageText, agent.MessageThinking:
+ return msg.Content != ""
+ case agent.MessageToolUse, agent.MessageToolResult, agent.MessageError:
+ return true
+ default:
+ return false
+ }
+}
+
+func isTaskToolUse(msg agent.Message) bool {
+ return msg.Type == agent.MessageToolUse
+}
diff --git a/server/internal/daemon/task_phase_timing_test.go b/server/internal/daemon/task_phase_timing_test.go
new file mode 100644
index 0000000000..ad09080822
--- /dev/null
+++ b/server/internal/daemon/task_phase_timing_test.go
@@ -0,0 +1,195 @@
+package daemon
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "slices"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+func TestTaskPhaseRecorderRecordsElapsedDurations(t *testing.T) {
+ times := []time.Time{
+ time.Unix(0, 0),
+ time.Unix(0, 20*time.Millisecond.Nanoseconds()),
+ time.Unix(0, 55*time.Millisecond.Nanoseconds()),
+ }
+ recorder := newTaskPhaseRecorder(testTaskPhaseLogger(), func() time.Time {
+ now := times[0]
+ times = times[1:]
+ return now
+ })
+
+ if got, want := recorder.Mark(taskPhaseClaimed), (taskPhaseSample{
+ Phase: taskPhaseClaimed, PhaseElapsed: 20 * time.Millisecond, TotalElapsed: 20 * time.Millisecond,
+ }); got != want {
+ t.Fatalf("Mark(%q) = %#v, want %#v", taskPhaseClaimed, got, want)
+ }
+ if got, want := recorder.Mark(taskPhasePrepareStarted), (taskPhaseSample{
+ Phase: taskPhasePrepareStarted, PhaseElapsed: 35 * time.Millisecond, TotalElapsed: 55 * time.Millisecond,
+ }); got != want {
+ t.Fatalf("Mark(%q) = %#v, want %#v", taskPhasePrepareStarted, got, want)
+ }
+}
+
+func TestTaskPhaseRecorderLogsEachPhaseOnlyOnce(t *testing.T) {
+ var logs bytes.Buffer
+ logger := slog.New(slog.NewJSONHandler(&logs, nil)).With("task_id", "task-1", "runtime_id", "runtime-1")
+ recorder := newTaskPhaseRecorder(logger, func() time.Time { return time.Unix(0, 0) })
+
+ recorder.Mark(taskPhaseClaimed)
+ recorder.Mark(taskPhaseClaimed)
+
+ var record map[string]any
+ if err := json.Unmarshal(logs.Bytes(), &record); err != nil {
+ t.Fatalf("decode log record: %v", err)
+ }
+ if got, want := record["task_phase"], string(taskPhaseClaimed); got != want {
+ t.Fatalf("task_phase = %#v, want %#v", got, want)
+ }
+ for _, field := range []string{"phase_elapsed_ms", "total_elapsed_ms", "task_id", "runtime_id"} {
+ if _, ok := record[field]; !ok {
+ t.Fatalf("missing stable log field %q in %#v", field, record)
+ }
+ }
+}
+
+func TestTaskPhaseRecorderClassifiesOutputReceived(t *testing.T) {
+ cases := []struct {
+ name string
+ msg agent.Message
+ want bool
+ }{
+ {name: "status progress", msg: agent.Message{Type: agent.MessageStatus, Status: "running"}, want: false},
+ {name: "empty text", msg: agent.Message{Type: agent.MessageText}, want: false},
+ {name: "text", msg: agent.Message{Type: agent.MessageText, Content: "working"}, want: true},
+ {name: "tool use", msg: agent.Message{Type: agent.MessageToolUse, Tool: "shell"}, want: true},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := isTaskOutputReceived(tc.msg); got != tc.want {
+ t.Fatalf("isTaskOutputReceived(%#v) = %t, want %t", tc.msg, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestTaskPhaseRecorderClassifiesToolUse(t *testing.T) {
+ cases := []struct {
+ name string
+ msg agent.Message
+ want bool
+ }{
+ {name: "status progress", msg: agent.Message{Type: agent.MessageStatus, Status: "running"}, want: false},
+ {name: "text progress", msg: agent.Message{Type: agent.MessageText, Content: "Working on it"}, want: false},
+ {name: "tool use", msg: agent.Message{Type: agent.MessageToolUse, Tool: "shell"}, want: true},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := isTaskToolUse(tc.msg); got != tc.want {
+ t.Fatalf("isTaskToolUse(%#v) = %t, want %t", tc.msg, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestTaskPhaseRecorderRecordsReceivedAttemptPhasesInOrder(t *testing.T) {
+ capture := newTaskPhaseCaptureHandler()
+ recorder := newTaskPhaseRecorder(slog.New(capture), time.Now)
+ ctx := withTaskPhaseRecorder(context.Background(), recorder)
+ d := newTestDaemon(t)
+
+ messages := make(chan agent.Message, 3)
+ messages <- agent.Message{Type: agent.MessageStatus, Status: "running"}
+ messages <- agent.Message{Type: agent.MessageText, Content: "working"}
+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "shell"}
+ close(messages)
+ results := make(chan agent.Result, 1)
+ results <- agent.Result{Status: "completed"}
+ close(results)
+
+ _, _, err := d.executeAndDrain(ctx, taskPhaseTimingBackend{
+ session: &agent.Session{Messages: messages, Result: results},
+ }, "prompt", agent.ExecOptions{}, testTaskPhaseLogger(), "task-1", "", new(atomic.Int32))
+ if err != nil {
+ t.Fatalf("executeAndDrain() error = %v", err)
+ }
+
+ want := []taskPhase{
+ taskPhaseRuntimeStarted,
+ taskPhaseFirstOutputReceived,
+ taskPhaseFirstToolUse,
+ }
+ if got := capture.phasesSnapshot(); !slices.Equal(got, want) {
+ t.Fatalf("phase order = %v, want %v", got, want)
+ }
+}
+
+func TestTaskPhaseRecorderHandleTaskMarksBoundaryPhases(t *testing.T) {
+ capture := newTaskPhaseCaptureHandler()
+ d := newTestDaemon(t)
+ d.logger = slog.New(capture)
+ d.runtimeIndex = map[string]Runtime{"runtime-1": {ID: "runtime-1", Provider: "codex"}}
+ d.cancelPollInterval = time.Hour
+ d.runner = taskRunnerFunc(func(context.Context, Task, string, int, *slog.Logger) (TaskResult, error) {
+ return TaskResult{Status: "completed"}, nil
+ })
+
+ d.handleTask(context.Background(), Task{ID: "task-1", RuntimeID: "runtime-1"}, 0)
+
+ want := []taskPhase{taskPhaseClaimed, taskPhaseFinished}
+ if got := capture.phasesSnapshot(); !slices.Equal(got, want) {
+ t.Fatalf("phase order = %v, want %v", got, want)
+ }
+}
+
+type taskPhaseTimingBackend struct {
+ session *agent.Session
+}
+
+func (b taskPhaseTimingBackend) Execute(context.Context, string, agent.ExecOptions) (*agent.Session, error) {
+ return b.session, nil
+}
+
+type taskPhaseCaptureHandler struct {
+ mu sync.Mutex
+ phases []taskPhase
+}
+
+func newTaskPhaseCaptureHandler() *taskPhaseCaptureHandler { return &taskPhaseCaptureHandler{} }
+
+func (h *taskPhaseCaptureHandler) Enabled(context.Context, slog.Level) bool { return true }
+
+func (h *taskPhaseCaptureHandler) Handle(_ context.Context, record slog.Record) error {
+ record.Attrs(func(attr slog.Attr) bool {
+ if attr.Key == "task_phase" {
+ h.mu.Lock()
+ h.phases = append(h.phases, taskPhase(attr.Value.String()))
+ h.mu.Unlock()
+ }
+ return true
+ })
+ return nil
+}
+
+func (h *taskPhaseCaptureHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
+func (h *taskPhaseCaptureHandler) WithGroup(string) slog.Handler { return h }
+
+func (h *taskPhaseCaptureHandler) phasesSnapshot() []taskPhase {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return append([]taskPhase(nil), h.phases...)
+}
+
+func testTaskPhaseLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}