Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions core/scheduler/lifecycle_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package scheduler_test

import (
"os"
"sync"
"testing"
"time"

"github.com/mudler/LocalAGI/core/scheduler"
)

func newLifecycleScheduler(t *testing.T) *scheduler.Scheduler {
t.Helper()
f, err := os.CreateTemp(t.TempDir(), "sched_*.json")
if err != nil {
t.Fatal(err)
}
f.Close()
store, err := scheduler.NewJSONStore(f.Name())
if err != nil {
t.Fatal(err)
}
return scheduler.NewScheduler(store, &MockExecutor{}, time.Millisecond)
}

// Agent.Run starts the scheduler on one goroutine while Agent.Stop can stop it
// from another. Start and Stop must be safe to call concurrently.
func TestStartStopConcurrent(t *testing.T) {
for i := 0; i < 200; i++ {
s := newLifecycleScheduler(t)
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); s.Start() }()
go func() { defer wg.Done(); s.Stop() }()
wg.Wait()
s.Stop()
}
}

// Stop called twice must not panic or block.
func TestStopTwice(t *testing.T) {
s := newLifecycleScheduler(t)
s.Start()
s.Stop()
s.Stop()
}

// A scheduler that was stopped must not start again: its store is closed.
func TestStartAfterStopIsNoop(t *testing.T) {
s := newLifecycleScheduler(t)
s.Stop()
s.Start()
s.Stop()
}
41 changes: 31 additions & 10 deletions core/scheduler/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ type Scheduler struct {
cancel context.CancelFunc
wg sync.WaitGroup
mu sync.RWMutex
lifecycleMu sync.Mutex // guards ctx, cancel and stopped
stopped bool
runningTasks map[string]context.CancelFunc
policy CreationPolicy
}
Expand All @@ -39,8 +41,16 @@ func NewSchedulerWithPolicy(store TaskStore, executor AgentExecutor, pollInterva
}
}

// Start begins the scheduler's polling loop
// Start begins the scheduler's polling loop. It is safe to call concurrently
// with Stop. A scheduler that has been stopped cannot be started again.
func (s *Scheduler) Start() {
s.lifecycleMu.Lock()
defer s.lifecycleMu.Unlock()

if s.stopped {
xlog.Warn("Scheduler already stopped, not starting")
return
}
if s.ctx != nil {
xlog.Warn("Scheduler already started")
return
Expand All @@ -49,32 +59,43 @@ func (s *Scheduler) Start() {
s.ctx = ctx
s.cancel = cancel
s.wg.Add(1)
go s.run()
go s.run(ctx)
xlog.Info("Task scheduler started", "poll_interval", s.pollInterval)
}

// Stop gracefully stops the scheduler
// Stop gracefully stops the scheduler. It is safe to call concurrently with
// Start and more than once; only the first call has an effect.
func (s *Scheduler) Stop() {
if s.cancel != nil {
s.cancel()
s.lifecycleMu.Lock()
if s.stopped {
s.lifecycleMu.Unlock()
return
}
s.stopped = true
cancel := s.cancel
s.lifecycleMu.Unlock()
Comment on lines +69 to +76

// ctx and cancel stay set after Stop: executeTask reads s.ctx, and
// the goroutines that read it are all finished once Wait returns.
if cancel != nil {
cancel()
}
s.wg.Wait()
s.store.Close()
xlog.Info("Task scheduler stopped")
s.cancel = nil
s.ctx = nil
}

// run is the main polling loop
func (s *Scheduler) run() {
// run is the main polling loop. It gets ctx as an argument so it never reads
// the shared field.
func (s *Scheduler) run(ctx context.Context) {
defer s.wg.Done()

ticker := time.NewTicker(s.pollInterval)
defer ticker.Stop()

for {
select {
case <-s.ctx.Done():
case <-ctx.Done():
return
case <-ticker.C:
s.processDueTasks()
Expand Down
Loading