You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "fredia (via GitHub)" <gi...@apache.org> on 2024/04/08 10:28:11 UTC

[PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

fredia opened a new pull request, #24633:
URL: https://github.com/apache/flink/pull/24633

   <!--
   *Thank you very much for contributing to Apache Flink - we are happy that you want to help us improve Flink. To help the community review your contribution in the best possible way, please go through the checklist below, which will get the contribution into a shape in which it can be best reviewed.*
   
   *Please understand that we do not do this to make contributions to Flink a hassle. In order to uphold a high standard of quality for code contributions, while at the same time managing a large number of contributions, we need contributors to prepare the contributions well, and give reviewers enough contextual information for the review. Please also understand that contributions that do not follow this guide will take longer to review and thus typically be picked up with lower priority by the community.*
   
   ## Contribution Checklist
   
     - Make sure that the pull request corresponds to a [JIRA issue](https://issues.apache.org/jira/projects/FLINK/issues). Exceptions are made for typos in JavaDoc or documentation files, which need no JIRA issue.
     
     - Name the pull request in the form "[FLINK-XXXX] [component] Title of the pull request", where *FLINK-XXXX* should be replaced by the actual issue number. Skip *component* if you are unsure about which is the best component.
     Typo fixes that have no associated JIRA issue should be named following this pattern: `[hotfix] [docs] Fix typo in event time introduction` or `[hotfix] [javadocs] Expand JavaDoc for PuncuatedWatermarkGenerator`.
   
     - Fill out the template below to describe the changes contributed by the pull request. That will give reviewers the context they need to do the review.
     
     - Make sure that the change passes the automated tests, i.e., `mvn clean verify` passes. You can set up Azure Pipelines CI to do that following [this guide](https://cwiki.apache.org/confluence/display/FLINK/Azure+Pipelines#AzurePipelines-Tutorial:SettingupAzurePipelinesforaforkoftheFlinkrepository).
   
     - Each pull request should address only one issue, not mix up code from multiple issues.
     
     - Each commit in the pull request has a meaningful commit message (including the JIRA id)
   
     - Once all items of the checklist are addressed, remove the above text and this checklist, leaving only the filled out template below.
   
   
   **(The sections below can be removed for hotfixes of typos)**
   -->
   
   ## What is the purpose of the change
   
    This pr implements the record buffer of AsyncExecutionController, based on https://github.com/apache/flink/pull/24614
   
   ## Brief change log
   
   - Introduce `activeBuffer` , `blockingBuffer` and `inFlightRecordNum` into `AsyncExecutionController`.
   - Control the in-flight record number in `AsyncExecutionController`
   
   ## Verifying this change
   
   - Add `AsyncExecutionControllerTest#testInFlightRecordControl`
   
   ## 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): (yes)
     - 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? (yes)
     - If yes, how is the feature documented? (JavaDocs)
   


-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on PR #24633:
URL: https://github.com/apache/flink/pull/24633#issuecomment-2048858730

   @Zakelly Thanks for the suggestions, I updated and rebased this PR, please take a look again.


-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "Zakelly (via GitHub)" <gi...@apache.org>.
Zakelly commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1560916376


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestBuffer.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A buffer to hold state requests to execute state requests in batch, which can only be manipulated
+ * within task thread.
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+@NotThreadSafe
+public class StateRequestBuffer<R, K> {
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeQueue;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final Map<K, Deque<StateRequest<K, ?, ?>>> blockingQueue;
+
+    /** The number of state requests in blocking queue. */
+    int blockingQueueSize;
+
+    public StateRequestBuffer() {
+        this.activeQueue = new LinkedList<>();
+        this.blockingQueue = new HashMap<>();
+        this.blockingQueueSize = 0;
+    }
+
+    void enqueueToActive(StateRequest<K, ?, ?> request) {
+        activeQueue.add(request);
+    }
+
+    void enqueueToBlocking(StateRequest<K, ?, ?> request) {
+        blockingQueue
+                .computeIfAbsent(request.getRecordContext().getKey(), k -> new LinkedList<>())
+                .add(request);
+        blockingQueueSize++;
+    }
+
+    /**
+     * Try to pull one state request with specific key from blocking queue to active queue.
+     *
+     * @param key The key to release, the other records with this key is no longer blocking.
+     * @return The first record context with the same key in blocking queue, null if no such record.
+     */
+    @Nullable
+    RecordContext<R, K> tryActivateOneByKey(K key) {
+        if (!blockingQueue.containsKey(key)) {
+            return null;
+        }
+
+        StateRequest<K, ?, ?> stateRequest = blockingQueue.get(key).getFirst();
+        activeQueue.add(stateRequest);
+        blockingQueue.get(key).removeFirst();
+        if (blockingQueue.get(key).isEmpty()) {
+            blockingQueue.remove(key);
+        }
+        blockingQueueSize--;
+        return (RecordContext<R, K>) stateRequest.getRecordContext();
+    }
+
+    /**
+     * Get the number of state requests of blocking queue in constant-time.
+     *
+     * @return the number of state requests of blocking queue.
+     */
+    @VisibleForTesting
+    int blockingQueueSize() {
+        return blockingQueueSize;
+    }
+
+    /**
+     * Get the number of state requests of active queue in constant-time.
+     *
+     * @return the number of state requests of active queue.
+     */
+    @VisibleForTesting
+    int activeQueueSize() {
+        return activeQueue.size();
+    }
+
+    /**
+     * Try to pop N state requests from active queue, if the size of active queue is less than N,
+     * return all the requests in active queue.
+     *
+     * @param N the number of state requests to pop.
+     * @return A list of state requests.
+     */
+    List<StateRequest<?, ?, ?>> popActive(int N) {

Review Comment:
   ```suggestion
       List<StateRequest<?, ?, ?>> popActive(int n) {
   ```



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "Zakelly (via GitHub)" <gi...@apache.org>.
Zakelly commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1559199086


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestsBuffer.java:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import oshi.annotation.concurrent.NotThreadSafe;
+
+import javax.annotation.Nullable;
+
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A buffer to hold state requests to execute state requests in batch.
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+@NotThreadSafe
+public class StateRequestsBuffer<R, K> {

Review Comment:
   How about naming it `StateRequestBuffer` without the 's' ?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    /**
+     * The batch size. When the number of state requests in the active buffer exceeds the batch
+     * size, a batched state execution would be triggered.
+     */
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /**
+     * The mailbox executor borrowed from {@code StreamTask}. Keeping the reference of
+     * mailboxExecutor here is to restrict the number of in-flight records, when the number of
+     * in-flight records > {@link #maxInFlightRecordNum}, the newly entering records would be
+     * blocked.
+     */
+    private final MailboxExecutor mailboxExecutor;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /** The buffer to store the state requests to execute in batch. */
+    StateRequestsBuffer<R, K> stateRequestsBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.stateRequestsBuffer = new StateRequestsBuffer<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(record, key, this::disposeContext);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Dispose a context.
+     *
+     * @param toDispose the context to dispose.
+     */
+    public void disposeContext(RecordContext<R, K> toDispose) {
+        keyAccountingUnit.release(toDispose.getRecord(), toDispose.getKey());
+        inFlightRecordNum.decrementAndGet();
+        RecordContext<R, K> nextRecordCtx =
+                stateRequestsBuffer.tryMigrateSpecificOne(toDispose.getKey());
+        if (nextRecordCtx != null) {
+            Preconditions.checkState(
+                    tryOccupyKey(nextRecordCtx),
+                    String.format("key(%s) is already occupied.", nextRecordCtx.getKey()));
+        }
+    }
+
+    /**
+     * Try to occupy a key by a given context.
+     *
+     * @param recordContext the given context.
+     * @return true if occupy succeed or the key has already occupied by this context.
+     */
+    boolean tryOccupyKey(RecordContext<R, K> recordContext) {
+        boolean occupied = recordContext.isKeyOccupied();
+        if (!occupied
+                && keyAccountingUnit.occupy(recordContext.getRecord(), recordContext.getKey())) {
+            recordContext.setKeyOccupied();
+            occupied = true;
+        }
+        return occupied;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (tryOccupyKey(currentContext)) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToActive(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToBlocking(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    void triggerIfNeeded(boolean force) {
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {
+            return;
+        }
+        List<StateRequest<?, ?, ?>> toRun = stateRequestsBuffer.nextToRun();
+        stateRequestsBuffer.clearActiveQueue();
+        stateExecutor.executeBatchRequests(toRun);
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isKeyOccupied()) {
+            return;
+        }
+        RecordContext<R, K> storedContext = currentContext;
+        // 2. If the state request is for a newly entered record, the in-flight record number should
+        // be less than the max in-flight record number.
+        // Note: the currentContext may be updated by {@code StateFutureFactory#build}.
+        try {
+            while (inFlightRecordNum.get() > maxInFlightRecordNum) {
+                if (!mailboxExecutor.tryYield()) {
+                    triggerIfNeeded(true);
+                    Thread.sleep(50);

Review Comment:
   Is `50ms` a little bit too long?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestsBuffer.java:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import oshi.annotation.concurrent.NotThreadSafe;
+
+import javax.annotation.Nullable;
+
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A buffer to hold state requests to execute state requests in batch.
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+@NotThreadSafe
+public class StateRequestsBuffer<R, K> {
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final Deque<StateRequest<K, ?, ?>> activeQueue;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final Map<K, Deque<StateRequest<K, ?, ?>>> blockingQueue;
+
+    /** The number of state requests in blocking queue. */
+    int blockingQueueSize;
+
+    public StateRequestsBuffer() {
+        this.activeQueue = new LinkedList<>();
+        this.blockingQueue = new HashMap<>();
+        this.blockingQueueSize = 0;
+    }
+
+    void enqueueToActive(StateRequest<K, ?, ?> request) {
+        activeQueue.add(request);
+    }
+
+    void enqueueToBlocking(StateRequest<K, ?, ?> request) {
+        blockingQueue
+                .computeIfAbsent(request.getRecordContext().getKey(), k -> new LinkedList<>())
+                .add(request);
+        blockingQueueSize++;
+    }
+
+    /**
+     * Try to migrate one state request with specific key from blocking queue to active queue.
+     *
+     * @param key The key to release, the other records with this key is no longer blocking.
+     * @return The first record context with the same key in blocking queue, null if no such record.
+     */
+    @Nullable
+    RecordContext<R, K> tryMigrateSpecificOne(K key) {
+        if (!blockingQueue.containsKey(key)) {
+            return null;
+        }
+
+        StateRequest<K, ?, ?> stateRequest = blockingQueue.get(key).getFirst();
+        activeQueue.add(stateRequest);
+        blockingQueue.get(key).removeFirst();
+        if (blockingQueue.get(key).isEmpty()) {
+            blockingQueue.remove(key);
+        }
+        blockingQueueSize--;
+        return (RecordContext<R, K>) stateRequest.getRecordContext();
+    }
+
+    /**
+     * Get the number of state requests of blocking queue in constant-time.
+     *
+     * @return the number of state requests of blocking queue.
+     */
+    @VisibleForTesting
+    int blockingQueueSize() {
+        return blockingQueueSize;
+    }
+
+    /**
+     * Get the number of state requests of active queue in constant-time.
+     *
+     * @return the number of state requests of active queue.
+     */
+    @VisibleForTesting
+    int activeQueueSize() {
+        return activeQueue.size();
+    }
+
+    /** Clear all state requests in the active queue. */
+    void clearActiveQueue() {
+        activeQueue.clear();
+    }
+
+    List<StateRequest<?, ?, ?>> nextToRun() {

Review Comment:
   I'd suggest we combine `clearActiveQueue` and `nextToRun` together and provide a new method that could `pop` a given number of `StateRequest`s to `AEC`.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    /**
+     * The batch size. When the number of state requests in the active buffer exceeds the batch
+     * size, a batched state execution would be triggered.
+     */
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /**
+     * The mailbox executor borrowed from {@code StreamTask}. Keeping the reference of
+     * mailboxExecutor here is to restrict the number of in-flight records, when the number of
+     * in-flight records > {@link #maxInFlightRecordNum}, the newly entering records would be
+     * blocked.
+     */
+    private final MailboxExecutor mailboxExecutor;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /** The buffer to store the state requests to execute in batch. */
+    StateRequestsBuffer<R, K> stateRequestsBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.stateRequestsBuffer = new StateRequestsBuffer<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(record, key, this::disposeContext);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Dispose a context.
+     *
+     * @param toDispose the context to dispose.
+     */
+    public void disposeContext(RecordContext<R, K> toDispose) {
+        keyAccountingUnit.release(toDispose.getRecord(), toDispose.getKey());
+        inFlightRecordNum.decrementAndGet();
+        RecordContext<R, K> nextRecordCtx =
+                stateRequestsBuffer.tryMigrateSpecificOne(toDispose.getKey());
+        if (nextRecordCtx != null) {
+            Preconditions.checkState(
+                    tryOccupyKey(nextRecordCtx),
+                    String.format("key(%s) is already occupied.", nextRecordCtx.getKey()));
+        }
+    }
+
+    /**
+     * Try to occupy a key by a given context.
+     *
+     * @param recordContext the given context.
+     * @return true if occupy succeed or the key has already occupied by this context.
+     */
+    boolean tryOccupyKey(RecordContext<R, K> recordContext) {
+        boolean occupied = recordContext.isKeyOccupied();
+        if (!occupied
+                && keyAccountingUnit.occupy(recordContext.getRecord(), recordContext.getKey())) {
+            recordContext.setKeyOccupied();
+            occupied = true;
+        }
+        return occupied;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (tryOccupyKey(currentContext)) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToActive(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToBlocking(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    void triggerIfNeeded(boolean force) {
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {
+            return;
+        }
+        List<StateRequest<?, ?, ?>> toRun = stateRequestsBuffer.nextToRun();
+        stateRequestsBuffer.clearActiveQueue();
+        stateExecutor.executeBatchRequests(toRun);
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isKeyOccupied()) {
+            return;
+        }
+        RecordContext<R, K> storedContext = currentContext;
+        // 2. If the state request is for a newly entered record, the in-flight record number should
+        // be less than the max in-flight record number.
+        // Note: the currentContext may be updated by {@code StateFutureFactory#build}.
+        try {
+            while (inFlightRecordNum.get() > maxInFlightRecordNum) {

Review Comment:
   I think we could clarify the definition of `inFlightRecordNum`... IIUC currently the `inFlightRecordNum` == `keyAccountingUnit.occupiedCount`. I'm not sure which size/count should we control, the record in AEC or the running record?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    /**
+     * The batch size. When the number of state requests in the active buffer exceeds the batch
+     * size, a batched state execution would be triggered.
+     */
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /**
+     * The mailbox executor borrowed from {@code StreamTask}. Keeping the reference of
+     * mailboxExecutor here is to restrict the number of in-flight records, when the number of
+     * in-flight records > {@link #maxInFlightRecordNum}, the newly entering records would be
+     * blocked.
+     */
+    private final MailboxExecutor mailboxExecutor;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /** The buffer to store the state requests to execute in batch. */
+    StateRequestsBuffer<R, K> stateRequestsBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.stateRequestsBuffer = new StateRequestsBuffer<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(record, key, this::disposeContext);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Dispose a context.
+     *
+     * @param toDispose the context to dispose.
+     */
+    public void disposeContext(RecordContext<R, K> toDispose) {
+        keyAccountingUnit.release(toDispose.getRecord(), toDispose.getKey());
+        inFlightRecordNum.decrementAndGet();
+        RecordContext<R, K> nextRecordCtx =
+                stateRequestsBuffer.tryMigrateSpecificOne(toDispose.getKey());
+        if (nextRecordCtx != null) {
+            Preconditions.checkState(
+                    tryOccupyKey(nextRecordCtx),
+                    String.format("key(%s) is already occupied.", nextRecordCtx.getKey()));
+        }
+    }
+
+    /**
+     * Try to occupy a key by a given context.
+     *
+     * @param recordContext the given context.
+     * @return true if occupy succeed or the key has already occupied by this context.
+     */
+    boolean tryOccupyKey(RecordContext<R, K> recordContext) {
+        boolean occupied = recordContext.isKeyOccupied();
+        if (!occupied
+                && keyAccountingUnit.occupy(recordContext.getRecord(), recordContext.getKey())) {
+            recordContext.setKeyOccupied();
+            occupied = true;
+        }
+        return occupied;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (tryOccupyKey(currentContext)) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToActive(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToBlocking(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    void triggerIfNeeded(boolean force) {
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {
+            return;
+        }
+        List<StateRequest<?, ?, ?>> toRun = stateRequestsBuffer.nextToRun();
+        stateRequestsBuffer.clearActiveQueue();
+        stateExecutor.executeBatchRequests(toRun);
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isKeyOccupied()) {
+            return;
+        }
+        RecordContext<R, K> storedContext = currentContext;
+        // 2. If the state request is for a newly entered record, the in-flight record number should
+        // be less than the max in-flight record number.
+        // Note: the currentContext may be updated by {@code StateFutureFactory#build}.
+        try {
+            while (inFlightRecordNum.get() > maxInFlightRecordNum) {
+                if (!mailboxExecutor.tryYield()) {
+                    triggerIfNeeded(true);
+                    Thread.sleep(50);
+                }
+            }
+            // 3. Ensure the currentContext is restored.
+            setCurrentContext(storedContext);
+            inFlightRecordNum.incrementAndGet();
+        } catch (InterruptedException e) {

Review Comment:
   IIUC, the `InterruptedException` should be ignored, otherwise it will produce a fatal error during TM normal exit (required by JM) ?



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "flinkbot (via GitHub)" <gi...@apache.org>.
flinkbot commented on PR #24633:
URL: https://github.com/apache/flink/pull/24633#issuecomment-2042405928

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "14fbde32439fc83b7e7e2f572d1e878d62b6cafb",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "14fbde32439fc83b7e7e2f572d1e878d62b6cafb",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 14fbde32439fc83b7e7e2f572d1e878d62b6cafb UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@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.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1562344262


##########
flink-runtime/src/test/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionControllerTest.java:
##########
@@ -152,66 +148,168 @@ void testBasicRun() {
 
         // Single-step run for another key.
         // Firstly, the user code generates value get in active buffer.
-        assertThat(aec.activeBuffer.size()).isEqualTo(1);
+        assertThat(aec.stateRequestsBuffer.activeQueueSize()).isEqualTo(1);
         assertThat(aec.keyAccountingUnit.occupiedCount()).isEqualTo(1);
+        assertThat(aec.inFlightRecordNum.get()).isEqualTo(1);
         aec.triggerIfNeeded(true);
         // After running, the value update is in active buffer.
-        assertThat(aec.activeBuffer.size()).isEqualTo(1);
+        assertThat(aec.stateRequestsBuffer.activeQueueSize()).isEqualTo(1);
         assertThat(aec.keyAccountingUnit.occupiedCount()).isEqualTo(1);
+        assertThat(aec.inFlightRecordNum.get()).isEqualTo(1);
         aec.triggerIfNeeded(true);
         // Value update finishes.
-        assertThat(aec.activeBuffer.size()).isEqualTo(0);
+        assertThat(aec.stateRequestsBuffer.activeQueueSize()).isEqualTo(0);
         assertThat(aec.keyAccountingUnit.occupiedCount()).isEqualTo(0);
+        assertThat(aec.inFlightRecordNum.get()).isEqualTo(0);
         assertThat(output.get()).isEqualTo(1);
         assertThat(recordContext4.getReferenceCount()).isEqualTo(0);
     }
 
-    /**
-     * An AsyncExecutionController for testing purpose, which integrates with basic buffer
-     * mechanism.
-     */
-    static class TestAsyncExecutionController<R, K> extends AsyncExecutionController<R, K> {
+    @Test
+    void testRecordsRunInOrder() {
+        AsyncExecutionController<String, String> aec =
+                new AsyncExecutionController<>(new SyncMailboxExecutor(), new TestStateExecutor());
+        TestUnderlyingState underlyingState = new TestUnderlyingState();
+        TestValueState valueState = new TestValueState(aec, underlyingState);
+        AtomicInteger output = new AtomicInteger();
+        Runnable userCode =

Review Comment:
   👍I extracted those codes into a `@BeforeEach` function.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1560382534


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    /**
+     * The batch size. When the number of state requests in the active buffer exceeds the batch
+     * size, a batched state execution would be triggered.
+     */
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /**
+     * The mailbox executor borrowed from {@code StreamTask}. Keeping the reference of
+     * mailboxExecutor here is to restrict the number of in-flight records, when the number of
+     * in-flight records > {@link #maxInFlightRecordNum}, the newly entering records would be
+     * blocked.
+     */
+    private final MailboxExecutor mailboxExecutor;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /** The buffer to store the state requests to execute in batch. */
+    StateRequestsBuffer<R, K> stateRequestsBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.stateRequestsBuffer = new StateRequestsBuffer<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(record, key, this::disposeContext);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Dispose a context.
+     *
+     * @param toDispose the context to dispose.
+     */
+    public void disposeContext(RecordContext<R, K> toDispose) {
+        keyAccountingUnit.release(toDispose.getRecord(), toDispose.getKey());
+        inFlightRecordNum.decrementAndGet();
+        RecordContext<R, K> nextRecordCtx =
+                stateRequestsBuffer.tryMigrateSpecificOne(toDispose.getKey());
+        if (nextRecordCtx != null) {
+            Preconditions.checkState(
+                    tryOccupyKey(nextRecordCtx),
+                    String.format("key(%s) is already occupied.", nextRecordCtx.getKey()));
+        }
+    }
+
+    /**
+     * Try to occupy a key by a given context.
+     *
+     * @param recordContext the given context.
+     * @return true if occupy succeed or the key has already occupied by this context.
+     */
+    boolean tryOccupyKey(RecordContext<R, K> recordContext) {
+        boolean occupied = recordContext.isKeyOccupied();
+        if (!occupied
+                && keyAccountingUnit.occupy(recordContext.getRecord(), recordContext.getKey())) {
+            recordContext.setKeyOccupied();
+            occupied = true;
+        }
+        return occupied;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (tryOccupyKey(currentContext)) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToActive(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToBlocking(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    void triggerIfNeeded(boolean force) {
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {
+            return;
+        }
+        List<StateRequest<?, ?, ?>> toRun = stateRequestsBuffer.nextToRun();
+        stateRequestsBuffer.clearActiveQueue();
+        stateExecutor.executeBatchRequests(toRun);
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isKeyOccupied()) {
+            return;
+        }
+        RecordContext<R, K> storedContext = currentContext;
+        // 2. If the state request is for a newly entered record, the in-flight record number should
+        // be less than the max in-flight record number.
+        // Note: the currentContext may be updated by {@code StateFutureFactory#build}.
+        try {
+            while (inFlightRecordNum.get() > maxInFlightRecordNum) {

Review Comment:
   `inFlightRecordNum` is the records in AEC, including the records in active buffer and blocking buffer.
   And the `inFlightRecordNum == keyAccountingUnit.occupiedCount` may not always be true.
   
   I rewrited the description and added some asserts in `testRecordsRunInOrder` and `testBasicRun`.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "Zakelly (via GitHub)" <gi...@apache.org>.
Zakelly commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1560429469


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -165,6 +215,31 @@ <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
      * @param force whether to trigger requests in force.
      */
     void triggerIfNeeded(boolean force) {
-        // TODO: implement the trigger logic.
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {

Review Comment:
   Another thing comes to my mind. The timeout trigger is needed here. How about adding a TODO here?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    /**
+     * The batch size. When the number of state requests in the active buffer exceeds the batch
+     * size, a batched state execution would be triggered.
+     */
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /**
+     * The mailbox executor borrowed from {@code StreamTask}. Keeping the reference of
+     * mailboxExecutor here is to restrict the number of in-flight records, when the number of
+     * in-flight records > {@link #maxInFlightRecordNum}, the newly entering records would be
+     * blocked.
+     */
+    private final MailboxExecutor mailboxExecutor;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /** The buffer to store the state requests to execute in batch. */
+    StateRequestsBuffer<R, K> stateRequestsBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.stateRequestsBuffer = new StateRequestsBuffer<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(record, key, this::disposeContext);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Dispose a context.
+     *
+     * @param toDispose the context to dispose.
+     */
+    public void disposeContext(RecordContext<R, K> toDispose) {
+        keyAccountingUnit.release(toDispose.getRecord(), toDispose.getKey());
+        inFlightRecordNum.decrementAndGet();
+        RecordContext<R, K> nextRecordCtx =
+                stateRequestsBuffer.tryMigrateSpecificOne(toDispose.getKey());
+        if (nextRecordCtx != null) {
+            Preconditions.checkState(
+                    tryOccupyKey(nextRecordCtx),
+                    String.format("key(%s) is already occupied.", nextRecordCtx.getKey()));
+        }
+    }
+
+    /**
+     * Try to occupy a key by a given context.
+     *
+     * @param recordContext the given context.
+     * @return true if occupy succeed or the key has already occupied by this context.
+     */
+    boolean tryOccupyKey(RecordContext<R, K> recordContext) {
+        boolean occupied = recordContext.isKeyOccupied();
+        if (!occupied
+                && keyAccountingUnit.occupy(recordContext.getRecord(), recordContext.getKey())) {
+            recordContext.setKeyOccupied();
+            occupied = true;
+        }
+        return occupied;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (tryOccupyKey(currentContext)) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToActive(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToBlocking(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    void triggerIfNeeded(boolean force) {
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {
+            return;
+        }
+        List<StateRequest<?, ?, ?>> toRun = stateRequestsBuffer.nextToRun();
+        stateRequestsBuffer.clearActiveQueue();
+        stateExecutor.executeBatchRequests(toRun);
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isKeyOccupied()) {
+            return;
+        }
+        RecordContext<R, K> storedContext = currentContext;
+        // 2. If the state request is for a newly entered record, the in-flight record number should
+        // be less than the max in-flight record number.
+        // Note: the currentContext may be updated by {@code StateFutureFactory#build}.
+        try {
+            while (inFlightRecordNum.get() > maxInFlightRecordNum) {
+                if (!mailboxExecutor.tryYield()) {
+                    triggerIfNeeded(true);
+                    Thread.sleep(50);

Review Comment:
   Yet I thought this `sleep` is meaningful for preventing the CPU keep running with 100% usage. I think sleep for `1ms` is better.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestBuffer.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import oshi.annotation.concurrent.NotThreadSafe;
+
+import javax.annotation.Nullable;
+
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A buffer to hold state requests to execute state requests in batch.
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+@NotThreadSafe
+public class StateRequestBuffer<R, K> {
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeQueue;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final Map<K, Deque<StateRequest<K, ?, ?>>> blockingQueue;
+
+    /** The number of state requests in blocking queue. */
+    int blockingQueueSize;
+
+    public StateRequestBuffer() {
+        this.activeQueue = new LinkedList<>();
+        this.blockingQueue = new HashMap<>();
+        this.blockingQueueSize = 0;
+    }
+
+    void enqueueToActive(StateRequest<K, ?, ?> request) {
+        activeQueue.add(request);
+    }
+
+    void enqueueToBlocking(StateRequest<K, ?, ?> request) {
+        blockingQueue
+                .computeIfAbsent(request.getRecordContext().getKey(), k -> new LinkedList<>())
+                .add(request);
+        blockingQueueSize++;
+    }
+
+    /**
+     * Try to migrate one state request with specific key from blocking queue to active queue.
+     *
+     * @param key The key to release, the other records with this key is no longer blocking.
+     * @return The first record context with the same key in blocking queue, null if no such record.
+     */
+    @Nullable
+    RecordContext<R, K> tryMigrateSpecificOne(K key) {
+        if (!blockingQueue.containsKey(key)) {
+            return null;
+        }
+
+        StateRequest<K, ?, ?> stateRequest = blockingQueue.get(key).getFirst();
+        activeQueue.add(stateRequest);
+        blockingQueue.get(key).removeFirst();
+        if (blockingQueue.get(key).isEmpty()) {
+            blockingQueue.remove(key);
+        }
+        blockingQueueSize--;
+        return (RecordContext<R, K>) stateRequest.getRecordContext();
+    }
+
+    /**
+     * Get the number of state requests of blocking queue in constant-time.
+     *
+     * @return the number of state requests of blocking queue.
+     */
+    @VisibleForTesting
+    int blockingQueueSize() {
+        return blockingQueueSize;
+    }
+
+    /**
+     * Get the number of state requests of active queue in constant-time.
+     *
+     * @return the number of state requests of active queue.
+     */
+    @VisibleForTesting
+    int activeQueueSize() {
+        return activeQueue.size();
+    }
+
+    /**
+     * Try to pop N state requests from active queue, if the size of active queue is less than N,
+     * return all the requests in active queue.
+     *
+     * @param N the number of state requests to pop.
+     * @return A list of state requests.
+     */
+    List<StateRequest<?, ?, ?>> popN(int N) {

Review Comment:
   `popActive` ?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestBuffer.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import oshi.annotation.concurrent.NotThreadSafe;

Review Comment:
   Should be `javax.annotation.concurrent.NotThreadSafe` ?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestBuffer.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import oshi.annotation.concurrent.NotThreadSafe;
+
+import javax.annotation.Nullable;
+
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A buffer to hold state requests to execute state requests in batch.
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+@NotThreadSafe

Review Comment:
   Better add some description about only manipulating this class within `task thread`



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestBuffer.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import oshi.annotation.concurrent.NotThreadSafe;
+
+import javax.annotation.Nullable;
+
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A buffer to hold state requests to execute state requests in batch.
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+@NotThreadSafe
+public class StateRequestBuffer<R, K> {
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeQueue;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final Map<K, Deque<StateRequest<K, ?, ?>>> blockingQueue;
+
+    /** The number of state requests in blocking queue. */
+    int blockingQueueSize;
+
+    public StateRequestBuffer() {
+        this.activeQueue = new LinkedList<>();
+        this.blockingQueue = new HashMap<>();
+        this.blockingQueueSize = 0;
+    }
+
+    void enqueueToActive(StateRequest<K, ?, ?> request) {
+        activeQueue.add(request);
+    }
+
+    void enqueueToBlocking(StateRequest<K, ?, ?> request) {
+        blockingQueue
+                .computeIfAbsent(request.getRecordContext().getKey(), k -> new LinkedList<>())
+                .add(request);
+        blockingQueueSize++;
+    }
+
+    /**
+     * Try to migrate one state request with specific key from blocking queue to active queue.
+     *
+     * @param key The key to release, the other records with this key is no longer blocking.
+     * @return The first record context with the same key in blocking queue, null if no such record.
+     */
+    @Nullable
+    RecordContext<R, K> tryMigrateSpecificOne(K key) {

Review Comment:
   How about naming this `tryActivateOneByKey` or else? The 'migrate' seems confusing.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1560378830


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    /**
+     * The batch size. When the number of state requests in the active buffer exceeds the batch
+     * size, a batched state execution would be triggered.
+     */
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /**
+     * The mailbox executor borrowed from {@code StreamTask}. Keeping the reference of
+     * mailboxExecutor here is to restrict the number of in-flight records, when the number of
+     * in-flight records > {@link #maxInFlightRecordNum}, the newly entering records would be
+     * blocked.
+     */
+    private final MailboxExecutor mailboxExecutor;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /** The buffer to store the state requests to execute in batch. */
+    StateRequestsBuffer<R, K> stateRequestsBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.stateRequestsBuffer = new StateRequestsBuffer<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(record, key, this::disposeContext);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Dispose a context.
+     *
+     * @param toDispose the context to dispose.
+     */
+    public void disposeContext(RecordContext<R, K> toDispose) {
+        keyAccountingUnit.release(toDispose.getRecord(), toDispose.getKey());
+        inFlightRecordNum.decrementAndGet();
+        RecordContext<R, K> nextRecordCtx =
+                stateRequestsBuffer.tryMigrateSpecificOne(toDispose.getKey());
+        if (nextRecordCtx != null) {
+            Preconditions.checkState(
+                    tryOccupyKey(nextRecordCtx),
+                    String.format("key(%s) is already occupied.", nextRecordCtx.getKey()));
+        }
+    }
+
+    /**
+     * Try to occupy a key by a given context.
+     *
+     * @param recordContext the given context.
+     * @return true if occupy succeed or the key has already occupied by this context.
+     */
+    boolean tryOccupyKey(RecordContext<R, K> recordContext) {
+        boolean occupied = recordContext.isKeyOccupied();
+        if (!occupied
+                && keyAccountingUnit.occupy(recordContext.getRecord(), recordContext.getKey())) {
+            recordContext.setKeyOccupied();
+            occupied = true;
+        }
+        return occupied;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (tryOccupyKey(currentContext)) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToActive(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToBlocking(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    void triggerIfNeeded(boolean force) {
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {
+            return;
+        }
+        List<StateRequest<?, ?, ?>> toRun = stateRequestsBuffer.nextToRun();
+        stateRequestsBuffer.clearActiveQueue();
+        stateExecutor.executeBatchRequests(toRun);
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isKeyOccupied()) {
+            return;
+        }
+        RecordContext<R, K> storedContext = currentContext;
+        // 2. If the state request is for a newly entered record, the in-flight record number should
+        // be less than the max in-flight record number.
+        // Note: the currentContext may be updated by {@code StateFutureFactory#build}.
+        try {
+            while (inFlightRecordNum.get() > maxInFlightRecordNum) {
+                if (!mailboxExecutor.tryYield()) {
+                    triggerIfNeeded(true);
+                    Thread.sleep(50);
+                }
+            }
+            // 3. Ensure the currentContext is restored.
+            setCurrentContext(storedContext);
+            inFlightRecordNum.incrementAndGet();
+        } catch (InterruptedException e) {

Review Comment:
   👍good catch, `Thread.sleep(50);` is deleted, so the `InterruptedException` wouldn't throw.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1559145024


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    private final MailboxExecutor mailboxExecutor;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeBuffer;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> blockingBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.activeBuffer = new LinkedList<>();
+        this.blockingBuffer = new LinkedList<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(keyAccountingUnit, inFlightRecordNum, record, key);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * <p>This method should only be invoked in task-thread based on the assumption of all callbacks
+     * should be executed in mailbox. Please make this method thread-safe if the assumption changes.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequest.RequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (currentContext.tryOccupyKey()) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        activeBuffer.add(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        blockingBuffer.add(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    @VisibleForTesting
+    void triggerIfNeeded(boolean force) {
+        if (!force && activeBuffer.size() < batchSize) {
+            return;
+        }
+        migrateBlockingToActive();
+        List<StateRequest<?, ?, ?>> toRun = new LinkedList<>(activeBuffer);
+        activeBuffer.clear();
+        stateExecutor.executeBatchRequests(toRun);
+        // migrate state requests in blocking buffer to active buffer actively, let the requests
+        // that enter the buffer first be processed first.
+        migrateBlockingToActive();
+    }
+
+    /** Migrate the blocking requests to the active buffer. */
+    @VisibleForTesting
+    void migrateBlockingToActive() {
+        Iterator<StateRequest<K, ?, ?>> blockingIter = blockingBuffer.iterator();
+        while (blockingIter.hasNext()) {
+            StateRequest<K, ?, ?> stateRequest = blockingIter.next();
+            if (stateRequest.getRecordContext().tryOccupyKey()) {
+                insertActiveBuffer(stateRequest);
+                blockingIter.remove();
+            }
+        }
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isInBuffer()) {

Review Comment:
   `keyOccupied` is enough, thanks for the suggestion.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1559152061


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    private final MailboxExecutor mailboxExecutor;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeBuffer;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> blockingBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.activeBuffer = new LinkedList<>();
+        this.blockingBuffer = new LinkedList<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(keyAccountingUnit, inFlightRecordNum, record, key);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * <p>This method should only be invoked in task-thread based on the assumption of all callbacks
+     * should be executed in mailbox. Please make this method thread-safe if the assumption changes.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequest.RequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (currentContext.tryOccupyKey()) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        activeBuffer.add(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        blockingBuffer.add(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    @VisibleForTesting
+    void triggerIfNeeded(boolean force) {
+        if (!force && activeBuffer.size() < batchSize) {
+            return;
+        }
+        migrateBlockingToActive();
+        List<StateRequest<?, ?, ?>> toRun = new LinkedList<>(activeBuffer);
+        activeBuffer.clear();
+        stateExecutor.executeBatchRequests(toRun);
+        // migrate state requests in blocking buffer to active buffer actively, let the requests
+        // that enter the buffer first be processed first.
+        migrateBlockingToActive();
+    }
+
+    /** Migrate the blocking requests to the active buffer. */
+    @VisibleForTesting
+    void migrateBlockingToActive() {

Review Comment:
   Thanks for the suggestion, I add a new class `StateRequestsBuffer` which groups state requests in the blocking buffer by key. Migrating one state request from blocking buffer to active buffer will trigger in `RecordContext#disposer`.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1560378400


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    /**
+     * The batch size. When the number of state requests in the active buffer exceeds the batch
+     * size, a batched state execution would be triggered.
+     */
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /**
+     * The mailbox executor borrowed from {@code StreamTask}. Keeping the reference of
+     * mailboxExecutor here is to restrict the number of in-flight records, when the number of
+     * in-flight records > {@link #maxInFlightRecordNum}, the newly entering records would be
+     * blocked.
+     */
+    private final MailboxExecutor mailboxExecutor;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /** The buffer to store the state requests to execute in batch. */
+    StateRequestsBuffer<R, K> stateRequestsBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.stateRequestsBuffer = new StateRequestsBuffer<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(record, key, this::disposeContext);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Dispose a context.
+     *
+     * @param toDispose the context to dispose.
+     */
+    public void disposeContext(RecordContext<R, K> toDispose) {
+        keyAccountingUnit.release(toDispose.getRecord(), toDispose.getKey());
+        inFlightRecordNum.decrementAndGet();
+        RecordContext<R, K> nextRecordCtx =
+                stateRequestsBuffer.tryMigrateSpecificOne(toDispose.getKey());
+        if (nextRecordCtx != null) {
+            Preconditions.checkState(
+                    tryOccupyKey(nextRecordCtx),
+                    String.format("key(%s) is already occupied.", nextRecordCtx.getKey()));
+        }
+    }
+
+    /**
+     * Try to occupy a key by a given context.
+     *
+     * @param recordContext the given context.
+     * @return true if occupy succeed or the key has already occupied by this context.
+     */
+    boolean tryOccupyKey(RecordContext<R, K> recordContext) {
+        boolean occupied = recordContext.isKeyOccupied();
+        if (!occupied
+                && keyAccountingUnit.occupy(recordContext.getRecord(), recordContext.getKey())) {
+            recordContext.setKeyOccupied();
+            occupied = true;
+        }
+        return occupied;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (tryOccupyKey(currentContext)) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToActive(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        stateRequestsBuffer.enqueueToBlocking(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    void triggerIfNeeded(boolean force) {
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {
+            return;
+        }
+        List<StateRequest<?, ?, ?>> toRun = stateRequestsBuffer.nextToRun();
+        stateRequestsBuffer.clearActiveQueue();
+        stateExecutor.executeBatchRequests(toRun);
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isKeyOccupied()) {
+            return;
+        }
+        RecordContext<R, K> storedContext = currentContext;
+        // 2. If the state request is for a newly entered record, the in-flight record number should
+        // be less than the max in-flight record number.
+        // Note: the currentContext may be updated by {@code StateFutureFactory#build}.
+        try {
+            while (inFlightRecordNum.get() > maxInFlightRecordNum) {
+                if (!mailboxExecutor.tryYield()) {
+                    triggerIfNeeded(true);
+                    Thread.sleep(50);

Review Comment:
   After referring to other components' usage of `ailboxExecutor.tryYield` and rethinking this scenario, I removed `Thread.sleep(50);`, the execution speed is controlled by inFlightNumer, forcing sleep does not make sense here.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1560594744


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -165,6 +215,31 @@ <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
      * @param force whether to trigger requests in force.
      */
     void triggerIfNeeded(boolean force) {
-        // TODO: implement the trigger logic.
+        if (!force && stateRequestsBuffer.activeQueueSize() < batchSize) {

Review Comment:
   Thanks for the reminder👍, added.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "Zakelly (via GitHub)" <gi...@apache.org>.
Zakelly commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1558754305


##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    private final MailboxExecutor mailboxExecutor;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeBuffer;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> blockingBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.activeBuffer = new LinkedList<>();
+        this.blockingBuffer = new LinkedList<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(keyAccountingUnit, inFlightRecordNum, record, key);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * <p>This method should only be invoked in task-thread based on the assumption of all callbacks
+     * should be executed in mailbox. Please make this method thread-safe if the assumption changes.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequest.RequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (currentContext.tryOccupyKey()) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        activeBuffer.add(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        blockingBuffer.add(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    @VisibleForTesting
+    void triggerIfNeeded(boolean force) {
+        if (!force && activeBuffer.size() < batchSize) {
+            return;
+        }
+        migrateBlockingToActive();
+        List<StateRequest<?, ?, ?>> toRun = new LinkedList<>(activeBuffer);
+        activeBuffer.clear();
+        stateExecutor.executeBatchRequests(toRun);
+        // migrate state requests in blocking buffer to active buffer actively, let the requests
+        // that enter the buffer first be processed first.
+        migrateBlockingToActive();
+    }
+
+    /** Migrate the blocking requests to the active buffer. */
+    @VisibleForTesting
+    void migrateBlockingToActive() {
+        Iterator<StateRequest<K, ?, ?>> blockingIter = blockingBuffer.iterator();
+        while (blockingIter.hasNext()) {
+            StateRequest<K, ?, ?> stateRequest = blockingIter.next();
+            if (stateRequest.getRecordContext().tryOccupyKey()) {
+                insertActiveBuffer(stateRequest);
+                blockingIter.remove();
+            }
+        }
+    }
+
+    private void seizeCapacity() {
+        // 1. Check if the record is already in buffer. If yes, this indicates that it is a state
+        // request resulting from a callback statement, otherwise, it signifies the initial state
+        // request
+        // for a newly entered record.
+        if (currentContext.isInBuffer()) {

Review Comment:
   Is `keyOccupied` enough for this senario?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/RecordContext.java:
##########
@@ -0,0 +1,138 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import javax.annotation.Nullable;
+
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * A context that preserves the necessary variables required by each operation, all operations for
+ * one record will share the same element context.
+ *
+ * <p>Reference counting mechanism, please refer to {@link ContextStateFutureImpl}.
+ *
+ * @param <R> The type of the record that extends {@code
+ *     org.apache.flink.streaming.runtime.streamrecord.StreamElement}.
+ * @param <K> The type of the key inside the record.
+ */
+public class RecordContext<R, K> extends ReferenceCounted {
+
+    /** The record to be processed. */
+    @Nullable private final R record;
+
+    /** The key inside the record. */
+    private final K key;
+
+    /** Whether this Record(Context) has occupied the corresponding key. */
+    private volatile boolean keyOccupied;
+
+    /**
+     * The KeyAccountingUnit that this record context will interact with. The reason why it keeps
+     * this reference here is that it would release the key within {@link
+     * #referenceCountReachedZero()}, which may be called once the ref count reaches zero in any
+     * thread.
+     */
+    private final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    /**
+     * Whether the record is already in buffer. If yes, this indicates that it is a state request
+     * resulting from a callback statement, otherwise, it signifies the initial state request for a
+     * newly entered record.
+     */
+    private volatile boolean inBuffer;
+
+    /**
+     * The reference of {@link AsyncExecutionController#inFlightRecordNum} that this record context
+     * will interact with. This reference is kept here to update related metrics when a record
+     * context is released.
+     */
+    private final AtomicInteger inflightRecordNumRef;
+
+    RecordContext(
+            KeyAccountingUnit<R, K> keyAccountingUnit,
+            AtomicInteger inflightRecordNumRef,
+            R record,
+            K key) {
+        super(0);
+        this.keyAccountingUnit = keyAccountingUnit;
+        this.inflightRecordNumRef = inflightRecordNumRef;
+        this.record = record;
+        this.key = key;
+        this.keyOccupied = false;
+        this.inBuffer = false;
+    }
+
+    public K getKey() {
+        return this.key;
+    }
+
+    /**
+     * Try to occupy the key via {@link KeyAccountingUnit}. When it has been already occupied once,
+     * the record could continue running. Package-private.
+     *
+     * @return true if occupying succeed.
+     */
+    boolean tryOccupyKey() {
+        return keyOccupied || (keyOccupied = keyAccountingUnit.occupy(record, key));
+    }
+
+    boolean isInBuffer() {
+        return inBuffer;
+    }
+
+    void setInBuffer() {
+        this.inBuffer = true;
+    }
+
+    @Override
+    protected void referenceCountReachedZero() {
+        if (keyOccupied) {
+            keyAccountingUnit.release(record, key);
+            keyOccupied = false;
+            inflightRecordNumRef.decrementAndGet();

Review Comment:
   How about only provide a `disposer` to `RecordContext` in constructor, and let `AEC` defines how to dispose a `RecordContext`? It prevents holding `keyAccountingUnit`  as well as `inflightRecordNumRef`.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionController.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.state.v2.State;
+import org.apache.flink.core.state.InternalStateFuture;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The Async Execution Controller (AEC) receives processing requests from operators, and put them
+ * into execution according to some strategies.
+ *
+ * <p>It is responsible for:
+ * <li>Preserving the sequence of elements bearing the same key by delaying subsequent requests
+ *     until the processing of preceding ones is finalized.
+ * <li>Tracking the in-flight data(records) and blocking the input if too much data in flight
+ *     (back-pressure). It invokes {@link MailboxExecutor#yield()} to pause current operations,
+ *     allowing for the execution of callbacks (mails in Mailbox).
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+public class AsyncExecutionController<R, K> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionController.class);
+
+    public static final int DEFAULT_BATCH_SIZE = 1000;
+    public static final int DEFAULT_MAX_IN_FLIGHT_RECORD_NUM = 6000;
+
+    private final int batchSize;
+
+    /** The max allow number of in-flight records. */
+    private final int maxInFlightRecordNum;
+
+    /** The key accounting unit which is used to detect the key conflict. */
+    final KeyAccountingUnit<R, K> keyAccountingUnit;
+
+    private final MailboxExecutor mailboxExecutor;
+
+    /**
+     * A factory to build {@link org.apache.flink.core.state.InternalStateFuture}, this will auto
+     * wire the created future with mailbox executor. Also conducting the context switch.
+     */
+    private final StateFutureFactory<R, K> stateFutureFactory;
+
+    /** The state executor where the {@link StateRequest} is actually executed. */
+    final StateExecutor stateExecutor;
+
+    /** The corresponding context that currently runs in task thread. */
+    RecordContext<R, K> currentContext;
+
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeBuffer;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> blockingBuffer;
+
+    /** The number of in-flight records. */
+    final AtomicInteger inFlightRecordNum;
+
+    public AsyncExecutionController(MailboxExecutor mailboxExecutor, StateExecutor stateExecutor) {
+        this(mailboxExecutor, stateExecutor, DEFAULT_BATCH_SIZE, DEFAULT_MAX_IN_FLIGHT_RECORD_NUM);
+    }
+
+    public AsyncExecutionController(
+            MailboxExecutor mailboxExecutor,
+            StateExecutor stateExecutor,
+            int batchSize,
+            int maxInFlightRecords) {
+        this.keyAccountingUnit = new KeyAccountingUnit<>();
+        this.mailboxExecutor = mailboxExecutor;
+        this.stateFutureFactory = new StateFutureFactory<>(this, mailboxExecutor);
+        this.stateExecutor = stateExecutor;
+        this.batchSize = batchSize;
+        this.maxInFlightRecordNum = maxInFlightRecords;
+        this.activeBuffer = new LinkedList<>();
+        this.blockingBuffer = new LinkedList<>();
+        this.inFlightRecordNum = new AtomicInteger(0);
+        LOG.info("Create AsyncExecutionController: maxInFlightRecordsNum {}", maxInFlightRecords);
+    }
+
+    /**
+     * Build a new context based on record and key. Also wired with internal {@link
+     * KeyAccountingUnit}.
+     *
+     * @param record the given record.
+     * @param key the given key.
+     * @return the built record context.
+     */
+    public RecordContext<R, K> buildContext(R record, K key) {
+        return new RecordContext<>(keyAccountingUnit, inFlightRecordNum, record, key);
+    }
+
+    /**
+     * Each time before a code segment (callback) is about to run in mailbox (task thread), this
+     * method should be called to switch a context in AEC.
+     *
+     * @param switchingContext the context to switch.
+     */
+    public void setCurrentContext(RecordContext<R, K> switchingContext) {
+        currentContext = switchingContext;
+    }
+
+    /**
+     * Submit a {@link StateRequest} to this AEC and trigger if needed.
+     *
+     * <p>This method should only be invoked in task-thread based on the assumption of all callbacks
+     * should be executed in mailbox. Please make this method thread-safe if the assumption changes.
+     *
+     * @param state the state to request.
+     * @param type the type of this request.
+     * @param payload the payload input for this request.
+     * @return the state future.
+     */
+    public <IN, OUT> InternalStateFuture<OUT> handleRequest(
+            @Nullable State state, StateRequest.RequestType type, @Nullable IN payload) {
+        // Step 1: build state future & assign context.
+        InternalStateFuture<OUT> stateFuture = stateFutureFactory.build(currentContext);
+
+        StateRequest<K, IN, OUT> request =
+                new StateRequest<>(state, type, payload, stateFuture, currentContext);
+
+        // Step 2: try to seize the capacity, if the current in-flight records exceeds the limit,
+        // block the current state request from entering until some buffered requests are processed.
+        seizeCapacity();
+
+        // Step 3: try to occupy the key and place it into right buffer.
+        if (currentContext.tryOccupyKey()) {
+            insertActiveBuffer(request);
+        } else {
+            insertBlockingBuffer(request);
+        }
+        // Step 4: trigger the (active) buffer if needed.
+        triggerIfNeeded(false);
+        return stateFuture;
+    }
+
+    <IN, OUT> void insertActiveBuffer(StateRequest<K, IN, OUT> request) {
+        activeBuffer.add(request);
+    }
+
+    <IN, OUT> void insertBlockingBuffer(StateRequest<K, IN, OUT> request) {
+        blockingBuffer.add(request);
+    }
+
+    /**
+     * Trigger a batch of requests.
+     *
+     * @param force whether to trigger requests in force.
+     */
+    @VisibleForTesting
+    void triggerIfNeeded(boolean force) {
+        if (!force && activeBuffer.size() < batchSize) {
+            return;
+        }
+        migrateBlockingToActive();
+        List<StateRequest<?, ?, ?>> toRun = new LinkedList<>(activeBuffer);
+        activeBuffer.clear();
+        stateExecutor.executeBatchRequests(toRun);
+        // migrate state requests in blocking buffer to active buffer actively, let the requests
+        // that enter the buffer first be processed first.
+        migrateBlockingToActive();
+    }
+
+    /** Migrate the blocking requests to the active buffer. */
+    @VisibleForTesting
+    void migrateBlockingToActive() {

Review Comment:
   Personally I'd suggest a queueing mechanism, meaning that each `blocked request` will queue under one key. While the `active request/context`'s reference counting reached zero, it pop one request from the corresponding queue of that key and put that into `active buffer`. I think this is a high-performance implementation.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia merged PR #24633:
URL: https://github.com/apache/flink/pull/24633


-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on PR #24633:
URL: https://github.com/apache/flink/pull/24633#issuecomment-2050847516

   @Zakelly Thanks for the review, updated and squashed.


-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-35024][Runtime/State] Implement the record buffer of AsyncExecutionController [flink]

Posted by "masteryhx (via GitHub)" <gi...@apache.org>.
masteryhx commented on code in PR #24633:
URL: https://github.com/apache/flink/pull/24633#discussion_r1562207787


##########
flink-runtime/src/test/java/org/apache/flink/runtime/asyncprocessing/AsyncExecutionControllerTest.java:
##########
@@ -152,66 +148,168 @@ void testBasicRun() {
 
         // Single-step run for another key.
         // Firstly, the user code generates value get in active buffer.
-        assertThat(aec.activeBuffer.size()).isEqualTo(1);
+        assertThat(aec.stateRequestsBuffer.activeQueueSize()).isEqualTo(1);
         assertThat(aec.keyAccountingUnit.occupiedCount()).isEqualTo(1);
+        assertThat(aec.inFlightRecordNum.get()).isEqualTo(1);
         aec.triggerIfNeeded(true);
         // After running, the value update is in active buffer.
-        assertThat(aec.activeBuffer.size()).isEqualTo(1);
+        assertThat(aec.stateRequestsBuffer.activeQueueSize()).isEqualTo(1);
         assertThat(aec.keyAccountingUnit.occupiedCount()).isEqualTo(1);
+        assertThat(aec.inFlightRecordNum.get()).isEqualTo(1);
         aec.triggerIfNeeded(true);
         // Value update finishes.
-        assertThat(aec.activeBuffer.size()).isEqualTo(0);
+        assertThat(aec.stateRequestsBuffer.activeQueueSize()).isEqualTo(0);
         assertThat(aec.keyAccountingUnit.occupiedCount()).isEqualTo(0);
+        assertThat(aec.inFlightRecordNum.get()).isEqualTo(0);
         assertThat(output.get()).isEqualTo(1);
         assertThat(recordContext4.getReferenceCount()).isEqualTo(0);
     }
 
-    /**
-     * An AsyncExecutionController for testing purpose, which integrates with basic buffer
-     * mechanism.
-     */
-    static class TestAsyncExecutionController<R, K> extends AsyncExecutionController<R, K> {
+    @Test
+    void testRecordsRunInOrder() {
+        AsyncExecutionController<String, String> aec =
+                new AsyncExecutionController<>(new SyncMailboxExecutor(), new TestStateExecutor());
+        TestUnderlyingState underlyingState = new TestUnderlyingState();
+        TestValueState valueState = new TestValueState(aec, underlyingState);
+        AtomicInteger output = new AtomicInteger();
+        Runnable userCode =

Review Comment:
   The logic seems same as other tests, could this be a seprate method ?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestBuffer.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A buffer to hold state requests to execute state requests in batch, which can only be manipulated
+ * within task thread.
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+@NotThreadSafe
+public class StateRequestBuffer<R, K> {
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeQueue;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final Map<K, Deque<StateRequest<K, ?, ?>>> blockingQueue;
+
+    /** The number of state requests in blocking queue. */
+    int blockingQueueSize;
+
+    public StateRequestBuffer() {
+        this.activeQueue = new LinkedList<>();
+        this.blockingQueue = new HashMap<>();
+        this.blockingQueueSize = 0;
+    }
+
+    void enqueueToActive(StateRequest<K, ?, ?> request) {
+        activeQueue.add(request);
+    }
+
+    void enqueueToBlocking(StateRequest<K, ?, ?> request) {
+        blockingQueue
+                .computeIfAbsent(request.getRecordContext().getKey(), k -> new LinkedList<>())
+                .add(request);
+        blockingQueueSize++;
+    }
+
+    /**
+     * Try to pull one state request with specific key from blocking queue to active queue.
+     *
+     * @param key The key to release, the other records with this key is no longer blocking.
+     * @return The first record context with the same key in blocking queue, null if no such record.
+     */
+    @Nullable
+    RecordContext<R, K> tryActivateOneByKey(K key) {
+        if (!blockingQueue.containsKey(key)) {
+            return null;
+        }
+
+        StateRequest<K, ?, ?> stateRequest = blockingQueue.get(key).getFirst();

Review Comment:
   How about just using `removeFirst()` and get `StateRequest` here ?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/StateRequestBuffer.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.runtime.asyncprocessing;
+
+import org.apache.flink.annotation.VisibleForTesting;
+
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A buffer to hold state requests to execute state requests in batch, which can only be manipulated
+ * within task thread.
+ *
+ * @param <R> the type of the record
+ * @param <K> the type of the key
+ */
+@NotThreadSafe
+public class StateRequestBuffer<R, K> {
+    /**
+     * The state requests in this buffer could be executed when the buffer is full or configured
+     * batch size is reached. All operations on this buffer must be invoked in task thread.
+     */
+    final LinkedList<StateRequest<K, ?, ?>> activeQueue;
+
+    /**
+     * The requests in that should wait until all preceding records with identical key finishing its
+     * execution. After which the queueing requests will move into the active buffer. All operations
+     * on this buffer must be invoked in task thread.
+     */
+    final Map<K, Deque<StateRequest<K, ?, ?>>> blockingQueue;
+
+    /** The number of state requests in blocking queue. */
+    int blockingQueueSize;
+
+    public StateRequestBuffer() {
+        this.activeQueue = new LinkedList<>();
+        this.blockingQueue = new HashMap<>();
+        this.blockingQueueSize = 0;
+    }
+
+    void enqueueToActive(StateRequest<K, ?, ?> request) {
+        activeQueue.add(request);
+    }
+
+    void enqueueToBlocking(StateRequest<K, ?, ?> request) {
+        blockingQueue
+                .computeIfAbsent(request.getRecordContext().getKey(), k -> new LinkedList<>())
+                .add(request);
+        blockingQueueSize++;
+    }
+
+    /**
+     * Try to pull one state request with specific key from blocking queue to active queue.
+     *
+     * @param key The key to release, the other records with this key is no longer blocking.
+     * @return The first record context with the same key in blocking queue, null if no such record.
+     */
+    @Nullable
+    RecordContext<R, K> tryActivateOneByKey(K key) {
+        if (!blockingQueue.containsKey(key)) {
+            return null;
+        }
+
+        StateRequest<K, ?, ?> stateRequest = blockingQueue.get(key).getFirst();
+        activeQueue.add(stateRequest);
+        blockingQueue.get(key).removeFirst();
+        if (blockingQueue.get(key).isEmpty()) {
+            blockingQueue.remove(key);
+        }
+        blockingQueueSize--;
+        return (RecordContext<R, K>) stateRequest.getRecordContext();

Review Comment:
   minor suggestion: add `SuppressWarnings` for this ?



-- 
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: issues-unsubscribe@flink.apache.org

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