yashmayya commented on code in PR #16299:
URL: https://github.com/apache/pinot/pull/16299#discussion_r2200232633


##########
pinot-core/src/main/java/org/apache/pinot/core/accounting/PerQueryCPUMemAccountantFactory.java:
##########
@@ -868,8 +891,12 @@ void killAllQueries() {
        * use XX:+ExplicitGCInvokesConcurrent to avoid a full gc when system.gc 
is triggered
        */
       private void killMostExpensiveQuery() {
+        if (!_isThreadMemorySamplingEnabled) {
+          LOGGER.warn("But unable to kill query memory tracking is enabled");

Review Comment:
   This log line looks strange - should it be something like `Unable to kill 
query because memory sampling is not enabled`?



##########
pinot-core/src/main/java/org/apache/pinot/core/accounting/PerQueryCPUMemAccountantFactory.java:
##########
@@ -132,6 +132,8 @@ public static class PerQueryCPUMemResourceUsageAccountant 
implements ThreadResou
 
     protected final Set<String> _inactiveQuery;
 
+    protected Set<String> _cancelSentQueries;

Review Comment:
   In the incident we encountered recently, we saw this framework attempting to 
kill the same query (which had a 60 second timeout) for over 3 hours - is the 
inactive query set not being used at all? Could we leverage that here or is it 
intentional to split out this cancel sent queries set wherein we might kill 
multiple queries consecutively?



##########
pinot-core/src/main/java/org/apache/pinot/core/accounting/PerQueryCPUMemAccountantFactory.java:
##########
@@ -715,46 +728,56 @@ private void logQueryMonitorConfig() {
       @Override
       public void run() {
         while (true) {
-          QueryMonitorConfig config = _queryMonitorConfig.get();
-
-          LOGGER.debug("Running timed task for PerQueryCPUMemAccountant.");
-          _triggeringLevel = TriggeringLevel.Normal;
-          _sleepTime = config.getNormalSleepTime();
-          _aggregatedUsagePerActiveQuery = null;
           try {
-            // Get the metrics used for triggering the kill
-            collectTriggerMetrics();
-            // Prioritize the panic check, kill ALL QUERIES immediately if 
triggered
-            if (outOfMemoryPanicTrigger()) {
-              continue;
-            }
-            // Check for other triggers
-            evalTriggers();
-            // Refresh thread usage and aggregate to per query usage if 
triggered
-            _aggregatedUsagePerActiveQuery = 
aggregate(_triggeringLevel.ordinal() > TriggeringLevel.Normal.ordinal());
-            // post aggregation function
-            postAggregation(_aggregatedUsagePerActiveQuery);
-            // Act on one triggered actions
-            triggeredActions();
-          } catch (Exception e) {
-            LOGGER.error("Caught exception while executing stats aggregation 
and query kill", e);
+            runOnce();
           } finally {
-            LOGGER.debug(_aggregatedUsagePerActiveQuery == null ? 
"_aggregatedUsagePerActiveQuery : null"
-                : _aggregatedUsagePerActiveQuery.toString());
-            LOGGER.debug("_threadEntriesMap size: {}", 
_threadEntriesMap.size());
-
-            // Publish server heap usage metrics
-            if (config.isPublishHeapUsageMetric()) {
-              _metrics.setValueOfGlobalGauge(_memoryUsageGauge, _usedBytes);
-            }
-            // Clean inactive query stats
-            cleanInactive();
             // Sleep for sometime
             reschedule();
           }
         }
       }
 
+      public void runOnce() {
+        QueryMonitorConfig config = _queryMonitorConfig.get();
+
+        LOGGER.debug("Running timed task for PerQueryCPUMemAccountant.");
+        _triggeringLevel = TriggeringLevel.Normal;
+        _sleepTime = config.getNormalSleepTime();
+        _aggregatedUsagePerActiveQuery = null;
+        try {
+          // Get the metrics used for triggering the kill
+          collectTriggerMetrics();
+          // Prioritize the panic check, kill ALL QUERIES immediately if 
triggered
+          if (outOfMemoryPanicTrigger()) {
+            return;
+          }
+          // Check for other triggers
+          evalTriggers();
+          // Refresh thread usage and aggregate to per query usage if triggered
+          reapFinishedTasks();
+          if (_triggeringLevel.ordinal() > TriggeringLevel.Normal.ordinal()) {
+            _aggregatedUsagePerActiveQuery = getQueryResourcesImpl();

Review Comment:
   Why is this directly calling `getQueryResourcesImpl` and not 
`getQueryResources`? What's the abstraction here exactly?



##########
pinot-core/src/test/java/org/apache/pinot/core/accounting/PerQueryCPUMemAccountCancelTest.java:
##########
@@ -0,0 +1,190 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.pinot.core.accounting;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import org.apache.pinot.spi.accounting.QueryResourceTracker;
+import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.util.TestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+
+public class PerQueryCPUMemAccountCancelTest {
+  static class AlwaysTerminateMostExpensiveQueryAccountant extends 
TestResourceAccountant {
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(AlwaysTerminateMostExpensiveQueryAccountant.class);
+    private final List<String> _cancelLog = new ArrayList<>();
+
+    AlwaysTerminateMostExpensiveQueryAccountant(
+        Map<Thread, CPUMemThreadLevelAccountingObjects.ThreadEntry> 
threadEntries) {
+      super(threadEntries);
+    }
+
+    @Override
+    public WatcherTask createWatcherTask() {
+      return new TerminatingWatcherTask();
+    }
+
+    @Override
+    public void cancelQuery(AggregatedStats queryResourceTracker) {
+      _cancelSentQueries.add(queryResourceTracker.getQueryId());
+      _cancelLog.add(queryResourceTracker.getQueryId());
+    }
+
+    public List<String> getCancelLog() {
+      return _cancelLog;
+    }
+
+    class TerminatingWatcherTask extends WatcherTask {
+      TerminatingWatcherTask() {
+        PinotConfiguration config = new PinotConfiguration();
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_MIN_MEMORY_FOOTPRINT_TO_KILL_RATIO,
 0.01);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_PANIC_LEVEL_HEAP_USAGE_RATIO,
+            CommonConstants.Accounting.DFAULT_PANIC_LEVEL_HEAP_USAGE_RATIO);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_CRITICAL_LEVEL_HEAP_USAGE_RATIO,
+            
CommonConstants.Accounting.DEFAULT_CRITICAL_LEVEL_HEAP_USAGE_RATIO);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_CRITICAL_LEVEL_HEAP_USAGE_RATIO_DELTA_AFTER_GC,
+            
CommonConstants.Accounting.DEFAULT_CONFIG_OF_CRITICAL_LEVEL_HEAP_USAGE_RATIO_DELTA_AFTER_GC);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_GC_BACKOFF_COUNT,
+            CommonConstants.Accounting.DEFAULT_GC_BACKOFF_COUNT);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_ALARMING_LEVEL_HEAP_USAGE_RATIO,
+            
CommonConstants.Accounting.DEFAULT_ALARMING_LEVEL_HEAP_USAGE_RATIO);
+
+        config.setProperty(CommonConstants.Accounting.CONFIG_OF_SLEEP_TIME_MS,
+            CommonConstants.Accounting.DEFAULT_SLEEP_TIME_MS);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_GC_WAIT_TIME_MS,
+            CommonConstants.Accounting.DEFAULT_CONFIG_OF_GC_WAIT_TIME_MS);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_SLEEP_TIME_DENOMINATOR,
+            CommonConstants.Accounting.DEFAULT_SLEEP_TIME_DENOMINATOR);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_OOM_PROTECTION_KILLING_QUERY,
 true);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_PUBLISHING_JVM_USAGE,
+            CommonConstants.Accounting.DEFAULT_PUBLISHING_JVM_USAGE);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_CPU_TIME_BASED_KILLING_ENABLED,
+            CommonConstants.Accounting.DEFAULT_CPU_TIME_BASED_KILLING_ENABLED);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_CPU_TIME_BASED_KILLING_THRESHOLD_MS,
+            
CommonConstants.Accounting.DEFAULT_CPU_TIME_BASED_KILLING_THRESHOLD_MS);
+
+        
config.setProperty(CommonConstants.Accounting.CONFIG_OF_QUERY_KILLED_METRIC_ENABLED,
+            CommonConstants.Accounting.DEFAULT_QUERY_KILLED_METRIC_ENABLED);
+
+        QueryMonitorConfig queryMonitorConfig = new QueryMonitorConfig(config, 
1000);
+        _queryMonitorConfig.set(queryMonitorConfig);
+      }
+
+      @Override
+      public void runOnce() {
+        _aggregatedUsagePerActiveQuery = null;
+        try {
+          evalTriggers();
+          reapFinishedTasks();
+          _aggregatedUsagePerActiveQuery = getQueryResourcesImpl();
+          triggeredActions();
+        } catch (Exception e) {
+          LOGGER.error("Caught exception while executing stats aggregation and 
query kill", e);
+        } finally {
+          // Clean inactive query stats
+          cleanInactive();
+        }
+      }
+
+      @Override
+      public void evalTriggers() {
+        _triggeringLevel = TriggeringLevel.HeapMemoryCritical;
+      }
+    }
+  }
+
+  @Test
+  void testCancelSingleQuery() {
+    Map<Thread, CPUMemThreadLevelAccountingObjects.ThreadEntry> threadEntries 
= new HashMap<>();
+    CountDownLatch threadLatch = new CountDownLatch(1);
+    String queryId = "testQueryAggregation";
+    TestResourceAccountant.getQueryThreadEntries(queryId, threadLatch, 
threadEntries);
+
+    AlwaysTerminateMostExpensiveQueryAccountant accountant =
+        new AlwaysTerminateMostExpensiveQueryAccountant(threadEntries);
+    Map<String, ? extends QueryResourceTracker> queryResourceTrackerMap = 
accountant.getQueryResources();
+    assertEquals(queryResourceTrackerMap.size(), 1);
+    QueryResourceTracker queryResourceTracker = 
queryResourceTrackerMap.get(queryId);
+    assertEquals(queryResourceTracker.getAllocatedBytes(), 5500);
+
+    // Cancel a query.
+    accountant.getWatcherTask().runOnce();
+    assertEquals(accountant.getCancelLog().size(), 1);
+
+    // Try once more. There should still be only one cancel.
+    accountant.getWatcherTask().runOnce();
+    assertEquals(accountant.getCancelLog().size(), 1);
+    threadLatch.countDown();
+    TestUtils.waitForCondition(aVoid -> {
+      accountant.reapFinishedTasks();
+      return accountant.getCancelSentQueries().isEmpty();
+    }, 100L, 1000L, "CancelSentList was not cleared");
+  }
+
+  @Test
+  void testCancelTwoQuery() {
+    Map<Thread, CPUMemThreadLevelAccountingObjects.ThreadEntry> threadEntries 
= new HashMap<>();
+    CountDownLatch threadLatch = new CountDownLatch(1);
+    String queryId = "testQueryOne";
+    TestResourceAccountant.getQueryThreadEntries(queryId, threadLatch, 
threadEntries);
+    String queryId2 = "testQueryTwo";
+    TestResourceAccountant.getQueryThreadEntries(queryId2, threadLatch, 
threadEntries);
+
+    AlwaysTerminateMostExpensiveQueryAccountant accountant =
+        new AlwaysTerminateMostExpensiveQueryAccountant(threadEntries);
+    Map<String, ? extends QueryResourceTracker> queryResourceTrackerMap = 
accountant.getQueryResources();
+    assertEquals(queryResourceTrackerMap.size(), 2);
+    assertEquals(queryResourceTrackerMap.get(queryId).getAllocatedBytes(), 
5500);
+    assertEquals(queryResourceTrackerMap.get(queryId2).getAllocatedBytes(), 
5500);
+
+    // Cancel a query.
+    accountant.getWatcherTask().runOnce();
+    assertEquals(accountant.getCancelLog().size(), 1);
+
+    // Try once more. There should still be only one cancel.

Review Comment:
   nit: copy paste error?



##########
pinot-core/src/main/java/org/apache/pinot/core/accounting/PerQueryCPUMemAccountantFactory.java:
##########
@@ -868,8 +891,12 @@ void killAllQueries() {
        * use XX:+ExplicitGCInvokesConcurrent to avoid a full gc when system.gc 
is triggered
        */
       private void killMostExpensiveQuery() {
+        if (!_isThreadMemorySamplingEnabled) {
+          LOGGER.warn("But unable to kill query memory tracking is enabled");

Review Comment:
   Also the condition earlier checked if both memory and CPU sampling were 
disabled but now only memory sampling is being checked?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to