This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new 7e00e83aeb [core] Extend existing Blob fetch metrics with copy cost 
and terminal 503 (#10922)
7e00e83aeb is described below

commit 7e00e83aeba840fa5b16b51cee62a1a531450f53
Author: wangwj <[email protected]>
AuthorDate: Mon Nov 23 12:17:10 2026 +0800

    [core] Extend existing Blob fetch metrics with copy cost and terminal 503 
(#10922)
---
 docs/docs/maintenance/metrics.md                   |  50 +++
 docs/generated/core_configuration.html             |   6 +
 .../main/java/org/apache/paimon/CoreOptions.java   |   8 +
 .../paimon/data/BlobFetchMetricReporter.java       |  13 +
 .../paimon/operation/BaseAppendFileStoreWrite.java |   7 +-
 .../paimon/operation/metrics/BlobFetchMetrics.java |  64 ++++
 .../java/org/apache/paimon/CoreOptionsTest.java    |  12 +
 .../operation/metrics/BlobFetchMetricsTest.java    | 125 ++++++++
 .../metrics/BlobFetchTableMetricsTest.java         |  98 ++++++
 .../flink/metrics/BlobFetchFlinkMetricsTest.java   |  55 ++++
 .../format/blob/AbstractBlobElementWriter.java     |  76 ++++-
 .../format/blob/BlobTransferMetricsTest.java       | 342 +++++++++++++++++++++
 12 files changed, 850 insertions(+), 6 deletions(-)

diff --git a/docs/docs/maintenance/metrics.md b/docs/docs/maintenance/metrics.md
index efd78e520d..bab2074205 100644
--- a/docs/docs/maintenance/metrics.md
+++ b/docs/docs/maintenance/metrics.md
@@ -343,6 +343,11 @@ Lookup metrics are available for local partial lookup. 
They are reported at look
 
 ### Blob Fetch Metrics
 
+The existing fetch outcome counters are always registered when the Blob writer 
has a metric
+registry. Setting `blob-transfer-metrics.enabled=true` adds the five counters 
listed at the end
+of this table to the same `paimon.table.<table_name>.blobFetch` group. The 
option defaults to
+`false` and does not change the existing fetch outcomes or successful-byte 
accounting.
+
 <table class="table table-bordered">
     <thead>
     <tr>
@@ -417,9 +422,54 @@ Lookup metrics are available for local partial lookup. 
They are reported at look
             <td>Counter</td>
             <td>Total number of blob fetch failures that are not classified as 
HTTP status or invalid URI failures.</td>
         </tr>
+        <tr>
+            <td>blobFetchTransferTimedCount</td>
+            <td>Counter</td>
+            <td>Number of timed payload copy attempts, including empty 
payloads and failed copies.</td>
+        </tr>
+        <tr>
+            <td>blobFetchTransferDurationNanos</td>
+            <td>Counter</td>
+            <td>Cumulative payload copy duration in nanoseconds.</td>
+        </tr>
+        <tr>
+            <td>blobFetchFailedReadBytes</td>
+            <td>Counter</td>
+            <td>Payload bytes returned by successful read calls before a copy 
failed.</td>
+        </tr>
+        <tr>
+            <td>blobFetchFailedWrittenBytes</td>
+            <td>Counter</td>
+            <td>Payload bytes passed to normally returning write calls before 
a copy failed.</td>
+        </tr>
+        <tr>
+            <td>blobFetchHttp503</td>
+            <td>Counter</td>
+            <td>Terminal blob fetch failures classified as HTTP 503, including 
failures written as NULL. A subset of blobFetchHttpServerError.</td>
+        </tr>
     </tbody>
 </table>
 
+Copy timing covers payload reads and writes, excluding source open, seek, and 
cleanup. NULL
+values and failures before copying are not timed; an empty payload that 
reaches copying is
+timed. Divide the duration-counter delta by the timed-count delta for the mean 
copy duration.
+
+Failed-copy bytes exclude framing, checksums, and protocol overhead. A 
throwing write may have
+unknown side effects: only preceding, normally returning writes contribute to
+`blobFetchFailedWrittenBytes`. These bytes are not storage acknowledgments or 
committed data.
+Successful payload bytes remain solely in `blobFetchSuccessBytes`. The 
failed-byte counters
+cover failures inside the copy loop only. Later source-close, footer, or 
consumer-callback
+failures do not reclassify a completed copy. Therefore, successful bytes and 
failed-copy bytes
+are not an exhaustive traffic partition and must not be added together as 
total traffic.
+
+`blobFetchHttp503` classifies the logical fetch's terminal error. It does not 
count every HTTP
+response, hidden client retry, or redirect, and HTTP 503 alone does not prove 
rate limiting.
+
+Compute counter rates only when the exporter preserves each producer's 
identity and resets.
+The existing Spark adapter shares registry keys for same-table writers in one 
JVM; later
+registrations may replace exported gauges. Such series do not establish 
concurrent-writer
+totals or per-writer rates. This option does not change that adapter behavior.
+
 ### Compaction Metrics
 
 <table class="table table-bordered">
diff --git a/docs/generated/core_configuration.html 
b/docs/generated/core_configuration.html
index 7fc527b43b..2578dd8560 100644
--- a/docs/generated/core_configuration.html
+++ b/docs/generated/core_configuration.html
@@ -86,6 +86,12 @@ under the License.
             <td>String</td>
             <td>Specifies column names that should be stored as blob type. 
This is used when you want to treat a BYTES column as a BLOB. Fields listed in 
blob-descriptor-field, blob-view-field, or video-frame-field are also treated 
as BLOB fields.</td>
         </tr>
+        <tr>
+            <td><h5>blob-transfer-metrics.enabled</h5></td>
+            <td style="word-wrap: break-word;">false</td>
+            <td>Boolean</td>
+            <td>Collect additional Blob copy duration, failed-copy payload 
bytes and terminal HTTP 503 metrics when a metric registry is provided.</td>
+        </tr>
         <tr>
             <td><h5>blob-view-field</h5></td>
             <td style="word-wrap: break-word;">(none)</td>
diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java 
b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
index 6c3a21d817..aa511a20e1 100644
--- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
+++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
@@ -3088,6 +3088,14 @@ public class CoreOptions implements Serializable {
                                     + "HTTP 404 is handled by 
'blob-write-null-on-missing-file'. "
                                     + "When false, the write fails when the 
descriptor is read.");
 
+    public static final ConfigOption<Boolean> BLOB_TRANSFER_METRICS_ENABLED =
+            key("blob-transfer-metrics.enabled")
+                    .booleanType()
+                    .defaultValue(false)
+                    .withDescription(
+                            "Collect additional Blob copy duration, 
failed-copy payload bytes and "
+                                    + "terminal HTTP 503 metrics when a metric 
registry is provided.");
+
     public static final ConfigOption<Boolean> COMMIT_DISCARD_DUPLICATE_FILES =
             key("commit.discard-duplicate-files")
                     .booleanType()
diff --git 
a/paimon-common/src/main/java/org/apache/paimon/data/BlobFetchMetricReporter.java
 
b/paimon-common/src/main/java/org/apache/paimon/data/BlobFetchMetricReporter.java
index 0670c7098c..9c918152d0 100644
--- 
a/paimon-common/src/main/java/org/apache/paimon/data/BlobFetchMetricReporter.java
+++ 
b/paimon-common/src/main/java/org/apache/paimon/data/BlobFetchMetricReporter.java
@@ -43,4 +43,17 @@ public interface BlobFetchMetricReporter {
     void recordFetchFailureNullWritten(Throwable throwable);
 
     void recordFetchFailure(Throwable throwable);
+
+    /** Whether to time and count payload copies. Legacy reporters remain 
disabled. */
+    default boolean isTransferMetricsEnabled() {
+        return false;
+    }
+
+    /**
+     * Records one payload-copy attempt, excluding stream open, seek, close 
and Blob framing.
+     * Written bytes count only writes which returned normally. The side 
effects of a throwing write
+     * are unknown. A completed copy does not imply a committed Paimon 
snapshot.
+     */
+    default void recordTransfer(
+            long readBytes, long writtenBytes, long durationNanos, boolean 
completed) {}
 }
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/operation/BaseAppendFileStoreWrite.java
 
b/paimon-core/src/main/java/org/apache/paimon/operation/BaseAppendFileStoreWrite.java
index 0e372c0ba1..7d23bb0093 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/operation/BaseAppendFileStoreWrite.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/operation/BaseAppendFileStoreWrite.java
@@ -146,7 +146,12 @@ public abstract class BaseAppendFileStoreWrite extends 
MemoryFileStoreWrite<Inte
     public BaseAppendFileStoreWrite withMetricRegistry(MetricRegistry 
metricRegistry) {
         super.withMetricRegistry(metricRegistry);
         if (blobContext != null) {
-            blobFetchMetrics = new BlobFetchMetrics(metricRegistry, tableName);
+            blobFetchMetrics =
+                    new BlobFetchMetrics(
+                            metricRegistry,
+                            tableName,
+                            options.toConfiguration()
+                                    
.get(CoreOptions.BLOB_TRANSFER_METRICS_ENABLED));
             blobContext = 
blobContext.withBlobFetchMetricReporter(blobFetchMetrics);
         }
         return this;
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/operation/metrics/BlobFetchMetrics.java
 
b/paimon-core/src/main/java/org/apache/paimon/operation/metrics/BlobFetchMetrics.java
index 3f708a1388..8ec12ee7cd 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/operation/metrics/BlobFetchMetrics.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/operation/metrics/BlobFetchMetrics.java
@@ -25,6 +25,8 @@ import org.apache.paimon.metrics.MetricGroup;
 import org.apache.paimon.metrics.MetricRegistry;
 import org.apache.paimon.rest.HttpClientUtils;
 
+import javax.annotation.Nullable;
+
 /** Metrics to measure blob fetches during write. */
 public class BlobFetchMetrics implements BlobFetchMetricReporter {
 
@@ -44,6 +46,12 @@ public class BlobFetchMetrics implements 
BlobFetchMetricReporter {
     public static final String BLOB_FETCH_HTTP_OTHER_ERROR = 
"blobFetchHttpOtherError";
     public static final String BLOB_FETCH_INVALID_URI = "blobFetchInvalidUri";
     public static final String BLOB_FETCH_OTHER_ERROR = "blobFetchOtherError";
+    public static final String BLOB_FETCH_TRANSFER_TIMED_COUNT = 
"blobFetchTransferTimedCount";
+    public static final String BLOB_FETCH_TRANSFER_DURATION_NANOS =
+            "blobFetchTransferDurationNanos";
+    public static final String BLOB_FETCH_FAILED_READ_BYTES = 
"blobFetchFailedReadBytes";
+    public static final String BLOB_FETCH_FAILED_WRITTEN_BYTES = 
"blobFetchFailedWrittenBytes";
+    public static final String BLOB_FETCH_HTTP_503 = "blobFetchHttp503";
 
     private final MetricGroup metricGroup;
     private final Counter totalCounter;
@@ -59,8 +67,20 @@ public class BlobFetchMetrics implements 
BlobFetchMetricReporter {
     private final Counter httpOtherErrorCounter;
     private final Counter invalidUriCounter;
     private final Counter otherErrorCounter;
+    private final boolean transferMetricsEnabled;
+    @Nullable private final Counter transferTimedCounter;
+    @Nullable private final Counter transferDurationNanosCounter;
+    @Nullable private final Counter failedReadBytesCounter;
+    @Nullable private final Counter failedWrittenBytesCounter;
+    @Nullable private final Counter http503Counter;
 
     public BlobFetchMetrics(MetricRegistry registry, String tableName) {
+        this(registry, tableName, false);
+    }
+
+    public BlobFetchMetrics(
+            MetricRegistry registry, String tableName, boolean 
transferMetricsEnabled) {
+        this.transferMetricsEnabled = transferMetricsEnabled;
         this.metricGroup = registry.createTableMetricGroup(GROUP_NAME, 
tableName);
         this.totalCounter = metricGroup.counter(BLOB_FETCH_TOTAL);
         this.successCounter = metricGroup.counter(BLOB_FETCH_SUCCESS);
@@ -76,6 +96,20 @@ public class BlobFetchMetrics implements 
BlobFetchMetricReporter {
         this.httpOtherErrorCounter = 
metricGroup.counter(BLOB_FETCH_HTTP_OTHER_ERROR);
         this.invalidUriCounter = metricGroup.counter(BLOB_FETCH_INVALID_URI);
         this.otherErrorCounter = metricGroup.counter(BLOB_FETCH_OTHER_ERROR);
+        if (transferMetricsEnabled) {
+            this.transferTimedCounter = 
metricGroup.counter(BLOB_FETCH_TRANSFER_TIMED_COUNT);
+            this.transferDurationNanosCounter =
+                    metricGroup.counter(BLOB_FETCH_TRANSFER_DURATION_NANOS);
+            this.failedReadBytesCounter = 
metricGroup.counter(BLOB_FETCH_FAILED_READ_BYTES);
+            this.failedWrittenBytesCounter = 
metricGroup.counter(BLOB_FETCH_FAILED_WRITTEN_BYTES);
+            this.http503Counter = metricGroup.counter(BLOB_FETCH_HTTP_503);
+        } else {
+            this.transferTimedCounter = null;
+            this.transferDurationNanosCounter = null;
+            this.failedReadBytesCounter = null;
+            this.failedWrittenBytesCounter = null;
+            this.http503Counter = null;
+        }
     }
 
     @VisibleForTesting
@@ -117,6 +151,29 @@ public class BlobFetchMetrics implements 
BlobFetchMetricReporter {
         recordFailureReason(throwable);
     }
 
+    @Override
+    public boolean isTransferMetricsEnabled() {
+        return transferMetricsEnabled;
+    }
+
+    @Override
+    public void recordTransfer(
+            long readBytes, long writtenBytes, long durationNanos, boolean 
completed) {
+        if (!transferMetricsEnabled) {
+            return;
+        }
+        transferTimedCounter.inc();
+        transferDurationNanosCounter.inc(Math.max(0, durationNanos));
+        if (!completed) {
+            if (readBytes > 0) {
+                failedReadBytesCounter.inc(readBytes);
+            }
+            if (writtenBytes > 0) {
+                failedWrittenBytesCounter.inc(writtenBytes);
+            }
+        }
+    }
+
     public void close() {
         metricGroup.close();
     }
@@ -130,6 +187,13 @@ public class BlobFetchMetrics implements 
BlobFetchMetricReporter {
                 httpClientErrorCounter.inc();
             } else if (statusCode >= 500 && statusCode < 600) {
                 httpServerErrorCounter.inc();
+                if (statusCode == 503 && http503Counter != null) {
+                    try {
+                        http503Counter.inc();
+                    } catch (RuntimeException ignored) {
+                        // Optional telemetry must not replace the original 
fetch failure.
+                    }
+                }
             } else {
                 httpOtherErrorCounter.inc();
             }
diff --git a/paimon-core/src/test/java/org/apache/paimon/CoreOptionsTest.java 
b/paimon-core/src/test/java/org/apache/paimon/CoreOptionsTest.java
index 6808206835..dc6eaf01af 100644
--- a/paimon-core/src/test/java/org/apache/paimon/CoreOptionsTest.java
+++ b/paimon-core/src/test/java/org/apache/paimon/CoreOptionsTest.java
@@ -32,6 +32,18 @@ import static 
org.assertj.core.api.Assertions.assertThatThrownBy;
 /** Tests for {@link org.apache.paimon.CoreOptions}. */
 public class CoreOptionsTest {
 
+    @Test
+    void testBlobTransferMetricsAreOptIn() {
+        Options options = new Options();
+        
assertThat(options.get(CoreOptions.BLOB_TRANSFER_METRICS_ENABLED)).isFalse();
+        options.set(CoreOptions.BLOB_TRANSFER_METRICS_ENABLED, true);
+        assertThat(
+                        new CoreOptions(options)
+                                .toConfiguration()
+                                
.get(CoreOptions.BLOB_TRANSFER_METRICS_ENABLED))
+                .isTrue();
+    }
+
     @Test
     void testCommitLastSafeSnapshotAndStrictMode() {
         Options options = new Options();
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/operation/metrics/BlobFetchMetricsTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/operation/metrics/BlobFetchMetricsTest.java
index 7fb53005fc..bce562f2c4 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/operation/metrics/BlobFetchMetricsTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/operation/metrics/BlobFetchMetricsTest.java
@@ -21,10 +21,13 @@ package org.apache.paimon.operation.metrics;
 import org.apache.paimon.metrics.Counter;
 import org.apache.paimon.metrics.Metric;
 import org.apache.paimon.metrics.MetricGroup;
+import org.apache.paimon.metrics.MetricGroupImpl;
+import org.apache.paimon.metrics.SimpleCounter;
 import org.apache.paimon.metrics.TestMetricRegistry;
 
 import org.junit.jupiter.api.Test;
 
+import java.io.IOException;
 import java.util.Map;
 
 import static org.assertj.core.api.Assertions.assertThat;
@@ -86,6 +89,128 @@ public class BlobFetchMetricsTest {
         assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_OTHER_ERROR, 1);
     }
 
+    @Test
+    public void testTransferMetricRegistration() {
+        BlobFetchMetrics legacy = new BlobFetchMetrics(new 
TestMetricRegistry(), TABLE_NAME);
+        BlobFetchMetrics enabled = new BlobFetchMetrics(new 
TestMetricRegistry(), TABLE_NAME, true);
+
+        assertThat(legacy.isTransferMetricsEnabled()).isFalse();
+        assertThat(enabled.isTransferMetricsEnabled()).isTrue();
+        
assertThat(enabled.getMetricGroup().getGroupName()).isEqualTo(BlobFetchMetrics.GROUP_NAME);
+        
assertThat(enabled.getMetricGroup().getAllVariables()).containsEntry("table", 
TABLE_NAME);
+        assertThat(enabled.getMetricGroup().getMetrics().keySet())
+                .hasSize(18)
+                .containsAll(legacy.getMetricGroup().getMetrics().keySet())
+                .contains(
+                        BlobFetchMetrics.BLOB_FETCH_TRANSFER_TIMED_COUNT,
+                        BlobFetchMetrics.BLOB_FETCH_TRANSFER_DURATION_NANOS,
+                        BlobFetchMetrics.BLOB_FETCH_FAILED_READ_BYTES,
+                        BlobFetchMetrics.BLOB_FETCH_FAILED_WRITTEN_BYTES,
+                        BlobFetchMetrics.BLOB_FETCH_HTTP_503);
+    }
+
+    @Test
+    public void testTransferMetricsAreUpdatedWithoutChangingFetchOutcomes() {
+        BlobFetchMetrics metrics = new BlobFetchMetrics(new 
TestMetricRegistry(), TABLE_NAME, true);
+
+        metrics.recordTransfer(10, 10, 30, true);
+        metrics.recordTransfer(7, 3, 40, false);
+        metrics.recordTransfer(0, 0, -1, false);
+
+        assertCounter(metrics, 
BlobFetchMetrics.BLOB_FETCH_TRANSFER_TIMED_COUNT, 3);
+        assertCounter(metrics, 
BlobFetchMetrics.BLOB_FETCH_TRANSFER_DURATION_NANOS, 70);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_FAILED_READ_BYTES, 
7);
+        assertCounter(metrics, 
BlobFetchMetrics.BLOB_FETCH_FAILED_WRITTEN_BYTES, 3);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_HTTP_503, 0);
+        BlobFetchMetrics legacy = new BlobFetchMetrics(new 
TestMetricRegistry(), TABLE_NAME);
+        legacy.getMetricGroup()
+                .getMetrics()
+                .keySet()
+                .forEach(name -> assertCounter(metrics, name, 0));
+    }
+
+    @Test
+    public void testDisabledTransferMetricsKeepLegacyCountersOnly() {
+        for (BlobFetchMetrics metrics :
+                new BlobFetchMetrics[] {
+                    new BlobFetchMetrics(new TestMetricRegistry(), TABLE_NAME),
+                    new BlobFetchMetrics(new TestMetricRegistry(), TABLE_NAME, 
false)
+                }) {
+            metrics.recordTransfer(7, 3, 40, false);
+            metrics.recordFetchFailure(new IOException("HTTP error code: 
503"));
+            assertThat(metrics.isTransferMetricsEnabled()).isFalse();
+            assertThat(metrics.getMetricGroup().getMetrics()).hasSize(13);
+            assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_TOTAL, 1);
+            assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_FAILURE, 1);
+            assertCounter(metrics, 
BlobFetchMetrics.BLOB_FETCH_HTTP_SERVER_ERROR, 1);
+            assertThat(metrics.getMetricGroup().getMetrics())
+                    .doesNotContainKeys(
+                            BlobFetchMetrics.BLOB_FETCH_TRANSFER_TIMED_COUNT,
+                            
BlobFetchMetrics.BLOB_FETCH_TRANSFER_DURATION_NANOS,
+                            BlobFetchMetrics.BLOB_FETCH_FAILED_READ_BYTES,
+                            BlobFetchMetrics.BLOB_FETCH_FAILED_WRITTEN_BYTES,
+                            BlobFetchMetrics.BLOB_FETCH_HTTP_503);
+        }
+    }
+
+    @Test
+    public void testHttp503IsATerminalFailureSubset() {
+        BlobFetchMetrics metrics = new BlobFetchMetrics(new 
TestMetricRegistry(), TABLE_NAME, true);
+
+        metrics.recordFetchFailure(new IOException("HTTP error code: 503"));
+        metrics.recordFetchFailureNullWritten(
+                new RuntimeException("fetch failed", new IOException("HTTP 
error code: 503")));
+        metrics.recordFetchFailure(new IOException("HTTP error code: 500"));
+        metrics.recordFetchFailure(new IOException("HTTP error code: 502"));
+        metrics.recordFetchFailure(new IOException("HTTP error code: 429"));
+        metrics.recordFetchFailure(new IOException("no response"));
+
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_HTTP_503, 2);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_HTTP_SERVER_ERROR, 
4);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_HTTP_CLIENT_ERROR, 
1);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_OTHER_ERROR, 1);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_TOTAL, 6);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_FAILURE, 5);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_NULL_WRITTEN, 1);
+        assertCounter(metrics, 
BlobFetchMetrics.BLOB_FETCH_FAILURE_NULL_WRITTEN, 1);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_SUCCESS, 0);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_SUCCESS_BYTES, 0);
+        assertCounter(metrics, 
BlobFetchMetrics.BLOB_FETCH_TRANSFER_TIMED_COUNT, 0);
+    }
+
+    @Test
+    public void testHttp503CounterFailurePreservesLegacyFailureMetrics() {
+        BlobFetchMetrics metrics =
+                new BlobFetchMetrics(
+                        (name, variables) ->
+                                new MetricGroupImpl(name, variables) {
+                                    @Override
+                                    public Counter counter(String metricName) {
+                                        if 
(BlobFetchMetrics.BLOB_FETCH_HTTP_503.equals(
+                                                metricName)) {
+                                            return new SimpleCounter() {
+                                                @Override
+                                                public void inc() {
+                                                    throw new 
IllegalStateException(
+                                                            "counter failed");
+                                                }
+                                            };
+                                        }
+                                        return super.counter(metricName);
+                                    }
+                                },
+                        TABLE_NAME,
+                        true);
+
+        metrics.recordFetchFailure(new IOException("HTTP error code: 503"));
+        metrics.recordFetchFailureNullWritten(new IOException("HTTP error 
code: 503"));
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_TOTAL, 2);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_FAILURE, 1);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_NULL_WRITTEN, 1);
+        assertCounter(metrics, 
BlobFetchMetrics.BLOB_FETCH_FAILURE_NULL_WRITTEN, 1);
+        assertCounter(metrics, BlobFetchMetrics.BLOB_FETCH_HTTP_SERVER_ERROR, 
2);
+    }
+
     private static void assertCounter(BlobFetchMetrics metrics, String name, 
long expected) {
         assertThat(counter(metrics, name)).isEqualTo(expected);
     }
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/operation/metrics/BlobFetchTableMetricsTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/operation/metrics/BlobFetchTableMetricsTest.java
new file mode 100644
index 0000000000..53d15dea0e
--- /dev/null
+++ 
b/paimon-core/src/test/java/org/apache/paimon/operation/metrics/BlobFetchTableMetricsTest.java
@@ -0,0 +1,98 @@
+/*
+ * 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.operation.metrics;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.data.Blob;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.metrics.Counter;
+import org.apache.paimon.metrics.MetricGroup;
+import org.apache.paimon.metrics.MetricGroupImpl;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.TableTestBase;
+import org.apache.paimon.table.sink.BatchTableCommit;
+import org.apache.paimon.table.sink.BatchTableWrite;
+import org.apache.paimon.table.sink.BatchWriteBuilder;
+import org.apache.paimon.types.DataTypes;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Verifies the table option reaches a native Blob writer, prepare, commit 
and readback. */
+class BlobFetchTableMetricsTest extends TableTestBase {
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void tableOptionControlsOnlyAdditionalCounters(boolean enabled) throws 
Exception {
+        catalog.createTable(
+                identifier(),
+                Schema.newBuilder()
+                        .column("id", DataTypes.INT())
+                        .column("payload", DataTypes.BLOB())
+                        .option(CoreOptions.DATA_EVOLUTION_ENABLED.key(), 
"true")
+                        .option(CoreOptions.ROW_TRACKING_ENABLED.key(), "true")
+                        .option(
+                                
CoreOptions.BLOB_TRANSFER_METRICS_ENABLED.key(),
+                                Boolean.toString(enabled))
+                        .build(),
+                false);
+        FileStoreTable table = getTableDefault();
+        Map<String, MetricGroup> groups = new HashMap<>();
+        BatchWriteBuilder builder = table.newBatchWriteBuilder();
+        try (BatchTableWrite write = builder.newWrite();
+                BatchTableCommit commit = builder.newCommit()) {
+            write.withMetricRegistry(
+                    (name, variables) -> {
+                        MetricGroup group = new MetricGroupImpl(name, 
variables);
+                        groups.put(name, group);
+                        return group;
+                    });
+            write.write(GenericRow.of(1, Blob.fromData(new byte[] {1, 2, 3})));
+            commit.commit(write.prepareCommit());
+            MetricGroup fetch = groups.get(BlobFetchMetrics.GROUP_NAME);
+            assertThat(fetch.getMetrics()).hasSize(enabled ? 18 : 13);
+            assertThat(
+                            ((Counter)
+                                            fetch.getMetrics()
+                                                    
.get(BlobFetchMetrics.BLOB_FETCH_SUCCESS_BYTES))
+                                    .getCount())
+                    .isEqualTo(3);
+            if (enabled) {
+                assertThat(
+                                ((Counter)
+                                                fetch.getMetrics()
+                                                        .get(
+                                                                
BlobFetchMetrics
+                                                                        
.BLOB_FETCH_TRANSFER_TIMED_COUNT))
+                                        .getCount())
+                        .isEqualTo(1);
+            }
+        }
+        assertThat(table.snapshotManager().latestSnapshot()).isNotNull();
+        assertThat(read(table))
+                .singleElement()
+                .satisfies(row -> 
assertThat(row.getBlob(1).toData()).containsExactly(1, 2, 3));
+    }
+}
diff --git 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/metrics/BlobFetchFlinkMetricsTest.java
 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/metrics/BlobFetchFlinkMetricsTest.java
new file mode 100644
index 0000000000..97d1dfe040
--- /dev/null
+++ 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/metrics/BlobFetchFlinkMetricsTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.metrics;
+
+import org.apache.paimon.operation.metrics.BlobFetchMetrics;
+
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Verifies the existing table-scoped Flink registry bridge for Blob fetch 
counters. */
+class BlobFetchFlinkMetricsTest {
+
+    @Test
+    void registersExistingAndOptionalCountersInSameTableGroup() {
+        MetricListener listener = new MetricListener();
+        BlobFetchMetrics metrics =
+                new BlobFetchMetrics(
+                        new FlinkMetricRegistry(listener.getMetricGroup()), 
"media", true);
+        metrics.recordSuccess(7);
+        metrics.recordTransfer(7, 7, 50, true);
+        metrics.recordTransfer(4, 2, 30, false);
+        metrics.recordFetchFailure(new RuntimeException("HTTP error code: 
503"));
+        assertCounter(listener, BlobFetchMetrics.BLOB_FETCH_SUCCESS_BYTES, 7);
+        assertCounter(listener, 
BlobFetchMetrics.BLOB_FETCH_TRANSFER_TIMED_COUNT, 2);
+        assertCounter(listener, 
BlobFetchMetrics.BLOB_FETCH_TRANSFER_DURATION_NANOS, 80);
+        assertCounter(listener, BlobFetchMetrics.BLOB_FETCH_FAILED_READ_BYTES, 
4);
+        assertCounter(listener, 
BlobFetchMetrics.BLOB_FETCH_FAILED_WRITTEN_BYTES, 2);
+        assertCounter(listener, BlobFetchMetrics.BLOB_FETCH_HTTP_503, 1);
+        assertCounter(listener, BlobFetchMetrics.BLOB_FETCH_HTTP_SERVER_ERROR, 
1);
+        metrics.close();
+    }
+
+    private static void assertCounter(MetricListener listener, String name, 
long expected) {
+        assertThat(listener.getCounter("paimon", "table", "media", 
"blobFetch", name))
+                .hasValueSatisfying(counter -> 
assertThat(counter.getCount()).isEqualTo(expected));
+    }
+}
diff --git 
a/paimon-format/src/main/java/org/apache/paimon/format/blob/AbstractBlobElementWriter.java
 
b/paimon-format/src/main/java/org/apache/paimon/format/blob/AbstractBlobElementWriter.java
index 0c52ea123b..1ef4d5328f 100644
--- 
a/paimon-format/src/main/java/org/apache/paimon/format/blob/AbstractBlobElementWriter.java
+++ 
b/paimon-format/src/main/java/org/apache/paimon/format/blob/AbstractBlobElementWriter.java
@@ -55,6 +55,7 @@ abstract class AbstractBlobElementWriter implements 
BlobElementSerializer.Writer
     private final boolean writeNullOnMissingFile;
     private final boolean writeNullOnFetchFailure;
     private final BlobFetchMetricReporter blobFetchMetricReporter;
+    private final boolean transferMetricsEnabled;
     private final CRC32 crc32;
     private final byte[] copyBuffer;
     private final ReusingBlobRefStreamProvider reuseSource;
@@ -79,6 +80,7 @@ abstract class AbstractBlobElementWriter implements 
BlobElementSerializer.Writer
         this.writeNullOnMissingFile = writeNullOnMissingFile;
         this.writeNullOnFetchFailure = writeNullOnFetchFailure;
         this.blobFetchMetricReporter = blobFetchMetricReporter;
+        this.transferMetricsEnabled = 
transferMetricsEnabled(blobFetchMetricReporter);
         this.crc32 = new CRC32();
         this.copyBuffer = new byte[copyBufferSize];
         this.reuseSource = new ReusingBlobRefStreamProvider();
@@ -193,7 +195,11 @@ abstract class AbstractBlobElementWriter implements 
BlobElementSerializer.Writer
         long blobPosition = out.getPos();
         if (source.reused()) {
             try {
-                copyExactly(source.stream(), source.length());
+                if (transferMetricsEnabled) {
+                    copyWithMetrics(source.stream(), source.length());
+                } else {
+                    copyExactly(source.stream(), source.length());
+                }
             } catch (IOException | RuntimeException e) {
                 blobFetchMetricReporter.recordFetchFailure(e);
                 // Source is at an unknown position now; drop it so the next 
blob reopens.
@@ -202,10 +208,14 @@ abstract class AbstractBlobElementWriter implements 
BlobElementSerializer.Writer
             }
         } else {
             try (SeekableInputStream stream = source.stream()) {
-                int bytesRead = stream.read(copyBuffer);
-                while (bytesRead >= 0) {
-                    write(copyBuffer, bytesRead);
-                    bytesRead = stream.read(copyBuffer);
+                if (transferMetricsEnabled) {
+                    copyWithMetrics(stream, -1L);
+                } else {
+                    int bytesRead = stream.read(copyBuffer);
+                    while (bytesRead >= 0) {
+                        write(copyBuffer, bytesRead);
+                        bytesRead = stream.read(copyBuffer);
+                    }
                 }
             } catch (IOException | RuntimeException e) {
                 blobFetchMetricReporter.recordFetchFailure(e);
@@ -238,6 +248,62 @@ abstract class AbstractBlobElementWriter implements 
BlobElementSerializer.Writer
         }
     }
 
+    private static boolean transferMetricsEnabled(BlobFetchMetricReporter 
reporter) {
+        try {
+            return reporter.isTransferMetricsEnabled();
+        } catch (RuntimeException ignored) {
+            // Optional telemetry must not prevent a Blob from being written.
+            return false;
+        }
+    }
+
+    /** Opt-in accounting around the payload-copy loop only. */
+    private void copyWithMetrics(SeekableInputStream stream, long length) 
throws IOException {
+        long started = System.nanoTime();
+        long readBytes = 0;
+        long writtenBytes = 0;
+        long remaining = length;
+        boolean completed = false;
+        try {
+            while (length < 0 || remaining > 0) {
+                int toRead =
+                        length < 0
+                                ? copyBuffer.length
+                                : (int) Math.min(copyBuffer.length, remaining);
+                int bytesRead =
+                        length < 0 ? stream.read(copyBuffer) : 
stream.read(copyBuffer, 0, toRead);
+                if (bytesRead < 0) {
+                    if (length >= 0) {
+                        throw new EOFException(
+                                String.format(
+                                        "Unexpected EOF while copying BLOB 
payload for field %s: expected %d "
+                                                + "bytes but source ended %d 
bytes early.",
+                                        blobFieldName, length, remaining));
+                    }
+                    break;
+                }
+                if (bytesRead == 0 && length >= 0) {
+                    throw new IOException(
+                            "Source returned 0 bytes while copying BLOB 
payload for field "
+                                    + blobFieldName);
+                }
+                readBytes += bytesRead;
+                write(copyBuffer, bytesRead);
+                writtenBytes += bytesRead;
+                remaining -= bytesRead;
+            }
+            completed = true;
+        } finally {
+            long durationNanos = Math.max(0L, System.nanoTime() - started);
+            try {
+                blobFetchMetricReporter.recordTransfer(
+                        readBytes, writtenBytes, durationNanos, completed);
+            } catch (RuntimeException ignored) {
+                // Do not replace a business exception or fail a successful 
copy for telemetry.
+            }
+        }
+    }
+
     protected final boolean accept(BlobDescriptor descriptor) throws 
IOException {
         return writeConsumer != null && writeConsumer.accept(blobFieldName, 
descriptor);
     }
diff --git 
a/paimon-format/src/test/java/org/apache/paimon/format/blob/BlobTransferMetricsTest.java
 
b/paimon-format/src/test/java/org/apache/paimon/format/blob/BlobTransferMetricsTest.java
new file mode 100644
index 0000000000..2ea6b7b54e
--- /dev/null
+++ 
b/paimon-format/src/test/java/org/apache/paimon/format/blob/BlobTransferMetricsTest.java
@@ -0,0 +1,342 @@
+/*
+ * 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.format.blob;
+
+import org.apache.paimon.data.Blob;
+import org.apache.paimon.data.BlobDescriptor;
+import org.apache.paimon.data.BlobFetchMetricReporter;
+import org.apache.paimon.data.BlobRef;
+import org.apache.paimon.data.GenericArray;
+import org.apache.paimon.data.GenericMap;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.fs.ByteArraySeekableStream;
+import org.apache.paimon.fs.PositionOutputStream;
+import org.apache.paimon.fs.PositionOutputStreamWrapper;
+import org.apache.paimon.fs.SeekableInputStream;
+import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.UriReader;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Payload-copy accounting without changing Blob write behavior. */
+class BlobTransferMetricsTest {
+
+    @Test
+    void disabledUsesOriginalCopyPath(@TempDir Path dir) throws Exception {
+        Reporter disabled = new Reporter(false);
+        Reporter enabled = new Reporter(true);
+        Path oldFile = dir.resolve("old.blob");
+        Path measuredFile = dir.resolve("measured.blob");
+        for (boolean active : new boolean[] {false, true}) {
+            try (BlobFormatWriter writer =
+                    writer(active ? measuredFile : oldFile, active ? enabled : 
disabled)) {
+                writer.addElement(GenericRow.of(Blob.fromData(new byte[] {1, 
2, 3})));
+                writer.addElement(GenericRow.of((Object) null));
+                writer.addElement(GenericRow.of(Blob.fromData(new byte[0])));
+            }
+        }
+        
assertThat(Files.readAllBytes(measuredFile)).isEqualTo(Files.readAllBytes(oldFile));
+        assertThat(disabled.transfers).isEmpty();
+        assertThat(enabled.transfers).hasSize(2);
+        assertTransfer(enabled.transfers.get(0), 3, 3, true);
+        assertTransfer(enabled.transfers.get(1), 0, 0, true);
+        
assertThat(disabled.successes).isEqualTo(enabled.successes).isEqualTo(2);
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void readFailurePreservesPartialBytesAndOriginalError(boolean bounded, 
@TempDir Path dir)
+            throws Exception {
+        IOException failure = new IOException("source failed");
+        Reporter reporter = new Reporter(true);
+        SeekableInputStream stream =
+                new ByteArraySeekableStream(new byte[] {1, 2, 3, 4}) {
+                    @Override
+                    public int read(byte[] b) throws IOException {
+                        return read(b, 0, b.length);
+                    }
+
+                    @Override
+                    public int read(byte[] b, int off, int len) throws 
IOException {
+                        if (getPos() >= 2) {
+                            throw failure;
+                        }
+                        return super.read(b, off, len);
+                    }
+                };
+        Blob blob =
+                bounded
+                        ? new BlobRef(uri -> stream, new 
BlobDescriptor("test://source", 0, 4))
+                        : Blob.fromInputStream(() -> stream);
+        // Telemetry must not replace the original I/O exception.
+        reporter.throwOnTransfer = true;
+        try (BlobFormatWriter writer = writer(dir.resolve("partial.blob"), 
reporter)) {
+            assertThatThrownBy(() -> 
writer.addElement(GenericRow.of(blob))).isSameAs(failure);
+        }
+        assertThat(reporter.transfers).hasSize(1);
+        assertTransfer(reporter.transfers.get(0), 2, 2, false);
+        assertThat(reporter.failures).isEqualTo(1);
+    }
+
+    @Test
+    void throwingDestinationOnlyCountsNormallyReturnedWrites(@TempDir Path 
dir) throws Exception {
+        Reporter reporter = new Reporter(true);
+        IOException failure = new IOException("destination failed");
+        PositionOutputStream out =
+                new PositionOutputStreamWrapper(
+                        new LocalFileIO.LocalPositionOutputStream(
+                                dir.resolve("out.blob").toFile())) {
+                    @Override
+                    public void write(byte[] b, int off, int len) throws 
IOException {
+                        if (getPos() >= 6) { // four framing bytes plus one 
successful payload write
+                            super.write(
+                                    b, off, 1); // unknown partial side effect 
of the throwing call
+                            throw failure;
+                        }
+                        super.write(b, off, len);
+                    }
+                };
+        try (BlobFormatWriter writer =
+                new BlobFormatWriter(
+                        out, null, RowType.of(DataTypes.BLOB()), false, false, 
reporter, 2)) {
+            assertThatThrownBy(
+                            () ->
+                                    writer.addElement(
+                                            GenericRow.of(Blob.fromData(new 
byte[] {1, 2, 3, 4}))))
+                    .isSameAs(failure);
+        }
+        assertTransfer(reporter.transfers.get(0), 4, 2, false);
+        assertThat(reporter.failures).isEqualTo(1);
+    }
+
+    @Test
+    void unknownLengthRetainsSingleArgumentReadDispatch(@TempDir Path dir) 
throws Exception {
+        Reporter reporter = new Reporter(true);
+        int[] reads = {0};
+        SeekableInputStream stream =
+                new ByteArraySeekableStream(new byte[] {1, 2, 3}) {
+                    @Override
+                    public int read(byte[] b) throws IOException {
+                        reads[0]++;
+                        return super.read(b);
+                    }
+
+                    @Override
+                    public int read(byte[] b, int off, int len) {
+                        throw new AssertionError("Unknown-length copy changed 
read overload");
+                    }
+                };
+        try (BlobFormatWriter writer = writer(dir.resolve("dispatch.blob"), 
reporter)) {
+            writer.addElement(GenericRow.of(Blob.fromInputStream(() -> 
stream)));
+        }
+        assertThat(reads[0]).isGreaterThan(0);
+        assertTransfer(reporter.transfers.get(0), 3, 3, true);
+    }
+
+    @Test
+    void telemetryFailureDoesNotBreakSuccessfulCopy(@TempDir Path dir) throws 
Exception {
+        Reporter reporter = new Reporter(true);
+        reporter.throwOnTransfer = true;
+        try (BlobFormatWriter writer = writer(dir.resolve("ok.blob"), 
reporter)) {
+            writer.addElement(GenericRow.of(Blob.fromData(new byte[] {1, 2, 
3})));
+        }
+        assertThat(reporter.successes).isEqualTo(1);
+        assertTransfer(reporter.transfers.get(0), 3, 3, true);
+    }
+
+    @Test
+    void capabilityFailureUsesOriginalCopy(@TempDir Path dir) throws Exception 
{
+        Reporter reporter =
+                new Reporter(true) {
+                    @Override
+                    public boolean isTransferMetricsEnabled() {
+                        throw new IllegalStateException("telemetry 
unavailable");
+                    }
+                };
+        try (BlobFormatWriter writer = writer(dir.resolve("ok.blob"), 
reporter)) {
+            writer.addElement(GenericRow.of(Blob.fromData(new byte[] {1})));
+        }
+        assertThat(reporter.transfers).isEmpty();
+        assertThat(reporter.successes).isEqualTo(1);
+    }
+
+    @Test
+    void openingFailureHasNoPayloadTiming(@TempDir Path dir) throws Exception {
+        Reporter reporter = new Reporter(true);
+        Blob blob =
+                Blob.fromInputStream(
+                        () -> {
+                            throw new IllegalStateException("open failed");
+                        });
+        try (BlobFormatWriter writer =
+                new BlobFormatWriter(
+                        new LocalFileIO.LocalPositionOutputStream(
+                                dir.resolve("null.blob").toFile()),
+                        null,
+                        RowType.of(DataTypes.BLOB()),
+                        false,
+                        true,
+                        reporter,
+                        2)) {
+            writer.addElement(GenericRow.of(blob));
+        }
+        assertThat(reporter.transfers).isEmpty();
+        assertThat(reporter.nullFailures).isEqualTo(1);
+    }
+
+    @Test
+    void exactRefsStillReuseSourceAndCountEmptyCopy(@TempDir Path dir) throws 
Exception {
+        Reporter reporter = new Reporter(true);
+        int[] opens = {0};
+        UriReader reader =
+                uri -> {
+                    opens[0]++;
+                    return new ByteArraySeekableStream(new byte[] {1, 2, 3, 
4});
+                };
+        try (BlobFormatWriter writer = writer(dir.resolve("refs.blob"), 
reporter)) {
+            writer.addElement(
+                    GenericRow.of(new BlobRef(reader, new 
BlobDescriptor("test://source", 0, 2))));
+            writer.addElement(
+                    GenericRow.of(new BlobRef(reader, new 
BlobDescriptor("test://source", 2, 2))));
+            writer.addElement(
+                    GenericRow.of(new BlobRef(reader, new 
BlobDescriptor("test://source", 4, 0))));
+        }
+        assertThat(opens[0]).isEqualTo(1);
+        assertThat(reporter.transfers).hasSize(3);
+        assertTransfer(reporter.transfers.get(0), 2, 2, true);
+        assertTransfer(reporter.transfers.get(1), 2, 2, true);
+        assertTransfer(reporter.transfers.get(2), 0, 0, true);
+    }
+
+    @Test
+    void nestedArrayAndMapUseSamePayloadBoundary(@TempDir Path dir) throws 
Exception {
+        Reporter reporter = new Reporter(true);
+        try (BlobFormatWriter writer =
+                new BlobFormatWriter(
+                        new LocalFileIO.LocalPositionOutputStream(
+                                dir.resolve("array.blob").toFile()),
+                        null,
+                        RowType.of(DataTypes.ARRAY(DataTypes.BLOB())),
+                        false,
+                        false,
+                        reporter,
+                        2)) {
+            writer.addElement(
+                    GenericRow.of(
+                            new GenericArray(
+                                    new Object[] {Blob.fromData(new byte[] {1, 
2, 3}), null})));
+        }
+        try (BlobFormatWriter writer =
+                new BlobFormatWriter(
+                        new 
LocalFileIO.LocalPositionOutputStream(dir.resolve("map.blob").toFile()),
+                        null,
+                        RowType.of(DataTypes.MAP(DataTypes.INT(), 
DataTypes.BLOB())),
+                        false,
+                        false,
+                        reporter,
+                        2)) {
+            writer.addElement(
+                    GenericRow.of(
+                            new GenericMap(
+                                    Collections.singletonMap(
+                                            1, Blob.fromData(new byte[] {4, 
5})))));
+        }
+        assertThat(reporter.transfers).hasSize(2);
+        assertTransfer(reporter.transfers.get(0), 3, 3, true);
+        assertTransfer(reporter.transfers.get(1), 2, 2, true);
+    }
+
+    private static BlobFormatWriter writer(Path path, Reporter reporter) 
throws IOException {
+        return new BlobFormatWriter(
+                new LocalFileIO.LocalPositionOutputStream(path.toFile()),
+                null,
+                RowType.of(DataTypes.BLOB()),
+                false,
+                false,
+                reporter,
+                2);
+    }
+
+    private static void assertTransfer(
+            long[] transfer, long read, long written, boolean completed) {
+        assertThat(transfer[0]).isEqualTo(read);
+        assertThat(transfer[1]).isEqualTo(written);
+        assertThat(transfer[2]).isGreaterThanOrEqualTo(0);
+        assertThat(transfer[3]).isEqualTo(completed ? 1 : 0);
+    }
+
+    private static class Reporter implements BlobFetchMetricReporter {
+        private final boolean enabled;
+        private final List<long[]> transfers = new ArrayList<>();
+        private boolean throwOnTransfer;
+        private int successes;
+        private int failures;
+        private int nullFailures;
+
+        private Reporter(boolean enabled) {
+            this.enabled = enabled;
+        }
+
+        @Override
+        public boolean isTransferMetricsEnabled() {
+            return enabled;
+        }
+
+        @Override
+        public void recordTransfer(long read, long written, long nanos, 
boolean completed) {
+            transfers.add(new long[] {read, written, nanos, completed ? 1 : 
0});
+            if (throwOnTransfer) {
+                throw new IllegalStateException("telemetry unavailable");
+            }
+        }
+
+        @Override
+        public void recordSuccess(long bytes) {
+            successes++;
+        }
+
+        @Override
+        public void recordMissingFileNullWritten(boolean httpNotFound) {}
+
+        @Override
+        public void recordFetchFailureNullWritten(Throwable throwable) {
+            nullFailures++;
+        }
+
+        @Override
+        public void recordFetchFailure(Throwable throwable) {
+            failures++;
+        }
+    }
+}

Reply via email to