You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by dw...@apache.org on 2021/06/01 11:50:38 UTC

[flink] 04/04: [FLINK-22686][checkpointing] Incompatible subtask mappings while resuming from unaligned checkpoints

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

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

commit 4011bde30cf3dee5cccb8eeb0faa7658d77a7f82
Author: Dawid Wysakowicz <dw...@apache.org>
AuthorDate: Thu May 20 08:58:00 2021 +0200

    [FLINK-22686][checkpointing] Incompatible subtask mappings while resuming from unaligned checkpoints
    
    In the initial implementation of rescaling channel data we assumed that
    the subtasks indices are the same for all input gates. This assumptions
    does not hold when there are different partitioners. It can happen e.g.
    in case of a broadcast with a keyed input.
    
    The commit tracks the subtask indices separately for each partition and
    input gate.
    
    This closes #16019
---
 .../InflightDataRescalingDescriptor.java           | 199 +++++++++++------
 .../checkpoint/StateAssignmentOperation.java       |   6 +-
 .../runtime/checkpoint/TaskStateAssignment.java    | 248 +++++++++++++++------
 .../InflightDataRescalingDescriptorUtil.java       |  17 ++
 .../checkpoint/OperatorSubtaskStateTest.java       |   4 +-
 .../checkpoint/StateAssignmentOperationTest.java   | 120 +++++++---
 .../recovery/DemultiplexingRecordDeserializer.java |   5 +-
 .../DemultiplexingRecordDeserializerTest.java      |   8 +-
 .../UnalignedCheckpointRescaleITCase.java          | 157 ++++++++++++-
 9 files changed, 583 insertions(+), 181 deletions(-)

diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptor.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptor.java
index 55a0026..18826d6 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptor.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptor.java
@@ -20,76 +20,41 @@ package org.apache.flink.runtime.checkpoint;
 import java.io.ObjectStreamException;
 import java.io.Serializable;
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.Objects;
 import java.util.Set;
 
 import static org.apache.flink.util.Preconditions.checkNotNull;
 
 /**
- * Captures ambiguous mappings of old channels to new channels.
+ * Captures ambiguous mappings of old channels to new channels for a particular gate or partition.
  *
- * <p>For inputs, this mapping implies the following:
- * <li>
- *
- *     <ul>
- *       {@link #oldSubtaskIndexes} is set when there is a rescale on this task potentially leading
- *       to different key groups. Upstream task has a corresponding {@link
- *       #rescaledChannelsMappings} where it sends data over virtual channel while specifying the
- *       channel index in the VirtualChannelSelector. This subtask then demultiplexes over the
- *       virtual subtask index.
- * </ul>
- *
- * <ul>
- *   {@link #rescaledChannelsMappings} is set when there is a downscale of the upstream task.
- *   Upstream task has a corresponding {@link #oldSubtaskIndexes} where it sends data over virtual
- *   channel while specifying the subtask index in the VirtualChannelSelector. This subtask then
- *   demultiplexes over channel indexes.
- * </ul>
- *
- * <p>For outputs, it's vice-versa. The information must be kept in sync but they are used in
- * opposite ways for multiplexing/demultiplexing.
- *
- * <p>Note that in the common rescaling case both information is set and need to be simultaneously
- * used. If the input subtask subsumes the state of 3 old subtasks and a channel corresponds to 2
- * old channels, then there are 6 virtual channels to be demultiplexed.
+ * @see InflightDataGateOrPartitionRescalingDescriptor
  */
 public class InflightDataRescalingDescriptor implements Serializable {
+
     public static final InflightDataRescalingDescriptor NO_RESCALE = new NoRescalingDescriptor();
 
     private static final long serialVersionUID = -3396674344669796295L;
 
     /** Set when several operator instances are merged into one. */
-    private final int[] oldSubtaskIndexes;
-
-    /**
-     * Set when channels are merged because the connected operator has been rescaled for each
-     * gate/partition.
-     */
-    private final RescaleMappings[] rescaledChannelsMappings;
-
-    /** All channels where upstream duplicates data (only valid for downstream mappings). */
-    private final Set<Integer> ambiguousSubtaskIndexes;
+    private final InflightDataGateOrPartitionRescalingDescriptor[] gateOrPartitionDescriptors;
 
     public InflightDataRescalingDescriptor(
-            int[] oldSubtaskIndexes,
-            RescaleMappings[] rescaledChannelsMappings,
-            Set<Integer> ambiguousSubtaskIndexes) {
-        this.oldSubtaskIndexes = checkNotNull(oldSubtaskIndexes);
-        this.rescaledChannelsMappings = checkNotNull(rescaledChannelsMappings);
-        this.ambiguousSubtaskIndexes = checkNotNull(ambiguousSubtaskIndexes);
+            InflightDataGateOrPartitionRescalingDescriptor[] gateOrPartitionDescriptors) {
+        this.gateOrPartitionDescriptors = checkNotNull(gateOrPartitionDescriptors);
     }
 
-    public int[] getOldSubtaskIndexes() {
-        return oldSubtaskIndexes;
+    public int[] getOldSubtaskIndexes(int gateOrPartitionIndex) {
+        return gateOrPartitionDescriptors[gateOrPartitionIndex].oldSubtaskIndexes;
     }
 
     public RescaleMappings getChannelMapping(int gateOrPartitionIndex) {
-        return rescaledChannelsMappings[gateOrPartitionIndex];
+        return gateOrPartitionDescriptors[gateOrPartitionIndex].rescaledChannelsMappings;
     }
 
-    public boolean isAmbiguous(int oldSubtaskIndex) {
-        return ambiguousSubtaskIndexes.contains(oldSubtaskIndex);
+    public boolean isAmbiguous(int gateOrPartitionIndex, int oldSubtaskIndex) {
+        return gateOrPartitionDescriptors[gateOrPartitionIndex].ambiguousSubtaskIndexes.contains(
+                oldSubtaskIndex);
     }
 
     @Override
@@ -101,36 +66,136 @@ public class InflightDataRescalingDescriptor implements Serializable {
             return false;
         }
         InflightDataRescalingDescriptor that = (InflightDataRescalingDescriptor) o;
-        return Arrays.equals(oldSubtaskIndexes, that.oldSubtaskIndexes)
-                && Arrays.equals(rescaledChannelsMappings, that.rescaledChannelsMappings)
-                && Objects.equals(ambiguousSubtaskIndexes, that.ambiguousSubtaskIndexes);
+        return Arrays.equals(gateOrPartitionDescriptors, that.gateOrPartitionDescriptors);
     }
 
     @Override
     public int hashCode() {
-        int result = Objects.hash(ambiguousSubtaskIndexes);
-        result = 31 * result + Arrays.hashCode(oldSubtaskIndexes);
-        result = 31 * result + Arrays.hashCode(rescaledChannelsMappings);
-        return result;
+        return Arrays.hashCode(gateOrPartitionDescriptors);
     }
 
     @Override
     public String toString() {
         return "InflightDataRescalingDescriptor{"
-                + "oldSubtaskIndexes="
-                + Arrays.toString(oldSubtaskIndexes)
-                + ", rescaledChannelsMappings="
-                + Arrays.toString(rescaledChannelsMappings)
-                + ", ambiguousSubtaskIndexes="
-                + ambiguousSubtaskIndexes
+                + "gateOrPartitionDescriptors="
+                + Arrays.toString(gateOrPartitionDescriptors)
                 + '}';
     }
 
+    /**
+     * Captures ambiguous mappings of old channels to new channels.
+     *
+     * <p>For inputs, this mapping implies the following:
+     * <li>
+     *
+     *     <ul>
+     *       {@link #oldSubtaskIndexes} is set when there is a rescale on this task potentially
+     *       leading to different key groups. Upstream task has a corresponding {@link
+     *       #rescaledChannelsMappings} where it sends data over virtual channel while specifying
+     *       the channel index in the VirtualChannelSelector. This subtask then demultiplexes over
+     *       the virtual subtask index.
+     * </ul>
+     *
+     * <ul>
+     *   {@link #rescaledChannelsMappings} is set when there is a downscale of the upstream task.
+     *   Upstream task has a corresponding {@link #oldSubtaskIndexes} where it sends data over
+     *   virtual channel while specifying the subtask index in the VirtualChannelSelector. This
+     *   subtask then demultiplexes over channel indexes.
+     * </ul>
+     *
+     * <p>For outputs, it's vice-versa. The information must be kept in sync but they are used in
+     * opposite ways for multiplexing/demultiplexing.
+     *
+     * <p>Note that in the common rescaling case both information is set and need to be
+     * simultaneously used. If the input subtask subsumes the state of 3 old subtasks and a channel
+     * corresponds to 2 old channels, then there are 6 virtual channels to be demultiplexed.
+     */
+    public static class InflightDataGateOrPartitionRescalingDescriptor implements Serializable {
+
+        private static final long serialVersionUID = 1L;
+
+        /** Set when several operator instances are merged into one. */
+        private final int[] oldSubtaskIndexes;
+
+        /**
+         * Set when channels are merged because the connected operator has been rescaled for each
+         * gate/partition.
+         */
+        private final RescaleMappings rescaledChannelsMappings;
+
+        /** All channels where upstream duplicates data (only valid for downstream mappings). */
+        private final Set<Integer> ambiguousSubtaskIndexes;
+
+        private final Rescaling rescaling;
+
+        enum Rescaling {
+            IDENTITY,
+            RESCALING
+        }
+
+        public InflightDataGateOrPartitionRescalingDescriptor(
+                int[] oldSubtaskIndexes,
+                RescaleMappings rescaledChannelsMappings,
+                Set<Integer> ambiguousSubtaskIndexes,
+                Rescaling rescaling) {
+            this.oldSubtaskIndexes = oldSubtaskIndexes;
+            this.rescaledChannelsMappings = rescaledChannelsMappings;
+            this.ambiguousSubtaskIndexes = ambiguousSubtaskIndexes;
+            this.rescaling = rescaling;
+        }
+
+        public boolean isIdentity() {
+            return rescaling == Rescaling.IDENTITY;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+            InflightDataGateOrPartitionRescalingDescriptor that =
+                    (InflightDataGateOrPartitionRescalingDescriptor) o;
+            return Arrays.equals(oldSubtaskIndexes, that.oldSubtaskIndexes)
+                    && Objects.equals(rescaledChannelsMappings, that.rescaledChannelsMappings)
+                    && Objects.equals(ambiguousSubtaskIndexes, that.ambiguousSubtaskIndexes)
+                    && rescaling == that.rescaling;
+        }
+
+        @Override
+        public int hashCode() {
+            int result = Objects.hash(rescaledChannelsMappings, ambiguousSubtaskIndexes, rescaling);
+            result = 31 * result + Arrays.hashCode(oldSubtaskIndexes);
+            return result;
+        }
+
+        @Override
+        public String toString() {
+            return "InflightDataGateOrPartitionRescalingDescriptor{"
+                    + "oldSubtaskIndexes="
+                    + Arrays.toString(oldSubtaskIndexes)
+                    + ", rescaledChannelsMappings="
+                    + rescaledChannelsMappings
+                    + ", ambiguousSubtaskIndexes="
+                    + ambiguousSubtaskIndexes
+                    + ", rescaling="
+                    + rescaling
+                    + '}';
+        }
+    }
+
     private static class NoRescalingDescriptor extends InflightDataRescalingDescriptor {
-        private static final long serialVersionUID = -5544173933105855751L;
+        private static final long serialVersionUID = 1L;
 
         public NoRescalingDescriptor() {
-            super(new int[0], new RescaleMappings[0], Collections.emptySet());
+            super(new InflightDataGateOrPartitionRescalingDescriptor[0]);
+        }
+
+        @Override
+        public int[] getOldSubtaskIndexes(int gateOrPartitionIndex) {
+            return new int[0];
         }
 
         @Override
@@ -138,13 +203,13 @@ public class InflightDataRescalingDescriptor implements Serializable {
             return RescaleMappings.SYMMETRIC_IDENTITY;
         }
 
-        private Object readResolve() throws ObjectStreamException {
-            return NO_RESCALE;
+        @Override
+        public boolean isAmbiguous(int gateOrPartitionIndex, int oldSubtaskIndex) {
+            return false;
         }
 
-        @Override
-        public String toString() {
-            return "NoRescalingDescriptor";
+        private Object readResolve() throws ObjectStreamException {
+            return NO_RESCALE;
         }
     }
 }
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StateAssignmentOperation.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StateAssignmentOperation.java
index 42d7edf..a9e667a 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StateAssignmentOperation.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StateAssignmentOperation.java
@@ -361,7 +361,8 @@ public class StateAssignmentOperation {
                                     ResultSubpartitionInfo::getPartitionIdx,
                                     partitionIndex);
             final MappingBasedRepartitioner<ResultSubpartitionStateHandle> repartitioner =
-                    new MappingBasedRepartitioner<>(assignment.getOutputMapping(partitionIndex));
+                    new MappingBasedRepartitioner<>(
+                            assignment.getOutputMapping(partitionIndex).getRescaleMappings());
             final Map<OperatorInstanceID, List<ResultSubpartitionStateHandle>> repartitioned =
                     applyRepartitioner(
                             assignment.outputOperatorID,
@@ -406,7 +407,8 @@ public class StateAssignmentOperation {
         // subtask 0 recovers data from old subtask 0 + 1 and subtask 1 recovers data from old
         // subtask 0 + 2
         for (int gateIndex = 0; gateIndex < inputs.size(); gateIndex++) {
-            final RescaleMappings mapping = stateAssignment.getInputMapping(gateIndex);
+            final RescaleMappings mapping =
+                    stateAssignment.getInputMapping(gateIndex).getRescaleMappings();
 
             final List<List<InputChannelStateHandle>> gateState =
                     inputs.size() == 1
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/TaskStateAssignment.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/TaskStateAssignment.java
index 283d131..e21cb98 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/TaskStateAssignment.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/TaskStateAssignment.java
@@ -18,6 +18,8 @@
 package org.apache.flink.runtime.checkpoint;
 
 import org.apache.flink.runtime.OperatorIDPair;
+import org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor.InflightDataGateOrPartitionRescalingDescriptor;
+import org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor.InflightDataGateOrPartitionRescalingDescriptor.Rescaling;
 import org.apache.flink.runtime.executiongraph.ExecutionJobVertex;
 import org.apache.flink.runtime.executiongraph.IntermediateResult;
 import org.apache.flink.runtime.io.network.api.writer.SubtaskStateMapper;
@@ -33,6 +35,7 @@ import org.apache.flink.runtime.state.StateObject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 
 import java.util.Arrays;
@@ -40,10 +43,11 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.Optional;
 import java.util.Set;
-import java.util.function.BooleanSupplier;
+import java.util.function.BiFunction;
 import java.util.function.Function;
-import java.util.function.Supplier;
+import java.util.stream.IntStream;
 
 import static java.util.Collections.emptySet;
 import static org.apache.flink.util.Preconditions.checkNotNull;
@@ -73,14 +77,9 @@ class TaskStateAssignment {
     final Map<OperatorInstanceID, List<InputChannelStateHandle>> inputChannelStates;
     final Map<OperatorInstanceID, List<ResultSubpartitionStateHandle>> resultSubpartitionStates;
     /** The subtask mapping when the output operator was rescaled. */
-    @Nullable private RescaleMappings outputSubtaskMappings;
+    private final Map<Integer, SubtasksRescaleMapping> outputSubtaskMappings = new HashMap<>();
     /** The subtask mapping when the input operator was rescaled. */
-    @Nullable private RescaleMappings inputSubtaskMappings;
-    /**
-     * If channel data cannot be safely divided into subtasks (several new subtask indexes are
-     * associated with the same old subtask index). Mostly used for range partitioners.
-     */
-    boolean mayHaveAmbiguousSubtasks;
+    private final Map<Integer, SubtasksRescaleMapping> inputSubtaskMappings = new HashMap<>();
 
     @Nullable private TaskStateAssignment[] downstreamAssignments;
     @Nullable private TaskStateAssignment[] upstreamAssignments;
@@ -134,6 +133,11 @@ class TaskStateAssignment {
         return downstreamAssignments;
     }
 
+    private static int getAssignmentIndex(
+            TaskStateAssignment[] assignments, TaskStateAssignment assignment) {
+        return Arrays.asList(assignments).indexOf(assignment);
+    }
+
     public TaskStateAssignment[] getUpstreamAssignments() {
         if (upstreamAssignments == null) {
             upstreamAssignments =
@@ -166,32 +170,41 @@ class TaskStateAssignment {
                                 instanceID,
                                 inputOperatorID,
                                 getUpstreamAssignments(),
-                                assignment -> assignment.outputSubtaskMappings,
-                                assignment ->
-                                        assignment.getOutputMapping(
-                                                Arrays.asList(assignment.getDownstreamAssignments())
-                                                        .indexOf(this)),
+                                (assignment, recompute) -> {
+                                    int assignmentIndex =
+                                            getAssignmentIndex(
+                                                    assignment.getDownstreamAssignments(), this);
+                                    return assignment.getOutputMapping(assignmentIndex, recompute);
+                                },
                                 inputSubtaskMappings,
-                                () -> getInputMapping(0),
-                                inputState,
-                                () -> mayHaveAmbiguousSubtasks))
+                                this::getInputMapping))
                 .setOutputRescalingDescriptor(
                         createRescalingDescriptor(
                                 instanceID,
                                 outputOperatorID,
                                 getDownstreamAssignments(),
-                                assignment -> assignment.inputSubtaskMappings,
-                                assignment ->
-                                        assignment.getInputMapping(
-                                                Arrays.asList(assignment.getUpstreamAssignments())
-                                                        .indexOf(this)),
+                                (assignment, recompute) -> {
+                                    int assignmentIndex =
+                                            getAssignmentIndex(
+                                                    assignment.getUpstreamAssignments(), this);
+                                    return assignment.getInputMapping(assignmentIndex, recompute);
+                                },
                                 outputSubtaskMappings,
-                                () -> getOutputMapping(0),
-                                outputState,
-                                () -> false))
+                                this::getOutputMapping))
                 .build();
     }
 
+    private InflightDataGateOrPartitionRescalingDescriptor log(
+            InflightDataGateOrPartitionRescalingDescriptor descriptor, int subtask, int partition) {
+        LOG.debug(
+                "created {} for task={} subtask={} partition={}",
+                descriptor,
+                executionJobVertex.getName(),
+                subtask,
+                partition);
+        return descriptor;
+    }
+
     private InflightDataRescalingDescriptor log(
             InflightDataRescalingDescriptor descriptor, int subtask) {
         LOG.debug(
@@ -206,60 +219,104 @@ class TaskStateAssignment {
             OperatorInstanceID instanceID,
             OperatorID expectedOperatorID,
             TaskStateAssignment[] connectedAssignments,
-            Function<TaskStateAssignment, RescaleMappings> mappingRetriever,
-            Function<TaskStateAssignment, RescaleMappings> mappingCalculator,
-            @Nullable RescaleMappings subtaskMappings,
-            Supplier<RescaleMappings> subtaskMappingCalculator,
-            StateObjectCollection<?> state,
-            BooleanSupplier mayHaveAmbiguousSubtasks) {
+            BiFunction<TaskStateAssignment, Boolean, SubtasksRescaleMapping> mappingRetriever,
+            Map<Integer, SubtasksRescaleMapping> subtaskGateOrPartitionMappings,
+            Function<Integer, SubtasksRescaleMapping> subtaskMappingCalculator) {
         if (!expectedOperatorID.equals(instanceID.getOperatorId())) {
             return InflightDataRescalingDescriptor.NO_RESCALE;
         }
 
-        RescaleMappings[] rescaledChannelsMappings =
+        SubtasksRescaleMapping[] rescaledChannelsMappings =
                 Arrays.stream(connectedAssignments)
-                        .map(mappingRetriever)
-                        .toArray(RescaleMappings[]::new);
+                        .map(assignment -> mappingRetriever.apply(assignment, false))
+                        .toArray(SubtasksRescaleMapping[]::new);
 
         // no state on input and output, especially for any aligned checkpoint
-        if (subtaskMappings == null
+        if (subtaskGateOrPartitionMappings.isEmpty()
                 && Arrays.stream(rescaledChannelsMappings).allMatch(Objects::isNull)) {
             return InflightDataRescalingDescriptor.NO_RESCALE;
         }
 
-        // no state for this assignment, but state on connected assignment
-        if (subtaskMappings == null) {
-            // calculate subtask mapping now
-            subtaskMappings = subtaskMappingCalculator.get();
-        }
-        int[] oldSubtaskInstances = subtaskMappings.getMappedIndexes(instanceID.getSubtaskId());
-        // No old task is mapped, so no data at all.
-        if (oldSubtaskInstances.length == 0) {
-            checkState(state.isEmpty(), "Unmapped new subtask should not have any state assigned");
+        InflightDataGateOrPartitionRescalingDescriptor[] gateOrPartitionDescriptors =
+                createGateOrPartitionRescalingDescriptors(
+                        instanceID,
+                        connectedAssignments,
+                        assignment -> mappingRetriever.apply(assignment, true),
+                        subtaskGateOrPartitionMappings,
+                        subtaskMappingCalculator,
+                        rescaledChannelsMappings);
+
+        if (Arrays.stream(gateOrPartitionDescriptors)
+                .allMatch(InflightDataGateOrPartitionRescalingDescriptor::isIdentity)) {
             return log(InflightDataRescalingDescriptor.NO_RESCALE, instanceID.getSubtaskId());
+        } else {
+            return log(
+                    new InflightDataRescalingDescriptor(gateOrPartitionDescriptors),
+                    instanceID.getSubtaskId());
         }
+    }
 
-        for (int partition = 0; partition < rescaledChannelsMappings.length; partition++) {
-            if (rescaledChannelsMappings[partition] == null) {
-                rescaledChannelsMappings[partition] =
-                        mappingCalculator.apply(connectedAssignments[partition]);
-            }
-        }
+    private InflightDataGateOrPartitionRescalingDescriptor[]
+            createGateOrPartitionRescalingDescriptors(
+                    OperatorInstanceID instanceID,
+                    TaskStateAssignment[] connectedAssignments,
+                    Function<TaskStateAssignment, SubtasksRescaleMapping> mappingCalculator,
+                    Map<Integer, SubtasksRescaleMapping> subtaskGateOrPartitionMappings,
+                    Function<Integer, SubtasksRescaleMapping> subtaskMappingCalculator,
+                    SubtasksRescaleMapping[] rescaledChannelsMappings) {
+        return IntStream.range(0, rescaledChannelsMappings.length)
+                .mapToObj(
+                        partition -> {
+                            TaskStateAssignment connectedAssignment =
+                                    connectedAssignments[partition];
+                            SubtasksRescaleMapping rescaleMapping =
+                                    Optional.ofNullable(rescaledChannelsMappings[partition])
+                                            .orElseGet(
+                                                    () ->
+                                                            mappingCalculator.apply(
+                                                                    connectedAssignment));
+                            SubtasksRescaleMapping subtaskMapping =
+                                    Optional.ofNullable(
+                                                    subtaskGateOrPartitionMappings.get(partition))
+                                            .orElseGet(
+                                                    () ->
+                                                            subtaskMappingCalculator.apply(
+                                                                    partition));
+                            return getInflightDataGateOrPartitionRescalingDescriptor(
+                                    instanceID, partition, rescaleMapping, subtaskMapping);
+                        })
+                .toArray(InflightDataGateOrPartitionRescalingDescriptor[]::new);
+    }
 
-        // no scaling or simple scale-up without the need of virtual channels.
-        if (subtaskMappings.isIdentity()
-                && Arrays.stream(rescaledChannelsMappings).allMatch(RescaleMappings::isIdentity)) {
-            return log(InflightDataRescalingDescriptor.NO_RESCALE, instanceID.getSubtaskId());
-        }
+    private InflightDataGateOrPartitionRescalingDescriptor
+            getInflightDataGateOrPartitionRescalingDescriptor(
+                    OperatorInstanceID instanceID,
+                    int partition,
+                    SubtasksRescaleMapping rescaleMapping,
+                    SubtasksRescaleMapping subtaskMapping) {
+
+        int[] oldSubtaskInstances =
+                subtaskMapping.rescaleMappings.getMappedIndexes(instanceID.getSubtaskId());
+
+        // no scaling or simple scale-up without the need of virtual
+        // channels.
+        boolean isIdentity =
+                (subtaskMapping.rescaleMappings.isIdentity()
+                                && rescaleMapping.getRescaleMappings().isIdentity())
+                        || oldSubtaskInstances.length == 0;
 
         final Set<Integer> ambiguousSubtasks =
-                mayHaveAmbiguousSubtasks.getAsBoolean()
-                        ? subtaskMappings.getAmbiguousTargets()
+                subtaskMapping.mayHaveAmbiguousSubtasks
+                        ? subtaskMapping.rescaleMappings.getAmbiguousTargets()
                         : emptySet();
         return log(
-                new InflightDataRescalingDescriptor(
-                        oldSubtaskInstances, rescaledChannelsMappings, ambiguousSubtasks),
-                instanceID.getSubtaskId());
+                new InflightDataGateOrPartitionRescalingDescriptor(
+                        oldSubtaskInstances,
+                        rescaleMapping.getRescaleMappings(),
+                        ambiguousSubtasks,
+                        isIdentity ? Rescaling.IDENTITY : Rescaling.RESCALING),
+                instanceID.getSubtaskId(),
+                partition);
     }
 
     private <T extends StateObject> StateObjectCollection<T> getState(
@@ -269,7 +326,25 @@ class TaskStateAssignment {
         return value != null ? new StateObjectCollection<>(value) : StateObjectCollection.empty();
     }
 
-    public RescaleMappings getOutputMapping(int partitionIndex) {
+    private SubtasksRescaleMapping getOutputMapping(int assignmentIndex, boolean recompute) {
+        SubtasksRescaleMapping mapping = outputSubtaskMappings.get(assignmentIndex);
+        if (recompute && mapping == null) {
+            return getOutputMapping(assignmentIndex);
+        } else {
+            return mapping;
+        }
+    }
+
+    private SubtasksRescaleMapping getInputMapping(int assignmentIndex, boolean recompute) {
+        SubtasksRescaleMapping mapping = inputSubtaskMappings.get(assignmentIndex);
+        if (recompute && mapping == null) {
+            return getInputMapping(assignmentIndex);
+        } else {
+            return mapping;
+        }
+    }
+
+    public SubtasksRescaleMapping getOutputMapping(int partitionIndex) {
         final TaskStateAssignment downstreamAssignment = getDownstreamAssignments()[partitionIndex];
         final IntermediateResult output = executionJobVertex.getProducedDataSets()[partitionIndex];
         final int gateIndex = downstreamAssignment.executionJobVertex.getInputs().indexOf(output);
@@ -286,11 +361,13 @@ class TaskStateAssignment {
         final RescaleMappings mapping =
                 mapper.getNewToOldSubtasksMapping(
                         oldState.get(outputOperatorID).getParallelism(), newParallelism);
-        outputSubtaskMappings = checkSubtaskMapping(outputSubtaskMappings, mapping);
-        return outputSubtaskMappings;
+        return outputSubtaskMappings.compute(
+                partitionIndex,
+                (idx, oldMapping) ->
+                        checkSubtaskMapping(oldMapping, mapping, mapper.isAmbiguous()));
     }
 
-    public RescaleMappings getInputMapping(int gateIndex) {
+    public SubtasksRescaleMapping getInputMapping(int gateIndex) {
         final SubtaskStateMapper mapper =
                 checkNotNull(
                         executionJobVertex
@@ -303,9 +380,10 @@ class TaskStateAssignment {
                 mapper.getNewToOldSubtasksMapping(
                         oldState.get(inputOperatorID).getParallelism(), newParallelism);
 
-        inputSubtaskMappings = checkSubtaskMapping(inputSubtaskMappings, mapping);
-        mayHaveAmbiguousSubtasks |= mapper.isAmbiguous();
-        return inputSubtaskMappings;
+        return inputSubtaskMappings.compute(
+                gateIndex,
+                (idx, oldMapping) ->
+                        checkSubtaskMapping(oldMapping, mapping, mapper.isAmbiguous()));
     }
 
     @Override
@@ -313,12 +391,14 @@ class TaskStateAssignment {
         return "TaskStateAssignment for " + executionJobVertex.getName();
     }
 
-    private static RescaleMappings checkSubtaskMapping(
-            @Nullable RescaleMappings oldMapping, RescaleMappings mapping) {
+    private static @Nonnull SubtasksRescaleMapping checkSubtaskMapping(
+            @Nullable SubtasksRescaleMapping oldMapping,
+            RescaleMappings mapping,
+            boolean mayHaveAmbiguousSubtasks) {
         if (oldMapping == null) {
-            return mapping;
+            return new SubtasksRescaleMapping(mapping, mayHaveAmbiguousSubtasks);
         }
-        if (!oldMapping.equals(mapping)) {
+        if (!oldMapping.rescaleMappings.equals(mapping)) {
             throw new IllegalStateException(
                     "Incompatible subtask mappings: are multiple operators "
                             + "ingesting/producing intermediate results with varying degrees of parallelism?"
@@ -328,6 +408,30 @@ class TaskStateAssignment {
                             + mapping
                             + ".");
         }
-        return oldMapping;
+        return new SubtasksRescaleMapping(
+                mapping, oldMapping.mayHaveAmbiguousSubtasks || mayHaveAmbiguousSubtasks);
+    }
+
+    static class SubtasksRescaleMapping {
+        private final RescaleMappings rescaleMappings;
+        /**
+         * If channel data cannot be safely divided into subtasks (several new subtask indexes are
+         * associated with the same old subtask index). Mostly used for range partitioners.
+         */
+        private final boolean mayHaveAmbiguousSubtasks;
+
+        private SubtasksRescaleMapping(
+                RescaleMappings rescaleMappings, boolean mayHaveAmbiguousSubtasks) {
+            this.rescaleMappings = rescaleMappings;
+            this.mayHaveAmbiguousSubtasks = mayHaveAmbiguousSubtasks;
+        }
+
+        public RescaleMappings getRescaleMappings() {
+            return rescaleMappings;
+        }
+
+        public boolean isMayHaveAmbiguousSubtasks() {
+            return mayHaveAmbiguousSubtasks;
+        }
     }
 }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptorUtil.java b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptorUtil.java
index cc432ee..77daee0 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptorUtil.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptorUtil.java
@@ -17,6 +17,9 @@
 
 package org.apache.flink.runtime.checkpoint;
 
+import org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor.InflightDataGateOrPartitionRescalingDescriptor;
+import org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor.InflightDataGateOrPartitionRescalingDescriptor.Rescaling;
+
 import org.apache.flink.shaded.guava18.com.google.common.collect.Sets;
 
 import java.util.Arrays;
@@ -45,4 +48,18 @@ public class InflightDataRescalingDescriptorUtil {
     public static <T> Set<T> set(T... elements) {
         return Sets.newHashSet(elements);
     }
+
+    public static InflightDataRescalingDescriptor rescalingDescriptor(
+            int[] oldIndices, RescaleMappings[] mappings, Set<Integer> ambiguousSubtasks) {
+        return new InflightDataRescalingDescriptor(
+                Arrays.stream(mappings)
+                        .map(
+                                mapping ->
+                                        new InflightDataGateOrPartitionRescalingDescriptor(
+                                                oldIndices,
+                                                mapping,
+                                                ambiguousSubtasks,
+                                                Rescaling.RESCALING))
+                        .toArray(InflightDataGateOrPartitionRescalingDescriptor[]::new));
+    }
 }
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/OperatorSubtaskStateTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/OperatorSubtaskStateTest.java
index a764c76..32901c3 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/OperatorSubtaskStateTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/OperatorSubtaskStateTest.java
@@ -86,12 +86,12 @@ public class OperatorSubtaskStateTest {
                                 StateObjectCollection.singleton(
                                         createNewResultSubpartitionStateHandle(3, random)))
                         .setInputRescalingDescriptor(
-                                new InflightDataRescalingDescriptor(
+                                InflightDataRescalingDescriptorUtil.rescalingDescriptor(
                                         new int[1],
                                         new RescaleMappings[0],
                                         Collections.singleton(1)))
                         .setOutputRescalingDescriptor(
-                                new InflightDataRescalingDescriptor(
+                                InflightDataRescalingDescriptorUtil.rescalingDescriptor(
                                         new int[1],
                                         new RescaleMappings[0],
                                         Collections.singleton(2)))
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/StateAssignmentOperationTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/StateAssignmentOperationTest.java
index 736e7f9..8a8f270 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/StateAssignmentOperationTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/StateAssignmentOperationTest.java
@@ -20,6 +20,7 @@ package org.apache.flink.runtime.checkpoint;
 
 import org.apache.flink.runtime.JobException;
 import org.apache.flink.runtime.OperatorIDPair;
+import org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor.InflightDataGateOrPartitionRescalingDescriptor;
 import org.apache.flink.runtime.client.JobExecutionException;
 import org.apache.flink.runtime.executiongraph.ExecutionGraph;
 import org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils;
@@ -53,20 +54,26 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Random;
+import java.util.Set;
 import java.util.function.Function;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
+import java.util.stream.Stream;
 
 import static java.util.Arrays.asList;
+import static java.util.Collections.emptySet;
 import static java.util.Collections.singletonList;
+import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor.InflightDataGateOrPartitionRescalingDescriptor.Rescaling.RESCALING;
 import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.array;
 import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.mappings;
+import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.rescalingDescriptor;
 import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.set;
 import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.to;
 import static org.apache.flink.runtime.checkpoint.StateHandleDummyUtil.createNewInputChannelStateHandle;
 import static org.apache.flink.runtime.checkpoint.StateHandleDummyUtil.createNewKeyedStateHandle;
 import static org.apache.flink.runtime.checkpoint.StateHandleDummyUtil.createNewOperatorStateHandle;
 import static org.apache.flink.runtime.checkpoint.StateHandleDummyUtil.createNewResultSubpartitionStateHandle;
+import static org.apache.flink.runtime.io.network.api.writer.SubtaskStateMapper.ARBITRARY;
 import static org.apache.flink.runtime.io.network.api.writer.SubtaskStateMapper.RANGE;
 import static org.apache.flink.runtime.io.network.api.writer.SubtaskStateMapper.ROUND_ROBIN;
 import static org.hamcrest.Matchers.containsInAnyOrder;
@@ -435,6 +442,52 @@ public class StateAssignmentOperationTest extends TestLogger {
     }
 
     @Test
+    public void testChannelStateAssignmentDownscalingTwoDifferentGates()
+            throws JobException, JobExecutionException {
+        JobVertex upstream1 = createJobVertex(new OperatorID(), 2);
+        JobVertex upstream2 = createJobVertex(new OperatorID(), 2);
+        JobVertex downstream = createJobVertex(new OperatorID(), 2);
+        List<OperatorID> operatorIds =
+                Stream.of(upstream1, upstream2, downstream)
+                        .map(v -> v.getOperatorIDs().get(0).getGeneratedOperatorID())
+                        .collect(Collectors.toList());
+        Map<OperatorID, OperatorState> states = buildOperatorStates(operatorIds, 3);
+
+        connectVertices(upstream1, downstream, ARBITRARY, RANGE);
+        connectVertices(upstream2, downstream, ROUND_ROBIN, ROUND_ROBIN);
+
+        Map<OperatorID, ExecutionJobVertex> vertices =
+                toExecutionVertices(upstream1, upstream2, downstream);
+
+        new StateAssignmentOperation(0, new HashSet<>(vertices.values()), states, false)
+                .assignStates();
+
+        assertEquals(
+                new InflightDataRescalingDescriptor(
+                        array(
+                                gate(to(0, 1), mappings(to(0, 2), to(1)), set(1), RESCALING),
+                                gate(to(0, 2), mappings(to(0, 2), to(1)), emptySet(), RESCALING))),
+                getAssignedState(vertices.get(operatorIds.get(2)), operatorIds.get(2), 0)
+                        .getInputRescalingDescriptor());
+        assertEquals(
+                new InflightDataRescalingDescriptor(
+                        array(
+                                gate(to(0, 1), mappings(to(0, 2), to(1)), set(1), RESCALING),
+                                gate(to(0, 2), mappings(to(0, 2), to(1)), emptySet(), RESCALING))),
+                getAssignedState(vertices.get(operatorIds.get(2)), operatorIds.get(2), 0)
+                        .getInputRescalingDescriptor());
+    }
+
+    private InflightDataGateOrPartitionRescalingDescriptor gate(
+            int[] oldIndices,
+            RescaleMappings rescaleMapping,
+            Set<Integer> ambiguousSubtaskIndexes,
+            InflightDataGateOrPartitionRescalingDescriptor.Rescaling rescalingMode) {
+        return new InflightDataGateOrPartitionRescalingDescriptor(
+                oldIndices, rescaleMapping, ambiguousSubtaskIndexes, rescalingMode);
+    }
+
+    @Test
     public void testChannelStateAssignmentDownscaling() throws JobException, JobExecutionException {
         List<OperatorID> operatorIds = buildOperatorIds(2);
         Map<OperatorID, OperatorState> states = buildOperatorStates(operatorIds, 3);
@@ -482,24 +535,20 @@ public class StateAssignmentOperationTest extends TestLogger {
         }
 
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(0, 2), array(mappings(to(0, 1), to(1, 2))), set()),
+                rescalingDescriptor(to(0, 2), array(mappings(to(0, 1), to(1, 2))), set()),
                 getAssignedState(vertices.get(operatorIds.get(0)), operatorIds.get(0), 0)
                         .getOutputRescalingDescriptor());
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(1), array(mappings(to(0, 1), to(1, 2))), set()),
+                rescalingDescriptor(to(1), array(mappings(to(0, 1), to(1, 2))), set()),
                 getAssignedState(vertices.get(operatorIds.get(0)), operatorIds.get(0), 1)
                         .getOutputRescalingDescriptor());
 
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(0, 1), array(mappings(to(0, 2), to(1))), set(1)),
+                rescalingDescriptor(to(0, 1), array(mappings(to(0, 2), to(1))), set(1)),
                 getAssignedState(vertices.get(operatorIds.get(1)), operatorIds.get(1), 0)
                         .getInputRescalingDescriptor());
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(1, 2), array(mappings(to(0, 2), to(1))), set(1)),
+                rescalingDescriptor(to(1, 2), array(mappings(to(0, 2), to(1))), set(1)),
                 getAssignedState(vertices.get(operatorIds.get(1)), operatorIds.get(1), 1)
                         .getInputRescalingDescriptor());
     }
@@ -606,13 +655,11 @@ public class StateAssignmentOperationTest extends TestLogger {
         }
 
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(0), array(mappings(to(0), to(0, 1), to(1))), set()),
+                rescalingDescriptor(to(0), array(mappings(to(0), to(0, 1), to(1))), set()),
                 getAssignedState(vertices.get(operatorIds.get(0)), operatorIds.get(0), 0)
                         .getOutputRescalingDescriptor());
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(1), array(mappings(to(0), to(0, 1), to(1))), set()),
+                rescalingDescriptor(to(1), array(mappings(to(0), to(0, 1), to(1))), set()),
                 getAssignedState(vertices.get(operatorIds.get(0)), operatorIds.get(0), 1)
                         .getOutputRescalingDescriptor());
         // unmapped subtask index, so nothing to do
@@ -622,18 +669,15 @@ public class StateAssignmentOperationTest extends TestLogger {
                         .getOutputRescalingDescriptor());
 
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(0), array(mappings(to(0), to(1), to())), set(0, 1)),
+                rescalingDescriptor(to(0), array(mappings(to(0), to(1), to())), set(0, 1)),
                 getAssignedState(vertices.get(operatorIds.get(1)), operatorIds.get(1), 0)
                         .getInputRescalingDescriptor());
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(0, 1), array(mappings(to(0), to(1), to())), set(0, 1)),
+                rescalingDescriptor(to(0, 1), array(mappings(to(0), to(1), to())), set(0, 1)),
                 getAssignedState(vertices.get(operatorIds.get(1)), operatorIds.get(1), 1)
                         .getInputRescalingDescriptor());
         assertEquals(
-                new InflightDataRescalingDescriptor(
-                        to(1), array(mappings(to(0), to(1), to())), set(0, 1)),
+                rescalingDescriptor(to(1), array(mappings(to(0), to(1), to())), set(0, 1)),
                 getAssignedState(vertices.get(operatorIds.get(1)), operatorIds.get(1), 2)
                         .getInputRescalingDescriptor());
     }
