Xiao-zhen-Liu commented on code in PR #9366:
URL: https://github.com/apache/texera/pull/9366#discussion_r4520689430


##########
amber/src/main/python/core/models/operator.py:
##########
@@ -392,6 +393,26 @@ def _eval_loop_expr(expr: str, state: State, table: 
Optional[Table]):
     return eval(expr, namespace)
 
 
+def _assigned_names(code: str) -> frozenset[str]:
+    """Return the names ``code`` assigns: every name it stores to (an
+    assignment, augmented, annotated, walrus, ``for`` or ``with`` target),
+    every name an import binds, and the names of the functions and classes it
+    defines. It reads the code rather than a run of it, so a conditional
+    assignment counts, and so does a name bound only inside a comprehension or
+    inside a function the code defines."""
+    names = set()
+    for node in ast.walk(ast.parse(code)):
+        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):

Review Comment:
   Walking the `update` syntax tree to guess which published variables become 
loop variables counts comprehension and function-local targets as assigned. If 
a body operator publishes `score` and `update` runs `total = sum(score for 
score in table["v"])`, `score` is saved into iteration 2's `Loop Start` state, 
and a downstream `Filter` on `$score` fails with `"loop variable score got two 
different values in one iteration"`. Track runtime top-level bindings instead 
of walking the syntax tree.



##########
amber/src/main/python/core/runnables/main_loop.py:
##########
@@ -512,93 +568,78 @@ def _process_state_frame(self, frame: StateFrame) -> None:
             # all of its own iterations.
             self.context.output_manager.reset_output_storage()
             # State belongs to an outer loop: step one level out and forward,
-            # carrying the outer loop's id unchanged.
-            self._emit_and_save_state(state, in_counter - 1, 
frame.loop_start_id)
+            # carrying the outer loop's id and the message id unchanged.
+            self._emit_and_save_state(
+                state, in_counter - 1, frame.loop_start_id, frame.message_id
+            )
             self._check_and_process_control()
             return
         if isinstance(executor, LoopStartOperator) and frame.loop_start_id:
             # Outer loop's state flowing through an inner LoopStart -- detected
             # by the outer LoopStart's id stamped on the envelope (a 
first-entry
             # state has no stamp): step one level deeper and forward, keeping
-            # the outer loop's id.
-            self._emit_and_save_state(state, in_counter + 1, 
frame.loop_start_id)
+            # the outer loop's id and the message id.
+            self._emit_and_save_state(
+                state, in_counter + 1, frame.loop_start_id, frame.message_id
+            )
             self._check_and_process_control()
             return
 
         # A LoopStart handles only the STAMPED case above. An UNstamped
         # counter-0 state at a LoopStart takes neither branch: it falls all the
         # way through to process_input_state at the bottom, and the operator's
-        # process_state MERGES its keys into the loop variables. That is the
-        # opposite of what the LoopEnd branch below does with the identical
-        # frame, and the asymmetry is forced, not an oversight. The back-edge
+        # process_state MERGES its keys into the loop variables. The back-edge
         # writes the next iteration's variables to the LoopStart's own
         # input-port state URI with that very same "no loop" envelope
         # (_jump_to_loop_start -> State.to_tuple(0)), so an unstamped counter-0
         # frame at a LoopStart is indistinguishable from -- and normally IS --
-        # the loop's own state. A LoopEnd may forward instead of consuming
-        # because its inbound loop state is always stamped by the matching
-        # LoopStart; a LoopStart has no such signal. Consequence of the merge:
-        # an upstream or body operator emitting a key that collides with a loop
-        # variable overwrites it, and one emitting `table` trips
-        # _reserved_name_error in produce_state_on_finish (see #7248).
+        # the loop's own state. Consequence of the merge: an upstream or body
+        # operator emitting a key that collides with a loop variable
+        # overwrites it, and one emitting `table` trips _reserved_name_error in
+        # produce_state_on_finish (see #7248).
 
         if isinstance(executor, LoopEndOperator):
