Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6957 fix(daemon): log full task ids so concurrent runs stay distinguishable (#7910)
Bohan Jiang10f4f8e938d9
diff --git a/apps/desktop/src/renderer/src/components/daemon-panel.tsx b/apps/desktop/src/renderer/src/components/daemon-panel.tsxindex c3a5d2459c..99f4315b8a 100644--- a/apps/desktop/src/renderer/src/components/daemon-panel.tsx+++ b/apps/desktop/src/renderer/src/components/daemon-panel.tsx@@ -666,7 +666,11 @@ function EmptyState({// ---------- Helpers -----------function truncateValue(value: string, max = 32): string {+// 36 is the width of a canonical UUID. Task, chat-session and holder ids are+// logged in full so concurrent runs stay distinguishable (#7326), and those+// ids carry their entropy in the tail — a budget that clipped them would put+// the ambiguity right back into this collapsed row.+function truncateValue(value: string, max = 36): string {// `max` is a content-character budget; the shared helper counts the ellipsis// toward its own budget, so pass `max + 1`.return truncateWithEllipsis(value, max + 1);diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 296d5d5a39..2acf6db5ec 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5104,9 +5104,9 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan islot := slots[i]taskTarget := t.IssueIDif taskTarget == "" && t.ChatSessionID != "" {- taskTarget = "chat:" + shortID(t.ChatSessionID)+ taskTarget = "chat:" + t.ChatSessionID}- d.logger.Info("task received", "task", shortID(t.ID), "target", taskTarget)+ d.logger.Info("task received", "task", t.ID, "target", taskTarget)taskWG.Add(1)d.activeTasks.Add(1)if cache, ok := d.repoCache.(interface{ CancelMaintenance() }); ok {@@ -5315,27 +5315,32 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {// like a misconfigured host and is not retried.if !tracked {d.logger.Warn("claimed task targets a runtime this daemon no longer hosts; failing it back for retry",- "task", shortID(task.ID), "runtime_id", task.RuntimeID)+ "task", task.ID, "runtime_id", task.RuntimeID)if err := d.reportTerminalTask(ctx, terminalTaskReport{kind: terminalTaskReportFail,taskID: task.ID,errorMessage: "runtime went offline before the task started",failureReason: taskfailure.ReasonRuntimeOffline.String(),}); err != nil {- d.logger.Error("fail task callback failed", "task", shortID(task.ID), "error", err)+ d.logger.Error("fail task callback failed", "task", task.ID, "error", err)}return}provider := rt.Provider- // Task-scoped logger with short ID for readable concurrent logs.- taskLog := d.logger.With("task", shortID(task.ID))+ // Task-scoped logger. The task id goes in whole: it is the key every+ // other surface prints (task JSON, env-root ownership manifest, server+ // logs), so a full id is what lets a log line be joined to them. An+ // 8-char prefix cannot — task ids are UUIDv7, whose leading 32 bits are+ // a millisecond timestamp that only advances every ~65s, so concurrent+ // tasks routinely share one (#7326).+ taskLog := d.logger.With("task", task.ID)agentName := "agent"if task.Agent != nil {agentName = task.Agent.Name}if task.ChatSessionID != "" {- taskLog.Info("picked chat task", "chat_session", shortID(task.ChatSessionID), "agent", agentName, "provider", provider)+ taskLog.Info("picked chat task", "chat_session", task.ChatSessionID, "agent", agentName, "provider", provider)} else {taskLog.Info("picked task", "issue", task.IssueID, "agent", agentName, "provider", provider)}@@ -5714,7 +5719,7 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas// client — worth doing if this hint grows, not for one parenthetical.reason = fmt.Sprintf("%s (held by task %s)", reason, shortID(holder))}- taskLog.Info("local_directory: waiting on path mutex", "holder", shortID(holder))+ taskLog.Info("local_directory: waiting on path mutex", "holder", holder)if waitErr := d.client.MarkTaskWaitingLocalDirectory(ctx, task.ID, reason); waitErr != nil {// Non-fatal: even if the server-side flag fails to update,// we still want to block on the lock and proceed when free.@@ -6652,12 +6657,12 @@ func (d *Daemon) lockReusablePriorEnvRoot(ctx context.Context, task Task, localAreturn nil, "", nil, false, context.Cause(ctx)case errors.Is(err, execenv.ErrEnvRootBusy):d.logger.Info("prior workdir is still in use after waiting for it; starting a fresh environment",- "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot),+ "task", task.ID, "prior_root", filepath.Base(priorRoot),"waited", time.Since(lockStartedAt).Round(time.Millisecond), "budget", d.envRootBusyWait)return nil, "", nil, false, nilcase err != nil:d.logger.Warn("could not lock prior workdir; starting a fresh environment",- "task", shortID(task.ID), "error", err)+ "task", task.ID, "error", err)return nil, "", nil, false, nilcase claim == nil:return nil, "", nil, false, nil@@ -6665,7 +6670,7 @@ func (d *Daemon) lockReusablePriorEnvRoot(ctx context.Context, task Task, localA// The lock has to have landed on the directory validation approved.if !os.SameFile(validatedInfo, lockedInfo) {d.logger.Info("prior workdir changed identity before it could be claimed; starting a fresh environment",- "task", shortID(task.ID))+ "task", task.ID)claim.Release()return nil, "", nil, false, nil}@@ -6686,7 +6691,7 @@ func (d *Daemon) lockReusablePriorEnvRoot(ctx context.Context, task Task, localAcurrentInfo, err := os.Stat(filepath.Dir(recheckedWorkDir))if err != nil || !os.SameFile(lockedInfo, currentInfo) {d.logger.Info("prior workdir changed identity while being claimed; starting a fresh environment",- "task", shortID(task.ID))+ "task", task.ID)claim.Release()return nil, "", nil, false, nil}@@ -6742,7 +6747,7 @@ func (d *Daemon) lockEnvRootForReuseWaitingOutTheBusyWindow(// instead of staying a guess.if waited && err == nil {d.logger.Info("prior workdir freed while waiting for the previous run to exit",- "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot),+ "task", task.ID, "prior_root", filepath.Base(priorRoot),"waited", time.Since(start).Round(time.Millisecond))}return claim, info, err@@ -6750,13 +6755,13 @@ func (d *Daemon) lockEnvRootForReuseWaitingOutTheBusyWindow(if !waited {waited = trued.logger.Info("prior workdir is still held by the previous run; waiting for it",- "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot),+ "task", task.ID, "prior_root", filepath.Base(priorRoot),"budget", d.envRootBusyWait)}select {case <-ctx.Done():d.logger.Info("stopped waiting for the prior workdir: the run was cancelled",- "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot),+ "task", task.ID, "prior_root", filepath.Base(priorRoot),"waited", time.Since(start).Round(time.Millisecond))// NOT the busy error the loop was carrying. A cancelled run is a// third outcome, and collapsing it into "still busy" would send the@@ -7463,8 +7468,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif env != nil && lockedPriorInfo != nil {usedInfo, statErr := os.Stat(filepath.Dir(env.WorkDir))if statErr != nil || !os.SameFile(lockedPriorInfo, usedInfo) {- taskLog.Info("reused workdir is not the directory that was claimed; starting a fresh environment",- "task", shortID(task.ID))+ // No "task" field here: taskLog already carries the full id.+ taskLog.Info("reused workdir is not the directory that was claimed; starting a fresh environment")env = nil}}@@ -7541,7 +7546,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ireason = fmt.Sprintf("%s (held by task %s)", reason, shortID(holder))}taskLog.Info("local_directory: worktree snapshot waiting for holder",- "holder", shortID(holder))+ "holder", holder)if waitErr := d.client.MarkTaskWaitingLocalDirectory(waitCtx, task.ID, reason); waitErr != nil {// Non-fatal: the wait still happens, the UI just won't// show the explicit "waiting" badge.@@ -8055,7 +8060,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// refresh spinner resolves via the client's own timeout.if task.RegenerateQuickActionsFor != "" {taskLog.Warn("refusing quick-actions refresh task from an older server; complete the daemon upgrade by updating the server",- "target_task", shortID(task.RegenerateQuickActionsFor),+ "target_task", task.RegenerateQuickActionsFor,)return TaskResult{Status: "completed", Comment: "", WorkDir: env.WorkDir, EnvRoot: env.RootDir}, nil}@@ -8669,7 +8674,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, provar idleWatchdogThreshold atomic.Int64idleWatchdogThreshold.Store(int64(idleWindow))if idleWindow > 0 {- go d.runIdleWatchdog(agentCtx, idleWindow, d.cfg.AgentToolWatchdog, &lastActivityAt, &inFlightTools, &idleWatchdogFired, &idleWatchdogThreshold, agentCancel, session.Messages, taskLog, taskID)+ go d.runIdleWatchdog(agentCtx, idleWindow, d.cfg.AgentToolWatchdog, &lastActivityAt, &inFlightTools, &idleWatchdogFired, &idleWatchdogThreshold, agentCancel, session.Messages, taskLog)}// drainFinished closes after the drain goroutine has flushed the last@@ -9006,7 +9011,7 @@ func idleWatchdogTickInterval(window time.Duration) time.Duration {//// Polling rate comes from idleWatchdogTickInterval, so a run is force-stopped// somewhere between its budget and budget + tick, never earlier.-func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow time.Duration, lastActivityAt *atomic.Int64, inFlightTools *atomic.Int32, fired *atomic.Bool, firedThreshold *atomic.Int64, cancel context.CancelFunc, messages <-chan agent.Message, taskLog *slog.Logger, taskID string) {+func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow time.Duration, lastActivityAt *atomic.Int64, inFlightTools *atomic.Int32, fired *atomic.Bool, firedThreshold *atomic.Int64, cancel context.CancelFunc, messages <-chan agent.Message, taskLog *slog.Logger) {ticker := time.NewTicker(idleWatchdogTickInterval(window))defer ticker.Stop()for {@@ -9037,8 +9042,8 @@ func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow tiif len(messages) > 0 {continue}+ // No "task" field here: taskLog already carries the full id.taskLog.Warn("idle watchdog firing: no agent activity, force-stopping run",- "task", shortID(taskID),"idle_for", idleFor.Round(time.Second).String(),"threshold", threshold.String(),"tool_in_flight", toolInFlight,@@ -9250,7 +9255,12 @@ func (d *Daemon) reserveStoreForDeletion(store string) (commit func(), ok bool)}, true}-// shortID returns the first 8 characters of an ID for readable logs.+// shortID returns the first 8 characters of an ID for a human-facing label.+//+// Display only, and only where the label is read rather than joined: the+// waiting-reason string the UI renders as "Waiting for {reason}" is the one+// caller left. Structured log fields must carry the FULL id — see the+// task-scoped logger in handleTask for why a prefix cannot identify a task.func shortID(id string) string {if len(id) <= 8 {return iddiff --git a/server/internal/daemon/task_log_correlation_test.go b/server/internal/daemon/task_log_correlation_test.gonew file mode 100644index 0000000000..063626699c--- /dev/null+++ b/server/internal/daemon/task_log_correlation_test.go@@ -0,0 +1,255 @@+package daemon++import (+ "bytes"+ "context"+ "go/ast"+ "go/parser"+ "go/token"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "regexp"+ "strings"+ "sync"+ "testing"+ "time"+)++// Two task ids from the field report on #7326. They differ from the fourth hex+// char of the second group onward and share the leading eight — which is not a+// coincidence worth guarding against once: task ids are UUIDv7, whose first 32+// bits are the high half of a millisecond timestamp, so every pair of tasks+// born inside the same ~65s window shares those eight chars. Truncating an id+// for a log field therefore merges concurrent runs into one indistinguishable+// stream exactly when telling them apart matters.+const (+ collidingTaskIDA = "01a05ec1-8413-76e0-82e3-fd427ee315fd"+ collidingTaskIDB = "01a05ec1-841d-7b0d-a60b-849f777505df"+)++// lockedBuffer is a slog sink safe to read while the task's cancellation+// watcher goroutine may still be alive.+type lockedBuffer struct {+ mu sync.Mutex+ buf bytes.Buffer+}++func (b *lockedBuffer) Write(p []byte) (int, error) {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.buf.Write(p)+}++func (b *lockedBuffer) String() string {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.buf.String()+}++// fieldValues returns every value the text handler emitted for `key=`.+func fieldValues(logs, key string) []string {+ re := regexp.MustCompile(`\b` + regexp.QuoteMeta(key) + `=(\S+)`)+ var out []string+ for _, m := range re.FindAllStringSubmatch(logs, -1) {+ out = append(out, strings.Trim(m[1], `"`))+ }+ return out+}++// TestHandleTask_LogsFullTaskIDSoConcurrentRunsStayDistinct is the log-side+// half of #7326. The workdir fix made two same-prefix tasks run in separate+// roots; this asserts their log lines can still be told apart afterwards, so+// scheduling/provider/workdir behaviour stays diagnosable per run.+func TestHandleTask_LogsFullTaskIDSoConcurrentRunsStayDistinct(t *testing.T) {+ t.Parallel()++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ logs := &lockedBuffer{}+ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})),+ workspaces: make(map[string]*workspaceState),+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},+ cancelPollInterval: time.Hour,+ cfg: Config{WorkspacesRoot: t.TempDir()},+ }+ // The runner's injected per-task logger is the one that carries `task=`+ // through the whole run, so make it emit a line we can inspect.+ d.runner = taskRunnerFunc(func(_ context.Context, _ Task, _ string, _ int, log *slog.Logger) (TaskResult, error) {+ log.Info("runner reached")+ return TaskResult{Status: "completed"}, nil+ })++ for _, id := range []string{collidingTaskIDA, collidingTaskIDB} {+ d.handleTask(context.Background(), Task{+ ID: id,+ RuntimeID: "rt-1",+ IssueID: "issue-log-correlation",+ Agent: &AgentData{Name: "test-agent"},+ }, 0)+ }++ out := logs.String()+ for _, id := range []string{collidingTaskIDA, collidingTaskIDB} {+ if !strings.Contains(out, "task="+id) {+ t.Errorf("no log line carried task=%s; logs:\n%s", id, out)+ }+ }+ for _, got := range fieldValues(out, "task") {+ if got != collidingTaskIDA && got != collidingTaskIDB {+ t.Errorf("task=%q is neither full task id — a truncated id cannot be joined to the task JSON, the env-root ownership manifest, or the other run's lines", got)+ }+ }+ // The per-task logger must reach the runner intact: everything the agent+ // run emits inherits this field.+ if !strings.Contains(out, "runner reached") {+ t.Fatal("runner never ran; the assertions above proved nothing about the per-task logger")+ }+ // One line, one `task=`. A call that re-passes the field its logger is+ // already bound to prints the id twice, which is 72 chars of noise now+ // that the value is a whole UUID.+ for _, line := range strings.Split(strings.TrimSpace(out), "\n") {+ if n := len(fieldValues(line, "task")); n > 1 {+ t.Errorf("log line carries %d task fields, want at most 1: %s", n, line)+ }+ }+}++// TestHandleTask_LogsFullChatSessionID covers the sibling correlation key on+// the chat path — a chat session id is a UUIDv7 too, and truncating it merges+// concurrent sessions the same way.+func TestHandleTask_LogsFullChatSessionID(t *testing.T) {+ t.Parallel()++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ const chatSessionID = "01a05ec1-9d02-7f11-9c3a-11c0de5510ab"++ logs := &lockedBuffer{}+ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})),+ workspaces: make(map[string]*workspaceState),+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},+ cancelPollInterval: time.Hour,+ cfg: Config{WorkspacesRoot: t.TempDir()},+ }+ d.runner = taskRunnerFunc(func(context.Context, Task, string, int, *slog.Logger) (TaskResult, error) {+ return TaskResult{Status: "completed"}, nil+ })++ d.handleTask(context.Background(), Task{+ ID: collidingTaskIDA,+ RuntimeID: "rt-1",+ ChatSessionID: chatSessionID,+ Agent: &AgentData{Name: "test-agent"},+ }, 0)++ out := logs.String()+ if !strings.Contains(out, "chat_session="+chatSessionID) {+ t.Errorf("no log line carried chat_session=%s; logs:\n%s", chatSessionID, out)+ }+}++// TestHandleTask_UntrackedRuntimeLogsFullTaskID guards the failure path, which+// logs before the per-task logger exists and so has its own `task=` argument.+func TestHandleTask_UntrackedRuntimeLogsFullTaskID(t *testing.T) {+ t.Parallel()++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ logs := &lockedBuffer{}+ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})),+ runtimeIndex: map[string]Runtime{},+ cancelPollInterval: time.Hour,+ }++ d.handleTask(context.Background(), Task{ID: collidingTaskIDB, RuntimeID: "rt-demoted"}, 0)++ if out := logs.String(); !strings.Contains(out, "task="+collidingTaskIDB) {+ t.Errorf("runtime-offline warning did not carry the full task id; logs:\n%s", out)+ }+}++// taskLogSourceFiles are the package sources the structural guard below reads.+// Asserting a call count against them keeps a rename or a file move from+// turning the guard into a vacuous pass (the failure mode MUL-5524 hit).+const minTaskLogCalls = 20++// TestTaskLogCallsDoNotRepeatTheBoundTaskField is the structural half of the+// one-line-one-`task=` rule above. The behavioural test can only see the lines+// its own code path emits; most `taskLog` calls live deep inside runTask,+// behind a real agent process. This reads the package source instead and fails+// on any `taskLog.<Level>(...)` that passes a literal "task" key — by+// convention in this package `taskLog` is always the logger handleTask bound+// the full task id to, so such an argument can only be a duplicate.+//+// A string literal "task" can never be a *value* in these calls, so matching+// the literal anywhere in the argument list needs no position arithmetic.+func TestTaskLogCallsDoNotRepeatTheBoundTaskField(t *testing.T) {+ t.Parallel()++ entries, err := os.ReadDir(".")+ if err != nil {+ t.Fatalf("read package dir: %v", err)+ }++ fset := token.NewFileSet()+ var calls int+ for _, entry := range entries {+ name := entry.Name()+ if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {+ continue+ }+ file, err := parser.ParseFile(fset, name, nil, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", name, err)+ }+ ast.Inspect(file, func(n ast.Node) bool {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok {+ return true+ }+ recv, ok := sel.X.(*ast.Ident)+ if !ok || recv.Name != "taskLog" {+ return true+ }+ switch sel.Sel.Name {+ case "Debug", "Info", "Warn", "Error":+ default:+ return true+ }+ calls+++ for _, arg := range call.Args {+ lit, ok := arg.(*ast.BasicLit)+ if !ok || lit.Kind != token.STRING || lit.Value != `"task"` {+ continue+ }+ t.Errorf("%s: taskLog call passes a \"task\" field it is already bound to — the id would print twice on that line", fset.Position(call.Pos()))+ }+ return true+ })+ }++ if calls < minTaskLogCalls {+ t.Fatalf("found only %d taskLog logging calls, want >= %d — the scan stopped matching (renamed logger? moved file?) and would pass vacuously", calls, minTaskLogCalls)+ }+}