@@ -766,23 +810,21 @@ public class StateAssignmentOperationTest extends TestLogger {
             throws JobException, JobExecutionException {
         final JobVertex[] jobVertices =
                 operatorIds.stream()
-                        .map(
-                                id -> {
-                                    final JobVertex jobVertex =
-                                            createJobVertex(id, id, parallelism);
-                                    return jobVertex;
-                                })
+                        .map(id -> createJobVertex(id, id, parallelism))
                         .toArray(JobVertex[]::new);
         for (int index = 1; index < jobVertices.length; index++) {
-            final JobEdge jobEdge =
-                    jobVertices[index].connectNewDataSetAsInput(
-                            jobVertices[index - 1],
-                            DistributionPattern.ALL_TO_ALL,
-                            ResultPartitionType.PIPELINED);
-            jobEdge.setDownstreamSubtaskStateMapper(downstreamRescaler);
-            jobEdge.setUpstreamSubtaskStateMapper(upstreamRescaler);
+            connectVertices(
+                    jobVertices[index - 1],
+                    jobVertices[index],
+                    upstreamRescaler,
+                    downstreamRescaler);
         }
 
+        return toExecutionVertices(jobVertices);
+    }
+
+    private Map<OperatorID, ExecutionJobVertex> toExecutionVertices(JobVertex... jobVertices)
+            throws JobException, JobExecutionException {
         JobGraph jobGraph = JobGraphTestUtils.streamingJobGraph(jobVertices);
         ExecutionGraph eg =
                 TestingDefaultExecutionGraphBuilder.newBuilder().setJobGraph(jobGraph).build();
@@ -800,6 +842,18 @@ public class StateAssignmentOperationTest extends TestLogger {
                                 }));
     }
 
