You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by "SaketaChalamchala (via GitHub)" <gi...@apache.org> on 2026/07/16 00:12:07 UTC

[PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

SaketaChalamchala opened a new pull request, #10778:
URL: https://github.com/apache/ozone/pull/10778

   ## What changes were proposed in this pull request?
   Developed with the help of Cursor AI.
   
   This PR is intended as the foundation for a more efficient snapshot diff ([HDDS-9154](https://issues.apache.org/jira/browse/HDDS-9154)).
   
   Baseline snapshot diff reports order entries by diff type (`DELETE`s first, then `RENAME`/`CREATE`/`MODIFY`). That ordering is not always safe to replay. For example, if `A/B` is renamed to `C/B` and directory `A` is deleted, replaying the `DELETE` before the `RENAME` fails on because the rename source no longer exists.
   This PR adds isolated utilities for dependency-ordered snapshot diff report generation.
   
   **SnapDiffDependencyEntry**
   - Wraps a classified diff entry with objectId, parentObjectId, and the underlying DiffReportEntry
   - Provides the metadata needed to build hierarchy and path-conflict edges
   
   **SnapDiffDependencyGraph**
   - Accepts a list of SnapDiffDependencyEntry values and builds a directed dependency graph in the constructor
   - Applies these dependency rules defined via directed edges (u -> v means u must appear before v):
     - Parent CREATE/RENAME/MODIFY before child CREATE/RENAME/MODIFY
     - Child DELETE before parent DELETE
     - Non-delete entry before DELETE of its parent object
     - DELETE before CREATE/RENAME(target) that targets the same path
     - RENAME(source) before CREATE that targets the same path
   - Exposes getOrderedEntries() using Kahn's algorithm
   - Exposes static toOrderedReportEntries() to convert ordered dependency entries into DiffReportEntry payloads
   
   ## What is the link to the Apache JIRA
   
   https://issues.apache.org/jira/browse/HDDS-15390
   
   ## How was this patch tested?
   
   Unit Test.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3799725775


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,569 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant non-delete before ancestor DELETE on a strict source-path
+ *       prefix.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  // Hotspot/OpenJDK cap the largest array a little below Integer.MAX_VALUE.
+  // Node and edge counts are assumed to fit in int; the configured changed-key
+  // limit (one billion) is well below this bound.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final char PATH_SEPARATOR = '/';
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges = new long[INITIAL_EDGE_CAPACITY];
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Released once edges are built.
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    nodes.addAll(entries);
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];

Review Comment:
   @smengcl PTAL



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3764593959


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,569 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant non-delete before ancestor DELETE on a strict source-path
+ *       prefix.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  // Hotspot/OpenJDK cap the largest array a little below Integer.MAX_VALUE.
+  // Node and edge counts are assumed to fit in int; the configured changed-key
+  // limit (one billion) is well below this bound.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final char PATH_SEPARATOR = '/';
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges = new long[INITIAL_EDGE_CAPACITY];
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Released once edges are built.
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    nodes.addAll(entries);
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];

Review Comment:
   Thanks @SaketaChalamchala .
   
   AFAICT the current producer still reports a directory `MODIFY` from `newParentIdPathMap`, but reports a key `MODIFY` at `oldKey`. The Javadoc does not match this behavior.
   
   `RENAME A -> B`, `RENAME X -> A`, and directory `MODIFY A/child` still cause a false cycle.
   Pls identify the path side for each `MODIFY` entry, and test both source-side key and target-side directory cases.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3644281227


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,252 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Parent CREATE/RENAME/MODIFY before child CREATE/RENAME/MODIFY.</li>
+ *   <li>Child DELETE before parent DELETE.</li>
+ *   <li>Non-delete entry before DELETE of its parent object.</li>
+ *   <li>DELETE before CREATE/RENAME that targets the same path.</li>
+ *   <li>RENAME before CREATE that reuses the rename source path.</li>
+ * </ul>
+ *
+ * <p>A RENAME target path cannot match a CREATE path in the same diff report.
+ */
+public final class SnapDiffDependencyGraph {
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+  private final Map<Integer, Set<Integer>> adjacencyList = new HashMap<>();
+  private final Map<Integer, Integer> inDegree = new HashMap<>();
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    for (SnapDiffDependencyEntry entry : entries) {
+      addNode(entry);
+    }
+    buildDependencyEdges();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    Queue<Integer> zeroInDegree = new ArrayDeque<>();
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      if (inDegree.get(nodeId) == 0) {
+        zeroInDegree.add(nodeId);
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodes.size());
+    while (!zeroInDegree.isEmpty()) {
+      int nodeId = zeroInDegree.remove();
+      orderedEntries.add(nodes.get(nodeId));
+      for (int dependentNodeId : adjacencyList.get(nodeId)) {
+        int updatedInDegree = inDegree.get(dependentNodeId) - 1;
+        inDegree.put(dependentNodeId, updatedInDegree);
+        if (updatedInDegree == 0) {
+          zeroInDegree.add(dependentNodeId);
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodes.size()) {
+      throw new IllegalStateException(
+          "Cycle detected in snapshot diff dependency graph");
+    }
+    return orderedEntries;
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private int addNode(SnapDiffDependencyEntry entry) {
+    int nodeId = nodes.size();
+    nodes.add(entry);
+    adjacencyList.put(nodeId, new HashSet<>());
+    inDegree.put(nodeId, 0);
+    return nodeId;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (adjacencyList.get(fromNodeId).add(toNodeId)) {
+      inDegree.put(toNodeId, inDegree.get(toNodeId) + 1);
+    }
+  }
+
+  private void buildDependencyEdges() {
+    // One objectId can map to multiple non-delete nodes, for example RENAME + MODIFY.
+    Map<Long, List<Integer>> nonDeleteNodesByObjectId = new HashMap<>();
+    // Each objectId has at most one DELETE entry after top-level delete retention.
+    Map<Long, Integer> deleteNodesByObjectId = new HashMap<>();
+    Map<String, List<Integer>> createNodesByPath = new HashMap<>();
+    Map<String, List<Integer>> deleteNodesByPath = new HashMap<>();
+    Map<String, List<Integer>> renameNodesBySourcePath = new HashMap<>();
+    Map<String, List<Integer>> renameNodesByTargetPath = new HashMap<>();
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        deleteNodesByObjectId.put(entry.getObjectId(), nodeId);
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        nonDeleteNodesByObjectId
+            .computeIfAbsent(entry.getObjectId(), ignored -> new ArrayList<>())
+            .add(nodeId);
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      long parentObjectId = entry.getParentObjectId();
+      if (parentObjectId <= 0L) {
+        continue;
+      }
+
+      Integer parentDeleteNodeId = deleteNodesByObjectId.get(parentObjectId);
+      if (entry.isDelete()) {
+        if (parentDeleteNodeId != null) {
+          addEdge(nodeId, parentDeleteNodeId);
+        }
+      } else {
+        addEdgesFromNodes(
+            nonDeleteNodesByObjectId.getOrDefault(parentObjectId,
+                Collections.emptyList()),
+            nodeId);
+        if (parentDeleteNodeId != null) {
+          addEdge(nodeId, parentDeleteNodeId);
+        }
+      }
+    }
+
+    addPathConflictEdges(deleteNodesByPath, createNodesByPath,
+        renameNodesByTargetPath);
+    addRenameBeforeCreateEdges(renameNodesBySourcePath, createNodesByPath);

Review Comment:
   Renames also need path dependencies on other renames. For `A -> B` and `B -> C`, `B -> C` must run first to free `B`. Currently only `RENAME -> CREATE` is covered, so input order `[A -> B, B -> C]` is returned unchanged and the first rename cannot be replayed. Please add the corresponding rename-to-rename edge, with chain and cycle tests.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,252 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Parent CREATE/RENAME/MODIFY before child CREATE/RENAME/MODIFY.</li>
+ *   <li>Child DELETE before parent DELETE.</li>
+ *   <li>Non-delete entry before DELETE of its parent object.</li>
+ *   <li>DELETE before CREATE/RENAME that targets the same path.</li>
+ *   <li>RENAME before CREATE that reuses the rename source path.</li>
+ * </ul>
+ *
+ * <p>A RENAME target path cannot match a CREATE path in the same diff report.
+ */
+public final class SnapDiffDependencyGraph {
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+  private final Map<Integer, Set<Integer>> adjacencyList = new HashMap<>();
+  private final Map<Integer, Integer> inDegree = new HashMap<>();
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    for (SnapDiffDependencyEntry entry : entries) {
+      addNode(entry);
+    }
+    buildDependencyEdges();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    Queue<Integer> zeroInDegree = new ArrayDeque<>();
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      if (inDegree.get(nodeId) == 0) {
+        zeroInDegree.add(nodeId);
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodes.size());
+    while (!zeroInDegree.isEmpty()) {
+      int nodeId = zeroInDegree.remove();
+      orderedEntries.add(nodes.get(nodeId));
+      for (int dependentNodeId : adjacencyList.get(nodeId)) {
+        int updatedInDegree = inDegree.get(dependentNodeId) - 1;
+        inDegree.put(dependentNodeId, updatedInDegree);
+        if (updatedInDegree == 0) {
+          zeroInDegree.add(dependentNodeId);
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodes.size()) {
+      throw new IllegalStateException(
+          "Cycle detected in snapshot diff dependency graph");
+    }
+    return orderedEntries;
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private int addNode(SnapDiffDependencyEntry entry) {
+    int nodeId = nodes.size();
+    nodes.add(entry);
+    adjacencyList.put(nodeId, new HashSet<>());
+    inDegree.put(nodeId, 0);
+    return nodeId;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (adjacencyList.get(fromNodeId).add(toNodeId)) {
+      inDegree.put(toNodeId, inDegree.get(toNodeId) + 1);
+    }
+  }
+
+  private void buildDependencyEdges() {
+    // One objectId can map to multiple non-delete nodes, for example RENAME + MODIFY.
+    Map<Long, List<Integer>> nonDeleteNodesByObjectId = new HashMap<>();
+    // Each objectId has at most one DELETE entry after top-level delete retention.
+    Map<Long, Integer> deleteNodesByObjectId = new HashMap<>();
+    Map<String, List<Integer>> createNodesByPath = new HashMap<>();
+    Map<String, List<Integer>> deleteNodesByPath = new HashMap<>();
+    Map<String, List<Integer>> renameNodesBySourcePath = new HashMap<>();
+    Map<String, List<Integer>> renameNodesByTargetPath = new HashMap<>();
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        deleteNodesByObjectId.put(entry.getObjectId(), nodeId);
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        nonDeleteNodesByObjectId
+            .computeIfAbsent(entry.getObjectId(), ignored -> new ArrayList<>())
+            .add(nodeId);
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      long parentObjectId = entry.getParentObjectId();
+      if (parentObjectId <= 0L) {
+        continue;
+      }
+
+      Integer parentDeleteNodeId = deleteNodesByObjectId.get(parentObjectId);
+      if (entry.isDelete()) {
+        if (parentDeleteNodeId != null) {
+          addEdge(nodeId, parentDeleteNodeId);
+        }

Review Comment:
   The `DELETE` branch ignores a parent `RENAME`. For `[RENAME A -> B, DELETE A/child]`, the input order remains unchanged and the delete then addresses a path that has moved. Please add a child `DELETE ->` parent `RENAME` edge and a test for this case.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,252 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Parent CREATE/RENAME/MODIFY before child CREATE/RENAME/MODIFY.</li>
+ *   <li>Child DELETE before parent DELETE.</li>
+ *   <li>Non-delete entry before DELETE of its parent object.</li>
+ *   <li>DELETE before CREATE/RENAME that targets the same path.</li>
+ *   <li>RENAME before CREATE that reuses the rename source path.</li>
+ * </ul>
+ *
+ * <p>A RENAME target path cannot match a CREATE path in the same diff report.
+ */
+public final class SnapDiffDependencyGraph {
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+  private final Map<Integer, Set<Integer>> adjacencyList = new HashMap<>();
+  private final Map<Integer, Integer> inDegree = new HashMap<>();
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    for (SnapDiffDependencyEntry entry : entries) {
+      addNode(entry);
+    }
+    buildDependencyEdges();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    Queue<Integer> zeroInDegree = new ArrayDeque<>();
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      if (inDegree.get(nodeId) == 0) {
+        zeroInDegree.add(nodeId);
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodes.size());
+    while (!zeroInDegree.isEmpty()) {
+      int nodeId = zeroInDegree.remove();
+      orderedEntries.add(nodes.get(nodeId));
+      for (int dependentNodeId : adjacencyList.get(nodeId)) {
+        int updatedInDegree = inDegree.get(dependentNodeId) - 1;
+        inDegree.put(dependentNodeId, updatedInDegree);

Review Comment:
   `getOrderedEntries()` mutates the graph’s stored `inDegree`. After one call, a second call can enqueue every node and return input order instead of dependency order. Please sort using a local copy of the indegrees or cache the result, and add a repeated-call test.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyEntry.java:
##########
@@ -0,0 +1,91 @@
+/*
+ * 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.snapshot;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Objects;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+
+/**
+ * Metadata for a classified snapshot diff entry used to build the dependency
+ * graph for dependency-ordered report emission.
+ */
+public final class SnapDiffDependencyEntry {
+
+  private final long objectId;
+  private final long parentObjectId;
+  private final DiffReportEntry reportEntry;
+
+  public SnapDiffDependencyEntry(long objectId, long parentObjectId,
+      DiffReportEntry reportEntry) {

Review Comment:
   A cross-parent rename needs both parent IDs. For `A/B -> C/B` with `DELETE A` and `CREATE C`, `C` must be created before the rename, while `A` must remain until after it. A single `parentObjectId` can enforce only one of these dependencies. Please carry the source and target parent IDs, or equivalent explicit dependencies.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,252 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Parent CREATE/RENAME/MODIFY before child CREATE/RENAME/MODIFY.</li>
+ *   <li>Child DELETE before parent DELETE.</li>
+ *   <li>Non-delete entry before DELETE of its parent object.</li>
+ *   <li>DELETE before CREATE/RENAME that targets the same path.</li>
+ *   <li>RENAME before CREATE that reuses the rename source path.</li>
+ * </ul>
+ *
+ * <p>A RENAME target path cannot match a CREATE path in the same diff report.
+ */
+public final class SnapDiffDependencyGraph {
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+  private final Map<Integer, Set<Integer>> adjacencyList = new HashMap<>();
+  private final Map<Integer, Integer> inDegree = new HashMap<>();
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    for (SnapDiffDependencyEntry entry : entries) {
+      addNode(entry);
+    }
+    buildDependencyEdges();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    Queue<Integer> zeroInDegree = new ArrayDeque<>();
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      if (inDegree.get(nodeId) == 0) {
+        zeroInDegree.add(nodeId);
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodes.size());
+    while (!zeroInDegree.isEmpty()) {
+      int nodeId = zeroInDegree.remove();
+      orderedEntries.add(nodes.get(nodeId));
+      for (int dependentNodeId : adjacencyList.get(nodeId)) {
+        int updatedInDegree = inDegree.get(dependentNodeId) - 1;
+        inDegree.put(dependentNodeId, updatedInDegree);
+        if (updatedInDegree == 0) {
+          zeroInDegree.add(dependentNodeId);
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodes.size()) {
+      throw new IllegalStateException(
+          "Cycle detected in snapshot diff dependency graph");
+    }
+    return orderedEntries;
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private int addNode(SnapDiffDependencyEntry entry) {
+    int nodeId = nodes.size();
+    nodes.add(entry);
+    adjacencyList.put(nodeId, new HashSet<>());
+    inDegree.put(nodeId, 0);

Review Comment:
   Each node allocates an empty `HashSet` plus boxed entries in two `HashMap`s, before the temporary path and object indexes. The default changed-key limit is one billion, so this representation can exhaust OM heap far below the configured limit. Please consider primitive, lazy, or batched graph state and add scale coverage.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3823003206


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/diff/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,569 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant non-delete before ancestor DELETE on a strict source-path
+ *       prefix.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  // Hotspot/OpenJDK cap the largest array a little below Integer.MAX_VALUE.
+  // Node and edge counts are assumed to fit in int; the configured changed-key
+  // limit (one billion) is well below this bound.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final char PATH_SEPARATOR = '/';
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges = new long[INITIAL_EDGE_CAPACITY];
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Released once edges are built.
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    nodes.addAll(entries);
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];

Review Comment:
   Thanks @SaketaChalamchala



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3709546064


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,569 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant non-delete before ancestor DELETE on a strict source-path
+ *       prefix.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  // Hotspot/OpenJDK cap the largest array a little below Integer.MAX_VALUE.
+  // Node and edge counts are assumed to fit in int; the configured changed-key
+  // limit (one billion) is well below this bound.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final char PATH_SEPARATOR = '/';
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges = new long[INITIAL_EDGE_CAPACITY];
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Released once edges are built.
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    nodes.addAll(entries);
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];

Review Comment:
   Thanks for [replacing the maps and sets](https://github.com/apache/ozone/pull/10778#discussion_r3644281240) with primitive arrays. That reduces memory usage.
   
   However, the graph still keeps all diff entries in memory. It also creates several arrays with one element for each entry. This method creates three more arrays with `nodeCount` elements.
   
   With a limit of one billion changed keys, these arrays require tens of GB:
   
   > Assuming 64-bit HotSpot with compressed 4-byte references:
   > - Sorting retains five `int` arrays and two reference arrays with about `N` elements: `(5 × 4N) + (2 × 4N) = 28N` bytes. If `N = 1B`, this is 28 GB (26.1 GiB).
   > - `adjTargets` adds `4 × E` bytes. If `E = N = 1B`, this adds 4 GB (3.7 GiB).
   > - Each path-index mapping needs approximately a 32-byte `HashMap.Node`, a 16-byte boxed `Integer`, and at least 4 bytes of bucket storage: at least 52 bytes.
   > - One billion mappings therefore need at least 52 GB (48.4 GiB).
   > - Rename-heavy input creates two mappings per entry. If `N = 1B`, then `M = 2N`, which needs at least 104 GB (96.9 GiB).
   >
   > Estimates exclude the entries, report objects, and decoded path strings.
   
   Shall we have a follow-up task for bounded or batched processing?



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,569 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant non-delete before ancestor DELETE on a strict source-path
+ *       prefix.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  // Hotspot/OpenJDK cap the largest array a little below Integer.MAX_VALUE.
+  // Node and edge counts are assumed to fit in int; the configured changed-key
+  // limit (one billion) is well below this bound.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final char PATH_SEPARATOR = '/';
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges = new long[INITIAL_EDGE_CAPACITY];
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Released once edges are built.
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    nodes.addAll(entries);
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];
+    int deleteHead = 0;
+    int deleteTail = 0;
+    int otherHead = 0;
+    int otherTail = 0;
+    for (int nodeId = 0; nodeId < nodeCount; nodeId++) {
+      if (remainingInDegree[nodeId] == 0) {
+        if (nodes.get(nodeId).isDelete()) {
+          deleteReady[deleteTail++] = nodeId;
+        } else {
+          otherReady[otherTail++] = nodeId;
+        }
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodeCount);
+    while (deleteHead < deleteTail || otherHead < otherTail) {
+      int nodeId = deleteHead < deleteTail
+          ? deleteReady[deleteHead++] : otherReady[otherHead++];
+      orderedEntries.add(nodes.get(nodeId));
+      for (int i = adjOffsets[nodeId]; i < adjOffsets[nodeId + 1]; i++) {
+        int dependentNodeId = adjTargets[i];
+        if (--remainingInDegree[dependentNodeId] == 0) {
+          if (nodes.get(dependentNodeId).isDelete()) {
+            deleteReady[deleteTail++] = dependentNodeId;
+          } else {
+            otherReady[otherTail++] = dependentNodeId;
+          }
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodeCount) {
+      logUnresolvedNodes(orderedEntries);
+      throw new IllegalStateException(
+          "Cycle detected in snapshot diff dependency graph");
+    }
+    return orderedEntries;
+  }
+
+  private void logUnresolvedNodes(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    if (!LOG.isDebugEnabled()) {
+      return;
+    }
+    Set<SnapDiffDependencyEntry> resolved =
+        Collections.newSetFromMap(new IdentityHashMap<>());
+    resolved.addAll(orderedEntries);
+    List<String> unresolved = new ArrayList<>();
+    for (SnapDiffDependencyEntry entry : nodes) {
+      if (!resolved.contains(entry)) {
+        unresolved.add(entry.getDiffType() + " " + entry.getSourcePath());
+      }
+    }
+    LOG.debug("Cycle detected in snapshot diff dependency graph. "
+        + "Unresolved entries: {}", unresolved);
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (edgeCount == edges.length) {
+      edges = Arrays.copyOf(edges, grownCapacity(edges.length));
+    }
+    edges[edgeCount++] =
+        ((long) fromNodeId << Integer.SIZE) | (toNodeId & 0xFFFFFFFFL);
+  }
+
+  private static int grownCapacity(int currentCapacity) {
+    // Grow by 1.5x to bound the transient overshoot of the edge buffer, and
+    // clamp to MAX_ARRAY_SIZE so the growth cannot overflow into a negative
+    // (or unallocatable) size.
+    int grown = currentCapacity + (currentCapacity >> 1);
+    if (grown < 0 || grown > MAX_ARRAY_SIZE) {
+      if (currentCapacity >= MAX_ARRAY_SIZE) {
+        throw new IllegalStateException(
+            "Snapshot diff dependency graph exceeds maximum edge capacity");
+      }
+      return MAX_ARRAY_SIZE;
+    }
+    return grown;
+  }
+
+  /**
+   * Deduplicates the collected edges and packs them into the CSR arrays.
+   * Encoding each edge as {@code (from << 32 | to)} lets a single sort group
+   * neighbors by source node and place duplicates next to each other, so the
+   * repeated {@code HashSet} allocations of the previous representation are no
+   * longer needed. The temporary edge buffer is released afterwards.
+   */
+  private void buildCsr() {
+    int nodeCount = nodes.size();
+    adjOffsets = new int[nodeCount + 1];
+    inDegree = new int[nodeCount];
+    if (edgeCount == 0) {
+      adjTargets = EMPTY_INT_ARRAY;
+      edges = null;
+      return;
+    }
+
+    Arrays.sort(edges, 0, edgeCount);
+
+    // First pass over the sorted edges: skip duplicates while counting the
+    // out-edges per source node and the in-degree per target node.
+    long previous = edges[0];
+    int uniqueCount = 1;
+    adjOffsets[(int) (previous >>> Integer.SIZE) + 1]++;
+    inDegree[(int) previous]++;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      uniqueCount++;
+      adjOffsets[(int) (edge >>> Integer.SIZE) + 1]++;
+      inDegree[(int) edge]++;
+    }
+
+    // Prefix sum turns per-node out-edge counts into CSR start offsets.
+    for (int i = 0; i < nodeCount; i++) {
+      adjOffsets[i + 1] += adjOffsets[i];
+    }
+
+    // Second pass: the unique edges are already ordered by source then target,
+    // so appending their targets sequentially matches the CSR offsets.
+    adjTargets = new int[uniqueCount];
+    previous = edges[0];
+    int index = 0;
+    adjTargets[index++] = (int) previous;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      adjTargets[index++] = (int) edge;
+    }
+    edges = null;
+  }
+
+  private void buildDependencyEdges() {
+    // At most one object occupies a given path on a given snapshot side, so a
+    // single node id per path is sufficient (see addToPathIndex).
+    Map<String, Integer> createNodesByPath = new HashMap<>();
+    Map<String, Integer> deleteNodesByPath = new HashMap<>();
+    Map<String, Integer> renameNodesBySourcePath = new HashMap<>();
+    Map<String, Integer> renameNodesByTargetPath = new HashMap<>();
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    addPathConflictEdges(deleteNodesByPath, createNodesByPath,
+        renameNodesByTargetPath);
+    addRenameBeforeCreateEdges(renameNodesBySourcePath, createNodesByPath);
+    addRenameChainEdges(renameNodesBySourcePath, renameNodesByTargetPath);
+    addPathPrefixFromSnapshotEdges(deleteNodesByPath, renameNodesBySourcePath);
+    addPathPrefixToSnapshotEdges(createNodesByPath, renameNodesByTargetPath);
+
+    buildObjectIdGroups();
+    addIntraObjectRenameEdges();
+
+    groupObjectIds = null;
+    groupOffsets = null;
+    groupNodes = null;
+  }
+
+  /**
+   * Groups node ids by objectId into primitive arrays for intra-object RENAME
+   * ordering. objectIds are sorted and de-duplicated so the matching node ids
+   * for one objectId are the slice of {@link #groupNodes} delimited by
+   * {@link #groupOffsets}.
+   */
+  private void buildObjectIdGroups() {
+    int nodeCount = nodes.size();
+    long[] sorted = new long[nodeCount];
+    for (int i = 0; i < nodeCount; i++) {
+      sorted[i] = nodes.get(i).getObjectId();
+    }
+    Arrays.sort(sorted);
+
+    int uniqueCount = 0;
+    long previous = 0L;
+    for (int i = 0; i < nodeCount; i++) {
+      long objectId = sorted[i];
+      if (uniqueCount == 0 || objectId != previous) {
+        sorted[uniqueCount++] = objectId;
+        previous = objectId;
+      }
+    }
+    groupObjectIds = Arrays.copyOf(sorted, uniqueCount);
+
+    int[] rankByNode = new int[nodeCount];
+    groupOffsets = new int[uniqueCount + 1];
+    for (int i = 0; i < nodeCount; i++) {
+      int rank = Arrays.binarySearch(groupObjectIds, nodes.get(i).getObjectId());
+      rankByNode[i] = rank;
+      groupOffsets[rank + 1]++;
+    }
+    for (int i = 0; i < uniqueCount; i++) {
+      groupOffsets[i + 1] += groupOffsets[i];
+    }
+
+    groupNodes = new int[nodeCount];
+    int[] fillCursor = Arrays.copyOf(groupOffsets, uniqueCount);
+    for (int i = 0; i < nodeCount; i++) {
+      groupNodes[fillCursor[rankByNode[i]]++] = i;
+    }
+  }
+
+  /**
+   * Orders the non-delete entries of a single object relative to its RENAME.
+   * An entry reported at the RENAME source (from-snapshot) path must be applied
+   * before the path is renamed away; an entry reported at the RENAME target
+   * (to-snapshot) path must be applied after the rename creates that path.
+   */
+  private void addIntraObjectRenameEdges() {
+    for (int rank = 0; rank < groupObjectIds.length; rank++) {
+      int start = groupOffsets[rank];
+      int end = groupOffsets[rank + 1];
+      if (end - start < 2) {
+        continue;
+      }
+      int renameNodeId = -1;
+      for (int i = start; i < end; i++) {
+        if (nodes.get(groupNodes[i]).getDiffType() == DiffType.RENAME) {
+          renameNodeId = groupNodes[i];
+          break;
+        }
+      }
+      if (renameNodeId < 0) {
+        continue;
+      }
+      SnapDiffDependencyEntry rename = nodes.get(renameNodeId);
+      for (int i = start; i < end; i++) {
+        int nodeId = groupNodes[i];
+        if (nodeId == renameNodeId) {
+          continue;
+        }
+        String path = nodes.get(nodeId).getSourcePath();
+        if (path == null) {
+          continue;
+        }
+        if (path.equals(rename.getSourcePath())) {
+          addEdge(nodeId, renameNodeId);
+        } else if (path.equals(rename.getTargetPath())) {
+          addEdge(renameNodeId, nodeId);
+        }
+      }
+    }
+  }
+
+  private static void addToPathIndex(Map<String, Integer> pathIndex,
+      String path, int nodeId) {
+    if (path == null) {
+      return;
+    }
+    // At most one object can occupy a path on a given snapshot side, so the
+    // first node wins. A second node on the same path indicates unexpected or
+    // duplicate diff input.
+    Integer existing = pathIndex.putIfAbsent(path, nodeId);
+    if (existing != null) {
+      LOG.debug("Multiple diff entries share path '{}'; keeping node {}, "
+          + "ignoring node {}", path, existing, nodeId);
+    }
+  }
+
+  /**
+   * Orders renames that reuse the same path: the rename whose source frees a
+   * path must precede the rename whose target occupies that same path.
+   */
+  private void addRenameChainEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> sourceEntry :
+        renameNodesBySourcePath.entrySet()) {
+      Integer targetNodeId =
+          renameNodesByTargetPath.get(sourceEntry.getKey());
+      if (targetNodeId != null) {
+        addEdge(sourceEntry.getValue(), targetNodeId);
+      }
+    }
+  }
+
+  private void addPathConflictEdges(Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      String path = deleteEntry.getKey();
+      int deleteNodeId = deleteEntry.getValue();
+      Integer createNodeId = createNodesByPath.get(path);
+      if (createNodeId != null) {
+        addEdge(deleteNodeId, createNodeId);
+      }
+      Integer renameTargetNodeId = renameNodesByTargetPath.get(path);
+      if (renameTargetNodeId != null) {
+        addEdge(deleteNodeId, renameTargetNodeId);
+      }
+    }
+  }
+
+  private void addRenameBeforeCreateEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> createNodesByPath) {
+    for (Map.Entry<String, Integer> createEntry :
+        createNodesByPath.entrySet()) {
+      Integer renameNodeId =
+          renameNodesBySourcePath.get(createEntry.getKey());
+      if (renameNodeId != null) {
+        addEdge(renameNodeId, createEntry.getValue());
+      }
+    }
+  }
+
+  /**
+   * From-snapshot path-prefix edges. Intermediate directories may be omitted
+   * from the report; ancestor ordering is derived from strict path prefixes.
+   */
+  private void addPathPrefixFromSnapshotEdges(
+      Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> renameNodesBySourcePath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      int descendantDeleteNodeId = deleteEntry.getValue();
+      forEachStrictPrefix(deleteEntry.getKey(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        continue;
+      }
+      final int fromNodeId = nodeId;
+      forEachStrictPrefix(entry.getSourcePath(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(fromNodeId, ancestorDeleteNodeId);
+        }
+      });

Review Comment:
   This from-snapshot check applies the same rule to all non-DELETE entries. There could be two issues.
   
   First, a CREATE entry does not exist in the from-snapshot. For `DELETE B`, `RENAME A -> B`, and `CREATE B/C`, the extra `CREATE -> DELETE` edge causes a false cycle.
   
   Second, a MODIFY entry can depend on an ancestor RENAME. For `RENAME A -> B` and `MODIFY A/child`, the MODIFY must occur first.
   
   Pls exclude CREATE entries from this check. For the remaining source-side entries, add an edge to an ancestor RENAME. Pls also add tests for both sequences.
   
   ```diff
   @@ -483,7 +483,7 @@
        for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
          SnapDiffDependencyEntry entry = nodes.get(nodeId);
   -      if (entry.isDelete()) {
   +      if (entry.isDelete() || entry.getDiffType() == DiffType.CREATE) {
            continue;
          }
          final int fromNodeId = nodeId;
   @@ -492,6 +492,11 @@
            if (ancestorDeleteNodeId != null) {
              addEdge(fromNodeId, ancestorDeleteNodeId);
            }
   +        Integer ancestorRenameNodeId =
   +            renameNodesBySourcePath.get(ancestorPath);
   +        if (ancestorRenameNodeId != null) {
   +          addEdge(fromNodeId, ancestorRenameNodeId);
   +        }
          });
   ```
   
   Below can be the test additions:
   
   ```diff
   diff --git a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/snapshot/TestSnapDiffDependencyGraph.java b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/snapshot/TestSnapDiffDependencyGraph.java
   index 4a183cd7846..446bf9f6acd 100644
   --- a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/snapshot/TestSnapDiffDependencyGraph.java
   +++ b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/snapshot/TestSnapDiffDependencyGraph.java
   @@ -177,6 +177,29 @@ void testRenameAfterTargetParentCreatedAndBeforeSourceParentDeleted() {
            indexOf(ordered, DELETE, "A"));
      }
    
   +  @Test
   +  void testCreateUnderReplacementRenameDoesNotCycle() {
   +    // DELETE B must precede RENAME A -> B. The rename must precede CREATE B/C.
   +    List<SnapDiffDependencyEntry> entries = Arrays.asList(
   +        entry(1L, 0L, DELETE, "B"),
   +        entry(2L, 0L, RENAME, "A", "B"),
   +        entry(3L, 2L, CREATE, "B/C"));
   +
   +    List<DiffType> orderedTypes = toDiffTypes(sort(entries));
   +    assertEquals(Arrays.asList(DELETE, RENAME, CREATE), orderedTypes);
   +  }
   +
   +  @Test
   +  void testDescendantModifyBeforeAncestorRenameOnPathPrefix() {
   +    // MODIFY A/child must precede RENAME A -> B.
   +    List<SnapDiffDependencyEntry> entries = Arrays.asList(
   +        entry(1L, 0L, RENAME, "A", "B"),
   +        entry(2L, 1L, MODIFY, "A/child"));
   +
   +    List<DiffType> orderedTypes = toDiffTypes(sort(entries));
   +    assertEquals(Arrays.asList(MODIFY, RENAME), orderedTypes);
   +  }
   +
      @Test
      void testRenameChainFreesPathBeforeReuse() {
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3742263888


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,656 @@
+/*
+ * 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.snapshot;
+
+import static org.apache.hadoop.ozone.OzoneConsts.OM_KEY_PREFIX;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant RENAME or MODIFY before ancestor DELETE or RENAME(source)
+ *       on a strict source-path prefix. CREATE is omitted because its source
+ *       path is a to-snapshot path, not a from-snapshot path.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  private static final int MAX_CYCLE_ENTRIES_IN_MESSAGE = 16;
+  // Defensive JVM-side ceiling on the growable long[] edge buffer used during
+  // construction (see grownCapacity). Hotspot/OpenJDK cap the largest array a
+  // little below Integer.MAX_VALUE; going any higher throws OutOfMemoryError
+  // with an unhelpful message.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final String PATH_SEPARATOR = OM_KEY_PREFIX;
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges;
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Only objectIds that have a RENAME entry are tracked;
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    Objects.requireNonNull(entries, "entries");
+    nodes.addAll(entries);
+    // Size the initial edge buffer to roughly the node count so realistic
+    // graphs (edge density 3-8 per node) skip most of the doubling copies.
+    // Clamp to INITIAL_EDGE_CAPACITY so tiny inputs still allocate cheaply.
+    edges = new long[Math.max(INITIAL_EDGE_CAPACITY, nodes.size())];
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];
+    int deleteHead = 0;
+    int deleteTail = 0;
+    int otherHead = 0;
+    int otherTail = 0;
+    for (int nodeId = 0; nodeId < nodeCount; nodeId++) {
+      if (remainingInDegree[nodeId] == 0) {
+        if (nodes.get(nodeId).isDelete()) {
+          deleteReady[deleteTail++] = nodeId;
+        } else {
+          otherReady[otherTail++] = nodeId;
+        }
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodeCount);
+    while (deleteHead < deleteTail || otherHead < otherTail) {
+      int nodeId = deleteHead < deleteTail
+          ? deleteReady[deleteHead++] : otherReady[otherHead++];
+      orderedEntries.add(nodes.get(nodeId));
+      for (int i = adjOffsets[nodeId]; i < adjOffsets[nodeId + 1]; i++) {
+        int dependentNodeId = adjTargets[i];
+        if (--remainingInDegree[dependentNodeId] == 0) {
+          if (nodes.get(dependentNodeId).isDelete()) {
+            deleteReady[deleteTail++] = dependentNodeId;
+          } else {
+            otherReady[otherTail++] = dependentNodeId;
+          }
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodeCount) {
+      List<String> unresolved = collectUnresolvedNodes(orderedEntries);
+      LOG.debug("Cycle detected in snapshot diff dependency graph. "
+          + "Unresolved entries: {}", unresolved);
+      int total = unresolved.size();
+      List<String> sample = total > MAX_CYCLE_ENTRIES_IN_MESSAGE
+          ? unresolved.subList(0, MAX_CYCLE_ENTRIES_IN_MESSAGE) : unresolved;
+      throw new IllegalStateException(String.format(
+          "Cycle detected in snapshot diff dependency graph; %d unresolved "
+              + "entries (showing up to %d): %s",
+          total, MAX_CYCLE_ENTRIES_IN_MESSAGE, sample));
+    }
+    return orderedEntries;
+  }
+
+  private List<String> collectUnresolvedNodes(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    Set<SnapDiffDependencyEntry> resolved =
+        Collections.newSetFromMap(new IdentityHashMap<>());
+    resolved.addAll(orderedEntries);
+    List<String> unresolved = new ArrayList<>();
+    for (SnapDiffDependencyEntry entry : nodes) {
+      if (!resolved.contains(entry)) {
+        unresolved.add(entry.getDiffType() + " " + entry.getSourcePath());
+      }
+    }
+    return unresolved;
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (edgeCount == edges.length) {
+      edges = Arrays.copyOf(edges, grownCapacity(edges.length));
+    }
+    edges[edgeCount++] =
+        ((long) fromNodeId << Integer.SIZE) | (toNodeId & 0xFFFFFFFFL);
+  }
+
+  private static int grownCapacity(int currentCapacity) {
+    // Grow by 1.5x to bound the transient overshoot of the edge buffer, and
+    // clamp to MAX_ARRAY_SIZE so the growth cannot overflow into a negative
+    // (or unallocatable) size.
+    int grown = currentCapacity + (currentCapacity >> 1);
+    if (grown < 0 || grown > MAX_ARRAY_SIZE) {
+      if (currentCapacity >= MAX_ARRAY_SIZE) {
+        throw new IllegalStateException(
+            "Snapshot diff dependency graph exceeds maximum edge capacity");
+      }
+      return MAX_ARRAY_SIZE;
+    }
+    return grown;
+  }
+
+  /**
+   * Deduplicates the collected edges and packs them into the CSR arrays.
+   * Encoding each edge as {@code (from << 32 | to)} lets a single sort group
+   * neighbors by source node and place duplicates next to each other, so the
+   * repeated {@code HashSet} allocations of the previous representation are no
+   * longer needed. The temporary edge buffer is released afterwards.
+   */
+  private void buildCsr() {
+    int nodeCount = nodes.size();
+    adjOffsets = new int[nodeCount + 1];
+    inDegree = new int[nodeCount];
+    if (edgeCount == 0) {
+      adjTargets = EMPTY_INT_ARRAY;
+      edges = null;
+      return;
+    }
+
+    Arrays.sort(edges, 0, edgeCount);
+
+    // First pass over the sorted edges: skip duplicates while counting the
+    // out-edges per source node and the in-degree per target node.
+    long previous = edges[0];
+    int uniqueCount = 1;
+    adjOffsets[(int) (previous >>> Integer.SIZE) + 1]++;
+    inDegree[(int) previous]++;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      uniqueCount++;
+      adjOffsets[(int) (edge >>> Integer.SIZE) + 1]++;
+      inDegree[(int) edge]++;
+    }
+
+    // Prefix sum turns per-node out-edge counts into CSR start offsets.
+    for (int i = 0; i < nodeCount; i++) {
+      adjOffsets[i + 1] += adjOffsets[i];
+    }
+
+    // Second pass: the unique edges are already ordered by source then target,
+    // so appending their targets sequentially matches the CSR offsets.
+    adjTargets = new int[uniqueCount];
+    previous = edges[0];
+    int index = 0;
+    adjTargets[index++] = (int) previous;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      adjTargets[index++] = (int) edge;
+    }
+    edges = null;
+  }
+
+  private void buildDependencyEdges() {
+    // At most one object occupies a given path on a given snapshot side, so a
+    // single node id per path is sufficient. Count each category first
+    // so the four indexes can be pre-sized exactly.
+    int createCount = 0;
+    int deleteCount = 0;
+    int renameCount = 0;
+    for (int i = 0; i < nodes.size(); i++) {
+      DiffType diffType = nodes.get(i).getDiffType();
+      if (diffType == DiffType.DELETE) {
+        deleteCount++;
+      } else if (diffType == DiffType.CREATE) {
+        createCount++;
+      } else if (diffType == DiffType.RENAME) {
+        renameCount++;
+      }
+    }
+    Map<String, Integer> createNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(createCount));
+    Map<String, Integer> deleteNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(deleteCount));
+    Map<String, Integer> renameNodesBySourcePath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    Map<String, Integer> renameNodesByTargetPath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    addPathConflictEdges(deleteNodesByPath, createNodesByPath,
+        renameNodesByTargetPath);
+    addRenameBeforeCreateEdges(renameNodesBySourcePath, createNodesByPath);
+    addRenameChainEdges(renameNodesBySourcePath, renameNodesByTargetPath);
+    addPathPrefixFromSnapshotEdges(deleteNodesByPath, renameNodesBySourcePath);
+    addPathPrefixToSnapshotEdges(createNodesByPath, renameNodesByTargetPath);
+
+    buildObjectIdGroups(renameCount);
+    addIntraObjectRenameEdges();
+
+    groupObjectIds = null;
+    groupOffsets = null;
+    groupNodes = null;
+
+    // Path strings were cached on each entry so that repeated edge-building
+    // passes did not re-decode. The graph no longer reads them once edges
+    // are built; drop the caches to reclaim per-entry heap.
+    for (int i = 0; i < nodes.size(); i++) {
+      nodes.get(i).clearPathCache();
+    }
+  }
+
+  /**
+   * Groups node ids by objectId, restricted to objectIds that have a RENAME
+   * entry (only those can pick up intra-object edges). The slice of
+   * {@link #groupNodes} between {@link #groupOffsets}{@code [rank]} and
+   * {@code [rank + 1]} lists the node ids for {@link #groupObjectIds}
+   * {@code [rank]}.
+   *
+   * <p>Uses a single hash-map lookup per node and no per-node binary search,
+   * so peak transient memory here is bounded by the number of nodes that
+   * belong to a renamed object rather than the full node count.
+   */
+  private void buildObjectIdGroups(int renameCount) {
+    if (renameCount == 0) {
+      groupObjectIds = new long[0];
+      groupOffsets = new int[1];
+      groupNodes = EMPTY_INT_ARRAY;
+      return;
+    }
+    int nodeCount = nodes.size();
+    // Rank the RENAMEd objectIds. Presize to the exact rename count; there is
+    // at most one RENAME per objectId (a second RENAME on the same id is
+    // rejected by addToPathIndex).
+    Map<Long, Integer> rankByObjectId =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    long[] renameObjectIds = new long[renameCount];
+    int uniqueCount = 0;
+    for (int i = 0; i < nodeCount && uniqueCount < renameCount; i++) {
+      SnapDiffDependencyEntry entry = nodes.get(i);
+      if (entry.getDiffType() == DiffType.RENAME) {
+        renameObjectIds[uniqueCount] = entry.getObjectId();
+        rankByObjectId.put(entry.getObjectId(), uniqueCount);
+        uniqueCount++;
+      }
+    }
+    groupObjectIds = renameObjectIds;
+
+    // Count how many nodes belong to each renamed object.
+    groupOffsets = new int[uniqueCount + 1];
+    int groupedNodeCount = 0;
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupOffsets[rank + 1]++;
+        groupedNodeCount++;
+      }
+    }
+    for (int i = 0; i < uniqueCount; i++) {
+      groupOffsets[i + 1] += groupOffsets[i];
+    }
+
+    // Fill groupNodes. Sized to groupedNodeCount, not the full node count.
+    groupNodes = new int[groupedNodeCount];
+    int[] fillCursor = Arrays.copyOf(groupOffsets, uniqueCount);
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupNodes[fillCursor[rank]++] = i;
+      }
+    }
+  }
+
+  /**
+   * Orders the non-delete entries of a single object relative to its RENAME.
+   * An entry reported at the RENAME source (from-snapshot) path must be applied
+   * before the path is renamed away; an entry reported at the RENAME target
+   * (to-snapshot) path must be applied after the rename creates that path.
+   */
+  private void addIntraObjectRenameEdges() {
+    for (int rank = 0; rank < groupObjectIds.length; rank++) {
+      int start = groupOffsets[rank];
+      int end = groupOffsets[rank + 1];
+      if (end - start < 2) {
+        continue;
+      }
+      int renameNodeId = -1;
+      for (int i = start; i < end; i++) {
+        if (nodes.get(groupNodes[i]).getDiffType() == DiffType.RENAME) {
+          renameNodeId = groupNodes[i];
+          break;
+        }
+      }
+      if (renameNodeId < 0) {
+        continue;
+      }
+      SnapDiffDependencyEntry rename = nodes.get(renameNodeId);
+      for (int i = start; i < end; i++) {
+        int nodeId = groupNodes[i];
+        if (nodeId == renameNodeId) {
+          continue;
+        }
+        String path = nodes.get(nodeId).getSourcePath();
+        if (path == null) {
+          continue;
+        }
+        if (path.equals(rename.getSourcePath())) {
+          addEdge(nodeId, renameNodeId);
+        } else if (path.equals(rename.getTargetPath())) {
+          addEdge(renameNodeId, nodeId);
+        }
+      }
+    }
+  }
+
+  /**
+   * Converts an expected element count to the initial capacity that keeps a
+   * default-load-factor (0.75) HashMap from resizing while it fills to that
+   * count. Mirrors what JDK 19's {@code HashMap.newHashMap(int)} does, but
+   * stays on Java 8 source.
+   */
+  private static int expectedHashMapCapacity(int expectedSize) {
+    if (expectedSize <= 0) {
+      return 1;
+    }
+    // ceil(expectedSize / 0.75) with an overflow guard for large sizes.
+    long capacity = (long) expectedSize + (expectedSize + 2) / 3;
+    return capacity > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) capacity;
+  }
+
+  private static void addToPathIndex(Map<String, Integer> pathIndex,
+      String path, int nodeId) {
+    if (path == null) {
+      return;
+    }
+    // At most one object can occupy a path on a given snapshot side, so the
+    // first node wins. A second node on the same path indicates malformed diff
+    // input (per SnapshotDiffManager, an object appears at most once in each of
+    // the CREATE/DELETE/RENAME(source)/RENAME(target) indices).
+    Integer existing = pathIndex.putIfAbsent(path, nodeId);
+    if (existing != null) {
+      LOG.warn("Multiple diff entries share path '{}'; keeping node {}, "
+          + "ignoring node {}", path, existing, nodeId);
+    }
+  }
+
+  /**
+   * Orders renames that reuse the same path: the rename whose source frees a
+   * path must precede the rename whose target occupies that same path.
+   */
+  private void addRenameChainEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> sourceEntry :
+        renameNodesBySourcePath.entrySet()) {
+      Integer targetNodeId =
+          renameNodesByTargetPath.get(sourceEntry.getKey());
+      if (targetNodeId != null) {
+        addEdge(sourceEntry.getValue(), targetNodeId);
+      }
+    }
+  }
+
+  private void addPathConflictEdges(Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      String path = deleteEntry.getKey();
+      int deleteNodeId = deleteEntry.getValue();
+      Integer createNodeId = createNodesByPath.get(path);
+      if (createNodeId != null) {
+        addEdge(deleteNodeId, createNodeId);
+      }
+      Integer renameTargetNodeId = renameNodesByTargetPath.get(path);
+      if (renameTargetNodeId != null) {
+        addEdge(deleteNodeId, renameTargetNodeId);
+      }
+    }
+  }
+
+  private void addRenameBeforeCreateEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> createNodesByPath) {
+    for (Map.Entry<String, Integer> createEntry :
+        createNodesByPath.entrySet()) {
+      Integer renameNodeId =
+          renameNodesBySourcePath.get(createEntry.getKey());
+      if (renameNodeId != null) {
+        addEdge(renameNodeId, createEntry.getValue());
+      }
+    }
+  }
+
+  /**
+   * From-snapshot path-prefix edges. Intermediate directories may be omitted
+   * from the report; ancestor ordering is derived from strict path prefixes.
+   *
+   * <p>DELETE, RENAME, and MODIFY entries all carry a from-snapshot source
+   * path (RENAME uses the pre-rename source, and MODIFY is reported at the
+   * old key path per SnapshotDiffManager). CREATE is excluded because a
+   * CREATE's source path is a to-snapshot path; to-snapshot prefixes are
+   * handled by {@link #addPathPrefixToSnapshotEdges}. Mixing the two would
+   * generate spurious edges (e.g. after DELETE A + CREATE A, a CREATE A/child
+   * would incorrectly point at DELETE A and produce a cycle).
+   */
+  private void addPathPrefixFromSnapshotEdges(
+      Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> renameNodesBySourcePath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      int descendantDeleteNodeId = deleteEntry.getValue();
+      forEachStrictPrefix(deleteEntry.getKey(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      DiffType diffType = entry.getDiffType();
+      if (diffType != DiffType.RENAME && diffType != DiffType.MODIFY) {
+        continue;
+      }
+      final int fromNodeId = nodeId;
+      forEachStrictPrefix(entry.getSourcePath(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(fromNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(fromNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+  }
+
+  /**
+   * To-snapshot path-prefix edges. A descendant CREATE/RENAME/MODIFY cannot be
+   * applied until ancestor directories exist on the to-snapshot side.
+   */
+  private void addPathPrefixToSnapshotEdges(
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        continue;
+      }
+      String toSnapshotPath = getToSnapshotPath(entry);
+      if (toSnapshotPath == null) {
+        continue;
+      }
+      final int toNodeId = nodeId;
+      forEachStrictPrefix(toSnapshotPath, ancestorPath -> {
+        Integer ancestorCreateNodeId = createNodesByPath.get(ancestorPath);
+        if (ancestorCreateNodeId != null) {
+          addEdge(ancestorCreateNodeId, toNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesByTargetPath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(ancestorRenameNodeId, toNodeId);
+        }
+      });
+    }
+  }
+
+  private static String getToSnapshotPath(SnapDiffDependencyEntry entry) {
+    if (entry.getDiffType() == DiffType.RENAME) {
+      return entry.getTargetPath();
+    }
+    return entry.getSourcePath();

Review Comment:
   A directory `MODIFY` can use the to-snapshot path, so excluding all `MODIFY` entries from this pass is not sufficient. The entry must identify which snapshot contains its path. Pls add tests for a source-side modified key and a target-side modified directory.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3779889122


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,569 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant non-delete before ancestor DELETE on a strict source-path
+ *       prefix.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  // Hotspot/OpenJDK cap the largest array a little below Integer.MAX_VALUE.
+  // Node and edge counts are assumed to fit in int; the configured changed-key
+  // limit (one billion) is well below this bound.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final char PATH_SEPARATOR = '/';
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges = new long[INITIAL_EDGE_CAPACITY];
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Released once edges are built.
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    nodes.addAll(entries);
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];

Review Comment:
   I extended the skip toSnapshot path dependencies to re-occupied paths and added more tests to cover these scenarios.
   
   Currently there is no producer for this dependency graph. The plan is implement the merge join diff [HDDS-15391](https://issues.apache.org/jira/browse/HDDS-15391) separate from the baseline snapdiff and have it be the producer to the dependency graph. The Merge Join diff will always outptut MODIFY entries from the fromSnapshot namespace regardless of whether it is a file/key/directory.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3734558367


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,656 @@
+/*
+ * 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.snapshot;
+
+import static org.apache.hadoop.ozone.OzoneConsts.OM_KEY_PREFIX;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant RENAME or MODIFY before ancestor DELETE or RENAME(source)
+ *       on a strict source-path prefix. CREATE is omitted because its source
+ *       path is a to-snapshot path, not a from-snapshot path.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  private static final int MAX_CYCLE_ENTRIES_IN_MESSAGE = 16;
+  // Defensive JVM-side ceiling on the growable long[] edge buffer used during
+  // construction (see grownCapacity). Hotspot/OpenJDK cap the largest array a
+  // little below Integer.MAX_VALUE; going any higher throws OutOfMemoryError
+  // with an unhelpful message.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final String PATH_SEPARATOR = OM_KEY_PREFIX;
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges;
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Only objectIds that have a RENAME entry are tracked;
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */

Review Comment:
   This constructor does not detect cycles; cycle detection occurs only when `getOrderedEntries()` runs. Remove the cycle claim here so callers do not assume construction validates the graph.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,656 @@
+/*
+ * 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.snapshot;
+
+import static org.apache.hadoop.ozone.OzoneConsts.OM_KEY_PREFIX;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant RENAME or MODIFY before ancestor DELETE or RENAME(source)
+ *       on a strict source-path prefix. CREATE is omitted because its source
+ *       path is a to-snapshot path, not a from-snapshot path.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  private static final int MAX_CYCLE_ENTRIES_IN_MESSAGE = 16;
+  // Defensive JVM-side ceiling on the growable long[] edge buffer used during
+  // construction (see grownCapacity). Hotspot/OpenJDK cap the largest array a
+  // little below Integer.MAX_VALUE; going any higher throws OutOfMemoryError
+  // with an unhelpful message.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final String PATH_SEPARATOR = OM_KEY_PREFIX;
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges;
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Only objectIds that have a RENAME entry are tracked;
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    Objects.requireNonNull(entries, "entries");
+    nodes.addAll(entries);
+    // Size the initial edge buffer to roughly the node count so realistic
+    // graphs (edge density 3-8 per node) skip most of the doubling copies.
+    // Clamp to INITIAL_EDGE_CAPACITY so tiny inputs still allocate cheaply.
+    edges = new long[Math.max(INITIAL_EDGE_CAPACITY, nodes.size())];
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];
+    int deleteHead = 0;
+    int deleteTail = 0;
+    int otherHead = 0;
+    int otherTail = 0;
+    for (int nodeId = 0; nodeId < nodeCount; nodeId++) {
+      if (remainingInDegree[nodeId] == 0) {
+        if (nodes.get(nodeId).isDelete()) {
+          deleteReady[deleteTail++] = nodeId;
+        } else {
+          otherReady[otherTail++] = nodeId;
+        }
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodeCount);
+    while (deleteHead < deleteTail || otherHead < otherTail) {
+      int nodeId = deleteHead < deleteTail
+          ? deleteReady[deleteHead++] : otherReady[otherHead++];
+      orderedEntries.add(nodes.get(nodeId));
+      for (int i = adjOffsets[nodeId]; i < adjOffsets[nodeId + 1]; i++) {
+        int dependentNodeId = adjTargets[i];
+        if (--remainingInDegree[dependentNodeId] == 0) {
+          if (nodes.get(dependentNodeId).isDelete()) {
+            deleteReady[deleteTail++] = dependentNodeId;
+          } else {
+            otherReady[otherTail++] = dependentNodeId;
+          }
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodeCount) {
+      List<String> unresolved = collectUnresolvedNodes(orderedEntries);
+      LOG.debug("Cycle detected in snapshot diff dependency graph. "
+          + "Unresolved entries: {}", unresolved);
+      int total = unresolved.size();
+      List<String> sample = total > MAX_CYCLE_ENTRIES_IN_MESSAGE
+          ? unresolved.subList(0, MAX_CYCLE_ENTRIES_IN_MESSAGE) : unresolved;
+      throw new IllegalStateException(String.format(
+          "Cycle detected in snapshot diff dependency graph; %d unresolved "
+              + "entries (showing up to %d): %s",
+          total, MAX_CYCLE_ENTRIES_IN_MESSAGE, sample));
+    }
+    return orderedEntries;
+  }
+
+  private List<String> collectUnresolvedNodes(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    Set<SnapDiffDependencyEntry> resolved =
+        Collections.newSetFromMap(new IdentityHashMap<>());
+    resolved.addAll(orderedEntries);
+    List<String> unresolved = new ArrayList<>();
+    for (SnapDiffDependencyEntry entry : nodes) {
+      if (!resolved.contains(entry)) {
+        unresolved.add(entry.getDiffType() + " " + entry.getSourcePath());
+      }
+    }
+    return unresolved;
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (edgeCount == edges.length) {
+      edges = Arrays.copyOf(edges, grownCapacity(edges.length));
+    }
+    edges[edgeCount++] =
+        ((long) fromNodeId << Integer.SIZE) | (toNodeId & 0xFFFFFFFFL);
+  }
+
+  private static int grownCapacity(int currentCapacity) {
+    // Grow by 1.5x to bound the transient overshoot of the edge buffer, and
+    // clamp to MAX_ARRAY_SIZE so the growth cannot overflow into a negative
+    // (or unallocatable) size.
+    int grown = currentCapacity + (currentCapacity >> 1);
+    if (grown < 0 || grown > MAX_ARRAY_SIZE) {
+      if (currentCapacity >= MAX_ARRAY_SIZE) {
+        throw new IllegalStateException(
+            "Snapshot diff dependency graph exceeds maximum edge capacity");
+      }
+      return MAX_ARRAY_SIZE;
+    }
+    return grown;
+  }
+
+  /**
+   * Deduplicates the collected edges and packs them into the CSR arrays.
+   * Encoding each edge as {@code (from << 32 | to)} lets a single sort group
+   * neighbors by source node and place duplicates next to each other, so the
+   * repeated {@code HashSet} allocations of the previous representation are no
+   * longer needed. The temporary edge buffer is released afterwards.
+   */
+  private void buildCsr() {
+    int nodeCount = nodes.size();
+    adjOffsets = new int[nodeCount + 1];
+    inDegree = new int[nodeCount];
+    if (edgeCount == 0) {
+      adjTargets = EMPTY_INT_ARRAY;
+      edges = null;
+      return;
+    }
+
+    Arrays.sort(edges, 0, edgeCount);
+
+    // First pass over the sorted edges: skip duplicates while counting the
+    // out-edges per source node and the in-degree per target node.
+    long previous = edges[0];
+    int uniqueCount = 1;
+    adjOffsets[(int) (previous >>> Integer.SIZE) + 1]++;
+    inDegree[(int) previous]++;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      uniqueCount++;
+      adjOffsets[(int) (edge >>> Integer.SIZE) + 1]++;
+      inDegree[(int) edge]++;
+    }
+
+    // Prefix sum turns per-node out-edge counts into CSR start offsets.
+    for (int i = 0; i < nodeCount; i++) {
+      adjOffsets[i + 1] += adjOffsets[i];
+    }
+
+    // Second pass: the unique edges are already ordered by source then target,
+    // so appending their targets sequentially matches the CSR offsets.
+    adjTargets = new int[uniqueCount];
+    previous = edges[0];
+    int index = 0;
+    adjTargets[index++] = (int) previous;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      adjTargets[index++] = (int) edge;
+    }
+    edges = null;
+  }
+
+  private void buildDependencyEdges() {
+    // At most one object occupies a given path on a given snapshot side, so a
+    // single node id per path is sufficient. Count each category first
+    // so the four indexes can be pre-sized exactly.
+    int createCount = 0;
+    int deleteCount = 0;
+    int renameCount = 0;
+    for (int i = 0; i < nodes.size(); i++) {
+      DiffType diffType = nodes.get(i).getDiffType();
+      if (diffType == DiffType.DELETE) {
+        deleteCount++;
+      } else if (diffType == DiffType.CREATE) {
+        createCount++;
+      } else if (diffType == DiffType.RENAME) {
+        renameCount++;
+      }
+    }
+    Map<String, Integer> createNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(createCount));
+    Map<String, Integer> deleteNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(deleteCount));
+    Map<String, Integer> renameNodesBySourcePath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    Map<String, Integer> renameNodesByTargetPath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    addPathConflictEdges(deleteNodesByPath, createNodesByPath,
+        renameNodesByTargetPath);
+    addRenameBeforeCreateEdges(renameNodesBySourcePath, createNodesByPath);
+    addRenameChainEdges(renameNodesBySourcePath, renameNodesByTargetPath);
+    addPathPrefixFromSnapshotEdges(deleteNodesByPath, renameNodesBySourcePath);
+    addPathPrefixToSnapshotEdges(createNodesByPath, renameNodesByTargetPath);
+
+    buildObjectIdGroups(renameCount);
+    addIntraObjectRenameEdges();
+
+    groupObjectIds = null;
+    groupOffsets = null;
+    groupNodes = null;
+
+    // Path strings were cached on each entry so that repeated edge-building
+    // passes did not re-decode. The graph no longer reads them once edges
+    // are built; drop the caches to reclaim per-entry heap.
+    for (int i = 0; i < nodes.size(); i++) {
+      nodes.get(i).clearPathCache();
+    }
+  }
+
+  /**
+   * Groups node ids by objectId, restricted to objectIds that have a RENAME
+   * entry (only those can pick up intra-object edges). The slice of
+   * {@link #groupNodes} between {@link #groupOffsets}{@code [rank]} and
+   * {@code [rank + 1]} lists the node ids for {@link #groupObjectIds}
+   * {@code [rank]}.
+   *
+   * <p>Uses a single hash-map lookup per node and no per-node binary search,
+   * so peak transient memory here is bounded by the number of nodes that
+   * belong to a renamed object rather than the full node count.
+   */
+  private void buildObjectIdGroups(int renameCount) {
+    if (renameCount == 0) {
+      groupObjectIds = new long[0];
+      groupOffsets = new int[1];
+      groupNodes = EMPTY_INT_ARRAY;
+      return;
+    }
+    int nodeCount = nodes.size();
+    // Rank the RENAMEd objectIds. Presize to the exact rename count; there is
+    // at most one RENAME per objectId (a second RENAME on the same id is
+    // rejected by addToPathIndex).
+    Map<Long, Integer> rankByObjectId =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    long[] renameObjectIds = new long[renameCount];
+    int uniqueCount = 0;
+    for (int i = 0; i < nodeCount && uniqueCount < renameCount; i++) {
+      SnapDiffDependencyEntry entry = nodes.get(i);
+      if (entry.getDiffType() == DiffType.RENAME) {
+        renameObjectIds[uniqueCount] = entry.getObjectId();
+        rankByObjectId.put(entry.getObjectId(), uniqueCount);
+        uniqueCount++;
+      }
+    }
+    groupObjectIds = renameObjectIds;
+
+    // Count how many nodes belong to each renamed object.
+    groupOffsets = new int[uniqueCount + 1];
+    int groupedNodeCount = 0;
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupOffsets[rank + 1]++;
+        groupedNodeCount++;
+      }
+    }
+    for (int i = 0; i < uniqueCount; i++) {
+      groupOffsets[i + 1] += groupOffsets[i];
+    }
+
+    // Fill groupNodes. Sized to groupedNodeCount, not the full node count.
+    groupNodes = new int[groupedNodeCount];
+    int[] fillCursor = Arrays.copyOf(groupOffsets, uniqueCount);
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupNodes[fillCursor[rank]++] = i;
+      }
+    }
+  }
+
+  /**
+   * Orders the non-delete entries of a single object relative to its RENAME.
+   * An entry reported at the RENAME source (from-snapshot) path must be applied
+   * before the path is renamed away; an entry reported at the RENAME target
+   * (to-snapshot) path must be applied after the rename creates that path.
+   */
+  private void addIntraObjectRenameEdges() {
+    for (int rank = 0; rank < groupObjectIds.length; rank++) {
+      int start = groupOffsets[rank];
+      int end = groupOffsets[rank + 1];
+      if (end - start < 2) {
+        continue;
+      }
+      int renameNodeId = -1;
+      for (int i = start; i < end; i++) {
+        if (nodes.get(groupNodes[i]).getDiffType() == DiffType.RENAME) {
+          renameNodeId = groupNodes[i];
+          break;
+        }
+      }
+      if (renameNodeId < 0) {
+        continue;
+      }
+      SnapDiffDependencyEntry rename = nodes.get(renameNodeId);
+      for (int i = start; i < end; i++) {
+        int nodeId = groupNodes[i];
+        if (nodeId == renameNodeId) {
+          continue;
+        }
+        String path = nodes.get(nodeId).getSourcePath();
+        if (path == null) {
+          continue;
+        }
+        if (path.equals(rename.getSourcePath())) {
+          addEdge(nodeId, renameNodeId);
+        } else if (path.equals(rename.getTargetPath())) {
+          addEdge(renameNodeId, nodeId);
+        }
+      }
+    }
+  }
+
+  /**
+   * Converts an expected element count to the initial capacity that keeps a
+   * default-load-factor (0.75) HashMap from resizing while it fills to that
+   * count. Mirrors what JDK 19's {@code HashMap.newHashMap(int)} does, but
+   * stays on Java 8 source.
+   */
+  private static int expectedHashMapCapacity(int expectedSize) {
+    if (expectedSize <= 0) {
+      return 1;
+    }
+    // ceil(expectedSize / 0.75) with an overflow guard for large sizes.
+    long capacity = (long) expectedSize + (expectedSize + 2) / 3;
+    return capacity > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) capacity;
+  }
+
+  private static void addToPathIndex(Map<String, Integer> pathIndex,
+      String path, int nodeId) {
+    if (path == null) {
+      return;
+    }
+    // At most one object can occupy a path on a given snapshot side, so the
+    // first node wins. A second node on the same path indicates malformed diff
+    // input (per SnapshotDiffManager, an object appears at most once in each of
+    // the CREATE/DELETE/RENAME(source)/RENAME(target) indices).
+    Integer existing = pathIndex.putIfAbsent(path, nodeId);
+    if (existing != null) {
+      LOG.warn("Multiple diff entries share path '{}'; keeping node {}, "
+          + "ignoring node {}", path, existing, nodeId);
+    }
+  }
+
+  /**
+   * Orders renames that reuse the same path: the rename whose source frees a
+   * path must precede the rename whose target occupies that same path.
+   */
+  private void addRenameChainEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> sourceEntry :
+        renameNodesBySourcePath.entrySet()) {
+      Integer targetNodeId =
+          renameNodesByTargetPath.get(sourceEntry.getKey());
+      if (targetNodeId != null) {
+        addEdge(sourceEntry.getValue(), targetNodeId);
+      }
+    }
+  }
+
+  private void addPathConflictEdges(Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      String path = deleteEntry.getKey();
+      int deleteNodeId = deleteEntry.getValue();
+      Integer createNodeId = createNodesByPath.get(path);
+      if (createNodeId != null) {
+        addEdge(deleteNodeId, createNodeId);
+      }
+      Integer renameTargetNodeId = renameNodesByTargetPath.get(path);
+      if (renameTargetNodeId != null) {
+        addEdge(deleteNodeId, renameTargetNodeId);
+      }
+    }
+  }
+
+  private void addRenameBeforeCreateEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> createNodesByPath) {
+    for (Map.Entry<String, Integer> createEntry :
+        createNodesByPath.entrySet()) {
+      Integer renameNodeId =
+          renameNodesBySourcePath.get(createEntry.getKey());
+      if (renameNodeId != null) {
+        addEdge(renameNodeId, createEntry.getValue());
+      }
+    }
+  }
+
+  /**
+   * From-snapshot path-prefix edges. Intermediate directories may be omitted
+   * from the report; ancestor ordering is derived from strict path prefixes.
+   *
+   * <p>DELETE, RENAME, and MODIFY entries all carry a from-snapshot source
+   * path (RENAME uses the pre-rename source, and MODIFY is reported at the
+   * old key path per SnapshotDiffManager). CREATE is excluded because a
+   * CREATE's source path is a to-snapshot path; to-snapshot prefixes are
+   * handled by {@link #addPathPrefixToSnapshotEdges}. Mixing the two would
+   * generate spurious edges (e.g. after DELETE A + CREATE A, a CREATE A/child
+   * would incorrectly point at DELETE A and produce a cycle).
+   */
+  private void addPathPrefixFromSnapshotEdges(
+      Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> renameNodesBySourcePath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      int descendantDeleteNodeId = deleteEntry.getValue();
+      forEachStrictPrefix(deleteEntry.getKey(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      DiffType diffType = entry.getDiffType();
+      if (diffType != DiffType.RENAME && diffType != DiffType.MODIFY) {
+        continue;
+      }
+      final int fromNodeId = nodeId;
+      forEachStrictPrefix(entry.getSourcePath(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(fromNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(fromNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+  }
+
+  /**
+   * To-snapshot path-prefix edges. A descendant CREATE/RENAME/MODIFY cannot be
+   * applied until ancestor directories exist on the to-snapshot side.
+   */
+  private void addPathPrefixToSnapshotEdges(
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        continue;
+      }
+      String toSnapshotPath = getToSnapshotPath(entry);
+      if (toSnapshotPath == null) {
+        continue;
+      }
+      final int toNodeId = nodeId;
+      forEachStrictPrefix(toSnapshotPath, ancestorPath -> {
+        Integer ancestorCreateNodeId = createNodesByPath.get(ancestorPath);
+        if (ancestorCreateNodeId != null) {
+          addEdge(ancestorCreateNodeId, toNodeId);

Review Comment:
   The PR specifies parent `CREATE`/`RENAME`/**`MODIFY`** before child non-delete entries, but this prefix lookup only considers CREATE ancestors (and the following lookup only RENAME targets). With `[CREATE A/child, MODIFY A]`, no edge is added and input order emits the child first. Either index MODIFY paths and add the promised ancestor edge, or narrow the documented dependency rule if MODIFY ordering is intentionally unnecessary.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,656 @@
+/*
+ * 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.snapshot;
+
+import static org.apache.hadoop.ozone.OzoneConsts.OM_KEY_PREFIX;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant RENAME or MODIFY before ancestor DELETE or RENAME(source)
+ *       on a strict source-path prefix. CREATE is omitted because its source
+ *       path is a to-snapshot path, not a from-snapshot path.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  private static final int MAX_CYCLE_ENTRIES_IN_MESSAGE = 16;
+  // Defensive JVM-side ceiling on the growable long[] edge buffer used during
+  // construction (see grownCapacity). Hotspot/OpenJDK cap the largest array a
+  // little below Integer.MAX_VALUE; going any higher throws OutOfMemoryError
+  // with an unhelpful message.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final String PATH_SEPARATOR = OM_KEY_PREFIX;
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges;
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Only objectIds that have a RENAME entry are tracked;
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    Objects.requireNonNull(entries, "entries");
+    nodes.addAll(entries);
+    // Size the initial edge buffer to roughly the node count so realistic
+    // graphs (edge density 3-8 per node) skip most of the doubling copies.
+    // Clamp to INITIAL_EDGE_CAPACITY so tiny inputs still allocate cheaply.
+    edges = new long[Math.max(INITIAL_EDGE_CAPACITY, nodes.size())];
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];
+    int deleteHead = 0;
+    int deleteTail = 0;
+    int otherHead = 0;
+    int otherTail = 0;
+    for (int nodeId = 0; nodeId < nodeCount; nodeId++) {
+      if (remainingInDegree[nodeId] == 0) {
+        if (nodes.get(nodeId).isDelete()) {
+          deleteReady[deleteTail++] = nodeId;
+        } else {
+          otherReady[otherTail++] = nodeId;
+        }
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodeCount);
+    while (deleteHead < deleteTail || otherHead < otherTail) {
+      int nodeId = deleteHead < deleteTail
+          ? deleteReady[deleteHead++] : otherReady[otherHead++];
+      orderedEntries.add(nodes.get(nodeId));
+      for (int i = adjOffsets[nodeId]; i < adjOffsets[nodeId + 1]; i++) {
+        int dependentNodeId = adjTargets[i];
+        if (--remainingInDegree[dependentNodeId] == 0) {
+          if (nodes.get(dependentNodeId).isDelete()) {
+            deleteReady[deleteTail++] = dependentNodeId;
+          } else {
+            otherReady[otherTail++] = dependentNodeId;
+          }
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodeCount) {
+      List<String> unresolved = collectUnresolvedNodes(orderedEntries);
+      LOG.debug("Cycle detected in snapshot diff dependency graph. "
+          + "Unresolved entries: {}", unresolved);
+      int total = unresolved.size();
+      List<String> sample = total > MAX_CYCLE_ENTRIES_IN_MESSAGE
+          ? unresolved.subList(0, MAX_CYCLE_ENTRIES_IN_MESSAGE) : unresolved;
+      throw new IllegalStateException(String.format(
+          "Cycle detected in snapshot diff dependency graph; %d unresolved "
+              + "entries (showing up to %d): %s",
+          total, MAX_CYCLE_ENTRIES_IN_MESSAGE, sample));
+    }
+    return orderedEntries;
+  }
+
+  private List<String> collectUnresolvedNodes(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    Set<SnapDiffDependencyEntry> resolved =
+        Collections.newSetFromMap(new IdentityHashMap<>());
+    resolved.addAll(orderedEntries);
+    List<String> unresolved = new ArrayList<>();
+    for (SnapDiffDependencyEntry entry : nodes) {
+      if (!resolved.contains(entry)) {
+        unresolved.add(entry.getDiffType() + " " + entry.getSourcePath());
+      }
+    }
+    return unresolved;
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (edgeCount == edges.length) {
+      edges = Arrays.copyOf(edges, grownCapacity(edges.length));
+    }
+    edges[edgeCount++] =
+        ((long) fromNodeId << Integer.SIZE) | (toNodeId & 0xFFFFFFFFL);
+  }
+
+  private static int grownCapacity(int currentCapacity) {
+    // Grow by 1.5x to bound the transient overshoot of the edge buffer, and
+    // clamp to MAX_ARRAY_SIZE so the growth cannot overflow into a negative
+    // (or unallocatable) size.
+    int grown = currentCapacity + (currentCapacity >> 1);
+    if (grown < 0 || grown > MAX_ARRAY_SIZE) {
+      if (currentCapacity >= MAX_ARRAY_SIZE) {
+        throw new IllegalStateException(
+            "Snapshot diff dependency graph exceeds maximum edge capacity");
+      }
+      return MAX_ARRAY_SIZE;
+    }
+    return grown;
+  }
+
+  /**
+   * Deduplicates the collected edges and packs them into the CSR arrays.
+   * Encoding each edge as {@code (from << 32 | to)} lets a single sort group
+   * neighbors by source node and place duplicates next to each other, so the
+   * repeated {@code HashSet} allocations of the previous representation are no
+   * longer needed. The temporary edge buffer is released afterwards.
+   */
+  private void buildCsr() {
+    int nodeCount = nodes.size();
+    adjOffsets = new int[nodeCount + 1];
+    inDegree = new int[nodeCount];
+    if (edgeCount == 0) {
+      adjTargets = EMPTY_INT_ARRAY;
+      edges = null;
+      return;
+    }
+
+    Arrays.sort(edges, 0, edgeCount);
+
+    // First pass over the sorted edges: skip duplicates while counting the
+    // out-edges per source node and the in-degree per target node.
+    long previous = edges[0];
+    int uniqueCount = 1;
+    adjOffsets[(int) (previous >>> Integer.SIZE) + 1]++;
+    inDegree[(int) previous]++;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      uniqueCount++;
+      adjOffsets[(int) (edge >>> Integer.SIZE) + 1]++;
+      inDegree[(int) edge]++;
+    }
+
+    // Prefix sum turns per-node out-edge counts into CSR start offsets.
+    for (int i = 0; i < nodeCount; i++) {
+      adjOffsets[i + 1] += adjOffsets[i];
+    }
+
+    // Second pass: the unique edges are already ordered by source then target,
+    // so appending their targets sequentially matches the CSR offsets.
+    adjTargets = new int[uniqueCount];
+    previous = edges[0];
+    int index = 0;
+    adjTargets[index++] = (int) previous;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      adjTargets[index++] = (int) edge;
+    }
+    edges = null;
+  }
+
+  private void buildDependencyEdges() {
+    // At most one object occupies a given path on a given snapshot side, so a
+    // single node id per path is sufficient. Count each category first
+    // so the four indexes can be pre-sized exactly.
+    int createCount = 0;
+    int deleteCount = 0;
+    int renameCount = 0;
+    for (int i = 0; i < nodes.size(); i++) {
+      DiffType diffType = nodes.get(i).getDiffType();
+      if (diffType == DiffType.DELETE) {
+        deleteCount++;
+      } else if (diffType == DiffType.CREATE) {
+        createCount++;
+      } else if (diffType == DiffType.RENAME) {
+        renameCount++;
+      }
+    }
+    Map<String, Integer> createNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(createCount));
+    Map<String, Integer> deleteNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(deleteCount));
+    Map<String, Integer> renameNodesBySourcePath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    Map<String, Integer> renameNodesByTargetPath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    addPathConflictEdges(deleteNodesByPath, createNodesByPath,
+        renameNodesByTargetPath);
+    addRenameBeforeCreateEdges(renameNodesBySourcePath, createNodesByPath);
+    addRenameChainEdges(renameNodesBySourcePath, renameNodesByTargetPath);
+    addPathPrefixFromSnapshotEdges(deleteNodesByPath, renameNodesBySourcePath);
+    addPathPrefixToSnapshotEdges(createNodesByPath, renameNodesByTargetPath);
+
+    buildObjectIdGroups(renameCount);
+    addIntraObjectRenameEdges();
+
+    groupObjectIds = null;
+    groupOffsets = null;
+    groupNodes = null;
+
+    // Path strings were cached on each entry so that repeated edge-building
+    // passes did not re-decode. The graph no longer reads them once edges
+    // are built; drop the caches to reclaim per-entry heap.
+    for (int i = 0; i < nodes.size(); i++) {
+      nodes.get(i).clearPathCache();
+    }
+  }
+
+  /**
+   * Groups node ids by objectId, restricted to objectIds that have a RENAME
+   * entry (only those can pick up intra-object edges). The slice of
+   * {@link #groupNodes} between {@link #groupOffsets}{@code [rank]} and
+   * {@code [rank + 1]} lists the node ids for {@link #groupObjectIds}
+   * {@code [rank]}.
+   *
+   * <p>Uses a single hash-map lookup per node and no per-node binary search,
+   * so peak transient memory here is bounded by the number of nodes that
+   * belong to a renamed object rather than the full node count.
+   */
+  private void buildObjectIdGroups(int renameCount) {
+    if (renameCount == 0) {
+      groupObjectIds = new long[0];
+      groupOffsets = new int[1];
+      groupNodes = EMPTY_INT_ARRAY;
+      return;
+    }
+    int nodeCount = nodes.size();
+    // Rank the RENAMEd objectIds. Presize to the exact rename count; there is
+    // at most one RENAME per objectId (a second RENAME on the same id is
+    // rejected by addToPathIndex).
+    Map<Long, Integer> rankByObjectId =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    long[] renameObjectIds = new long[renameCount];
+    int uniqueCount = 0;
+    for (int i = 0; i < nodeCount && uniqueCount < renameCount; i++) {
+      SnapDiffDependencyEntry entry = nodes.get(i);
+      if (entry.getDiffType() == DiffType.RENAME) {
+        renameObjectIds[uniqueCount] = entry.getObjectId();
+        rankByObjectId.put(entry.getObjectId(), uniqueCount);
+        uniqueCount++;
+      }
+    }
+    groupObjectIds = renameObjectIds;
+
+    // Count how many nodes belong to each renamed object.
+    groupOffsets = new int[uniqueCount + 1];
+    int groupedNodeCount = 0;
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupOffsets[rank + 1]++;
+        groupedNodeCount++;
+      }
+    }
+    for (int i = 0; i < uniqueCount; i++) {
+      groupOffsets[i + 1] += groupOffsets[i];
+    }
+
+    // Fill groupNodes. Sized to groupedNodeCount, not the full node count.
+    groupNodes = new int[groupedNodeCount];
+    int[] fillCursor = Arrays.copyOf(groupOffsets, uniqueCount);
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupNodes[fillCursor[rank]++] = i;
+      }
+    }
+  }
+
+  /**
+   * Orders the non-delete entries of a single object relative to its RENAME.
+   * An entry reported at the RENAME source (from-snapshot) path must be applied
+   * before the path is renamed away; an entry reported at the RENAME target
+   * (to-snapshot) path must be applied after the rename creates that path.
+   */
+  private void addIntraObjectRenameEdges() {
+    for (int rank = 0; rank < groupObjectIds.length; rank++) {
+      int start = groupOffsets[rank];
+      int end = groupOffsets[rank + 1];
+      if (end - start < 2) {
+        continue;
+      }
+      int renameNodeId = -1;
+      for (int i = start; i < end; i++) {
+        if (nodes.get(groupNodes[i]).getDiffType() == DiffType.RENAME) {
+          renameNodeId = groupNodes[i];
+          break;
+        }
+      }
+      if (renameNodeId < 0) {
+        continue;
+      }
+      SnapDiffDependencyEntry rename = nodes.get(renameNodeId);
+      for (int i = start; i < end; i++) {
+        int nodeId = groupNodes[i];
+        if (nodeId == renameNodeId) {
+          continue;
+        }
+        String path = nodes.get(nodeId).getSourcePath();
+        if (path == null) {
+          continue;
+        }
+        if (path.equals(rename.getSourcePath())) {
+          addEdge(nodeId, renameNodeId);
+        } else if (path.equals(rename.getTargetPath())) {
+          addEdge(renameNodeId, nodeId);
+        }
+      }
+    }
+  }
+
+  /**
+   * Converts an expected element count to the initial capacity that keeps a
+   * default-load-factor (0.75) HashMap from resizing while it fills to that
+   * count. Mirrors what JDK 19's {@code HashMap.newHashMap(int)} does, but
+   * stays on Java 8 source.
+   */
+  private static int expectedHashMapCapacity(int expectedSize) {
+    if (expectedSize <= 0) {
+      return 1;
+    }
+    // ceil(expectedSize / 0.75) with an overflow guard for large sizes.
+    long capacity = (long) expectedSize + (expectedSize + 2) / 3;
+    return capacity > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) capacity;
+  }
+
+  private static void addToPathIndex(Map<String, Integer> pathIndex,
+      String path, int nodeId) {
+    if (path == null) {
+      return;
+    }
+    // At most one object can occupy a path on a given snapshot side, so the
+    // first node wins. A second node on the same path indicates malformed diff
+    // input (per SnapshotDiffManager, an object appears at most once in each of
+    // the CREATE/DELETE/RENAME(source)/RENAME(target) indices).
+    Integer existing = pathIndex.putIfAbsent(path, nodeId);
+    if (existing != null) {
+      LOG.warn("Multiple diff entries share path '{}'; keeping node {}, "
+          + "ignoring node {}", path, existing, nodeId);
+    }
+  }
+
+  /**
+   * Orders renames that reuse the same path: the rename whose source frees a
+   * path must precede the rename whose target occupies that same path.
+   */
+  private void addRenameChainEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> sourceEntry :
+        renameNodesBySourcePath.entrySet()) {
+      Integer targetNodeId =
+          renameNodesByTargetPath.get(sourceEntry.getKey());
+      if (targetNodeId != null) {
+        addEdge(sourceEntry.getValue(), targetNodeId);
+      }
+    }
+  }
+
+  private void addPathConflictEdges(Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      String path = deleteEntry.getKey();
+      int deleteNodeId = deleteEntry.getValue();
+      Integer createNodeId = createNodesByPath.get(path);
+      if (createNodeId != null) {
+        addEdge(deleteNodeId, createNodeId);
+      }
+      Integer renameTargetNodeId = renameNodesByTargetPath.get(path);
+      if (renameTargetNodeId != null) {
+        addEdge(deleteNodeId, renameTargetNodeId);
+      }
+    }
+  }
+
+  private void addRenameBeforeCreateEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> createNodesByPath) {
+    for (Map.Entry<String, Integer> createEntry :
+        createNodesByPath.entrySet()) {
+      Integer renameNodeId =
+          renameNodesBySourcePath.get(createEntry.getKey());
+      if (renameNodeId != null) {
+        addEdge(renameNodeId, createEntry.getValue());
+      }
+    }
+  }
+
+  /**
+   * From-snapshot path-prefix edges. Intermediate directories may be omitted
+   * from the report; ancestor ordering is derived from strict path prefixes.
+   *
+   * <p>DELETE, RENAME, and MODIFY entries all carry a from-snapshot source
+   * path (RENAME uses the pre-rename source, and MODIFY is reported at the
+   * old key path per SnapshotDiffManager). CREATE is excluded because a
+   * CREATE's source path is a to-snapshot path; to-snapshot prefixes are
+   * handled by {@link #addPathPrefixToSnapshotEdges}. Mixing the two would
+   * generate spurious edges (e.g. after DELETE A + CREATE A, a CREATE A/child
+   * would incorrectly point at DELETE A and produce a cycle).
+   */
+  private void addPathPrefixFromSnapshotEdges(
+      Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> renameNodesBySourcePath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      int descendantDeleteNodeId = deleteEntry.getValue();
+      forEachStrictPrefix(deleteEntry.getKey(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      DiffType diffType = entry.getDiffType();
+      if (diffType != DiffType.RENAME && diffType != DiffType.MODIFY) {
+        continue;
+      }
+      final int fromNodeId = nodeId;
+      forEachStrictPrefix(entry.getSourcePath(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(fromNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(fromNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+  }
+
+  /**
+   * To-snapshot path-prefix edges. A descendant CREATE/RENAME/MODIFY cannot be
+   * applied until ancestor directories exist on the to-snapshot side.
+   */
+  private void addPathPrefixToSnapshotEdges(
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        continue;
+      }
+      String toSnapshotPath = getToSnapshotPath(entry);
+      if (toSnapshotPath == null) {
+        continue;
+      }
+      final int toNodeId = nodeId;
+      forEachStrictPrefix(toSnapshotPath, ancestorPath -> {
+        Integer ancestorCreateNodeId = createNodesByPath.get(ancestorPath);
+        if (ancestorCreateNodeId != null) {
+          addEdge(ancestorCreateNodeId, toNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesByTargetPath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(ancestorRenameNodeId, toNodeId);
+        }
+      });
+    }
+  }
+
+  private static String getToSnapshotPath(SnapDiffDependencyEntry entry) {
+    if (entry.getDiffType() == DiffType.RENAME) {
+      return entry.getTargetPath();
+    }
+    return entry.getSourcePath();

Review Comment:
   `MODIFY` is reported at the from-snapshot path (`SnapshotDiffManager` explicitly emits `oldKey`), so it is not always a valid to-snapshot path. For example, moving and modifying `A/child` while deleting/recreating `A` produces `CREATE A -> MODIFY A/child -> DELETE A -> CREATE A`, and this graph rejects an otherwise valid diff as cyclic. For a modified object that also has a `RENAME`, avoid treating the MODIFY source as its to-snapshot location; derive its target-side ordering from the matching rename instead.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl merged PR #10778:
URL: https://github.com/apache/ozone/pull/10778


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3762141108


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,656 @@
+/*
+ * 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.snapshot;
+
+import static org.apache.hadoop.ozone.OzoneConsts.OM_KEY_PREFIX;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant RENAME or MODIFY before ancestor DELETE or RENAME(source)
+ *       on a strict source-path prefix. CREATE is omitted because its source
+ *       path is a to-snapshot path, not a from-snapshot path.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  private static final int MAX_CYCLE_ENTRIES_IN_MESSAGE = 16;
+  // Defensive JVM-side ceiling on the growable long[] edge buffer used during
+  // construction (see grownCapacity). Hotspot/OpenJDK cap the largest array a
+  // little below Integer.MAX_VALUE; going any higher throws OutOfMemoryError
+  // with an unhelpful message.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final String PATH_SEPARATOR = OM_KEY_PREFIX;
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges;
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Only objectIds that have a RENAME entry are tracked;
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    Objects.requireNonNull(entries, "entries");
+    nodes.addAll(entries);
+    // Size the initial edge buffer to roughly the node count so realistic
+    // graphs (edge density 3-8 per node) skip most of the doubling copies.
+    // Clamp to INITIAL_EDGE_CAPACITY so tiny inputs still allocate cheaply.
+    edges = new long[Math.max(INITIAL_EDGE_CAPACITY, nodes.size())];
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];
+    int deleteHead = 0;
+    int deleteTail = 0;
+    int otherHead = 0;
+    int otherTail = 0;
+    for (int nodeId = 0; nodeId < nodeCount; nodeId++) {
+      if (remainingInDegree[nodeId] == 0) {
+        if (nodes.get(nodeId).isDelete()) {
+          deleteReady[deleteTail++] = nodeId;
+        } else {
+          otherReady[otherTail++] = nodeId;
+        }
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodeCount);
+    while (deleteHead < deleteTail || otherHead < otherTail) {
+      int nodeId = deleteHead < deleteTail
+          ? deleteReady[deleteHead++] : otherReady[otherHead++];
+      orderedEntries.add(nodes.get(nodeId));
+      for (int i = adjOffsets[nodeId]; i < adjOffsets[nodeId + 1]; i++) {
+        int dependentNodeId = adjTargets[i];
+        if (--remainingInDegree[dependentNodeId] == 0) {
+          if (nodes.get(dependentNodeId).isDelete()) {
+            deleteReady[deleteTail++] = dependentNodeId;
+          } else {
+            otherReady[otherTail++] = dependentNodeId;
+          }
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodeCount) {
+      List<String> unresolved = collectUnresolvedNodes(orderedEntries);
+      LOG.debug("Cycle detected in snapshot diff dependency graph. "
+          + "Unresolved entries: {}", unresolved);
+      int total = unresolved.size();
+      List<String> sample = total > MAX_CYCLE_ENTRIES_IN_MESSAGE
+          ? unresolved.subList(0, MAX_CYCLE_ENTRIES_IN_MESSAGE) : unresolved;
+      throw new IllegalStateException(String.format(
+          "Cycle detected in snapshot diff dependency graph; %d unresolved "
+              + "entries (showing up to %d): %s",
+          total, MAX_CYCLE_ENTRIES_IN_MESSAGE, sample));
+    }
+    return orderedEntries;
+  }
+
+  private List<String> collectUnresolvedNodes(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    Set<SnapDiffDependencyEntry> resolved =
+        Collections.newSetFromMap(new IdentityHashMap<>());
+    resolved.addAll(orderedEntries);
+    List<String> unresolved = new ArrayList<>();
+    for (SnapDiffDependencyEntry entry : nodes) {
+      if (!resolved.contains(entry)) {
+        unresolved.add(entry.getDiffType() + " " + entry.getSourcePath());
+      }
+    }
+    return unresolved;
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (edgeCount == edges.length) {
+      edges = Arrays.copyOf(edges, grownCapacity(edges.length));
+    }
+    edges[edgeCount++] =
+        ((long) fromNodeId << Integer.SIZE) | (toNodeId & 0xFFFFFFFFL);
+  }
+
+  private static int grownCapacity(int currentCapacity) {
+    // Grow by 1.5x to bound the transient overshoot of the edge buffer, and
+    // clamp to MAX_ARRAY_SIZE so the growth cannot overflow into a negative
+    // (or unallocatable) size.
+    int grown = currentCapacity + (currentCapacity >> 1);
+    if (grown < 0 || grown > MAX_ARRAY_SIZE) {
+      if (currentCapacity >= MAX_ARRAY_SIZE) {
+        throw new IllegalStateException(
+            "Snapshot diff dependency graph exceeds maximum edge capacity");
+      }
+      return MAX_ARRAY_SIZE;
+    }
+    return grown;
+  }
+
+  /**
+   * Deduplicates the collected edges and packs them into the CSR arrays.
+   * Encoding each edge as {@code (from << 32 | to)} lets a single sort group
+   * neighbors by source node and place duplicates next to each other, so the
+   * repeated {@code HashSet} allocations of the previous representation are no
+   * longer needed. The temporary edge buffer is released afterwards.
+   */
+  private void buildCsr() {
+    int nodeCount = nodes.size();
+    adjOffsets = new int[nodeCount + 1];
+    inDegree = new int[nodeCount];
+    if (edgeCount == 0) {
+      adjTargets = EMPTY_INT_ARRAY;
+      edges = null;
+      return;
+    }
+
+    Arrays.sort(edges, 0, edgeCount);
+
+    // First pass over the sorted edges: skip duplicates while counting the
+    // out-edges per source node and the in-degree per target node.
+    long previous = edges[0];
+    int uniqueCount = 1;
+    adjOffsets[(int) (previous >>> Integer.SIZE) + 1]++;
+    inDegree[(int) previous]++;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      uniqueCount++;
+      adjOffsets[(int) (edge >>> Integer.SIZE) + 1]++;
+      inDegree[(int) edge]++;
+    }
+
+    // Prefix sum turns per-node out-edge counts into CSR start offsets.
+    for (int i = 0; i < nodeCount; i++) {
+      adjOffsets[i + 1] += adjOffsets[i];
+    }
+
+    // Second pass: the unique edges are already ordered by source then target,
+    // so appending their targets sequentially matches the CSR offsets.
+    adjTargets = new int[uniqueCount];
+    previous = edges[0];
+    int index = 0;
+    adjTargets[index++] = (int) previous;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      adjTargets[index++] = (int) edge;
+    }
+    edges = null;
+  }
+
+  private void buildDependencyEdges() {
+    // At most one object occupies a given path on a given snapshot side, so a
+    // single node id per path is sufficient. Count each category first
+    // so the four indexes can be pre-sized exactly.
+    int createCount = 0;
+    int deleteCount = 0;
+    int renameCount = 0;
+    for (int i = 0; i < nodes.size(); i++) {
+      DiffType diffType = nodes.get(i).getDiffType();
+      if (diffType == DiffType.DELETE) {
+        deleteCount++;
+      } else if (diffType == DiffType.CREATE) {
+        createCount++;
+      } else if (diffType == DiffType.RENAME) {
+        renameCount++;
+      }
+    }
+    Map<String, Integer> createNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(createCount));
+    Map<String, Integer> deleteNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(deleteCount));
+    Map<String, Integer> renameNodesBySourcePath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    Map<String, Integer> renameNodesByTargetPath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    addPathConflictEdges(deleteNodesByPath, createNodesByPath,
+        renameNodesByTargetPath);
+    addRenameBeforeCreateEdges(renameNodesBySourcePath, createNodesByPath);
+    addRenameChainEdges(renameNodesBySourcePath, renameNodesByTargetPath);
+    addPathPrefixFromSnapshotEdges(deleteNodesByPath, renameNodesBySourcePath);
+    addPathPrefixToSnapshotEdges(createNodesByPath, renameNodesByTargetPath);
+
+    buildObjectIdGroups(renameCount);
+    addIntraObjectRenameEdges();
+
+    groupObjectIds = null;
+    groupOffsets = null;
+    groupNodes = null;
+
+    // Path strings were cached on each entry so that repeated edge-building
+    // passes did not re-decode. The graph no longer reads them once edges
+    // are built; drop the caches to reclaim per-entry heap.
+    for (int i = 0; i < nodes.size(); i++) {
+      nodes.get(i).clearPathCache();
+    }
+  }
+
+  /**
+   * Groups node ids by objectId, restricted to objectIds that have a RENAME
+   * entry (only those can pick up intra-object edges). The slice of
+   * {@link #groupNodes} between {@link #groupOffsets}{@code [rank]} and
+   * {@code [rank + 1]} lists the node ids for {@link #groupObjectIds}
+   * {@code [rank]}.
+   *
+   * <p>Uses a single hash-map lookup per node and no per-node binary search,
+   * so peak transient memory here is bounded by the number of nodes that
+   * belong to a renamed object rather than the full node count.
+   */
+  private void buildObjectIdGroups(int renameCount) {
+    if (renameCount == 0) {
+      groupObjectIds = new long[0];
+      groupOffsets = new int[1];
+      groupNodes = EMPTY_INT_ARRAY;
+      return;
+    }
+    int nodeCount = nodes.size();
+    // Rank the RENAMEd objectIds. Presize to the exact rename count; there is
+    // at most one RENAME per objectId (a second RENAME on the same id is
+    // rejected by addToPathIndex).
+    Map<Long, Integer> rankByObjectId =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    long[] renameObjectIds = new long[renameCount];
+    int uniqueCount = 0;
+    for (int i = 0; i < nodeCount && uniqueCount < renameCount; i++) {
+      SnapDiffDependencyEntry entry = nodes.get(i);
+      if (entry.getDiffType() == DiffType.RENAME) {
+        renameObjectIds[uniqueCount] = entry.getObjectId();
+        rankByObjectId.put(entry.getObjectId(), uniqueCount);
+        uniqueCount++;
+      }
+    }
+    groupObjectIds = renameObjectIds;
+
+    // Count how many nodes belong to each renamed object.
+    groupOffsets = new int[uniqueCount + 1];
+    int groupedNodeCount = 0;
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupOffsets[rank + 1]++;
+        groupedNodeCount++;
+      }
+    }
+    for (int i = 0; i < uniqueCount; i++) {
+      groupOffsets[i + 1] += groupOffsets[i];
+    }
+
+    // Fill groupNodes. Sized to groupedNodeCount, not the full node count.
+    groupNodes = new int[groupedNodeCount];
+    int[] fillCursor = Arrays.copyOf(groupOffsets, uniqueCount);
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupNodes[fillCursor[rank]++] = i;
+      }
+    }
+  }
+
+  /**
+   * Orders the non-delete entries of a single object relative to its RENAME.
+   * An entry reported at the RENAME source (from-snapshot) path must be applied
+   * before the path is renamed away; an entry reported at the RENAME target
+   * (to-snapshot) path must be applied after the rename creates that path.
+   */
+  private void addIntraObjectRenameEdges() {
+    for (int rank = 0; rank < groupObjectIds.length; rank++) {
+      int start = groupOffsets[rank];
+      int end = groupOffsets[rank + 1];
+      if (end - start < 2) {
+        continue;
+      }
+      int renameNodeId = -1;
+      for (int i = start; i < end; i++) {
+        if (nodes.get(groupNodes[i]).getDiffType() == DiffType.RENAME) {
+          renameNodeId = groupNodes[i];
+          break;
+        }
+      }
+      if (renameNodeId < 0) {
+        continue;
+      }
+      SnapDiffDependencyEntry rename = nodes.get(renameNodeId);
+      for (int i = start; i < end; i++) {
+        int nodeId = groupNodes[i];
+        if (nodeId == renameNodeId) {
+          continue;
+        }
+        String path = nodes.get(nodeId).getSourcePath();
+        if (path == null) {
+          continue;
+        }
+        if (path.equals(rename.getSourcePath())) {
+          addEdge(nodeId, renameNodeId);
+        } else if (path.equals(rename.getTargetPath())) {
+          addEdge(renameNodeId, nodeId);
+        }
+      }
+    }
+  }
+
+  /**
+   * Converts an expected element count to the initial capacity that keeps a
+   * default-load-factor (0.75) HashMap from resizing while it fills to that
+   * count. Mirrors what JDK 19's {@code HashMap.newHashMap(int)} does, but
+   * stays on Java 8 source.
+   */
+  private static int expectedHashMapCapacity(int expectedSize) {
+    if (expectedSize <= 0) {
+      return 1;
+    }
+    // ceil(expectedSize / 0.75) with an overflow guard for large sizes.
+    long capacity = (long) expectedSize + (expectedSize + 2) / 3;
+    return capacity > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) capacity;
+  }
+
+  private static void addToPathIndex(Map<String, Integer> pathIndex,
+      String path, int nodeId) {
+    if (path == null) {
+      return;
+    }
+    // At most one object can occupy a path on a given snapshot side, so the
+    // first node wins. A second node on the same path indicates malformed diff
+    // input (per SnapshotDiffManager, an object appears at most once in each of
+    // the CREATE/DELETE/RENAME(source)/RENAME(target) indices).
+    Integer existing = pathIndex.putIfAbsent(path, nodeId);
+    if (existing != null) {
+      LOG.warn("Multiple diff entries share path '{}'; keeping node {}, "
+          + "ignoring node {}", path, existing, nodeId);
+    }
+  }
+
+  /**
+   * Orders renames that reuse the same path: the rename whose source frees a
+   * path must precede the rename whose target occupies that same path.
+   */
+  private void addRenameChainEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> sourceEntry :
+        renameNodesBySourcePath.entrySet()) {
+      Integer targetNodeId =
+          renameNodesByTargetPath.get(sourceEntry.getKey());
+      if (targetNodeId != null) {
+        addEdge(sourceEntry.getValue(), targetNodeId);
+      }
+    }
+  }
+
+  private void addPathConflictEdges(Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      String path = deleteEntry.getKey();
+      int deleteNodeId = deleteEntry.getValue();
+      Integer createNodeId = createNodesByPath.get(path);
+      if (createNodeId != null) {
+        addEdge(deleteNodeId, createNodeId);
+      }
+      Integer renameTargetNodeId = renameNodesByTargetPath.get(path);
+      if (renameTargetNodeId != null) {
+        addEdge(deleteNodeId, renameTargetNodeId);
+      }
+    }
+  }
+
+  private void addRenameBeforeCreateEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> createNodesByPath) {
+    for (Map.Entry<String, Integer> createEntry :
+        createNodesByPath.entrySet()) {
+      Integer renameNodeId =
+          renameNodesBySourcePath.get(createEntry.getKey());
+      if (renameNodeId != null) {
+        addEdge(renameNodeId, createEntry.getValue());
+      }
+    }
+  }
+
+  /**
+   * From-snapshot path-prefix edges. Intermediate directories may be omitted
+   * from the report; ancestor ordering is derived from strict path prefixes.
+   *
+   * <p>DELETE, RENAME, and MODIFY entries all carry a from-snapshot source
+   * path (RENAME uses the pre-rename source, and MODIFY is reported at the
+   * old key path per SnapshotDiffManager). CREATE is excluded because a
+   * CREATE's source path is a to-snapshot path; to-snapshot prefixes are
+   * handled by {@link #addPathPrefixToSnapshotEdges}. Mixing the two would
+   * generate spurious edges (e.g. after DELETE A + CREATE A, a CREATE A/child
+   * would incorrectly point at DELETE A and produce a cycle).
+   */
+  private void addPathPrefixFromSnapshotEdges(
+      Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> renameNodesBySourcePath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      int descendantDeleteNodeId = deleteEntry.getValue();
+      forEachStrictPrefix(deleteEntry.getKey(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      DiffType diffType = entry.getDiffType();
+      if (diffType != DiffType.RENAME && diffType != DiffType.MODIFY) {
+        continue;
+      }
+      final int fromNodeId = nodeId;
+      forEachStrictPrefix(entry.getSourcePath(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(fromNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(fromNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+  }
+
+  /**
+   * To-snapshot path-prefix edges. A descendant CREATE/RENAME/MODIFY cannot be
+   * applied until ancestor directories exist on the to-snapshot side.
+   */
+  private void addPathPrefixToSnapshotEdges(
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        continue;
+      }
+      String toSnapshotPath = getToSnapshotPath(entry);
+      if (toSnapshotPath == null) {
+        continue;
+      }
+      final int toNodeId = nodeId;
+      forEachStrictPrefix(toSnapshotPath, ancestorPath -> {
+        Integer ancestorCreateNodeId = createNodesByPath.get(ancestorPath);
+        if (ancestorCreateNodeId != null) {
+          addEdge(ancestorCreateNodeId, toNodeId);

Review Comment:
   Updated the PR description. MODIFY ordering in this case is unnecessary.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3762338623


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,656 @@
+/*
+ * 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.snapshot;
+
+import static org.apache.hadoop.ozone.OzoneConsts.OM_KEY_PREFIX;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant RENAME or MODIFY before ancestor DELETE or RENAME(source)
+ *       on a strict source-path prefix. CREATE is omitted because its source
+ *       path is a to-snapshot path, not a from-snapshot path.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  private static final int MAX_CYCLE_ENTRIES_IN_MESSAGE = 16;
+  // Defensive JVM-side ceiling on the growable long[] edge buffer used during
+  // construction (see grownCapacity). Hotspot/OpenJDK cap the largest array a
+  // little below Integer.MAX_VALUE; going any higher throws OutOfMemoryError
+  // with an unhelpful message.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final String PATH_SEPARATOR = OM_KEY_PREFIX;
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges;
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Only objectIds that have a RENAME entry are tracked;
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    Objects.requireNonNull(entries, "entries");
+    nodes.addAll(entries);
+    // Size the initial edge buffer to roughly the node count so realistic
+    // graphs (edge density 3-8 per node) skip most of the doubling copies.
+    // Clamp to INITIAL_EDGE_CAPACITY so tiny inputs still allocate cheaply.
+    edges = new long[Math.max(INITIAL_EDGE_CAPACITY, nodes.size())];
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];
+    int deleteHead = 0;
+    int deleteTail = 0;
+    int otherHead = 0;
+    int otherTail = 0;
+    for (int nodeId = 0; nodeId < nodeCount; nodeId++) {
+      if (remainingInDegree[nodeId] == 0) {
+        if (nodes.get(nodeId).isDelete()) {
+          deleteReady[deleteTail++] = nodeId;
+        } else {
+          otherReady[otherTail++] = nodeId;
+        }
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodeCount);
+    while (deleteHead < deleteTail || otherHead < otherTail) {
+      int nodeId = deleteHead < deleteTail
+          ? deleteReady[deleteHead++] : otherReady[otherHead++];
+      orderedEntries.add(nodes.get(nodeId));
+      for (int i = adjOffsets[nodeId]; i < adjOffsets[nodeId + 1]; i++) {
+        int dependentNodeId = adjTargets[i];
+        if (--remainingInDegree[dependentNodeId] == 0) {
+          if (nodes.get(dependentNodeId).isDelete()) {
+            deleteReady[deleteTail++] = dependentNodeId;
+          } else {
+            otherReady[otherTail++] = dependentNodeId;
+          }
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodeCount) {
+      List<String> unresolved = collectUnresolvedNodes(orderedEntries);
+      LOG.debug("Cycle detected in snapshot diff dependency graph. "
+          + "Unresolved entries: {}", unresolved);
+      int total = unresolved.size();
+      List<String> sample = total > MAX_CYCLE_ENTRIES_IN_MESSAGE
+          ? unresolved.subList(0, MAX_CYCLE_ENTRIES_IN_MESSAGE) : unresolved;
+      throw new IllegalStateException(String.format(
+          "Cycle detected in snapshot diff dependency graph; %d unresolved "
+              + "entries (showing up to %d): %s",
+          total, MAX_CYCLE_ENTRIES_IN_MESSAGE, sample));
+    }
+    return orderedEntries;
+  }
+
+  private List<String> collectUnresolvedNodes(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    Set<SnapDiffDependencyEntry> resolved =
+        Collections.newSetFromMap(new IdentityHashMap<>());
+    resolved.addAll(orderedEntries);
+    List<String> unresolved = new ArrayList<>();
+    for (SnapDiffDependencyEntry entry : nodes) {
+      if (!resolved.contains(entry)) {
+        unresolved.add(entry.getDiffType() + " " + entry.getSourcePath());
+      }
+    }
+    return unresolved;
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (edgeCount == edges.length) {
+      edges = Arrays.copyOf(edges, grownCapacity(edges.length));
+    }
+    edges[edgeCount++] =
+        ((long) fromNodeId << Integer.SIZE) | (toNodeId & 0xFFFFFFFFL);
+  }
+
+  private static int grownCapacity(int currentCapacity) {
+    // Grow by 1.5x to bound the transient overshoot of the edge buffer, and
+    // clamp to MAX_ARRAY_SIZE so the growth cannot overflow into a negative
+    // (or unallocatable) size.
+    int grown = currentCapacity + (currentCapacity >> 1);
+    if (grown < 0 || grown > MAX_ARRAY_SIZE) {
+      if (currentCapacity >= MAX_ARRAY_SIZE) {
+        throw new IllegalStateException(
+            "Snapshot diff dependency graph exceeds maximum edge capacity");
+      }
+      return MAX_ARRAY_SIZE;
+    }
+    return grown;
+  }
+
+  /**
+   * Deduplicates the collected edges and packs them into the CSR arrays.
+   * Encoding each edge as {@code (from << 32 | to)} lets a single sort group
+   * neighbors by source node and place duplicates next to each other, so the
+   * repeated {@code HashSet} allocations of the previous representation are no
+   * longer needed. The temporary edge buffer is released afterwards.
+   */
+  private void buildCsr() {
+    int nodeCount = nodes.size();
+    adjOffsets = new int[nodeCount + 1];
+    inDegree = new int[nodeCount];
+    if (edgeCount == 0) {
+      adjTargets = EMPTY_INT_ARRAY;
+      edges = null;
+      return;
+    }
+
+    Arrays.sort(edges, 0, edgeCount);
+
+    // First pass over the sorted edges: skip duplicates while counting the
+    // out-edges per source node and the in-degree per target node.
+    long previous = edges[0];
+    int uniqueCount = 1;
+    adjOffsets[(int) (previous >>> Integer.SIZE) + 1]++;
+    inDegree[(int) previous]++;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      uniqueCount++;
+      adjOffsets[(int) (edge >>> Integer.SIZE) + 1]++;
+      inDegree[(int) edge]++;
+    }
+
+    // Prefix sum turns per-node out-edge counts into CSR start offsets.
+    for (int i = 0; i < nodeCount; i++) {
+      adjOffsets[i + 1] += adjOffsets[i];
+    }
+
+    // Second pass: the unique edges are already ordered by source then target,
+    // so appending their targets sequentially matches the CSR offsets.
+    adjTargets = new int[uniqueCount];
+    previous = edges[0];
+    int index = 0;
+    adjTargets[index++] = (int) previous;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      adjTargets[index++] = (int) edge;
+    }
+    edges = null;
+  }
+
+  private void buildDependencyEdges() {
+    // At most one object occupies a given path on a given snapshot side, so a
+    // single node id per path is sufficient. Count each category first
+    // so the four indexes can be pre-sized exactly.
+    int createCount = 0;
+    int deleteCount = 0;
+    int renameCount = 0;
+    for (int i = 0; i < nodes.size(); i++) {
+      DiffType diffType = nodes.get(i).getDiffType();
+      if (diffType == DiffType.DELETE) {
+        deleteCount++;
+      } else if (diffType == DiffType.CREATE) {
+        createCount++;
+      } else if (diffType == DiffType.RENAME) {
+        renameCount++;
+      }
+    }
+    Map<String, Integer> createNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(createCount));
+    Map<String, Integer> deleteNodesByPath =
+        new HashMap<>(expectedHashMapCapacity(deleteCount));
+    Map<String, Integer> renameNodesBySourcePath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    Map<String, Integer> renameNodesByTargetPath =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    addPathConflictEdges(deleteNodesByPath, createNodesByPath,
+        renameNodesByTargetPath);
+    addRenameBeforeCreateEdges(renameNodesBySourcePath, createNodesByPath);
+    addRenameChainEdges(renameNodesBySourcePath, renameNodesByTargetPath);
+    addPathPrefixFromSnapshotEdges(deleteNodesByPath, renameNodesBySourcePath);
+    addPathPrefixToSnapshotEdges(createNodesByPath, renameNodesByTargetPath);
+
+    buildObjectIdGroups(renameCount);
+    addIntraObjectRenameEdges();
+
+    groupObjectIds = null;
+    groupOffsets = null;
+    groupNodes = null;
+
+    // Path strings were cached on each entry so that repeated edge-building
+    // passes did not re-decode. The graph no longer reads them once edges
+    // are built; drop the caches to reclaim per-entry heap.
+    for (int i = 0; i < nodes.size(); i++) {
+      nodes.get(i).clearPathCache();
+    }
+  }
+
+  /**
+   * Groups node ids by objectId, restricted to objectIds that have a RENAME
+   * entry (only those can pick up intra-object edges). The slice of
+   * {@link #groupNodes} between {@link #groupOffsets}{@code [rank]} and
+   * {@code [rank + 1]} lists the node ids for {@link #groupObjectIds}
+   * {@code [rank]}.
+   *
+   * <p>Uses a single hash-map lookup per node and no per-node binary search,
+   * so peak transient memory here is bounded by the number of nodes that
+   * belong to a renamed object rather than the full node count.
+   */
+  private void buildObjectIdGroups(int renameCount) {
+    if (renameCount == 0) {
+      groupObjectIds = new long[0];
+      groupOffsets = new int[1];
+      groupNodes = EMPTY_INT_ARRAY;
+      return;
+    }
+    int nodeCount = nodes.size();
+    // Rank the RENAMEd objectIds. Presize to the exact rename count; there is
+    // at most one RENAME per objectId (a second RENAME on the same id is
+    // rejected by addToPathIndex).
+    Map<Long, Integer> rankByObjectId =
+        new HashMap<>(expectedHashMapCapacity(renameCount));
+    long[] renameObjectIds = new long[renameCount];
+    int uniqueCount = 0;
+    for (int i = 0; i < nodeCount && uniqueCount < renameCount; i++) {
+      SnapDiffDependencyEntry entry = nodes.get(i);
+      if (entry.getDiffType() == DiffType.RENAME) {
+        renameObjectIds[uniqueCount] = entry.getObjectId();
+        rankByObjectId.put(entry.getObjectId(), uniqueCount);
+        uniqueCount++;
+      }
+    }
+    groupObjectIds = renameObjectIds;
+
+    // Count how many nodes belong to each renamed object.
+    groupOffsets = new int[uniqueCount + 1];
+    int groupedNodeCount = 0;
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupOffsets[rank + 1]++;
+        groupedNodeCount++;
+      }
+    }
+    for (int i = 0; i < uniqueCount; i++) {
+      groupOffsets[i + 1] += groupOffsets[i];
+    }
+
+    // Fill groupNodes. Sized to groupedNodeCount, not the full node count.
+    groupNodes = new int[groupedNodeCount];
+    int[] fillCursor = Arrays.copyOf(groupOffsets, uniqueCount);
+    for (int i = 0; i < nodeCount; i++) {
+      Integer rank = rankByObjectId.get(nodes.get(i).getObjectId());
+      if (rank != null) {
+        groupNodes[fillCursor[rank]++] = i;
+      }
+    }
+  }
+
+  /**
+   * Orders the non-delete entries of a single object relative to its RENAME.
+   * An entry reported at the RENAME source (from-snapshot) path must be applied
+   * before the path is renamed away; an entry reported at the RENAME target
+   * (to-snapshot) path must be applied after the rename creates that path.
+   */
+  private void addIntraObjectRenameEdges() {
+    for (int rank = 0; rank < groupObjectIds.length; rank++) {
+      int start = groupOffsets[rank];
+      int end = groupOffsets[rank + 1];
+      if (end - start < 2) {
+        continue;
+      }
+      int renameNodeId = -1;
+      for (int i = start; i < end; i++) {
+        if (nodes.get(groupNodes[i]).getDiffType() == DiffType.RENAME) {
+          renameNodeId = groupNodes[i];
+          break;
+        }
+      }
+      if (renameNodeId < 0) {
+        continue;
+      }
+      SnapDiffDependencyEntry rename = nodes.get(renameNodeId);
+      for (int i = start; i < end; i++) {
+        int nodeId = groupNodes[i];
+        if (nodeId == renameNodeId) {
+          continue;
+        }
+        String path = nodes.get(nodeId).getSourcePath();
+        if (path == null) {
+          continue;
+        }
+        if (path.equals(rename.getSourcePath())) {
+          addEdge(nodeId, renameNodeId);
+        } else if (path.equals(rename.getTargetPath())) {
+          addEdge(renameNodeId, nodeId);
+        }
+      }
+    }
+  }
+
+  /**
+   * Converts an expected element count to the initial capacity that keeps a
+   * default-load-factor (0.75) HashMap from resizing while it fills to that
+   * count. Mirrors what JDK 19's {@code HashMap.newHashMap(int)} does, but
+   * stays on Java 8 source.
+   */
+  private static int expectedHashMapCapacity(int expectedSize) {
+    if (expectedSize <= 0) {
+      return 1;
+    }
+    // ceil(expectedSize / 0.75) with an overflow guard for large sizes.
+    long capacity = (long) expectedSize + (expectedSize + 2) / 3;
+    return capacity > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) capacity;
+  }
+
+  private static void addToPathIndex(Map<String, Integer> pathIndex,
+      String path, int nodeId) {
+    if (path == null) {
+      return;
+    }
+    // At most one object can occupy a path on a given snapshot side, so the
+    // first node wins. A second node on the same path indicates malformed diff
+    // input (per SnapshotDiffManager, an object appears at most once in each of
+    // the CREATE/DELETE/RENAME(source)/RENAME(target) indices).
+    Integer existing = pathIndex.putIfAbsent(path, nodeId);
+    if (existing != null) {
+      LOG.warn("Multiple diff entries share path '{}'; keeping node {}, "
+          + "ignoring node {}", path, existing, nodeId);
+    }
+  }
+
+  /**
+   * Orders renames that reuse the same path: the rename whose source frees a
+   * path must precede the rename whose target occupies that same path.
+   */
+  private void addRenameChainEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> sourceEntry :
+        renameNodesBySourcePath.entrySet()) {
+      Integer targetNodeId =
+          renameNodesByTargetPath.get(sourceEntry.getKey());
+      if (targetNodeId != null) {
+        addEdge(sourceEntry.getValue(), targetNodeId);
+      }
+    }
+  }
+
+  private void addPathConflictEdges(Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      String path = deleteEntry.getKey();
+      int deleteNodeId = deleteEntry.getValue();
+      Integer createNodeId = createNodesByPath.get(path);
+      if (createNodeId != null) {
+        addEdge(deleteNodeId, createNodeId);
+      }
+      Integer renameTargetNodeId = renameNodesByTargetPath.get(path);
+      if (renameTargetNodeId != null) {
+        addEdge(deleteNodeId, renameTargetNodeId);
+      }
+    }
+  }
+
+  private void addRenameBeforeCreateEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> createNodesByPath) {
+    for (Map.Entry<String, Integer> createEntry :
+        createNodesByPath.entrySet()) {
+      Integer renameNodeId =
+          renameNodesBySourcePath.get(createEntry.getKey());
+      if (renameNodeId != null) {
+        addEdge(renameNodeId, createEntry.getValue());
+      }
+    }
+  }
+
+  /**
+   * From-snapshot path-prefix edges. Intermediate directories may be omitted
+   * from the report; ancestor ordering is derived from strict path prefixes.
+   *
+   * <p>DELETE, RENAME, and MODIFY entries all carry a from-snapshot source
+   * path (RENAME uses the pre-rename source, and MODIFY is reported at the
+   * old key path per SnapshotDiffManager). CREATE is excluded because a
+   * CREATE's source path is a to-snapshot path; to-snapshot prefixes are
+   * handled by {@link #addPathPrefixToSnapshotEdges}. Mixing the two would
+   * generate spurious edges (e.g. after DELETE A + CREATE A, a CREATE A/child
+   * would incorrectly point at DELETE A and produce a cycle).
+   */
+  private void addPathPrefixFromSnapshotEdges(
+      Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> renameNodesBySourcePath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      int descendantDeleteNodeId = deleteEntry.getValue();
+      forEachStrictPrefix(deleteEntry.getKey(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      DiffType diffType = entry.getDiffType();
+      if (diffType != DiffType.RENAME && diffType != DiffType.MODIFY) {
+        continue;
+      }
+      final int fromNodeId = nodeId;
+      forEachStrictPrefix(entry.getSourcePath(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(fromNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(fromNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+  }
+
+  /**
+   * To-snapshot path-prefix edges. A descendant CREATE/RENAME/MODIFY cannot be
+   * applied until ancestor directories exist on the to-snapshot side.
+   */
+  private void addPathPrefixToSnapshotEdges(
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        continue;
+      }
+      String toSnapshotPath = getToSnapshotPath(entry);
+      if (toSnapshotPath == null) {
+        continue;
+      }
+      final int toNodeId = nodeId;
+      forEachStrictPrefix(toSnapshotPath, ancestorPath -> {
+        Integer ancestorCreateNodeId = createNodesByPath.get(ancestorPath);
+        if (ancestorCreateNodeId != null) {
+          addEdge(ancestorCreateNodeId, toNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesByTargetPath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(ancestorRenameNodeId, toNodeId);
+        }
+      });
+    }
+  }
+
+  private static String getToSnapshotPath(SnapDiffDependencyEntry entry) {
+    if (entry.getDiffType() == DiffType.RENAME) {
+      return entry.getTargetPath();
+    }
+    return entry.getSourcePath();

Review Comment:
   Updated the patch to skip to-snapshot dependency edges for ancestors that have been recreated (deleted and created again) and added a test to verify that the dependencies are resolved without creating a cycle.
   
   @smengcl directory `MODIFY` using the to-snapshot path and file/key `MODIFY` using from-snapshot path seems like an inconsistency in reporting. Both report `MODIFY path` but it is not intuitive that file/key report path from from-snapshot and directory from to-snapshot.
   When reporting a diff between from-snapshot and to-snapshot I think it makes sense to report "File/Key/Dir X in fromSnapshot was modified" rather than "File/Key/Dir X in toSnapshot was modified prior to taking the snapshot". Added a javadoc in `SnapDiffDependencyEntry` that expects the same.
   This was what was intended to come out of [HDDS-15391](https://issues.apache.org/jira/browse/HDDS-15391) as well.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3762301932


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,656 @@
+/*
+ * 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.snapshot;
+
+import static org.apache.hadoop.ozone.OzoneConsts.OM_KEY_PREFIX;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant RENAME or MODIFY before ancestor DELETE or RENAME(source)
+ *       on a strict source-path prefix. CREATE is omitted because its source
+ *       path is a to-snapshot path, not a from-snapshot path.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  private static final int MAX_CYCLE_ENTRIES_IN_MESSAGE = 16;
+  // Defensive JVM-side ceiling on the growable long[] edge buffer used during
+  // construction (see grownCapacity). Hotspot/OpenJDK cap the largest array a
+  // little below Integer.MAX_VALUE; going any higher throws OutOfMemoryError
+  // with an unhelpful message.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final String PATH_SEPARATOR = OM_KEY_PREFIX;
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges;
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Only objectIds that have a RENAME entry are tracked;
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */

Review Comment:
   Done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3715915144


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,569 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant non-delete before ancestor DELETE on a strict source-path
+ *       prefix.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  // Hotspot/OpenJDK cap the largest array a little below Integer.MAX_VALUE.
+  // Node and edge counts are assumed to fit in int; the configured changed-key
+  // limit (one billion) is well below this bound.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final char PATH_SEPARATOR = '/';
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges = new long[INITIAL_EDGE_CAPACITY];
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Released once edges are built.
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    nodes.addAll(entries);
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];
+    int deleteHead = 0;
+    int deleteTail = 0;
+    int otherHead = 0;
+    int otherTail = 0;
+    for (int nodeId = 0; nodeId < nodeCount; nodeId++) {
+      if (remainingInDegree[nodeId] == 0) {
+        if (nodes.get(nodeId).isDelete()) {
+          deleteReady[deleteTail++] = nodeId;
+        } else {
+          otherReady[otherTail++] = nodeId;
+        }
+      }
+    }
+
+    List<SnapDiffDependencyEntry> orderedEntries = new ArrayList<>(nodeCount);
+    while (deleteHead < deleteTail || otherHead < otherTail) {
+      int nodeId = deleteHead < deleteTail
+          ? deleteReady[deleteHead++] : otherReady[otherHead++];
+      orderedEntries.add(nodes.get(nodeId));
+      for (int i = adjOffsets[nodeId]; i < adjOffsets[nodeId + 1]; i++) {
+        int dependentNodeId = adjTargets[i];
+        if (--remainingInDegree[dependentNodeId] == 0) {
+          if (nodes.get(dependentNodeId).isDelete()) {
+            deleteReady[deleteTail++] = dependentNodeId;
+          } else {
+            otherReady[otherTail++] = dependentNodeId;
+          }
+        }
+      }
+    }
+
+    if (orderedEntries.size() != nodeCount) {
+      logUnresolvedNodes(orderedEntries);
+      throw new IllegalStateException(
+          "Cycle detected in snapshot diff dependency graph");
+    }
+    return orderedEntries;
+  }
+
+  private void logUnresolvedNodes(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    if (!LOG.isDebugEnabled()) {
+      return;
+    }
+    Set<SnapDiffDependencyEntry> resolved =
+        Collections.newSetFromMap(new IdentityHashMap<>());
+    resolved.addAll(orderedEntries);
+    List<String> unresolved = new ArrayList<>();
+    for (SnapDiffDependencyEntry entry : nodes) {
+      if (!resolved.contains(entry)) {
+        unresolved.add(entry.getDiffType() + " " + entry.getSourcePath());
+      }
+    }
+    LOG.debug("Cycle detected in snapshot diff dependency graph. "
+        + "Unresolved entries: {}", unresolved);
+  }
+
+  /**
+   * Converts dependency-ordered entries to report entries.
+   */
+  public static List<DiffReportEntry> toOrderedReportEntries(
+      List<SnapDiffDependencyEntry> orderedEntries) {
+    List<DiffReportEntry> reportEntries =
+        new ArrayList<>(orderedEntries.size());
+    for (SnapDiffDependencyEntry entry : orderedEntries) {
+      reportEntries.add(entry.getReportEntry());
+    }
+    return reportEntries;
+  }
+
+  private void addEdge(int fromNodeId, int toNodeId) {
+    if (fromNodeId == toNodeId) {
+      return;
+    }
+    if (edgeCount == edges.length) {
+      edges = Arrays.copyOf(edges, grownCapacity(edges.length));
+    }
+    edges[edgeCount++] =
+        ((long) fromNodeId << Integer.SIZE) | (toNodeId & 0xFFFFFFFFL);
+  }
+
+  private static int grownCapacity(int currentCapacity) {
+    // Grow by 1.5x to bound the transient overshoot of the edge buffer, and
+    // clamp to MAX_ARRAY_SIZE so the growth cannot overflow into a negative
+    // (or unallocatable) size.
+    int grown = currentCapacity + (currentCapacity >> 1);
+    if (grown < 0 || grown > MAX_ARRAY_SIZE) {
+      if (currentCapacity >= MAX_ARRAY_SIZE) {
+        throw new IllegalStateException(
+            "Snapshot diff dependency graph exceeds maximum edge capacity");
+      }
+      return MAX_ARRAY_SIZE;
+    }
+    return grown;
+  }
+
+  /**
+   * Deduplicates the collected edges and packs them into the CSR arrays.
+   * Encoding each edge as {@code (from << 32 | to)} lets a single sort group
+   * neighbors by source node and place duplicates next to each other, so the
+   * repeated {@code HashSet} allocations of the previous representation are no
+   * longer needed. The temporary edge buffer is released afterwards.
+   */
+  private void buildCsr() {
+    int nodeCount = nodes.size();
+    adjOffsets = new int[nodeCount + 1];
+    inDegree = new int[nodeCount];
+    if (edgeCount == 0) {
+      adjTargets = EMPTY_INT_ARRAY;
+      edges = null;
+      return;
+    }
+
+    Arrays.sort(edges, 0, edgeCount);
+
+    // First pass over the sorted edges: skip duplicates while counting the
+    // out-edges per source node and the in-degree per target node.
+    long previous = edges[0];
+    int uniqueCount = 1;
+    adjOffsets[(int) (previous >>> Integer.SIZE) + 1]++;
+    inDegree[(int) previous]++;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      uniqueCount++;
+      adjOffsets[(int) (edge >>> Integer.SIZE) + 1]++;
+      inDegree[(int) edge]++;
+    }
+
+    // Prefix sum turns per-node out-edge counts into CSR start offsets.
+    for (int i = 0; i < nodeCount; i++) {
+      adjOffsets[i + 1] += adjOffsets[i];
+    }
+
+    // Second pass: the unique edges are already ordered by source then target,
+    // so appending their targets sequentially matches the CSR offsets.
+    adjTargets = new int[uniqueCount];
+    previous = edges[0];
+    int index = 0;
+    adjTargets[index++] = (int) previous;
+    for (int i = 1; i < edgeCount; i++) {
+      long edge = edges[i];
+      if (edge == previous) {
+        continue;
+      }
+      previous = edge;
+      adjTargets[index++] = (int) edge;
+    }
+    edges = null;
+  }
+
+  private void buildDependencyEdges() {
+    // At most one object occupies a given path on a given snapshot side, so a
+    // single node id per path is sufficient (see addToPathIndex).
+    Map<String, Integer> createNodesByPath = new HashMap<>();
+    Map<String, Integer> deleteNodesByPath = new HashMap<>();
+    Map<String, Integer> renameNodesBySourcePath = new HashMap<>();
+    Map<String, Integer> renameNodesByTargetPath = new HashMap<>();
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        addToPathIndex(deleteNodesByPath, entry.getSourcePath(), nodeId);
+      } else {
+        DiffType diffType = entry.getDiffType();
+        if (diffType == DiffType.CREATE) {
+          addToPathIndex(createNodesByPath, entry.getSourcePath(), nodeId);
+        } else if (diffType == DiffType.RENAME) {
+          addToPathIndex(renameNodesBySourcePath, entry.getSourcePath(), nodeId);
+          addToPathIndex(renameNodesByTargetPath, entry.getTargetPath(), nodeId);
+        }
+      }
+    }
+
+    validateRenameTargetDoesNotMatchCreatePath(renameNodesByTargetPath,
+        createNodesByPath);
+
+    addPathConflictEdges(deleteNodesByPath, createNodesByPath,
+        renameNodesByTargetPath);
+    addRenameBeforeCreateEdges(renameNodesBySourcePath, createNodesByPath);
+    addRenameChainEdges(renameNodesBySourcePath, renameNodesByTargetPath);
+    addPathPrefixFromSnapshotEdges(deleteNodesByPath, renameNodesBySourcePath);
+    addPathPrefixToSnapshotEdges(createNodesByPath, renameNodesByTargetPath);
+
+    buildObjectIdGroups();
+    addIntraObjectRenameEdges();
+
+    groupObjectIds = null;
+    groupOffsets = null;
+    groupNodes = null;
+  }
+
+  /**
+   * Groups node ids by objectId into primitive arrays for intra-object RENAME
+   * ordering. objectIds are sorted and de-duplicated so the matching node ids
+   * for one objectId are the slice of {@link #groupNodes} delimited by
+   * {@link #groupOffsets}.
+   */
+  private void buildObjectIdGroups() {
+    int nodeCount = nodes.size();
+    long[] sorted = new long[nodeCount];
+    for (int i = 0; i < nodeCount; i++) {
+      sorted[i] = nodes.get(i).getObjectId();
+    }
+    Arrays.sort(sorted);
+
+    int uniqueCount = 0;
+    long previous = 0L;
+    for (int i = 0; i < nodeCount; i++) {
+      long objectId = sorted[i];
+      if (uniqueCount == 0 || objectId != previous) {
+        sorted[uniqueCount++] = objectId;
+        previous = objectId;
+      }
+    }
+    groupObjectIds = Arrays.copyOf(sorted, uniqueCount);
+
+    int[] rankByNode = new int[nodeCount];
+    groupOffsets = new int[uniqueCount + 1];
+    for (int i = 0; i < nodeCount; i++) {
+      int rank = Arrays.binarySearch(groupObjectIds, nodes.get(i).getObjectId());
+      rankByNode[i] = rank;
+      groupOffsets[rank + 1]++;
+    }
+    for (int i = 0; i < uniqueCount; i++) {
+      groupOffsets[i + 1] += groupOffsets[i];
+    }
+
+    groupNodes = new int[nodeCount];
+    int[] fillCursor = Arrays.copyOf(groupOffsets, uniqueCount);
+    for (int i = 0; i < nodeCount; i++) {
+      groupNodes[fillCursor[rankByNode[i]]++] = i;
+    }
+  }
+
+  /**
+   * Orders the non-delete entries of a single object relative to its RENAME.
+   * An entry reported at the RENAME source (from-snapshot) path must be applied
+   * before the path is renamed away; an entry reported at the RENAME target
+   * (to-snapshot) path must be applied after the rename creates that path.
+   */
+  private void addIntraObjectRenameEdges() {
+    for (int rank = 0; rank < groupObjectIds.length; rank++) {
+      int start = groupOffsets[rank];
+      int end = groupOffsets[rank + 1];
+      if (end - start < 2) {
+        continue;
+      }
+      int renameNodeId = -1;
+      for (int i = start; i < end; i++) {
+        if (nodes.get(groupNodes[i]).getDiffType() == DiffType.RENAME) {
+          renameNodeId = groupNodes[i];
+          break;
+        }
+      }
+      if (renameNodeId < 0) {
+        continue;
+      }
+      SnapDiffDependencyEntry rename = nodes.get(renameNodeId);
+      for (int i = start; i < end; i++) {
+        int nodeId = groupNodes[i];
+        if (nodeId == renameNodeId) {
+          continue;
+        }
+        String path = nodes.get(nodeId).getSourcePath();
+        if (path == null) {
+          continue;
+        }
+        if (path.equals(rename.getSourcePath())) {
+          addEdge(nodeId, renameNodeId);
+        } else if (path.equals(rename.getTargetPath())) {
+          addEdge(renameNodeId, nodeId);
+        }
+      }
+    }
+  }
+
+  private static void addToPathIndex(Map<String, Integer> pathIndex,
+      String path, int nodeId) {
+    if (path == null) {
+      return;
+    }
+    // At most one object can occupy a path on a given snapshot side, so the
+    // first node wins. A second node on the same path indicates unexpected or
+    // duplicate diff input.
+    Integer existing = pathIndex.putIfAbsent(path, nodeId);
+    if (existing != null) {
+      LOG.debug("Multiple diff entries share path '{}'; keeping node {}, "
+          + "ignoring node {}", path, existing, nodeId);
+    }
+  }
+
+  /**
+   * Orders renames that reuse the same path: the rename whose source frees a
+   * path must precede the rename whose target occupies that same path.
+   */
+  private void addRenameChainEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> sourceEntry :
+        renameNodesBySourcePath.entrySet()) {
+      Integer targetNodeId =
+          renameNodesByTargetPath.get(sourceEntry.getKey());
+      if (targetNodeId != null) {
+        addEdge(sourceEntry.getValue(), targetNodeId);
+      }
+    }
+  }
+
+  private void addPathConflictEdges(Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> createNodesByPath,
+      Map<String, Integer> renameNodesByTargetPath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      String path = deleteEntry.getKey();
+      int deleteNodeId = deleteEntry.getValue();
+      Integer createNodeId = createNodesByPath.get(path);
+      if (createNodeId != null) {
+        addEdge(deleteNodeId, createNodeId);
+      }
+      Integer renameTargetNodeId = renameNodesByTargetPath.get(path);
+      if (renameTargetNodeId != null) {
+        addEdge(deleteNodeId, renameTargetNodeId);
+      }
+    }
+  }
+
+  private void addRenameBeforeCreateEdges(
+      Map<String, Integer> renameNodesBySourcePath,
+      Map<String, Integer> createNodesByPath) {
+    for (Map.Entry<String, Integer> createEntry :
+        createNodesByPath.entrySet()) {
+      Integer renameNodeId =
+          renameNodesBySourcePath.get(createEntry.getKey());
+      if (renameNodeId != null) {
+        addEdge(renameNodeId, createEntry.getValue());
+      }
+    }
+  }
+
+  /**
+   * From-snapshot path-prefix edges. Intermediate directories may be omitted
+   * from the report; ancestor ordering is derived from strict path prefixes.
+   */
+  private void addPathPrefixFromSnapshotEdges(
+      Map<String, Integer> deleteNodesByPath,
+      Map<String, Integer> renameNodesBySourcePath) {
+    for (Map.Entry<String, Integer> deleteEntry :
+        deleteNodesByPath.entrySet()) {
+      int descendantDeleteNodeId = deleteEntry.getValue();
+      forEachStrictPrefix(deleteEntry.getKey(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorDeleteNodeId);
+        }
+        Integer ancestorRenameNodeId =
+            renameNodesBySourcePath.get(ancestorPath);
+        if (ancestorRenameNodeId != null) {
+          addEdge(descendantDeleteNodeId, ancestorRenameNodeId);
+        }
+      });
+    }
+
+    for (int nodeId = 0; nodeId < nodes.size(); nodeId++) {
+      SnapDiffDependencyEntry entry = nodes.get(nodeId);
+      if (entry.isDelete()) {
+        continue;
+      }
+      final int fromNodeId = nodeId;
+      forEachStrictPrefix(entry.getSourcePath(), ancestorPath -> {
+        Integer ancestorDeleteNodeId = deleteNodesByPath.get(ancestorPath);
+        if (ancestorDeleteNodeId != null) {
+          addEdge(fromNodeId, ancestorDeleteNodeId);
+        }
+      });

Review Comment:
   Yeah, I found the same issues when I did a self review. Addressing them now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "jojochuang (via GitHub)" <gi...@apache.org>.
jojochuang commented on PR #10778:
URL: https://github.com/apache/ozone/pull/10778#issuecomment-5064178365

   ## Potential issue: same-object RENAME/MODIFY are not ordered
   
   `SnapDiffDependencyGraph` indexes multiple non-delete nodes per `objectId` (e.g. a `RENAME` + a `MODIFY` for the same object), but it never adds an edge **between** those entries. Topological sort can therefore emit the `RENAME` before a `MODIFY` that is reported at the from-snapshot (pre-rename) source path — and once the path has been renamed away, that `MODIFY` can no longer be applied at its reported path.
   
   ### Concrete example
   
   Object `2` under dir `1`, from `parent/a.txt` (v1) to `parent/b.txt` (v2) — renamed **and** modified. Snapdiff emits, with `MODIFY` at the from-snapshot path:
   
   ```
   RENAME  source="parent/a.txt"  target="parent/b.txt"   (objectId=2, parent=1)
   MODIFY  source="parent/a.txt"                          (objectId=2, parent=1)
   ```
   
   No edge links the two nodes, so both have `inDegree == 0` and Kahn's sort emits them in input order: `[RENAME, MODIFY]`. A consumer then renames `parent/a.txt -> parent/b.txt` and tries to modify the now-nonexistent `parent/a.txt`. Correct order is `[MODIFY, RENAME]`.
   
   Note the existing `testModifyAndRenameForSameObjectKeepDependencyOrder` does not catch this: it only asserts the parent `CREATE` is first and that the two tail entries share `objectId == 2` — it never asserts the RENAME-vs-MODIFY relative order, and its data uses `MODIFY` at the rename *target* path.
   
   ### Reproduction test (fails on current code)
   
   ```java
   @Test
   void testModifyAtSourcePathOrderedBeforeRename() {
     List<SnapDiffDependencyEntry> entries = Arrays.asList(
         entry(2L, 1L, RENAME, "parent/a.txt", "parent/b.txt"),
         entry(2L, 1L, MODIFY, "parent/a.txt"));
   
     List<DiffType> orderedTypes = toDiffTypes(sort(entries));
     assertEquals(Arrays.asList(MODIFY, RENAME), orderedTypes);
   }
   ```
   
   ```
   expected: <[MODIFY, RENAME]> but was: <[RENAME, MODIFY]>
   ```
   
   ### Suggested fix
   
   Add an intra-object edge oriented by which path the entry carries: an entry at the RENAME **source** path must precede the RENAME; the RENAME must precede an entry at its **target** path. With that edge, the reproduction test and all existing `TestSnapDiffDependencyGraph` cases pass (11/11).
   
   I pushed a candidate fix + the reproduction test to a branch for reference:
   https://github.com/jojochuang/ozone/tree/HDDS-15390-rename-modify-order-fix
   
   _Found via automated review (Cursor Bugbot)._


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10778:
URL: https://github.com/apache/ozone/pull/10778#discussion_r3725184489


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/SnapDiffDependencyGraph.java:
##########
@@ -0,0 +1,569 @@
+/*
+ * 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.snapshot;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
+import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Directed graph of snapshot diff entries and Kahn topological sort for
+ * dependency-ordered report emission.
+ *
+ * <p>Dependency rules encoded by edges (edge {@code u -> v} means {@code u}
+ * must appear before {@code v}):
+ * <ul>
+ *   <li>Descendant DELETE before ancestor DELETE or RENAME(source), using
+ *       strict source-path prefixes when intermediate directories are omitted
+ *       from the report.</li>
+ *   <li>Descendant non-delete before ancestor DELETE on a strict source-path
+ *       prefix.</li>
+ *   <li>Ancestor CREATE/RENAME(target) before descendant CREATE/RENAME/MODIFY
+ *       on a strict to-snapshot path prefix.</li>
+ *   <li>DELETE before CREATE/RENAME(target) that targets the same path.</li>
+ *   <li>RENAME(source) before CREATE that reuses the rename source path.</li>
+ *   <li>RENAME(source) before RENAME(target) that reuses the same path, so a
+ *       path is freed before another rename occupies it.</li>
+ *   <li>For the same object, an entry at the RENAME source path before the
+ *       RENAME, and the RENAME before an entry at its target path.</li>
+ *   <li>A RENAME target path cannot match a CREATE path in the same diff
+ *       report; such input is rejected with {@link IllegalStateException}.</li>
+ * </ul>
+ */
+public final class SnapDiffDependencyGraph {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(SnapDiffDependencyGraph.class);
+
+  private static final int INITIAL_EDGE_CAPACITY = 16;
+  private static final int[] EMPTY_INT_ARRAY = new int[0];
+  // Hotspot/OpenJDK cap the largest array a little below Integer.MAX_VALUE.
+  // Node and edge counts are assumed to fit in int; the configured changed-key
+  // limit (one billion) is well below this bound.
+  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
+  private static final char PATH_SEPARATOR = '/';
+
+  private final List<SnapDiffDependencyEntry> nodes = new ArrayList<>();
+
+  // Edges collected during construction, each encoded as (from << 32 | to).
+  // Deduplicated and compacted into the CSR arrays below by buildCsr(), then
+  // released so the graph keeps only the primitive adjacency.
+  private long[] edges = new long[INITIAL_EDGE_CAPACITY];
+  private int edgeCount;
+
+  // Compressed sparse row adjacency. The out-edges of node i are the targets
+  // adjTargets[adjOffsets[i] .. adjOffsets[i + 1]).
+  private int[] adjOffsets;
+  private int[] adjTargets;
+  private int[] inDegree;
+
+  // Construction-only grouping of node ids by objectId for intra-object
+  // RENAME ordering. Released once edges are built.
+  private long[] groupObjectIds;
+  private int[] groupOffsets;
+  private int[] groupNodes;
+
+  /**
+   * @throws IllegalStateException if entries contain a RENAME target path that
+   *     matches a CREATE path, or if dependency edges form a cycle
+   */
+  public SnapDiffDependencyGraph(List<SnapDiffDependencyEntry> entries) {
+    nodes.addAll(entries);
+    buildDependencyEdges();
+    buildCsr();
+  }
+
+  /**
+   * Returns entries in dependency order using Kahn's algorithm.
+   *
+   * @return topologically sorted dependency entries
+   * @throws IllegalStateException if the graph contains a cycle
+   */
+  public List<SnapDiffDependencyEntry> getOrderedEntries() {
+    int nodeCount = nodes.size();
+    // Work on a local copy of the in-degrees so the method is idempotent and
+    // does not mutate the graph's shared state.
+    int[] remainingInDegree = Arrays.copyOf(inDegree, nodeCount);
+    // Split the ready set into two ring buffers so that, among nodes whose
+    // dependencies are already satisfied, DELETEs are emitted before other
+    // types. This retains the baseline "deletes first" ordering wherever the
+    // dependency edges leave the order free. Each node is enqueued at most
+    // once, so buffers sized to the node count are large enough.
+    int[] deleteReady = new int[nodeCount];
+    int[] otherReady = new int[nodeCount];

Review Comment:
   Yes, the memory footprint can become large for large diffs. The 1B changed keys limit is currently being checked against the total estimated keys in the delta file set to decide whether the snapshot diff can be accepted/rejected. 
   I propose we add another guardrail limiting the number of actual diff entries to 1M in order to be eligible for in-memory dependency ordering enforced in [HDDS-15391](https://issues.apache.org/jira/browse/HDDS-15391). (This limit may also be useful in prior stages of the diff to decide whether to spill to disk). 
   As a follow-up task enable RocksDB backed graph for larger diffs and fallback to current order meanwhile.
   What do you think?
   
   More memory optimizations in the latest commit: 
     - Free cached path strings after edge building.                                                                                                                        
     - Presize the four path-index HashMaps to their exact per-category counts.                                                                                
     - Presize the edges buffer to max(INITIAL_EDGE_CAPACITY, nodeCount) so realistic graphs (edge density 3–8 per node) skip most doubling copies.                                                           
     - Rework buildObjectIdGroups to track only objectIds that have a RENAME (the only objectIds that can pick up intra-object edges).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15390. Utility to generate dependency ordered snapdiff report. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on PR #10778:
URL: https://github.com/apache/ozone/pull/10778#issuecomment-5363629259

   Thanks @SaketaChalamchala for the patch. Thanks @jojochuang for the review.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org