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
5 changes: 5 additions & 0 deletions .changeset/bound-failover-execution-concurrency.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"chainlink": patch
---

#internal Bound timeout-based shard failover executions by the workflow execution concurrency limit
21 changes: 21 additions & 0 deletions core/services/workflows/monitoring/shard_failover_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ const (
ShardFailoverReplayMiss = "miss"
)

// Outcome values for platform_shard_failover_deferred_events (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
Expand All @@ -40,6 +46,7 @@ type ShardFailoverMetrics struct {
cachedEvents metric.Int64UpDownCounter
cacheExitCounter metric.Int64Counter
replayCounter metric.Int64Counter
deferredEvents metric.Int64UpDownCounter
replayDurationSeconds metric.Float64Histogram
}

Expand Down Expand Up @@ -106,6 +113,11 @@ func newShardFailoverMetricsWithMeter(meter metric.Meter) (*ShardFailoverMetrics
if err != nil {
return nil, err
}
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
}
m.replayDurationSeconds, err = meter.Float64Histogram("platform_shard_failover_replay_duration_seconds",
metric.WithDescription("Duration of failover replays of cached trigger events"),
metric.WithUnit("s"),
Expand Down Expand Up @@ -158,6 +170,15 @@ func (m *ShardFailoverMetrics) RecordReplay(ctx context.Context, outcome string)
m.replayCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("outcome", outcome)))
}

// 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.deferredEvents.Add(ctx, delta, 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ func TestShardFailoverMetrics_Emissions(t *testing.T) {
fm.RecordTriggerCached(ctx)
fm.RecordCacheExit(ctx, ShardFailoverCacheExitClosed, 1)
fm.RecordReplay(ctx, ShardFailoverReplaySucceeded)
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)

Expand All @@ -85,6 +88,7 @@ func TestShardFailoverMetrics_Emissions(t *testing.T) {
nilFM.RecordTriggerCached(ctx)
nilFM.RecordCacheExit(ctx, ShardFailoverCacheExitDrained, 1)
nilFM.RecordReplay(ctx, ShardFailoverReplayFailed)
nilFM.AddDeferredEvents(ctx, ShardFailoverAutoDeferredLimiterError, 1)
nilFM.RecordReplayDuration(ctx, ShardFailoverReplayFailed, time.Second)

var rm metricdata.ResourceMetrics
Expand Down Expand Up @@ -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(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")
Expand Down
1 change: 1 addition & 0 deletions core/services/workflows/syncer/v2/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to be careful to not reuse the same limiter more than once, otherwise we will double-count.
IIUC it's fine here because ShardFailoverManager calls ExecuteTrigger directly. But that might change in the future when we start putting failover events on the trigger queue. Maybe worth leaving a comment here.

},
Logger: h.lggr,
})
Expand Down
53 changes: 52 additions & 1 deletion core/services/workflows/syncer/v2/shard_failover_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -130,6 +135,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.
Expand All @@ -139,6 +147,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)
Expand Down Expand Up @@ -217,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
}

Expand Down Expand Up @@ -492,15 +504,30 @@ 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
}

switch m.checkShardOwnership(ctx) {
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)
}
deferred, deferredOutcome = int64(len(due)-i), outcome
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",
Expand All @@ -519,6 +546,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,
Expand All @@ -538,6 +566,29 @@ 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 {
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) {
Expand Down
158 changes: 158 additions & 0 deletions core/services/workflows/syncer/v2/shard_failover_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1061,6 +1061,164 @@ 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)
}

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{}{}
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")
}

// 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()

Expand Down
Loading
Loading