+    private void connectVertices(
+            JobVertex upstream,
+            JobVertex downstream,
+            SubtaskStateMapper upstreamRescaler,
+            SubtaskStateMapper downstreamRescaler) {
+        final JobEdge jobEdge =
+                downstream.connectNewDataSetAsInput(
+                        upstream, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED);
+        jobEdge.setDownstreamSubtaskStateMapper(downstreamRescaler);
+        jobEdge.setUpstreamSubtaskStateMapper(upstreamRescaler);
+    }
+
     private ExecutionJobVertex buildExecutionJobVertex(
             OperatorID operatorID, OperatorID userDefinedOperatorId, int parallelism) {
         try {
@@ -810,6 +864,10 @@ public class StateAssignmentOperationTest extends TestLogger {
         }
     }
 
+    private JobVertex createJobVertex(OperatorID operatorID, int parallelism) {
+        return createJobVertex(operatorID, operatorID, parallelism);
+    }
+
     private JobVertex createJobVertex(
             OperatorID operatorID, OperatorID userDefinedOperatorId, int parallelism) {
         JobVertex jobVertex =
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/recovery/DemultiplexingRecordDeserializer.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/recovery/DemultiplexingRecordDeserializer.java
index 50be846..994fd58 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/recovery/DemultiplexingRecordDeserializer.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/recovery/DemultiplexingRecordDeserializer.java
@@ -197,7 +197,8 @@ class DemultiplexingRecordDeserializer<T>
             Function<Integer, RecordDeserializer<DeserializationDelegate<StreamElement>>>
                     deserializerFactory,
             Function<InputChannelInfo, Predicate<StreamRecord<T>>> recordFilterFactory) {
-        int[] oldSubtaskIndexes = rescalingDescriptor.getOldSubtaskIndexes();
+        int[] oldSubtaskIndexes =
+                rescalingDescriptor.getOldSubtaskIndexes(channelInfo.getGateIdx());
         if (oldSubtaskIndexes.length == 0) {
             return UNMAPPED;
         }
@@ -219,7 +220,7 @@ class DemultiplexingRecordDeserializer<T>
                         descriptor,
                         new VirtualChannel<>(
                                 deserializerFactory.apply(totalChannels),
-                                rescalingDescriptor.isAmbiguous(subtask)
+                                rescalingDescriptor.isAmbiguous(channelInfo.getGateIdx(), subtask)
                                         ? recordFilterFactory.apply(channelInfo)
                                         : RecordFilter.all()));
             }
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/io/recovery/DemultiplexingRecordDeserializerTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/io/recovery/DemultiplexingRecordDeserializerTest.java
index 6a47c26..447c2be 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/io/recovery/DemultiplexingRecordDeserializerTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/io/recovery/DemultiplexingRecordDeserializerTest.java
@@ -19,7 +19,6 @@ package org.apache.flink.streaming.runtime.io.recovery;
 
 import org.apache.flink.api.common.typeutils.base.LongSerializer;
 import org.apache.flink.core.memory.DataOutputSerializer;
