This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git


The following commit(s) were added to refs/heads/main by this push:
     new 4fba9ebcfa feat(pyamber): register the state before process_state 
(#8642)
4fba9ebcfa is described below

commit 4fba9ebcfaa3fc8437ef4c2479fef3d0ebb0071b
Author: Xinyuan Lin <[email protected]>
AuthorDate: Tue Nov 10 02:54:18 2026 +0000

    feat(pyamber): register the state before process_state (#8642)
    
    ### What changes were proposed in this PR?
    
    Inside a control block (Loop Start ... Loop End), the loop variables
    reach every operator as state messages. Until now a Python operator saw
    each message only as the argument of `process_state`. With this PR it
    can read the loop variables at any point, in `process_tuple` or
    `process_table` too, through `self.loop_variables`.
    
    - `Operator.loop_variables` is a read-only mapping of the loop variables
    the operator received from upstream, by name. It is empty until the
    first state message arrives.
    - The worker calls `Operator.register_state(state, loop_counter)` for
    every state message, right before `process_state`: in
    `DataProcessor.process_state`, and in the Loop End's deferred consume in
    `MainLoop`, which calls the operator directly. `loop_counter` is the
    nesting depth on the message's envelope: 0 from the innermost loop
    around the operator, 1 from the loop around that, and so on.
    
    For each name, the value from the smallest depth wins, so an inner
    loop's variable shadows an outer one of the same name, even when another
    copy of the outer message arrives later, and a message adds only the
    names it carries. A message from the same depth may repeat a value, as
    copies from several workers or branches do, but not change it: reading a
    name that got two different values from one depth fails with the error a
    JVM operator whose setting refers to it gets (`StateReferenceBinding`),
    and the other names still read:
    
    ```
    state message                        depth   self.loop_variables
    {i: 1, n: 10}  from the outer loop     1     {i: 1, n: 10}
    {i: 5}         from the inner loop     0     {i: 5, n: 10}
    {i: 1}         from the outer loop     1     {i: 5, n: 10}              the 
inner i still wins
    {note: "x"}    from a body UDF         0     {i: 5, n: 10, note: "x"}   
adds its own name only
    {i: 9}         from a body UDF         0     reading i fails: "loop 
variable i got two different values in one iteration, 5 and 9"
    ```
    
    A state no loop sent, such as one a body operator returns from
    `produce_state_on_finish`, travels at depth 0. It adds only the names it
    carries, so a UDF behind a stateful UDF still reads the loop's `i`; a
    state that carries `i` with another value makes reading `i` fail, as
    above.
    
    `process_state` itself is unchanged: the default still forwards the
    message. Loop Start and Loop End keep their own variables in
    `self.state`, as on `main`.
    
    ### Any related issues, documentation, discussions?
    
    Closes #8641.
    
    ### How was this PR tested?
    
    New tests at three levels; each new unit test was run red before its
    change.
    
    - Operator (`test_operator.py`): `loop_variables` is empty until a state
    is registered; reading a name that got two different values from one
    depth raises the JVM's error, while equal copies read, the other names
    read and the name stays listed; an inner value wins over an outer one
    that arrives later, at any depth, also over two different outer values;
    an outer variable the inner loop does not name stays visible; a state
    that names no loop variable leaves them intact; the mapping is read-only
    and per instance, also when a subclass `__init__` skips `super()`; the
    registered message is left unchanged.
    - Worker (`test_data_processor.py`, `test_main_loop.py`): the state is
    registered before `process_state` runs, with the depth from its
    envelope, and in the Loop End's deferred consume too; an operator still
    reads `i` in `process_tuple` after another operator's state arrives, and
    fails with that error when the state carries `i` with another value,
    also through the real `MainLoop` and `DataProcessor` threads; Loop
    Start's first-entry merge and Loop End's back edge still use their own
    `state`.
    - End to end (`LoopIntegrationSpec`), `Text Input (a, b, c) -> Loop
    Start (i = 0, table.iloc[i]) -> ... -> Loop End (i += 1 while i <
    len(table))`: a Python UDF that writes `self.loop_variables["i"]` into
    each row in `process_tuple` produces `(a, 0), (b, 1), (c, 2)`, and so
    does one that reads it in `process_table` behind a UDF that returns its
    own state from `produce_state_on_finish`. That second case fails with
    `KeyError: 'i'` when `loop_variables` holds only the latest message.
    
    ```
    cd amber && pytest src/test/python/core/models 
src/test/python/core/runnables \
      
src/test/python/core/architecture/managers/test_state_processing_manager.py
    # 475 passed, 9 skipped, 1 xfailed; on Windows only, test_tuple.py's 
test_hash fails, as on main
    ruff check src/main/python src/test/python && ruff format --check 
src/main/python src/test/python
    # clean
    sbt "WorkflowExecutionService/testOnly 
org.apache.texera.amber.engine.e2e.LoopIntegrationSpec -- -z UDF"
    # 2 passed
    sbt "WorkflowExecutionService/scalafmtCheckAll" 
"WorkflowExecutionService/scalafixAll --check"
    # clean
    ```
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Fable 5.1, Claude Opus 5.5)
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
---
 .../managers/state_processing_manager.py           |   3 +
 amber/src/main/python/core/models/operator.py      | 118 +++++++++-
 .../main/python/core/runnables/data_processor.py   |  10 +-
 amber/src/main/python/core/runnables/main_loop.py  |   5 +
 .../amber/engine/e2e/LoopIntegrationSpec.scala     | 100 +++++++++
 amber/src/test/python/core/models/test_operator.py | 140 ++++++++++++
 .../python/core/runnables/test_data_processor.py   | 238 ++++++++++++++++++++-
 .../test/python/core/runnables/test_main_loop.py   | 168 ++++++++++++++-
 8 files changed, 772 insertions(+), 10 deletions(-)

diff --git 
a/amber/src/main/python/core/architecture/managers/state_processing_manager.py 
b/amber/src/main/python/core/architecture/managers/state_processing_manager.py
index 442b6e0356..f8e0a5ed93 100644
--- 
a/amber/src/main/python/core/architecture/managers/state_processing_manager.py
+++ 
b/amber/src/main/python/core/architecture/managers/state_processing_manager.py
@@ -23,6 +23,9 @@ from core.models.state import State
 class StateProcessingManager:
     def __init__(self):
         self.current_input_state: Optional[State] = None
+        # The nesting depth (loop_counter) the envelope of current_input_state
+        # carried, for the operator to register the state with.
+        self.current_input_loop_counter: int = 0
         self.current_output_state: Optional[State] = None
 
     def get_input_state(self) -> Optional[State]:
diff --git a/amber/src/main/python/core/models/operator.py 
b/amber/src/main/python/core/models/operator.py
index 1b6ff18c49..c5ed52349a 100644
--- a/amber/src/main/python/core/models/operator.py
+++ b/amber/src/main/python/core/models/operator.py
@@ -20,7 +20,17 @@ import pandas
 from functools import lru_cache
 from abc import ABC, abstractmethod
 from collections import defaultdict
-from typing import Iterator, List, Mapping, Optional, Union, MutableMapping, 
Protocol
+from typing import (
+    Any,
+    Iterator,
+    List,
+    Mapping,
+    Optional,
+    Union,
+    MutableMapping,
+    Protocol,
+    Tuple as TypingTuple,
+)
 
 from . import Table, TableLike, Tuple, TupleLike, Batch, BatchLike, Schema
 from .state import State
@@ -45,6 +55,42 @@ def require_yielded(result, method_name: str):
     return result
 
 
+class _LoopVariables(Mapping):
+    """
+    A read-only view of an operator's loop variables. Reading a name that got
+    two different values from the same loop raises the error a JVM operator
+    whose setting refers to that name raises (``StateReferenceBinding``); the
+    other names read as usual, and the name itself is still listed.
+    """
+
+    def __init__(
+        self,
+        values: Mapping[str, Any],
+        conflicts: Mapping[str, TypingTuple[Any, Any]],
+    ) -> None:
+        self._values = values
+        self._conflicts = conflicts
+
+    def __getitem__(self, name: str) -> Any:
+        if name in self._conflicts:
+            earlier, later = self._conflicts[name]
+            raise RuntimeError(
+                f"loop variable {name} got two different values in one 
iteration, "
+                f"{earlier} and {later}: a loop's variables must not change 
inside "
+                "its body"
+            )
+        return self._values[name]
+
+    def __contains__(self, name: object) -> bool:
+        return name in self._values
+
+    def __iter__(self) -> Iterator[str]:
+        return iter(self._values)
+
+    def __len__(self) -> int:
+        return len(self._values)
+
+
 class Operator(ABC):
     """
     Abstract base class for all operators.
@@ -92,6 +138,76 @@ class Operator(ABC):
 
     __internal_is_source: bool = False
 
+    # The loop variables received so far, by name, and the nesting depth of
+    # the message each value came in; see ``register_state``. ``None`` until
+    # the first state message. Class-level defaults rather than ``__init__``
+    # assignments: a subclass ``__init__`` that skips ``super()`` still reads
+    # no loop variables until a state arrives.
+    __internal_loop_variables: Optional[MutableMapping[str, Any]] = None
+    __internal_loop_variable_depths: Optional[MutableMapping[str, int]] = None
+    # The names that got two different values at the depth they are held at,
+    # with those two values; see ``register_state``.
+    __internal_loop_variable_conflicts: Optional[
+        MutableMapping[str, TypingTuple[Any, Any]]
+    ] = None
+
+    @property
+    @overrides.final
+    def loop_variables(self) -> Mapping[str, Any]:
+        """
+        The loop variables received from upstream, read-only: inside a control
+        block, the values the state messages handed to this operator carried,
+        by name. The runtime registers each message (``register_state``) right
+        before ``process_state`` runs, so the callback and every call after it
+        can read them. Empty until a state message arrives. Reading a name
+        that got two different values from the same loop raises an error; see
+        ``register_state``.
+        """
+        return _LoopVariables(
+            self.__internal_loop_variables or {},
+            self.__internal_loop_variable_conflicts or {},
+        )
+
+    @overrides.final
+    def register_state(self, state: State, loop_counter: int = 0) -> None:
+        """
+        Merge the values ``state`` carries into ``loop_variables``. The runtime
+        calls this for every state message, with the nesting depth its envelope
+        carries (``loop_counter``): 0 from the innermost loop around this
+        operator, 1 from the loop around that, and so on. A state no loop sent,
+        such as one an operator returns from ``produce_state_on_finish``,
+        travels at depth 0.
+
+        For each name, the value from the smallest depth wins. So an inner
+        loop's variable shadows an enclosing one of the same name, even when 
the
+        enclosing message arrives later, and a state adds only the names it
+        carries. A message from the same depth may repeat a value, as copies
+        from several upstream workers or branches do, but must not change it:
+        reading a name that got two different values from one depth raises the
+        error a JVM operator whose setting refers to it raises
+        (``StateReferenceBinding``), until a value from a smaller depth 
replaces
+        both.
+
+        :param state: State, the state message that arrived.
+        :param loop_counter: int, the message's nesting depth.
+        """
+        if self.__internal_loop_variables is None:
+            self.__internal_loop_variables = {}
+            self.__internal_loop_variable_depths = {}
+            self.__internal_loop_variable_conflicts = {}
+        for name, value in state.items():
+            depth = self.__internal_loop_variable_depths.get(name)
+            if depth is None or loop_counter < depth:
+                self.__internal_loop_variables[name] = value
+                self.__internal_loop_variable_depths[name] = loop_counter
+                self.__internal_loop_variable_conflicts.pop(name, None)
+            elif loop_counter == depth:
+                earlier = self.__internal_loop_variables[name]
+                if earlier != value:
+                    self.__internal_loop_variable_conflicts.setdefault(
+                        name, (earlier, value)
+                    )
+
     @property
     @overrides.final
     def is_source(self) -> bool:
diff --git a/amber/src/main/python/core/runnables/data_processor.py 
b/amber/src/main/python/core/runnables/data_processor.py
index 54192e1cf5..b848589f67 100644
--- a/amber/src/main/python/core/runnables/data_processor.py
+++ b/amber/src/main/python/core/runnables/data_processor.py
@@ -64,7 +64,9 @@ class DataProcessor(Runnable, Stoppable):
             if has_marker:
                 self.process_internal_marker(tpm.get_internal_marker())
             elif has_state:
-                self.process_state(spm.get_input_state())
+                self.process_state(
+                    spm.get_input_state(), spm.current_input_loop_counter
+                )
             else:
                 self.process_tuple()
 
@@ -105,12 +107,16 @@ class DataProcessor(Runnable, Stoppable):
             port_identity
         ).get_schema()
 
-    def process_state(self, state: State) -> None:
+    def process_state(self, state: State, loop_counter: int = 0) -> None:
         """
         Process an input marker by invoking appropriate state
         or tuple generation based on the marker type.
         """
         with self._executor_session() as (executor, port_id):
+            # Register the state message, with the nesting depth its envelope
+            # carried, before the callback runs, so process_state (and every
+            # call after it) can read its values in self.loop_variables.
+            executor.register_state(state, loop_counter)
             self._set_output_state(executor.process_state(state, port_id))
 
     def process_tuple(self) -> None:
diff --git a/amber/src/main/python/core/runnables/main_loop.py 
b/amber/src/main/python/core/runnables/main_loop.py
index 2664925fb8..72abba2549 100644
--- a/amber/src/main/python/core/runnables/main_loop.py
+++ b/amber/src/main/python/core/runnables/main_loop.py
@@ -200,6 +200,10 @@ class MainLoop(StoppableQueueBlockingRunnable):
         with replace_print(
             self.context.worker_id, 
self.context.console_message_manager.print_buf
         ):
+            # This deferred consume bypasses DataProcessor.process_state, so
+            # register the state here too, before the callback runs. A
+            # matching loop state is consumed at loop_counter == 0.
+            executor.register_state(pending, 0)
             executor.process_state(pending, 0)
 
     def _jump_to_loop_start(
@@ -596,6 +600,7 @@ class MainLoop(StoppableQueueBlockingRunnable):
             return
 
         self.context.state_processing_manager.current_input_state = state
+        self.context.state_processing_manager.current_input_loop_counter = 
in_counter
         self.process_input_state(
             output_loop_counter=in_counter,
             output_loop_start_id=frame.loop_start_id,
diff --git 
a/amber/src/test/integration/org/apache/texera/amber/engine/e2e/LoopIntegrationSpec.scala
 
b/amber/src/test/integration/org/apache/texera/amber/engine/e2e/LoopIntegrationSpec.scala
index f08681beae..8b2a13e972 100644
--- 
a/amber/src/test/integration/org/apache/texera/amber/engine/e2e/LoopIntegrationSpec.scala
+++ 
b/amber/src/test/integration/org/apache/texera/amber/engine/e2e/LoopIntegrationSpec.scala
@@ -24,6 +24,7 @@ import org.apache.pekko.actor.{ActorSystem, Props}
 import org.apache.pekko.testkit.{ImplicitSender, TestKit}
 import org.apache.pekko.util.Timeout
 import org.apache.texera.amber.clustering.SingleNodeListener
+import org.apache.texera.amber.core.tuple.{Attribute, AttributeType}
 import org.apache.texera.amber.core.virtualidentity.OperatorIdentity
 import org.apache.texera.amber.core.workflow.{
   ExecutionMode,
@@ -237,9 +238,65 @@ class LoopIntegrationSpec
     op
   }
 
+  /** A Python UDF that adds an `i` column to every row it passes: loop 
variable `i`, as it reads
+    * it off `self.loop_variables` in `process_tuple`.
+    */
+  private def pythonUDFReadingLoopVariableInProcessTuple(): PythonUDFOpDescV2 
= {
+    val op = new PythonUDFOpDescV2()
+    op.code = """from pytexera import *
+                |
+                |class ProcessTupleOperator(UDFOperatorV2):
+                |
+                |    @overrides
+                |    def process_tuple(self, tuple_: Tuple, port: int) -> 
Iterator[Optional[TupleLike]]:
+                |        tuple_["i"] = self.loop_variables["i"]
+                |        yield tuple_
+                |""".stripMargin
+    op.workers = 1
+    op.retainInputColumns = true
+    op.outputColumns = List(new Attribute("i", AttributeType.INTEGER))
+    op
+  }
+
+  /** As `pythonUDFReadingLoopVariableInProcessTuple`, but reading `i` in 
`process_table`, which
+    * runs once its input has ended, after every state message on it arrived.
+    */
+  private def pythonUDFReadingLoopVariableInProcessTable(): PythonUDFOpDescV2 
= {
+    val op = new PythonUDFOpDescV2()
+    op.code = """from pytexera import *
+                |
+                |class ProcessTableOperator(UDFTableOperator):
+                |
+                |    @overrides
+                |    def process_table(self, table: Table, port: int) -> 
Iterator[Optional[TableLike]]:
+                |        for line in table["line"]:
+                |            yield {"line": line, "i": 
self.loop_variables["i"]}
+                |""".stripMargin
+    op.workers = 1
+    op.retainInputColumns = true
+    op.outputColumns = List(new Attribute("i", AttributeType.INTEGER))
+    op
+  }
+
   private def link(from: LogicalOp, to: LogicalOp): LogicalLink =
     LogicalLink(from.operatorIdentifier, PortIdentity(), 
to.operatorIdentifier, PortIdentity())
 
+  /** Run the loop workflow and return the (line, i) rows the Loop End `end` 
materialized, sorted. */
+  private def runAndGetLinesWithLoopVariable(
+      operators: List[LogicalOp],
+      links: List[LogicalLink],
+      end: LogicalOp
+  ): List[(String, Int)] =
+    runWorkflowAndReadResults(
+      system,
+      buildWorkflow(operators, links, materializedContext()),
+      List(end.operatorIdentifier),
+      _.get().toList,
+      Duration.fromSeconds(90)
+    ).getOrElse(end.operatorIdentifier, Nil)
+      .map(row => (row.getField[String]("line"), row.getField[Int]("i")))
+      .sorted
+
   "Engine" should "run a single TextInput -> LoopStart -> LoopEnd loop for 
exactly 3 iterations" in {
     val src = textInput("1\n2\n3")
     val start = loopStart("i = 0", "table.iloc[i]")
@@ -496,4 +553,47 @@ class LoopIntegrationSpec
     )
   }
 
+  it should "read a loop variable in a Python UDF on every iteration" in {
+    // TextInput("a","b","c") -> LoopStart(i = 0 / table.iloc[i]) -> Python 
UDF -> LoopEnd.
+    // Iteration i hands the UDF the row of index i, and the UDF adds the i it 
reads off
+    // self.loop_variables in process_tuple, so the LoopEnd accumulates (a, 
0), (b, 1), (c, 2).
+    // A UDF that kept reading the first iteration's i would write 0 on every 
row.
+    val src = textInput("a\nb\nc")
+    val start = loopStart("i = 0", "table.iloc[i]")
+    val mid = pythonUDFReadingLoopVariableInProcessTuple()
+    val end = loopEnd("i += 1", "i < len(table)")
+    val rows = runAndGetLinesWithLoopVariable(
+      List(src, start, mid, end),
+      List(link(src, start), link(start, mid), link(mid, end)),
+      end
+    )
+    assert(
+      rows == List(("a", 0), ("b", 1), ("c", 2)),
+      s"each iteration's row must carry that iteration's i: got $rows"
+    )
+  }
+
+  it should "read a loop variable in a Python UDF after another body 
operator's own state arrives" in {
+    // TextInput("a","b","c") -> LoopStart(i = 0 / table.iloc[i]) -> stateful 
Python UDF
+    //   -> Python UDF reading i in process_table -> LoopEnd.
+    // The first UDF returns its own state, {"note": ...}, from 
produce_state_on_finish, so the
+    // second receives that state after the loop's. process_table runs once 
the input ends, after
+    // both arrived, and must still read the loop's i: that state names no 
loop variable, so it
+    // must not hide one. Reading only the latest state message would fail 
with KeyError 'i'.
+    val src = textInput("a\nb\nc")
+    val start = loopStart("i = 0", "table.iloc[i]")
+    val first = statefulPythonUDF()
+    val second = pythonUDFReadingLoopVariableInProcessTable()
+    val end = loopEnd("i += 1", "i < len(table)")
+    val rows = runAndGetLinesWithLoopVariable(
+      List(src, start, first, second, end),
+      List(link(src, start), link(start, first), link(first, second), 
link(second, end)),
+      end
+    )
+    assert(
+      rows == List(("a", 0), ("b", 1), ("c", 2)),
+      s"each iteration's row must carry that iteration's i: got $rows"
+    )
+  }
+
 }
diff --git a/amber/src/test/python/core/models/test_operator.py 
b/amber/src/test/python/core/models/test_operator.py
index cf0fb17f27..edb674ea00 100644
--- a/amber/src/test/python/core/models/test_operator.py
+++ b/amber/src/test/python/core/models/test_operator.py
@@ -289,6 +289,146 @@ class TestOperatorDefaultMethods:
         assert list(_ConcreteOperator().on_finish(port=0)) == [None]
 
 
+class TestLoopVariables:
+    # Inside a control block the loop variables reach an operator as state
+    # messages; the runtime registers each one (register_state) right before
+    # process_state, with the nesting depth its envelope carries: 0 from the
+    # innermost loop around the operator, 1 from the loop around that. A state
+    # no loop sent (an operator's produce_state_on_finish) travels at depth 0.
+
+    def test_empty_until_the_runtime_registers_a_state(self):
+        assert dict(_ConcreteOperator().loop_variables) == {}
+
+    def test_holds_the_variables_a_registered_state_carries(self):
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 2, "k": "a"}), 0)
+        assert dict(op.loop_variables) == {"i": 2, "k": "a"}
+
+    def test_a_state_that_names_no_loop_variable_leaves_them_intact(self):
+        # The loop's state, then a body operator's own state from
+        # produce_state_on_finish, both at depth 0: the second adds its names
+        # and must not erase i (Xiaozhen's KeyError 'i' on #8642).
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 2}), 0)
+        op.register_state(State({"note": "from-body-op"}), 0)
+        assert dict(op.loop_variables) == {"i": 2, "note": "from-body-op"}
+
+    def test_two_different_values_from_the_same_depth_fail_when_read(self):
+        # Xiaozhen's case on #8642: the loop's i = 0, then a body operator's
+        # state carrying i = 99, both at depth 0. A JVM operator whose setting
+        # refers to i fails with this message (StateReferenceBinding); a UDF
+        # gets the same one when it reads i.
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 0, "k": "a"}), 0)
+        op.register_state(State({"i": 99}), 0)
+        with pytest.raises(RuntimeError) as error:
+            op.loop_variables["i"]
+        assert str(error.value) == (
+            "loop variable i got two different values in one iteration, 0 and 
99: "
+            "a loop's variables must not change inside its body"
+        )
+        for read in (
+            lambda view: view.get("i"),
+            lambda view: dict(view),
+            lambda view: list(view.values()),
+            lambda view: list(view.items()),
+        ):
+            with pytest.raises(RuntimeError, match="two different values"):
+                read(op.loop_variables)
+        # Only reading i fails: the other names read, and i is still listed.
+        assert op.loop_variables["k"] == "a"
+        assert "i" in op.loop_variables
+        assert sorted(op.loop_variables) == ["i", "k"]
+        assert len(op.loop_variables) == 2
+
+    def test_equal_copies_from_the_same_depth_read_without_error(self):
+        # Copies of one message, from several upstream workers or branches,
+        # carry equal values: no conflict, as on the JVM (2 equals 2.0 there).
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 2}), 0)
+        op.register_state(State({"i": 2}), 0)
+        op.register_state(State({"i": 2.0}), 0)
+        assert op.loop_variables["i"] == 2
+        assert dict(op.loop_variables) == {"i": 2}
+
+    def test_an_inner_value_replaces_two_different_outer_ones(self):
+        # The enclosing loop delivered two different values of i, then the
+        # inner loop's own i arrives: the operator reads the inner one.
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 1}), 1)
+        op.register_state(State({"i": 2}), 1)
+        op.register_state(State({"i": 5}), 0)
+        assert op.loop_variables["i"] == 5
+
+    def 
test_different_outer_values_after_an_inner_one_read_the_inner_one(self):
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 5}), 0)
+        op.register_state(State({"i": 1}), 1)
+        op.register_state(State({"i": 2}), 1)
+        assert op.loop_variables["i"] == 5
+
+    def test_the_inner_value_wins_over_an_outer_one_that_arrives_later(self):
+        # i = 1 from the outer loop, i = 5 from the inner one, then the outer
+        # message again: the smallest depth wins, as a JVM operator binds it.
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 1}), 1)
+        assert op.loop_variables["i"] == 1, "the outer i until the inner 
arrives"
+        op.register_state(State({"i": 5}), 0)
+        op.register_state(State({"i": 1}), 1)
+        assert op.loop_variables["i"] == 5
+
+    def 
test_an_outer_variable_the_inner_loop_does_not_name_stays_visible(self):
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 1, "n": 10}), 1)
+        op.register_state(State({"i": 5}), 0)
+        assert dict(op.loop_variables) == {"i": 5, "n": 10}
+
+    def test_a_deeper_message_takes_over_from_an_outer_one_at_any_depth(self):
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 1}), 2)
+        op.register_state(State({"i": 2}), 1)
+        op.register_state(State({"i": 3}), 2)
+        assert op.loop_variables["i"] == 2
+
+    def test_registering_leaves_the_state_message_unchanged(self):
+        op = _ConcreteOperator()
+        first, second = State({"i": 1}), State({"note": "n"})
+        op.register_state(first, 0)
+        op.register_state(second, 0)
+        assert first == State({"i": 1})
+        assert second == State({"note": "n"})
+
+    def test_loop_variables_are_read_only(self):
+        # A UDF changes a loop variable by sending a state message, which
+        # downstream operators then receive too, not by writing this view.
+        op = _ConcreteOperator()
+        op.register_state(State({"i": 1}), 0)
+        with pytest.raises(TypeError):
+            op.loop_variables["i"] = 2
+        assert op.loop_variables["i"] == 1
+
+    def test_registers_on_the_instance_only(self):
+        # The defaults live on the class, so a registration written to the
+        # class (instead of the instance) would reach every operator.
+        target, bystander = _ConcreteOperator(), _ConcreteOperator()
+        target.register_state(State({"i": 1}), 0)
+        assert dict(bystander.loop_variables) == {}
+        assert dict(_ConcreteOperator().loop_variables) == {}
+
+    def test_a_subclass_init_that_skips_super_still_reads_and_registers(self):
+        class _NoSuperInit(TupleOperatorV2):
+            def __init__(self):
+                pass
+
+            def process_tuple(self, tuple_, port):
+                yield tuple_
+
+        op = _NoSuperInit()
+        assert dict(op.loop_variables) == {}
+        op.register_state(State({"i": 1}), 0)
+        assert dict(op.loop_variables) == {"i": 1}
+
+
 class TestLazyTemplateDecoder:
     def test_first_call_creates_decoder_and_caches_on_instance(self):
         op = _ConcreteOperator()
diff --git a/amber/src/test/python/core/runnables/test_data_processor.py 
b/amber/src/test/python/core/runnables/test_data_processor.py
index 3ac98e7362..8b27ac3fdc 100644
--- a/amber/src/test/python/core/runnables/test_data_processor.py
+++ b/amber/src/test/python/core/runnables/test_data_processor.py
@@ -23,9 +23,10 @@ import pytest
 from core.architecture.handlers.control.end_channel_handler import 
EndChannelHandler
 from core.architecture.handlers.control.start_channel_handler import 
StartChannelHandler
 from core.architecture.managers import Context
-from core.models import Schema, State, Tuple
+from core.models import Schema, State, Tuple, TupleOperatorV2
 from core.models.internal_queue import InternalQueue
 from core.models.internal_marker import EndChannel, InternalMarker, 
StartChannel
+from core.models.operator import LoopStartOperator
 from core.runnables.data_processor import DataProcessor
 from proto.org.apache.texera.amber.core import (
     ActorVirtualIdentity,
@@ -201,6 +202,221 @@ class TestProcessInternalMarker:
         assert data_processor.switch_calls == 2
 
 
+class _StateSpy(TupleOperatorV2):
+    """
+    Records what `loop_variables` holds at the moment `process_state` runs, so
+    the test can pin that the runtime registers the state message BEFORE the
+    callback rather than after it.
+    """
+
+    def __init__(self):
+        super().__init__()
+        self.seen = []
+
+    def process_tuple(self, tuple_, port):
+        yield tuple_
+
+    def process_state(self, state, port):
+        self.seen.append((dict(self.loop_variables), port))
+        return super().process_state(state, port)
+
+
+class _LoopVariableReader(TupleOperatorV2):
+    """For every tuple, outputs the loop variable `i` it reads off 
`loop_variables`."""
+
+    def process_tuple(self, tuple_, port):
+        yield Tuple({"x": self.loop_variables["i"]})
+
+
+class _LoopStart(LoopStartOperator):
+    """A Loop Start whose `initialization` seeds one loop variable, `i = 0`."""
+
+    def open(self):
+        self.run_initialization("i = 0")
+
+    def process_table(self, table, port):
+        yield table
+
+
+class TestProcessState:
+    @pytest.mark.timeout(2)
+    def test_registers_state_before_invoking_process_state(
+        self, context, data_processor
+    ):
+        executor = _StateSpy()
+        context.executor_manager.executor = executor
+        context.tuple_processing_manager.current_input_port_id = 
PortIdentity(0, False)
+
+        state = State({"i": 2})
+        data_processor.process_state(state)
+
+        # The callback observed the state already registered, on its port...
+        assert executor.seen == [({"i": 2}, 0)]
+        # ...it stays registered afterwards, and the default still forwards.
+        assert executor.loop_variables == {"i": 2}
+        assert context.state_processing_manager.current_output_state is state
+        assert not context.exception_manager.has_exception()
+        # `_executor_session` always switches once on exit.
+        assert data_processor.switch_calls == 1
+
+    @pytest.mark.timeout(2)
+    def test_a_later_state_message_adds_to_the_registered_one(
+        self, context, data_processor
+    ):
+        # A copy of the loop's state (another upstream worker's), then a state
+        # with one more name: the operator holds both names, on its port.
+        executor = _StateSpy()
+        context.executor_manager.executor = executor
+        context.tuple_processing_manager.current_input_port_id = 
PortIdentity(1, False)
+
+        data_processor.process_state(State({"i": 0}))
+        data_processor.process_state(State({"i": 0}))
+        data_processor.process_state(State({"i": 0, "j": 1}))
+
+        assert executor.seen == [({"i": 0}, 1), ({"i": 0}, 1), ({"i": 0, "j": 
1}, 1)]
+        assert executor.loop_variables == {"i": 0, "j": 1}
+        assert not context.exception_manager.has_exception()
+
+    @pytest.mark.timeout(2)
+    def test_reading_a_loop_variable_two_states_disagree_on_fails(
+        self, context, data_processor, monkeypatch
+    ):
+        # Xiaozhen's case on #8642: inside a loop, a body operator upstream
+        # returns i = 99 from produce_state_on_finish, after the loop's i = 0,
+        # both at depth 0. A JVM operator whose setting refers to i fails;
+        # this operator fails the same way when it reads i in process_tuple,
+        # and outputs nothing.
+        schema = Schema(raw_schema={"x": "INTEGER"})
+        monkeypatch.setattr(
+            context.output_manager,
+            "get_port",
+            lambda *args, **kwargs: SimpleNamespace(get_schema=lambda: schema),
+        )
+        context.executor_manager.executor = _LoopVariableReader()
+        tpm = context.tuple_processing_manager
+        tpm.current_input_port_id = PortIdentity(0, False)
+
+        data_processor.process_state(State({"i": 0}), 0)
+        data_processor.process_state(State({"i": 99}), 0)
+        assert not context.exception_manager.has_exception(), (
+            "registering the two states does not fail; reading i does"
+        )
+
+        outputs = []
+
+        def switch_and_collect():
+            if tpm.current_output_tuple is not None:
+                outputs.append(tpm.get_output_tuple())
+            # Ends process_tuple's loop even when the operator raises.
+            tpm.finished_current.set()
+
+        data_processor._switch_context = switch_and_collect
+        tpm.current_input_tuple = Tuple({"x": 0})
+        data_processor.process_tuple()
+
+        assert context.exception_manager.has_exception()
+        exc_type, exc_value, _ = context.exception_manager.get_exc_info()
+        assert exc_type is RuntimeError
+        assert str(exc_value) == (
+            "loop variable i got two different values in one iteration, 0 and 
99: "
+            "a loop's variables must not change inside its body"
+        )
+        assert outputs == []
+
+    @pytest.mark.timeout(2)
+    def test_registers_on_the_running_operator_only(self, context, 
data_processor):
+        # The default lives on the class, so a registration written to the
+        # class (instead of the running instance) would reach every operator.
+        target, bystander = _StateSpy(), _StateSpy()
+        context.executor_manager.executor = target
+        context.tuple_processing_manager.current_input_port_id = 
PortIdentity(0, False)
+
+        data_processor.process_state(State({"i": 5}))
+
+        assert target.loop_variables == {"i": 5}
+        assert not bystander.loop_variables
+        assert not _StateSpy().loop_variables
+
+    @pytest.mark.timeout(2)
+    def test_reads_the_loop_variable_after_another_operators_state_arrives(
+        self, context, data_processor, monkeypatch
+    ):
+        # Xiaozhen's scenario on #8642: inside a loop, a body operator upstream
+        # returns its own state from produce_state_on_finish, which reaches
+        # this operator after the loop's state, both at depth 0. The operator
+        # must still read the loop's i, here in process_tuple.
+        schema = Schema(raw_schema={"x": "INTEGER"})
+        monkeypatch.setattr(
+            context.output_manager,
+            "get_port",
+            lambda *args, **kwargs: SimpleNamespace(get_schema=lambda: schema),
+        )
+        context.executor_manager.executor = _LoopVariableReader()
+        tpm = context.tuple_processing_manager
+        tpm.current_input_port_id = PortIdentity(0, False)
+
+        data_processor.process_state(State({"i": 2}), 0)
+        data_processor.process_state(State({"note": "from-body-op"}), 0)
+
+        outputs = []
+
+        def switch_and_collect():
+            if tpm.current_output_tuple is not None:
+                outputs.append(tpm.get_output_tuple())
+            # Ends process_tuple's loop even when the operator raises.
+            tpm.finished_current.set()
+
+        data_processor._switch_context = switch_and_collect
+        tpm.current_input_tuple = Tuple({"x": 0})
+        data_processor.process_tuple()
+
+        assert not context.exception_manager.has_exception(), (
+            context.exception_manager.get_exc_info()
+        )
+        assert [output["x"] for output in outputs] == [2]
+
+    @pytest.mark.timeout(2)
+    def test_an_inner_loops_value_wins_over_an_outer_one_arriving_after_it(
+        self, context, data_processor
+    ):
+        # i = 1 from the outer loop (depth 1), i = 5 from the inner loop
+        # (depth 0), then the outer message again: the operator reads the
+        # inner i, as a JVM operator binds it.
+        executor = _StateSpy()
+        context.executor_manager.executor = executor
+        context.tuple_processing_manager.current_input_port_id = 
PortIdentity(0, False)
+
+        data_processor.process_state(State({"i": 1}), 1)
+        data_processor.process_state(State({"i": 5}), 0)
+        data_processor.process_state(State({"i": 1}), 1)
+
+        assert executor.seen == [({"i": 1}, 0), ({"i": 5}, 0), ({"i": 5}, 0)]
+        assert executor.loop_variables == {"i": 5}
+
+    @pytest.mark.timeout(2)
+    def test_a_loop_start_keeps_its_own_state_apart_from_the_loop_variables(
+        self, context, data_processor
+    ):
+        # A LoopStart keeps its own loop variables on `state`, as on main; the
+        # runtime registers the incoming message on `loop_variables`, so the
+        # first-entry merge still merges the message into the LoopStart's own
+        # variables and leaves the message itself unchanged.
+        executor = _LoopStart()
+        executor.open()
+        context.executor_manager.executor = executor
+        context.tuple_processing_manager.current_input_port_id = 
PortIdentity(0, False)
+
+        state = State({"seed": 7})
+        data_processor.process_state(state)
+
+        assert executor.loop_variables == {"seed": 7}
+        assert state == State({"seed": 7}), "the registered message is 
unchanged"
+        assert executor.state == State({"i": 0, "seed": 7})
+        # LoopStart forwards nothing on first entry.
+        assert context.state_processing_manager.current_output_state is None
+        assert not context.exception_manager.has_exception()
+
+
 class TestExecutorSession:
     @pytest.mark.timeout(2)
     def test_exception_inside_session_is_reported_before_the_switch(
@@ -282,6 +498,26 @@ class TestRunInvariant:
         assert "expected exactly one queued input" in str(excinfo.value)
         assert "marker=False, state=False, tuple=False" in str(excinfo.value)
 
+    @pytest.mark.timeout(2)
+    def test_hands_a_queued_state_its_loop_counter(self, context, monkeypatch):
+        # MainLoop queues a state message with the nesting depth its envelope
+        # carried; run() passes both on, so the operator can tell an inner
+        # loop's value from an outer one's.
+        dp = self._drive_run_synchronously(context, monkeypatch)
+        spm = context.state_processing_manager
+        spm.current_input_state = State({"i": 1})
+        spm.current_input_loop_counter = 1
+        calls = []
+
+        def record(state, loop_counter):
+            calls.append((state, loop_counter))
+            dp.stop()
+
+        monkeypatch.setattr(dp, "process_state", record)
+        dp.run()
+
+        assert calls == [(State({"i": 1}), 1)]
+
     @pytest.mark.timeout(2)
     def test_two_queued_inputs_raises_invariant_error(self, context, 
monkeypatch):
         dp = self._drive_run_synchronously(context, monkeypatch)
diff --git a/amber/src/test/python/core/runnables/test_main_loop.py 
b/amber/src/test/python/core/runnables/test_main_loop.py
index 93a7a38536..64753f584e 100644
--- a/amber/src/test/python/core/runnables/test_main_loop.py
+++ b/amber/src/test/python/core/runnables/test_main_loop.py
@@ -221,12 +221,11 @@ class TestMainLoop:
         # In-process executor for the state-pipeline tests. Tags processed
         # states with `processed_marker` and emits a finish-marker state
         # from `produce_state_on_finish` so EndChannel handling can be
-        # observed.
-        class StateProcessingExecutor:
-            # What Operator gives a real executor, for DataProcessor to record
-            # the finishing port's declared schema in.
-            input_schemas: dict = {}
-
+        # observed. An Operator, as every executor the worker loads is: the
+        # runtime registers each state message on it before process_state,
+        # and DataProcessor records the finishing port's declared schema in
+        # its input_schemas.
+        class StateProcessingExecutor(UDFOperatorV2):
             @staticmethod
             def process_tuple(tuple_, port):
                 yield tuple_
@@ -1912,6 +1911,76 @@ class TestMainLoop:
 
         reraise()
 
+    @pytest.mark.timeout(2)
+    def 
test_main_loop_thread_keeps_the_loop_variables_when_another_state_arrives(
+        self,
+        mock_data_input_channel,
+        mock_data_output_channel,
+        mock_control_output_channel,
+        input_queue,
+        output_queue,
+        main_loop,
+        main_loop_thread,
+        mock_assign_input_port,
+        mock_assign_output_port,
+        mock_add_input_channel,
+        mock_add_partitioning,
+        mock_initialize_executor,
+        mock_data_element,
+        command_sequence,
+        reraise,
+    ):
+        # Xiaozhen's scenario on #8642, through the real MainLoop and
+        # DataProcessor threads: inside a loop, the loop's state, then the
+        # state a body operator upstream returns from produce_state_on_finish
+        # (the "no loop" envelope, also depth 0), then a tuple. The operator
+        # must still read the loop's i; reading only the latest state message
+        # fails with KeyError 'i'.
+        class LoopVariableReader(UDFOperatorV2):
+            def process_state(self, state, port):
+                return None  # emit no state, so the tuple is the only output
+
+            def process_tuple(self, tuple_, port):
+                yield Tuple(
+                    {"test-1": tuple_["test-1"], "test-2": 
self.loop_variables["i"]}
+                )
+
+        main_loop_thread.start()
+
+        for setup_msg in [
+            mock_assign_input_port,
+            mock_assign_output_port,
+            mock_add_input_channel,
+            mock_add_partitioning,
+            mock_initialize_executor,
+        ]:
+            input_queue.put(setup_msg)
+            assert output_queue.get() == DCMElement(
+                tag=mock_control_output_channel,
+                payload=DirectControlMessagePayloadV2(
+                    return_invocation=ReturnInvocation(
+                        command_id=command_sequence,
+                        return_value=ControlReturn(empty_return=EmptyReturn()),
+                    )
+                ),
+            )
+
+        main_loop.context.executor_manager.executor = LoopVariableReader()
+
+        for frame in (
+            StateFrame(State({"i": 2}), loop_counter=0, 
loop_start_id="loop-1"),
+            StateFrame(State({"note": "from-body-op"})),
+        ):
+            input_queue.put(DataElement(tag=mock_data_input_channel, 
payload=frame))
+        input_queue.put(mock_data_element)
+
+        output: DataElement = output_queue.get()
+        assert output.tag == mock_data_output_channel
+        assert isinstance(output.payload, DataFrame), output
+        assert output.payload.frame.to_pylist() == [{"test-1": "hello", 
"test-2": 2}]
+
+        reraise()
+
     @staticmethod
     def _expected_port_completed_dcm(
         mock_control_output_channel, command_id, port_id, is_input
@@ -2784,6 +2853,93 @@ class TestMainLoop:
         assert consumed == [(incoming, 0)]
         assert main_loop._pending_loop_state is None, "stash must be cleared"
 
+    def test_loopend_deferred_consume_registers_state_first(
+        self, main_loop, monkeypatch
+    ):
+        # The deferred consume calls process_state directly, bypassing
+        # DataProcessor.process_state (which registers the state message), so
+        # it must register the stashed state itself before the user's update.
+        executor = _FalseLoopEnd()
+        main_loop.context.executor_manager.executor = executor
+        monkeypatch.setattr(
+            main_loop, "_read_loop_input_table", lambda: Table([Tuple({"v": 
1})])
+        )
+        pending = State({"i": 7})
+        main_loop._pending_loop_state = pending
+        seen = []
+        monkeypatch.setattr(
+            executor,
+            "process_state",
+            lambda st, port: seen.append((dict(executor.loop_variables), st)),
+        )
+
+        main_loop._consume_pending_loop_state(executor)
+
+        assert seen == [({"i": 7}, pending)]
+        assert executor.loop_variables == {"i": 7}
+
+    def test_state_frame_reaches_the_operator_with_its_loop_counter(
+        self, main_loop, monkeypatch
+    ):
+        # The operator registers each state message with the nesting depth its
+        # envelope carries, so the frame's loop_counter must reach the
+        # DataProcessor alongside the state.
+        self._capture_state_emit(main_loop, monkeypatch)
+        spm = main_loop.context.state_processing_manager
+        handed = []
+        monkeypatch.setattr(
+            main_loop,
+            "_switch_context",
+            lambda: handed.append(
+                (spm.current_input_state, spm.current_input_loop_counter)
+            ),
+        )
+
+        main_loop._process_state_frame(
+            StateFrame(State({"i": 1}), loop_counter=1, 
loop_start_id="outer-loop")
+        )
+
+        assert handed == [(State({"i": 1}), 1)]
+
+    def test_loopend_back_edge_writes_its_own_state_not_the_loop_variables(
+        self, main_loop, monkeypatch
+    ):
+        # The deferred consume registers the stashed message on
+        # `loop_variables`; the user's update writes the next iteration's loop
+        # variables to the LoopEnd's own `state`. The back-edge must carry the
+        # latter.
+        class _IncrementingLoopEnd(LoopEndOperator):
+            def process_state(self, state, port):
+                self.run_update("i += 1", state)
+                return None
+
+            def condition(self):
+                return True
+
+        executor = _IncrementingLoopEnd()
+        main_loop.context.executor_manager.executor = executor
+        monkeypatch.setattr(
+            main_loop, "_read_loop_input_table", lambda: Table([Tuple({"v": 
1})])
+        )
+        pending = State({"i": 7})
+        main_loop._pending_loop_state = pending
+
+        main_loop._consume_pending_loop_state(executor)
+
+        assert executor.loop_variables == {"i": 7}
+        assert pending == State({"i": 7}), "the registered message is 
unchanged"
+        assert executor.state == State({"i": 8})
+
+        main_loop._loop_start_id = "outer-loop"
+        main_loop.context.loop_start_port_uris = {"outer-loop": 
"vfs:///wf/port/outer"}
+        events = []
+        self._patch_create_document(monkeypatch, events)
+
+        main_loop._jump_to_loop_start(executor, self._stub_coordinator([]))
+
+        puts = [event for event in events if event[0] == "put_one"]
+        assert puts == [("put_one", State({"i": 8}).to_tuple(0))]
+
     def test_loopend_forwards_unstamped_state_without_consuming(
         self, main_loop, monkeypatch
     ):

Reply via email to