philo-he commented on code in PR #13730: URL: https://github.com/apache/gluten/pull/13730#discussion_r4691292718
########## gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenWindowOneInputOperator.java: ########## @@ -0,0 +1,183 @@ +/* + * 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 io.github.zhztheplayer.velox4j.plan.StatefulPlanNode; +import io.github.zhztheplayer.velox4j.query.SerialTask; +import io.github.zhztheplayer.velox4j.type.RowType; + +import org.apache.flink.api.common.state.ListState; +import org.apache.flink.api.common.state.ListStateDescriptor; +import org.apache.flink.api.common.typeutils.base.StringSerializer; +import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend; +import org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend; +import org.apache.flink.contrib.streaming.state.RocksDBStateBackend; +import org.apache.flink.runtime.state.StateBackend; +import org.apache.flink.runtime.state.StateBackendLoader; +import org.apache.flink.runtime.state.StateInitializationContext; +import org.apache.flink.runtime.state.StateSnapshotContext; +import org.apache.flink.runtime.state.delegate.DelegatingStateBackend; +import org.apache.flink.streaming.api.operators.OneInputStreamOperator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * A {@link GlutenOneInputOperator} for the group-window aggregation: replaces the base class's + * RocksDB behavior (silently skipping native state initialization) with fail-loud rejection, and + * persists the native keyed-state checkpoint records into Flink operator state so they survive + * restarts and rescales. + * + * <p>RocksDB rejection: the window aggregation transformation is intentionally non-keyed (the user + * key rides the plan's KeyedStateSpec and the upstream exchange), so no keyed backend is ever + * materialized for this operator and inspecting the materialized keyed backend alone can never fire + * in production. {@code usesRocksDBStateBackend} therefore resolves the effective backend the same + * way the containing task does (application backend from the operator config, then job + * configuration, then cluster configuration, via {@link + * StateBackendLoader#fromApplicationOrConfigOrDefault}) and inspects the resolved factory, in + * addition to the materialized keyed backend. + * + * <p>Checkpoint round-trip: {@code snapshotNativeState} stores the records returned by {@link + * SerialTask#snapshotState(long)} into a union-list operator state; {@code initializeNativeState} + * replays them through {@link SerialTask#initializeState(long, + * io.github.zhztheplayer.velox4j.stateful.KeyedStateBackendParameters, String[])}. The union list + * hands every restored task the full set of snapshot records; the velox-side restore keeps only the + * entries overlapping the task's key-group range. (The records ride the velox4j JNI String + * boundary, which is not binary-safe - the known checkpoint e2e limitation; the native Review Comment: **Blocking.** If the records aren't binary-safe across the JNI `String` boundary, a restore can silently corrupt window state. Since this PR already moves the network serde to `byte[]` (`GlutenStatefulRecordSerializer`), could snapshot/restore move to `byte[]` too (`ListState<byte[]>` + `BytePrimitiveArraySerializer`)? If not, I'd rather reject checkpointing for this operator than restore wrong results. ########## gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenWindowOneInputOperator.java: ########## @@ -0,0 +1,183 @@ +/* + * 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 io.github.zhztheplayer.velox4j.plan.StatefulPlanNode; +import io.github.zhztheplayer.velox4j.query.SerialTask; +import io.github.zhztheplayer.velox4j.type.RowType; + +import org.apache.flink.api.common.state.ListState; +import org.apache.flink.api.common.state.ListStateDescriptor; +import org.apache.flink.api.common.typeutils.base.StringSerializer; +import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend; +import org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend; +import org.apache.flink.contrib.streaming.state.RocksDBStateBackend; +import org.apache.flink.runtime.state.StateBackend; +import org.apache.flink.runtime.state.StateBackendLoader; +import org.apache.flink.runtime.state.StateInitializationContext; +import org.apache.flink.runtime.state.StateSnapshotContext; +import org.apache.flink.runtime.state.delegate.DelegatingStateBackend; +import org.apache.flink.streaming.api.operators.OneInputStreamOperator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * A {@link GlutenOneInputOperator} for the group-window aggregation: replaces the base class's + * RocksDB behavior (silently skipping native state initialization) with fail-loud rejection, and + * persists the native keyed-state checkpoint records into Flink operator state so they survive + * restarts and rescales. + * + * <p>RocksDB rejection: the window aggregation transformation is intentionally non-keyed (the user + * key rides the plan's KeyedStateSpec and the upstream exchange), so no keyed backend is ever + * materialized for this operator and inspecting the materialized keyed backend alone can never fire + * in production. {@code usesRocksDBStateBackend} therefore resolves the effective backend the same + * way the containing task does (application backend from the operator config, then job + * configuration, then cluster configuration, via {@link + * StateBackendLoader#fromApplicationOrConfigOrDefault}) and inspects the resolved factory, in + * addition to the materialized keyed backend. + * + * <p>Checkpoint round-trip: {@code snapshotNativeState} stores the records returned by {@link + * SerialTask#snapshotState(long)} into a union-list operator state; {@code initializeNativeState} + * replays them through {@link SerialTask#initializeState(long, + * io.github.zhztheplayer.velox4j.stateful.KeyedStateBackendParameters, String[])}. The union list + * hands every restored task the full set of snapshot records; the velox-side restore keeps only the + * entries overlapping the task's key-group range. (The records ride the velox4j JNI String + * boundary, which is not binary-safe - the known checkpoint e2e limitation; the native + * snapshot/restore semantics are pinned by the velox-side unit tests.) + */ +public class GlutenWindowOneInputOperator<IN, OUT> extends GlutenOneInputOperator<IN, OUT> + implements OneInputStreamOperator<IN, OUT> { + + private static final long serialVersionUID = 1L; + + private static final String NATIVE_STATE_NAME = "group-window-agg-native-state"; + + private static final ListStateDescriptor<String> NATIVE_STATE_DESCRIPTOR = + new ListStateDescriptor<>(NATIVE_STATE_NAME, StringSerializer.INSTANCE); + + /** Union list carrying the native keyed-state records; captured in initializeState. */ + private transient ListState<String> nativeStateStore; + + public GlutenWindowOneInputOperator( + StatefulPlanNode plan, + String id, + RowType inputType, + Map<String, RowType> outputTypes, + Class<IN> inClass, + Class<OUT> outClass, + String description) { + super(plan, id, inputType, outputTypes, inClass, outClass, description); + } + + public GlutenWindowOneInputOperator( + StatefulPlanNode plan, + String id, + RowType inputType, + Map<String, RowType> outputTypes, + Class<IN> inClass, + Class<OUT> outClass) { + super(plan, id, inputType, outputTypes, inClass, outClass); + } + + /** + * Clones into the same subclass, not the base class: the offloaded job graph generator rebuilds + * every offloadable one-input operator through this method ({@code + * OffloadedJobGraphGenerator#createOffloadedOneInputOperator}), and the base implementation + * constructs a plain {@link GlutenOneInputOperator} - silently dropping this subclass's RocksDB + * fail-loud rejection and native-checkpoint persistence on the way to the task managers. Same + * override pattern as {@code WindowAggOperator#cloneWithInputOutputClasses}. + */ + @Override + public <NIN, NOUT> GlutenWindowOneInputOperator<NIN, NOUT> cloneWithInputOutputClasses( + StatefulPlanNode plan, Class<NIN> newInClass, Class<NOUT> newOutClass) { + return new GlutenWindowOneInputOperator<>( + plan, getId(), getInputType(), getOutputTypes(), newInClass, newOutClass, getDescription()); + } + + @Override + protected void initializeNativeState(StateInitializationContext context) throws Exception { + if (usesRocksDBStateBackend()) { + // The shared base class silently skips the native state initialization + // for RocksDB; a keyed native operator must fail loud instead of + // running without its state. Checked before any native session is + // created so the rejection needs no native library. + throw new UnsupportedOperationException( + "VELOX_UNSUPPORTED: group window aggregation does not support the RocksDB keyed " + + "state backend; configure the heap state backend (state.backend: hashmap)"); + } + if (task == null) { + initSession(); + } + // The union list is registered and captured here (on every + // initializeState, fresh or restoring); snapshotNativeState below writes + // through the same state handle, the standard Flink operator pattern. + nativeStateStore = context.getOperatorStateStore().getUnionListState(NATIVE_STATE_DESCRIPTOR); Review Comment: **Blocking.** Union list state hands every subtask the full window state on restore, so restore memory and time grow with parallelism × state size. That will hurt for large SESSION state. At minimum, please document the limit and open a follow-up for keyed or raw keyed state. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -178,69 +186,124 @@ protected Transformation<RowData> translateToPlanInternal( } else { isCountWindow = false; } - - if (isCountWindow && grouping.length > 0 && config.getStateRetentionTime() < 0) { - LOGGER.warn( - "No state retention interval configured for a query which accumulates state. " - + "Please provide a query configuration with valid retention interval to prevent " - + "excessive state size. You may specify a retention time of 0 to not clean up the state."); + checkArgument( + !isCountWindow, Review Comment: This class overrides Flink's own `StreamExecGroupWindowAggregate` and the vanilla path is removed, so processing-time windows, row-count windows, EMIT strategies and unsupported key types now fail queries that plain Flink runs. Could these cases build Flink's original `WindowOperator` instead of throwing? If fail-loud is intended, please say so in `Flink.md`. ########## gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenWindowOneInputOperator.java: ########## @@ -0,0 +1,183 @@ +/* + * 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 io.github.zhztheplayer.velox4j.plan.StatefulPlanNode; +import io.github.zhztheplayer.velox4j.query.SerialTask; +import io.github.zhztheplayer.velox4j.type.RowType; + +import org.apache.flink.api.common.state.ListState; +import org.apache.flink.api.common.state.ListStateDescriptor; +import org.apache.flink.api.common.typeutils.base.StringSerializer; +import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend; +import org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend; +import org.apache.flink.contrib.streaming.state.RocksDBStateBackend; +import org.apache.flink.runtime.state.StateBackend; +import org.apache.flink.runtime.state.StateBackendLoader; +import org.apache.flink.runtime.state.StateInitializationContext; +import org.apache.flink.runtime.state.StateSnapshotContext; +import org.apache.flink.runtime.state.delegate.DelegatingStateBackend; +import org.apache.flink.streaming.api.operators.OneInputStreamOperator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * A {@link GlutenOneInputOperator} for the group-window aggregation: replaces the base class's + * RocksDB behavior (silently skipping native state initialization) with fail-loud rejection, and + * persists the native keyed-state checkpoint records into Flink operator state so they survive + * restarts and rescales. + * + * <p>RocksDB rejection: the window aggregation transformation is intentionally non-keyed (the user + * key rides the plan's KeyedStateSpec and the upstream exchange), so no keyed backend is ever + * materialized for this operator and inspecting the materialized keyed backend alone can never fire + * in production. {@code usesRocksDBStateBackend} therefore resolves the effective backend the same + * way the containing task does (application backend from the operator config, then job + * configuration, then cluster configuration, via {@link + * StateBackendLoader#fromApplicationOrConfigOrDefault}) and inspects the resolved factory, in + * addition to the materialized keyed backend. + * + * <p>Checkpoint round-trip: {@code snapshotNativeState} stores the records returned by {@link + * SerialTask#snapshotState(long)} into a union-list operator state; {@code initializeNativeState} + * replays them through {@link SerialTask#initializeState(long, + * io.github.zhztheplayer.velox4j.stateful.KeyedStateBackendParameters, String[])}. The union list + * hands every restored task the full set of snapshot records; the velox-side restore keeps only the + * entries overlapping the task's key-group range. (The records ride the velox4j JNI String + * boundary, which is not binary-safe - the known checkpoint e2e limitation; the native + * snapshot/restore semantics are pinned by the velox-side unit tests.) + */ +public class GlutenWindowOneInputOperator<IN, OUT> extends GlutenOneInputOperator<IN, OUT> + implements OneInputStreamOperator<IN, OUT> { + + private static final long serialVersionUID = 1L; + + private static final String NATIVE_STATE_NAME = "group-window-agg-native-state"; + + private static final ListStateDescriptor<String> NATIVE_STATE_DESCRIPTOR = + new ListStateDescriptor<>(NATIVE_STATE_NAME, StringSerializer.INSTANCE); + + /** Union list carrying the native keyed-state records; captured in initializeState. */ + private transient ListState<String> nativeStateStore; + + public GlutenWindowOneInputOperator( + StatefulPlanNode plan, + String id, + RowType inputType, + Map<String, RowType> outputTypes, + Class<IN> inClass, + Class<OUT> outClass, + String description) { + super(plan, id, inputType, outputTypes, inClass, outClass, description); + } + + public GlutenWindowOneInputOperator( + StatefulPlanNode plan, + String id, + RowType inputType, + Map<String, RowType> outputTypes, + Class<IN> inClass, + Class<OUT> outClass) { + super(plan, id, inputType, outputTypes, inClass, outClass); + } + + /** + * Clones into the same subclass, not the base class: the offloaded job graph generator rebuilds + * every offloadable one-input operator through this method ({@code + * OffloadedJobGraphGenerator#createOffloadedOneInputOperator}), and the base implementation + * constructs a plain {@link GlutenOneInputOperator} - silently dropping this subclass's RocksDB + * fail-loud rejection and native-checkpoint persistence on the way to the task managers. Same + * override pattern as {@code WindowAggOperator#cloneWithInputOutputClasses}. + */ + @Override + public <NIN, NOUT> GlutenWindowOneInputOperator<NIN, NOUT> cloneWithInputOutputClasses( + StatefulPlanNode plan, Class<NIN> newInClass, Class<NOUT> newOutClass) { + return new GlutenWindowOneInputOperator<>( + plan, getId(), getInputType(), getOutputTypes(), newInClass, newOutClass, getDescription()); + } + + @Override + protected void initializeNativeState(StateInitializationContext context) throws Exception { + if (usesRocksDBStateBackend()) { + // The shared base class silently skips the native state initialization + // for RocksDB; a keyed native operator must fail loud instead of + // running without its state. Checked before any native session is + // created so the rejection needs no native library. + throw new UnsupportedOperationException( + "VELOX_UNSUPPORTED: group window aggregation does not support the RocksDB keyed " + + "state backend; configure the heap state backend (state.backend: hashmap)"); + } + if (task == null) { + initSession(); + } + // The union list is registered and captured here (on every + // initializeState, fresh or restoring); snapshotNativeState below writes + // through the same state handle, the standard Flink operator pattern. + nativeStateStore = context.getOperatorStateStore().getUnionListState(NATIVE_STATE_DESCRIPTOR); + List<String> restored = new ArrayList<>(); + if (context.isRestored()) { + for (String record : nativeStateStore.get()) { + if (record != null && !record.isEmpty()) { + restored.add(record); + } + } + } + task.initializeState(0, null, restored.toArray(new String[0])); Review Comment: **Blocking.** How does the native restore know this subtask's key-group range? The class Javadoc says the velox restore keeps only entries overlapping the task's key-group range, but `KeyedStateBackendParameters` is `null` here (and only carries `jobId`/`operatorId`/`stateBackendType`), and `VeloxQueryConfig` doesn't pass max parallelism, subtask index or key-group range. Rows are routed upstream by the native `KeyGroupPartitionFunctionSpec(..., maxParallelism)` in `StreamExecExchange`. Since the union list gives every subtask the full state on restore, the native filter needs the same `maxParallelism` and this subtask's range. Otherwise each subtask keeps all windows (duplicate output) or none. Where does velox get these values? ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -96,15 +95,19 @@ minPlanVersion = FlinkVersion.v1_15, minStateVersion = FlinkVersion.v1_15) Review Comment: The state layout moved from Flink keyed state to native records in operator state, but the ExecNode version and `minStateVersion` are unchanged, so earlier savepoints can't restore. Worth a note in the docs. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -255,19 +318,99 @@ protected Transformation<RowData> translateToPlanInternal( inputTransform, createTransformationMeta(GROUP_WINDOW_AGGREGATE_TRANSFORMATION, config), SimpleOperatorFactory.of(windowOperator), - InternalTypeInfo.of(getOutputType()), + org.apache.flink.table.runtime.typeutils.InternalTypeInfo.of(getOutputType()), inputTransform.getParallelism(), false); - // set KeyType and Selector for state - final RowDataKeySelector selector = - KeySelectorUtil.getRowDataSelector( - planner.getFlinkContext().getClassLoader(), - grouping, - InternalTypeInfo.of(inputRowType)); - transform.setStateKeySelector(selector); - transform.setStateKeyType(selector.getProducedType()); + // The transformation stays non-keyed by design: the user key rides the + // plan's KeyedStateSpec into the velox keyed state backend, and a + // Flink-side state key selector would put the transformation into a + // keyed context the native backend does not share (the q11 + // "Key group not in KeyGroupRange" failure). return transform; } + + /** Index of the first no-argument COUNT(*) among the calls; -1 when absent. */ + private static int countStarIndexOf(AggregateCall[] aggCalls) { + for (int i = 0; i < aggCalls.length; i++) { + AggregateCall call = aggCalls[i]; + if (call.getAggregation().getName().equalsIgnoreCase("COUNT") + && call.getArgList().isEmpty()) { + return i; + } + } + return -1; + } + + /** + * The user key as pure plan data: grouping channels and their input types, restricted to the + * fixed-width scalar and varchar/varbinary shapes the velox key equality supports. + */ + private static KeyedStateSpec keyedStateSpec( Review Comment: With `grouping.length == 0` (no GROUP BY key) the `KeyedStateSpec` is empty. Does velox handle that? A test would be good. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -178,69 +186,124 @@ protected Transformation<RowData> translateToPlanInternal( } else { isCountWindow = false; } - - if (isCountWindow && grouping.length > 0 && config.getStateRetentionTime() < 0) { - LOGGER.warn( - "No state retention interval configured for a query which accumulates state. " - + "Please provide a query configuration with valid retention interval to prevent " - + "excessive state size. You may specify a retention time of 0 to not clean up the state."); + checkArgument( + !isCountWindow, + "VELOX_UNSUPPORTED: group window aggregation does not support row-count windows " + + "(CountTumbling/CountSliding are out of scope)"); + checkArgument( + !config.get( + ConfigOptions.key("table.exec.emit.early-fire.enabled") + .booleanType() + .defaultValue(false)), + "VELOX_UNSUPPORTED: group window aggregation does not support the early-fire EMIT " + + "strategy (table.exec.emit.early-fire.enabled)"); + checkArgument( + config + .getOptional( + ConfigOptions.key("table.exec.emit.early-fire.delay") + .durationType() + .noDefaultValue()) + .orElse(Duration.ZERO) + .toMillis() + <= 0, + "VELOX_UNSUPPORTED: group window aggregation does not support the early-fire EMIT " + + "strategy (table.exec.emit.early-fire.delay)"); + checkArgument( + !config.get( + ConfigOptions.key("table.exec.emit.late-fire.enabled") + .booleanType() + .defaultValue(false)), + "VELOX_UNSUPPORTED: group window aggregation does not support the late-fire EMIT " + + "strategy (table.exec.emit.late-fire.enabled)"); + checkArgument( + config + .getOptional( + ConfigOptions.key("table.exec.emit.allow-lateness") + .durationType() + .noDefaultValue()) + .orElse(Duration.ZERO) + .toMillis() + <= 0, + "VELOX_UNSUPPORTED: group window aggregation does not support non-zero allowed " + + "lateness (table.exec.emit.allow-lateness)"); + checkArgument( + isRowtimeAttribute(window.timeAttribute()), + "VELOX_UNSUPPORTED: group window aggregation requires a rowtime time attribute " + + "(processing-time windows are out of scope)"); + if (!(window instanceof SessionGroupWindow + || window instanceof TumblingGroupWindow + || window instanceof SlidingGroupWindow)) { + throw new TableException( + "VELOX_UNSUPPORTED: group window aggregation supports SESSION / TUMBLE / " + + "HOP windows only, window was: " + + window.toString()); } + // --- End of fail-loud faces --- final ExecEdge inputEdge = getInputEdges().get(0); final Transformation<RowData> inputTransform = (Transformation<RowData>) inputEdge.translateToPlan(planner); - final RowType inputRowType = (RowType) inputEdge.getOutputType(); - - final int inputTimeFieldIndex; - if (isRowtimeAttribute(window.timeAttribute())) { - inputTimeFieldIndex = window.timeAttribute().getFieldIndex(); - if (inputTimeFieldIndex < 0) { - throw new TableException( - "Group window must defined on a time attribute, " - + "but the time attribute can't be found.\n" - + "This should never happen. Please file an issue."); - } - } else { - inputTimeFieldIndex = -1; - } + final org.apache.flink.table.types.logical.RowType inputRowType = Review Comment: Nit: `RowType` is already imported, so the fully qualified name isn't needed. Same for `InternalTypeInfo` further down. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -178,69 +186,124 @@ protected Transformation<RowData> translateToPlanInternal( } else { isCountWindow = false; } - - if (isCountWindow && grouping.length > 0 && config.getStateRetentionTime() < 0) { - LOGGER.warn( - "No state retention interval configured for a query which accumulates state. " - + "Please provide a query configuration with valid retention interval to prevent " - + "excessive state size. You may specify a retention time of 0 to not clean up the state."); + checkArgument( + !isCountWindow, + "VELOX_UNSUPPORTED: group window aggregation does not support row-count windows " + + "(CountTumbling/CountSliding are out of scope)"); + checkArgument( + !config.get( + ConfigOptions.key("table.exec.emit.early-fire.enabled") + .booleanType() + .defaultValue(false)), + "VELOX_UNSUPPORTED: group window aggregation does not support the early-fire EMIT " + + "strategy (table.exec.emit.early-fire.enabled)"); + checkArgument( + config + .getOptional( + ConfigOptions.key("table.exec.emit.early-fire.delay") + .durationType() + .noDefaultValue()) + .orElse(Duration.ZERO) + .toMillis() + <= 0, + "VELOX_UNSUPPORTED: group window aggregation does not support the early-fire EMIT " + + "strategy (table.exec.emit.early-fire.delay)"); + checkArgument( + !config.get( + ConfigOptions.key("table.exec.emit.late-fire.enabled") + .booleanType() + .defaultValue(false)), + "VELOX_UNSUPPORTED: group window aggregation does not support the late-fire EMIT " + + "strategy (table.exec.emit.late-fire.enabled)"); + checkArgument( + config + .getOptional( + ConfigOptions.key("table.exec.emit.allow-lateness") + .durationType() + .noDefaultValue()) + .orElse(Duration.ZERO) + .toMillis() + <= 0, + "VELOX_UNSUPPORTED: group window aggregation does not support non-zero allowed " + + "lateness (table.exec.emit.allow-lateness)"); + checkArgument( + isRowtimeAttribute(window.timeAttribute()), + "VELOX_UNSUPPORTED: group window aggregation requires a rowtime time attribute " + + "(processing-time windows are out of scope)"); + if (!(window instanceof SessionGroupWindow + || window instanceof TumblingGroupWindow + || window instanceof SlidingGroupWindow)) { + throw new TableException( + "VELOX_UNSUPPORTED: group window aggregation supports SESSION / TUMBLE / " + + "HOP windows only, window was: " + + window.toString()); } + // --- End of fail-loud faces --- final ExecEdge inputEdge = getInputEdges().get(0); final Transformation<RowData> inputTransform = (Transformation<RowData>) inputEdge.translateToPlan(planner); - final RowType inputRowType = (RowType) inputEdge.getOutputType(); - - final int inputTimeFieldIndex; - if (isRowtimeAttribute(window.timeAttribute())) { - inputTimeFieldIndex = window.timeAttribute().getFieldIndex(); - if (inputTimeFieldIndex < 0) { - throw new TableException( - "Group window must defined on a time attribute, " - + "but the time attribute can't be found.\n" - + "This should never happen. Please file an issue."); - } - } else { - inputTimeFieldIndex = -1; - } + final org.apache.flink.table.types.logical.RowType inputRowType = + (org.apache.flink.table.types.logical.RowType) inputEdge.getOutputType(); + + final int inputTimeFieldIndex = window.timeAttribute().getFieldIndex(); + checkArgument( + inputTimeFieldIndex >= 0, + "Group window must be defined on a time attribute, but the time attribute can't be " + + "found.\nThis should never happen. Please file an issue."); WindowEmitStrategy emitStrategy = WindowEmitStrategy.apply(config, window); - // --- Begin Gluten-specific code changes --- - // TODO: velox window not equal to flink window. io.github.zhztheplayer.velox4j.type.RowType inputType = (io.github.zhztheplayer.velox4j.type.RowType) LogicalTypeConverter.toVLType(inputRowType); io.github.zhztheplayer.velox4j.type.RowType outputType = (io.github.zhztheplayer.velox4j.type.RowType) LogicalTypeConverter.toVLType(getOutputType()); - List<FieldAccessTypedExpr> groupingKeys = Utils.generateFieldAccesses(inputType, grouping); List<Aggregate> aggregates = AggregateCallConverter.toAggregates(aggCalls, inputType); - checkArgument(outputType.getNames().size() >= grouping.length + aggCalls.length); - List<String> aggNames = - outputType.getNames().stream() - .skip(grouping.length) - .limit(aggCalls.length) - .collect(Collectors.toList()); - List<Integer> keyIndexes = Arrays.stream(grouping).boxed().collect(Collectors.toList()); - PartitionFunctionSpec keySelectorSpec = new HashPartitionFunctionSpec(inputType, keyIndexes); - // TODO: support more window types. - PartitionFunctionSpec sliceAssignerSpec = - new StreamWindowPartitionFunctionSpec(inputType, inputTimeFieldIndex, 0L, 0L, 0L, 1); - PlanNode aggregation = new GroupWindowAggsHandlerNode(PlanNodeIdGenerator.newId(), outputType); + PlanNode aggregation = + new GroupWindowAggsHandlerNode( + PlanNodeIdGenerator.newId(), outputType, aggregates, countStarIndexOf(aggCalls)); + KeyedStateSpec keyedStateSpec = keyedStateSpec(grouping, inputRowType); + // Window parameters keyed by window kind, routed through the velox + // WindowType enum (experimental/stateful/window/Window.h: HOP=0, + // TUMBLE=1, SESSION=2, CUMULATIVE=3). SESSION carries the gap; TUMBLE + // the size; HOP the size and slide (the legacy group window planner + // exposes no user offset — it stays the fixed 0 on the velox side). + int windowType; + long gap = 0L; + long size = 0L; + long slide = 0L; + if (window instanceof SessionGroupWindow) { + windowType = VELOX_WINDOW_TYPE_SESSION; + gap = toDuration(((SessionGroupWindow) window).gap()).toMillis(); + } else if (window instanceof TumblingGroupWindow) { + windowType = VELOX_WINDOW_TYPE_TUMBLE; + size = toDuration(((TumblingGroupWindow) window).size()).toMillis(); + } else { + windowType = VELOX_WINDOW_TYPE_HOP; + size = toDuration(((SlidingGroupWindow) window).size()).toMillis(); + slide = toDuration(((SlidingGroupWindow) window).slide()).toMillis(); + } PlanNode windowAgg = new GroupWindowAggregationNode( PlanNodeIdGenerator.newId(), aggregation, - keySelectorSpec, - sliceAssignerSpec, + keyedStateSpec, + inputType, + // The EMIT fail-loud faces above pin these to the P0 defaults. emitStrategy.getAllowLateness(), emitStrategy.produceUpdates(), inputTimeFieldIndex, - true, // TODO: get from window attributes - 1, // TODO: get from window attributes + true, Review Comment: Nit: a one-line comment tying the hard-coded `isEventTime = true` to the rowtime check above would help. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -255,19 +318,99 @@ protected Transformation<RowData> translateToPlanInternal( inputTransform, createTransformationMeta(GROUP_WINDOW_AGGREGATE_TRANSFORMATION, config), SimpleOperatorFactory.of(windowOperator), - InternalTypeInfo.of(getOutputType()), + org.apache.flink.table.runtime.typeutils.InternalTypeInfo.of(getOutputType()), inputTransform.getParallelism(), false); - // set KeyType and Selector for state - final RowDataKeySelector selector = - KeySelectorUtil.getRowDataSelector( - planner.getFlinkContext().getClassLoader(), - grouping, - InternalTypeInfo.of(inputRowType)); - transform.setStateKeySelector(selector); - transform.setStateKeyType(selector.getProducedType()); + // The transformation stays non-keyed by design: the user key rides the + // plan's KeyedStateSpec into the velox keyed state backend, and a + // Flink-side state key selector would put the transformation into a + // keyed context the native backend does not share (the q11 Review Comment: Nit: "q11" is an internal reference. Could the comment describe the failure without it? Same for "P0" and "KeyedStateSpec ironclad" elsewhere. ########## gluten-flink/ut/src/test/java/org/apache/gluten/planner/StreamExecGroupWindowAggregateWindowAggTest.java: ########## @@ -0,0 +1,280 @@ +/* + * 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.planner; + +import org.apache.gluten.table.runtime.operators.GlutenWindowOneInputOperator; + +import org.apache.flink.api.dag.Transformation; +import org.apache.flink.streaming.api.datastream.DataStream; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.transformations.OneInputTransformation; +import org.apache.flink.table.api.EnvironmentSettings; +import org.apache.flink.table.api.Table; +import org.apache.flink.table.api.Tumble; +import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; +import org.apache.flink.table.planner.factories.TestValuesTableFactory; +import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecGroupWindowAggregate; +import org.apache.flink.types.Row; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.List; + +import static org.apache.flink.table.api.Expressions.$; +import static org.apache.flink.table.api.Expressions.lit; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +/** + * Planner-level tests for the gluten override of {@link StreamExecGroupWindowAggregate}: the + * translated transformation stays non-keyed (the user key belongs to the velox keyed state backend + * and the upstream exchange, so no Flink state key selector may be declared - the q11 regression + * line), the operator is the {@link GlutenWindowOneInputOperator} subclass, and the fail-loud faces + * of the P0 scope: row-count windows, non-default EMIT strategies, processing-time attributes, and + * the TUMBLE / HOP windows phased into the next stage. + */ +public class StreamExecGroupWindowAggregateWindowAggTest { + + @Test + public void sessionWindowTransformationStaysNonKeyed() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createRowtimeTable(tEnv, Arrays.asList(row(1, 1, 100L), row(2, 2, 200L))); + Table result = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c," + + " SESSION_START(ts, INTERVAL '10' SECOND) AS ws," + + " SESSION_END(ts, INTERVAL '10' SECOND) AS we" + + " FROM T GROUP BY k, SESSION(ts, INTERVAL '10' SECOND)"); + DataStream<Row> changelog = tEnv.toChangelogStream(result); + OneInputTransformation<?, ?> windowAgg = findGroupWindowAgg(changelog.getTransformation()); + assertThat(windowAgg) + .as("the translated plan must contain the group-window-aggregate transformation") + .isNotNull(); + // A declared Flink state key selector would put the transformation into a + // keyed context the native keyed state backend does not share (the q11 + // "Key group not in KeyGroupRange" failure); the user key rides the + // plan's KeyedStateSpec and the upstream exchange instead. + assertThat(windowAgg.getStateKeySelector()).isNull(); + assertThat(windowAgg.getStateKeyType()).isNull(); + assertThat(windowAgg.getOperator()).isInstanceOf(GlutenWindowOneInputOperator.class); + } + + @Test + public void rowCountWindowFailsLoud() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createProctimeTable(tEnv, Arrays.asList(Row.of(1, 1))); + // A BIGINT window size means a row-count window (CountTumbling), out of + // scope for the velox group window aggregation - the same check Flink + // applies to route to the count-window operator family. Row-count + // windows reach the planner through the Table API (the SQL validator + // only accepts interval sizes); the check fires before the proctime + // face. + Table result = + tEnv.from("T") + .window(Tumble.over(lit(5L)).on($("pt")).as("w")) + .groupBy($("k"), $("w")) + .select($("k"), $("v").count()); + Throwable thrown = catchThrowable(() -> tEnv.toChangelogStream(result)); + Throwable root = rootCause(thrown); + assertThat(root) + .as("a row-count window must fail at translation, got: %s", thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("VELOX_UNSUPPORTED") + .hasMessageContaining("row-count"); + } + + @Test + public void earlyFireEmitFailsLoud() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createRowtimeTable(tEnv, Arrays.asList(row(1, 1, 100L))); + tEnv.getConfig().getConfiguration().setString("table.exec.emit.early-fire.enabled", "true"); + // A positive early-fire delay carries the plan past Flink's own emit + // validation (session windows and enabled-without-delay are rejected + // there earlier); a TUMBLE window with a valid strategy reaches the + // gluten rejection of non-default EMIT. + tEnv.getConfig().getConfiguration().setString("table.exec.emit.early-fire.delay", "1 s"); + Table result = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c FROM T GROUP BY k, TUMBLE(ts, INTERVAL '10' SECOND)"); + Throwable thrown = catchThrowable(() -> tEnv.toChangelogStream(result)); + Throwable root = rootCause(thrown); + assertThat(root) + .as("the early-fire EMIT strategy must fail at translation, got: %s", thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("VELOX_UNSUPPORTED") + .hasMessageContaining("early-fire"); + } + + @Test + public void allowLatenessFailsLoud() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createRowtimeTable(tEnv, Arrays.asList(row(1, 1, 100L))); + tEnv.getConfig().getConfiguration().setString("table.exec.emit.allow-lateness", "10 s"); + Table result = sessionQuery(tEnv); + Throwable thrown = catchThrowable(() -> tEnv.toChangelogStream(result)); + Throwable root = rootCause(thrown); + assertThat(root) + .as("non-zero allowed lateness must fail at translation, got: %s", thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("VELOX_UNSUPPORTED") + .hasMessageContaining("lateness"); + } + + @Test + public void proctimeWindowFailsLoud() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createProctimeTable(tEnv, Arrays.asList(Row.of(1, 1))); + Table result = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c FROM T GROUP BY k, SESSION(pt, INTERVAL '10' SECOND)"); + Throwable thrown = catchThrowable(() -> tEnv.toChangelogStream(result)); + Throwable root = rootCause(thrown); + assertThat(root) + .as("a processing-time window must fail at translation, got: %s", thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("VELOX_UNSUPPORTED") + .hasMessageContaining("rowtime"); + } + + @Test + public void tumbleAndHopWindowsPlanToVelox() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createRowtimeTable(tEnv, Arrays.asList(row(1, 1, 100L))); + // TUMBLE and HOP plan through the gluten override to the velox window + // aggregation node now (the former next-phase fail-loud is lifted); the + // transformation must still be non-keyed (the KeyedStateSpec ironclad). + Table tumble = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c FROM T GROUP BY k, TUMBLE(ts, INTERVAL '10' SECOND)"); + Transformation<?> tumbleTransform = tEnv.toChangelogStream(tumble).getTransformation(); + assertThat(tumbleTransform).isNotNull(); + + Table hop = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c FROM T" + + " GROUP BY k, HOP(ts, INTERVAL '10' SECOND, INTERVAL '5' SECOND)"); + Transformation<?> hopTransform = tEnv.toChangelogStream(hop).getTransformation(); + assertThat(hopTransform).isNotNull(); + } + + /** + * The classpath must resolve the gluten-flink-planner override of the ExecNode, not Flink's own: + * otherwise these assertions would guard code that never runs. The jar carries the artifact name; + * an IDE build resolves the module's classes directory. + */ + private static void assertGlutenOverrideIsUnderTest() { + String location = + StreamExecGroupWindowAggregate.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .toString(); + boolean fromGlutenPlanner = + location.contains("gluten-flink-planner") || location.contains("/planner/"); Review Comment: Nit: `location.contains("/planner/")` is loose and can match unrelated paths. ########## gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/typeutils/GlutenStatefulRecordSerializer.java: ########## @@ -60,20 +60,20 @@ public StatefulRecord createInstance() { @Override public void serialize(StatefulRecord record, DataOutputView target) throws IOException { - String vectorStr = record.getRowVector().serialize(); - target.writeInt(vectorStr.getBytes().length); - target.write(vectorStr.getBytes()); + byte[] vectorBytes = record.getRowVector().serialize(); Review Comment: This changes the network serialization format and is unrelated to window aggregation. Could it be a separate PR, or at least a separately titled commit? ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -178,69 +186,124 @@ protected Transformation<RowData> translateToPlanInternal( } else { isCountWindow = false; } - - if (isCountWindow && grouping.length > 0 && config.getStateRetentionTime() < 0) { - LOGGER.warn( - "No state retention interval configured for a query which accumulates state. " - + "Please provide a query configuration with valid retention interval to prevent " - + "excessive state size. You may specify a retention time of 0 to not clean up the state."); + checkArgument( + !isCountWindow, + "VELOX_UNSUPPORTED: group window aggregation does not support row-count windows " + + "(CountTumbling/CountSliding are out of scope)"); + checkArgument( + !config.get( + ConfigOptions.key("table.exec.emit.early-fire.enabled") Review Comment: These checks re-read raw config strings, and `WindowEmitStrategy.apply(config, window)` is computed below anyway. Checking `emitStrategy.produceUpdates()` and `emitStrategy.getAllowLateness() != 0` is simpler and follows Flink's own derivation of lateness. If you keep the keys, please use the `WindowEmitStrategy.TABLE_EXEC_EMIT_*` constants. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -170,6 +173,11 @@ public StreamExecGroupWindowAggregate( @Override protected Transformation<RowData> translateToPlanInternal( PlannerBase planner, ExecNodeConfig config) { + // --- Gluten-specific code changes --- + // Fail-loud faces, most specific first: row-count windows are out of + // scope, non-default EMIT strategies are out of scope, processing-time + // attributes are out of scope, and the TUMBLE / HOP windows are phased Review Comment: Nit: stale comment. TUMBLE/HOP are supported now. The test class Javadoc has the same text. ########## gluten-flink/runtime/src/main/java/org/apache/gluten/table/runtime/operators/GlutenWindowOneInputOperator.java: ########## @@ -0,0 +1,183 @@ +/* + * 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 io.github.zhztheplayer.velox4j.plan.StatefulPlanNode; +import io.github.zhztheplayer.velox4j.query.SerialTask; +import io.github.zhztheplayer.velox4j.type.RowType; + +import org.apache.flink.api.common.state.ListState; +import org.apache.flink.api.common.state.ListStateDescriptor; +import org.apache.flink.api.common.typeutils.base.StringSerializer; +import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend; +import org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend; +import org.apache.flink.contrib.streaming.state.RocksDBStateBackend; +import org.apache.flink.runtime.state.StateBackend; +import org.apache.flink.runtime.state.StateBackendLoader; +import org.apache.flink.runtime.state.StateInitializationContext; +import org.apache.flink.runtime.state.StateSnapshotContext; +import org.apache.flink.runtime.state.delegate.DelegatingStateBackend; +import org.apache.flink.streaming.api.operators.OneInputStreamOperator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * A {@link GlutenOneInputOperator} for the group-window aggregation: replaces the base class's + * RocksDB behavior (silently skipping native state initialization) with fail-loud rejection, and + * persists the native keyed-state checkpoint records into Flink operator state so they survive + * restarts and rescales. + * + * <p>RocksDB rejection: the window aggregation transformation is intentionally non-keyed (the user + * key rides the plan's KeyedStateSpec and the upstream exchange), so no keyed backend is ever + * materialized for this operator and inspecting the materialized keyed backend alone can never fire + * in production. {@code usesRocksDBStateBackend} therefore resolves the effective backend the same + * way the containing task does (application backend from the operator config, then job + * configuration, then cluster configuration, via {@link + * StateBackendLoader#fromApplicationOrConfigOrDefault}) and inspects the resolved factory, in + * addition to the materialized keyed backend. + * + * <p>Checkpoint round-trip: {@code snapshotNativeState} stores the records returned by {@link + * SerialTask#snapshotState(long)} into a union-list operator state; {@code initializeNativeState} + * replays them through {@link SerialTask#initializeState(long, + * io.github.zhztheplayer.velox4j.stateful.KeyedStateBackendParameters, String[])}. The union list + * hands every restored task the full set of snapshot records; the velox-side restore keeps only the + * entries overlapping the task's key-group range. (The records ride the velox4j JNI String + * boundary, which is not binary-safe - the known checkpoint e2e limitation; the native + * snapshot/restore semantics are pinned by the velox-side unit tests.) + */ +public class GlutenWindowOneInputOperator<IN, OUT> extends GlutenOneInputOperator<IN, OUT> + implements OneInputStreamOperator<IN, OUT> { + + private static final long serialVersionUID = 1L; + + private static final String NATIVE_STATE_NAME = "group-window-agg-native-state"; + + private static final ListStateDescriptor<String> NATIVE_STATE_DESCRIPTOR = + new ListStateDescriptor<>(NATIVE_STATE_NAME, StringSerializer.INSTANCE); + + /** Union list carrying the native keyed-state records; captured in initializeState. */ + private transient ListState<String> nativeStateStore; + + public GlutenWindowOneInputOperator( + StatefulPlanNode plan, + String id, + RowType inputType, + Map<String, RowType> outputTypes, + Class<IN> inClass, + Class<OUT> outClass, + String description) { + super(plan, id, inputType, outputTypes, inClass, outClass, description); + } + + public GlutenWindowOneInputOperator( + StatefulPlanNode plan, + String id, + RowType inputType, + Map<String, RowType> outputTypes, + Class<IN> inClass, + Class<OUT> outClass) { + super(plan, id, inputType, outputTypes, inClass, outClass); + } + + /** + * Clones into the same subclass, not the base class: the offloaded job graph generator rebuilds + * every offloadable one-input operator through this method ({@code + * OffloadedJobGraphGenerator#createOffloadedOneInputOperator}), and the base implementation + * constructs a plain {@link GlutenOneInputOperator} - silently dropping this subclass's RocksDB + * fail-loud rejection and native-checkpoint persistence on the way to the task managers. Same + * override pattern as {@code WindowAggOperator#cloneWithInputOutputClasses}. + */ + @Override + public <NIN, NOUT> GlutenWindowOneInputOperator<NIN, NOUT> cloneWithInputOutputClasses( + StatefulPlanNode plan, Class<NIN> newInClass, Class<NOUT> newOutClass) { + return new GlutenWindowOneInputOperator<>( + plan, getId(), getInputType(), getOutputTypes(), newInClass, newOutClass, getDescription()); + } + + @Override + protected void initializeNativeState(StateInitializationContext context) throws Exception { + if (usesRocksDBStateBackend()) { + // The shared base class silently skips the native state initialization + // for RocksDB; a keyed native operator must fail loud instead of + // running without its state. Checked before any native session is + // created so the rejection needs no native library. + throw new UnsupportedOperationException( Review Comment: **Blocking.** RocksDB is the usual production backend. Before, the base class skipped native state init for it. Now the job is accepted at submission and then fails here on every restart, so the restart strategy loops. Could the planner also check `StateBackendOptions.STATE_BACKEND` and reject at translation time? This runtime check is fine as a backstop. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -255,19 +318,99 @@ protected Transformation<RowData> translateToPlanInternal( inputTransform, createTransformationMeta(GROUP_WINDOW_AGGREGATE_TRANSFORMATION, config), SimpleOperatorFactory.of(windowOperator), - InternalTypeInfo.of(getOutputType()), + org.apache.flink.table.runtime.typeutils.InternalTypeInfo.of(getOutputType()), inputTransform.getParallelism(), false); - // set KeyType and Selector for state - final RowDataKeySelector selector = - KeySelectorUtil.getRowDataSelector( - planner.getFlinkContext().getClassLoader(), - grouping, - InternalTypeInfo.of(inputRowType)); - transform.setStateKeySelector(selector); - transform.setStateKeyType(selector.getProducedType()); + // The transformation stays non-keyed by design: the user key rides the + // plan's KeyedStateSpec into the velox keyed state backend, and a + // Flink-side state key selector would put the transformation into a + // keyed context the native backend does not share (the q11 + // "Key group not in KeyGroupRange" failure). return transform; } + + /** Index of the first no-argument COUNT(*) among the calls; -1 when absent. */ + private static int countStarIndexOf(AggregateCall[] aggCalls) { Review Comment: Matching on name `"COUNT"` with no args also matches `COUNT(*) FILTER (WHERE ...)`. Suggest `getAggregation().getKind() == SqlKind.COUNT && getArgList().isEmpty() && !call.hasFilter()`. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -255,19 +318,99 @@ protected Transformation<RowData> translateToPlanInternal( inputTransform, createTransformationMeta(GROUP_WINDOW_AGGREGATE_TRANSFORMATION, config), SimpleOperatorFactory.of(windowOperator), - InternalTypeInfo.of(getOutputType()), + org.apache.flink.table.runtime.typeutils.InternalTypeInfo.of(getOutputType()), inputTransform.getParallelism(), false); - // set KeyType and Selector for state - final RowDataKeySelector selector = - KeySelectorUtil.getRowDataSelector( - planner.getFlinkContext().getClassLoader(), - grouping, - InternalTypeInfo.of(inputRowType)); - transform.setStateKeySelector(selector); - transform.setStateKeyType(selector.getProducedType()); + // The transformation stays non-keyed by design: the user key rides the + // plan's KeyedStateSpec into the velox keyed state backend, and a + // Flink-side state key selector would put the transformation into a + // keyed context the native backend does not share (the q11 + // "Key group not in KeyGroupRange" failure). return transform; } + + /** Index of the first no-argument COUNT(*) among the calls; -1 when absent. */ + private static int countStarIndexOf(AggregateCall[] aggCalls) { + for (int i = 0; i < aggCalls.length; i++) { + AggregateCall call = aggCalls[i]; + if (call.getAggregation().getName().equalsIgnoreCase("COUNT") + && call.getArgList().isEmpty()) { + return i; + } + } + return -1; + } + + /** + * The user key as pure plan data: grouping channels and their input types, restricted to the + * fixed-width scalar and varchar/varbinary shapes the velox key equality supports. + */ + private static KeyedStateSpec keyedStateSpec( + int[] grouping, org.apache.flink.table.types.logical.RowType inputRowType) { + List<Integer> keyChannels = Arrays.stream(grouping).boxed().collect(Collectors.toList()); + for (int channel : grouping) { + LogicalType keyType = inputRowType.getTypeAt(channel); + switch (keyType.getTypeRoot()) { + case BOOLEAN: + case TINYINT: + case SMALLINT: + case INTEGER: + case BIGINT: + case FLOAT: + case DOUBLE: + case TIMESTAMP_WITHOUT_TIME_ZONE: + case VARCHAR: + case VARBINARY: + break; + default: + throw new IllegalArgumentException( + "VELOX_UNSUPPORTED: group window aggregation does not support a group key of " + + "type " + + keyType.asSummaryString()); + } + } + List<Type> keyTypes = + keyChannels.stream() + .map(channel -> LogicalTypeConverter.toVLType(inputRowType.getTypeAt(channel))) + .collect(Collectors.toList()); + return new KeyedStateSpec(keyChannels, keyTypes); + } + + /** + * Output index of the window-start property: keys, aggregates, then properties. + * + * <p>Cross-repo contract (CODE_REVIEW r3 item 7): the native emit loop fills the trailing + * time-attribute columns in the fixed planner order [start, end, rowtime, proctime] (rowtime = + * window maxTimestamp, proctime = NULL), so any change in the Flink window-property order must be + * synchronized with the velox emit loop in GroupWindowAggregator. + */ + private static int windowStartIndex( Review Comment: Only start/end indices are sent, and the native side is said to fill trailing columns in a fixed `[start, end, rowtime, proctime]` order. `namedWindowProperties` follows SELECT order, though. Does something like `SELECT ..., SESSION_END(...), SESSION_ROWTIME(...)` (no start) produce the right layout? These helpers also return `-1` when a property is absent, as in the TUMBLE/HOP test queries. Is `-1` handled natively? Passing an explicit index per property kind would remove the cross-repo ordering assumption. A test selecting only end + rowtime would help. Nit: please drop "CODE_REVIEW r3 item 7" here and in `windowEndIndex`. ########## gluten-flink/planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecGroupWindowAggregate.java: ########## @@ -178,69 +186,124 @@ protected Transformation<RowData> translateToPlanInternal( } else { isCountWindow = false; } - - if (isCountWindow && grouping.length > 0 && config.getStateRetentionTime() < 0) { - LOGGER.warn( - "No state retention interval configured for a query which accumulates state. " - + "Please provide a query configuration with valid retention interval to prevent " - + "excessive state size. You may specify a retention time of 0 to not clean up the state."); + checkArgument( + !isCountWindow, + "VELOX_UNSUPPORTED: group window aggregation does not support row-count windows " + + "(CountTumbling/CountSliding are out of scope)"); + checkArgument( + !config.get( + ConfigOptions.key("table.exec.emit.early-fire.enabled") + .booleanType() + .defaultValue(false)), + "VELOX_UNSUPPORTED: group window aggregation does not support the early-fire EMIT " + + "strategy (table.exec.emit.early-fire.enabled)"); + checkArgument( + config + .getOptional( + ConfigOptions.key("table.exec.emit.early-fire.delay") + .durationType() + .noDefaultValue()) + .orElse(Duration.ZERO) + .toMillis() + <= 0, + "VELOX_UNSUPPORTED: group window aggregation does not support the early-fire EMIT " + + "strategy (table.exec.emit.early-fire.delay)"); + checkArgument( + !config.get( + ConfigOptions.key("table.exec.emit.late-fire.enabled") + .booleanType() + .defaultValue(false)), + "VELOX_UNSUPPORTED: group window aggregation does not support the late-fire EMIT " + + "strategy (table.exec.emit.late-fire.enabled)"); + checkArgument( + config + .getOptional( + ConfigOptions.key("table.exec.emit.allow-lateness") + .durationType() + .noDefaultValue()) + .orElse(Duration.ZERO) + .toMillis() + <= 0, + "VELOX_UNSUPPORTED: group window aggregation does not support non-zero allowed " + + "lateness (table.exec.emit.allow-lateness)"); + checkArgument( + isRowtimeAttribute(window.timeAttribute()), + "VELOX_UNSUPPORTED: group window aggregation requires a rowtime time attribute " + + "(processing-time windows are out of scope)"); + if (!(window instanceof SessionGroupWindow + || window instanceof TumblingGroupWindow + || window instanceof SlidingGroupWindow)) { + throw new TableException( Review Comment: Nit: this throws `TableException` while the other checks use `checkArgument` (`IllegalArgumentException`). Pick one. ########## gluten-flink/ut/src/test/java/org/apache/gluten/planner/StreamExecGroupWindowAggregateWindowAggTest.java: ########## @@ -0,0 +1,280 @@ +/* + * 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.planner; + +import org.apache.gluten.table.runtime.operators.GlutenWindowOneInputOperator; + +import org.apache.flink.api.dag.Transformation; +import org.apache.flink.streaming.api.datastream.DataStream; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.transformations.OneInputTransformation; +import org.apache.flink.table.api.EnvironmentSettings; +import org.apache.flink.table.api.Table; +import org.apache.flink.table.api.Tumble; +import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; +import org.apache.flink.table.planner.factories.TestValuesTableFactory; +import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecGroupWindowAggregate; +import org.apache.flink.types.Row; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.List; + +import static org.apache.flink.table.api.Expressions.$; +import static org.apache.flink.table.api.Expressions.lit; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +/** + * Planner-level tests for the gluten override of {@link StreamExecGroupWindowAggregate}: the + * translated transformation stays non-keyed (the user key belongs to the velox keyed state backend + * and the upstream exchange, so no Flink state key selector may be declared - the q11 regression + * line), the operator is the {@link GlutenWindowOneInputOperator} subclass, and the fail-loud faces + * of the P0 scope: row-count windows, non-default EMIT strategies, processing-time attributes, and + * the TUMBLE / HOP windows phased into the next stage. + */ +public class StreamExecGroupWindowAggregateWindowAggTest { + + @Test + public void sessionWindowTransformationStaysNonKeyed() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createRowtimeTable(tEnv, Arrays.asList(row(1, 1, 100L), row(2, 2, 200L))); + Table result = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c," + + " SESSION_START(ts, INTERVAL '10' SECOND) AS ws," + + " SESSION_END(ts, INTERVAL '10' SECOND) AS we" + + " FROM T GROUP BY k, SESSION(ts, INTERVAL '10' SECOND)"); + DataStream<Row> changelog = tEnv.toChangelogStream(result); + OneInputTransformation<?, ?> windowAgg = findGroupWindowAgg(changelog.getTransformation()); + assertThat(windowAgg) + .as("the translated plan must contain the group-window-aggregate transformation") + .isNotNull(); + // A declared Flink state key selector would put the transformation into a + // keyed context the native keyed state backend does not share (the q11 + // "Key group not in KeyGroupRange" failure); the user key rides the + // plan's KeyedStateSpec and the upstream exchange instead. + assertThat(windowAgg.getStateKeySelector()).isNull(); + assertThat(windowAgg.getStateKeyType()).isNull(); + assertThat(windowAgg.getOperator()).isInstanceOf(GlutenWindowOneInputOperator.class); + } + + @Test + public void rowCountWindowFailsLoud() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createProctimeTable(tEnv, Arrays.asList(Row.of(1, 1))); + // A BIGINT window size means a row-count window (CountTumbling), out of + // scope for the velox group window aggregation - the same check Flink + // applies to route to the count-window operator family. Row-count + // windows reach the planner through the Table API (the SQL validator + // only accepts interval sizes); the check fires before the proctime + // face. + Table result = + tEnv.from("T") + .window(Tumble.over(lit(5L)).on($("pt")).as("w")) + .groupBy($("k"), $("w")) + .select($("k"), $("v").count()); + Throwable thrown = catchThrowable(() -> tEnv.toChangelogStream(result)); + Throwable root = rootCause(thrown); + assertThat(root) + .as("a row-count window must fail at translation, got: %s", thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("VELOX_UNSUPPORTED") + .hasMessageContaining("row-count"); + } + + @Test + public void earlyFireEmitFailsLoud() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createRowtimeTable(tEnv, Arrays.asList(row(1, 1, 100L))); + tEnv.getConfig().getConfiguration().setString("table.exec.emit.early-fire.enabled", "true"); + // A positive early-fire delay carries the plan past Flink's own emit + // validation (session windows and enabled-without-delay are rejected + // there earlier); a TUMBLE window with a valid strategy reaches the + // gluten rejection of non-default EMIT. + tEnv.getConfig().getConfiguration().setString("table.exec.emit.early-fire.delay", "1 s"); + Table result = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c FROM T GROUP BY k, TUMBLE(ts, INTERVAL '10' SECOND)"); + Throwable thrown = catchThrowable(() -> tEnv.toChangelogStream(result)); + Throwable root = rootCause(thrown); + assertThat(root) + .as("the early-fire EMIT strategy must fail at translation, got: %s", thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("VELOX_UNSUPPORTED") + .hasMessageContaining("early-fire"); + } + + @Test + public void allowLatenessFailsLoud() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createRowtimeTable(tEnv, Arrays.asList(row(1, 1, 100L))); + tEnv.getConfig().getConfiguration().setString("table.exec.emit.allow-lateness", "10 s"); + Table result = sessionQuery(tEnv); + Throwable thrown = catchThrowable(() -> tEnv.toChangelogStream(result)); + Throwable root = rootCause(thrown); + assertThat(root) + .as("non-zero allowed lateness must fail at translation, got: %s", thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("VELOX_UNSUPPORTED") + .hasMessageContaining("lateness"); + } + + @Test + public void proctimeWindowFailsLoud() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createProctimeTable(tEnv, Arrays.asList(Row.of(1, 1))); + Table result = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c FROM T GROUP BY k, SESSION(pt, INTERVAL '10' SECOND)"); + Throwable thrown = catchThrowable(() -> tEnv.toChangelogStream(result)); + Throwable root = rootCause(thrown); + assertThat(root) + .as("a processing-time window must fail at translation, got: %s", thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("VELOX_UNSUPPORTED") + .hasMessageContaining("rowtime"); + } + + @Test + public void tumbleAndHopWindowsPlanToVelox() { + assertGlutenOverrideIsUnderTest(); + StreamTableEnvironment tEnv = newTableEnv(); + createRowtimeTable(tEnv, Arrays.asList(row(1, 1, 100L))); + // TUMBLE and HOP plan through the gluten override to the velox window + // aggregation node now (the former next-phase fail-loud is lifted); the + // transformation must still be non-keyed (the KeyedStateSpec ironclad). + Table tumble = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c FROM T GROUP BY k, TUMBLE(ts, INTERVAL '10' SECOND)"); + Transformation<?> tumbleTransform = tEnv.toChangelogStream(tumble).getTransformation(); + assertThat(tumbleTransform).isNotNull(); + + Table hop = + tEnv.sqlQuery( + "SELECT k, COUNT(v) AS c FROM T" + + " GROUP BY k, HOP(ts, INTERVAL '10' SECOND, INTERVAL '5' SECOND)"); + Transformation<?> hopTransform = tEnv.toChangelogStream(hop).getTransformation(); + assertThat(hopTransform).isNotNull(); Review Comment: This only asserts the transformation is non-null, so it would pass with a wrong window type, gap, size or slide. Could it pull the `GroupWindowAggregationNode` from `operator.getPlanNode()` and assert `windowType`, `gap`, `size`, `slide` and the start/end indices for each window kind? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
