Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(automation): prevent premature SQLite automation claims (#4501)
LuckVde93739625e0d
diff --git a/internal/application/service/automation_scheduler.go b/internal/application/service/automation_scheduler.goindex c248c2ff2..94ec6448e 100644--- a/internal/application/service/automation_scheduler.go+++ b/internal/application/service/automation_scheduler.go@@ -48,7 +48,10 @@ func (s *AutomationService) tick(ctx context.Context) {logger.Errorf(ctx, "Automation scheduler panicked: %v", r)}}()- now := s.now()+ // The clock is normalized to UTC: next_run_at is persisted as UTC, and+ // SQLite compares DATETIME as text, so a zoned now (e.g. +08:00) would+ // order future tasks as due.+ now := s.now().UTC()steps := []struct {name stringrun func(context.Context, time.Time) error@@ -94,6 +97,11 @@ func (s *AutomationService) claim(ctx context.Context, a *types.Automation, nowreturn s.pause(ctx, a, "the trigger is no longer valid: "+err.Error())}dueAt := a.NextRunAt.UTC()+ // Never claim a task before its time, whatever the query matched: the+ // stored text may compare as due while the instant is still future.+ if dueAt.After(now) {+ return nil+ }next := sched.Next(now)kind := types.AutomationRunScheduleif now.Sub(dueAt) > s.misfireGrace() {@@ -120,10 +128,13 @@ func (s *AutomationService) claim(ctx context.Context, a *types.Automation, now} else if reason != "" {run.Status, run.Error, run.FinishedAt = types.AutomationRunSkipped, reason, &now}- if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(run).Error; err != nil {- return err+ ins := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(run)+ if ins.Error != nil {+ return ins.Error}- queued = run.Status == types.AutomationRunQueued+ // A conflicting slot inserted nothing; waking on it would hot-loop+ // the scheduler without any new run to execute.+ queued = ins.RowsAffected > 0 && run.Status == types.AutomationRunQueuedreturn nil})if err == nil && queued {diff --git a/internal/application/service/automation_scheduler_timezone_test.go b/internal/application/service/automation_scheduler_timezone_test.gonew file mode 100644index 000000000..94ad86bd5--- /dev/null+++ b/internal/application/service/automation_scheduler_timezone_test.go@@ -0,0 +1,116 @@+package service++import (+ "context"+ "testing"+ "time"++ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/internal/types"+)++// utc8 stands in for a scheduler process running with its local clock in+// UTC+08 (e.g. TZ=Asia/Shanghai): time.Now there carries a +08:00 offset.+var utc8 = time.FixedZone("UTC+08", 8*3600)++func onceTrigger(at time.Time) *types.AutomationTrigger {+ return &types.AutomationTrigger{Type: types.AutomationTriggerOnce, At: at.Format(time.RFC3339), Timezone: "UTC"}+}++// The scheduler clock shows a +08:00 wall time while next_run_at is stored+// as UTC. One second before the real due instant, the raw text comparison+// next_run_at <= now still matches, so the task must not be claimed.+func TestAutomationTickDoesNotClaimFutureTaskInNonUTCClock(t *testing.T) {+ f := newAutomationFixture(t)+ due := f.now.Add(time.Hour)+ a := f.create(t, types.AutomationPatch{Trigger: onceTrigger(due)})+ require.Equal(t, due, a.NextRunAt.UTC())++ f.now = due.Add(-time.Second).In(utc8)+ f.svc.tick(context.Background())++ require.Empty(t, f.runs(t, a.ID))+ reloaded := f.reload(t, a.ID)+ require.True(t, reloaded.Enabled)+ require.NotNil(t, reloaded.NextRunAt)+ require.Equal(t, due, reloaded.NextRunAt.UTC())+ require.Equal(t, int64(0), reloaded.Version)+ select {+ case <-f.svc.wake:+ t.Fatal("a future task woke the scheduler")+ default:+ }+}++// claim must refuse a due time in the future even when the query let it+// through, whatever offset the caller's clock carried.+func TestAutomationClaimRejectsFutureDueAt(t *testing.T) {+ f := newAutomationFixture(t)+ due := f.now.Add(time.Minute)+ a := f.create(t, types.AutomationPatch{Trigger: onceTrigger(due)})++ require.NoError(t, f.svc.claimDue(context.Background(), due.Add(-59*time.Second).In(utc8)))++ require.Empty(t, f.runs(t, a.ID))+ require.Equal(t, int64(0), f.reload(t, a.ID).Version)+}++// A unique slot (automation, scheduled_at, trigger_kind) that already holds+// a run must not be reported as a fresh queued run: no wake, no extra rows,+// however often the claim replays.+func TestAutomationDuplicateSlotDoesNotWake(t *testing.T) {+ f := newAutomationFixture(t)+ due := f.now.Add(time.Minute)+ a := f.create(t, types.AutomationPatch{Trigger: onceTrigger(due)})++ f.now = due.Add(time.Second)+ require.NoError(t, f.svc.claim(context.Background(), f.reload(t, a.ID), f.now))+ require.Len(t, f.runs(t, a.ID), 1)+ select {+ case <-f.svc.wake:+ default:+ t.Fatal("expected a wake for the first queued run")+ }++ // The executor finished; the slot stays taken for this scheduled_at.+ require.NoError(t, f.db.Model(&types.AutomationRun{}).+ Where("automation_id = ?", a.ID).+ Update("status", types.AutomationRunSucceeded).Error)++ // Pretend the same slot comes due again with no new schedule behind it.+ wakes := 0+ for i := 0; i < 32; i++ {+ require.NoError(t, f.db.Model(&types.Automation{}).Where("id = ?", a.ID).+ Updates(map[string]any{"next_run_at": due, "enabled": true, "version": 0}).Error)+ var stale types.Automation+ require.NoError(t, f.db.Where("id = ?", a.ID).First(&stale).Error)+ require.NoError(t, f.svc.claim(context.Background(), &stale, f.now))+ select {+ case <-f.svc.wake:+ wakes+++ default:+ }+ }+ require.Zero(t, wakes)+ require.Len(t, f.runs(t, a.ID), 1)+}++// A due task still claims exactly once, and a once trigger then stops.+func TestAutomationDueTaskStillClaimsUnderUTCClock(t *testing.T) {+ f := newAutomationFixture(t)+ due := f.now.Add(time.Minute)+ a := f.create(t, types.AutomationPatch{Trigger: onceTrigger(due)})++ f.now = due.Add(time.Second)+ f.svc.tick(context.Background())++ runs := f.runs(t, a.ID)+ require.Len(t, runs, 1)+ require.Contains(t, []string{types.AutomationRunQueued, types.AutomationRunRunning}, runs[0].Status)+ reloaded := f.reload(t, a.ID)+ require.False(t, reloaded.Enabled)+ require.Nil(t, reloaded.NextRunAt)+ // Claiming advances the schedule; starting the queued run acquires a second version.+ require.Equal(t, int64(2), reloaded.Version)+}diff --git a/internal/automation/trigger.go b/internal/automation/trigger.goindex 91b132ada..ee5549343 100644--- a/internal/automation/trigger.go+++ b/internal/automation/trigger.go@@ -106,7 +106,10 @@ func Parse(t types.AutomationTrigger) (*Schedule, error) {return nil, err}s.once = at- s.trigger.At = at.Format(time.RFC3339)+ // RFC3339Nano drops trailing zeros, so whole seconds stay whole and+ // fractional seconds survive normalization; re-parsing the trigger+ // yields the same planned instant.+ s.trigger.At = at.Format(time.RFC3339Nano)default:return nil, invalid("unknown trigger type %q", t.Type)}diff --git a/internal/automation/trigger_test.go b/internal/automation/trigger_test.goindex e242e938c..bf40eb346 100644--- a/internal/automation/trigger_test.go+++ b/internal/automation/trigger_test.go@@ -69,6 +69,23 @@ func TestOnceFiresOnce(t *testing.T) {}}+// Normalizing a once trigger must not move the planned instant: the At+// written back re-parses to the same moment, fractional seconds included.+func TestOnceNormalizationPreservesInstant(t *testing.T) {+ at := time.Date(2026, 10, 20, 7, 1, 0, 794*int(time.Millisecond), time.UTC)+ s, err := Parse(types.AutomationTrigger{Type: types.AutomationTriggerOnce, At: at.Format(time.RFC3339Nano)})+ require.NoError(t, err)++ normalized, err := time.Parse(time.RFC3339Nano, s.Trigger().At)+ require.NoError(t, err)+ require.Equal(t, at, normalized)++ roundTrip, err := Parse(s.Trigger())+ require.NoError(t, err)+ from := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC)+ require.Equal(t, *s.Next(from), *roundTrip.Next(from))+}+func TestCheckInterval(t *testing.T) {from := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC)for expr, ok := range map[string]bool{