ebyhr commented on code in PR #16250: URL: https://github.com/apache/iceberg/pull/16250#discussion_r3207104533
########## core/src/test/java/org/apache/iceberg/metrics/TestOtelEndpointSmoke.java: ########## @@ -0,0 +1,181 @@ +/* Review Comment: There is no assertion in this test class. Is it intentional? ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelEndpointSmoke.java: ########## @@ -0,0 +1,181 @@ +/* + * 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.iceberg.metrics; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.resources.Resource; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; + +/** + * Vendor-neutral E2E smoke test for {@link OtelMetricsReporter}. Builds an {@link + * OpenTelemetrySdk}, registers it as the global SDK, then exports synthetic ScanReport and + * CommitReport against any OTLP-compatible backend (e.g. ADOT Collector, Databricks Zerobus, + * Datadog OTLP, Grafana Cloud OTLP). Only runs when {@code OTEL_SMOKE_ENABLED=true}. + * + * <p>Required env vars when enabled: + * + * <ul> + * <li>{@code OTEL_SMOKE_ENDPOINT} — full OTLP endpoint URL + * <li>{@code OTEL_SMOKE_PROTOCOL} — {@code grpc} or {@code http/protobuf} Review Comment: The buildExporter method silently falls back to `http/protobuf` when the value isn't `grpc`. We could deny unsupported protocols instead: ```java private static MetricExporter buildExporter(String protocol, String endpoint, String headers) { if (protocol.equals("grpc")) { ... } else if (protocol.equals("http/protobuf")) { ... } else { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } } ``` ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelEndpointSmoke.java: ########## @@ -0,0 +1,181 @@ +/* + * 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.iceberg.metrics; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.resources.Resource; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; + +/** + * Vendor-neutral E2E smoke test for {@link OtelMetricsReporter}. Builds an {@link + * OpenTelemetrySdk}, registers it as the global SDK, then exports synthetic ScanReport and + * CommitReport against any OTLP-compatible backend (e.g. ADOT Collector, Databricks Zerobus, + * Datadog OTLP, Grafana Cloud OTLP). Only runs when {@code OTEL_SMOKE_ENABLED=true}. + * + * <p>Required env vars when enabled: + * + * <ul> + * <li>{@code OTEL_SMOKE_ENDPOINT} — full OTLP endpoint URL + * <li>{@code OTEL_SMOKE_PROTOCOL} — {@code grpc} or {@code http/protobuf} + * </ul> + * + * <p>Optional env vars: + * + * <ul> + * <li>{@code OTEL_SMOKE_HEADERS} — comma-separated {@code key=value} pairs (e.g. for bearer auth: + * {@code Authorization=Bearer <token>}) + * <li>{@code OTEL_SMOKE_SERVICE_NAME} — defaults to {@code iceberg-smoke-test} + * <li>{@code OTEL_SMOKE_EXPORT_INTERVAL_MS} — defaults to {@code 2000} + * <li>{@code OTEL_SMOKE_FLUSH_WAIT_MS} — sleep before close, defaults to {@code 5000} + * </ul> + */ +@EnabledIfEnvironmentVariable(named = "OTEL_SMOKE_ENABLED", matches = "true") +public class TestOtelEndpointSmoke { + + @Test + public void exportToOtlpEndpoint() throws Exception { + String endpoint = requireEnv("OTEL_SMOKE_ENDPOINT"); + String protocol = requireEnv("OTEL_SMOKE_PROTOCOL"); + String headers = System.getenv("OTEL_SMOKE_HEADERS"); + String serviceName = envOrDefault("OTEL_SMOKE_SERVICE_NAME", "iceberg-smoke-test"); + long exportIntervalMs = Long.parseLong(envOrDefault("OTEL_SMOKE_EXPORT_INTERVAL_MS", "2000")); + long flushWaitMs = Long.parseLong(envOrDefault("OTEL_SMOKE_FLUSH_WAIT_MS", "5000")); + + GlobalOpenTelemetry.resetForTest(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .setResource(Resource.getDefault().toBuilder().put("service.name", serviceName).build()) + .registerMetricReader( + PeriodicMetricReader.builder(buildExporter(protocol, endpoint, headers)) + .setInterval(Duration.ofMillis(exportIntervalMs)) + .build()) + .build(); + OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().setMeterProvider(meterProvider).build(); + GlobalOpenTelemetry.set(sdk); + + OtelMetricsReporter reporter = new OtelMetricsReporter(); + try { + reporter.initialize(ImmutableMap.of()); + + ScanReport scanReport = + ImmutableScanReport.builder() + .tableName("smoke.test_table") + .snapshotId(1001L) + .filter(Expressions.alwaysTrue()) + .schemaId(1) + .projectedFieldIds(ImmutableList.of(1, 2)) + .projectedFieldNames(ImmutableList.of("id", "data")) + .scanMetrics( + ImmutableScanMetricsResult.builder() + .totalPlanningDuration( + TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(123), 1)) + .resultDataFiles(CounterResult.of(Unit.COUNT, 7)) + .resultDeleteFiles(CounterResult.of(Unit.COUNT, 1)) + .scannedDataManifests(CounterResult.of(Unit.COUNT, 3)) + .skippedDataManifests(CounterResult.of(Unit.COUNT, 0)) + .totalFileSizeInBytes(CounterResult.of(Unit.BYTES, 4_096_000L)) + .build()) + .metadata(ImmutableMap.of("env", "smoke")) + .build(); + reporter.report(scanReport); + + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("smoke.test_table") + .snapshotId(1002L) + .sequenceNumber(2L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .totalDuration( + TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(231), 1)) + .attempts(CounterResult.of(Unit.COUNT, 1)) + .addedDataFiles(CounterResult.of(Unit.COUNT, 4)) + .removedDataFiles(CounterResult.of(Unit.COUNT, 0)) + .addedRecords(CounterResult.of(Unit.COUNT, 12345)) + .addedFilesSizeInBytes(CounterResult.of(Unit.BYTES, 2_048_000L)) + .build()) + .metadata(ImmutableMap.of("env", "smoke")) + .build(); + reporter.report(commitReport); + + // Wait so PeriodicMetricReader exports at least once before close(). + Thread.sleep(flushWaitMs); + } finally { + reporter.close(); + meterProvider.close(); + GlobalOpenTelemetry.resetForTest(); + } + } + + private static MetricExporter buildExporter(String protocol, String endpoint, String headers) { + if ("grpc".equals(protocol)) { + OtlpGrpcMetricExporterBuilder builder = + OtlpGrpcMetricExporter.builder().setEndpoint(endpoint); + addHeaders(headers, builder::addHeader); + return builder.build(); Review Comment: We could remove a local variable once we change the return type of the helper method to `Map<String, String>`: ```java return OtlpGrpcMetricExporter.builder() .setEndpoint(endpoint) .setHeaders(() -> toMap(headers)) .build(); ... private static Map<String, String> toMap(String headers) { if (Strings.isNullOrEmpty(headers)) { return Map.of(); } return Splitter.on(',').withKeyValueSeparator('=').split(headers); } ``` ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelEndpointSmoke.java: ########## @@ -0,0 +1,181 @@ +/* + * 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.iceberg.metrics; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.resources.Resource; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; + +/** + * Vendor-neutral E2E smoke test for {@link OtelMetricsReporter}. Builds an {@link + * OpenTelemetrySdk}, registers it as the global SDK, then exports synthetic ScanReport and + * CommitReport against any OTLP-compatible backend (e.g. ADOT Collector, Databricks Zerobus, + * Datadog OTLP, Grafana Cloud OTLP). Only runs when {@code OTEL_SMOKE_ENABLED=true}. + * + * <p>Required env vars when enabled: + * + * <ul> + * <li>{@code OTEL_SMOKE_ENDPOINT} — full OTLP endpoint URL + * <li>{@code OTEL_SMOKE_PROTOCOL} — {@code grpc} or {@code http/protobuf} + * </ul> + * + * <p>Optional env vars: + * + * <ul> + * <li>{@code OTEL_SMOKE_HEADERS} — comma-separated {@code key=value} pairs (e.g. for bearer auth: + * {@code Authorization=Bearer <token>}) + * <li>{@code OTEL_SMOKE_SERVICE_NAME} — defaults to {@code iceberg-smoke-test} + * <li>{@code OTEL_SMOKE_EXPORT_INTERVAL_MS} — defaults to {@code 2000} + * <li>{@code OTEL_SMOKE_FLUSH_WAIT_MS} — sleep before close, defaults to {@code 5000} + * </ul> + */ +@EnabledIfEnvironmentVariable(named = "OTEL_SMOKE_ENABLED", matches = "true") Review Comment: I'm not a fan of conditional tests unless they require cloud resources. These tests can easily become obsolete, and we can't identify the broken test until someone runs it. We could run this test using Testcontainers by default with any OTEL-compatible Docker image, such as jaegertracing. We could also allow arbitrary OTEL options via environment variables. This is just an idea, not a requested change. ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelEndpointSmoke.java: ########## @@ -0,0 +1,181 @@ +/* + * 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.iceberg.metrics; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.resources.Resource; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; + +/** + * Vendor-neutral E2E smoke test for {@link OtelMetricsReporter}. Builds an {@link + * OpenTelemetrySdk}, registers it as the global SDK, then exports synthetic ScanReport and + * CommitReport against any OTLP-compatible backend (e.g. ADOT Collector, Databricks Zerobus, + * Datadog OTLP, Grafana Cloud OTLP). Only runs when {@code OTEL_SMOKE_ENABLED=true}. + * + * <p>Required env vars when enabled: + * + * <ul> + * <li>{@code OTEL_SMOKE_ENDPOINT} — full OTLP endpoint URL + * <li>{@code OTEL_SMOKE_PROTOCOL} — {@code grpc} or {@code http/protobuf} + * </ul> + * + * <p>Optional env vars: + * + * <ul> + * <li>{@code OTEL_SMOKE_HEADERS} — comma-separated {@code key=value} pairs (e.g. for bearer auth: + * {@code Authorization=Bearer <token>}) + * <li>{@code OTEL_SMOKE_SERVICE_NAME} — defaults to {@code iceberg-smoke-test} + * <li>{@code OTEL_SMOKE_EXPORT_INTERVAL_MS} — defaults to {@code 2000} + * <li>{@code OTEL_SMOKE_FLUSH_WAIT_MS} — sleep before close, defaults to {@code 5000} + * </ul> + */ +@EnabledIfEnvironmentVariable(named = "OTEL_SMOKE_ENABLED", matches = "true") +public class TestOtelEndpointSmoke { + + @Test + public void exportToOtlpEndpoint() throws Exception { + String endpoint = requireEnv("OTEL_SMOKE_ENDPOINT"); + String protocol = requireEnv("OTEL_SMOKE_PROTOCOL"); + String headers = System.getenv("OTEL_SMOKE_HEADERS"); + String serviceName = envOrDefault("OTEL_SMOKE_SERVICE_NAME", "iceberg-smoke-test"); + long exportIntervalMs = Long.parseLong(envOrDefault("OTEL_SMOKE_EXPORT_INTERVAL_MS", "2000")); + long flushWaitMs = Long.parseLong(envOrDefault("OTEL_SMOKE_FLUSH_WAIT_MS", "5000")); + + GlobalOpenTelemetry.resetForTest(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .setResource(Resource.getDefault().toBuilder().put("service.name", serviceName).build()) + .registerMetricReader( + PeriodicMetricReader.builder(buildExporter(protocol, endpoint, headers)) + .setInterval(Duration.ofMillis(exportIntervalMs)) + .build()) + .build(); + OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().setMeterProvider(meterProvider).build(); + GlobalOpenTelemetry.set(sdk); + + OtelMetricsReporter reporter = new OtelMetricsReporter(); + try { + reporter.initialize(ImmutableMap.of()); + + ScanReport scanReport = + ImmutableScanReport.builder() + .tableName("smoke.test_table") + .snapshotId(1001L) + .filter(Expressions.alwaysTrue()) + .schemaId(1) + .projectedFieldIds(ImmutableList.of(1, 2)) + .projectedFieldNames(ImmutableList.of("id", "data")) + .scanMetrics( + ImmutableScanMetricsResult.builder() + .totalPlanningDuration( + TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(123), 1)) + .resultDataFiles(CounterResult.of(Unit.COUNT, 7)) + .resultDeleteFiles(CounterResult.of(Unit.COUNT, 1)) + .scannedDataManifests(CounterResult.of(Unit.COUNT, 3)) + .skippedDataManifests(CounterResult.of(Unit.COUNT, 0)) + .totalFileSizeInBytes(CounterResult.of(Unit.BYTES, 4_096_000L)) + .build()) + .metadata(ImmutableMap.of("env", "smoke")) + .build(); + reporter.report(scanReport); + + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("smoke.test_table") + .snapshotId(1002L) + .sequenceNumber(2L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .totalDuration( + TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(231), 1)) + .attempts(CounterResult.of(Unit.COUNT, 1)) + .addedDataFiles(CounterResult.of(Unit.COUNT, 4)) + .removedDataFiles(CounterResult.of(Unit.COUNT, 0)) + .addedRecords(CounterResult.of(Unit.COUNT, 12345)) + .addedFilesSizeInBytes(CounterResult.of(Unit.BYTES, 2_048_000L)) + .build()) + .metadata(ImmutableMap.of("env", "smoke")) + .build(); + reporter.report(commitReport); + + // Wait so PeriodicMetricReader exports at least once before close(). + Thread.sleep(flushWaitMs); + } finally { + reporter.close(); + meterProvider.close(); + GlobalOpenTelemetry.resetForTest(); + } + } + + private static MetricExporter buildExporter(String protocol, String endpoint, String headers) { + if ("grpc".equals(protocol)) { + OtlpGrpcMetricExporterBuilder builder = + OtlpGrpcMetricExporter.builder().setEndpoint(endpoint); + addHeaders(headers, builder::addHeader); + return builder.build(); + } else { + OtlpHttpMetricExporterBuilder builder = + OtlpHttpMetricExporter.builder().setEndpoint(endpoint); + addHeaders(headers, builder::addHeader); + return builder.build(); + } + } + + private static void addHeaders( + String headers, java.util.function.BiConsumer<String, String> add) { + if (headers == null || headers.isEmpty()) { + return; + } + for (String pair : headers.split(",")) { + int eq = pair.indexOf('='); + if (eq > 0) { + add.accept(pair.substring(0, eq).trim(), pair.substring(eq + 1).trim()); + } + } + } + + private static String requireEnv(String name) { + String value = System.getenv(name); + if (value == null || value.isEmpty()) { + throw new IllegalStateException("Missing env var: " + name); + } + return value; + } + + private static String envOrDefault(String name, String fallback) { + String value = System.getenv(name); + return (value == null || value.isEmpty()) ? fallback : value; Review Comment: We could use `Strings.isNullOrEmpty` method here. ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelMetricsReporter.java: ########## @@ -0,0 +1,226 @@ +/* + * 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.iceberg.metrics; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.time.Duration; +import java.util.Collection; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestOtelMetricsReporter { + + private InMemoryMetricReader metricReader; + private SdkMeterProvider meterProvider; + private OpenTelemetrySdk openTelemetry; Review Comment: This filed can be converted to a local variable. ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelEndpointSmoke.java: ########## @@ -0,0 +1,181 @@ +/* + * 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.iceberg.metrics; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.resources.Resource; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; + +/** + * Vendor-neutral E2E smoke test for {@link OtelMetricsReporter}. Builds an {@link + * OpenTelemetrySdk}, registers it as the global SDK, then exports synthetic ScanReport and + * CommitReport against any OTLP-compatible backend (e.g. ADOT Collector, Databricks Zerobus, + * Datadog OTLP, Grafana Cloud OTLP). Only runs when {@code OTEL_SMOKE_ENABLED=true}. + * + * <p>Required env vars when enabled: + * + * <ul> + * <li>{@code OTEL_SMOKE_ENDPOINT} — full OTLP endpoint URL + * <li>{@code OTEL_SMOKE_PROTOCOL} — {@code grpc} or {@code http/protobuf} + * </ul> + * + * <p>Optional env vars: + * + * <ul> + * <li>{@code OTEL_SMOKE_HEADERS} — comma-separated {@code key=value} pairs (e.g. for bearer auth: + * {@code Authorization=Bearer <token>}) + * <li>{@code OTEL_SMOKE_SERVICE_NAME} — defaults to {@code iceberg-smoke-test} + * <li>{@code OTEL_SMOKE_EXPORT_INTERVAL_MS} — defaults to {@code 2000} + * <li>{@code OTEL_SMOKE_FLUSH_WAIT_MS} — sleep before close, defaults to {@code 5000} + * </ul> + */ +@EnabledIfEnvironmentVariable(named = "OTEL_SMOKE_ENABLED", matches = "true") +public class TestOtelEndpointSmoke { + + @Test + public void exportToOtlpEndpoint() throws Exception { Review Comment: This test appears to be flawed. It passes even when I provide a random endpoint, such as `http://localhost:8080`. ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelEndpointSmoke.java: ########## @@ -0,0 +1,181 @@ +/* + * 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.iceberg.metrics; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.resources.Resource; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; + +/** + * Vendor-neutral E2E smoke test for {@link OtelMetricsReporter}. Builds an {@link + * OpenTelemetrySdk}, registers it as the global SDK, then exports synthetic ScanReport and + * CommitReport against any OTLP-compatible backend (e.g. ADOT Collector, Databricks Zerobus, + * Datadog OTLP, Grafana Cloud OTLP). Only runs when {@code OTEL_SMOKE_ENABLED=true}. + * + * <p>Required env vars when enabled: + * + * <ul> + * <li>{@code OTEL_SMOKE_ENDPOINT} — full OTLP endpoint URL + * <li>{@code OTEL_SMOKE_PROTOCOL} — {@code grpc} or {@code http/protobuf} + * </ul> + * + * <p>Optional env vars: + * + * <ul> + * <li>{@code OTEL_SMOKE_HEADERS} — comma-separated {@code key=value} pairs (e.g. for bearer auth: + * {@code Authorization=Bearer <token>}) + * <li>{@code OTEL_SMOKE_SERVICE_NAME} — defaults to {@code iceberg-smoke-test} + * <li>{@code OTEL_SMOKE_EXPORT_INTERVAL_MS} — defaults to {@code 2000} + * <li>{@code OTEL_SMOKE_FLUSH_WAIT_MS} — sleep before close, defaults to {@code 5000} + * </ul> + */ +@EnabledIfEnvironmentVariable(named = "OTEL_SMOKE_ENABLED", matches = "true") +public class TestOtelEndpointSmoke { + + @Test + public void exportToOtlpEndpoint() throws Exception { + String endpoint = requireEnv("OTEL_SMOKE_ENDPOINT"); + String protocol = requireEnv("OTEL_SMOKE_PROTOCOL"); + String headers = System.getenv("OTEL_SMOKE_HEADERS"); + String serviceName = envOrDefault("OTEL_SMOKE_SERVICE_NAME", "iceberg-smoke-test"); + long exportIntervalMs = Long.parseLong(envOrDefault("OTEL_SMOKE_EXPORT_INTERVAL_MS", "2000")); + long flushWaitMs = Long.parseLong(envOrDefault("OTEL_SMOKE_FLUSH_WAIT_MS", "5000")); + + GlobalOpenTelemetry.resetForTest(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .setResource(Resource.getDefault().toBuilder().put("service.name", serviceName).build()) + .registerMetricReader( + PeriodicMetricReader.builder(buildExporter(protocol, endpoint, headers)) + .setInterval(Duration.ofMillis(exportIntervalMs)) + .build()) + .build(); + OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().setMeterProvider(meterProvider).build(); + GlobalOpenTelemetry.set(sdk); + + OtelMetricsReporter reporter = new OtelMetricsReporter(); + try { + reporter.initialize(ImmutableMap.of()); + + ScanReport scanReport = + ImmutableScanReport.builder() + .tableName("smoke.test_table") + .snapshotId(1001L) + .filter(Expressions.alwaysTrue()) + .schemaId(1) + .projectedFieldIds(ImmutableList.of(1, 2)) + .projectedFieldNames(ImmutableList.of("id", "data")) + .scanMetrics( + ImmutableScanMetricsResult.builder() + .totalPlanningDuration( + TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(123), 1)) + .resultDataFiles(CounterResult.of(Unit.COUNT, 7)) + .resultDeleteFiles(CounterResult.of(Unit.COUNT, 1)) + .scannedDataManifests(CounterResult.of(Unit.COUNT, 3)) + .skippedDataManifests(CounterResult.of(Unit.COUNT, 0)) + .totalFileSizeInBytes(CounterResult.of(Unit.BYTES, 4_096_000L)) + .build()) + .metadata(ImmutableMap.of("env", "smoke")) + .build(); + reporter.report(scanReport); + + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("smoke.test_table") + .snapshotId(1002L) + .sequenceNumber(2L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .totalDuration( + TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(231), 1)) + .attempts(CounterResult.of(Unit.COUNT, 1)) + .addedDataFiles(CounterResult.of(Unit.COUNT, 4)) + .removedDataFiles(CounterResult.of(Unit.COUNT, 0)) + .addedRecords(CounterResult.of(Unit.COUNT, 12345)) + .addedFilesSizeInBytes(CounterResult.of(Unit.BYTES, 2_048_000L)) + .build()) + .metadata(ImmutableMap.of("env", "smoke")) + .build(); + reporter.report(commitReport); + + // Wait so PeriodicMetricReader exports at least once before close(). + Thread.sleep(flushWaitMs); + } finally { + reporter.close(); + meterProvider.close(); + GlobalOpenTelemetry.resetForTest(); + } + } + + private static MetricExporter buildExporter(String protocol, String endpoint, String headers) { + if ("grpc".equals(protocol)) { + OtlpGrpcMetricExporterBuilder builder = + OtlpGrpcMetricExporter.builder().setEndpoint(endpoint); + addHeaders(headers, builder::addHeader); + return builder.build(); + } else { + OtlpHttpMetricExporterBuilder builder = + OtlpHttpMetricExporter.builder().setEndpoint(endpoint); + addHeaders(headers, builder::addHeader); + return builder.build(); + } + } + + private static void addHeaders( + String headers, java.util.function.BiConsumer<String, String> add) { + if (headers == null || headers.isEmpty()) { + return; + } + for (String pair : headers.split(",")) { + int eq = pair.indexOf('='); + if (eq > 0) { + add.accept(pair.substring(0, eq).trim(), pair.substring(eq + 1).trim()); + } + } + } + + private static String requireEnv(String name) { + String value = System.getenv(name); + if (value == null || value.isEmpty()) { + throw new IllegalStateException("Missing env var: " + name); + } Review Comment: We could use a helper method in Preconditions: ```java Preconditions.checkState(!Strings.isNullOrEmpty(value), "Missing env var: ", name); ``` ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelMetricsReporter.java: ########## @@ -0,0 +1,226 @@ +/* + * 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.iceberg.metrics; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.time.Duration; +import java.util.Collection; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestOtelMetricsReporter { + + private InMemoryMetricReader metricReader; + private SdkMeterProvider meterProvider; + private OpenTelemetrySdk openTelemetry; + private OtelMetricsReporter reporter; + + @BeforeEach + public void before() { + metricReader = InMemoryMetricReader.create(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(metricReader).build(); + openTelemetry = OpenTelemetrySdk.builder().setMeterProvider(meterProvider).build(); + reporter = new OtelMetricsReporter(openTelemetry); + } + + @AfterEach + public void after() { + if (meterProvider != null) { + meterProvider.close(); + } + } + + @Test + public void testScanReportMetrics() { + ScanReport scanReport = + ImmutableScanReport.builder() + .tableName("test_db.test_table") + .snapshotId(42L) + .filter(Expressions.alwaysTrue()) + .schemaId(1) + .projectedFieldIds(ImmutableList.of(1, 2, 3)) + .projectedFieldNames(ImmutableList.of("id", "name", "value")) + .scanMetrics( + ImmutableScanMetricsResult.builder() + .totalPlanningDuration( + TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(150), 1)) + .resultDataFiles(CounterResult.of(Unit.COUNT, 10)) + .resultDeleteFiles(CounterResult.of(Unit.COUNT, 2)) + .scannedDataManifests(CounterResult.of(Unit.COUNT, 5)) + .skippedDataManifests(CounterResult.of(Unit.COUNT, 3)) + .totalFileSizeInBytes(CounterResult.of(Unit.BYTES, 1024000)) + .build()) + .metadata(ImmutableMap.of()) + .build(); + + reporter.report(scanReport); + + Collection<MetricData> metrics = metricReader.collectAllMetrics(); + assertThat(metrics).isNotEmpty(); + + assertMetricExists(metrics, "iceberg.scan.planning.duration"); + assertMetricExists(metrics, "iceberg.scan.result.data_files"); + assertMetricExists(metrics, "iceberg.scan.result.delete_files"); + assertMetricExists(metrics, "iceberg.scan.data_manifests.scanned"); + assertMetricExists(metrics, "iceberg.scan.data_manifests.skipped"); + assertMetricExists(metrics, "iceberg.scan.file_size.bytes"); + + assertSumValue(metrics, "iceberg.scan.result.data_files", 10); + assertSumValue(metrics, "iceberg.scan.result.delete_files", 2); + assertSumValue(metrics, "iceberg.scan.data_manifests.scanned", 5); + assertSumValue(metrics, "iceberg.scan.data_manifests.skipped", 3); + assertSumValue(metrics, "iceberg.scan.file_size.bytes", 1024000); + } + + @Test + public void testCommitReportMetrics() { + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("test_db.test_table") + .snapshotId(43L) + .sequenceNumber(1L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .totalDuration(TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(200), 1)) + .attempts(CounterResult.of(Unit.COUNT, 1)) + .addedDataFiles(CounterResult.of(Unit.COUNT, 5)) + .removedDataFiles(CounterResult.of(Unit.COUNT, 0)) + .addedRecords(CounterResult.of(Unit.COUNT, 1000)) + .addedFilesSizeInBytes(CounterResult.of(Unit.BYTES, 512000)) + .build()) + .metadata(ImmutableMap.of()) + .build(); + + reporter.report(commitReport); + + Collection<MetricData> metrics = metricReader.collectAllMetrics(); + assertThat(metrics).isNotEmpty(); + + assertMetricExists(metrics, "iceberg.commit.duration"); + assertMetricExists(metrics, "iceberg.commit.attempts"); + assertMetricExists(metrics, "iceberg.commit.data_files.added"); + assertMetricExists(metrics, "iceberg.commit.records.added"); + assertMetricExists(metrics, "iceberg.commit.file_size.added_bytes"); + + assertSumValue(metrics, "iceberg.commit.attempts", 1); + assertSumValue(metrics, "iceberg.commit.data_files.added", 5); + assertSumValue(metrics, "iceberg.commit.records.added", 1000); + assertSumValue(metrics, "iceberg.commit.file_size.added_bytes", 512000); + } + + @Test + public void testNullMetricsAreHandled() { + ScanReport scanReport = + ImmutableScanReport.builder() + .tableName("test_db.test_table") + .snapshotId(44L) + .filter(Expressions.alwaysTrue()) + .schemaId(1) + .projectedFieldIds(ImmutableList.of()) + .projectedFieldNames(ImmutableList.of()) + .scanMetrics(ImmutableScanMetricsResult.builder().build()) + .metadata(ImmutableMap.of()) + .build(); + + reporter.report(scanReport); + + Collection<MetricData> metrics = metricReader.collectAllMetrics(); + assertThat(metrics).isEmpty(); + } + + @Test + public void testMultipleReports() { + for (int i = 0; i < 3; i++) { + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("test_db.test_table") + .snapshotId(50L + i) + .sequenceNumber(i + 1L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .attempts(CounterResult.of(Unit.COUNT, 1)) + .addedDataFiles(CounterResult.of(Unit.COUNT, 10)) + .build()) + .metadata(ImmutableMap.of()) + .build(); + reporter.report(commitReport); + } + + Collection<MetricData> metrics = metricReader.collectAllMetrics(); + assertSumValue(metrics, "iceberg.commit.data_files.added", 30); + assertSumValue(metrics, "iceberg.commit.attempts", 3); + } + + @Test + public void testInitializeFallsBackToGlobalOpenTelemetry() { + // No global SDK registered → GlobalOpenTelemetry returns no-op; init must not throw and + // subsequent reports must be silently dropped. + OtelMetricsReporter noopReporter = new OtelMetricsReporter(); + noopReporter.initialize(ImmutableMap.of()); + + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("test_db.test_table") + .snapshotId(60L) + .sequenceNumber(1L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .attempts(CounterResult.of(Unit.COUNT, 1)) + .build()) + .metadata(ImmutableMap.of()) + .build(); + noopReporter.report(commitReport); + noopReporter.close(); + } + + private static void assertMetricExists(Collection<MetricData> metrics, String name) { + assertThat(metrics.stream().anyMatch(m -> m.getName().equals(name))) + .as("Expected metric '%s' to exist", name) + .isTrue(); + } + + private static void assertSumValue( + Collection<MetricData> metrics, String name, long expectedValue) { + MetricData metric = + metrics.stream() + .filter(m -> m.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new AssertionError("Metric not found: " + name)); + + long actualSum = + metric.getLongSumData().getPoints().stream().mapToLong(p -> p.getValue()).sum(); Review Comment: We could use a method reference in mapToLong: ```java LongPointData::getValue ``` ########## core/src/test/java/org/apache/iceberg/metrics/TestOtelMetricsReporter.java: ########## @@ -0,0 +1,226 @@ +/* + * 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.iceberg.metrics; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.time.Duration; +import java.util.Collection; +import java.util.concurrent.TimeUnit; +import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.metrics.MetricsContext.Unit; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestOtelMetricsReporter { + + private InMemoryMetricReader metricReader; + private SdkMeterProvider meterProvider; + private OpenTelemetrySdk openTelemetry; + private OtelMetricsReporter reporter; + + @BeforeEach + public void before() { + metricReader = InMemoryMetricReader.create(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(metricReader).build(); + openTelemetry = OpenTelemetrySdk.builder().setMeterProvider(meterProvider).build(); + reporter = new OtelMetricsReporter(openTelemetry); + } + + @AfterEach + public void after() { + if (meterProvider != null) { + meterProvider.close(); + } + } + + @Test + public void testScanReportMetrics() { + ScanReport scanReport = + ImmutableScanReport.builder() + .tableName("test_db.test_table") + .snapshotId(42L) + .filter(Expressions.alwaysTrue()) + .schemaId(1) + .projectedFieldIds(ImmutableList.of(1, 2, 3)) + .projectedFieldNames(ImmutableList.of("id", "name", "value")) + .scanMetrics( + ImmutableScanMetricsResult.builder() + .totalPlanningDuration( + TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(150), 1)) + .resultDataFiles(CounterResult.of(Unit.COUNT, 10)) + .resultDeleteFiles(CounterResult.of(Unit.COUNT, 2)) + .scannedDataManifests(CounterResult.of(Unit.COUNT, 5)) + .skippedDataManifests(CounterResult.of(Unit.COUNT, 3)) + .totalFileSizeInBytes(CounterResult.of(Unit.BYTES, 1024000)) + .build()) + .metadata(ImmutableMap.of()) + .build(); + + reporter.report(scanReport); + + Collection<MetricData> metrics = metricReader.collectAllMetrics(); + assertThat(metrics).isNotEmpty(); + + assertMetricExists(metrics, "iceberg.scan.planning.duration"); + assertMetricExists(metrics, "iceberg.scan.result.data_files"); + assertMetricExists(metrics, "iceberg.scan.result.delete_files"); + assertMetricExists(metrics, "iceberg.scan.data_manifests.scanned"); + assertMetricExists(metrics, "iceberg.scan.data_manifests.skipped"); + assertMetricExists(metrics, "iceberg.scan.file_size.bytes"); + + assertSumValue(metrics, "iceberg.scan.result.data_files", 10); + assertSumValue(metrics, "iceberg.scan.result.delete_files", 2); + assertSumValue(metrics, "iceberg.scan.data_manifests.scanned", 5); + assertSumValue(metrics, "iceberg.scan.data_manifests.skipped", 3); + assertSumValue(metrics, "iceberg.scan.file_size.bytes", 1024000); + } + + @Test + public void testCommitReportMetrics() { + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("test_db.test_table") + .snapshotId(43L) + .sequenceNumber(1L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .totalDuration(TimerResult.of(TimeUnit.NANOSECONDS, Duration.ofMillis(200), 1)) + .attempts(CounterResult.of(Unit.COUNT, 1)) + .addedDataFiles(CounterResult.of(Unit.COUNT, 5)) + .removedDataFiles(CounterResult.of(Unit.COUNT, 0)) + .addedRecords(CounterResult.of(Unit.COUNT, 1000)) + .addedFilesSizeInBytes(CounterResult.of(Unit.BYTES, 512000)) + .build()) + .metadata(ImmutableMap.of()) + .build(); + + reporter.report(commitReport); + + Collection<MetricData> metrics = metricReader.collectAllMetrics(); + assertThat(metrics).isNotEmpty(); + + assertMetricExists(metrics, "iceberg.commit.duration"); + assertMetricExists(metrics, "iceberg.commit.attempts"); + assertMetricExists(metrics, "iceberg.commit.data_files.added"); + assertMetricExists(metrics, "iceberg.commit.records.added"); + assertMetricExists(metrics, "iceberg.commit.file_size.added_bytes"); + + assertSumValue(metrics, "iceberg.commit.attempts", 1); + assertSumValue(metrics, "iceberg.commit.data_files.added", 5); + assertSumValue(metrics, "iceberg.commit.records.added", 1000); + assertSumValue(metrics, "iceberg.commit.file_size.added_bytes", 512000); + } + + @Test + public void testNullMetricsAreHandled() { + ScanReport scanReport = + ImmutableScanReport.builder() + .tableName("test_db.test_table") + .snapshotId(44L) + .filter(Expressions.alwaysTrue()) + .schemaId(1) + .projectedFieldIds(ImmutableList.of()) + .projectedFieldNames(ImmutableList.of()) + .scanMetrics(ImmutableScanMetricsResult.builder().build()) + .metadata(ImmutableMap.of()) + .build(); + + reporter.report(scanReport); + + Collection<MetricData> metrics = metricReader.collectAllMetrics(); + assertThat(metrics).isEmpty(); + } + + @Test + public void testMultipleReports() { + for (int i = 0; i < 3; i++) { + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("test_db.test_table") + .snapshotId(50L + i) + .sequenceNumber(i + 1L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .attempts(CounterResult.of(Unit.COUNT, 1)) + .addedDataFiles(CounterResult.of(Unit.COUNT, 10)) + .build()) + .metadata(ImmutableMap.of()) + .build(); + reporter.report(commitReport); + } + + Collection<MetricData> metrics = metricReader.collectAllMetrics(); + assertSumValue(metrics, "iceberg.commit.data_files.added", 30); + assertSumValue(metrics, "iceberg.commit.attempts", 3); + } + + @Test + public void testInitializeFallsBackToGlobalOpenTelemetry() { + // No global SDK registered → GlobalOpenTelemetry returns no-op; init must not throw and + // subsequent reports must be silently dropped. + OtelMetricsReporter noopReporter = new OtelMetricsReporter(); + noopReporter.initialize(ImmutableMap.of()); + + CommitReport commitReport = + ImmutableCommitReport.builder() + .tableName("test_db.test_table") + .snapshotId(60L) + .sequenceNumber(1L) + .operation("append") + .commitMetrics( + ImmutableCommitMetricsResult.builder() + .attempts(CounterResult.of(Unit.COUNT, 1)) + .build()) + .metadata(ImmutableMap.of()) + .build(); + noopReporter.report(commitReport); + noopReporter.close(); + } + + private static void assertMetricExists(Collection<MetricData> metrics, String name) { + assertThat(metrics.stream().anyMatch(m -> m.getName().equals(name))) + .as("Expected metric '%s' to exist", name) + .isTrue(); Review Comment: We should try to avoid filtering on the caller's side as much as possible because it makes the failure message less helpful. ```java assertThat(metrics).extracting(MetricData::getName).contains(name); ``` -- 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]
