weiqingy commented on code in PR #887:
URL: https://github.com/apache/flink-agents/pull/887#discussion_r3556911302


##########
python/flink_agents/api/core_options.py:
##########
@@ -215,6 +215,42 @@ class AgentConfigOptions:
     )
 
 
+class MemoryEventOptions:

Review Comment:
   There's an enforced parity guard that reflects a Java options class against 
its Python mirror and asserts the field names, keys, types, and defaults all 
match — `check_java_python_config_options_parity.py`, run in CI via 
`test_java_config_in_python.sh`. Its `main()` registers `AgentConfigOptions` 
and `AgentExecutionOptions`, but this new `MemoryEventOptions` family isn't 
wired in on either side. `test_memory_event.py:104` looks like it fills that 
gap, but it checks the Python constants against hardcoded literals — it can't 
see Java, so by construction it can't catch Java↔Python drift. Given the 9 new 
keys and their tri-state `null` defaults are exactly the shape that's easiest 
to break asymmetrically, would registering the class in that checker's `main()` 
be worth it? `normalize_java_default` already maps a Java `null` default to 
Python `None`, so it should compare cleanly with no checker changes.



##########
runtime/src/main/java/org/apache/flink/agents/runtime/context/RunnerContextImpl.java:
##########
@@ -169,6 +218,56 @@ public List<Event> drainEvents(Long timestamp) {
         return list;
     }
 
