gustavodemorais commented on code in PR #29809:
URL: https://github.com/apache/flink/pull/29809#discussion_r4562262905


##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/snapshot/UpsertLateralSnapshotJoinOperator.java:
##########
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.operators.join.snapshot;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.runtime.generated.GeneratedJoinCondition;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.runtime.typeutils.RowDataSerializer;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.types.RowKind;
+import org.apache.flink.util.Preconditions;
+
+import javax.annotation.Nullable;
+
+/**
+ * {@link LateralSnapshotJoinOperator} that keys the committed build side by 
its upsert key.
+ *
+ * <p>For each keyed-state key (the join key) the latest full build row is 
held per upsert key in a
+ * {@link MapState} from the upsert-key projection to the row. Insertions and 
updates ({@code
+ * +I}/{@code +U}) overwrite the row for the key; deletes and update-befores 
({@code -D}/{@code
+ * -U}), including partial deletes that carry only the upsert-key columns, 
remove it by key. Unlike
+ * {@link MultiSetLateralSnapshotJoinOperator} this needs no full 
before-image, so an upsert
+ * changelog can feed the build side directly without a ChangelogNormalize.
+ */
+@Internal
+public class UpsertLateralSnapshotJoinOperator extends 
LateralSnapshotJoinOperator {
+
+    private static final long serialVersionUID = 1L;
+
+    @VisibleForTesting static final String BUILD_TABLE_STATE_NAME = 
"build-table-upsert";
+
+    /** Field indices of the build-side upsert key within the build row. */
+    private final int[] buildUpsertKeyIndices;
+
+    /** Committed build rows of the current key, keyed by their upsert-key 
projection. */
+    private transient MapState<RowData, RowData> buildTableByKey;
+
+    /** Field getters to project the upsert key out of a build row. */
+    private transient RowData.FieldGetter[] upsertKeyGetters;
+
+    /** Serializes the projected upsert key into a {@link RowData}. */
+    private transient RowDataSerializer upsertKeySerializer;
+
+    public UpsertLateralSnapshotJoinOperator(
+            boolean isLeftOuterJoin,
+            InternalTypeInfo<RowData> leftType,
+            InternalTypeInfo<RowData> rightType,
+            int buildRowtimeIndex,
+            GeneratedJoinCondition generatedJoinCondition,
+            boolean[] filterNullKeys,
+            long loadCompletedTime,
+            @Nullable Long loadCompletedIdleTimeoutMs,
+            @Nullable Long stateTtlMs,
+            int[] buildUpsertKeyIndices) {
+        super(
+                isLeftOuterJoin,
+                leftType,
+                rightType,
+                buildRowtimeIndex,
+                generatedJoinCondition,
+                filterNullKeys,
+                loadCompletedTime,
+                loadCompletedIdleTimeoutMs,
+                stateTtlMs);
+        Preconditions.checkNotNull(buildUpsertKeyIndices);
+        Preconditions.checkArgument(
+                buildUpsertKeyIndices.length > 0,
+                "buildUpsertKeyIndices must not be empty for the upsert 
build-side layout");
+        final int fieldCount = rightType.toRowType().getFieldCount();
+        for (int idx : buildUpsertKeyIndices) {
+            Preconditions.checkArgument(
+                    idx >= 0 && idx < fieldCount,
+                    "buildUpsertKeyIndices out of bounds for build row: %s",
+                    idx);
+        }
+        this.buildUpsertKeyIndices = buildUpsertKeyIndices;
+    }
+
+    @Override
+    protected void openBuildState() {
+        final RowType buildRow = getRightType().toRowType();
+        final LogicalType[] keyTypes = new 
LogicalType[buildUpsertKeyIndices.length];
+        upsertKeyGetters = new 
RowData.FieldGetter[buildUpsertKeyIndices.length];
+        for (int i = 0; i < buildUpsertKeyIndices.length; i++) {
+            final int idx = buildUpsertKeyIndices[i];
+            final LogicalType fieldType = buildRow.getTypeAt(idx);
+            keyTypes[i] = fieldType;
+            upsertKeyGetters[i] = RowData.createFieldGetter(fieldType, idx);
+        }
+        final InternalTypeInfo<RowData> upsertKeyType = 
InternalTypeInfo.ofFields(keyTypes);
+        upsertKeySerializer = upsertKeyType.toRowSerializer();
+        buildTableByKey =
+                getRuntimeContext()
+                        .getMapState(
+                                new MapStateDescriptor<>(
+                                        BUILD_TABLE_STATE_NAME, upsertKeyType, 
getRightType()));
+    }
+
+    @Override
+    protected void applyBuildChange(RowData change) throws Exception {
+        final RowKind changeType = change.getRowKind();
+        final RowData upsertKey = projectUpsertKey(change);
+        if (changeType == RowKind.INSERT || changeType == 
RowKind.UPDATE_AFTER) {
+            change.setRowKind(RowKind.INSERT);
+            buildTableByKey.put(upsertKey, change);
+        } else {
+            // DELETE / UPDATE_BEFORE, including partial deletes that carry 
only the upsert key.
+            if (!buildTableByKey.contains(upsertKey)) {

Review Comment:
   `contains` + `remove` costs two state accesses per delete just for the 
unmatched-retraction metric. The regular join does a blind 
[remove](https://github.com/apache/flink/blob/2e89b879f1e99612c92be845ec53c90efeb77b0d/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/state/JoinRecordStateViews.java#L149-L152).
 Is the metric worth the extra read on this path?



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/snapshot/LateralSnapshotJoinOperator.java:
##########
@@ -604,6 +609,22 @@ public void processElement2(StreamRecord<RowData> element) 
throws Exception {
         refreshStateTtl();
     }
 
+    /**
+     * Returns the row-time of a build change. A partial delete (delete by 
key) carries no row-time
+     * because it is not part of the key. It is ordered after the changes 
already buffered for the
+     * current key, i.e. in arrival order.
+     */
+    private long buildRowtimeOf(RowData build) throws Exception {

Review Comment:
   Row-time ordering is safe for the row -> count state because +1/-1 commute, 
but keyed overwrite doesn't. Changes for one upsert key arrive in order 
([upsert keys must be 
co-located](https://github.com/apache/flink/blob/2e89b879f1e99612c92be845ec53c90efeb77b0d/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/metadata/FlinkRelMdUpsertKeys.scala#L403-L407)),
 and sorting them by row-time reorders them (harness test, same key):
   
   | build changes | today (CN + row -> count) | this PR |
   |---|---|---|
   | `+I(v1, t=10)`, `+U(v2, t=5)` | v2 | v1 |
   | `+I(v1, 10)`, `-U(v1, 10)`, `+U(v2, 5)` | v2 | no row |
   | `+I(v1, 10)`, `-D(key only)`, `+I(v2, 8)` | v2 | no row |
   
   The class Javadoc says the gating is there to keep `-U`/`+U` pairs atomic, 
which an upsert-keyed build side doesn't need. Could this layout skip the 
row-time buffer and apply changes on arrival, like 
[ChangelogNormalize](https://github.com/apache/flink/blob/2e89b879f1e99612c92be845ec53c90efeb77b0d/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/deduplicate/utils/DeduplicateFunctionHelper.java#L104)
 and the [proc-time temporal 
join](https://github.com/apache/flink/blob/2e89b879f1e99612c92be845ec53c90efeb77b0d/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/temporal/TemporalProcessTimeJoinOperator.java#L124-L131)
 do? The flip can stay on the build watermark, and this method goes away.



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/snapshot/UpsertLateralSnapshotJoinOperator.java:
##########
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.operators.join.snapshot;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.runtime.generated.GeneratedJoinCondition;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.runtime.typeutils.RowDataSerializer;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.types.RowKind;
+import org.apache.flink.util.Preconditions;
+
+import javax.annotation.Nullable;
+
+/**
+ * {@link LateralSnapshotJoinOperator} that keys the committed build side by 
its upsert key.
+ *
+ * <p>For each keyed-state key (the join key) the latest full build row is 
held per upsert key in a
+ * {@link MapState} from the upsert-key projection to the row. Insertions and 
updates ({@code
+ * +I}/{@code +U}) overwrite the row for the key; deletes and update-befores 
({@code -D}/{@code
+ * -U}), including partial deletes that carry only the upsert-key columns, 
remove it by key. Unlike
+ * {@link MultiSetLateralSnapshotJoinOperator} this needs no full 
before-image, so an upsert
+ * changelog can feed the build side directly without a ChangelogNormalize.
+ */
+@Internal
+public class UpsertLateralSnapshotJoinOperator extends 
LateralSnapshotJoinOperator {
+
+    private static final long serialVersionUID = 1L;
+
+    @VisibleForTesting static final String BUILD_TABLE_STATE_NAME = 
"build-table-upsert";
+
+    /** Field indices of the build-side upsert key within the build row. */
+    private final int[] buildUpsertKeyIndices;
+
+    /** Committed build rows of the current key, keyed by their upsert-key 
projection. */
+    private transient MapState<RowData, RowData> buildTableByKey;

Review Comment:
   When upsert key = join key (the common case, e.g. `currency_rates` in the 
docs), this map holds a single entry, and on RocksDB every probe opens an 
iterator in `values()`. Could we use a `ValueState<RowData>` there, like the 
regular join's 
[JoinKeyContainsUniqueKey](https://github.com/apache/flink/blob/2e89b879f1e99612c92be845ec53c90efeb77b0d/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/state/JoinRecordStateViews.java#L72-L115)
 and the [proc-time temporal 
join](https://github.com/apache/flink/blob/2e89b879f1e99612c92be845ec53c90efeb77b0d/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/temporal/TemporalProcessTimeJoinOperator.java#L124-L131),
 and keep the map only for a strictly larger upsert key?



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/snapshot/UpsertLateralSnapshotJoinOperator.java:
##########
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.operators.join.snapshot;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.runtime.generated.GeneratedJoinCondition;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.runtime.typeutils.RowDataSerializer;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.types.RowKind;
+import org.apache.flink.util.Preconditions;
+
+import javax.annotation.Nullable;
+
+/**
+ * {@link LateralSnapshotJoinOperator} that keys the committed build side by 
its upsert key.
+ *
+ * <p>For each keyed-state key (the join key) the latest full build row is 
held per upsert key in a
+ * {@link MapState} from the upsert-key projection to the row. Insertions and 
updates ({@code
+ * +I}/{@code +U}) overwrite the row for the key; deletes and update-befores 
({@code -D}/{@code
+ * -U}), including partial deletes that carry only the upsert-key columns, 
remove it by key. Unlike
+ * {@link MultiSetLateralSnapshotJoinOperator} this needs no full 
before-image, so an upsert
+ * changelog can feed the build side directly without a ChangelogNormalize.
+ */
+@Internal
+public class UpsertLateralSnapshotJoinOperator extends 
LateralSnapshotJoinOperator {
+
+    private static final long serialVersionUID = 1L;
+
+    @VisibleForTesting static final String BUILD_TABLE_STATE_NAME = 
"build-table-upsert";
+
+    /** Field indices of the build-side upsert key within the build row. */
+    private final int[] buildUpsertKeyIndices;
+
+    /** Committed build rows of the current key, keyed by their upsert-key 
projection. */
+    private transient MapState<RowData, RowData> buildTableByKey;
+
+    /** Field getters to project the upsert key out of a build row. */
+    private transient RowData.FieldGetter[] upsertKeyGetters;
+
+    /** Serializes the projected upsert key into a {@link RowData}. */
+    private transient RowDataSerializer upsertKeySerializer;
+
+    public UpsertLateralSnapshotJoinOperator(
+            boolean isLeftOuterJoin,
+            InternalTypeInfo<RowData> leftType,
+            InternalTypeInfo<RowData> rightType,
+            int buildRowtimeIndex,
+            GeneratedJoinCondition generatedJoinCondition,
+            boolean[] filterNullKeys,
+            long loadCompletedTime,
+            @Nullable Long loadCompletedIdleTimeoutMs,
+            @Nullable Long stateTtlMs,
+            int[] buildUpsertKeyIndices) {
+        super(
+                isLeftOuterJoin,
+                leftType,
+                rightType,
+                buildRowtimeIndex,
+                generatedJoinCondition,
+                filterNullKeys,
+                loadCompletedTime,
+                loadCompletedIdleTimeoutMs,
+                stateTtlMs);
+        Preconditions.checkNotNull(buildUpsertKeyIndices);
+        Preconditions.checkArgument(
+                buildUpsertKeyIndices.length > 0,
+                "buildUpsertKeyIndices must not be empty for the upsert 
build-side layout");
+        final int fieldCount = rightType.toRowType().getFieldCount();
+        for (int idx : buildUpsertKeyIndices) {
+            Preconditions.checkArgument(
+                    idx >= 0 && idx < fieldCount,
+                    "buildUpsertKeyIndices out of bounds for build row: %s",
+                    idx);
+        }
+        this.buildUpsertKeyIndices = buildUpsertKeyIndices;
+    }
+
+    @Override
+    protected void openBuildState() {
+        final RowType buildRow = getRightType().toRowType();
+        final LogicalType[] keyTypes = new 
LogicalType[buildUpsertKeyIndices.length];
+        upsertKeyGetters = new 
RowData.FieldGetter[buildUpsertKeyIndices.length];
+        for (int i = 0; i < buildUpsertKeyIndices.length; i++) {
+            final int idx = buildUpsertKeyIndices[i];
+            final LogicalType fieldType = buildRow.getTypeAt(idx);
+            keyTypes[i] = fieldType;
+            upsertKeyGetters[i] = RowData.createFieldGetter(fieldType, idx);
+        }
+        final InternalTypeInfo<RowData> upsertKeyType = 
InternalTypeInfo.ofFields(keyTypes);
+        upsertKeySerializer = upsertKeyType.toRowSerializer();
+        buildTableByKey =
+                getRuntimeContext()
+                        .getMapState(
+                                new MapStateDescriptor<>(
+                                        BUILD_TABLE_STATE_NAME, upsertKeyType, 
getRightType()));
+    }
+
+    @Override
+    protected void applyBuildChange(RowData change) throws Exception {
+        final RowKind changeType = change.getRowKind();
+        final RowData upsertKey = projectUpsertKey(change);
+        if (changeType == RowKind.INSERT || changeType == 
RowKind.UPDATE_AFTER) {
+            change.setRowKind(RowKind.INSERT);
+            buildTableByKey.put(upsertKey, change);
+        } else {
+            // DELETE / UPDATE_BEFORE, including partial deletes that carry 
only the upsert key.
+            if (!buildTableByKey.contains(upsertKey)) {
+                incUnmatchedBuildRetractions();
+                return;
+            }
+            buildTableByKey.remove(upsertKey);
+        }
+    }
+
+    @Override
+    protected long joinBuildRows(RowData probe) throws Exception {
+        long fanOut = 0;
+        for (RowData buildRow : buildTableByKey.values()) {
+            if (joinMatches(probe, buildRow)) {
+                emitJoined(probe, buildRow);
+                fanOut++;
+            }
+        }
+        return fanOut;
+    }
+
+    @Override
+    protected void clearBuildTable() {
+        buildTableByKey.clear();
+    }
+
+    /**
+     * Projects the upsert key out of a (possibly partial) build row into a 
fresh {@code
+     * BinaryRowData}. A binary key keeps {@link MapState} lookups consistent 
across state backends
+     * and after restore, where heap keys deserialize to {@code BinaryRowData} 
and would not compare
+     * equal to a {@code GenericRowData} probe key.
+     */
+    private RowData projectUpsertKey(RowData row) {

Review Comment:
   This boxes each key field through `FieldGetter`, builds a `GenericRowData`, 
serializes it and copies it again for every build change. Could the ExecNode 
pass in a generated projection via `KeySelectorUtil.getRowDataSelector`, like 
the [regular 
join](https://github.com/apache/flink/blob/2e89b879f1e99612c92be845ec53c90efeb77b0d/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/utils/JoinUtil.scala#L186)
 and ChangelogNormalize do?



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/snapshot/LateralSnapshotJoinOperator.java:
##########
@@ -71,7 +71,23 @@
 import java.util.concurrent.ScheduledFuture;
 
 /**
- * Stream operator implementing the {@code LATERAL SNAPSHOT} processing-time 
temporal table join.
+ * Base stream operator implementing the {@code LATERAL SNAPSHOT} 
processing-time temporal table
+ * join. It owns the two-phase (LOAD then JOIN) state machine, the probe- and 
build-side buffering,
+ * the watermark handling, timers and metrics, and delegates how the committed 
build side is stored,
+ * updated and looked up to concrete subclasses through {@link 
#openBuildState()}, {@link
+ * #applyBuildChange(RowData)}, {@link #joinBuildRows(RowData)} and {@link 
#clearBuildTable()}.
+ *
+ * <p>Two build-side layouts exist: {@link 
MultiSetLateralSnapshotJoinOperator} keeps a row → count
+ * multi-set and matches retractions by full-row equality, while {@link
+ * UpsertLateralSnapshotJoinOperator} keys the build side by its upsert key so 
partial updates and
+ * deletes apply directly.
+ *
+ * <p>Note on naming: this abstract base keeps the concrete class name {@code

Review Comment:
   What do you think about composition instead, like `JoinRecordStateViews` / 
`MultiJoinStateViews`? A small build-state view chosen by a factory keeps this 
operator concrete, so the naming constraint goes away, and the `ValueState` 
variant doesn't need a third subclass.



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/snapshot/UpsertLateralSnapshotJoinOperator.java:
##########
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.operators.join.snapshot;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.runtime.generated.GeneratedJoinCondition;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.runtime.typeutils.RowDataSerializer;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.types.RowKind;
+import org.apache.flink.util.Preconditions;
+
+import javax.annotation.Nullable;
+
+/**
+ * {@link LateralSnapshotJoinOperator} that keys the committed build side by 
its upsert key.
+ *
+ * <p>For each keyed-state key (the join key) the latest full build row is 
held per upsert key in a
+ * {@link MapState} from the upsert-key projection to the row. Insertions and 
updates ({@code
+ * +I}/{@code +U}) overwrite the row for the key; deletes and update-befores 
({@code -D}/{@code
+ * -U}), including partial deletes that carry only the upsert-key columns, 
remove it by key. Unlike
+ * {@link MultiSetLateralSnapshotJoinOperator} this needs no full 
before-image, so an upsert
+ * changelog can feed the build side directly without a ChangelogNormalize.
+ */
+@Internal
+public class UpsertLateralSnapshotJoinOperator extends 
LateralSnapshotJoinOperator {
+
+    private static final long serialVersionUID = 1L;
+
+    @VisibleForTesting static final String BUILD_TABLE_STATE_NAME = 
"build-table-upsert";
+
+    /** Field indices of the build-side upsert key within the build row. */
+    private final int[] buildUpsertKeyIndices;
+
+    /** Committed build rows of the current key, keyed by their upsert-key 
projection. */
+    private transient MapState<RowData, RowData> buildTableByKey;
+
+    /** Field getters to project the upsert key out of a build row. */
+    private transient RowData.FieldGetter[] upsertKeyGetters;
+
+    /** Serializes the projected upsert key into a {@link RowData}. */
+    private transient RowDataSerializer upsertKeySerializer;
+
+    public UpsertLateralSnapshotJoinOperator(
+            boolean isLeftOuterJoin,
+            InternalTypeInfo<RowData> leftType,
+            InternalTypeInfo<RowData> rightType,
+            int buildRowtimeIndex,
+            GeneratedJoinCondition generatedJoinCondition,
+            boolean[] filterNullKeys,
+            long loadCompletedTime,
+            @Nullable Long loadCompletedIdleTimeoutMs,
+            @Nullable Long stateTtlMs,
+            int[] buildUpsertKeyIndices) {
+        super(
+                isLeftOuterJoin,
+                leftType,
+                rightType,
+                buildRowtimeIndex,
+                generatedJoinCondition,
+                filterNullKeys,
+                loadCompletedTime,
+                loadCompletedIdleTimeoutMs,
+                stateTtlMs);
+        Preconditions.checkNotNull(buildUpsertKeyIndices);
+        Preconditions.checkArgument(
+                buildUpsertKeyIndices.length > 0,
+                "buildUpsertKeyIndices must not be empty for the upsert 
build-side layout");
+        final int fieldCount = rightType.toRowType().getFieldCount();
+        for (int idx : buildUpsertKeyIndices) {
+            Preconditions.checkArgument(
+                    idx >= 0 && idx < fieldCount,
+                    "buildUpsertKeyIndices out of bounds for build row: %s",
+                    idx);
+        }
+        this.buildUpsertKeyIndices = buildUpsertKeyIndices;
+    }
+
+    @Override
+    protected void openBuildState() {
+        final RowType buildRow = getRightType().toRowType();
+        final LogicalType[] keyTypes = new 
LogicalType[buildUpsertKeyIndices.length];
+        upsertKeyGetters = new 
RowData.FieldGetter[buildUpsertKeyIndices.length];
+        for (int i = 0; i < buildUpsertKeyIndices.length; i++) {
+            final int idx = buildUpsertKeyIndices[i];
+            final LogicalType fieldType = buildRow.getTypeAt(idx);
+            keyTypes[i] = fieldType;
+            upsertKeyGetters[i] = RowData.createFieldGetter(fieldType, idx);
+        }
+        final InternalTypeInfo<RowData> upsertKeyType = 
InternalTypeInfo.ofFields(keyTypes);
+        upsertKeySerializer = upsertKeyType.toRowSerializer();
+        buildTableByKey =
+                getRuntimeContext()
+                        .getMapState(
+                                new MapStateDescriptor<>(
+                                        BUILD_TABLE_STATE_NAME, upsertKeyType, 
getRightType()));
+    }
+
+    @Override
+    protected void applyBuildChange(RowData change) throws Exception {
+        final RowKind changeType = change.getRowKind();
+        final RowData upsertKey = projectUpsertKey(change);
+        if (changeType == RowKind.INSERT || changeType == 
RowKind.UPDATE_AFTER) {
+            change.setRowKind(RowKind.INSERT);
+            buildTableByKey.put(upsertKey, change);
+        } else {
+            // DELETE / UPDATE_BEFORE, including partial deletes that carry 
only the upsert key.

Review Comment:
   Since the upsert key contains the join key, a `-U` is always followed by its 
`+U` in the same partition, so we can drop it here, the same reasoning the 
regular join uses to ignore UPDATE_BEFORE 
([StreamPhysicalJoin](https://github.com/apache/flink/blob/2e89b879f1e99612c92be845ec53c90efeb77b0d/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalJoin.scala#L56-L66)).
 That also covers the fallback when the input still sends `-U`.



##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalLateralSnapshotJoin.java:
##########
@@ -57,6 +62,9 @@ public class StreamPhysicalLateralSnapshotJoin extends 
CommonPhysicalJoin
     private final @Nullable Long loadCompletedIdleTimeoutMs;
     private final @Nullable Long stateTtlMs;
 
+    /** Resolved on first use and handed to copies, so all planner phases 
agree on the layout. */
+    private @Nullable Optional<int[]> buildUpsertKey;

Review Comment:
   Why does this need caching across copies? 
`StreamPhysicalJoin.inputUniqueKeyContainsJoinKey` recomputes it from metadata 
each time. If the upsert key can change between phases, I'd like to understand 
that case; otherwise a plain method avoids the tri-state `@Nullable Optional`.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to