You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gluten.apache.org by "lgbo-ustc (via GitHub)" <gi...@apache.org> on 2026/01/06 01:54:25 UTC
[PR] [GLUTEN-11364][Flink] Improve the job graph generation code [incubator-gluten]
lgbo-ustc opened a new pull request, #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365
<!--
Thank you for submitting a pull request! Here are some tips:
1. For first-time contributors, please read our contributing guide:
https://github.com/apache/incubator-gluten/blob/main/CONTRIBUTING.md
2. If necessary, create a GitHub issue for discussion beforehand to avoid duplicate work.
3. If the PR is specific to a single backend, include [VL] or [CH] in the PR title to indicate the
Velox or ClickHouse backend, respectively.
4. If the PR is not ready for review, please mark it as a draft.
-->
## What changes are proposed in this pull request?
Improve the job graph generation code.
<!--
Provide a clear and concise description of the changes introduced in this PR.
Ensure the PR description aligns with the code changes, especially after updates.
If applicable, include "Fixes #<GitHub_Issue_ID>" to automatically close the corresponding issue
when the PR is merged.
-->
## How was this patch tested?
<!--
Describe how the changes were tested, if applicable.
Include new tests to validate the functionality, if necessary.
For UI-related changes, attach screenshots to demonstrate the updates.
-->
tested by UTs
--
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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org
Re: [PR] [GLUTEN-11364][Flink] Improve the job graph generation code [incubator-gluten]
Posted by "ryyyyyy1 (via GitHub)" <gi...@apache.org>.
ryyyyyy1 commented on PR #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365#issuecomment-3722770747
does this support falling back to Flink native operator chain when the gluten+velox is unsupported?
--
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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org
Re: [PR] [GLUTEN-11364][Flink] Improve the job graph generation code [incubator-gluten]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365#discussion_r2675446219
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OperatorChainSliceGraphGenerator.java:
##########
@@ -0,0 +1,197 @@
+/*
+ * 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.gluten.client;
+
+import org.apache.gluten.streaming.api.operators.GlutenOneInputOperatorFactory;
+import org.apache.gluten.streaming.api.operators.GlutenOperator;
+
+import org.apache.flink.runtime.jobgraph.JobVertex;
+import org.apache.flink.streaming.api.graph.StreamConfig;
+import org.apache.flink.streaming.api.graph.StreamEdge;
+import org.apache.flink.streaming.api.operators.SimpleOperatorFactory;
+import org.apache.flink.streaming.api.operators.StreamOperator;
+import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+class OperatorChainSliceGraphGenerator {
+ private static final Logger LOG = LoggerFactory.getLogger(OperatorChainSliceGraphGenerator.class);
+ private OperatorChainSliceGraph chainSliceGraph = null;
+ private Map<Integer, List<Integer>> operatorParents;
+ private JobVertex jobVertex;
+ private Map<Integer, StreamConfig> chainedConfigs;
+ private final ClassLoader userClassloader;
+
+ public OperatorChainSliceGraphGenerator(JobVertex jobVertex, ClassLoader userClassloader) {
+ this.operatorParents = new HashMap<>();
+ this.jobVertex = jobVertex;
+ this.userClassloader = userClassloader;
+ }
+
+ public OperatorChainSliceGraph getGraph() {
+ generateInternal();
+ return chainSliceGraph;
+ }
+
+ private void generateInternal() {
+ if (chainSliceGraph != null) {
+ return;
+ }
+ chainSliceGraph = new OperatorChainSliceGraph();
+
+ StreamConfig rootOpConfig = new StreamConfig(jobVertex.getConfiguration());
+
+ chainedConfigs = new HashMap<>();
+ rootOpConfig
+ .getTransitiveChainedTaskConfigs(userClassloader)
+ .forEach(
+ (id, config) -> {
+ chainedConfigs.put(id, new StreamConfig(config.getConfiguration()));
+ });
+ chainedConfigs.put(rootOpConfig.getVertexID(), rootOpConfig);
+
+ collectOperatorParents(rootOpConfig, null);
+
+ OperatorChainSlice chainSlice = new OperatorChainSlice(rootOpConfig.getVertexID());
+ chainSlice.setOffloadable(isOffloadableOperator(rootOpConfig));
+ chainSlice.getOperatorConfigs().add(rootOpConfig);
+ chainSliceGraph.addSlice(chainSlice.id(), chainSlice);
+
+ advanceOperatorChainSlice(chainSlice, rootOpConfig);
+ }
+
+ private void advanceOperatorChainSlice(
+ OperatorChainSlice chainSlice, StreamConfig currentOpConfig) {
+ List<StreamEdge> outputEdges = currentOpConfig.getChainedOutputs(userClassloader);
+ if (outputEdges == null || outputEdges.isEmpty()) {
+ return;
+ }
+ if (outputEdges.size() == 1) {
+ Integer targetId = outputEdges.get(0).getTargetId();
+ StreamConfig childOpConfig = chainedConfigs.get(targetId);
+ // We don't coalesce operators into the same velox plan at present. Each operator is a
+ // separate velox plan.
+ startNewOperatorChainSlice(chainSlice, childOpConfig);
+ } else {
+ for (StreamEdge edge : outputEdges) {
+ Integer targetId = edge.getTargetId();
+ StreamConfig childOpConfig = chainedConfigs.get(targetId);
+ startNewOperatorChainSlice(chainSlice, childOpConfig);
+ }
+ }
+ }
+
+ private void startNewOperatorChainSlice(
+ OperatorChainSlice parentChainSlice, StreamConfig childOpConfig) {
+ Boolean isFistVisit = false;
+ OperatorChainSlice childChainSlice = chainSliceGraph.getSlice(childOpConfig.getVertexID());
+ if (childChainSlice == null) {
+ isFistVisit = true;
+ childChainSlice = new OperatorChainSlice(childOpConfig.getVertexID());
+ }
+
+ parentChainSlice.getOutputs().add(childChainSlice.id());
+ childChainSlice.getInputs().add(parentChainSlice.id());
+ // If this path has been visited, do not advance again.
+ if (isFistVisit) {
Review Comment:
Corrected spelling of 'isFistVisit' to 'isFirstVisit'.
```suggestion
Boolean isFirstVisit = false;
OperatorChainSlice childChainSlice = chainSliceGraph.getSlice(childOpConfig.getVertexID());
if (childChainSlice == null) {
isFirstVisit = true;
childChainSlice = new OperatorChainSlice(childOpConfig.getVertexID());
}
parentChainSlice.getOutputs().add(childChainSlice.id());
childChainSlice.getInputs().add(parentChainSlice.id());
// If this path has been visited, do not advance again.
if (isFirstVisit) {
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/util/VectorInputBridge.java:
##########
@@ -0,0 +1,71 @@
+/*
+ * 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.gluten.table.runtime.operators;
+
+import org.apache.gluten.vectorized.FlinkRowToVLVectorConvertor;
+
+import io.github.zhztheplayer.velox4j.data.RowVector;
+import io.github.zhztheplayer.velox4j.session.Session;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.type.RowType;
+
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.table.data.RowData;
+
+import org.apache.arrow.memory.BufferAllocator;
+
+import java.io.Serializable;
+
+// This bridge is used to convert the input data to RowVector.
+public class VectorInputBridge<IN> implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private final Class<IN> inClass;
+ private final String nodeId;
+
+ public class RowVectorWrapper {
+ public RowVector rowVector;
+ public String nodeId;
+
+ public RowVectorWrapper(RowVector rowVector, String nodeId) {
+ this.rowVector = rowVector;
+ this.nodeId = nodeId;
+ }
+ }
+ ;
Review Comment:
Remove the unnecessary semicolon after the closing brace of the inner class `RowVectorWrapper`. Semicolons after class declarations are not required in Java and should be removed for cleaner code.
```suggestion
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OffloadedJobGraphGenerator.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.gluten.client;
+
+import org.apache.gluten.streaming.api.operators.GlutenOneInputOperatorFactory;
+import org.apache.gluten.streaming.api.operators.GlutenOperator;
+import org.apache.gluten.streaming.api.operators.GlutenStreamSource;
+import org.apache.gluten.table.runtime.keyselector.GlutenKeySelector;
+import org.apache.gluten.table.runtime.operators.GlutenOneInputOperator;
+import org.apache.gluten.table.runtime.operators.GlutenSourceFunction;
+import org.apache.gluten.table.runtime.operators.GlutenTwoInputOperator;
+import org.apache.gluten.table.runtime.typeutils.GlutenStatefulRecordSerializer;
+
+import io.github.zhztheplayer.velox4j.plan.StatefulPlanNode;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.type.RowType;
+
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.jobgraph.JobVertex;
+import org.apache.flink.streaming.api.graph.StreamConfig;
+import org.apache.flink.streaming.api.graph.StreamEdge;
+import org.apache.flink.streaming.api.graph.StreamNode;
+import org.apache.flink.streaming.api.operators.SimpleOperatorFactory;
+import org.apache.flink.streaming.api.operators.StreamOperator;
+import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
+import org.apache.flink.table.data.RowData;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/*
+ * If a operator is offloadable
+ * - update its input/output serializers as needed.
+ * - update its key selectors as needed.
+ * - coalesce it with its siblings as needed. Also need to update the stream edges.
+ */
+public class OffloadedJobGraphGenerator {
+ private static final Logger LOG = LoggerFactory.getLogger(OffloadedJobGraphGenerator.class);
+ private final JobGraph jobGraph;
+ private final ClassLoader userClassloader;
+ private boolean hasGenerated = false;
+
+ public OffloadedJobGraphGenerator(JobGraph jobGraph, ClassLoader userClassloader) {
+ this.jobGraph = jobGraph;
+ this.userClassloader = userClassloader;
+ }
+
+ public JobGraph generate() {
+ if (hasGenerated) {
+ throw new IllegalStateException("JobGraph has been generated.");
+ }
+ hasGenerated = true;
+ for (JobVertex jobVertex : jobGraph.getVertices()) {
+ offloadJobVertex(jobVertex);
+ }
+ return jobGraph;
+ }
+
+ private void offloadJobVertex(JobVertex jobVertex) {
+ OperatorChainSliceGraphGenerator graphGenerator =
+ new OperatorChainSliceGraphGenerator(jobVertex, userClassloader);
+ OperatorChainSliceGraph chainSliceGraph = graphGenerator.getGraph();
+ chainSliceGraph.dumpLog();
+
+ OperatorChainSlice sourceChainSlice = chainSliceGraph.getSourceSlice();
+ OperatorChainSliceGraph targetChainSliceGraph = new OperatorChainSliceGraph();
+ visitAndOffloadChainOperators(sourceChainSlice, chainSliceGraph, targetChainSliceGraph, 0);
+ visitAndUpdateStreamEdges(sourceChainSlice, chainSliceGraph, targetChainSliceGraph);
+ serializeAllOperatorsConfigs(targetChainSliceGraph);
+
+ StreamConfig sourceConfig = sourceChainSlice.getOperatorConfigs().get(0);
+ StreamConfig targetSourceConfig =
+ targetChainSliceGraph.getSlice(sourceChainSlice.id()).getOperatorConfigs().get(0);
+
+ Map<Integer, StreamConfig> chainedConfig = new HashMap<Integer, StreamConfig>();
+ if (sourceChainSlice.isOffloadable()) {
+ // Update the first operator config
+ sourceConfig.setStreamOperatorFactory(
+ targetSourceConfig.getStreamOperatorFactory(userClassloader));
+ List<StreamEdge> chainedOutputs = targetSourceConfig.getChainedOutputs(userClassloader);
+ sourceConfig.setChainedOutputs(targetSourceConfig.getChainedOutputs(userClassloader));
+
+ // Update the serializers and partitioners
+ sourceConfig.setTypeSerializerOut(targetSourceConfig.getTypeSerializerOut(userClassloader));
+ sourceConfig.setInputs(targetSourceConfig.getInputs(userClassloader));
+ KeySelector<?, ?> keySelector0 = targetSourceConfig.getStatePartitioner(0, userClassloader);
+ if (keySelector0 != null) {
+ sourceConfig.setStatePartitioner(0, keySelector0);
+ }
+ KeySelector<?, ?> keySelector1 = targetSourceConfig.getStatePartitioner(1, userClassloader);
+ if (keySelector1 != null) {
+ sourceConfig.setStatePartitioner(1, keySelector1);
+ }
+
+ // The chained operators should be empty.
+ } else {
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+ for (int i = 1; i < operatorConfigs.size(); i++) {
+ StreamConfig opConfig = operatorConfigs.get(i);
+ chainedConfig.put(opConfig.getVertexID(), opConfig);
+ }
+ }
+ for (OperatorChainSlice chainSlice : targetChainSliceGraph.getSlices().values()) {
+ if (chainSlice.id().equals(sourceChainSlice.id())) {
+ continue;
+ }
+ List<StreamConfig> operatorConfigs = chainSlice.getOperatorConfigs();
+ for (StreamConfig opConfig : operatorConfigs) {
+ chainedConfig.put(opConfig.getVertexID(), opConfig);
+ }
+ }
+ sourceConfig.setAndSerializeTransitiveChainedTaskConfigs(chainedConfig);
+ sourceConfig.serializeAllConfigs();
+ }
+
+ // Fold offloadable operator chain slice
+ private void visitAndOffloadChainOperators(
+ OperatorChainSlice chainSlice,
+ OperatorChainSliceGraph originalChainSliceGraph,
+ OperatorChainSliceGraph targetChainSliceGraph,
+ Integer chainedIndex) {
+ List<Integer> outputs = chainSlice.getOutputs();
+ List<Integer> outputIndex = new ArrayList<>();
+ OperatorChainSlice finalChainSlice = null;
+ if (chainSlice.isOffloadable()) {
+ finalChainSlice =
+ OffloadOperatorChainSlice(originalChainSliceGraph, chainSlice, chainedIndex);
+ chainedIndex = chainedIndex + 1;
+ } else {
+ finalChainSlice = applyUnoffloadableOperatorChainSlice(chainSlice, chainedIndex);
+ chainedIndex = chainedIndex + chainSlice.getOperatorConfigs().size();
+ }
+
+ finalChainSlice.getInputs().addAll(chainSlice.getInputs());
+ finalChainSlice.getOutputs().addAll(chainSlice.getOutputs());
+ targetChainSliceGraph.addSlice(chainSlice.id(), finalChainSlice);
+
+ for (Integer outputChainIndex : outputs) {
+ OperatorChainSlice outputChainSlice = originalChainSliceGraph.getSlice(outputChainIndex);
+ OperatorChainSlice outputResultChainSlice = targetChainSliceGraph.getSlice(outputChainIndex);
+ if (outputResultChainSlice == null) {
+ visitAndOffloadChainOperators(
+ outputChainSlice, originalChainSliceGraph, targetChainSliceGraph, chainedIndex);
+ }
+ }
+ }
+
+ // Keep the original operator chain slice as is.
+ private OperatorChainSlice applyUnoffloadableOperatorChainSlice(
+ OperatorChainSlice originalChainSlice, Integer chainedIndex) {
+ OperatorChainSlice finalChainSlice = new OperatorChainSlice(originalChainSlice.id());
+ List<StreamConfig> operatorConfigs = originalChainSlice.getOperatorConfigs();
+ for (StreamConfig opConfig : operatorConfigs) {
+ StreamConfig newOpConfig = new StreamConfig(new Configuration(opConfig.getConfiguration()));
+ newOpConfig.setChainIndex(chainedIndex);
+ finalChainSlice.getOperatorConfigs().add(newOpConfig);
+ }
+ finalChainSlice.setOffloadable(false);
+ return finalChainSlice;
+ }
+
+ // Fold offloadable operator chain slice, and update the input/output channel serializers
+ private OperatorChainSlice OffloadOperatorChainSlice(
+ OperatorChainSliceGraph chainSliceGraph,
+ OperatorChainSlice originalChainSlice,
+ Integer chainedIndex) {
+ OperatorChainSlice finalChainSlice = new OperatorChainSlice(originalChainSlice.id());
+ List<StreamConfig> operatorConfigs = originalChainSlice.getOperatorConfigs();
+
+ // May coalesce multiple operators into one in the future.
+ if (operatorConfigs.size() != 1) {
+ throw new UnsupportedOperationException(
+ "Only one operator is supported for offloaded operator chain slice.");
+ }
+
+ StreamConfig originalOpConfig = operatorConfigs.get(0);
+ GlutenOperator originalOp = getGlutenOperator(originalOpConfig).get();
+ StatefulPlanNode planNode = originalOp.getPlanNode();
+ // Create a new operator config for the offloaded operator.
+ StreamConfig finalOpConfig =
+ new StreamConfig(new Configuration(originalOpConfig.getConfiguration()));
+ if (originalOp instanceof GlutenStreamSource) {
+ boolean couldOutputRowVector = couldOutputRowVector(originalChainSlice, chainSliceGraph);
+ Class<?> outClass = couldOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenStreamSource newSourceOp =
+ new GlutenStreamSource(
+ new GlutenSourceFunction<>(
+ planNode,
+ originalOp.getOutputTypes(),
+ originalOp.getId(),
+ ((GlutenStreamSource) originalOp).getConnectorSplit(),
+ outClass));
+ finalOpConfig.setStreamOperator(newSourceOp);
+ if (couldOutputRowVector) {
+ RowType rowType = originalOp.getOutputTypes().entrySet().iterator().next().getValue();
+ finalOpConfig.setTypeSerializerOut(
+ new GlutenStatefulRecordSerializer(rowType, originalOp.getId()));
+ }
+ } else if (originalOp instanceof GlutenOneInputOperator) {
+ boolean couldOutputRowVector = couldOutputRowVector(originalChainSlice, chainSliceGraph);
+ boolean couldInputRowVector = couldInputRowVector(originalChainSlice, chainSliceGraph);
+ Class<?> inClass = couldInputRowVector ? StatefulRecord.class : RowData.class;
+ Class<?> outClass = couldOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenOneInputOperator<?, ?> newOneInputOp =
+ new GlutenOneInputOperator<>(
+ planNode,
+ originalOp.getId(),
+ originalOp.getInputType(),
+ originalOp.getOutputTypes(),
+ inClass,
+ outClass,
+ originalOp.getDescription());
+ finalOpConfig.setStreamOperator(newOneInputOp);
+ if (couldOutputRowVector) {
+ RowType rowType = originalOp.getOutputTypes().entrySet().iterator().next().getValue();
+ finalOpConfig.setTypeSerializerOut(
+ new GlutenStatefulRecordSerializer(rowType, originalOp.getId()));
+ }
+ if (couldInputRowVector) {
+ finalOpConfig.setupNetworkInputs(
+ new GlutenStatefulRecordSerializer(originalOp.getInputType(), originalOp.getId()));
+
+ // This node is the first node in the chain. If it has a state partitioner, we need to
+ // change it to GlutenKeySelector.
+ KeySelector<?, ?> keySelector = originalOpConfig.getStatePartitioner(0, userClassloader);
+ if (keySelector != null) {
+ LOG.info(
+ "State partitioner ({}) found in the first node {}, change it to GlutenKeySelector.",
+ keySelector.getClass().getName(),
+ originalOp.getDescription());
+ finalOpConfig.setStatePartitioner(0, new GlutenKeySelector());
+ }
+ }
+ } else if (originalOp instanceof GlutenTwoInputOperator) {
+ GlutenTwoInputOperator<?, ?> twoInputOp = (GlutenTwoInputOperator<?, ?>) originalOp;
+ boolean couldOutputRowVector = couldOutputRowVector(originalChainSlice, chainSliceGraph);
+ boolean couldInputRowVector = couldInputRowVector(originalChainSlice, chainSliceGraph);
+ KeySelector<?, ?> keySelector0 = originalOpConfig.getStatePartitioner(0, userClassloader);
+ if (keySelector0 != null) {
+ LOG.info(
+ "State partitioner ({}) found in the first node {}, change it to GlutenKeySelector.",
+ keySelector0.getClass().getName(),
+ originalOp.getDescription());
+ finalOpConfig.setStatePartitioner(0, new GlutenKeySelector());
+ }
+ KeySelector<?, ?> keySelector1 = originalOpConfig.getStatePartitioner(1, userClassloader);
+ if (keySelector1 != null) {
+ LOG.info(
+ "State partitioner ({}) found in the second node {}, change it to GlutenKeySelector.",
+ keySelector1.getClass().getName(),
+ originalOp.getDescription());
+ finalOpConfig.setStatePartitioner(1, new GlutenKeySelector());
+ }
+ Class<?> inClass = couldInputRowVector ? StatefulRecord.class : RowData.class;
+ Class<?> outClass = couldOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenTwoInputOperator<?, ?> newTwoInputOp =
+ new GlutenTwoInputOperator<>(
+ planNode,
+ twoInputOp.getLeftId(),
+ twoInputOp.getRightId(),
+ twoInputOp.getLeftInputType(),
+ twoInputOp.getRightInputType(),
+ twoInputOp.getOutputTypes(),
+ inClass,
+ outClass);
+ finalOpConfig.setStreamOperator(newTwoInputOp);
+ finalOpConfig.setStatePartitioner(0, new GlutenKeySelector());
+ finalOpConfig.setStatePartitioner(1, new GlutenKeySelector());
+ // Update the output channel serializer
+ if (couldOutputRowVector) {
+ RowType rowType = twoInputOp.getOutputTypes().entrySet().iterator().next().getValue();
+ finalOpConfig.setTypeSerializerOut(
+ new GlutenStatefulRecordSerializer(rowType, twoInputOp.getId()));
+ }
+ // Update the input channel serializers
+ if (couldInputRowVector) {
+ finalOpConfig.setupNetworkInputs(
+ new GlutenStatefulRecordSerializer(twoInputOp.getLeftInputType(), twoInputOp.getId()),
+ new GlutenStatefulRecordSerializer(twoInputOp.getRightInputType(), twoInputOp.getId()));
+ }
+ } else {
+ throw new UnsupportedOperationException(
+ "Only GlutenStreamSource is supported for offloaded operator chain slice.");
+ }
+
+ finalOpConfig.setChainIndex(chainedIndex);
+ finalChainSlice.getOperatorConfigs().add(finalOpConfig);
+ finalChainSlice.setOffloadable(true);
+ return finalChainSlice;
+ }
+
+ private StreamNode mockStreamNode(StreamConfig streamConfig) {
+ return new StreamNode(
+ streamConfig.getVertexID(),
+ null,
+ null,
+ (StreamOperatorFactory<?>) streamConfig.getStreamOperatorFactory(userClassloader),
+ streamConfig.getOperatorName(),
+ null);
+ }
+
+ // Incase the vetexs has been changed, update the stream edges.
Review Comment:
Corrected spelling of 'Incase' to 'In case' and 'vetexs' to 'vertices'.
```suggestion
// In case the vertices have been changed, update the stream 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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org
Re: [PR] [GLUTEN-11364][Flink] Improve the job graph generation code [incubator-gluten]
Posted by "KevinyhZou (via GitHub)" <gi...@apache.org>.
KevinyhZou commented on PR #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365#issuecomment-3741595077
LGTM
--
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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org
Re: [PR] [GLUTEN-11364][FLINK] Improve the job graph generation code [incubator-gluten]
Posted by "lgbo-ustc (via GitHub)" <gi...@apache.org>.
lgbo-ustc merged PR #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365
--
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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org
Re: [PR] [GLUTEN-11364][Flink] Improve the job graph generation code [incubator-gluten]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365#discussion_r2684538572
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/util/VectorInputBridge.java:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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.gluten.util;
+
+import io.github.zhztheplayer.velox4j.session.Session;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.type.RowType;
+
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+
+import org.apache.arrow.memory.BufferAllocator;
+
+import java.io.Serializable;
+
+/**
+ * Interface for converting input data from Flink StreamRecord to StatefulRecord. Different
+ * implementations handle different input types.
+ */
+public interface VectorInputBridge<IN> extends Serializable {
+
+ /**
+ * Converts a StreamRecord to StatefulRecord based on the input type.
+ *
+ * @param inputData the input StreamRecord
+ * @param allocator buffer allocator for creating RowVector
+ * @param session Velox session
+ * @param inputType the RowType schema of the input
+ * @return StatefulRecord containing the converted or original data
+ */
+ StatefulRecord convertToStatefulRecord(
+ StreamRecord<IN> inputData, BufferAllocator allocator, Session session, RowType inputType);
+
+ /** Factory for creating VectorInputBridge instances based on input type. */
+ class Factory {
+ /**
+ * Creates a VectorInputBridge instance for the given input class.
+ *
+ * @param inputClass the input class type
+ * @param nodeId the node ID for the bridge
+ * @param <IN> the input type
+ * @return a VectorInputBridge instance
+ * @throws UnsupportedOperationException if input class is not supported
+ */
+ public static <IN> VectorInputBridge<IN> create(Class<IN> inputClass, String nodeId) {
+ if (inputClass.isAssignableFrom(org.apache.flink.table.data.RowData.class)) {
+ @SuppressWarnings("unchecked")
+ VectorInputBridge<IN> bridge = (VectorInputBridge<IN>) new RowDataInputBridge(nodeId);
+ return bridge;
+ } else if (inputClass.isAssignableFrom(StatefulRecord.class)) {
+ @SuppressWarnings("unchecked")
+ VectorInputBridge<IN> bridge = (VectorInputBridge<IN>) new StatefulRecordInputBridge();
+ return bridge;
+ } else {
+ throw new UnsupportedOperationException("Unsupported input class: " + inputClass.getName());
+ }
+ }
+ }
+
+ /**
+ * Implementation for RowData input type. Converts RowData to RowVector and wraps in
+ * StatefulRecord.
+ */
+ class RowDataInputBridge implements VectorInputBridge<org.apache.flink.table.data.RowData> {
+ private static final long serialVersionUID = 1L;
+ private final String nodeId;
+
+ public RowDataInputBridge(String nodeId) {
+ this.nodeId = nodeId;
+ }
+
+ @Override
+ public StatefulRecord convertToStatefulRecord(
+ StreamRecord<org.apache.flink.table.data.RowData> inputData,
+ BufferAllocator allocator,
+ Session session,
+ RowType inputType) {
+ org.apache.flink.table.data.RowData rowData = inputData.getValue();
+ var rowVector =
+ org.apache.gluten.vectorized.FlinkRowToVLVectorConvertor.fromRowData(
+ rowData, allocator, session, inputType);
+ StatefulRecord statefulRecord = new StatefulRecord(nodeId, rowVector.id(), 0, false, -1);
+ statefulRecord.setRowVector(rowVector);
+ return statefulRecord;
+ }
+ }
+
+ /** Implementation for StatefulRecord input type. Passes through the StatefulRecord directly. */
+ class StatefulRecordInputBridge implements VectorInputBridge<StatefulRecord> {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public StatefulRecord convertToStatefulRecord(
+ StreamRecord<StatefulRecord> inputData,
+ BufferAllocator allocator,
+ Session session,
+ RowType inputType) {
+ // Pass through the StatefulRecord directly. The original RowVector object is safe to close.
Review Comment:
This comment is ambiguous. It's unclear whether the comment means the caller should close the RowVector or that closing is handled elsewhere. Clarify the ownership and lifecycle management of the RowVector resource.
```suggestion
// Pass through the StatefulRecord directly. This bridge does not take ownership of or close
// the underlying RowVector; its lifecycle is managed by the code that created the
// StatefulRecord.
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OperatorChainSliceGraph.java:
##########
@@ -0,0 +1,85 @@
+/*
+ * 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.gluten.client;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OperatorChainSliceGraph {
+ private Map<Integer, OperatorChainSlice> slices;
+
+ public OperatorChainSliceGraph() {
+ slices = new HashMap<>();
+ }
+
+ public void addSlice(Integer id, OperatorChainSlice chainSlice) {
+ slices.put(id, chainSlice);
+ }
+
+ public OperatorChainSlice getSlice(Integer id) {
+ return slices.get(id);
+ }
+
+ public OperatorChainSlice getSourceSlice() {
+ List<OperatorChainSlice> sourceCandidates = new ArrayList<>();
+
+ for (OperatorChainSlice chainSlice : slices.values()) {
+ if (chainSlice.getInputs().isEmpty()) {
+ sourceCandidates.add(chainSlice);
+ }
+ }
+
+ if (sourceCandidates.isEmpty()) {
+ throw new IllegalStateException(
+ "No source suboperator chain found (no suboperator chain with empty inputs)");
+ } else if (sourceCandidates.size() > 1) {
+ throw new IllegalStateException(
+ "Multiple source suboperator chains found: "
+ + sourceCandidates.size()
+ + " suboperator chains have empty inputs");
Review Comment:
The term 'suboperator chain' is inconsistent with the class name 'OperatorChainSlice'. Consider using 'operator chain slice' consistently throughout the codebase for clarity.
```suggestion
"No source operator chain slice found (no operator chain slice with empty inputs)");
} else if (sourceCandidates.size() > 1) {
throw new IllegalStateException(
"Multiple source operator chain slices found: "
+ sourceCandidates.size()
+ " operator chain slices have empty inputs");
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenSourceFunction.java:
##########
@@ -88,48 +96,139 @@ public ConnectorSplit getConnectorSplit() {
}
@Override
- public void run(SourceContext<RowData> sourceContext) throws Exception {
- LOG.debug("Running GlutenSourceFunction: " + Serde.toJson(planNode));
- memoryManager = MemoryManager.create(AllocationListener.NOOP);
- session = Velox4j.newSession(memoryManager);
- query =
- new Query(
- planNode,
- VeloxQueryConfig.getConfig(getRuntimeContext()),
- VeloxConnectorConfig.getConfig(getRuntimeContext()));
- allocator = new RootAllocator(Long.MAX_VALUE);
+ public void open(Configuration parameters) throws Exception {
+ initSession();
+ }
- SerialTask task = session.queryOps().execute(query);
- task.addSplit(id, split);
- task.noMoreSplits(id);
+ @Override
+ public void run(SourceContext<OUT> sourceContext) throws Exception {
while (isRunning) {
UpIterator.State state = task.advance();
- if (state == UpIterator.State.AVAILABLE) {
- final StatefulElement element = task.statefulGet();
- try (final RowVector outRv = element.asRecord().getRowVector()) {
- List<RowData> rows =
- FlinkRowToVLVectorConvertor.toRowData(
- outRv, allocator, outputTypes.values().iterator().next());
- for (RowData row : rows) {
- sourceContext.collect(row);
- }
- }
- } else if (state == UpIterator.State.BLOCKED) {
- LOG.debug("Get empty row");
+ switch (state) {
+ case AVAILABLE:
+ processAvailableElement(sourceContext);
+ break;
+ case BLOCKED:
+ LOG.debug("Get empty row");
+ break;
+ default:
+ LOG.info("Velox task finished");
+ return;
+ }
+ taskMetrics.updateMetrics(task, id);
+ }
+ }
+
+ /** Processes an available element from the task, handling records and watermarks. */
+ private void processAvailableElement(SourceContext<OUT> sourceContext) {
+ StatefulElement element = task.statefulGet();
+ try {
+ if (element.isRecord()) {
+ processRecord(sourceContext, element.asRecord());
+ } else if (element.isWatermark()) {
+ processWatermark(sourceContext, element.asWatermark());
} else {
- LOG.info("Velox task finished");
- break;
+ LOG.debug("Ignoring element that is neither record nor watermark");
}
+ } finally {
+ element.close();
}
+ }
+
+ /** Processes a StatefulRecord and collects it to the source context. */
+ private void processRecord(SourceContext<OUT> sourceContext, StatefulRecord record) {
+ if (isRowDataOutput()) {
+ collectAsRowData(sourceContext, record);
+ } else if (isStatefulRecordOutput()) {
+ collectAsStatefulRecord(sourceContext, record);
+ } else {
+ throw new UnsupportedOperationException("Unsupported output class: " + outClass.getName());
+ }
+ }
+
Review Comment:
The output type checking logic is duplicated between `isRowDataOutput()`, `isStatefulRecordOutput()`, and the exception message. Consider refactoring to use a strategy pattern or a map of output type handlers to reduce code duplication and improve maintainability.
```suggestion
/** Strategy for collecting a StatefulRecord into the source context. */
private interface OutputHandler {
void collect(SourceContext<OUT> sourceContext, StatefulRecord record);
}
/** Returns the appropriate OutputHandler based on the configured output class. */
private OutputHandler getOutputHandler() {
if (isRowDataOutput()) {
return this::collectAsRowData;
}
if (isStatefulRecordOutput()) {
return this::collectAsStatefulRecord;
}
throw unsupportedOutputException();
}
/** Creates an exception for unsupported output class configurations. */
private UnsupportedOperationException unsupportedOutputException() {
return new UnsupportedOperationException("Unsupported output class: " + outClass.getName());
}
/** Processes a StatefulRecord and collects it to the source context. */
private void processRecord(SourceContext<OUT> sourceContext, StatefulRecord record) {
OutputHandler handler = getOutputHandler();
handler.collect(sourceContext, record);
}
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenOneInputOperator.java:
##########
@@ -104,43 +141,66 @@ public void open() throws Exception {
mockInput,
VeloxQueryConfig.getConfig(getRuntimeContext()),
VeloxConnectorConfig.getConfig(getRuntimeContext()));
- allocator = new RootAllocator(Long.MAX_VALUE);
- task = session.queryOps().execute(query);
- ExternalStreamConnectorSplit split =
- new ExternalStreamConnectorSplit("connector-external-stream", inputQueue.id());
- task.addSplit(id, split);
+ task = sessionResource.getSession().queryOps().execute(query);
+ task.addSplit(
+ id, new ExternalStreamConnectorSplit("connector-external-stream", inputQueue.id()));
task.noMoreSplits(id);
}
@Override
- public void processElement(StreamRecord<RowData> element) {
- try (RowVector inRv =
- FlinkRowToVLVectorConvertor.fromRowData(
- element.getValue(), allocator, session, inputType)) {
- inputQueue.put(inRv);
+ public void open() throws Exception {
+ super.open();
+ initSession();
+ }
+
+ @Override
+ public void processElement(StreamRecord<IN> element) {
+ if (element.getValue() == null) {
+ return;
+ }
+ StatefulRecord statefulRecord =
+ inputBridge.convertToStatefulRecord(
+ element, sessionResource.getAllocator(), sessionResource.getSession(), inputType);
+ inputQueue.put(statefulRecord.getRowVector());
+
+ // Only the rowvectors generated by this operator should be closed here.
+ if (getId().equals(statefulRecord.getNodeId())) {
+ statefulRecord.close();
+ }
+ processElementInternal();
+ }
+
+ private void processElementInternal() {
+ while (true) {
UpIterator.State state = task.advance();
if (state == UpIterator.State.AVAILABLE) {
final StatefulElement statefulElement = task.statefulGet();
-
- try (RowVector outRv = statefulElement.asRecord().getRowVector()) {
- List<RowData> rows =
- FlinkRowToVLVectorConvertor.toRowData(
- outRv, allocator, outputTypes.values().iterator().next());
- for (RowData row : rows) {
- output.collect(outElement.replace(row));
- }
+ if (statefulElement.isWatermark()) {
+ StatefulWatermark watermark = statefulElement.asWatermark();
+ output.emitWatermark(new Watermark(watermark.getTimestamp()));
+ } else {
+ outputBridge.collect(
+ output, statefulElement.asRecord(), sessionResource.getAllocator(), outputType);
}
+ statefulElement.close();
+ } else {
+ break;
}
}
}
@Override
public void close() throws Exception {
- inputQueue.close();
- task.close();
- session.close();
- memoryManager.close();
- allocator.close();
+ if (inputQueue != null) {
+ inputQueue.noMoreInput();
Review Comment:
The `noMoreInput()` call should be wrapped in a null check similar to the other cleanup operations. If `inputQueue` is null, this will throw a NullPointerException.
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenOneInputOperator.java:
##########
@@ -19,75 +19,112 @@
import org.apache.gluten.streaming.api.operators.GlutenOperator;
import org.apache.gluten.table.runtime.config.VeloxConnectorConfig;
import org.apache.gluten.table.runtime.config.VeloxQueryConfig;
-import org.apache.gluten.vectorized.FlinkRowToVLVectorConvertor;
+import org.apache.gluten.util.VectorInputBridge;
+import org.apache.gluten.util.VectorOutputBridge;
-import io.github.zhztheplayer.velox4j.Velox4j;
import io.github.zhztheplayer.velox4j.connector.ExternalStreamConnectorSplit;
import io.github.zhztheplayer.velox4j.connector.ExternalStreamTableHandle;
import io.github.zhztheplayer.velox4j.connector.ExternalStreams;
-import io.github.zhztheplayer.velox4j.data.RowVector;
import io.github.zhztheplayer.velox4j.iterator.UpIterator;
-import io.github.zhztheplayer.velox4j.memory.AllocationListener;
-import io.github.zhztheplayer.velox4j.memory.MemoryManager;
import io.github.zhztheplayer.velox4j.plan.StatefulPlanNode;
import io.github.zhztheplayer.velox4j.plan.TableScanNode;
import io.github.zhztheplayer.velox4j.query.Query;
import io.github.zhztheplayer.velox4j.query.SerialTask;
import io.github.zhztheplayer.velox4j.serde.Serde;
-import io.github.zhztheplayer.velox4j.session.Session;
import io.github.zhztheplayer.velox4j.stateful.StatefulElement;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.stateful.StatefulWatermark;
import io.github.zhztheplayer.velox4j.type.RowType;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
-import org.apache.flink.table.data.RowData;
import org.apache.flink.table.runtime.operators.TableStreamOperator;
-import org.apache.arrow.memory.BufferAllocator;
-import org.apache.arrow.memory.RootAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
/** Calculate operator in gluten, which will call Velox to run. */
-public class GlutenOneInputOperator extends TableStreamOperator<RowData>
- implements OneInputStreamOperator<RowData, RowData>, GlutenOperator {
+public class GlutenOneInputOperator<IN, OUT> extends TableStreamOperator<OUT>
+ implements OneInputStreamOperator<IN, OUT>, GlutenOperator {
private static final Logger LOG = LoggerFactory.getLogger(GlutenOneInputOperator.class);
private final StatefulPlanNode glutenPlan;
private final String id;
private final RowType inputType;
private final Map<String, RowType> outputTypes;
+ private final RowType outputType;
+ private final String description;
- private StreamRecord<RowData> outElement = null;
-
- private MemoryManager memoryManager;
- private Session session;
- private Query query;
- private ExternalStreams.BlockingQueue inputQueue;
- private BufferAllocator allocator;
- private SerialTask task;
+ private transient GlutenSessionResource sessionResource;
+ private transient Query query;
+ private transient ExternalStreams.BlockingQueue inputQueue;
+ private transient SerialTask task;
+ private final Class<IN> inClass;
+ private final Class<OUT> outClass;
+ private transient VectorInputBridge<IN> inputBridge;
+ private transient VectorOutputBridge<OUT> outputBridge;
public GlutenOneInputOperator(
- StatefulPlanNode plan, String id, RowType inputType, Map<String, RowType> outputTypes) {
+ StatefulPlanNode plan,
+ String id,
+ RowType inputType,
+ Map<String, RowType> outputTypes,
+ Class<IN> inClass,
+ Class<OUT> outClass,
+ String description) {
+ if (plan == null) {
+ throw new IllegalArgumentException("plan is null");
Review Comment:
The error message should be more descriptive. Consider including context about which parameter is null and what the expected value should be. For example: 'StatefulPlanNode cannot be null in GlutenOneInputOperator constructor'.
```suggestion
throw new IllegalArgumentException(
"StatefulPlanNode 'plan' cannot be null in GlutenOneInputOperator constructor");
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenOneInputOperator.java:
##########
@@ -19,75 +19,112 @@
import org.apache.gluten.streaming.api.operators.GlutenOperator;
import org.apache.gluten.table.runtime.config.VeloxConnectorConfig;
import org.apache.gluten.table.runtime.config.VeloxQueryConfig;
-import org.apache.gluten.vectorized.FlinkRowToVLVectorConvertor;
+import org.apache.gluten.util.VectorInputBridge;
+import org.apache.gluten.util.VectorOutputBridge;
-import io.github.zhztheplayer.velox4j.Velox4j;
import io.github.zhztheplayer.velox4j.connector.ExternalStreamConnectorSplit;
import io.github.zhztheplayer.velox4j.connector.ExternalStreamTableHandle;
import io.github.zhztheplayer.velox4j.connector.ExternalStreams;
-import io.github.zhztheplayer.velox4j.data.RowVector;
import io.github.zhztheplayer.velox4j.iterator.UpIterator;
-import io.github.zhztheplayer.velox4j.memory.AllocationListener;
-import io.github.zhztheplayer.velox4j.memory.MemoryManager;
import io.github.zhztheplayer.velox4j.plan.StatefulPlanNode;
import io.github.zhztheplayer.velox4j.plan.TableScanNode;
import io.github.zhztheplayer.velox4j.query.Query;
import io.github.zhztheplayer.velox4j.query.SerialTask;
import io.github.zhztheplayer.velox4j.serde.Serde;
-import io.github.zhztheplayer.velox4j.session.Session;
import io.github.zhztheplayer.velox4j.stateful.StatefulElement;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.stateful.StatefulWatermark;
import io.github.zhztheplayer.velox4j.type.RowType;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
-import org.apache.flink.table.data.RowData;
import org.apache.flink.table.runtime.operators.TableStreamOperator;
-import org.apache.arrow.memory.BufferAllocator;
-import org.apache.arrow.memory.RootAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
/** Calculate operator in gluten, which will call Velox to run. */
-public class GlutenOneInputOperator extends TableStreamOperator<RowData>
- implements OneInputStreamOperator<RowData, RowData>, GlutenOperator {
+public class GlutenOneInputOperator<IN, OUT> extends TableStreamOperator<OUT>
+ implements OneInputStreamOperator<IN, OUT>, GlutenOperator {
private static final Logger LOG = LoggerFactory.getLogger(GlutenOneInputOperator.class);
private final StatefulPlanNode glutenPlan;
private final String id;
private final RowType inputType;
private final Map<String, RowType> outputTypes;
+ private final RowType outputType;
+ private final String description;
- private StreamRecord<RowData> outElement = null;
-
- private MemoryManager memoryManager;
- private Session session;
- private Query query;
- private ExternalStreams.BlockingQueue inputQueue;
- private BufferAllocator allocator;
- private SerialTask task;
+ private transient GlutenSessionResource sessionResource;
+ private transient Query query;
+ private transient ExternalStreams.BlockingQueue inputQueue;
+ private transient SerialTask task;
+ private final Class<IN> inClass;
+ private final Class<OUT> outClass;
+ private transient VectorInputBridge<IN> inputBridge;
+ private transient VectorOutputBridge<OUT> outputBridge;
public GlutenOneInputOperator(
- StatefulPlanNode plan, String id, RowType inputType, Map<String, RowType> outputTypes) {
+ StatefulPlanNode plan,
+ String id,
+ RowType inputType,
+ Map<String, RowType> outputTypes,
+ Class<IN> inClass,
+ Class<OUT> outClass,
+ String description) {
+ if (plan == null) {
+ throw new IllegalArgumentException("plan is null");
+ }
this.glutenPlan = plan;
this.id = id;
this.inputType = inputType;
this.outputTypes = outputTypes;
+ this.inClass = inClass;
+ this.outClass = outClass;
+ this.inputBridge = VectorInputBridge.Factory.create(inClass, getId());
+ this.outputBridge = VectorOutputBridge.Factory.create(outClass);
+ this.outputType = outputTypes.values().iterator().next();
+ this.description = description;
+ }
+
+ public GlutenOneInputOperator(
+ StatefulPlanNode plan,
+ String id,
+ RowType inputType,
+ Map<String, RowType> outputTypes,
+ Class<IN> inClass,
+ Class<OUT> outClass) {
+ this(plan, id, inputType, outputTypes, inClass, outClass, "");
}
@Override
- public void open() throws Exception {
- super.open();
- outElement = new StreamRecord(null);
- memoryManager = MemoryManager.create(AllocationListener.NOOP);
- session = Velox4j.newSession(memoryManager);
+ public String getDescription() {
+ return description;
+ }
- inputQueue = session.externalStreamOps().newBlockingQueue();
+ void initSession() {
+ if (sessionResource != null) {
+ return;
+ }
+ if (inputBridge == null) {
+ inputBridge = VectorInputBridge.Factory.create(inClass, getId());
+ }
+ if (outputBridge == null) {
+ outputBridge = VectorOutputBridge.Factory.create(outClass);
+ }
+ sessionResource = new GlutenSessionResource();
+ inputQueue = sessionResource.getSession().externalStreamOps().newBlockingQueue();
// add a mock input as velox not allow the source is empty.
+ if (inputType == null) {
+ throw new IllegalArgumentException("inputType is null. plan is " + Serde.toJson(glutenPlan));
Review Comment:
The error message should not serialize the entire plan as it may be large and contain sensitive information. Consider logging the plan separately if needed for debugging, and keep the exception message concise: 'inputType cannot be null'.
```suggestion
if (LOG.isDebugEnabled()) {
LOG.debug("inputType is null. Plan: {}", Serde.toJson(glutenPlan));
}
throw new IllegalArgumentException("inputType cannot be null");
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OffloadedJobGraphGenerator.java:
##########
@@ -0,0 +1,611 @@
+/*
+ * 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.gluten.client;
+
+import org.apache.gluten.streaming.api.operators.GlutenOperator;
+import org.apache.gluten.streaming.api.operators.GlutenStreamSource;
+import org.apache.gluten.table.runtime.keyselector.GlutenKeySelector;
+import org.apache.gluten.table.runtime.operators.GlutenOneInputOperator;
+import org.apache.gluten.table.runtime.operators.GlutenSourceFunction;
+import org.apache.gluten.table.runtime.operators.GlutenTwoInputOperator;
+import org.apache.gluten.table.runtime.typeutils.GlutenStatefulRecordSerializer;
+import org.apache.gluten.util.Utils;
+
+import io.github.zhztheplayer.velox4j.plan.StatefulPlanNode;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.type.RowType;
+
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.jobgraph.IntermediateDataSet;
+import org.apache.flink.runtime.jobgraph.JobEdge;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.jobgraph.JobVertex;
+import org.apache.flink.streaming.api.graph.StreamConfig;
+import org.apache.flink.streaming.api.graph.StreamEdge;
+import org.apache.flink.streaming.api.graph.StreamNode;
+import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
+import org.apache.flink.table.data.RowData;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/*
+ * Generates an offloaded JobGraph by transforming offloadable operators to Gluten operators.
+ * Main workflow:
+ * 1. For each JobVertex, generate an OperatorChainSliceGraph to identify offloadable slices.
+ * 2. Recursively visit chain slices: create offloaded operators for offloadable slices,
+ * keep original operators for unoffloadable ones.
+ * 3. For offloadable operators: update input/output serializers and state partitioners
+ * based on upstream/downstream operator capabilities.
+ * 4. Update stream edges and serialize all operator configurations.
+ */
+public class OffloadedJobGraphGenerator {
+ private static final Logger LOG = LoggerFactory.getLogger(OffloadedJobGraphGenerator.class);
+ private final JobGraph jobGraph;
+ private final ClassLoader userClassloader;
+ private boolean hasGenerated = false;
+
+ public OffloadedJobGraphGenerator(JobGraph jobGraph, ClassLoader userClassloader) {
+ this.jobGraph = jobGraph;
+ this.userClassloader = userClassloader;
+ }
+
+ public JobGraph generate() {
+ if (hasGenerated) {
+ throw new IllegalStateException("JobGraph has been generated.");
+ }
+ hasGenerated = true;
+ for (JobVertex jobVertex : jobGraph.getVertices()) {
+ offloadJobVertex(jobVertex);
+ }
+ return jobGraph;
+ }
+
+ private void offloadJobVertex(JobVertex jobVertex) {
+ OperatorChainSliceGraphGenerator graphGenerator =
+ new OperatorChainSliceGraphGenerator(jobVertex, userClassloader);
+ OperatorChainSliceGraph chainSliceGraph = graphGenerator.getGraph();
+ LOG.info("OperatorChainSliceGraph:\n{}", chainSliceGraph);
+
+ OperatorChainSlice sourceChainSlice = chainSliceGraph.getSourceSlice();
+ OperatorChainSliceGraph offloadedChainSliceGraph = new OperatorChainSliceGraph();
+ visitAndOffloadChainOperators(
+ sourceChainSlice, chainSliceGraph, offloadedChainSliceGraph, 0, jobVertex);
+ visitAndUpdateStreamEdges(sourceChainSlice, chainSliceGraph, offloadedChainSliceGraph);
+ serializeAllOperatorsConfigs(offloadedChainSliceGraph);
+
+ StreamConfig sourceConfig = sourceChainSlice.getOperatorConfigs().get(0);
+ StreamConfig offloadedSourceConfig =
+ offloadedChainSliceGraph.getSlice(sourceChainSlice.id()).getOperatorConfigs().get(0);
+
+ Map<Integer, StreamConfig> chainedConfigs =
+ collectChainedConfigs(sourceChainSlice, offloadedChainSliceGraph);
+ updateSourceConfigIfOffloadable(
+ sourceConfig, offloadedSourceConfig, sourceChainSlice, chainedConfigs);
+ sourceConfig.setAndSerializeTransitiveChainedTaskConfigs(chainedConfigs);
+ sourceConfig.serializeAllConfigs();
+ }
+
+ // Process and offload operator chain slices recursively
+ private void visitAndOffloadChainOperators(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph,
+ Integer chainIndex,
+ JobVertex jobVertex) {
+ OperatorChainSlice processedChainSlice;
+ if (sourceChainSlice.isOffloadable()) {
+ processedChainSlice =
+ createOffloadedOperatorChainSlice(
+ sourceChainSliceGraph, sourceChainSlice, chainIndex, jobVertex);
+ chainIndex = chainIndex + 1;
+ } else {
+ processedChainSlice = createUnoffloadableOperatorChainSlice(sourceChainSlice, chainIndex);
+ chainIndex = chainIndex + sourceChainSlice.getOperatorConfigs().size();
+ }
+
+ processedChainSlice.getInputs().addAll(sourceChainSlice.getInputs());
+ processedChainSlice.getOutputs().addAll(sourceChainSlice.getOutputs());
+ offloadedChainSliceGraph.addSlice(sourceChainSlice.id(), processedChainSlice);
+
+ // Recursively process downstream chain slices
+ for (Integer downstreamSliceId : sourceChainSlice.getOutputs()) {
+ OperatorChainSlice downstreamSourceSlice = sourceChainSliceGraph.getSlice(downstreamSliceId);
+ OperatorChainSlice downstreamProcessedSlice =
+ offloadedChainSliceGraph.getSlice(downstreamSliceId);
+ if (downstreamProcessedSlice == null) {
+ visitAndOffloadChainOperators(
+ downstreamSourceSlice,
+ sourceChainSliceGraph,
+ offloadedChainSliceGraph,
+ chainIndex,
+ jobVertex);
+ }
+ }
+ }
+
+ // Keep the original operator chain slice as is.
+ private OperatorChainSlice createUnoffloadableOperatorChainSlice(
+ OperatorChainSlice sourceChainSlice, Integer chainIndex) {
+ OperatorChainSlice unoffloadableChainSlice = new OperatorChainSlice(sourceChainSlice.id());
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+ for (StreamConfig opConfig : operatorConfigs) {
+ StreamConfig newOpConfig = new StreamConfig(new Configuration(opConfig.getConfiguration()));
+ newOpConfig.setChainIndex(chainIndex);
+ unoffloadableChainSlice.getOperatorConfigs().add(newOpConfig);
+ }
+ unoffloadableChainSlice.setOffloadable(false);
+ return unoffloadableChainSlice;
+ }
+
+ // Create offloadable operator chain slice, and update the input/output channel serializers
+ private OperatorChainSlice createOffloadedOperatorChainSlice(
+ OperatorChainSliceGraph chainSliceGraph,
+ OperatorChainSlice sourceChainSlice,
+ Integer chainIndex,
+ JobVertex jobVertex) {
+ OperatorChainSlice offloadedChainSlice = new OperatorChainSlice(sourceChainSlice.id());
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+
+ // May coalesce multiple operators into one in the future.
+ if (operatorConfigs.size() != 1) {
+ throw new UnsupportedOperationException(
+ "Only one operator is supported for offloaded operator chain slice.");
+ }
+
+ StreamConfig sourceOpConfig = operatorConfigs.get(0);
+ GlutenOperator sourceOperator = Utils.getGlutenOperator(sourceOpConfig, userClassloader).get();
+ StatefulPlanNode planNode = sourceOperator.getPlanNode();
+ // Create a new operator config for the offloaded operator.
+ StreamConfig offloadedOpConfig =
+ new StreamConfig(new Configuration(sourceOpConfig.getConfiguration()));
+ if (sourceOperator instanceof GlutenStreamSource) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenStreamSource newSourceOp =
+ new GlutenStreamSource(
+ new GlutenSourceFunction<>(
+ planNode,
+ sourceOperator.getOutputTypes(),
+ sourceOperator.getId(),
+ ((GlutenStreamSource) sourceOperator).getConnectorSplit(),
+ outClass));
+ offloadedOpConfig.setStreamOperator(newSourceOp);
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ } else if (sourceOperator instanceof GlutenOneInputOperator) {
+ createOffloadedOneInputOperator(
+ sourceChainSlice,
+ chainSliceGraph,
+ jobVertex,
+ planNode,
+ (GlutenOneInputOperator<?, ?>) sourceOperator,
+ sourceOpConfig,
+ offloadedOpConfig);
+ } else if (sourceOperator instanceof GlutenTwoInputOperator) {
+ createOffloadedTwoInputOperator(
+ sourceChainSlice,
+ chainSliceGraph,
+ jobVertex,
+ planNode,
+ (GlutenTwoInputOperator<?, ?>) sourceOperator,
+ sourceOpConfig,
+ offloadedOpConfig);
+ } else {
+ throw new UnsupportedOperationException(
+ "Unsupported operator type for offloading: " + sourceOperator.getClass().getName());
+ }
+
+ offloadedOpConfig.setChainIndex(chainIndex);
+ offloadedChainSlice.getOperatorConfigs().add(offloadedOpConfig);
+ offloadedChainSlice.setOffloadable(true);
+ return offloadedChainSlice;
+ }
+
+ private void createOffloadedOneInputOperator(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph chainSliceGraph,
+ JobVertex jobVertex,
+ StatefulPlanNode planNode,
+ GlutenOneInputOperator<?, ?> sourceOperator,
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ boolean canInputRowVector = canInputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ Class<?> inClass = canInputRowVector ? StatefulRecord.class : RowData.class;
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenOneInputOperator<?, ?> newOneInputOp =
+ new GlutenOneInputOperator<>(
+ planNode,
+ sourceOperator.getId(),
+ sourceOperator.getInputType(),
+ sourceOperator.getOutputTypes(),
+ inClass,
+ outClass,
+ sourceOperator.getDescription());
+ offloadedOpConfig.setStreamOperator(newOneInputOp);
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ if (canInputRowVector) {
+ setOffloadedInputSerializer(offloadedOpConfig, sourceOperator);
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 0, sourceOperator.getDescription());
+ }
+ }
+
+ private void createOffloadedTwoInputOperator(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph chainSliceGraph,
+ JobVertex jobVertex,
+ StatefulPlanNode planNode,
+ GlutenTwoInputOperator<?, ?> sourceOperator,
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ boolean canInputRowVector = canInputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 0, sourceOperator.getDescription());
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 1, sourceOperator.getDescription());
+ Class<?> inClass = canInputRowVector ? StatefulRecord.class : RowData.class;
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenTwoInputOperator<?, ?> newTwoInputOp =
+ new GlutenTwoInputOperator<>(
+ planNode,
+ sourceOperator.getLeftId(),
+ sourceOperator.getRightId(),
+ sourceOperator.getLeftInputType(),
+ sourceOperator.getRightInputType(),
+ sourceOperator.getOutputTypes(),
+ inClass,
+ outClass);
+ offloadedOpConfig.setStreamOperator(newTwoInputOp);
+ offloadedOpConfig.setStatePartitioner(0, new GlutenKeySelector());
+ offloadedOpConfig.setStatePartitioner(1, new GlutenKeySelector());
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ if (canInputRowVector) {
+ setOffloadedInputSerializersForTwoInputOperator(offloadedOpConfig, sourceOperator);
+ }
+ }
+
+ private void setOffloadedOutputSerializer(StreamConfig opConfig, GlutenOperator operator) {
+ RowType rowType = operator.getOutputTypes().entrySet().iterator().next().getValue();
+ opConfig.setTypeSerializerOut(new GlutenStatefulRecordSerializer(rowType, operator.getId()));
+ }
+
+ private void setOffloadedInputSerializer(StreamConfig opConfig, GlutenOperator operator) {
+ opConfig.setupNetworkInputs(
+ new GlutenStatefulRecordSerializer(operator.getInputType(), operator.getId()));
+ }
+
+ private void setOffloadedInputSerializersForTwoInputOperator(
+ StreamConfig opConfig, GlutenTwoInputOperator<?, ?> operator) {
+ opConfig.setupNetworkInputs(
+ new GlutenStatefulRecordSerializer(operator.getLeftInputType(), operator.getId()),
+ new GlutenStatefulRecordSerializer(operator.getRightInputType(), operator.getId()));
+ }
+
+ private void setOffloadedStatePartitioner(
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig,
+ int inputIndex,
+ String operatorDescription) {
+ KeySelector<?, ?> keySelector = sourceOpConfig.getStatePartitioner(inputIndex, userClassloader);
+ if (keySelector != null) {
+ LOG.info(
+ "State partitioner ({}) found in input {} of operator {}, change it to GlutenKeySelector.",
+ keySelector.getClass().getName(),
+ inputIndex,
+ operatorDescription);
+ offloadedOpConfig.setStatePartitioner(inputIndex, new GlutenKeySelector());
+ }
+ }
+
+ private StreamConfig findLastOperatorInChain(JobVertex vertex) {
+ StreamConfig rootStreamConfig = new StreamConfig(vertex.getConfiguration());
+ Map<Integer, StreamConfig> chainedConfigs =
+ rootStreamConfig.getTransitiveChainedTaskConfigs(userClassloader);
+ chainedConfigs.put(rootStreamConfig.getVertexID(), rootStreamConfig);
+
+ // Find the last operator (the one with no chained outputs)
+ for (StreamConfig config : chainedConfigs.values()) {
+ List<StreamEdge> chainedOutputs = config.getChainedOutputs(userClassloader);
+ if (chainedOutputs == null || chainedOutputs.isEmpty()) {
+ return config;
+ }
+ }
+
+ // If no last operator found, use the root config
+ return rootStreamConfig;
+ }
+
+ private StreamNode mockStreamNode(StreamConfig streamConfig) {
+ return new StreamNode(
+ streamConfig.getVertexID(),
+ null,
+ null,
+ (StreamOperatorFactory<?>) streamConfig.getStreamOperatorFactory(userClassloader),
+ streamConfig.getOperatorName(),
+ null);
+ }
+
+ // Update stream edges when vertices have been changed due to offloading
+ private void visitAndUpdateStreamEdges(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph) {
+ OperatorChainSlice offloadedChainSlice =
+ offloadedChainSliceGraph.getSlice(sourceChainSlice.id());
+ if (offloadedChainSlice.isOffloadable()) {
+ updateStreamEdgesForOffloadedSlice(
+ sourceChainSlice, sourceChainSliceGraph, offloadedChainSliceGraph, offloadedChainSlice);
+ }
+
+ // Recursively update downstream chain slices
+ for (Integer downstreamSliceId : sourceChainSlice.getOutputs()) {
+ visitAndUpdateStreamEdges(
+ sourceChainSliceGraph.getSlice(downstreamSliceId),
+ sourceChainSliceGraph,
+ offloadedChainSliceGraph);
+ }
+ }
+
+ private void updateStreamEdgesForOffloadedSlice(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph,
+ OperatorChainSlice offloadedChainSlice) {
+ List<Integer> downstreamSliceIds = sourceChainSlice.getOutputs();
+ if (downstreamSliceIds.isEmpty()) {
+ StreamConfig offloadedOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ offloadedOpConfig.setChainedOutputs(new ArrayList<>());
+ return;
+ }
+
+ List<StreamEdge> newOutputEdges = new ArrayList<>();
+ List<StreamConfig> sourceOperatorConfigs = sourceChainSlice.getOperatorConfigs();
+ StreamConfig lastSourceOpConfig = sourceOperatorConfigs.get(sourceOperatorConfigs.size() - 1);
+ List<StreamEdge> originalOutputEdges = lastSourceOpConfig.getChainedOutputs(userClassloader);
+
+ for (int i = 0; i < downstreamSliceIds.size(); i++) {
+ Integer downstreamSliceId = downstreamSliceIds.get(i);
+ OperatorChainSlice downstreamOffloadedSlice =
+ offloadedChainSliceGraph.getSlice(downstreamSliceId);
+ StreamConfig downstreamOpConfig = downstreamOffloadedSlice.getOperatorConfigs().get(0);
+ StreamEdge originalEdge = originalOutputEdges.get(i);
+ StreamEdge newEdge = createStreamEdge(originalEdge, downstreamOpConfig, offloadedChainSlice);
+ newOutputEdges.add(newEdge);
+ }
+
+ StreamConfig offloadedOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ offloadedOpConfig.setChainedOutputs(newOutputEdges);
+ }
+
+ private StreamEdge createStreamEdge(
+ StreamEdge originalEdge,
+ StreamConfig downstreamOpConfig,
+ OperatorChainSlice offloadedChainSlice) {
+ StreamConfig sourceOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ return new StreamEdge(
+ mockStreamNode(sourceOpConfig),
+ mockStreamNode(downstreamOpConfig),
+ originalEdge.getTypeNumber(),
+ originalEdge.getBufferTimeout(),
+ originalEdge.getPartitioner(),
+ originalEdge.getOutputTag(),
+ originalEdge.getExchangeMode(),
+ 0,
Review Comment:
The magic number '0' for buffer size in StreamEdge creation is unclear. Add a comment explaining why buffer size is set to 0 or use a named constant to clarify the intent.
--
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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org
Re: [PR] [GLUTEN-11364][Flink] Improve the job graph generation code [incubator-gluten]
Posted by "lgbo-ustc (via GitHub)" <gi...@apache.org>.
lgbo-ustc commented on PR #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365#issuecomment-3742469991
@PHILO-HE Would you mind reviewing this PR ?
--
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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org
Re: [PR] [GLUTEN-11364][Flink] Improve the job graph generation code [incubator-gluten]
Posted by "PHILO-HE (via GitHub)" <gi...@apache.org>.
PHILO-HE commented on code in PR #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365#discussion_r2688734143
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OffloadedJobGraphGenerator.java:
##########
@@ -0,0 +1,611 @@
+/*
+ * 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.gluten.client;
+
+import org.apache.gluten.streaming.api.operators.GlutenOperator;
+import org.apache.gluten.streaming.api.operators.GlutenStreamSource;
+import org.apache.gluten.table.runtime.keyselector.GlutenKeySelector;
+import org.apache.gluten.table.runtime.operators.GlutenOneInputOperator;
+import org.apache.gluten.table.runtime.operators.GlutenSourceFunction;
+import org.apache.gluten.table.runtime.operators.GlutenTwoInputOperator;
+import org.apache.gluten.table.runtime.typeutils.GlutenStatefulRecordSerializer;
+import org.apache.gluten.util.Utils;
+
+import io.github.zhztheplayer.velox4j.plan.StatefulPlanNode;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.type.RowType;
+
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.jobgraph.IntermediateDataSet;
+import org.apache.flink.runtime.jobgraph.JobEdge;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.jobgraph.JobVertex;
+import org.apache.flink.streaming.api.graph.StreamConfig;
+import org.apache.flink.streaming.api.graph.StreamEdge;
+import org.apache.flink.streaming.api.graph.StreamNode;
+import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
+import org.apache.flink.table.data.RowData;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/*
+ * Generates an offloaded JobGraph by transforming offloadable operators to Gluten operators.
+ * Main workflow:
+ * 1. For each JobVertex, generate an OperatorChainSliceGraph to identify offloadable slices.
+ * 2. Recursively visit chain slices: create offloaded operators for offloadable slices,
+ * keep original operators for unoffloadable ones.
+ * 3. For offloadable operators: update input/output serializers and state partitioners
+ * based on upstream/downstream operator capabilities.
+ * 4. Update stream edges and serialize all operator configurations.
+ */
+public class OffloadedJobGraphGenerator {
+ private static final Logger LOG = LoggerFactory.getLogger(OffloadedJobGraphGenerator.class);
+ private final JobGraph jobGraph;
+ private final ClassLoader userClassloader;
+ private boolean hasGenerated = false;
+
+ public OffloadedJobGraphGenerator(JobGraph jobGraph, ClassLoader userClassloader) {
+ this.jobGraph = jobGraph;
+ this.userClassloader = userClassloader;
+ }
+
+ public JobGraph generate() {
+ if (hasGenerated) {
+ throw new IllegalStateException("JobGraph has been generated.");
+ }
+ hasGenerated = true;
Review Comment:
Nit: suggest to move this state flag to the end before result is returned.
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenSourceFunction.java:
##########
@@ -18,35 +18,40 @@
import org.apache.gluten.table.runtime.config.VeloxConnectorConfig;
import org.apache.gluten.table.runtime.config.VeloxQueryConfig;
+import org.apache.gluten.table.runtime.metrics.SourceTaskMetrics;
import org.apache.gluten.vectorized.FlinkRowToVLVectorConvertor;
-import io.github.zhztheplayer.velox4j.Velox4j;
import io.github.zhztheplayer.velox4j.connector.ConnectorSplit;
-import io.github.zhztheplayer.velox4j.data.RowVector;
import io.github.zhztheplayer.velox4j.iterator.UpIterator;
-import io.github.zhztheplayer.velox4j.memory.AllocationListener;
-import io.github.zhztheplayer.velox4j.memory.MemoryManager;
import io.github.zhztheplayer.velox4j.plan.StatefulPlanNode;
import io.github.zhztheplayer.velox4j.query.Query;
import io.github.zhztheplayer.velox4j.query.SerialTask;
-import io.github.zhztheplayer.velox4j.serde.Serde;
import io.github.zhztheplayer.velox4j.session.Session;
import io.github.zhztheplayer.velox4j.stateful.StatefulElement;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.stateful.StatefulWatermark;
import io.github.zhztheplayer.velox4j.type.RowType;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;
+import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.table.data.RowData;
-import org.apache.arrow.memory.BufferAllocator;
-import org.apache.arrow.memory.RootAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
-/** Gluten legacy source function, call velox plan to execute. */
-public class GlutenSourceFunction extends RichParallelSourceFunction<RowData> {
+/**
+ * Gluten legacy source function, call velox plan to execute. It sends RowVector to downstream
+ * instead of RowData to avoid data convert.
Review Comment:
Nit: conversion
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OffloadedJobGraphGenerator.java:
##########
@@ -0,0 +1,611 @@
+/*
+ * 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.gluten.client;
+
+import org.apache.gluten.streaming.api.operators.GlutenOperator;
+import org.apache.gluten.streaming.api.operators.GlutenStreamSource;
+import org.apache.gluten.table.runtime.keyselector.GlutenKeySelector;
+import org.apache.gluten.table.runtime.operators.GlutenOneInputOperator;
+import org.apache.gluten.table.runtime.operators.GlutenSourceFunction;
+import org.apache.gluten.table.runtime.operators.GlutenTwoInputOperator;
+import org.apache.gluten.table.runtime.typeutils.GlutenStatefulRecordSerializer;
+import org.apache.gluten.util.Utils;
+
+import io.github.zhztheplayer.velox4j.plan.StatefulPlanNode;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.type.RowType;
+
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.jobgraph.IntermediateDataSet;
+import org.apache.flink.runtime.jobgraph.JobEdge;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.jobgraph.JobVertex;
+import org.apache.flink.streaming.api.graph.StreamConfig;
+import org.apache.flink.streaming.api.graph.StreamEdge;
+import org.apache.flink.streaming.api.graph.StreamNode;
+import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
+import org.apache.flink.table.data.RowData;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/*
+ * Generates an offloaded JobGraph by transforming offloadable operators to Gluten operators.
+ * Main workflow:
+ * 1. For each JobVertex, generate an OperatorChainSliceGraph to identify offloadable slices.
+ * 2. Recursively visit chain slices: create offloaded operators for offloadable slices,
+ * keep original operators for unoffloadable ones.
+ * 3. For offloadable operators: update input/output serializers and state partitioners
+ * based on upstream/downstream operator capabilities.
+ * 4. Update stream edges and serialize all operator configurations.
+ */
+public class OffloadedJobGraphGenerator {
+ private static final Logger LOG = LoggerFactory.getLogger(OffloadedJobGraphGenerator.class);
+ private final JobGraph jobGraph;
+ private final ClassLoader userClassloader;
+ private boolean hasGenerated = false;
+
+ public OffloadedJobGraphGenerator(JobGraph jobGraph, ClassLoader userClassloader) {
+ this.jobGraph = jobGraph;
+ this.userClassloader = userClassloader;
+ }
+
+ public JobGraph generate() {
+ if (hasGenerated) {
+ throw new IllegalStateException("JobGraph has been generated.");
+ }
+ hasGenerated = true;
+ for (JobVertex jobVertex : jobGraph.getVertices()) {
+ offloadJobVertex(jobVertex);
+ }
+ return jobGraph;
+ }
+
+ private void offloadJobVertex(JobVertex jobVertex) {
+ OperatorChainSliceGraphGenerator graphGenerator =
+ new OperatorChainSliceGraphGenerator(jobVertex, userClassloader);
+ OperatorChainSliceGraph chainSliceGraph = graphGenerator.getGraph();
+ LOG.info("OperatorChainSliceGraph:\n{}", chainSliceGraph);
+
+ OperatorChainSlice sourceChainSlice = chainSliceGraph.getSourceSlice();
+ OperatorChainSliceGraph offloadedChainSliceGraph = new OperatorChainSliceGraph();
+ visitAndOffloadChainOperators(
+ sourceChainSlice, chainSliceGraph, offloadedChainSliceGraph, 0, jobVertex);
+ visitAndUpdateStreamEdges(sourceChainSlice, chainSliceGraph, offloadedChainSliceGraph);
+ serializeAllOperatorsConfigs(offloadedChainSliceGraph);
+
+ StreamConfig sourceConfig = sourceChainSlice.getOperatorConfigs().get(0);
+ StreamConfig offloadedSourceConfig =
+ offloadedChainSliceGraph.getSlice(sourceChainSlice.id()).getOperatorConfigs().get(0);
+
+ Map<Integer, StreamConfig> chainedConfigs =
+ collectChainedConfigs(sourceChainSlice, offloadedChainSliceGraph);
+ updateSourceConfigIfOffloadable(
+ sourceConfig, offloadedSourceConfig, sourceChainSlice, chainedConfigs);
+ sourceConfig.setAndSerializeTransitiveChainedTaskConfigs(chainedConfigs);
+ sourceConfig.serializeAllConfigs();
+ }
+
+ // Process and offload operator chain slices recursively
+ private void visitAndOffloadChainOperators(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph,
+ Integer chainIndex,
+ JobVertex jobVertex) {
+ OperatorChainSlice processedChainSlice;
+ if (sourceChainSlice.isOffloadable()) {
+ processedChainSlice =
+ createOffloadedOperatorChainSlice(
+ sourceChainSliceGraph, sourceChainSlice, chainIndex, jobVertex);
+ chainIndex = chainIndex + 1;
+ } else {
+ processedChainSlice = createUnoffloadableOperatorChainSlice(sourceChainSlice, chainIndex);
+ chainIndex = chainIndex + sourceChainSlice.getOperatorConfigs().size();
+ }
+
+ processedChainSlice.getInputs().addAll(sourceChainSlice.getInputs());
+ processedChainSlice.getOutputs().addAll(sourceChainSlice.getOutputs());
+ offloadedChainSliceGraph.addSlice(sourceChainSlice.id(), processedChainSlice);
+
+ // Recursively process downstream chain slices
+ for (Integer downstreamSliceId : sourceChainSlice.getOutputs()) {
+ OperatorChainSlice downstreamSourceSlice = sourceChainSliceGraph.getSlice(downstreamSliceId);
+ OperatorChainSlice downstreamProcessedSlice =
+ offloadedChainSliceGraph.getSlice(downstreamSliceId);
+ if (downstreamProcessedSlice == null) {
+ visitAndOffloadChainOperators(
+ downstreamSourceSlice,
+ sourceChainSliceGraph,
+ offloadedChainSliceGraph,
+ chainIndex,
+ jobVertex);
+ }
+ }
+ }
+
+ // Keep the original operator chain slice as is.
+ private OperatorChainSlice createUnoffloadableOperatorChainSlice(
+ OperatorChainSlice sourceChainSlice, Integer chainIndex) {
+ OperatorChainSlice unoffloadableChainSlice = new OperatorChainSlice(sourceChainSlice.id());
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+ for (StreamConfig opConfig : operatorConfigs) {
+ StreamConfig newOpConfig = new StreamConfig(new Configuration(opConfig.getConfiguration()));
+ newOpConfig.setChainIndex(chainIndex);
+ unoffloadableChainSlice.getOperatorConfigs().add(newOpConfig);
+ }
+ unoffloadableChainSlice.setOffloadable(false);
+ return unoffloadableChainSlice;
+ }
+
+ // Create offloadable operator chain slice, and update the input/output channel serializers
+ private OperatorChainSlice createOffloadedOperatorChainSlice(
+ OperatorChainSliceGraph chainSliceGraph,
+ OperatorChainSlice sourceChainSlice,
+ Integer chainIndex,
+ JobVertex jobVertex) {
+ OperatorChainSlice offloadedChainSlice = new OperatorChainSlice(sourceChainSlice.id());
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+
+ // May coalesce multiple operators into one in the future.
+ if (operatorConfigs.size() != 1) {
+ throw new UnsupportedOperationException(
+ "Only one operator is supported for offloaded operator chain slice.");
+ }
+
+ StreamConfig sourceOpConfig = operatorConfigs.get(0);
+ GlutenOperator sourceOperator = Utils.getGlutenOperator(sourceOpConfig, userClassloader).get();
+ StatefulPlanNode planNode = sourceOperator.getPlanNode();
+ // Create a new operator config for the offloaded operator.
+ StreamConfig offloadedOpConfig =
+ new StreamConfig(new Configuration(sourceOpConfig.getConfiguration()));
+ if (sourceOperator instanceof GlutenStreamSource) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenStreamSource newSourceOp =
+ new GlutenStreamSource(
+ new GlutenSourceFunction<>(
+ planNode,
+ sourceOperator.getOutputTypes(),
+ sourceOperator.getId(),
+ ((GlutenStreamSource) sourceOperator).getConnectorSplit(),
+ outClass));
+ offloadedOpConfig.setStreamOperator(newSourceOp);
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ } else if (sourceOperator instanceof GlutenOneInputOperator) {
+ createOffloadedOneInputOperator(
+ sourceChainSlice,
+ chainSliceGraph,
+ jobVertex,
+ planNode,
+ (GlutenOneInputOperator<?, ?>) sourceOperator,
+ sourceOpConfig,
+ offloadedOpConfig);
+ } else if (sourceOperator instanceof GlutenTwoInputOperator) {
+ createOffloadedTwoInputOperator(
+ sourceChainSlice,
+ chainSliceGraph,
+ jobVertex,
+ planNode,
+ (GlutenTwoInputOperator<?, ?>) sourceOperator,
+ sourceOpConfig,
+ offloadedOpConfig);
+ } else {
+ throw new UnsupportedOperationException(
+ "Unsupported operator type for offloading: " + sourceOperator.getClass().getName());
+ }
+
+ offloadedOpConfig.setChainIndex(chainIndex);
+ offloadedChainSlice.getOperatorConfigs().add(offloadedOpConfig);
+ offloadedChainSlice.setOffloadable(true);
+ return offloadedChainSlice;
+ }
+
+ private void createOffloadedOneInputOperator(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph chainSliceGraph,
+ JobVertex jobVertex,
+ StatefulPlanNode planNode,
+ GlutenOneInputOperator<?, ?> sourceOperator,
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ boolean canInputRowVector = canInputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ Class<?> inClass = canInputRowVector ? StatefulRecord.class : RowData.class;
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenOneInputOperator<?, ?> newOneInputOp =
+ new GlutenOneInputOperator<>(
+ planNode,
+ sourceOperator.getId(),
+ sourceOperator.getInputType(),
+ sourceOperator.getOutputTypes(),
+ inClass,
+ outClass,
+ sourceOperator.getDescription());
+ offloadedOpConfig.setStreamOperator(newOneInputOp);
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ if (canInputRowVector) {
+ setOffloadedInputSerializer(offloadedOpConfig, sourceOperator);
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 0, sourceOperator.getDescription());
+ }
+ }
+
+ private void createOffloadedTwoInputOperator(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph chainSliceGraph,
+ JobVertex jobVertex,
+ StatefulPlanNode planNode,
+ GlutenTwoInputOperator<?, ?> sourceOperator,
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ boolean canInputRowVector = canInputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 0, sourceOperator.getDescription());
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 1, sourceOperator.getDescription());
+ Class<?> inClass = canInputRowVector ? StatefulRecord.class : RowData.class;
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenTwoInputOperator<?, ?> newTwoInputOp =
+ new GlutenTwoInputOperator<>(
+ planNode,
+ sourceOperator.getLeftId(),
+ sourceOperator.getRightId(),
+ sourceOperator.getLeftInputType(),
+ sourceOperator.getRightInputType(),
+ sourceOperator.getOutputTypes(),
+ inClass,
+ outClass);
+ offloadedOpConfig.setStreamOperator(newTwoInputOp);
+ offloadedOpConfig.setStatePartitioner(0, new GlutenKeySelector());
+ offloadedOpConfig.setStatePartitioner(1, new GlutenKeySelector());
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ if (canInputRowVector) {
+ setOffloadedInputSerializersForTwoInputOperator(offloadedOpConfig, sourceOperator);
+ }
+ }
+
+ private void setOffloadedOutputSerializer(StreamConfig opConfig, GlutenOperator operator) {
+ RowType rowType = operator.getOutputTypes().entrySet().iterator().next().getValue();
+ opConfig.setTypeSerializerOut(new GlutenStatefulRecordSerializer(rowType, operator.getId()));
+ }
+
+ private void setOffloadedInputSerializer(StreamConfig opConfig, GlutenOperator operator) {
+ opConfig.setupNetworkInputs(
+ new GlutenStatefulRecordSerializer(operator.getInputType(), operator.getId()));
+ }
+
+ private void setOffloadedInputSerializersForTwoInputOperator(
+ StreamConfig opConfig, GlutenTwoInputOperator<?, ?> operator) {
+ opConfig.setupNetworkInputs(
+ new GlutenStatefulRecordSerializer(operator.getLeftInputType(), operator.getId()),
+ new GlutenStatefulRecordSerializer(operator.getRightInputType(), operator.getId()));
+ }
+
+ private void setOffloadedStatePartitioner(
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig,
+ int inputIndex,
+ String operatorDescription) {
+ KeySelector<?, ?> keySelector = sourceOpConfig.getStatePartitioner(inputIndex, userClassloader);
+ if (keySelector != null) {
+ LOG.info(
+ "State partitioner ({}) found in input {} of operator {}, change it to GlutenKeySelector.",
+ keySelector.getClass().getName(),
+ inputIndex,
+ operatorDescription);
+ offloadedOpConfig.setStatePartitioner(inputIndex, new GlutenKeySelector());
+ }
+ }
+
+ private StreamConfig findLastOperatorInChain(JobVertex vertex) {
+ StreamConfig rootStreamConfig = new StreamConfig(vertex.getConfiguration());
+ Map<Integer, StreamConfig> chainedConfigs =
+ rootStreamConfig.getTransitiveChainedTaskConfigs(userClassloader);
+ chainedConfigs.put(rootStreamConfig.getVertexID(), rootStreamConfig);
+
+ // Find the last operator (the one with no chained outputs)
+ for (StreamConfig config : chainedConfigs.values()) {
+ List<StreamEdge> chainedOutputs = config.getChainedOutputs(userClassloader);
+ if (chainedOutputs == null || chainedOutputs.isEmpty()) {
+ return config;
+ }
+ }
+
+ // If no last operator found, use the root config
+ return rootStreamConfig;
+ }
+
+ private StreamNode mockStreamNode(StreamConfig streamConfig) {
+ return new StreamNode(
+ streamConfig.getVertexID(),
+ null,
+ null,
+ (StreamOperatorFactory<?>) streamConfig.getStreamOperatorFactory(userClassloader),
+ streamConfig.getOperatorName(),
+ null);
+ }
+
+ // Update stream edges when vertices have been changed due to offloading
+ private void visitAndUpdateStreamEdges(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph) {
+ OperatorChainSlice offloadedChainSlice =
+ offloadedChainSliceGraph.getSlice(sourceChainSlice.id());
+ if (offloadedChainSlice.isOffloadable()) {
+ updateStreamEdgesForOffloadedSlice(
+ sourceChainSlice, sourceChainSliceGraph, offloadedChainSliceGraph, offloadedChainSlice);
+ }
+
+ // Recursively update downstream chain slices
+ for (Integer downstreamSliceId : sourceChainSlice.getOutputs()) {
+ visitAndUpdateStreamEdges(
+ sourceChainSliceGraph.getSlice(downstreamSliceId),
+ sourceChainSliceGraph,
+ offloadedChainSliceGraph);
+ }
+ }
+
+ private void updateStreamEdgesForOffloadedSlice(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph,
+ OperatorChainSlice offloadedChainSlice) {
+ List<Integer> downstreamSliceIds = sourceChainSlice.getOutputs();
+ if (downstreamSliceIds.isEmpty()) {
+ StreamConfig offloadedOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ offloadedOpConfig.setChainedOutputs(new ArrayList<>());
+ return;
+ }
+
+ List<StreamEdge> newOutputEdges = new ArrayList<>();
+ List<StreamConfig> sourceOperatorConfigs = sourceChainSlice.getOperatorConfigs();
+ StreamConfig lastSourceOpConfig = sourceOperatorConfigs.get(sourceOperatorConfigs.size() - 1);
+ List<StreamEdge> originalOutputEdges = lastSourceOpConfig.getChainedOutputs(userClassloader);
+
+ for (int i = 0; i < downstreamSliceIds.size(); i++) {
+ Integer downstreamSliceId = downstreamSliceIds.get(i);
+ OperatorChainSlice downstreamOffloadedSlice =
+ offloadedChainSliceGraph.getSlice(downstreamSliceId);
+ StreamConfig downstreamOpConfig = downstreamOffloadedSlice.getOperatorConfigs().get(0);
+ StreamEdge originalEdge = originalOutputEdges.get(i);
+ StreamEdge newEdge = createStreamEdge(originalEdge, downstreamOpConfig, offloadedChainSlice);
+ newOutputEdges.add(newEdge);
+ }
+
+ StreamConfig offloadedOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ offloadedOpConfig.setChainedOutputs(newOutputEdges);
+ }
+
+ private StreamEdge createStreamEdge(
+ StreamEdge originalEdge,
+ StreamConfig downstreamOpConfig,
+ OperatorChainSlice offloadedChainSlice) {
+ StreamConfig sourceOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ return new StreamEdge(
+ mockStreamNode(sourceOpConfig),
+ mockStreamNode(downstreamOpConfig),
+ originalEdge.getTypeNumber(),
+ originalEdge.getBufferTimeout(),
+ originalEdge.getPartitioner(),
+ originalEdge.getOutputTag(),
+ originalEdge.getExchangeMode(),
+ 0, // default value
+ originalEdge.getIntermediateDatasetIdToProduce());
+ }
+
+ private void serializeAllOperatorsConfigs(OperatorChainSliceGraph chainSliceGraph) {
+ for (OperatorChainSlice chainSlice : chainSliceGraph.getSlices().values()) {
+ for (StreamConfig opConfig : chainSlice.getOperatorConfigs()) {
+ opConfig.serializeAllConfigs();
+ }
+ }
+ }
+
+ private Map<Integer, StreamConfig> collectChainedConfigs(
+ OperatorChainSlice sourceChainSlice, OperatorChainSliceGraph offloadedChainSliceGraph) {
+ Map<Integer, StreamConfig> chainedConfigs = new HashMap<>();
+ if (!sourceChainSlice.isOffloadable()) {
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+ for (int i = 1; i < operatorConfigs.size(); i++) {
+ StreamConfig opConfig = operatorConfigs.get(i);
+ chainedConfigs.put(opConfig.getVertexID(), opConfig);
+ }
+ }
+ for (OperatorChainSlice chainSlice : offloadedChainSliceGraph.getSlices().values()) {
+ if (chainSlice.id().equals(sourceChainSlice.id())) {
+ continue;
+ }
+ for (StreamConfig opConfig : chainSlice.getOperatorConfigs()) {
+ chainedConfigs.put(opConfig.getVertexID(), opConfig);
+ }
+ }
+ return chainedConfigs;
+ }
+
+ private void updateSourceConfigIfOffloadable(
+ StreamConfig sourceConfig,
+ StreamConfig offloadedSourceConfig,
+ OperatorChainSlice sourceChainSlice,
+ Map<Integer, StreamConfig> chainedConfigs) {
+ if (sourceChainSlice.isOffloadable()) {
+ // Update the first operator config
+ sourceConfig.setStreamOperatorFactory(
+ offloadedSourceConfig.getStreamOperatorFactory(userClassloader));
+ sourceConfig.setChainedOutputs(offloadedSourceConfig.getChainedOutputs(userClassloader));
+ sourceConfig.setTypeSerializerOut(
+ offloadedSourceConfig.getTypeSerializerOut(userClassloader));
+ sourceConfig.setInputs(offloadedSourceConfig.getInputs(userClassloader));
+ updateStatePartitioners(sourceConfig, offloadedSourceConfig);
+ }
+ }
+
+ private void updateStatePartitioners(StreamConfig sourceConfig, StreamConfig offloadedConfig) {
+ KeySelector<?, ?> keySelector0 = offloadedConfig.getStatePartitioner(0, userClassloader);
+ if (keySelector0 != null) {
+ sourceConfig.setStatePartitioner(0, keySelector0);
+ }
+ KeySelector<?, ?> keySelector1 = offloadedConfig.getStatePartitioner(1, userClassloader);
+ if (keySelector1 != null) {
+ sourceConfig.setStatePartitioner(1, keySelector1);
+ }
+ }
+
+ private boolean areAllOffloadable(
+ OperatorChainSliceGraph chainSliceGraph, List<Integer> chainIds) {
+ for (Integer chainId : chainIds) {
+ OperatorChainSlice chainSlice = chainSliceGraph.getSlice(chainId);
+ if (!chainSlice.isOffloadable()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean canOutputRowVector(
+ OperatorChainSlice chainSlice, OperatorChainSliceGraph chainSliceGraph, JobVertex jobVertex) {
+ List<Integer> downstreamSliceIds = chainSlice.getOutputs();
+
+ // If chainSlice has downstream in the operator chain, check these downstream
+ if (!downstreamSliceIds.isEmpty()) {
+ return checkDownstreamSlicesInChain(chainSliceGraph, downstreamSliceIds);
+ } else {
+ // If chainSlice has no downstream in the operator chain, check downstream JobVertex from
+ // JobGraph level
+ return checkDownstreamVerticesFromJobGraph(jobVertex);
+ }
+ }
+
+ private boolean checkDownstreamSlicesInChain(
+ OperatorChainSliceGraph chainSliceGraph, List<Integer> downstreamSliceIds) {
+ for (Integer downstreamSliceId : downstreamSliceIds) {
+ OperatorChainSlice downstreamSlice = chainSliceGraph.getSlice(downstreamSliceId);
+ if (!downstreamSlice.isOffloadable()) {
+ return false;
+ }
+ List<Integer> inputSliceIds = downstreamSlice.getInputs();
+ if (!areAllOffloadable(chainSliceGraph, inputSliceIds)) {
Review Comment:
Can we simply use the following code for brevity?
```java
inputSliceIds.stream().map(chainSliceGraph::getSlice).allMatch(OperatorChainSlice::isOffloadable)
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OperatorChainSliceGraph.java:
##########
@@ -0,0 +1,85 @@
+/*
+ * 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.gluten.client;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OperatorChainSliceGraph {
+ private Map<Integer, OperatorChainSlice> slices;
+
+ public OperatorChainSliceGraph() {
+ slices = new HashMap<>();
+ }
+
+ public void addSlice(Integer id, OperatorChainSlice chainSlice) {
+ slices.put(id, chainSlice);
+ }
+
+ public OperatorChainSlice getSlice(Integer id) {
+ return slices.get(id);
+ }
+
+ public OperatorChainSlice getSourceSlice() {
+ List<OperatorChainSlice> sourceCandidates = new ArrayList<>();
+
+ for (OperatorChainSlice chainSlice : slices.values()) {
+ if (chainSlice.getInputs().isEmpty()) {
+ sourceCandidates.add(chainSlice);
+ }
+ }
+
+ if (sourceCandidates.isEmpty()) {
+ throw new IllegalStateException(
+ "No source operator chain slice found (no operator chain slice with empty inputs)");
+ } else if (sourceCandidates.size() > 1) {
+ throw new IllegalStateException(
+ "Multiple source operator chain slices found: "
+ + sourceCandidates.size()
+ + " operator chain slices have empty inputs");
Review Comment:
Nit: simplify the check with Flink's Preconditions class.
```java
Preconditions.checkState(sourceCandidates.size() == 1, "Expected exactly one source operator chain slice with empty inputs, but found %s", sourceCandidates.size())
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OffloadedJobGraphGenerator.java:
##########
@@ -0,0 +1,611 @@
+/*
+ * 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.gluten.client;
+
+import org.apache.gluten.streaming.api.operators.GlutenOperator;
+import org.apache.gluten.streaming.api.operators.GlutenStreamSource;
+import org.apache.gluten.table.runtime.keyselector.GlutenKeySelector;
+import org.apache.gluten.table.runtime.operators.GlutenOneInputOperator;
+import org.apache.gluten.table.runtime.operators.GlutenSourceFunction;
+import org.apache.gluten.table.runtime.operators.GlutenTwoInputOperator;
+import org.apache.gluten.table.runtime.typeutils.GlutenStatefulRecordSerializer;
+import org.apache.gluten.util.Utils;
+
+import io.github.zhztheplayer.velox4j.plan.StatefulPlanNode;
+import io.github.zhztheplayer.velox4j.stateful.StatefulRecord;
+import io.github.zhztheplayer.velox4j.type.RowType;
+
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.jobgraph.IntermediateDataSet;
+import org.apache.flink.runtime.jobgraph.JobEdge;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.jobgraph.JobVertex;
+import org.apache.flink.streaming.api.graph.StreamConfig;
+import org.apache.flink.streaming.api.graph.StreamEdge;
+import org.apache.flink.streaming.api.graph.StreamNode;
+import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
+import org.apache.flink.table.data.RowData;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/*
+ * Generates an offloaded JobGraph by transforming offloadable operators to Gluten operators.
+ * Main workflow:
+ * 1. For each JobVertex, generate an OperatorChainSliceGraph to identify offloadable slices.
+ * 2. Recursively visit chain slices: create offloaded operators for offloadable slices,
+ * keep original operators for unoffloadable ones.
+ * 3. For offloadable operators: update input/output serializers and state partitioners
+ * based on upstream/downstream operator capabilities.
+ * 4. Update stream edges and serialize all operator configurations.
+ */
+public class OffloadedJobGraphGenerator {
+ private static final Logger LOG = LoggerFactory.getLogger(OffloadedJobGraphGenerator.class);
+ private final JobGraph jobGraph;
+ private final ClassLoader userClassloader;
+ private boolean hasGenerated = false;
+
+ public OffloadedJobGraphGenerator(JobGraph jobGraph, ClassLoader userClassloader) {
+ this.jobGraph = jobGraph;
+ this.userClassloader = userClassloader;
+ }
+
+ public JobGraph generate() {
+ if (hasGenerated) {
+ throw new IllegalStateException("JobGraph has been generated.");
+ }
+ hasGenerated = true;
+ for (JobVertex jobVertex : jobGraph.getVertices()) {
+ offloadJobVertex(jobVertex);
+ }
+ return jobGraph;
+ }
+
+ private void offloadJobVertex(JobVertex jobVertex) {
+ OperatorChainSliceGraphGenerator graphGenerator =
+ new OperatorChainSliceGraphGenerator(jobVertex, userClassloader);
+ OperatorChainSliceGraph chainSliceGraph = graphGenerator.getGraph();
+ LOG.info("OperatorChainSliceGraph:\n{}", chainSliceGraph);
+
+ OperatorChainSlice sourceChainSlice = chainSliceGraph.getSourceSlice();
+ OperatorChainSliceGraph offloadedChainSliceGraph = new OperatorChainSliceGraph();
+ visitAndOffloadChainOperators(
+ sourceChainSlice, chainSliceGraph, offloadedChainSliceGraph, 0, jobVertex);
+ visitAndUpdateStreamEdges(sourceChainSlice, chainSliceGraph, offloadedChainSliceGraph);
+ serializeAllOperatorsConfigs(offloadedChainSliceGraph);
+
+ StreamConfig sourceConfig = sourceChainSlice.getOperatorConfigs().get(0);
+ StreamConfig offloadedSourceConfig =
+ offloadedChainSliceGraph.getSlice(sourceChainSlice.id()).getOperatorConfigs().get(0);
+
+ Map<Integer, StreamConfig> chainedConfigs =
+ collectChainedConfigs(sourceChainSlice, offloadedChainSliceGraph);
+ updateSourceConfigIfOffloadable(
+ sourceConfig, offloadedSourceConfig, sourceChainSlice, chainedConfigs);
+ sourceConfig.setAndSerializeTransitiveChainedTaskConfigs(chainedConfigs);
+ sourceConfig.serializeAllConfigs();
+ }
+
+ // Process and offload operator chain slices recursively
+ private void visitAndOffloadChainOperators(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph,
+ Integer chainIndex,
+ JobVertex jobVertex) {
+ OperatorChainSlice processedChainSlice;
+ if (sourceChainSlice.isOffloadable()) {
+ processedChainSlice =
+ createOffloadedOperatorChainSlice(
+ sourceChainSliceGraph, sourceChainSlice, chainIndex, jobVertex);
+ chainIndex = chainIndex + 1;
+ } else {
+ processedChainSlice = createUnoffloadableOperatorChainSlice(sourceChainSlice, chainIndex);
+ chainIndex = chainIndex + sourceChainSlice.getOperatorConfigs().size();
+ }
+
+ processedChainSlice.getInputs().addAll(sourceChainSlice.getInputs());
+ processedChainSlice.getOutputs().addAll(sourceChainSlice.getOutputs());
+ offloadedChainSliceGraph.addSlice(sourceChainSlice.id(), processedChainSlice);
+
+ // Recursively process downstream chain slices
+ for (Integer downstreamSliceId : sourceChainSlice.getOutputs()) {
+ OperatorChainSlice downstreamSourceSlice = sourceChainSliceGraph.getSlice(downstreamSliceId);
+ OperatorChainSlice downstreamProcessedSlice =
+ offloadedChainSliceGraph.getSlice(downstreamSliceId);
+ if (downstreamProcessedSlice == null) {
+ visitAndOffloadChainOperators(
+ downstreamSourceSlice,
+ sourceChainSliceGraph,
+ offloadedChainSliceGraph,
+ chainIndex,
+ jobVertex);
+ }
+ }
+ }
+
+ // Keep the original operator chain slice as is.
+ private OperatorChainSlice createUnoffloadableOperatorChainSlice(
+ OperatorChainSlice sourceChainSlice, Integer chainIndex) {
+ OperatorChainSlice unoffloadableChainSlice = new OperatorChainSlice(sourceChainSlice.id());
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+ for (StreamConfig opConfig : operatorConfigs) {
+ StreamConfig newOpConfig = new StreamConfig(new Configuration(opConfig.getConfiguration()));
+ newOpConfig.setChainIndex(chainIndex);
+ unoffloadableChainSlice.getOperatorConfigs().add(newOpConfig);
+ }
+ unoffloadableChainSlice.setOffloadable(false);
+ return unoffloadableChainSlice;
+ }
+
+ // Create offloadable operator chain slice, and update the input/output channel serializers
+ private OperatorChainSlice createOffloadedOperatorChainSlice(
+ OperatorChainSliceGraph chainSliceGraph,
+ OperatorChainSlice sourceChainSlice,
+ Integer chainIndex,
+ JobVertex jobVertex) {
+ OperatorChainSlice offloadedChainSlice = new OperatorChainSlice(sourceChainSlice.id());
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+
+ // May coalesce multiple operators into one in the future.
+ if (operatorConfigs.size() != 1) {
+ throw new UnsupportedOperationException(
+ "Only one operator is supported for offloaded operator chain slice.");
+ }
+
+ StreamConfig sourceOpConfig = operatorConfigs.get(0);
+ GlutenOperator sourceOperator = Utils.getGlutenOperator(sourceOpConfig, userClassloader).get();
+ StatefulPlanNode planNode = sourceOperator.getPlanNode();
+ // Create a new operator config for the offloaded operator.
+ StreamConfig offloadedOpConfig =
+ new StreamConfig(new Configuration(sourceOpConfig.getConfiguration()));
+ if (sourceOperator instanceof GlutenStreamSource) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenStreamSource newSourceOp =
+ new GlutenStreamSource(
+ new GlutenSourceFunction<>(
+ planNode,
+ sourceOperator.getOutputTypes(),
+ sourceOperator.getId(),
+ ((GlutenStreamSource) sourceOperator).getConnectorSplit(),
+ outClass));
+ offloadedOpConfig.setStreamOperator(newSourceOp);
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ } else if (sourceOperator instanceof GlutenOneInputOperator) {
+ createOffloadedOneInputOperator(
+ sourceChainSlice,
+ chainSliceGraph,
+ jobVertex,
+ planNode,
+ (GlutenOneInputOperator<?, ?>) sourceOperator,
+ sourceOpConfig,
+ offloadedOpConfig);
+ } else if (sourceOperator instanceof GlutenTwoInputOperator) {
+ createOffloadedTwoInputOperator(
+ sourceChainSlice,
+ chainSliceGraph,
+ jobVertex,
+ planNode,
+ (GlutenTwoInputOperator<?, ?>) sourceOperator,
+ sourceOpConfig,
+ offloadedOpConfig);
+ } else {
+ throw new UnsupportedOperationException(
+ "Unsupported operator type for offloading: " + sourceOperator.getClass().getName());
+ }
+
+ offloadedOpConfig.setChainIndex(chainIndex);
+ offloadedChainSlice.getOperatorConfigs().add(offloadedOpConfig);
+ offloadedChainSlice.setOffloadable(true);
+ return offloadedChainSlice;
+ }
+
+ private void createOffloadedOneInputOperator(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph chainSliceGraph,
+ JobVertex jobVertex,
+ StatefulPlanNode planNode,
+ GlutenOneInputOperator<?, ?> sourceOperator,
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ boolean canInputRowVector = canInputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ Class<?> inClass = canInputRowVector ? StatefulRecord.class : RowData.class;
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenOneInputOperator<?, ?> newOneInputOp =
+ new GlutenOneInputOperator<>(
+ planNode,
+ sourceOperator.getId(),
+ sourceOperator.getInputType(),
+ sourceOperator.getOutputTypes(),
+ inClass,
+ outClass,
+ sourceOperator.getDescription());
+ offloadedOpConfig.setStreamOperator(newOneInputOp);
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ if (canInputRowVector) {
+ setOffloadedInputSerializer(offloadedOpConfig, sourceOperator);
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 0, sourceOperator.getDescription());
+ }
+ }
+
+ private void createOffloadedTwoInputOperator(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph chainSliceGraph,
+ JobVertex jobVertex,
+ StatefulPlanNode planNode,
+ GlutenTwoInputOperator<?, ?> sourceOperator,
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig) {
+ boolean canOutputRowVector = canOutputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ boolean canInputRowVector = canInputRowVector(sourceChainSlice, chainSliceGraph, jobVertex);
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 0, sourceOperator.getDescription());
+ setOffloadedStatePartitioner(
+ sourceOpConfig, offloadedOpConfig, 1, sourceOperator.getDescription());
+ Class<?> inClass = canInputRowVector ? StatefulRecord.class : RowData.class;
+ Class<?> outClass = canOutputRowVector ? StatefulRecord.class : RowData.class;
+ GlutenTwoInputOperator<?, ?> newTwoInputOp =
+ new GlutenTwoInputOperator<>(
+ planNode,
+ sourceOperator.getLeftId(),
+ sourceOperator.getRightId(),
+ sourceOperator.getLeftInputType(),
+ sourceOperator.getRightInputType(),
+ sourceOperator.getOutputTypes(),
+ inClass,
+ outClass);
+ offloadedOpConfig.setStreamOperator(newTwoInputOp);
+ offloadedOpConfig.setStatePartitioner(0, new GlutenKeySelector());
+ offloadedOpConfig.setStatePartitioner(1, new GlutenKeySelector());
+ if (canOutputRowVector) {
+ setOffloadedOutputSerializer(offloadedOpConfig, sourceOperator);
+ }
+ if (canInputRowVector) {
+ setOffloadedInputSerializersForTwoInputOperator(offloadedOpConfig, sourceOperator);
+ }
+ }
+
+ private void setOffloadedOutputSerializer(StreamConfig opConfig, GlutenOperator operator) {
+ RowType rowType = operator.getOutputTypes().entrySet().iterator().next().getValue();
+ opConfig.setTypeSerializerOut(new GlutenStatefulRecordSerializer(rowType, operator.getId()));
+ }
+
+ private void setOffloadedInputSerializer(StreamConfig opConfig, GlutenOperator operator) {
+ opConfig.setupNetworkInputs(
+ new GlutenStatefulRecordSerializer(operator.getInputType(), operator.getId()));
+ }
+
+ private void setOffloadedInputSerializersForTwoInputOperator(
+ StreamConfig opConfig, GlutenTwoInputOperator<?, ?> operator) {
+ opConfig.setupNetworkInputs(
+ new GlutenStatefulRecordSerializer(operator.getLeftInputType(), operator.getId()),
+ new GlutenStatefulRecordSerializer(operator.getRightInputType(), operator.getId()));
+ }
+
+ private void setOffloadedStatePartitioner(
+ StreamConfig sourceOpConfig,
+ StreamConfig offloadedOpConfig,
+ int inputIndex,
+ String operatorDescription) {
+ KeySelector<?, ?> keySelector = sourceOpConfig.getStatePartitioner(inputIndex, userClassloader);
+ if (keySelector != null) {
+ LOG.info(
+ "State partitioner ({}) found in input {} of operator {}, change it to GlutenKeySelector.",
+ keySelector.getClass().getName(),
+ inputIndex,
+ operatorDescription);
+ offloadedOpConfig.setStatePartitioner(inputIndex, new GlutenKeySelector());
+ }
+ }
+
+ private StreamConfig findLastOperatorInChain(JobVertex vertex) {
+ StreamConfig rootStreamConfig = new StreamConfig(vertex.getConfiguration());
+ Map<Integer, StreamConfig> chainedConfigs =
+ rootStreamConfig.getTransitiveChainedTaskConfigs(userClassloader);
+ chainedConfigs.put(rootStreamConfig.getVertexID(), rootStreamConfig);
+
+ // Find the last operator (the one with no chained outputs)
+ for (StreamConfig config : chainedConfigs.values()) {
+ List<StreamEdge> chainedOutputs = config.getChainedOutputs(userClassloader);
+ if (chainedOutputs == null || chainedOutputs.isEmpty()) {
+ return config;
+ }
+ }
+
+ // If no last operator found, use the root config
+ return rootStreamConfig;
+ }
+
+ private StreamNode mockStreamNode(StreamConfig streamConfig) {
+ return new StreamNode(
+ streamConfig.getVertexID(),
+ null,
+ null,
+ (StreamOperatorFactory<?>) streamConfig.getStreamOperatorFactory(userClassloader),
+ streamConfig.getOperatorName(),
+ null);
+ }
+
+ // Update stream edges when vertices have been changed due to offloading
+ private void visitAndUpdateStreamEdges(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph) {
+ OperatorChainSlice offloadedChainSlice =
+ offloadedChainSliceGraph.getSlice(sourceChainSlice.id());
+ if (offloadedChainSlice.isOffloadable()) {
+ updateStreamEdgesForOffloadedSlice(
+ sourceChainSlice, sourceChainSliceGraph, offloadedChainSliceGraph, offloadedChainSlice);
+ }
+
+ // Recursively update downstream chain slices
+ for (Integer downstreamSliceId : sourceChainSlice.getOutputs()) {
+ visitAndUpdateStreamEdges(
+ sourceChainSliceGraph.getSlice(downstreamSliceId),
+ sourceChainSliceGraph,
+ offloadedChainSliceGraph);
+ }
+ }
+
+ private void updateStreamEdgesForOffloadedSlice(
+ OperatorChainSlice sourceChainSlice,
+ OperatorChainSliceGraph sourceChainSliceGraph,
+ OperatorChainSliceGraph offloadedChainSliceGraph,
+ OperatorChainSlice offloadedChainSlice) {
+ List<Integer> downstreamSliceIds = sourceChainSlice.getOutputs();
+ if (downstreamSliceIds.isEmpty()) {
+ StreamConfig offloadedOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ offloadedOpConfig.setChainedOutputs(new ArrayList<>());
+ return;
+ }
+
+ List<StreamEdge> newOutputEdges = new ArrayList<>();
+ List<StreamConfig> sourceOperatorConfigs = sourceChainSlice.getOperatorConfigs();
+ StreamConfig lastSourceOpConfig = sourceOperatorConfigs.get(sourceOperatorConfigs.size() - 1);
+ List<StreamEdge> originalOutputEdges = lastSourceOpConfig.getChainedOutputs(userClassloader);
+
+ for (int i = 0; i < downstreamSliceIds.size(); i++) {
+ Integer downstreamSliceId = downstreamSliceIds.get(i);
+ OperatorChainSlice downstreamOffloadedSlice =
+ offloadedChainSliceGraph.getSlice(downstreamSliceId);
+ StreamConfig downstreamOpConfig = downstreamOffloadedSlice.getOperatorConfigs().get(0);
+ StreamEdge originalEdge = originalOutputEdges.get(i);
+ StreamEdge newEdge = createStreamEdge(originalEdge, downstreamOpConfig, offloadedChainSlice);
+ newOutputEdges.add(newEdge);
+ }
+
+ StreamConfig offloadedOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ offloadedOpConfig.setChainedOutputs(newOutputEdges);
+ }
+
+ private StreamEdge createStreamEdge(
+ StreamEdge originalEdge,
+ StreamConfig downstreamOpConfig,
+ OperatorChainSlice offloadedChainSlice) {
+ StreamConfig sourceOpConfig = offloadedChainSlice.getOperatorConfigs().get(0);
+ return new StreamEdge(
+ mockStreamNode(sourceOpConfig),
+ mockStreamNode(downstreamOpConfig),
+ originalEdge.getTypeNumber(),
+ originalEdge.getBufferTimeout(),
+ originalEdge.getPartitioner(),
+ originalEdge.getOutputTag(),
+ originalEdge.getExchangeMode(),
+ 0, // default value
+ originalEdge.getIntermediateDatasetIdToProduce());
+ }
+
+ private void serializeAllOperatorsConfigs(OperatorChainSliceGraph chainSliceGraph) {
+ for (OperatorChainSlice chainSlice : chainSliceGraph.getSlices().values()) {
+ for (StreamConfig opConfig : chainSlice.getOperatorConfigs()) {
+ opConfig.serializeAllConfigs();
+ }
+ }
+ }
+
+ private Map<Integer, StreamConfig> collectChainedConfigs(
+ OperatorChainSlice sourceChainSlice, OperatorChainSliceGraph offloadedChainSliceGraph) {
+ Map<Integer, StreamConfig> chainedConfigs = new HashMap<>();
+ if (!sourceChainSlice.isOffloadable()) {
+ List<StreamConfig> operatorConfigs = sourceChainSlice.getOperatorConfigs();
+ for (int i = 1; i < operatorConfigs.size(); i++) {
+ StreamConfig opConfig = operatorConfigs.get(i);
+ chainedConfigs.put(opConfig.getVertexID(), opConfig);
+ }
+ }
+ for (OperatorChainSlice chainSlice : offloadedChainSliceGraph.getSlices().values()) {
+ if (chainSlice.id().equals(sourceChainSlice.id())) {
+ continue;
+ }
+ for (StreamConfig opConfig : chainSlice.getOperatorConfigs()) {
+ chainedConfigs.put(opConfig.getVertexID(), opConfig);
+ }
+ }
+ return chainedConfigs;
+ }
+
+ private void updateSourceConfigIfOffloadable(
+ StreamConfig sourceConfig,
+ StreamConfig offloadedSourceConfig,
+ OperatorChainSlice sourceChainSlice,
+ Map<Integer, StreamConfig> chainedConfigs) {
+ if (sourceChainSlice.isOffloadable()) {
+ // Update the first operator config
+ sourceConfig.setStreamOperatorFactory(
+ offloadedSourceConfig.getStreamOperatorFactory(userClassloader));
+ sourceConfig.setChainedOutputs(offloadedSourceConfig.getChainedOutputs(userClassloader));
+ sourceConfig.setTypeSerializerOut(
+ offloadedSourceConfig.getTypeSerializerOut(userClassloader));
+ sourceConfig.setInputs(offloadedSourceConfig.getInputs(userClassloader));
+ updateStatePartitioners(sourceConfig, offloadedSourceConfig);
+ }
+ }
+
+ private void updateStatePartitioners(StreamConfig sourceConfig, StreamConfig offloadedConfig) {
+ KeySelector<?, ?> keySelector0 = offloadedConfig.getStatePartitioner(0, userClassloader);
+ if (keySelector0 != null) {
+ sourceConfig.setStatePartitioner(0, keySelector0);
+ }
+ KeySelector<?, ?> keySelector1 = offloadedConfig.getStatePartitioner(1, userClassloader);
+ if (keySelector1 != null) {
+ sourceConfig.setStatePartitioner(1, keySelector1);
+ }
+ }
+
+ private boolean areAllOffloadable(
+ OperatorChainSliceGraph chainSliceGraph, List<Integer> chainIds) {
+ for (Integer chainId : chainIds) {
+ OperatorChainSlice chainSlice = chainSliceGraph.getSlice(chainId);
+ if (!chainSlice.isOffloadable()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean canOutputRowVector(
+ OperatorChainSlice chainSlice, OperatorChainSliceGraph chainSliceGraph, JobVertex jobVertex) {
+ List<Integer> downstreamSliceIds = chainSlice.getOutputs();
+
+ // If chainSlice has downstream in the operator chain, check these downstream
+ if (!downstreamSliceIds.isEmpty()) {
+ return checkDownstreamSlicesInChain(chainSliceGraph, downstreamSliceIds);
+ } else {
+ // If chainSlice has no downstream in the operator chain, check downstream JobVertex from
+ // JobGraph level
+ return checkDownstreamVerticesFromJobGraph(jobVertex);
+ }
+ }
+
+ private boolean checkDownstreamSlicesInChain(
+ OperatorChainSliceGraph chainSliceGraph, List<Integer> downstreamSliceIds) {
+ for (Integer downstreamSliceId : downstreamSliceIds) {
+ OperatorChainSlice downstreamSlice = chainSliceGraph.getSlice(downstreamSliceId);
+ if (!downstreamSlice.isOffloadable()) {
+ return false;
+ }
+ List<Integer> inputSliceIds = downstreamSlice.getInputs();
+ if (!areAllOffloadable(chainSliceGraph, inputSliceIds)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean checkDownstreamVerticesFromJobGraph(JobVertex jobVertex) {
+ List<JobVertex> downstreamVertices = getDownstreamJobVertices(jobVertex);
+ if (downstreamVertices.isEmpty()) {
+ // If there is no downstream JobVertex, can output RowVector (no downstream needs
+ // conversion)
+ return true;
+ }
+ // Check if all downstream vertices' operators are gluten operators
+ for (JobVertex downstreamVertex : downstreamVertices) {
+ StreamConfig downstreamStreamConfig = new StreamConfig(downstreamVertex.getConfiguration());
+ Optional<GlutenOperator> glutenOperator =
+ Utils.getGlutenOperator(downstreamStreamConfig, userClassloader);
+ if (!glutenOperator.isPresent()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean canInputRowVector(
Review Comment:
Nit: suggest the following names which seems more natural.
```
canInputRowVector -> supportsVectorInput
canOutputRowVector -> supportsVectorOutput
```
##########
gluten-flink/runtime/src/main/java/org/apache/gluten/client/OperatorChainSliceGraph.java:
##########
@@ -0,0 +1,85 @@
+/*
+ * 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.gluten.client;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OperatorChainSliceGraph {
+ private Map<Integer, OperatorChainSlice> slices;
+
+ public OperatorChainSliceGraph() {
+ slices = new HashMap<>();
+ }
+
+ public void addSlice(Integer id, OperatorChainSlice chainSlice) {
+ slices.put(id, chainSlice);
+ }
+
+ public OperatorChainSlice getSlice(Integer id) {
+ return slices.get(id);
+ }
+
+ public OperatorChainSlice getSourceSlice() {
+ List<OperatorChainSlice> sourceCandidates = new ArrayList<>();
+
+ for (OperatorChainSlice chainSlice : slices.values()) {
+ if (chainSlice.getInputs().isEmpty()) {
+ sourceCandidates.add(chainSlice);
+ }
+ }
+
+ if (sourceCandidates.isEmpty()) {
+ throw new IllegalStateException(
+ "No source operator chain slice found (no operator chain slice with empty inputs)");
+ } else if (sourceCandidates.size() > 1) {
+ throw new IllegalStateException(
+ "Multiple source operator chain slices found: "
+ + sourceCandidates.size()
+ + " operator chain slices have empty inputs");
+ }
+
+ return sourceCandidates.get(0);
+ }
+
+ public Map<Integer, OperatorChainSlice> getSlices() {
+ return slices;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ for (OperatorChainSlice chainSlice : slices.values()) {
+ sb.append("Slice ID: ")
+ .append(chainSlice.id())
+ .append(", offloadable: ")
+ .append(chainSlice.isOffloadable())
+ .append("\n");
+ sb.append(" Inputs: ").append(chainSlice.getInputs()).append("\n");
+ sb.append(" Outputs: ").append(chainSlice.getOutputs()).append("\n");
+ String operatorConfigs =
+ chainSlice.getOperatorConfigs().stream()
+ .map(config -> config.getOperatorName() + "(" + config.getVertexID() + ")")
+ .reduce((a, b) -> a + ", " + b)
Review Comment:
Can we simplify it with the code below?
`map(xxx).collect(Collectors.joining(", ")`
--
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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org
Re: [PR] [GLUTEN-11364][Flink] Improve the job graph generation code [incubator-gluten]
Posted by "lgbo-ustc (via GitHub)" <gi...@apache.org>.
lgbo-ustc commented on PR #11365:
URL: https://github.com/apache/incubator-gluten/pull/11365#issuecomment-3723062129
> does this support falling back to Flink native operator chain when the gluten+velox is unsupported?
Not in this version
--
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: commits-unsubscribe@gluten.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org