diff --git a/docs/docs/maintenance/metrics.md b/docs/docs/maintenance/metrics.md index bab207420538..5c4e9583def8 100644 --- a/docs/docs/maintenance/metrics.md +++ b/docs/docs/maintenance/metrics.md @@ -52,7 +52,7 @@ From Flink Web-UI, go to the committer operator's metrics, it's shown as: :::info 1. Please refer to [System Scope](https://nightlies.apache.org/flink/flink-docs-master/docs/ops/metrics/#system-scope) to understand Flink `scope` -2. Scan metrics are only supported by Flink versions >= 1.18 +2. Scan metrics in the JobManager source enumerator scope are supported by Flink versions >= 1.18. ::: @@ -66,9 +66,24 @@ From Flink Web-UI, go to the committer operator's metrics, it's shown as: - Scan Metrics + Scan Metrics (Enumerator) <host>.jobmanager.<job_name> - <source_operator_name>.coordinator. enumerator.paimon.table.<table_name>.scan + <source_operator_name>.coordinator.enumerator.paimon.table.<table_name>.scan + + + Scan Metrics (Monitor) + <host>.taskmanager.<tm_id>.<job_name>.<monitor_operator_name>.<subtask_index> + paimon.table.<table_name>.scan + + + Scan Metrics (Sink Writer) + <host>.taskmanager.<tm_id>.<job_name>.<writer_operator_name>.<subtask_index> + paimon.table.<table_name>.scan + + + Scan Metrics (Sink Coordinator) + <host>.jobmanager.<job_name> + <writer_operator_name>.coordinator.paimon.table.<table_name>.scan Lookup Metrics @@ -113,6 +128,24 @@ From Flink Web-UI, go to the committer operator's metrics, it's shown as: +When dedicated split generation uses a `Monitor` operator, scan metrics are reported by that operator on +the TaskManager. This includes streaming queries with `consumer-id` and `consumer.mode = 'exactly-once'` +when `source.checkpoint-align.enabled` is disabled. The `last*` gauges describe the last completed scan +and start at zero after a restart, until the next scan completes. + +Sink scan metrics measure manifest scans used to initialize or recover writers. With +`sink.writer-coordinator.enabled = false`, scans are reported by each writer subtask on the TaskManager. +With writer coordination enabled, use the JobManager sink coordinator metrics for the actual scans; +writer subtasks delegate recovery to the coordinator and their local scan metrics are not updated. +The coordinator reports both manifest prefetch scans and scans for individual partition/bucket requests +in the same metric group, including prefetch during startup and metadata refresh. + +For sink scans, `lastScanDuration` and `scanDuration` measure metadata planning in milliseconds: +reading manifest lists and manifests, filtering entries, and merging file metadata. They exclude +index restoration, coordinator RPC waits, and data writes. Measurements update when a scan completes; +the `last*` gauges describe the latest scan, and `scanDuration` records the durations of recent scans. +When initialization skips data file metadata scanning, no scan duration sample is recorded. + ## Choose Metrics for a Task Use these groups to identify the operation to investigate. For tuning options, follow the related guide. @@ -142,12 +175,12 @@ Below is lists of Paimon built-in metrics. They are summarized into types of sca lastScanDuration Gauge - The time it took to complete the last scan. + The time it took to complete the last scan, in milliseconds. scanDuration Histogram - Distributions of the time taken by the last few scans. + Distributions of the time taken by the last few scans, in milliseconds. lastScannedSnapshotId @@ -623,7 +656,8 @@ When using Flink to read and write, Paimon has implemented some key standard Fli :::info -Please note that if you specified `consumer-id` in your streaming query, the level of source metrics should turn into the reader operator, which is behind the `Monitor` operator. +When a query uses separate `Monitor` and `Reader` operators, the source reader metrics above are reported +by the downstream `Reader` operator. Scan metrics are reported by the `Monitor` operator. ::: diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/AbstractFileStoreWrite.java b/paimon-core/src/main/java/org/apache/paimon/operation/AbstractFileStoreWrite.java index 74f5877e1184..2cbd0cfe24e6 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/AbstractFileStoreWrite.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/AbstractFileStoreWrite.java @@ -37,6 +37,7 @@ import org.apache.paimon.memory.MemoryPoolFactory; import org.apache.paimon.metrics.MetricRegistry; import org.apache.paimon.operation.metrics.CompactionMetrics; +import org.apache.paimon.operation.metrics.ScanMetrics; import org.apache.paimon.partition.PartitionTimeExtractor; import org.apache.paimon.table.sink.CommitMessage; import org.apache.paimon.table.sink.CommitMessageImpl; @@ -111,6 +112,7 @@ public abstract class AbstractFileStoreWrite implements FileStoreWrite { protected final SnapshotManager snapshotManager; protected CompactionMetrics compactionMetrics = null; + @Nullable private ScanMetrics scanMetrics; protected final String tableName; private final boolean legacyPartitionName; private final CoreOptions options; @@ -151,6 +153,9 @@ protected AbstractFileStoreWrite( @Override public FileStoreWrite withWriteRestore(WriteRestore writeRestore) { this.restore = writeRestore; + if (scanMetrics != null) { + restore.withMetrics(scanMetrics); + } return this; } @@ -665,6 +670,8 @@ long startingMaxSequenceNumber(long restoredMaxSeqNumber, @Nullable Snapshot lat @Override public FileStoreWrite withMetricRegistry(MetricRegistry metricRegistry) { this.compactionMetrics = new CompactionMetrics(metricRegistry, tableName); + this.scanMetrics = new ScanMetrics(metricRegistry, tableName); + restore.withMetrics(scanMetrics); return this; } diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/FileSystemWriteRestore.java b/paimon-core/src/main/java/org/apache/paimon/operation/FileSystemWriteRestore.java index b203ba761c79..a5c961dc65ba 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/FileSystemWriteRestore.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/FileSystemWriteRestore.java @@ -25,6 +25,7 @@ import org.apache.paimon.index.IndexFileMeta; import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.operation.metrics.ScanMetrics; import org.apache.paimon.utils.SnapshotManager; import javax.annotation.Nullable; @@ -76,6 +77,13 @@ private FileSystemWriteRestore( } } + @Override + public void withMetrics(ScanMetrics scanMetrics) { + if (scan != null) { + scan.withMetrics(scanMetrics); + } + } + @Override public long latestCommittedIdentifier(String user) { return snapshotManager diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/WriteRestore.java b/paimon-core/src/main/java/org/apache/paimon/operation/WriteRestore.java index d594ba11e557..60a702a19653 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/WriteRestore.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/WriteRestore.java @@ -21,6 +21,7 @@ import org.apache.paimon.data.BinaryRow; import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.operation.metrics.ScanMetrics; import javax.annotation.Nullable; @@ -29,6 +30,9 @@ /** Restores data file metadata and indexes for write initialization. */ public interface WriteRestore { + /** Attaches metrics to manifest scans performed by this restore. */ + default void withMetrics(ScanMetrics scanMetrics) {} + long latestCommittedIdentifier(String user); /** Restores data file metadata and the requested indexes for a partition and bucket. */ diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/TableWriteCoordinator.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/TableWriteCoordinator.java index 0323f2a43bb7..f2728dc81ba4 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/TableWriteCoordinator.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/TableWriteCoordinator.java @@ -25,13 +25,17 @@ import org.apache.paimon.index.IndexFileMeta; import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.metrics.MetricRegistry; import org.apache.paimon.operation.FileStoreScan; import org.apache.paimon.operation.WriteRestore; +import org.apache.paimon.operation.metrics.ScanMetrics; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.shade.caffeine2.com.github.benmanes.caffeine.cache.Cache; import org.apache.paimon.shade.caffeine2.com.github.benmanes.caffeine.cache.Caffeine; +import javax.annotation.Nullable; + import java.io.IOException; import java.time.Duration; import java.util.ArrayList; @@ -57,6 +61,7 @@ public class TableWriteCoordinator { private final FileStoreTable table; private final Map latestCommittedIdentifiers; private final FileStoreScan scan; + @Nullable private final ScanMetrics scanMetrics; private final IndexFileHandler indexFileHandler; private final int pageSize; private final boolean prefetchManifests; @@ -65,10 +70,19 @@ public class TableWriteCoordinator { private volatile Snapshot snapshot; public TableWriteCoordinator(FileStoreTable table) { + this(table, null); + } + + public TableWriteCoordinator(FileStoreTable table, @Nullable MetricRegistry metricRegistry) { this.table = table; checkNotNull(table.getManifestCache()); this.latestCommittedIdentifiers = new ConcurrentHashMap<>(); + this.scanMetrics = + metricRegistry == null ? null : new ScanMetrics(metricRegistry, table.name()); this.scan = table.store().newScan(); + if (scanMetrics != null) { + scan.withMetrics(scanMetrics); + } if (table.coreOptions().manifestDeleteFileDropStats()) { scan.dropStats(); } @@ -107,6 +121,9 @@ private synchronized void refresh() { // used so the shared request `scan`'s bucket/partition state never narrows the // warm-up. FileStoreScan prefetchScan = table.store().newScan().withSnapshot(snapshot); + if (scanMetrics != null) { + prefetchScan.withMetrics(scanMetrics); + } if (table.coreOptions().manifestDeleteFileDropStats()) { prefetchScan.dropStats(); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinator.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinator.java index bc1e1b9efb55..1a1f48a326a9 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinator.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinator.java @@ -19,13 +19,16 @@ package org.apache.paimon.flink.sink.coordinator; import org.apache.paimon.CoreOptions; +import org.apache.paimon.flink.metrics.FlinkMetricRegistry; import org.apache.paimon.flink.sink.TableWriteOperator; import org.apache.paimon.fs.Path; +import org.apache.paimon.metrics.MetricRegistry; import org.apache.paimon.options.MemorySize; import org.apache.paimon.options.Options; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.utils.SegmentsCache; +import org.apache.flink.metrics.MetricGroup; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.operators.coordination.CoordinationRequest; import org.apache.flink.runtime.operators.coordination.CoordinationRequestHandler; @@ -33,6 +36,8 @@ import org.apache.flink.runtime.operators.coordination.OperatorCoordinator; import org.apache.flink.runtime.operators.coordination.OperatorEvent; +import javax.annotation.Nullable; + import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -51,6 +56,7 @@ public class WriteOperatorCoordinator implements OperatorCoordinator, CoordinationRequestHandler { private final FileStoreTable table; + @Nullable private final MetricRegistry metricRegistry; private final AtomicLong recoveryGeneration = new AtomicLong(); @@ -61,14 +67,19 @@ public class WriteOperatorCoordinator implements OperatorCoordinator, Coordinati private TableWriteCoordinator coordinator; public WriteOperatorCoordinator(FileStoreTable table) { + this(table, null); + } + + public WriteOperatorCoordinator(FileStoreTable table, @Nullable MetricRegistry metricRegistry) { this.table = table; + this.metricRegistry = metricRegistry; } @Override public void start() throws Exception { executor = createCachedThreadPool(1, "WriteCoordinator"); table.setManifestCache(buildManifestCache(table.coreOptions().toConfiguration())); - coordinator = new TableWriteCoordinator(table); + coordinator = new TableWriteCoordinator(table, metricRegistry); } /** @@ -184,7 +195,9 @@ public OperatorID getOperatorId() { @Override public OperatorCoordinator create(Context context) { - return new WriteOperatorCoordinator(table); + MetricGroup metricGroup = context.metricGroup(); + return new WriteOperatorCoordinator( + table, metricGroup == null ? null : new FlinkMetricRegistry(metricGroup)); } } } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java index 1b1ad2392fe1..ba3c39cf69c0 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java @@ -20,6 +20,7 @@ import org.apache.paimon.flink.FlinkConnectorOptions; import org.apache.paimon.flink.NestedProjectedRowData; +import org.apache.paimon.flink.metrics.FlinkMetricRegistry; import org.apache.paimon.flink.source.AbstractNonCoordinatedSource; import org.apache.paimon.flink.source.AbstractNonCoordinatedSourceReader; import org.apache.paimon.flink.source.NoOpEnumState; @@ -27,6 +28,7 @@ import org.apache.paimon.flink.source.SimpleSourceSplit; import org.apache.paimon.flink.source.SplitListState; import org.apache.paimon.flink.utils.JavaTypeInfo; +import org.apache.paimon.metrics.MetricRegistry; import org.apache.paimon.options.Options; import org.apache.paimon.table.Table; import org.apache.paimon.table.sink.ChannelComputer; @@ -133,7 +135,7 @@ public Boundedness getBoundedness() { @Override public SourceReader createReader( SourceReaderContext sourceReaderContext) throws Exception { - return new Reader(); + return new Reader(new FlinkMetricRegistry(sourceReaderContext.metricGroup())); } private class Reader extends AbstractNonCoordinatedSourceReader { @@ -156,6 +158,11 @@ private class Reader extends AbstractNonCoordinatedSourceReader { private final Deque inFlightNextSnapshots = new ArrayDeque<>(); private CompletableFuture availableFuture = CompletableFuture.completedFuture(null); + private Reader(MetricRegistry registry) { + TableScan activeScan = isBounded ? batchScan : scan; + activeScan.withMetricRegistry(registry); + } + @Override public void notifyCheckpointComplete(long checkpointId) { NavigableMap nextSnapshots = diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/FileStoreSinkMetricsTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/FileStoreSinkMetricsTest.java new file mode 100644 index 000000000000..ad77eeb05670 --- /dev/null +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/FileStoreSinkMetricsTest.java @@ -0,0 +1,131 @@ +/* + * 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.paimon.flink.sink; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.flink.metrics.FlinkMetricRegistry; +import org.apache.paimon.operation.FileSystemWriteRestore; +import org.apache.paimon.schema.Schema; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.TableTestBase; +import org.apache.paimon.table.sink.TableWriteImpl; +import org.apache.paimon.types.DataTypes; + +import org.apache.flink.metrics.Gauge; +import org.apache.flink.metrics.Histogram; +import org.apache.flink.metrics.testutils.MetricListener; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Tests for sink manifest scan metrics. */ +class FileStoreSinkMetricsTest extends TableTestBase { + + @ParameterizedTest + @CsvSource({"false, false", "false, true", "true, false", "true, true"}) + void testWriterRestoreScanMetrics(boolean primaryKey, boolean replaceRestore) throws Exception { + FileStoreTable table = createTable(primaryKey); + write(table, GenericRow.of(1, 10)); + write(table, GenericRow.of(2, 20)); + + MetricListener metrics = new MetricListener(); + try (TableWriteImpl writer = table.newWrite("metrics")) { + writer.withIOManager(ioManager); + writer.withMetricRegistry(new FlinkMetricRegistry(metrics.getMetricGroup())); + if (replaceRestore) { + writer.withWriteRestore( + new FileSystemWriteRestore( + table.coreOptions(), + table.snapshotManager(), + table.store().newScan(), + table.store().newIndexFileHandler())); + } + Histogram duration = scanDuration(metrics, table); + assertThat(duration.getCount()).isZero(); + assertThat(scanGauge(metrics, table, "lastScanDuration").getValue()).isZero(); + + // Creating the partition's writer restores its existing files from the table. + writer.write(GenericRow.of(1, 11)); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(scanGauge(metrics, table, "lastScannedSnapshotId").getValue()).isEqualTo(2L); + assertThat(scanGauge(metrics, table, "lastScannedManifests").getValue()).isEqualTo(1L); + assertThat(scanGauge(metrics, table, "lastScanResultedTableFiles").getValue()) + .isEqualTo(1L); + assertThat(scanGauge(metrics, table, "lastScanDuration").getValue()) + .isGreaterThanOrEqualTo(0L); + + // Further rows for an initialized writer do not perform another restore scan. + writer.write(GenericRow.of(1, 12)); + assertThat(duration.getCount()).isEqualTo(1); + + writer.write(GenericRow.of(2, 21)); + assertThat(duration.getCount()).isEqualTo(2); + assertThat(scanGauge(metrics, table, "lastScannedManifests").getValue()).isEqualTo(1L); + assertThat(scanGauge(metrics, table, "lastScanResultedTableFiles").getValue()) + .isEqualTo(1L); + } + } + + @Test + void testSkippedRestoreDoesNotReportScan() throws Exception { + FileStoreTable table = createTable(true); + write(table, GenericRow.of(1, 10)); + + MetricListener metrics = new MetricListener(); + try (TableWriteImpl writer = table.newWrite("metrics")) { + writer.withIOManager(ioManager); + writer.withMetricRegistry(new FlinkMetricRegistry(metrics.getMetricGroup())); + writer.withIgnorePreviousFiles(true); + writer.write(GenericRow.of(1, 11)); + + assertThat(scanDuration(metrics, table).getCount()).isZero(); + assertThat(scanGauge(metrics, table, "lastScannedSnapshotId").getValue()).isZero(); + assertThat(scanGauge(metrics, table, "lastScanDuration").getValue()).isZero(); + } + } + + private FileStoreTable createTable(boolean primaryKey) throws Exception { + Schema.Builder schema = + Schema.newBuilder() + .column("pt", DataTypes.INT()) + .column("id", DataTypes.INT()) + .partitionKeys("pt") + .option(CoreOptions.BUCKET.key(), "1") + .option(CoreOptions.BUCKET_KEY.key(), "id") + .option(CoreOptions.WRITE_ONLY.key(), "true"); + if (primaryKey) { + schema.primaryKey("pt", "id"); + } + catalog.createTable(identifier(), schema.build(), false); + return getTableDefault(); + } + + private Gauge scanGauge(MetricListener metrics, FileStoreTable table, String name) { + return metrics.getGauge("paimon", "table", table.name(), "scan", name) + .orElseThrow(AssertionError::new); + } + + private Histogram scanDuration(MetricListener metrics, FileStoreTable table) { + return metrics.getHistogram("paimon", "table", table.name(), "scan", "scanDuration") + .orElseThrow(AssertionError::new); + } +} diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/TableWriteCoordinatorTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/TableWriteCoordinatorTest.java index 5ac3333f3af4..f455858976e7 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/TableWriteCoordinatorTest.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/TableWriteCoordinatorTest.java @@ -24,6 +24,7 @@ import org.apache.paimon.catalog.Identifier; import org.apache.paimon.data.GenericRow; import org.apache.paimon.flink.FlinkConnectorOptions; +import org.apache.paimon.flink.metrics.FlinkMetricRegistry; import org.apache.paimon.fs.Path; import org.apache.paimon.index.GlobalIndexMeta; import org.apache.paimon.index.IndexFileMeta; @@ -44,6 +45,7 @@ import org.apache.paimon.types.DataTypes; import org.apache.paimon.utils.SegmentsCache; +import org.apache.flink.metrics.testutils.MetricListener; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway; import org.apache.flink.runtime.operators.coordination.CoordinationRequest; @@ -103,7 +105,9 @@ public void testCoordinatedRestoreHashIndex(boolean scanDataFileMetas, boolean l FileStoreScan scan = spy(store.newScan()); doReturn(scan).when(store).newScan(); doReturn(store).when(table).store(); - TableWriteCoordinator coordinator = new TableWriteCoordinator(table); + MetricListener metrics = new MetricListener(); + TableWriteCoordinator coordinator = + new TableWriteCoordinator(table, new FlinkMetricRegistry(metrics.getMetricGroup())); OperatorID operatorID = new OperatorID(); TaskOperatorEventGateway gateway = mock(TaskOperatorEventGateway.class); when(gateway.sendRequestToCoordinator(eq(operatorID), any())) @@ -135,6 +139,12 @@ public void testCoordinatedRestoreHashIndex(boolean scanDataFileMetas, boolean l assertThat(restored.totalBuckets()).isNull(); } verify(scan, times(scanDataFileMetas ? 1 : 0)).plan(); + assertThat( + metrics.getHistogram( + "paimon", "table", table.name(), "scan", "scanDuration") + .orElseThrow(AssertionError::new) + .getCount()) + .isEqualTo(scanDataFileMetas ? 1 : 0); verify(gateway, atLeast(2)).sendRequestToCoordinator(eq(operatorID), any()); } diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinatorTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinatorTest.java index 3b84a00b84ba..d50f3c4df2de 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinatorTest.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinatorTest.java @@ -22,6 +22,7 @@ import org.apache.paimon.Snapshot; import org.apache.paimon.data.GenericRow; import org.apache.paimon.data.InternalRow; +import org.apache.paimon.flink.FlinkConnectorOptions; import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.schema.Schema; import org.apache.paimon.table.FileStoreTable; @@ -31,14 +32,20 @@ import org.apache.paimon.table.sink.StreamWriteBuilder; import org.apache.paimon.types.DataTypes; +import org.apache.flink.metrics.Histogram; +import org.apache.flink.metrics.groups.OperatorCoordinatorMetricGroup; +import org.apache.flink.metrics.testutils.MetricListener; +import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.operators.coordination.CoordinationRequest; import org.apache.flink.runtime.operators.coordination.CoordinationResponse; +import org.apache.flink.runtime.operators.coordination.OperatorCoordinator; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.io.ByteArrayOutputStream; +import java.util.Collections; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -55,12 +62,61 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; /** Tests for refreshing writer metadata after coordinator recovery. */ @Timeout(60) class WriteOperatorCoordinatorTest extends TableTestBase { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testScanMetricsIncludePrefetchAndRecovery(boolean prefetch) throws Exception { + FileStoreTable table = + createTable(128) + .copy( + Collections.singletonMap( + FlinkConnectorOptions + .SINK_WRITER_COORDINATOR_PREFETCH_MANIFESTS + .key(), + Boolean.toString(prefetch))); + commit(table, 1, GenericRow.of(1L, 3)); + commit(table, 2, GenericRow.of(2L, 4)); + + MetricListener metrics = new MetricListener(); + OperatorCoordinatorMetricGroup group = mock(OperatorCoordinatorMetricGroup.class); + when(group.addGroup("paimon")).thenReturn(metrics.getMetricGroup().addGroup("paimon")); + OperatorCoordinator.Context context = mock(OperatorCoordinator.Context.class); + when(context.metricGroup()).thenReturn(group); + + try (WriteOperatorCoordinator coordinator = + (WriteOperatorCoordinator) + new WriteOperatorCoordinator.Provider(new OperatorID(), table) + .create(context)) { + coordinator.start(); + Histogram duration = + metrics.getHistogram("paimon", "table", table.name(), "scan", "scanDuration") + .orElseThrow(AssertionError::new); + assertThat(duration.getCount()).isEqualTo(prefetch ? 1 : 0); + if (prefetch) { + assertThat(scanGauge(metrics, table, "lastScanResultedTableFiles")).isEqualTo(2L); + } + + // A paged restore response still performs just one metadata scan. + assertThat(scan(coordinator).extractDataFiles()).hasSize(2); + assertThat(duration.getCount()).isEqualTo(prefetch ? 2 : 1); + assertThat(scanGauge(metrics, table, "lastScannedManifests")).isEqualTo(2L); + assertThat(scanGauge(metrics, table, "lastScanDuration")).isGreaterThanOrEqualTo(0L); + + commit(table, 3, GenericRow.of(3L, 5)); + coordinator.subtaskReset(0, 2); + assertThat(scan(coordinator).snapshot().id()).isEqualTo(3L); + assertThat(duration.getCount()).isEqualTo(prefetch ? 4 : 2); + assertThat(scanGauge(metrics, table, "lastScannedSnapshotId")).isEqualTo(3L); + } + } + @ParameterizedTest @ValueSource(booleans = {true, false}) void testRecoveryRefreshesFilesAndLatestIdentifier(boolean globalRecovery) throws Exception { @@ -212,6 +268,12 @@ void testResetDuringRefreshIsNotLost() throws Exception { } } + private long scanGauge(MetricListener metrics, FileStoreTable table, String name) { + return metrics.getGauge("paimon", "table", table.name(), "scan", name) + .orElseThrow(AssertionError::new) + .getValue(); + } + private FileStoreTable createTable(int pageSize) throws Exception { Schema schema = Schema.newBuilder() diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/FileStoreSourceMetricsTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/FileStoreSourceMetricsTest.java index b7e495f389db..6a0fe7292859 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/FileStoreSourceMetricsTest.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/FileStoreSourceMetricsTest.java @@ -20,6 +20,7 @@ import org.apache.paimon.data.GenericRow; import org.apache.paimon.flink.FlinkConnectorOptions; +import org.apache.paimon.flink.source.operator.MonitorSource; import org.apache.paimon.flink.utils.TestingMetricUtils; import org.apache.paimon.fs.FileIO; import org.apache.paimon.fs.Path; @@ -32,17 +33,26 @@ import org.apache.paimon.table.FileStoreTableFactory; import org.apache.paimon.table.sink.InnerTableWrite; import org.apache.paimon.table.sink.TableCommitImpl; +import org.apache.paimon.table.source.Split; import org.apache.paimon.types.DataTypes; import org.apache.flink.api.common.JobID; +import org.apache.flink.api.connector.source.SourceReader; +import org.apache.flink.configuration.Configuration; +import org.apache.flink.connector.testutils.source.reader.TestingReaderContext; +import org.apache.flink.connector.testutils.source.reader.TestingReaderOutput; import org.apache.flink.connector.testutils.source.reader.TestingSplitEnumeratorContext; +import org.apache.flink.core.io.InputStatus; import org.apache.flink.metrics.Gauge; +import org.apache.flink.metrics.Histogram; import org.apache.flink.metrics.MetricGroup; import org.apache.flink.metrics.groups.SplitEnumeratorMetricGroup; +import org.apache.flink.metrics.testutils.MetricListener; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.metrics.MetricRegistry; import org.apache.flink.runtime.metrics.groups.InternalOperatorCoordinatorMetricGroup; +import org.apache.flink.runtime.metrics.groups.InternalSourceReaderMetricGroup; import org.apache.flink.runtime.metrics.groups.InternalSplitEnumeratorMetricGroup; import org.apache.flink.runtime.metrics.groups.JobManagerMetricGroup; import org.apache.flink.runtime.metrics.groups.JobManagerOperatorMetricGroup; @@ -53,6 +63,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; /** Tests for file store sources with metrics. */ @@ -147,6 +159,88 @@ public void continuousFileStoreSourceScanMetricsTest() throws Exception { .isEqualTo(1L); } + @Test + public void monitorSourceScanMetricsTest() throws Exception { + writeOnce(table); + MetricListener metrics = new MetricListener(); + MonitorSource source = new MonitorSource(table.newReadBuilder(), 10, false, false); + try (SourceReader reader = + source.createReader(readerContext(metrics))) { + assertThat(scanGauge(metrics, "lastScannedSnapshotId").getValue()).isZero(); + assertThat(scanGauge(metrics, "lastScannedManifests").getValue()).isZero(); + assertThat(scanDuration(metrics).getCount()).isZero(); + + TestingReaderOutput output = new TestingReaderOutput<>(); + reader.start(); + reader.pollNext(output); + assertThat(scanGauge(metrics, "lastScannedSnapshotId").getValue()).isEqualTo(1L); + assertThat(scanGauge(metrics, "lastScannedManifests").getValue()).isEqualTo(1L); + assertThat(scanGauge(metrics, "lastScanResultedTableFiles").getValue()).isEqualTo(1L); + assertThat(scanGauge(metrics, "lastScanDuration").getValue()) + .isGreaterThanOrEqualTo(0L); + assertThat(scanDuration(metrics).getCount()).isEqualTo(1); + + writeAgain(table); + reader.pollNext(output); + assertThat(scanGauge(metrics, "lastScannedSnapshotId").getValue()).isEqualTo(2L); + assertThat(scanGauge(metrics, "lastScannedManifests").getValue()).isEqualTo(1L); + assertThat(scanGauge(metrics, "lastScanResultedTableFiles").getValue()).isEqualTo(1L); + assertThat(scanDuration(metrics).getCount()).isEqualTo(2); + assertThat(output.getEmittedRecords()).hasSize(2); + } + } + + @Test + public void boundedMonitorSourceScanMetricsTest() throws Exception { + writeOnce(table); + writeAgain(table); + MetricListener metrics = new MetricListener(); + MonitorSource source = new MonitorSource(table.newReadBuilder(), 10, false, true); + try (SourceReader reader = + source.createReader(readerContext(metrics))) { + reader.start(); + TestingReaderOutput output = new TestingReaderOutput<>(); + assertThat(reader.pollNext(output)).isEqualTo(InputStatus.END_OF_INPUT); + assertThat(scanGauge(metrics, "lastScannedSnapshotId").getValue()).isEqualTo(2L); + assertThat(scanGauge(metrics, "lastScannedManifests").getValue()).isEqualTo(2L); + assertThat(scanGauge(metrics, "lastScanResultedTableFiles").getValue()).isEqualTo(2L); + assertThat(scanDuration(metrics).getCount()).isEqualTo(1); + assertThat(output.getEmittedRecords()).isNotEmpty(); + } + } + + @Test + public void restoredMonitorSourceScanMetricsTest() throws Exception { + writeOnce(table); + List checkpoint; + MonitorSource source = new MonitorSource(table.newReadBuilder(), 10, false, false); + try (SourceReader reader = + source.createReader(readerContext(new MetricListener()))) { + reader.start(); + reader.pollNext(new TestingReaderOutput<>()); + checkpoint = reader.snapshotState(1L); + } + + writeAgain(table); + MetricListener metrics = new MetricListener(); + MonitorSource restoredSource = new MonitorSource(table.newReadBuilder(), 10, false, false); + try (SourceReader reader = + restoredSource.createReader(readerContext(metrics))) { + reader.addSplits(checkpoint); + reader.start(); + assertThat(scanGauge(metrics, "lastScannedSnapshotId").getValue()).isZero(); + assertThat(scanDuration(metrics).getCount()).isZero(); + + TestingReaderOutput output = new TestingReaderOutput<>(); + reader.pollNext(output); + assertThat(scanGauge(metrics, "lastScannedSnapshotId").getValue()).isEqualTo(2L); + assertThat(scanGauge(metrics, "lastScannedManifests").getValue()).isEqualTo(1L); + assertThat(scanGauge(metrics, "lastScanResultedTableFiles").getValue()).isEqualTo(1L); + assertThat(scanDuration(metrics).getCount()).isEqualTo(1); + assertThat(output.getEmittedRecords()).hasSize(1); + } + } + @Test public void continuousFileStoreFixBucketEnumeratorMetricsTest() throws Exception { writeOnce(fixBucketTable); @@ -237,6 +331,22 @@ public void testUnassignedSplitsMetric(boolean unordered) throws Exception { } } + private TestingReaderContext readerContext(MetricListener metrics) { + return new TestingReaderContext( + new Configuration(), + InternalSourceReaderMetricGroup.mock(metrics.getMetricGroup())); + } + + private Gauge scanGauge(MetricListener metrics, String name) { + return metrics.getGauge("paimon", "table", table.name(), "scan", name) + .orElseThrow(AssertionError::new); + } + + private Histogram scanDuration(MetricListener metrics) { + return metrics.getHistogram("paimon", "table", table.name(), "scan", "scanDuration") + .orElseThrow(AssertionError::new); + } + private void writeOnce(FileStoreTable table) throws Exception { InnerTableWrite writer = table.newWrite("test"); TableCommitImpl commit = table.newCommit("test"); diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/IndexQuerySourceTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/IndexQuerySourceTest.java index 94290a31b8a2..4e749abfdfb8 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/IndexQuerySourceTest.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/IndexQuerySourceTest.java @@ -46,13 +46,13 @@ import org.apache.flink.api.connector.source.ReaderOutput; import org.apache.flink.api.connector.source.Source; import org.apache.flink.api.connector.source.SourceReader; -import org.apache.flink.api.connector.source.SourceReaderContext; import org.apache.flink.api.connector.source.SplitEnumerator; import org.apache.flink.api.connector.source.SplitEnumeratorContext; import org.apache.flink.connector.base.source.reader.RecordsWithSplitIds; import org.apache.flink.connector.base.source.reader.splitreader.SplitsAddition; import org.apache.flink.connector.file.src.reader.BulkFormat; import org.apache.flink.connector.file.src.util.RecordAndPosition; +import org.apache.flink.connector.testutils.source.reader.TestingReaderContext; import org.apache.flink.core.io.InputStatus; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; @@ -116,7 +116,7 @@ public void testDistributedIndexAndDedicatedSplitGeneration() throws Exception { .when(output) .collect(any(Split.class)); try (SourceReader reader = - transformation.getSource().createReader(mock(SourceReaderContext.class))) { + transformation.getSource().createReader(new TestingReaderContext())) { assertThat(reader.pollNext(output)).isEqualTo(InputStatus.END_OF_INPUT); } assertThat(splits).isNotEmpty().allMatch(IndexQuerySplit.class::isInstance); diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/operator/OperatorSourceTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/operator/OperatorSourceTest.java index 4446278be1d0..b24f7241dbab 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/operator/OperatorSourceTest.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/source/operator/OperatorSourceTest.java @@ -37,6 +37,7 @@ import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.connector.source.SourceReader; +import org.apache.flink.connector.testutils.source.reader.TestingReaderContext; import org.apache.flink.connector.testutils.source.reader.TestingReaderOutput; import org.apache.flink.core.io.InputStatus; import org.apache.flink.metrics.MetricGroup; @@ -140,7 +141,9 @@ public void testMonitorSourceWhenIsBoundedIsTrue() throws Exception { TestingSourceOperator operator = (TestingSourceOperator) TestingSourceOperator.createTestOperator( - source.createReader(null), WatermarkStrategy.noWatermarks(), false); + source.createReader(new TestingReaderContext()), + WatermarkStrategy.noWatermarks(), + false); AbstractStreamOperatorTestHarness testHarness = new AbstractStreamOperatorTestHarness<>(operator, 1, 1, 0); testHarness.open(); @@ -157,7 +160,7 @@ public void testMonitorSource() throws Exception { TestingSourceOperator operator = (TestingSourceOperator) TestingSourceOperator.createTestOperator( - source.createReader(null), + source.createReader(new TestingReaderContext()), WatermarkStrategy.noWatermarks(), false); AbstractStreamOperatorTestHarness testHarness = @@ -172,7 +175,7 @@ public void testMonitorSource() throws Exception { TestingSourceOperator operatorCopy1 = (TestingSourceOperator) TestingSourceOperator.createTestOperator( - sourceCopy1.createReader(null), + sourceCopy1.createReader(new TestingReaderContext()), WatermarkStrategy.noWatermarks(), false); AbstractStreamOperatorTestHarness testHarnessCopy1 = @@ -197,7 +200,7 @@ public void testMonitorSource() throws Exception { TestingSourceOperator operatorCopy2 = (TestingSourceOperator) TestingSourceOperator.createTestOperator( - sourceCopy2.createReader(null), + sourceCopy2.createReader(new TestingReaderContext()), WatermarkStrategy.noWatermarks(), false); AbstractStreamOperatorTestHarness testHarnessCopy2 = @@ -233,7 +236,7 @@ public void testMonitorSourceLimitsSnapshotsUntilCheckpointCompletes() throws Ex @SuppressWarnings("unchecked") SourceReader reader = (SourceReader) - sourceTransformation.getSource().createReader(null); + sourceTransformation.getSource().createReader(new TestingReaderContext()); TestingReaderOutput output = new TestingReaderOutput<>(); writeToTable(1, 1, 1); @@ -256,7 +259,8 @@ public void testMonitorSourceLimitsSnapshotsUntilCheckpointCompletes() throws Ex @Test public void testCheckpointBeforeSnapshotDoesNotReleaseSnapshotLimit() throws Exception { MonitorSource source = new MonitorSource(table.newReadBuilder(), 10, false, false, 1); - SourceReader reader = source.createReader(null); + SourceReader reader = + source.createReader(new TestingReaderContext()); TestingReaderOutput output = new TestingReaderOutput<>(); reader.snapshotState(1L); @@ -274,7 +278,8 @@ public void testCheckpointBeforeSnapshotDoesNotReleaseSnapshotLimit() throws Exc @Test public void testCompletedCheckpointReleasesCoveredSnapshotCredits() throws Exception { MonitorSource source = new MonitorSource(table.newReadBuilder(), 10, false, false, 2); - SourceReader reader = source.createReader(null); + SourceReader reader = + source.createReader(new TestingReaderContext()); TestingReaderOutput output = new TestingReaderOutput<>(); writeToTable(1, 1, 1); @@ -296,7 +301,8 @@ public void testCompletedCheckpointReleasesCoveredSnapshotCredits() throws Excep @Test public void testMonitorSourceSnapshotLimitIsOpenAfterRestore() throws Exception { MonitorSource source = new MonitorSource(table.newReadBuilder(), 10, false, false, 1); - SourceReader reader = source.createReader(null); + SourceReader reader = + source.createReader(new TestingReaderContext()); writeToTable(1, 1, 1); assertThat(reader.pollNext(new TestingReaderOutput<>())) @@ -305,7 +311,8 @@ public void testMonitorSourceSnapshotLimitIsOpenAfterRestore() throws Exception MonitorSource restoredSource = new MonitorSource(table.newReadBuilder(), 10, false, false, 1); - SourceReader restoredReader = restoredSource.createReader(null); + SourceReader restoredReader = + restoredSource.createReader(new TestingReaderContext()); restoredReader.addSplits(checkpoint); assertThat(restoredReader.isAvailable()).isDone();