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

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


The following commit(s) were added to refs/heads/master by this push:
     new 8389bf3d430 HDDS-16943. Avoid the extra ListStatus RPC at the end of 
every file system listing (#11549)
8389bf3d430 is described below

commit 8389bf3d430d1f65f65c5f29606b32443be87b89
Author: Andrey Yarovoy <[email protected]>
AuthorDate: Fri Oct 16 11:01:49 2026 -0400

    HDDS-16943. Avoid the extra ListStatus RPC at the end of every file system 
listing (#11549)
---
 .../apache/hadoop/ozone/client/OzoneBucket.java    |  21 +++
 .../ozone/client/protocol/ClientProtocol.java      |  19 +++
 .../apache/hadoop/ozone/client/rpc/RpcClient.java  |  23 ++-
 .../hadoop/ozone/om/helpers/ListStatusResult.java  |  65 ++++++++
 .../ozone/om/protocol/OzoneManagerProtocol.java    |  19 +++
 ...OzoneManagerProtocolClientSideTranslatorPB.java |  21 ++-
 .../fs/ozone/AbstractOzoneFileSystemTest.java      |  11 +-
 .../fs/ozone/TestOfsListStatusRpcBenchmark.java    |  14 +-
 .../src/main/proto/OmClientProtocol.proto          |   4 +
 .../apache/hadoop/ozone/om/OmMetadataReader.java   |  25 +--
 .../protocolPB/OzoneManagerRequestHandler.java     |  18 +-
 .../protocolPB/TestOzoneManagerRequestHandler.java |  61 +++++++
 .../fs/ozone/BasicOzoneClientAdapterImpl.java      |  26 +--
 .../hadoop/fs/ozone/BasicOzoneFileSystem.java      |  56 ++++---
 .../ozone/BasicRootedOzoneClientAdapterImpl.java   |  37 ++++-
 .../fs/ozone/BasicRootedOzoneFileSystem.java       |  46 +++---
 .../apache/hadoop/fs/ozone/OzoneClientAdapter.java |  12 ++
 ...estBasicRootedOzoneClientAdapterListStatus.java |  45 ++++-
 .../ozone/TestOzoneFileSystemListStatusPages.java  | 182 +++++++++++++++++++++
 19 files changed, 604 insertions(+), 101 deletions(-)

diff --git 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneBucket.java
 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneBucket.java
index 29fa6de0ff6..6a85a402988 100644
--- 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneBucket.java
+++ 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneBucket.java
@@ -56,6 +56,7 @@
 import org.apache.hadoop.ozone.om.helpers.BasicOmKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.BucketLayout;
 import org.apache.hadoop.ozone.om.helpers.ErrorInfo;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.OmLifecycleConfiguration;
 import org.apache.hadoop.ozone.om.helpers.OmMultipartInfo;
@@ -1217,6 +1218,26 @@ public List<OzoneFileStatusLight> listStatusLight(String 
keyName, boolean recurs
     return proxy.listStatusLight(volumeName, name, keyName, recursive, 
startKey, numEntries, false);
   }
 
+  /**
+   * Like {@link #listStatus(String, boolean, String, long)}, but also returns 
whether OM reported that no
+   * entries follow this page.
+   */
+  public ListStatusResult<OzoneFileStatus> listStatusPage(String keyName, 
boolean recursive,
+      String startKey, long numEntries) throws IOException {
+    return proxy.listStatusPage(
+        ListStatusLightOptions.of(volumeName, name, keyName, recursive, 
startKey, numEntries, false));
+  }
+
+  /**
+   * Like {@link #listStatusLight(String, boolean, String, long)}, but also 
returns whether OM reported that
+   * no entries follow this page.
+   */
+  public ListStatusResult<OzoneFileStatusLight> listStatusLightPage(String 
keyName, boolean recursive,
+      String startKey, long numEntries) throws IOException {
+    return proxy.listStatusLightPage(
+        ListStatusLightOptions.of(volumeName, name, keyName, recursive, 
startKey, numEntries, false));
+  }
+
   /**
    * List the status for a file or a directory and its contents.
    *
diff --git 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/protocol/ClientProtocol.java
 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/protocol/ClientProtocol.java
index f6eee8909a8..90f999732a2 100644
--- 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/protocol/ClientProtocol.java
+++ 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/protocol/ClientProtocol.java
@@ -54,6 +54,7 @@
 import org.apache.hadoop.ozone.om.helpers.DeleteTenantState;
 import org.apache.hadoop.ozone.om.helpers.ErrorInfo;
 import org.apache.hadoop.ozone.om.helpers.LeaseKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
 import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
@@ -1274,6 +1275,24 @@ List<OzoneFileStatus> listStatus(ListStatusLightOptions 
options)
   List<OzoneFileStatusLight> listStatusLight(ListStatusLightOptions options)
       throws IOException;
 
+  /**
+   * Like {@link #listStatus(ListStatusLightOptions)}, but also returns 
whether OM reported that no entries
+   * follow this page.
+   */
+  default ListStatusResult<OzoneFileStatus> 
listStatusPage(ListStatusLightOptions options)
+      throws IOException {
+    return ListStatusResult.unknown(listStatus(options));
+  }
+
+  /**
+   * Like {@link #listStatusLight(ListStatusLightOptions)}, but also returns 
whether OM reported that no
+   * entries follow this page.
+   */
+  default ListStatusResult<OzoneFileStatusLight> 
listStatusLightPage(ListStatusLightOptions options)
+      throws IOException {
+    return ListStatusResult.unknown(listStatusLight(options));
+  }
+
   /**
    * Lightweight listStatus API (convenience overload without listPrefix).
    *
diff --git 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/rpc/RpcClient.java
 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/rpc/RpcClient.java
index 37240037f61..b2500676779 100644
--- 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/rpc/RpcClient.java
+++ 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/rpc/RpcClient.java
@@ -141,6 +141,7 @@
 import org.apache.hadoop.ozone.om.helpers.ErrorInfo;
 import org.apache.hadoop.ozone.om.helpers.KeyInfoWithVolumeContext;
 import org.apache.hadoop.ozone.om.helpers.LeaseKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OmBucketArgs;
 import org.apache.hadoop.ozone.om.helpers.OmBucketInfo;
 import org.apache.hadoop.ozone.om.helpers.OmDeleteKeys;
@@ -2587,26 +2588,36 @@ public List<OzoneFileStatus> listStatus(String 
volumeName, String bucketName,
   @Override
   public List<OzoneFileStatus> listStatus(ListStatusLightOptions options)
       throws IOException {
+    return listStatusPage(options).getStatuses();
+  }
+
+  @Override
+  public ListStatusResult<OzoneFileStatus> 
listStatusPage(ListStatusLightOptions options)
+      throws IOException {
     final OmKeyArgs keyArgs = prepareListStatusKeyArgs(options);
-    return ozoneManagerClient.listStatus(keyArgs, options.isRecursive(), 
options.getStartKey(),
+    return ozoneManagerClient.listStatusPage(keyArgs, options.isRecursive(), 
options.getStartKey(),
         options.getNumEntries(), options.isAllowPartialPrefixes());
   }
 
   @Override
   public List<OzoneFileStatusLight> listStatusLight(ListStatusLightOptions 
options)
       throws IOException {
+    return listStatusLightPage(options).getStatuses();
+  }
+
+  @Override
+  public ListStatusResult<OzoneFileStatusLight> 
listStatusLightPage(ListStatusLightOptions options)
+      throws IOException {
     final OmKeyArgs keyArgs = prepareListStatusKeyArgs(options);
     if (OzoneManagerVersion.LIGHTWEIGHT_LIST_STATUS.isSupportedBy(omVersion)) {
-      return ozoneManagerClient.listStatusLight(
+      return ozoneManagerClient.listStatusLightPage(
           keyArgs, options.isRecursive(), options.getStartKey(), 
options.getNumEntries(),
           options.isAllowPartialPrefixes());
     } else {
-      return ozoneManagerClient.listStatus(
+      return ozoneManagerClient.listStatusPage(
           keyArgs, options.isRecursive(), options.getStartKey(), 
options.getNumEntries(),
               options.isAllowPartialPrefixes())
-          .stream()
-          .map(OzoneFileStatusLight::fromOzoneFileStatus)
-          .collect(Collectors.toList());
+          .map(OzoneFileStatusLight::fromOzoneFileStatus);
     }
   }
 
diff --git 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/helpers/ListStatusResult.java
 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/helpers/ListStatusResult.java
new file mode 100644
index 00000000000..48f834688db
--- /dev/null
+++ 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/helpers/ListStatusResult.java
@@ -0,0 +1,65 @@
+/*
+ * 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.helpers;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Function;
+
+/**
+ * One page of a listStatus or listStatusLight result, with whether OM 
reported that it is the last page.
+ *
+ * @param <T> type of the listed entries
+ */
+public final class ListStatusResult<T> {
+  private final List<T> statuses;
+  private final boolean complete;
+
+  private ListStatusResult(List<T> statuses, boolean complete) {
+    this.statuses = statuses;
+    this.complete = complete;
+  }
+
+  /** A page for which OM reported whether more entries follow. */
+  public static <T> ListStatusResult<T> of(List<T> statuses, boolean 
truncated) {
+    return new ListStatusResult<>(statuses, !truncated);
+  }
+
+  /** A page for which it is unknown whether more entries follow, for example 
from an OM that does not report it. */
+  public static <T> ListStatusResult<T> unknown(List<T> statuses) {
+    return new ListStatusResult<>(statuses, false);
+  }
+
+  public List<T> getStatuses() {
+    return statuses;
+  }
+
+  /** True only if OM reported that no entries follow this page; false if more 
may follow or it is unknown. */
+  public boolean isComplete() {
+    return complete;
+  }
+
+  /** The same page with every entry converted by {@code converter}. */
+  public <R> ListStatusResult<R> map(Function<? super T, ? extends R> 
converter) {
+    List<R> converted = new ArrayList<>(statuses.size());
+    for (T status : statuses) {
+      converted.add(converter.apply(status));
+    }
+    return new ListStatusResult<>(converted, complete);
+  }
+}
diff --git 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocol/OzoneManagerProtocol.java
 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocol/OzoneManagerProtocol.java
index 627d42ee359..317391b869e 100644
--- 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocol/OzoneManagerProtocol.java
+++ 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocol/OzoneManagerProtocol.java
@@ -38,6 +38,7 @@
 import org.apache.hadoop.ozone.om.helpers.KeyInfoWithVolumeContext;
 import org.apache.hadoop.ozone.om.helpers.LeaseKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.ListOpenFilesResult;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OmBucketArgs;
 import org.apache.hadoop.ozone.om.helpers.OmBucketInfo;
 import org.apache.hadoop.ozone.om.helpers.OmDeleteKeys;
@@ -1113,6 +1114,24 @@ List<OzoneFileStatusLight> listStatusLight(OmKeyArgs 
keyArgs,
       boolean recursive, String startKey, long numEntries,
       boolean allowPartialPrefixes) throws IOException;
 
+  /**
+   * Like {@link #listStatus(OmKeyArgs, boolean, String, long, boolean)}, but 
also returns whether OM reported
+   * that no entries follow this page.
+   */
+  default ListStatusResult<OzoneFileStatus> listStatusPage(OmKeyArgs keyArgs, 
boolean recursive,
+      String startKey, long numEntries, boolean allowPartialPrefixes) throws 
IOException {
+    return ListStatusResult.unknown(listStatus(keyArgs, recursive, startKey, 
numEntries, allowPartialPrefixes));
+  }
+
+  /**
+   * Like {@link #listStatusLight(OmKeyArgs, boolean, String, long, boolean)}, 
but also returns whether OM
+   * reported that no entries follow this page.
+   */
+  default ListStatusResult<OzoneFileStatusLight> listStatusLightPage(OmKeyArgs 
keyArgs, boolean recursive,
+      String startKey, long numEntries, boolean allowPartialPrefixes) throws 
IOException {
+    return ListStatusResult.unknown(listStatusLight(keyArgs, recursive, 
startKey, numEntries, allowPartialPrefixes));
+  }
+
   /**
    * Add acl for Ozone object. Return true if acl is added successfully else
    * false.
diff --git 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerProtocolClientSideTranslatorPB.java
 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerProtocolClientSideTranslatorPB.java
index 5c46210c272..25d8a34d0ec 100644
--- 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerProtocolClientSideTranslatorPB.java
+++ 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/OzoneManagerProtocolClientSideTranslatorPB.java
@@ -72,6 +72,7 @@
 import org.apache.hadoop.ozone.om.helpers.ListKeysLightResult;
 import org.apache.hadoop.ozone.om.helpers.ListKeysResult;
 import org.apache.hadoop.ozone.om.helpers.ListOpenFilesResult;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OmBucketArgs;
 import org.apache.hadoop.ozone.om.helpers.OmBucketInfo;
 import org.apache.hadoop.ozone.om.helpers.OmDeleteKeys;
@@ -2640,6 +2641,12 @@ private OMResponse 
handleSubmitRequestAndSCMSafeModeRetry(OMRequest omRequest) t
   public List<OzoneFileStatus> listStatus(OmKeyArgs args, boolean recursive,
       String startKey, long numEntries, boolean allowPartialPrefixes)
       throws IOException {
+    return listStatusPage(args, recursive, startKey, numEntries, 
allowPartialPrefixes).getStatuses();
+  }
+
+  @Override
+  public ListStatusResult<OzoneFileStatus> listStatusPage(OmKeyArgs args, 
boolean recursive,
+      String startKey, long numEntries, boolean allowPartialPrefixes) throws 
IOException {
     KeyArgs keyArgs = KeyArgs.newBuilder()
         .setVolumeName(args.getVolumeName())
         .setBucketName(args.getBucketName())
@@ -2665,13 +2672,21 @@ public List<OzoneFileStatus> listStatus(OmKeyArgs args, 
boolean recursive,
         .getStatusesList()) {
       statusList.add(OzoneFileStatus.getFromProtobuf(fileStatus));
     }
-    return statusList;
+    return listStatusResponse.hasIsTruncated()
+        ? ListStatusResult.of(statusList, listStatusResponse.getIsTruncated())
+        : ListStatusResult.unknown(statusList);
   }
 
   @Override
   public List<OzoneFileStatusLight> listStatusLight(OmKeyArgs args,
       boolean recursive, String startKey, long numEntries,
       boolean allowPartialPrefixes) throws IOException {
+    return listStatusLightPage(args, recursive, startKey, numEntries, 
allowPartialPrefixes).getStatuses();
+  }
+
+  @Override
+  public ListStatusResult<OzoneFileStatusLight> listStatusLightPage(OmKeyArgs 
args, boolean recursive,
+      String startKey, long numEntries, boolean allowPartialPrefixes) throws 
IOException {
     KeyArgs keyArgs = KeyArgs.newBuilder()
         .setVolumeName(args.getVolumeName())
         .setBucketName(args.getBucketName())
@@ -2702,7 +2717,9 @@ public List<OzoneFileStatusLight> 
listStatusLight(OmKeyArgs args,
 
       statusList.add(OzoneFileStatusLight.getFromProtobuf(fileStatus));
     }
-    return statusList;
+    return listStatusLightResponse.hasIsTruncated()
+        ? ListStatusResult.of(statusList, 
listStatusLightResponse.getIsTruncated())
+        : ListStatusResult.unknown(statusList);
   }
 
   private ListStatusRequest.Builder createListStatusRequestBuilder(KeyArgs 
keyArgs, boolean recursive, String startKey,
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/AbstractOzoneFileSystemTest.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/AbstractOzoneFileSystemTest.java
index 9b112e9de84..998834d6222 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/AbstractOzoneFileSystemTest.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/AbstractOzoneFileSystemTest.java
@@ -1753,8 +1753,9 @@ void testListStatus2() throws IOException {
     final long initialListStatusCount = omMetrics.getNumListStatus();
     FileStatus[] statusList = fs.listStatus(createPath("/"));
     assertEquals(1, statusList.length);
-    assertChange(initialStats, statistics, Statistic.OBJECTS_LIST.getSymbol(), 
2);
-    assertEquals(initialListStatusCount + 2, omMetrics.getNumListStatus());
+    // One listing: the page is shorter than OM's limit, so OM reports it 
complete (HDDS-16943).
+    assertChange(initialStats, statistics, Statistic.OBJECTS_LIST.getSymbol(), 
1);
+    assertEquals(initialListStatusCount + 1, omMetrics.getNumListStatus());
     assertEquals(fs.getFileStatus(path), statusList[0]);
 
     dirPath = RandomStringUtils.secure().nextAlphanumeric(5);
@@ -1765,8 +1766,10 @@ void testListStatus2() throws IOException {
 
     statusList = fs.listStatus(createPath("/"));
     assertEquals(2, statusList.length);
-    assertChange(initialStats, statistics, Statistic.OBJECTS_LIST.getSymbol(), 
4);
-    assertEquals(initialListStatusCount + 4, omMetrics.getNumListStatus());
+    // Two listings: this suite caps OM listings at 2 entries 
(ozone.om.server.list.max.size), so the full
+    // 2-entry page may be followed by more and the client lists once more.
+    assertChange(initialStats, statistics, Statistic.OBJECTS_LIST.getSymbol(), 
3);
+    assertEquals(initialListStatusCount + 3, omMetrics.getNumListStatus());
     for (Path p : paths) {
       assertThat(Arrays.asList(statusList)).contains(fs.getFileStatus(p));
     }
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestOfsListStatusRpcBenchmark.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestOfsListStatusRpcBenchmark.java
index 1266766248a..b2cfb675107 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestOfsListStatusRpcBenchmark.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestOfsListStatusRpcBenchmark.java
@@ -64,8 +64,9 @@
  * {@link TestOfsGetFileChecksumRpcBenchmark}: {@link #NUM_BUCKETS} buckets 
are listed
  * {@link #ACCESSES_PER_BUCKET} times each from a shuffled access sequence, 
single-threaded and with
  * {@link #CONCURRENT_THREADS} client threads. Each listed directory holds 
{@link #FILES_PER_DIR} files, so the
- * entries fit in one page; {@code BasicRootedOzoneFileSystem} still lists 
until a page adds nothing, so each
- * listStatus makes {@link #LISTINGS_PER_CALL} adapter listings on both arms.
+ * entries fit in one page, and since HDDS-16943 OM reports that page as 
complete, so each listStatus makes
+ * {@link #LISTINGS_PER_CALL} adapter listing. Before HDDS-16943 the client 
listed until a page added nothing,
+ * which took two listings.
  */
 @Tag("benchmark")
 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
@@ -83,8 +84,8 @@ public class TestOfsListStatusRpcBenchmark {
   private static final int CONCURRENT_THREADS = 10;
   /** Entries in each listed directory. */
   private static final int FILES_PER_DIR = 10;
-  /** Adapter listings per listStatus: the page with the entries, then one 
that adds nothing. */
-  private static final int LISTINGS_PER_CALL = 2;
+  /** Adapter listings per listStatus: one page, which OM reports as complete 
(HDDS-16943). */
+  private static final int LISTINGS_PER_CALL = 1;
 
   private MiniOzoneCluster cluster;
   private OzoneClient client;
@@ -150,9 +151,8 @@ void benchmarkListStatus() throws Exception {
   }
 
   /**
-   * Invariants that hold on both the baseline and the fixed code, so the 
identical benchmark passes in either
-   * worktree: every listStatus issues {@link #LISTINGS_PER_CALL} listing 
RPCs, and the bucket and volume RPCs stay
-   * within one per listing.
+   * Invariants of the workload: every listStatus issues {@link 
#LISTINGS_PER_CALL} listing RPCs, and the bucket and
+   * volume RPCs stay within one per listing.
    */
   private void assertWorkloadInvariants(Result r) {
     long listings = (long) TOTAL_CALLS * LISTINGS_PER_CALL;
diff --git 
a/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto 
b/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
index 529ef0ffd85..c64c7510db0 100644
--- a/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
+++ b/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
@@ -1386,10 +1386,14 @@ message ListStatusRequest {
 
 message ListStatusResponse {
     repeated OzoneFileStatusProto statuses = 1;
+    // Set by OM: false means no entries follow this page. Absent from older 
OMs.
+    optional bool isTruncated = 2;
 }
 
 message ListStatusLightResponse {
     repeated OzoneFileStatusProtoLight statuses = 1;
+    // Set by OM: false means no entries follow this page. Absent from older 
OMs.
+    optional bool isTruncated = 2;
 }
 
 message CreateKeyRequest {
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmMetadataReader.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmMetadataReader.java
index dfefbef845f..240591cd3b1 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmMetadataReader.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmMetadataReader.java
@@ -36,6 +36,7 @@
 import java.util.stream.Collectors;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.tuple.Pair;
+import org.apache.hadoop.hdds.conf.ConfigurationSource;
 import org.apache.hadoop.ipc_.ProtobufRpcEngine;
 import org.apache.hadoop.ipc_.Server;
 import org.apache.hadoop.ozone.OzoneAcl;
@@ -232,17 +233,22 @@ public KeyInfoWithVolumeContext getKeyInfo(final 
OmKeyArgs args,
     }
   }
 
+  /**
+   * The number of entries listStatus and listStatusLight return at most for a 
request of {@code numEntries}:
+   * capped by {@code ozone.fs.listing.page.size.max} and at least 2.
+   */
+  public static long listStatusPageSize(ConfigurationSource conf, long 
numEntries) {
+    long maxListingPageSize = conf.getInt(OZONE_FS_LISTING_PAGE_SIZE_MAX, 
OZONE_FS_LISTING_PAGE_SIZE_DEFAULT);
+    return OzoneConfigUtil.limitValue(numEntries, OZONE_FS_LISTING_PAGE_SIZE, 
OZONE_FS_LISTING_PAGE_SIZE_MAX,
+        maxListingPageSize);
+  }
+
   @Override
   public List<OzoneFileStatus> listStatus(OmKeyArgs args, boolean recursive,
       String startKey, long numEntries, boolean allowPartialPrefixes)
       throws IOException {
 
-    long maxListingPageSize = ozoneManager.getConfiguration().getInt(
-        OZONE_FS_LISTING_PAGE_SIZE_MAX,
-        OZONE_FS_LISTING_PAGE_SIZE_DEFAULT);
-    maxListingPageSize = OzoneConfigUtil.limitValue(numEntries,
-        OZONE_FS_LISTING_PAGE_SIZE, OZONE_FS_LISTING_PAGE_SIZE_MAX,
-        maxListingPageSize);
+    long maxListingPageSize = 
listStatusPageSize(ozoneManager.getConfiguration(), numEntries);
 
     ResolvedBucket bucket = ozoneManager.resolveBucketLink(args);
 
@@ -279,12 +285,7 @@ public List<OzoneFileStatus> listStatus(OmKeyArgs args, 
boolean recursive,
   public List<OzoneFileStatusLight> listStatusLight(OmKeyArgs args,
       boolean recursive, String startKey, long numEntries,
       boolean allowPartialPrefixes) throws IOException {
-    long maxListingPageSize = ozoneManager.getConfiguration().getInt(
-        OZONE_FS_LISTING_PAGE_SIZE_MAX,
-        OZONE_FS_LISTING_PAGE_SIZE_DEFAULT);
-    maxListingPageSize = OzoneConfigUtil.limitValue(numEntries,
-        OZONE_FS_LISTING_PAGE_SIZE, OZONE_FS_LISTING_PAGE_SIZE_MAX,
-        maxListingPageSize);
+    long maxListingPageSize = 
listStatusPageSize(ozoneManager.getConfiguration(), numEntries);
 
     ResolvedBucket bucket = ozoneManager.resolveBucketLink(args);
     Map<String, String> auditMap = bucket.audit(args.toAuditMap());
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/protocolPB/OzoneManagerRequestHandler.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/protocolPB/OzoneManagerRequestHandler.java
index a0a4d400dfb..495e5dd9aed 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/protocolPB/OzoneManagerRequestHandler.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/protocolPB/OzoneManagerRequestHandler.java
@@ -64,6 +64,7 @@
 import org.apache.hadoop.ipc_.ProtobufRpcEngine;
 import org.apache.hadoop.ozone.ClientVersion;
 import org.apache.hadoop.ozone.OzoneAcl;
+import org.apache.hadoop.ozone.om.OmMetadataReader;
 import org.apache.hadoop.ozone.om.OzoneAclUtils;
 import org.apache.hadoop.ozone.om.OzoneManager;
 import org.apache.hadoop.ozone.om.exceptions.OMException;
@@ -1336,9 +1337,10 @@ private ListStatusResponse listStatus(
         .build();
     boolean allowPartialPrefixes =
         request.hasAllowPartialPrefix() && request.getAllowPartialPrefix();
+    final long numEntries = limitListSize(request.getNumEntries());
     List<OzoneFileStatus> statuses =
         impl.listStatus(omKeyArgs, request.getRecursive(),
-            request.getStartKey(), limitListSize(request.getNumEntries()),
+            request.getStartKey(), numEntries,
             allowPartialPrefixes);
     ListStatusResponse.Builder
         listStatusResponseBuilder =
@@ -1346,6 +1348,7 @@ private ListStatusResponse listStatus(
     for (OzoneFileStatus status : statuses) {
       listStatusResponseBuilder.addStatuses(status.getProtobuf(clientVersion));
     }
+    
listStatusResponseBuilder.setIsTruncated(isListStatusTruncated(statuses.size(), 
numEntries));
     return listStatusResponseBuilder.build();
   }
 
@@ -1365,9 +1368,10 @@ private ListStatusLightResponse 
listStatusLight(ListStatusRequest request) throw
     OmKeyArgs omKeyArgs = omKeyArgsBuilder.build();
     boolean allowPartialPrefixes =
         request.hasAllowPartialPrefix() && request.getAllowPartialPrefix();
+    final long numEntries = limitListSize(request.getNumEntries());
     List<OzoneFileStatusLight> statuses =
         impl.listStatusLight(omKeyArgs, request.getRecursive(),
-            request.getStartKey(), limitListSize(request.getNumEntries()),
+            request.getStartKey(), numEntries,
             allowPartialPrefixes);
     ListStatusLightResponse.Builder
         listStatusLightResponseBuilder =
@@ -1375,9 +1379,19 @@ private ListStatusLightResponse 
listStatusLight(ListStatusRequest request) throw
     for (OzoneFileStatusLight status : statuses) {
       listStatusLightResponseBuilder.addStatuses(status.getProtobuf());
     }
+    
listStatusLightResponseBuilder.setIsTruncated(isListStatusTruncated(statuses.size(),
 numEntries));
     return listStatusLightResponseBuilder.build();
   }
 
+  /**
+   * More entries may follow a listing page only if it is full. listStatus 
returns
+   * {@code min(page size, remaining entries)}, where the page size is the 
request
+   * capped by both server limits, so a shorter page is the last one.
+   */
+  private boolean isListStatusTruncated(int returned, long numEntries) {
+    return returned >= 
OmMetadataReader.listStatusPageSize(impl.getConfiguration(), numEntries);
+  }
+
   @RequestFeatureValidator(
       conditions = ValidationCondition.OLDER_CLIENT_REQUESTS,
       processingPhase = RequestProcessingPhase.POST_PROCESS,
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/protocolPB/TestOzoneManagerRequestHandler.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/protocolPB/TestOzoneManagerRequestHandler.java
index e50547f93b3..db49e81906c 100644
--- 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/protocolPB/TestOzoneManagerRequestHandler.java
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/protocolPB/TestOzoneManagerRequestHandler.java
@@ -33,6 +33,7 @@
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
 import org.apache.hadoop.ozone.ClientVersion;
+import org.apache.hadoop.ozone.OzoneConfigKeys;
 import org.apache.hadoop.ozone.audit.AuditLogger;
 import org.apache.hadoop.ozone.audit.AuditMessage;
 import org.apache.hadoop.ozone.om.OMPerformanceMetrics;
@@ -47,6 +48,7 @@
 import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
 import org.apache.hadoop.ozone.om.helpers.OzoneFileStatus;
+import org.apache.hadoop.ozone.om.helpers.OzoneFileStatusLight;
 import org.apache.hadoop.ozone.om.upgrade.OMVersionManager;
 import org.apache.hadoop.ozone.om.upgrade.OMVersionManagerTestUtils;
 import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
@@ -67,10 +69,15 @@
 public class TestOzoneManagerRequestHandler {
 
   private OzoneManagerRequestHandler getRequestHandler(int limitListKeySize) {
+    return getRequestHandler(limitListKeySize, new OzoneConfiguration());
+  }
+
+  private OzoneManagerRequestHandler getRequestHandler(int limitListKeySize, 
OzoneConfiguration conf) {
     OmConfig config = OzoneConfiguration.newInstanceOf(OmConfig.class);
     config.setMaxListSize(limitListKeySize);
     OzoneManager ozoneManager = Mockito.mock(OzoneManager.class);
     Mockito.when(ozoneManager.getConfig()).thenReturn(config);
+    Mockito.when(ozoneManager.getConfiguration()).thenReturn(conf);
     return new OzoneManagerRequestHandler(ozoneManager);
   }
 
@@ -307,6 +314,60 @@ public void testListStatusResponseSize(int resultSize) 
throws IOException {
     }
   }
 
+  /**
+   * isTruncated is set when a ListStatus / ListStatusLight page is full: OM 
returned as many entries as the
+   * request allows after ozone.om.server.list.max.size, 
ozone.fs.listing.page.size.max and the minimum page
+   * size of 2. A shorter page is the last one.
+   */
+  @ParameterizedTest
+  @ValueSource(strings = {"ListStatus", "ListStatusLight"})
+  public void testListStatusIsTruncated(String typeName) throws IOException {
+    OzoneManagerProtocolProtos.Type type = 
OzoneManagerProtocolProtos.Type.valueOf(typeName);
+    // {server list max size, listing page size max, requested entries, 
effective page size}
+    long[][] cases = {
+        {1000, 1024, 1024, 1000},  // ozone.om.server.list.max.size is the 
limit
+        {1000, 5, 1024, 5},        // ozone.fs.listing.page.size.max is the 
limit
+        {1000, 1024, 7, 7},        // the request is the limit
+        {1000, 1024, 1, 2},        // OM raises a page size of 1 to 2
+    };
+    for (long[] c : cases) {
+      OzoneConfiguration conf = new OzoneConfiguration();
+      conf.setInt(OzoneConfigKeys.OZONE_FS_LISTING_PAGE_SIZE_MAX, (int) c[1]);
+      OzoneManagerRequestHandler requestHandler = getRequestHandler((int) 
c[0], conf);
+      long effective = c[3];
+      for (long returned : new long[] {0, effective - 1, effective}) {
+        mockListStatusResult(requestHandler.getOzoneManager(), (int) returned);
+        OzoneManagerProtocolProtos.OMRequest request = 
Mockito.mock(OzoneManagerProtocolProtos.OMRequest.class);
+        Mockito.when(request.getTraceID()).thenReturn("traceId");
+        Mockito.when(request.getCmdType()).thenReturn(type);
+        Mockito.when(request.getListStatusRequest()).thenReturn(
+            OzoneManagerProtocolProtos.ListStatusRequest.newBuilder()
+                .setKeyArgs(OzoneManagerProtocolProtos.KeyArgs.newBuilder()
+                    
.setVolumeName("volume").setBucketName("bucket").setKeyName("dir"))
+                .setRecursive(false).setStartKey("").setNumEntries(c[2])
+                .build());
+        OzoneManagerProtocolProtos.OMResponse response = 
requestHandler.handleReadRequest(request);
+        boolean truncated = type == OzoneManagerProtocolProtos.Type.ListStatus
+            ? response.getListStatusResponse().getIsTruncated()
+            : response.getListStatusLightResponse().getIsTruncated();
+        Assertions.assertEquals(returned >= effective, truncated,
+            "case " + Arrays.toString(c) + ", returned " + returned);
+      }
+    }
+  }
+
+  private void mockListStatusResult(OzoneManager ozoneManager, int count) 
throws IOException {
+    List<OzoneFileStatus> statuses = IntStream.range(0, count)
+        .mapToObj(i -> 
getMockedOzoneFileStatus()).collect(Collectors.toList());
+    List<OzoneFileStatusLight> lightStatuses = IntStream.range(0, count)
+        .mapToObj(i -> new OzoneFileStatusLight())
+        .collect(Collectors.toList());
+    Mockito.when(ozoneManager.listStatus(any(OmKeyArgs.class), 
Mockito.anyBoolean(), Mockito.anyString(),
+        Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(statuses);
+    Mockito.when(ozoneManager.listStatusLight(any(OmKeyArgs.class), 
Mockito.anyBoolean(), Mockito.anyString(),
+        Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(lightStatuses);
+  }
+
   /**
    * ListStatus and ListStatusLight must forward requireFileSystemLayout from
    * the request into the OmKeyArgs handed to the OM.
diff --git 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicOzoneClientAdapterImpl.java
 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicOzoneClientAdapterImpl.java
index 513156e50ff..a06c2f8b258 100644
--- 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicOzoneClientAdapterImpl.java
+++ 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicOzoneClientAdapterImpl.java
@@ -79,6 +79,7 @@
 import org.apache.hadoop.ozone.om.helpers.BasicOmKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.BucketLayout;
 import org.apache.hadoop.ozone.om.helpers.LeaseKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
 import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
@@ -445,23 +446,22 @@ public Iterator<BasicKeyInfo> listKeys(String pathKey) 
throws IOException {
   public List<FileStatusAdapter> listStatus(String keyName, boolean recursive,
       String startKey, long numEntries, URI uri,
       Path workingDir, String username, boolean lite) throws IOException {
+    return listStatusPage(keyName, recursive, startKey, numEntries, uri, 
workingDir, username, lite)
+        .getStatuses();
+  }
+
+  @Override
+  public ListStatusResult<FileStatusAdapter> listStatusPage(String keyName, 
boolean recursive,
+      String startKey, long numEntries, URI uri,
+      Path workingDir, String username, boolean lite) throws IOException {
     try {
       incrementCounter(Statistic.OBJECTS_LIST, 1);
-      List<FileStatusAdapter> result = new ArrayList<>();
       if (lite) {
-        List<OzoneFileStatusLight> statuses = bucket
-            .listStatusLight(keyName, recursive, startKey, numEntries);
-        for (OzoneFileStatusLight status : statuses) {
-          result.add(toFileStatusAdapter(status, username, uri, workingDir));
-        }
-      } else {
-        List<OzoneFileStatus> statuses = bucket
-            .listStatus(keyName, recursive, startKey, numEntries);
-        for (OzoneFileStatus status : statuses) {
-          result.add(toFileStatusAdapter(status, username, uri, workingDir));
-        }
+        return bucket.listStatusLightPage(keyName, recursive, startKey, 
numEntries)
+            .map(status -> toFileStatusAdapter(status, username, uri, 
workingDir));
       }
-      return result;
+      return bucket.listStatusPage(keyName, recursive, startKey, numEntries)
+          .map(status -> toFileStatusAdapter(status, username, uri, 
workingDir));
     } catch (OMException e) {
       if (e.getResult() == OMException.ResultCodes.FILE_NOT_FOUND) {
         throw new FileNotFoundException(e.getMessage());
diff --git 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicOzoneFileSystem.java
 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicOzoneFileSystem.java
index 2d569f7a68c..8c6a38afb96 100644
--- 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicOzoneFileSystem.java
+++ 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicOzoneFileSystem.java
@@ -49,7 +49,6 @@
 import java.util.Objects;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-import java.util.stream.Collectors;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.BlockLocation;
 import org.apache.hadoop.fs.ContentSummary;
@@ -79,6 +78,7 @@
 import org.apache.hadoop.ozone.client.OzoneClientUtils;
 import org.apache.hadoop.ozone.client.io.SelectorOutputStream;
 import org.apache.hadoop.ozone.om.exceptions.OMException;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OzoneFSUtils;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.Token;
@@ -694,16 +694,15 @@ public FileStatus[] listStatus(Path f) throws IOException 
{
     LOG.trace("listStatus() path:{}", f);
     int numEntries = listingPageSize;
     LinkedList<FileStatus> statuses = new LinkedList<>();
+    ListStatusResult<FileStatus> page;
     List<FileStatus> tmpStatusList;
     String startKey = "";
     int entriesAdded;
     do {
-      tmpStatusList =
-          adapter.listStatus(pathToKey(f), false, startKey, numEntries, uri,
-                  workingDir, getUsername(), true)
-              .stream()
-              .map(this::convertFileStatus)
-              .collect(Collectors.toList());
+      page = adapter.listStatusPage(pathToKey(f), false, startKey, numEntries, 
uri,
+              workingDir, getUsername(), true)
+          .map(this::convertFileStatus);
+      tmpStatusList = page.getStatuses();
       entriesAdded = 0;
       if (!tmpStatusList.isEmpty()) {
         if (startKey.isEmpty() || !statuses.getLast().getPath().toString()
@@ -716,10 +715,9 @@ workingDir, getUsername(), true)
         }
         startKey = pathToKey(statuses.getLast().getPath());
       }
-      // listStatus returns entries numEntries in size if available.
-      // Any lesser number of entries indicate that the required entries have
-      // exhausted.
-    } while (entriesAdded > 0);
+      // OM may return fewer than numEntries even when more entries follow, as 
it caps the page size, so
+      // stop only when OM reports the listing complete or a page adds nothing.
+    } while (entriesAdded > 0 && !page.isComplete());
 
 
     return statuses.toArray(new FileStatus[0]);
@@ -958,12 +956,14 @@ protected void applyEcPolicy(ContentSummary.Builder 
builder, String ecPolicy) {
   private List<FileStatusAdapter> listStatusAdapter(Path f) throws IOException 
{
     int numEntries = listingPageSize;
     LinkedList<FileStatusAdapter> statuses = new LinkedList<>();
+    ListStatusResult<FileStatusAdapter> page;
     List<FileStatusAdapter> tmpStatusList;
     String startKey = "";
     int entriesAdded;
     do {
-      tmpStatusList = adapter.listStatus(pathToKey(f), false, startKey,
+      page = adapter.listStatusPage(pathToKey(f), false, startKey,
           numEntries, uri, workingDir, getUsername(), true);
+      tmpStatusList = page.getStatuses();
       entriesAdded = 0;
       if (!tmpStatusList.isEmpty()) {
         if (startKey.isEmpty() || !statuses.getLast().getPath().toString()
@@ -976,7 +976,7 @@ private List<FileStatusAdapter> listStatusAdapter(Path f) 
throws IOException {
         }
         startKey = pathToKey(statuses.getLast().getPath());
       }
-    } while (entriesAdded > 0);
+    } while (entriesAdded > 0 && !page.isComplete());
 
     return statuses;
   }
@@ -1132,6 +1132,8 @@ private final class OzoneFileStatusIterator<T extends 
FileStatus>
     private T curStat = null;
     private String startPath = "";
     private boolean lite;
+    /** True once OM reported that no entries follow the current listing. */
+    private boolean listingComplete;
     private Function<FileStatus, T> transformFunc;
 
     /**
@@ -1148,7 +1150,7 @@ private OzoneFileStatusIterator(Path p, 
Function<FileStatus, T> transformFunc, b
       this.lite = lite;
       this.transformFunc = transformFunc;
       // fetch the first batch of entries in the directory
-      thisListing = listFileStatus(p, startPath, lite);
+      thisListing = nextListing();
       if (thisListing != null && !thisListing.isEmpty()) {
         startPath = pathToKey(
             thisListing.get(thisListing.size() - 1).getPath());
@@ -1185,9 +1187,9 @@ private boolean hasNextNoFilter() throws IOException {
         return false;
       }
       if (i >= thisListing.size()) {
-        if (startPath != null && (!thisListing.isEmpty())) {
+        if (startPath != null && !thisListing.isEmpty() && !listingComplete) {
           // current listing is exhausted & fetch a new listing
-          thisListing = listFileStatus(p, startPath, lite);
+          thisListing = nextListing();
           if (thisListing != null && !thisListing.isEmpty()) {
             startPath = pathToKey(
                 thisListing.get(thisListing.size() - 1).getPath());
@@ -1202,6 +1204,12 @@ private boolean hasNextNoFilter() throws IOException {
       return (i < thisListing.size());
     }
 
+    private List<FileStatus> nextListing() throws IOException {
+      ListStatusResult<FileStatus> page = listFileStatus(p, startPath, lite);
+      listingComplete = page.isComplete();
+      return page.getStatuses();
+    }
+
     /**
      * @return next entry.
      * @throws IOException
@@ -1223,27 +1231,25 @@ public T next() throws IOException {
    * @param f
    * @param startPath
    * @param lite if true return lightweight keys
-   * @return list of file status.
+   * @return list of file status, and whether OM reported that no entries 
follow.
    * @throws IOException
    */
-  private List<FileStatus> listFileStatus(Path f, String startPath, boolean 
lite)
+  private ListStatusResult<FileStatus> listFileStatus(Path f, String 
startPath, boolean lite)
       throws IOException {
     incrementCounter(Statistic.INVOCATION_LIST_STATUS, 1);
     statistics.incrementReadOps(1);
     LOG.trace("listFileStatus() path:{}", f);
-    List<FileStatus> statusList;
-    statusList =
-        adapter.listStatus(pathToKey(f), false, startPath,
+    ListStatusResult<FileStatus> page =
+        adapter.listStatusPage(pathToKey(f), false, startPath,
                 listingPageSize, uri, workingDir, getUsername(), lite)
-            .stream()
-            .map(this::convertFileStatus)
-            .collect(Collectors.toList());
+            .map(this::convertFileStatus);
+    List<FileStatus> statusList = page.getStatuses();
 
     if (!statusList.isEmpty() && !startPath.isEmpty()) {
       // Excluding the 1st file status element from list.
       statusList.remove(0);
     }
-    return statusList;
+    return page;
   }
 
   /**
diff --git 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicRootedOzoneClientAdapterImpl.java
 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicRootedOzoneClientAdapterImpl.java
index 311c7bfc3a3..cb867af7299 100644
--- 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicRootedOzoneClientAdapterImpl.java
+++ 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicRootedOzoneClientAdapterImpl.java
@@ -96,6 +96,7 @@
 import org.apache.hadoop.ozone.om.helpers.BasicOmKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.BucketLayout;
 import org.apache.hadoop.ozone.om.helpers.LeaseKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
 import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
 import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
@@ -941,6 +942,19 @@ private List<FileStatusAdapter> listStatusBucketSnapshot(
   public List<FileStatusAdapter> listStatus(String pathStr, boolean recursive,
       String startPath, long numEntries, URI uri,
       Path workingDir, String username, boolean lite) throws IOException {
+    return listStatusPage(pathStr, recursive, startPath, numEntries, uri, 
workingDir, username, lite)
+        .getStatuses();
+  }
+
+  /**
+   * {@link #listStatus} that also returns whether OM reported that no entries 
follow. Only listings inside a
+   * bucket can report it; root, volume and snapshot listings do not.
+   */
+  @SuppressWarnings("checkstyle:ParameterNumber")
+  @Override
+  public ListStatusResult<FileStatusAdapter> listStatusPage(String pathStr, 
boolean recursive,
+      String startPath, long numEntries, URI uri,
+      Path workingDir, String username, boolean lite) throws IOException {
 
     incrementCounter(Statistic.OBJECTS_LIST, 1);
     // Remove authority from startPath if it exists
@@ -958,19 +972,19 @@ public List<FileStatusAdapter> listStatus(String pathStr, 
boolean recursive,
 
     OFSPath ofsPath = new OFSPath(pathStr, config);
     if (ofsPath.isRoot()) {
-      return listStatusRoot(
-          recursive, startPath, numEntries, uri, workingDir, username, lite);
+      return ListStatusResult.unknown(listStatusRoot(
+          recursive, startPath, numEntries, uri, workingDir, username, lite));
     }
     OFSPath ofsStartPath = new OFSPath(startPath, config);
     if (ofsPath.isVolume()) {
       String startBucketPath = ofsStartPath.getNonKeyPath();
-      return listStatusVolume(ofsPath.getVolumeName(),
-          recursive, startBucketPath, numEntries, uri, workingDir, username, 
lite);
+      return ListStatusResult.unknown(listStatusVolume(ofsPath.getVolumeName(),
+          recursive, startBucketPath, numEntries, uri, workingDir, username, 
lite));
     }
 
     if (ofsPath.isSnapshotPath()) {
-      return listStatusBucketSnapshot(ofsPath.getVolumeName(),
-          ofsPath.getBucketName(), uri, ofsStartPath.getSnapshotName(), 
numEntries);
+      return 
ListStatusResult.unknown(listStatusBucketSnapshot(ofsPath.getVolumeName(),
+          ofsPath.getBucketName(), uri, ofsStartPath.getSnapshotName(), 
numEntries));
     }
     List<FileStatusAdapter> result = new ArrayList<>();
     String keyName = ofsPath.getKeyName();
@@ -979,6 +993,7 @@ public List<FileStatusAdapter> listStatus(String pathStr, 
boolean recursive,
     try {
       List<OzoneFileStatus> statuses = Collections.emptyList();
       List<OzoneFileStatusLight> lightStatuses = Collections.emptyList();
+      boolean complete = false;
       if 
(proxy.getOmVersion().compareTo(OzoneManagerVersion.LIST_STATUS_REJECTS_OBS) >= 
0) {
         // Ask OM to reject an OBJECT_STORE bucket (HDDS-16760), so list 
without
         // fetching the bucket first. The bucket is fetched only when the 
listing
@@ -995,9 +1010,13 @@ public List<FileStatusAdapter> listStatus(String pathStr, 
boolean recursive,
             .build();
         try {
           if (lite) {
-            lightStatuses = proxy.listStatusLight(options);
+            ListStatusResult<OzoneFileStatusLight> page = 
proxy.listStatusLightPage(options);
+            lightStatuses = page.getStatuses();
+            complete = page.isComplete();
           } else {
-            statuses = proxy.listStatus(options);
+            ListStatusResult<OzoneFileStatus> page = 
proxy.listStatusPage(options);
+            statuses = page.getStatuses();
+            complete = page.isComplete();
           }
         } catch (OMException e) {
           if (e.getResult() == 
OMException.ResultCodes.NOT_SUPPORTED_OPERATION) {
@@ -1045,7 +1064,7 @@ public List<FileStatusAdapter> listStatus(String pathStr, 
boolean recursive,
         }
       }
 
-      return result;
+      return complete ? ListStatusResult.of(result, false) : 
ListStatusResult.unknown(result);
     } catch (OMException e) {
       if (e.getResult() == OMException.ResultCodes.FILE_NOT_FOUND) {
         throw new FileNotFoundException(e.getMessage());
diff --git 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicRootedOzoneFileSystem.java
 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicRootedOzoneFileSystem.java
index 30ed630b4a7..bb5a0826d3e 100644
--- 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicRootedOzoneFileSystem.java
+++ 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/BasicRootedOzoneFileSystem.java
@@ -53,7 +53,6 @@
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Objects;
-import java.util.stream.Collectors;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.BlockLocation;
 import org.apache.hadoop.fs.ContentSummary;
@@ -88,6 +87,7 @@
 import org.apache.hadoop.ozone.client.OzoneVolume;
 import org.apache.hadoop.ozone.client.io.SelectorOutputStream;
 import org.apache.hadoop.ozone.om.exceptions.OMException;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OzoneFSUtils;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.Token;
@@ -951,13 +951,14 @@ private List<FileStatusAdapter> listStatusAdapter(Path f, 
boolean lite) throws I
     LOG.trace("listStatus() path:{}", f);
     int numEntries = listingPageSize;
     LinkedList<FileStatusAdapter> statuses = new LinkedList<>();
+    ListStatusResult<FileStatusAdapter> page;
     List<FileStatusAdapter> tmpStatusList;
     String startPath = "";
     int entriesAdded;
     do {
-      tmpStatusList =
-          adapter.listStatus(pathToKey(f), false, startPath,
-              numEntries, uri, workingDir, getUsername(), lite);
+      page = adapter.listStatusPage(pathToKey(f), false, startPath,
+          numEntries, uri, workingDir, getUsername(), lite);
+      tmpStatusList = page.getStatuses();
       entriesAdded = 0;
       if (!tmpStatusList.isEmpty()) {
         if (startPath.isEmpty() || !statuses.getLast().getPath().toString()
@@ -970,10 +971,9 @@ private List<FileStatusAdapter> listStatusAdapter(Path f, 
boolean lite) throws I
         }
         startPath = pathToKey(statuses.getLast().getPath());
       }
-      // listStatus returns entries numEntries in size if available.
-      // Any lesser number of entries indicate that the required entries have
-      // exhausted.
-    } while (entriesAdded > 0);
+      // OM may return fewer than numEntries even when more entries follow, as 
it caps the page size, so
+      // stop only when OM reports the listing complete or a page adds nothing.
+    } while (entriesAdded > 0 && !page.isComplete());
 
     return statuses;
   }
@@ -1261,6 +1261,8 @@ private final class OzoneFileStatusIterator<T extends 
FileStatus>
     private T curStat = null;
     private String startPath = "";
     private boolean lite;
+    /** True once OM reported that no entries follow the current listing. */
+    private boolean listingComplete;
 
     /**
      * Constructor to initialize OzoneFileStatusIterator.
@@ -1276,7 +1278,7 @@ private OzoneFileStatusIterator(Path p, 
Function<FileStatus, T> transformFunc, b
       this.lite = lite;
       this.transformFunc = transformFunc;
       // fetch the first batch of entries in the directory
-      thisListing = listFileStatus(p, startPath, lite);
+      thisListing = nextListing();
       if (thisListing != null && !thisListing.isEmpty()) {
         startPath = pathToKey(
             thisListing.get(thisListing.size() - 1).getPath());
@@ -1313,9 +1315,9 @@ private boolean hasNextNoFilter() throws IOException {
         return false;
       }
       if (i >= thisListing.size()) {
-        if (startPath != null && (!thisListing.isEmpty())) {
+        if (startPath != null && !thisListing.isEmpty() && !listingComplete) {
           // current listing is exhausted & fetch a new listing
-          thisListing = listFileStatus(p, startPath, lite);
+          thisListing = nextListing();
           if (thisListing != null && !thisListing.isEmpty()) {
             startPath = pathToKey(
                 thisListing.get(thisListing.size() - 1).getPath());
@@ -1330,6 +1332,12 @@ private boolean hasNextNoFilter() throws IOException {
       return (i < thisListing.size());
     }
 
+    private List<FileStatus> nextListing() throws IOException {
+      ListStatusResult<FileStatus> page = listFileStatus(p, startPath, lite);
+      listingComplete = page.isComplete();
+      return page.getStatuses();
+    }
+
     /**
      * @return next entry.
      * @throws IOException
@@ -1351,27 +1359,25 @@ public T next() throws IOException {
    * @param f
    * @param startPath
    * @param lite if true return lightweight keys
-   * @return list of file status.
+   * @return list of file status, and whether OM reported that no entries 
follow.
    * @throws IOException
    */
-  private List<FileStatus> listFileStatus(Path f, String startPath, boolean 
lite)
+  private ListStatusResult<FileStatus> listFileStatus(Path f, String 
startPath, boolean lite)
       throws IOException {
     incrementCounter(Statistic.INVOCATION_LIST_STATUS, 1);
     statistics.incrementReadOps(1);
     LOG.trace("listFileStatus() path:{}", f);
-    List<FileStatus> statusList;
-    statusList =
-        adapter.listStatus(pathToKey(f), false, startPath,
+    ListStatusResult<FileStatus> page =
+        adapter.listStatusPage(pathToKey(f), false, startPath,
                 listingPageSize, uri, workingDir, getUsername(), lite)
-            .stream()
-            .map(this::convertFileStatus)
-            .collect(Collectors.toList());
+            .map(this::convertFileStatus);
+    List<FileStatus> statusList = page.getStatuses();
 
     if (!statusList.isEmpty() && !startPath.isEmpty()) {
       // Excluding the 1st file status element from list.
       statusList.remove(0);
     }
-    return statusList;
+    return page;
   }
 
   /**
diff --git 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/OzoneClientAdapter.java
 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/OzoneClientAdapter.java
index e398b4374d6..b07c6fe26fc 100644
--- 
a/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/OzoneClientAdapter.java
+++ 
b/hadoop-ozone/ozonefs-common/src/main/java/org/apache/hadoop/fs/ozone/OzoneClientAdapter.java
@@ -29,6 +29,7 @@
 import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
 import org.apache.hadoop.ozone.OzoneFsServerDefaults;
 import org.apache.hadoop.ozone.om.helpers.LeaseKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
 import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
 import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
 import org.apache.hadoop.ozone.security.OzoneTokenIdentifier;
@@ -73,6 +74,17 @@ List<FileStatusAdapter> listStatus(String keyName, boolean 
recursive,
       String startKey, long numEntries, URI uri,
       Path workingDir, String username, boolean lite) throws IOException;
 
+  /**
+   * Like {@link #listStatus}, but also returns whether OM reported that no 
entries follow this page.
+   */
+  @SuppressWarnings("checkstyle:ParameterNumber")
+  default ListStatusResult<FileStatusAdapter> listStatusPage(String keyName, 
boolean recursive,
+      String startKey, long numEntries, URI uri,
+      Path workingDir, String username, boolean lite) throws IOException {
+    return ListStatusResult.unknown(listStatus(keyName, recursive, startKey, 
numEntries, uri, workingDir,
+        username, lite));
+  }
+
   Token<OzoneTokenIdentifier> getDelegationToken(String renewer)
       throws IOException;
   
diff --git 
a/hadoop-ozone/ozonefs-common/src/test/java/org/apache/hadoop/fs/ozone/TestBasicRootedOzoneClientAdapterListStatus.java
 
b/hadoop-ozone/ozonefs-common/src/test/java/org/apache/hadoop/fs/ozone/TestBasicRootedOzoneClientAdapterListStatus.java
index 541a42ba9a9..9fc94e5ed84 100644
--- 
a/hadoop-ozone/ozonefs-common/src/test/java/org/apache/hadoop/fs/ozone/TestBasicRootedOzoneClientAdapterListStatus.java
+++ 
b/hadoop-ozone/ozonefs-common/src/test/java/org/apache/hadoop/fs/ozone/TestBasicRootedOzoneClientAdapterListStatus.java
@@ -19,6 +19,7 @@
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.mockito.ArgumentMatchers.any;
@@ -38,6 +39,7 @@
 import java.io.IOException;
 import java.lang.reflect.Field;
 import java.net.URI;
+import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicBoolean;
 import org.apache.hadoop.fs.Path;
@@ -45,11 +47,15 @@
 import org.apache.hadoop.ozone.OzoneManagerVersion;
 import org.apache.hadoop.ozone.client.ObjectStore;
 import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneVolume;
 import org.apache.hadoop.ozone.client.protocol.ClientProtocol;
 import org.apache.hadoop.ozone.client.protocol.ListStatusLightOptions;
 import org.apache.hadoop.ozone.om.exceptions.OMException;
 import org.apache.hadoop.ozone.om.exceptions.OMException.ResultCodes;
 import org.apache.hadoop.ozone.om.helpers.BucketLayout;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
+import org.apache.hadoop.ozone.om.helpers.OzoneFileStatus;
+import org.apache.hadoop.ozone.om.helpers.OzoneFileStatusLight;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
@@ -77,7 +83,8 @@ public class TestBasicRootedOzoneClientAdapterListStatus {
   @BeforeEach
   public void setUp() throws Exception {
     adapter = mock(BasicRootedOzoneClientAdapterImpl.class, 
CALLS_REAL_METHODS);
-    proxy = mock(ClientProtocol.class);
+    // Real default methods, so the page methods delegate to the stubbed 
listStatus / listStatusLight.
+    proxy = mock(ClientProtocol.class, CALLS_REAL_METHODS);
     objectStore = mock(ObjectStore.class);
     bucket = mock(OzoneBucket.class);
 
@@ -111,6 +118,10 @@ private List<FileStatusAdapter> listStatus(boolean lite) 
throws IOException {
     return adapter.listStatus(DIR_PATH, false, "", 100, OFS_URI, new 
Path("/"), "user", lite);
   }
 
+  private ListStatusResult<FileStatusAdapter> listStatusPage(String path, 
boolean lite) throws IOException {
+    return adapter.listStatusPage(path, false, "", 100, OFS_URI, new 
Path("/"), "user", lite);
+  }
+
   private void failListing(OMException e) throws IOException {
     when(proxy.listStatus(any(ListStatusLightOptions.class))).thenThrow(e);
     
when(proxy.listStatusLight(any(ListStatusLightOptions.class))).thenThrow(e);
@@ -146,6 +157,38 @@ public void listingIsTheOnlyOmCall(boolean lite) throws 
IOException {
     verify(objectStore, never()).getVolume(anyString());
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {true, false})
+  public void listingPassesOnWhetherOmReportedTheListingComplete(boolean lite) 
throws IOException {
+    for (boolean truncated : new boolean[] {true, false}) {
+      when(proxy.listStatusLightPage(any(ListStatusLightOptions.class)))
+          
.thenReturn(ListStatusResult.<OzoneFileStatusLight>of(Collections.emptyList(), 
truncated));
+      when(proxy.listStatusPage(any(ListStatusLightOptions.class)))
+          
.thenReturn(ListStatusResult.<OzoneFileStatus>of(Collections.emptyList(), 
truncated));
+
+      assertEquals(!truncated, listStatusPage(DIR_PATH, lite).isComplete());
+    }
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {true, false})
+  public void listingWithoutOmReportIsNotComplete(boolean lite) throws 
IOException {
+    // The default page methods wrap listStatus / listStatusLight, as for an 
OM that does not set the flag.
+    assertFalse(listStatusPage(DIR_PATH, lite).isComplete());
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"/", "/vol"})
+  public void rootAndVolumeListingsAreNotComplete(String path) throws 
IOException {
+    // Root and volume listings do not come from ListStatus, so they cannot 
report completeness.
+    when(objectStore.listVolumesByUser(anyString(), any(), 
any())).thenAnswer(i -> Collections.emptyIterator());
+    OzoneVolume volume = mock(OzoneVolume.class);
+    when(objectStore.getVolume("vol")).thenReturn(volume);
+    when(volume.listBuckets(any(), any())).thenAnswer(i -> 
Collections.emptyIterator());
+
+    assertFalse(listStatusPage(path, true).isComplete());
+  }
+
   @ParameterizedTest
   @EnumSource(value = ResultCodes.class, names = {"BUCKET_NOT_FOUND", 
"VOLUME_NOT_FOUND"})
   public void orphanLinkReturnsEmptyListAfterFailedListing(ResultCodes code) 
throws IOException {
diff --git 
a/hadoop-ozone/ozonefs-common/src/test/java/org/apache/hadoop/fs/ozone/TestOzoneFileSystemListStatusPages.java
 
b/hadoop-ozone/ozonefs-common/src/test/java/org/apache/hadoop/fs/ozone/TestOzoneFileSystemListStatusPages.java
new file mode 100644
index 00000000000..44951fbc764
--- /dev/null
+++ 
b/hadoop-ozone/ozonefs-common/src/test/java/org/apache/hadoop/fs/ozone/TestOzoneFileSystemListStatusPages.java
@@ -0,0 +1,182 @@
+/*
+ * 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.fs.ozone;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.apache.hadoop.fs.BlockLocation;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.hadoop.hdds.conf.ConfigurationSource;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.ozone.om.helpers.ListStatusResult;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+/**
+ * The ofs and o3fs listing loops (listStatus and listStatusIterator) stop 
after a page that OM reports as
+ * complete, and keep listing until a page adds nothing when OM does not 
report it (HDDS-16943). Uses a mock
+ * adapter so no cluster is required.
+ */
+public class TestOzoneFileSystemListStatusPages {
+
+  private static final String DIR = "/vol/bucket/dir";
+
+  private OzoneClientAdapter adapter;
+
+  /** The file system under test, with its listed directory. */
+  enum Fs { OFS, O3FS }
+
+  private FileSystem create(Fs type) throws IOException {
+    FileSystem fs;
+    if (type == Fs.OFS) {
+      adapter = mock(BasicRootedOzoneClientAdapterImpl.class);
+      fs = new BasicRootedOzoneFileSystem() {
+        @Override
+        protected OzoneClientAdapter createAdapter(ConfigurationSource conf, 
String omHost, int omPort) {
+          return adapter;
+        }
+      };
+      fs.initialize(URI.create("ofs://om/"), new OzoneConfiguration());
+    } else {
+      adapter = mock(BasicOzoneClientAdapterImpl.class);
+      fs = new BasicOzoneFileSystem() {
+        @Override
+        protected OzoneClientAdapter createAdapter(ConfigurationSource conf, 
String bucketStr, String volumeStr,
+            String omHost, int omPort) {
+          return adapter;
+        }
+      };
+      fs.initialize(URI.create("o3fs://bucket.vol/"), new 
OzoneConfiguration());
+    }
+    return fs;
+  }
+
+  private static FileStatusAdapter entry(String name) {
+    return new FileStatusAdapter(0L, 0L, new Path(DIR + "/" + name), false, 
(short) 3, 0L, 0L, 0L,
+        (short) 0, "user", "group", null, new BlockLocation[0], false, false);
+  }
+
+  private static List<FileStatusAdapter> entries(String... names) {
+    return Arrays.stream(names).map(TestOzoneFileSystemListStatusPages::entry)
+        .collect(Collectors.toCollection(ArrayList::new));
+  }
+
+  /** Each listing call returns the next page; the listing repeats its start 
key, as OM does. */
+  @SafeVarargs
+  private final void stubPages(ListStatusResult<FileStatusAdapter>... pages) 
throws IOException {
+    when(adapter.listStatusPage(anyString(), anyBoolean(), anyString(), 
anyLong(), any(URI.class),
+        any(Path.class), anyString(), anyBoolean()))
+        .thenReturn(pages[0], Arrays.copyOfRange(pages, 1, pages.length));
+  }
+
+  private void verifyListingCalls(int calls) throws IOException {
+    verify(adapter, times(calls)).listStatusPage(anyString(), anyBoolean(), 
anyString(), anyLong(),
+        any(URI.class), any(Path.class), anyString(), anyBoolean());
+  }
+
+  private static List<String> names(FileStatus[] statuses) {
+    return Arrays.stream(statuses).map(s -> 
s.getPath().getName()).collect(Collectors.toList());
+  }
+
+  private static List<String> names(RemoteIterator<FileStatus> it) throws 
IOException {
+    List<String> names = new ArrayList<>();
+    while (it.hasNext()) {
+      names.add(it.next().getPath().getName());
+    }
+    return names;
+  }
+
+  @ParameterizedTest
+  @EnumSource(Fs.class)
+  public void listStatusStopsAfterCompletePage(Fs type) throws IOException {
+    FileSystem fs = create(type);
+    stubPages(ListStatusResult.of(entries("a", "b", "c"), false));
+
+    assertThat(names(fs.listStatus(new Path(DIR)))).containsExactly("a", "b", 
"c");
+    verifyListingCalls(1);
+  }
+
+  @ParameterizedTest
+  @EnumSource(Fs.class)
+  public void listStatusContinuesAfterTruncatedPage(Fs type) throws 
IOException {
+    FileSystem fs = create(type);
+    // OM capped the first page below the requested size; only the flag says 
that more entries follow.
+    stubPages(ListStatusResult.of(entries("a", "b"), true), 
ListStatusResult.of(entries("b", "c"), false));
+
+    assertThat(names(fs.listStatus(new Path(DIR)))).containsExactly("a", "b", 
"c");
+    verifyListingCalls(2);
+  }
+
+  @ParameterizedTest
+  @EnumSource(Fs.class)
+  public void listStatusWithoutOmReportListsUntilPageAddsNothing(Fs type) 
throws IOException {
+    FileSystem fs = create(type);
+    // An older OM: keep listing until a page only repeats the start key.
+    stubPages(ListStatusResult.unknown(entries("a", "b", "c")), 
ListStatusResult.unknown(entries("c")));
+
+    assertThat(names(fs.listStatus(new Path(DIR)))).containsExactly("a", "b", 
"c");
+    verifyListingCalls(2);
+  }
+
+  @ParameterizedTest
+  @EnumSource(Fs.class)
+  public void listStatusIteratorStopsAfterCompletePage(Fs type) throws 
IOException {
+    FileSystem fs = create(type);
+    stubPages(ListStatusResult.of(entries("a", "b", "c"), false));
+
+    assertThat(names(fs.listStatusIterator(new 
Path(DIR)))).containsExactly("a", "b", "c");
+    verifyListingCalls(1);
+  }
+
+  @ParameterizedTest
+  @EnumSource(Fs.class)
+  public void listStatusIteratorContinuesAfterTruncatedPage(Fs type) throws 
IOException {
+    FileSystem fs = create(type);
+    stubPages(ListStatusResult.of(entries("a", "b"), true), 
ListStatusResult.of(entries("b", "c"), false));
+
+    assertThat(names(fs.listStatusIterator(new 
Path(DIR)))).containsExactly("a", "b", "c");
+    verifyListingCalls(2);
+  }
+
+  @ParameterizedTest
+  @EnumSource(Fs.class)
+  public void listStatusIteratorWithoutOmReportListsUntilEmptyPage(Fs type) 
throws IOException {
+    FileSystem fs = create(type);
+    stubPages(ListStatusResult.unknown(entries("a", "b", "c")), 
ListStatusResult.unknown(entries("c")));
+
+    assertThat(names(fs.listStatusIterator(new 
Path(DIR)))).containsExactly("a", "b", "c");
+    verifyListingCalls(2);
+  }
+}


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

Reply via email to