-            if not frame.loop_start_id:
-                # An UNstamped counter-0 state at a LoopEnd is not the loop's
-                # own boundary state -- it was produced by a loop-body
-                # operator's produce_state_on_start/finish (a public API on
-                # both engine sides), which emits with the "no loop" envelope.
-                # A real loop state is always stamped: the matching LoopStart
-                # stamps its own id on every iteration's output state.
-                # Forward it downstream unchanged, skipping the operator, like
-                # any default pass-through: taking it would clobber the
-                # captured back-jump id with "" and then fail the deferred
-                # consume's bookkeeping-URI lookup for LoopStart ''.
-                #
-                # This MUST stay ahead of the dedup and the stash below: an
-                # unstamped frame is not the loop's own state, so it may
-                # neither mark that state as taken nor be handed to the
-                # operator as the iteration's state.
-                self._forwarded_unstamped_state = True
-                self._emit_and_save_state(state, in_counter, 
frame.loop_start_id)
-                self._check_and_process_control()
-                return
-            # Matching LoopEnd (in_counter == 0, stamped): it will consume this
-            # state and jump back. Remember which LoopStart to jump to (it
-            # rides the envelope) for complete()/_jump_to_loop_start, and STASH
-            # the state -- the operator runs its update at EndChannel instead
-            # of here, because the loop's input table is read from storage and
-            # that read must not overlap this worker's own materialization
-            # reader (see _consume_pending_loop_state). The LoopEnd emits no
-            # state downstream on the matching consume, so deferring it
-            # changes nothing observable outside the operator.
+            # Matching LoopEnd (in_counter == 0): it takes every distinct
+            # message of its loop until its input ends -- the loop's own state,
+            # stamped by the matching LoopStart, and whatever a loop-body
+            # operator sent after it: a state its process_state changed, or one
+            # its produce_state_on_start/finish (a public API on both engine
+            # sides) emitted with the "no loop" envelope. Their values are
+            # COLLECTED, a later message's replacing an earlier one's, so the
+            # user's update and condition see what the body computed. Later
+            # copies of a message were dropped above, so they cannot undo a
+            # value that arrived after its first copy; which of two distinct
+            # messages arrives last, and so wins, can depend on the paths they
+            # take. Nothing is sent downstream: the loop's own values stay
+            # inside the block.
             #
-            # With a branching loop body, each branch's reader replays the same
-            # iteration's state, so this fires once per inbound link. The
-            # deferred consume runs the user's update exactly once either way
-            # (and run_update seeds its namespace from the incoming copy, so
-            # re-running it on an identical copy would even be idempotent);
-            # what this flag pins is WHICH copy is stashed -- the first,
-            # instead of each later arrival silently overwriting
-            # _pending_loop_state. The copies are the same state emitted by
-            # the one matching LoopStart unless a body operator overrides
-            # process_state to forward a modified one; rewriting the loop
-            # state in a branching body is not supported (which copy arrives
-            # first is scheduling-dependent either way), so take the first
-            # deliberately.
-            if self._loop_state_consumed:
-                self._check_and_process_control()
-                return
-            self._loop_state_consumed = True
-            self._loop_start_id = frame.loop_start_id
-            self._pending_loop_state = state
+            # The operator runs its update at EndChannel instead of here,
+            # because the loop's input table is read from storage and that
+            # read must not overlap this worker's own materialization reader
+            # (see _consume_pending_loop_state).
+            if frame.loop_start_id:
+                # Remember which LoopStart to jump to (it rides the envelope)
+                # for complete()/_jump_to_loop_start.
+                self._loop_start_id = frame.loop_start_id
+                self._loop_state_names.update(state)
+            else:
+                # An unstamped state must not clobber the captured back-jump id
+                # with "", which would fail the deferred consume's
+                # bookkeeping-URI lookup for LoopStart ''.
+                self._took_unstamped_state = True
+                self._published_names.update(state)
+            if self._pending_loop_state is None:
+                self._pending_loop_state = State()
+            self._pending_loop_state.update(state)

Review Comment:
   When a loop body splits after `Loop Start(x = 1)` into a Python UDF whose 
`process_state` sets `x = 2` and a slower `Sleep` branch that forwards `Loop 
Start`'s state unchanged, the modified state gets a new message ID and reaches 
`Loop End` first, and the slower branch arrives later with the original ID and 
overwrites `x` back to `1`. Track `Loop Start`'s initial state separately from 
body modifications so an unmodified branch cannot overwrite a modified key.



##########
amber/src/main/python/core/runnables/main_loop.py:
##########
@@ -178,11 +184,6 @@ def _consume_pending_loop_state(self, executor: 
LoopEndOperator) -> None:
             return
         pending = self._pending_loop_state
         self._pending_loop_state = None

Review Comment:
   Nit: If a `Loop End` worker runs a second iteration without being recreated, 
the state names and unstamped flag from iteration 1 stay set on the worker. If 
iteration 2 receives only an unstamped state because an upstream hop dropped 
the loop header, `Loop End` still sees iteration 1's loop ID instead of raising 
the lost-envelope error. Clear the per-iteration state name sets and unstamped 
flag after the back-edge write.