+    private void flushMemoryObservation() {
+        if (memoryContext == null) {
+            return;
+        }
+        // ALWAYS drain LTM records for this key (mailbox thread) — discarded 
below if
+        // suppressed/disabled; skipping the drain would leak them into the 
next action.

Review Comment:
   The "ALWAYS drain" invariant here holds for suppressed/disabled actions — 
they finish normally and hit this drain before the early returns. But 
`flushMemoryObservation` only runs from `drainEvents(_, true)`, which the 
action tasks call only on normal finish (`JavaActionTask:85-86`, and the Python 
task). When an action throws after doing LTM ops, `invoke()` rethrows, 
`drainEvents(_, true)` is never reached, and the Python-side buffer for this 
key isn't drained — so the guarantee is actually narrower than "a suppressed or 
disabled action still drains the buffer" reads. In practice it looks masked: a 
thrown action fails the mailbox task → operator restart → the interpreter's 
buffer is recreated fresh. I traced that path and restart appears to be the 
only exit, but I couldn't prove it exhaustively — is operator restart 
guaranteed to be the only way out here? A small test driving an action that 
throws and asserting no memory events leak into the next same-key action would 
set
 tle both the invariant and my uncertainty.



##########
runtime/src/main/java/org/apache/flink/agents/runtime/memory/MemoryEventBuilder.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.memory;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.context.MemoryUpdate;
+import org.apache.flink.agents.api.event.LongTermGetEvent;
+import org.apache.flink.agents.api.event.LongTermSearchEvent;
+import org.apache.flink.agents.api.event.LongTermUpdateEvent;
+import org.apache.flink.agents.api.event.MemoryEvent;
+import org.apache.flink.agents.runtime.memory.MemoryEventSettings.MemoryOp;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Converts per-action memory records into {@link MemoryEvent}s at the action 
finish boundary.
+ *
+ * <p>Values are dot-key flat maps; multiple operations on the same field 
within one action fold to
+ * the last value (net effect). LTM search values map each query to its (last) 
hit list.
+ */
+public final class MemoryEventBuilder {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(MemoryEventBuilder.class);
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    private MemoryEventBuilder() {}
+
+    public static List<MemoryEvent> buildWriteEvents(
+            String key,
+            List<MemoryUpdate> sensoryUpdates,
+            List<MemoryUpdate> shortTermUpdates,
+            MemoryEventSettings settings) {
+        List<MemoryEvent> events = new ArrayList<>(2);
+        addFolded(events, key, MemoryOp.SENSORY_WRITE, sensoryUpdates, 
settings);
+        addFolded(events, key, MemoryOp.SHORT_TERM_WRITE, shortTermUpdates, 
settings);
+        return events;
+    }
+
+    public static List<MemoryEvent> buildReadEvents(
+            String key,
+            List<MemoryUpdate> sensoryReads,
+            List<MemoryUpdate> shortTermReads,
+            MemoryEventSettings settings) {
+        List<MemoryEvent> events = new ArrayList<>(2);
+        addFolded(events, key, MemoryOp.SENSORY_READ, sensoryReads, settings);
+        addFolded(events, key, MemoryOp.SHORT_TERM_READ, shortTermReads, 
settings);
+        return events;
+    }
+
+    /**
+     * Builds LTM events from drained Python-side records ({@code 
{op,set,id,value,key}} maps). The
+     * record-level {@code key} is a hashed partition key used only for drain 
filtering; the emitted
+     * events carry the finishing action's readable {@code key} passed in here.
+     */
+    public static List<MemoryEvent> buildLtmEvents(
+            String key, List<Map<String, Object>> records, MemoryEventSettings 
settings) {
+        Map<String, Object> updates = new LinkedHashMap<>();
+        Map<String, Object> gets = new LinkedHashMap<>();
+        Map<String, Object> searches = new LinkedHashMap<>();
+        for (Map<String, Object> record : records) {
+            Object op = record.get("op");
+            String set = record.get("set") != null ? 
record.get("set").toString() : null;
+            if (set == null) {
+                continue;
+            }
+            Object id = record.get("id");
+            Object value = record.get("value");
+            if ("ADD".equals(op)) {
+                updates.put(set + "." + id, value);
+            } else if ("DELETE".equals(op)) {
+                updates.put(set + "." + id, null);
+            } else if ("DELETE_SET".equals(op)) {
+                updates.put(set, null);
+            } else if ("GET".equals(op)) {
+                gets.put(set + "." + id, value);
+            } else if ("SEARCH".equals(op)) {
+                searches.put(set, value);
+            }
+            // unknown op: skip rather than fail the action
+        }
+        List<MemoryEvent> events = new ArrayList<>(3);
+        if (!updates.isEmpty() && 
settings.generate(MemoryOp.LONG_TERM_UPDATE)) {
+            events.add(new LongTermUpdateEvent(key, updates));
+        }
+        if (!gets.isEmpty() && settings.generate(MemoryOp.LONG_TERM_GET)) {
+            events.add(new LongTermGetEvent(key, gets));
+        }
+        if (!searches.isEmpty() && 
settings.generate(MemoryOp.LONG_TERM_SEARCH)) {
+            events.add(new LongTermSearchEvent(key, searches));
+        }
+        return events;
+    }
+
+    /**
+     * Parses a drained JSON array of LTM records; malformed input yields an 
empty list and
+     * non-object elements are filtered out.
+     */
+    @SuppressWarnings("unchecked")
+    public static List<Map<String, Object>> parseDrainedRecords(String json) {
+        if (json == null || json.isEmpty()) {
+            return Collections.emptyList();
+        }
+        try {
+            List<?> raw = MAPPER.readValue(json, List.class);
+            List<Map<String, Object>> records = new ArrayList<>(raw.size());
+            for (Object item : raw) {
+                if (item instanceof Map) {
+                    records.add((Map<String, Object>) item);
+                }
+            }
+            return records;
+        } catch (Exception e) {
+            LOG.debug("Dropping malformed LTM observation payload", e);
+            return Collections.emptyList();
+        }
+    }
+
+    private static void addFolded(
+            List<MemoryEvent> events,
+            String key,
+            MemoryOp op,
+            List<MemoryUpdate> records,
+            MemoryEventSettings settings) {
+        if (records == null || records.isEmpty() || !settings.generate(op)) {
+            return;
+        }
+        Map<String, Object> flat = new LinkedHashMap<>();
+        for (MemoryUpdate update : records) {
+            flat.put(update.getPath(), update.getValue());

Review Comment:
   This puts the raw memory value object straight into the event's `value` map 
(`update.getValue()`, no normalization). Those events get drained into 
`pendingEvents`, persisted into `ActionState.outputEvents`, and re-emitted on 
replay via the completed-action path. The Kryo `{serde,version,payload}` 
envelope that preserves an untyped memory value's concrete type across durable 
recovery is bound class-scoped to `MemoryUpdate.value` 
(`addMixIn(MemoryUpdate.class, ...)` in `ActionStateSerde`) — it doesn't cover 
`Event.attributes`, which serializes through stock Jackson. So a `byte[]` 
short-term value (a supported type — 
`ActionStateSerdeTest.testByteArrayMemoryValuePreserved`) comes back as a 
base64 `String` after recovery, and a POJO as a `LinkedHashMap`. An action 
subscribing to `_short_term_write_event` would then see `byte[]` on the live 
run and `String` on the recovered run.
   
   It only bites under a narrow combination — durable execution enabled, a 
non-JSON-native STM value, and an action that actually depends on the concrete 
type — so I don't think it blocks merge. And it may well be intentional: if 
memory events are audit-only, a base64 string is arguably fine. Is that the 
intent, or should the event path reuse the same envelope? Either way, 
`testMemoryEventsSurviveActionStateRoundTrip` currently uses only `"gold"` and 
`1` (both JSON-native, so type is trivially preserved) — a `byte[]` assertion 
there would pin whichever answer you land on.



##########
runtime/src/main/java/org/apache/flink/agents/runtime/memory/MemoryEventBuilder.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.memory;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.context.MemoryUpdate;
+import org.apache.flink.agents.api.event.LongTermGetEvent;
+import org.apache.flink.agents.api.event.LongTermSearchEvent;
+import org.apache.flink.agents.api.event.LongTermUpdateEvent;
+import org.apache.flink.agents.api.event.MemoryEvent;
+import org.apache.flink.agents.runtime.memory.MemoryEventSettings.MemoryOp;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Converts per-action memory records into {@link MemoryEvent}s at the action 
finish boundary.
+ *
+ * <p>Values are dot-key flat maps; multiple operations on the same field 
within one action fold to
+ * the last value (net effect). LTM search values map each query to its (last) 
hit list.
+ */
+public final class MemoryEventBuilder {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(MemoryEventBuilder.class);
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    private MemoryEventBuilder() {}
+
+    public static List<MemoryEvent> buildWriteEvents(
+            String key,
+            List<MemoryUpdate> sensoryUpdates,
+            List<MemoryUpdate> shortTermUpdates,
+            MemoryEventSettings settings) {
+        List<MemoryEvent> events = new ArrayList<>(2);
+        addFolded(events, key, MemoryOp.SENSORY_WRITE, sensoryUpdates, 
settings);
+        addFolded(events, key, MemoryOp.SHORT_TERM_WRITE, shortTermUpdates, 
settings);
+        return events;
+    }
+
+    public static List<MemoryEvent> buildReadEvents(
+            String key,
+            List<MemoryUpdate> sensoryReads,
+            List<MemoryUpdate> shortTermReads,
+            MemoryEventSettings settings) {
+        List<MemoryEvent> events = new ArrayList<>(2);
+        addFolded(events, key, MemoryOp.SENSORY_READ, sensoryReads, settings);
+        addFolded(events, key, MemoryOp.SHORT_TERM_READ, shortTermReads, 
settings);
+        return events;
+    }
+
+    /**
+     * Builds LTM events from drained Python-side records ({@code 
{op,set,id,value,key}} maps). The
+     * record-level {@code key} is a hashed partition key used only for drain 
filtering; the emitted
+     * events carry the finishing action's readable {@code key} passed in here.
+     */
+    public static List<MemoryEvent> buildLtmEvents(
+            String key, List<Map<String, Object>> records, MemoryEventSettings 
settings) {
+        Map<String, Object> updates = new LinkedHashMap<>();
+        Map<String, Object> gets = new LinkedHashMap<>();
+        Map<String, Object> searches = new LinkedHashMap<>();
+        for (Map<String, Object> record : records) {
+            Object op = record.get("op");
+            String set = record.get("set") != null ? 
record.get("set").toString() : null;
+            if (set == null) {
+                continue;
+            }
+            Object id = record.get("id");
+            Object value = record.get("value");
+            if ("ADD".equals(op)) {
+                updates.put(set + "." + id, value);
+            } else if ("DELETE".equals(op)) {
+                updates.put(set + "." + id, null);
+            } else if ("DELETE_SET".equals(op)) {
+                updates.put(set, null);

Review Comment:
   `DELETE_SET` adds `set -> null` but doesn't purge the earlier `set + "." + 
id` entries folded in above, so `ADD s.m1=v` then `DELETE_SET s` within one 
action yields `{"s.m1": v, "s": null}`. A log consumer reconstructing state 
from this event would see `s.m1=v` as a live member even though the same 
event's `s -> null` says the set — and that member with it — was deleted. It's 
observability-only, but the emitted value misreports the member. Purging the 
`set + "."` prefix entries when folding in a `DELETE_SET` would keep the 
reconstruction accurate.



##########
runtime/src/main/java/org/apache/flink/agents/runtime/context/RunnerContextImpl.java:
##########
@@ -169,6 +218,56 @@ public List<Event> drainEvents(Long timestamp) {
         return list;
     }
 
+    private void flushMemoryObservation() {
+        if (memoryContext == null) {
+            return;
+        }
+        // ALWAYS drain LTM records for this key (mailbox thread) — discarded 
below if
+        // suppressed/disabled; skipping the drain would leak them into the 
next action.
+        List<Map<String, Object>> ltmRecords = Collections.emptyList();
+        if (ltm != null) {
+            try {
+                ltmRecords =
+                        MemoryEventBuilder.parseDrainedRecords(
+                                
ltm.drainObservationRecordsJson(observationKeyHash));
+            } catch (Exception e) {
+                LOG.debug("LTM observation drain failed; skipping", e);

Review Comment:
   If the Pemja `drain_ltm_observation_records` call throws, this swallows it 
at DEBUG and moves on. Two things go quiet: this action's LTM observation is 
lost, and if the Python side threw *before* clearing its buffer, those records 
survive and get attributed to the next same-key action's flush — the exact 
cross-action leak the drain exists to prevent. A persistent drain failure would 
misattribute LTM records with no visible signal. Would a throttled `WARN` fit 
better here, so the condition is at least observable?



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