You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2020/05/05 18:14:33 UTC

[GitHub] [flink] rkhachatryan opened a new pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

rkhachatryan opened a new pull request #12000:
URL: https://github.com/apache/flink/pull/12000


   ## What is the purpose of the change
   
   *Test recovery from snapshot created in different UC mode (i.e. unaligned checkpoints enabled/disabled) (`ITCase`)*
   
   ## Verifying this change
   
   This change is a test addition itself without any test coverage.
   
   ## Does this pull request potentially affect one of the following parts:
   
     - Dependencies (does it add or upgrade a dependency): no
     - The public API, i.e., is any changed class annotated with `@Public(Evolving)`: no
     - The serializers: no
     - The runtime per-record code paths (performance sensitive): no
     - Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn/Mesos, ZooKeeper: no
     - The S3 file system connector: no
   
   ## Documentation
   
     - Does this pull request introduce a new feature? no
     - If yes, how is the feature documented? not applicable
   


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rkhachatryan commented on a change in pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #12000:
URL: https://github.com/apache/flink/pull/12000#discussion_r422905043



##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/utils/CancellingIntegerSource.java
##########
@@ -0,0 +1,127 @@
+/*
+ * 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.test.checkpointing.utils;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.CheckpointListener;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+
+import static java.util.Collections.singletonList;
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Integer source that cancels itself after a specified number emitted and subsequent checkpoint is fully completed.
+ */
+public class CancellingIntegerSource extends RichSourceFunction<Integer> implements CheckpointedFunction, CheckpointListener {
+
+	private final int count;
+	private final Integer cancelAfter;
+
+	@Nullable private transient Long cancelAfterCheckpointId;
+	private transient volatile boolean isCanceled;
+	private transient volatile int sentCount;
+	private transient ListState<Integer> lastSentStored;
+
+	private CancellingIntegerSource(int count, @Nullable Integer cancelAfter) {
+		checkArgument(count > 0);
+		checkArgument(cancelAfter == null || cancelAfter > 0);
+		this.cancelAfter = cancelAfter;
+		this.count = count;
+	}
+
+	@Override
+	public void run(SourceContext<Integer> ctx) throws InterruptedException {
+		emitInLoop(ctx);
+		awaitCancellation();
+	}
+
+	private void emitInLoop(SourceContext<Integer> ctx) throws InterruptedException {
+		while (sentCount < count && !isCanceled) {
+			synchronized (ctx.getCheckpointLock()) {
+				if (sentCount < count && !isCanceled) {
+					ctx.collect(sentCount++);
+				}
+			}
+			Thread.sleep(10); // allow to snapshot state (Thread.yield() doesn't always work)
+		}
+	}
+
+	private void awaitCancellation() {
+		while (!isCanceled) {
+			try {
+				Thread.sleep(50);
+			} catch (InterruptedException e) {
+				if (isCanceled) {
+					Thread.currentThread().interrupt();
+				}
+			}
+		}
+	}
+
+	@Override
+	public void initializeState(FunctionInitializationContext context) throws Exception {
+		lastSentStored = context.getOperatorStateStore().getListState(new ListStateDescriptor<>("counter", Integer.class));
+		if (context.isRestored()) {
+			Iterator<Integer> iterator = lastSentStored.get().iterator();
+			checkState(iterator.hasNext());
+			sentCount = iterator.next();
+			checkState(!iterator.hasNext());
+		}
+		checkState(cancelAfter == null || sentCount < cancelAfter);
+	}
+
+	@Override
+	public void open(Configuration parameters) throws Exception {
+		super.open(parameters);
+	}
+
+	@Override
+	public void snapshotState(FunctionSnapshotContext context) throws Exception {
+		lastSentStored.update(singletonList(sentCount));
+		if (cancelAfter != null && cancelAfter <= sentCount && cancelAfterCheckpointId == null) {
+			cancelAfterCheckpointId = context.getCheckpointId();
+		}
+	}
+
+	@Override
+	public void notifyCheckpointComplete(long checkpointId) {
+		if (cancelAfterCheckpointId != null && cancelAfterCheckpointId == checkpointId) {
+			cancel();
+		}
+	}
+
+	@Override
+	public void cancel() {
+		isCanceled = true;
+	}
+
+	public static CancellingIntegerSource upTo(int count, boolean continueAfterCount) {

Review comment:
       Changed to `max`.




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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rkhachatryan commented on a change in pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #12000:
URL: https://github.com/apache/flink/pull/12000#discussion_r422904179



##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/utils/CancellingIntegerSource.java
##########
@@ -0,0 +1,127 @@
+/*
+ * 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.test.checkpointing.utils;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.CheckpointListener;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+
+import static java.util.Collections.singletonList;
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Integer source that cancels itself after a specified number emitted and subsequent checkpoint is fully completed.
+ */
+public class CancellingIntegerSource extends RichSourceFunction<Integer> implements CheckpointedFunction, CheckpointListener {
+
+	private final int count;
+	private final Integer cancelAfter;
+
+	@Nullable private transient Long cancelAfterCheckpointId;
+	private transient volatile boolean isCanceled;
+	private transient volatile int sentCount;
+	private transient ListState<Integer> lastSentStored;
+
+	private CancellingIntegerSource(int count, @Nullable Integer cancelAfter) {
+		checkArgument(count > 0);
+		checkArgument(cancelAfter == null || cancelAfter > 0);
+		this.cancelAfter = cancelAfter;
+		this.count = count;
+	}
+
+	@Override
+	public void run(SourceContext<Integer> ctx) throws InterruptedException {
+		emitInLoop(ctx);
+		awaitCancellation();
+	}
+
+	private void emitInLoop(SourceContext<Integer> ctx) throws InterruptedException {
+		while (sentCount < count && !isCanceled) {
+			synchronized (ctx.getCheckpointLock()) {
+				if (sentCount < count && !isCanceled) {
+					ctx.collect(sentCount++);
+				}
+			}
+			Thread.sleep(10); // allow to snapshot state (Thread.yield() doesn't always work)
+		}
+	}
+
+	private void awaitCancellation() {
+		while (!isCanceled) {
+			try {
+				Thread.sleep(50);
+			} catch (InterruptedException e) {
+				if (isCanceled) {
+					Thread.currentThread().interrupt();
+				}
+			}
+		}
+	}
+
+	@Override
+	public void initializeState(FunctionInitializationContext context) throws Exception {
+		lastSentStored = context.getOperatorStateStore().getListState(new ListStateDescriptor<>("counter", Integer.class));
+		if (context.isRestored()) {
+			Iterator<Integer> iterator = lastSentStored.get().iterator();
+			checkState(iterator.hasNext());
+			sentCount = iterator.next();
+			checkState(!iterator.hasNext());
+		}
+		checkState(cancelAfter == null || sentCount < cancelAfter);
+	}
+
+	@Override
+	public void open(Configuration parameters) throws Exception {
+		super.open(parameters);
+	}
+
+	@Override
+	public void snapshotState(FunctionSnapshotContext context) throws Exception {
+		lastSentStored.update(singletonList(sentCount));
+		if (cancelAfter != null && cancelAfter <= sentCount && cancelAfterCheckpointId == null) {
+			cancelAfterCheckpointId = context.getCheckpointId();
+		}
+	}
+
+	@Override
+	public void notifyCheckpointComplete(long checkpointId) {
+		if (cancelAfterCheckpointId != null && cancelAfterCheckpointId == checkpointId) {

Review comment:
       You're right, changing to `<=`.




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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624234586


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640",
       "triggerID" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "triggerType" : "PUSH"
     }, {
       "hash" : "9d21fe810a520f20461a070f8925ba388bd73808",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "9d21fe810a520f20461a070f8925ba388bd73808",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 1eb638dded0a0234b396bb9a84a29c8f447d0bd7 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640) 
   * 9d21fe810a520f20461a070f8925ba388bd73808 UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot commented on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624223359


   Thanks a lot for your contribution to the Apache Flink project. I'm the @flinkbot. I help the community
   to review your pull request. We will use this comment to track the progress of the review.
   
   
   ## Automated Checks
   Last check on commit 1eb638dded0a0234b396bb9a84a29c8f447d0bd7 (Tue May 05 18:18:08 UTC 2020)
   
   **Warnings:**
    * No documentation files were touched! Remember to keep the Flink docs up to date!
   
   
   <sub>Mention the bot in a comment to re-run the automated checks.</sub>
   ## Review Progress
   
   * ❓ 1. The [description] looks good.
   * ❓ 2. There is [consensus] that the contribution should go into to Flink.
   * ❓ 3. Needs [attention] from.
   * ❓ 4. The change fits into the overall [architecture].
   * ❓ 5. Overall code [quality] is good.
   
   Please see the [Pull Request Review Guide](https://flink.apache.org/contributing/reviewing-prs.html) for a full explanation of the review process.<details>
    The Bot is tracking the review progress through labels. Labels are applied according to the order of the review items. For consensus, approval by a Flink committer of PMC member is required <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot approve description` to approve one or more aspects (aspects: `description`, `consensus`, `architecture` and `quality`)
    - `@flinkbot approve all` to approve all aspects
    - `@flinkbot approve-until architecture` to approve everything until `architecture`
    - `@flinkbot attention @username1 [@username2 ..]` to require somebody's attention
    - `@flinkbot disapprove architecture` to remove an approval you gave earlier
   </details>


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624234586


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640",
       "triggerID" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "triggerType" : "PUSH"
     }, {
       "hash" : "9d21fe810a520f20461a070f8925ba388bd73808",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=973",
       "triggerID" : "9d21fe810a520f20461a070f8925ba388bd73808",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 9d21fe810a520f20461a070f8925ba388bd73808 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=973) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rkhachatryan commented on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-626592715


   Thanks for the feedback @AHeise .
   I've addressed the issues, please check out the `fixup` commit.


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] AHeise commented on a change in pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #12000:
URL: https://github.com/apache/flink/pull/12000#discussion_r421712906



##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/utils/CancellingIntegerSource.java
##########
@@ -0,0 +1,127 @@
+/*
+ * 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.test.checkpointing.utils;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.CheckpointListener;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+
+import static java.util.Collections.singletonList;
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Integer source that cancels itself after a specified number emitted and subsequent checkpoint is fully completed.
+ */
+public class CancellingIntegerSource extends RichSourceFunction<Integer> implements CheckpointedFunction, CheckpointListener {
+
+	private final int count;
+	private final Integer cancelAfter;
+
+	@Nullable private transient Long cancelAfterCheckpointId;
+	private transient volatile boolean isCanceled;
+	private transient volatile int sentCount;
+	private transient ListState<Integer> lastSentStored;
+
+	private CancellingIntegerSource(int count, @Nullable Integer cancelAfter) {
+		checkArgument(count > 0);
+		checkArgument(cancelAfter == null || cancelAfter > 0);
+		this.cancelAfter = cancelAfter;
+		this.count = count;
+	}
+
+	@Override
+	public void run(SourceContext<Integer> ctx) throws InterruptedException {
+		emitInLoop(ctx);
+		awaitCancellation();
+	}
+
+	private void emitInLoop(SourceContext<Integer> ctx) throws InterruptedException {
+		while (sentCount < count && !isCanceled) {
+			synchronized (ctx.getCheckpointLock()) {
+				if (sentCount < count && !isCanceled) {
+					ctx.collect(sentCount++);
+				}
+			}
+			Thread.sleep(10); // allow to snapshot state (Thread.yield() doesn't always work)
+		}
+	}
+
+	private void awaitCancellation() {
+		while (!isCanceled) {
+			try {
+				Thread.sleep(50);
+			} catch (InterruptedException e) {
+				if (isCanceled) {
+					Thread.currentThread().interrupt();
+				}
+			}
+		}
+	}
+
+	@Override
+	public void initializeState(FunctionInitializationContext context) throws Exception {
+		lastSentStored = context.getOperatorStateStore().getListState(new ListStateDescriptor<>("counter", Integer.class));
+		if (context.isRestored()) {
+			Iterator<Integer> iterator = lastSentStored.get().iterator();
+			checkState(iterator.hasNext());
+			sentCount = iterator.next();
+			checkState(!iterator.hasNext());

Review comment:
       Guava's `Iterables.getOnlyElement` might be more crisp.

##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/SnapshotCompatibilityITCase.java
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.test.checkpointing;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.execution.JobClient;
+import org.apache.flink.runtime.checkpoint.CheckpointType;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.graph.StreamGraph;
+import org.apache.flink.test.checkpointing.utils.AccumulatingIntegerSink;
+import org.apache.flink.test.checkpointing.utils.CancellingIntegerSource;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static java.util.Collections.emptyMap;
+import static org.apache.flink.configuration.CheckpointingOptions.CHECKPOINTS_DIRECTORY;
+import static org.apache.flink.configuration.CheckpointingOptions.MAX_RETAINED_CHECKPOINTS;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.CHECKPOINT;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.SAVEPOINT;
+import static org.apache.flink.runtime.jobgraph.SavepointConfigOptions.SAVEPOINT_PATH;
+import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
+import static org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.createLocalEnvironment;
+import static org.apache.flink.util.Preconditions.checkState;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests recovery from a snapshot created in different UC mode (i.e. unaligned checkpoints enabled/disabled).
+ */
+@RunWith(Parameterized.class)
+public class SnapshotCompatibilityITCase {

Review comment:
       Snapshot compatibility is rather used for state migration. Can we add `Unaligned` to the name? `UnAlignedCheckpointCompatibilityITCase`?

##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/utils/CancellingIntegerSource.java
##########
@@ -0,0 +1,127 @@
+/*
+ * 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.test.checkpointing.utils;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.CheckpointListener;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+
+import static java.util.Collections.singletonList;
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Integer source that cancels itself after a specified number emitted and subsequent checkpoint is fully completed.
+ */
+public class CancellingIntegerSource extends RichSourceFunction<Integer> implements CheckpointedFunction, CheckpointListener {
+
+	private final int count;
+	private final Integer cancelAfter;
+
+	@Nullable private transient Long cancelAfterCheckpointId;
+	private transient volatile boolean isCanceled;
+	private transient volatile int sentCount;
+	private transient ListState<Integer> lastSentStored;
+
+	private CancellingIntegerSource(int count, @Nullable Integer cancelAfter) {
+		checkArgument(count > 0);
+		checkArgument(cancelAfter == null || cancelAfter > 0);
+		this.cancelAfter = cancelAfter;
+		this.count = count;
+	}
+
+	@Override
+	public void run(SourceContext<Integer> ctx) throws InterruptedException {
+		emitInLoop(ctx);
+		awaitCancellation();
+	}
+
+	private void emitInLoop(SourceContext<Integer> ctx) throws InterruptedException {
+		while (sentCount < count && !isCanceled) {
+			synchronized (ctx.getCheckpointLock()) {
+				if (sentCount < count && !isCanceled) {
+					ctx.collect(sentCount++);
+				}
+			}
+			Thread.sleep(10); // allow to snapshot state (Thread.yield() doesn't always work)
+		}
+	}
+
+	private void awaitCancellation() {
+		while (!isCanceled) {
+			try {
+				Thread.sleep(50);
+			} catch (InterruptedException e) {
+				if (isCanceled) {
+					Thread.currentThread().interrupt();
+				}
+			}
+		}
+	}
+
+	@Override
+	public void initializeState(FunctionInitializationContext context) throws Exception {
+		lastSentStored = context.getOperatorStateStore().getListState(new ListStateDescriptor<>("counter", Integer.class));
+		if (context.isRestored()) {
+			Iterator<Integer> iterator = lastSentStored.get().iterator();
+			checkState(iterator.hasNext());
+			sentCount = iterator.next();
+			checkState(!iterator.hasNext());
+		}
+		checkState(cancelAfter == null || sentCount < cancelAfter);
+	}
+
+	@Override
+	public void open(Configuration parameters) throws Exception {
+		super.open(parameters);
+	}
+
+	@Override
+	public void snapshotState(FunctionSnapshotContext context) throws Exception {
+		lastSentStored.update(singletonList(sentCount));
+		if (cancelAfter != null && cancelAfter <= sentCount && cancelAfterCheckpointId == null) {
+			cancelAfterCheckpointId = context.getCheckpointId();
+		}
+	}
+
+	@Override
+	public void notifyCheckpointComplete(long checkpointId) {
+		if (cancelAfterCheckpointId != null && cancelAfterCheckpointId == checkpointId) {
+			cancel();
+		}
+	}
+
+	@Override
+	public void cancel() {
+		isCanceled = true;
+	}
+
+	public static CancellingIntegerSource upTo(int count, boolean continueAfterCount) {

Review comment:
       `count` sounds a bit strange. I have seen `upTo(int to)`, `upTo(int max)`, and `upTo(int endExclusive)`.

##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/utils/CancellingIntegerSource.java
##########
@@ -0,0 +1,127 @@
+/*
+ * 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.test.checkpointing.utils;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.CheckpointListener;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+
+import static java.util.Collections.singletonList;
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Integer source that cancels itself after a specified number emitted and subsequent checkpoint is fully completed.
+ */
+public class CancellingIntegerSource extends RichSourceFunction<Integer> implements CheckpointedFunction, CheckpointListener {
+
+	private final int count;
+	private final Integer cancelAfter;
+
+	@Nullable private transient Long cancelAfterCheckpointId;
+	private transient volatile boolean isCanceled;
+	private transient volatile int sentCount;
+	private transient ListState<Integer> lastSentStored;
+
+	private CancellingIntegerSource(int count, @Nullable Integer cancelAfter) {
+		checkArgument(count > 0);
+		checkArgument(cancelAfter == null || cancelAfter > 0);
+		this.cancelAfter = cancelAfter;
+		this.count = count;
+	}
+
+	@Override
+	public void run(SourceContext<Integer> ctx) throws InterruptedException {
+		emitInLoop(ctx);
+		awaitCancellation();
+	}
+
+	private void emitInLoop(SourceContext<Integer> ctx) throws InterruptedException {
+		while (sentCount < count && !isCanceled) {
+			synchronized (ctx.getCheckpointLock()) {
+				if (sentCount < count && !isCanceled) {
+					ctx.collect(sentCount++);
+				}
+			}
+			Thread.sleep(10); // allow to snapshot state (Thread.yield() doesn't always work)
+		}
+	}
+
+	private void awaitCancellation() {
+		while (!isCanceled) {
+			try {
+				Thread.sleep(50);
+			} catch (InterruptedException e) {
+				if (isCanceled) {
+					Thread.currentThread().interrupt();
+				}
+			}
+		}
+	}
+
+	@Override
+	public void initializeState(FunctionInitializationContext context) throws Exception {
+		lastSentStored = context.getOperatorStateStore().getListState(new ListStateDescriptor<>("counter", Integer.class));
+		if (context.isRestored()) {
+			Iterator<Integer> iterator = lastSentStored.get().iterator();
+			checkState(iterator.hasNext());
+			sentCount = iterator.next();
+			checkState(!iterator.hasNext());
+		}
+		checkState(cancelAfter == null || sentCount < cancelAfter);
+	}
+
+	@Override
+	public void open(Configuration parameters) throws Exception {
+		super.open(parameters);
+	}
+
+	@Override
+	public void snapshotState(FunctionSnapshotContext context) throws Exception {
+		lastSentStored.update(singletonList(sentCount));
+		if (cancelAfter != null && cancelAfter <= sentCount && cancelAfterCheckpointId == null) {
+			cancelAfterCheckpointId = context.getCheckpointId();
+		}
+	}
+
+	@Override
+	public void notifyCheckpointComplete(long checkpointId) {
+		if (cancelAfterCheckpointId != null && cancelAfterCheckpointId == checkpointId) {

Review comment:
       What happens if a checkpoint fails? Wouldn't `cancelAfterCheckpointId <= checkpointId` be more safe?

##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/SnapshotCompatibilityITCase.java
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.test.checkpointing;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.execution.JobClient;
+import org.apache.flink.runtime.checkpoint.CheckpointType;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.graph.StreamGraph;
+import org.apache.flink.test.checkpointing.utils.AccumulatingIntegerSink;
+import org.apache.flink.test.checkpointing.utils.CancellingIntegerSource;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static java.util.Collections.emptyMap;
+import static org.apache.flink.configuration.CheckpointingOptions.CHECKPOINTS_DIRECTORY;
+import static org.apache.flink.configuration.CheckpointingOptions.MAX_RETAINED_CHECKPOINTS;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.CHECKPOINT;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.SAVEPOINT;
+import static org.apache.flink.runtime.jobgraph.SavepointConfigOptions.SAVEPOINT_PATH;
+import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
+import static org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.createLocalEnvironment;
+import static org.apache.flink.util.Preconditions.checkState;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests recovery from a snapshot created in different UC mode (i.e. unaligned checkpoints enabled/disabled).
+ */
+@RunWith(Parameterized.class)
+public class SnapshotCompatibilityITCase {
+
+	@ClassRule
+	public static TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+	private static final int TOTAL_ELEMENTS = 20;
+	private static final int FIRST_RUN_EL_COUNT = TOTAL_ELEMENTS / 2;
+	private static final int FIRST_RUN_BACKPRESSURE_MS = 100; // per element
+	private static final int PARALLELISM = 1;
+
+	private final boolean startAligned;
+	private final CheckpointType type;
+	private File folder;
+
+	@Parameterized.Parameters(name = "type: {0}, startAligned: {1}")
+	public static Object[][] parameters() {
+		return new Object[][]{
+			{CHECKPOINT, true},
+			{CHECKPOINT, false},
+			{SAVEPOINT, true},
+			{SAVEPOINT, false},
+		};
+	}
+
+	public SnapshotCompatibilityITCase(CheckpointType type, boolean startAligned) {
+		this.startAligned = startAligned;
+		this.type = type;
+	}
+
+	@Before
+	public void init() throws IOException {
+		folder = temporaryFolder.newFolder();
+	}
+

Review comment:
       Could be removed by using an instance Rule and using `temporaryFolder` directly.

##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/SnapshotCompatibilityITCase.java
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.test.checkpointing;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.execution.JobClient;
+import org.apache.flink.runtime.checkpoint.CheckpointType;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.graph.StreamGraph;
+import org.apache.flink.test.checkpointing.utils.AccumulatingIntegerSink;
+import org.apache.flink.test.checkpointing.utils.CancellingIntegerSource;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static java.util.Collections.emptyMap;
+import static org.apache.flink.configuration.CheckpointingOptions.CHECKPOINTS_DIRECTORY;
+import static org.apache.flink.configuration.CheckpointingOptions.MAX_RETAINED_CHECKPOINTS;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.CHECKPOINT;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.SAVEPOINT;
+import static org.apache.flink.runtime.jobgraph.SavepointConfigOptions.SAVEPOINT_PATH;
+import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
+import static org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.createLocalEnvironment;
+import static org.apache.flink.util.Preconditions.checkState;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests recovery from a snapshot created in different UC mode (i.e. unaligned checkpoints enabled/disabled).
+ */
+@RunWith(Parameterized.class)
+public class SnapshotCompatibilityITCase {
+
+	@ClassRule
+	public static TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+	private static final int TOTAL_ELEMENTS = 20;
+	private static final int FIRST_RUN_EL_COUNT = TOTAL_ELEMENTS / 2;
+	private static final int FIRST_RUN_BACKPRESSURE_MS = 100; // per element
+	private static final int PARALLELISM = 1;
+
+	private final boolean startAligned;
+	private final CheckpointType type;
+	private File folder;
+
+	@Parameterized.Parameters(name = "type: {0}, startAligned: {1}")
+	public static Object[][] parameters() {
+		return new Object[][]{
+			{CHECKPOINT, true},
+			{CHECKPOINT, false},
+			{SAVEPOINT, true},
+			{SAVEPOINT, false},
+		};
+	}
+
+	public SnapshotCompatibilityITCase(CheckpointType type, boolean startAligned) {
+		this.startAligned = startAligned;
+		this.type = type;
+	}
+
+	@Before
+	public void init() throws IOException {
+		folder = temporaryFolder.newFolder();
+	}
+
+	@Test
+	@SuppressWarnings("unchecked")
+	public void test() throws Exception {
+		Tuple2<String, Map<String, Object>> pathAndAccumulators = type.isSavepoint() ? runAndTakeSavepoint() : runAndTakeExternalCheckpoint();
+		String savepointPath = pathAndAccumulators.f0;
+		Map<String, Object> accumulatorsBeforeBarrier = pathAndAccumulators.f1;
+		Map<String, Object> accumulatorsAfterBarrier = runFromSavepoint(savepointPath, !startAligned, TOTAL_ELEMENTS);
+		if (type.isSavepoint()) { // consistency can only be checked for savepoints because output is lost for ext. checkpoints
+			assertEquals(
+					intRange(0, TOTAL_ELEMENTS),
+					extractAndConcat(accumulatorsBeforeBarrier, accumulatorsAfterBarrier));
+		}
+	}
+
+	private Tuple2<String, Map<String, Object>> runAndTakeSavepoint() throws Exception {
+		JobClient jobClient = submitJobInitially(env(startAligned, 0, emptyMap()));
+		Thread.sleep(FIRST_RUN_EL_COUNT * FIRST_RUN_BACKPRESSURE_MS); // wait for all tasks to run and some backpressure from sink
+		Future<Map<String, Object>> accFuture = jobClient.getAccumulators(getClass().getClassLoader());
+		Future<String> savepointFuture = jobClient.stopWithSavepoint(false, folder.toURI().toString());
+		return new Tuple2<>(savepointFuture.get(), accFuture.get());
+	}
+
+	private Tuple2<String, Map<String, Object>> runAndTakeExternalCheckpoint() throws Exception {
+		JobClient jobClient = submitJobInitially(externalCheckpointEnv(startAligned, folder, 100));
+		File metadata = waitForChild(waitForChild(waitForChild(folder))); // structure: root/attempt/checkpoint/_metadata
+		cancelJob(jobClient);
+		return new Tuple2<>(metadata.getParentFile().toString(), emptyMap());
+	}
+
+	private static JobClient submitJobInitially(StreamExecutionEnvironment env) throws Exception {
+		return env.executeAsync(dag(FIRST_RUN_EL_COUNT, true, FIRST_RUN_BACKPRESSURE_MS, env));
+	}
+
+	private Map<String, Object> runFromSavepoint(String path, boolean isAligned, int totalCount) throws Exception {
+		StreamExecutionEnvironment env = env(isAligned, 50, Collections.singletonMap(SAVEPOINT_PATH, path));
+		return env.execute(dag(totalCount, false, 0, env)).getJobExecutionResult().getAllAccumulatorResults();
+	}
+
+	@SuppressWarnings({"OptionalGetWithoutIsPresent", "ConstantConditions"})
+	private static File waitForChild(File dir) throws InterruptedException {
+		while (dir.listFiles().length == 0) {
+			Thread.sleep(50);
+		}
+		return Arrays.stream(dir.listFiles()).max(Comparator.naturalOrder()).get();
+	}
+
+	private void cancelJob(JobClient jobClient) throws InterruptedException, java.util.concurrent.ExecutionException {
+		jobClient.cancel().get();
+		try {
+			jobClient.getJobExecutionResult(getClass().getClassLoader()); // wait for cancellation
+		} catch (Exception e) {
+			// ignore cancellation exception
+		}
+	}
+
+	private StreamExecutionEnvironment externalCheckpointEnv(boolean isAligned, File dir, int checkpointingInterval) {
+		Map<ConfigOption<?>, String> cfg = new HashMap<>();
+		cfg.put(CHECKPOINTS_DIRECTORY, dir.toURI().toString());
+		cfg.put(MAX_RETAINED_CHECKPOINTS, Integer.toString(Integer.MAX_VALUE)); // prevent deletion of checkpoint files while it's being checked and used
+		StreamExecutionEnvironment env = env(isAligned, checkpointingInterval, cfg);
+		env.getCheckpointConfig().enableExternalizedCheckpoints(RETAIN_ON_CANCELLATION);
+		return env;
+	}
+
+	@SuppressWarnings("unchecked")
+	private StreamExecutionEnvironment env(boolean isAligned, int checkpointingInterval, Map<ConfigOption<?>, String> cfg) {
+		Configuration configuration = new Configuration();
+		for (Map.Entry<ConfigOption<?>, String> e: cfg.entrySet()) {
+			configuration.setString((ConfigOption<String>) e.getKey(), e.getValue());
+		}

Review comment:
       Why not pass `configuration` directly instead of `cfg`?




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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rkhachatryan commented on a change in pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #12000:
URL: https://github.com/apache/flink/pull/12000#discussion_r422912681



##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/SnapshotCompatibilityITCase.java
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.test.checkpointing;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.execution.JobClient;
+import org.apache.flink.runtime.checkpoint.CheckpointType;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.graph.StreamGraph;
+import org.apache.flink.test.checkpointing.utils.AccumulatingIntegerSink;
+import org.apache.flink.test.checkpointing.utils.CancellingIntegerSource;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static java.util.Collections.emptyMap;
+import static org.apache.flink.configuration.CheckpointingOptions.CHECKPOINTS_DIRECTORY;
+import static org.apache.flink.configuration.CheckpointingOptions.MAX_RETAINED_CHECKPOINTS;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.CHECKPOINT;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.SAVEPOINT;
+import static org.apache.flink.runtime.jobgraph.SavepointConfigOptions.SAVEPOINT_PATH;
+import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
+import static org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.createLocalEnvironment;
+import static org.apache.flink.util.Preconditions.checkState;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests recovery from a snapshot created in different UC mode (i.e. unaligned checkpoints enabled/disabled).
+ */
+@RunWith(Parameterized.class)
+public class SnapshotCompatibilityITCase {
+
+	@ClassRule
+	public static TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+	private static final int TOTAL_ELEMENTS = 20;
+	private static final int FIRST_RUN_EL_COUNT = TOTAL_ELEMENTS / 2;
+	private static final int FIRST_RUN_BACKPRESSURE_MS = 100; // per element
+	private static final int PARALLELISM = 1;
+
+	private final boolean startAligned;
+	private final CheckpointType type;
+	private File folder;
+
+	@Parameterized.Parameters(name = "type: {0}, startAligned: {1}")
+	public static Object[][] parameters() {
+		return new Object[][]{
+			{CHECKPOINT, true},
+			{CHECKPOINT, false},
+			{SAVEPOINT, true},
+			{SAVEPOINT, false},
+		};
+	}
+
+	public SnapshotCompatibilityITCase(CheckpointType type, boolean startAligned) {
+		this.startAligned = startAligned;
+		this.type = type;
+	}
+
+	@Before
+	public void init() throws IOException {
+		folder = temporaryFolder.newFolder();
+	}
+
+	@Test
+	@SuppressWarnings("unchecked")
+	public void test() throws Exception {
+		Tuple2<String, Map<String, Object>> pathAndAccumulators = type.isSavepoint() ? runAndTakeSavepoint() : runAndTakeExternalCheckpoint();
+		String savepointPath = pathAndAccumulators.f0;
+		Map<String, Object> accumulatorsBeforeBarrier = pathAndAccumulators.f1;
+		Map<String, Object> accumulatorsAfterBarrier = runFromSavepoint(savepointPath, !startAligned, TOTAL_ELEMENTS);
+		if (type.isSavepoint()) { // consistency can only be checked for savepoints because output is lost for ext. checkpoints
+			assertEquals(
+					intRange(0, TOTAL_ELEMENTS),
+					extractAndConcat(accumulatorsBeforeBarrier, accumulatorsAfterBarrier));
+		}
+	}
+
+	private Tuple2<String, Map<String, Object>> runAndTakeSavepoint() throws Exception {
+		JobClient jobClient = submitJobInitially(env(startAligned, 0, emptyMap()));
+		Thread.sleep(FIRST_RUN_EL_COUNT * FIRST_RUN_BACKPRESSURE_MS); // wait for all tasks to run and some backpressure from sink
+		Future<Map<String, Object>> accFuture = jobClient.getAccumulators(getClass().getClassLoader());
+		Future<String> savepointFuture = jobClient.stopWithSavepoint(false, folder.toURI().toString());
+		return new Tuple2<>(savepointFuture.get(), accFuture.get());
+	}
+
+	private Tuple2<String, Map<String, Object>> runAndTakeExternalCheckpoint() throws Exception {
+		JobClient jobClient = submitJobInitially(externalCheckpointEnv(startAligned, folder, 100));
+		File metadata = waitForChild(waitForChild(waitForChild(folder))); // structure: root/attempt/checkpoint/_metadata
+		cancelJob(jobClient);
+		return new Tuple2<>(metadata.getParentFile().toString(), emptyMap());
+	}
+
+	private static JobClient submitJobInitially(StreamExecutionEnvironment env) throws Exception {
+		return env.executeAsync(dag(FIRST_RUN_EL_COUNT, true, FIRST_RUN_BACKPRESSURE_MS, env));
+	}
+
+	private Map<String, Object> runFromSavepoint(String path, boolean isAligned, int totalCount) throws Exception {
+		StreamExecutionEnvironment env = env(isAligned, 50, Collections.singletonMap(SAVEPOINT_PATH, path));
+		return env.execute(dag(totalCount, false, 0, env)).getJobExecutionResult().getAllAccumulatorResults();
+	}
+
+	@SuppressWarnings({"OptionalGetWithoutIsPresent", "ConstantConditions"})
+	private static File waitForChild(File dir) throws InterruptedException {
+		while (dir.listFiles().length == 0) {
+			Thread.sleep(50);
+		}
+		return Arrays.stream(dir.listFiles()).max(Comparator.naturalOrder()).get();
+	}
+
+	private void cancelJob(JobClient jobClient) throws InterruptedException, java.util.concurrent.ExecutionException {
+		jobClient.cancel().get();
+		try {
+			jobClient.getJobExecutionResult(getClass().getClassLoader()); // wait for cancellation
+		} catch (Exception e) {
+			// ignore cancellation exception
+		}
+	}
+
+	private StreamExecutionEnvironment externalCheckpointEnv(boolean isAligned, File dir, int checkpointingInterval) {
+		Map<ConfigOption<?>, String> cfg = new HashMap<>();
+		cfg.put(CHECKPOINTS_DIRECTORY, dir.toURI().toString());
+		cfg.put(MAX_RETAINED_CHECKPOINTS, Integer.toString(Integer.MAX_VALUE)); // prevent deletion of checkpoint files while it's being checked and used
+		StreamExecutionEnvironment env = env(isAligned, checkpointingInterval, cfg);
+		env.getCheckpointConfig().enableExternalizedCheckpoints(RETAIN_ON_CANCELLATION);
+		return env;
+	}
+
+	@SuppressWarnings("unchecked")
+	private StreamExecutionEnvironment env(boolean isAligned, int checkpointingInterval, Map<ConfigOption<?>, String> cfg) {
+		Configuration configuration = new Configuration();
+		for (Map.Entry<ConfigOption<?>, String> e: cfg.entrySet()) {
+			configuration.setString((ConfigOption<String>) e.getKey(), e.getValue());
+		}

Review comment:
       For some cases constructing a `Map` requires less boilerplate.




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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rkhachatryan edited a comment on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
rkhachatryan edited a comment on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624500453


   Azure build failure is unrelated: https://issues.apache.org/jira/browse/FLINK-17336


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot commented on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624234586


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 1eb638dded0a0234b396bb9a84a29c8f447d0bd7 UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624234586


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640",
       "triggerID" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 1eb638dded0a0234b396bb9a84a29c8f447d0bd7 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rkhachatryan commented on a change in pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #12000:
URL: https://github.com/apache/flink/pull/12000#discussion_r422910373



##########
File path: flink-tests/src/test/java/org/apache/flink/test/checkpointing/SnapshotCompatibilityITCase.java
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.test.checkpointing;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.execution.JobClient;
+import org.apache.flink.runtime.checkpoint.CheckpointType;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.graph.StreamGraph;
+import org.apache.flink.test.checkpointing.utils.AccumulatingIntegerSink;
+import org.apache.flink.test.checkpointing.utils.CancellingIntegerSource;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static java.util.Collections.emptyMap;
+import static org.apache.flink.configuration.CheckpointingOptions.CHECKPOINTS_DIRECTORY;
+import static org.apache.flink.configuration.CheckpointingOptions.MAX_RETAINED_CHECKPOINTS;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.CHECKPOINT;
+import static org.apache.flink.runtime.checkpoint.CheckpointType.SAVEPOINT;
+import static org.apache.flink.runtime.jobgraph.SavepointConfigOptions.SAVEPOINT_PATH;
+import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
+import static org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.createLocalEnvironment;
+import static org.apache.flink.util.Preconditions.checkState;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests recovery from a snapshot created in different UC mode (i.e. unaligned checkpoints enabled/disabled).
+ */
+@RunWith(Parameterized.class)
+public class SnapshotCompatibilityITCase {

Review comment:
       Yes, it makes sense.




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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624234586


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640",
       "triggerID" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 1eb638dded0a0234b396bb9a84a29c8f447d0bd7 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rkhachatryan commented on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624500453


   Azure build failure is unrelated: https://issues.apache.org/jira/browse/FLINK-17336
   Travis build succeeded: https://travis-ci.org/github/rkhachatryan/flink/builds/683573559


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12000: [FLINK-17476][tests] test recovery from snapshot created in different …

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12000:
URL: https://github.com/apache/flink/pull/12000#issuecomment-624234586


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640",
       "triggerID" : "1eb638dded0a0234b396bb9a84a29c8f447d0bd7",
       "triggerType" : "PUSH"
     }, {
       "hash" : "9d21fe810a520f20461a070f8925ba388bd73808",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=973",
       "triggerID" : "9d21fe810a520f20461a070f8925ba388bd73808",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 1eb638dded0a0234b396bb9a84a29c8f447d0bd7 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=640) 
   * 9d21fe810a520f20461a070f8925ba388bd73808 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=973) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org