-import org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor;
 import org.apache.flink.runtime.checkpoint.channel.InputChannelInfo;
 import org.apache.flink.runtime.io.disk.iomanager.IOManager;
 import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync;
@@ -59,6 +58,7 @@ import java.util.stream.Collectors;
 import static java.util.Collections.emptySet;
 import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.array;
 import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.mappings;
+import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.rescalingDescriptor;
 import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.set;
 import static org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptorUtil.to;
 import static org.apache.flink.runtime.io.network.buffer.BufferBuilderTestUtils.createBufferBuilder;
@@ -92,7 +92,7 @@ public class DemultiplexingRecordDeserializerTest {
         DemultiplexingRecordDeserializer<Long> deserializer =
                 DemultiplexingRecordDeserializer.create(
                         new InputChannelInfo(2, 0),
-                        new InflightDataRescalingDescriptor(
+                        rescalingDescriptor(
                                 to(0, 1),
                                 array(mappings(), mappings(), mappings(to(2, 3), to(4, 5))),
                                 emptySet()),
@@ -133,7 +133,7 @@ public class DemultiplexingRecordDeserializerTest {
         DemultiplexingRecordDeserializer<Long> deserializer =
                 DemultiplexingRecordDeserializer.create(
                         new InputChannelInfo(1, 0),
-                        new InflightDataRescalingDescriptor(
+                        rescalingDescriptor(
                                 to(41, 42),
                                 array(mappings(), mappings(to(2, 3), to(4, 5))),
                                 set(42)),
@@ -177,7 +177,7 @@ public class DemultiplexingRecordDeserializerTest {
         DemultiplexingRecordDeserializer<Long> deserializer =
                 DemultiplexingRecordDeserializer.create(
                         new InputChannelInfo(0, 0),
-                        new InflightDataRescalingDescriptor(
+                        rescalingDescriptor(
                                 to(0, 1), array(mappings(to(0, 1), to(4, 5))), emptySet()),
                         unused ->
                                 new SpillingAdaptiveSpanningRecordDeserializer<>(
diff --git a/flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointRescaleITCase.java b/flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointRescaleITCase.java
index 0420494..fed104f 100644
--- a/flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointRescaleITCase.java
+++ b/flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointRescaleITCase.java
@@ -31,6 +31,7 @@ import org.apache.flink.api.common.state.ValueStateDescriptor;
 import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
 import org.apache.flink.api.common.typeinfo.Types;
 import org.apache.flink.api.common.typeutils.base.LongSerializer;
+import org.apache.flink.api.java.functions.KeySelector;
 import org.apache.flink.configuration.Configuration;
 import org.apache.flink.runtime.state.FunctionInitializationContext;
 import org.apache.flink.runtime.state.FunctionSnapshotContext;
@@ -41,6 +42,8 @@ import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
 import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
 import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
 import org.apache.flink.streaming.api.functions.co.CoMapFunction;
+import org.apache.flink.streaming.api.functions.co.KeyedBroadcastProcessFunction;
+import org.apache.flink.streaming.api.functions.co.KeyedCoProcessFunction;
 import org.apache.flink.util.Collector;
 
 import org.junit.Test;
@@ -122,6 +125,46 @@ public class UnalignedCheckpointRescaleITCase extends UnalignedCheckpointTestBas
             }
         },
 
+        KEYED_DIFFERENT_PARALLELISM {
+            @Override
+            public void create(
+                    StreamExecutionEnvironment env,
+                    int minCheckpoints,
+                    boolean slotSharing,
+                    int expectedRestarts) {
+
+                final int parallelism = env.getParallelism();
+                checkState(parallelism >= 4);
+                final DataStream<Long> source1 =
+                        createSourcePipeline(
+                                env,
+                                minCheckpoints,
+                                slotSharing,
+                                expectedRestarts,
+                                parallelism / 2,
+                                0,
+                                val -> withoutHeader(val) % 2 == 0);
+                final DataStream<Long> source2 =
+                        createSourcePipeline(
+                                env,
+                                minCheckpoints,
+                                slotSharing,
+                                expectedRestarts,
+                                parallelism / 3,
+                                1,
+                                val -> withoutHeader(val) % 2 == 1);
+
+                KeySelector<Long, Long> keySelector = i -> withoutHeader(i) % NUM_GROUPS;
+                SingleOutputStreamOperator<Long> connected =
+                        source1.connect(source2)
+                                .keyBy(keySelector, keySelector)
+                                .process(new TestKeyedCoProcessFunction())
+                                .setParallelism(parallelism);
+
+                addFailingSink(connected, minCheckpoints, slotSharing);
+            }
+        },
+
         UNION {
             @Override
             public void create(
@@ -189,7 +232,80 @@ public class UnalignedCheckpointRescaleITCase extends UnalignedCheckpointTestBas
                                 BasicTypeInfo.LONG_TYPE_INFO);
                 final BroadcastStream<Long> broadcast = broadcastSide.broadcast(descriptor);
                 final SingleOutputStreamOperator<Long> joined =
-                        source.connect(broadcast).process(new TestBroadcastProcessFunction());
+                        source.connect(broadcast)
+                                .process(new TestBroadcastProcessFunction())
+                                .setParallelism(2 * parallelism);
+
+                addFailingSink(joined, minCheckpoints, slotSharing);
+            }
+        },
+
+        KEYED_BROADCAST {
+            @Override
+            public void create(
+                    StreamExecutionEnvironment env,
+                    int minCheckpoints,
+                    boolean slotSharing,
+                    int expectedRestarts) {
+
+                final int parallelism = env.getParallelism();
+                final DataStream<Long> broadcastSide1 =
+                        env.fromSource(
+                                        new LongSource(
+                                                minCheckpoints,
+                                                1,
+                                                expectedRestarts,
+                                                env.getCheckpointInterval()),
+                                        noWatermarks(),
+                                        "source-1")
+                                .setParallelism(1);
+                final DataStream<Long> broadcastSide2 =
+                        env.fromSource(
+                                        new LongSource(
+                                                minCheckpoints,
+                                                1,
+                                                expectedRestarts,
+                                                env.getCheckpointInterval()),
+                                        noWatermarks(),
+                                        "source-2")
+                                .setParallelism(1);
+                final DataStream<Long> broadcastSide3 =
+                        env.fromSource(
+                                        new LongSource(
+                                                minCheckpoints,
+                                                1,
+                                                expectedRestarts,
+                                                env.getCheckpointInterval()),
+                                        noWatermarks(),
+                                        "source-3")
+                                .setParallelism(1);
+                final DataStream<Long> source =
+                        createSourcePipeline(
+                                        env,
+                                        minCheckpoints,
+                                        slotSharing,
+                                        expectedRestarts,
+                                        parallelism,
+                                        0,
+                                        val -> true)
+                                .map(i -> checkHeader(i))
+                                .name("map")
+                                .uid("map")
+                                .slotSharingGroup(slotSharing ? "default" : "failing-map");
+
+                final MapStateDescriptor<Long, Long> descriptor =
+                        new MapStateDescriptor<>(
+                                "broadcast",
+                                BasicTypeInfo.LONG_TYPE_INFO,
+                                BasicTypeInfo.LONG_TYPE_INFO);
+                DataStream<Long> broadcastSide =
+                        broadcastSide1.union(broadcastSide2).union(broadcastSide3);
+                final BroadcastStream<Long> broadcast = broadcastSide.broadcast(descriptor);
+                final SingleOutputStreamOperator<Long> joined =
+                        source.keyBy(i -> withoutHeader(i) % NUM_GROUPS)
+                                .connect(broadcast)
+                                .process(new TestKeyedBroadcastProcessFunction())
+                                .setParallelism(parallelism + 2);
 
                 addFailingSink(joined, minCheckpoints, slotSharing);
             }
@@ -304,12 +420,51 @@ public class UnalignedCheckpointRescaleITCase extends UnalignedCheckpointTestBas
             @Override
             public void processBroadcastElement(Long value, Context ctx, Collector<Long> out) {}
         }
+
+        private static class TestKeyedCoProcessFunction
+                extends KeyedCoProcessFunction<Long, Long, Long, Long> {
+            private static final long serialVersionUID = 1L;
+
+            TestKeyedCoProcessFunction() {}
+
+            @Override
+            public void processElement1(Long value, Context ctx, Collector<Long> out)
+                    throws Exception {
+                out.collect(checkHeader(value));
+            }
+
+            @Override
+            public void processElement2(Long value, Context ctx, Collector<Long> out)
+                    throws Exception {
+                out.collect(checkHeader(value));
+            }
+        }
+
+        private static class TestKeyedBroadcastProcessFunction
+                extends KeyedBroadcastProcessFunction<Long, Long, Long, Long> {
+            private static final long serialVersionUID = 7852973507735751404L;
+
+            TestKeyedBroadcastProcessFunction() {}
+
+            @Override
+            public void processElement(Long value, ReadOnlyContext ctx, Collector<Long> out) {
+                out.collect(checkHeader(value));
+            }
+
+            @Override
+            public void processBroadcastElement(Long value, Context ctx, Collector<Long> out) {}
+        }
     }
 
     @Parameterized.Parameters(name = "{0} {1} from {2} to {3}")
     public static Object[][] getScaleFactors() {
         return new Object[][] {
+            new Object[] {"downscale", Topology.KEYED_DIFFERENT_PARALLELISM, 12, 7},
+            new Object[] {"upscale", Topology.KEYED_DIFFERENT_PARALLELISM, 7, 12},
+            new Object[] {"downscale", Topology.KEYED_BROADCAST, 7, 2},
+            new Object[] {"upscale", Topology.KEYED_BROADCAST, 2, 7},
             new Object[] {"downscale", Topology.BROADCAST, 5, 2},
+            new Object[] {"upscale", Topology.BROADCAST, 2, 5},
             new Object[] {"upscale", Topology.PIPELINE, 1, 2},
             new Object[] {"upscale", Topology.PIPELINE, 2, 3},
             new Object[] {"upscale", Topology.PIPELINE, 3, 7},