1fanwang opened a new pull request, #29960:
URL: https://github.com/apache/flink/pull/29960

   ## What is the purpose of the change
   
   Fixes [FLINK-41417](https://issues.apache.org/jira/browse/FLINK-41417).
   
   A job on the async state API with a TTL-enabled MapState can call 
asyncEntries, asyncKeys or asyncValues and check isEmpty on the returned 
iterator, for example to skip work when the map has nothing in it. With TTL 
enabled, isEmpty always returned false, even right after asyncClear, so the job 
treated an empty map as having entries. The same map without TTL returns true.
   
   After this change, isEmpty on the TTL iterators returns what the wrapped 
backend iterator reports, matching state without TTL.
   
   One case is unchanged: if every remaining entry has expired but has not been 
cleaned up yet, isEmpty still returns false. Answering that would mean reading 
ahead and dropping expired entries before the caller asks for them. The issue 
proposes the same scope.
   
   ## Brief change log
   
     - The TTL layer wraps the backend's map iterator to filter out expired 
entries. Its isEmpty answer was a hard-coded false; it now asks the backend 
iterator underneath. The entries, keys and values iterators share that wrapper, 
so one change fixes all three.
     - A regression test exercises a TTL map on the ForSt backend, since that 
is where async state applies the TTL wrapper, and checks all three iterators 
after a clear.
   
   ## Verifying this change
   
   Please make sure both new and modified tests in this PR follow [the 
conventions for tests defined in our code quality 
guide](https://flink.apache.org/how-to-contribute/code-style-and-quality-common/#7-testing).
   
   This change added tests and can be verified as follows:
   
     - Added 
ForStMapStateTest#testTtlMapStateAsyncIteratorsReportEmptyAfterClear. It puts 
one entry into a TTL MapState on ForSt, clears the map, then checks that the 
entries, keys and values iterators report empty. On master it fails at the 
first isEmpty check after the clear.
   
   ### Testing done
   
   A one-key streaming job on the ForSt backend with async state enabled. Its 
process function puts one entry into a TTL MapState, prints isEmpty for the 
entries iterator, clears the map, then prints isEmpty for the entries, keys and 
values iterators. JDK 17, from the repository root at this PR's head, with the 
source at the end of this section saved there as Flink41417Repro.java:
   
   ```
   ./mvnw -q -pl flink-state-backends/flink-statebackend-forst -am test-compile 
dependency:build-classpath -Dmdep.outputFile=cp.txt -Dmdep.includeScope=test 
-DskipTests -Dfast -Pskip-webui-build
   ./mvnw -q -pl flink-rpc/flink-rpc-akka,flink-rpc/flink-rpc-akka-loader -am 
package -DskipTests -Dfast -Pskip-webui-build
   
CP="flink-rpc/flink-rpc-akka-loader/target/flink-rpc-akka-loader-2.5-SNAPSHOT.jar:flink-state-backends/flink-statebackend-forst/target/classes:$(cat
 cp.txt)"
   cat > log4j2.properties <<'EOF'
   rootLogger.level = INFO
   rootLogger.appenderRef.c.ref = c
   appender.c.type = Console
   appender.c.name = c
   appender.c.layout.type = PatternLayout
   appender.c.layout.pattern = %c{1} - %m%n
   EOF
   mkdir -p out
   javac -d out -cp "$CP" Flink41417Repro.java
   ```
   
   Before the fix, with TtlMapState compiled from the base commit 7e4930389ad 
and placed first on the classpath:
   
   ```
   mkdir -p base-src base-classes
   git show 
7e4930389ad:flink-runtime/src/main/java/org/apache/flink/runtime/state/v2/ttl/TtlMapState.java
 > base-src/TtlMapState.java
   javac -nowarn -d base-classes -cp "$CP" base-src/TtlMapState.java
   java -Dlog4j.configurationFile=log4j2.properties -cp "base-classes:out:$CP" 
Flink41417Repro 2>&1 | grep -E 'ForStStateBackend - Successfully|^after'
   ```
   
   ```
   ForStStateBackend - Successfully loaded ForSt native library
   after put:   entries.isEmpty()=false
   after clear: entries.isEmpty()=false
   after clear: keys.isEmpty()=false
   after clear: values.isEmpty()=false
   ```
   
   After the fix, same job at this PR's head:
   
   ```
   java -Dlog4j.configurationFile=log4j2.properties -cp "out:$CP" 
Flink41417Repro 2>&1 | grep -E 'ForStStateBackend - Successfully|^after'
   ```
   
   ```
   ForStStateBackend - Successfully loaded ForSt native library
   after put:   entries.isEmpty()=false
   after clear: entries.isEmpty()=true
   after clear: keys.isEmpty()=true
   after clear: values.isEmpty()=true
   ```
   
   Both runs exit 0.
   
   <details><summary>Reproducer source: Flink41417Repro.java</summary>
   
   ```java
   import org.apache.flink.api.common.functions.OpenContext;
   import org.apache.flink.api.common.state.StateTtlConfig;
   import org.apache.flink.api.common.state.v2.MapState;
   import org.apache.flink.api.common.state.v2.MapStateDescriptor;
   import org.apache.flink.api.common.typeinfo.Types;
   import org.apache.flink.configuration.Configuration;
   import org.apache.flink.configuration.StateBackendOptions;
   import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
   import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
   import org.apache.flink.streaming.api.operators.StreamingRuntimeContext;
   import org.apache.flink.util.Collector;
   
   import java.time.Duration;
   
   public class Flink41417Repro {
   
       public static void main(String[] args) throws Exception {
           Configuration conf = new Configuration();
           conf.set(StateBackendOptions.STATE_BACKEND, "forst");
           StreamExecutionEnvironment env = 
StreamExecutionEnvironment.getExecutionEnvironment(conf);
           env.setParallelism(1);
           env.fromData("k")
                   .keyBy(value -> value)
                   .enableAsyncState()
                   .process(new CheckEmpty())
                   .executeAndCollect(10)
                   .forEach(System.out::println);
       }
   
       static class CheckEmpty extends KeyedProcessFunction<String, String, 
String> {
   
           private transient MapState<String, String> map;
   
           @Override
           public void open(OpenContext openContext) {
               MapStateDescriptor<String, String> descriptor =
                       new MapStateDescriptor<>("map", Types.STRING, 
Types.STRING);
               
descriptor.enableTimeToLive(StateTtlConfig.newBuilder(Duration.ofHours(1)).build());
               map = ((StreamingRuntimeContext) 
getRuntimeContext()).getMapState(descriptor);
           }
   
           @Override
           public void processElement(String value, Context ctx, 
Collector<String> out) {
               map.asyncPut(value, "v")
                       .thenCompose(ignored -> map.asyncEntries())
                       .thenCompose(
                               entries -> {
                                   out.collect("after put:   
entries.isEmpty()=" + entries.isEmpty());
                                   return map.asyncClear();
                               })
                       .thenCompose(ignored -> map.asyncEntries())
                       .thenCompose(
                               entries -> {
                                   out.collect("after clear: 
entries.isEmpty()=" + entries.isEmpty());
                                   return map.asyncKeys();
                               })
                       .thenCompose(
                               keys -> {
                                   out.collect("after clear: keys.isEmpty()=" + 
keys.isEmpty());
                                   return map.asyncValues();
                               })
                       .thenAccept(
                               values ->
                                       out.collect(
                                               "after clear: values.isEmpty()="
                                                       + values.isEmpty()));
           }
       }
   }
   ```
   
   </details>
   
   ## 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, 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
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes (please specify the tool below)
   
   Generated-by: GitHub Copilot CLI 1.0.102 (Auto)
   


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