Skip to content

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

Go

fix(autopilot): invalidate empty cache for scheduled tasks (MUL-5747) (#6410)

rongchenzhengc6c3be5935c9
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 13bf20b7c2..0ef0243dbe 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -172,6 +172,10 @@ func envBool(name string, def bool) bool {
return v
}
+func backgroundServices(h *handler.Handler) (*service.TaskService, *service.AutopilotService) {
+ return h.TaskService, h.AutopilotService
+}
+
func main() {
logger.Init()
@@ -407,10 +411,12 @@ func main() {
// Start background workers.
sweepCtx, sweepCancel := context.WithCancel(context.Background())
autopilotCtx, autopilotCancel := context.WithCancel(context.Background())
- taskSvc := service.NewTaskService(queries, pool, hub, bus, daemonWakeup)
- taskSvc.Analytics = analyticsClient
- taskSvc.Metrics = businessMetrics
- autopilotSvc := service.NewAutopilotService(queries, pool, bus, taskSvc)
+ // Reuse the router's services here. In particular, the router wires the
+ // EmptyClaim cache into TaskService; constructing a second TaskService for
+ // scheduled Autopilot dispatch would send the daemon wakeup without bumping
+ // that cache's version, so an idle runtime could keep returning an empty
+ // claim until the cache TTL expires.
+ taskSvc, autopilotSvc := backgroundServices(h)
registerAutopilotListeners(bus, autopilotSvc)
// Construct a LivenessStore that mirrors the one wired into the HTTP
diff --git a/server/cmd/server/main_test.go b/server/cmd/server/main_test.go
index 262cc7fecb..540b549f1f 100644
--- a/server/cmd/server/main_test.go
+++ b/server/cmd/server/main_test.go
@@ -1,8 +1,15 @@
package main
import (
+ "bytes"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/printer"
+ "go/token"
"os"
"strconv"
+ "strings"
"syscall"
"testing"
"time"
@@ -82,6 +89,162 @@ func TestNewNamedRedisClient_DisableClientName_InvalidValue(t *testing.T) {
}
}
+// mainSourceFile is parsed by TestMainUsesRouterOwnedBackgroundServices. The
+// test asserts the markers below are actually present so a future move of the
+// background-worker wiring fails loudly instead of vacuously passing on a walk
+// that matched nothing.
+const mainSourceFile = "main.go"
+
+// backgroundServiceConstructors must never be called from main(): they build a
+// TaskService / AutopilotService that the router has not finished wiring.
+var backgroundServiceConstructors = []string{
+ "service.NewTaskService",
+ "service.NewAutopilotService",
+}
+
+// TestMainUsesRouterOwnedBackgroundServices guards the process wiring behind
+// scheduled Autopilot dispatch and the runtime sweeper: both must take the
+// router's fully wired services off *handler.Handler instead of constructing
+// their own.
+//
+// The router — not NewTaskService — assigns h.TaskService.EmptyClaim. A second
+// TaskService built inside main() therefore has EmptyClaim == nil, and because
+// EmptyClaimCache is deliberately nil-safe the missed invalidation is silent:
+// a scheduled dispatch still delivers the daemon wakeup while the claim path's
+// cached "no queued task" verdict survives, so an idle runtime keeps returning
+// empty claims until EmptyClaimCacheTTL expires.
+//
+// This parses main.go instead of asserting on backgroundServices' return
+// values. A value-level assertion only proves the helper hands back h's fields,
+// which stays true even when main() stops calling it and constructs its own
+// services again — i.e. it cannot fail on the exact regression it names.
+func TestMainUsesRouterOwnedBackgroundServices(t *testing.T) {
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, mainSourceFile, nil, 0)
+ if err != nil {
+ t.Fatalf("parse %s: %v", mainSourceFile, err)
+ }
+
+ var mainFunc *ast.FuncDecl
+ for _, decl := range file.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if ok && fn.Recv == nil && fn.Name.Name == "main" {
+ mainFunc = fn
+ break
+ }
+ }
+ if mainFunc == nil || mainFunc.Body == nil {
+ t.Fatalf("no func main() with a body found in %s — this guard must be pointed at the real wiring", mainSourceFile)
+ }
+
+ // Resolve the variable holding the router's *handler.Handler rather than
+ // hardcoding "h": the argument identity is the whole point of the guard,
+ // and reading it off the NewRouterWithOptions assignment keeps a rename of
+ // that variable from silently weakening the check below.
+ routerHandlerVar := routerHandlerIdent(mainFunc.Body)
+ if routerHandlerVar == "" {
+ t.Fatalf("could not find the *handler.Handler result of NewRouterWithOptions in main() — re-point this guard at the current router wiring")
+ }
+
+ forbidden := make(map[string]bool, len(backgroundServiceConstructors))
+ for _, name := range backgroundServiceConstructors {
+ forbidden[name] = true
+ }
+
+ var (
+ offenders []string
+ badReuse []string
+ reusesRouter bool
+ registersScheduler bool
+ )
+ ast.Inspect(mainFunc.Body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ switch callee := calleeName(call); {
+ case forbidden[callee]:
+ offenders = append(offenders, fmt.Sprintf("%s at %s", callee, fset.Position(call.Pos())))
+ case callee == "backgroundServices":
+ // Matching the callee name alone would accept
+ // backgroundServices(nil) — which compiles, reuses nothing, and
+ // panics at startup. The argument must be the router's handler.
+ if len(call.Args) == 1 {
+ if arg, ok := call.Args[0].(*ast.Ident); ok && arg.Name == routerHandlerVar {
+ reusesRouter = true
+ return true
+ }
+ }
+ badReuse = append(badReuse, fmt.Sprintf("%s at %s", exprText(fset, call), fset.Position(call.Pos())))
+ case callee == "scheduler.AutopilotScheduleDispatchJob":
+ registersScheduler = true
+ }
+ return true
+ })
+
+ // Anti-vacuity: the scheduled-dispatch registration is what makes the
+ // unwired-service hazard reachable. If it moves out of main(), this test
+ // no longer covers the path it claims to and must fail rather than pass.
+ if !registersScheduler {
+ t.Fatalf("scheduler.AutopilotScheduleDispatchJob is no longer registered in main() — re-point this guard at wherever the schedule job is now wired")
+ }
+ if len(offenders) > 0 {
+ t.Errorf("main() constructs its own background services (%s); take them from the router via backgroundServices(%s) so EmptyClaim and the rest of the router wiring come along", strings.Join(offenders, ", "), routerHandlerVar)
+ }
+ if len(badReuse) > 0 {
+ t.Errorf("main() calls backgroundServices with something other than the router handler %q (%s); background workers must reuse the services the router finished wiring", routerHandlerVar, strings.Join(badReuse, ", "))
+ }
+ if !reusesRouter {
+ t.Errorf("main() no longer calls backgroundServices(%s); background workers must reuse the router-owned TaskService/AutopilotService", routerHandlerVar)
+ }
+}
+
+// routerHandlerIdent returns the name of the variable that receives the
+// *handler.Handler from NewRouterWithOptions (the `h` in `r, h := ...`), or ""
+// when that assignment is no longer recognizable.
+func routerHandlerIdent(body *ast.BlockStmt) string {
+ var name string
+ ast.Inspect(body, func(n ast.Node) bool {
+ assign, ok := n.(*ast.AssignStmt)
+ if !ok || len(assign.Rhs) != 1 || len(assign.Lhs) != 2 {
+ return true
+ }
+ call, ok := assign.Rhs[0].(*ast.CallExpr)
+ if !ok || calleeName(call) != "NewRouterWithOptions" {
+ return true
+ }
+ if ident, ok := assign.Lhs[1].(*ast.Ident); ok {
+ name = ident.Name
+ return false
+ }
+ return true
+ })
+ return name
+}
+
+// exprText renders an expression back to source for error messages.
+func exprText(fset *token.FileSet, expr ast.Expr) string {
+ var buf bytes.Buffer
+ if err := printer.Fprint(&buf, fset, expr); err != nil {
+ return "<unprintable expression>"
+ }
+ return buf.String()
+}
+
+// calleeName renders a call's target as "pkg.Func" or "Func" for matching.
+func calleeName(call *ast.CallExpr) string {
+ switch fn := call.Fun.(type) {
+ case *ast.Ident:
+ return fn.Name
+ case *ast.SelectorExpr:
+ if pkg, ok := fn.X.(*ast.Ident); ok {
+ return pkg.Name + "." + fn.Sel.Name
+ }
+ return fn.Sel.Name
+ }
+ return ""
+}
+
// TestNormalizeServerVersion covers the router-config wiring path (not just
// a hand-set handler.Config field): an unstamped "dev" build must not leak
// into /api/config's server_version, or the Help popover would render
diff --git a/server/internal/service/task_notify_test.go b/server/internal/service/task_notify_test.go
index 4655ac9030..e05147a75d 100644
--- a/server/internal/service/task_notify_test.go
+++ b/server/internal/service/task_notify_test.go
@@ -162,3 +162,57 @@ func TestNotifyTasksFinished_CoalescesByRuntime(t *testing.T) {
}
}
}
+
+// TestNotifyTaskEnqueued_UnwiredServiceCannotInvalidateClaimVerdict documents
+// why enqueue and claim must run through the SAME TaskService instance.
+//
+// EmptyClaimCache is nil-safe by design so a deployment without Redis degrades
+// to direct DB lookups. The cost of that convenience is that a TaskService
+// which never had EmptyClaim assigned fails silently instead of loudly: Bump
+// is a no-op while the daemon wakeup still fires. Pair that with a second,
+// fully wired TaskService serving claims and the runtime is woken for a task
+// it is then told does not exist — for up to EmptyClaimCacheTTL.
+//
+// This is the failure the process wiring in cmd/server avoids by handing
+// background workers the router's service (see
+// TestMainUsesRouterOwnedBackgroundServices). Asserting it here keeps the
+// reason legible from the cache's own package: if a future change makes the
+// unwired case impossible — e.g. EmptyClaim becomes a constructor argument —
+// this test should be deleted along with the hazard, not adjusted to fit.
+func TestNotifyTaskEnqueued_UnwiredServiceCannotInvalidateClaimVerdict(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ ctx := context.Background()
+
+ // The router's service: serves daemon claims, owns the cache.
+ claimSvc := &TaskService{EmptyClaim: NewEmptyClaimCache(rdb), Wakeup: &stubWakeup{}}
+ // A background service built without the router's post-construction
+ // wiring. Same wakeup notifier, no EmptyClaim.
+ enqueueWakeup := &stubWakeup{}
+ unwiredSvc := &TaskService{Wakeup: enqueueWakeup}
+
+ runtimeID := testUUID(18)
+ runtimeKey := util.UUIDToString(runtimeID)
+
+ // An idle runtime polled, found nothing, and cached that verdict.
+ claimSvc.EmptyClaim.MarkEmpty(ctx, runtimeKey, claimSvc.EmptyClaim.CurrentVersion(ctx, runtimeKey))
+ if !claimSvc.EmptyClaim.IsEmpty(ctx, runtimeKey) {
+ t.Fatal("precondition: claim path should see a cached empty verdict")
+ }
+
+ unwiredSvc.NotifyTaskEnqueued(ctx, db.AgentTaskQueue{ID: testUUID(19), RuntimeID: runtimeID})
+
+ if got := len(enqueueWakeup.calls); got != 1 {
+ t.Fatalf("expected the daemon wakeup to fire regardless of cache wiring, got %d calls", got)
+ }
+ // ClaimTaskForRuntime consults exactly this predicate before querying
+ // Postgres, so a surviving verdict means the woken claim returns nil.
+ if !claimSvc.EmptyClaim.IsEmpty(ctx, runtimeKey) {
+ t.Fatal("unexpected: an EmptyClaim-less service invalidated the verdict — the split-instance hazard this documents is gone, so delete this test")
+ }
+
+ // Same enqueue through the service that owns the cache: verdict dies.
+ claimSvc.NotifyTaskEnqueued(ctx, db.AgentTaskQueue{ID: testUUID(20), RuntimeID: runtimeID})
+ if claimSvc.EmptyClaim.IsEmpty(ctx, runtimeKey) {
+ t.Fatal("enqueue through the claim path's own service must invalidate the verdict")
+ }
+}