feat(system): add failed-task inspection and manual retry for runtime queues

Give system admins visibility into asynq tasks that exhausted retries, with safe retry/delete actions and operator-facing UI in Runtime Queues.
This commit is contained in:
wizardchen
2026-07-14 12:14:19 +08:00
committed by lyingbug
parent f7ec759cc6
commit 6171962e56
15 changed files with 1167 additions and 17 deletions
+161
View File
@@ -1593,6 +1593,167 @@ func (h *SystemHandler) GetRuntimeQueues(c *gin.Context) {
c.JSON(http.StatusOK, resp)
}
// RuntimeFailedTasksResponse is a page of tasks that exhausted automatic
// retries. Available=false is used by Lite mode, where there is no durable
// queue backend to inspect or mutate.
type RuntimeFailedTasksResponse struct {
Available bool `json:"available"`
Tasks []types.FailedTaskInfo `json:"tasks"`
Page int `json:"page"`
PageSize int `json:"page_size"`
HasMore bool `json:"has_more"`
}
func isKnownRuntimeQueue(name string) bool {
for _, definition := range types.QueueDefinitions() {
if definition.Name == name {
return true
}
}
return false
}
func runtimeFailedTaskPage(c *gin.Context) (int, int) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
if pageSize > 100 {
pageSize = 100
}
return page, pageSize
}
// ListRuntimeFailedTasks godoc
// @Summary List tasks that stopped after exhausting automatic retries
// @Tags System Admin
// @Produce json
// @Param queue path string true "Queue name"
// @Success 200 {object} RuntimeFailedTasksResponse
// @Router /system/admin/runtime/queues/{queue}/failed-tasks [get]
func (h *SystemHandler) ListRuntimeFailedTasks(c *gin.Context) {
queue := c.Param("queue")
if !isKnownRuntimeQueue(queue) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Unknown task queue"})
return
}
page, pageSize := runtimeFailedTaskPage(c)
inspector, ok := h.taskInspector.(interfaces.FailedTaskInspector)
if !ok {
c.JSON(http.StatusOK, RuntimeFailedTasksResponse{
Available: false,
Tasks: []types.FailedTaskInfo{},
Page: page,
PageSize: pageSize,
})
return
}
tasks, supported, err := inspector.ListFailedTasks(c.Request.Context(), queue, page, pageSize)
if err != nil {
logger.Errorf(c.Request.Context(), "list failed queue tasks queue=%s: %v", queue, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list stopped tasks"})
return
}
if tasks == nil {
tasks = []types.FailedTaskInfo{}
}
c.JSON(http.StatusOK, RuntimeFailedTasksResponse{
Available: supported,
Tasks: tasks,
Page: page,
PageSize: pageSize,
HasMore: len(tasks) == pageSize,
})
}
func (h *SystemHandler) emitQueueTaskAudit(
ctx context.Context,
action types.AuditAction,
queue, taskID string,
) {
if h.auditSvc == nil {
return
}
actorID, _ := types.UserIDFromContext(ctx)
details, _ := json.Marshal(map[string]string{"queue": queue, "task_id": taskID})
_ = h.auditSvc.Log(ctx, &types.AuditLog{
TenantID: 0,
ActorUserID: actorID,
ActorRole: "system_admin",
Action: action,
TargetType: "queue_task",
TargetID: taskID,
Outcome: types.AuditOutcomeSuccess,
Details: types.JSON(details),
})
}
func runtimeFailedTaskParams(c *gin.Context) (string, string, bool) {
queue := c.Param("queue")
taskID := c.Param("task_id")
if !isKnownRuntimeQueue(queue) || taskID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid queue or task ID"})
return "", "", false
}
return queue, taskID, true
}
// RetryRuntimeFailedTask schedules one stopped task for one immediate manual
// run. It does not reset the automatic retry counter.
func (h *SystemHandler) RetryRuntimeFailedTask(c *gin.Context) {
queue, taskID, ok := runtimeFailedTaskParams(c)
if !ok {
return
}
inspector, supported := h.taskInspector.(interfaces.FailedTaskInspector)
if !supported {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
return
}
available, err := inspector.RetryFailedTask(c.Request.Context(), queue, taskID)
if !available {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
return
}
if err != nil {
logger.Errorf(c.Request.Context(), "retry failed queue task queue=%s task=%s: %v", queue, taskID, err)
c.JSON(http.StatusConflict, gin.H{"error": "Task is no longer available for retry"})
return
}
h.emitQueueTaskAudit(c.Request.Context(), types.AuditActionSystemQueueTaskRetried, queue, taskID)
c.JSON(http.StatusOK, gin.H{"success": true})
}
// DeleteRuntimeFailedTask removes one stopped task from the queue archive. It
// does not rerun the task or change its related business object.
func (h *SystemHandler) DeleteRuntimeFailedTask(c *gin.Context) {
queue, taskID, ok := runtimeFailedTaskParams(c)
if !ok {
return
}
inspector, supported := h.taskInspector.(interfaces.FailedTaskInspector)
if !supported {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
return
}
available, err := inspector.DeleteFailedTask(c.Request.Context(), queue, taskID)
if !available {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
return
}
if err != nil {
logger.Errorf(c.Request.Context(), "delete failed queue task queue=%s task=%s: %v", queue, taskID, err)
c.JSON(http.StatusConflict, gin.H{"error": "Task is no longer available for deletion"})
return
}
h.emitQueueTaskAudit(c.Request.Context(), types.AuditActionSystemQueueTaskDeleted, queue, taskID)
c.JSON(http.StatusOK, gin.H{"success": true})
}
func (h *SystemHandler) ListSystemSettings(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
rows, err := h.systemSettingSvc.List(ctx)
+108
View File
@@ -75,6 +75,36 @@ func (runtimeTestInspector) WorkerServerStats(context.Context) ([]types.WorkerSe
}, true, nil
}
type runtimeFailedTestInspector struct {
runtimeTestInspector
tasks []types.FailedTaskInfo
retriedTask string
deletedTask string
mutatedQueue string
}
func (r *runtimeFailedTestInspector) ListFailedTasks(
context.Context, string, int, int,
) ([]types.FailedTaskInfo, bool, error) {
return r.tasks, true, nil
}
func (r *runtimeFailedTestInspector) RetryFailedTask(
_ context.Context, queue, taskID string,
) (bool, error) {
r.mutatedQueue = queue
r.retriedTask = taskID
return true, nil
}
func (r *runtimeFailedTestInspector) DeleteFailedTask(
_ context.Context, queue, taskID string,
) (bool, error) {
r.mutatedQueue = queue
r.deletedTask = taskID
return true, nil
}
func TestGetRuntimeQueuesReportsIsolatedPoolCapacity(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := &SystemHandler{
@@ -155,3 +185,81 @@ func TestGetRuntimeQueuesFallsBackFromInvalidHistoricalConcurrency(t *testing.T)
}
}
}
func TestListRuntimeFailedTasksReturnsSafeTaskDetails(t *testing.T) {
gin.SetMode(gin.TestMode)
inspector := &runtimeFailedTestInspector{tasks: []types.FailedTaskInfo{{
ID: "task-1",
Queue: types.QueueDefault,
Type: types.TypeDocumentProcess,
LastError: "model unavailable",
Retried: 5,
MaxRetry: 5,
KnowledgeBaseID: "kb-1",
KnowledgeID: "knowledge-1",
}}}
handler := &SystemHandler{taskInspector: inspector}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "queue", Value: types.QueueDefault}}
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/v1/system/admin/runtime/queues/default/failed-tasks", nil)
handler.ListRuntimeFailedTasks(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String())
}
var response RuntimeFailedTasksResponse
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatalf("decode response: %v", err)
}
if !response.Available || len(response.Tasks) != 1 {
t.Fatalf("unexpected response: %+v", response)
}
if response.Tasks[0].KnowledgeID != "knowledge-1" || response.Tasks[0].LastError != "model unavailable" {
t.Fatalf("task details missing: %+v", response.Tasks[0])
}
}
func TestRuntimeFailedTaskMutationsDelegateToInspector(t *testing.T) {
gin.SetMode(gin.TestMode)
inspector := &runtimeFailedTestInspector{}
handler := &SystemHandler{taskInspector: inspector}
retryRecorder := httptest.NewRecorder()
retryCtx, _ := gin.CreateTestContext(retryRecorder)
retryCtx.Params = gin.Params{
{Key: "queue", Value: types.QueueDefault},
{Key: "task_id", Value: "task-1"},
}
retryCtx.Request = httptest.NewRequest(http.MethodPost, "/retry", nil)
handler.RetryRuntimeFailedTask(retryCtx)
if retryRecorder.Code != http.StatusOK || inspector.retriedTask != "task-1" {
t.Fatalf("retry failed: status=%d inspector=%+v", retryRecorder.Code, inspector)
}
deleteRecorder := httptest.NewRecorder()
deleteCtx, _ := gin.CreateTestContext(deleteRecorder)
deleteCtx.Params = gin.Params{
{Key: "queue", Value: types.QueueDefault},
{Key: "task_id", Value: "task-2"},
}
deleteCtx.Request = httptest.NewRequest(http.MethodDelete, "/task-2", nil)
handler.DeleteRuntimeFailedTask(deleteCtx)
if deleteRecorder.Code != http.StatusOK || inspector.deletedTask != "task-2" {
t.Fatalf("delete failed: status=%d inspector=%+v", deleteRecorder.Code, inspector)
}
}
func TestListRuntimeFailedTasksRejectsUnknownQueue(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := &SystemHandler{taskInspector: &runtimeFailedTestInspector{}}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "queue", Value: "unknown"}}
ctx.Request = httptest.NewRequest(http.MethodGet, "/failed-tasks", nil)
handler.ListRuntimeFailedTasks(ctx)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusBadRequest)
}
}
+3
View File
@@ -904,6 +904,9 @@ func RegisterSystemAdminRoutes(
// SystemAdmin runtime dashboard. Returns available=false in Lite
// mode (no Redis) so the UI degrades gracefully.
adminRoutes.GET("/runtime/queues", handler.GetRuntimeQueues)
adminRoutes.GET("/runtime/queues/:queue/failed-tasks", handler.ListRuntimeFailedTasks)
adminRoutes.POST("/runtime/queues/:queue/failed-tasks/:task_id/retry", handler.RetryRuntimeFailedTask)
adminRoutes.DELETE("/runtime/queues/:queue/failed-tasks/:task_id", handler.DeleteRuntimeFailedTask)
// Bulk action — write the current default-quota setting onto
// every existing tenant. Lives under /tenants instead of
+104
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -45,6 +46,14 @@ type knowledgeIDProbe struct {
KnowledgeID string `json:"knowledge_id,omitempty"`
}
type failedTaskPayloadProbe struct {
TenantID uint64 `json:"tenant_id,omitempty"`
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
KBID string `json:"kb_id,omitempty"`
KnowledgeID string `json:"knowledge_id,omitempty"`
TaskID string `json:"task_id,omitempty"`
}
// queuesScanned is the fixed set of queue names this codebase enqueues
// into. Kept tight on purpose — we never scan user-defined queues.
// MUST include every queue any cancelable task type can land in; the
@@ -183,6 +192,101 @@ func (a *asynqTaskInspector) QueueStats(
return stats, true, nil
}
// ListFailedTasks returns archived tasks newest-first. Only routing metadata is
// projected from the payload so the SystemAdmin dashboard never exposes raw
// document content or connector secrets.
func (a *asynqTaskInspector) ListFailedTasks(
ctx context.Context,
queue string,
page, pageSize int,
) ([]types.FailedTaskInfo, bool, error) {
if a == nil || a.inspector == nil {
return nil, false, nil
}
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
if pageSize > 100 {
pageSize = 100
}
tasks, err := a.inspector.ListArchivedTasks(queue, asynq.Page(page), asynq.PageSize(pageSize))
if errors.Is(err, asynq.ErrQueueNotFound) {
return []types.FailedTaskInfo{}, true, nil
}
if err != nil {
return nil, true, err
}
result := make([]types.FailedTaskInfo, 0, len(tasks))
for _, task := range tasks {
if task == nil {
continue
}
probe := failedTaskPayloadProbe{}
_ = json.Unmarshal(task.Payload, &probe)
kbID := probe.KnowledgeBaseID
if kbID == "" {
kbID = probe.KBID
}
result = append(result, types.FailedTaskInfo{
ID: task.ID,
Queue: task.Queue,
Type: task.Type,
LastError: task.LastErr,
LastFailedAt: task.LastFailedAt,
Retried: task.Retried,
MaxRetry: task.MaxRetry,
TenantID: probe.TenantID,
KnowledgeBaseID: kbID,
KnowledgeID: probe.KnowledgeID,
TaskID: probe.TaskID,
})
}
return result, true, nil
}
// RetryFailedTask schedules one archived task for one immediate manual run.
// Asynq deliberately preserves the retry counter, so a repeated failure is
// archived again instead of silently starting a fresh automatic retry cycle.
func (a *asynqTaskInspector) RetryFailedTask(
ctx context.Context,
queue, taskID string,
) (bool, error) {
if a == nil || a.inspector == nil {
return false, nil
}
if err := a.ensureTaskArchived(queue, taskID); err != nil {
return true, err
}
return true, a.inspector.RunTask(queue, taskID)
}
func (a *asynqTaskInspector) DeleteFailedTask(
ctx context.Context,
queue, taskID string,
) (bool, error) {
if a == nil || a.inspector == nil {
return false, nil
}
if err := a.ensureTaskArchived(queue, taskID); err != nil {
return true, err
}
return true, a.inspector.DeleteTask(queue, taskID)
}
func (a *asynqTaskInspector) ensureTaskArchived(queue, taskID string) error {
task, err := a.inspector.GetTaskInfo(queue, taskID)
if err != nil {
return err
}
if task.State != asynq.TaskStateArchived {
return fmt.Errorf("task %s in queue %s is no longer archived", taskID, queue)
}
return nil
}
func (a *asynqTaskInspector) WorkerServerStats(
ctx context.Context,
) ([]types.WorkerServerStat, bool, error) {
+6
View File
@@ -121,6 +121,12 @@ const (
// another user's local password. Details identify the target and record
// session revocation, but never contain the old or new password.
AuditActionSystemUserPasswordReset AuditAction = "system.user_password_reset"
// Runtime queue mutations are privileged SystemAdmin actions. Retrying an
// archived task can repeat its original side effects; deleting one removes
// the Redis failure record. Both must leave a platform audit trail.
AuditActionSystemQueueTaskRetried AuditAction = "system.queue_task_retried"
AuditActionSystemQueueTaskDeleted AuditAction = "system.queue_task_deleted"
)
// AuditOutcome distinguishes successful mutations from middleware-level
+8
View File
@@ -38,6 +38,8 @@ func TestAuditAction_DotNamespaceConvention(t *testing.T) {
AuditActionSystemAdminPromoted,
AuditActionSystemAdminRevoked,
AuditActionSystemUserPasswordReset,
AuditActionSystemQueueTaskRetried,
AuditActionSystemQueueTaskDeleted,
}
for _, a := range all {
s := string(a)
@@ -120,6 +122,8 @@ func TestAuditAction_NoCollisionsAcrossNamespaces(t *testing.T) {
register("AuditActionSystemAdminPromoted", AuditActionSystemAdminPromoted)
register("AuditActionSystemAdminRevoked", AuditActionSystemAdminRevoked)
register("AuditActionSystemUserPasswordReset", AuditActionSystemUserPasswordReset)
register("AuditActionSystemQueueTaskRetried", AuditActionSystemQueueTaskRetried)
register("AuditActionSystemQueueTaskDeleted", AuditActionSystemQueueTaskDeleted)
}
// TestAuditAction_SystemNamespacePrefix pins the system.* actions
@@ -134,6 +138,8 @@ func TestAuditAction_SystemNamespacePrefix(t *testing.T) {
AuditActionSystemAdminPromoted,
AuditActionSystemAdminRevoked,
AuditActionSystemUserPasswordReset,
AuditActionSystemQueueTaskRetried,
AuditActionSystemQueueTaskDeleted,
}
for _, a := range cases {
assert.True(t,
@@ -156,6 +162,8 @@ func TestAuditAction_SystemWireValues(t *testing.T) {
{AuditActionSystemAdminPromoted, "system.admin_promoted"},
{AuditActionSystemAdminRevoked, "system.admin_revoked"},
{AuditActionSystemUserPasswordReset, "system.user_password_reset"},
{AuditActionSystemQueueTaskRetried, "system.queue_task_retried"},
{AuditActionSystemQueueTaskDeleted, "system.queue_task_deleted"},
}
for _, c := range cases {
assert.Equal(t, c.wire, string(c.constant))
+21
View File
@@ -0,0 +1,21 @@
package types
import "time"
// FailedTaskInfo is the operator-facing projection of an asynq task that
// exhausted its automatic retry budget. Payloads are intentionally not
// exposed by the SystemAdmin API: they may contain document content or
// connector credentials. Only stable routing identifiers are copied out.
type FailedTaskInfo struct {
ID string `json:"id"`
Queue string `json:"queue"`
Type string `json:"type"`
LastError string `json:"last_error"`
LastFailedAt time.Time `json:"last_failed_at"`
Retried int `json:"retried"`
MaxRetry int `json:"max_retry"`
TenantID uint64 `json:"tenant_id,omitempty"`
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
KnowledgeID string `json:"knowledge_id,omitempty"`
TaskID string `json:"task_id,omitempty"`
}
@@ -63,3 +63,17 @@ type TaskInspector interface {
// capacity and busy workers for each configured pool.
WorkerServerStats(ctx context.Context) (stats []types.WorkerServerStat, supported bool, err error)
}
// FailedTaskInspector is the optional operator surface implemented by queue
// backends that retain tasks after their automatic retry budget is exhausted.
// It is separate from TaskInspector so Lite-mode and test implementations that
// only support cancellation/metrics do not need to pretend failed tasks exist.
type FailedTaskInspector interface {
ListFailedTasks(
ctx context.Context,
queue string,
page, pageSize int,
) (tasks []types.FailedTaskInfo, supported bool, err error)
RetryFailedTask(ctx context.Context, queue, taskID string) (supported bool, err error)
DeleteFailedTask(ctx context.Context, queue, taskID string) (supported bool, err error)
}