This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 8a9266e3726 Stop the ingestion delay tracker cleanly so a table delete 
always stops its consumers (#20214)
8a9266e3726 is described below

commit 8a9266e3726e3034757b72cf55c66621eb35152d
Author: RAGHVENDRA KUMAR YADAV <[email protected]>
AuthorDate: Tue Nov 24 16:05:50 2026 -0800

    Stop the ingestion delay tracker cleanly so a table delete always stops its 
consumers (#20214)
    
    * Stop the ingestion delay tracker cleanly so a table delete always stops 
its consumers
    
    On REALTIME table delete, IngestionDelayTracker.shutdown() stopped its 
polling executor without waiting and
    then closed the stream metadata providers. An in-flight upstream offset 
fetch on a Kafka consumer made the
    close throw ConcurrentModificationException, which the IOException catch 
did not cover. The exception left
    RealtimeTableDataManager.doShutdown() before releaseAndRemoveAllSegments(), 
so the table's consuming segment
    managers were never stopped and kept consuming after the table was gone.
    
    The tracker now interrupts and waits (bounded) for its polling task before 
closing providers, and logs any
    close failure instead of throwing. doShutdown() also guards the tracker 
shutdown so segments are always
    released.
    
    * Do not report the fetch that shutdown interrupts as an offset fetch error
    
    Shutting the tracker down interrupts its in-flight upstream offset fetch. 
That surfaced as an ERROR with a stack
    trace and an INGESTION_DELAY_LATEST_OFFSET_FETCH_ERRORS increment on every 
routine table delete, which could trip
    alerts on the meter. A fetch that fails while the tracker is shutting down 
is now logged at debug only. The test
    also verifies the provider is closed and the error meter is not touched.
    
    * Close a stream metadata provider created after the tracker shut down
    
    If the tracking task is still creating a provider when shutdown() stops
    waiting for it, the provider was put into the map after the close loop and
    never closed. Both sides now remove an entry before closing it, so whichever
    removes it closes it exactly once.
    
    * Clean up the ingestion delay tracker on its own thread so shutdown leaves 
no gauges or open providers
    
    Closing the stream metadata providers before removing the partitions' 
metrics made the removal skip the
    offset lag, upstream offset and consuming offset gauges, because it asks 
the partition's provider which gauges
    it registered. Closing them right after a timed-out or interrupted wait 
could also close a provider under a
    fetch still running on it, and left nothing to close it afterwards.
    
    Shutdown now cancels the tracking task with an interrupt and runs the 
metric removal and the provider close as
    one task on the tracking thread, behind any fetch in flight. The table data 
manager releases its segments with
    the caller's interrupt cleared and restores it afterwards, so a tracker 
wait that was interrupted no longer
    makes the segment release give up and drop queued consumer offloads.
    
    * Remove every tracked partition's gauges on tracker shutdown and keep a 
repeated shutdown off the caller's thread
    
    Shutdown removed the gauges only of partitions with ingestion info. The 
tracking task also registers gauges for a
    hosted partition whose consumer has not reported anything, such as one 
whose consuming segment is in ERROR, so those
    gauges outlived the table and the offset lag gauge kept reporting the whole 
upstream offset. The cleanup now also
    goes by the partitions that have metrics.
    
    A repeated shutdown() ran the cleanup on the calling thread, which could 
close a provider under the fetch the first
    call was still waiting out. The first call has already queued the cleanup, 
so a repeated call now only waits for it.
    
    Tests: the provider close failure test uses two failing providers and 
checks that both are closed, since a failed
    close no longer reaches the caller. A new test checks that the table still 
releases its segments when the tracker
    fails to shut down.
    
    ---------
    
    Co-authored-by: Xiang Fu <[email protected]>
---
 .../manager/realtime/IngestionDelayTracker.java    | 101 +++++++++--
 .../manager/realtime/RealtimeTableDataManager.java |  24 ++-
 .../realtime/IngestionDelayTrackerTest.java        | 189 +++++++++++++++++++++
 .../realtime/RealtimeTableDataManagerTest.java     |  54 ++++++
 4 files changed, 348 insertions(+), 20 deletions(-)

diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/IngestionDelayTracker.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/IngestionDelayTracker.java
index 896d60d7b21..414d4f177fb 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/IngestionDelayTracker.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/IngestionDelayTracker.java
@@ -21,7 +21,6 @@ package org.apache.pinot.core.data.manager.realtime;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.cache.Cache;
 import com.google.common.cache.CacheBuilder;
-import java.io.IOException;
 import java.time.Clock;
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -30,7 +29,9 @@ import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.Executors;
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
 import java.util.function.BooleanSupplier;
@@ -120,6 +121,8 @@ public class IngestionDelayTracker {
   private static final long PARTITION_TIMEOUT_MS = 
TimeUnit.MINUTES.toMillis(10);
   // Delay scheduled executor service for this amount of time after starting 
service
   private static final int INITIAL_SCHEDULED_EXECUTOR_THREAD_DELAY_MS = 100;
+  // Bounds how long table shutdown waits for an in-flight upstream offset 
fetch to stop
+  private static final long TRACKING_SHUTDOWN_TIMEOUT_MS = 
TimeUnit.SECONDS.toMillis(10);
   // Cache expire time for ignored segment if there is no update from the 
segment.
   private static final int IGNORED_SEGMENT_CACHE_TIME_MINUTES = 10;
   // Timeout after 5 seconds while fetching the latest stream offset.
@@ -146,8 +149,11 @@ public class IngestionDelayTracker {
   private final Map<Integer, Long> _partitionsMarkedForVerification = new 
ConcurrentHashMap<>();
   private final ScheduledExecutorService _metricsRemovalScheduler;
   private final ScheduledExecutorService _ingestionDelayTrackingScheduler;
+  private final ScheduledFuture<?> _ingestionDelayTrackingFuture;
 
   private Clock _clock = Clock.systemUTC();
+  // Set when the table is shutting down, so the fetch that shutdown 
interrupts is not reported as an error
+  private volatile boolean _shuttingDown;
 
   protected volatile Map<Integer, StreamPartitionMsgOffset> 
_partitionIdToLatestOffset;
   protected volatile ConcurrentHashMap<Integer, Boolean> 
_partitionsHostedByThisServer = new ConcurrentHashMap<>();
@@ -186,7 +192,7 @@ public class IngestionDelayTracker {
     _ingestionDelayTrackingScheduler = 
Executors.newSingleThreadScheduledExecutor(
         getThreadFactory("IngestionDelayTrackingThread-" + 
TableNameBuilder.extractRawTableName(tableNameWithType)));
     // schedule periodically to update latest upstream offset or create 
metrics for newly added partitions.
-    
_ingestionDelayTrackingScheduler.scheduleWithFixedDelay(this::trackIngestionDelay,
+    _ingestionDelayTrackingFuture = 
_ingestionDelayTrackingScheduler.scheduleWithFixedDelay(this::trackIngestionDelay,
         INITIAL_SCHEDULED_EXECUTOR_THREAD_DELAY_MS, metricsTrackingIntervalMs, 
TimeUnit.MILLISECONDS);
   }
 
@@ -213,6 +219,15 @@ public class IngestionDelayTracker {
 
       assert streamMetadataProvider != null;
       _streamConfigIndexToStreamMetadataProvider.put(streamConfigIndex, 
streamMetadataProvider);
+      // A create still running when shutdown() started has no use for the 
provider, so close it here rather than
+      // leave it to the queued cleanup. Whichever side removes the entry 
closes the provider, so it is closed exactly
+      // once.
+      if (_shuttingDown) {
+        if 
(_streamConfigIndexToStreamMetadataProvider.remove(streamConfigIndex, 
streamMetadataProvider)) {
+          closeStreamMetadataProvider(streamMetadataProvider);
+        }
+        return;
+      }
 
       if ((streamMetadataProvider.supportsOffsetLag()) && 
(_partitionIdToLatestOffset == null)) {
         _partitionIdToLatestOffset = new ConcurrentHashMap<>();
@@ -300,6 +315,11 @@ public class IngestionDelayTracker {
             _partitionIdToLatestOffset.putAll(streamPartitionIdToLatestOffset);
           }
         } catch (Exception e) {
+          if (_shuttingDown) {
+            // Shutdown interrupts the in-flight fetch on purpose; a routine 
table delete is not a fetch error
+            LOGGER.debug("Stopped fetching latest stream offsets for 
partitions: {} on shutdown", streamPartitionIds);
+            return;
+          }
           
_serverMetrics.addMeteredTableValue(_realTimeTableDataManager.getTableName(),
               ServerMeter.INGESTION_DELAY_LATEST_OFFSET_FETCH_ERRORS, 1);
           LOGGER.error("Failed to update latest stream offsets for partitions: 
{}", streamPartitionIds, e);
@@ -642,28 +662,73 @@ public class IngestionDelayTracker {
     return ((LongMsgOffset) latestOffset).getOffset();
   }
 
-  /// We use this method to clean up when a table is being removed. No updates 
are expected at this time as all
-  /// RealtimeSegmentManagers should be down now.
+  private static void closeStreamMetadataProvider(StreamMetadataProvider 
streamMetadataProvider) {
+    try {
+      streamMetadataProvider.close();
+    } catch (Exception e) {
+      LOGGER.error("Failed to close streamMetadataProvider", e);
+    }
+  }
+
+  /// We use this method to clean up when a table is being removed. It does 
not throw, so the caller can go on to stop
+  /// the table's consumers.
+  ///
+  /// The tracking task may be inside a fetch on a stream metadata provider, 
and a stream consumer such as Kafka's is
+  /// not safe for concurrent use, so a provider is closed only after that 
fetch returns. The cleanup that needs the
+  /// providers therefore runs on the tracking thread, behind the fetch: 
removing the partitions' metrics asks each
+  /// provider which gauges it registered, and then the providers are closed. 
This waits a bounded time for it; if the
+  /// wait runs out or the caller is interrupted, the cleanup still completes 
on that thread once the fetch returns.
+  /// The interrupt is left set on the calling thread. A repeated call only 
waits again for that cleanup.
   public void shutdown() {
+    _shuttingDown = true;
     // Now that segments can't report metric, destroy metric for this table
     _metricsRemovalScheduler.shutdown(); // ScheduledExecutor is installed in 
constructor so must always be cancelled
-    if (_ingestionDelayTrackingScheduler != null) {
-      _ingestionDelayTrackingScheduler.shutdown();
+    if (_ingestionDelayTrackingScheduler == null) {
+      cleanUpAfterTracking();
+      return;
     }
-    for (StreamMetadataProvider streamMetadataProvider : 
_streamConfigIndexToStreamMetadataProvider.values()) {
-      try {
-        streamMetadataProvider.close();
-      } catch (IOException e) {
-        LOGGER.error("Failed to close streamMetadataProvider", e);
-      }
+    // Interrupt a fetch in flight and stop scheduling new ones, but keep the 
executor open for the cleanup below
+    _ingestionDelayTrackingFuture.cancel(true);
+    try {
+      _ingestionDelayTrackingScheduler.execute(this::cleanUpAfterTracking);
+    } catch (RejectedExecutionException e) {
+      // Only an earlier call can have shut the executor down, and that call 
queued the cleanup first. Running it on
+      // this thread instead could close a provider under the fetch that call 
is still waiting out.
+      LOGGER.debug("Ingestion delay tracker for table: {} is already shutting 
down", _tableNameWithType);
     }
-    if (!_isServerReadyToServeQueries.getAsBoolean()) {
-      // Do not update the tracker state during server startup period
-      return;
+    _ingestionDelayTrackingScheduler.shutdown();
+    try {
+      if 
(!_ingestionDelayTrackingScheduler.awaitTermination(TRACKING_SHUTDOWN_TIMEOUT_MS,
 TimeUnit.MILLISECONDS)) {
+        LOGGER.warn("Ingestion delay tracking task for table: {} did not stop 
within {}ms; its cleanup completes once "
+            + "it does", _tableNameWithType, TRACKING_SHUTDOWN_TIMEOUT_MS);
+      }
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
     }
-    // Remove partitions so their related metrics get uninstalled.
-    for (Integer partitionId : _ingestionInfoMap.keySet()) {
-      removePartitionId(partitionId);
+  }
+
+  /// Removes the metrics of all tracked partitions, then closes the stream 
metadata providers. Metrics go first
+  /// because removing them looks the partition's provider up; the providers 
are closed even when that fails.
+  private void cleanUpAfterTracking() {
+    try {
+      if (_isServerReadyToServeQueries.getAsBoolean()) {
+        // Remove partitions so their related metrics get uninstalled. Not 
during server startup, when the tracker
+        // state is not updated. The tracking task also registers metrics for 
a hosted partition whose consumer has
+        // not reported anything, so go by the partitions with metrics as well 
as those with ingestion info.
+        Set<Integer> partitionIds = new HashSet<>(_partitionsTracked.keySet());
+        partitionIds.addAll(_ingestionInfoMap.keySet());
+        for (Integer partitionId : partitionIds) {
+          removePartitionId(partitionId);
+        }
+      }
+    } catch (RuntimeException e) {
+      LOGGER.error("Failed to remove the ingestion metrics of table: {}", 
_tableNameWithType, e);
+    } finally {
+      for (Map.Entry<Integer, StreamMetadataProvider> entry : 
_streamConfigIndexToStreamMetadataProvider.entrySet()) {
+        if (_streamConfigIndexToStreamMetadataProvider.remove(entry.getKey(), 
entry.getValue())) {
+          closeStreamMetadataProvider(entry.getValue());
+        }
+      }
     }
   }
 }
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManager.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManager.java
index 7ce04858abb..632e131dc9a 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManager.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManager.java
@@ -341,8 +341,28 @@ public class RealtimeTableDataManager extends 
BaseTableDataManager {
   @Override
   protected void doShutdown() {
     // Make sure we do metric cleanup when we shut down the table.
-    // Do this first, so we do not show ingestion lag during shutdown.
-    _ingestionDelayTracker.shutdown();
+    // Do this first, so we do not show ingestion lag during shutdown. A 
failure here must not skip releasing the
+    // segments below, which is what stops the table's consumers.
+    try {
+      _ingestionDelayTracker.shutdown();
+    } catch (Exception e) {
+      _logger.error("Caught exception while shutting down the ingestion delay 
tracker", e);
+    }
+    // The tracker leaves the caller's interrupt set when its bounded wait is 
interrupted. Releasing the segments waits
+    // on an executor, and that wait gives up at once under an interrupt and 
drops the queued offloads, which would
+    // leave consuming segments running after the table is gone. So run the 
cleanup with the interrupt cleared and
+    // restore it afterwards.
+    boolean interrupted = Thread.interrupted();
+    try {
+      releaseSegmentsAndStopLeaseExtender();
+    } finally {
+      if (interrupted) {
+        Thread.currentThread().interrupt();
+      }
+    }
+  }
+
+  private void releaseSegmentsAndStopLeaseExtender() {
     if (_tableUpsertMetadataManager != null || _tableDedupMetadataManager != 
null) {
       // Stop the upsert metadata manager first to prevent removing metadata 
when destroying segments
       if (_tableUpsertMetadataManager != null) {
diff --git 
a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/IngestionDelayTrackerTest.java
 
b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/IngestionDelayTrackerTest.java
index 543a6c5b8ba..24027981e2b 100644
--- 
a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/IngestionDelayTrackerTest.java
+++ 
b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/IngestionDelayTrackerTest.java
@@ -29,12 +29,15 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.BooleanSupplier;
 import org.apache.commons.lang3.tuple.Pair;
 import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
 import org.apache.pinot.common.metrics.ServerMetrics;
 import org.apache.pinot.common.utils.LLCSegmentName;
 import org.apache.pinot.spi.config.table.TableConfig;
@@ -42,6 +45,7 @@ import org.apache.pinot.spi.config.table.TableType;
 import org.apache.pinot.spi.config.table.ingestion.IngestionConfig;
 import org.apache.pinot.spi.config.table.ingestion.StreamIngestionConfig;
 import org.apache.pinot.spi.stream.LongMsgOffset;
+import org.apache.pinot.spi.stream.StreamMetadataProvider;
 import org.apache.pinot.spi.stream.StreamPartitionMsgOffset;
 import org.apache.pinot.spi.utils.IngestionConfigUtils;
 import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
@@ -49,9 +53,19 @@ import org.apache.pinot.spi.utils.builder.TableNameBuilder;
 import org.apache.pinot.util.TestUtils;
 import org.testng.annotations.Test;
 
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anySet;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNull;
 import static org.testng.Assert.assertTrue;
 import static org.testng.Assert.fail;
@@ -157,6 +171,181 @@ public class IngestionDelayTrackerTest {
     return new MockIngestionDelayTracker(_serverMetrics, REALTIME_TABLE_NAME, 
REALTIME_TABLE_DATA_MANAGER);
   }
 
+  /// Shutdown must stop an in-flight upstream offset fetch before closing the 
provider it runs on: a stream consumer
+  /// such as Kafka's throws ConcurrentModificationException when closed under 
a concurrent fetch.
+  @Test
+  public void testShutdownClosesProviderOnlyAfterInFlightFetchStops()
+      throws Exception {
+    ServerMetrics serverMetrics = mock(ServerMetrics.class);
+    IngestionDelayTracker tracker = new IngestionDelayTracker(serverMetrics, 
REALTIME_TABLE_NAME,
+        REALTIME_TABLE_DATA_MANAGER, 60_000, 5, () -> true);
+    AtomicBoolean inFetch = new AtomicBoolean();
+    AtomicBoolean closedDuringFetch = new AtomicBoolean();
+    CountDownLatch fetchStarted = new CountDownLatch(1);
+    CountDownLatch neverReleased = new CountDownLatch(1);
+    StreamMetadataProvider provider = mock(StreamMetadataProvider.class);
+    when(provider.supportsOffsetLag()).thenReturn(true);
+    when(provider.fetchLatestStreamOffset(anySet(), 
anyLong())).thenAnswer(invocation -> {
+      inFetch.set(true);
+      fetchStarted.countDown();
+      try {
+        // Blocks until the tracking task is interrupted, like a consumer 
waiting on the broker
+        neverReleased.await();
+      } finally {
+        inFetch.set(false);
+      }
+      return Map.of();
+    });
+    doAnswer(invocation -> {
+      closedDuringFetch.set(inFetch.get());
+      return null;
+    }).when(provider).close();
+    tracker._streamConfigIndexToStreamMetadataProvider.put(0, provider);
+    tracker._partitionsHostedByThisServer.put(0, true);
+
+    assertTrue(fetchStarted.await(10, TimeUnit.SECONDS), "The tracking task 
should start a fetch");
+    tracker.shutdown();
+    verify(provider).close();
+    assertFalse(closedDuringFetch.get(), "The provider was closed while a 
fetch was still running on it");
+    // The fetch that shutdown interrupts is not counted as a fetch error, 
which would trip alerts on table deletes
+    verify(serverMetrics, never()).addMeteredTableValue(any(),
+        eq(ServerMeter.INGESTION_DELAY_LATEST_OFFSET_FETCH_ERRORS), anyLong());
+  }
+
+  /// Removing a partition's metrics asks its provider whether it registered 
the offset gauges, so the provider must
+  /// still be known then: closing it first leaves the offset lag, upstream 
offset and consuming offset gauges behind.
+  @Test
+  public void testShutdownRemovesOffsetGaugesOfTrackedPartitions()
+      throws Exception {
+    ServerMetrics serverMetrics = mock(ServerMetrics.class);
+    IngestionDelayTracker tracker = new IngestionDelayTracker(serverMetrics, 
REALTIME_TABLE_NAME,
+        REALTIME_TABLE_DATA_MANAGER, 60_000, 5, () -> true);
+    StreamMetadataProvider provider = mock(StreamMetadataProvider.class);
+    when(provider.supportsOffsetLag()).thenReturn(true);
+    when(provider.fetchLatestStreamOffset(anySet(), 
anyLong())).thenReturn(Map.of());
+    tracker._streamConfigIndexToStreamMetadataProvider.put(0, provider);
+    tracker._partitionsHostedByThisServer.put(0, true);
+    // A consuming segment reports its progress, which puts the partition in 
the tracker's ingestion info
+    String segment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, 
123).getSegmentName();
+    tracker.updateMetrics(segment, 0, Long.MIN_VALUE, Long.MIN_VALUE, new 
LongMsgOffset(50));
+    // The tracking task registers the gauges of a hosted partition on its 
first tick
+    verify(serverMetrics, timeout(10_000)).setOrUpdatePartitionGauge(any(), 
eq(0),
+        eq(ServerGauge.REALTIME_INGESTION_OFFSET_LAG), any());
+
+    tracker.shutdown();
+
+    verify(serverMetrics).removePartitionGauge(any(), eq(0), 
eq(ServerGauge.REALTIME_INGESTION_OFFSET_LAG));
+    verify(serverMetrics).removePartitionGauge(any(), eq(0), 
eq(ServerGauge.REALTIME_INGESTION_UPSTREAM_OFFSET));
+    verify(serverMetrics).removePartitionGauge(any(), eq(0), 
eq(ServerGauge.REALTIME_INGESTION_CONSUMING_OFFSET));
+    verify(serverMetrics).removePartitionGauge(any(), eq(0), 
eq(ServerGauge.REALTIME_INGESTION_DELAY_MS));
+    verify(provider).close();
+  }
+
+  /// When the caller is interrupted, or the wait for the tracking task runs 
out, the task can still be inside a fetch.
+  /// The provider is then closed once that fetch returns, not under it, and 
not left open for good.
+  @Test
+  public void testInterruptedShutdownClosesProviderAfterTheFetchReturns()
+      throws Exception {
+    ServerMetrics serverMetrics = mock(ServerMetrics.class);
+    IngestionDelayTracker tracker = new IngestionDelayTracker(serverMetrics, 
REALTIME_TABLE_NAME,
+        REALTIME_TABLE_DATA_MANAGER, 60_000, 5, () -> true);
+    AtomicBoolean inFetch = new AtomicBoolean();
+    AtomicBoolean closedDuringFetch = new AtomicBoolean();
+    CountDownLatch fetchStarted = new CountDownLatch(1);
+    CountDownLatch releaseFetch = new CountDownLatch(1);
+    StreamMetadataProvider provider = mock(StreamMetadataProvider.class);
+    when(provider.supportsOffsetLag()).thenReturn(true);
+    when(provider.fetchLatestStreamOffset(anySet(), 
anyLong())).thenAnswer(invocation -> {
+      inFetch.set(true);
+      fetchStarted.countDown();
+      try {
+        // A fetch stuck in a blocking call: it ignores the interrupt and 
returns only when released
+        while (true) {
+          try {
+            releaseFetch.await();
+            break;
+          } catch (InterruptedException e) {
+            // keep waiting
+          }
+        }
+      } finally {
+        inFetch.set(false);
+      }
+      return Map.of();
+    });
+    doAnswer(invocation -> {
+      closedDuringFetch.set(inFetch.get());
+      return null;
+    }).when(provider).close();
+    tracker._streamConfigIndexToStreamMetadataProvider.put(0, provider);
+    tracker._partitionsHostedByThisServer.put(0, true);
+    assertTrue(fetchStarted.await(10, TimeUnit.SECONDS), "The tracking task 
should start a fetch");
+
+    // The caller is interrupted, so its bounded wait for the tracking task 
ends at once
+    Thread.currentThread().interrupt();
+    try {
+      tracker.shutdown();
+      assertTrue(Thread.currentThread().isInterrupted(), "Shutdown must keep 
the caller's interrupt");
+      // A repeated call finds the cleanup already queued behind the fetch, 
and must not run it on this thread
+      tracker.shutdown();
+    } finally {
+      Thread.interrupted();
+    }
+    verify(provider, never()).close();
+
+    releaseFetch.countDown();
+    verify(provider, timeout(10_000)).close();
+    assertFalse(closedDuringFetch.get(), "The provider was closed while a 
fetch was still running on it");
+  }
+
+  /// The tracking task also registers gauges for a partition the server hosts 
whose consumer has not reported
+  /// anything, for example one whose consuming segment is in ERROR. Shutdown 
removes those too: nothing else does once
+  /// the table is gone, and the offset lag gauge would go on reporting the 
whole upstream offset as lag.
+  @Test
+  public void testShutdownRemovesGaugesOfPartitionsWithoutIngestionInfo()
+      throws Exception {
+    ServerMetrics serverMetrics = mock(ServerMetrics.class);
+    IngestionDelayTracker tracker = new IngestionDelayTracker(serverMetrics, 
REALTIME_TABLE_NAME,
+        REALTIME_TABLE_DATA_MANAGER, 60_000, 5, () -> true);
+    StreamMetadataProvider provider = mock(StreamMetadataProvider.class);
+    when(provider.supportsOffsetLag()).thenReturn(true);
+    when(provider.fetchLatestStreamOffset(anySet(), 
anyLong())).thenReturn(Map.of());
+    tracker._streamConfigIndexToStreamMetadataProvider.put(0, provider);
+    tracker._partitionsHostedByThisServer.put(0, true);
+    // The tracking task registers this gauge last
+    verify(serverMetrics, timeout(10_000)).setOrUpdatePartitionGauge(any(), 
eq(0),
+        eq(ServerGauge.REALTIME_INGESTION_DELAY_REPORTING_STATUS), any());
+
+    tracker.shutdown();
+
+    for (ServerGauge gauge : List.of(ServerGauge.REALTIME_INGESTION_OFFSET_LAG,
+        ServerGauge.REALTIME_INGESTION_UPSTREAM_OFFSET, 
ServerGauge.REALTIME_INGESTION_CONSUMING_OFFSET,
+        ServerGauge.REALTIME_INGESTION_DELAY_MS, 
ServerGauge.END_TO_END_REALTIME_INGESTION_DELAY_MS,
+        ServerGauge.REALTIME_INGESTION_DELAY_REPORTING_STATUS)) {
+      verify(serverMetrics).removePartitionGauge(any(), eq(0), eq(gauge));
+    }
+    verify(provider).close();
+  }
+
+  /// A provider that fails to close with a runtime exception must not make 
shutdown throw, which would skip stopping
+  /// the table's consumers in the caller, and must not keep the table's other 
providers from being closed.
+  @Test
+  public void testShutdownSurvivesProviderCloseFailure()
+      throws Exception {
+    IngestionDelayTracker tracker = createTracker();
+    StreamMetadataProvider provider = mock(StreamMetadataProvider.class);
+    StreamMetadataProvider otherProvider = mock(StreamMetadataProvider.class);
+    doThrow(new IllegalStateException("KafkaConsumer is not safe for 
multi-threaded access")).when(provider).close();
+    doThrow(new IllegalStateException("KafkaConsumer is not safe for 
multi-threaded access")).when(otherProvider)
+        .close();
+    tracker._streamConfigIndexToStreamMetadataProvider.put(0, provider);
+    tracker._streamConfigIndexToStreamMetadataProvider.put(1, otherProvider);
+    tracker.shutdown();
+    // Whichever provider is closed first fails, and the other one is still 
closed
+    verify(provider).close();
+    verify(otherProvider).close();
+  }
+
   @Test
   public void testTrackerConstructors() {
     // Test regular constructor
diff --git 
a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManagerTest.java
 
b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManagerTest.java
index 34d5378fbf9..e979cdc378f 100644
--- 
a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManagerTest.java
+++ 
b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManagerTest.java
@@ -82,6 +82,7 @@ import static org.mockito.Mockito.clearInvocations;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doCallRealMethod;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
@@ -456,6 +457,50 @@ public class RealtimeTableDataManagerTest {
     }
   }
 
+  // The tracker interrupts the caller when its bounded wait is interrupted. 
Releasing the segments is what stops the
+  // table's consumers, and its own wait would give up at once under that 
interrupt and drop the queued offloads.
+  @Test
+  public void testShutdownReleasesSegmentsBeforeRestoringTheCallersInterrupt()
+      throws Exception {
+    ServerMetrics.register(mock(ServerMetrics.class));
+    File indexDir = Files.createTempDirectory("shutdown-interrupt").toFile();
+    LifecycleTableDataManager table =
+        new LifecycleTableDataManager(indexDir, 
mock(RealtimeSegmentDataManager.class), false, () -> { });
+    IngestionDelayTracker tracker = (IngestionDelayTracker) 
FieldUtils.readField(table, "_ingestionDelayTracker", true);
+    doAnswer(invocation -> {
+      Thread.currentThread().interrupt();
+      return null;
+    }).when(tracker).shutdown();
+    try {
+      table.shutDown();
+      assertTrue(table._releasedSegments, "The segments were not released");
+      assertFalse(table._interruptedWhileReleasingSegments,
+          "The segments were released with the caller interrupted, so queued 
offloads could be dropped");
+      assertTrue(Thread.currentThread().isInterrupted(), "The caller's 
interrupt must be restored after cleanup");
+    } finally {
+      Thread.interrupted();
+      FileUtils.deleteDirectory(indexDir);
+    }
+  }
+
+  // Releasing the segments is what stops the table's consumers, so a tracker 
that fails to shut down must not skip it.
+  @Test
+  public void testShutdownReleasesSegmentsWhenTheTrackerFailsToShutDown()
+      throws Exception {
+    ServerMetrics.register(mock(ServerMetrics.class));
+    File indexDir = 
Files.createTempDirectory("shutdown-tracker-failure").toFile();
+    LifecycleTableDataManager table =
+        new LifecycleTableDataManager(indexDir, 
mock(RealtimeSegmentDataManager.class), false, () -> { });
+    IngestionDelayTracker tracker = (IngestionDelayTracker) 
FieldUtils.readField(table, "_ingestionDelayTracker", true);
+    doThrow(new IllegalStateException("KafkaConsumer is not safe for 
multi-threaded access")).when(tracker).shutdown();
+    try {
+      table.shutDown();
+      assertTrue(table._releasedSegments, "The segments were not released 
after the tracker failed to shut down");
+    } finally {
+      FileUtils.deleteDirectory(indexDir);
+    }
+  }
+
   @DataProvider
   public Object[][] upsertConsistencyModes() {
     return new Object[][]{{ConsistencyMode.NONE}, {ConsistencyMode.SYNC}, 
{ConsistencyMode.SNAPSHOT}};
@@ -619,6 +664,15 @@ public class RealtimeTableDataManagerTest {
     private final PartitionUpsertMetadataManager 
_partitionUpsertMetadataManager =
         mock(PartitionUpsertMetadataManager.class);
     private final TableUpsertMetadataManager _upsertMetadataManager = 
mock(TableUpsertMetadataManager.class);
+    volatile boolean _releasedSegments;
+    volatile boolean _interruptedWhileReleasingSegments;
+
+    @Override
+    protected void releaseAndRemoveAllSegments() {
+      _releasedSegments = true;
+      _interruptedWhileReleasingSegments = 
Thread.currentThread().isInterrupted();
+      super.releaseAndRemoveAllSegments();
+    }
 
     LifecycleTableDataManager(File indexDir, RealtimeSegmentDataManager 
segment, boolean upsertEnabled,
         Runnable beforeConstructionReturns)


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to