From ffbda118bd20ce84b4982d8fc10f7c2c5c28b102 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:47 -0500 Subject: [PATCH 1/4] fix(pg): release the lease on a fresh connection if refresh killed the old one Release cancels the lease loop's context. If that lands while a refresh query is in flight, the cancelled query closes the dedicated connection, the release UPDATE fails with "bad connection", and the lease stays held until it expires. The next instance then waits out the full lease duration (1 minute by default). Retry the release on a pooled connection. Co-Authored-By: Claude Sonnet 5.5 --- core/services/pg/lease_lock.go | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/core/services/pg/lease_lock.go b/core/services/pg/lease_lock.go index 5e731191dac..e00f2d6d6d0 100644 --- a/core/services/pg/lease_lock.go +++ b/core/services/pg/lease_lock.go @@ -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) @@ -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{ From 5a4066cb1ac97939bac3c1f4a7b8f927a051e803 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:47 -0500 Subject: [PATCH 2/4] fix(pipeline): stop task retries once the run context expires The scheduler's retry goroutine slept through task backoff (5s + 10s with retries=2) after the run context had expired, because it only woke on failEarly. A retry cannot succeed once the run context is done, so scheduler.Run now takes the run context, skips retries after it expires, and ends a pending backoff wait. This also delayed node shutdown (DataSource.Close waits on the in-flight run) by up to 15s. Adds TestScheduler_RunContextDoneCutsRetryBackoff. Co-Authored-By: Claude Sonnet 5.5 --- core/services/pipeline/runner.go | 2 +- core/services/pipeline/scheduler.go | 16 +++++++- core/services/pipeline/scheduler_test.go | 50 +++++++++++++++++++++++- 3 files changed, 64 insertions(+), 4 deletions(-) diff --git a/core/services/pipeline/runner.go b/core/services/pipeline/runner.go index 9e452a9295d..3491cec3003 100644 --- a/core/services/pipeline/runner.go +++ b/core/services/pipeline/runner.go @@ -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 diff --git a/core/services/pipeline/scheduler.go b/core/services/pipeline/scheduler.go index 0b207adc36b..0ccea9b17c1 100644 --- a/core/services/pipeline/scheduler.go +++ b/core/services/pipeline/scheduler.go @@ -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 { @@ -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++ @@ -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) diff --git a/core/services/pipeline/scheduler_test.go b/core/services/pipeline/scheduler_test.go index a1d91fcca3d..30d13254b3b 100644 --- a/core/services/pipeline/scheduler_test.go +++ b/core/services/pipeline/scheduler_test.go @@ -1,6 +1,7 @@ package pipeline import ( + "context" "testing" "time" @@ -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 { @@ -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) +} From 87f52b2ab51489ba940bcdcc0eb322d07d3ce644 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 08:23:47 -0500 Subject: [PATCH 3/4] refactor: make the registry sync tick and chip ingress health interval injectable registrysyncer.New takes variadic options; WithTickInterval sets how often the sync loop polls the registry (default stays 12s). The chip ingress batch client's health-check interval is a field (default stays 5s) with NewTestChipIngressBatchClientWithHealthInterval. Tests use short intervals instead of waiting out the defaults. No behaviour change at the defaults. Co-Authored-By: Claude Sonnet 5.5 --- core/services/registrysyncer/syncer.go | 38 +++++++++++++++---- .../chip_ingress_batch_client.go | 11 +++++- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/core/services/registrysyncer/syncer.go b/core/services/registrysyncer/syncer.go index 1010dc574ab..040b4edf4de 100644 --- a/core/services/registrysyncer/syncer.go +++ b/core/services/registrysyncer/syncer.go @@ -57,6 +57,10 @@ type registrySyncer struct { updateChan chan *registry.RegistryMetadata + // tickInterval is how often the sync loop polls the remote registry after + // the initial sync. + tickInterval time.Duration + wg sync.WaitGroup lggr logger.Logger mu sync.RWMutex @@ -64,7 +68,21 @@ type registrySyncer struct { var _ services.Service = ®istrySyncer{} -var defaultTickInterval = 12 * time.Second +const defaultTickInterval = 12 * time.Second + +// Option customizes a RegistrySyncer. +type Option func(*registrySyncer) + +// WithTickInterval sets how often the syncer polls the remote registry. It is +// mainly useful in tests, which would otherwise wait out the 12 s default to +// see a change made after the initial sync. Non-positive values are ignored. +func WithTickInterval(d time.Duration) Option { + return func(s *registrySyncer) { + if d > 0 { + s.tickInterval = d + } + } +} // New instantiates a new RegistrySyncer func New( @@ -73,13 +91,14 @@ func New( relayer ContractReaderFactory, registryAddress string, orm ORM, + opts ...Option, ) (RegistrySyncer, error) { metricLabeler, err := newSyncerMetricLabeler() if err != nil { return nil, fmt.Errorf("failed to create syncer metric labeler: %w", err) } - return ®istrySyncer{ + s := ®istrySyncer{ metrics: metricLabeler, stopCh: make(services.StopChan), updateChan: make(chan *registry.RegistryMetadata), @@ -89,10 +108,15 @@ func New( Address: registryAddress, Name: "CapabilitiesRegistry", }, - initReader: newReader, - orm: orm, - getPeerID: getPeerID, - }, nil + initReader: newReader, + orm: orm, + getPeerID: getPeerID, + tickInterval: defaultTickInterval, + } + for _, opt := range opts { + opt(s) + } + return s, nil } // NOTE: this can't be called while initializing the syncer and needs to be called in the sync loop. @@ -149,7 +173,7 @@ func (s *registrySyncer) syncLoop() { ctx, cancel := s.stopCh.NewCtx() defer cancel() - ticker := time.NewTicker(defaultTickInterval) + ticker := time.NewTicker(s.tickInterval) defer ticker.Stop() // Sync for a first time outside the loop; this means we'll start a remote diff --git a/core/services/synchronization/chip_ingress_batch_client.go b/core/services/synchronization/chip_ingress_batch_client.go index b2b385a0573..ad0cd922726 100644 --- a/core/services/synchronization/chip_ingress_batch_client.go +++ b/core/services/synchronization/chip_ingress_batch_client.go @@ -26,10 +26,15 @@ type chipIngressBatchClient struct { telemSendInterval time.Duration telemSendTimeout time.Duration + // healthCheckInterval is how often the connection is pinged. + healthCheckInterval time.Duration + workers map[string]*chipIngressBatchWorker workersMutex sync.RWMutex } +const defaultHealthCheckInterval = 5 * time.Second + // NewChipIngressBatchClient returns a client backed by chipingress.Client that // can send telemetry to the chip ingress server func NewChipIngressBatchClient(chipClient chipingress.Client, logging bool, lggr logger.Logger, telemBufferSize uint, telemMaxBatchSize uint, telemSendInterval time.Duration, telemSendTimeout time.Duration) ChipIngressService { @@ -41,6 +46,8 @@ func NewChipIngressBatchClient(chipClient chipingress.Client, logging bool, lggr chipClient: chipClient, logging: logging, workers: make(map[string]*chipIngressBatchWorker), + + healthCheckInterval: defaultHealthCheckInterval, } c.Service, c.eng = services.Config{ Name: "ChipIngressBatchClient", @@ -105,10 +112,10 @@ func (cc *chipIngressBatchClient) findOrCreateWorker(payload TelemPayload) *chip return worker } -// startHealthMonitoring starts a goroutine to monitor the connection state and update other relevant metrics every 5 seconds +// startHealthMonitoring starts a goroutine to monitor the connection state and update other relevant metrics every healthCheckInterval (5 seconds by default) func (cc *chipIngressBatchClient) startHealthMonitoring(_ context.Context, chipClient chipingress.Client) { cc.eng.GoTick(timeutil.NewTicker(func() time.Duration { - return 5 * time.Second + return cc.healthCheckInterval }), func(ctx context.Context) { connected := float64(0) pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second) From 6cfabe4322eaf9f856af5ae5bb1a519ad4e140b9 Mon Sep 17 00:00:00 2001 From: Adam Hamrick Date: Wed, 11 Nov 2026 09:24:58 -0500 Subject: [PATCH 4/4] fix(llo): stop observing streams once Observe stops refreshing them The observation loop polls whatever stream set Observe last stored, and nothing expired it. A node that falls behind in consensus stops getting Observe calls, so its loop kept hitting adapters for streams the DON had already tombstoned or removed. Drop the set if Observe has not refreshed it within max(10*T, 5s) and let the loop exit. The next Observe restarts it. This was the cause of the TestIntegration_LLO_tombstone_stops_observations_and_reports flake: one of four nodes lagged after a KV commit conflict, kept a stale two-stream set, and bridge calls for the tombstoned stream never stopped. Co-Authored-By: Claude Sonnet 5.5 --- core/services/llo/observation/data_source.go | 55 ++++++++++++++++ .../llo/observation/data_source_test.go | 64 +++++++++++++++++++ 2 files changed, 119 insertions(+) diff --git a/core/services/llo/observation/data_source.go b/core/services/llo/observation/data_source.go index e5e1d4e3aef..029cd3b1e73 100644 --- a/core/services/llo/observation/data_source.go +++ b/core/services/llo/observation/data_source.go @@ -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 } @@ -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 @@ -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()) @@ -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 @@ -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 { @@ -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 { diff --git a/core/services/llo/observation/data_source_test.go b/core/services/llo/observation/data_source_test.go index db0d72341c5..61be131633b 100644 --- a/core/services/llo/observation/data_source_test.go +++ b/core/services/llo/observation/data_source_test.go @@ -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