From 95d257a47dbaf5f39219afab39f668193ba7e4fd Mon Sep 17 00:00:00 2001 From: Dmitriy Tymoshchenko Date: Mon, 23 Nov 2026 17:45:21 +0100 Subject: [PATCH 1/3] [CRE-7138] Bound timeout-based shard failover executions by execution concurrency --- .../bound-failover-execution-concurrency.md | 5 +++ core/services/workflows/syncer/v2/handler.go | 1 + .../syncer/v2/shard_failover_manager.go | 19 ++++++++ .../syncer/v2/shard_failover_manager_test.go | 45 +++++++++++++++++++ 4 files changed, 70 insertions(+) create mode 100644 .changeset/bound-failover-execution-concurrency.md diff --git a/.changeset/bound-failover-execution-concurrency.md b/.changeset/bound-failover-execution-concurrency.md new file mode 100644 index 00000000000..0b1b0d64662 --- /dev/null +++ b/.changeset/bound-failover-execution-concurrency.md @@ -0,0 +1,5 @@ +--- +"chainlink": patch +--- + +#internal Bound timeout-based shard failover executions by the workflow execution concurrency limit diff --git a/core/services/workflows/syncer/v2/handler.go b/core/services/workflows/syncer/v2/handler.go index bbd5ec39d58..a3559bb3e81 100644 --- a/core/services/workflows/syncer/v2/handler.go +++ b/core/services/workflows/syncer/v2/handler.go @@ -1092,6 +1092,7 @@ func (h *eventHandler) newEngine(ctx context.Context, workflowID, owner string, TimeoutBasedFailoverGate: h.engineLimiters.TimeoutBasedFailover, TimeoutBasedFailoverWindow: h.engineLimiters.TimeoutBasedFailoverWindow, Communicator: h.getShardFailoverComm(), + ExecutionConcurrency: h.engineLimiters.ExecutionConcurrency, }, Logger: h.lggr, }) diff --git a/core/services/workflows/syncer/v2/shard_failover_manager.go b/core/services/workflows/syncer/v2/shard_failover_manager.go index 1d5e2857a9d..a19d64aad99 100644 --- a/core/services/workflows/syncer/v2/shard_failover_manager.go +++ b/core/services/workflows/syncer/v2/shard_failover_manager.go @@ -130,6 +130,9 @@ type FailoverConfig struct { // A nil limiter (or closed gate) disables timeout-based failover. TimeoutBasedFailoverWindow limits.TimeLimiter Communicator *sharding.ShardFailoverCommunicator + // ExecutionConcurrency bounds in-flight timeout-based failover executions; due events + // over the limit stay cached for a later tick. A nil limiter leaves them unbounded. + ExecutionConcurrency limits.ResourcePoolLimiter[int] } // NewShardFailoverManager creates a manager that is not yet wired to an engine. @@ -139,6 +142,9 @@ func NewShardFailoverManager(cfg ShardFailoverManagerConfig) *ShardFailoverManag cfg: cfg, cache: make(map[string]cachedEvent), } + if m.cfg.Failover.ExecutionConcurrency == nil { + m.cfg.Failover.ExecutionConcurrency = limits.UnlimitedResourcePoolLimiter[int]() + } autoExecCounter, err := beholder.GetMeter().Int64Counter(failoverAutoExecutionTotalMetric) if err != nil { m.cfg.Logger.Warnw("shard failover: failed to register failover_auto_execution_total counter", "err", err) @@ -499,8 +505,13 @@ func (m *ShardFailoverManager) executeDueTimeoutBasedFailovers(ctx context.Conte switch m.checkShardOwnership(ctx) { case shardownership.DenyNotOwner: + execCtx := m.replayExecCtx(ctx) + if err := m.cfg.Failover.ExecutionConcurrency.Use(execCtx, 1); err != nil { + return + } event, ok := m.popCachedEvent(c.eventID, monitoring.ShardFailoverCacheExitReplayed) if !ok { + m.freeExecutionConcurrency(execCtx) continue } m.cfg.Logger.Infow("secondary shard: auto failover executed cached trigger event", @@ -519,6 +530,7 @@ func (m *ShardFailoverManager) executeDueTimeoutBasedFailovers(ctx context.Conte // serializing due events would prevent concurrent executions of // this workflow. m.eng.GoCtx(ctx, func(ctx context.Context) { + defer m.freeExecutionConcurrency(execCtx) if err := m.engine.ExecuteTrigger(m.replayExecCtx(ctx), event); err != nil { m.cfg.Logger.Errorw("secondary shard: auto failover failed to execute cached trigger event", "eventID", c.eventID, @@ -538,6 +550,13 @@ func (m *ShardFailoverManager) executeDueTimeoutBasedFailovers(ctx context.Conte } } +// freeExecutionConcurrency expects ctx to carry the workflow's CRE: the limit is keyed on it. +func (m *ShardFailoverManager) freeExecutionConcurrency(ctx context.Context) { + if err := m.cfg.Failover.ExecutionConcurrency.Free(ctx, 1); err != nil { + m.cfg.Logger.Errorw("secondary shard: failed to free execution concurrency", "workflowID", m.cfg.WorkflowID, "err", err) + } +} + // popCachedEvent removes eventID from the cache for replay. exit is the // ShardFailoverCacheExit* constant describing why the entry left the cache. func (m *ShardFailoverManager) popCachedEvent(eventID string, exit string) (triggers.CoordinatedEvent, bool) { diff --git a/core/services/workflows/syncer/v2/shard_failover_manager_test.go b/core/services/workflows/syncer/v2/shard_failover_manager_test.go index 92e6162e7a8..43028a2e619 100644 --- a/core/services/workflows/syncer/v2/shard_failover_manager_test.go +++ b/core/services/workflows/syncer/v2/shard_failover_manager_test.go @@ -1061,6 +1061,51 @@ func TestShardFailoverManager_TimeoutBasedFailover_CompletionDrainsCache(t *test assert.Empty(t, eng.executedIDs(), "cached event was auto-executed although the primary reported success") } +// releasableEngine holds each execution until release receives a value. +type releasableEngine struct { + recordingEngine + release chan struct{} +} + +func (e *releasableEngine) ExecuteTrigger(ctx context.Context, event triggers.CoordinatedEvent) error { + err := e.recordingEngine.ExecuteTrigger(ctx, event) + select { + case <-e.release: + case <-ctx.Done(): + } + return err +} + +func TestShardFailoverManager_TimeoutBasedFailover_ExecutionConcurrencyBound(t *testing.T) { + t.Parallel() + + eng := &releasableEngine{release: make(chan struct{})} + t.Cleanup(func() { close(eng.release) }) + gate := &fakeGateLimiter{open: true} + window := &fakeWindowLimiter{window: 10 * time.Millisecond} + m := newTimeoutBasedFailoverManager(t, &eng.recordingEngine, gate, window, &switchableShardResolver{ownerDON: 1, found: true}) + m.SetEngine(eng) + m.cfg.Failover.ExecutionConcurrency = limits.GlobalResourcePoolLimiter(3) + + for i := range 10 { + err := m.admissionCheck(t.Context(), timeoutBasedFailoverTestEvent(fmt.Sprintf("evt-%d", i))) + require.ErrorIs(t, err, v2.ErrAdmissionCache) + } + + time.Sleep(15 * time.Millisecond) + m.executeDueTimeoutBasedFailovers(t.Context()) + require.Eventually(t, func() bool { return len(eng.executedIDs()) == 3 }, 10*time.Second, 10*time.Millisecond, + "auto failover did not start executions up to the concurrency limit") + assert.Len(t, m.cacheIDs(), 7, "events over the concurrency limit were not kept in the cache") + + eng.release <- struct{}{} + require.Eventually(t, func() bool { + m.executeDueTimeoutBasedFailovers(t.Context()) + return len(eng.executedIDs()) == 4 + }, 10*time.Second, 10*time.Millisecond, "a later tick did not execute a cached event after a slot was freed") + assert.Len(t, m.cacheIDs(), 6, "a later tick executed more cached events than the freed slots") +} + func TestShardFailoverManager_TimeoutBasedFailover_DisabledByDefault(t *testing.T) { t.Parallel() From 6c0cc80b4aa0abd987a5d6820cd83be46be482bf Mon Sep 17 00:00:00 2001 From: Dmitriy Tymoshchenko Date: Tue, 24 Nov 2026 11:48:37 +0100 Subject: [PATCH 2/3] [CRE-7138] Log and count timeout-based failover passes deferred by execution concurrency --- .../monitoring/shard_failover_metrics.go | 21 +++ .../monitoring/shard_failover_metrics_test.go | 6 + .../syncer/v2/shard_failover_manager.go | 7 + .../syncer/v2/shard_failover_manager_test.go | 121 +++++++++++++++++- 4 files changed, 151 insertions(+), 4 deletions(-) diff --git a/core/services/workflows/monitoring/shard_failover_metrics.go b/core/services/workflows/monitoring/shard_failover_metrics.go index 5c7567f92fa..925d40a5c4c 100644 --- a/core/services/workflows/monitoring/shard_failover_metrics.go +++ b/core/services/workflows/monitoring/shard_failover_metrics.go @@ -26,6 +26,12 @@ const ( ShardFailoverReplayMiss = "miss" ) +// Outcome values for platform_shard_failover_auto_deferred (low cardinality). +const ( + ShardFailoverAutoDeferredConcurrencyLimit = "concurrency_limit" + ShardFailoverAutoDeferredLimiterError = "limiter_error" +) + // ShardFailoverMetrics are the process-global failover instruments, emitted by // the per-workflow ShardFailoverManager instances and the syncer through the // shared unlabeled meter. The instruments are per-node aggregates with no @@ -40,6 +46,7 @@ type ShardFailoverMetrics struct { cachedEvents metric.Int64UpDownCounter cacheExitCounter metric.Int64Counter replayCounter metric.Int64Counter + autoDeferredCounter metric.Int64Counter replayDurationSeconds metric.Float64Histogram } @@ -106,6 +113,11 @@ func newShardFailoverMetricsWithMeter(meter metric.Meter) (*ShardFailoverMetrics if err != nil { return nil, err } + m.autoDeferredCounter, err = meter.Int64Counter("platform_shard_failover_auto_deferred", + metric.WithDescription("Timeout-based failover passes cut short before executing the remaining due events, by outcome: concurrency_limit (execution concurrency limit reached), limiter_error (limiter failed for another reason)")) + if err != nil { + return nil, err + } m.replayDurationSeconds, err = meter.Float64Histogram("platform_shard_failover_replay_duration_seconds", metric.WithDescription("Duration of failover replays of cached trigger events"), metric.WithUnit("s"), @@ -158,6 +170,15 @@ func (m *ShardFailoverMetrics) RecordReplay(ctx context.Context, outcome string) m.replayCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("outcome", outcome))) } +// RecordAutoDeferred counts one timeout-based failover pass that stopped before +// executing all due events. outcome must be a ShardFailoverAutoDeferred* constant. +func (m *ShardFailoverMetrics) RecordAutoDeferred(ctx context.Context, outcome string) { + if m == nil { + return + } + m.autoDeferredCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("outcome", outcome))) +} + // RecordReplayDuration records the duration of one failover replay, in // fractional seconds. outcome must be a ShardFailoverReplay* constant. func (m *ShardFailoverMetrics) RecordReplayDuration(ctx context.Context, outcome string, d time.Duration) { diff --git a/core/services/workflows/monitoring/shard_failover_metrics_test.go b/core/services/workflows/monitoring/shard_failover_metrics_test.go index 03f7ece8bb3..74ff03ab6d0 100644 --- a/core/services/workflows/monitoring/shard_failover_metrics_test.go +++ b/core/services/workflows/monitoring/shard_failover_metrics_test.go @@ -77,6 +77,9 @@ func TestShardFailoverMetrics_Emissions(t *testing.T) { fm.RecordTriggerCached(ctx) fm.RecordCacheExit(ctx, ShardFailoverCacheExitClosed, 1) fm.RecordReplay(ctx, ShardFailoverReplaySucceeded) + fm.RecordAutoDeferred(ctx, ShardFailoverAutoDeferredConcurrencyLimit) + fm.RecordAutoDeferred(ctx, ShardFailoverAutoDeferredConcurrencyLimit) + fm.RecordAutoDeferred(ctx, ShardFailoverAutoDeferredLimiterError) fm.RecordReplayDuration(ctx, ShardFailoverReplaySucceeded, 1500*time.Millisecond) fm.RecordReplayDuration(ctx, ShardFailoverReplaySucceeded, 400*time.Millisecond) @@ -85,6 +88,7 @@ func TestShardFailoverMetrics_Emissions(t *testing.T) { nilFM.RecordTriggerCached(ctx) nilFM.RecordCacheExit(ctx, ShardFailoverCacheExitDrained, 1) nilFM.RecordReplay(ctx, ShardFailoverReplayFailed) + nilFM.RecordAutoDeferred(ctx, ShardFailoverAutoDeferredLimiterError) nilFM.RecordReplayDuration(ctx, ShardFailoverReplayFailed, time.Second) var rm metricdata.ResourceMetrics @@ -126,6 +130,8 @@ func TestShardFailoverMetrics_Emissions(t *testing.T) { assert.Equal(t, int64(2), sums["platform_shard_failover_cache_exit"][ShardFailoverCacheExitExpired]) assert.Equal(t, int64(1), sums["platform_shard_failover_cache_exit"][ShardFailoverCacheExitClosed]) assert.Equal(t, int64(1), sums["platform_shard_failover_replay"][ShardFailoverReplaySucceeded]) + assert.Equal(t, int64(2), sums["platform_shard_failover_auto_deferred"][ShardFailoverAutoDeferredConcurrencyLimit]) + assert.Equal(t, int64(1), sums["platform_shard_failover_auto_deferred"][ShardFailoverAutoDeferredLimiterError]) assert.Equal(t, "s", units["platform_shard_failover_replay_duration_seconds"]) require.NotNil(t, replayHist, "replay duration histogram recorded") diff --git a/core/services/workflows/syncer/v2/shard_failover_manager.go b/core/services/workflows/syncer/v2/shard_failover_manager.go index a19d64aad99..631b51a101c 100644 --- a/core/services/workflows/syncer/v2/shard_failover_manager.go +++ b/core/services/workflows/syncer/v2/shard_failover_manager.go @@ -507,6 +507,13 @@ func (m *ShardFailoverManager) executeDueTimeoutBasedFailovers(ctx context.Conte case shardownership.DenyNotOwner: execCtx := m.replayExecCtx(ctx) if err := m.cfg.Failover.ExecutionConcurrency.Use(execCtx, 1); err != nil { + outcome := monitoring.ShardFailoverAutoDeferredConcurrencyLimit + if !errors.Is(err, limits.ErrorResourceLimited[int]{}) { + outcome = monitoring.ShardFailoverAutoDeferredLimiterError + m.cfg.Logger.Errorw("secondary shard: failed to acquire execution concurrency, due events stay cached", + "workflowID", m.cfg.WorkflowID, "err", err) + } + shardFailoverMetrics().RecordAutoDeferred(ctx, outcome) return } event, ok := m.popCachedEvent(c.eventID, monitoring.ShardFailoverCacheExitReplayed) diff --git a/core/services/workflows/syncer/v2/shard_failover_manager_test.go b/core/services/workflows/syncer/v2/shard_failover_manager_test.go index 43028a2e619..806603ad815 100644 --- a/core/services/workflows/syncer/v2/shard_failover_manager_test.go +++ b/core/services/workflows/syncer/v2/shard_failover_manager_test.go @@ -1092,10 +1092,10 @@ func TestShardFailoverManager_TimeoutBasedFailover_ExecutionConcurrencyBound(t * require.ErrorIs(t, err, v2.ErrAdmissionCache) } - time.Sleep(15 * time.Millisecond) - m.executeDueTimeoutBasedFailovers(t.Context()) - require.Eventually(t, func() bool { return len(eng.executedIDs()) == 3 }, 10*time.Second, 10*time.Millisecond, - "auto failover did not start executions up to the concurrency limit") + require.Eventually(t, func() bool { + m.executeDueTimeoutBasedFailovers(t.Context()) + return len(eng.executedIDs()) == 3 + }, 10*time.Second, 10*time.Millisecond, "auto failover did not start executions up to the concurrency limit") assert.Len(t, m.cacheIDs(), 7, "events over the concurrency limit were not kept in the cache") eng.release <- struct{}{} @@ -1106,6 +1106,119 @@ func TestShardFailoverManager_TimeoutBasedFailover_ExecutionConcurrencyBound(t * assert.Len(t, m.cacheIDs(), 6, "a later tick executed more cached events than the freed slots") } +// countingLimiter records Use and Free calls. useErr, when set, fails every Use; onUse runs +// after a successful Use. +type countingLimiter struct { + limits.ResourcePoolLimiter[int] + useErr error + onUse func() + + mu sync.Mutex + used int + freed int +} + +func (l *countingLimiter) Use(context.Context, int) error { + if l.useErr != nil { + return l.useErr + } + l.mu.Lock() + l.used++ + l.mu.Unlock() + if l.onUse != nil { + l.onUse() + } + return nil +} + +func (l *countingLimiter) Free(context.Context, int) error { + l.mu.Lock() + defer l.mu.Unlock() + l.freed++ + return nil +} + +func (l *countingLimiter) counts() (used, freed int) { + l.mu.Lock() + defer l.mu.Unlock() + return l.used, l.freed +} + +func newConcurrencyTestManager(t *testing.T, eng *recordingEngine, limiter limits.ResourcePoolLimiter[int], eventIDs ...string) *ShardFailoverManager { + t.Helper() + window := &fakeWindowLimiter{window: 10 * time.Millisecond} + m := newTimeoutBasedFailoverManager(t, eng, &fakeGateLimiter{open: true}, window, &switchableShardResolver{ownerDON: 1, found: true}) + m.cfg.Failover.ExecutionConcurrency = limiter + for _, id := range eventIDs { + require.ErrorIs(t, m.admissionCheck(t.Context(), timeoutBasedFailoverTestEvent(id)), v2.ErrAdmissionCache) + } + time.Sleep(15 * time.Millisecond) + return m +} + +func TestShardFailoverManager_TimeoutBasedFailover_LimiterErrorKeepsEventsCached(t *testing.T) { + t.Parallel() + + eng := &recordingEngine{} + m := newConcurrencyTestManager(t, eng, &countingLimiter{useErr: errors.New("limiter stopped")}, "evt-1", "evt-2", "evt-3") + + m.executeDueTimeoutBasedFailovers(t.Context()) + + assert.Empty(t, eng.executedIDs(), "events were executed although the limiter failed") + assert.Len(t, m.cacheIDs(), 3, "events were not kept in the cache after a limiter error") +} + +func TestShardFailoverManager_TimeoutBasedFailover_FreesSlotWhenExecuteTriggerFails(t *testing.T) { + t.Parallel() + + eng := &recordingEngine{execErr: errors.New("execution failed")} + limiter := &countingLimiter{} + m := newConcurrencyTestManager(t, eng, limiter, "evt-1") + + m.executeDueTimeoutBasedFailovers(t.Context()) + + require.Eventually(t, func() bool { + used, freed := limiter.counts() + return used == 1 && freed == 1 + }, 10*time.Second, 10*time.Millisecond, "slot was not freed after ExecuteTrigger failed") +} + +func TestShardFailoverManager_TimeoutBasedFailover_FreesSlotWhenEventLeftCache(t *testing.T) { + t.Parallel() + + eng := &recordingEngine{} + limiter := &countingLimiter{} + m := newConcurrencyTestManager(t, eng, limiter, "evt-1") + limiter.onUse = func() { m.removeCachedEvent("evt-1") } + + m.executeDueTimeoutBasedFailovers(t.Context()) + + used, freed := limiter.counts() + assert.Equal(t, 1, used) + assert.Equal(t, 1, freed, "slot leaked when the event left the cache before it was popped") + assert.Empty(t, eng.executedIDs()) +} + +func TestShardFailoverManager_TimeoutBasedFailover_FreesSlotWhenContextCancelled(t *testing.T) { + t.Parallel() + + eng := &releasableEngine{release: make(chan struct{})} + t.Cleanup(func() { close(eng.release) }) + limiter := &countingLimiter{} + m := newConcurrencyTestManager(t, &eng.recordingEngine, limiter, "evt-1") + m.SetEngine(eng) + + ctx, cancel := context.WithCancel(t.Context()) + m.executeDueTimeoutBasedFailovers(ctx) + require.Eventually(t, func() bool { return len(eng.executedIDs()) == 1 }, 10*time.Second, 10*time.Millisecond) + cancel() + + require.Eventually(t, func() bool { + _, freed := limiter.counts() + return freed == 1 + }, 10*time.Second, 10*time.Millisecond, "slot was not freed after the context was cancelled") +} + func TestShardFailoverManager_TimeoutBasedFailover_DisabledByDefault(t *testing.T) { t.Parallel() From 29b831604a452e9ca377362f836986bbf72f0c7b Mon Sep 17 00:00:00 2001 From: Dmitriy Tymoshchenko Date: Tue, 24 Nov 2026 12:50:02 +0100 Subject: [PATCH 3/3] [CRE-7138] Track events deferred by execution concurrency as a node-wide gauge --- .../monitoring/shard_failover_metrics.go | 16 +++---- .../monitoring/shard_failover_metrics_test.go | 12 ++--- .../syncer/v2/shard_failover_manager.go | 29 +++++++++++- .../syncer/v2/shard_failover_metrics_test.go | 45 ++++++++++++++++++- 4 files changed, 85 insertions(+), 17 deletions(-) diff --git a/core/services/workflows/monitoring/shard_failover_metrics.go b/core/services/workflows/monitoring/shard_failover_metrics.go index 925d40a5c4c..853391a1a1e 100644 --- a/core/services/workflows/monitoring/shard_failover_metrics.go +++ b/core/services/workflows/monitoring/shard_failover_metrics.go @@ -26,7 +26,7 @@ const ( ShardFailoverReplayMiss = "miss" ) -// Outcome values for platform_shard_failover_auto_deferred (low cardinality). +// Outcome values for platform_shard_failover_deferred_events (low cardinality). const ( ShardFailoverAutoDeferredConcurrencyLimit = "concurrency_limit" ShardFailoverAutoDeferredLimiterError = "limiter_error" @@ -46,7 +46,7 @@ type ShardFailoverMetrics struct { cachedEvents metric.Int64UpDownCounter cacheExitCounter metric.Int64Counter replayCounter metric.Int64Counter - autoDeferredCounter metric.Int64Counter + deferredEvents metric.Int64UpDownCounter replayDurationSeconds metric.Float64Histogram } @@ -113,8 +113,8 @@ func newShardFailoverMetricsWithMeter(meter metric.Meter) (*ShardFailoverMetrics if err != nil { return nil, err } - m.autoDeferredCounter, err = meter.Int64Counter("platform_shard_failover_auto_deferred", - metric.WithDescription("Timeout-based failover passes cut short before executing the remaining due events, by outcome: concurrency_limit (execution concurrency limit reached), limiter_error (limiter failed for another reason)")) + m.deferredEvents, err = meter.Int64UpDownCounter("platform_shard_failover_deferred_events", + metric.WithDescription("Due trigger events currently left cached because the last timeout-based failover pass stopped early, node-wide across all failover managers on this node, by outcome: concurrency_limit (execution concurrency limit reached), limiter_error (limiter failed for another reason)")) if err != nil { return nil, err } @@ -170,13 +170,13 @@ func (m *ShardFailoverMetrics) RecordReplay(ctx context.Context, outcome string) m.replayCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("outcome", outcome))) } -// RecordAutoDeferred counts one timeout-based failover pass that stopped before -// executing all due events. outcome must be a ShardFailoverAutoDeferred* constant. -func (m *ShardFailoverMetrics) RecordAutoDeferred(ctx context.Context, outcome string) { +// AddDeferredEvents moves the node-wide deferred-events total for outcome by +// delta. outcome must be a ShardFailoverAutoDeferred* constant. +func (m *ShardFailoverMetrics) AddDeferredEvents(ctx context.Context, outcome string, delta int64) { if m == nil { return } - m.autoDeferredCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("outcome", outcome))) + m.deferredEvents.Add(ctx, delta, metric.WithAttributes(attribute.String("outcome", outcome))) } // RecordReplayDuration records the duration of one failover replay, in diff --git a/core/services/workflows/monitoring/shard_failover_metrics_test.go b/core/services/workflows/monitoring/shard_failover_metrics_test.go index 74ff03ab6d0..eecb2341bfc 100644 --- a/core/services/workflows/monitoring/shard_failover_metrics_test.go +++ b/core/services/workflows/monitoring/shard_failover_metrics_test.go @@ -77,9 +77,9 @@ func TestShardFailoverMetrics_Emissions(t *testing.T) { fm.RecordTriggerCached(ctx) fm.RecordCacheExit(ctx, ShardFailoverCacheExitClosed, 1) fm.RecordReplay(ctx, ShardFailoverReplaySucceeded) - fm.RecordAutoDeferred(ctx, ShardFailoverAutoDeferredConcurrencyLimit) - fm.RecordAutoDeferred(ctx, ShardFailoverAutoDeferredConcurrencyLimit) - fm.RecordAutoDeferred(ctx, ShardFailoverAutoDeferredLimiterError) + fm.AddDeferredEvents(ctx, ShardFailoverAutoDeferredConcurrencyLimit, 7) + fm.AddDeferredEvents(ctx, ShardFailoverAutoDeferredConcurrencyLimit, -4) + fm.AddDeferredEvents(ctx, ShardFailoverAutoDeferredLimiterError, 2) fm.RecordReplayDuration(ctx, ShardFailoverReplaySucceeded, 1500*time.Millisecond) fm.RecordReplayDuration(ctx, ShardFailoverReplaySucceeded, 400*time.Millisecond) @@ -88,7 +88,7 @@ func TestShardFailoverMetrics_Emissions(t *testing.T) { nilFM.RecordTriggerCached(ctx) nilFM.RecordCacheExit(ctx, ShardFailoverCacheExitDrained, 1) nilFM.RecordReplay(ctx, ShardFailoverReplayFailed) - nilFM.RecordAutoDeferred(ctx, ShardFailoverAutoDeferredLimiterError) + nilFM.AddDeferredEvents(ctx, ShardFailoverAutoDeferredLimiterError, 1) nilFM.RecordReplayDuration(ctx, ShardFailoverReplayFailed, time.Second) var rm metricdata.ResourceMetrics @@ -130,8 +130,8 @@ func TestShardFailoverMetrics_Emissions(t *testing.T) { assert.Equal(t, int64(2), sums["platform_shard_failover_cache_exit"][ShardFailoverCacheExitExpired]) assert.Equal(t, int64(1), sums["platform_shard_failover_cache_exit"][ShardFailoverCacheExitClosed]) assert.Equal(t, int64(1), sums["platform_shard_failover_replay"][ShardFailoverReplaySucceeded]) - assert.Equal(t, int64(2), sums["platform_shard_failover_auto_deferred"][ShardFailoverAutoDeferredConcurrencyLimit]) - assert.Equal(t, int64(1), sums["platform_shard_failover_auto_deferred"][ShardFailoverAutoDeferredLimiterError]) + assert.Equal(t, int64(3), sums["platform_shard_failover_deferred_events"][ShardFailoverAutoDeferredConcurrencyLimit]) + assert.Equal(t, int64(2), sums["platform_shard_failover_deferred_events"][ShardFailoverAutoDeferredLimiterError]) assert.Equal(t, "s", units["platform_shard_failover_replay_duration_seconds"]) require.NotNil(t, replayHist, "replay duration histogram recorded") diff --git a/core/services/workflows/syncer/v2/shard_failover_manager.go b/core/services/workflows/syncer/v2/shard_failover_manager.go index 631b51a101c..68f2aa45d77 100644 --- a/core/services/workflows/syncer/v2/shard_failover_manager.go +++ b/core/services/workflows/syncer/v2/shard_failover_manager.go @@ -74,6 +74,11 @@ type ShardFailoverManager struct { autoExecCounter metric.Int64Counter + // deferred is this manager's share of the node-wide deferred-events total, under + // deferredOutcome. Only the timeout-based failover loop and close touch it. + deferred int64 + deferredOutcome string + mu sync.RWMutex cache map[string]cachedEvent @@ -223,6 +228,7 @@ func (m *ShardFailoverManager) close() error { fm := shardFailoverMetrics() fm.RecordCacheExit(context.Background(), monitoring.ShardFailoverCacheExitClosed, cached) } + m.setDeferredEvents(context.Background(), m.deferredOutcome, 0) return err } @@ -498,7 +504,10 @@ func (m *ShardFailoverManager) executeDueTimeoutBasedFailovers(ctx context.Conte } m.mu.RUnlock() - for _, c := range due { + deferred, deferredOutcome := int64(0), m.deferredOutcome + defer func() { m.setDeferredEvents(ctx, deferredOutcome, deferred) }() + + for i, c := range due { if m.cfg.Failover.TimeoutBasedFailoverGate.AllowErr(ctx) != nil { return } @@ -513,7 +522,7 @@ func (m *ShardFailoverManager) executeDueTimeoutBasedFailovers(ctx context.Conte m.cfg.Logger.Errorw("secondary shard: failed to acquire execution concurrency, due events stay cached", "workflowID", m.cfg.WorkflowID, "err", err) } - shardFailoverMetrics().RecordAutoDeferred(ctx, outcome) + deferred, deferredOutcome = int64(len(due)-i), outcome return } event, ok := m.popCachedEvent(c.eventID, monitoring.ShardFailoverCacheExitReplayed) @@ -557,6 +566,22 @@ func (m *ShardFailoverManager) executeDueTimeoutBasedFailovers(ctx context.Conte } } +// setDeferredEvents sets this manager's share of the node-wide deferred-events total to n +// under outcome, moving any previous share off its old outcome. +func (m *ShardFailoverManager) setDeferredEvents(ctx context.Context, outcome string, n int64) { + fm := shardFailoverMetrics() + if outcome != m.deferredOutcome { + if m.deferred != 0 { + fm.AddDeferredEvents(ctx, m.deferredOutcome, -m.deferred) + } + m.deferred, m.deferredOutcome = 0, outcome + } + if n != m.deferred { + fm.AddDeferredEvents(ctx, outcome, n-m.deferred) + m.deferred = n + } +} + // freeExecutionConcurrency expects ctx to carry the workflow's CRE: the limit is keyed on it. func (m *ShardFailoverManager) freeExecutionConcurrency(ctx context.Context) { if err := m.cfg.Failover.ExecutionConcurrency.Free(ctx, 1); err != nil { diff --git a/core/services/workflows/syncer/v2/shard_failover_metrics_test.go b/core/services/workflows/syncer/v2/shard_failover_metrics_test.go index 733fe932b99..18d191aa6ea 100644 --- a/core/services/workflows/syncer/v2/shard_failover_metrics_test.go +++ b/core/services/workflows/syncer/v2/shard_failover_metrics_test.go @@ -49,13 +49,14 @@ type failoverTotals struct { cacheExit map[string]int64 replay map[string]int64 replayCount map[string]uint64 + autoDeferred map[string]int64 } func collectFailoverTotals(t *testing.T) failoverTotals { t.Helper() var rm metricdata.ResourceMetrics require.NoError(t, shardFailoverReader.Collect(t.Context(), &rm)) - totals := failoverTotals{cacheExit: map[string]int64{}, replay: map[string]int64{}, replayCount: map[string]uint64{}} + totals := failoverTotals{cacheExit: map[string]int64{}, replay: map[string]int64{}, replayCount: map[string]uint64{}, autoDeferred: map[string]int64{}} for _, sm := range rm.ScopeMetrics { for _, m := range sm.Metrics { switch m.Name { @@ -77,6 +78,12 @@ func collectFailoverTotals(t *testing.T) failoverTotals { totals.replay[failoverOutcome(dp.Attributes)] += dp.Value } } + case "platform_shard_failover_deferred_events": + if sum, ok := m.Data.(metricdata.Sum[int64]); ok { + for _, dp := range sum.DataPoints { + totals.autoDeferred[failoverOutcome(dp.Attributes)] += dp.Value + } + } case "platform_shard_failover_replay_duration_seconds": if h, ok := m.Data.(metricdata.Histogram[float64]); ok { for _, dp := range h.DataPoints { @@ -389,3 +396,39 @@ func TestWorkflowRegistry_ShardFailoverEnabledGauge(t *testing.T) { require.True(t, ok, "enabled gauge recorded") assert.Equal(t, int64(0), enabled, "failover disabled") } + +//nolint:paralleltest // asserts deltas on process-global failover metrics +func TestShardFailoverMetrics_DeferredEventsTracksEventsWaitingForSlot(t *testing.T) { + cl, le := monitoring.ShardFailoverAutoDeferredConcurrencyLimit, monitoring.ShardFailoverAutoDeferredLimiterError + start := collectFailoverTotals(t) + delta := func(outcome string) int64 { + return collectFailoverTotals(t).autoDeferred[outcome] - start.autoDeferred[outcome] + } + + eng := &releasableEngine{release: make(chan struct{})} + t.Cleanup(func() { close(eng.release) }) + m := newConcurrencyTestManager(t, &eng.recordingEngine, limits.GlobalResourcePoolLimiter(2), "evt-1", "evt-2", "evt-3", "evt-4", "evt-5") + m.SetEngine(eng) + + m.executeDueTimeoutBasedFailovers(t.Context()) + assert.Equal(t, int64(3), delta(cl), "deferred_events must equal the due events left cached") + + m.executeDueTimeoutBasedFailovers(t.Context()) + assert.Equal(t, int64(3), delta(cl), "a later pass must not count the same waiting events again") + + eng.release <- struct{}{} + require.Eventually(t, func() bool { + m.executeDueTimeoutBasedFailovers(t.Context()) + return len(eng.executedIDs()) == 3 + }, 10*time.Second, 10*time.Millisecond) + assert.Equal(t, int64(2), delta(cl), "deferred_events must drop when a waiting event runs") + + require.NoError(t, m.close()) + assert.Equal(t, int64(0), delta(cl), "close must remove this manager's deferred events") + + m2 := newConcurrencyTestManager(t, &recordingEngine{}, &countingLimiter{useErr: errors.New("limiter stopped")}, "evt-1", "evt-2") + m2.executeDueTimeoutBasedFailovers(t.Context()) + assert.Equal(t, int64(2), delta(le)) + require.NoError(t, m2.close()) + assert.Equal(t, int64(0), delta(le)) +}