##########
amber/src/test/integration/org/apache/texera/amber/engine/e2e/LoopIntegrationSpec.scala:
##########
@@ -496,4 +547,107 @@ class LoopIntegrationSpec
     )
   }
 
+  it should "stop a loop once a score computed in its body stops improving" in 
{
+    // TextInput("3","5","4","6") -> LoopStart(i = 0, prev = None, score = 0 / 
table.iloc[i])
+    //   -> scoring UDF -> LoopEnd(again = prev is None or score > prev; prev 
= score; i += 1 / again).
+    // The UDF publishes the row it saw as `score` after the loop's state has 
passed it. The scores
+    // are 3, 5, 4: the third does not improve, so the loop stops after 3 
iterations. A LoopEnd that
+    // never sees the body's score compares the initial 0 with itself and 
stops after 2.
+    val src = textInput("3\n5\n4\n6")
+    val start = loopStart("i = 0\nprev = None\nscore = 0", "table.iloc[i]")
+    val mid = scoringPythonUDF()
+    val end = loopEnd("again = prev is None or score > prev\nprev = score\ni 
+= 1", "again")
+    val materialized = runAndGetMaterializedRowCounts(
+      List(src, start, mid, end),
+      List(link(src, start), link(start, mid), link(mid, end))
+    )
+    val endRows = materialized.getOrElse(end.operatorIdentifier, -1L)
+    assert(
+      endRows == 3,
+      s"the loop must stop on the first score that does not improve (3, 5, 4): 
expected 3 " +
+        s"iterations, got $endRows (all: $materialized)"
+    )
+  }
+
+  it should "run a body operator's process_state once per message where two 
branches meet" in {
+    // TextInput("0","1","2") -> LoopStart(i = 0 / table.iloc[i]) -> Limit(10) 
and Sleep(0)
+    //   -> both into one input port of a message-counting UDF -> LoopEnd.
+    // Loop Start's message reaches the UDF once per branch, as copies of one 
message. Each
+    // iteration's row passes both branches (2 rows) and the UDF adds a row 
per message it
+    // processed: 1 for the one message, so 3 rows on each of 3 iterations. 
Processing every copy
+    // would add 2 and give 12.
+    val src = textInput("0\n1\n2")
+    val start = loopStart("i = 0", "table.iloc[i]")
+    val left = limit(10)
+    val right = sleep(0)
+    val mid = messageCountingPythonUDF()
+    val end = loopEnd("i += 1", "i < len(table)")
+    val materialized = runAndGetMaterializedRowCounts(
+      List(src, start, left, right, mid, end),
+      List(
+        link(src, start),
+        link(start, left),
+        link(start, right),
+        link(left, mid),
+        link(right, mid),
+        link(mid, end)
+      )
+    )
+    val endRows = materialized.getOrElse(end.operatorIdentifier, -1L)
+    assert(
+      endRows == 9,
+      s"the UDF must process Loop Start's message once per iteration, not once 
per branch: " +
+        s"expected 9, got $endRows (all: $materialized)"
+    )
+  }
+
+  it should "keep a loop variable set to None through a JVM operator in the 
loop body" in {
+    // The stopping example with Limit(10), a JVM operator, between Loop Start 
and the scoring UDF:
+    // TextInput("3","5","4","6") -> LoopStart(i = 0, prev = None, score = 0 / 
table.iloc[i])
+    //   -> Limit(10) -> scoring UDF -> LoopEnd(again = prev is None or score 
> prev;
+    //   prev = score; i += 1 / again).
+    // Loop Start's message passes the Limit on its way to Loop End, whose 
update reads `prev` in
+    // the first iteration, so `prev = None` must still be there. The scores 
are 3, 5, 4: the loop
+    // stops after 3 iterations.
+    val src = textInput("3\n5\n4\n6")
+    val start = loopStart("i = 0\nprev = None\nscore = 0", "table.iloc[i]")
+    val jvm = limit(10)
+    val mid = scoringPythonUDF()
+    val end = loopEnd("again = prev is None or score > prev\nprev = score\ni 
+= 1", "again")
+    val materialized = runAndGetMaterializedRowCounts(
+      List(src, start, jvm, mid, end),
+      List(link(src, start), link(start, jvm), link(jvm, mid), link(mid, end))
+    )
+    val endRows = materialized.getOrElse(end.operatorIdentifier, -1L)
+    assert(
+      endRows == 3,
+      s"prev = None must reach Loop End through the Limit, and the loop must 
stop on the first " +
+        s"score that does not improve (3, 5, 4): expected 3, got $endRows 
(all: $materialized)"
+    )
+  }
+
+  it should "give a JVM operator the value the loop body publishes in every 
iteration" in {
+    // TextInput("1","2","3") -> LoopStart(i = 0 / table.iloc[i]) -> scoring 
UDF
+    //   -> Filter(line = $score) -> LoopEnd(i += 1 / i < len(table)).
+    // The UDF publishes the row it saw as `score`, a value for one iteration 
and not a loop
+    // variable, so Loop End does not save it for the next iteration. If it 
did, Loop Start's next
+    // message would carry the old score and the Filter would get two 
different values of it in
+    // one iteration. Each iteration's row passes its Filter: 3 rows.
+    val src = textInput("1\n2\n3")
+    val start = loopStart("i = 0", "table.iloc[i]")

