rkhachatryan commented on a change in pull request #18224:
URL: https://github.com/apache/flink/pull/18224#discussion_r787022001



##########
File path: 
flink-tests/src/test/java/org/apache/flink/test/checkpointing/ChangelogPeriodicMaterializationITCase.java
##########
@@ -0,0 +1,734 @@
+/*
+ * 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.JobExecutionResult;
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.api.common.JobStatus;
+import org.apache.flink.api.common.functions.RichFlatMapFunction;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.state.CheckpointListener;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.state.State;
+import org.apache.flink.api.common.state.StateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.changelog.fs.FsStateChangelogStorageFactory;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.StateChangelogOptions;
+import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend;
+import org.apache.flink.core.fs.CloseableRegistry;
+import org.apache.flink.metrics.MetricGroup;
+import org.apache.flink.runtime.checkpoint.CheckpointOptions;
+import org.apache.flink.runtime.execution.Environment;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
+import org.apache.flink.runtime.query.TaskKvStateRegistry;
+import org.apache.flink.runtime.state.AbstractKeyedStateBackend;
+import org.apache.flink.runtime.state.AbstractStateBackend;
+import org.apache.flink.runtime.state.CheckpointStreamFactory;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.KeyGroupedInternalPriorityQueue;
+import org.apache.flink.runtime.state.Keyed;
+import org.apache.flink.runtime.state.KeyedStateHandle;
+import org.apache.flink.runtime.state.OperatorStateBackend;
+import org.apache.flink.runtime.state.OperatorStateHandle;
+import org.apache.flink.runtime.state.PriorityComparable;
+import org.apache.flink.runtime.state.SavepointResources;
+import org.apache.flink.runtime.state.SnapshotResult;
+import org.apache.flink.runtime.state.StateSnapshotTransformer;
+import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
+import org.apache.flink.runtime.state.heap.HeapPriorityQueueElement;
+import org.apache.flink.runtime.state.ttl.TtlTimeProvider;
+import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import org.apache.flink.streaming.api.environment.CheckpointConfig;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.sink.SinkFunction;
+import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
+import org.apache.flink.streaming.api.graph.StreamGraph;
+import org.apache.flink.test.util.MiniClusterWithClientResource;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.TestLogger;
+import org.apache.flink.util.function.FunctionWithException;
+
+import org.junit.After;
+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 javax.annotation.Nonnull;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.RunnableFuture;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BooleanSupplier;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static 
org.apache.flink.shaded.guava30.com.google.common.collect.Iterables.get;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * This verifies that checkpointing works correctly for Changelog state 
backend with materialized
+ * state / non-materialized state.
+ */
+@RunWith(Parameterized.class)
+public class ChangelogPeriodicMaterializationITCase extends TestLogger {
+
+    private static final int TOTAL_ELEMENTS = 20;
+    private static final int NUM_TASK_MANAGERS = 1;
+    private static final int NUM_TASK_SLOTS = 4;
+    private static final int NUM_SLOTS = NUM_TASK_MANAGERS * NUM_TASK_SLOTS;
+
+    private final AbstractStateBackend delegatedStateBackend;
+
+    private StreamExecutionEnvironment env;
+
+    private URI checkpointURI;
+
+    private MiniClusterWithClientResource cluster;
+
+    @ClassRule public static final TemporaryFolder TEMPORARY_FOLDER = new 
TemporaryFolder();
+
+    @Parameterized.Parameters(name = "delegated state backend type ={0}")
+    public static Collection<AbstractStateBackend> parameter() {
+        return Arrays.asList(
+                new HashMapStateBackend(),
+                new EmbeddedRocksDBStateBackend(),
+                new EmbeddedRocksDBStateBackend(true));
+    }
+
+    public ChangelogPeriodicMaterializationITCase(AbstractStateBackend 
delegatedStateBackend) {
+        this.delegatedStateBackend = delegatedStateBackend;
+    }
+
+    @Before
+    public void setup() throws Exception {
+        cluster =
+                new MiniClusterWithClientResource(
+                        new MiniClusterResourceConfiguration.Builder()
+                                .setConfiguration(configureDSTL())
+                                .setNumberTaskManagers(NUM_TASK_MANAGERS)
+                                .setNumberSlotsPerTaskManager(NUM_TASK_SLOTS)
+                                .build());
+        cluster.before();
+        env = StreamExecutionEnvironment.getExecutionEnvironment();
+        checkpointURI = TEMPORARY_FOLDER.newFolder().toURI();
+        env.enableCheckpointing(10)
+                .enableChangelogStateBackend(true)
+                .getCheckpointConfig()
+                .setCheckpointStorage(checkpointURI);
+        // init source data randomly
+        PreHandlingSource.initSourceData(TOTAL_ELEMENTS);
+        triggerDelegatedSnapshot = new AtomicBoolean(false);
+    }
+
+    @After
+    public void teardown() throws IOException {
+        cluster.after();
+        // clear result in sink
+        CollectionSink.clearExpectedResult();
+    }
+
+    /** Recovery from checkpoint only containing non-materialized state. */
+    @Test
+    public void testNonMaterialization() {
+        env.setStateBackend(new 
DelegatedStateBackendWrapper(delegatedStateBackend, t -> t))
+                .setRestartStrategy(RestartStrategies.fixedDelayRestart(1, 0));
+        env.configure(
+                new Configuration()
+                        .set(
+                                
StateChangelogOptions.PERIODIC_MATERIALIZATION_INTERVAL,
+                                Duration.ofMinutes(3)));
+        waitAndAssert(
+                buildStreamGraph(
+                        new PreHandlingSource() {
+                            @Override
+                            protected void preHandle() throws Exception {
+                                if (getRuntimeContext().getAttemptNumber() == 0
+                                        && currentIndex == TOTAL_ELEMENTS / 2) 
{
+                                    waitUntilFalse(() -> 
completedCheckpointNum.get() <= 0);
+                                    throwArtificialFailure();
+                                }
+                            }
+                        }));
+    }
+
+    /** Recovery from checkpoint containing non-materialized state and 
materialized state. */
+    @Test
+    public void testMaterialization() {
+        // Maintain the RunnableFuture of SnapshotResult to make sure the 
materialization phase has
+        // been done
+        Queue<RunnableFuture<SnapshotResult<KeyedStateHandle>>> 
pendingMaterialization =
+                new ConcurrentLinkedQueue<>();
+        
SerializableFunctionWithException<RunnableFuture<SnapshotResult<KeyedStateHandle>>>
+                snapshotResultConsumer =
+                        snapshotResultFuture -> {
+                            pendingMaterialization.add(snapshotResultFuture);
+                            return snapshotResultFuture;
+                        };
+        env.setStateBackend(
+                        new DelegatedStateBackendWrapper(
+                                delegatedStateBackend, snapshotResultConsumer))
+                .setRestartStrategy(RestartStrategies.fixedDelayRestart(2, 0));
+        env.configure(
+                new Configuration()
+                        .set(
+                                
StateChangelogOptions.PERIODIC_MATERIALIZATION_INTERVAL,
+                                Duration.ofMillis(10)));
+        waitAndAssert(
+                buildStreamGraph(
+                        new PreHandlingSource() {
+                            @Override
+                            protected void preHandle() throws Exception {
+                                if (getRuntimeContext().getAttemptNumber() == 0
+                                        && currentIndex == TOTAL_ELEMENTS / 4) 
{
+                                    waitUntilFalse(
+                                            () ->
+                                                    
completedCheckpointNum.get() <= 0
+                                                            && 
pendingMaterialization.stream()
+                                                                    
.noneMatch(Future::isDone));

Review comment:
       I don't fully understand this statement, could you clarify the following?
   I'm assuming the goal is to wait for the materialization completion (PCIIW), 
then..
   
   1. With `&&`, the wait will stop once some checkpoint completes, regardless 
of materialization, right?
   2. Completion of the `Future` doesn't guarantee that the backend is updated 
with the results. I guess the subsuquent sleep tries to address this (?); but 
they both use the Task thread, so it seems that backend doesn't (maybe I'm 
missing the goal or some thread details)
   3. `waitUntilFalse` is equivalent to `waitWhile`? The latter name is more 
clear to me.
   
   edit:
   (2) I see that this code is not executed by the task thread, nor under a 
checkpoint lock. 
   Still, when running `testMaterialization` with a longer materialization 
interval, I don't see materialization happenning. But that may be caused by (1).




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