HuangXingBo commented on code in PR #47:
URL: https://github.com/apache/flink-agents/pull/47#discussion_r2179519337


##########
plan/src/main/java/org/apache/flink/agents/plan/WorkflowPlan.java:
##########
@@ -19,23 +19,56 @@
 package org.apache.flink.agents.plan;
 
 import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.plan.serializer.WorkflowPlanJsonDeserializer;
+import org.apache.flink.agents.plan.serializer.WorkflowPlanJsonSerializer;
+import 
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+import 
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import 
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize;
 
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
 import java.util.List;
 import java.util.Map;
 
 /** Workflow plan compiled from user defined workflow. */
-public class WorkflowPlan {
-    private final Map<Class<? extends Event>, List<Action>> actions;
+@JsonSerialize(using = WorkflowPlanJsonSerializer.class)
+@JsonDeserialize(using = WorkflowPlanJsonDeserializer.class)
+public class WorkflowPlan implements Serializable {
+    private Map<String, Action> actions;
+    private Map<Class<? extends Event>, List<Action>> eventTriggerActions;
 
-    public WorkflowPlan(Map<Class<? extends Event>, List<Action>> actions) {
+    public WorkflowPlan() {}
+
+    public WorkflowPlan(
+            Map<String, Action> actions,
+            Map<Class<? extends Event>, List<Action>> eventTriggerActions) {
         this.actions = actions;
+        this.eventTriggerActions = eventTriggerActions;
     }
 
-    public List<Action> getAction(Class<? extends Event> type) {
-        return actions.get(type);
+    public Map<String, Action> getActions() {
+        return actions;
     }
 
-    public Map<Class<? extends Event>, List<Action>> getActions() {
-        return actions;
+    public Map<Class<? extends Event>, List<Action>> getEventTriggerActions() {
+        return eventTriggerActions;
+    }
+
+    public List<Action> getEventTriggerActions(Class<? extends Event> event) {
+        return eventTriggerActions.get(event);
+    }
+
+    private void writeObject(ObjectOutputStream out) throws IOException {
+        String serializedStr = new ObjectMapper().writeValueAsString(this);

Review Comment:
   new ObjectMapper() -> static final field?



##########
plan/src/main/java/org/apache/flink/agents/plan/serializer/ActionJsonDeserializer.java:
##########
@@ -0,0 +1,118 @@
+/*
+ * 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.agents.plan.serializer;
+
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.plan.Action;
+import org.apache.flink.agents.plan.Function;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser;
+import 
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.DeserializationContext;
+import 
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
+import 
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Custom deserializer for {@link Action} that handles the deserialization of 
the function and event
+ * types.
+ */
+public class ActionJsonDeserializer extends StdDeserializer<Action> {
+
+    public ActionJsonDeserializer() {
+        super(Action.class);
+    }
+
+    @Override
+    public Action deserialize(JsonParser jsonParser, DeserializationContext 
deserializationContext)
+            throws IOException {
+        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
+        String name = node.get("name").asText();
+
+        // Deserialize the function based on its type
+        JsonNode execNode = node.get("exec");
+        String funcType = execNode.get("func_type").asText();
+        Function func;
+        if (JavaFunction.class.getSimpleName().equals(funcType)) {
+            func = deserializeJavaFunction(execNode);
+        } else if (PythonFunction.class.getSimpleName().equals(funcType)) {
+            func = deserializePythonFunction(execNode);
+        } else {
+            throw new IOException("Unsupported function type: " + funcType);
+        }
+
+        // Deserialize listenEventTypes
+        List<Class<? extends Event>> listenEventTypes = new ArrayList<>();
+        node.get("listenEventTypes")

Review Comment:
   Why is a camel name here, while other places use snake name?



##########
runtime/pom.xml:
##########
@@ -29,29 +29,62 @@ under the License.
     <name>Flink Agents : Runtime</name>
 
     <dependencies>
+        <!-- flink agents -->
+        <dependency>
+            <groupId>org.apache.flink</groupId>
+            <artifactId>flink-agents-api</artifactId>
+            <version>0.1-SNAPSHOT</version>

Review Comment:
   -> ${project.version}



##########
runtime/src/main/java/org/apache/flink/agents/runtime/PythonActionExecutor.java:
##########
@@ -39,13 +40,13 @@ public class PythonActionExecutor {
     private static final String FLINK_RUNNER_CONTEXT_VAR_NAME = 
"flink_runner_context";
 
     private final PythonEnvironmentManager environmentManager;
-    private final PythonRunnerContext runnerContext;
+    private final PythonRunnerContextImpl runnerContext;
 
     private PythonInterpreter interpreter;
 
     public PythonActionExecutor(PythonEnvironmentManager environmentManager) {

Review Comment:
   Could we put python-related components such as pythonevent and 
pythonexecutor in specific subdir?
   



##########
runtime/src/main/java/org/apache/flink/agents/runtime/operator/ActionExecutionOperator.java:
##########
@@ -0,0 +1,271 @@
+/*
+ * 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.agents.runtime.operator;
+
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.plan.Action;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.WorkflowPlan;
+import org.apache.flink.agents.runtime.PythonActionExecutor;
+import org.apache.flink.agents.runtime.PythonEvent;
+import org.apache.flink.agents.runtime.context.RunnerContextImpl;
+import org.apache.flink.agents.runtime.env.PythonEnvironmentManager;
+import org.apache.flink.agents.runtime.message.EventMessage;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.python.env.PythonDependencyInfo;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.ChainingStrategy;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.OutputTag;
+import org.apache.flink.util.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * An operator that executes the actions defined in the workflow plan. It 
receives {@link
+ * EventMessage} from the {@link FeedbackOperator}, invokes the corresponding 
action, and collects
+ * the action output event. For events of type {@link OutputEvent}, the output 
will be sent to a
+ * side output; for all other event types, it will be forwarded to the {@link 
FeedbackSinkOperator}.
+ *
+ * <p>Note that this operator ensures that only one {@link Event} is processed 
at a time per key.
+ *
+ * <p>NOTE: This code is adapted from the <a
+ * href="https://github.com/apache/flink-statefun";>flink-statefun</a>.
+ *
+ * @param <K> The type of the key of input event.
+ */
+public class ActionExecutionOperator<K> extends 
AbstractStreamOperator<EventMessage<K>>
+        implements OneInputStreamOperator<EventMessage<K>, EventMessage<K>> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ActionExecutionOperator.class);
+
+    private static final long serialVersionUID = 1L;

Review Comment:
   put before `private static final Logger LOG = 
LoggerFactory.getLogger(ActionExecutionOperator.class);`?



##########
runtime/src/main/java/org/apache/flink/agents/runtime/operator/ActionExecutionOperator.java:
##########
@@ -0,0 +1,271 @@
+/*
+ * 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.agents.runtime.operator;
+
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.plan.Action;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.WorkflowPlan;
+import org.apache.flink.agents.runtime.PythonActionExecutor;
+import org.apache.flink.agents.runtime.PythonEvent;
+import org.apache.flink.agents.runtime.context.RunnerContextImpl;
+import org.apache.flink.agents.runtime.env.PythonEnvironmentManager;
+import org.apache.flink.agents.runtime.message.EventMessage;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.python.env.PythonDependencyInfo;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.ChainingStrategy;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.OutputTag;
+import org.apache.flink.util.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * An operator that executes the actions defined in the workflow plan. It 
receives {@link
+ * EventMessage} from the {@link FeedbackOperator}, invokes the corresponding 
action, and collects
+ * the action output event. For events of type {@link OutputEvent}, the output 
will be sent to a
+ * side output; for all other event types, it will be forwarded to the {@link 
FeedbackSinkOperator}.
+ *
+ * <p>Note that this operator ensures that only one {@link Event} is processed 
at a time per key.
+ *
+ * <p>NOTE: This code is adapted from the <a
+ * href="https://github.com/apache/flink-statefun";>flink-statefun</a>.
+ *
+ * @param <K> The type of the key of input event.
+ */
+public class ActionExecutionOperator<K> extends 
AbstractStreamOperator<EventMessage<K>>
+        implements OneInputStreamOperator<EventMessage<K>, EventMessage<K>> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ActionExecutionOperator.class);
+
+    private static final long serialVersionUID = 1L;
+
+    private final OutputTag<EventMessage<K>> sideOutputTag;
+
+    private transient StreamRecord<EventMessage<K>> reusedStreamRecord;
+
+    private transient StreamRecord<EventMessage<K>> 
reusedSideOutputStreamRecord;
+
+    private final WorkflowPlan workflowPlan;
+
+    /**
+     * If an event with the same key is currently being processed, the newly 
received {@link
+     * InputEvent} should not be processed immediately. It will be added to 
the pending queue and
+     * processed during a periodic timer trigger.
+     */
+    private transient ListState<EventMessage<K>> pendingInputEventsState;
+
+    /** The number of actions that are still pending to be executed for the 
current key. */
+    private transient ValueState<Integer> pendingActionCountState;
+
+    private final TypeInformation<EventMessage<K>> eventMessageTypeInfo;
+
+    // RunnerContext for Java actions
+    private final RunnerContextImpl runnerContext;
+
+    // PythonActionExecutor for Python actions
+    private transient PythonActionExecutor pythonActionExecutor;
+
+    public ActionExecutionOperator(
+            OutputTag<EventMessage<K>> sideOutputTag,
+            WorkflowPlan workflowPlan,
+            TypeInformation<EventMessage<K>> eventMessageTypeInfo) {
+        this.sideOutputTag = sideOutputTag;
+        this.workflowPlan = workflowPlan;
+        this.eventMessageTypeInfo = eventMessageTypeInfo;
+        this.runnerContext = new RunnerContextImpl();
+        this.chainingStrategy = ChainingStrategy.ALWAYS;
+    }
+
+    @Override
+    public void open() throws Exception {
+        super.open();
+
+        reusedStreamRecord = new StreamRecord<>(null);
+        reusedSideOutputStreamRecord = new StreamRecord<>(null);
+
+        // init state
+        ValueStateDescriptor<Integer> pendingActionCountDescriptor =
+                new ValueStateDescriptor<>(
+                        "pendingActionCount", 
TypeInformation.of(Integer.class), 0);
+        pendingActionCountState = 
getRuntimeContext().getState(pendingActionCountDescriptor);
+        ListStateDescriptor<EventMessage<K>> pendingInputEventsDescriptor =
+                new ListStateDescriptor<>("pendingInputEvents", 
eventMessageTypeInfo);
+        pendingInputEventsState = 
getRuntimeContext().getListState(pendingInputEventsDescriptor);
+
+        // init PythonActionExecutor
+        initPythonActionExecutor();
+    }
+
+    @Override
+    public void processElement(StreamRecord<EventMessage<K>> record) throws 
Exception {
+        EventMessage<K> eventMessage = record.getValue();
+        LOG.debug("ActionExecutionOperator receive element {}", eventMessage);
+
+        if (eventMessage.isInputEvent() && !canProcessInputEvent()) {
+            // If the event is an InputEvent and there is already another 
event with the same key
+            // being processed, it will be added to pendingInputEvents and 
processed later.
+            LOG.debug("Add element {} to pending list.", eventMessage);
+            pendingInputEventsState.add(eventMessage);
+            return;
+        }
+
+        processEventMessage(eventMessage);
+        tryProcessPendingInputEvents();
+    }
+
+    private void processEventMessage(EventMessage<K> eventMessage) throws 
Exception {
+        LOG.debug("ActionExecutionOperator process element {}", eventMessage);
+        Event event = eventMessage.getEvent();
+        List<Action> actions = 
workflowPlan.getEventTriggerActions(event.getClass());
+        if (actions != null && !actions.isEmpty()) {
+            // add pending action count for InputEvent.
+            // We should record the number of actions to be processed for each 
event only once.
+            // For InputEvents that must originate from the regular input 
stream, we increment the
+            // action count once before processing the event.
+            // For other Events, which are guaranteed to be generated by an 
action and enter the
+            // feedback loop, we increment the action count once at generation 
time.
+            if (eventMessage.isInputEvent()) {
+                addPendingActionCount(actions.size());
+            }
+            for (Action action : actions) {
+                // execute action
+                List<Event> actionOutputEvents;
+                if (action.getExec() instanceof JavaFunction) {
+                    action.getExec().call(event, runnerContext);
+                    actionOutputEvents = runnerContext.drainEvents();
+                } else if (action.getExec() instanceof PythonFunction) {
+                    Preconditions.checkState(event instanceof PythonEvent);
+                    actionOutputEvents =
+                            pythonActionExecutor.executePythonFunction(
+                                    (PythonFunction) action.getExec(), 
(PythonEvent) event);

Review Comment:
   When I see this code, I get a sense of fragmentation. Perhaps having a Java 
executor would feel more natural, but that might fall outside the scope of what 
this PR needs to address.
   



##########
runtime/src/main/java/org/apache/flink/agents/runtime/operator/ActionExecutionOperator.java:
##########
@@ -0,0 +1,271 @@
+/*
+ * 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.agents.runtime.operator;
+
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.plan.Action;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.WorkflowPlan;
+import org.apache.flink.agents.runtime.PythonActionExecutor;
+import org.apache.flink.agents.runtime.PythonEvent;
+import org.apache.flink.agents.runtime.context.RunnerContextImpl;
+import org.apache.flink.agents.runtime.env.PythonEnvironmentManager;
+import org.apache.flink.agents.runtime.message.EventMessage;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.python.env.PythonDependencyInfo;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.ChainingStrategy;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.OutputTag;
+import org.apache.flink.util.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * An operator that executes the actions defined in the workflow plan. It 
receives {@link
+ * EventMessage} from the {@link FeedbackOperator}, invokes the corresponding 
action, and collects
+ * the action output event. For events of type {@link OutputEvent}, the output 
will be sent to a
+ * side output; for all other event types, it will be forwarded to the {@link 
FeedbackSinkOperator}.
+ *
+ * <p>Note that this operator ensures that only one {@link Event} is processed 
at a time per key.
+ *
+ * <p>NOTE: This code is adapted from the <a
+ * href="https://github.com/apache/flink-statefun";>flink-statefun</a>.
+ *
+ * @param <K> The type of the key of input event.
+ */
+public class ActionExecutionOperator<K> extends 
AbstractStreamOperator<EventMessage<K>>
+        implements OneInputStreamOperator<EventMessage<K>, EventMessage<K>> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ActionExecutionOperator.class);
+
+    private static final long serialVersionUID = 1L;
+
+    private final OutputTag<EventMessage<K>> sideOutputTag;
+
+    private transient StreamRecord<EventMessage<K>> reusedStreamRecord;
+
+    private transient StreamRecord<EventMessage<K>> 
reusedSideOutputStreamRecord;
+
+    private final WorkflowPlan workflowPlan;
+
+    /**
+     * If an event with the same key is currently being processed, the newly 
received {@link
+     * InputEvent} should not be processed immediately. It will be added to 
the pending queue and
+     * processed during a periodic timer trigger.
+     */
+    private transient ListState<EventMessage<K>> pendingInputEventsState;
+
+    /** The number of actions that are still pending to be executed for the 
current key. */
+    private transient ValueState<Integer> pendingActionCountState;
+
+    private final TypeInformation<EventMessage<K>> eventMessageTypeInfo;
+
+    // RunnerContext for Java actions
+    private final RunnerContextImpl runnerContext;
+
+    // PythonActionExecutor for Python actions
+    private transient PythonActionExecutor pythonActionExecutor;
+
+    public ActionExecutionOperator(
+            OutputTag<EventMessage<K>> sideOutputTag,
+            WorkflowPlan workflowPlan,
+            TypeInformation<EventMessage<K>> eventMessageTypeInfo) {
+        this.sideOutputTag = sideOutputTag;
+        this.workflowPlan = workflowPlan;
+        this.eventMessageTypeInfo = eventMessageTypeInfo;
+        this.runnerContext = new RunnerContextImpl();
+        this.chainingStrategy = ChainingStrategy.ALWAYS;
+    }
+
+    @Override
+    public void open() throws Exception {
+        super.open();
+
+        reusedStreamRecord = new StreamRecord<>(null);
+        reusedSideOutputStreamRecord = new StreamRecord<>(null);
+
+        // init state
+        ValueStateDescriptor<Integer> pendingActionCountDescriptor =

Review Comment:
   default value constructor has been deprecated instead use the null to check



##########
runtime/src/main/java/org/apache/flink/agents/runtime/operator/ActionExecutionOperator.java:
##########
@@ -0,0 +1,271 @@
+/*
+ * 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.agents.runtime.operator;
+
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.plan.Action;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.WorkflowPlan;
+import org.apache.flink.agents.runtime.PythonActionExecutor;
+import org.apache.flink.agents.runtime.PythonEvent;
+import org.apache.flink.agents.runtime.context.RunnerContextImpl;
+import org.apache.flink.agents.runtime.env.PythonEnvironmentManager;
+import org.apache.flink.agents.runtime.message.EventMessage;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.python.env.PythonDependencyInfo;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.ChainingStrategy;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.OutputTag;
+import org.apache.flink.util.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * An operator that executes the actions defined in the workflow plan. It 
receives {@link
+ * EventMessage} from the {@link FeedbackOperator}, invokes the corresponding 
action, and collects
+ * the action output event. For events of type {@link OutputEvent}, the output 
will be sent to a
+ * side output; for all other event types, it will be forwarded to the {@link 
FeedbackSinkOperator}.
+ *
+ * <p>Note that this operator ensures that only one {@link Event} is processed 
at a time per key.
+ *
+ * <p>NOTE: This code is adapted from the <a
+ * href="https://github.com/apache/flink-statefun";>flink-statefun</a>.
+ *
+ * @param <K> The type of the key of input event.
+ */
+public class ActionExecutionOperator<K> extends 
AbstractStreamOperator<EventMessage<K>>
+        implements OneInputStreamOperator<EventMessage<K>, EventMessage<K>> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ActionExecutionOperator.class);
+
+    private static final long serialVersionUID = 1L;
+
+    private final OutputTag<EventMessage<K>> sideOutputTag;
+
+    private transient StreamRecord<EventMessage<K>> reusedStreamRecord;
+
+    private transient StreamRecord<EventMessage<K>> 
reusedSideOutputStreamRecord;
+
+    private final WorkflowPlan workflowPlan;
+
+    /**
+     * If an event with the same key is currently being processed, the newly 
received {@link
+     * InputEvent} should not be processed immediately. It will be added to 
the pending queue and
+     * processed during a periodic timer trigger.
+     */
+    private transient ListState<EventMessage<K>> pendingInputEventsState;
+
+    /** The number of actions that are still pending to be executed for the 
current key. */
+    private transient ValueState<Integer> pendingActionCountState;
+
+    private final TypeInformation<EventMessage<K>> eventMessageTypeInfo;
+
+    // RunnerContext for Java actions
+    private final RunnerContextImpl runnerContext;
+
+    // PythonActionExecutor for Python actions
+    private transient PythonActionExecutor pythonActionExecutor;
+
+    public ActionExecutionOperator(
+            OutputTag<EventMessage<K>> sideOutputTag,
+            WorkflowPlan workflowPlan,
+            TypeInformation<EventMessage<K>> eventMessageTypeInfo) {
+        this.sideOutputTag = sideOutputTag;
+        this.workflowPlan = workflowPlan;
+        this.eventMessageTypeInfo = eventMessageTypeInfo;
+        this.runnerContext = new RunnerContextImpl();
+        this.chainingStrategy = ChainingStrategy.ALWAYS;
+    }
+
+    @Override
+    public void open() throws Exception {
+        super.open();
+
+        reusedStreamRecord = new StreamRecord<>(null);
+        reusedSideOutputStreamRecord = new StreamRecord<>(null);
+
+        // init state
+        ValueStateDescriptor<Integer> pendingActionCountDescriptor =
+                new ValueStateDescriptor<>(
+                        "pendingActionCount", 
TypeInformation.of(Integer.class), 0);
+        pendingActionCountState = 
getRuntimeContext().getState(pendingActionCountDescriptor);
+        ListStateDescriptor<EventMessage<K>> pendingInputEventsDescriptor =
+                new ListStateDescriptor<>("pendingInputEvents", 
eventMessageTypeInfo);
+        pendingInputEventsState = 
getRuntimeContext().getListState(pendingInputEventsDescriptor);
+
+        // init PythonActionExecutor
+        initPythonActionExecutor();
+    }
+
+    @Override
+    public void processElement(StreamRecord<EventMessage<K>> record) throws 
Exception {
+        EventMessage<K> eventMessage = record.getValue();
+        LOG.debug("ActionExecutionOperator receive element {}", eventMessage);
+
+        if (eventMessage.isInputEvent() && !canProcessInputEvent()) {
+            // If the event is an InputEvent and there is already another 
event with the same key
+            // being processed, it will be added to pendingInputEvents and 
processed later.
+            LOG.debug("Add element {} to pending list.", eventMessage);
+            pendingInputEventsState.add(eventMessage);
+            return;
+        }
+
+        processEventMessage(eventMessage);
+        tryProcessPendingInputEvents();
+    }
+
+    private void processEventMessage(EventMessage<K> eventMessage) throws 
Exception {
+        LOG.debug("ActionExecutionOperator process element {}", eventMessage);
+        Event event = eventMessage.getEvent();
+        List<Action> actions = 
workflowPlan.getEventTriggerActions(event.getClass());
+        if (actions != null && !actions.isEmpty()) {
+            // add pending action count for InputEvent.
+            // We should record the number of actions to be processed for each 
event only once.
+            // For InputEvents that must originate from the regular input 
stream, we increment the
+            // action count once before processing the event.
+            // For other Events, which are guaranteed to be generated by an 
action and enter the
+            // feedback loop, we increment the action count once at generation 
time.
+            if (eventMessage.isInputEvent()) {
+                addPendingActionCount(actions.size());
+            }
+            for (Action action : actions) {
+                // execute action
+                List<Event> actionOutputEvents;
+                if (action.getExec() instanceof JavaFunction) {
+                    action.getExec().call(event, runnerContext);
+                    actionOutputEvents = runnerContext.drainEvents();
+                } else if (action.getExec() instanceof PythonFunction) {
+                    Preconditions.checkState(event instanceof PythonEvent);
+                    actionOutputEvents =
+                            pythonActionExecutor.executePythonFunction(
+                                    (PythonFunction) action.getExec(), 
(PythonEvent) event);
+                } else {
+                    throw new RuntimeException("Unsupported action type: " + 
action.getClass());
+                }
+
+                // send action output events
+                for (Event actionOutputEvent : actionOutputEvents) {
+                    EventMessage<K> actionOutputEventMessage =
+                            new EventMessage<>(eventMessage.getKey(), 
actionOutputEvent);
+                    if (actionOutputEvent.isOutputEvent()) {
+                        output.collect(
+                                sideOutputTag,
+                                
reusedSideOutputStreamRecord.replace(actionOutputEventMessage));
+                    } else {
+                        List<Action> pendingActions =
+                                
workflowPlan.getEventTriggerActions(actionOutputEvent.getClass());
+                        addPendingActionCount(pendingActions == null ? 0 : 
pendingActions.size());
+                        
output.collect(reusedStreamRecord.replace(actionOutputEventMessage));
+                    }
+                }
+
+                addPendingActionCount(-1);
+            }
+        }
+    }
+
+    private boolean canProcessInputEvent() throws Exception {
+        if (pendingInputEventsState.get() != null
+                && pendingInputEventsState.get().iterator().hasNext()) {
+            // If there is already a pending input event with the same key, 
the subsequent input
+            // event should not be processed immediately.
+            return false;
+        }
+
+        // If there is some actions in progress with the same key, the 
subsequent input event should

Review Comment:
   is -> are



##########
runtime/src/main/java/org/apache/flink/agents/runtime/operator/ActionExecutionOperator.java:
##########
@@ -0,0 +1,271 @@
+/*
+ * 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.agents.runtime.operator;
+
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.plan.Action;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.WorkflowPlan;
+import org.apache.flink.agents.runtime.PythonActionExecutor;
+import org.apache.flink.agents.runtime.PythonEvent;
+import org.apache.flink.agents.runtime.context.RunnerContextImpl;
+import org.apache.flink.agents.runtime.env.PythonEnvironmentManager;
+import org.apache.flink.agents.runtime.message.EventMessage;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.python.env.PythonDependencyInfo;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.ChainingStrategy;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.OutputTag;
+import org.apache.flink.util.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * An operator that executes the actions defined in the workflow plan. It 
receives {@link
+ * EventMessage} from the {@link FeedbackOperator}, invokes the corresponding 
action, and collects
+ * the action output event. For events of type {@link OutputEvent}, the output 
will be sent to a
+ * side output; for all other event types, it will be forwarded to the {@link 
FeedbackSinkOperator}.
+ *
+ * <p>Note that this operator ensures that only one {@link Event} is processed 
at a time per key.
+ *
+ * <p>NOTE: This code is adapted from the <a
+ * href="https://github.com/apache/flink-statefun";>flink-statefun</a>.
+ *
+ * @param <K> The type of the key of input event.
+ */
+public class ActionExecutionOperator<K> extends 
AbstractStreamOperator<EventMessage<K>>
+        implements OneInputStreamOperator<EventMessage<K>, EventMessage<K>> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ActionExecutionOperator.class);
+
+    private static final long serialVersionUID = 1L;
+
+    private final OutputTag<EventMessage<K>> sideOutputTag;
+
+    private transient StreamRecord<EventMessage<K>> reusedStreamRecord;
+
+    private transient StreamRecord<EventMessage<K>> 
reusedSideOutputStreamRecord;
+
+    private final WorkflowPlan workflowPlan;
+
+    /**
+     * If an event with the same key is currently being processed, the newly 
received {@link
+     * InputEvent} should not be processed immediately. It will be added to 
the pending queue and
+     * processed during a periodic timer trigger.
+     */
+    private transient ListState<EventMessage<K>> pendingInputEventsState;
+
+    /** The number of actions that are still pending to be executed for the 
current key. */
+    private transient ValueState<Integer> pendingActionCountState;
+
+    private final TypeInformation<EventMessage<K>> eventMessageTypeInfo;
+
+    // RunnerContext for Java actions
+    private final RunnerContextImpl runnerContext;
+
+    // PythonActionExecutor for Python actions
+    private transient PythonActionExecutor pythonActionExecutor;
+
+    public ActionExecutionOperator(
+            OutputTag<EventMessage<K>> sideOutputTag,
+            WorkflowPlan workflowPlan,
+            TypeInformation<EventMessage<K>> eventMessageTypeInfo) {
+        this.sideOutputTag = sideOutputTag;
+        this.workflowPlan = workflowPlan;
+        this.eventMessageTypeInfo = eventMessageTypeInfo;
+        this.runnerContext = new RunnerContextImpl();
+        this.chainingStrategy = ChainingStrategy.ALWAYS;
+    }
+
+    @Override
+    public void open() throws Exception {
+        super.open();
+
+        reusedStreamRecord = new StreamRecord<>(null);
+        reusedSideOutputStreamRecord = new StreamRecord<>(null);
+
+        // init state
+        ValueStateDescriptor<Integer> pendingActionCountDescriptor =
+                new ValueStateDescriptor<>(
+                        "pendingActionCount", 
TypeInformation.of(Integer.class), 0);
+        pendingActionCountState = 
getRuntimeContext().getState(pendingActionCountDescriptor);
+        ListStateDescriptor<EventMessage<K>> pendingInputEventsDescriptor =
+                new ListStateDescriptor<>("pendingInputEvents", 
eventMessageTypeInfo);
+        pendingInputEventsState = 
getRuntimeContext().getListState(pendingInputEventsDescriptor);
+
+        // init PythonActionExecutor
+        initPythonActionExecutor();
+    }
+
+    @Override
+    public void processElement(StreamRecord<EventMessage<K>> record) throws 
Exception {
+        EventMessage<K> eventMessage = record.getValue();
+        LOG.debug("ActionExecutionOperator receive element {}", eventMessage);
+
+        if (eventMessage.isInputEvent() && !canProcessInputEvent()) {
+            // If the event is an InputEvent and there is already another 
event with the same key
+            // being processed, it will be added to pendingInputEvents and 
processed later.
+            LOG.debug("Add element {} to pending list.", eventMessage);
+            pendingInputEventsState.add(eventMessage);
+            return;
+        }
+
+        processEventMessage(eventMessage);
+        tryProcessPendingInputEvents();
+    }
+
+    private void processEventMessage(EventMessage<K> eventMessage) throws 
Exception {
+        LOG.debug("ActionExecutionOperator process element {}", eventMessage);
+        Event event = eventMessage.getEvent();
+        List<Action> actions = 
workflowPlan.getEventTriggerActions(event.getClass());
+        if (actions != null && !actions.isEmpty()) {
+            // add pending action count for InputEvent.
+            // We should record the number of actions to be processed for each 
event only once.
+            // For InputEvents that must originate from the regular input 
stream, we increment the
+            // action count once before processing the event.
+            // For other Events, which are guaranteed to be generated by an 
action and enter the
+            // feedback loop, we increment the action count once at generation 
time.
+            if (eventMessage.isInputEvent()) {
+                addPendingActionCount(actions.size());
+            }
+            for (Action action : actions) {
+                // execute action
+                List<Event> actionOutputEvents;
+                if (action.getExec() instanceof JavaFunction) {
+                    action.getExec().call(event, runnerContext);
+                    actionOutputEvents = runnerContext.drainEvents();
+                } else if (action.getExec() instanceof PythonFunction) {
+                    Preconditions.checkState(event instanceof PythonEvent);
+                    actionOutputEvents =
+                            pythonActionExecutor.executePythonFunction(
+                                    (PythonFunction) action.getExec(), 
(PythonEvent) event);
+                } else {
+                    throw new RuntimeException("Unsupported action type: " + 
action.getClass());
+                }
+
+                // send action output events
+                for (Event actionOutputEvent : actionOutputEvents) {
+                    EventMessage<K> actionOutputEventMessage =
+                            new EventMessage<>(eventMessage.getKey(), 
actionOutputEvent);
+                    if (actionOutputEvent.isOutputEvent()) {
+                        output.collect(
+                                sideOutputTag,
+                                
reusedSideOutputStreamRecord.replace(actionOutputEventMessage));
+                    } else {
+                        List<Action> pendingActions =
+                                
workflowPlan.getEventTriggerActions(actionOutputEvent.getClass());
+                        addPendingActionCount(pendingActions == null ? 0 : 
pendingActions.size());
+                        
output.collect(reusedStreamRecord.replace(actionOutputEventMessage));
+                    }
+                }
+
+                addPendingActionCount(-1);
+            }
+        }
+    }
+
+    private boolean canProcessInputEvent() throws Exception {
+        if (pendingInputEventsState.get() != null
+                && pendingInputEventsState.get().iterator().hasNext()) {
+            // If there is already a pending input event with the same key, 
the subsequent input
+            // event should not be processed immediately.
+            return false;
+        }
+
+        // If there is some actions in progress with the same key, the 
subsequent input event should
+        // not be processed immediately.
+        return pendingActionCountState.value() == 0;
+    }
+
+    private void tryProcessPendingInputEvents() throws Exception {
+        if (pendingActionCountState.value() != 0
+                || pendingInputEventsState.get() == null
+                || !pendingInputEventsState.get().iterator().hasNext()) {

Review Comment:
   -> `if (!canProcessInputEvent())`?



##########
runtime/src/main/java/org/apache/flink/agents/runtime/operator/ActionExecutionOperator.java:
##########
@@ -0,0 +1,271 @@
+/*
+ * 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.agents.runtime.operator;
+
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.plan.Action;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.WorkflowPlan;
+import org.apache.flink.agents.runtime.PythonActionExecutor;
+import org.apache.flink.agents.runtime.PythonEvent;
+import org.apache.flink.agents.runtime.context.RunnerContextImpl;
+import org.apache.flink.agents.runtime.env.PythonEnvironmentManager;
+import org.apache.flink.agents.runtime.message.EventMessage;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.python.env.PythonDependencyInfo;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.ChainingStrategy;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.OutputTag;
+import org.apache.flink.util.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * An operator that executes the actions defined in the workflow plan. It 
receives {@link
+ * EventMessage} from the {@link FeedbackOperator}, invokes the corresponding 
action, and collects
+ * the action output event. For events of type {@link OutputEvent}, the output 
will be sent to a
+ * side output; for all other event types, it will be forwarded to the {@link 
FeedbackSinkOperator}.
+ *
+ * <p>Note that this operator ensures that only one {@link Event} is processed 
at a time per key.
+ *
+ * <p>NOTE: This code is adapted from the <a
+ * href="https://github.com/apache/flink-statefun";>flink-statefun</a>.
+ *
+ * @param <K> The type of the key of input event.
+ */
+public class ActionExecutionOperator<K> extends 
AbstractStreamOperator<EventMessage<K>>
+        implements OneInputStreamOperator<EventMessage<K>, EventMessage<K>> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ActionExecutionOperator.class);
+
+    private static final long serialVersionUID = 1L;
+
+    private final OutputTag<EventMessage<K>> sideOutputTag;
+
+    private transient StreamRecord<EventMessage<K>> reusedStreamRecord;
+
+    private transient StreamRecord<EventMessage<K>> 
reusedSideOutputStreamRecord;
+
+    private final WorkflowPlan workflowPlan;
+
+    /**
+     * If an event with the same key is currently being processed, the newly 
received {@link
+     * InputEvent} should not be processed immediately. It will be added to 
the pending queue and
+     * processed during a periodic timer trigger.
+     */
+    private transient ListState<EventMessage<K>> pendingInputEventsState;
+
+    /** The number of actions that are still pending to be executed for the 
current key. */
+    private transient ValueState<Integer> pendingActionCountState;
+
+    private final TypeInformation<EventMessage<K>> eventMessageTypeInfo;
+
+    // RunnerContext for Java actions
+    private final RunnerContextImpl runnerContext;
+
+    // PythonActionExecutor for Python actions
+    private transient PythonActionExecutor pythonActionExecutor;
+
+    public ActionExecutionOperator(
+            OutputTag<EventMessage<K>> sideOutputTag,
+            WorkflowPlan workflowPlan,
+            TypeInformation<EventMessage<K>> eventMessageTypeInfo) {
+        this.sideOutputTag = sideOutputTag;
+        this.workflowPlan = workflowPlan;
+        this.eventMessageTypeInfo = eventMessageTypeInfo;
+        this.runnerContext = new RunnerContextImpl();
+        this.chainingStrategy = ChainingStrategy.ALWAYS;
+    }
+
+    @Override
+    public void open() throws Exception {
+        super.open();
+
+        reusedStreamRecord = new StreamRecord<>(null);
+        reusedSideOutputStreamRecord = new StreamRecord<>(null);
+
+        // init state
+        ValueStateDescriptor<Integer> pendingActionCountDescriptor =
+                new ValueStateDescriptor<>(
+                        "pendingActionCount", 
TypeInformation.of(Integer.class), 0);
+        pendingActionCountState = 
getRuntimeContext().getState(pendingActionCountDescriptor);
+        ListStateDescriptor<EventMessage<K>> pendingInputEventsDescriptor =
+                new ListStateDescriptor<>("pendingInputEvents", 
eventMessageTypeInfo);
+        pendingInputEventsState = 
getRuntimeContext().getListState(pendingInputEventsDescriptor);
+
+        // init PythonActionExecutor
+        initPythonActionExecutor();
+    }
+
+    @Override
+    public void processElement(StreamRecord<EventMessage<K>> record) throws 
Exception {
+        EventMessage<K> eventMessage = record.getValue();
+        LOG.debug("ActionExecutionOperator receive element {}", eventMessage);
+
+        if (eventMessage.isInputEvent() && !canProcessInputEvent()) {
+            // If the event is an InputEvent and there is already another 
event with the same key
+            // being processed, it will be added to pendingInputEvents and 
processed later.
+            LOG.debug("Add element {} to pending list.", eventMessage);
+            pendingInputEventsState.add(eventMessage);
+            return;
+        }
+
+        processEventMessage(eventMessage);
+        tryProcessPendingInputEvents();
+    }
+
+    private void processEventMessage(EventMessage<K> eventMessage) throws 
Exception {
+        LOG.debug("ActionExecutionOperator process element {}", eventMessage);
+        Event event = eventMessage.getEvent();
+        List<Action> actions = 
workflowPlan.getEventTriggerActions(event.getClass());
+        if (actions != null && !actions.isEmpty()) {
+            // add pending action count for InputEvent.
+            // We should record the number of actions to be processed for each 
event only once.
+            // For InputEvents that must originate from the regular input 
stream, we increment the
+            // action count once before processing the event.
+            // For other Events, which are guaranteed to be generated by an 
action and enter the
+            // feedback loop, we increment the action count once at generation 
time.
+            if (eventMessage.isInputEvent()) {
+                addPendingActionCount(actions.size());
+            }
+            for (Action action : actions) {
+                // execute action
+                List<Event> actionOutputEvents;
+                if (action.getExec() instanceof JavaFunction) {
+                    action.getExec().call(event, runnerContext);
+                    actionOutputEvents = runnerContext.drainEvents();
+                } else if (action.getExec() instanceof PythonFunction) {
+                    Preconditions.checkState(event instanceof PythonEvent);
+                    actionOutputEvents =
+                            pythonActionExecutor.executePythonFunction(
+                                    (PythonFunction) action.getExec(), 
(PythonEvent) event);
+                } else {
+                    throw new RuntimeException("Unsupported action type: " + 
action.getClass());
+                }
+
+                // send action output events
+                for (Event actionOutputEvent : actionOutputEvents) {
+                    EventMessage<K> actionOutputEventMessage =
+                            new EventMessage<>(eventMessage.getKey(), 
actionOutputEvent);
+                    if (actionOutputEvent.isOutputEvent()) {
+                        output.collect(
+                                sideOutputTag,
+                                
reusedSideOutputStreamRecord.replace(actionOutputEventMessage));
+                    } else {
+                        List<Action> pendingActions =
+                                
workflowPlan.getEventTriggerActions(actionOutputEvent.getClass());
+                        addPendingActionCount(pendingActions == null ? 0 : 
pendingActions.size());
+                        
output.collect(reusedStreamRecord.replace(actionOutputEventMessage));
+                    }
+                }
+
+                addPendingActionCount(-1);
+            }
+        }
+    }
+
+    private boolean canProcessInputEvent() throws Exception {
+        if (pendingInputEventsState.get() != null

Review Comment:
   Why don't we only use pendingActionCountState to judge it? What's more, 
ListState has worse performance, should we use valueState to judge it first?
   



##########
runtime/src/main/java/org/apache/flink/agents/runtime/operator/ActionExecutionOperator.java:
##########
@@ -0,0 +1,271 @@
+/*
+ * 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.agents.runtime.operator;
+
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.plan.Action;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.WorkflowPlan;
+import org.apache.flink.agents.runtime.PythonActionExecutor;
+import org.apache.flink.agents.runtime.PythonEvent;
+import org.apache.flink.agents.runtime.context.RunnerContextImpl;
+import org.apache.flink.agents.runtime.env.PythonEnvironmentManager;
+import org.apache.flink.agents.runtime.message.EventMessage;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.python.env.PythonDependencyInfo;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.ChainingStrategy;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.OutputTag;
+import org.apache.flink.util.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * An operator that executes the actions defined in the workflow plan. It 
receives {@link
+ * EventMessage} from the {@link FeedbackOperator}, invokes the corresponding 
action, and collects
+ * the action output event. For events of type {@link OutputEvent}, the output 
will be sent to a
+ * side output; for all other event types, it will be forwarded to the {@link 
FeedbackSinkOperator}.
+ *
+ * <p>Note that this operator ensures that only one {@link Event} is processed 
at a time per key.
+ *
+ * <p>NOTE: This code is adapted from the <a
+ * href="https://github.com/apache/flink-statefun";>flink-statefun</a>.
+ *
+ * @param <K> The type of the key of input event.
+ */
+public class ActionExecutionOperator<K> extends 
AbstractStreamOperator<EventMessage<K>>
+        implements OneInputStreamOperator<EventMessage<K>, EventMessage<K>> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ActionExecutionOperator.class);
+
+    private static final long serialVersionUID = 1L;
+
+    private final OutputTag<EventMessage<K>> sideOutputTag;
+
+    private transient StreamRecord<EventMessage<K>> reusedStreamRecord;
+
+    private transient StreamRecord<EventMessage<K>> 
reusedSideOutputStreamRecord;
+
+    private final WorkflowPlan workflowPlan;
+
+    /**
+     * If an event with the same key is currently being processed, the newly 
received {@link
+     * InputEvent} should not be processed immediately. It will be added to 
the pending queue and
+     * processed during a periodic timer trigger.
+     */
+    private transient ListState<EventMessage<K>> pendingInputEventsState;
+
+    /** The number of actions that are still pending to be executed for the 
current key. */
+    private transient ValueState<Integer> pendingActionCountState;
+
+    private final TypeInformation<EventMessage<K>> eventMessageTypeInfo;
+
+    // RunnerContext for Java actions
+    private final RunnerContextImpl runnerContext;
+
+    // PythonActionExecutor for Python actions
+    private transient PythonActionExecutor pythonActionExecutor;
+
+    public ActionExecutionOperator(
+            OutputTag<EventMessage<K>> sideOutputTag,
+            WorkflowPlan workflowPlan,
+            TypeInformation<EventMessage<K>> eventMessageTypeInfo) {
+        this.sideOutputTag = sideOutputTag;
+        this.workflowPlan = workflowPlan;
+        this.eventMessageTypeInfo = eventMessageTypeInfo;
+        this.runnerContext = new RunnerContextImpl();
+        this.chainingStrategy = ChainingStrategy.ALWAYS;
+    }
+
+    @Override
+    public void open() throws Exception {
+        super.open();
+
+        reusedStreamRecord = new StreamRecord<>(null);
+        reusedSideOutputStreamRecord = new StreamRecord<>(null);
+
+        // init state
+        ValueStateDescriptor<Integer> pendingActionCountDescriptor =
+                new ValueStateDescriptor<>(
+                        "pendingActionCount", 
TypeInformation.of(Integer.class), 0);
+        pendingActionCountState = 
getRuntimeContext().getState(pendingActionCountDescriptor);
+        ListStateDescriptor<EventMessage<K>> pendingInputEventsDescriptor =
+                new ListStateDescriptor<>("pendingInputEvents", 
eventMessageTypeInfo);
+        pendingInputEventsState = 
getRuntimeContext().getListState(pendingInputEventsDescriptor);
+
+        // init PythonActionExecutor
+        initPythonActionExecutor();
+    }
+
+    @Override
+    public void processElement(StreamRecord<EventMessage<K>> record) throws 
Exception {
+        EventMessage<K> eventMessage = record.getValue();
+        LOG.debug("ActionExecutionOperator receive element {}", eventMessage);
+
+        if (eventMessage.isInputEvent() && !canProcessInputEvent()) {
+            // If the event is an InputEvent and there is already another 
event with the same key
+            // being processed, it will be added to pendingInputEvents and 
processed later.
+            LOG.debug("Add element {} to pending list.", eventMessage);
+            pendingInputEventsState.add(eventMessage);
+            return;
+        }
+
+        processEventMessage(eventMessage);
+        tryProcessPendingInputEvents();
+    }
+
+    private void processEventMessage(EventMessage<K> eventMessage) throws 
Exception {
+        LOG.debug("ActionExecutionOperator process element {}", eventMessage);
+        Event event = eventMessage.getEvent();
+        List<Action> actions = 
workflowPlan.getEventTriggerActions(event.getClass());
+        if (actions != null && !actions.isEmpty()) {
+            // add pending action count for InputEvent.
+            // We should record the number of actions to be processed for each 
event only once.
+            // For InputEvents that must originate from the regular input 
stream, we increment the
+            // action count once before processing the event.
+            // For other Events, which are guaranteed to be generated by an 
action and enter the
+            // feedback loop, we increment the action count once at generation 
time.
+            if (eventMessage.isInputEvent()) {
+                addPendingActionCount(actions.size());
+            }
+            for (Action action : actions) {
+                // execute action
+                List<Event> actionOutputEvents;
+                if (action.getExec() instanceof JavaFunction) {
+                    action.getExec().call(event, runnerContext);
+                    actionOutputEvents = runnerContext.drainEvents();
+                } else if (action.getExec() instanceof PythonFunction) {
+                    Preconditions.checkState(event instanceof PythonEvent);
+                    actionOutputEvents =
+                            pythonActionExecutor.executePythonFunction(
+                                    (PythonFunction) action.getExec(), 
(PythonEvent) event);
+                } else {
+                    throw new RuntimeException("Unsupported action type: " + 
action.getClass());
+                }
+
+                // send action output events
+                for (Event actionOutputEvent : actionOutputEvents) {
+                    EventMessage<K> actionOutputEventMessage =
+                            new EventMessage<>(eventMessage.getKey(), 
actionOutputEvent);
+                    if (actionOutputEvent.isOutputEvent()) {
+                        output.collect(
+                                sideOutputTag,
+                                
reusedSideOutputStreamRecord.replace(actionOutputEventMessage));
+                    } else {
+                        List<Action> pendingActions =
+                                
workflowPlan.getEventTriggerActions(actionOutputEvent.getClass());
+                        addPendingActionCount(pendingActions == null ? 0 : 
pendingActions.size());
+                        
output.collect(reusedStreamRecord.replace(actionOutputEventMessage));
+                    }
+                }
+
+                addPendingActionCount(-1);
+            }
+        }
+    }
+
+    private boolean canProcessInputEvent() throws Exception {
+        if (pendingInputEventsState.get() != null
+                && pendingInputEventsState.get().iterator().hasNext()) {
+            // If there is already a pending input event with the same key, 
the subsequent input
+            // event should not be processed immediately.
+            return false;
+        }
+
+        // If there is some actions in progress with the same key, the 
subsequent input event should
+        // not be processed immediately.
+        return pendingActionCountState.value() == 0;
+    }
+
+    private void tryProcessPendingInputEvents() throws Exception {
+        if (pendingActionCountState.value() != 0
+                || pendingInputEventsState.get() == null
+                || !pendingInputEventsState.get().iterator().hasNext()) {
+            // If there is some actions in progress with the same key, the 
pending input event

Review Comment:
   is -> are



##########
runtime/src/main/java/org/apache/flink/agents/runtime/operator/FeedbackOperator.java:
##########
@@ -0,0 +1,203 @@
+/*
+ * 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.agents.runtime.operator;
+
+import org.apache.flink.agents.runtime.common.MailboxExecutorFacade;
+import org.apache.flink.agents.runtime.feedback.Checkpoints;
+import org.apache.flink.agents.runtime.feedback.FeedbackChannel;
+import org.apache.flink.agents.runtime.feedback.FeedbackChannelBroker;
+import org.apache.flink.agents.runtime.feedback.FeedbackConsumer;
+import org.apache.flink.agents.runtime.feedback.FeedbackKey;
+import org.apache.flink.agents.runtime.feedback.SubtaskFeedbackKey;
+import org.apache.flink.agents.runtime.logger.Loggers;
+import org.apache.flink.agents.runtime.logger.UnboundedFeedbackLogger;
+import org.apache.flink.agents.runtime.logger.UnboundedFeedbackLoggerFactory;
+import org.apache.flink.agents.runtime.message.EventMessage;
+import org.apache.flink.agents.runtime.message.Message;
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.state.KeyGroupStatePartitionStreamProvider;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
+import org.apache.flink.util.IOUtils;
+import org.apache.flink.util.function.SerializableFunction;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Objects;
+import java.util.OptionalLong;
+import java.util.concurrent.Executor;
+
+/**
+ * A special operator designed to receive both the input data stream and the 
feedback stream from
+ * the {@link FeedbackSinkOperator}. It will serve as the head node of the 
workflow execution loop
+ * and forward the data to the {@link ActionExecutionOperator} operator.
+ *
+ * <p>NOTE: This code is adapted from the <a
+ * href="https://github.com/apache/flink-statefun";>flink-statefun</a>.
+ *
+ * @param <K> The type of the key of input event.
+ */
+public class FeedbackOperator<K> extends 
AbstractStreamOperator<EventMessage<K>>
+        implements FeedbackConsumer<Message>,
+                OneInputStreamOperator<EventMessage<K>, EventMessage<K>> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(FeedbackOperator.class);
+
+    private static final long serialVersionUID = 1L;

Review Comment:
   put before `private static final Logger LOG = 
LoggerFactory.getLogger(FeedbackOperator.class);`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to