diff --git a/docs/design/2026-10-14-syncpoint-backpressure-and-memory-reclamation.md b/docs/design/2026-10-14-syncpoint-backpressure-and-memory-reclamation.md new file mode 100644 index 0000000000..18cd47a1ae --- /dev/null +++ b/docs/design/2026-10-14-syncpoint-backpressure-and-memory-reclamation.md @@ -0,0 +1,293 @@ +# Sync-point and Redo-wait Backpressure and Memory Reclamation + +## Scope + +This design addresses the memory starvation described in +[#4605](https://github.com/pingcap/ticdc/issues/4605). + +Two changes work together: + +1. Check for stalled EventCollector memory periodically, independently of new + events, and retain a recovery event when reclaiming queued data. +2. Advertise zero scan quota for an ordinary dispatcher actually waiting for, + or writing, a sync-point, or caching a batch above the redo watermark. + Resume advertising its available memory when that wait is satisfied. + +The design does not add another broker prepare/commit protocol, change +maintainer barrier coverage, skip non-replicating members, or alter transaction +cursors and scan-window escape paths. Adaptive window tuning and general +cross-broker quota fairness remain separate work. This does not claim to resolve +all possible causes of prolonged dispatcher migration. + +## Existing behavior + +A fast dispatcher A can already be waiting at sync-point S while its pending +queue holds substantial data after S. A slow dispatcher B needs shared memory +to scan up to S. If A consumes the shared quota, a cycle exists: + +```text +A waits for B at S -> B needs shared quota -> quota needs A to drain -> A waits +``` + +Redo introduces another dependency: an ordinary dispatcher caches its active +batch until `redoGlobalTs` reaches the batch's final commit TS. Its pending queue +can fill with later events. Collector changefeed availability is the minimum +of ordinary and redo stream availability, so a full ordinary stream can stop a +lagging redo dispatcher from scanning. That dispatcher then pins the global +redo watermark needed to drain the ordinary stream. Periodic reclamation frees +pending payload; stopping prefetch on the waiting ordinary path prevents it +from immediately consuming that space again. + +Current reclamation is invoked from `areaMemStat.appendEvent`. It requires +recent input, more than five seconds without ordinary event consumption or +reclamation, and memory usage above 60%. Adjacent periodic signals return from +the merge branch before that check. Moreover, a broker with an unfinished +transaction cursor cannot send a signal resolved event. Consequently, neither +silence nor repeated resolved signals guarantees another reclamation check. + +Current manual `Release` clears pending events without retaining recovery +notifications. Recovery normally relies on a later event revealing a sequence +gap. Silence can also prevent that recovery step. + +The reverted [two-stage implementation](https://github.com/pingcap/ticdc/pull/4429) +coordinated a broker's members before emitting S. Once S was emitted it allowed +scanning toward the next sync-point. The proposed backpressure observes the +actual consumer barrier state, including waits caused by another broker. It +reacts later than a prepare fence, so reclamation is still necessary. + +## Invariants + +- Only an ordinary dispatcher in sync-point WAITING/WRITING or with an actual + cached batch above the redo watermark is paused by this rule. Redo dispatchers + produce that watermark and must remain eligible to scan. +- WAITING retries, Write/Pass, heartbeats, registration, handshake and reset must + remain usable while scan quota is zero. +- Reclamation cannot discard the active barrier or events already owned by the sink. +- Periodic checks, completion callbacks and queued recovery notifications provide + progress without a new upstream event. +- Data loss from reclamation is recovered through the existing checkpoint, + sequence and epoch rules; never advance a checkpoint to skip missing data. +- Only the owning dynamic-stream handle loop mutates pending queues. +- Memory accounting reflects actual retained and released bytes. A reclamation + request is not itself progress. +- Stale recovery notifications cannot reset a new source/epoch. Delayed quota + snapshots must not create a sticky pause requiring a matching resume message. +- A main dispatcher's synthetic zero quota must not become a changefeed-wide or + redo-wide synthetic zero quota. +- Checks, feedback congestion, Wake/Release/Remove and shutdown must not create + lock/channel dependency cycles. + +## Periodic reclamation + +### Scheduling and policy + +EventCollector invokes an explicit `DynamicStream.CheckMemoryPressure()` on its +main and redo streams from the existing one-second congestion-control loop, +before publishing memory snapshots. `GetMetrics()` remains observational. No +additional timer goroutine or user setting is needed. + +The memory controller snapshots area references under its mutex and releases +that mutex before checking areas. Only `MemoryControlForEventCollector` is +eligible. The periodic check requires usage above 60%, more than five seconds +since real ordinary-event consumption or reclamation, and reclaimable blocked +pending data. It does not require recent append activity. + +Retain the existing candidate ordering (descending last handled event TS), +256-byte path threshold and 60% pending-byte reclamation target. Use a CAS to +claim the per-area one-second request interval across append-driven and periodic +checks. Do not hold controller, path-map or barrier locks while waiting for +feedback. Feedback delivery must be nonblocking and retried on a later check +when congested. Do not update the actual-progress timestamp for a request alone. + +Other ordinary traffic in an area can defer the stall detector. This first +change covers the exhausted-quota, no-consumption cycle; it is not a proof of +fair scheduling under arbitrary competing traffic. A per-path stall policy +would require a separately reviewed extension if experiments demonstrate that +need. + +### Owner-thread reclamation + +Validate that a feedback destination still matches the registered dispatcher. +Bind release to the particular path object, so feedback for a removed object +cannot release a replacement. In the owning handle loop, recheck that the path +is still present, blocked and has reclaimable data. A release arriving after +Wake may be skipped. If the path is blocked at another event, only its current +pending data can be reclaimed; the active event remains outside that queue. +Admission to the owning stream queue is nonblocking too. If it is full, the +next pressure check retries; cancellation does not wait for reclamation queue +space. Once a path has been visited, skip it until a new droppable data event +arrives, so retained controls alone do not cause repeated ineffective requests. + +The owning stream reconciles both reclamation and removal accounting. +RemovePath only unregisters the path; it leaves pending bytes accounted until +the owner clears the queue. If removal precedes or occurs during reclamation, +clear the removed path completely and deduct its pending bytes once. Otherwise, +subtract the reclaimed payload bytes from both the path and area. The existing +admission-time payload-to-DropEvent replacement also +charges the actual retained marker size, preserving wrapper overhead. + +The EventCollector memory-release path retains recovery/control events: + +- Replace discarded DML, BatchDML, DDL and sync-point data with the lightweight + event returned by the existing handler `OnDrop` callback. +- Preserve source and epoch. Do not coalesce recovery markers across events or + epochs in this first implementation. The first current-epoch marker resets + the stream; later old-epoch markers are ignored. +- Preserve non-droppable events, including Ready, Handshake, NotReusable and + existing DropEvent notifications, in order. +- Preserve resolved watermarks using the existing adjacent-signal coalescing + behavior. Dropping the last resolved event can otherwise strand an idle + table's checkpoint without further upstream input. +- Only apply a replacement that reduces retained bytes. Count markers and + control events in pending memory; do not set the accounting blindly to zero. +- Keep signal-queue accounting correct so Wake schedules retained markers even + with no new input. + +Puller reclamation policy and removal cleanup are unchanged. Avoid clearing the +barrier or issuing Wake as a side effect of memory reclamation. + +```text +A handles S and blocks + -> reclaim A's queued post-S data, retaining DropEvent + -> B obtains memory and reaches S + -> maintainer coordinates Write/Pass + -> A successfully completes S and wakes + -> DropEvent triggers reset from the existing safe checkpoint +``` + +This retains the existing sequence checks as another recovery defense without +requiring a future message to reveal a gap. + +## Dispatcher scan backpressure + +### Derive state from the existing barrier + +Expose a lightweight `DispatcherService.ShouldPauseScan() bool`. The basic +dispatcher checks the existing barrier under its mutex and returns true only +for a non-redo dispatcher handling a sync-point in WAITING or WRITING. Do not +copy large protobuf status objects or perform I/O or stream operations under +that mutex. + +The ordinary event dispatcher also checks its redo cache. An atomic required TS +is stored before publishing a cached batch and cleared before retrying it. A +retry that still needs redo progress republishes the required TS. Clearing +before handling or Wake prevents completion of an old batch from clearing a +new batch's wait. Removal clears the required TS under the existing cache +mutex; a concurrent retry cannot cache another batch after removal. + +Pause for redo only when redo is enabled and the cached required TS exceeds +the current `redoGlobalTs`. A low watermark without a cached batch is not a +pause condition. Reaching the required TS removes the redo pause even before +the cache retry runs, so no paired resume notification or new scanned event +is required. Pre-WAITING asynchronous sync-point flush remains outside the +pause condition. + +Each one-second congestion snapshot computes: + +```text +path quota = 0 if ShouldPauseScan() +path quota = actual available bytes otherwise +``` + +Apply this override to the individual target ID after obtaining actual memory +snapshots. Keep actual main/redo area accounting; do not propagate a synthetic +zero by table ID or changefeed. Reuse the existing quota protocol without an +additional pause/resume RPC or immediate-notification callback. + +### Broker and resume behavior + +In `doScan`, after Ready/Handshake and scan-request calculation, reject zero +per-dispatcher quota before consuming scan-rate tokens or reserving shared +quota. Retain no-data resolved fast paths, safe signal-resolved emission, +pending-barrier local advance and same-commit/large-transaction cursors. Do not +cancel active scans merely because feedback changed. Already queued or in-flight +data may still arrive and remains eligible for reclamation. + +Table-trigger dispatchers use their separate tick instead of the DML quota gate. +Do not add a new DDL/resolved pause there; doing so can prevent schema/scheduling +progress. Their blocked pending queues still participate in memory reclamation. + +Existing successful PostFlush/Pass clears barrier state before waking the data +stream. The next periodic snapshot advertises actual availability without +waiting for checkpoint advancement or new input. If the next sync-point is +already pending, continuing to advertise zero is correct. A failed write must +not clear the barrier. + +Redo watermark forwarding already calls `HandleCacheEvents()` after advancing +`redoGlobalTs`. This retries the active batch and wakes the stream when it can +continue. If processing enters a sync-point barrier, that barrier independently +keeps the scan pause active. Do not gate the actual redo dispatcher on +`redoGlobalTs`, since its progress is needed to advance that value. + +Current quota messages do not carry a per-path epoch. A delayed zero snapshot +can temporarily overwrite a newer value, but periodic current snapshots +converge after a finite backlog and network recovery. There is no persistent +pause bit requiring a paired Resume. Reset/move/recreated dispatchers derive +state from their own live barrier; removed sessions must not be resurrected. + +## Liveness and concurrency review + +Under readable upstream/schema progress, eventually writable sink, eventual +control delivery and scheduling, and sufficient reclaimable pending data: + +1. Periodic checks request reclamation without needing input. +2. Owner-thread reclamation frees actual bytes and the next quota report exposes them. +3. The slow participant can scan to S and satisfy existing barrier coverage. +4. Write/Pass runs independently of DML scan quota and clears the pause reason. +5. Wake processes the retained DropEvent and recovery proceeds through the existing epoch protocol. + +This breaks the stated resource cycle. Permanent sink failures, disconnected +members and infinite starvation by other producers are outside these premises. + +Required interleavings include both Wake/Release orders, Remove/recreation, +feedback saturation, old/new sources and epochs, back-to-back barriers, reset +while a barrier is pending, redo dependencies, and shutdown. Memory requests +must not masquerade as progress; recovery markers must survive later reclamation. + +## Observability, cost and compatibility + +No configuration, protobuf or wire version changes are required. Existing +brokers understand zero quota. Full behavior requires an updated collector; +mixed-version deployments do not provide all guarantees immediately. + +The status getter is constant-time once per dispatcher per second. Area checks +are linear in area count; only pressured stalled areas enumerate/sort paths. +Reclamation remains linear in the affected queue, and retained recovery markers +consume real memory. Measure control latency with long queues. + +Reuse existing quota-skip, release, DropEvent/reset and barrier diagnostics. +Any additions should be bounded area summaries with representative IDs rather +than per-event logging or high-cardinality Prometheus labels. Correlate barrier +TS, epoch, pending bytes, quota, cursor, reclaimed bytes and checkpoint. DS +pending memory is not equivalent to total process RSS. + +## Implementation and validation + +Changes are owned by dynamic-stream memory/queue management, dispatcher barrier +state, collector congestion reporting and the broker's scan admission gate. +Only necessary interface test doubles are adapted. Generated mocks, if affected, +are regenerated through the repository workflow. + +First construct failing regressions, then implement reclamation/recovery before +adding sync-point-derived zero quota. Cover: + +- Silence and merged resolved signals with blocked high-memory queues. +- Concurrent periodic/append checks, bounded feedback, retry and actual accounting. +- Retained data-loss markers and idle resolved watermarks; Wake without new input. +- Non-droppable events and multiple sources/epochs; removal/shutdown races. +- Puller exclusion, redo separation and WAITING/WRITING eligibility. +- Redo cache waits, partial/sufficient watermark advances, consecutive waits, + concurrent removal and handoff to sync-point backpressure. +- Successful/failed completion, delayed/lost quota reports and consecutive barriers. +- Zero-quota rate/shared-budget preservation, cursor safety and local advance. +- Shared A/B starvation followed by barrier completion and checksum-correct replay. + +Run targeted package tests using the repository race/failpoint workflow: + +```sh +make unit_test_pkg PKG=./utils/dynstream/... +make unit_test_pkg PKG=./downstreamadapter/dispatcher/... +make unit_test_pkg PKG=./downstreamadapter/eventcollector/... +make unit_test_pkg PKG=./pkg/eventservice/... +make cdc +``` diff --git a/downstreamadapter/dispatcher/basic_dispatcher.go b/downstreamadapter/dispatcher/basic_dispatcher.go index 736342bf9d..06ffca2aeb 100644 --- a/downstreamadapter/dispatcher/basic_dispatcher.go +++ b/downstreamadapter/dispatcher/basic_dispatcher.go @@ -54,6 +54,7 @@ type DispatcherService interface { GetTxnAtomicity() config.AtomicityLevel GetResolvedTs() uint64 GetCheckpointTs() uint64 + ShouldPauseScan() bool HandleEvents(events []DispatcherEvent, wakeCallback func()) (block bool) IsOutputRawChangeEvent() bool } @@ -1189,6 +1190,17 @@ func (d *BasicDispatcher) GetBlockEventStatus() *heartbeatpb.State { } } +// ShouldPauseScan reports a syncpoint already being handled by this dispatcher. +// Redo dispatchers must keep scanning to advance the redo watermark. +func (d *BasicDispatcher) ShouldPauseScan() bool { + if common.IsRedoMode(d.GetMode()) { + return false + } + pending, stage := d.blockEventStatus.getEventAndStage() + return pending != nil && pending.GetType() == commonEvent.TypeSyncPointEvent && + (stage == heartbeatpb.BlockStage_WAITING || stage == heartbeatpb.BlockStage_WRITING) +} + func (d *BasicDispatcher) Remove() { log.Panic("should not call this") } diff --git a/downstreamadapter/dispatcher/event_dispatcher.go b/downstreamadapter/dispatcher/event_dispatcher.go index a9463e72be..b05c424e04 100644 --- a/downstreamadapter/dispatcher/event_dispatcher.go +++ b/downstreamadapter/dispatcher/event_dispatcher.go @@ -46,6 +46,9 @@ type EventDispatcher struct { cacheEvents struct { sync.Mutex events chan cacheEvents + // requiredTs is published before the cached batch can be retried and + // cleared before handling it, so completion cannot erase a newer wait. + requiredTs atomic.Uint64 } } @@ -99,6 +102,7 @@ func (d *EventDispatcher) HandleCacheEvents() { if !ok { return } + d.cacheEvents.requiredTs.Store(0) block := d.HandleEvents(cacheEvents.events, cacheEvents.wakeCallback) if !block { cacheEvents.wakeCallback() @@ -120,6 +124,7 @@ func (d *EventDispatcher) cache(dispatcherEvents []DispatcherEvent, wakeCallback events: append(make([]DispatcherEvent, 0, len(dispatcherEvents)), dispatcherEvents...), wakeCallback: wakeCallback, } + d.cacheEvents.requiredTs.Store(dispatcherEvents[len(dispatcherEvents)-1].GetCommitTs()) select { case d.cacheEvents.events <- cacheEvents: log.Debug("cache events", @@ -144,12 +149,20 @@ func (d *EventDispatcher) HandleEvents(dispatcherEvents []DispatcherEvent, wakeC return d.handleEvents(dispatcherEvents, wakeCallback) } +// ShouldPauseScan stops prefetch while an actual cached batch needs redo +// progress, or while this dispatcher is handling a syncpoint barrier. +func (d *EventDispatcher) ShouldPauseScan() bool { + return d.BasicDispatcher.ShouldPauseScan() || + (d.redoEnable && d.cacheEvents.requiredTs.Load() > d.redoGlobalTs.Load()) +} + // Remove is called when TryClose returns true // It set isRemoving to true, to make the dispatcher can be clean by the DispatcherManager. func (d *EventDispatcher) Remove() { if d.isRemoving.CompareAndSwap(false, true) { d.cacheEvents.Lock() defer d.cacheEvents.Unlock() + d.cacheEvents.requiredTs.Store(0) close(d.cacheEvents.events) } d.removeDispatcher() diff --git a/downstreamadapter/dispatcher/event_dispatcher_test.go b/downstreamadapter/dispatcher/event_dispatcher_test.go index 7c7c896ecc..d1a1d06a88 100644 --- a/downstreamadapter/dispatcher/event_dispatcher_test.go +++ b/downstreamadapter/dispatcher/event_dispatcher_test.go @@ -499,7 +499,12 @@ func TestDispatcherHandleEvents(t *testing.T) { syncPointEvent := &commonEvent.SyncPointEvent{ CommitTs: 6, } - block = dispatcher.HandleEvents([]DispatcherEvent{NewDispatcherEvent(&nodeID, syncPointEvent)}, callback) + var pausedAtSyncPointWake atomic.Bool + pausedAtSyncPointWake.Store(true) + block = dispatcher.HandleEvents([]DispatcherEvent{NewDispatcherEvent(&nodeID, syncPointEvent)}, func() { + pausedAtSyncPointWake.Store(dispatcher.ShouldPauseScan()) + callback() + }) require.Equal(t, true, block) require.Eventually(t, func() bool { blockPendingEvent, blockStage = dispatcher.blockEventStatus.getEventAndStage() @@ -511,6 +516,7 @@ func TestDispatcherHandleEvents(t *testing.T) { require.NotNil(t, blockPendingEvent) require.Equal(t, blockStage, heartbeatpb.BlockStage_WAITING) + require.True(t, dispatcher.ShouldPauseScan()) // not available for write to sink checkpointTs, isEmpty = tableProgress.GetCheckpointTs() require.Equal(t, true, isEmpty) @@ -547,6 +553,9 @@ func TestDispatcherHandleEvents(t *testing.T) { return count.Load() == int32(6) }, 5*time.Second, 10*time.Millisecond) + require.False(t, pausedAtSyncPointWake.Load(), "successful Pass must clear the pause before Wake") + require.False(t, dispatcher.ShouldPauseScan()) + // ===== resolved event ===== checkpointTs = dispatcher.GetCheckpointTs() require.Equal(t, uint64(5), checkpointTs) diff --git a/downstreamadapter/dispatcher/redo_quota_test.go b/downstreamadapter/dispatcher/redo_quota_test.go new file mode 100644 index 0000000000..c006f82f65 --- /dev/null +++ b/downstreamadapter/dispatcher/redo_quota_test.go @@ -0,0 +1,114 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dispatcher + +import ( + "sync" + "testing" + + "github.com/pingcap/ticdc/heartbeatpb" + "github.com/pingcap/ticdc/pkg/common" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/node" + "github.com/stretchr/testify/require" +) + +func TestScanPauseFollowsRedoWaitLifecycle(t *testing.T) { + testSink := newDispatcherTestSink(t, common.MysqlSinkType) + d := newDispatcherForTest(testSink.Sink(), getUncompleteTableSpan()) + defer d.Remove() + d.redoGlobalTs.Store(50) + from := node.NewID() + batch := func(ts uint64) []DispatcherEvent { + return []DispatcherEvent{NewDispatcherEvent(&from, commonEvent.NewResolvedEvent(ts, d.id, 1))} + } + // Redo-disabled dispatchers do not wait even when the watermark is behind. + require.False(t, d.HandleEvents(batch(60), func() {})) + require.False(t, d.ShouldPauseScan()) + d.redoEnable = true + require.False(t, d.ShouldPauseScan(), "a low watermark alone must not pause scanning") + wakes := 0 + require.True(t, d.HandleEvents(batch(100), func() { + wakes++ + require.False(t, d.ShouldPauseScan(), "clear the old wait before Wake") + // Wake can immediately begin a new wait. Completion of the old batch + // must not clear this new pause. + require.True(t, d.HandleEvents(batch(200), func() { + wakes++ + require.False(t, d.ShouldPauseScan()) + })) + })) + require.True(t, d.ShouldPauseScan()) + d.redoGlobalTs.Store(90) + d.HandleCacheEvents() + require.True(t, d.ShouldPauseScan(), "an insufficient watermark must retain the wait") + require.Zero(t, wakes) + require.Equal(t, uint64(60), d.GetResolvedTs()) + + d.redoGlobalTs.Store(100) + require.False(t, d.ShouldPauseScan(), "quota can recover as soon as the watermark catches up") + d.HandleCacheEvents() + require.Equal(t, 1, wakes) + require.Equal(t, uint64(100), d.GetResolvedTs()) + require.True(t, d.ShouldPauseScan(), "the next cached batch still needs redo progress") + d.redoGlobalTs.Store(201) + d.HandleCacheEvents() + require.Equal(t, 2, wakes) + require.Equal(t, uint64(200), d.GetResolvedTs()) + require.False(t, d.ShouldPauseScan()) + d.HandleCacheEvents() + require.Equal(t, 2, wakes, "recovery must not replay a batch twice") + + // A completed redo wait must not mask a subsequent syncpoint barrier. + d.blockEventStatus.setBlockEvent(commonEvent.NewSyncPointEvent(d.id, 200, 1, 1), heartbeatpb.BlockStage_WAITING) + require.True(t, d.ShouldPauseScan()) + d.blockEventStatus.clear() + require.False(t, d.ShouldPauseScan()) +} + +func TestRedoScanPauseConcurrentRemoval(t *testing.T) { + testSink := newDispatcherTestSink(t, common.MysqlSinkType) + d := newDispatcherForTest(testSink.Sink(), getUncompleteTableSpan()) + d.redoEnable = true + d.redoGlobalTs.Store(50) + from := node.NewID() + batch := []DispatcherEvent{NewDispatcherEvent(&from, commonEvent.NewResolvedEvent(100, d.id, 1))} + require.True(t, d.HandleEvents(batch, func() { t.Error("insufficient redo progress must not wake the path") })) + require.True(t, d.ShouldPauseScan()) + + // The watermark retry, congestion snapshot and removal run on different + // goroutines. A retry racing with removal must not republish an old wait. + var workers sync.WaitGroup + start := make(chan struct{}) + for _, action := range []func(){d.HandleCacheEvents, d.Remove, func() { d.ShouldPauseScan() }} { + workers.Add(1) + go func(action func()) { + defer workers.Done() + <-start + action() + }(action) + } + close(start) + workers.Wait() + require.False(t, d.ShouldPauseScan()) + d.HandleCacheEvents() + require.False(t, d.ShouldPauseScan(), "a removed dispatcher must not reenter a redo wait") + + replacement := newDispatcherForTest(testSink.Sink(), getUncompleteTableSpan()) + defer replacement.Remove() + replacement.redoEnable = true + replacement.redoGlobalTs.Store(50) + require.False(t, replacement.ShouldPauseScan(), "a new dispatcher must derive its own pause state") +} diff --git a/downstreamadapter/dispatcher/syncpoint_quota_test.go b/downstreamadapter/dispatcher/syncpoint_quota_test.go new file mode 100644 index 0000000000..7b2685a78d --- /dev/null +++ b/downstreamadapter/dispatcher/syncpoint_quota_test.go @@ -0,0 +1,41 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dispatcher + +import ( + "testing" + + "github.com/pingcap/ticdc/heartbeatpb" + "github.com/pingcap/ticdc/pkg/common" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/stretchr/testify/require" +) + +func TestScanPauseFollowsSyncPointLifecycle(t *testing.T) { + d := &BasicDispatcher{} + require.False(t, d.ShouldPauseScan()) + sp := commonEvent.NewSyncPointEvent(common.NewDispatcherID(), 100, 1, 1) + for _, stage := range []heartbeatpb.BlockStage{heartbeatpb.BlockStage_WAITING, heartbeatpb.BlockStage_WRITING} { + d.blockEventStatus.setBlockEvent(sp, stage) + require.True(t, d.ShouldPauseScan()) + } + d.blockEventStatus.clear() + require.False(t, d.ShouldPauseScan()) + d.blockEventStatus.setBlockEvent(&commonEvent.DDLEvent{FinishedTs: 101}, heartbeatpb.BlockStage_WAITING) + require.False(t, d.ShouldPauseScan(), "DDL must not activate the syncpoint quota override") + d.blockEventStatus.setBlockEvent(sp, heartbeatpb.BlockStage_WAITING) + d.mode = common.RedoMode + require.False(t, d.ShouldPauseScan(), "redo must remain able to reach the barrier") +} diff --git a/downstreamadapter/eventcollector/dispatcher_stat_test.go b/downstreamadapter/eventcollector/dispatcher_stat_test.go index 73ccdbe3cf..470c68e092 100644 --- a/downstreamadapter/eventcollector/dispatcher_stat_test.go +++ b/downstreamadapter/eventcollector/dispatcher_stat_test.go @@ -2492,3 +2492,5 @@ func TestUpdateTableInfoByDDLStateChange(t *testing.T) { }) } } + +func (m *mockDispatcher) ShouldPauseScan() bool { return false } diff --git a/downstreamadapter/eventcollector/event_collector.go b/downstreamadapter/eventcollector/event_collector.go index 773934247f..cc321f0f24 100644 --- a/downstreamadapter/eventcollector/event_collector.go +++ b/downstreamadapter/eventcollector/event_collector.go @@ -448,20 +448,20 @@ func (c *EventCollector) processDSFeedback(ctx context.Context) error { case <-ctx.Done(): return context.Cause(ctx) case feedback := <-c.ds.Feedback(): - if feedback.FeedbackType == dynstream.ReleasePath { + if feedback.FeedbackType == dynstream.ReleasePath && feedback.Release != nil && + c.getDispatcherStatByID(feedback.Path) == feedback.Dest && feedback.Release() { if v, ok := c.changefeedMap.Load(feedback.Area); ok { v.(*changefeedStat).memoryReleaseCount.Add(1) } log.Info("release dispatcher memory in DS", zap.Any("dispatcherID", feedback.Path)) - c.ds.Release(feedback.Path) } case feedback := <-c.redoDs.Feedback(): - if feedback.FeedbackType == dynstream.ReleasePath { + if feedback.FeedbackType == dynstream.ReleasePath && feedback.Release != nil && + c.getDispatcherStatByID(feedback.Path) == feedback.Dest && feedback.Release() { if v, ok := c.changefeedMap.Load(feedback.Area); ok { v.(*changefeedStat).memoryReleaseCount.Add(1) } log.Info("release dispatcher memory in redo DS", zap.Any("dispatcherID", feedback.Path)) - c.redoDs.Release(feedback.Path) } } } @@ -581,22 +581,23 @@ func (c *EventCollector) runDispatchMessage(ctx context.Context, inCh <-chan *me case <-ctx.Done(): return context.Cause(ctx) case targetMessage := <-inCh: + // Queued events must not keep the message and its payload alive via From. + from := targetMessage.From for _, msg := range targetMessage.Message { switch e := msg.(type) { case event.Event: switch e.GetType() { case event.TypeBatchResolvedEvent: events := e.(*event.BatchResolvedEvent).Events - from := &targetMessage.From resolvedTsCount := int32(0) for _, resolvedEvent := range events { - ds.Push(resolvedEvent.DispatcherID, dispatcher.NewDispatcherEvent(from, resolvedEvent)) + ds.Push(resolvedEvent.DispatcherID, dispatcher.NewDispatcherEvent(&from, resolvedEvent)) resolvedTsCount += resolvedEvent.Len() } metricDispatcherReceivedResolvedTsEventCount.Add(float64(resolvedTsCount)) default: metricDispatcherReceivedKVEventCount.Add(float64(e.Len())) - dispatcherEvent := dispatcher.NewDispatcherEvent(&targetMessage.From, e) + dispatcherEvent := dispatcher.NewDispatcherEvent(&from, e) ds.Push(e.GetDispatcherID(), dispatcherEvent) } default: @@ -618,6 +619,8 @@ func (c *EventCollector) controlCongestion(ctx context.Context) error { case <-ctx.Done(): return context.Cause(ctx) case <-ticker.C: + c.ds.CheckMemoryPressure() + c.redoDs.CheckMemoryPressure() messages := c.newCongestionControlMessages() for serverID, m := range messages { if len(m.GetAvailables()) != 0 { @@ -720,7 +723,10 @@ func (c *EventCollector) newCongestionControlMessages() map[node.ID]*event.Conge // get available memory for this dispatcher if pathMemory, exists := changefeedPathMemory[changefeedID][dispatcherID]; exists { - nodeDispatcherMemory[eventServiceID][changefeedID][dispatcherID] = uint64(pathMemory) + if !common.IsRedoMode(stat.target.GetMode()) && stat.target.ShouldPauseScan() { + pathMemory = 0 + } + nodeDispatcherMemory[eventServiceID][changefeedID][dispatcherID] = pathMemory } return true }) diff --git a/downstreamadapter/eventcollector/event_collector_test.go b/downstreamadapter/eventcollector/event_collector_test.go index 5b33a3b69a..d5ee8d72ba 100644 --- a/downstreamadapter/eventcollector/event_collector_test.go +++ b/downstreamadapter/eventcollector/event_collector_test.go @@ -31,12 +31,15 @@ import ( "github.com/pingcap/ticdc/pkg/node" "github.com/pingcap/ticdc/pkg/routing" "github.com/pingcap/ticdc/pkg/util" + "github.com/pingcap/ticdc/utils/dynstream" "github.com/stretchr/testify/require" ) var _ dispatcher.DispatcherService = (*mockEventDispatcher)(nil) type mockEventDispatcher struct { + pauseScan bool + mode int64 id common.DispatcherID tableSpan *heartbeatpb.TableSpan handle func(commonEvent.Event) @@ -58,7 +61,7 @@ func (m *mockEventDispatcher) GetId() common.DispatcherID { } func (m *mockEventDispatcher) GetMode() int64 { - return common.DefaultMode + return m.mode } func (m *mockEventDispatcher) GetStartTs() uint64 { @@ -665,3 +668,45 @@ func TestEventCollectorBatchByBytes(t *testing.T) { require.Equal(t, totalDML, sumDML) require.Equal(t, 1, maxBatch) } + +func (m *mockEventDispatcher) ShouldPauseScan() bool { return m.pauseScan } + +func TestScanPauseQuotaUsesCurrentState(t *testing.T) { + c := &EventCollector{ds: NewEventDynamicStream(false), redoDs: NewEventDynamicStream(true)} + defer c.ds.Close() + defer c.redoDs.Close() + cf := common.NewChangefeedID4Test("default", "syncpoint-quota") + c.changefeedMap.Store(cf.ID(), newChangefeedStat(cf)) + blocked := &mockEventDispatcher{id: common.NewDispatcherID(), changefeedID: cf} + lagging := &mockEventDispatcher{id: common.NewDispatcherID(), changefeedID: cf} + // Even a synthetic pause reported for a redo target must not stop the + // producer of the watermark the ordinary dispatcher is waiting for. + redo := &mockEventDispatcher{id: common.NewDispatcherID(), changefeedID: cf, mode: common.RedoMode, pauseScan: true} + for _, target := range []*mockEventDispatcher{blocked, lagging, redo} { + stat := newDispatcherStat(target, c, nil) + markSessionReceiving(stat.session, "broker") + c.dispatcherMap.Store(target.id, stat) + require.NoError(t, c.getDynamicStream(target.mode).AddPath(target.id, stat, dynstream.NewAreaSettingsWithMaxPendingSize(1<<20, dynstream.MemoryControlForEventCollector, "test"))) + } + available := func() commonEvent.AvailableMemory { + msgs := c.newCongestionControlMessages() + require.Contains(t, msgs, node.ID("broker")) + entries := msgs["broker"].GetAvailables() + require.Len(t, entries, 1) + return entries[0] + } + before := available() + require.Positive(t, before.DispatcherAvailable[blocked.id]) + require.Positive(t, before.DispatcherAvailable[lagging.id]) + require.Positive(t, before.DispatcherAvailable[redo.id]) + blocked.pauseScan = true + paused := available() + require.Zero(t, paused.DispatcherAvailable[blocked.id]) + require.Equal(t, before.Available, paused.Available, "pausing a path must not change shared physical quota") + require.Equal(t, before.DispatcherAvailable[lagging.id], paused.DispatcherAvailable[lagging.id]) + require.Equal(t, before.DispatcherAvailable[redo.id], paused.DispatcherAvailable[redo.id]) + blocked.pauseScan = false + after := available() + require.Equal(t, before.Available, after.Available) + require.Equal(t, before.DispatcherAvailable, after.DispatcherAvailable, "resume must use current quotas without new input") +} diff --git a/downstreamadapter/eventcollector/reclamation_test.go b/downstreamadapter/eventcollector/reclamation_test.go new file mode 100644 index 0000000000..8446629938 --- /dev/null +++ b/downstreamadapter/eventcollector/reclamation_test.go @@ -0,0 +1,320 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package eventcollector + +import ( + "context" + "runtime" + "testing" + "time" + + "github.com/pingcap/ticdc/downstreamadapter/dispatcher" + "github.com/pingcap/ticdc/eventpb" + "github.com/pingcap/ticdc/heartbeatpb" + "github.com/pingcap/ticdc/pkg/common" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/messaging" + "github.com/pingcap/ticdc/pkg/node" + "github.com/pingcap/ticdc/utils/dynstream" + "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/require" +) + +func sendLargeBatchForReclamation(ch chan<- *messaging.TargetMessage, from node.ID, id common.DispatcherID, collected chan<- struct{}) { + batch := &commonEvent.BatchDMLEvent{ + DMLEvents: []*commonEvent.DMLEvent{{DispatcherID: id, Seq: 3, Epoch: 1, CommitTs: 101}}, + RawRows: make([]byte, 1<<20), + } + runtime.SetFinalizer(batch, func(*commonEvent.BatchDMLEvent) { close(collected) }) + ch <- newMessage(from, batch) +} + +func TestReclaimedBatchDoesNotRetainTargetMessage(t *testing.T) { + c := &EventCollector{ + ds: NewEventDynamicStream(false), redoDs: NewEventDynamicStream(true), + metricDispatcherReceivedKVEventCount: prometheus.NewCounter(prometheus.CounterOpts{Name: "test_reclaimed_batch_received_events"}), + } + defer c.ds.Close() + defer c.redoDs.Close() + id := common.NewDispatcherID() + from := node.ID("broker") + blocked := make(chan func(), 1) + target := &mockEventDispatcher{ + id: id, changefeedID: common.NewChangefeedID4Test("default", "reclamation-retention"), + tableSpan: &heartbeatpb.TableSpan{TableID: 1}, checkpointTs: 99, + handleEvents: func(events []dispatcher.DispatcherEvent, wake func()) bool { + blocked <- wake + return true + }, + } + messages := make(chan *messaging.TargetMessage, 1) + stat := newDispatcherStatInternal(target, c, from, func(msg *messaging.TargetMessage) { messages <- msg }, nil) + stat.currentEpoch.Store(newDispatcherEpochState(1, 1, 99)) + markSessionReceiving(stat.session, from) + c.dispatcherMap.Store(id, stat) + require.NoError(t, c.ds.AddPath(id, stat, dynstream.NewAreaSettingsWithMaxPendingSize(1<<20, dynstream.MemoryControlForEventCollector, "test"))) + ctx, cancel := context.WithCancel(context.Background()) + feedbackDone := make(chan error, 1) + go func() { feedbackDone <- c.processDSFeedback(ctx) }() + defer func() { + cancel() + require.ErrorIs(t, <-feedbackDone, context.Canceled) + }() + runCtx, stopRun := context.WithCancel(context.Background()) + defer stopRun() + inCh := make(chan *messaging.TargetMessage, 2) + runDone := make(chan error, 1) + go func() { runDone <- c.runDispatchMessage(runCtx, inCh, common.DefaultMode) }() + inCh <- newMessage(from, commonEvent.NewSyncPointEvent(id, 100, 2, 1)) + var wake func() + select { + case wake = <-blocked: + case <-time.After(5 * time.Second): + t.Fatal("syncpoint did not block") + } + collected := make(chan struct{}) + sendLargeBatchForReclamation(inCh, from, id, collected) + used := func() int64 { return c.ds.GetMetrics().MemoryControl.AreaMemoryMetrics[0].MemoryUsage() } + require.Eventually(t, func() bool { return used() >= 1<<20 }, 5*time.Second, time.Millisecond) + stopRun() + require.ErrorIs(t, <-runDone, context.Canceled) + require.Eventually(t, func() bool { + c.ds.CheckMemoryPressure() + return used() < 1000 + }, 10*time.Second, 10*time.Millisecond) + require.Eventually(t, func() bool { + runtime.GC() + select { + case <-collected: + return true + default: + return false + } + }, 5*time.Second, 20*time.Millisecond, "reclaimed payload remains reachable while the drop marker is queued") + require.Empty(t, messages) + wake() + select { + case msg := <-messages: + req := msg.Message[0].(*messaging.DispatcherRequest) + require.Equal(t, eventpb.ActionType_ACTION_TYPE_RESET, req.ActionType) + case <-time.After(5 * time.Second): + t.Fatal("retained drop notification did not reset") + } +} + +func TestReclaimedDataResetsAfterWakeWithoutNewInput(t *testing.T) { + for _, mode := range []struct { + name string + value int64 + }{{"main", common.DefaultMode}, {"redo", common.RedoMode}} { + t.Run(mode.name, func(t *testing.T) { + c := &EventCollector{ds: NewEventDynamicStream(false), redoDs: NewEventDynamicStream(true)} + defer c.ds.Close() + defer c.redoDs.Close() + ds := c.getDynamicStream(mode.value) + blocked := make(chan func(), 1) + target := &mockEventDispatcher{ + mode: mode.value, + id: common.NewDispatcherID(), + changefeedID: common.NewChangefeedID4Test("default", "reclamation"), + tableSpan: &heartbeatpb.TableSpan{TableID: 1}, + checkpointTs: 99, + handleEvents: func(events []dispatcher.DispatcherEvent, wake func()) bool { + blocked <- wake + return true + }, + } + messages := make(chan *messaging.TargetMessage, 4) + stat := newDispatcherStatInternal(target, c, "broker", func(msg *messaging.TargetMessage) { messages <- msg }, nil) + stat.currentEpoch.Store(newDispatcherEpochState(1, 1, 99)) + markSessionReceiving(stat.session, "broker") + c.dispatcherMap.Store(target.id, stat) + require.NoError(t, ds.AddPath(target.id, stat, dynstream.NewAreaSettingsWithMaxPendingSize(1<<20, dynstream.MemoryControlForEventCollector, "test"))) + ctx, cancel := context.WithCancel(context.Background()) + feedbackDone := make(chan error, 1) + go func() { feedbackDone <- c.processDSFeedback(ctx) }() + defer func() { + cancel() + require.ErrorIs(t, <-feedbackDone, context.Canceled) + }() + from := node.ID("broker") + push := func(e commonEvent.Event) { ds.Push(target.id, dispatcher.NewDispatcherEvent(&from, e)) } + if common.IsRedoMode(mode.value) { + // Redo can block on sink enqueue; it does not wait for syncpoints. + push(&commonEvent.DMLEvent{DispatcherID: target.id, Seq: 2, Epoch: 1, CommitTs: 100, ApproximateSize: 100}) + } else { + push(commonEvent.NewSyncPointEvent(target.id, 100, 2, 1)) + } + var wake func() + select { + case wake = <-blocked: + case <-time.After(5 * time.Second): + t.Fatal("active batch not handled") + } + push(&commonEvent.DMLEvent{DispatcherID: target.id, Seq: 3, Epoch: 1, CommitTs: 101, ApproximateSize: 900000}) + resolved := commonEvent.NewResolvedEvent(102, target.id, 1) + push(resolved) + used := func() int64 { return ds.GetMetrics().MemoryControl.AreaMemoryMetrics[0].MemoryUsage() } + require.Eventually(t, func() bool { return used() >= 900000 }, 5*time.Second, time.Millisecond) + // No new input drives recovery: periodic pressure checks and feedback alone + // must reclaim the blocked pending data in either stream. + require.Eventually(t, func() bool { + ds.CheckMemoryPressure() + return used() < 1000 + }, 10*time.Second, 10*time.Millisecond) + require.Empty(t, messages, "reclamation cannot reset or release an active batch") + // Upstream sends nothing further: the retained DropEvent alone must reset. + wake() + select { + case msg := <-messages: + req := msg.Message[0].(*messaging.DispatcherRequest) + require.Equal(t, eventpb.ActionType_ACTION_TYPE_RESET, req.ActionType) + require.Equal(t, uint64(2), req.Epoch) + require.Equal(t, uint64(99), req.StartTs) + case <-time.After(5 * time.Second): + t.Fatal("retained drop notification did not reset") + } + require.Eventually(t, func() bool { return used() == 0 }, 5*time.Second, time.Millisecond) + // A delayed marker from the old epoch must not reset the new session. + ds.Close() + stat.handleDropEvent(dispatcher.NewDispatcherEvent(&from, commonEvent.NewDropEvent(target.id, 4, 1, 103))) + require.Empty(t, messages) + require.Equal(t, uint64(2), stat.loadCurrentEpochState().epoch) + }) + } +} + +// A fast table waiting at a syncpoint retains an active batch while its +// pending DML consumes the shared quota. Reclamation must advertise the freed +// capacity to the lagging table (or its redo producer), then the barrier can +// finish and the reclaimed fast path can reset without another input event. +func TestSyncpointReclamationRestoresLaggingScanQuota(t *testing.T) { + for _, withRedo := range []bool{false, true} { + name := "main" + if withRedo { + name = "redo" + } + t.Run(name, func(t *testing.T) { + c := &EventCollector{ds: NewEventDynamicStream(false), redoDs: NewEventDynamicStream(true)} + defer c.ds.Close() + defer c.redoDs.Close() + cf := common.NewChangefeedID4Test("default", "syncpoint-reclaim-"+name) + cfStat := newChangefeedStat(cf) + c.changefeedMap.Store(cf.ID(), cfStat) + from := node.ID("broker") + blocked := make(chan func(), 1) + fast := &mockEventDispatcher{ + id: common.NewDispatcherID(), changefeedID: cf, + tableSpan: &heartbeatpb.TableSpan{TableID: 1}, checkpointTs: 99, + handleEvents: func(events []dispatcher.DispatcherEvent, wake func()) bool { + blocked <- wake + return true + }, + } + slowProgress := make(chan struct{}, 1) + slowMode := common.DefaultMode + if withRedo { + slowMode = common.RedoMode + } + slow := &mockEventDispatcher{ + id: common.NewDispatcherID(), changefeedID: cf, mode: slowMode, + tableSpan: &heartbeatpb.TableSpan{TableID: 2}, checkpointTs: 99, + handleEvents: func(events []dispatcher.DispatcherEvent, wake func()) bool { + slowProgress <- struct{}{} + return false + }, + } + messages := make(chan *messaging.TargetMessage, 2) + for _, target := range []*mockEventDispatcher{fast, slow} { + stat := newDispatcherStatInternal(target, c, from, func(msg *messaging.TargetMessage) { messages <- msg }, nil) + stat.currentEpoch.Store(newDispatcherEpochState(1, 1, 99)) + markSessionReceiving(stat.session, from) + c.dispatcherMap.Store(target.id, stat) + require.NoError(t, c.getDynamicStream(target.mode).AddPath(target.id, stat, + dynstream.NewAreaSettingsWithMaxPendingSize(1<<20, dynstream.MemoryControlForEventCollector, "test"))) + } + ctx, cancel := context.WithCancel(context.Background()) + feedbackDone := make(chan error, 1) + go func() { feedbackDone <- c.processDSFeedback(ctx) }() + defer func() { + cancel() + require.ErrorIs(t, <-feedbackDone, context.Canceled) + }() + push := func(target *mockEventDispatcher, e commonEvent.Event) { + c.getDynamicStream(target.mode).Push(target.id, dispatcher.NewDispatcherEvent(&from, e)) + } + quota := func() commonEvent.AvailableMemory { + msgs := c.newCongestionControlMessages() + require.Contains(t, msgs, from) + entries := msgs[from].GetAvailables() + require.Len(t, entries, 1) + return entries[0] + } + + push(fast, commonEvent.NewSyncPointEvent(fast.id, 100, 2, 1)) + var wakeFast func() + select { + case wakeFast = <-blocked: + case <-time.After(5 * time.Second): + t.Fatal("fast syncpoint did not block") + } + fast.pauseScan = true + push(fast, &commonEvent.DMLEvent{DispatcherID: fast.id, Seq: 3, Epoch: 1, CommitTs: 101, ApproximateSize: 1 << 20}) + require.Eventually(t, func() bool { + return c.ds.GetMetrics().MemoryControl.AreaMemoryMetrics[0].MemoryUsage() >= 1<<20 + }, 5*time.Second, time.Millisecond) + before := quota() + require.Zero(t, before.Available, "the fast path has exhausted shared scan capacity") + require.Zero(t, before.DispatcherAvailable[fast.id], "syncpoint waiter must stop scanning") + require.Positive(t, before.DispatcherAvailable[slow.id], "lagging producer must retain its path quota") + + // The periodic pressure check works even though no further events arrive. + require.Eventually(t, func() bool { + c.ds.CheckMemoryPressure() + return c.ds.GetMetrics().MemoryControl.AreaMemoryMetrics[0].MemoryUsage() < 1000 + }, 10*time.Second, 10*time.Millisecond) + require.Eventually(t, func() bool { return cfStat.memoryReleaseCount.Load() == 1 }, 5*time.Second, time.Millisecond) + after := quota() + require.Zero(t, after.DispatcherAvailable[fast.id]) + require.Greater(t, after.Available, before.Available) + require.Equal(t, uint32(1), after.MemoryReleaseCount) + require.Empty(t, messages, "reclamation must not reset an active batch") + + // Model the producer's next scan only after it receives freed quota. + if withRedo { + push(slow, &commonEvent.DMLEvent{DispatcherID: slow.id, Seq: 2, Epoch: 1, CommitTs: 100, ApproximateSize: 100}) + } else { + push(slow, commonEvent.NewSyncPointEvent(slow.id, 100, 2, 1)) + } + select { + case <-slowProgress: + case <-time.After(5 * time.Second): + t.Fatal("lagging producer did not advance") + } + fast.pauseScan = false + wakeFast() + select { + case msg := <-messages: + req := msg.Message[0].(*messaging.DispatcherRequest) + require.Equal(t, fast.id, req.GetID()) + require.Equal(t, eventpb.ActionType_ACTION_TYPE_RESET, req.ActionType) + require.Equal(t, uint64(2), req.Epoch) + case <-time.After(5 * time.Second): + t.Fatal("reclaimed fast path did not reset after barrier completion") + } + require.Positive(t, quota().DispatcherAvailable[fast.id], "resumed path must be eligible to scan") + }) + } +} diff --git a/logservice/logpuller/region_event_sink_test.go b/logservice/logpuller/region_event_sink_test.go index 249c877883..b0c91f5f7d 100644 --- a/logservice/logpuller/region_event_sink_test.go +++ b/logservice/logpuller/region_event_sink_test.go @@ -165,3 +165,5 @@ func TestRegionEventSinkRemovePathReleasesQueuedEventMemory(t *testing.T) { return getMemoryQuotaTestState(quota).used == 0 }, time.Second, 10*time.Millisecond) } + +func (s *mockRegionEventSinkStream) CheckMemoryPressure() {} diff --git a/logservice/logpuller/region_request_worker_test.go b/logservice/logpuller/region_request_worker_test.go index a5cd6174a6..c0fc6d6052 100644 --- a/logservice/logpuller/region_request_worker_test.go +++ b/logservice/logpuller/region_request_worker_test.go @@ -762,3 +762,7 @@ func TestReceiveAndDispatchChangeEventsEOFIsRetriable(t *testing.T) { }) } } + +func (m *recordingRegionEventDynamicStream) CheckMemoryPressure() {} + +func (m *mockRegionEventDynamicStream) CheckMemoryPressure() {} diff --git a/logservice/logpuller/subscription_client_test.go b/logservice/logpuller/subscription_client_test.go index 025b54a22a..3533048c14 100644 --- a/logservice/logpuller/subscription_client_test.go +++ b/logservice/logpuller/subscription_client_test.go @@ -829,3 +829,5 @@ func TestGetResolvedTargetTs(t *testing.T) { require.Equal(t, uint64(0), targetTs5, "targetTs should be 0 when currentTime - resolvedTime < resolveLockFence") } + +func (s *mockDynamicStream) CheckMemoryPressure() {} diff --git a/pkg/eventservice/event_broker.go b/pkg/eventservice/event_broker.go index f9039bc034..f364ee152c 100644 --- a/pkg/eventservice/event_broker.go +++ b/pkg/eventservice/event_broker.go @@ -19,6 +19,7 @@ import ( "sync" "time" + "github.com/pingcap/failpoint" "github.com/pingcap/log" "github.com/pingcap/ticdc/logservice/eventstore" "github.com/pingcap/ticdc/logservice/schemastore" @@ -493,6 +494,16 @@ func (c *eventBroker) getScanTaskRequest(task scanTask) (bool, eventstore.ScanRe // It also reports when the applied SchemaStore frontier is the effective range // cap, so low-latency mode can retry the dispatcher after that frontier advances. func (c *eventBroker) getScanTaskRequestResult(task scanTask) scanTaskRequestResult { + failpoint.Inject("DelayCursorRoundsUntil", func(value failpoint.Value) { + if testShouldDelayCursorRound(task, value.(string)) { + failpoint.Return(scanTaskRequestResult{}) + } + }) + failpoint.Inject("DelayChangefeedScanUntil", func(value failpoint.Value) { + if testShouldDelayChangefeedScan(task, value.(string)) { + failpoint.Return(scanTaskRequestResult{}) + } + }) // 1. Get the range and resume cursor of the dispatcher. request, needScan := task.getScanRequest() if !needScan { @@ -753,6 +764,13 @@ func (c *eventBroker) doScan(ctx context.Context, task scanTask) { return } + failpoint.Inject("DelayTableScanUntil", func(value failpoint.Value) { + if testShouldDelayTableScan(task, value.(string)) { + time.Sleep(10 * time.Millisecond) + failpoint.Return() + } + }) + requestResult := c.getScanTaskRequestResult(task) if !requestResult.needScan { schemaBlocked = requestResult.schemaBlocked @@ -761,6 +779,15 @@ func (c *eventBroker) doScan(ctx context.Context, task scanTask) { } request := requestResult.request + // A consumer waiting for a syncpoint or redo watermark needs no more DML + // scans. Keep ready, handshake and no-data progress above this gate, without + // spending scan tokens or reserving shared memory needed by lagging dispatchers. + if task.availableMemoryQuota.Load() == 0 { + c.sendSignalResolvedTs(task) + metrics.EventServiceSkipScanCount.WithLabelValues("dispatcher_quota").Inc() + return + } + // TODO: Currently, this rate limit does not take into account the priority of each task, which may lead to situations where certain tasks are starved and cannot be scheduled for a long time. // For example, there are 10 dispatchers in the incremental scanning phase, with a large amount of traffic and a continuous stream of tasks, which occupy all the rate limits. // At this time, a dispatcher with very little traffic comes in. It cannot apply for the rate limit, resulting in it being starved and unable to be scheduled for a long time. diff --git a/pkg/eventservice/event_broker_failpoint.go b/pkg/eventservice/event_broker_failpoint.go new file mode 100644 index 0000000000..30437fd32d --- /dev/null +++ b/pkg/eventservice/event_broker_failpoint.go @@ -0,0 +1,112 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package eventservice + +import ( + "strconv" + "strings" + "sync" + "time" + + "github.com/pingcap/log" + "go.uber.org/zap" +) + +// These helpers implement the bounded scheduling fault used by the syncpoint +// regression test. The failpoint.Inject sites stay in event_broker.go at the +// actual scan decisions, so normal builds do not call these helpers. The same +// fault can be applied to master and the fix: it delays selected scans only; +// it never changes the scan cursor, memory quota, or barrier state. +// +// DelayTableScanUntil uses "tableID:deadlineMillis" for the slow table's +// active transaction cursor. DelayChangefeedScanUntil uses +// "changefeedName:slowTableID:deadlineMillis" to delay other tables, including +// idle scans. DelayCursorRoundsUntil uses +// "changefeedName:slowTableID:firstDeadlineMillis:secondDeadlineMillis" to +// hold two distinct cursor positions of the fast tables. Absolute deadlines +// bound each fault even if the test process loses control. + +// Cursor state is keyed by scan task so independently dispatched tables do +// not share round numbers. It is removed when the deadline expires or the +// active transaction cursor ends. +var testCursorPauseStates sync.Map + +type testCursorPauseState struct { + sync.Mutex + position string + count int +} + +func testShouldDelayCursorRound(task scanTask, specification string) bool { + parts := strings.SplitN(specification, ":", 4) + if len(parts) != 4 || task.changefeedStat.changefeedID.Name() != parts[0] { + return false + } + slowTableID, e0 := strconv.ParseInt(parts[1], 10, 64) + firstUntil, e1 := strconv.ParseInt(parts[2], 10, 64) + secondUntil, e2 := strconv.ParseInt(parts[3], 10, 64) + if e0 != nil || e1 != nil || e2 != nil || task.info.GetTableSpan().TableID == slowTableID { + return false + } + if time.Now().UnixMilli() >= secondUntil { + testCursorPauseStates.Delete(task) + return false + } + progress := task.loadScanProgress() + if progress.txnStartTs == 0 { + testCursorPauseStates.Delete(task) + return false + } + valueState, _ := testCursorPauseStates.LoadOrStore(task, &testCursorPauseState{}) + state := valueState.(*testCursorPauseState) + state.Lock() + position := string(progress.rowLevelScanPosition) + changed := state.count == 0 || position != state.position + if changed { + state.count++ + state.position = position + } + count := state.count + state.Unlock() + until := secondUntil + if count == 1 { + until = firstUntil + } + if changed { + log.Info("test cursor scheduling delay", zap.Stringer("changefeedID", task.changefeedStat.changefeedID), zap.Stringer("dispatcherID", task.id), zap.Int64("tableID", task.info.GetTableSpan().TableID), zap.Int("cursorRound", count), zap.Int64("untilMillis", until)) + } + return time.Now().UnixMilli() < until +} + +func testShouldDelayChangefeedScan(task scanTask, specification string) bool { + parts := strings.SplitN(specification, ":", 3) + if len(parts) != 3 || task.changefeedStat.changefeedID.Name() != parts[0] { + return false + } + slowTableID, tableErr := strconv.ParseInt(parts[1], 10, 64) + until, timeErr := strconv.ParseInt(parts[2], 10, 64) + return tableErr == nil && timeErr == nil && task.info.GetTableSpan().TableID != slowTableID && time.Now().UnixMilli() < until +} + +func testShouldDelayTableScan(task scanTask, specification string) bool { + parts := strings.SplitN(specification, ":", 2) + if len(parts) != 2 { + return false + } + tableID, tableErr := strconv.ParseInt(parts[0], 10, 64) + until, timeErr := strconv.ParseInt(parts[1], 10, 64) + return tableErr == nil && timeErr == nil && task.info.GetTableSpan().TableID == tableID && + task.loadScanProgress().txnStartTs != 0 && time.Now().UnixMilli() < until +} diff --git a/pkg/eventservice/event_broker_test.go b/pkg/eventservice/event_broker_test.go index 20a36a64c7..8b74d8b5a1 100644 --- a/pkg/eventservice/event_broker_test.go +++ b/pkg/eventservice/event_broker_test.go @@ -38,6 +38,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tikv/client-go/v2/oracle" "go.uber.org/atomic" + "golang.org/x/time/rate" ) const testTableTriggerKeyspaceID uint32 = 1 @@ -1825,3 +1826,25 @@ func TestAddDispatcherFailure(t *testing.T) { _, ok := broker.changefeedMap.Load(dispInfo.GetChangefeedID()) require.False(t, ok, "changefeedStatus should be removed after failed registration") } + +func TestZeroDispatcherQuotaDoesNotSpendScanTokens(t *testing.T) { + broker, _, _, _ := newEventBrokerForTest() + defer broker.close() + info := newMockDispatcherInfoForTest(t) + info.epoch = 1 + status := broker.getOrSetChangefeedStatus(info) + disp := newDispatcherStat(info, 1, 1, nil, status) + disp.receivedResolvedTs.Store(102) + disp.eventStoreCommitTs.Store(101) + disp.availableMemoryQuota.Store(0) + shared := atomic.NewUint64(minScanLimitInBytes * 2) + status.availableMemoryQuota.Store(node.ID(info.GetServerID()), shared) + broker.scanRateLimiter = rate.NewLimiter(0, minScanLimitInBytes*2) + before := broker.scanRateLimiter.Tokens() + cursor := disp.sentResolvedTs.Load() + disp.scanState = dispatcherScanQueued + broker.doScan(context.Background(), disp) + require.Equal(t, before, broker.scanRateLimiter.Tokens()) + require.Equal(t, uint64(minScanLimitInBytes*2), shared.Load()) + require.Equal(t, cursor, disp.sentResolvedTs.Load(), "unsent DML must not be bypassed by a resolved signal") +} diff --git a/utils/dynstream/event_queue.go b/utils/dynstream/event_queue.go index c7e3d39ce7..ad976cb8e0 100644 --- a/utils/dynstream/event_queue.go +++ b/utils/dynstream/event_queue.go @@ -76,6 +76,11 @@ func (q *eventQueue[A, P, T, D, H]) appendEvent(event eventWrap[A, P, T, D, H]) if !appended { return } + // Admission may have replaced droppable data with a recovery marker. + queued, _ := path.pendingQueue.BackRef() + if queued.eventType.Droppable && queued.eventType.Property != PeriodicSignal { + path.reclaimed.Store(false) + } addSignal() } @@ -83,6 +88,11 @@ func (q *eventQueue[A, P, T, D, H]) releasePath( path *pathInfo[A, P, T, D, H], notifyDrop bool, ) { + if !notifyDrop && !path.removed.Load() && path.areaMemStat != nil && + path.areaMemStat.settings.Load().algorithm == MemoryControlForEventCollector { + q.reclaimBlockedPath(path) + return + } for { event, ok := path.pendingQueue.PopFront() if !ok { @@ -99,6 +109,52 @@ func (q *eventQueue[A, P, T, D, H]) releasePath( } path.pendingSize.Store(0) + if path.removed.Load() && path.areaMemStat != nil { + path.areaMemStat.memControl.removeAreaIfUnused(path.areaMemStat) + } +} + +// reclaimBlockedPath runs only on the queue owner. Keep recovery notifications +// and watermarks so a later Wake can recover even without new upstream events. +func (q *eventQueue[A, P, T, D, H]) reclaimBlockedPath(path *pathInfo[A, P, T, D, H]) { + if path.removed.Load() { + q.releasePath(path, false) + return + } + if !path.blocking.Load() { + return + } + releasedBytes := int64(0) + count := path.pendingQueue.Length() + for range count { + e, _ := path.pendingQueue.PopFront() + if e.eventType.Droppable && e.eventType.Property != PeriodicSignal { + if replacement := q.handler.OnDrop(e.event); replacement != nil { + recoveryEvent := replacement.(T) + // Preserve the wrapper overhead included in the original size. + recoverySize := e.eventSize - q.handler.GetSize(e.event) + q.handler.GetSize(recoveryEvent) + if recoverySize < e.eventSize { + releasedBytes += int64(e.eventSize - recoverySize) + e.event = recoveryEvent + e.eventSize = recoverySize + e.eventType = q.handler.GetType(recoveryEvent) + } + } + } + path.pendingQueue.PushBack(e) + } + if path.removed.Load() { + q.releasePath(path, false) + return + } + path.reclaimed.Store(true) + // The queue owner also reconciles removal, so no other goroutine changes + // this path's pending memory while reclamation updates its accounting. + if releasedBytes > 0 { + path.pendingSize.Add(-releasedBytes) + path.areaMemStat.decPendingSize(path, releasedBytes) + path.areaMemStat.lastSizeDecreaseTime.Store(time.Now()) + } } func (q *eventQueue[A, P, T, D, H]) blockPath(path *pathInfo[A, P, T, D, H]) { @@ -149,8 +205,8 @@ func (q *eventQueue[A, P, T, D, H]) popEvents(b *batcher[T]) ([]T, *pathInfo[A, // The signal could contain more events than the pendingQueue, // which is possible when the path is removed or recovered from blocked. // We should ignore the signal completely. - q.signalQueue.PopFront() q.totalPendingLength.Add(-int64(signal.eventCount)) + q.signalQueue.PopFront() continue } firstGroup := firstEvent.eventType.DataGroup diff --git a/utils/dynstream/interfaces.go b/utils/dynstream/interfaces.go index 881bd87630..6bf488eb46 100644 --- a/utils/dynstream/interfaces.go +++ b/utils/dynstream/interfaces.go @@ -185,8 +185,9 @@ type DynamicStream[A Area, P Path, T Event, D Dest, H Handler[A, P, T, D]] inter // If the path doesn't exist, it will return ErrorTypeNotExist. RemovePath(path P) error - // ReleasePath releases all the events of the path. - // After this call return, events in the path will be dropped. + // Release reclaims pending payloads. EventCollector paths retain recovery + // notifications and control events; other algorithms clear the queue. + // The request is executed asynchronously by the queue owner. Release(path P) // SetAreaSettings sets the settings of the area. An area uses the default settings if it is not set. @@ -194,6 +195,9 @@ type DynamicStream[A Area, P Path, T Event, D Dest, H Handler[A, P, T, D]] inter SetAreaSettings(area A, settings AreaSettings) GetMetrics() Metrics[A, P] + + // CheckMemoryPressure checks stalled collector areas without requiring input. + CheckMemoryPressure() } const ( @@ -324,6 +328,11 @@ type Feedback[A Area, P Path, D Dest] struct { Dest D FeedbackType FeedbackType + + // Release enqueues reclamation for the original path object, even if its ID + // has since been removed and reused. It returns false if the path is gone + // or the owner queue is full; later pressure checks retry. Only ReleasePath sets it. + Release func() bool } func (f *Feedback[A, P, D]) String() string { diff --git a/utils/dynstream/memory_control.go b/utils/dynstream/memory_control.go index 79ee345eb2..d79b5bf425 100644 --- a/utils/dynstream/memory_control.go +++ b/utils/dynstream/memory_control.go @@ -139,6 +139,7 @@ func (as *areaMemStat[A, P, T, D, H]) appendEvent( if event.eventType.Droppable { dropEvent := handler.OnDrop(event.event) if dropEvent != nil { + event.eventSize += handler.GetSize(dropEvent.(T)) - handler.GetSize(event.event) event.eventType = handler.GetType(dropEvent.(T)) event.event = dropEvent.(T) appendToPendingQueue() @@ -151,6 +152,7 @@ func (as *areaMemStat[A, P, T, D, H]) appendEvent( if as.settings.Load().algorithm == MemoryControlForEventCollector { dropEvent := handler.OnDrop(event.event) if dropEvent != nil { + event.eventSize += handler.GetSize(dropEvent.(T)) - handler.GetSize(event.event) event.eventType = handler.GetType(dropEvent.(T)) event.event = dropEvent.(T) appendToPendingQueue() @@ -179,10 +181,11 @@ func (as *areaMemStat[A, P, T, D, H]) checkDeadlock() bool { } func (as *areaMemStat[A, P, T, D, H]) releaseMemory() { - if time.Since(as.lastReleaseMemoryTime.Load().(time.Time)) < 1*time.Second { + now := time.Now() + lastRequest := as.lastReleaseMemoryTime.Load().(time.Time) + if now.Sub(lastRequest) < time.Second || !as.lastReleaseMemoryTime.CompareAndSwap(lastRequest, now) { return } - as.lastReleaseMemoryTime.Store(time.Now()) paths := make([]*pathInfo[A, P, T, D, H], 0, as.pathCount.Load()) as.pathMap.Range(func(k, v interface{}) bool { @@ -199,13 +202,11 @@ func (as *areaMemStat[A, P, T, D, H]) releaseMemory() { releasedSize := int64(0) releasedPaths := make([]*pathInfo[A, P, T, D, H], 0) - log.Info("release memory", zap.Any("area", as.area), zap.Int64("sizeToRelease", sizeToRelease), zap.Int64("totalPendingSize", as.totalPendingSize.Load()), zap.Float64("releaseMemoryRatio", defaultReleaseMemoryRatio)) - for _, path := range paths { // Only release path that is blocking and has pending size larger than the threshold. if releasedSize >= sizeToRelease || path.pendingSize.Load() < int64(defaultReleaseMemoryThreshold) || - !path.blocking.Load() { + !path.blocking.Load() || path.removed.Load() || path.reclaimed.Load() { continue } @@ -213,16 +214,30 @@ func (as *areaMemStat[A, P, T, D, H]) releaseMemory() { releasedPaths = append(releasedPaths, path) } + requestedBytes := int64(0) for _, path := range releasedPaths { - log.Debug("release path", zap.Any("area", as.area), zap.Any("path", path.path), zap.Any("dest", path.dest), zap.Int64("releasedSize", path.pendingSize.Load())) - as.feedbackChan <- Feedback[A, P, D]{ + select { + case as.feedbackChan <- Feedback[A, P, D]{ Area: as.area, Path: path.path, Dest: path.dest, FeedbackType: ReleasePath, + Release: func() bool { + return !path.removed.Load() && path.stream.tryAddEvent(eventWrap[A, P, T, D, H]{release: true, pathInfo: path}) + }, + }: + requestedBytes += path.pendingSize.Load() + default: + // A full feedback queue must not block a stream or the periodic + // quota publisher. The next check retries against current state. } } - as.lastSizeDecreaseTime.Store(time.Now()) + if requestedBytes > 0 { + log.Info("request memory reclamation", + zap.Any("area", as.area), + zap.Int64("requestedBytes", requestedBytes), + zap.Int64("totalPendingSize", as.totalPendingSize.Load())) + } } func (as *areaMemStat[A, P, T, D, H]) memoryUsageRatio() float64 { @@ -343,6 +358,7 @@ func (m *memControl[A, P, T, D, H]) addPathToArea(path *pathInfo[A, P, T, D, H], // The owning stream reconciles the path's pending memory when it clears the // pending queue. Do not deduct it here, because RemovePath can race with the // stream popping an event and cause the same memory to be deducted twice. +// Keep the area until the owner has cleared the last removed path's queue. func (m *memControl[A, P, T, D, H]) removePathFromArea(path *pathInfo[A, P, T, D, H]) { area := path.areaMemStat @@ -351,11 +367,35 @@ func (m *memControl[A, P, T, D, H]) removePathFromArea(path *pathInfo[A, P, T, D area.pathMap.Delete(path.path) area.pathCount.Add(-1) - if area.pathCount.Load() == 0 { +} + +func (m *memControl[A, P, T, D, H]) removeAreaIfUnused(area *areaMemStat[A, P, T, D, H]) { + m.mutex.Lock() + defer m.mutex.Unlock() + if area.pathCount.Load() == 0 && area.totalPendingSize.Load() == 0 && m.areaStatMap[area.area] == area { delete(m.areaStatMap, area.area) } } +// checkMemoryPressure does not require recent input: paused scans and merged +// periodic signals must not prevent a stalled area from reclaiming memory. +func (m *memControl[A, P, T, D, H]) checkMemoryPressure() { + m.mutex.Lock() + areas := make([]*areaMemStat[A, P, T, D, H], 0, len(m.areaStatMap)) + for _, area := range m.areaStatMap { + areas = append(areas, area) + } + m.mutex.Unlock() + + for _, area := range areas { + if area.settings.Load().algorithm == MemoryControlForEventCollector && + area.memoryUsageRatio() > defaultReleaseMemoryRatio && + time.Since(area.lastSizeDecreaseTime.Load().(time.Time)) > defaultDeadlockDuration { + area.releaseMemory() + } + } +} + // FIXME/TODO: We use global metric here, which is not good for multiple streams. func (m *memControl[A, P, T, D, H]) getMetrics() MemoryMetric[A, P] { m.mutex.Lock() diff --git a/utils/dynstream/memory_control_test.go b/utils/dynstream/memory_control_test.go index 4d4fd97df4..4d35dd2ab5 100644 --- a/utils/dynstream/memory_control_test.go +++ b/utils/dynstream/memory_control_test.go @@ -52,8 +52,13 @@ func TestMemControlAddRemovePath(t *testing.T) { require.Equal(t, int64(1), path.areaMemStat.pathCount.Load()) // Test removing path + path.removed.Store(true) mc.removePathFromArea(path) require.Equal(t, int64(0), path.areaMemStat.pathCount.Load()) + require.Len(t, mc.areaStatMap, 1, "the owner has not cleared the path yet") + handler := &mockHandler{} + eq := newEventQueue(handler, newTestBatchConfigRegistry()) + eq.releasePath(path, true) require.Empty(t, mc.areaStatMap) } diff --git a/utils/dynstream/parallel_dynamic_stream.go b/utils/dynstream/parallel_dynamic_stream.go index 8d8b4772c0..6e3a9932b4 100644 --- a/utils/dynstream/parallel_dynamic_stream.go +++ b/utils/dynstream/parallel_dynamic_stream.go @@ -258,6 +258,12 @@ func (s *parallelDynamicStream[A, P, T, D, H]) SetAreaSettings(area A, settings } } +func (s *parallelDynamicStream[A, P, T, D, H]) CheckMemoryPressure() { + if !s.closed.Load() && s.memControl != nil { + s.memControl.checkMemoryPressure() + } +} + func (s *parallelDynamicStream[A, P, T, D, H]) GetMetrics() Metrics[A, P] { metrics := Metrics[A, P]{} for _, ds := range s.streams { diff --git a/utils/dynstream/reclamation_test.go b/utils/dynstream/reclamation_test.go new file mode 100644 index 0000000000..92be70b66d --- /dev/null +++ b/utils/dynstream/reclamation_test.go @@ -0,0 +1,325 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dynstream + +import ( + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// Use the existing handler's routing and instrumentation with sized data and +// recovery events, like EventCollector's DML -> DropEvent replacement. +type recoveryHandler struct { + mockHandler + dropHook func() +} + +func (h *recoveryHandler) GetSize(e *mockEvent) int { return e.value } +func (h *recoveryHandler) GetType(e *mockEvent) EventType { + if e.id < 0 { + return EventType{Property: NonBatchable} + } + if e.id == 0 { + return EventType{Property: PeriodicSignal, Droppable: true} + } + return EventType{Property: BatchableData, Droppable: true} +} + +func (h *recoveryHandler) OnDrop(e *mockEvent) any { + if h.dropHook != nil { + h.dropHook() + } + return &mockEvent{id: -e.id, path: e.path, value: 32} +} + +func TestReleaseRetainsRecoveryAndIdleWatermark(t *testing.T) { + h := &recoveryHandler{} + q := newEventQueue[int, string, *mockEvent, any](h, newTestBatchConfigRegistry()) + p := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "a", nil) + mc := newMemControl[int, string, *mockEvent, any, *recoveryHandler]() + mc.addPathToArea(p, AreaSettings{maxPendingSize: 1024, algorithm: MemoryControlForEventCollector}, make(chan Feedback[int, string, any], 1)) + q.initPath(p) + q.blockPath(p) + for _, e := range []*mockEvent{{id: 1, value: 900}, {id: -2, value: 32}, {id: 0, value: 32}} { + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: p, event: e, eventSize: e.value, eventType: h.GetType(e)}) + } + q.releasePath(p, false) + require.True(t, p.blocking.Load(), "reclamation must not release the active barrier") + require.Equal(t, 3, p.pendingQueue.Length(), "recovery, control and final watermark must survive") + require.Equal(t, int64(96), p.pendingSize.Load()) + require.Equal(t, int64(96), p.areaMemStat.totalPendingSize.Load()) + require.True(t, p.reclaimed.Load()) + // Repeated release must not discard recovery notifications. + q.releasePath(p, false) + require.Equal(t, int64(96), p.pendingSize.Load()) + q.wakePath(p) + b := newDefaultBatcher[*mockEvent]() + var ids []int + for { + events, _, _, _ := q.popEvents(b) + if len(events) == 0 { + break + } + for _, e := range events { + ids = append(ids, e.id) + } + } + require.Equal(t, []int{-1, -2, 0}, ids) + require.Zero(t, p.areaMemStat.totalPendingSize.Load()) + require.Zero(t, q.totalPendingLength.Load()) +} + +func TestPeriodicReclamationWithoutInput(t *testing.T) { + for _, algorithm := range []int{MemoryControlForPuller, MemoryControlForEventCollector} { + mc := newMemControl[int, string, *mockEvent, any, *mockHandler]() + p := newPathInfo[int, string, *mockEvent, any, *mockHandler](0, "test", "a", nil) + feedback := make(chan Feedback[int, string, any], 1) + mc.addPathToArea(p, AreaSettings{maxPendingSize: 1024, algorithm: algorithm}, feedback) + area := p.areaMemStat + p.pendingSize.Store(900) + area.totalPendingSize.Store(900) + p.blocking.Store(true) + old := time.Now().Add(-time.Minute) + area.lastAppendEventTime.Store(old) + area.lastSizeDecreaseTime.Store(old) + area.lastReleaseMemoryTime.Store(old) + require.False(t, area.checkDeadlock(), "the append-driven check cannot help a silent producer") + + var wg sync.WaitGroup + for range 16 { + wg.Go(mc.checkMemoryPressure) + } + wg.Wait() + if algorithm == MemoryControlForPuller { + require.Empty(t, feedback) + continue + } + require.Len(t, feedback, 1) + require.Equal(t, old, area.lastSizeDecreaseTime.Load(), "a request is not actual memory progress") + // A saturated feedback channel does not block the publisher. It retries + // once capacity returns, without pretending that reclamation succeeded. + area.lastReleaseMemoryTime.Store(old) + mc.checkMemoryPressure() + require.Len(t, feedback, 1) + <-feedback + area.lastReleaseMemoryTime.Store(old) + mc.checkMemoryPressure() + require.Len(t, feedback, 1) + } +} + +func TestLateReleaseDoesNotDiscardRunningPath(t *testing.T) { + h := &recoveryHandler{} + q := newEventQueue[int, string, *mockEvent, any](h, newTestBatchConfigRegistry()) + p := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "a", nil) + mc := newMemControl[int, string, *mockEvent, any, *recoveryHandler]() + mc.addPathToArea(p, AreaSettings{maxPendingSize: 1024, algorithm: MemoryControlForEventCollector}, make(chan Feedback[int, string, any], 1)) + q.initPath(p) + e := &mockEvent{id: 1, value: 900} + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: p, event: e, eventSize: e.value, eventType: h.GetType(e)}) + q.releasePath(p, false) + got, _, _, _ := q.popEvents(newDefaultBatcher[*mockEvent]()) + require.Equal(t, []*mockEvent{e}, got) + require.Zero(t, p.areaMemStat.totalPendingSize.Load()) +} + +func TestReclamationSkipsRetainedMarkersUntilNewData(t *testing.T) { + h := &recoveryHandler{} + q := newEventQueue[int, string, *mockEvent, any](h, newTestBatchConfigRegistry()) + p := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "a", nil) + mc := newMemControl[int, string, *mockEvent, any, *recoveryHandler]() + feedback := make(chan Feedback[int, string, any], 1) + mc.addPathToArea(p, AreaSettings{maxPendingSize: 1024, algorithm: MemoryControlForEventCollector}, feedback) + q.initPath(p) + q.blockPath(p) + marker := &mockEvent{id: -1, value: 700} + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: p, event: marker, eventSize: 700, eventType: h.GetType(marker)}) + q.releasePath(p, false) + p.areaMemStat.lastSizeDecreaseTime.Store(time.Now().Add(-time.Minute)) + mc.checkMemoryPressure() + require.Empty(t, feedback, "no repeated recovery request for retained controls") + e := &mockEvent{id: 1, value: 280} + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: p, event: e, eventSize: 280, eventType: h.GetType(e)}) + p.areaMemStat.lastReleaseMemoryTime.Store(time.Now().Add(-time.Minute)) + mc.checkMemoryPressure() + require.Len(t, feedback, 1, "new data makes the path reclaimable again") +} + +func TestPressureConvertedMarkerDoesNotRearmReclamation(t *testing.T) { + h := &recoveryHandler{} + q := newEventQueue[int, string, *mockEvent, any](h, newTestBatchConfigRegistry()) + p := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "a", nil) + mc := newMemControl[int, string, *mockEvent, any, *recoveryHandler]() + feedback := make(chan Feedback[int, string, any], 1) + mc.addPathToArea(p, AreaSettings{maxPendingSize: 1024, algorithm: MemoryControlForEventCollector}, feedback) + q.initPath(p) + q.blockPath(p) + marker := &mockEvent{id: -1, value: 32} + for range 50 { + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: p, event: marker, eventSize: marker.value, eventType: h.GetType(marker)}) + } + q.releasePath(p, false) + require.True(t, p.reclaimed.Load()) + + e := &mockEvent{id: 1, value: 280} + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: p, event: e, eventSize: e.value, eventType: h.GetType(e)}) + last, ok := p.pendingQueue.BackRef() + require.True(t, ok) + require.Equal(t, -1, last.event.id, "pressure must convert incoming data to a recovery marker") + require.True(t, p.reclaimed.Load(), "a retained marker has no payload to reclaim") + p.areaMemStat.lastSizeDecreaseTime.Store(time.Now().Add(-time.Minute)) + p.areaMemStat.lastReleaseMemoryTime.Store(time.Now().Add(-time.Minute)) + mc.checkMemoryPressure() + require.Empty(t, feedback) +} + +func TestReleaseFeedbackKeepsOriginalPathIdentity(t *testing.T) { + h := &recoveryHandler{} + ds := newParallelDynamicStream("reclamation-identity", h, Option{StreamCount: 1, EnableMemoryControl: true}) + ds.Start() + defer ds.Close() + settings := NewAreaSettingsWithMaxPendingSize(1024, MemoryControlForEventCollector, "test") + require.NoError(t, ds.AddPath("a", "old", settings)) + old, ok := ds.pathMap.m["a"] + require.True(t, ok) + old.blocking.Store(true) + old.pendingSize.Store(900) + old.areaMemStat.totalPendingSize.Store(900) + old.areaMemStat.lastSizeDecreaseTime.Store(time.Now().Add(-time.Minute)) + old.areaMemStat.lastReleaseMemoryTime.Store(time.Now().Add(-time.Minute)) + ds.CheckMemoryPressure() + feedback := <-ds.Feedback() + require.NotNil(t, feedback.Release) + require.NoError(t, ds.RemovePath("a")) + require.NoError(t, ds.AddPath("a", "new", settings)) + current, ok := ds.pathMap.m["a"] + require.True(t, ok) + require.NotSame(t, old, current) + feedback.Release() + require.False(t, current.reclaimed.Load(), "stale feedback cannot target the replacement path") + ds.Close() + done := make(chan struct{}) + go func() { defer close(done); feedback.Release(); ds.CheckMemoryPressure() }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("late reclamation blocked after close") + } +} + +func TestRemoveDuringReclamationPreservesOtherPathAccounting(t *testing.T) { + h := &recoveryHandler{} + q := newEventQueue[int, string, *mockEvent, any](h, newTestBatchConfigRegistry()) + mc := newMemControl[int, string, *mockEvent, any, *recoveryHandler]() + a := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "a", nil) + b := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "b", nil) + for _, p := range []*pathInfo[int, string, *mockEvent, any, *recoveryHandler]{a, b} { + mc.addPathToArea(p, AreaSettings{maxPendingSize: 4096, algorithm: MemoryControlForEventCollector}, make(chan Feedback[int, string, any], 1)) + q.initPath(p) + q.blockPath(p) + e := &mockEvent{id: 1, value: 900} + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: p, event: e, eventSize: 900, eventType: h.GetType(e)}) + } + h.dropHook = func() { + done := make(chan struct{}) + go func() { a.removed.Store(true); mc.removePathFromArea(a); close(done) }() + <-done + } + q.releasePath(a, false) + require.Zero(t, a.pendingSize.Load()) + require.Zero(t, a.pendingQueue.Length()) + require.Equal(t, int64(900), b.pendingSize.Load()) + require.Equal(t, int64(900), b.areaMemStat.totalPendingSize.Load()) +} + +func TestLastRemovedPathKeepsAreaAccountingUntilDrained(t *testing.T) { + h := &recoveryHandler{} + q := newEventQueue[int, string, *mockEvent, any](h, newTestBatchConfigRegistry()) + mc := newMemControl[int, string, *mockEvent, any, *recoveryHandler]() + feedback := make(chan Feedback[int, string, any], 1) + settings := AreaSettings{maxPendingSize: 1024, algorithm: MemoryControlForEventCollector} + old := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "old", nil) + mc.addPathToArea(old, settings, feedback) + q.initPath(old) + e := &mockEvent{id: 1, value: 900} + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: old, event: e, eventSize: e.value, eventType: h.GetType(e)}) + old.removed.Store(true) + mc.removePathFromArea(old) + + current := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "current", nil) + mc.addPathToArea(current, settings, feedback) + require.Same(t, old.areaMemStat, current.areaMemStat) + require.Equal(t, int64(900), mc.getMetrics().AreaMemoryMetrics[0].MemoryUsage()) + + current.removed.Store(true) + mc.removePathFromArea(current) + require.Contains(t, mc.areaStatMap, 0, "pending bytes still belong to the area") + q.releasePath(old, true) + require.NotContains(t, mc.areaStatMap, 0, "draining the last queue releases the area") +} + +func TestPressureDropChargesRecoveryMarkerSize(t *testing.T) { + h := &recoveryHandler{} + q := newEventQueue[int, string, *mockEvent, any](h, newTestBatchConfigRegistry()) + mc := newMemControl[int, string, *mockEvent, any, *recoveryHandler]() + p := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "a", nil) + mc.addPathToArea(p, AreaSettings{maxPendingSize: 1024, algorithm: MemoryControlForEventCollector}, make(chan Feedback[int, string, any], 1)) + q.initPath(p) + q.blockPath(p) + for i := 1; i <= 3; i++ { + e := &mockEvent{id: i, value: 900} + q.appendEvent(eventWrap[int, string, *mockEvent, any, *recoveryHandler]{pathInfo: p, event: e, eventSize: 900, eventType: h.GetType(e)}) + } + require.Equal(t, int64(1832), p.pendingSize.Load(), "pressure drop must charge the retained marker, not the discarded payload") + q.releasePath(p, false) + require.Equal(t, int64(96), p.areaMemStat.totalPendingSize.Load()) +} + +func TestReleaseRequestDoesNotWaitForOwnerQueue(t *testing.T) { + for _, buffered := range []bool{false, true} { + h := &recoveryHandler{} + s := newStream(0, "test", h, Option{InputChanSize: 1, UseBuffer: buffered}, newTestBatchConfigRegistry()) + p := newPathInfo[int, string, *mockEvent, any, *recoveryHandler](0, "test", "a", nil) + mc := newMemControl[int, string, *mockEvent, any, *recoveryHandler]() + feedback := make(chan Feedback[int, string, any], 1) + mc.addPathToArea(p, AreaSettings{maxPendingSize: 1024, algorithm: MemoryControlForEventCollector}, feedback) + p.stream = s + p.blocking.Store(true) + p.pendingSize.Store(900) + p.areaMemStat.totalPendingSize.Store(900) + p.areaMemStat.lastReleaseMemoryTime.Store(time.Now().Add(-time.Minute)) + p.areaMemStat.releaseMemory() + request := <-feedback + capacity := cap(s.eventChan) + if buffered { + capacity = cap(s.inChan) + } + for i := 0; i < capacity; i++ { + require.True(t, request.Release()) + } + require.False(t, request.Release(), "full owner queue must not block feedback or shutdown") + if buffered { + <-s.inChan + } else { + <-s.eventChan + } + require.True(t, request.Release(), "a later retry can enter the owner queue") + s.close() + require.False(t, request.Release()) + } +} diff --git a/utils/dynstream/stream.go b/utils/dynstream/stream.go index bf8ca6deed..b37f02ad8a 100644 --- a/utils/dynstream/stream.go +++ b/utils/dynstream/stream.go @@ -163,6 +163,24 @@ func (s *stream[A, P, T, D, H]) addEvent(event eventWrap[A, P, T, D, H]) { } } +// tryAddEvent is used for retryable reclamation requests. A saturated owner +// queue must not prevent the feedback consumer from observing cancellation. +func (s *stream[A, P, T, D, H]) tryAddEvent(event eventWrap[A, P, T, D, H]) bool { + if s.closed.Load() { + return false + } + eventChan := s.eventChan + if s.option.UseBuffer { + eventChan = s.inChan + } + select { + case eventChan <- event: + return true + default: + return false + } +} + // Start the stream. func (s *stream[A, P, T, D, H]) start() { if s.closed.Load() { @@ -403,6 +421,10 @@ type pathInfo[A Area, P Path, T Event, D Dest, H Handler[A, P, T, D]] struct { pendingSize atomic.Int64 // The total size(bytes) of pending events in the pendingQueue of the path. + // Reclamation has visited the pending queue since the last data append. + // Skip repeated requests for a queue containing only retained markers. + reclaimed atomic.Bool + lastHandleEventTs atomic.Uint64 }