Skip to content
Open
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
55 changes: 55 additions & 0 deletions core/services/llo/observation/data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,22 @@ const (

observationLoopPacingFloor = 10 * time.Millisecond
observationLoopPacingDivisor = 2 // pacing targets T/2, capped below by cache invariant

// The observable stream set is only refreshed when the plugin calls Observe. A node that falls behind in
// consensus stops getting Observe calls, so the set can go stale: the loop would keep polling adapters for
// streams the DON has since tombstoned or removed. The loop drops a set that Observe has not refreshed for
// max(observableStreamsStaleMultiplier·T, observableStreamsStaleFloor). That is far beyond any healthy round
// interval (cache entries themselves expire after cacheTTLMultiplier·T).
observableStreamsStaleMultiplier = 10
observableStreamsStaleFloor = 5 * time.Second
)

// observableStreamsStaleAfter returns how long the observation loop keeps using an observable stream set that the
// plugin has not refreshed via Observe.
func observableStreamsStaleAfter(observationTimeout time.Duration) time.Duration {
return max(time.Duration(observableStreamsStaleMultiplier)*observationTimeout, observableStreamsStaleFloor)
}

func cacheEntryTTL(observationTimeout time.Duration) time.Duration {
return time.Duration(cacheTTLMultiplier) * observationTimeout
}
Expand Down Expand Up @@ -167,6 +181,8 @@ type dataSource struct {

observableStreamsMu sync.Mutex
observableStreams *observableStreamValues
// observableStreamsStaleAfterOverride replaces observableStreamsStaleAfter when non-zero (tests).
observableStreamsStaleAfterOverride time.Duration

// closeMu serialises Close against startObservationLoop. Once closed is
// set, no new observation loop may be started (and therefore no new
Expand Down Expand Up @@ -339,6 +355,15 @@ func (d *dataSource) startObservationLoop(loopStartedCh chan struct{}) {
return
}

// Checked after the pacing wait so a lagging node stops polling adapters instead of looping forever.
if d.expireStaleObservableStreams() {
return
}
// The set may have been refreshed or cleared while we waited.
if osv = d.getObservableStreams(); osv == nil || len(osv.streamValues) == 0 {
return
}

startTS := time.Now()
ctx, cancel := context.WithTimeout(stopChanCtx, osv.observationTimeout)
lggr := logger.With(d.lggr, "observationTimestamp", osv.opts.ObservationTimestamp(), "configDigest", osv.opts.ConfigDigest(), "seqNr", osv.opts.SeqNr())
Expand Down Expand Up @@ -565,6 +590,8 @@ type observableStreamValues struct {
opts telem.DSOpts
streamValues lloprotocol.StreamValues
observationTimeout time.Duration
// setAt is when the plugin last refreshed this set via Observe.
setAt time.Time
}

// setObservableStreams updates the stream set and observation deadline (T) used by the background loop. When
Expand All @@ -587,6 +614,7 @@ func (d *dataSource) setObservableStreams(ctx context.Context, streamValues llop
opts: opts,
streamValues: make(lloprotocol.StreamValues, len(streamValues)),
observationTimeout: 250 * time.Millisecond,
setAt: time.Now(),
}

for streamID := range streamValues {
Expand Down Expand Up @@ -616,6 +644,33 @@ func (d *dataSource) setObservableStreams(ctx context.Context, streamValues llop
d.observableStreams = osv
}

// expireStaleObservableStreams clears the observable stream set and reports true if the plugin has not refreshed it
// within observableStreamsStaleAfter. The loop then exits; the next Observe call restarts it with a fresh set. This
// stops a node that is no longer being asked to observe (e.g. lagging behind in consensus) from polling adapters
// for streams that have since been tombstoned or removed.
func (d *dataSource) expireStaleObservableStreams() bool {
d.observableStreamsMu.Lock()
defer d.observableStreamsMu.Unlock()

osv := d.observableStreams
if osv == nil {
return false
}
staleAfter := observableStreamsStaleAfter(osv.observationTimeout)
if d.observableStreamsStaleAfterOverride > 0 {
staleAfter = d.observableStreamsStaleAfterOverride
}
age := time.Since(osv.setAt)
if age <= staleAfter {
return false
}
d.lggr.Warnw("observation loop: observable streams not refreshed by Observe, stopping until the next Observe call",
"age_ms", age.Milliseconds(), "stale_after_ms", staleAfter.Milliseconds(),
"observable_streams", len(osv.streamValues))
d.observableStreams = nil
return true
}

// getObservableStreams returns the current observableStreamValues (opts, stream key set, and T), or nil if unset.
// T is the plugin Observe deadline; the loop uses a separate pacing timer between iterations and WithTimeout(..., T) per round.
func (d *dataSource) getObservableStreams() *observableStreamValues {
Expand Down
64 changes: 64 additions & 0 deletions core/services/llo/observation/data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1026,6 +1026,70 @@ func Test_DataSource_StagingDoesNotObserve(t *testing.T) {
require.Zero(t, reg.pipelines[1].runCount.Load(), "staging instance must not run pipelines")
}

// Test_DataSource_StaleObservableStreamsStopLoop asserts that a node the plugin stops calling Observe on (for
// example one lagging behind in consensus) stops polling pipelines once its observable stream set goes stale,
// rather than polling streams that were since tombstoned or removed forever. A later Observe restarts the loop.
func Test_DataSource_StaleObservableStreamsStopLoop(t *testing.T) {
t.Parallel()
reg := &mockRegistry{pipelines: make(map[streams.StreamID]*mockPipeline)}
reg.pipelines[1] = pipelineForStream(1, 1, big.NewInt(42), nil)
ds := newDataSource(logger.NullLogger, reg, telem.NullTelemeter)
ds.observableStreamsStaleAfterOverride = 300 * time.Millisecond
defer ds.Close()

ctx, cancel := context.WithTimeout(t.Context(), observationTimeout)
defer cancel()
require.NoError(t, ds.Observe(ctx, makeStreamValues(1), &mockOpts{}))
require.Positive(t, reg.pipelines[1].runCount.Load(), "observation loop should have run the pipeline")

// No further Observe calls: the set goes stale and the loop stops.
require.Eventually(t, func() bool {
return ds.getObservableStreams() == nil && !ds.observationLoopStarted.Load()
}, 5*time.Second, 10*time.Millisecond, "stale observable streams should stop the loop")

stoppedRuns := reg.pipelines[1].runCount.Load()
require.Never(t, func() bool {
return reg.pipelines[1].runCount.Load() != stoppedRuns
}, 500*time.Millisecond, 25*time.Millisecond, "no pipeline may run once the loop has stopped")

// The next Observe restarts the loop with a fresh set.
require.NoError(t, ds.Observe(ctx, makeStreamValues(1), &mockOpts{}))
require.NotNil(t, ds.getObservableStreams(), "Observe should set a fresh observable set")
require.True(t, ds.observationLoopStarted.Load(), "Observe should restart the loop")
// Cached values from before the stop may still be fresh, so the pipeline only reruns once they expire.
// Keep calling Observe, as the plugin does each round, so the set stays fresh meanwhile.
require.Eventually(t, func() bool {
_ = ds.Observe(ctx, makeStreamValues(1), &mockOpts{})
return reg.pipelines[1].runCount.Load() > stoppedRuns
}, 5*time.Second, 20*time.Millisecond, "restarted loop should run the pipeline again")
}

// Test_DataSource_RefreshedObservableStreamsKeepLoopRunning asserts that regular Observe calls keep the loop
// alive for far longer than the stale window.
func Test_DataSource_RefreshedObservableStreamsKeepLoopRunning(t *testing.T) {
t.Parallel()
reg := &mockRegistry{pipelines: make(map[streams.StreamID]*mockPipeline)}
reg.pipelines[1] = pipelineForStream(1, 1, big.NewInt(42), nil)
ds := newDataSource(logger.NullLogger, reg, telem.NullTelemeter)
ds.observableStreamsStaleAfterOverride = 300 * time.Millisecond
defer ds.Close()

ctx, cancel := context.WithTimeout(t.Context(), observationTimeout)
defer cancel()
for range 30 { // 30 * 40ms = 1.2s, 4x the stale window
require.NoError(t, ds.Observe(ctx, makeStreamValues(1), &mockOpts{}))
require.NotNil(t, ds.getObservableStreams(), "refreshed set must not be expired")
time.Sleep(40 * time.Millisecond)
}
}

func Test_observableStreamsStaleAfter(t *testing.T) {
t.Parallel()
assert.Equal(t, observableStreamsStaleFloor, observableStreamsStaleAfter(0))
assert.Equal(t, observableStreamsStaleFloor, observableStreamsStaleAfter(250*time.Millisecond))
assert.Equal(t, 10*time.Second, observableStreamsStaleAfter(time.Second))
}

// Test_DataSource_CloseIsFinal asserts that Close is idempotent and that an
// Observe call racing with shutdown cannot start a new observation loop. A
// late-started loop would run pipeline work (and log through the plugin
Expand Down
26 changes: 22 additions & 4 deletions core/services/pg/lease_lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,7 @@ func (l *leaseLock) loop(ctx context.Context) {
select {
case <-ctx.Done():
qctx, cancel := context.WithTimeout(context.Background(), l.cfg.DefaultQueryTimeout)
err := stderrors.Join(
utils.JustError(l.conn.ExecContext(qctx, `UPDATE lease_lock SET expires_at=NOW() WHERE client_id = $1 AND expires_at > NOW()`, l.id)),
l.conn.Close(),
)
err := l.releaseLease(qctx)
cancel()
if err != nil {
l.logger.Warnw("Error trying to release lease on cancelled ctx", "err", err)
Expand Down Expand Up @@ -233,6 +230,27 @@ func (l *leaseLock) loop(ctx context.Context) {
}
}

const releaseLeaseSQL = `UPDATE lease_lock SET expires_at=NOW() WHERE client_id = $1 AND expires_at > NOW()`

// releaseLease expires our lease and closes the dedicated connection.
//
// Release cancels the loop's context, which can land while a refresh query is
// in flight. Cancelling that query closes the connection, so the release has to
// fall back to a fresh connection from the pool. Otherwise the lease stays
// held and the next instance waits out the full lease duration.
func (l *leaseLock) releaseLease(ctx context.Context) error {
_, err := l.conn.ExecContext(ctx, releaseLeaseSQL, l.id)
if err != nil {
l.logger.Debugw("Failed to release lease on dedicated connection, retrying on a new one", "err", err)
_, err = l.db.ExecContext(ctx, releaseLeaseSQL, l.id)
}
closeErr := l.conn.Close()
if errors.Is(closeErr, sql.ErrConnDone) {
closeErr = nil
}
return stderrors.Join(err, closeErr)
}

// initialSQL is necessary because the application attempts to take the lease
// lock BEFORE running migrations
var initialSQL = []string{
Expand Down
2 changes: 1 addition & 1 deletion core/services/pipeline/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ func (r *runner) run(ctx context.Context, pipeline *Pipeline, run *Run, vars Var
}

scheduler := newScheduler(pipeline, run, vars, l)
go scheduler.Run() //nolint:gosec // G118
go scheduler.Run(ctx) //nolint:gosec // G118

// This is "just in case" for cleaning up any stray reports.
// Normally the scheduler loop doesn't stop until all in progress runs report back
Expand Down
16 changes: 14 additions & 2 deletions core/services/pipeline/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,10 @@ func (s *scheduler) reconstructResults() {
}
}

func (s *scheduler) Run() {
// Run drives the pipeline until all tasks report. Once runCtx is done, retries
// cannot succeed (task contexts derive from it), so they are not attempted and
// pending backoff waits are cut short.
func (s *scheduler) Run(runCtx context.Context) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for s.waiting > 0 {
Expand Down Expand Up @@ -220,7 +223,7 @@ func (s *scheduler) Run() {
}

// if task hasn't reached it's max retry count yet, we schedule it again
if result.Attempts < uint(result.Task.TaskRetries()) && result.Result.Error != nil {
if result.Attempts < uint(result.Task.TaskRetries()) && result.Result.Error != nil && runCtx.Err() == nil {
// we immediately increase the in-flight counter so the pipeline doesn't terminate
// while we wait for the next retry
s.waiting++
Expand All @@ -242,6 +245,15 @@ func (s *scheduler) Run() {
CreatedAt: now, // TODO: more accurate start time
FinishedAt: null.TimeFrom(now),
})
case <-runCtx.Done():
// the run's context expired while waiting to retry, a retry cannot succeed
now := time.Now()
s.report(context.Background(), TaskRunResult{
Task: result.Task,
Result: Result{Error: ErrCancelled},
CreatedAt: now,
FinishedAt: null.TimeFrom(now),
})
case <-time.After(backoff.ForAttempt(float64(result.Attempts - 1))): // we subtract 1 because backoff 0-indexes
// schedule a new attempt
run := s.newMemoryTaskRun(result.Task, vars)
Expand Down
50 changes: 49 additions & 1 deletion core/services/pipeline/scheduler_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package pipeline

import (
"context"
"testing"
"time"

Expand Down Expand Up @@ -136,7 +137,7 @@ func TestScheduler(t *testing.T) {
run := NewRun(Spec{}, vars)
s := newScheduler(p, run, vars, logger.TestLogger(t))

go s.Run()
go s.Run(t.Context())

for _, event := range test.events {
select {
Expand Down Expand Up @@ -166,3 +167,50 @@ func TestScheduler(t *testing.T) {
test.assertion(t, *p, s.results)
}
}

func TestScheduler_RunContextDoneCutsRetryBackoff(t *testing.T) {
t.Parallel()

p, err := Parse(`a [type=median retries=3 minBackoff="1h" maxBackoff="1h" index=0]`)
require.NoError(t, err)
vars := NewVarsFrom(nil)
run := NewRun(Spec{}, vars)
runCtx, cancel := context.WithCancel(t.Context())
s := newScheduler(p, run, vars, logger.TestLogger(t))

done := make(chan struct{})
go func() {
s.Run(runCtx)
close(done)
}()

select {
case taskRun := <-s.taskCh:
now := time.Now()
s.report(t.Context(), TaskRunResult{
ID: uuid.New(),
Task: taskRun.task,
Result: Result{Error: ErrTaskRunFailed},
FinishedAt: null.TimeFrom(now),
CreatedAt: now,
})
case <-time.After(time.Second):
t.Fatal("timed out waiting for task run")
}

// The task failed and is now waiting out a 1h backoff; expiring the run
// context must end the wait instead of blocking the run. The scheduler
// handles the report asynchronously and there is nothing to observe, so
// give it a moment to enter the backoff before cancelling.
time.Sleep(100 * time.Millisecond)
cancel()

select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("scheduler still waiting on retry backoff after run context was cancelled")
}
// If the cancel beat the scheduler to the report, it skips the retry and
// keeps the task's own error. Either way the run must not wait out the backoff.
require.Contains(t, []error{ErrCancelled, ErrTaskRunFailed}, s.results[p.ByDotID("a").ID()].Result.Error)
}
Loading
Loading