aglinxinyuan commented on code in PR #9366:
URL: https://github.com/apache/texera/pull/9366#discussion_r4535784901


##########
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:
   Done in fa08044725 — a UDF that changes `Loop Start`'s message now sends the 
message on unchanged before its change, so the `Sleep` branch's later copy is 
dropped at `Loop End`, and `Loop End` applies `Loop Start`'s message first and 
every other message after it, in arrival order, so the copy can't overwrite `x 
= 2`. Unit tests in d0280bfb51 cover both orders, and `LoopIntegrationSpec` 
runs your split-body workflow.
   



##########
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:
   Done in fa08044725 — `_assigned_names` is gone: `run_update` now records the 
names the update binds at top level as it runs, so the generator's `score` in 
`total = sum(score for score in table["v"])` is not saved, while `score = score 
* 2` is (tests in d0280bfb51).
   



##########
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:
   Done in fa08044725 — modules, classes, functions (`def`s and imported Python 
or built-in functions) and names that start and end with two underscores, such 
as the `__annotations__` an annotated assignment binds now stay out of what 
`Loop Start` sends and what `Loop End` saves (`without_definitions`, tests in 
d0280bfb51), while staying usable in `update` and `condition`, or in `Loop 
Start`'s `output`. Another kind of callable, such as a numpy ufunc imported by 
name, is still sent and fails to serialize.
   



##########
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:
   Good catch — main already has this gap (both inner boundaries only forward 
the outer message, and the inner body's operators lose it after the first inner 
iteration), so we'll take it up in #9409, with a read-only outer scope that 
every inner iteration sees, instead of growing this PR.
   



##########
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:
   Done in fa08044725 — a later message from the same loop now replaces an 
unbound `$var` value, and once the operator binds it, at its first row or when 
one of its inputs ends, the value stays without an error; d0280bfb51 changes 
this case to set `score = 0` in `Loop Start` and keep `score` in `update` 
(`score = int(score)`).
   



##########
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:
   Done in fa08044725 — `Loop End` now clears its per-iteration state (the loop 
id, the unstamped flag and the collected messages) right after the back-edge 
write, so a second iteration that only gets an unstamped state raises the 
lost-envelope error (test in d0280bfb51).
   



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