JingsongLi commented on code in PR #10109:
URL: https://github.com/apache/paimon/pull/10109#discussion_r4662154892


##########
docs/docs/flink/savepoint.md:
##########
@@ -84,3 +85,92 @@ chosen recovery point before executing it. Coordinate this 
for each Paimon table
 
 [Resume the job from the matching 
savepoint](https://nightlies.apache.org/flink/flink-docs-stable/docs/ops/state/savepoints/#resuming-from-savepoints).
 Verify that checkpoints complete and new Paimon snapshots appear before 
resuming dependent work.
+
+## Operator UIDs
+
+Flink maps checkpoint state to operators by id. An operator without a UID gets 
an id from its
+place in the job graph, so adding an operator upstream, or a parallelism 
change that alters
+chaining, gives it a new id and orphans its state.
+
+A Paimon source or sink is several operators. The suffix options name some of 
them; the cover
+options name the rest:
+
+| Option | Operators named |
+| --- | --- |
+| `sink.operator-uid.suffix` | Writer, Global Committer, 
dynamic-bucket-assigner |
+| `sink.operator-uid.cover-table-sink-operators` | Also the row conversions, 
`local merge`, the compaction operators, `Collect Statistics` and `Strip 
Statistics`, `INDEX_BOOTSTRAP` and `cross-partition-bucket-assigner`, and the 
final `end` sink |
+| `source.operator-uid.suffix` | The source |
+| `source.operator-uid.cover-table-source-operators` | Also the split monitor 
and reader used by dedicated split generation and exactly-once consumers, the 
watermark assigner, the DataStream row conversion, and the operators of the 
postpone merge-on-read route |
+
+Each UID is `<operator>_<table name>_<suffix>`. The table name leaves out the 
database, so two
+tables with the same name and suffix in one job collide, and Flink rejects the 
job with
+`Hash collision on user-specified ID`. Give each table its own suffix.
+
+The cover options do nothing without the matching suffix. Set the sink pair 
before the first
+streaming job writes the table, and the source pair before the first streaming 
job reads it:
+
+```sql
+ALTER TABLE my_table SET (
+    'sink.operator-uid.suffix' = 'my_table_v1',
+    'sink.operator-uid.cover-table-sink-operators' = 'true',
+    'source.operator-uid.suffix' = 'my_table_v1',
+    'source.operator-uid.cover-table-source-operators' = 'true'
+);
+```
+
+Not covered:
+
+- The CDC sync actions: the operators they add around the table sink, such as 
Side Output,
+  Schema Evolution and Case-insensitive Convert, and the shared operators of a 
database sync.
+  Such jobs cannot run with `pipeline.auto-generate-uids=false`.
+- Operators only a `BATCH` job builds, such as sort and clustering. Flink does 
not checkpoint in
+  `BATCH` mode. A bounded job in `STREAMING` mode is covered.
+
+### Migrate a running job
+
+Turning on a cover option gives the newly covered operators new ids, so their 
entries in the
+job's checkpoints become unclaimed. A restore from a savepoint or from
+`execution.state-recovery.path` skips an unclaimed entry that holds no state 
and rejects one
+that does. A restore from the high-availability checkpoint store, as in a 
JobManager failover or
+a Kubernetes Operator `last-state` upgrade, rejects every unclaimed entry, and 
neither
+`allowNonRestoredState` nor `execution.state-recovery.ignore-unclaimed-state` 
helps:
+
+```
+JobInitializationException: Could not start the JobMaster.
+Caused by: IllegalStateException: There is no operator for the state <operator 
id>
+```
+
+So migrate through a savepoint:
+
+1. **Stop the job** with
+   
[stop-with-savepoint](https://nightlies.apache.org/flink/flink-docs-stable/docs/ops/state/savepoints/#stopping-a-job-with-savepoint)
+   (`flink stop`) and wait for it to finish.
+
+2. **Set the options** with `ALTER TABLE ... SET` or SQL hints. Keep the 
existing suffix:
+   changing it renames the Writer and Global Committer too, and loses their 
state.
+3. **Restart from the savepoint** with the same topology. The operators the 
sink options newly
+   cover hold no state, so Flink skips their entries without 
`allowNonRestoredState` and logs
+   `Skipping empty savepoint state for operator` once per operator. Check that 
the snapshot ids
+   in `<table>$snapshots` continue past the one the job stopped at, under the 
same `commit_user`.
+
+   Two cases drop an entry that holds state. Without `allowNonRestoredState` 
the restore fails
+   with `Cannot map checkpoint/savepoint state for operator <id>`, so submit 
this one restart

Review Comment:
   **[P1] Check downstream state mappings before allowing unclaimed state**
   
   Enabling source coverage changes the Monitor and Reader hashes. Flink 
includes upstream hashes in the OperatorIDs it generates for downstream 
operators without explicit UIDs, so `allowNonRestoredState` can drop a 
downstream aggregate's state even when the suffix and SQL topology are 
identical. [Flink hash 
calculation](https://github.com/apache/flink/blob/release-1.20.1/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphHasherV2.java#L216-L232)
   
   **Reproduction on Flink 1.20.1**
   
   1. In a fresh Paimon catalog, create the source and a print sink. Use a 
streaming session at parallelism 1, a 500 ms checkpoint interval, and the 
default `table.exec.uid.generation=PLAN_ONLY`. The consumer uses the default 
exactly-once mode.
   
      ```sql
      CREATE TABLE src (k INT) WITH (
          'source.operator-uid.suffix' = 'preexisting',
          'consumer-id' = 'c',
          'consumer.expiration-time' = '1 d'
      );
      CREATE TEMPORARY TABLE outp (k INT, n BIGINT) WITH ('connector' = 
'print');
      ```
   
   2. Commit three rows with `k = 1` in one batch. Run the aggregation with 
source coverage unset.
   
      ```sql
      INSERT INTO outp SELECT k, COUNT(*) FROM src GROUP BY k;
      ```
   
   3. Wait for count `3` and consumer `next_snapshot_id = 2`. Stop the job with 
`flink stop` without `--drain` and wait for the savepoint. Commit two more rows 
with `k = 1` in one batch.
   
   4. In a new streaming session with the same catalog and print sink, restore 
from the savepoint using the option and restore flag in the guide.
   
      ```sql
      SET 'execution.state-recovery.path' = '<savepoint-path>';
      SET 'execution.state-recovery.ignore-unclaimed-state' = 'true';
      INSERT INTO outp
      SELECT k, COUNT(*)
      FROM src /*+ OPTIONS('source.operator-uid.cover-table-source-operators' = 
'true') */
      GROUP BY k;
      ```
   
   The restored job stayed `RUNNING` and the consumer advanced to 
`next_snapshot_id = 3`. The print sink emitted `+I[1, 1]` and then `+U[1, 2]`. 
The expected cumulative count was `5`. In the control run with coverage off and 
strict savepoint restore, the aggregate retained its state and emitted `+U[1, 
5]`.
   
   Please require a comparison of the savepoint's state entries against the new 
job graph before `allowNonRestoredState` is used. Proceed only when every 
unmatched state entry is expected and safe to discard. If a downstream stateful 
operator loses its mapping, preserve its original OperatorID before migrating 
or keep coverage off. The documented migration should also explicitly require a 
pre-existing suffix.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java:
##########
@@ -379,28 +383,33 @@ public static DataStream<RowData> buildSource(
         if (table != null) {
             source = new PaimonDataStreamSource<>(monitorSource, table);
         }
+        OperatorUidAssigner uids = OperatorUidAssigner.forSource(table);
         SingleOutputStreamOperator<Split> operator =
-                env.fromSource(
-                                source,
-                                WatermarkStrategy.noWatermarks(),
-                                name + "-Monitor",
-                                new JavaTypeInfo<>(Split.class))
-                        .forceNonParallel();
+                uids.assign(
+                        env.fromSource(
+                                        source,
+                                        WatermarkStrategy.noWatermarks(),
+                                        name + "-Monitor",
+                                        new JavaTypeInfo<>(Split.class))
+                                .forceNonParallel(),
+                        MONITOR_NAME);
 
         DataStream<Split> sourceDataStream =
                 unordered
                         ? shuffleUnordered(operator)
                         : shuffleOrdered(operator, shuffleBucketWithPartition);
 
-        return sourceDataStream.transform(
-                name + "-Reader",
-                typeInfo,
-                new ReadOperator(
-                        readBuilder::newRead,
-                        nestedProjectedRowData,
-                        limit,
-                        readType,
-                        blobAsDescriptor));
+        return uids.assign(

Review Comment:
   **[P2] Account for the Flink SQL planner overwriting the Reader UID**
   
   On Flink 1.20.1, an exactly-once SQL source with a suffix and source 
coverage enabled gives the Reader its Paimon UID in an ad hoc query under 
`PLAN_ONLY`. Under `table.exec.uid.generation=ALWAYS`, the planner overwrites 
that UID on the transformation returned by `DataStreamScanProvider`. Adding an 
unrelated `INSERT` ahead of the original one in the same statement set changed 
the Reader UID from `1_source` to `3_source` and changed its OperatorID. The 
Monitor ID stayed stable. The unmatched Reader entry can still block HA 
checkpoint recovery. [Scan 
translation](https://github.com/apache/flink/blob/release-1.20.1/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecTableSourceScan.java#L160-L166)
 ยท [UID 
override](https://github.com/apache/flink/blob/release-1.20.1/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/TransformationMetadata.java#L60-L66)
   
   Please add a SQL source graph test for this route and either preserve the 
Paimon UID or scope the coverage guarantee to account for planner-managed UIDs.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkConnectorOptions.java:
##########
@@ -481,18 +486,64 @@ public class FlinkConnectorOptions {
                     .stringType()
                     .noDefaultValue()
                     .withDescription(
-                            "Set the uid suffix for the source operators. 
After setting, the uid format is "
-                                    + 
"${UID_PREFIX}_${TABLE_NAME}_${USER_UID_SUFFIX}. If the uid suffix is not set, 
flink will "
-                                    + "automatically generate the operator 
uid, which may be incompatible when the topology changes.");
+                            Description.builder()
+                                    .text(
+                                            "Set the uid suffix for the source 
operators. The uid format is "
+                                                    + 
"${UID_PREFIX}_${TABLE_NAME}_${USER_UID_SUFFIX}. Without a suffix Flink "
+                                                    + "generates these ids 
from the shape of the stream graph, so a topology "
+                                                    + "change can orphan their 
state. The suffix alone does not prevent that: "
+                                                    + "the other operators the 
table source adds keep generated ids, and a "
+                                                    + "recovery from the HA 
checkpoint store fails when one of them moves. "
+                                                    + "For stable ids also set 
'source.operator-uid.cover-table-source-operators'; existing jobs must follow 
the %s first.",
+                                            link(OPERATOR_UID_GUIDE, 
"migration steps"))
+                                    .build());
+
+    public static final ConfigOption<Boolean> 
SOURCE_OPERATOR_UID_COVER_TABLE_SOURCE_OPERATORS =
+            key("source.operator-uid.cover-table-source-operators")
+                    .booleanType()
+                    .defaultValue(false)
+                    .withDescription(
+                            Description.builder()
+                                    .text(
+                                            "If true, 
'source.operator-uid.suffix' also names every other operator the table source 
adds in a streaming job: the split monitor, the split reader, the watermark 
assigner and the DataStream row conversion. "
+                                                    + "Without it those 
operators get ids generated from the shape of the "
+                                                    + "stream graph, so a 
change elsewhere in the job orphans their checkpoint "
+                                                    + "state. Has no effect 
unless 'source.operator-uid.suffix' is set. Enabling it on an existing "
+                                                    + "job changes those ids 
at the next restore; follow the %s first.",
+                                            link(OPERATOR_UID_GUIDE, 
"migration steps"))
+                                    .build());
 
     public static final ConfigOption<String> SINK_OPERATOR_UID_SUFFIX =
             key("sink.operator-uid.suffix")
                     .stringType()
                     .noDefaultValue()
                     .withDescription(
-                            "Set the uid suffix for the writer, dynamic bucket 
assigner and committer operators. The uid format is "
-                                    + 
"${UID_PREFIX}_${TABLE_NAME}_${USER_UID_SUFFIX}. If the uid suffix is not set, 
flink will "
-                                    + "automatically generate the operator 
uid, which may be incompatible when the topology changes.");
+                            Description.builder()
+                                    .text(
+                                            "Set the uid suffix for the 
writer, dynamic bucket assigner and committer operators. The uid format is "
+                                                    + 
"${UID_PREFIX}_${TABLE_NAME}_${USER_UID_SUFFIX}. Without a suffix Flink "
+                                                    + "generates these ids 
from the shape of the stream graph, so a topology "
+                                                    + "change can orphan their 
state. The suffix alone does not prevent that: "
+                                                    + "the other operators the 
table sink adds keep generated ids, and a "
+                                                    + "recovery from the HA 
checkpoint store fails when one of them moves. "
+                                                    + "For stable ids also set 
'sink.operator-uid.cover-table-sink-operators'; existing jobs must follow the 
%s first.",
+                                            link(OPERATOR_UID_GUIDE, 
"migration steps"))
+                                    .build());
+
+    public static final ConfigOption<Boolean> 
SINK_OPERATOR_UID_COVER_TABLE_SINK_OPERATORS =
+            key("sink.operator-uid.cover-table-sink-operators")
+                    .booleanType()
+                    .defaultValue(false)
+                    .withDescription(
+                            Description.builder()
+                                    .text(
+                                            "If true, 
'sink.operator-uid.suffix' also names every other operator the table sink adds 
in a streaming job: the row conversions, the local merge, the compaction 
operators, the partition statistics operators, the index bootstrap and the 
final sink. Operators the CDC sync actions add before the table sink are not 
covered. "

Review Comment:
   **[P2] Assign a UID to the stored generated-column operator**
   
   On Flink 1.20.1, I created a Paimon table with a stored generated column 
`label = UPPER(name)` and enabled both sink UID options. A streaming `INSERT 
INTO events (id, name) VALUES (1, 'hello')` adds `Paimon generated columns` 
with a null UID. With `pipeline.auto-generate-uids=false` and explicit UIDs on 
the planner's Values and Calc, Flink rejects the graph at `Paimon generated 
columns`. Assigning a UID to that map alone makes the graph build. 
[Generated-column 
map](https://github.com/apache/paimon/blob/f17ee8e7e1d64ec678f9db1586e45daa8e6b4957/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSinkBase.java#L155-L170)
   
   Please use the same opt-in assigner for that map and add a streaming SQL 
test with an explicit target column list that omits the generated column.



-- 
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