From 2a4ec33c33beed3701b6a0be2d3803ab7e825127 Mon Sep 17 00:00:00 2001 From: Tarcisio Ferraz Date: Mon, 23 Nov 2026 10:21:54 -0300 Subject: [PATCH 1/4] backpressure and other improvements --- pkg/durableemitter/backpressure_test.go | 220 ++++++++++++++++++ pkg/durableemitter/durable_emitter.go | 202 ++++++++++++++-- pkg/durableemitter/durable_emitter_metrics.go | 64 +++-- pkg/durableemitter/observable_store.go | 19 ++ pkg/durableemitter/process_stats.go | 8 +- pkg/durableemitter/process_stats_stub.go | 4 +- pkg/durableemitter/store.go | 17 ++ pkg/loop/config_test.go | 14 ++ pkg/loop/server.go | 5 +- pkg/loop/telemetry/config.go | 31 +++ 10 files changed, 529 insertions(+), 55 deletions(-) create mode 100644 pkg/durableemitter/backpressure_test.go diff --git a/pkg/durableemitter/backpressure_test.go b/pkg/durableemitter/backpressure_test.go new file mode 100644 index 0000000000..a13fc7c6d2 --- /dev/null +++ b/pkg/durableemitter/backpressure_test.go @@ -0,0 +1,220 @@ +package durableemitter + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/sdk/metric/metricdata" + + "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" +) + +// estimatingStore adds a settable BacklogEstimator to MemDurableEventStore. +type estimatingStore struct { + *MemDurableEventStore + estimate atomic.Int64 +} + +var _ BacklogEstimator = (*estimatingStore)(nil) + +func (s *estimatingStore) EstimateBacklog(context.Context) (int64, error) { + return s.estimate.Load(), nil +} + +// faultyStore fails BatchDelete while failDeletes is set and counts store reads. +type faultyStore struct { + *MemDurableEventStore + failDeletes atomic.Bool + listCalls atomic.Int64 + observeCalls atomic.Int64 +} + +func (s *faultyStore) BatchDelete(ctx context.Context, ids []int64) (int64, error) { + if s.failDeletes.Load() { + return 0, errors.New("delete timeout") + } + return s.MemDurableEventStore.BatchDelete(ctx, ids) +} + +func (s *faultyStore) ListPending(ctx context.Context, createdBefore, afterCreatedAt time.Time, afterID int64, limit int) ([]DurableEvent, error) { + s.listCalls.Add(1) + return s.MemDurableEventStore.ListPending(ctx, createdBefore, afterCreatedAt, afterID, limit) +} + +func (s *faultyStore) ObserveDurableQueue(ctx context.Context, eventTTL time.Duration) (DurableQueueStats, error) { + s.observeCalls.Add(1) + return s.MemDurableEventStore.ObserveDurableQueue(ctx, eventTTL) +} + +func TestDurableEmitter_BackpressureRejectsWhileBacklogged(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} + store.estimate.Store(100) + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 100 + cfg.BacklogPollInterval = 10 * time.Millisecond + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + // The estimate is seeded at start, so the first emit is already rejected. + err := em.Emit(ctx, []byte("rejected"), testEmitAttrs()...) + require.ErrorIs(t, err, ErrBacklogged) + assert.Equal(t, 0, store.Len(), "rejected events must not be persisted") + + store.estimate.Store(99) + require.Eventually(t, func() bool { + return em.Emit(ctx, []byte("accepted"), testEmitAttrs()...) == nil + }, 2*time.Second, 10*time.Millisecond, "emits resume once the polled estimate drops below MaxQueueDepth") +} + +func TestDurableEmitter_BackpressureCountsOwnInsertsBetweenPolls(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} + be := newTestBatchEmitter() + be.setPublishErr(errors.New("chip unavailable")) // rows are never deleted + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 2 + cfg.BacklogPollInterval = time.Hour + cfg.RetransmitInterval = time.Hour + em := newTestDurableEmitter(t, store, be, &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + require.NoError(t, em.Emit(ctx, []byte("1"), testEmitAttrs()...)) + require.NoError(t, em.Emit(ctx, []byte("2"), testEmitAttrs()...)) + require.ErrorIs(t, em.Emit(ctx, []byte("3"), testEmitAttrs()...), ErrBacklogged) + assert.Equal(t, 2, store.Len()) +} + +func TestDurableEmitter_BackpressureOffByDefault(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} + store.estimate.Store(DefaultMaxQueueDepth) + + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), nil) + servicetest.Run(t, em) + + require.NoError(t, em.Emit(t.Context(), []byte("x"), testEmitAttrs()...)) + assert.Nil(t, em.backlogEstimator, "the backlog is not polled unless back-pressure is enabled") +} + +func TestDurableEmitter_BackpressureDisabledWithoutEstimator(t *testing.T) { + store := NewMemDurableEventStore() + be := newTestBatchEmitter() + be.setPublishErr(errors.New("chip unavailable")) + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 1 + cfg.RetransmitInterval = time.Hour + em := newTestDurableEmitter(t, store, be, &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + for range 3 { + require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) + } + assert.Equal(t, 3, store.Len()) +} + +func TestDurableEmitter_RetransmitPausesWhileDeletesFail(t *testing.T) { + store := &faultyStore{MemDurableEventStore: NewMemDurableEventStore()} + store.failDeletes.Store(true) + + cfg := DefaultConfig() + cfg.RetransmitInterval = 10 * time.Millisecond + cfg.RetransmitAfter = time.Millisecond + cfg.DeleteFailureRetransmitBackoff = 2 * time.Second + cfg.DeleteBatchFlushInterval = time.Millisecond + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + require.NoError(t, em.Emit(ctx, []byte("stuck"), testEmitAttrs()...)) + require.Eventually(t, func() bool { return em.deleteFailedAt.Load() != 0 }, 2*time.Second, 5*time.Millisecond) + + listed := store.listCalls.Load() + time.Sleep(150 * time.Millisecond) // ~15 ticks, all inside the backoff window + assert.Equal(t, listed, store.listCalls.Load(), "retransmit must not list pending rows while deletes fail") + + store.failDeletes.Store(false) + require.Eventually(t, func() bool { return store.Len() == 0 }, 10*time.Second, 10*time.Millisecond, + "retransmit resumes after the backoff and the row is deleted once deletes succeed") +} + +func TestDurableEmitter_PluginMetricsLabelledAndSkipQueueScan(t *testing.T) { + meter, reader := newTestMeter(t) + store := &faultyStore{MemDurableEventStore: NewMemDurableEventStore()} + + cfg := DefaultConfig() + cfg.Metrics = &DurableEmitterMetricsConfig{PollInterval: 10 * time.Millisecond, Instance: "cron"} + em, err := NewDurableEmitter(store, newTestBatchEmitter(), false, cfg, logger.Test(t), meter) + require.NoError(t, err) + servicetest.Run(t, em) + ctx := t.Context() + + require.NoError(t, em.Emit(ctx, []byte("m"), testEmitAttrs()...)) + time.Sleep(80 * time.Millisecond) // several metrics polls + + assert.Zero(t, store.observeCalls.Load(), "only the host process scans the shared queue") + + var rm metricdata.ResourceMetrics + require.NoError(t, reader.Collect(ctx, &rm)) + var sawEmit bool + for _, sm := range rm.ScopeMetrics { + for _, m := range sm.Metrics { + assert.NotEqual(t, "durable_emitter.queue.depth", m.Name, "plugins must not record queue depth") + if m.Name != "durable_emitter.emit.success" { + continue + } + sum, ok := m.Data.(metricdata.Sum[int64]) + require.True(t, ok) + for _, dp := range sum.DataPoints { + sawEmit = true + assert.True(t, hasMetricStringAttr(dp.Attributes, "emitter_instance", "cron")) + } + } + } + assert.True(t, sawEmit, "expected durable_emitter.emit.success data points") +} + +func TestDurableEmitter_HostObservesQueueWithDefaultInstance(t *testing.T) { + meter, reader := newTestMeter(t) + store := &faultyStore{MemDurableEventStore: NewMemDurableEventStore()} + + cfg := DefaultConfig() + cfg.RetransmitInterval = time.Hour + cfg.Metrics = &DurableEmitterMetricsConfig{PollInterval: 10 * time.Millisecond} + em, err := NewDurableEmitter(store, newTestBatchEmitter(), true, cfg, logger.Test(t), meter) + require.NoError(t, err) + servicetest.Run(t, em) + ctx := t.Context() + + require.Eventually(t, func() bool { return store.observeCalls.Load() > 0 }, 2*time.Second, 10*time.Millisecond) + + var rm metricdata.ResourceMetrics + require.NoError(t, reader.Collect(ctx, &rm)) + var sawDepth bool + for _, sm := range rm.ScopeMetrics { + for _, m := range sm.Metrics { + if m.Name != "durable_emitter.queue.depth" { + continue + } + g, ok := m.Data.(metricdata.Gauge[int64]) + require.True(t, ok) + for _, dp := range g.DataPoints { + sawDepth = true + assert.True(t, hasMetricStringAttr(dp.Attributes, "emitter_instance", "host")) + } + } + } + assert.True(t, sawDepth, "expected durable_emitter.queue.depth data points from the host") +} diff --git a/pkg/durableemitter/durable_emitter.go b/pkg/durableemitter/durable_emitter.go index 5a0ad088f4..bf92ee1758 100644 --- a/pkg/durableemitter/durable_emitter.go +++ b/pkg/durableemitter/durable_emitter.go @@ -110,6 +110,20 @@ type Config struct { // DeleteBatchWorkers is the number of concurrent batch-delete goroutines. // Zero defaults to 2. DeleteBatchWorkers int + // BackpressureEnabled makes Emit reject events with ErrBacklogged, without + // persisting them, once the estimated backlog of the shared store reaches + // MaxQueueDepth. Rejected events are lost. Requires a store implementing + // BacklogEstimator. + BackpressureEnabled bool + // MaxQueueDepth is the back-pressure threshold. Zero defaults to DefaultMaxQueueDepth. + MaxQueueDepth int64 + // BacklogPollInterval is how often the backlog estimate is refreshed from the + // store. Zero defaults to DefaultBacklogPollInterval. + BacklogPollInterval time.Duration + // DeleteFailureRetransmitBackoff pauses the retransmit loop for this long after + // a delivery delete fails, as rows that cannot be deleted would only be re-sent. + // Zero defaults to DefaultDeleteFailureRetransmitBackoff. + DeleteFailureRetransmitBackoff time.Duration } // Hooks records delivery latency to locate pipeline bottlenecks. @@ -132,6 +146,16 @@ const DefaultMaxEventBytes = 1024 * 1024 // ErrEventTooLarge is returned by Emit for an event larger than MaxEventBytes. var ErrEventTooLarge = errors.New("durable emitter: event exceeds max size") +// ErrBacklogged is returned by Emit while back-pressure rejects events. +var ErrBacklogged = errors.New("durable emitter: backlog exceeds max queue depth") + +// Defaults for the back-pressure and retransmit backoff settings in Config. +const ( + DefaultMaxQueueDepth = 500_000 + DefaultBacklogPollInterval = 5 * time.Second + DefaultDeleteFailureRetransmitBackoff = 30 * time.Second +) + func DefaultConfig() Config { return Config{ MaxEventBytes: DefaultMaxEventBytes, @@ -147,6 +171,7 @@ func DefaultConfig() Config { DeleteBatchSize: 100, DeleteBatchFlushInterval: 500 * time.Millisecond, DeleteBatchWorkers: 2, + MaxQueueDepth: DefaultMaxQueueDepth, // Metrics is opt-in: callers who want instrumentation must set this // and pass a metric.Meter to NewDurableEmitter. Metrics: nil, @@ -228,6 +253,15 @@ type DurableEmitter struct { // Accessed only from the single retransmit-loop goroutine — no locking. retransmitCursorTs time.Time retransmitCursorID int64 + + // backlogEstimator is non-nil when back-pressure is enabled. backlog is the + // polled estimate, adjusted in between by this process's own writes. + backlogEstimator BacklogEstimator + backlog atomic.Int64 + + // deleteFailedAt is the UnixNano time of the last failed delivery delete, or 0 + // once a delete succeeds. + deleteFailedAt atomic.Int64 } // Compile-time assertion that *DurableEmitter exposes the canonical emit and @@ -264,13 +298,21 @@ func NewDurableEmitter( } bi, isStoreBatch := store.(BatchInserter) _, isQueue := store.(DurableQueueObserver) + _, isEstimator := store.(BacklogEstimator) var m *durableEmitterMetrics if cfg.Metrics != nil { if meter == nil { return nil, errors.New("durable emitter metrics enabled but meter is nil") } + instance := cfg.Metrics.Instance + if instance == "" { + instance = "plugin" + if retransmitEnabled { + instance = "host" + } + } var err error - m, err = newDurableEmitterMetrics(meter, chipingressbatch.ClientNameDurableEmitter) + m, err = newDurableEmitterMetrics(meter, chipingressbatch.ClientNameDurableEmitter, instance) if err != nil { return nil, fmt.Errorf("durable emitter metrics: %w", err) } @@ -306,6 +348,27 @@ func NewDurableEmitter( "insertBatchFlushInterval", cfg.InsertBatchFlushInterval) } + if d.cfg.MaxQueueDepth <= 0 { + d.cfg.MaxQueueDepth = DefaultMaxQueueDepth + } + if d.cfg.BacklogPollInterval <= 0 { + d.cfg.BacklogPollInterval = DefaultBacklogPollInterval + } + if d.cfg.DeleteFailureRetransmitBackoff <= 0 { + d.cfg.DeleteFailureRetransmitBackoff = DefaultDeleteFailureRetransmitBackoff + } + if cfg.BackpressureEnabled { + if isEstimator { + // Asserted on the possibly metrics-wrapped store so estimates are instrumented. + d.backlogEstimator = store.(BacklogEstimator) + d.eng.Infow("DurableEmitter: back-pressure enabled", + "maxQueueDepth", d.cfg.MaxQueueDepth, + "backlogPollInterval", d.cfg.BacklogPollInterval) + } else { + d.eng.Warn("DurableEmitter: back-pressure enabled but the store cannot estimate its backlog; ignoring") + } + } + if cfg.DeleteBatchSize > 0 { chanSize := max(cfg.DeleteBatchSize*200, 10_000) d.deleteCh = make(chan int64, chanSize) @@ -345,6 +408,12 @@ func (d *DurableEmitter) start(ctx context.Context) error { } } + if d.backlogEstimator != nil { + // Seed before accepting emits so a restart into an existing backlog is covered. + d.refreshBacklog(ctx) + d.wg.Go(d.backlogLoop) + } + if d.retransmitEnabled { d.wg.Go(d.retransmitLoop) if !d.cfg.DisablePruning { @@ -357,6 +426,58 @@ func (d *DurableEmitter) start(ctx context.Context) error { return nil } +func (d *DurableEmitter) backlogLoop() { + ticker := time.NewTicker(d.cfg.BacklogPollInterval) + defer ticker.Stop() + + ctx, cancel := d.stopCh.NewCtx() + defer cancel() + for { + select { + case <-d.stopCh: + return + case <-ticker.C: + d.refreshBacklog(ctx) + } + } +} + +// refreshBacklog replaces the backlog estimate with the store's. On error the +// previous estimate is kept. +func (d *DurableEmitter) refreshBacklog(ctx context.Context) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + n, err := d.backlogEstimator.EstimateBacklog(ctx) + if err != nil { + d.eng.Warnw("DurableEmitter: backlog estimate failed; keeping last estimate", "estimate", d.backlog.Load(), "error", err) + return + } + d.backlog.Store(n) +} + +// backlogged reports whether Emit should reject with ErrBacklogged. +func (d *DurableEmitter) backlogged() bool { + return d.backlogEstimator != nil && d.backlog.Load() >= d.cfg.MaxQueueDepth +} + +// adjustBacklog applies this process's own store writes to the estimate between polls. +func (d *DurableEmitter) adjustBacklog(delta int64) { + if d.backlogEstimator != nil && delta != 0 { + d.backlog.Add(delta) + } +} + +// recordDeleteResult tracks delivery-delete health for the retransmit backoff +// and applies successful deletes to the backlog estimate. +func (d *DurableEmitter) recordDeleteResult(deleted int64, err error) { + if err != nil { + d.deleteFailedAt.Store(time.Now().UnixNano()) + return + } + d.deleteFailedAt.Store(0) + d.adjustBacklog(-deleted) +} + // EmitAsync runs Emit in a background goroutine and ignores the result, so the // caller is never blocked on the DB insert. Use it on hot paths where the // durable emitter's value is persistence for retransmit (not inline delivery) @@ -386,13 +507,19 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) tEmitTotal := time.Now() defer func() { if d.metrics != nil { - d.metrics.emitTotalDuration.Record(ctx, time.Since(tEmitTotal).Seconds()) + d.metrics.emitTotalDuration.Record(ctx, time.Since(tEmitTotal).Seconds(), d.metrics.with()) } }() emitFail := func() { if d.metrics != nil { - d.metrics.emitFail.Add(ctx, 1) + d.metrics.emitFail.Add(ctx, 1, d.metrics.with()) + } + } + if d.backlogged() { + if d.metrics != nil { + d.metrics.backpressureReject.Add(ctx, 1, d.metrics.with()) } + return ErrBacklogged } sourceDomain, entityType, err := beholder.ExtractSourceAndType(attrKVs...) if err != nil { @@ -478,9 +605,9 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) if d.metrics != nil { d.metrics.recordEmitDuration(ctx, insElapsed, res.err) if res.err != nil { - d.metrics.emitFail.Add(ctx, 1) + d.metrics.emitFail.Add(ctx, 1, d.metrics.with()) } else { - d.metrics.emitSuccess.Add(ctx, 1) + d.metrics.emitSuccess.Add(ctx, 1, d.metrics.with()) } } if res.err != nil { @@ -497,15 +624,16 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) if d.metrics != nil { d.metrics.recordEmitDuration(ctx, insElapsed, err) if err != nil { - d.metrics.emitFail.Add(ctx, 1) + d.metrics.emitFail.Add(ctx, 1, d.metrics.with()) } else { - d.metrics.emitSuccess.Add(ctx, 1) + d.metrics.emitSuccess.Add(ctx, 1, d.metrics.with()) } } if err != nil { return fmt.Errorf("failed to persist event: %w", err) } } + d.adjustBacklog(1) // Hand off to the batch emitter. The callback fires once the batch // containing this event is sent (success or failure). @@ -514,7 +642,7 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) d.eng.Warnw("DurableEmitter: batch emitter buffer full, relying on retransmit", "id", id) if d.metrics != nil { d.metrics.batchEnqueueBufferFull.Add(ctx, 1, - metric.WithAttributes(attribute.String("phase", publishPhaseBatch.String()))) + d.metrics.with(attribute.String("phase", publishPhaseBatch.String()))) } } return nil @@ -574,12 +702,13 @@ func (d *DurableEmitter) deliveryCallback(id int64, eventPb *chipingress.CloudEv if h := d.cfg.Hooks; h != nil && h.OnBatchDelete != nil { h.OnBatchDelete(deleteElapsed, int(deleted)) } + d.recordDeleteResult(deleted, deleteErr) if deleteErr != nil { d.eng.Errorw("failed to delete event from persistence", "id", id, "error", deleteErr) return } if d.metrics != nil { - d.metrics.deliverComplete.Add(delCtx, deleted) + d.metrics.deliverComplete.Add(delCtx, deleted, d.metrics.with()) } } } @@ -750,12 +879,13 @@ func (d *DurableEmitter) flushDeletes(ids []int64) { if h := d.cfg.Hooks; h != nil && h.OnBatchDelete != nil { h.OnBatchDelete(deleteElapsed, int(deleted)) } + d.recordDeleteResult(deleted, err) if err != nil { d.eng.Errorw("failed to batch delete delivered events", "count", len(ids), "error", err) return } if d.metrics != nil { - d.metrics.deliverComplete.Add(ctx, deleted) + d.metrics.deliverComplete.Add(ctx, deleted, d.metrics.with()) } } @@ -774,6 +904,13 @@ func (d *DurableEmitter) retransmitLoop() { } func (d *DurableEmitter) retransmitPending() { + if failedAt := d.deleteFailedAt.Load(); failedAt != 0 { + if since := time.Since(time.Unix(0, failedAt)); since < d.cfg.DeleteFailureRetransmitBackoff { + d.eng.Debugw("DurableEmitter: retransmit paused while delivery deletes fail", "last_delete_failure_ago", since.String()) + return + } + } + ctx, cancel := d.stopCh.NewCtx() defer cancel() @@ -846,7 +983,7 @@ func (d *DurableEmitter) retransmit(ctx context.Context, pending []DurableEvent) skipped++ if d.metrics != nil { d.metrics.batchEnqueueBufferFull.Add(ctx, 1, - metric.WithAttributes(attribute.String("phase", publishPhaseRetransmit.String()))) + d.metrics.with(attribute.String("phase", publishPhaseRetransmit.String()))) } } else { enqueued++ @@ -937,6 +1074,7 @@ func (d *DurableEmitter) purgeExpired(ctx context.Context) { var purged int64 var purgeErr error defer func() { + d.adjustBacklog(-purged) span.SetAttributes(attribute.Int64("purged", purged)) if purgeErr != nil { span.RecordError(purgeErr) @@ -1008,6 +1146,30 @@ drain: d.eng.Infow("purged expired events", "count", total, "undecodable", undecodable, "by_domain_subject", breakdown) } +// observeQueue records the queue gauges. Only the retransmit-owning process +// scans the shared store; while back-pressure is engaged, depth comes from the +// estimate instead of the scan. +func (d *DurableEmitter) observeQueue(ctx context.Context, mc *DurableEmitterMetricsConfig) { + if !d.retransmitEnabled || !d.isStoreQueue { + return + } + if d.backlogged() { + d.metrics.queueDepth.Record(ctx, d.backlog.Load(), d.metrics.with()) + return + } + obs, ok := d.store.(DurableQueueObserver) + if !ok { + return + } + st, err := obs.ObserveDurableQueue(ctx, d.cfg.EventTTL) + if err != nil { + d.eng.Debugw("DurableEmitter: queue observe failed; keeping last depth", "error", err) + return + } + d.metrics.queueDepth.Record(ctx, st.TotalRows, d.metrics.with()) + d.metrics.recordQueueStats(ctx, st, mc.MaxQueuePayloadBytes) +} + func (d *DurableEmitter) metricsLoop() { mc := d.cfg.Metrics poll := mc.PollInterval @@ -1025,28 +1187,20 @@ func (d *DurableEmitter) metricsLoop() { case <-d.stopCh: return case <-ticker.C: - if obs, ok := d.store.(DurableQueueObserver); ok && d.isStoreQueue { - st, err := obs.ObserveDurableQueue(ctx, d.cfg.EventTTL) - if err != nil { - d.eng.Debugw("DurableEmitter: queue observe failed; keeping last depth", "error", err) - } else { - d.metrics.queueDepth.Record(ctx, st.TotalRows) - d.metrics.recordQueueStats(ctx, st, mc.MaxQueuePayloadBytes) - } - } + d.observeQueue(ctx, mc) if d.insertCh != nil { if c := cap(d.insertCh); c > 0 { - d.metrics.insertCoalescerFill.Record(ctx, float64(len(d.insertCh))/float64(c)) + d.metrics.insertCoalescerFill.Record(ctx, float64(len(d.insertCh))/float64(c), d.metrics.with()) } } else { - d.metrics.insertCoalescerFill.Record(ctx, 0) + d.metrics.insertCoalescerFill.Record(ctx, 0, d.metrics.with()) } if d.deleteCh != nil { if c := cap(d.deleteCh); c > 0 { - d.metrics.deleteCoalescerFill.Record(ctx, float64(len(d.deleteCh))/float64(c)) + d.metrics.deleteCoalescerFill.Record(ctx, float64(len(d.deleteCh))/float64(c), d.metrics.with()) } } else { - d.metrics.deleteCoalescerFill.Record(ctx, 0) + d.metrics.deleteCoalescerFill.Record(ctx, 0, d.metrics.with()) } d.metrics.pollProcessGauges(ctx) } diff --git a/pkg/durableemitter/durable_emitter_metrics.go b/pkg/durableemitter/durable_emitter_metrics.go index 6883002428..ebaa823110 100644 --- a/pkg/durableemitter/durable_emitter_metrics.go +++ b/pkg/durableemitter/durable_emitter_metrics.go @@ -22,6 +22,11 @@ type DurableEmitterMetricsConfig struct { PollInterval time.Duration // MaxQueuePayloadBytes, if > 0, records capacity_usage_ratio = queue_payload_bytes / max. MaxQueuePayloadBytes int64 + // Instance is recorded as the emitter_instance attribute on every metric, so + // emitters of processes sharing a node (host and LOOP plugins) export distinct + // series. Empty defaults to "host" for the retransmit-owning process and + // "plugin" otherwise. + Instance string } // publishPhase identifies the delivery path recorded by publish metrics. @@ -44,7 +49,10 @@ func (p publishPhase) String() string { } type durableEmitterMetrics struct { - clientName string + clientName string + // base holds the attributes recorded on every measurement. + base []attribute.KeyValue + backpressureReject metric.Int64Counter emitSuccess metric.Int64Counter emitFail metric.Int64Counter emitDuration metric.Float64Histogram @@ -94,14 +102,22 @@ var batchSizeBuckets = metric.WithExplicitBucketBoundaries( // newDurableEmitterMetrics registers all DurableEmitter instruments on the // supplied meter. The caller is responsible for the meter's scope (the // instrument prefix below acts as the metric namespace). -func newDurableEmitterMetrics(meter metric.Meter, clientName string) (*durableEmitterMetrics, error) { +func newDurableEmitterMetrics(meter metric.Meter, clientName, instance string) (*durableEmitterMetrics, error) { if meter == nil { return nil, errors.New("durable emitter metrics: meter is nil") } m := &durableEmitterMetrics{ clientName: clientName, + base: []attribute.KeyValue{attribute.String("emitter_instance", instance)}, } var err error + if m.backpressureReject, err = meter.Int64Counter( + "durable_emitter.emit.backpressure_rejects", + metric.WithUnit("{call}"), + metric.WithDescription("Emit calls rejected with ErrBacklogged because the estimated backlog reached MaxQueueDepth"), + ); err != nil { + return nil, err + } if m.emitSuccess, err = meter.Int64Counter( "durable_emitter.emit.success", metric.WithUnit("{call}"), @@ -278,13 +294,18 @@ func newDurableEmitterMetrics(meter metric.Meter, clientName string) (*durableEm return m, nil } +// with returns the measurement option carrying the base attributes plus kvs. +func (m *durableEmitterMetrics) with(kvs ...attribute.KeyValue) metric.MeasurementOption { + return metric.WithAttributes(append(append(make([]attribute.KeyValue, 0, len(m.base)+len(kvs)), m.base...), kvs...)...) +} + // recordExpiredPurged counts events the expiry loop deleted, attributed by // domain (CloudEvent source) and subject (CloudEvent type). func (m *durableEmitterMetrics) recordExpiredPurged(ctx context.Context, domain, subject string, n int64) { if m == nil || n <= 0 { return } - m.expiredPurged.Add(ctx, n, metric.WithAttributes( + m.expiredPurged.Add(ctx, n, m.with( attribute.String("domain", domain), attribute.String("subject", subject), )) @@ -294,19 +315,18 @@ func (m *durableEmitterMetrics) recordStoreOp(ctx context.Context, op string, el if m == nil { return } - attrs := metric.WithAttributes( + m.storeOps.Add(ctx, 1, m.with( attribute.String("operation", op), attribute.Bool("error", opErr != nil), - ) - m.storeOps.Add(ctx, 1, attrs) - m.storeOpDuration.Record(ctx, elapsed.Seconds(), metric.WithAttributes(attribute.String("operation", op))) + )) + m.storeOpDuration.Record(ctx, elapsed.Seconds(), m.with(attribute.String("operation", op))) } func (m *durableEmitterMetrics) recordInsertBatchSize(ctx context.Context, n int, batchErr error) { if m == nil { return } - m.insertBatchSize.Record(ctx, int64(n), metric.WithAttributes(attribute.Bool("error", batchErr != nil))) + m.insertBatchSize.Record(ctx, int64(n), m.with(attribute.Bool("error", batchErr != nil))) } // recordQueueStats records the DB-derived queue statistics (payload bytes, @@ -317,15 +337,15 @@ func (m *durableEmitterMetrics) recordQueueStats(ctx context.Context, st Durable if m == nil { return } - m.queuePayloadBytes.Record(ctx, st.PayloadBytes) + m.queuePayloadBytes.Record(ctx, st.PayloadBytes, m.with()) if st.Depth == 0 { - m.queueOldestAgeSec.Record(ctx, 0) + m.queueOldestAgeSec.Record(ctx, 0, m.with()) } else { - m.queueOldestAgeSec.Record(ctx, st.OldestPendingAge.Seconds()) + m.queueOldestAgeSec.Record(ctx, st.OldestPendingAge.Seconds(), m.with()) } - m.queueTTLBudgetSec.Record(ctx, int64(st.TTLBudget/time.Second)) + m.queueTTLBudgetSec.Record(ctx, int64(st.TTLBudget/time.Second), m.with()) if maxBytes > 0 { - m.queueCapacityRatio.Record(ctx, float64(st.PayloadBytes)/float64(maxBytes)) + m.queueCapacityRatio.Record(ctx, float64(st.PayloadBytes)/float64(maxBytes), m.with()) } } @@ -333,29 +353,25 @@ func (m *durableEmitterMetrics) recordEmitDuration(ctx context.Context, elapsed if m == nil { return } - m.emitDuration.Record(ctx, elapsed.Seconds(), - metric.WithAttributes(attribute.Bool("error", err != nil)), - ) + m.emitDuration.Record(ctx, elapsed.Seconds(), m.with(attribute.Bool("error", err != nil))) } func (m *durableEmitterMetrics) recordPublish(ctx context.Context, elapsed time.Duration, phase publishPhase, err error) { if m == nil { return } - m.publishDuration.Record(ctx, elapsed.Seconds(), - metric.WithAttributes( - attribute.String("phase", phase.String()), - attribute.Bool("error", err != nil), - attribute.String("client_name", m.clientName), - ), - ) + m.publishDuration.Record(ctx, elapsed.Seconds(), m.with( + attribute.String("phase", phase.String()), + attribute.Bool("error", err != nil), + attribute.String("client_name", m.clientName), + )) } func (m *durableEmitterMetrics) recordPublishBatchEvent(ctx context.Context, phase publishPhase, err error) { if m == nil { return } - attrs := metric.WithAttributes( + attrs := m.with( attribute.String("phase", phase.String()), attribute.String("client_name", m.clientName), ) diff --git a/pkg/durableemitter/observable_store.go b/pkg/durableemitter/observable_store.go index 7e969f52d3..65d870345a 100644 --- a/pkg/durableemitter/observable_store.go +++ b/pkg/durableemitter/observable_store.go @@ -63,6 +63,14 @@ type ExpiredPurger interface { DeleteExpiredBatch(ctx context.Context, ttl time.Duration, limit int) ([][]byte, error) } +// BacklogEstimator is optionally implemented by DurableEventStore implementations +// that can estimate the number of rows in the queue without scanning it. +// DurableEmitter polls it for back-pressure (Config.BackpressureEnabled) from +// every process sharing the store, so it must stay cheap on a large table. +type BacklogEstimator interface { + EstimateBacklog(ctx context.Context) (int64, error) +} + // DurableEventStore abstracts the persistence layer for durable chip events. // Implementations must be safe for concurrent use. type DurableEventStore interface { @@ -162,6 +170,17 @@ func (s *metricsInstrumentedStore) ObserveDurableQueue(ctx context.Context, even return o.ObserveDurableQueue(ctx, eventTTL) } +func (s *metricsInstrumentedStore) EstimateBacklog(ctx context.Context) (int64, error) { + e, ok := s.inner.(BacklogEstimator) + if !ok { + return 0, errors.New("inner DurableEventStore does not implement BacklogEstimator") + } + t0 := time.Now() + n, err := e.EstimateBacklog(ctx) + s.m.recordStoreOp(ctx, "estimate_backlog", time.Since(t0), err) + return n, err +} + func (s *metricsInstrumentedStore) InsertBatch(ctx context.Context, payloads [][]byte) ([]int64, error) { bi, ok := s.inner.(BatchInserter) if !ok { diff --git a/pkg/durableemitter/process_stats.go b/pkg/durableemitter/process_stats.go index 43417278e3..fde3954af7 100644 --- a/pkg/durableemitter/process_stats.go +++ b/pkg/durableemitter/process_stats.go @@ -14,8 +14,8 @@ func (m *durableEmitterMetrics) pollProcessGauges(ctx context.Context) { } var mem runtime.MemStats runtime.ReadMemStats(&mem) - m.procHeapInuse.Record(ctx, int64(mem.HeapInuse)) - m.procHeapSys.Record(ctx, int64(mem.HeapSys)) + m.procHeapInuse.Record(ctx, int64(mem.HeapInuse), m.with()) + m.procHeapSys.Record(ctx, int64(mem.HeapSys), m.with()) var rusage syscall.Rusage if err := syscall.Getrusage(syscall.RUSAGE_SELF, &rusage); err != nil { @@ -23,6 +23,6 @@ func (m *durableEmitterMetrics) pollProcessGauges(ctx context.Context) { } user := float64(rusage.Utime.Sec) + float64(rusage.Utime.Usec)/1e6 sys := float64(rusage.Stime.Sec) + float64(rusage.Stime.Usec)/1e6 - m.procCPUUser.Record(ctx, user) - m.procCPUSys.Record(ctx, sys) + m.procCPUUser.Record(ctx, user, m.with()) + m.procCPUSys.Record(ctx, sys, m.with()) } diff --git a/pkg/durableemitter/process_stats_stub.go b/pkg/durableemitter/process_stats_stub.go index c853e1a828..9d3cc27508 100644 --- a/pkg/durableemitter/process_stats_stub.go +++ b/pkg/durableemitter/process_stats_stub.go @@ -13,6 +13,6 @@ func (m *durableEmitterMetrics) pollProcessGauges(ctx context.Context) { } var mem runtime.MemStats runtime.ReadMemStats(&mem) - m.procHeapInuse.Record(ctx, int64(mem.HeapInuse)) - m.procHeapSys.Record(ctx, int64(mem.HeapSys)) + m.procHeapInuse.Record(ctx, int64(mem.HeapInuse), m.with()) + m.procHeapSys.Record(ctx, int64(mem.HeapSys), m.with()) } diff --git a/pkg/durableemitter/store.go b/pkg/durableemitter/store.go index f72010d028..90b6d964b1 100644 --- a/pkg/durableemitter/store.go +++ b/pkg/durableemitter/store.go @@ -24,6 +24,7 @@ var ( _ DurableQueueObserver = (*PgDurableEventStore)(nil) _ BatchInserter = (*PgDurableEventStore)(nil) _ ExpiredPurger = (*PgDurableEventStore)(nil) + _ BacklogEstimator = (*PgDurableEventStore)(nil) ) func NewPgDurableEventStore(ds sqlutil.DataSource) *PgDurableEventStore { @@ -181,6 +182,22 @@ SELECT payload FROM deleted` return payloads, nil } +// EstimateBacklog implements BacklogEstimator from pg_stat_user_tables.n_live_tup, +// a catalog lookup that stays cheap on a large table, unlike count(*). It reads 0 +// after a statistics reset, so back-pressure fails open. +func (s *PgDurableEventStore) EstimateBacklog(ctx context.Context) (int64, error) { + const q = ` +SELECT coalesce( + (SELECT n_live_tup FROM pg_stat_user_tables WHERE relid = '` + chipDurableEventsTable + `'::regclass), + 0 +)::bigint` + var n int64 + if err := s.ds.GetContext(ctx, &n, q); err != nil { + return 0, fmt.Errorf("failed to estimate chip durable events backlog: %w", err) + } + return n, nil +} + type chipDurableQueueAgg struct { Cnt int64 `db:"cnt"` Total int64 `db:"total"` diff --git a/pkg/loop/config_test.go b/pkg/loop/config_test.go index ffea0ca4d1..c628ef306f 100644 --- a/pkg/loop/config_test.go +++ b/pkg/loop/config_test.go @@ -55,6 +55,9 @@ const ( envChipIngressSendTimeout = "CL_CHIP_INGRESS_SEND_TIMEOUT" envChipIngressDrainTimeout = "CL_CHIP_INGRESS_DRAIN_TIMEOUT" envChipIngressMaxGRPCRequestSize = "CL_CHIP_INGRESS_MAX_GRPC_REQUEST_SIZE" + envDurableEmitterBackpressureEnabled = "CL_CHIP_INGRESS_DURABLE_EMITTER_BACKPRESSURE_ENABLED" + envDurableEmitterMaxQueueDepth = "CL_CHIP_INGRESS_DURABLE_EMITTER_MAX_QUEUE_DEPTH" + envDurableEmitterBacklogPollInterval = "CL_CHIP_INGRESS_DURABLE_EMITTER_BACKLOG_POLL_INTERVAL" envPyroscopeAuthToken = "CL_PYROSCOPE_AUTH_TOKEN" envPyroscopeServerAddress = "CL_PYROSCOPE_SERVER_ADDRESS" @@ -157,6 +160,10 @@ func TestEnvConfig_parse(t *testing.T) { envChipIngressDrainTimeout: "10s", envChipIngressMaxGRPCRequestSize: "10485760", + envDurableEmitterBackpressureEnabled: "true", + envDurableEmitterMaxQueueDepth: "250000", + envDurableEmitterBacklogPollInterval: "2s", + envCRESettings: `{"global":{}}`, envCRESettingsDefault: `{"foo":"bar"}`, }, @@ -257,6 +264,10 @@ var envCfgFull = EnvConfig{ ChipIngressSendTimeout: 3 * time.Second, ChipIngressDrainTimeout: 10 * time.Second, ChipIngressMaxGRPCRequestSize: 10485760, + + DurableEmitterBackpressureEnabled: true, + DurableEmitterMaxQueueDepth: 250000, + DurableEmitterBacklogPollInterval: 2 * time.Second, }, DatabaseURL: config.MustSecretURL("postgres://user:password@localhost:5432/db"), @@ -387,6 +398,9 @@ func TestEnvConfig_AsCmdEnv(t *testing.T) { assert.Equal(t, "3s", got[envChipIngressSendTimeout]) assert.Equal(t, "10s", got[envChipIngressDrainTimeout]) assert.Equal(t, "10485760", got[envChipIngressMaxGRPCRequestSize]) + assert.Equal(t, "true", got[envDurableEmitterBackpressureEnabled]) + assert.Equal(t, "250000", got[envDurableEmitterMaxQueueDepth]) + assert.Equal(t, "2s", got[envDurableEmitterBacklogPollInterval]) assert.JSONEq(t, `{"global":{}}`, got[envCRESettings]) assert.JSONEq(t, `{"foo":"bar"}`, got[envCRESettingsDefault]) diff --git a/pkg/loop/server.go b/pkg/loop/server.go index e2a1807e05..57f1653872 100644 --- a/pkg/loop/server.go +++ b/pkg/loop/server.go @@ -209,7 +209,10 @@ func (s *Server) start(opts ...ServerOpt) error { // Rotating auth: signer is injected later via durableemitter.SetGlobalSigner when the host // provides the CSA keystore (see relayer and standard capabilities startup). emitterCfg := durableemitter.DefaultConfig() - emitterCfg.Metrics = &durableemitter.DurableEmitterMetricsConfig{} + emitterCfg.Metrics = &durableemitter.DurableEmitterMetricsConfig{Instance: s.Logger.Name()} + emitterCfg.BackpressureEnabled = s.EnvConfig.DurableEmitterBackpressureEnabled + emitterCfg.MaxQueueDepth = s.EnvConfig.DurableEmitterMaxQueueDepth + emitterCfg.BacklogPollInterval = s.EnvConfig.DurableEmitterBacklogPollInterval durableCfg := durableemitter.SetupConfig{ Endpoint: s.EnvConfig.ChipIngressEndpoint, InsecureConnection: s.EnvConfig.ChipIngressInsecureConnection, diff --git a/pkg/loop/telemetry/config.go b/pkg/loop/telemetry/config.go index 5e307d63e5..c6f750b3cd 100644 --- a/pkg/loop/telemetry/config.go +++ b/pkg/loop/telemetry/config.go @@ -53,6 +53,9 @@ const ( envChipIngressInsecureConnection = "CL_CHIP_INGRESS_INSECURE_CONNECTION" envChipIngressBatchEmitterEnabled = "CL_CHIP_INGRESS_BATCH_EMITTER_ENABLED" envChipIngressDurableEmitterEnabled = "CL_CHIP_INGRESS_DURABLE_EMITTER_ENABLED" + envDurableEmitterBackpressureEnabled = "CL_CHIP_INGRESS_DURABLE_EMITTER_BACKPRESSURE_ENABLED" + envDurableEmitterMaxQueueDepth = "CL_CHIP_INGRESS_DURABLE_EMITTER_MAX_QUEUE_DEPTH" + envDurableEmitterBacklogPollInterval = "CL_CHIP_INGRESS_DURABLE_EMITTER_BACKLOG_POLL_INTERVAL" envChipIngressBufferSize = "CL_CHIP_INGRESS_BUFFER_SIZE" envChipIngressMaxBatchSize = "CL_CHIP_INGRESS_MAX_BATCH_SIZE" envChipIngressMaxConcurrentSends = "CL_CHIP_INGRESS_MAX_CONCURRENT_SENDS" @@ -121,6 +124,11 @@ type TelemetryConfig struct { ChipIngressInsecureConnection bool ChipIngressBatchEmitterEnabled bool ChipIngressDurableEmitterEnabled bool + // DurableEmitter* configure the plugin's durable emitter back-pressure; see + // durableemitter.Config. Zero values use the durableemitter defaults. + DurableEmitterBackpressureEnabled bool + DurableEmitterMaxQueueDepth int64 + DurableEmitterBacklogPollInterval time.Duration ChipIngressBufferSize uint ChipIngressMaxBatchSize uint @@ -192,6 +200,9 @@ func (c *TelemetryConfig) AsCmdEnv() []string { add(envChipIngressInsecureConnection, strconv.FormatBool(c.ChipIngressInsecureConnection)) add(envChipIngressBatchEmitterEnabled, strconv.FormatBool(c.ChipIngressBatchEmitterEnabled)) add(envChipIngressDurableEmitterEnabled, strconv.FormatBool(c.ChipIngressDurableEmitterEnabled)) + add(envDurableEmitterBackpressureEnabled, strconv.FormatBool(c.DurableEmitterBackpressureEnabled)) + add(envDurableEmitterMaxQueueDepth, strconv.FormatInt(c.DurableEmitterMaxQueueDepth, 10)) + add(envDurableEmitterBacklogPollInterval, c.DurableEmitterBacklogPollInterval.String()) add(envChipIngressBufferSize, strconv.FormatUint(uint64(c.ChipIngressBufferSize), 10)) add(envChipIngressMaxBatchSize, strconv.FormatUint(uint64(c.ChipIngressMaxBatchSize), 10)) add(envChipIngressMaxConcurrentSends, strconv.Itoa(c.ChipIngressMaxConcurrentSends)) @@ -340,6 +351,18 @@ func (c *TelemetryConfig) Parse() error { if err != nil { return fmt.Errorf("failed to parse %s: %w", envChipIngressDurableEmitterEnabled, err) } + c.DurableEmitterBackpressureEnabled, err = getBool(envDurableEmitterBackpressureEnabled) + if err != nil { + return fmt.Errorf("failed to parse %s: %w", envDurableEmitterBackpressureEnabled, err) + } + c.DurableEmitterMaxQueueDepth, err = getInt64(envDurableEmitterMaxQueueDepth) + if err != nil { + return fmt.Errorf("failed to parse %s: %w", envDurableEmitterMaxQueueDepth, err) + } + c.DurableEmitterBacklogPollInterval, err = getDuration(envDurableEmitterBacklogPollInterval) + if err != nil { + return fmt.Errorf("failed to parse %s: %w", envDurableEmitterBacklogPollInterval, err) + } c.ChipIngressBufferSize, err = getUint(envChipIngressBufferSize) if err != nil { return fmt.Errorf("failed to parse %s: %w", envChipIngressBufferSize, err) @@ -452,6 +475,14 @@ func getDuration(envKey string) (time.Duration, error) { return time.ParseDuration(s) } +func getInt64(envKey string) (int64, error) { + s := os.Getenv(envKey) + if s == "" { + return 0, nil + } + return strconv.ParseInt(s, 10, 64) +} + func getInt(envKey string) (int, error) { s := os.Getenv(envKey) if s == "" { From 51e9fd3e53731df9dec64cd09396a033514f74f6 Mon Sep 17 00:00:00 2001 From: Tarcisio Ferraz Date: Mon, 23 Nov 2026 11:02:28 -0300 Subject: [PATCH 2/4] estimate backlog and enforce retransmit pause --- pkg/durableemitter/backpressure_test.go | 58 ++++++++++++++++++++++- pkg/durableemitter/durable_emitter.go | 63 ++++++++++++++----------- 2 files changed, 93 insertions(+), 28 deletions(-) diff --git a/pkg/durableemitter/backpressure_test.go b/pkg/durableemitter/backpressure_test.go index a13fc7c6d2..9e1eea7880 100644 --- a/pkg/durableemitter/backpressure_test.go +++ b/pkg/durableemitter/backpressure_test.go @@ -27,6 +27,24 @@ func (s *estimatingStore) EstimateBacklog(context.Context) (int64, error) { return s.estimate.Load(), nil } +// gatedEstimatingStore holds EstimateBacklog open while gate is set, so a test +// can write rows while a refresh is in flight. +type gatedEstimatingStore struct { + *MemDurableEventStore + estimate atomic.Int64 + gate atomic.Bool + entered chan struct{} + release chan struct{} +} + +func (s *gatedEstimatingStore) EstimateBacklog(context.Context) (int64, error) { + if s.gate.Load() { + s.entered <- struct{}{} + <-s.release + } + return s.estimate.Load(), nil +} + // faultyStore fails BatchDelete while failDeletes is set and counts store reads. type faultyStore struct { *MemDurableEventStore @@ -106,6 +124,39 @@ func TestDurableEmitter_BackpressureOffByDefault(t *testing.T) { assert.Nil(t, em.backlogEstimator, "the backlog is not polled unless back-pressure is enabled") } +func TestDurableEmitter_BackpressureRefreshKeepsInsertsMadeDuringPoll(t *testing.T) { + store := &gatedEstimatingStore{ + MemDurableEventStore: NewMemDurableEventStore(), + entered: make(chan struct{}), + release: make(chan struct{}), + } + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 10 + cfg.BacklogPollInterval = time.Hour + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + store.gate.Store(true) + done := make(chan struct{}) + go func() { + defer close(done) + em.refreshBacklog(ctx) + }() + <-store.entered + for range 3 { + require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) + } + // The estimate was taken before the inserts, so it does not include them. + store.estimate.Store(8) + store.release <- struct{}{} + <-done + + assert.Equal(t, int64(11), em.estimatedBacklog(), "inserts made during the poll stay counted") + require.ErrorIs(t, em.Emit(ctx, []byte("rejected"), testEmitAttrs()...), ErrBacklogged) +} + func TestDurableEmitter_BackpressureDisabledWithoutEstimator(t *testing.T) { store := NewMemDurableEventStore() be := newTestBatchEmitter() @@ -145,9 +196,14 @@ func TestDurableEmitter_RetransmitPausesWhileDeletesFail(t *testing.T) { time.Sleep(150 * time.Millisecond) // ~15 ticks, all inside the backoff window assert.Equal(t, listed, store.listCalls.Load(), "retransmit must not list pending rows while deletes fail") + // A later successful delete must not cut the pause short. store.failDeletes.Store(false) + require.NoError(t, em.Emit(ctx, []byte("fresh"), testEmitAttrs()...)) + require.Eventually(t, func() bool { return store.Len() == 1 }, 2*time.Second, 5*time.Millisecond) + assert.Equal(t, listed, store.listCalls.Load(), "retransmit stays paused for the full window after the last failure") + require.Eventually(t, func() bool { return store.Len() == 0 }, 10*time.Second, 10*time.Millisecond, - "retransmit resumes after the backoff and the row is deleted once deletes succeed") + "retransmit resumes after the backoff and the stuck row is deleted") } func TestDurableEmitter_PluginMetricsLabelledAndSkipQueueScan(t *testing.T) { diff --git a/pkg/durableemitter/durable_emitter.go b/pkg/durableemitter/durable_emitter.go index bf92ee1758..40fe18e1f0 100644 --- a/pkg/durableemitter/durable_emitter.go +++ b/pkg/durableemitter/durable_emitter.go @@ -254,16 +254,25 @@ type DurableEmitter struct { retransmitCursorTs time.Time retransmitCursorID int64 - // backlogEstimator is non-nil when back-pressure is enabled. backlog is the - // polled estimate, adjusted in between by this process's own writes. + // backlogEstimator is non-nil when back-pressure is enabled. The estimate is + // the last polled snapshot plus this process's inserts since that poll began; + // deletes and purges are only reflected by the next poll, so between polls the + // estimate can only overshoot. backlogEstimator BacklogEstimator - backlog atomic.Int64 + backlogSnap atomic.Pointer[backlogSnapshot] + insertedRows atomic.Int64 // deleteFailedAt is the UnixNano time of the last failed delivery delete, or 0 - // once a delete succeeds. + // if none has failed. Successes do not clear it, so the retransmit pause always + // runs its full window after a failure. deleteFailedAt atomic.Int64 } +type backlogSnapshot struct { + rows int64 // store estimate + inserted int64 // insertedRows when the estimate query started +} + // Compile-time assertion that *DurableEmitter exposes the canonical emit and // close methods expected of an emitter. var _ interface { @@ -442,40 +451,39 @@ func (d *DurableEmitter) backlogLoop() { } } -// refreshBacklog replaces the backlog estimate with the store's. On error the -// previous estimate is kept. +// refreshBacklog replaces the backlog snapshot with the store's estimate. Inserts +// made while the query runs stay counted on top of it. On error the previous +// snapshot is kept. func (d *DurableEmitter) refreshBacklog(ctx context.Context) { ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() + inserted := d.insertedRows.Load() n, err := d.backlogEstimator.EstimateBacklog(ctx) if err != nil { - d.eng.Warnw("DurableEmitter: backlog estimate failed; keeping last estimate", "estimate", d.backlog.Load(), "error", err) + d.eng.Warnw("DurableEmitter: backlog estimate failed; keeping last estimate", "estimate", d.estimatedBacklog(), "error", err) return } - d.backlog.Store(n) + d.backlogSnap.Store(&backlogSnapshot{rows: n, inserted: inserted}) } -// backlogged reports whether Emit should reject with ErrBacklogged. -func (d *DurableEmitter) backlogged() bool { - return d.backlogEstimator != nil && d.backlog.Load() >= d.cfg.MaxQueueDepth +func (d *DurableEmitter) estimatedBacklog() int64 { + var base, insertedAtPoll int64 + if snap := d.backlogSnap.Load(); snap != nil { + base, insertedAtPoll = snap.rows, snap.inserted + } + return base + d.insertedRows.Load() - insertedAtPoll } -// adjustBacklog applies this process's own store writes to the estimate between polls. -func (d *DurableEmitter) adjustBacklog(delta int64) { - if d.backlogEstimator != nil && delta != 0 { - d.backlog.Add(delta) - } +// backlogged reports whether Emit should reject with ErrBacklogged. +func (d *DurableEmitter) backlogged() bool { + return d.backlogEstimator != nil && d.estimatedBacklog() >= d.cfg.MaxQueueDepth } -// recordDeleteResult tracks delivery-delete health for the retransmit backoff -// and applies successful deletes to the backlog estimate. -func (d *DurableEmitter) recordDeleteResult(deleted int64, err error) { +// recordDeleteFailure starts (or extends) the retransmit pause. +func (d *DurableEmitter) recordDeleteFailure(err error) { if err != nil { d.deleteFailedAt.Store(time.Now().UnixNano()) - return } - d.deleteFailedAt.Store(0) - d.adjustBacklog(-deleted) } // EmitAsync runs Emit in a background goroutine and ignores the result, so the @@ -633,7 +641,9 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) return fmt.Errorf("failed to persist event: %w", err) } } - d.adjustBacklog(1) + if d.backlogEstimator != nil { + d.insertedRows.Add(1) + } // Hand off to the batch emitter. The callback fires once the batch // containing this event is sent (success or failure). @@ -702,7 +712,7 @@ func (d *DurableEmitter) deliveryCallback(id int64, eventPb *chipingress.CloudEv if h := d.cfg.Hooks; h != nil && h.OnBatchDelete != nil { h.OnBatchDelete(deleteElapsed, int(deleted)) } - d.recordDeleteResult(deleted, deleteErr) + d.recordDeleteFailure(deleteErr) if deleteErr != nil { d.eng.Errorw("failed to delete event from persistence", "id", id, "error", deleteErr) return @@ -879,7 +889,7 @@ func (d *DurableEmitter) flushDeletes(ids []int64) { if h := d.cfg.Hooks; h != nil && h.OnBatchDelete != nil { h.OnBatchDelete(deleteElapsed, int(deleted)) } - d.recordDeleteResult(deleted, err) + d.recordDeleteFailure(err) if err != nil { d.eng.Errorw("failed to batch delete delivered events", "count", len(ids), "error", err) return @@ -1074,7 +1084,6 @@ func (d *DurableEmitter) purgeExpired(ctx context.Context) { var purged int64 var purgeErr error defer func() { - d.adjustBacklog(-purged) span.SetAttributes(attribute.Int64("purged", purged)) if purgeErr != nil { span.RecordError(purgeErr) @@ -1154,7 +1163,7 @@ func (d *DurableEmitter) observeQueue(ctx context.Context, mc *DurableEmitterMet return } if d.backlogged() { - d.metrics.queueDepth.Record(ctx, d.backlog.Load(), d.metrics.with()) + d.metrics.queueDepth.Record(ctx, d.estimatedBacklog(), d.metrics.with()) return } obs, ok := d.store.(DurableQueueObserver) From ab7a4bcc748adccd95aa86a6a53b16152767186b Mon Sep 17 00:00:00 2001 From: Tarcisio Ferraz Date: Mon, 23 Nov 2026 11:31:51 -0300 Subject: [PATCH 3/4] durable emitter backpressure accuracy --- pkg/durableemitter/backpressure_test.go | 290 +++++++++++++++++++++++- pkg/durableemitter/durable_emitter.go | 229 +++++++++++++++---- 2 files changed, 473 insertions(+), 46 deletions(-) diff --git a/pkg/durableemitter/backpressure_test.go b/pkg/durableemitter/backpressure_test.go index 9e1eea7880..cecbb3d8de 100644 --- a/pkg/durableemitter/backpressure_test.go +++ b/pkg/durableemitter/backpressure_test.go @@ -3,6 +3,7 @@ package durableemitter import ( "context" "errors" + "sync" "sync/atomic" "testing" "time" @@ -16,17 +17,40 @@ import ( ) // estimatingStore adds a settable BacklogEstimator to MemDurableEventStore. +// EstimateBacklog errors while fail is set and returns the exact row count when +// exact is set. A non-nil insertHold blocks batch inserts until it is closed; +// failInserts makes them fail. type estimatingStore struct { *MemDurableEventStore - estimate atomic.Int64 + estimate atomic.Int64 + fail atomic.Bool + exact bool + failInserts atomic.Bool + insertHold chan struct{} } var _ BacklogEstimator = (*estimatingStore)(nil) func (s *estimatingStore) EstimateBacklog(context.Context) (int64, error) { + if s.fail.Load() { + return 0, errors.New("estimate timeout") + } + if s.exact { + return int64(s.Len()), nil + } return s.estimate.Load(), nil } +func (s *estimatingStore) InsertBatch(ctx context.Context, payloads [][]byte) ([]int64, error) { + if s.insertHold != nil { + <-s.insertHold + } + if s.failInserts.Load() { + return nil, errors.New("insert timeout") + } + return s.MemDurableEventStore.InsertBatch(ctx, payloads) +} + // gatedEstimatingStore holds EstimateBacklog open while gate is set, so a test // can write rows while a refresh is in flight. type gatedEstimatingStore struct { @@ -157,6 +181,270 @@ func TestDurableEmitter_BackpressureRefreshKeepsInsertsMadeDuringPoll(t *testing require.ErrorIs(t, em.Emit(ctx, []byte("rejected"), testEmitAttrs()...), ErrBacklogged) } +func TestDurableEmitter_BackpressureStalePollKeepsRecentInserts(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} + store.estimate.Store(90) + be := newTestBatchEmitter() + be.setPublishErr(errors.New("chip unavailable")) // rows are never deleted + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 100 + cfg.BacklogPollInterval = time.Hour + cfg.RetransmitInterval = time.Hour + em := newTestDurableEmitter(t, store, be, &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + for range 10 { + require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) + } + require.ErrorIs(t, em.Emit(ctx, []byte("over"), testEmitAttrs()...), ErrBacklogged) + + // Postgres statistics may not include the 10 inserts yet: a poll still + // returning 90 must not drop them from the estimate. + em.refreshBacklog(ctx) + require.ErrorIs(t, em.Emit(ctx, []byte("over"), testEmitAttrs()...), ErrBacklogged) + + // One poll later they are assumed to be reflected in the statistics. + em.refreshBacklog(ctx) + require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) +} + +func TestDurableEmitter_BackpressureCountsRemovalsWhilePollsFail(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 5 + cfg.BacklogPollInterval = 10 * time.Millisecond + cfg.DeleteBatchFlushInterval = time.Millisecond + cfg.RetransmitInterval = time.Hour + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + store.fail.Store(true) // seeded at 0, every later poll fails + for range 3 { + for range 5 { + require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) + } + require.Eventually(t, func() bool { return em.estimatedBacklog() == 0 }, 2*time.Second, 5*time.Millisecond, + "delivered rows are removed from the estimate without a successful poll") + } + assert.Equal(t, 0, store.Len()) +} + +func TestDurableEmitter_BackpressureReservesBeforeInsert(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore(), insertHold: make(chan struct{})} + be := newTestBatchEmitter() + be.setPublishErr(errors.New("chip unavailable")) + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 5 + cfg.BacklogPollInterval = time.Hour + cfg.RetransmitInterval = time.Hour + em := newTestDurableEmitter(t, store, be, &cfg) + servicetest.Run(t, em) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(store.insertHold) }) } + t.Cleanup(release) + ctx := t.Context() + + // Inserts are held, so no emit completes before all of them are admitted or rejected. + var accepted, rejected atomic.Int64 + var wg sync.WaitGroup + for range 20 { + wg.Go(func() { + switch err := em.Emit(ctx, []byte("x"), testEmitAttrs()...); { + case err == nil: + accepted.Add(1) + case errors.Is(err, ErrBacklogged): + rejected.Add(1) + } + }) + } + require.Eventually(t, func() bool { return rejected.Load() == 15 }, 2*time.Second, 5*time.Millisecond, + "emits beyond MaxQueueDepth are rejected while the admitted inserts are still in flight") + release() + wg.Wait() + assert.Equal(t, int64(5), accepted.Load()) + assert.Equal(t, 5, store.Len()) +} + +func TestDurableEmitter_BackpressureInflightSurvivesPolls(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore(), insertHold: make(chan struct{})} + be := newTestBatchEmitter() + be.setPublishErr(errors.New("chip unavailable")) + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 5 + cfg.BacklogPollInterval = time.Hour + cfg.RetransmitInterval = time.Hour + em := newTestDurableEmitter(t, store, be, &cfg) + servicetest.Run(t, em) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(store.insertHold) }) } + t.Cleanup(release) + ctx := t.Context() + + var wg sync.WaitGroup + for range 5 { + wg.Go(func() { assert.NoError(t, em.Emit(ctx, []byte("held"), testEmitAttrs()...)) }) + } + require.Eventually(t, func() bool { return em.backlogInflight.Load() == 5 }, 2*time.Second, 5*time.Millisecond) + + // The held inserts have not committed, so polls cannot see them. + em.refreshBacklog(ctx) + em.refreshBacklog(ctx) + require.ErrorIs(t, em.Emit(ctx, []byte("over"), testEmitAttrs()...), ErrBacklogged, + "in-flight inserts stay counted across polls") + + release() + wg.Wait() + assert.Equal(t, int64(5), em.estimatedBacklog()) +} + +func TestDurableEmitter_BackpressureCountsFailedInsertsAsPossiblyPersisted(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} + store.failInserts.Store(true) + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 1 + cfg.BacklogPollInterval = time.Hour + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + require.Error(t, em.Emit(ctx, []byte("timed out"), testEmitAttrs()...)) + require.ErrorIs(t, em.Emit(ctx, []byte("over"), testEmitAttrs()...), ErrBacklogged, + "an insert that reached the store may have committed") + + // Two polls later it is assumed to be reflected by the store estimate (0 here). + store.failInserts.Store(false) + em.refreshBacklog(ctx) + em.refreshBacklog(ctx) + require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) +} + +func TestDurableEmitter_BackpressureIgnoresRemovalsStartedBeforePoll(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} + store.estimate.Store(10) + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.BacklogPollInterval = time.Hour + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + before := em.removalGen() + em.refreshBacklog(ctx) // may already reflect a removal that started before it + em.recordRemovals(before, nil, 3) + assert.Equal(t, int64(10), em.estimatedBacklog()) + + em.recordRemovals(em.removalGen(), nil, 3) + assert.Equal(t, int64(7), em.estimatedBacklog()) +} + +func TestDurableEmitter_BackpressureRefreshDoesNotRecountDeliveredInserts(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore(), exact: true} + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 5 + cfg.BacklogPollInterval = time.Hour + cfg.DeleteBatchFlushInterval = time.Millisecond + cfg.RetransmitInterval = time.Hour + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + for range 5 { + require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) + } + require.Eventually(t, func() bool { return store.Len() == 0 && em.estimatedBacklog() == 0 }, + 2*time.Second, 5*time.Millisecond) + + // The inserts move to the previous generation, but they are already deleted. + em.refreshBacklog(ctx) + assert.Equal(t, int64(0), em.estimatedBacklog()) + for range 5 { + require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) + } +} + +func TestDurableEmitter_BackpressureNeverCountsARemovalTwice(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} + be := newTestBatchEmitter() + be.setPublishErr(errors.New("chip unavailable")) // rows are never deleted by delivery + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.BacklogPollInterval = time.Hour + cfg.RetransmitInterval = time.Hour + em := newTestDurableEmitter(t, store, be, &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + require.NoError(t, em.Emit(ctx, []byte("a"), testEmitAttrs()...)) + require.NoError(t, em.Emit(ctx, []byte("b"), testEmitAttrs()...)) + own := em.backlogSnap.Load().cur + started := em.removalGen() + require.Equal(t, int64(2), em.estimatedBacklog()) + + // Retransmit deletes row a, then the original delivery's delete finds it gone. + em.recordRemovals(started, []*backlogGen{nil}, 1) + em.recordRemovals(started, []*backlogGen{own}, 0) + assert.Equal(t, int64(1), em.estimatedBacklog()) + + // One of two rows removed, without knowing which: neither group is credited. + em.recordRemovals(started, []*backlogGen{own, nil}, 1) + assert.Equal(t, int64(1), em.estimatedBacklog()) + + em.recordRemovals(started, []*backlogGen{own}, 1) + assert.Equal(t, int64(0), em.estimatedBacklog()) +} + +// Exercises inserts, deliveries, deletes, retransmit and polls concurrently for +// the race detector, then checks the estimate converges to the real row count. +func TestDurableEmitter_BackpressureConcurrentAccounting(t *testing.T) { + store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore(), exact: true} + + cfg := DefaultConfig() + cfg.BackpressureEnabled = true + cfg.MaxQueueDepth = 50 + cfg.BacklogPollInterval = time.Millisecond + cfg.DeleteBatchFlushInterval = time.Millisecond + cfg.RetransmitInterval = 5 * time.Millisecond + cfg.RetransmitAfter = time.Millisecond + cfg.InsertBatchFlushInterval = time.Millisecond + em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) + servicetest.Run(t, em) + ctx := t.Context() + + var wg sync.WaitGroup + for range 16 { + wg.Go(func() { + for range 50 { + err := em.Emit(ctx, []byte("x"), testEmitAttrs()...) + if err != nil && !errors.Is(err, ErrBacklogged) { + assert.NoError(t, err) + } + } + }) + } + wg.Wait() + + require.Eventually(t, func() bool { return store.Len() == 0 }, 5*time.Second, 5*time.Millisecond) + assert.Zero(t, em.backlogInflight.Load()) + // Two polls after the last write, only the store estimate remains. + require.Eventually(t, func() bool { return em.estimatedBacklog() == 0 }, 5*time.Second, 5*time.Millisecond) +} + func TestDurableEmitter_BackpressureDisabledWithoutEstimator(t *testing.T) { store := NewMemDurableEventStore() be := newTestBatchEmitter() diff --git a/pkg/durableemitter/durable_emitter.go b/pkg/durableemitter/durable_emitter.go index 40fe18e1f0..c3de21cfe9 100644 --- a/pkg/durableemitter/durable_emitter.go +++ b/pkg/durableemitter/durable_emitter.go @@ -115,13 +115,16 @@ type Config struct { // MaxQueueDepth. Rejected events are lost. Requires a store implementing // BacklogEstimator. BackpressureEnabled bool - // MaxQueueDepth is the back-pressure threshold. Zero defaults to DefaultMaxQueueDepth. + // MaxQueueDepth is the back-pressure threshold. It is a soft limit: the backlog + // is an estimate, and writes by other processes sharing the store are only + // seen at each poll. Zero defaults to DefaultMaxQueueDepth. MaxQueueDepth int64 // BacklogPollInterval is how often the backlog estimate is refreshed from the // store. Zero defaults to DefaultBacklogPollInterval. BacklogPollInterval time.Duration // DeleteFailureRetransmitBackoff pauses the retransmit loop for this long after // a delivery delete fails, as rows that cannot be deleted would only be re-sent. + // Only this process's deletes count, including those of retransmitted rows. // Zero defaults to DefaultDeleteFailureRetransmitBackoff. DeleteFailureRetransmitBackoff time.Duration } @@ -237,7 +240,7 @@ type DurableEmitter struct { // batchEmitter.Stop can return at its shutdown timeout while callbacks are still // running, so deleteCh is closed under deleteMu and sends happen under its read // lock; a callback that arrives after deleteClosed leaves the event persisted. - deleteCh chan int64 + deleteCh chan pendingDelete deleteWg sync.WaitGroup deleteMu sync.RWMutex deleteClosed bool @@ -254,13 +257,12 @@ type DurableEmitter struct { retransmitCursorTs time.Time retransmitCursorID int64 - // backlogEstimator is non-nil when back-pressure is enabled. The estimate is - // the last polled snapshot plus this process's inserts since that poll began; - // deletes and purges are only reflected by the next poll, so between polls the - // estimate can only overshoot. + // backlogEstimator is non-nil when back-pressure is enabled; backlogSnap is + // then always set. backlogInflight counts admitted inserts not yet settled. + // See estimateBacklog for how the estimate is derived. backlogEstimator BacklogEstimator backlogSnap atomic.Pointer[backlogSnapshot] - insertedRows atomic.Int64 + backlogInflight atomic.Int64 // deleteFailedAt is the UnixNano time of the last failed delivery delete, or 0 // if none has failed. Successes do not clear it, so the retransmit pause always @@ -268,9 +270,33 @@ type DurableEmitter struct { deleteFailedAt atomic.Int64 } +// backlogSnapshot is one successful backlog poll. Each poll starts a new +// generation for this process's own writes; the previous one is kept because +// the store estimate may not reflect writes from just before the poll yet. type backlogSnapshot struct { - rows int64 // store estimate - inserted int64 // insertedRows when the estimate query started + rows int64 // store estimate + cur, prev *backlogGen +} + +// backlogGen counts this process's writes while a generation is current. The +// counters only grow; a generation is dropped two polls after it started. +type backlogGen struct { + // added counts settled inserts that reached the store, including failed + // ones: a timed-out insert may still have committed. + added atomic.Int64 + // gone counts rows of added that have since been removed. They are gone + // whether or not the store estimate reflects their insert. + gone atomic.Int64 + // removed counts other rows removed by deletes and purges that started while + // this generation was current, so after the poll that created it read the store. + removed atomic.Int64 +} + +// pendingDelete is a delivered row awaiting the delete coalescer. gen is the +// generation its insert was counted in, or nil if this process did not insert it. +type pendingDelete struct { + id int64 + gen *backlogGen } // Compile-time assertion that *DurableEmitter exposes the canonical emit and @@ -370,6 +396,7 @@ func NewDurableEmitter( if isEstimator { // Asserted on the possibly metrics-wrapped store so estimates are instrumented. d.backlogEstimator = store.(BacklogEstimator) + d.backlogSnap.Store(&backlogSnapshot{cur: new(backlogGen), prev: new(backlogGen)}) d.eng.Infow("DurableEmitter: back-pressure enabled", "maxQueueDepth", d.cfg.MaxQueueDepth, "backlogPollInterval", d.cfg.BacklogPollInterval) @@ -380,7 +407,7 @@ func NewDurableEmitter( if cfg.DeleteBatchSize > 0 { chanSize := max(cfg.DeleteBatchSize*200, 10_000) - d.deleteCh = make(chan int64, chanSize) + d.deleteCh = make(chan pendingDelete, chanSize) d.eng.Infow("DurableEmitter: delete coalescing enabled", "deleteBatchSize", cfg.DeleteBatchSize, "deleteBatchWorkers", cfg.DeleteBatchWorkers, @@ -451,34 +478,121 @@ func (d *DurableEmitter) backlogLoop() { } } -// refreshBacklog replaces the backlog snapshot with the store's estimate. Inserts -// made while the query runs stay counted on top of it. On error the previous -// snapshot is kept. +// refreshBacklog starts a new generation from the store's estimate; on error the +// current snapshot is kept. func (d *DurableEmitter) refreshBacklog(ctx context.Context) { ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() - inserted := d.insertedRows.Load() n, err := d.backlogEstimator.EstimateBacklog(ctx) if err != nil { d.eng.Warnw("DurableEmitter: backlog estimate failed; keeping last estimate", "estimate", d.estimatedBacklog(), "error", err) return } - d.backlogSnap.Store(&backlogSnapshot{rows: n, inserted: inserted}) + // CAS so that overlapping refreshes cannot discard a generation that writers + // have already recorded into. + for { + old := d.backlogSnap.Load() + if d.backlogSnap.CompareAndSwap(old, &backlogSnapshot{rows: n, cur: new(backlogGen), prev: old.cur}) { + return + } + } +} + +// estimateBacklog derives the backlog from the last poll and this process's own +// writes, erring towards overcounting: +// - inserts count from admission (inflight) and, until removed, for the current +// and previous generation, which covers the store estimate lagging recent +// commits by up to one poll interval; +// - removals of other rows are subtracted only if they started after the poll, +// since earlier ones may already be reflected in it. +// +// Load order matters. inflight comes before the snapshot because settleBacklog +// adds to the current generation before decrementing inflight. Removal counters +// come before added because a row is always added before it is removed. +func (d *DurableEmitter) estimateBacklog(inflight int64) int64 { + snap := d.backlogSnap.Load() + removed := snap.cur.removed.Load() + snap.cur.gone.Load() + snap.prev.gone.Load() + return snap.rows + snap.prev.added.Load() + snap.cur.added.Load() - removed + inflight } func (d *DurableEmitter) estimatedBacklog() int64 { - var base, insertedAtPoll int64 - if snap := d.backlogSnap.Load(); snap != nil { - base, insertedAtPoll = snap.rows, snap.inserted - } - return base + d.insertedRows.Load() - insertedAtPoll + return d.estimateBacklog(d.backlogInflight.Load()) } -// backlogged reports whether Emit should reject with ErrBacklogged. +// backlogged reports whether the estimated backlog is at or above MaxQueueDepth. func (d *DurableEmitter) backlogged() bool { return d.backlogEstimator != nil && d.estimatedBacklog() >= d.cfg.MaxQueueDepth } +// reserveBacklog admits one insert, counting it before it runs so concurrent +// emits cannot all pass the same estimate. On false the insert must be +// rejected; on true, settleBacklog must follow. +func (d *DurableEmitter) reserveBacklog() bool { + if d.backlogEstimator == nil { + return true + } + if d.estimateBacklog(d.backlogInflight.Add(1)) > d.cfg.MaxQueueDepth { + d.backlogInflight.Add(-1) + return false + } + return true +} + +// settleBacklog resolves a reservation. reachedStore is whether the insert was +// issued to the store, in which case the row may exist even if it failed. It +// returns the generation the row was counted in, which its delete must report. +func (d *DurableEmitter) settleBacklog(reachedStore bool) *backlogGen { + if d.backlogEstimator == nil { + return nil + } + var gen *backlogGen + if reachedStore { + gen = d.backlogSnap.Load().cur + gen.added.Add(1) + } + d.backlogInflight.Add(-1) + return gen +} + +// removalGen returns the generation a delete or purge starting now is charged +// to, or nil when back-pressure is disabled. +func (d *DurableEmitter) removalGen() *backlogGen { + if d.backlogEstimator == nil { + return nil + } + return d.backlogSnap.Load().cur +} + +// recordRemovals accounts for a delete or purge that removed n rows. started is +// removalGen() from before it ran; gens[i] is the generation the i-th targeted +// row was counted in, or nil. No gens means all n rows are other rows. +// +// A delete may remove fewer rows than targeted without saying which, so each +// group is credited only the removals it must have had. A row is therefore never +// subtracted twice, e.g. when retransmit and the original delivery both delete it. +func (d *DurableEmitter) recordRemovals(started *backlogGen, gens []*backlogGen, n int64) { + if started == nil || n <= 0 { + return + } + snap := d.backlogSnap.Load() + var inCur, inPrev int64 + for _, g := range gens { + switch g { + case snap.cur: + inCur++ + case snap.prev: + inPrev++ + } + } + // Rows counted in an older generation are assumed reflected in the store + // estimate, so they are removed like other rows. + targeted := max(int64(len(gens)), n) + atLeast := func(group int64) int64 { return max(0, n-(targeted-group)) } + snap.cur.gone.Add(atLeast(inCur)) + snap.prev.gone.Add(atLeast(inPrev)) + started.removed.Add(atLeast(targeted - inCur - inPrev)) +} + // recordDeleteFailure starts (or extends) the retransmit pause. func (d *DurableEmitter) recordDeleteFailure(err error) { if err != nil { @@ -523,12 +637,6 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) d.metrics.emitFail.Add(ctx, 1, d.metrics.with()) } } - if d.backlogged() { - if d.metrics != nil { - d.metrics.backpressureReject.Add(ctx, 1, d.metrics.with()) - } - return ErrBacklogged - } sourceDomain, entityType, err := beholder.ExtractSourceAndType(attrKVs...) if err != nil { emitFail() @@ -572,6 +680,20 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) return fmt.Errorf("%w: %d bytes, max %d", ErrEventTooLarge, len(payload), maxEventBytes) } + if !d.reserveBacklog() { + emitFail() + if d.metrics != nil { + d.metrics.backpressureReject.Add(ctx, 1, d.metrics.with()) + } + return ErrBacklogged + } + reachedStore, settled := false, false + defer func() { + if !settled { + d.settleBacklog(reachedStore) + } + }() + var id int64 var insElapsed time.Duration @@ -594,6 +716,7 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) tIns := time.Now() select { case d.insertCh <- req: + reachedStore = true case <-ctx.Done(): cerr = ctx.Err() return @@ -624,6 +747,7 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) id = res.id } else { tIns := time.Now() + reachedStore = true id, err = d.store.Insert(ctx, payload) insElapsed = time.Since(tIns) if h := d.cfg.Hooks; h != nil && h.OnEmitInsert != nil { @@ -641,14 +765,15 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) return fmt.Errorf("failed to persist event: %w", err) } } - if d.backlogEstimator != nil { - d.insertedRows.Add(1) - } + + // Settled before delivery can delete the row. + gen := d.settleBacklog(true) + settled = true // Hand off to the batch emitter. The callback fires once the batch // containing this event is sent (success or failure). t0Publish := time.Now() - if qErr := d.batchEmitter.QueueMessage(eventPb, d.deliveryCallback(id, eventPb, t0Publish, publishPhaseBatch, span.SpanContext())); qErr != nil { + if qErr := d.batchEmitter.QueueMessage(eventPb, d.deliveryCallback(id, gen, eventPb, t0Publish, publishPhaseBatch, span.SpanContext())); qErr != nil { d.eng.Warnw("DurableEmitter: batch emitter buffer full, relying on retransmit", "id", id) if d.metrics != nil { d.metrics.batchEnqueueBufferFull.Add(ctx, 1, @@ -661,8 +786,9 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) // deliveryCallback returns the function passed to BatchEmitter.QueueMessage. // On success, it deletes the delivered event. On failure, it leaves the event -// in the DB for the retransmit loop. -func (d *DurableEmitter) deliveryCallback(id int64, eventPb *chipingress.CloudEventPb, t0Publish time.Time, phase publishPhase, origin trace.SpanContext) func(error) { +// in the DB for the retransmit loop. gen is the backlog generation the event's +// insert was counted in, nil for retransmits. +func (d *DurableEmitter) deliveryCallback(id int64, gen *backlogGen, eventPb *chipingress.CloudEventPb, t0Publish time.Time, phase publishPhase, origin trace.SpanContext) func(error) { return func(sendErr error) { publishElapsed := time.Since(t0Publish) @@ -697,7 +823,7 @@ func (d *DurableEmitter) deliveryCallback(id int64, eventPb *chipingress.CloudEv // When delete coalescing is enabled the id is handed to the batch-delete // workers (one DELETE for many ids); otherwise delete it inline. - if d.enqueueDelete(id) { + if d.enqueueDelete(pendingDelete{id: id, gen: gen}) { return } @@ -705,6 +831,7 @@ func (d *DurableEmitter) deliveryCallback(id int64, eventPb *chipingress.CloudEv // flush, which would cancel the delete for every event acked during shutdown. delCtx, delCancel := d.deleteContext() defer delCancel() + started := d.removalGen() tDelete := time.Now() deleted, deleteErr := d.store.BatchDelete(delCtx, []int64{id}) deleteElapsed := time.Since(tDelete) @@ -713,6 +840,7 @@ func (d *DurableEmitter) deliveryCallback(id int64, eventPb *chipingress.CloudEv h.OnBatchDelete(deleteElapsed, int(deleted)) } d.recordDeleteFailure(deleteErr) + d.recordRemovals(started, []*backlogGen{gen}, deleted) if deleteErr != nil { d.eng.Errorw("failed to delete event from persistence", "id", id, "error", deleteErr) return @@ -820,17 +948,17 @@ func (d *DurableEmitter) insertBatchLoop() { // Send is a blocking hand-off; back-pressure here slows the delivery callback // rather than dropping a delete. After shutdown it skips the delete: the event // stays persisted and is retransmitted on the next start (at-least-once). -func (d *DurableEmitter) enqueueDelete(id int64) bool { +func (d *DurableEmitter) enqueueDelete(del pendingDelete) bool { if d.deleteCh == nil { return false } d.deleteMu.RLock() defer d.deleteMu.RUnlock() if d.deleteClosed { - d.eng.Debugw("DurableEmitter: delivery confirmed after shutdown; event left for retransmit", "id", id) + d.eng.Debugw("DurableEmitter: delivery confirmed after shutdown; event left for retransmit", "id", del.id) return true } - d.deleteCh <- id + d.deleteCh <- del return true } @@ -844,28 +972,28 @@ func (d *DurableEmitter) deleteBatchLoop() { if linger <= 0 { linger = 100 * time.Millisecond } - batch := make([]int64, 0, batchSize) + batch := make([]pendingDelete, 0, batchSize) for { batch = batch[:0] - id, ok := <-d.deleteCh + del, ok := <-d.deleteCh if !ok { return } - batch = append(batch, id) + batch = append(batch, del) timer := time.NewTimer(linger) collecting: for len(batch) < batchSize { select { - case id, ok := <-d.deleteCh: + case del, ok := <-d.deleteCh: if !ok { timer.Stop() d.flushDeletes(batch) return } - batch = append(batch, id) + batch = append(batch, del) case <-timer.C: break collecting } @@ -875,13 +1003,19 @@ func (d *DurableEmitter) deleteBatchLoop() { } } -func (d *DurableEmitter) flushDeletes(ids []int64) { - if len(ids) == 0 { +func (d *DurableEmitter) flushDeletes(batch []pendingDelete) { + if len(batch) == 0 { return } + ids := make([]int64, len(batch)) + gens := make([]*backlogGen, len(batch)) + for i, del := range batch { + ids[i], gens[i] = del.id, del.gen + } ctx, cancel := context.WithTimeout(context.Background(), d.cfg.PublishTimeout) defer cancel() + started := d.removalGen() tDelete := time.Now() deleted, err := d.store.BatchDelete(ctx, ids) deleteElapsed := time.Since(tDelete) @@ -890,6 +1024,7 @@ func (d *DurableEmitter) flushDeletes(ids []int64) { h.OnBatchDelete(deleteElapsed, int(deleted)) } d.recordDeleteFailure(err) + d.recordRemovals(started, gens, deleted) if err != nil { d.eng.Errorw("failed to batch delete delivered events", "count", len(ids), "error", err) return @@ -989,7 +1124,7 @@ func (d *DurableEmitter) retransmit(ctx context.Context, pending []DurableEvent) } id := pe.ID - if err := d.batchEmitter.QueueMessage(eventPb, d.deliveryCallback(id, eventPb, time.Now(), publishPhaseRetransmit, trace.SpanContextFromContext(ctx))); err != nil { + if err := d.batchEmitter.QueueMessage(eventPb, d.deliveryCallback(id, nil, eventPb, time.Now(), publishPhaseRetransmit, trace.SpanContextFromContext(ctx))); err != nil { skipped++ if d.metrics != nil { d.metrics.batchEnqueueBufferFull.Add(ctx, 1, @@ -1093,6 +1228,7 @@ func (d *DurableEmitter) purgeExpired(ctx context.Context) { }() purger, ok := expiredPurgerOf(d.store) if !ok { + started := d.removalGen() deleted, err := d.store.DeleteExpired(ctx, d.cfg.EventTTL) if err != nil { d.eng.Errorw("failed to delete expired events", "error", err) @@ -1100,6 +1236,7 @@ func (d *DurableEmitter) purgeExpired(ctx context.Context) { return } purged = deleted + d.recordRemovals(started, nil, deleted) if deleted > 0 { d.metrics.recordExpiredPurged(ctx, purgeUnknown, purgeUnknown, deleted) d.eng.Infow("purged expired events", "count", deleted) @@ -1115,12 +1252,14 @@ func (d *DurableEmitter) purgeExpired(ctx context.Context) { var total, undecodable int64 drain: for { + started := d.removalGen() payloads, err := purger.DeleteExpiredBatch(ctx, d.cfg.EventTTL, batch) if err != nil { d.eng.Errorw("failed to delete expired events", "error", err, "purged_before_error", total) purgeErr = err break } + d.recordRemovals(started, nil, int64(len(payloads))) for _, p := range payloads { k, ok := purgeKeyOf(p) if !ok { From 73af7a8bcc3fa12822cb8b6ec7534a65f9a45857 Mon Sep 17 00:00:00 2001 From: Tarcisio Ferraz Date: Mon, 23 Nov 2026 13:30:53 -0300 Subject: [PATCH 4/4] simplify code --- pkg/durableemitter/backpressure_test.go | 352 +----------------------- pkg/durableemitter/durable_emitter.go | 214 ++------------ 2 files changed, 39 insertions(+), 527 deletions(-) diff --git a/pkg/durableemitter/backpressure_test.go b/pkg/durableemitter/backpressure_test.go index cecbb3d8de..ac0ef37503 100644 --- a/pkg/durableemitter/backpressure_test.go +++ b/pkg/durableemitter/backpressure_test.go @@ -3,7 +3,6 @@ package durableemitter import ( "context" "errors" - "sync" "sync/atomic" "testing" "time" @@ -17,16 +16,11 @@ import ( ) // estimatingStore adds a settable BacklogEstimator to MemDurableEventStore. -// EstimateBacklog errors while fail is set and returns the exact row count when -// exact is set. A non-nil insertHold blocks batch inserts until it is closed; -// failInserts makes them fail. +// EstimateBacklog errors while fail is set. type estimatingStore struct { *MemDurableEventStore - estimate atomic.Int64 - fail atomic.Bool - exact bool - failInserts atomic.Bool - insertHold chan struct{} + estimate atomic.Int64 + fail atomic.Bool } var _ BacklogEstimator = (*estimatingStore)(nil) @@ -35,37 +29,6 @@ func (s *estimatingStore) EstimateBacklog(context.Context) (int64, error) { if s.fail.Load() { return 0, errors.New("estimate timeout") } - if s.exact { - return int64(s.Len()), nil - } - return s.estimate.Load(), nil -} - -func (s *estimatingStore) InsertBatch(ctx context.Context, payloads [][]byte) ([]int64, error) { - if s.insertHold != nil { - <-s.insertHold - } - if s.failInserts.Load() { - return nil, errors.New("insert timeout") - } - return s.MemDurableEventStore.InsertBatch(ctx, payloads) -} - -// gatedEstimatingStore holds EstimateBacklog open while gate is set, so a test -// can write rows while a refresh is in flight. -type gatedEstimatingStore struct { - *MemDurableEventStore - estimate atomic.Int64 - gate atomic.Bool - entered chan struct{} - release chan struct{} -} - -func (s *gatedEstimatingStore) EstimateBacklog(context.Context) (int64, error) { - if s.gate.Load() { - s.entered <- struct{}{} - <-s.release - } return s.estimate.Load(), nil } @@ -117,26 +80,6 @@ func TestDurableEmitter_BackpressureRejectsWhileBacklogged(t *testing.T) { }, 2*time.Second, 10*time.Millisecond, "emits resume once the polled estimate drops below MaxQueueDepth") } -func TestDurableEmitter_BackpressureCountsOwnInsertsBetweenPolls(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} - be := newTestBatchEmitter() - be.setPublishErr(errors.New("chip unavailable")) // rows are never deleted - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.MaxQueueDepth = 2 - cfg.BacklogPollInterval = time.Hour - cfg.RetransmitInterval = time.Hour - em := newTestDurableEmitter(t, store, be, &cfg) - servicetest.Run(t, em) - ctx := t.Context() - - require.NoError(t, em.Emit(ctx, []byte("1"), testEmitAttrs()...)) - require.NoError(t, em.Emit(ctx, []byte("2"), testEmitAttrs()...)) - require.ErrorIs(t, em.Emit(ctx, []byte("3"), testEmitAttrs()...), ErrBacklogged) - assert.Equal(t, 2, store.Len()) -} - func TestDurableEmitter_BackpressureOffByDefault(t *testing.T) { store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} store.estimate.Store(DefaultMaxQueueDepth) @@ -148,301 +91,26 @@ func TestDurableEmitter_BackpressureOffByDefault(t *testing.T) { assert.Nil(t, em.backlogEstimator, "the backlog is not polled unless back-pressure is enabled") } -func TestDurableEmitter_BackpressureRefreshKeepsInsertsMadeDuringPoll(t *testing.T) { - store := &gatedEstimatingStore{ - MemDurableEventStore: NewMemDurableEventStore(), - entered: make(chan struct{}), - release: make(chan struct{}), - } - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.MaxQueueDepth = 10 - cfg.BacklogPollInterval = time.Hour - em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) - servicetest.Run(t, em) - ctx := t.Context() - - store.gate.Store(true) - done := make(chan struct{}) - go func() { - defer close(done) - em.refreshBacklog(ctx) - }() - <-store.entered - for range 3 { - require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) - } - // The estimate was taken before the inserts, so it does not include them. - store.estimate.Store(8) - store.release <- struct{}{} - <-done - - assert.Equal(t, int64(11), em.estimatedBacklog(), "inserts made during the poll stay counted") - require.ErrorIs(t, em.Emit(ctx, []byte("rejected"), testEmitAttrs()...), ErrBacklogged) -} - -func TestDurableEmitter_BackpressureStalePollKeepsRecentInserts(t *testing.T) { +func TestDurableEmitter_BackpressureKeepsLastEstimateWhenPollFails(t *testing.T) { store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} - store.estimate.Store(90) - be := newTestBatchEmitter() - be.setPublishErr(errors.New("chip unavailable")) // rows are never deleted + store.estimate.Store(100) cfg := DefaultConfig() cfg.BackpressureEnabled = true cfg.MaxQueueDepth = 100 cfg.BacklogPollInterval = time.Hour - cfg.RetransmitInterval = time.Hour - em := newTestDurableEmitter(t, store, be, &cfg) - servicetest.Run(t, em) - ctx := t.Context() - - for range 10 { - require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) - } - require.ErrorIs(t, em.Emit(ctx, []byte("over"), testEmitAttrs()...), ErrBacklogged) - - // Postgres statistics may not include the 10 inserts yet: a poll still - // returning 90 must not drop them from the estimate. - em.refreshBacklog(ctx) - require.ErrorIs(t, em.Emit(ctx, []byte("over"), testEmitAttrs()...), ErrBacklogged) - - // One poll later they are assumed to be reflected in the statistics. - em.refreshBacklog(ctx) - require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) -} - -func TestDurableEmitter_BackpressureCountsRemovalsWhilePollsFail(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.MaxQueueDepth = 5 - cfg.BacklogPollInterval = 10 * time.Millisecond - cfg.DeleteBatchFlushInterval = time.Millisecond - cfg.RetransmitInterval = time.Hour em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) servicetest.Run(t, em) ctx := t.Context() - store.fail.Store(true) // seeded at 0, every later poll fails - for range 3 { - for range 5 { - require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) - } - require.Eventually(t, func() bool { return em.estimatedBacklog() == 0 }, 2*time.Second, 5*time.Millisecond, - "delivered rows are removed from the estimate without a successful poll") - } - assert.Equal(t, 0, store.Len()) -} - -func TestDurableEmitter_BackpressureReservesBeforeInsert(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore(), insertHold: make(chan struct{})} - be := newTestBatchEmitter() - be.setPublishErr(errors.New("chip unavailable")) - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.MaxQueueDepth = 5 - cfg.BacklogPollInterval = time.Hour - cfg.RetransmitInterval = time.Hour - em := newTestDurableEmitter(t, store, be, &cfg) - servicetest.Run(t, em) - var releaseOnce sync.Once - release := func() { releaseOnce.Do(func() { close(store.insertHold) }) } - t.Cleanup(release) - ctx := t.Context() - - // Inserts are held, so no emit completes before all of them are admitted or rejected. - var accepted, rejected atomic.Int64 - var wg sync.WaitGroup - for range 20 { - wg.Go(func() { - switch err := em.Emit(ctx, []byte("x"), testEmitAttrs()...); { - case err == nil: - accepted.Add(1) - case errors.Is(err, ErrBacklogged): - rejected.Add(1) - } - }) - } - require.Eventually(t, func() bool { return rejected.Load() == 15 }, 2*time.Second, 5*time.Millisecond, - "emits beyond MaxQueueDepth are rejected while the admitted inserts are still in flight") - release() - wg.Wait() - assert.Equal(t, int64(5), accepted.Load()) - assert.Equal(t, 5, store.Len()) -} - -func TestDurableEmitter_BackpressureInflightSurvivesPolls(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore(), insertHold: make(chan struct{})} - be := newTestBatchEmitter() - be.setPublishErr(errors.New("chip unavailable")) - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.MaxQueueDepth = 5 - cfg.BacklogPollInterval = time.Hour - cfg.RetransmitInterval = time.Hour - em := newTestDurableEmitter(t, store, be, &cfg) - servicetest.Run(t, em) - var releaseOnce sync.Once - release := func() { releaseOnce.Do(func() { close(store.insertHold) }) } - t.Cleanup(release) - ctx := t.Context() - - var wg sync.WaitGroup - for range 5 { - wg.Go(func() { assert.NoError(t, em.Emit(ctx, []byte("held"), testEmitAttrs()...)) }) - } - require.Eventually(t, func() bool { return em.backlogInflight.Load() == 5 }, 2*time.Second, 5*time.Millisecond) - - // The held inserts have not committed, so polls cannot see them. - em.refreshBacklog(ctx) + store.fail.Store(true) + store.estimate.Store(0) em.refreshBacklog(ctx) - require.ErrorIs(t, em.Emit(ctx, []byte("over"), testEmitAttrs()...), ErrBacklogged, - "in-flight inserts stay counted across polls") - - release() - wg.Wait() - assert.Equal(t, int64(5), em.estimatedBacklog()) -} - -func TestDurableEmitter_BackpressureCountsFailedInsertsAsPossiblyPersisted(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} - store.failInserts.Store(true) - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.MaxQueueDepth = 1 - cfg.BacklogPollInterval = time.Hour - em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) - servicetest.Run(t, em) - ctx := t.Context() - - require.Error(t, em.Emit(ctx, []byte("timed out"), testEmitAttrs()...)) - require.ErrorIs(t, em.Emit(ctx, []byte("over"), testEmitAttrs()...), ErrBacklogged, - "an insert that reached the store may have committed") - - // Two polls later it is assumed to be reflected by the store estimate (0 here). - store.failInserts.Store(false) - em.refreshBacklog(ctx) - em.refreshBacklog(ctx) - require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) -} - -func TestDurableEmitter_BackpressureIgnoresRemovalsStartedBeforePoll(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} - store.estimate.Store(10) - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.BacklogPollInterval = time.Hour - em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) - servicetest.Run(t, em) - ctx := t.Context() - - before := em.removalGen() - em.refreshBacklog(ctx) // may already reflect a removal that started before it - em.recordRemovals(before, nil, 3) - assert.Equal(t, int64(10), em.estimatedBacklog()) - - em.recordRemovals(em.removalGen(), nil, 3) - assert.Equal(t, int64(7), em.estimatedBacklog()) -} - -func TestDurableEmitter_BackpressureRefreshDoesNotRecountDeliveredInserts(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore(), exact: true} - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.MaxQueueDepth = 5 - cfg.BacklogPollInterval = time.Hour - cfg.DeleteBatchFlushInterval = time.Millisecond - cfg.RetransmitInterval = time.Hour - em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) - servicetest.Run(t, em) - ctx := t.Context() - - for range 5 { - require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) - } - require.Eventually(t, func() bool { return store.Len() == 0 && em.estimatedBacklog() == 0 }, - 2*time.Second, 5*time.Millisecond) + require.ErrorIs(t, em.Emit(ctx, []byte("rejected"), testEmitAttrs()...), ErrBacklogged) - // The inserts move to the previous generation, but they are already deleted. + store.fail.Store(false) em.refreshBacklog(ctx) - assert.Equal(t, int64(0), em.estimatedBacklog()) - for range 5 { - require.NoError(t, em.Emit(ctx, []byte("x"), testEmitAttrs()...)) - } -} - -func TestDurableEmitter_BackpressureNeverCountsARemovalTwice(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore()} - be := newTestBatchEmitter() - be.setPublishErr(errors.New("chip unavailable")) // rows are never deleted by delivery - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.BacklogPollInterval = time.Hour - cfg.RetransmitInterval = time.Hour - em := newTestDurableEmitter(t, store, be, &cfg) - servicetest.Run(t, em) - ctx := t.Context() - - require.NoError(t, em.Emit(ctx, []byte("a"), testEmitAttrs()...)) - require.NoError(t, em.Emit(ctx, []byte("b"), testEmitAttrs()...)) - own := em.backlogSnap.Load().cur - started := em.removalGen() - require.Equal(t, int64(2), em.estimatedBacklog()) - - // Retransmit deletes row a, then the original delivery's delete finds it gone. - em.recordRemovals(started, []*backlogGen{nil}, 1) - em.recordRemovals(started, []*backlogGen{own}, 0) - assert.Equal(t, int64(1), em.estimatedBacklog()) - - // One of two rows removed, without knowing which: neither group is credited. - em.recordRemovals(started, []*backlogGen{own, nil}, 1) - assert.Equal(t, int64(1), em.estimatedBacklog()) - - em.recordRemovals(started, []*backlogGen{own}, 1) - assert.Equal(t, int64(0), em.estimatedBacklog()) -} - -// Exercises inserts, deliveries, deletes, retransmit and polls concurrently for -// the race detector, then checks the estimate converges to the real row count. -func TestDurableEmitter_BackpressureConcurrentAccounting(t *testing.T) { - store := &estimatingStore{MemDurableEventStore: NewMemDurableEventStore(), exact: true} - - cfg := DefaultConfig() - cfg.BackpressureEnabled = true - cfg.MaxQueueDepth = 50 - cfg.BacklogPollInterval = time.Millisecond - cfg.DeleteBatchFlushInterval = time.Millisecond - cfg.RetransmitInterval = 5 * time.Millisecond - cfg.RetransmitAfter = time.Millisecond - cfg.InsertBatchFlushInterval = time.Millisecond - em := newTestDurableEmitter(t, store, newTestBatchEmitter(), &cfg) - servicetest.Run(t, em) - ctx := t.Context() - - var wg sync.WaitGroup - for range 16 { - wg.Go(func() { - for range 50 { - err := em.Emit(ctx, []byte("x"), testEmitAttrs()...) - if err != nil && !errors.Is(err, ErrBacklogged) { - assert.NoError(t, err) - } - } - }) - } - wg.Wait() - - require.Eventually(t, func() bool { return store.Len() == 0 }, 5*time.Second, 5*time.Millisecond) - assert.Zero(t, em.backlogInflight.Load()) - // Two polls after the last write, only the store estimate remains. - require.Eventually(t, func() bool { return em.estimatedBacklog() == 0 }, 5*time.Second, 5*time.Millisecond) + require.NoError(t, em.Emit(ctx, []byte("accepted"), testEmitAttrs()...)) } func TestDurableEmitter_BackpressureDisabledWithoutEstimator(t *testing.T) { diff --git a/pkg/durableemitter/durable_emitter.go b/pkg/durableemitter/durable_emitter.go index c3de21cfe9..f8e1ffbd22 100644 --- a/pkg/durableemitter/durable_emitter.go +++ b/pkg/durableemitter/durable_emitter.go @@ -116,8 +116,8 @@ type Config struct { // BacklogEstimator. BackpressureEnabled bool // MaxQueueDepth is the back-pressure threshold. It is a soft limit: the backlog - // is an estimate, and writes by other processes sharing the store are only - // seen at each poll. Zero defaults to DefaultMaxQueueDepth. + // is an estimate refreshed every BacklogPollInterval, so rejects start and stop + // up to one interval late. Zero defaults to DefaultMaxQueueDepth. MaxQueueDepth int64 // BacklogPollInterval is how often the backlog estimate is refreshed from the // store. Zero defaults to DefaultBacklogPollInterval. @@ -240,7 +240,7 @@ type DurableEmitter struct { // batchEmitter.Stop can return at its shutdown timeout while callbacks are still // running, so deleteCh is closed under deleteMu and sends happen under its read // lock; a callback that arrives after deleteClosed leaves the event persisted. - deleteCh chan pendingDelete + deleteCh chan int64 deleteWg sync.WaitGroup deleteMu sync.RWMutex deleteClosed bool @@ -257,12 +257,10 @@ type DurableEmitter struct { retransmitCursorTs time.Time retransmitCursorID int64 - // backlogEstimator is non-nil when back-pressure is enabled; backlogSnap is - // then always set. backlogInflight counts admitted inserts not yet settled. - // See estimateBacklog for how the estimate is derived. + // backlogEstimator is non-nil when back-pressure is enabled; backlogRows is + // then its last successful estimate. backlogEstimator BacklogEstimator - backlogSnap atomic.Pointer[backlogSnapshot] - backlogInflight atomic.Int64 + backlogRows atomic.Int64 // deleteFailedAt is the UnixNano time of the last failed delivery delete, or 0 // if none has failed. Successes do not clear it, so the retransmit pause always @@ -270,35 +268,6 @@ type DurableEmitter struct { deleteFailedAt atomic.Int64 } -// backlogSnapshot is one successful backlog poll. Each poll starts a new -// generation for this process's own writes; the previous one is kept because -// the store estimate may not reflect writes from just before the poll yet. -type backlogSnapshot struct { - rows int64 // store estimate - cur, prev *backlogGen -} - -// backlogGen counts this process's writes while a generation is current. The -// counters only grow; a generation is dropped two polls after it started. -type backlogGen struct { - // added counts settled inserts that reached the store, including failed - // ones: a timed-out insert may still have committed. - added atomic.Int64 - // gone counts rows of added that have since been removed. They are gone - // whether or not the store estimate reflects their insert. - gone atomic.Int64 - // removed counts other rows removed by deletes and purges that started while - // this generation was current, so after the poll that created it read the store. - removed atomic.Int64 -} - -// pendingDelete is a delivered row awaiting the delete coalescer. gen is the -// generation its insert was counted in, or nil if this process did not insert it. -type pendingDelete struct { - id int64 - gen *backlogGen -} - // Compile-time assertion that *DurableEmitter exposes the canonical emit and // close methods expected of an emitter. var _ interface { @@ -396,7 +365,6 @@ func NewDurableEmitter( if isEstimator { // Asserted on the possibly metrics-wrapped store so estimates are instrumented. d.backlogEstimator = store.(BacklogEstimator) - d.backlogSnap.Store(&backlogSnapshot{cur: new(backlogGen), prev: new(backlogGen)}) d.eng.Infow("DurableEmitter: back-pressure enabled", "maxQueueDepth", d.cfg.MaxQueueDepth, "backlogPollInterval", d.cfg.BacklogPollInterval) @@ -407,7 +375,7 @@ func NewDurableEmitter( if cfg.DeleteBatchSize > 0 { chanSize := max(cfg.DeleteBatchSize*200, 10_000) - d.deleteCh = make(chan pendingDelete, chanSize) + d.deleteCh = make(chan int64, chanSize) d.eng.Infow("DurableEmitter: delete coalescing enabled", "deleteBatchSize", cfg.DeleteBatchSize, "deleteBatchWorkers", cfg.DeleteBatchWorkers, @@ -478,119 +446,21 @@ func (d *DurableEmitter) backlogLoop() { } } -// refreshBacklog starts a new generation from the store's estimate; on error the -// current snapshot is kept. +// refreshBacklog polls the store's backlog estimate; on error the last one is kept. func (d *DurableEmitter) refreshBacklog(ctx context.Context) { ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() n, err := d.backlogEstimator.EstimateBacklog(ctx) if err != nil { - d.eng.Warnw("DurableEmitter: backlog estimate failed; keeping last estimate", "estimate", d.estimatedBacklog(), "error", err) + d.eng.Warnw("DurableEmitter: backlog estimate failed; keeping last estimate", "estimate", d.backlogRows.Load(), "error", err) return } - // CAS so that overlapping refreshes cannot discard a generation that writers - // have already recorded into. - for { - old := d.backlogSnap.Load() - if d.backlogSnap.CompareAndSwap(old, &backlogSnapshot{rows: n, cur: new(backlogGen), prev: old.cur}) { - return - } - } + d.backlogRows.Store(n) } -// estimateBacklog derives the backlog from the last poll and this process's own -// writes, erring towards overcounting: -// - inserts count from admission (inflight) and, until removed, for the current -// and previous generation, which covers the store estimate lagging recent -// commits by up to one poll interval; -// - removals of other rows are subtracted only if they started after the poll, -// since earlier ones may already be reflected in it. -// -// Load order matters. inflight comes before the snapshot because settleBacklog -// adds to the current generation before decrementing inflight. Removal counters -// come before added because a row is always added before it is removed. -func (d *DurableEmitter) estimateBacklog(inflight int64) int64 { - snap := d.backlogSnap.Load() - removed := snap.cur.removed.Load() + snap.cur.gone.Load() + snap.prev.gone.Load() - return snap.rows + snap.prev.added.Load() + snap.cur.added.Load() - removed + inflight -} - -func (d *DurableEmitter) estimatedBacklog() int64 { - return d.estimateBacklog(d.backlogInflight.Load()) -} - -// backlogged reports whether the estimated backlog is at or above MaxQueueDepth. +// backlogged reports whether the last backlog estimate is at or above MaxQueueDepth. func (d *DurableEmitter) backlogged() bool { - return d.backlogEstimator != nil && d.estimatedBacklog() >= d.cfg.MaxQueueDepth -} - -// reserveBacklog admits one insert, counting it before it runs so concurrent -// emits cannot all pass the same estimate. On false the insert must be -// rejected; on true, settleBacklog must follow. -func (d *DurableEmitter) reserveBacklog() bool { - if d.backlogEstimator == nil { - return true - } - if d.estimateBacklog(d.backlogInflight.Add(1)) > d.cfg.MaxQueueDepth { - d.backlogInflight.Add(-1) - return false - } - return true -} - -// settleBacklog resolves a reservation. reachedStore is whether the insert was -// issued to the store, in which case the row may exist even if it failed. It -// returns the generation the row was counted in, which its delete must report. -func (d *DurableEmitter) settleBacklog(reachedStore bool) *backlogGen { - if d.backlogEstimator == nil { - return nil - } - var gen *backlogGen - if reachedStore { - gen = d.backlogSnap.Load().cur - gen.added.Add(1) - } - d.backlogInflight.Add(-1) - return gen -} - -// removalGen returns the generation a delete or purge starting now is charged -// to, or nil when back-pressure is disabled. -func (d *DurableEmitter) removalGen() *backlogGen { - if d.backlogEstimator == nil { - return nil - } - return d.backlogSnap.Load().cur -} - -// recordRemovals accounts for a delete or purge that removed n rows. started is -// removalGen() from before it ran; gens[i] is the generation the i-th targeted -// row was counted in, or nil. No gens means all n rows are other rows. -// -// A delete may remove fewer rows than targeted without saying which, so each -// group is credited only the removals it must have had. A row is therefore never -// subtracted twice, e.g. when retransmit and the original delivery both delete it. -func (d *DurableEmitter) recordRemovals(started *backlogGen, gens []*backlogGen, n int64) { - if started == nil || n <= 0 { - return - } - snap := d.backlogSnap.Load() - var inCur, inPrev int64 - for _, g := range gens { - switch g { - case snap.cur: - inCur++ - case snap.prev: - inPrev++ - } - } - // Rows counted in an older generation are assumed reflected in the store - // estimate, so they are removed like other rows. - targeted := max(int64(len(gens)), n) - atLeast := func(group int64) int64 { return max(0, n-(targeted-group)) } - snap.cur.gone.Add(atLeast(inCur)) - snap.prev.gone.Add(atLeast(inPrev)) - started.removed.Add(atLeast(targeted - inCur - inPrev)) + return d.backlogEstimator != nil && d.backlogRows.Load() >= d.cfg.MaxQueueDepth } // recordDeleteFailure starts (or extends) the retransmit pause. @@ -680,19 +550,13 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) return fmt.Errorf("%w: %d bytes, max %d", ErrEventTooLarge, len(payload), maxEventBytes) } - if !d.reserveBacklog() { + if d.backlogged() { emitFail() if d.metrics != nil { d.metrics.backpressureReject.Add(ctx, 1, d.metrics.with()) } return ErrBacklogged } - reachedStore, settled := false, false - defer func() { - if !settled { - d.settleBacklog(reachedStore) - } - }() var id int64 var insElapsed time.Duration @@ -716,7 +580,6 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) tIns := time.Now() select { case d.insertCh <- req: - reachedStore = true case <-ctx.Done(): cerr = ctx.Err() return @@ -747,7 +610,6 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) id = res.id } else { tIns := time.Now() - reachedStore = true id, err = d.store.Insert(ctx, payload) insElapsed = time.Since(tIns) if h := d.cfg.Hooks; h != nil && h.OnEmitInsert != nil { @@ -766,14 +628,10 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) } } - // Settled before delivery can delete the row. - gen := d.settleBacklog(true) - settled = true - // Hand off to the batch emitter. The callback fires once the batch // containing this event is sent (success or failure). t0Publish := time.Now() - if qErr := d.batchEmitter.QueueMessage(eventPb, d.deliveryCallback(id, gen, eventPb, t0Publish, publishPhaseBatch, span.SpanContext())); qErr != nil { + if qErr := d.batchEmitter.QueueMessage(eventPb, d.deliveryCallback(id, eventPb, t0Publish, publishPhaseBatch, span.SpanContext())); qErr != nil { d.eng.Warnw("DurableEmitter: batch emitter buffer full, relying on retransmit", "id", id) if d.metrics != nil { d.metrics.batchEnqueueBufferFull.Add(ctx, 1, @@ -786,9 +644,8 @@ func (d *DurableEmitter) Emit(ctx context.Context, body []byte, attrKVs ...any) // deliveryCallback returns the function passed to BatchEmitter.QueueMessage. // On success, it deletes the delivered event. On failure, it leaves the event -// in the DB for the retransmit loop. gen is the backlog generation the event's -// insert was counted in, nil for retransmits. -func (d *DurableEmitter) deliveryCallback(id int64, gen *backlogGen, eventPb *chipingress.CloudEventPb, t0Publish time.Time, phase publishPhase, origin trace.SpanContext) func(error) { +// in the DB for the retransmit loop. +func (d *DurableEmitter) deliveryCallback(id int64, eventPb *chipingress.CloudEventPb, t0Publish time.Time, phase publishPhase, origin trace.SpanContext) func(error) { return func(sendErr error) { publishElapsed := time.Since(t0Publish) @@ -823,7 +680,7 @@ func (d *DurableEmitter) deliveryCallback(id int64, gen *backlogGen, eventPb *ch // When delete coalescing is enabled the id is handed to the batch-delete // workers (one DELETE for many ids); otherwise delete it inline. - if d.enqueueDelete(pendingDelete{id: id, gen: gen}) { + if d.enqueueDelete(id) { return } @@ -831,7 +688,6 @@ func (d *DurableEmitter) deliveryCallback(id int64, gen *backlogGen, eventPb *ch // flush, which would cancel the delete for every event acked during shutdown. delCtx, delCancel := d.deleteContext() defer delCancel() - started := d.removalGen() tDelete := time.Now() deleted, deleteErr := d.store.BatchDelete(delCtx, []int64{id}) deleteElapsed := time.Since(tDelete) @@ -840,7 +696,6 @@ func (d *DurableEmitter) deliveryCallback(id int64, gen *backlogGen, eventPb *ch h.OnBatchDelete(deleteElapsed, int(deleted)) } d.recordDeleteFailure(deleteErr) - d.recordRemovals(started, []*backlogGen{gen}, deleted) if deleteErr != nil { d.eng.Errorw("failed to delete event from persistence", "id", id, "error", deleteErr) return @@ -948,17 +803,17 @@ func (d *DurableEmitter) insertBatchLoop() { // Send is a blocking hand-off; back-pressure here slows the delivery callback // rather than dropping a delete. After shutdown it skips the delete: the event // stays persisted and is retransmitted on the next start (at-least-once). -func (d *DurableEmitter) enqueueDelete(del pendingDelete) bool { +func (d *DurableEmitter) enqueueDelete(id int64) bool { if d.deleteCh == nil { return false } d.deleteMu.RLock() defer d.deleteMu.RUnlock() if d.deleteClosed { - d.eng.Debugw("DurableEmitter: delivery confirmed after shutdown; event left for retransmit", "id", del.id) + d.eng.Debugw("DurableEmitter: delivery confirmed after shutdown; event left for retransmit", "id", id) return true } - d.deleteCh <- del + d.deleteCh <- id return true } @@ -972,28 +827,28 @@ func (d *DurableEmitter) deleteBatchLoop() { if linger <= 0 { linger = 100 * time.Millisecond } - batch := make([]pendingDelete, 0, batchSize) + batch := make([]int64, 0, batchSize) for { batch = batch[:0] - del, ok := <-d.deleteCh + id, ok := <-d.deleteCh if !ok { return } - batch = append(batch, del) + batch = append(batch, id) timer := time.NewTimer(linger) collecting: for len(batch) < batchSize { select { - case del, ok := <-d.deleteCh: + case id, ok := <-d.deleteCh: if !ok { timer.Stop() d.flushDeletes(batch) return } - batch = append(batch, del) + batch = append(batch, id) case <-timer.C: break collecting } @@ -1003,19 +858,13 @@ func (d *DurableEmitter) deleteBatchLoop() { } } -func (d *DurableEmitter) flushDeletes(batch []pendingDelete) { - if len(batch) == 0 { +func (d *DurableEmitter) flushDeletes(ids []int64) { + if len(ids) == 0 { return } - ids := make([]int64, len(batch)) - gens := make([]*backlogGen, len(batch)) - for i, del := range batch { - ids[i], gens[i] = del.id, del.gen - } ctx, cancel := context.WithTimeout(context.Background(), d.cfg.PublishTimeout) defer cancel() - started := d.removalGen() tDelete := time.Now() deleted, err := d.store.BatchDelete(ctx, ids) deleteElapsed := time.Since(tDelete) @@ -1024,7 +873,6 @@ func (d *DurableEmitter) flushDeletes(batch []pendingDelete) { h.OnBatchDelete(deleteElapsed, int(deleted)) } d.recordDeleteFailure(err) - d.recordRemovals(started, gens, deleted) if err != nil { d.eng.Errorw("failed to batch delete delivered events", "count", len(ids), "error", err) return @@ -1124,7 +972,7 @@ func (d *DurableEmitter) retransmit(ctx context.Context, pending []DurableEvent) } id := pe.ID - if err := d.batchEmitter.QueueMessage(eventPb, d.deliveryCallback(id, nil, eventPb, time.Now(), publishPhaseRetransmit, trace.SpanContextFromContext(ctx))); err != nil { + if err := d.batchEmitter.QueueMessage(eventPb, d.deliveryCallback(id, eventPb, time.Now(), publishPhaseRetransmit, trace.SpanContextFromContext(ctx))); err != nil { skipped++ if d.metrics != nil { d.metrics.batchEnqueueBufferFull.Add(ctx, 1, @@ -1228,7 +1076,6 @@ func (d *DurableEmitter) purgeExpired(ctx context.Context) { }() purger, ok := expiredPurgerOf(d.store) if !ok { - started := d.removalGen() deleted, err := d.store.DeleteExpired(ctx, d.cfg.EventTTL) if err != nil { d.eng.Errorw("failed to delete expired events", "error", err) @@ -1236,7 +1083,6 @@ func (d *DurableEmitter) purgeExpired(ctx context.Context) { return } purged = deleted - d.recordRemovals(started, nil, deleted) if deleted > 0 { d.metrics.recordExpiredPurged(ctx, purgeUnknown, purgeUnknown, deleted) d.eng.Infow("purged expired events", "count", deleted) @@ -1252,14 +1098,12 @@ func (d *DurableEmitter) purgeExpired(ctx context.Context) { var total, undecodable int64 drain: for { - started := d.removalGen() payloads, err := purger.DeleteExpiredBatch(ctx, d.cfg.EventTTL, batch) if err != nil { d.eng.Errorw("failed to delete expired events", "error", err, "purged_before_error", total) purgeErr = err break } - d.recordRemovals(started, nil, int64(len(payloads))) for _, p := range payloads { k, ok := purgeKeyOf(p) if !ok { @@ -1302,7 +1146,7 @@ func (d *DurableEmitter) observeQueue(ctx context.Context, mc *DurableEmitterMet return } if d.backlogged() { - d.metrics.queueDepth.Record(ctx, d.estimatedBacklog(), d.metrics.with()) + d.metrics.queueDepth.Record(ctx, d.backlogRows.Load(), d.metrics.with()) return } obs, ok := d.store.(DurableQueueObserver)