rahil-c commented on code in PR #19575:
URL: https://github.com/apache/hudi/pull/19575#discussion_r3859016150


##########
hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/index/RecordIndexLookupMetrics.java:
##########
@@ -0,0 +1,117 @@
+/*
+ * 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.hudi.index;
+
+import org.apache.hudi.common.engine.HoodieEngineContext;
+import org.apache.hudi.common.metrics.Registry;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metrics.DistributedRegistry;
+import org.apache.hudi.metrics.ExecutorMetricGroup;
+import org.apache.hudi.metrics.ExecutorMetricRegistry;
+import org.apache.hudi.metrics.RecordIndexMetricNames;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/** Executor-side emission for the record index lookup counters. */
+public class RecordIndexLookupMetrics {
+
+  /** Set by the read client around its own tagging call, so dedupe traffic is 
attributable separately. */
+  private static final ThreadLocal<String> CALLER =
+      ThreadLocal.withInitial(() -> 
RecordIndexMetricNames.CALLER_TAG_LOCATION);
+
+  private RecordIndexLookupMetrics() {
+  }
+
+  public static String currentCaller() {
+    return CALLER.get();
+  }
+
+  /** Restore rather than clear, so a nested tagging call does not reset the 
label. */
+  public static String setCaller(String caller) {
+    String previous = CALLER.get();
+    CALLER.set(caller);
+    return previous;
+  }
+
+  public static void restoreCaller(String previous) {
+    CALLER.set(previous);
+  }
+
+  /**
+   * The registries a lookup task collects into, keyed by bare name. Includes 
every entry on
+   * {@link ExecutorMetricRegistry}. Delivery is by closure capture, which is 
deterministic; resolution is
+   * by name, which lets code below the write API take part without a 
signature change.
+   */
+  public static Map<String, Registry> resolveBundle(HoodieEngineContext 
context, HoodieWriteConfig config) {
+    return resolveBundle(context, config, 
Arrays.asList(ExecutorMetricRegistry.values()));
+  }
+
+  /** Visible for testing the bundle against a group the enum does not ship 
with. */
+  public static Map<String, Registry> resolveBundle(HoodieEngineContext 
context, HoodieWriteConfig config,
+                                                    Collection<? extends 
ExecutorMetricGroup> groups) {
+    Map<String, Registry> bundle = new HashMap<>();
+    for (ExecutorMetricGroup metricRegistry : groups) {
+      if (!metricRegistry.isEnabled(config)) {

Review Comment:
   Taking the config half. `RLI_LOOKUP_METRICS_ENABLE` now defaults to `false` 
with `withInferFunction(cfg -> cfg.getBoolean(TURN_METRICS_ON))`, matching 
`LOCK_METRICS_ENABLE`. With the commit-metadata sink removed there is no longer 
any reason to collect when metrics are off -- there is nowhere to publish -- so 
this closes the opt-in gap rather than just narrowing it.
   
   The per-task accumulator cost is real and I could reproduce the unbounded 
growth: a single functional run leaves 40+ never-evicted 
`HoodieRecordIndexLookup.<digest>` entries in `REGISTRY_MAP`. Keeping the 
registry out of the engine-context captures is the right follow-up but it is 
the same change as the instance-scoped registry, so I am deferring both to the 
follow-up rather than reshaping the map in this PR.



##########
hudi-common/src/main/java/org/apache/hudi/common/config/metrics/HoodieMetricsConfig.java:
##########
@@ -109,6 +109,17 @@ public class HoodieMetricsConfig extends HoodieConfig {
       .sinceVersion("0.13.0")
       .withDocumentation("Enable metrics for locking infra. Useful when 
operating in multiwriter mode");
 
+  public static final ConfigProperty<Boolean> RLI_LOOKUP_METRICS_ENABLE = 
ConfigProperty
+      .key(METRIC_PREFIX + ".rli.lookup.enable")
+      .defaultValue(true)
+      .markAdvanced()
+      .sinceVersion("1.3.0")
+      .withDocumentation("Collect counters for the record level index lookup 
phase (records looked up, "

Review Comment:
   Fixed. The config doc now says Spark only and states that counters aggregate 
per table per JVM rather than per writer. It also no longer describes the 
commit-metadata sink, which has been removed.



##########
hudi-utilities/src/test/java/org/apache/hudi/utilities/deltastreamer/TestRliMetricsOnStreamerPath.java:
##########
@@ -0,0 +1,125 @@
+/*
+ * 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.hudi.utilities.deltastreamer;
+
+import org.apache.hudi.common.config.HoodieMetadataConfig;
+import org.apache.hudi.common.model.HoodieCommitMetadata;
+import org.apache.hudi.common.model.WriteOperationType;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.config.HoodieIndexConfig;
+import org.apache.hudi.metrics.RecordIndexMetricNames;
+
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The RLI lookup counters must reach commit metadata on the DeltaStreamer 
path, not only on the Spark DataSource path.
+ */
+@Tag("functional")
+public class TestRliMetricsOnStreamerPath extends HoodieDeltaStreamerTestBase {
+
+  /** Selects the global or partitioned record index. */
+  private static void enableRecordIndex(HoodieDeltaStreamer.Config cfg, 
boolean partitioned) {
+    cfg.configs.add(HoodieMetadataConfig.ENABLE.key() + "=true");
+    
cfg.configs.add(HoodieMetadataConfig.GLOBAL_RECORD_LEVEL_INDEX_ENABLE_PROP.key()
 + "=" + !partitioned);
+    cfg.configs.add(HoodieMetadataConfig.RECORD_LEVEL_INDEX_ENABLE_PROP.key() 
+ "=" + partitioned);
+    cfg.configs.add(HoodieIndexConfig.INDEX_TYPE.key() + "="
+        + (partitioned ? "RECORD_LEVEL_INDEX" : "GLOBAL_RECORD_LEVEL_INDEX"));
+  }
+
+  private static Map<String, String> rliCountersOnLatestCommit(String 
tableBasePath) throws Exception {
+    HoodieTableMetaClient metaClient = HoodieTableMetaClient.builder()
+        .setConf(HoodieTestUtils.getDefaultStorageConf())
+        .setBasePath(tableBasePath)
+        .build();
+    metaClient.reloadActiveTimeline();
+    HoodieInstant lastInstant = metaClient.getActiveTimeline()
+        .getCommitsTimeline().filterCompletedInstants().lastInstant().get();
+    HoodieCommitMetadata commitMetadata = 
metaClient.getActiveTimeline().readCommitMetadata(lastInstant);
+    Map<String, String> rli = new HashMap<>();
+    commitMetadata.getExtraMetadata().forEach((k, v) -> {
+      if (k.startsWith(RecordIndexMetricNames.COMMIT_METADATA_PREFIX)) {
+        rli.put(k, v);
+      }
+    });
+    return rli;
+  }
+
+  private static String tagKey(String metric) {
+    return RecordIndexMetricNames.COMMIT_METADATA_PREFIX
+        + 
RecordIndexMetricNames.key(RecordIndexMetricNames.CALLER_TAG_LOCATION, metric);
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void testRliCountersReachCommitMetadataOnStreamerPath(boolean 
partitioned) throws Exception {
+    String label = partitioned ? "partitioned" : "global";
+    String tableBasePath = basePath + "/test_rli_metrics_streamer_" + label;
+
+    // Sync 1 -- build the table and the record index.
+    HoodieDeltaStreamer.Config insertCfg =
+        TestHoodieDeltaStreamer.TestHelpers.makeConfig(tableBasePath, 
WriteOperationType.INSERT);
+    enableRecordIndex(insertCfg, partitioned);
+    new HoodieDeltaStreamer(insertCfg, jsc).sync();
+
+    // Sync 2 -- upsert, which tags incoming keys against the record index.
+    HoodieDeltaStreamer.Config upsertCfg =
+        TestHoodieDeltaStreamer.TestHelpers.makeConfig(tableBasePath, 
WriteOperationType.UPSERT);
+    enableRecordIndex(upsertCfg, partitioned);
+    new HoodieDeltaStreamer(upsertCfg, jsc).sync();
+
+    Map<String, String> counters = rliCountersOnLatestCommit(tableBasePath);
+
+    System.out.println("\n===== DeltaStreamer (" + label + " RLI) -- RLI 
counters on the commit =====");
+    if (counters.isEmpty()) {
+      System.out.println("  (none found)");
+    } else {
+      counters.entrySet().stream()
+          .sorted(Map.Entry.comparingByKey())
+          .forEach(e -> System.out.println(String.format("  %-52s %s", 
e.getKey(), e.getValue())));
+    }
+    
System.out.println("==========================================================\n");
+
+    assertFalse(counters.isEmpty(),
+        "the commit-boundary drain must fire on the DeltaStreamer path; 
hudi-utilities never calls "
+            + "Metrics.shutdownAllMetrics, so nothing else would publish 
these");
+
+    String lookedUp = tagKey(RecordIndexMetricNames.KEY_COUNT);
+    assertTrue(counters.containsKey(lookedUp),
+        "tag-location traffic must be attributed on the streamer path too; got 
" + counters.keySet());
+
+    long records = Long.parseLong(counters.get(lookedUp));
+    long hits = 
Long.parseLong(counters.get(tagKey(RecordIndexMetricNames.KEY_HIT_COUNT)));
+    long misses = 
Long.parseLong(counters.get(tagKey(RecordIndexMetricNames.KEY_MISS_COUNT)));
+    assertTrue(records > 0, "the upsert sync looked up at least one key");
+    assertEquals(records, hits + misses, "hits + misses must account for every 
key looked up");

Review Comment:
   Fixed, took the suggestion. You are right that `records == hits + misses` 
holds by construction -- `misses` is derived as `records - hits` at the 
emission site -- so it could not have caught a doubled count. Now asserts 1000 
/ 500 / 500 exactly.



##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/RliLookupMetricsTestBase.scala:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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.hudi.functional
+
+import org.apache.hudi.DataSourceWriteOptions
+import org.apache.hudi.common.config.HoodieMetadataConfig
+import org.apache.hudi.common.metrics.Registry
+import org.apache.hudi.config.HoodieIndexConfig
+import org.apache.hudi.metrics.RecordIndexMetricNames
+
+import scala.collection.JavaConverters._
+
+/**
+ * Shared plumbing for the record level index lookup metric tests: index 
selection, and reading the counters back the way an operator would -- off the la

Review Comment:
   Fixed -- the sentence was truncated. Rewritten, and it now describes reading 
off the reporter rather than the commit, since the commit-metadata sink is gone.



##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/RliLookupMetricsTestBase.scala:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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.hudi.functional
+
+import org.apache.hudi.DataSourceWriteOptions
+import org.apache.hudi.common.config.HoodieMetadataConfig
+import org.apache.hudi.common.metrics.Registry
+import org.apache.hudi.config.HoodieIndexConfig
+import org.apache.hudi.metrics.RecordIndexMetricNames
+
+import scala.collection.JavaConverters._
+
+/**
+ * Shared plumbing for the record level index lookup metric tests: index 
selection, and reading the counters back the way an operator would -- off the la
+ */
+abstract class RliLookupMetricsTestBase extends RecordLevelIndexTestBase {
+
+  /** Overridden by the partitioned subclasses; both variants are separate 
closures on separate paths. */
+  protected def isPartitionedRli: Boolean = false
+
+  /**
+   * Table type under test. Tagging is an index-level concern and does not 
branch on table type, so MOR
+   * is expected to behave identically -- the MOR subclasses exist to prove 
that rather than assume it.
+   */
+  protected def tableTypeOpt: String = 
DataSourceWriteOptions.COW_TABLE_TYPE_OPT_VAL
+
+  protected def indexLabel: String = {
+    val idx = if (isPartitionedRli) "partitioned RLI" else "global RLI"
+    val tt = if (tableTypeOpt == 
DataSourceWriteOptions.MOR_TABLE_TYPE_OPT_VAL) "MOR" else "COW"
+    s"$idx, $tt"
+  }
+
+  /**
+   * `commonOpts` turns the global record index on, so the metadata-partition 
flags and the index type
+   * have to be flipped together to select the partitioned variant.
+   */
+  protected def rliOpts: Map[String, String] = {
+    val withTableType = Map(DataSourceWriteOptions.TABLE_TYPE.key -> 
tableTypeOpt)
+    if (isPartitionedRli) {
+      commonOpts ++ withTableType ++ Map(
+        HoodieMetadataConfig.GLOBAL_RECORD_LEVEL_INDEX_ENABLE_PROP.key -> 
"false",
+        HoodieMetadataConfig.RECORD_LEVEL_INDEX_ENABLE_PROP.key -> "true",
+        HoodieIndexConfig.INDEX_TYPE.key -> "RECORD_LEVEL_INDEX")
+    } else {
+      commonOpts ++ withTableType ++ Map(
+        HoodieMetadataConfig.GLOBAL_RECORD_LEVEL_INDEX_ENABLE_PROP.key -> 
"true",
+        HoodieMetadataConfig.RECORD_LEVEL_INDEX_ENABLE_PROP.key -> "false",
+        HoodieIndexConfig.INDEX_TYPE.key -> "GLOBAL_RECORD_LEVEL_INDEX")
+    }
+  }
+
+  protected def counterKey(caller: String, metric: String): String =
+    RecordIndexMetricNames.COMMIT_METADATA_PREFIX + 
RecordIndexMetricNames.key(caller, metric)
+
+  protected def tagKey(metric: String): String =
+    counterKey(RecordIndexMetricNames.CALLER_TAG_LOCATION, metric)
+
+  /**
+   * A caller that looked something up stamps its full counter set, zeros 
included, so an absent key means
+   * that caller contributed nothing at all. The default is defensive against 
exactly that case.
+   */
+  protected def counterOrZero(counters: Map[String, String], caller: String, 
metric: String): Long =
+    counters.getOrElse(counterKey(caller, metric), "0").toLong
+
+  /** The counters as an operator would read them: off the latest completed 
commit. */
+  protected def rliCountersFromLatestCommit(): Map[String, String] = {
+    metaClient.reloadActiveTimeline()
+    val lastInstant = 
metaClient.getActiveTimeline.getCommitsTimeline.filterCompletedInstants().lastInstant().get()
+    
metaClient.getActiveTimeline.readCommitMetadata(lastInstant).getExtraMetadata.asScala.toMap
+      .filter { case (k, _) => 
k.startsWith(RecordIndexMetricNames.COMMIT_METADATA_PREFIX) }
+  }
+
+  /** Leftover counters from a previous write would otherwise be folded into 
the next commit. */
+  protected def clearRliRegistry(): Unit = {
+    Registry.REGISTRY_MAP.asScala.foreach {
+      case (key, registry) => if 
(key.contains(RecordIndexMetricNames.REGISTRY_NAME)) registry.clear()
+    }
+  }
+
+  /** Asserts the core invariant and returns the looked-up count. */
+  protected def assertSumInvariant(counters: Map[String, String], caller: 
String): Long = {
+    val lookedUp = counterOrZero(counters, caller, 
RecordIndexMetricNames.KEY_COUNT)
+    val hits = counterOrZero(counters, caller, 
RecordIndexMetricNames.KEY_HIT_COUNT)
+    val misses = counterOrZero(counters, caller, 
RecordIndexMetricNames.KEY_MISS_COUNT)
+    org.junit.jupiter.api.Assertions.assertEquals(lookedUp, hits + misses,
+      s"hits + misses must account for every key looked up by '$caller'")
+    // A caller that looked something up must also report the time it took, or 
the timing metric is
+    // silently absent on paths nobody checked. Zero is allowed: a shard read 
can round below a millisecond.
+    if (lookedUp > 0) {
+      org.junit.jupiter.api.Assertions.assertTrue(
+        counters.contains(counterKey(caller, 
RecordIndexMetricNames.LOOKUP_TIME)),
+        s"'$caller' looked up $lookedUp keys but reported no 
${RecordIndexMetricNames.LOOKUP_TIME}; " +
+          s"counters were ${counters.keys.toSeq.sorted.mkString(", ")}")
+      org.junit.jupiter.api.Assertions.assertTrue(
+        counterOrZero(counters, caller, RecordIndexMetricNames.LOOKUP_TIME) >= 
0L,

Review Comment:
   Took the first half: the `>= 0L` assertion is dropped, since an unsigned 
counter cannot fail it and the `contains` above is the real check.
   
   Keeping the `report(...)` helpers for now. They are the only way the actual 
counter values reach the CI log, and on a metrics feature that is what makes a 
failure diagnosable rather than just a boolean. Happy to drop them if you would 
rather keep the log clean.



##########
hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/index/PartitionedRecordIndexFileGroupLookupFunction.java:
##########
@@ -44,36 +47,57 @@ public class PartitionedRecordIndexFileGroupLookupFunction
     implements PairFlatMapFunction<Iterator<Pair<String, String>>, String, 
HoodieRecordGlobalLocation> {
 
   private final HoodieTableMetadata metadataTable;
+  // Empty when no counters should be collected; see 
RecordIndexLookupMetrics#resolveBundle.
+  private final Map<String, Registry> metricsBundle;
+  private final String caller;
 
+  /** Uninstrumented, for the query-side read path. */
   public PartitionedRecordIndexFileGroupLookupFunction(HoodieTableMetadata 
metadataTable) {
+    this(metadataTable, Collections.emptyMap(), null);
+  }
+
+  public PartitionedRecordIndexFileGroupLookupFunction(HoodieTableMetadata 
metadataTable,
+                                                       Map<String, Registry> 
metricsBundle, String caller) {
     this.metadataTable = metadataTable;
+    this.metricsBundle = metricsBundle;
+    this.caller = caller;
   }
 
   @Override
   public Iterator<Tuple2<String, HoodieRecordGlobalLocation>> 
call(Iterator<Pair<String, String>> partitionPathRecordKeyIterator) {
-    String partitionName = null;
-    List<String> keysToLookup = new ArrayList<>();
-    while (partitionPathRecordKeyIterator.hasNext()) {
-      Pair<String, String> partitionPathRecordKey = 
partitionPathRecordKeyIterator.next();
-      keysToLookup.add(partitionPathRecordKey.getRight());
-      if (partitionName == null) {
-        partitionName = partitionPathRecordKey.getLeft();
+    // Bound for the whole task so a metric raised deeper in the lookup 
resolves here too.

Review Comment:
   Fixed, took the suggestion -- the binding is released in the `finally` 
before Spark consumes the iterator, so it covers the shard read, not the whole 
task.



-- 
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]

Reply via email to