Review Comment:
   Unlike the two tests above, this test omits `score = 0` in `Loop Start` and 
never assigns `score` in `Loop End`. Because `$var` binding rejects any second 
message at the same depth even before the first row arrives, setting `score = 
0` in `Loop Start` or assigning `score` in `update` fails at `Filter(line = 
$score)` with `"loop variable score got two different values in one 
iteration"`. Let a message arriving before the first row update the unbound 
`$var` value.



##########
amber/src/main/python/core/models/operator.py:
##########
@@ -392,6 +393,26 @@ def _eval_loop_expr(expr: str, state: State, table: 
Optional[Table]):
     return eval(expr, namespace)
 
 
+def _assigned_names(code: str) -> frozenset[str]:
+    """Return the names ``code`` assigns: every name it stores to (an
+    assignment, augmented, annotated, walrus, ``for`` or ``with`` target),
+    every name an import binds, and the names of the functions and classes it
+    defines. It reads the code rather than a run of it, so a conditional
+    assignment counts, and so does a name bound only inside a comprehension or
+    inside a function the code defines."""
+    names = set()
+    for node in ast.walk(ast.parse(code)):
+        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
+            names.add(node.id)
+        elif isinstance(node, (ast.Import, ast.ImportFrom)):
+            names.update(
+                (alias.asname or alias.name).split(".")[0] for alias in 
node.names
+            )
+        elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, 
ast.ClassDef)):
+            names.add(node.name)

Review Comment:
   Running `update` directly in the state dictionary and recording imports, 
functions, and classes as assigned loop variables leaves module, function, and 
class objects in `Loop End`'s state (and in `Loop Start`'s state after `init`). 
When `condition` is `True`, writing the next iteration's state fails with 
`"TypeError: State value of type module is not JSON serializable"` (or `"type 
function"`). Keep imported modules, functions, and classes out of the saved 
state in both `Loop Start` and `Loop End`.



##########
amber/src/main/python/core/runnables/main_loop.py:
##########
@@ -512,93 +568,78 @@ def _process_state_frame(self, frame: StateFrame) -> None:
             # all of its own iterations.
             self.context.output_manager.reset_output_storage()
             # State belongs to an outer loop: step one level out and forward,
-            # carrying the outer loop's id unchanged.
-            self._emit_and_save_state(state, in_counter - 1, 
frame.loop_start_id)
+            # carrying the outer loop's id and the message id unchanged.
+            self._emit_and_save_state(
+                state, in_counter - 1, frame.loop_start_id, frame.message_id
+            )
             self._check_and_process_control()
             return

Review Comment:
   In a nested loop where the outer `Loop Start` sets `threshold = 10` and the 
inner `Loop Start`'s `output` or inner `Loop End`'s `condition` reads 
`threshold`, both inner boundaries forward the outer state message without 
recording its variables, failing with `"NameError: name 'threshold' is not 
defined"`. Record outer-loop state messages in a read-only outer scope on inner 
`Loop Start` and `Loop End` so their expressions can read outer variables 
without writing them to the inner back-edge.



##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala:
##########
@@ -150,8 +164,12 @@ class DataProcessor(
         // Carry the incoming loop envelope through unchanged: loop operators
         // are Python-only, so a JVM operator inside a loop body only ever
         // forwards the envelope (the +1/-1 bookkeeping lives in the Python
-        // runtime's _process_state_frame).
-        outputManager.emitState(outputState.get, loopCounter, loopStartId)
+        // runtime's _process_state_frame). A state sent on unchanged is the
+        // same message and keeps its id; a changed one is a new message.
+        val outputMessageId =
+          if (outputState.get.toJson == state.toJson) messageId

Review Comment:
   Nit: Every operator in a loop body serializes both the incoming and outgoing 
state maps to JSON strings on every state message to check whether the state 
changed, even though the default pass-through returns the input state 
unchanged. Check reference identity (or direct equality on the JVM) before 
serializing to JSON.



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