fix(wiki): release documents a stranded wiki queue holds in finalizing
Housekeeping skips any row that still has a durable wiki ingest op, with no age limit, so a wiki that can never run left its documents in "finalizing" forever: - A KB whose wiki was disabled, has no synthesis model, or whose model was deleted failed the trigger before claiming anything; after the retries the trigger was archived and the ops stayed. Treat these as terminal: drain the unclaimed ingest ops and release each document's wiki slot. Retract ops stay queued; rows a live batch holds are left to it. - A lost or archived trigger left the ops with nothing to wake their consumer until a restart. Housekeeping now re-arms one trigger per KB for rows held only by durable ops, at most once per stale threshold.main
parent
273db881c6
commit
af3ac25bc1
|
|
@ -366,6 +366,37 @@ func (r *taskPendingOpsRepository) DeleteByScope(ctx context.Context, scope, sco
|
|||
Delete(&types.TaskPendingOp{}).Error
|
||||
}
|
||||
|
||||
// DrainUnclaimed deletes the lane's op rows that no live batch holds and
|
||||
// returns the distinct dedup keys removed. One DELETE ... RETURNING keeps a
|
||||
// row claimed mid-drain out of both the delete and the result.
|
||||
func (r *taskPendingOpsRepository) DrainUnclaimed(
|
||||
ctx context.Context, taskType, scope, scopeID, op string, staleBefore time.Time,
|
||||
) ([]string, error) {
|
||||
if taskType == "" || scope == "" || scopeID == "" || op == "" {
|
||||
return nil, errors.New("task pending ops: task_type, scope, scope_id and op are required")
|
||||
}
|
||||
var removed []string
|
||||
if err := r.db.WithContext(ctx).Raw(
|
||||
`DELETE FROM task_pending_ops
|
||||
WHERE task_type = ? AND scope = ? AND scope_id = ? AND op = ?
|
||||
AND (claimed_at IS NULL OR claimed_at < ?)
|
||||
RETURNING dedup_key`,
|
||||
taskType, scope, scopeID, op, staleBefore,
|
||||
).Scan(&removed).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys := make([]string, 0, len(removed))
|
||||
seen := make(map[string]struct{}, len(removed))
|
||||
for _, key := range removed {
|
||||
if _, ok := seen[key]; ok || key == "" {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// IncrFailCount atomically bumps fail_count for one row and returns the
|
||||
// new value. We use UPDATE ... RETURNING so the read+write happens in
|
||||
// one round trip and races between concurrent IncrFailCount callers
|
||||
|
|
|
|||
|
|
@ -919,3 +919,40 @@ func TestTaskDeadLetter_DeleteByID_IsIdempotent(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
assert.Len(t, rows, 0)
|
||||
}
|
||||
|
||||
// DrainUnclaimed removes only the lane's matching op rows that no live batch
|
||||
// holds, and reports each document once even when it has several rows.
|
||||
func TestTaskPendingOps_DrainUnclaimedSparesLiveClaimsAndOtherOps(t *testing.T) {
|
||||
db := setupTaskQueueTestDB(t)
|
||||
repo := NewTaskPendingOpsRepository(db)
|
||||
drainer, ok := repo.(interfaces.TaskPendingOpsDrainer)
|
||||
require.True(t, ok)
|
||||
ctx := context.Background()
|
||||
lane := func(scopeID, op, dedup string) *types.TaskPendingOp {
|
||||
return makePendingOp(types.TypeWikiIngest, types.TaskScopeKnowledgeBase, scopeID, op, dedup, []byte(`{}`))
|
||||
}
|
||||
for _, op := range []*types.TaskPendingOp{
|
||||
lane("kb-1", "ingest", "k-unclaimed"),
|
||||
lane("kb-1", "ingest", "k-unclaimed"),
|
||||
lane("kb-1", "ingest", "k-stale"),
|
||||
lane("kb-1", "ingest", "k-live"),
|
||||
lane("kb-1", "retract", "k-retract"),
|
||||
lane("kb-2", "ingest", "k-other-kb"),
|
||||
} {
|
||||
require.NoError(t, repo.Enqueue(ctx, op))
|
||||
}
|
||||
staleBefore := time.Now().Add(-time.Hour)
|
||||
require.NoError(t, db.Model(&types.TaskPendingOp{}).Where("dedup_key = ?", "k-stale").
|
||||
Update("claimed_at", staleBefore.Add(-time.Minute)).Error)
|
||||
require.NoError(t, db.Model(&types.TaskPendingOp{}).Where("dedup_key = ?", "k-live").
|
||||
Update("claimed_at", time.Now()).Error)
|
||||
|
||||
keys, err := drainer.DrainUnclaimed(ctx, types.TypeWikiIngest, types.TaskScopeKnowledgeBase, "kb-1",
|
||||
"ingest", staleBefore)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, []string{"k-unclaimed", "k-stale"}, keys)
|
||||
var left []string
|
||||
require.NoError(t, db.Model(&types.TaskPendingOp{}).Order("dedup_key").Pluck("dedup_key", &left).Error)
|
||||
assert.Equal(t, []string{"k-live", "k-other-kb", "k-retract"}, left)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,21 +46,29 @@ type HousekeepingService struct {
|
|||
// Durable Wiki ownership in task_pending_ops is always probed through db,
|
||||
// so the sweep never falls back to the span/updated_at heuristics alone.
|
||||
inspector interfaces.TaskInspector
|
||||
// task re-arms the wiki trigger for rows kept alive only by a durable
|
||||
// Wiki op, which a lost trigger would otherwise strand. nil disables it.
|
||||
task interfaces.TaskEnqueuer
|
||||
|
||||
mu sync.Mutex
|
||||
started bool
|
||||
|
||||
kickMu sync.Mutex
|
||||
wikiKicks map[string]time.Time
|
||||
}
|
||||
|
||||
// NewHousekeepingService constructs a HousekeepingService. It does NOT start
|
||||
// the cron — call Start in the application bootstrap so a misconfigured
|
||||
// cron schedule cannot prevent the rest of the service from coming up.
|
||||
func NewHousekeepingService(
|
||||
db *gorm.DB, cfg *config.Config, inspector interfaces.TaskInspector,
|
||||
db *gorm.DB, cfg *config.Config, inspector interfaces.TaskInspector, task interfaces.TaskEnqueuer,
|
||||
) *HousekeepingService {
|
||||
return &HousekeepingService{
|
||||
db: db,
|
||||
cfg: cfg,
|
||||
inspector: inspector,
|
||||
task: task,
|
||||
wikiKicks: make(map[string]time.Time),
|
||||
cron: cron.New(cron.WithSeconds(), cron.WithChain(
|
||||
cron.Recover(cron.DefaultLogger),
|
||||
)),
|
||||
|
|
@ -156,7 +164,8 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
|
|||
// positive users hit under heavy upload bursts. Drop any candidate
|
||||
// that still has a queued/active task referencing it; only rows with
|
||||
// nothing left in the queue are treated as genuinely orphaned.
|
||||
stuck, queueSkipped := h.filterOutQueued(ctx, stuck)
|
||||
stuck, queueSkipped, wikiHeld := h.filterOutQueued(ctx, stuck)
|
||||
h.rearmWikiTriggers(ctx, wikiHeld, threshold)
|
||||
|
||||
if len(stuck) > 0 {
|
||||
stuckIDs := make([]string, 0, len(stuck))
|
||||
|
|
@ -348,9 +357,9 @@ func (h *HousekeepingService) filterByLastSpanActivity(ctx context.Context, cand
|
|||
// by the user, while waiting one more interval is.
|
||||
func (h *HousekeepingService) filterOutQueued(
|
||||
ctx context.Context, candidates []types.Knowledge,
|
||||
) (kept []types.Knowledge, skipped int) {
|
||||
) (kept []types.Knowledge, skipped int, wikiHeld []types.Knowledge) {
|
||||
if len(candidates) == 0 {
|
||||
return candidates, 0
|
||||
return candidates, 0, nil
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(candidates))
|
||||
|
|
@ -367,7 +376,7 @@ func (h *HousekeepingService) filterOutQueued(
|
|||
logger.Warnf(ctx,
|
||||
"[Housekeeping] durable queue probe failed: %v (deferring %d candidate(s))",
|
||||
err, len(candidates))
|
||||
return candidates[:0], len(candidates)
|
||||
return candidates[:0], len(candidates), nil
|
||||
}
|
||||
durable := make(map[string]struct{}, len(durableIDs))
|
||||
for _, id := range durableIDs {
|
||||
|
|
@ -378,6 +387,7 @@ func (h *HousekeepingService) filterOutQueued(
|
|||
for _, k := range candidates {
|
||||
if _, ok := durable[k.ID]; ok {
|
||||
skipped++
|
||||
wikiHeld = append(wikiHeld, k)
|
||||
continue
|
||||
}
|
||||
if h.inspector == nil {
|
||||
|
|
@ -397,7 +407,46 @@ func (h *HousekeepingService) filterOutQueued(
|
|||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, skipped
|
||||
return out, skipped, wikiHeld
|
||||
}
|
||||
|
||||
// rearmWikiTriggers enqueues one wiki ingest trigger per KB whose stale rows
|
||||
// are held only by durable Wiki ops. The trigger is ephemeral: once lost (or
|
||||
// archived after its retries), nothing wakes the consumer until a restart or
|
||||
// another upload, and the row sits in "finalizing" indefinitely. A KB is
|
||||
// re-armed at most once per threshold so a genuine backlog is not flooded.
|
||||
func (h *HousekeepingService) rearmWikiTriggers(
|
||||
ctx context.Context, held []types.Knowledge, threshold time.Duration,
|
||||
) {
|
||||
if h.task == nil || len(held) == 0 {
|
||||
return
|
||||
}
|
||||
h.kickMu.Lock()
|
||||
defer h.kickMu.Unlock()
|
||||
now := time.Now()
|
||||
for kbID, last := range h.wikiKicks {
|
||||
if now.Sub(last) >= threshold {
|
||||
delete(h.wikiKicks, kbID)
|
||||
}
|
||||
}
|
||||
rearmed := 0
|
||||
for _, k := range held {
|
||||
if k.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
if _, recent := h.wikiKicks[k.KnowledgeBaseID]; recent {
|
||||
continue
|
||||
}
|
||||
if err := enqueueWikiIngestTrigger(ctx, h.task, k.TenantID, k.KnowledgeBaseID); err != nil {
|
||||
logger.Warnf(ctx, "[Housekeeping] re-arm wiki trigger for KB %s failed: %v", k.KnowledgeBaseID, err)
|
||||
continue
|
||||
}
|
||||
h.wikiKicks[k.KnowledgeBaseID] = now
|
||||
rearmed++
|
||||
}
|
||||
if rearmed > 0 {
|
||||
logger.Infof(ctx, "[Housekeeping] re-armed wiki ingest trigger for %d knowledge base(s)", rearmed)
|
||||
}
|
||||
}
|
||||
|
||||
// parseHeartbeatTime accepts the timestamp formats Postgres and SQLite
|
||||
|
|
|
|||
|
|
@ -186,7 +186,7 @@ func newHousekeepingSvcWithInspector(db *gorm.DB, inspector interfaces.TaskInspe
|
|||
// default of 2h+10min is just a constant scale factor.
|
||||
DocumentProcessTimeout: 1 * time.Hour,
|
||||
}}
|
||||
return NewHousekeepingService(db, cfg, inspector)
|
||||
return NewHousekeepingService(db, cfg, inspector, nil)
|
||||
}
|
||||
|
||||
// TestHousekeeping_RecoversAbandoned exercises the happy path: a
|
||||
|
|
|
|||
|
|
@ -694,6 +694,30 @@ func (s *wikiIngestService) clearDeletedKnowledgeBasePendingOps(ctx context.Cont
|
|||
return cleaner.DeleteByScope(cleanupCtx, types.TaskScopeKnowledgeBase, kbID)
|
||||
}
|
||||
|
||||
// releaseIngestForUnavailableWiki drops the KB's queued ingest ops when the
|
||||
// wiki cannot run for a reason retries will not fix, and releases each
|
||||
// document's wiki slot so it leaves "finalizing". Retract ops stay queued for
|
||||
// when the wiki is usable again. Rows held by a live batch are left to it.
|
||||
func (s *wikiIngestService) releaseIngestForUnavailableWiki(ctx context.Context, kbID, reason string) error {
|
||||
drainer, ok := s.pendingRepo.(interfaces.TaskPendingOpsDrainer)
|
||||
if !ok {
|
||||
return fmt.Errorf("wiki ingest: KB %s unavailable (%s)", kbID, reason)
|
||||
}
|
||||
cleanupCtx, cancel := wikiIngestCleanupContext(ctx)
|
||||
defer cancel()
|
||||
knowledgeIDs, err := drainer.DrainUnclaimed(cleanupCtx, wikiTaskType, wikiTaskScope, kbID,
|
||||
WikiOpIngest, time.Now().Add(-wikiClaimStaleAfter))
|
||||
if err != nil {
|
||||
return fmt.Errorf("wiki ingest: KB %s unavailable (%s), drain pending ingest: %w", kbID, reason, err)
|
||||
}
|
||||
for _, knowledgeID := range knowledgeIDs {
|
||||
s.finalizeWikiSubtask(ctx, knowledgeID)
|
||||
}
|
||||
logger.Warnf(ctx, "wiki ingest: KB %s unavailable (%s), dropped pending ingest for %d document(s)",
|
||||
kbID, reason, len(knowledgeIDs))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *wikiIngestService) enqueueFinalizeRow(ctx context.Context, op *types.TaskPendingOp) bool {
|
||||
accepted, err := enqueueWikiPendingOp(ctx, s.pendingRepo, op)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -292,7 +292,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
}
|
||||
if !kb.IsWikiEnabled() {
|
||||
exitStatus = "kb_not_wiki_enabled"
|
||||
return fmt.Errorf("wiki ingest: KB %s is not wiki type", kb.ID)
|
||||
return s.releaseIngestForUnavailableWiki(ctx, kb.ID, "wiki disabled")
|
||||
}
|
||||
|
||||
var synthesisModelID string
|
||||
|
|
@ -304,9 +304,13 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
}
|
||||
if synthesisModelID == "" {
|
||||
exitStatus = "missing_synthesis_model"
|
||||
return fmt.Errorf("wiki ingest: no synthesis model configured for KB %s", kb.ID)
|
||||
return s.releaseIngestForUnavailableWiki(ctx, kb.ID, "no synthesis model configured")
|
||||
}
|
||||
chatModel, err := s.modelService.GetChatModel(ctx, synthesisModelID)
|
||||
if errors.Is(err, ErrModelNotFound) {
|
||||
exitStatus = "synthesis_model_not_found"
|
||||
return s.releaseIngestForUnavailableWiki(ctx, kb.ID, "synthesis model "+synthesisModelID+" not found")
|
||||
}
|
||||
if err != nil {
|
||||
exitStatus = "get_chat_model_failed"
|
||||
return fmt.Errorf("wiki ingest: get chat model: %w", err)
|
||||
|
|
|
|||
|
|
@ -95,6 +95,16 @@ type TaskPendingOpsScopeCleaner interface {
|
|||
DeleteByScope(ctx context.Context, scope, scopeID string) error
|
||||
}
|
||||
|
||||
// TaskPendingOpsDrainer is an optional extension for consumers that must give
|
||||
// up on a queue lane: DrainUnclaimed deletes the lane's rows for op that no
|
||||
// live batch holds (unclaimed, or claimed before staleBefore) and returns the
|
||||
// distinct dedup keys it removed so the caller can release what they owned.
|
||||
type TaskPendingOpsDrainer interface {
|
||||
DrainUnclaimed(
|
||||
ctx context.Context, taskType, scope, scopeID, op string, staleBefore time.Time,
|
||||
) ([]string, error)
|
||||
}
|
||||
|
||||
// TaskPendingOpsKnowledgeBaseGuard atomically persists a KB-scoped operation
|
||||
// only while its knowledge base is still active. Implementations must
|
||||
// serialize the active-KB check with soft deletion so a detached worker cannot
|
||||
|
|
|
|||
Loading…
Reference in New Issue