polyzos commented on code in PR #29662:
URL: https://github.com/apache/flink/pull/29662#discussion_r4548482280


##########
flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/Dispatcher.java:
##########
@@ -1275,11 +1276,38 @@ private CompletableFuture<Boolean> 
isInGloballyTerminalState(JobID jobId) {
     }
 
     private CompletableFuture<Acknowledge> internalSubmitJob(ExecutionPlan 
executionPlan) {
-        if (executionPlan instanceof JobGraph) {
-            applyParallelismOverrides((JobGraph) executionPlan);
+        final JobID jobId = executionPlan.getJobID();
+
+        final Map<String, String> parallelismOverrides =
+                JobVertexParallelismOverrides.merge(
+                        configuration, executionPlan.getJobConfiguration());
+        if (!parallelismOverrides.isEmpty()) {
+            final Map<JobVertexID, String> overridesByJobVertexId =
+                    
JobVertexParallelismOverrides.byJobVertexId(parallelismOverrides);
+            log.info(
+                    "Resolved {} for job {} to {}.",
+                    PipelineOptions.PARALLELISM_OVERRIDES.key(),
+                    jobId,
+                    overridesByJobVertexId);
+            if (executionPlan instanceof JobGraph) {
+                try {
+                    applyParallelismOverrides((JobGraph) executionPlan, 
overridesByJobVertexId);
+                } catch (IllegalArgumentException e) {
+                    return FutureUtils.completedExceptionally(
+                            new JobSubmissionException(jobId, e.getMessage(), 
e));
+                }
+            } else {

Review Comment:
   A bad value (`abc`, `0`) now fails at different points depending on the plan 
type. A JobGraph is rejected at submission. A StreamGraph is accepted and 
stored in HA, and the job only fails when the JobMaster builds it.
   
   Checking cluster-level entries lazily makes sense, but entries from the 
job's own configuration could be validated here for both plan types, so the 
client and the operator get the same error either way.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/jobgraph/JobVertexParallelismOverrides.java:
##########
@@ -0,0 +1,134 @@
+/*
+ * 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.flink.runtime.jobgraph;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.configuration.PipelineOptions;
+import org.apache.flink.configuration.ReadableConfig;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+/**
+ * Resolution and application of {@link PipelineOptions#PARALLELISM_OVERRIDES}.
+ *
+ * <p>The map is resolved once at submission, job configuration over cluster 
configuration, and
+ * applied after the job vertex ids are computed: by the Dispatcher for a 
submitted {@link
+ * JobGraph}, by the JobGraph generator for a {@link
+ * org.apache.flink.streaming.api.graph.StreamGraph}, whose job configuration 
carries the resolved
+ * map. The persisted plan therefore replays the same overrides on recovery, 
and an override never
+ * changes a job vertex id, an operator id or the chaining.
+ *
+ * <p>A value that is not a positive integer fails only the job that contains 
the vertex, so a bad
+ * entry in the cluster configuration does not block other jobs.
+ */
+@Internal
+public final class JobVertexParallelismOverrides {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(JobVertexParallelismOverrides.class);
+
+    private static final Pattern JOB_VERTEX_ID = 
Pattern.compile("[0-9a-f]{32}");
+
+    private JobVertexParallelismOverrides() {}
+
+    /** Merges the cluster and the job map; the entries of the job map win. */
+    public static Map<String, String> merge(
+            ReadableConfig clusterConfiguration, ReadableConfig 
jobConfiguration) {
+        final Map<String, String> overrides =
+                new 
HashMap<>(clusterConfiguration.get(PipelineOptions.PARALLELISM_OVERRIDES));
+        
overrides.putAll(jobConfiguration.get(PipelineOptions.PARALLELISM_OVERRIDES));
+        return overrides;
+    }
+
+    /**
+     * Keys the map by job vertex id. Entries whose key is not the hex form of 
a job vertex id are
+     * dropped with a warning; values are kept as they are and checked when 
they are applied.
+     */
+    public static Map<JobVertexID, String> byJobVertexId(Map<String, String> 
overrides) {
+        final Map<JobVertexID, String> keyed = new HashMap<>(overrides.size());
+        for (Map.Entry<String, String> override : overrides.entrySet()) {
+            final String key = override.getKey();
+            if (JOB_VERTEX_ID.matcher(key).matches()) {
+                keyed.put(JobVertexID.fromHexString(key), override.getValue());
+            } else {
+                LOG.warn(
+                        "Ignoring the entry '{}' of {}: a job vertex id has 32 
lowercase hex characters.",
+                        key,
+                        PipelineOptions.PARALLELISM_OVERRIDES.key());
+            }
+        }
+        return keyed;
+    }
+
+    /** The inverse of {@link #byJobVertexId(Map)}, in the format of the 
configuration option. */
+    public static Map<String, String> toConfigurationValue(Map<JobVertexID, 
String> overrides) {
+        final Map<String, String> value = new HashMap<>(overrides.size());
+        for (Map.Entry<JobVertexID, String> override : overrides.entrySet()) {
+            value.put(override.getKey().toHexString(), override.getValue());
+        }
+        return value;
+    }
+
+    /**
+     * Sets the overridden parallelism on the vertex if the map contains one 
for it.
+     *
+     * @return whether the vertex was changed
+     * @throws IllegalArgumentException if the override for the vertex is not 
a positive integer
+     */
+    public static boolean apply(JobVertex vertex, Map<JobVertexID, String> 
overrides) {

Review Comment:
   Nit: an override above the vertex's max parallelism isn't caught here. The 
job fails later in the scheduler, with an error that doesn't mention this 
option. Checking it here, when max parallelism is set, would point users at the 
right setting. 1.x behaved the same.



##########
flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGenerator.java:
##########
@@ -1166,6 +1190,17 @@ public static JobVertex createJobVertex(
 
         jobVertex.setMaxParallelism(streamNode.getMaxParallelism());
 
+        if (JobVertexParallelismOverrides.apply(

Review Comment:
   An override can now give the two ends of a non-chained forward edge 
different parallelism, and nothing checks it. Example: chaining disabled, a 
source and a `forward()` map both at 2, only the map overridden to 4. Half of 
the map's subtasks then get no input, and after `reinterpretAsKeyedStream` 
records would reach subtasks that don't own their keys.
   
   As far as I can tell, 1.x behaves the same with JobGraph submissions, so 
this isn't a regression. But the generator now sees both ends, so it could warn 
or reject the override, as the adaptive batch path already does for forward 
groups. A test that pins down the intended behaviour would help either way.



##########
flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/AdaptiveGraphManager.java:
##########
@@ -447,6 +473,88 @@ private void 
connectToFinishedUpStreamVertex(JobVertexBuildContext jobVertexBuil
         }
     }
 
+    /**
+     * An overridden parallelism decides the forward group of its vertex like 
a configured one. A
+     * group that is still undecided takes the value. A group that was decided 
to another value is
+     * re-decided when the other members only carried that value by 
propagation; a member that the
+     * user configured to another value or that already runs as a job vertex 
is a conflict, as a
+     * differently configured member is for the full generator.
+     */
+    private void applyParallelismOverridesToForwardGroups(
+            JobVertexBuildContext jobVertexBuildContext) {
+        for (JobVertex jobVertex : 
jobVertexBuildContext.getJobVerticesInOrder().values()) {
+            if 
(!jobVertexBuildContext.getParallelismOverrides().containsKey(jobVertex.getID()))
 {
+                continue;
+            }
+            // createJobVertex has already applied and validated the override
+            final int overriddenParallelism = jobVertex.getParallelism();
+            final StreamNodeForwardGroup forwardGroup =
+                    getStreamNodeForwardGroupByVertexId(jobVertex.getID());
+            if (forwardGroup == null) {
+                continue;
+            }
+            if (forwardGroup.isMaxParallelismDecided()
+                    && overriddenParallelism > 
forwardGroup.getMaxParallelism()) {
+                throw new IllegalStateException(
+                        String.format(
+                                "The parallelism override %d for job vertex %s 
(%s) exceeds the max"
+                                        + " parallelism %d of its forward 
group.",
+                                overriddenParallelism,
+                                jobVertex.getName(),
+                                jobVertex.getID(),
+                                forwardGroup.getMaxParallelism()));
+            }
+            if (!forwardGroup.isParallelismDecided()) {
+                forwardGroup.setParallelism(overriddenParallelism);
+                continue;
+            }
+            if (forwardGroup.getParallelism() == overriddenParallelism) {
+                continue;
+            }

Review Comment:
   This one is real for adaptive batch: a `-1` override conflicts with any 
member that already runs, such as the source, and an undecided group would take 
`-1` as its parallelism. Treating `-1` as "no constraint" here, or not 
accepting it for the incremental generator, would avoid both.



##########
flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/AdaptiveGraphManager.java:
##########
@@ -447,6 +473,88 @@ private void 
connectToFinishedUpStreamVertex(JobVertexBuildContext jobVertexBuil
         }
     }
 
+    /**
+     * An overridden parallelism decides the forward group of its vertex like 
a configured one. A
+     * group that is still undecided takes the value. A group that was decided 
to another value is
+     * re-decided when the other members only carried that value by 
propagation; a member that the
+     * user configured to another value or that already runs as a job vertex 
is a conflict, as a
+     * differently configured member is for the full generator.
+     */
+    private void applyParallelismOverridesToForwardGroups(
+            JobVertexBuildContext jobVertexBuildContext) {
+        for (JobVertex jobVertex : 
jobVertexBuildContext.getJobVerticesInOrder().values()) {
+            if 
(!jobVertexBuildContext.getParallelismOverrides().containsKey(jobVertex.getID()))
 {
+                continue;
+            }
+            // createJobVertex has already applied and validated the override
+            final int overriddenParallelism = jobVertex.getParallelism();
+            final StreamNodeForwardGroup forwardGroup =
+                    getStreamNodeForwardGroupByVertexId(jobVertex.getID());
+            if (forwardGroup == null) {
+                continue;
+            }
+            if (forwardGroup.isMaxParallelismDecided()
+                    && overriddenParallelism > 
forwardGroup.getMaxParallelism()) {
+                throw new IllegalStateException(
+                        String.format(
+                                "The parallelism override %d for job vertex %s 
(%s) exceeds the max"
+                                        + " parallelism %d of its forward 
group.",
+                                overriddenParallelism,
+                                jobVertex.getName(),
+                                jobVertex.getID(),
+                                forwardGroup.getMaxParallelism()));
+            }
+            if (!forwardGroup.isParallelismDecided()) {
+                forwardGroup.setParallelism(overriddenParallelism);
+                continue;
+            }
+            if (forwardGroup.getParallelism() == overriddenParallelism) {
+                continue;
+            }
+            final Set<Integer> chainedNodeIds =
+                    new 
HashSet<>(jobVertexToChainedStreamNodeIdsMap.get(jobVertex.getID()));
+            final Set<StreamNode> members = new HashSet<>();
+            for (Integer memberId : forwardGroup.getVertexIds()) {
+                members.add(streamGraph.getStreamNode(memberId));
+                if (chainedNodeIds.contains(memberId)) {
+                    continue;
+                }
+                final Integer userConfigured = 
userConfiguredParallelisms.get(memberId);
+                if (frozenNodeToStartNodeMap.containsKey(memberId)
+                        || (userConfigured != null && userConfigured != 
overriddenParallelism)) {

Review Comment:
   Confirmed for adaptive batch, and of the three this is the one users are 
most likely to hit, since overriding a whole forward group to the same value is 
the normal case. Taking the pending members' overrides into account before 
declaring a conflict should fix it, ideally with a regression test.



##########
flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGenerator.java:
##########
@@ -1166,6 +1190,17 @@ public static JobVertex createJobVertex(
 
         jobVertex.setMaxParallelism(streamNode.getMaxParallelism());
 
+        if (JobVertexParallelismOverrides.apply(
+                jobVertex, jobVertexBuildContext.getParallelismOverrides())) {
+            parallelism = jobVertex.getParallelism();

Review Comment:
   Also real for adaptive batch: a consumer explicitly configured to 1 can't be 
overridden higher, which is stricter than the max parallelism limit the option 
description documents. Looking up the consumer's override when the producer is 
created would fix it; otherwise the documented limit should be the configured 
parallelism, if one is set.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to