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

devmadhuu pushed a commit to branch HDDS-11233
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/HDDS-11233 by this push:
     new 81bd58ebfe6 HDDS-17819. Add OM metrics for committed key bytes by 
storage policy, storage tier and fallback outcome. (#12071)
81bd58ebfe6 is described below

commit 81bd58ebfe6e0f72da3ddbfcedd333a718de7f98
Author: Devesh Kumar Singh <[email protected]>
AuthorDate: Thu Nov 26 13:14:56 2026 +0530

    HDDS-17819. Add OM metrics for committed key bytes by storage policy, 
storage tier and fallback outcome. (#12071)
---
 .../ozone/client/rpc/TestOzoneStoragePolicy.java   |  34 ++
 .../java/org/apache/hadoop/ozone/om/OMMetrics.java |  14 +-
 .../hadoop/ozone/om/OMStoragePolicyMetrics.java    | 180 +++++++++++
 .../ozone/om/request/key/OMKeyCommitRequest.java   |  10 +-
 .../om/request/key/OMKeyCommitRequestWithFSO.java  |   8 +-
 .../ozone/om/TestOMStoragePolicyMetrics.java       | 345 +++++++++++++++++++++
 .../om/request/key/TestOMKeyCommitRequest.java     |  97 ++++++
 7 files changed, 685 insertions(+), 3 deletions(-)

diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestOzoneStoragePolicy.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestOzoneStoragePolicy.java
index 2d763a2b77b..2c9c633b034 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestOzoneStoragePolicy.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/client/rpc/TestOzoneStoragePolicy.java
@@ -35,6 +35,7 @@
 import java.util.TreeMap;
 import java.util.UUID;
 import java.util.function.BooleanSupplier;
+import java.util.stream.Collectors;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.fs.StorageType;
@@ -61,6 +62,10 @@
 import org.apache.hadoop.hdds.scm.pipeline.PipelineManager;
 import org.apache.hadoop.hdds.scm.storage.ContainerProtocolCalls;
 import org.apache.hadoop.hdds.utils.IOUtils;
+import org.apache.hadoop.metrics2.AbstractMetric;
+import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
+import org.apache.hadoop.metrics2.impl.MetricsRecordImpl;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.ozone.HddsDatanodeService;
 import org.apache.hadoop.ozone.MiniOzoneCluster;
 import org.apache.hadoop.ozone.OzoneConsts;
@@ -165,6 +170,7 @@ public void testKeyStoragePolicyIsHonoured() throws 
Exception {
       OzoneBucket bucket = createBucket(null, BucketLayout.OBJECT_STORE);
       OmKeyInfo keyInfo = createKeyAndLookup(bucket, storagePolicy);
 
+      assertEquals(keyInfo.getDataSize(), policyBytes(storagePolicy, 
storagePolicy.getCreationTier(), "preferred"));
       assertKeyInfo(keyInfo, storagePolicy);
       assertScmContainerAndPipeline(keyInfo, storagePolicy.getCreationTier());
       assertDatanodeContainerAndBlock(keyInfo, 
storagePolicy.getCreationTier());
@@ -241,6 +247,7 @@ public void testStoragePolicyOnFsoBucket() throws Exception 
{
         createBucket(null, BucketLayout.FILE_SYSTEM_OPTIMIZED);
     OmKeyInfo keyInfo = createKeyAndLookup(bucket, OzoneStoragePolicy.HOT);
 
+    assertEquals(keyInfo.getDataSize(), policyBytes(OzoneStoragePolicy.HOT, 
StorageTier.SSD, "preferred"));
     assertKeyInfo(keyInfo, OzoneStoragePolicy.HOT);
     assertScmContainerAndPipeline(keyInfo,
         OzoneStoragePolicy.HOT.getCreationTier());
@@ -270,6 +277,7 @@ public void testEmptyKeyRecordsStoragePolicy() throws 
Exception {
     assertEquals(OzoneStoragePolicy.COLD, keyInfo.getStoragePolicy());
     assertTrue(keyInfo.getLatestVersionLocations()
         .getBlocksLatestVersionOnly().isEmpty());
+    assertEquals(0, policyBytes(OzoneStoragePolicy.COLD, StorageTier.ARCHIVE, 
"preferred"));
   }
 
   /**
@@ -312,6 +320,7 @@ public void 
testStoragePolicyHonouredOnSubsequentBlockAllocation()
 
     // Every block, not just the first, must sit on the tier the key asked for.
     assertAllBlocksOnTier(keyInfo, OzoneStoragePolicy.COLD.getCreationTier());
+    assertEquals(data.length, policyBytes(OzoneStoragePolicy.COLD, 
StorageTier.ARCHIVE, "preferred"));
   }
 
   /**
@@ -342,6 +351,8 @@ public void 
testOverwriteWithDifferentStoragePolicyUpdatesKey()
     // The recorded policy and the tier the data actually sits on must agree.
     assertEquals(OzoneStoragePolicy.COLD, overwritten.getStoragePolicy());
     assertAllBlocksOnTier(overwritten, 
OzoneStoragePolicy.COLD.getCreationTier());
+    assertEquals(original.getDataSize(), policyBytes(OzoneStoragePolicy.HOT, 
StorageTier.SSD, "preferred"));
+    assertEquals(overwritten.getDataSize(), 
policyBytes(OzoneStoragePolicy.COLD, StorageTier.ARCHIVE, "preferred"));
   }
 
   /**
@@ -459,6 +470,9 @@ public void 
testCheckReportsMismatchWhenKeyFellBackToFallbackTier() throws Excep
       OzoneBucket bucket = createBucket(null, BucketLayout.OBJECT_STORE);
       String keyName = UUID.randomUUID().toString();
       writeKey(bucket, keyName, OzoneStoragePolicy.HOT);
+      assertEquals(lookupKey(bucket, keyName).getDataSize(),
+          policyBytes(OzoneStoragePolicy.HOT, StorageTier.DISK, "fallback"));
+      assertEquals(0, policyBytes(OzoneStoragePolicy.HOT, StorageTier.SSD, 
"preferred"));
       OzoneKeyDetails keyDetails = bucket.getKey(keyName);
       waitForReplicaReports(scmClient, keyDetails);
 
@@ -629,6 +643,26 @@ private OzoneBucket createBucket(OzoneStoragePolicy 
storagePolicy,
     return store.getVolume(volumeName).getBucket(bucketName);
   }
 
+  private long policyBytes(OzoneStoragePolicy policy, StorageTier actualTier, 
String outcome) {
+    MetricsCollectorImpl collector = new MetricsCollectorImpl();
+    
DefaultMetricsSystem.instance().getSource("OMStoragePolicyMetrics").getMetrics(collector,
 true);
+    long bytes = 0;
+    for (MetricsRecordImpl record : collector.getRecords()) {
+      Map<String, String> tags = record.tags().stream()
+          .collect(Collectors.toMap(tag -> tag.name(), tag -> tag.value()));
+      if (policy.name().equals(tags.get("Policy")) && 
actualTier.name().equals(tags.get("ActualTier"))
+          && outcome.equals(tags.get("Outcome"))) {
+        assertEquals(policy.getCreationTier().name(), 
tags.get("RequestedTier"));
+        for (AbstractMetric metric : record.metrics()) {
+          if ("CommittedBytes".equals(metric.name())) {
+            bytes += metric.value().longValue();
+          }
+        }
+      }
+    }
+    return bytes;
+  }
+
   private void writeKey(OzoneBucket bucket, String keyName,
       OzoneStoragePolicy storagePolicy) throws IOException {
     byte[] data = UUID.randomUUID().toString().getBytes(UTF_8);
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMMetrics.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMMetrics.java
index 590675c9d5b..974dd523842 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMMetrics.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMMetrics.java
@@ -30,6 +30,7 @@
 import org.apache.hadoop.metrics2.lib.MutableCounterLong;
 import org.apache.hadoop.metrics2.lib.MutableGaugeInt;
 import org.apache.hadoop.metrics2.lib.MutableGaugeLong;
+import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
 import org.apache.hadoop.ozone.om.snapshot.OMSnapshotDirectoryMetrics;
 import org.apache.hadoop.util.Time;
 
@@ -214,6 +215,7 @@ public class OMMetrics implements OmMetadataReaderMetrics {
 
   // Metrics for total amount of data written
   private @Metric MutableCounterLong totalDataCommitted;
+  private final OMStoragePolicyMetrics storagePolicyMetrics = new 
OMStoragePolicyMetrics();
 
   // Metrics for total number of volumes, buckets and keys
 
@@ -276,9 +278,11 @@ public static OMMetrics create(ConfigurationSource conf) {
         ? OMConfigKeys.OZONE_OM_RATIS_EVENTS_MAX_LIMIT_DEFAULT
         : conf.getInt(OMConfigKeys.OZONE_OM_RATIS_EVENTS_MAX_LIMIT,
         OMConfigKeys.OZONE_OM_RATIS_EVENTS_MAX_LIMIT_DEFAULT);
-    return ms.register(SOURCE_NAME,
+    OMMetrics metrics = ms.register(SOURCE_NAME,
         "Ozone Manager Metrics",
         new OMMetrics(maxRatisEvents));
+    metrics.storagePolicyMetrics.register(conf);
+    return metrics;
   }
 
   public DBCheckpointMetrics getDBCheckpointMetrics() {
@@ -311,6 +315,13 @@ public void incDataCommittedBytes(long bytesWritten) {
     totalDataCommitted.incr(bytesWritten);
   }
 
+  /**
+   * Records final committed key bytes using allocation attributes retained 
before the client locations replace them.
+   */
+  public void incStoragePolicyCommittedBytes(OmKeyInfo allocatedKey, OmKeyInfo 
committedKey) {
+    storagePolicyMetrics.recordCommit(allocatedKey, committedKey);
+  }
+
   public void incNumVolumes() {
     numVolumes.incr();
   }
@@ -1619,6 +1630,7 @@ public String getRatisEvents() {
   }
 
   public void unRegister() {
+    storagePolicyMetrics.unregister();
     if (dbCheckpointMetrics != null) {
       dbCheckpointMetrics.unRegister();
     }
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMStoragePolicyMetrics.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMStoragePolicyMetrics.java
new file mode 100644
index 00000000000..72aa2e128eb
--- /dev/null
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMStoragePolicyMetrics.java
@@ -0,0 +1,180 @@
+/*
+ * 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.hadoop.ozone.om;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.commons.lang3.tuple.Triple;
+import org.apache.hadoop.hdds.client.ContainerBlockID;
+import org.apache.hadoop.hdds.client.OzoneStoragePolicy;
+import org.apache.hadoop.hdds.client.StorageTier;
+import org.apache.hadoop.hdds.conf.ConfigurationSource;
+import org.apache.hadoop.metrics2.MetricsCollector;
+import org.apache.hadoop.metrics2.MetricsInfo;
+import org.apache.hadoop.metrics2.MetricsSource;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+import org.apache.hadoop.metrics2.lib.Interns;
+import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
+import org.apache.hadoop.ozone.util.MetricUtil;
+
+/**
+ * Committed logical bytes attributed to each block's storage-policy 
allocation outcome. Bytes from a key
+ * spanning multiple tiers are counted separately per tier. These are per-OM 
counters with the same commit
+ * boundary as {@code OMMetrics.TotalDataCommitted}, not current 
physical-volume usage.
+ */
+public final class OMStoragePolicyMetrics implements MetricsSource {
+  private static final String SOURCE_NAME = 
OMStoragePolicyMetrics.class.getSimpleName();
+  private static final MetricsInfo POLICY = Interns.info("Policy", "Recorded 
key storage policy");
+  private static final MetricsInfo REQUESTED_TIER = 
Interns.info("RequestedTier", "Policy creation tier");
+  private static final MetricsInfo ACTUAL_TIER = Interns.info("ActualTier", 
"SCM-selected tiers of committed blocks");
+  private static final MetricsInfo OUTCOME = Interns.info("Outcome", 
"Preferred, fallback or unknown allocation");
+  private static final MetricsInfo COMMITTED_BYTES = 
Interns.info("CommittedBytes", "Committed logical key bytes");
+
+  private static final String UNKNOWN = "UNKNOWN";
+
+  // Keyed by policy, the SCM-selected StorageTier (null when unknown) and the 
outcome. These bound metric
+  // cardinality; key, bucket and volume names are never retained or exported.
+  private final ConcurrentMap<Triple<OzoneStoragePolicy, StorageTier, 
Outcome>, AtomicLong> committedBytes =
+      new ConcurrentHashMap<>();
+  private String sourceName;
+
+  private enum Outcome {
+    PREFERRED, FALLBACK, UNKNOWN
+  }
+
+  /** Registers this source once; repeated calls on the same instance are 
no-ops. */
+  synchronized void register(ConfigurationSource conf) {
+    if (sourceName != null) {
+      return;
+    }
+    String name = MetricUtil.getMetricsSourceName(SOURCE_NAME,
+        conf == null ? null : 
conf.get(OMConfigKeys.OZONE_OM_INTERNAL_SERVICE_ID),
+        conf == null ? null : conf.get(OMConfigKeys.OZONE_OM_NODE_ID_KEY));
+    DefaultMetricsSystem.instance().register(name, "OM storage policy commit 
metrics", this);
+    sourceName = name;
+  }
+
+  /** Unregisters this source if registered, so a later {@link #register} can 
register it again. */
+  synchronized void unregister() {
+    if (sourceName != null) {
+      DefaultMetricsSystem.instance().unregisterSource(sourceName);
+      sourceName = null;
+    }
+  }
+
+  /**
+   * Counts one successful final commit using OM-owned allocation metadata and 
the accepted committed block IDs.
+   * Client commit locations can omit or disagree with allocation attributes. 
Neither key is modified or retained.
+   * Committed block lengths split the key size across series; unaccounted 
bytes are UNKNOWN. Invalid lengths
+   * make the entire key UNKNOWN so counters cannot exceed its size. Empty 
keys add no bytes. Callers must exclude
+   * failures and intermediate hsync commits.
+   */
+  void recordCommit(OmKeyInfo allocatedKey, OmKeyInfo committedKey) {
+    if (committedKey == null || committedKey.getDataSize() <= 0) {
+      return;
+    }
+    OzoneStoragePolicy policy = committedKey.getStoragePolicy() instanceof 
OzoneStoragePolicy
+        ? (OzoneStoragePolicy) committedKey.getStoragePolicy() : null;
+    StorageTier requestedTier = knownTier(policy == null ? null : 
policy.getCreationTier());
+    Map<ContainerBlockID, OmKeyLocationInfo> allocations = new HashMap<>();
+    OmKeyLocationInfoGroup allocatedLocations = allocatedKey == null ? null : 
allocatedKey.getLatestVersionLocations();
+    if (allocatedLocations != null) {
+      for (List<OmKeyLocationInfo> locations : 
allocatedLocations.getLocationLists()) {
+        for (OmKeyLocationInfo location : locations) {
+          allocations.put(location.getBlockID().getContainerBlockID(), 
location);
+        }
+      }
+    }
+
+    Map<Triple<OzoneStoragePolicy, StorageTier, Outcome>, Long> blockBytes = 
new HashMap<>();
+    long remaining = committedKey.getDataSize();
+    OmKeyLocationInfoGroup committedLocations = 
committedKey.getLatestVersionLocations();
+    if (committedLocations != null) {
+      for (OmKeyLocationInfo committed : 
committedLocations.getBlocksLatestVersionOnly()) {
+        long length = committed.getLength();
+        if (length < 0 || length > remaining) {
+          // Inconsistent lengths cannot support an accurate split. Preserve 
the total without guessing a tier.
+          addBytes(Triple.of(policy, null, Outcome.UNKNOWN), 
committedKey.getDataSize());
+          return;
+        }
+        if (length == 0) {
+          continue;
+        }
+        remaining -= length;
+        OmKeyLocationInfo allocated = 
allocations.get(committed.getBlockID().getContainerBlockID());
+        StorageTier selected = knownTier(allocated == null ? null : 
allocated.getStorageTier());
+        blockBytes.merge(Triple.of(policy, selected, outcome(allocated, 
requestedTier, selected)), length, Long::sum);
+      }
+    }
+    if (remaining > 0) {
+      blockBytes.merge(Triple.of(policy, null, Outcome.UNKNOWN), remaining, 
Long::sum);
+    }
+    blockBytes.forEach(this::addBytes);
+  }
+
+  private void addBytes(Triple<OzoneStoragePolicy, StorageTier, Outcome> 
attribution, long bytes) {
+    committedBytes.computeIfAbsent(attribution, ignored -> new 
AtomicLong()).addAndGet(bytes);
+  }
+
+  /** FALLBACK if OM allocated the block as fallback; PREFERRED if its tier is 
the requested tier; else UNKNOWN. */
+  private static Outcome outcome(OmKeyLocationInfo allocated, StorageTier 
requested, StorageTier selected) {
+    if (allocated != null && allocated.getIsFallBack()) {
+      // Kept even when the tier is unknown.
+      return Outcome.FALLBACK;
+    }
+    if (requested != null && selected == requested) {
+      return Outcome.PREFERRED;
+    }
+    // No allocation record, or a tier mismatch without a fallback flag.
+    return Outcome.UNKNOWN;
+  }
+
+  /**
+   * Returns the tier when it names real storage, or null when it is unknown. 
EMPTY only marks "no fallback tier"
+   * on a policy and is never a block's tier, so it is treated as unknown.
+   */
+  private static StorageTier knownTier(StorageTier storageTier) {
+    return storageTier == StorageTier.EMPTY ? null : storageTier;
+  }
+
+  /** The exported tier label: the StorageTier name, or UNKNOWN. A new 
StorageTier is reported under its own name. */
+  static String tierLabel(StorageTier storageTier) {
+    StorageTier tier = knownTier(storageTier);
+    return tier == null ? UNKNOWN : tier.name();
+  }
+
+  @Override
+  public void getMetrics(MetricsCollector collector, boolean all) {
+    committedBytes.forEach((attribution, bytes) -> {
+      OzoneStoragePolicy policy = attribution.getLeft();
+      collector.addRecord(SOURCE_NAME).setContext("dfs")
+          .tag(POLICY, policy == null ? UNKNOWN : policy.name())
+          .tag(REQUESTED_TIER, tierLabel(policy == null ? null : 
policy.getCreationTier()))
+          .tag(ACTUAL_TIER, tierLabel(attribution.getMiddle()))
+          .tag(OUTCOME, attribution.getRight().name().toLowerCase(Locale.ROOT))
+          .addCounter(COMMITTED_BYTES, bytes.get());
+    });
+  }
+}
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/key/OMKeyCommitRequest.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/key/OMKeyCommitRequest.java
index d745c23d66e..026f0ce608e 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/key/OMKeyCommitRequest.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/key/OMKeyCommitRequest.java
@@ -155,6 +155,7 @@ public OMClientResponse validateAndUpdateCache(OzoneManager 
ozoneManager, Execut
 
     Exception exception = null;
     OmKeyInfo omKeyInfo = null;
+    OmKeyInfo allocatedKeyInfo = null;
     OmBucketInfo omBucketInfo = null;
     OMClientResponse omClientResponse = null;
     boolean bucketLockAcquired = false;
@@ -251,6 +252,10 @@ public OMClientResponse 
validateAndUpdateCache(OzoneManager ozoneManager, Execut
           keyName, writerClientId);
       omKeyInfo =
           omMetadataManager.getOpenKeyTable(getBucketLayout()).get(dbOpenKey);
+      // Keep the allocated block tiers and fallback flags for 
successful-commit metrics. No copy is needed: get()
+      // returns a request-private object, later steps rebuild omKeyInfo via 
toBuilder() (which copies the location
+      // groups) before updating locations, and this reference never enters 
the table cache or the response.
+      allocatedKeyInfo = omKeyInfo;
       if (omKeyInfo == null) {
         String action = isRecovery ? "recovery" : isHSync ? "hsync" : "commit";
         throw new OMException("Failed to " + action + " key, as " + dbOpenKey +
@@ -437,7 +442,7 @@ public OMClientResponse validateAndUpdateCache(OzoneManager 
ozoneManager, Execut
       markForAudit(auditLogger, buildAuditMessage(OMAction.COMMIT_KEY, 
auditMap,
               exception, getOmRequest().getUserInfo()));
       processResult(commitKeyRequest, volumeName, bucketName, keyName,
-          omMetrics, exception, omKeyInfo, result);
+          omMetrics, exception, omKeyInfo, allocatedKeyInfo, result);
     }
 
     return omClientResponse;
@@ -472,6 +477,7 @@ protected List<OmKeyLocationInfo> getOmKeyLocationInfos(
    * @param omMetrics        om metrics
    * @param exception        exception trace
    * @param omKeyInfo        omKeyInfo
+   * @param allocatedKeyInfo original open key retaining OM's allocated tiers 
and fallback flags
    * @param result           stores the result of the execution
    */
   @SuppressWarnings("parameternumber")
@@ -479,6 +485,7 @@ protected void processResult(CommitKeyRequest 
commitKeyRequest,
                                String volumeName, String bucketName,
                                String keyName, OMMetrics omMetrics,
                                Exception exception, OmKeyInfo omKeyInfo,
+                               OmKeyInfo allocatedKeyInfo,
                                Result result) {
     switch (result) {
     case SUCCESS:
@@ -494,6 +501,7 @@ protected void processResult(CommitKeyRequest 
commitKeyRequest,
         omMetrics.incEcKeysTotal();
       }
       omMetrics.incDataCommittedBytes(omKeyInfo.getDataSize());
+      omMetrics.incStoragePolicyCommittedBytes(allocatedKeyInfo, omKeyInfo);
       LOG.debug("Key committed. Volume:{}, Bucket:{}, Key:{}", volumeName,
               bucketName, keyName);
       break;
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/key/OMKeyCommitRequestWithFSO.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/key/OMKeyCommitRequestWithFSO.java
index fc2c6e73f75..2ab4b815346 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/key/OMKeyCommitRequestWithFSO.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/request/key/OMKeyCommitRequestWithFSO.java
@@ -274,6 +274,10 @@ private void buildCommittedKey(CommitKeyRequest 
commitKeyRequest, PreparedCommit
     final boolean isHSync = commitKeyRequest.hasHsync() && 
commitKeyRequest.getHsync();
     final String clientIdString = 
String.valueOf(commitKeyRequest.getClientID());
 
+    // Keep the allocated block tiers and fallback flags for metrics. No copy 
is needed: the open key is
+    // request-private, the committed key is rebuilt via toBuilder() (which 
copies the location groups) before its
+    // locations are updated, and this reference never enters the table cache 
or the response.
+    prepared.allocatedKeyInfo = prepared.omKeyInfo;
     
prepared.omKeyInfo.setModificationTime(commitKeyArgs.getModificationTime());
 
     if (isHSync) {
@@ -500,6 +504,7 @@ private static final class PreparedCommit {
     private OmKeyInfo newOpenKeyInfo;
     private List<OmKeyLocationInfo> uncommitted;
     private OmKeyInfo omKeyInfo;
+    private OmKeyInfo allocatedKeyInfo;
   }
 
   /**
@@ -528,7 +533,8 @@ private void auditAndLogResult(OzoneManager ozoneManager, 
CommitKeyRequest commi
       markForAudit(ozoneManager.getAuditLogger(), 
buildAuditMessage(OMAction.COMMIT_KEY, auditMap,
               exception, getOmRequest().getUserInfo()));
       processResult(commitKeyRequest, commitKeyArgs.getVolumeName(), 
commitKeyArgs.getBucketName(),
-          commitKeyArgs.getKeyName(), ozoneManager.getMetrics(), exception, 
prepared.omKeyInfo, result);
+          commitKeyArgs.getKeyName(), ozoneManager.getMetrics(), exception, 
prepared.omKeyInfo,
+          prepared.allocatedKeyInfo, result);
     }
   }
 }
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOMStoragePolicyMetrics.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOMStoragePolicyMetrics.java
new file mode 100644
index 00000000000..dc756731229
--- /dev/null
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOMStoragePolicyMetrics.java
@@ -0,0 +1,345 @@
+/*
+ * 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.hadoop.ozone.om;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+import java.io.StringWriter;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.ECReplicationConfig;
+import org.apache.hadoop.hdds.client.OzoneStoragePolicy;
+import org.apache.hadoop.hdds.client.RatisReplicationConfig;
+import org.apache.hadoop.hdds.client.StorageTier;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.server.http.PrometheusMetricsSink;
+import org.apache.hadoop.metrics2.AbstractMetric;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
+import org.apache.hadoop.metrics2.impl.MetricsRecordImpl;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/** Tests attribution, export and lifecycle of committed storage-policy bytes. 
*/
+public class TestOMStoragePolicyMetrics {
+  @ParameterizedTest
+  @EnumSource(OzoneStoragePolicy.class)
+  void testPreferredPolicy(OzoneStoragePolicy policy) throws Exception {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo allocated = key(policy, 100, block(1, 100, 
policy.getCreationTier(), false));
+    // Client locations omit the allocation attributes; OM's evidence is 
authoritative.
+    metrics.recordCommit(allocated, key(policy, 100, block(1, 100, null, 
false)));
+    assertThat(export(metrics)).contains("policy=\"" + policy.name() + "\"")
+        .contains("requestedtier=\"" + policy.getCreationTier().name() + "\"")
+        .contains("actualtier=\"" + policy.getCreationTier().name() + "\"")
+        .contains("outcome=\"preferred\"").contains(" 100\n");
+  }
+
+  @Test
+  void testMixedKeySplitsCommittedBytesAndIgnoresClientClaims() throws 
Exception {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo allocated = key(OzoneStoragePolicy.HOT, 12,
+        block(1, StorageTier.SSD, false), block(2, StorageTier.DISK, true));
+    metrics.recordCommit(allocated, key(OzoneStoragePolicy.HOT, 12,
+        block(1, 8, StorageTier.ARCHIVE, true), block(2, 4, StorageTier.SSD, 
false)));
+    assertThat(snapshot(metrics)).isEqualTo(Map.of(
+        "HOT/SSD/SSD/preferred", 8L, "HOT/SSD/DISK/fallback", 4L));
+    String text = export(metrics);
+    assertThat(text).contains("# TYPE 
om_storage_policy_metrics_committed_bytes counter")
+        .doesNotContain("MIXED", "bucket=", "key=", "volume=", "user=");
+    assertThat(text.lines().filter(line -> 
!line.startsWith("#")).count()).isEqualTo(2);
+    
assertThat(allocated.getLatestVersionLocations().getBlocksLatestVersionOnly().get(0).getStorageTier())
+        .isEqualTo(StorageTier.SSD);
+  }
+
+  @Test
+  void testBlocksOnSameTierAggregateWithoutMixingOutcomes() {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo allocated = key(OzoneStoragePolicy.WARM, 18,
+        block(1, StorageTier.DISK, false), block(2, StorageTier.DISK, false), 
block(3, StorageTier.DISK, true));
+    metrics.recordCommit(allocated, allocated);
+    assertThat(snapshot(metrics)).isEqualTo(Map.of(
+        "WARM/DISK/DISK/preferred", 12L, "WARM/DISK/DISK/fallback", 6L));
+  }
+
+  @Test
+  void testUnusedPreallocationAndEmptyBlockDoNotImplyFallback() throws 
Exception {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo allocated = key(OzoneStoragePolicy.HOT, 12,
+        block(1, StorageTier.SSD, false), block(2, StorageTier.DISK, true));
+    OmKeyLocationInfo empty = block(2, null, false);
+    empty.setLength(0);
+    metrics.recordCommit(allocated, key(OzoneStoragePolicy.HOT, 6, block(1, 
null, false), empty));
+    
assertThat(export(metrics)).contains("actualtier=\"SSD\"").contains("outcome=\"preferred\"");
+  }
+
+  @Test
+  void testLegacyAndIncompleteEvidenceIsUnknown() throws Exception {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    metrics.recordCommit(null, key(null, 10, block(1, StorageTier.DISK, 
false)));
+    metrics.recordCommit(key(OzoneStoragePolicy.HOT, 20, block(1, null, 
false)),
+        key(OzoneStoragePolicy.HOT, 20, block(1, StorageTier.SSD, false)));
+    String text = export(metrics);
+    
assertThat(text).contains("policy=\"UNKNOWN\",requestedtier=\"UNKNOWN\",actualtier=\"UNKNOWN\"")
+        
.contains("policy=\"HOT\",requestedtier=\"SSD\",actualtier=\"UNKNOWN\"")
+        .doesNotContain("outcome=\"preferred\"");
+  }
+
+  @Test
+  void testKnownFallbackAndUnknownBlocksAreCountedSeparately() {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    metrics.recordCommit(key(OzoneStoragePolicy.HOT, 12, block(1, 
StorageTier.DISK, true)),
+        key(OzoneStoragePolicy.HOT, 12, block(1, null, false), block(2, null, 
false)));
+    assertThat(snapshot(metrics)).isEqualTo(Map.of(
+        "HOT/SSD/DISK/fallback", 6L, "HOT/SSD/UNKNOWN/unknown", 6L));
+  }
+
+  @Test
+  void testFallbackWithUnknownTierRetainsKnownOutcome() {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo key = key(OzoneStoragePolicy.HOT, 6, block(1, null, true));
+    metrics.recordCommit(key, key);
+    assertThat(snapshot(metrics)).isEqualTo(Map.of("HOT/SSD/UNKNOWN/fallback", 
6L));
+  }
+
+  @Test
+  void testUnaccountedBytesAreUnknown() {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo key = key(OzoneStoragePolicy.HOT, 10, block(1, StorageTier.SSD, 
false));
+    metrics.recordCommit(key, key);
+    assertThat(snapshot(metrics)).isEqualTo(Map.of(
+        "HOT/SSD/SSD/preferred", 6L, "HOT/SSD/UNKNOWN/unknown", 4L));
+  }
+
+  @ParameterizedTest
+  @ValueSource(longs = {-1, 7, Long.MAX_VALUE})
+  void testInvalidBlockLengthsDoNotOvercountOrPartiallyPublish(long 
invalidLength) {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    // First block is valid, but neither it nor the invalid block may leak 
into the counters.
+    OmKeyInfo key = key(OzoneStoragePolicy.HOT, 12,
+        block(1, StorageTier.SSD, false), block(2, invalidLength, 
StorageTier.DISK, true));
+    metrics.recordCommit(key, key);
+    assertThat(snapshot(metrics)).isEqualTo(Map.of("HOT/SSD/UNKNOWN/unknown", 
12L));
+  }
+
+  @Test
+  void testLargestValidLogicalSizeDoesNotOverflow() {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo key = key(OzoneStoragePolicy.HOT, Long.MAX_VALUE,
+        block(1, Long.MAX_VALUE - 1, StorageTier.SSD, false), block(2, 1, 
StorageTier.DISK, true));
+    metrics.recordCommit(key, key);
+    assertThat(snapshot(metrics)).isEqualTo(Map.of(
+        "HOT/SSD/SSD/preferred", Long.MAX_VALUE - 1, "HOT/SSD/DISK/fallback", 
1L));
+  }
+
+  @Test
+  void testECCountsLogicalBytesWithoutReplicationOverhead() {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo key = key(OzoneStoragePolicy.HOT, 12,
+        block(1, 8, StorageTier.SSD, false), block(2, 4, StorageTier.DISK, 
true))
+        .toBuilder().setReplicationConfig(new ECReplicationConfig(3, 
2)).build();
+    metrics.recordCommit(key, key);
+    assertThat(snapshot(metrics)).isEqualTo(Map.of(
+        "HOT/SSD/SSD/preferred", 8L, "HOT/SSD/DISK/fallback", 4L));
+  }
+
+  @Test
+  void testInconsistentTierWithoutFallbackEvidenceIsUnknown() throws Exception 
{
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo key = key(OzoneStoragePolicy.HOT, 6, block(1, StorageTier.DISK, 
false));
+    metrics.recordCommit(key, key);
+    
assertThat(export(metrics)).contains("actualtier=\"DISK\"").contains("outcome=\"unknown\"");
+  }
+
+  @Test
+  void testEmptyAndMissingLocations() throws Exception {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    metrics.recordCommit(null, null);
+    metrics.recordCommit(null, key(OzoneStoragePolicy.HOT, 0));
+    assertThat(export(metrics)).isEmpty();
+    metrics.recordCommit(null, key(OzoneStoragePolicy.HOT, 10));
+    
assertThat(export(metrics)).contains("actualtier=\"UNKNOWN\"").contains("outcome=\"unknown\"");
+  }
+
+  @Test
+  void testHistoricalVersionsDoNotChangeCurrentKeyAttribution() throws 
Exception {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyLocationInfo old = block(1, StorageTier.DISK, true);
+    OmKeyLocationInfo current = block(2, 10, StorageTier.SSD, false);
+    current.setCreateVersion(1);
+    OmKeyInfo allocated = key(OzoneStoragePolicy.HOT, 
10).toBuilder().setOmKeyLocationInfos(Arrays.asList(
+        new OmKeyLocationInfoGroup(0, Collections.singletonList(old)),
+        new OmKeyLocationInfoGroup(1, Arrays.asList(old, current)))).build();
+    OmKeyInfo committed = allocated.toBuilder().build();
+    metrics.recordCommit(allocated, committed);
+    
assertThat(export(metrics)).contains("actualtier=\"SSD\"").contains("outcome=\"preferred\"")
+        .contains(" 10\n");
+  }
+
+  @Test
+  void testOMMetricsOwnsRegistrationAndCleanup() {
+    OMMetrics owner = OMMetrics.create(null);
+    try {
+      
assertThat(DefaultMetricsSystem.instance().getSource("OMStoragePolicyMetrics"))
+          .isInstanceOf(OMStoragePolicyMetrics.class);
+    } finally {
+      owner.unRegister();
+    }
+    
assertNull(DefaultMetricsSystem.instance().getSource("OMStoragePolicyMetrics"));
+  }
+
+  @Test
+  void testConcurrentCommitsAndScrapes() throws Exception {
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    OmKeyInfo key = key(OzoneStoragePolicy.HOT, 12,
+        block(1, 8, StorageTier.SSD, false), block(2, 4, StorageTier.DISK, 
true));
+    ExecutorService executor = Executors.newFixedThreadPool(4);
+    try {
+      List<Future<?>> futures = IntStream.range(0, 4).mapToObj(i -> 
executor.submit(() -> {
+        for (int j = 0; j < 100; j++) {
+          metrics.recordCommit(key, key);
+          metrics.getMetrics(new MetricsCollectorImpl(), true);
+        }
+      })).collect(Collectors.toList());
+      for (Future<?> future : futures) {
+        future.get();
+      }
+    } finally {
+      executor.shutdownNow();
+    }
+    assertThat(snapshot(metrics)).isEqualTo(Map.of(
+        "HOT/SSD/SSD/preferred", 3200L, "HOT/SSD/DISK/fallback", 1600L));
+  }
+
+  /**
+   * A started metrics system, as in a running OM, rejects a second 
registration of the same source name, so
+   * repeated calls on one instance must not register twice.
+   */
+  @Test
+  void testRepeatedRegisterAndUnregisterAreSafe() {
+    MetricsSystem metricsSystem = 
DefaultMetricsSystem.initialize("TestOMStoragePolicyMetrics");
+    boolean miniClusterMode = DefaultMetricsSystem.inMiniClusterMode();
+    DefaultMetricsSystem.setMiniClusterMode(false);
+    OMStoragePolicyMetrics metrics = new OMStoragePolicyMetrics();
+    try {
+      metrics.register(null);
+      metrics.register(null);
+      assertSame(metrics, metricsSystem.getSource("OMStoragePolicyMetrics"));
+      metrics.unregister();
+      metrics.unregister();
+      assertNull(metricsSystem.getSource("OMStoragePolicyMetrics"));
+      metrics.register(null);
+      assertSame(metrics, metricsSystem.getSource("OMStoragePolicyMetrics"));
+    } finally {
+      metrics.unregister();
+      DefaultMetricsSystem.shutdown();
+      DefaultMetricsSystem.setMiniClusterMode(miniClusterMode);
+    }
+  }
+
+  @Test
+  void testSourceLifecycleAndReset() throws Exception {
+    boolean miniClusterMode = DefaultMetricsSystem.inMiniClusterMode();
+    DefaultMetricsSystem.setMiniClusterMode(true);
+    OzoneConfiguration firstConf = new OzoneConfiguration();
+    firstConf.set(OMConfigKeys.OZONE_OM_INTERNAL_SERVICE_ID, "service");
+    firstConf.set(OMConfigKeys.OZONE_OM_NODE_ID_KEY, "one");
+    OzoneConfiguration secondConf = new OzoneConfiguration(firstConf);
+    secondConf.set(OMConfigKeys.OZONE_OM_NODE_ID_KEY, "two");
+    OMStoragePolicyMetrics first = new OMStoragePolicyMetrics();
+    OMStoragePolicyMetrics second = new OMStoragePolicyMetrics();
+    try {
+      first.register(firstConf);
+      second.register(secondConf);
+      assertSame(first, 
DefaultMetricsSystem.instance().getSource("OMStoragePolicyMetrics-service-one"));
+      assertSame(second, 
DefaultMetricsSystem.instance().getSource("OMStoragePolicyMetrics-service-two"));
+      first.recordCommit(null, key(null, 10));
+      first.unregister();
+      
assertNull(DefaultMetricsSystem.instance().getSource("OMStoragePolicyMetrics-service-one"));
+      assertSame(second, 
DefaultMetricsSystem.instance().getSource("OMStoragePolicyMetrics-service-two"));
+      first = new OMStoragePolicyMetrics();
+      first.register(firstConf);
+      assertThat(export(first)).isEmpty();
+    } finally {
+      first.unregister();
+      second.unregister();
+      DefaultMetricsSystem.setMiniClusterMode(miniClusterMode);
+    }
+  }
+
+  private static OmKeyLocationInfo block(long localID, StorageTier tier, 
boolean fallback) {
+    return block(localID, 6, tier, fallback);
+  }
+
+  private static OmKeyLocationInfo block(long localID, long length, 
StorageTier tier, boolean fallback) {
+    return new OmKeyLocationInfo.Builder().setBlockID(new BlockID(1, 
localID)).setLength(length)
+        .setStorageTier(tier).setIsFallBack(fallback).build();
+  }
+
+  private static Map<String, Long> snapshot(OMStoragePolicyMetrics metrics) {
+    MetricsCollectorImpl collector = new MetricsCollectorImpl();
+    metrics.getMetrics(collector, true);
+    Map<String, Long> result = new HashMap<>();
+    for (MetricsRecordImpl record : collector.getRecords()) {
+      Map<String, String> tags = record.tags().stream()
+          .collect(Collectors.toMap(tag -> tag.name(), tag -> tag.value()));
+      for (AbstractMetric metric : record.metrics()) {
+        result.put(tags.get("Policy") + "/" + tags.get("RequestedTier") + "/" 
+ tags.get("ActualTier") + "/"
+            + tags.get("Outcome"), metric.value().longValue());
+      }
+    }
+    return result;
+  }
+
+  private static OmKeyInfo key(OzoneStoragePolicy policy, long size, 
OmKeyLocationInfo... blocks) {
+    return new 
OmKeyInfo.Builder().setVolumeName("volume").setBucketName("bucket").setKeyName("key")
+        
.setReplicationConfig(RatisReplicationConfig.getInstance(HddsProtos.ReplicationFactor.THREE))
+        .setDataSize(size).setStoragePolicy(policy)
+        .setOmKeyLocationInfos(Collections.singletonList(new 
OmKeyLocationInfoGroup(0, Arrays.asList(blocks))))
+        .build();
+  }
+
+  private static String export(OMStoragePolicyMetrics metrics) throws 
Exception {
+    MetricsCollectorImpl collector = new MetricsCollectorImpl();
+    metrics.getMetrics(collector, true);
+    PrometheusMetricsSink sink = new PrometheusMetricsSink("om");
+    collector.getRecords().forEach(sink::putMetrics);
+    sink.flush();
+    StringWriter writer = new StringWriter();
+    sink.writeMetrics(writer);
+    return writer.toString();
+  }
+}
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/key/TestOMKeyCommitRequest.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/key/TestOMKeyCommitRequest.java
index f14b0006aff..133cd8416a6 100644
--- 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/key/TestOMKeyCommitRequest.java
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/key/TestOMKeyCommitRequest.java
@@ -38,11 +38,16 @@
 import java.util.Map;
 import java.util.UUID;
 import java.util.stream.Collectors;
+import org.apache.hadoop.hdds.client.OzoneStoragePolicy;
 import org.apache.hadoop.hdds.client.RatisReplicationConfig;
+import org.apache.hadoop.hdds.client.StorageTier;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
 import org.apache.hadoop.hdds.utils.db.BatchOperation;
 import org.apache.hadoop.hdds.utils.db.Table;
+import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
+import org.apache.hadoop.metrics2.impl.MetricsRecordImpl;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.ozone.OmUtils;
 import org.apache.hadoop.ozone.OzoneAcl;
 import org.apache.hadoop.ozone.OzoneConfigKeys;
@@ -67,6 +72,7 @@
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
 
 /**
  * Class tests OMKeyCommitRequest class.
@@ -722,6 +728,8 @@ public void 
testValidateAndUpdateCacheWithBucketQuotaExceeds()
 
     assertEquals(OzoneManagerProtocolProtos.Status.QUOTA_EXCEEDED,
         omClientResponse.getOMResponse().getStatus());
+    assertThat(storagePolicyRecords().getRecords()).isEmpty();
+    assertEquals(0, omMetrics.getDataCommittedBytes());
 
     OmBucketInfo bucketInfo = omMetadataManager.getBucketTable()
         .get(omMetadataManager.getBucketKey(volumeName, bucketName));
@@ -982,6 +990,95 @@ public void testPreAllocatedUncommittedBlockForEmptyFile() 
throws Exception {
     assertNotNull(omKeyInfo);
   }
 
+  @Test
+  public void testStoragePolicyMetricsUseAcceptedAllocationEvidence() throws 
Exception {
+    OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName, 
omMetadataManager, getBucketLayout());
+    List<KeyLocation> clientLocations = getKeyLocation(3);
+    List<OmKeyLocationInfo> allocated = 
clientLocations.stream().map(OmKeyLocationInfo::getFromProtobuf)
+        .collect(Collectors.toList());
+    allocated.get(0).setStorageTier(StorageTier.SSD);
+    allocated.get(1).setStorageTier(StorageTier.DISK);
+    allocated.get(1).setIsFallBack(true);
+    allocated.get(2).setStorageTier(StorageTier.ARCHIVE);
+    allocated.get(2).setIsFallBack(true);
+    String openKey = addKeyToOpenKeyTable(allocated);
+    Table<String, OmKeyInfo> openTable = 
omMetadataManager.getOpenKeyTable(getBucketLayout());
+    openTable.put(openKey, 
openTable.get(openKey).toBuilder().setStoragePolicy(OzoneStoragePolicy.HOT).build());
+    dataSize = 400;
+    clientLocations.set(0, 
clientLocations.get(0).toBuilder().setLength(300).build());
+    clientLocations.set(1, 
clientLocations.get(1).toBuilder().setLength(100).build());
+    // The unused ARCHIVE allocation must not affect attribution. The client 
echoes no tier attributes.
+    OMRequest request = 
doPreExecute(createCommitKeyRequest(clientLocations.subList(0, 2), false));
+    OMClientResponse response = 
getOmKeyCommitRequest(request).validateAndUpdateCache(ozoneManager, 101L);
+    assertEquals(OK, response.getOMResponse().getStatus());
+    assertEquals(2, storagePolicyRecords().getRecords().size());
+    assertPolicyMetric("HOT", "SSD", "SSD", "preferred", 300);
+    assertPolicyMetric("HOT", "SSD", "DISK", "fallback", 100);
+    assertEquals(400, omMetrics.getDataCommittedBytes());
+    assertNull(openTable.get(openKey));
+    OmKeyInfo committed = 
omMetadataManager.getKeyTable(getBucketLayout()).get(getOzonePathKey());
+    assertEquals(2, 
committed.getLatestVersionLocations().getBlocksLatestVersionOnly().size());
+    // A second application cannot count another commit after the open key has 
been removed.
+    response = 
getOmKeyCommitRequest(request).validateAndUpdateCache(ozoneManager, 102L);
+    assertEquals(KEY_NOT_FOUND, response.getOMResponse().getStatus());
+    assertEquals(2, storagePolicyRecords().getRecords().size());
+    assertPolicyMetric("HOT", "SSD", "SSD", "preferred", 300);
+    assertPolicyMetric("HOT", "SSD", "DISK", "fallback", 100);
+    assertEquals(400, omMetrics.getDataCommittedBytes());
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void 
testStoragePolicyMetricsCountFinalCloseOrRecoveryAfterHsync(boolean recovery) 
throws Exception {
+    OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName, 
omMetadataManager, getBucketLayout());
+    List<KeyLocation> locations = getKeyLocation(1);
+    List<OmKeyLocationInfo> allocated = 
locations.stream().map(OmKeyLocationInfo::getFromProtobuf)
+        .collect(Collectors.toList());
+    allocated.get(0).setStorageTier(StorageTier.SSD);
+    String openKey = addKeyToOpenKeyTable(allocated);
+    Table<String, OmKeyInfo> openTable = 
omMetadataManager.getOpenKeyTable(getBucketLayout());
+    openTable.put(openKey, 
openTable.get(openKey).toBuilder().setStoragePolicy(OzoneStoragePolicy.HOT).build());
+    dataSize = 200;
+    for (long transaction = 101; transaction <= 102; transaction++) {
+      OMRequest hsync = doPreExecute(createCommitKeyRequest(locations, true));
+      assertEquals(OK, 
getOmKeyCommitRequest(hsync).validateAndUpdateCache(ozoneManager, transaction)
+          .getOMResponse().getStatus());
+      assertEquals(0, storagePolicyRecords().getRecords().size());
+      assertEquals(0, omMetrics.getDataCommittedBytes());
+      assertEquals(StorageTier.SSD,
+          
openTable.get(openKey).getLatestVersionLocations().getBlocksLatestVersionOnly().get(0).getStorageTier());
+    }
+    OMRequest close = createCommitKeyRequest(locations, false);
+    close = close.toBuilder()
+        
.setCommitKeyRequest(close.getCommitKeyRequest().toBuilder().setRecovery(recovery)).build();
+    assertEquals(OK, 
getOmKeyCommitRequest(doPreExecute(close)).validateAndUpdateCache(ozoneManager, 
103L)
+        .getOMResponse().getStatus());
+    assertEquals(1, storagePolicyRecords().getRecords().size());
+    assertPolicyMetric("HOT", "SSD", "SSD", "preferred", 200);
+    assertEquals(200, omMetrics.getDataCommittedBytes());
+  }
+
+  private MetricsCollectorImpl storagePolicyRecords() {
+    MetricsCollectorImpl collector = new MetricsCollectorImpl();
+    
DefaultMetricsSystem.instance().getSource("OMStoragePolicyMetrics").getMetrics(collector,
 true);
+    return collector;
+  }
+
+  private void assertPolicyMetric(String policy, String requestedTier, String 
actualTier, String outcome, long bytes) {
+    MetricsCollectorImpl collector = storagePolicyRecords();
+    List<MetricsRecordImpl> matching = 
collector.getRecords().stream().filter(record -> {
+      Map<String, String> tags = record.tags().stream()
+          .collect(Collectors.toMap(tag -> tag.name(), tag -> tag.value()));
+      return policy.equals(tags.get("Policy")) && 
requestedTier.equals(tags.get("RequestedTier"))
+          && actualTier.equals(tags.get("ActualTier")) && 
outcome.equals(tags.get("Outcome"));
+    }).collect(Collectors.toList());
+    assertThat(matching).hasSize(1);
+    assertThat(matching.get(0).metrics()).singleElement().satisfies(metric -> {
+      assertEquals("CommittedBytes", metric.name());
+      assertEquals(bytes, metric.value().longValue());
+    });
+  }
+
   /**
    * This method calls preExecute and verify the modified request.
    * @param originalOMRequest


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to