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


##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestRliLookupMetricsReporting.scala:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.metrics.HoodieMetricsConfig
+import org.apache.hudi.metrics.{ExecutorMetricRegistry, RecordIndexMetricNames}
+
+import org.apache.spark.sql.SaveMode
+import org.junit.jupiter.api.{Tag, Test}
+import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue}
+
+import java.io.{ByteArrayOutputStream, PrintStream}
+
+/** The counters must reach a live metrics reporter, not only commit metadata. 
*/
+@Tag("functional")
+class TestRliLookupMetricsReporting extends RliLookupMetricsTestBase {
+
+  private def metricsOpts: Map[String, String] = rliOpts ++ Map(
+    HoodieMetricsConfig.TURN_METRICS_ON.key -> "true",
+    HoodieMetricsConfig.METRICS_REPORTER_TYPE_VALUE.key -> "CONSOLE")
+
+  /** Captures stdout for the duration of the write. */
+  private def captureStdout(body: => Unit): String = {
+    val buffer = new ByteArrayOutputStream()
+    val original = System.out
+    try {
+      System.setOut(new PrintStream(buffer, true, "UTF-8"))
+      body
+    } finally {
+      System.setOut(original)
+    }
+    buffer.toString("UTF-8")
+  }
+
+  @Test
+  def testCountersReachBothCommitMetadataAndTheReporter(): Unit = {
+    val numUpdates = 12
+
+    doWriteAndValidateDataAndRecordIndex(metricsOpts, 
INSERT_OPERATION_OPT_VAL, SaveMode.Overwrite,
+      validate = false, numInserts = 50)
+    clearRliRegistry()
+
+    val stdout = captureStdout {
+      doWriteAndValidateDataAndRecordIndex(metricsOpts, 
UPSERT_OPERATION_OPT_VAL, SaveMode.Append,
+        validate = false, numUpdates = numUpdates)
+    }
+
+    // Sink 1 -- the timeline.
+    val counters = rliCountersFromLatestCommit()
+    report(s"Reporter test ($indexLabel) -- commit metadata", counters)
+    assertTrue(counters.nonEmpty, "the commit must still carry the counters 
when a reporter is configured")
+    assertEquals(numUpdates.toString, 
counters(tagKey(RecordIndexMetricNames.KEY_HIT_COUNT)))
+    assertEquals((numUpdates + 1).toLong, assertSumInvariant(counters, 
RecordIndexMetricNames.CALLER_TAG_LOCATION))
+
+    // Sink 2 -- the reporter. Gauge names are 
<prefix>.rli.lookup.<caller>.<metric>.
+    val gaugePrefix = 
s"${ExecutorMetricRegistry.RECORD_INDEX_LOOKUP.metricAction}.${ExecutorMetricRegistry.RECORD_INDEX_LOOKUP.metricQualifier}"
+    val reported = stdout.linesIterator.filter(_.contains(gaugePrefix)).toSeq
+
+    println(s"\n===== Reporter test ($indexLabel) -- ConsoleMetricsReporter 
output =====")
+    if (reported.isEmpty) println("  (no rli.lookup gauges printed)") else 
reported.foreach(l => println(s"  ${l.trim}"))
+    
println("=======================================================================\n")
+
+    assertTrue(reported.nonEmpty,
+      s"ConsoleMetricsReporter must publish the '$gaugePrefix' gauges; the 
drain feeds the reporter and " +
+        "commit metadata from a single read, so finding them in the commit but 
not here means the " +
+        "reporter sink regressed")
+    Seq(RecordIndexMetricNames.KEY_HIT_COUNT, 
RecordIndexMetricNames.KEY_MISS_COUNT,
+      RecordIndexMetricNames.KEY_COUNT, 
RecordIndexMetricNames.SHARDS_READ).foreach { metric =>
+      val name = 
s"$gaugePrefix.${RecordIndexMetricNames.key(RecordIndexMetricNames.CALLER_TAG_LOCATION,
 metric)}"
+      assertTrue(stdout.contains(name), s"reporter output must contain the 
gauge '$name'")

Review Comment:
   Resolved -- `TestRliLookupMetricsReporting` is deleted. Reporting is now the 
only sink, so every remaining functional test reads values back off a reporter 
and asserts them, which is the stronger check you were asking for.



##########
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 = {

Review Comment:
   Fixed -- `clearRliRegistry()` and all its call sites are deleted. You were 
right that `@TempDir` being per method makes the base-path digest unique per 
test, so it could never have been doing anything.



##########
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)) {
+        continue;
+      }
+      Registry registry = context.getMetricRegistry(config.getTableName(),
+          metricRegistry.scopedName(config.getBasePath()));
+      // Only the accumulator-backed registry aggregates back to the driver, 
so anything else is left out
+      // rather than bound: a bound LocalRegistry would collect on the 
executor and be dropped on the floor,
+      // whereas leaving it out makes the lookup resolve to a no-op that 
reports nothing.
+      if (registry instanceof DistributedRegistry) {
+        bundle.put(metricRegistry.registryName(), registry);
+      }
+    }
+    return bundle.isEmpty() ? Collections.emptyMap() : bundle;
+  }
+
+  /**
+   * Records one shard's lookup outcome. Counts records rather than distinct 
keys, so
+   * {@code hits + misses == records_looked_up} holds when a batch repeats a 
key. Membership is tested
+   * against the found set, bounded by the hit count, not the asked-about set, 
bounded by shard size.
+   *
+   * @param keysLookedUp every record key routed to this shard
+   * @param foundKeys    the subset present in the index
+   * @param elapsedMs    wall-clock spent reading this shard
+   */
+  public static void recordShardLookup(String caller, Collection<String> 
keysLookedUp,
+                                       Collection<String> foundKeys, long 
elapsedMs) {
+    if (keysLookedUp.isEmpty()) {
+      return;
+    }
+    Registry registry = 
Registry.getRegistry(RecordIndexMetricNames.REGISTRY_NAME);

Review Comment:
   Deferring, but this is the one I most want to come back to. You are right 
that nothing shipped emits without the bundle in hand, and that passing the 
`Registry` in directly would let `ExecutorMetricsContext`, `NoOpRegistry`, 
`TestRegistryExecutorLookup`, the `HoodieSparkTable` binding and the 
`Registry.getRegistry` contract change all go, both hudi-io additions included.
   
   Not taking it here for one reason: name resolution is the part the requester 
specifically asked for, so that code below the write API can take part without 
a signature change. Collapsing it to a passed-in `Registry` is the right call 
if that requirement softens, and it is a much larger delete than anything else 
on this PR, so it deserves its own change rather than being folded into a 
review pass. Filed as a follow-up.



##########
hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/common/HoodieSparkEngineContext.java:
##########
@@ -278,11 +279,43 @@ public String getApplicationId() {
     return javaSparkContext.sc().applicationId();
   }
 
+  /**
+   * Drops a registry from both process-wide maps. Only for tests that create 
their own SparkContexts:
+   * without it they leave accumulators bound to stopped contexts behind for 
whatever runs next in the
+   * same JVM.
+   */
+  @VisibleForTesting
+  public static void removeMetricRegistryForTesting(String tableName, String 
registryName) {
+    DISTRIBUTED_REGISTRY_MAP.remove(tableName.isEmpty() ? registryName : 
tableName + "." + registryName);
+    Registry.REGISTRY_MAP.remove(Registry.makeKey(tableName, registryName));
+  }
+
   @Override
   public Registry getMetricRegistry(String tableName, String registryName) {

Review Comment:
   Deferring to the follow-up, agreed on the diagnosis. The process-wide map is 
what forces the digest, the stale-context branch, the replacement branch and 
the remover, and it is where the unbounded growth lives -- I reproduced 40+ 
never-evicted entries in one functional run. #19063 already lists 
instance-scoped registry lifetime as the intended next step and your pointers 
(`StreamSync:1104`, `client.getEngineContext` in scope at 
`HoodieSparkSqlWriter:553`) look right. It changes the lifetime model for an 
existing shared component, so it wants its own PR and its own review rather 
than riding along here.



##########
hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/metrics/DistributedRegistry.java:
##########
@@ -48,9 +51,17 @@ public String getName() {
   public void register(JavaSparkContext jsc) {
     if (!isRegistered()) {
       jsc.sc().register(this);
+      // Only when this call actually registers: stamping unconditionally 
would re-brand an accumulator
+      // bound to a dead context and mask the staleness this field exists to 
detect.
+      this.registeredAppId = jsc.sc().applicationId();
     }
   }
 
+  /** False when bound to a different (typically stopped) context, meaning it 
must be recreated. */
+  public boolean isRegisteredWith(JavaSparkContext jsc) {

Review Comment:
   Agreed that the `DistributedRegistry` / `getMetricRegistry` hardening is 
separable, and that it fixes `hoodie.metrics.executor.enable` for the existing 
`HoodieWrapperFileSystem` user independent of anything RLI. It is about 830 
lines across 11 files, a third of this PR.
   
   Holding off only because splitting now means restacking a PR that is close 
to landing, and the counters do not work without it. Adding the #19063 
reference to the description in the meantime so the relationship is not lost.



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