You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@texera.apache.org by gi...@apache.org on 2026/10/03 07:40:51 UTC
(texera) 01/01: feat(amber): bind $i loop-variable references in operators (#8639)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-8639-b7993fbafac472d0ef1b87d86169978c42343ac4
in repository https://gitbox.apache.org/repos/asf/texera.git
commit d7ce3a6bff97a43a380ce71ff48f3bc016b261ae
Author: Xinyuan Lin <xi...@uci.edu>
AuthorDate: Sat Oct 3 07:40:27 2026 +0000
feat(amber): bind $i loop-variable references in operators (#8639)
### What changes were proposed in this PR?
Inside a loop block (LoopStart ... LoopEnd), a property of a JVM
operator may now hold `$i`, a reference to the loop variable `i`. This
works for string and numeric/boolean properties alike; the frontend
(#8640) sends the literal `"$i"`, and the operator's own code does not
change. The reference is handled in three places:
- **Parse.** When `"$i"` cannot be converted to a numeric or boolean
property's type, a Jackson problem handler (`StateReferenceModule`) puts
in a typed placeholder (0 / 0.0 / false) and records the property's JSON
pointer in a hidden `stateReferences` sidecar on `LogicalOp`. Strings
are left alone.
- **Compile.** The compiler works out which operators sit inside a loop
block (`LogicalPlan.enclosingLoopStarts`: each operator's Loop Starts,
from folds over the plan's topological order). Inside a block it also
records every whole-string `"$i"` literal. Outside every block, a typed
reference is a compile error.
- **Worker.** The operator's own executor is built and opened as usual,
with the placeholders in its setting: the descriptor its constructor
parses. The worker registers every state message on the executor right
before `processState` (`OperatorExecutor.registerState` and `state`, the
JVM counterpart of Python's `self.state` in #8642). Until the operator
first sees data, each referenced variable that a message carries is
written into that setting, in place. Right before the first tuple, or
the end of input, the worker checks that every reference has a value,
and the setting is not written after that. Copies of one loop's state
that disagree are an error; an inner loop's value shadows an outer one's
(the worker passes each message's nesting depth).
**Which settings can hold `$i`** (inside a loop block)
| Setting | Holds `$i`? | What the user sees |
|---|---|---|
| Text read while the operator processes rows (a Filter's value or
column, ...) | Yes | The iteration's value, written into the setting
before the operator's first row |
| Number, integer or decimal (Limit's `limit`, Interval Join's constant,
...) | Yes | The iteration's value, converted to the setting's type.
Before the run, the compiler sees the placeholder `0` / `0.0` |
| True/false | Yes | Same as a number, with the placeholder `false` |
| A setting the compiled plan is built from: an output column's name or
type, or what an input is partitioned on (Projection's columns and Drop
Option, Unnest String's and Dictionary Matcher's result column,
Aggregate, join keys, Type Casting, Sort Partitions) | No | With #8750,
a compile error: `Projection cannot refer to loop variables (/isDrop ->
$drop): its output schema or partitioning is built from that property
when the workflow is compiled, before the loop runs`. With this PR
alone, a wrong result or the operator's own error (Projection's
missing-column message) |
| Any setting of an operator that runs generated or user code: Python
UDFs (code editor included), sklearn, Python charts, Sort | No | Compile
error: `Sort cannot refer to loop variables yet (/attributes/0/attribute
-> $col): its code is generated before the loop runs` |
| A dropdown of fixed choices (an enum, e.g. a Filter's condition) | No;
the panel (#8640) doesn't offer `$i` there | If it is sent anyway (e.g.
through `SyncExecutionResource`), the workflow fails to parse with
Jackson's `not one of the values accepted for Enum class` |
**Other cases** (replaces the current Case / Behaviour table)
| Case | Behaviour |
|---|---|
| Outside every loop block | A text `"$AAPL"` stays a literal, as on
main. A number or true/false `"$n"` is a compile error: `Limit refers to
loop variables (/limit -> $n), but is not inside a loop block` |
| An input the operator reads first is fed, even by a single link, from
outside one of the operator's loop blocks: from outside the loop, from
an outer loop's body, or from a sibling block | Compile error: `Interval
Join refers to loop variables (/constant -> $i), but its input 'left
table' is fed from outside the loop block, so tuples from there can
arrive before the loop state`. An input read only after one that carries
the state (a join's probe side) may come from anywhere |
| A name no enclosing Loop Start assigns (the panel flags it;
`SyncExecutionResource` doesn't) | Fails at the operator's first row, or
at its finish if it gets no rows: `property /limit refers to loop
variable n, but no state message carried it` |
| A value that doesn't fit the setting | Fails at the same point:
`property /limit refers to loop variable n, but its value abc does not
fit it: ...` |
| Nested loops that name the same variable | The inner loop's value wins
|
| Copies of one loop's state that reach an operator disagree (e.g. a UDF
changed `i` on one branch, and the branches meet) | Fails: `loop
variable i got two different values in one iteration, 1 and 2: a loop's
variables must not change inside its body`. On a single path there is
only one copy, so the operators after the UDF get its changed value |
| Editing the operator while the workflow runs | Refused, with #8750 |
Which operators are inside a block is decided on the plan the compiler
receives. That plan has no disabled operators, and for run-to-operator
it keeps only the target's upstream. The panel decides on the whole
canvas.
**The operator's lifecycle is unchanged.** The value is set in the
operator's setting when the state arrives, so the operator runs exactly
as it does outside a loop:
```
worker starts state messages arrive first tuple
executor built and opened, registered on the executor (state), and every reference has a value, or the operator
placeholders in its setting each variable written into the setting, fails naming the missing ones;
in place (a later message wins) the setting is not written after this
```
`open()` runs at worker start, and `produceStateOnStart` and
`processState` run on the operator itself, with what they return used.
Three executors used to read their setting before a state can arrive,
and now read it at first use: Reservoir Sampling in its constructor, and
Split and Dictionary Matcher in `open()`. Every other JVM executor
already reads its setting while it processes data.
### Any related issues, documentation, discussions?
Closes #8635
Lands together with #8750, which makes `$i` in a setting the compiled
plan is built from a compile error. Frontend: #8640 (merges after this
PR). Python operators: #8642 (independent). User-facing overview:
https://github.com/apache/texera/discussions/8643
### How was this PR tested?
| Suite | Result |
|---|---|
| WorkflowCore: `org.apache.texera.amber.core.state.*` and
`core.executor.*`, incl. `StateReferenceModuleSpec`,
`StateReferenceBindingSpec`, `CoreExecutorReflectionSpec` | 71/71 |
| WorkflowCompiler full `test`, incl. `LogicalPlanSpec` (loop-block
membership and enclosing Loop Starts, checked against a port of the
panel's walk on every case and 400 random plans) and the loop-variable
cases of `WorkflowCompilerSpec` (lenient and strict) | 80/80 |
| WorkflowOperator: Reservoir Sampling, Split, Dictionary Matcher and
metadata specs | 260/260 |
| workflow-compiling-service `test` | 55/55 |
| amber: `Test/compile`, `DataProcessorSpec`, `DPThreadSpec`, the
worker's promise handlers incl. `EndChannelHandlerSpec`,
`ComputingUnitMasterSpec` | 116/116 |
| Lint | `scalafixAll --check` and `scalafmtCheckAll` on all five
touched sbt projects |
```
sbt "project WorkflowCore" "testOnly *StateReferenceModuleSpec *StateReferenceBindingSpec *CoreExecutorReflectionSpec"
sbt "project WorkflowCompiler" test
```
What the tests pin:
- **End to end in unit form.** The frontend's
`{"limit":"$n","operatorType":"Limit"}` is compiled inside `TextInput ->
LoopStart -> Limit -> LoopEnd` and built through `ExecFactory`. After
the state `{n: 2}`, exactly 2 of 5 tuples pass.
- **Parse handovers.** Typed placeholders get the right pointers whether
the object is parsed directly, with the type id first, in the middle or
last, or nested in another document.
- **Compile rules.** Outside every block, Filter `"$AAPL"` stays a
literal and Limit `"$n"` is a compile error. Inside a block, a
Scala-built Filter `"$i"` gets its sidecar, while Sort `"$col"` is a
compile error, and so is an operator with a reference whose read-first
input has a link from outside one of its loop blocks (outside the loop,
an outer loop's body, a sibling block, or one outside link next to an
inside one).
- **Worker.** The executor is built and opened at worker start.
`produceStateOnStart` and `processState` run on the operator itself, and
what `processState` returns is emitted. Each state message writes the
variables into the setting in place, into every property that names
them, top-level and nested pointers alike, keeping the object the
executor holds; an outer `{i: 1}` followed by an inner `{i: 5}` leaves
5. A tuple before any state fails, naming only the missing variables,
and the setting is not written after the first tuple; an operator with
no rows fails the same way at its finish. Copies of one loop's state
with different values fail, equal ones pass, and a deeper loop's value
replaces an outer one's in either arrival order. Values are coerced to
the property's type, and a null, a list or a map for a string property
is refused.
- **Executors.** Reservoir Sampling, Split and Dictionary Matcher use
the value written after construction and `open()`.
- **Mappers.** Every Dropwizard application that parses workflows
registers the module through `JSONUtils.registerWorkflowModules`;
`WorkflowCompilingServiceRunSpec` and `ComputingUnitMasterSpec` parse a
typed `"$n"` through each bootstrap mapper.
`LoopIntegrationSpec` gains three `@IntegrationTest` runs, which CI's
`amber-integration` job runs:
- a number setting: `Limit($n)` with n = 1, 2, 3 gives 1 + 2 + 3 = 6
rows;
- nested loops that both name `i`: `Filter(line = $i)` in the inner body
passes all 2 x 2 rows only with the inner `i`;
- a text setting on two branches meeting at a Union before `Filter(line
= $i)`: 2 copies x 3 iterations = 6 rows (a constant or a `$i` that
never rebinds gives 2).
**Run by hand.** On a local deployment of this PR together with #8642
and #8640 (the test branch in #8645), a workflow `Text Input (1..6) ->
Loop Start (i = 0, output table) -> Limit ($i) -> Loop End (i += 1 while
i < len(table))` runs to completion. Each iteration binds `$i` to its
own `i`, so Loop End collects 0 + 1 + 2 + 3 + 4 + 5 = 15 rows: `1`, then
`1, 2`, then `1, 2, 3`, and so on. The Limit fed straight from Text
Input, outside the loop, keeps its constant 3.
| The Limit's property inside the loop | Loop End's result after the run
|
|---|---|
| 
| 
|

### 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)
---
.../engine/architecture/worker/DataProcessor.scala | 17 ++
.../worker/promisehandlers/EndChannelHandler.scala | 2 +
.../apache/texera/web/ComputingUnitMaster.scala | 7 +-
.../amber/engine/e2e/LoopIntegrationSpec.scala | 103 ++++++++
.../architecture/worker/DataProcessorSpec.scala | 262 ++++++++++++++++++-
.../promisehandlers/EndChannelHandlerSpec.scala | 33 +++
.../texera/web/ComputingUnitMasterSpec.scala | 7 +-
.../texera/common/compiler/WorkflowCompiler.scala | 100 ++++++-
.../texera/common/compiler/model/LogicalPlan.scala | 45 ++++
.../texera/common/compiler/LogicalPlanSpec.scala | 162 ++++++++++++
.../common/compiler/WorkflowCompilerSpec.scala | 282 +++++++++++++++++++-
.../texera/amber/core/executor/ExecFactory.scala | 51 ++++
.../amber/core/executor/OperatorExecutor.scala | 45 ++++
.../core/executor/StateReferenceBinding.scala | 154 +++++++++++
.../amber/core/state/StateReferenceModule.scala | 171 ++++++++++++
.../texera/amber/core/state/StateReferencing.scala | 81 ++++++
.../org/apache/texera/amber/util/JSONUtils.scala | 8 +-
.../core/executor/CoreExecutorReflectionSpec.scala | 173 ++++++++++++-
.../core/executor/StateReferenceBindingSpec.scala | 288 +++++++++++++++++++++
.../core/state/StateReferenceModuleSpec.scala | 262 +++++++++++++++++++
.../apache/texera/amber/operator/LogicalOp.scala | 3 +-
.../dictionary/DictionaryMatcherOpExec.scala | 4 +-
.../metadata/OperatorMetadataGenerator.scala | 3 +
.../ReservoirSamplingOpExec.scala | 11 +-
.../texera/amber/operator/split/SplitOpExec.scala | 5 +-
.../dictionary/DictionaryMatcherOpExecSpec.scala | 7 +-
.../metadata/OperatorMetadataGeneratorSpec.scala | 15 ++
.../ReservoirSamplingOpExecSpec.scala | 54 +++-
.../amber/operator/split/SplitOpExecSpec.scala | 49 ++++
.../texera/service/WorkflowCompilingService.scala | 6 +-
.../service/WorkflowCompilingServiceRunSpec.scala | 7 +-
31 files changed, 2379 insertions(+), 38 deletions(-)
diff --git a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala
index bbe1ed84e7..0bfce2d04b 100644
--- a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala
+++ b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala
@@ -71,6 +71,9 @@ class DataProcessor(
@transient var executor: OperatorExecutor = _
+ /** The executor whose loop-variable references `bindStateReferences` has bound. */
+ @transient private var executorWithBoundReferences: OperatorExecutor = _
+
def initTimerService(adaptiveBatchingMonitor: WorkerTimerService): Unit = {
this.adaptiveBatchingMonitor = adaptiveBatchingMonitor
}
@@ -97,6 +100,16 @@ class DataProcessor(
def collectStatistics(): WorkerStatistics =
statisticsManager.getStatistics(executor)
+ /**
+ * `OperatorExecutor.bindStateReferences`, before the executor first sees data or finishes; after
+ * that a reference comparison per tuple. An executor installed in its place binds its own.
+ */
+ def bindStateReferences(): Unit =
+ if (executorWithBoundReferences ne executor) {
+ executor.bindStateReferences()
+ executorWithBoundReferences = executor
+ }
+
/**
* process currentInputTuple through executor logic.
* this function is only called by the DP thread.
@@ -105,6 +118,8 @@ class DataProcessor(
try {
val portIdentity: PortIdentity =
this.inputGateway.getChannel(inputManager.currentChannelId).getPortId
+ // The executor sees data: its setting must have its loop variables by now.
+ bindStateReferences()
outputManager.outputIterator.setTupleOutput(
executor.processTupleMultiPort(
tuple,
@@ -128,6 +143,8 @@ class DataProcessor(
loopStartId: String
): Unit = {
try {
+ // Before processState, which then sees the loop variables written into the setting.
+ executor.registerState(state, loopCounter)
val outputState = executor.processState(state, port)
if (outputState.isDefined) {
// Carry the incoming loop envelope through unchanged: loop operators
diff --git a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/EndChannelHandler.scala b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/EndChannelHandler.scala
index f1b37d7d32..3e76ce6431 100644
--- a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/EndChannelHandler.scala
+++ b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/EndChannelHandler.scala
@@ -41,6 +41,8 @@ trait EndChannelHandler {
dp.inputManager.getPort(portId).completed = true
dp.inputManager.initBatch(channelId, Array.empty)
try {
+ // The executor finishes: a setting that refers to loop variables must have them by now.
+ dp.bindStateReferences()
val outputState = dp.executor.produceStateOnFinish(portId.id)
if (outputState.isDefined) {
// Operator-ORIGINATED boundary state, so no LoopStart stamp
diff --git a/amber/src/main/scala/org/apache/texera/web/ComputingUnitMaster.scala b/amber/src/main/scala/org/apache/texera/web/ComputingUnitMaster.scala
index 6616ff47d1..6f49fe1c3d 100644
--- a/amber/src/main/scala/org/apache/texera/web/ComputingUnitMaster.scala
+++ b/amber/src/main/scala/org/apache/texera/web/ComputingUnitMaster.scala
@@ -19,7 +19,6 @@
package org.apache.texera.web
-import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.typesafe.scalalogging.LazyLogging
import io.dropwizard.Configuration
import io.dropwizard.configuration.{EnvironmentVariableSubstitutor, SubstitutingSourceProvider}
@@ -40,7 +39,7 @@ import org.apache.texera.amber.engine.common.client.AmberClient
import org.apache.texera.amber.engine.common.storage.SequentialRecordStorage
import org.apache.texera.amber.engine.common.{AmberRuntime, Utils}
import org.apache.texera.amber.util.JSONUtils.objectMapper
-import org.apache.texera.amber.util.ObjectMapperUtils
+import org.apache.texera.amber.util.{JSONUtils, ObjectMapperUtils}
import org.apache.commons.jcs3.access.exception.InvalidArgumentException
import org.apache.texera.auth.SessionUser
import org.apache.texera.dao.SqlServer
@@ -134,8 +133,8 @@ class ComputingUnitMaster extends io.dropwizard.Application[Configuration] with
classOf[PveWebsocketResource]
)
)
- // register scala module to dropwizard default object mapper
- bootstrap.getObjectMapper.registerModule(DefaultScalaModule)
+ // register the modules that parse workflows (SyncExecutionResource) to dropwizard's mapper
+ JSONUtils.registerWorkflowModules(bootstrap.getObjectMapper)
}
override def run(configuration: Configuration, environment: Environment): Unit = {
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 0a567b678b..f08681beae 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
@@ -41,12 +41,19 @@ import org.apache.texera.amber.engine.e2e.TestUtils.{
workflowContext
}
import org.apache.texera.amber.operator.LogicalOp
+import org.apache.texera.amber.operator.filter.{
+ ComparisonType,
+ FilterPredicate,
+ SpecializedFilterOpDesc
+}
import org.apache.texera.amber.operator.limit.LimitOpDesc
import org.apache.texera.amber.operator.loop.{LoopEndOpDesc, LoopStartOpDesc}
import org.apache.texera.amber.operator.sleep.SleepOpDesc
import org.apache.texera.amber.operator.source.scan.text.TextInputSourceOpDesc
import org.apache.texera.amber.operator.udf.python.PythonUDFOpDescV2
+import org.apache.texera.amber.operator.union.UnionOpDesc
import org.apache.texera.amber.tags.IntegrationTest
+import org.apache.texera.amber.util.JSONUtils.objectMapper
import org.apache.texera.common.compiler.model.LogicalLink
import org.scalatest.flatspec.AnyFlatSpecLike
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Outcome, Retries}
@@ -188,6 +195,17 @@ class LoopIntegrationSpec
op
}
+ /** A Limit whose Int `limit` is `"$name"`, parsed as the editor's JSON is, into a placeholder. */
+ private def limitReferringTo(name: String): LogicalOp =
+ objectMapper.readValue(s"""{"operatorType":"Limit","limit":"$$$name"}""", classOf[LogicalOp])
+
+ /** `attribute = value`; a `$name` value refers to a loop variable (bound at the worker). */
+ private def filterEquals(attribute: String, value: String): SpecializedFilterOpDesc = {
+ val op = new SpecializedFilterOpDesc()
+ op.predicates = List(new FilterPredicate(attribute, ComparisonType.EQUAL_TO, value))
+ op
+ }
+
// NOTE: a JavaUDF (runtime-compiled Java) case cannot run in this suite.
// The integration tests run forkless under sbt (fork := false), where
// `javax.tools` sees only the sbt launcher on `java.class.path` -- the
@@ -317,6 +335,91 @@ class LoopIntegrationSpec
)
}
+ it should "bind a $n loop-variable reference in a JVM operator's number setting on every iteration" in {
+ // TextInput(3 rows) -> LoopStart(n = 1 / table) -> Limit($n)
+ // -> LoopEnd(n += 1 / n <= len(table)).
+ // Iteration n passes n of the 3 rows: 1 + 2 + 3 = 6 at the LoopEnd. The placeholder 0 would
+ // give 0, and an n that never rebinds to the new value 3.
+ val src = textInput("a\nb\nc")
+ val start = loopStart("n = 1", "table")
+ val mid = limitReferringTo("n")
+ val end = loopEnd("n += 1", "n <= len(table)")
+ 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 == 6,
+ s"Limit($$n) must pass n rows on iterations n = 1, 2, 3: expected 6, got $endRows " +
+ s"(all: $materialized)"
+ )
+ }
+
+ it should "bind the inner loop's variable where it shadows the outer loop's of the same name" in {
+ // TextInput("0","1") -> OuterStart(i = 0 / table) -> InnerStart(i = 0 / table.iloc[i])
+ // -> Filter(line = $i) -> InnerEnd -> OuterEnd.
+ // Both loops name their variable i. On each first inner iteration the Filter receives both
+ // loops' states, the outer one's a loop further out (loopCounter 1), and must take the inner
+ // i: inner iteration i emits the row "i", so all 2 x 2 rows pass. The outer i on the second
+ // outer iteration (1, against the row "0") would drop one, and treating the two as one loop's
+ // conflicting values would fail the run.
+ val src = textInput("0\n1")
+ val outerStart = loopStart("i = 0", "table")
+ val innerStart = loopStart("i = 0", "table.iloc[i]")
+ val mid = filterEquals("line", "$i")
+ val innerEnd = loopEnd("i += 1", "i < len(table)")
+ val outerEnd = loopEnd("i += 1", "i < len(table)")
+ val materialized = runAndGetMaterializedRowCounts(
+ List(src, outerStart, innerStart, mid, innerEnd, outerEnd),
+ List(
+ link(src, outerStart),
+ link(outerStart, innerStart),
+ link(innerStart, mid),
+ link(mid, innerEnd),
+ link(innerEnd, outerEnd)
+ )
+ )
+ val outerRows = materialized.getOrElse(outerEnd.operatorIdentifier, -1L)
+ assert(
+ outerRows == 4,
+ s"Filter(line = $$i) must bind the inner i on all 4 inner iterations: expected 4, got " +
+ s"$outerRows (all: $materialized)"
+ )
+ }
+
+ it should "bind a $i reference after two branches of the loop body meet again" in {
+ // TextInput("0","1","2") -> LoopStart(i = 0 / table.iloc[i]) -> Limit(10) and Sleep(0)
+ // -> Union -> Filter(line = $i) -> LoopEnd.
+ // The Filter receives the iteration's state once per branch, and the copies agree; the row
+ // "i" arrives once per branch and passes against i: 2 rows on each of 3 iterations.
+ val src = textInput("0\n1\n2")
+ val start = loopStart("i = 0", "table.iloc[i]")
+ val left = limit(10)
+ val right = sleep(0)
+ val union = new UnionOpDesc()
+ val mid = filterEquals("line", "$i")
+ val end = loopEnd("i += 1", "i < len(table)")
+ val materialized = runAndGetMaterializedRowCounts(
+ List(src, start, left, right, union, mid, end),
+ List(
+ link(src, start),
+ link(start, left),
+ link(start, right),
+ link(left, union),
+ link(right, union),
+ link(union, mid),
+ link(mid, end)
+ )
+ )
+ val endRows = materialized.getOrElse(end.operatorIdentifier, -1L)
+ assert(
+ endRows == 6,
+ s"Filter(line = $$i) after the branches meet must pass both copies of each iteration's " +
+ s"row: expected 6, got $endRows (all: $materialized)"
+ )
+ }
+
it should "run a nested loop whose inner body chains multiple JVM operators" in {
// TextInput -> OuterStart -> InnerStart -> Limit -> Sleep(0) -> InnerEnd -> OuterEnd.
//
diff --git a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessorSpec.scala b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessorSpec.scala
index ab1b0ad0b3..c48e959420 100644
--- a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessorSpec.scala
+++ b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessorSpec.scala
@@ -19,8 +19,9 @@
package org.apache.texera.amber.engine.architecture.worker
-import org.apache.texera.amber.core.executor.OperatorExecutor
-import org.apache.texera.amber.core.state.State
+import com.fasterxml.jackson.annotation.JsonProperty
+import org.apache.texera.amber.core.executor.{ExecFactory, OpExecWithClassName, OperatorExecutor}
+import org.apache.texera.amber.core.state.{State, StateReferencing}
import org.apache.texera.amber.core.tuple.{AttributeType, Schema, Tuple, TupleLike}
import org.apache.texera.amber.core.virtualidentity._
import org.apache.texera.amber.core.workflow.{PhysicalLink, PortIdentity}
@@ -35,12 +36,15 @@ import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
ControlInvocation => ControlInvocationMessage,
EmbeddedControlMessage,
EmbeddedControlMessageType,
- EmptyRequest
+ EmptyRequest,
+ InitializeExecutorRequest
}
import org.apache.texera.amber.engine.architecture.rpc.workerservice.WorkerServiceGrpc.{
METHOD_END_CHANNEL,
METHOD_FLUSH_NETWORK_BUFFER,
- METHOD_OPEN_EXECUTOR
+ METHOD_INITIALIZE_EXECUTOR,
+ METHOD_OPEN_EXECUTOR,
+ METHOD_START_CHANNEL
}
import org.apache.texera.amber.engine.architecture.worker.WorkflowWorker.{
DPInputQueueElement,
@@ -55,6 +59,7 @@ import org.apache.texera.amber.engine.common.ambermessage.{
import org.apache.texera.amber.engine.common.rpc.AsyncRPCClient.ControlInvocation
import org.apache.texera.amber.engine.common.storage.SequentialRecordStorage
import org.apache.texera.amber.engine.common.virtualidentity.util.COORDINATOR
+import org.apache.texera.amber.util.JSONUtils.objectMapper
import org.apache.texera.amber.util.VirtualIdentityUtils
import org.scalamock.scalatest.MockFactory
import org.scalatest.BeforeAndAfterEach
@@ -62,8 +67,12 @@ import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import java.util.concurrent.LinkedBlockingQueue
+import scala.collection.mutable.ArrayBuffer
class DataProcessorSpec extends AnyFlatSpec with MockFactory with Matchers with BeforeAndAfterEach {
+
+ import DataProcessorSpec._
+
private val testOpId = PhysicalOpIdentity(OperatorIdentity("testop"), "main")
private val upstreamOpId = PhysicalOpIdentity(OperatorIdentity("sender"), "main")
private val testWorkerId: ActorVirtualIdentity = VirtualIdentityUtils.createWorkerIdentity(
@@ -434,6 +443,199 @@ class DataProcessorSpec extends AnyFlatSpec with MockFactory with Matchers with
dp.pauseManager.isPaused shouldBe true
}
+ // ---------------------------------------------------------------------------
+ // An operator whose setting refers to a loop variable
+ // ---------------------------------------------------------------------------
+
+ private val senderChannel = ChannelIdentity(senderWorkerId, testWorkerId, isControl = false)
+ private val coordinatorChannel = ChannelIdentity(COORDINATOR, testWorkerId, isControl = true)
+
+ private val startChannelPayload = EmbeddedControlMessage(
+ EmbeddedControlMessageIdentity("StartChannel"),
+ EmbeddedControlMessageType.NO_ALIGNMENT,
+ Seq(),
+ Map(
+ testWorkerId.name ->
+ ControlInvocation(
+ METHOD_START_CHANNEL.getBareMethodName,
+ EmptyRequest(),
+ AsyncRPCContext(ActorVirtualIdentity(""), ActorVirtualIdentity("")),
+ -1
+ )
+ )
+ )
+
+ /**
+ * A data processor whose executor is initialized the way the coordinator initializes a worker,
+ * from `descString` for `LoopLimitExec`, with everything the worker sends collected.
+ */
+ private def initializedWith(
+ descString: String
+ ): (DataProcessor, LoopLimitExec, ArrayBuffer[WorkflowFIFOMessage]) = {
+ val dp = mkDataProcessor
+ val sent = ArrayBuffer[WorkflowFIFOMessage]()
+ (outputHandler.apply _)
+ .expects(*)
+ .onCall { (m: Either[MainThreadDelegateMessage, WorkflowFIFOMessage]) =>
+ m.foreach(sent += _); ()
+ }
+ .anyNumberOfTimes()
+ (adaptiveBatchingMonitor.startAdaptiveBatching _).expects().anyNumberOfTimes()
+ dp.stateManager.transitTo(READY)
+ dp.inputManager.addPort(inputPortId, schema, List.empty, List.empty)
+ dp.inputGateway.getChannel(senderChannel).setPortId(inputPortId)
+ dp.outputManager.addPort(outputPortId, schema, None)
+ dp.outputManager.addPartitionerWithPartitioning(
+ PhysicalLink(testOpId, outputPortId, upstreamOpId, inputPortId),
+ OneToOnePartitioning(1, Seq(ChannelIdentity(testWorkerId, senderWorkerId, isControl = false)))
+ )
+ dp.processDCM(
+ coordinatorChannel,
+ ControlInvocation(
+ METHOD_INITIALIZE_EXECUTOR,
+ InitializeExecutorRequest(
+ totalWorkerCount = 1,
+ opExecInitInfo = OpExecWithClassName(classOf[LoopLimitExec].getName, descString),
+ isSource = false,
+ loopStartPortUris = Map.empty
+ ),
+ AsyncRPCContext(COORDINATOR, testWorkerId),
+ 0
+ )
+ )
+ (dp, dp.executor.asInstanceOf[LoopLimitExec], sent)
+ }
+
+ private def openExecutor(dp: DataProcessor): Unit =
+ dp.processDCM(
+ coordinatorChannel,
+ ControlInvocation(
+ METHOD_OPEN_EXECUTOR,
+ EmptyRequest(),
+ AsyncRPCContext(COORDINATOR, testWorkerId),
+ 1
+ )
+ )
+
+ private def drain(dp: DataProcessor): Unit =
+ while (dp.inputManager.hasUnfinishedInput || dp.outputManager.hasUnfinishedOutput) {
+ dp.continueDataProcessing()
+ }
+
+ private def statesSent(sent: ArrayBuffer[WorkflowFIFOMessage]): List[State] =
+ sent.map(_.payload).collect { case StateFrame(state, _, _) => state }.toList
+
+ private def tuplesSent(sent: ArrayBuffer[WorkflowFIFOMessage]): List[Tuple] =
+ sent.map(_.payload).collect { case DataFrame(frame) => frame.toList }.flatten.toList
+
+ private def consoleTitles(sent: ArrayBuffer[WorkflowFIFOMessage]): List[String] =
+ sent
+ .map(_.payload)
+ .collect {
+ case invocation: org.apache.texera.amber.engine.architecture.rpc.controlcommands.ControlInvocation =>
+ invocation.command
+ }
+ .collect { case request: ConsoleMessageTriggeredRequest => request.consoleMessage.title }
+ .toList
+
+ "data processor" should "run an operator whose setting refers to a loop variable as any other, the variable written in as the state arrives" in {
+ val (dp, exec, sent) = initializedWith(limitReferringToN)
+ // The operator's own executor, built at worker start from the descString with its placeholder.
+ assert(exec.setting.limit == 0)
+
+ openExecutor(dp)
+ dp.processECM(senderChannel, startChannelPayload, logManager)
+ val first = State(Map("n" -> 2L))
+ dp.processDataPayload(senderChannel, StateFrame(first, loopCounter = 1))
+ dp.processDataPayload(senderChannel, DataFrame(tuples.take(5)))
+ drain(dp)
+ val later = State(Map("n" -> 9L))
+ dp.processDataPayload(senderChannel, StateFrame(later))
+
+ // open() and produceStateOnStart see the placeholder; each processState sees its message
+ // registered and the variable written; a state after the first tuple no longer writes, even
+ // one from a more deeply nested loop.
+ assert(
+ exec.calls.toList == List(
+ ("open", 0, None),
+ ("start", 0, None),
+ ("state", 2, Some(first)),
+ ("state", 2, Some(later))
+ )
+ )
+ // What the worker sends on is what the operator returned for each callback.
+ assert(
+ statesSent(sent) == List(
+ State(Map("start" -> 0)),
+ State(Map("seen" -> 2L, "limit" -> 2)),
+ State(Map("seen" -> 9L, "limit" -> 2))
+ )
+ )
+ assert(tuplesSent(sent) == tuples.take(2).toList)
+ assert(consoleTitles(sent).isEmpty)
+ assert(!dp.pauseManager.isPaused)
+ }
+
+ "data processor" should "fail a state message from the same loop that changes a loop variable" in {
+ val (dp, exec, sent) = initializedWith(limitReferringToN)
+ openExecutor(dp)
+ dp.processDataPayload(senderChannel, StateFrame(State(Map("n" -> 2L))))
+ dp.processDataPayload(senderChannel, StateFrame(State(Map("n" -> 3L))))
+
+ // The operator never sees the changed state.
+ assert(exec.calls.map(_._1).toList == List("open", "state"))
+ assert(
+ consoleTitles(sent) == List(
+ new IllegalStateException(
+ "loop variable n got two different values in one iteration, 2 and 3: a loop's " +
+ "variables must not change inside its body"
+ ).toString
+ )
+ )
+ dp.pauseManager.isPaused shouldBe true
+ }
+
+ "data processor" should "fail the first tuple of an operator whose setting refers to a loop variable no state message carried" in {
+ val (dp, exec, sent) = initializedWith(limitReferringToN)
+ openExecutor(dp)
+
+ dp.processDataPayload(senderChannel, DataFrame(tuples.take(1)))
+
+ // The operator never sees the tuple: it would be processed with the placeholder.
+ assert(exec.tuplesSeen == 0)
+ assert(
+ consoleTitles(sent) == List(
+ new IllegalStateException(
+ "property /limit refers to loop variable n, but no state message carried it"
+ ).toString
+ )
+ )
+ dp.pauseManager.isPaused shouldBe true
+ }
+
+ "data processor" should "bind the references of an executor that replaces one already bound" in {
+ // Reconfiguration and checkpoint restore install a new executor: its references are its own.
+ val (dp, exec, sent) = initializedWith(limitReferringToN)
+ openExecutor(dp)
+ dp.processDataPayload(senderChannel, StateFrame(State(Map("n" -> 2L))))
+ dp.processDataPayload(senderChannel, DataFrame(tuples.take(1)))
+ drain(dp)
+ assert(exec.tuplesSeen == 1)
+
+ val replacement = loopLimitExec()
+ dp.executor = replacement
+ dp.processDataPayload(senderChannel, DataFrame(tuples.slice(1, 2)))
+
+ assert(replacement.tuplesSeen == 0)
+ assert(
+ consoleTitles(sent) == List(
+ new IllegalStateException(
+ "property /limit refers to loop variable n, but no state message carried it"
+ ).toString
+ )
+ )
+ }
+
"data processor" should "handle an exception thrown while advancing the output iterator" in {
val dp = mkDataProcessor
dp.executor = executor
@@ -544,3 +746,55 @@ class DataProcessorSpec extends AnyFlatSpec with MockFactory with Matchers with
}
}
+
+object DataProcessorSpec {
+
+ /** A descString whose `limit` refers to the loop variable `n`. */
+ val limitReferringToN = """{"limit":0,"stateReferences":{"/limit":"n"}}"""
+
+ /** Built as a worker builds it, from `limitReferringToN`. */
+ def loopLimitExec(): LoopLimitExec =
+ ExecFactory
+ .newExecFromJavaClassName(classOf[LoopLimitExec].getName, limitReferringToN)
+ .asInstanceOf[LoopLimitExec]
+
+ /** A setting with one Int property, as Limit's. */
+ class LimitSetting extends StateReferencing {
+ @JsonProperty var limit: Int = _
+ }
+
+ /**
+ * Passes the first `limit` tuples, as Limit does, and records each callback the worker makes with
+ * the limit and the registered state at that moment. Public, for the factory's reflection.
+ */
+ class LoopLimitExec(descString: String) extends OperatorExecutor {
+ val setting: LimitSetting = objectMapper.readValue(descString, classOf[LimitSetting])
+ val calls: ArrayBuffer[(String, Int, Option[State])] = ArrayBuffer()
+ var tuplesSeen = 0
+
+ private def record(call: String): Unit = calls += ((call, setting.limit, state))
+
+ override def open(): Unit = record("open")
+
+ override def produceStateOnStart(port: Int): Option[State] = {
+ record("start")
+ Some(State(Map("start" -> setting.limit)))
+ }
+
+ // Transforms the state, so what the worker sends on shows whose return value it is.
+ override def processState(incoming: State, port: Int): Option[State] = {
+ record("state")
+ Some(State(Map("seen" -> incoming.values("n"), "limit" -> setting.limit)))
+ }
+
+ override def processTuple(tuple: Tuple, port: Int): Iterator[TupleLike] = {
+ tuplesSeen += 1
+ if (tuplesSeen <= setting.limit) Iterator.single(tuple) else Iterator.empty
+ }
+
+ override def produceStateOnFinish(port: Int): Option[State] = {
+ record("finish")
+ None
+ }
+ }
+}
diff --git a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/EndChannelHandlerSpec.scala b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/EndChannelHandlerSpec.scala
index e9ba636963..d768b93c7d 100644
--- a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/EndChannelHandlerSpec.scala
+++ b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/EndChannelHandlerSpec.scala
@@ -49,6 +49,7 @@ import org.apache.texera.amber.engine.architecture.worker.WorkflowWorker.{
DPInputQueueElement,
MainThreadDelegateMessage
}
+import org.apache.texera.amber.engine.architecture.worker.DataProcessorSpec.loopLimitExec
import org.apache.texera.amber.engine.architecture.worker.{
DataProcessor,
DataProcessorRPCHandlerInitializer,
@@ -394,6 +395,38 @@ class EndChannelHandlerSpec extends AnyFlatSpec {
assert(fixture.drainOutput() == List(FinalizePort(currentPortId, input = true)))
}
+ it should "fail the finish of an operator whose setting refers to a loop variable no state message carried, before asking it for a state" in {
+ val executor = loopLimitExec()
+ val fixture = new Fixture(executor)
+
+ assert(fixture.endChannel() == EmptyReturn())
+
+ assert(
+ fixture.consoleMessages.map(_.consoleMessage.title) == Seq(
+ new IllegalStateException(
+ "property /limit refers to loop variable n, but no state message carried it"
+ ).toString
+ )
+ )
+ assertPausedByOperatorLogic(fixture.dp)
+ // Neither finish callback ran with the placeholder, and the port is still finalized.
+ assert(executor.calls.isEmpty)
+ assert(fixture.emittedStates.isEmpty)
+ assert(fixture.drainOutput().contains(FinalizePort(currentPortId, input = true)))
+ }
+
+ it should "finish an operator whose setting refers to a loop variable with the value its state message wrote" in {
+ val executor = loopLimitExec()
+ val fixture = new Fixture(executor)
+ fixture.dp.processDataPayload(currentChannelId, StateFrame(State(Map("n" -> 3L))))
+
+ assert(fixture.endChannel() == EmptyReturn())
+
+ assert(fixture.consoleMessages.isEmpty)
+ // The finish callback sees the limit the state message wrote.
+ assert(executor.calls.map(c => (c._1, c._2)) == Seq(("state", 3), ("finish", 3)))
+ }
+
it should "finalize the output once the last input port completes" in {
val fixture = new Fixture(new RecordingExecutor(), otherInputPortCompleted = true)
diff --git a/amber/src/test/scala/org/apache/texera/web/ComputingUnitMasterSpec.scala b/amber/src/test/scala/org/apache/texera/web/ComputingUnitMasterSpec.scala
index bfd9a02c5f..c89bbb174c 100644
--- a/amber/src/test/scala/org/apache/texera/web/ComputingUnitMasterSpec.scala
+++ b/amber/src/test/scala/org/apache/texera/web/ComputingUnitMasterSpec.scala
@@ -40,6 +40,7 @@ import org.apache.texera.amber.engine.common.AmberRuntime
import org.apache.texera.amber.engine.common.client.AmberClient
import org.apache.texera.amber.engine.common.virtualidentity.util.COORDINATOR
import org.apache.texera.amber.engine.e2e.TestUtils.buildWorkflow
+import org.apache.texera.amber.operator.LogicalOp
import org.apache.texera.amber.operator.TestOperators
import org.apache.texera.amber.util.VirtualIdentityUtils
import org.apache.texera.common.config.ApplicationConfig
@@ -559,7 +560,7 @@ class ComputingUnitMasterSpec
)
}
- it should "register the Scala module on the bootstrap object mapper" in {
+ it should "register the Scala and loop-variable modules on the bootstrap object mapper" in {
val bootstrap = new Bootstrap[Configuration](master)
master.initialize(bootstrap)
@@ -567,6 +568,10 @@ class ComputingUnitMasterSpec
bootstrap.getObjectMapper.getRegisteredModuleIds.asScala should contain(
com.fasterxml.jackson.module.scala.DefaultScalaModule.getClass.getName
)
+ // Jersey parses SyncExecutionResource's request body, a typed '$n' included, with this mapper.
+ bootstrap.getObjectMapper
+ .readValue("""{"limit":"$n","operatorType":"Limit"}""", classOf[LogicalOp])
+ .stateReferences shouldBe Map("/limit" -> "n")
}
"run" should "serve the Jersey resources under the /api prefix" in {
diff --git a/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala b/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala
index 65d13e4179..b3b8144d25 100644
--- a/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala
+++ b/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala
@@ -19,13 +19,18 @@
package org.apache.texera.common.compiler
+import com.fasterxml.jackson.databind.node.ObjectNode
import com.google.protobuf.timestamp.Timestamp
import com.typesafe.scalalogging.{LazyLogging, Logger}
import org.apache.texera.common.compiler.WorkflowCompiler.{
collectOutputSchemaFromPhysicalPlan,
- convertErrorListToWorkflowFatalErrorMap
+ convertErrorListToWorkflowFatalErrorMap,
+ normalizeStateReferences,
+ unbindableStateReferences
}
import org.apache.texera.common.compiler.model.{LogicalPlan, LogicalPlanPojo}
+import org.apache.texera.amber.core.executor.OpExecWithCode
+import org.apache.texera.amber.core.state.StateReferencing.literalReferences
import org.apache.texera.amber.core.tuple.Schema
import org.apache.texera.amber.core.virtualidentity.OperatorIdentity
import org.apache.texera.amber.core.workflow.{
@@ -37,6 +42,8 @@ import org.apache.texera.amber.core.workflow.{
}
import org.apache.texera.amber.core.workflowruntimestate.FatalErrorType.COMPILATION_ERROR
import org.apache.texera.amber.core.workflowruntimestate.WorkflowFatalError
+import org.apache.texera.amber.operator.LogicalOp
+import org.apache.texera.amber.util.JSONUtils.objectMapper
import org.apache.texera.amber.util.StackTraceUtils.getStackTraceWithAllCauses
import java.time.Instant
@@ -72,6 +79,87 @@ object WorkflowCompiler {
opIdToError.toMap
}
+ /**
+ * Makes `logicalOp`'s `stateReferences` sidecar final, before its physical plan serializes it
+ * into the executor's descString. Inside a loop block it adds every whole-string `$name` value
+ * of the operator's JSON (`StateReferencing.literalReferences`). Outside every block a string
+ * such as "$AAPL" stays a literal, and a typed placeholder (the user wrote "$n" for an Int),
+ * which nothing would bind, is an error; it stays in the sidecar, so a recompile reports it too.
+ */
+ def normalizeStateReferences(logicalOp: LogicalOp, plan: LogicalPlan): Option[Throwable] =
+ if (plan.operatorsInsideLoopBlocks.contains(logicalOp.operatorIdentifier)) {
+ logicalOp.stateReferences =
+ literalReferences(objectMapper.valueToTree[ObjectNode](logicalOp)) ++
+ logicalOp.stateReferences
+ inputsAheadOfLoopState(logicalOp, plan)
+ } else {
+ Option.when(logicalOp.stateReferences.nonEmpty) {
+ new IllegalArgumentException(
+ s"${logicalOp.operatorInfo.userFriendlyName} refers to loop variables " +
+ s"(${formatReferences(logicalOp.stateReferences)}), but is not inside a loop block"
+ )
+ }
+ }
+
+ /**
+ * The first tuple fails on a loop variable its state has not written yet, and the states of
+ * the blocks around the operator come ahead of the tuples only on links from inside all of
+ * them, or from the LoopStart of the innermost. An input with any other link is an error,
+ * unless the operator reads it only after an input whose links all carry the state (a join's
+ * probe input).
+ */
+ private def inputsAheadOfLoopState(logicalOp: LogicalOp, plan: LogicalPlan): Option[Throwable] = {
+ val around = plan.enclosingLoopStarts
+ val mine = around(logicalOp.operatorIdentifier)
+ val linksByPort = plan.getUpstreamLinks(logicalOp.operatorIdentifier).groupBy(_.toPortId)
+ // A LoopStart's link carries its own block's state too.
+ def carriesOnlyState(port: PortIdentity): Boolean =
+ linksByPort
+ .get(port)
+ .exists(_.forall { link =>
+ mine.subsetOf(around.getOrElse(link.fromOpId, Set.empty) + link.fromOpId)
+ })
+ val exposed = logicalOp.operatorInfo.inputPorts.filter { input =>
+ linksByPort.contains(input.id) && !carriesOnlyState(input.id) &&
+ !input.dependencies.exists(carriesOnlyState)
+ }
+ Option.when(logicalOp.stateReferences.nonEmpty && exposed.nonEmpty) {
+ val inputs = exposed.map { input =>
+ if (input.displayName.nonEmpty) s"input '${input.displayName}'"
+ else s"input port ${input.id.id}"
+ }
+ new IllegalArgumentException(
+ s"${logicalOp.operatorInfo.userFriendlyName} refers to loop variables " +
+ s"(${formatReferences(logicalOp.stateReferences)}), but its ${inputs.mkString(" and ")} " +
+ s"${if (exposed.size == 1) "is" else "are"} fed from outside the loop block, so " +
+ "tuples from there can arrive before the loop state"
+ )
+ }
+ }
+
+ /**
+ * A reference is bound in the executor that `ExecFactory` builds from the descriptor's JSON: the
+ * state message writes the loop variable into the descriptor that executor parsed. An operator
+ * whose executor runs code instead -- a UDF, or a descriptor that generates Python from its
+ * properties, such as the sklearn operators -- never takes that path: its code is built from the
+ * placeholders before the loop runs, and nothing binds them.
+ */
+ def unbindableStateReferences(logicalOp: LogicalOp, subPlan: PhysicalPlan): Option[Throwable] =
+ Option.when(
+ logicalOp.stateReferences.nonEmpty &&
+ subPlan.operators.exists(_.opExecInitInfo.isInstanceOf[OpExecWithCode])
+ ) {
+ new UnsupportedOperationException(
+ s"${logicalOp.operatorInfo.userFriendlyName} cannot refer to loop variables yet " +
+ s"(${formatReferences(logicalOp.stateReferences)}): its code is generated before " +
+ "the loop runs"
+ )
+ }
+
+ /** A descriptor's references as the compile errors name them: `/pointer -> $name, ...`. */
+ private def formatReferences(references: Map[String, String]): String =
+ references.toSeq.sorted.map { case (pointer, name) => s"$pointer -> $$$name" }.mkString(", ")
+
private def collectOutputSchemaFromPhysicalPlan(
physicalPlan: PhysicalPlan,
errorList: ArrayBuffer[(OperatorIdentity, Throwable)]
@@ -151,7 +239,17 @@ class WorkflowCompiler(
val logicalOp = logicalPlan.getOperator(logicalOpId)
val upstreamLinks = logicalPlan.getUpstreamLinks(logicalOp.operatorIdentifier)
+ def report(error: Throwable): Unit =
+ errorList match {
+ case Some(list) => list.append((logicalOpId, error))
+ case None => throw error
+ }
+ // Before the physical plan: the descriptor serializes its sidecar into its descString.
+ normalizeStateReferences(logicalOp, logicalPlan).foreach(report)
val subPlan = logicalOp.getPhysicalPlan(context.workflowId, context.executionId)
+ // Before the code-generation check below: the first error per operator is reported, and
+ // code generated from a placeholder may fail on it with a less specific message.
+ unbindableStateReferences(logicalOp, subPlan).foreach(report)
subPlan
.topologicalIterator()
.map(subPlan.getOperator)
diff --git a/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/model/LogicalPlan.scala b/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/model/LogicalPlan.scala
index f4d694ff66..83cee4a717 100644
--- a/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/model/LogicalPlan.scala
+++ b/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/model/LogicalPlan.scala
@@ -23,12 +23,14 @@ import com.typesafe.scalalogging.LazyLogging
import org.apache.texera.amber.core.storage.FileResolver
import org.apache.texera.amber.core.virtualidentity.OperatorIdentity
import org.apache.texera.amber.operator.LogicalOp
+import org.apache.texera.amber.operator.loop.{LoopEndOpDesc, LoopStartOpDesc}
import org.apache.texera.amber.operator.source.scan.ScanSourceOpDesc
import org.jgrapht.graph.DirectedAcyclicGraph
import org.jgrapht.util.SupplierUtil
import java.util
import scala.collection.mutable.ArrayBuffer
+import scala.jdk.CollectionConverters.IteratorHasAsScala
import scala.util.{Failure, Success, Try}
object LogicalPlan {
@@ -86,6 +88,49 @@ case class LogicalPlan(
links.filter(l => l.toOpId == opId)
}
+ /**
+ * The operators inside some loop block, on a path LoopStart -> ... -> operator -> ... -> LoopEnd
+ * whose two ends match, each with the LoopStarts of the blocks it is inside: those with a path
+ * to it on which no LoopEnd closes their block (a LoopEnd closes the innermost block the path
+ * opened). A control operator is not inside its own block, but an inner block's are inside the
+ * outer one. The property panel decides where it offers `$K` with its own walk from each
+ * operator (`getEnclosingLoopStarts`, loop-block.util.ts); `LogicalPlanSpec` checks that the
+ * two agree on the same graph.
+ */
+ lazy val enclosingLoopStarts: Map[OperatorIdentity, Set[OperatorIdentity]] = {
+ val order = getTopologicalOpIds.asScala.toList
+ // 1 for a LoopStart, which opens a block, -1 for a LoopEnd, which closes one, 0 otherwise.
+ val change = operatorMap.map {
+ case (id, _: LoopStartOpDesc) => id -> 1
+ case (id, _: LoopEndOpDesc) => id -> -1
+ case (id, _) => id -> 0
+ }
+ val upstream = links.groupMap(_.toOpId)(_.fromOpId).withDefaultValue(Nil)
+ val downstream = links.groupMap(_.fromOpId)(_.toOpId).withDefaultValue(Nil)
+ // The most blocks a path from each operator closes that it did not open, the operator
+ // included; a block closed below is one besides a LoopEnd's own.
+ val closing = order.reverse.foldLeft(Map.empty[OperatorIdentity, Int]) { (closing, id) =>
+ closing.updated(id, (0 :: downstream(id).map(closing)).max - change(id))
+ }
+ val closedBelow = order.filter(id => closing(id) > (if (change(id) < 0) 1 else 0)).toSet
+ order
+ .filter(change(_) > 0)
+ .flatMap { start =>
+ // The most blocks a path from `start` leaves open at each operator, its own still open.
+ val open = order.dropWhile(_ != start).tail.foldLeft(Map(start -> 1)) { (open, id) =>
+ upstream(id).flatMap(open.get).maxOption.map(_ + change(id)) match {
+ case Some(blocks) if blocks > 0 => open.updated(id, blocks)
+ case _ => open
+ }
+ }
+ (open.keySet - start).intersect(closedBelow).map(_ -> start)
+ }
+ .groupMap(_._1)(_._2)
+ .map { case (id, starts) => id -> starts.toSet }
+ }
+
+ def operatorsInsideLoopBlocks: Set[OperatorIdentity] = enclosingLoopStarts.keySet
+
/**
* Resolves each scan source operator's user-given file name to a URI and sets it on the
* operator via `setResolvedFileName`.
diff --git a/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/LogicalPlanSpec.scala b/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/LogicalPlanSpec.scala
index 6e926d4715..b2856a5e9d 100644
--- a/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/LogicalPlanSpec.scala
+++ b/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/LogicalPlanSpec.scala
@@ -25,6 +25,8 @@ import org.apache.texera.amber.core.workflow.PortIdentity
import org.apache.texera.amber.operator.aggregate.AggregateOpDesc
import org.apache.texera.amber.operator.hashJoin.HashJoinOpDesc
import org.apache.texera.amber.operator.keywordSearch.KeywordSearchOpDesc
+import org.apache.texera.amber.operator.limit.LimitOpDesc
+import org.apache.texera.amber.operator.loop.{LoopEndOpDesc, LoopStartOpDesc}
import org.apache.texera.amber.operator.source.scan.csv.CSVScanSourceOpDesc
import org.apache.texera.amber.operator.source.scan.json.JSONLScanSourceOpDesc
import org.apache.texera.amber.operator.split.SplitOpDesc
@@ -37,6 +39,7 @@ import org.scalatest.flatspec.AnyFlatSpec
import scala.collection.mutable.ArrayBuffer
import scala.jdk.CollectionConverters.IteratorHasAsScala
+import scala.util.Random
class LogicalPlanSpec extends AnyFlatSpec {
@@ -278,6 +281,165 @@ class LogicalPlanSpec extends AnyFlatSpec {
assert(r.plan.getUpstreamLinks(r.csv.operatorIdentifier).isEmpty)
}
+ // ---------------------------------------------------------------------------
+ // operatorsInsideLoopBlocks: the cases mirror the frontend's `getEnclosingLoopStarts` spec
+ // ---------------------------------------------------------------------------
+
+ private def loopStart(id: String): LogicalOp = named(new LoopStartOpDesc, id)
+ private def loopEnd(id: String): LogicalOp = named(new LoopEndOpDesc, id)
+ private def op(id: String): LogicalOp = named(new LimitOpDesc, id)
+
+ /**
+ * The ids of the operators inside a loop block, `edges` as "from" -> "to" ids, checked against
+ * the property panel's walk, as are the LoopStarts around each (`enclosingLoopStarts`).
+ */
+ private def inside(operators: List[LogicalOp], edges: (String, String)*): Set[String] = {
+ val plan = LogicalPlan(
+ operators,
+ edges.toList.map { case (from, to) => link(OperatorIdentity(from), OperatorIdentity(to)) }
+ )
+ val around = plan.enclosingLoopStarts.map { case (id, starts) => id.id -> starts.map(_.id) }
+ val byPanel = enclosingByPanel(operators, edges)
+ assert(
+ around == byPanel,
+ s"the panel's walk finds $byPanel, not $around, in ${operators.map(_.operatorIdentifier.id)} " +
+ s"with $edges"
+ )
+ plan.operatorsInsideLoopBlocks.map(_.id)
+ }
+
+ /**
+ * A port of the property panel's `getEnclosingLoopStarts` (frontend loop-block.util.ts), which
+ * decides where the panel offers `$K`: each operator with an enclosing LoopStart, and those
+ * LoopStarts. It walks from each operator where `enclosingLoopStarts` folds over the plan. It
+ * leaves out the panel's hop counts, which only order the LoopStarts, and its cap on open
+ * blocks, which binds only on a cycle.
+ */
+ private def enclosingByPanel(
+ operators: List[LogicalOp],
+ edges: Seq[(String, String)]
+ ): Map[String, Set[String]] = {
+ val typeOf = operators.map {
+ case op: LoopStartOpDesc => op.operatorIdentifier.id -> "LoopStart"
+ case op: LoopEndOpDesc => op.operatorIdentifier.id -> "LoopEnd"
+ case op => op.operatorIdentifier.id -> ""
+ }.toMap
+ // The `closes`-typed operators a walk from `origin` meets with no block open.
+ def walk(origin: String, adjacency: Map[String, Seq[String]], opens: String, closes: String) = {
+ def from(id: String, open: Int): Set[String] =
+ adjacency.getOrElse(id, Nil).toSet.flatMap { next: String =>
+ val change = if (typeOf(next) == opens) 1 else if (typeOf(next) == closes) -1 else 0
+ from(next, (open + change).max(0)) ++ Option.when(change < 0 && open == 0)(next)
+ }
+ from(origin, if (typeOf(origin) == opens) 1 else 0)
+ }
+ typeOf.keySet
+ .filter(walk(_, edges.groupMap(_._1)(_._2), "LoopStart", "LoopEnd").nonEmpty)
+ .map(id => id -> walk(id, edges.groupMap(_._2)(_._1), "LoopEnd", "LoopStart"))
+ .filter(_._2.nonEmpty)
+ .toMap
+ }
+
+ "LogicalPlan.operatorsInsideLoopBlocks" should "find nothing unless a LoopStart and a LoopEnd close a block" in {
+ assert(inside(List(op("a"), op("b")), "a" -> "b").isEmpty)
+ assert(inside(List(loopStart("S"), op("a"), op("b")), "S" -> "a", "a" -> "b").isEmpty)
+ assert(inside(List(op("a"), op("b"), loopEnd("E")), "a" -> "b", "b" -> "E").isEmpty)
+ }
+
+ it should "put the body of a straight block inside it, and neither control operator" in {
+ // src -> S -> a -> b -> E -> sink
+ val ops = List(op("src"), loopStart("S"), op("a"), op("b"), loopEnd("E"), op("sink"))
+ val result =
+ inside(ops, "src" -> "S", "S" -> "a", "a" -> "b", "b" -> "E", "E" -> "sink")
+ assert(result == Set("a", "b"))
+ }
+
+ it should "put both branches of a block that branches and converges inside it" in {
+ // S -> a -> E, S -> b -> c -> E
+ val ops = List(loopStart("S"), op("a"), op("b"), op("c"), loopEnd("E"))
+ val result = inside(ops, "S" -> "a", "a" -> "E", "S" -> "b", "b" -> "c", "c" -> "E")
+ assert(result == Set("a", "b", "c"))
+ }
+
+ it should "leave out a dangling branch that never reaches the LoopEnd" in {
+ // S -> a -> E, and S -> d -> e: the block never closes on the path through d and e.
+ val ops = List(loopStart("S"), op("a"), loopEnd("E"), op("d"), op("e"))
+ val result = inside(ops, "S" -> "a", "a" -> "E", "S" -> "d", "d" -> "e")
+ assert(result == Set("a"))
+ }
+
+ it should "leave out a branch that joins the body from outside the block" in {
+ // src2 -> a, where a is in the body of S ... E: src2 reaches E but no LoopStart reaches src2.
+ val ops = List(loopStart("S"), op("a"), loopEnd("E"), op("src2"))
+ val result = inside(ops, "S" -> "a", "a" -> "E", "src2" -> "a")
+ assert(result == Set("a"))
+ }
+
+ it should "put a nested block's LoopStart and LoopEnd inside the outer block, and not the outer ones" in {
+ // S0 -> x -> S1 -> a -> E1 -> y -> E0
+ val ops =
+ List(
+ loopStart("S0"),
+ op("x"),
+ loopStart("S1"),
+ op("a"),
+ loopEnd("E1"),
+ op("y"),
+ loopEnd("E0")
+ )
+ val result =
+ inside(ops, "S0" -> "x", "x" -> "S1", "S1" -> "a", "a" -> "E1", "E1" -> "y", "y" -> "E0")
+ assert(result == Set("x", "S1", "a", "E1", "y"))
+ }
+
+ it should "not count a control operator inside its own block when an outer block is left open" in {
+ // S0 -> x -> S1 -> a -> E1, where no LoopEnd closes S0's block: S1 is only in its own.
+ val openAbove = List(loopStart("S0"), op("x"), loopStart("S1"), op("a"), loopEnd("E1"))
+ assert(inside(openAbove, "S0" -> "x", "x" -> "S1", "S1" -> "a", "a" -> "E1") == Set("a"))
+ // S -> a -> E -> b -> E2, where no LoopStart opens E2's block: E is only in its own.
+ val openBelow = List(loopStart("S"), op("a"), loopEnd("E"), op("b"), loopEnd("E2"))
+ assert(inside(openBelow, "S" -> "a", "a" -> "E", "E" -> "b", "b" -> "E2") == Set("a"))
+ }
+
+ it should "not leak one block into the next when blocks run in sequence" in {
+ // S1 -> a -> E1 -> x -> S2 -> b -> E2: x is in neither block.
+ val ops =
+ List(
+ loopStart("S1"),
+ op("a"),
+ loopEnd("E1"),
+ op("x"),
+ loopStart("S2"),
+ op("b"),
+ loopEnd("E2")
+ )
+ val result =
+ inside(ops, "S1" -> "a", "a" -> "E1", "E1" -> "x", "x" -> "S2", "S2" -> "b", "b" -> "E2")
+ assert(result == Set("a", "b"))
+ // S1 -> a -> E1 -> S2 -> b -> E2: nor are E1 and S2, linked directly.
+ val linked =
+ List(loopStart("S1"), op("a"), loopEnd("E1"), loopStart("S2"), op("b"), loopEnd("E2"))
+ assert(
+ inside(linked, "S1" -> "a", "a" -> "E1", "E1" -> "S2", "S2" -> "b", "b" -> "E2") ==
+ Set("a", "b")
+ )
+ }
+
+ it should "agree with the property panel's walk on random graphs of loop and plain operators" in {
+ val random = new Random(8640)
+ (1 to 400).foreach { _ =>
+ val size = 2 + random.nextInt(11)
+ val density = Seq(0.15, 0.3, 0.5)(random.nextInt(3))
+ val operators =
+ (0 until size).map(i => Seq(loopStart _, loopEnd _, op _, op _)(random.nextInt(4))(s"n$i"))
+ val edges =
+ for (from <- 0 until size; to <- from + 1 until size if random.nextDouble() < density)
+ yield s"n$from" -> s"n$to"
+ // In shuffled order, so the plan's topological order differs from the ids'.
+ inside(random.shuffle(operators).toList, random.shuffle(edges): _*)
+ }
+ }
+
// ---------------------------------------------------------------------------
// resolveScanSourceOpFileName
// ---------------------------------------------------------------------------
diff --git a/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/WorkflowCompilerSpec.scala b/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/WorkflowCompilerSpec.scala
index da7ac59482..2dcefc4942 100644
--- a/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/WorkflowCompilerSpec.scala
+++ b/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/WorkflowCompilerSpec.scala
@@ -20,7 +20,9 @@
package org.apache.texera.common.compiler
import org.apache.texera.common.compiler.model.{LogicalLink, LogicalPlanPojo}
-import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema}
+import org.apache.texera.amber.core.executor.{ExecFactory, OpExecWithClassName}
+import org.apache.texera.amber.core.state.State
+import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple}
import org.apache.texera.amber.core.virtualidentity.WorkflowIdentity
import org.apache.texera.amber.core.workflow.{OutputPort, PortIdentity, WorkflowContext}
import org.apache.texera.amber.core.workflowruntimestate.FatalErrorType.COMPILATION_ERROR
@@ -30,11 +32,14 @@ import org.apache.texera.amber.operator.filter.{
SpecializedFilterOpDesc
}
import org.apache.texera.amber.operator.limit.LimitOpDesc
+import org.apache.texera.amber.operator.loop.{LoopEndOpDesc, LoopStartOpDesc}
import org.apache.texera.amber.operator.metadata.{OperatorGroupConstants, OperatorInfo}
import org.apache.texera.amber.operator.projection.{AttributeUnit, ProjectionOpDesc}
import org.apache.texera.amber.operator.sort.{SortCriteriaUnit, SortOpDesc, SortPreference}
import org.apache.texera.amber.operator.source.scan.csv.CSVScanSourceOpDesc
-import org.apache.texera.amber.operator.{PythonOperatorDescriptor, TestOperators}
+import org.apache.texera.amber.operator.source.scan.text.TextInputSourceOpDesc
+import org.apache.texera.amber.operator.{LogicalOp, PythonOperatorDescriptor, TestOperators}
+import org.apache.texera.amber.util.JSONUtils.objectMapper
import org.scalatest.flatspec.AnyFlatSpec
/**
@@ -840,4 +845,277 @@ class WorkflowCompilerSpec extends AnyFlatSpec {
assert(result.physicalPlan.isDefined)
assert(result.operatorIdToError.isEmpty)
}
+
+ // -------------------- loop-variable references --------------------
+
+ /** An operator as the frontend sends it: its properties, then its type, "$..." whatever the type. */
+ private def parsed(json: String): LogicalOp = objectMapper.readValue(json, classOf[LogicalOp])
+
+ private def linked(upstream: LogicalOp, downstream: LogicalOp, toPort: Int = 0): LogicalLink =
+ LogicalLink(
+ upstream.operatorIdentifier,
+ PortIdentity(0),
+ downstream.operatorIdentifier,
+ PortIdentity(toPort)
+ )
+
+ private def chain(operators: LogicalOp*): List[LogicalLink] =
+ operators.sliding(2).map(pair => linked(pair.head, pair.last)).toList
+
+ private def textInputOp(text: String): TextInputSourceOpDesc = {
+ val op = new TextInputSourceOpDesc()
+ op.textInput = text
+ op
+ }
+
+ private def loopStartOp(): LoopStartOpDesc = {
+ val op = new LoopStartOpDesc()
+ op.initialization = "i = 0"
+ op.output = "table.iloc[i]"
+ op
+ }
+
+ private def loopEndOp(): LoopEndOpDesc = {
+ val op = new LoopEndOpDesc()
+ op.update = "i += 1"
+ op.condition = "i < len(table)"
+ op
+ }
+
+ /** The class name and descString the worker builds `op`'s executor from. */
+ private def executorInit(result: WorkflowCompilationResult, op: LogicalOp): (String, String) =
+ result.physicalPlan.get
+ .getPhysicalOpsOfLogicalOp(op.operatorIdentifier)
+ .head
+ .opExecInitInfo match {
+ case OpExecWithClassName(className, descString) => (className, descString)
+ case other => fail(s"unexpected opExecInitInfo: $other")
+ }
+
+ /** The `stateReferences` sidecar a descString carries to the worker. */
+ private def sidecarOf(descString: String): Map[String, String] =
+ objectMapper.convertValue(
+ objectMapper.readTree(descString).get("stateReferences"),
+ classOf[Map[String, String]]
+ )
+
+ /** The message of the compile's only error, which must be `op`'s. */
+ private def onlyErrorOf(result: WorkflowCompilationResult, op: LogicalOp): String = {
+ assert(result.operatorIdToError.keySet == Set(op.operatorIdentifier))
+ result.operatorIdToError(op.operatorIdentifier).message
+ }
+
+ private def line(text: String): Tuple = {
+ val schema = Schema().add(new Attribute("line", AttributeType.STRING))
+ Tuple.builder(schema).add(schema.getAttribute("line"), text).build()
+ }
+
+ "WorkflowCompiler" should "keep a '$AAPL' on a Filter outside every loop block the literal it is on main" in {
+ val csv = csvOp(realCsvPath)
+ val filter = parsed(
+ """{"predicates":[{"attribute":"Region","condition":"=","value":"$AAPL"}],"operatorType":"Filter"}"""
+ )
+
+ val result = new WorkflowCompiler(newContext()).compile(
+ pojo(List(csv, filter), List(linked(csv, filter)))
+ )
+
+ assert(result.operatorIdToError.isEmpty, s"unexpected errors: ${result.operatorIdToError}")
+ val (_, descString) = executorInit(result, filter)
+ assert(sidecarOf(descString).isEmpty)
+ }
+
+ it should "report a typed '$n' outside every loop block, naming the property and the variable" in {
+ val csv = csvOp(realCsvPath)
+ val limit = parsed("""{"limit":"$n","operatorType":"Limit"}""")
+ val plan = pojo(List(csv, limit), List(linked(csv, limit)))
+ val message = "Limit refers to loop variables (/limit -> $n), but is not inside a loop block"
+
+ val result = new WorkflowCompiler(newContext()).compile(plan)
+
+ assert(result.physicalPlan.isEmpty)
+ assert(onlyErrorOf(result, limit).contains(message))
+ val ex = intercept[IllegalArgumentException] {
+ new WorkflowCompiler(newContext()).compile(plan, CompilationErrorHandling.Strict)
+ }
+ assert(ex.getMessage == message)
+ }
+
+ it should "find a '$i' literal on a descriptor built in Scala inside a loop block" in {
+ // No parse step ran: the compiler finds the whole-string '$i' in the operator's own JSON.
+ val src = textInputOp("0\n1")
+ val start = loopStartOp()
+ val filter = filterOp(new FilterPredicate("line", ComparisonType.EQUAL_TO, "$i"))
+ val end = loopEndOp()
+
+ val result = new WorkflowCompiler(newContext()).compile(
+ pojo(List(src, start, filter, end), chain(src, start, filter, end))
+ )
+
+ assert(result.operatorIdToError.isEmpty, s"unexpected errors: ${result.operatorIdToError}")
+ val (className, descString) = executorInit(result, filter)
+ assert(sidecarOf(descString) == Map("/predicates/0/value" -> "i"))
+ val exec = ExecFactory.newExecFromJavaClassName(className, descString)
+ exec.open()
+ exec.registerState(State(Map("i" -> 1L)))
+ exec.bindStateReferences()
+ assert(exec.processTuple(line("1"), 0).toList == List(line("1")))
+ assert(exec.processTuple(line("$i"), 0).isEmpty)
+ }
+
+ it should "bind a frontend '$n' in Limit's Int property inside a loop block when the state arrives, end to end" in {
+ // TextInput -> LoopStart -> Projection -> Limit("$n") -> LoopEnd, the Limit parsed as the
+ // frontend sends it: the state reaches Limit through Projection, another operator of the block.
+ val src = textInputOp("0\n1")
+ val start = loopStartOp()
+ val project = projectOp(List("line"))
+ val limit = parsed("""{"limit":"$n","operatorType":"Limit"}""")
+ val end = loopEndOp()
+
+ val result = new WorkflowCompiler(newContext()).compile(
+ pojo(List(src, start, project, limit, end), chain(src, start, project, limit, end))
+ )
+
+ assert(result.operatorIdToError.isEmpty, s"unexpected errors: ${result.operatorIdToError}")
+ val (className, descString) = executorInit(result, limit)
+ assert(sidecarOf(descString) == Map("/limit" -> "n"))
+ // Driven the way the worker drives it: Limit's own executor, opened before any state.
+ val exec = ExecFactory.newExecFromJavaClassName(className, descString)
+ exec.open()
+ exec.registerState(State(Map("n" -> 2L)))
+ exec.bindStateReferences()
+ val passed = (1 to 5).flatMap(i => exec.processTuple(line(i.toString), 0))
+ assert(passed.size == 2)
+ }
+
+ it should "report a reference inside a loop block on an operator whose code is generated" in {
+ // Sort generates its Python from its properties before the loop runs; outside every block
+ // "$USD" is the column name it is on main.
+ val csv = csvOp(realCsvPath)
+ val start = loopStartOp()
+ val sortJson =
+ """{"attributes":[{"attribute":"$%s","sortPreference":"ASC"}],"operatorType":"Sort"}"""
+ val sort = parsed(sortJson.format("col"))
+ val end = loopEndOp()
+
+ val result = new WorkflowCompiler(newContext()).compile(
+ pojo(List(csv, start, sort, end), chain(csv, start, sort, end))
+ )
+
+ assert(result.physicalPlan.isEmpty)
+ assert(result.operatorIdToError.keySet == Set(sort.operatorIdentifier))
+ assert(
+ result
+ .operatorIdToError(sort.operatorIdentifier)
+ .message
+ .contains("cannot refer to loop variables yet (/attributes/0/attribute -> $col)")
+ )
+
+ val outside = parsed(sortJson.format("USD"))
+ val outsideResult = new WorkflowCompiler(newContext()).compile(
+ pojo(List(csv, outside), List(linked(csv, outside)))
+ )
+ assert(
+ outsideResult.operatorIdToError.isEmpty,
+ s"unexpected: ${outsideResult.operatorIdToError}"
+ )
+ }
+
+ private def intervalJoinOp(): LogicalOp =
+ parsed(
+ """{"leftAttributeName":"line","rightAttributeName":"line","constant":"$i",
+ |"includeLeftBound":true,"includeRightBound":true,"operatorType":"IntervalJoin"}""".stripMargin
+ )
+
+ /**
+ * TextInput -> LoopStart -> Interval Join -> LoopEnd, the join's other table from outside the
+ * block: from a TextInput, or, `nested`, from the Projection of an outer block's body (outer
+ * LoopStart -> Projection, and outer LoopStart -> this LoopStart; LoopEnd -> outer LoopEnd).
+ */
+ private def compileJoin(
+ nested: Boolean,
+ leftFromOutside: Boolean
+ ): (LogicalOp, WorkflowCompilationResult) = {
+ val (src, start, end) = (textInputOp("0\n1"), loopStartOp(), loopEndOp())
+ val (outerStart, join, outerEnd) = (loopStartOp(), intervalJoinOp(), loopEndOp())
+ val outside = if (nested) projectOp(List("line")) else textInputOp("0")
+ val (left, right) = if (leftFromOutside) (outside, start) else (start, outside)
+ val operators =
+ if (!nested) List(outside, src, start, join, end)
+ else List(src, outerStart, outside, start, join, end, outerEnd)
+ val around =
+ if (!nested) chain(src, start)
+ else chain(src, outerStart, outside) ++ chain(outerStart, start) ++ chain(end, outerEnd)
+ val links = around ++ List(linked(left, join), linked(right, join, 1), linked(join, end))
+ (join, new WorkflowCompiler(newContext()).compile(pojo(operators, links)))
+ }
+
+ it should "report a reference inside a loop block, an inner one too, on an operator whose first input comes from outside it" in {
+ // Its right input waits for the left one, whose tuples can arrive before this block's state.
+ Seq(false, true).foreach { nested =>
+ val (join, result) = compileJoin(nested, leftFromOutside = true)
+ assert(
+ onlyErrorOf(result, join).contains(
+ "Interval Join refers to loop variables (/constant -> $i), but its input 'left table' " +
+ "is fed from outside the loop block"
+ ),
+ s"nested = $nested"
+ )
+ }
+ }
+
+ it should "accept a reference inside a loop block, an inner one too, on an operator whose input from outside it waits for one from inside" in {
+ Seq(false, true).foreach { nested =>
+ val (join, result) = compileJoin(nested, leftFromOutside = false)
+ assert(result.operatorIdToError.isEmpty, s"nested = $nested: ${result.operatorIdToError}")
+ val (_, descString) = executorInit(result, join)
+ assert(sidecarOf(descString) == Map("/constant" -> "i"))
+ }
+ }
+
+ it should "report a reference inside a loop block on an operator whose input also has a link from outside the block" in {
+ // Limit's one input takes the LoopStart's link and an outside one, whose tuples can come first.
+ val outside = textInputOp("0")
+ val src = textInputOp("0\n1")
+ val start = loopStartOp()
+ val limit = parsed("""{"limit":"$n","operatorType":"Limit"}""")
+ val end = loopEndOp()
+
+ val result = new WorkflowCompiler(newContext()).compile(
+ pojo(
+ List(outside, src, start, limit, end),
+ List(linked(src, start), linked(start, limit), linked(outside, limit), linked(limit, end))
+ )
+ )
+
+ assert(
+ onlyErrorOf(result, limit).contains(
+ "Limit refers to loop variables (/limit -> $n), but its input port 0 is fed from " +
+ "outside the loop block"
+ )
+ )
+ }
+
+ it should "report a reference in a loop block on an operator with an input from a sibling block" in {
+ // Inside the outer block, S1 -> Projection -> E1 and S2 -> Limit("$n") -> E2, and Projection
+ // -> Limit: neither of Limit's links carries both S1's and S2's state.
+ val src = textInputOp("0\n1")
+ val outerStart = loopStartOp()
+ val (first, project, firstEnd) = (loopStartOp(), projectOp(List("line")), loopEndOp())
+ val (second, limit, secondEnd) =
+ (loopStartOp(), parsed("""{"limit":"$n","operatorType":"Limit"}"""), loopEndOp())
+ val outerEnd = loopEndOp()
+
+ val result = new WorkflowCompiler(newContext()).compile(
+ pojo(
+ List(src, outerStart, first, project, firstEnd, second, limit, secondEnd, outerEnd),
+ chain(src, outerStart, first, project, firstEnd, outerEnd) ++
+ chain(outerStart, second, limit, secondEnd, outerEnd) :+ linked(project, limit)
+ )
+ )
+
+ assert(
+ onlyErrorOf(result, limit).contains("but its input port 0 is fed from outside the loop block")
+ )
+ }
}
diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/ExecFactory.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/ExecFactory.scala
index 88deaf7beb..360aa13313 100644
--- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/ExecFactory.scala
+++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/ExecFactory.scala
@@ -19,6 +19,10 @@
package org.apache.texera.amber.core.executor
+import org.apache.texera.amber.core.state.StateReferencing
+
+import java.lang.reflect.Modifier
+
object ExecFactory {
def newExecFromJavaCode(code: String): OperatorExecutor = {
@@ -29,11 +33,58 @@ object ExecFactory {
.asInstanceOf[OperatorExecutor]
}
+ /** A sidecar's loop variables are bound to the executor's one setting (`OperatorExecutor`). */
def newExecFromJavaClassName[K](
className: String,
descString: String = "",
idx: Int = 0,
workerCount: Int = 1
+ ): OperatorExecutor = {
+ val executor = instantiate[K](className, descString, idx, workerCount)
+ val references = StateReferenceBinding.sidecarOf(descString)
+ if (references.nonEmpty) {
+ def refuse(reason: String): Nothing = {
+ val named = references.toSeq.sorted.map { case (pointer, name) => s"$pointer -> $$$name" }
+ throw new IllegalStateException(
+ s"$className refers to loop variables (${named.mkString(", ")}), but it holds $reason"
+ )
+ }
+ settingsHeldBy(executor) match {
+ case List(setting) =>
+ OperatorExecutor.bindings.put(
+ executor,
+ new StateReferenceBinding(className, setting, references)
+ )
+ case Nil => refuse("no descriptor to write them into")
+ case settings =>
+ refuse(s"${settings.size} descriptors, so which one is its setting is unclear")
+ }
+ }
+ executor
+ }
+
+ /** The descriptors `executor` holds in a field of its class or a superclass, each object once. */
+ private def settingsHeldBy(executor: OperatorExecutor): List[StateReferencing] =
+ Iterator
+ .iterate[Class[_]](executor.getClass)(_.getSuperclass)
+ .takeWhile(_ != null)
+ .flatMap(_.getDeclaredFields)
+ .filter(field =>
+ !Modifier.isStatic(field.getModifiers) &&
+ classOf[StateReferencing].isAssignableFrom(field.getType)
+ )
+ .flatMap { field => field.setAccessible(true); Option(field.get(executor)) }
+ // By identity: a descriptor's equals compares its properties.
+ .foldLeft(List.empty[StateReferencing]) {
+ case (held, setting: StateReferencing) if !held.exists(_ eq setting) => held :+ setting
+ case (held, _) => held
+ }
+
+ private def instantiate[K](
+ className: String,
+ descString: String,
+ idx: Int,
+ workerCount: Int
): OperatorExecutor = {
val clazz = Class.forName(className).asInstanceOf[Class[K]]
try {
diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/OperatorExecutor.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/OperatorExecutor.scala
index 86412fae3b..e5b5f63818 100644
--- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/OperatorExecutor.scala
+++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/OperatorExecutor.scala
@@ -19,10 +19,21 @@
package org.apache.texera.amber.core.executor
+import com.google.common.collect.MapMaker
import org.apache.texera.amber.core.state.State
import org.apache.texera.amber.core.tuple.{Tuple, TupleLike}
import org.apache.texera.amber.core.workflow.PortIdentity
+/**
+ * Inside a loop block a setting may refer to a loop variable (`$i`): the worker writes each
+ * iteration's value into the settings object the executor holds, in place (`registerState`). For
+ * its settings to take loop variables, an executor built from a descString must:
+ * - keep exactly one settings object, the descriptor it parses from its descString, in a field;
+ * with none or several the worker fails to start;
+ * - read its settings only while processing data (`processState`, `processTuple`, the finish
+ * callbacks), never in its constructor, `open` or `produceStateOnStart`, which run before the
+ * state arrives: a value worked out there silently keeps the placeholder.
+ */
trait OperatorExecutor {
def open(): Unit = {}
@@ -55,4 +66,38 @@ trait OperatorExecutor {
def close(): Unit = {}
+ /**
+ * The state message most recently registered on this executor, `None` until one arrives; inside
+ * a loop block it carries the iteration's loop variables.
+ */
+ final def state: Option[State] = Option(OperatorExecutor.states.get(this))
+
+ /**
+ * The worker calls it for every state message, right before `processState`, with the message's
+ * `loopCounter`: 0 from the innermost loop around this operator, 1 from the one around that, and
+ * so on. Until `bindStateReferences`, it also writes each loop variable the message carries that
+ * the executor's setting (the descriptor it holds) refers to into that setting, in place. It
+ * fails when a message from the same loop gives such a variable another value.
+ */
+ final def registerState(state: State, loopCounter: Long = 0L): Unit = {
+ Option(OperatorExecutor.bindings.get(this)).foreach(_.write(state, loopCounter))
+ OperatorExecutor.states.put(this, state)
+ }
+
+ /**
+ * The worker calls it right before this executor first sees data or finishes. It fails, naming
+ * each reference no state message could write, and otherwise ends the writing: later messages
+ * no longer change the setting.
+ */
+ final def bindStateReferences(): Unit =
+ Option(OperatorExecutor.bindings.get(this)).foreach(_.bind())
+}
+
+object OperatorExecutor {
+
+ // Kept beside the executors instead of in fields of the trait, which a Java class implementing it
+ // (a Java UDF) would have to declare itself. Weak identity keys: an entry goes with its executor.
+ private val states = new MapMaker().weakKeys().makeMap[OperatorExecutor, State]()
+ private[executor] val bindings =
+ new MapMaker().weakKeys().makeMap[OperatorExecutor, StateReferenceBinding]()
}
diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/StateReferenceBinding.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/StateReferenceBinding.scala
new file mode 100644
index 0000000000..658841b632
--- /dev/null
+++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/StateReferenceBinding.scala
@@ -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.texera.amber.core.executor
+
+import com.fasterxml.jackson.core.{JsonPointer, JsonProcessingException}
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.{ArrayNode, JsonNodeFactory, ObjectNode}
+import org.apache.texera.amber.core.state.StateReferencing.SIDECAR_PROPERTY
+import org.apache.texera.amber.core.state.{State, StateReferencing}
+import org.apache.texera.amber.util.JSONUtils.objectMapper
+
+import scala.collection.mutable
+import scala.jdk.CollectionConverters.IteratorHasAsScala
+import scala.util.Try
+
+/**
+ * Writes the loop variables each state message carries into one executor's setting, the
+ * descriptor it holds, in place, at the placeholders its `stateReferences` sidecar names. Each
+ * value is coerced to the placeholder's JSON type. A message from a more deeply nested loop (a
+ * smaller `loopCounter`) replaces an outer one's value, so an inner loop's variable shadows an
+ * outer one of the same name. Messages from the same loop are copies, from several upstream
+ * workers or branches, so a different value is an error, bound or not. A value that cannot be
+ * written leaves the property as it was and is reported by `bind`, unless a deeper one can be.
+ *
+ * @param className the executor's class, named in the errors.
+ */
+private[executor] final class StateReferenceBinding(
+ className: String,
+ setting: StateReferencing,
+ references: Map[String, String]
+) {
+
+ /** Why each pointer is not written yet; a pointer is removed once a value is written to it. */
+ private val problems: mutable.SortedMap[String, String] = mutable.SortedMap.from(references.map {
+ case (pointer, name) =>
+ pointer -> s"property $pointer refers to loop variable $name, but no state message carried it"
+ })
+
+ /** Each referenced variable's value so far, and the `loopCounter` of the message carrying it. */
+ private val values = mutable.Map.empty[String, (Long, Any)]
+
+ /** Set once bound: a later message is still checked, but no longer written. */
+ private var bound = false
+
+ /** Writes each referenced variable `state` carries into the setting, in pointer order. */
+ def write(state: State, loopCounter: Long): Unit = {
+ val carried =
+ references.values.toSeq.distinct.sorted.flatMap(n => state.values.get(n).map(n -> _))
+ for ((name, value) <- carried; (depth, earlier) <- values.get(name))
+ if (depth == loopCounter && earlier != value)
+ throw new IllegalStateException(
+ s"loop variable $name got two different values in one iteration, $earlier and " +
+ s"$value: a loop's variables must not change inside its body"
+ )
+ val replacing =
+ if (bound) Map.empty[String, Any]
+ else carried.filter { case (name, _) => values.get(name).forall(_._1 > loopCounter) }.toMap
+ replacing.foreach { case (name, value) => values(name) = (loopCounter, value) }
+ for ((pointer, name) <- references.toSeq.sorted; value <- replacing.get(name))
+ try {
+ writeAt(pointer, name, value)
+ problems -= pointer
+ } catch {
+ case e: IllegalStateException => problems(pointer) = e.getMessage
+ case e: JsonProcessingException =>
+ problems(pointer) = s"property $pointer refers to loop variable $name, but its " +
+ s"value $value does not fit it: ${e.getOriginalMessage}"
+ }
+ }
+
+ /** Fails, naming in pointer order each reference not written yet, or ends the writing. */
+ def bind(): Unit = {
+ if (problems.nonEmpty) throw new IllegalStateException(problems.values.mkString("; "))
+ bound = true
+ }
+
+ /**
+ * Puts `value` at `pointer` in a fresh JSON of the setting, and hands the top-level property it
+ * falls under back to Jackson, which replaces that property of the setting in place. Jackson
+ * sets a property only once its whole value has parsed, so a refused value changes nothing.
+ */
+ private def writeAt(pointer: String, name: String, value: Any): Unit = {
+ val json = objectMapper.valueToTree[ObjectNode](setting)
+ val path = Try(JsonPointer.compile(pointer)).toOption
+ .filter(json.at(_).isValueNode)
+ .getOrElse(
+ throw new IllegalStateException(
+ s"property $pointer refers to loop variable $name, but $className parsed a setting " +
+ "with no value there"
+ )
+ )
+ val node = StateReferenceBinding.coerce(json.at(path), value, pointer, name)
+ json.at(path.head) match {
+ case obj: ObjectNode => obj.replace(path.last.getMatchingProperty, node)
+ case array: ArrayNode => array.set(path.last.getMatchingIndex, node)
+ }
+ objectMapper.readerForUpdating(setting).readValue[AnyRef](json.retain(path.getMatchingProperty))
+ }
+}
+
+private[executor] object StateReferenceBinding {
+
+ private val nodes = JsonNodeFactory.instance
+
+ /** The `stateReferences` sidecar of `descString`: empty unless it is a descriptor naming one. */
+ def sidecarOf(descString: String): Map[String, String] =
+ Try(objectMapper.readTree(descString)).toOption
+ .collect { case tree: ObjectNode => tree }
+ .flatMap(tree => Option(tree.get(SIDECAR_PROPERTY)))
+ .iterator
+ .flatMap(_.fields().asScala)
+ .map(entry => entry.getKey -> entry.getValue.asText())
+ .toMap
+
+ /** The node that takes `placeholder`'s place for `value`: the placeholder's JSON type wins. */
+ private def coerce(placeholder: JsonNode, value: Any, pointer: String, name: String): JsonNode = {
+ val text = String.valueOf(value).trim
+ def fail(kind: String): Nothing =
+ throw new IllegalStateException(
+ s"property $pointer refers to loop variable $name, but its value $value is not $kind"
+ )
+ def as[T](kind: String)(convert: => T): T = Try(convert).getOrElse(fail(kind))
+ if (placeholder.isIntegralNumber) {
+ nodes.numberNode(as("an integer")(new java.math.BigDecimal(text).longValueExact()))
+ } else if (placeholder.isNumber) {
+ nodes.numberNode(as("a number")(text.toDouble))
+ } else if (placeholder.isBoolean) {
+ nodes.booleanNode(as("a boolean")(text.toBooleanOption.get))
+ } else {
+ value match {
+ case _: String | _: java.lang.Number | _: java.lang.Boolean =>
+ nodes.textNode(value.toString)
+ case _ => fail("a scalar")
+ }
+ }
+ }
+}
diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/state/StateReferenceModule.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/state/StateReferenceModule.scala
new file mode 100644
index 0000000000..b11f22c8dd
--- /dev/null
+++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/state/StateReferenceModule.scala
@@ -0,0 +1,171 @@
+/*
+ * 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.texera.amber.core.state
+
+import com.fasterxml.jackson.core.{JsonParser, JsonToken}
+import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer
+import com.fasterxml.jackson.databind.deser.{
+ BeanDeserializerModifier,
+ DeserializationProblemHandler
+}
+import com.fasterxml.jackson.databind.module.SimpleModule
+import com.fasterxml.jackson.databind.{
+ BeanDescription,
+ DeserializationConfig,
+ DeserializationContext,
+ JsonDeserializer,
+ Module
+}
+import org.apache.texera.amber.core.state.StateReferencing.referencedVariable
+
+import java.lang.reflect.Modifier
+import scala.collection.mutable
+
+/**
+ * Parses a `$K` loop-variable reference in a typed property of a `StateReferencing` descriptor.
+ *
+ * The frontend sends the literal string `"$K"` whatever the property's type, so an Int property
+ * such as Limit's `limit` would not parse. When Jackson cannot convert a whole-string `$name` to
+ * an integral, floating-point or boolean value, this module's handler puts the placeholder `0` /
+ * `0.0` / `false` there and records the value's JSON pointer, relative to the object, -> `name`
+ * in the object's `stateReferences` sidecar. Any other target keeps Jackson's ordinary error. A
+ * String property keeps the literal: the compiler finds those itself, and only inside a loop
+ * block (`WorkflowCompiler.normalizeStateReferences`).
+ */
+class StateReferenceModule extends SimpleModule("StateReferenceModule") {
+
+ setDeserializerModifier(new BeanDeserializerModifier {
+ override def modifyDeserializer(
+ config: DeserializationConfig,
+ beanDesc: BeanDescription,
+ deserializer: JsonDeserializer[_]
+ ): JsonDeserializer[_] = {
+ val beanClass = beanDesc.getBeanClass
+ if (
+ classOf[StateReferencing].isAssignableFrom(beanClass) &&
+ !Modifier.isAbstract(beanClass.getModifiers)
+ ) {
+ new StateReferenceModule.RecordingDeserializer(deserializer)
+ } else {
+ deserializer
+ }
+ }
+ })
+
+ override def setupModule(context: Module.SetupContext): Unit = {
+ super.setupModule(context)
+ context.addDeserializationProblemHandler(StateReferenceModule.PlaceholderHandler)
+ }
+}
+
+object StateReferenceModule {
+
+ /** The placeholder for each target Jackson converts a string to: primitive and boxed. */
+ private val Placeholders: Map[Class[_], AnyRef] =
+ Seq[(Class[_], Class[_], AnyRef)](
+ (classOf[Int], classOf[java.lang.Integer], Int.box(0)),
+ (classOf[Long], classOf[java.lang.Long], Long.box(0L)),
+ (classOf[Short], classOf[java.lang.Short], Short.box(0)),
+ (classOf[Double], classOf[java.lang.Double], Double.box(0.0)),
+ (classOf[Float], classOf[java.lang.Float], Float.box(0f)),
+ (classOf[Boolean], classOf[java.lang.Boolean], Boolean.box(false))
+ ).flatMap { case (primitive, boxed, zero) => Seq(primitive -> zero, boxed -> zero) }.toMap
+
+ /**
+ * The innermost `StateReferencing` object being parsed, kept on the context under
+ * `classOf[Frame]`: the parser over its own copy, and the references recorded so far.
+ */
+ private final class Frame(val parser: JsonParser) {
+ val references: mutable.Map[String, String] = mutable.Map.empty
+ }
+
+ private object PlaceholderHandler extends DeserializationProblemHandler {
+ override def handleWeirdStringValue(
+ ctxt: DeserializationContext,
+ targetType: Class[_],
+ valueToConvert: String,
+ failureMsg: String
+ ): AnyRef = {
+ val placeholder = for {
+ name <- referencedVariable(valueToConvert)
+ placeholder <- Placeholders.get(targetType)
+ frame <- Option(ctxt.getAttribute(classOf[Frame]).asInstanceOf[Frame])
+ // The object's parser must stand on this very string: one that a nested object Jackson
+ // replays from a buffer of its own does not, and its pointer cannot be told from here.
+ if frame.parser.hasToken(JsonToken.VALUE_STRING) && frame.parser.getText == valueToConvert
+ } yield {
+ // The parser reads the object's own copy, so its path is relative to the object.
+ frame.references(frame.parser.getParsingContext.pathAsPointer.toString) = name
+ placeholder
+ }
+ placeholder.getOrElse(DeserializationProblemHandler.NOT_HANDLED)
+ }
+ }
+
+ /**
+ * Wraps the deserializer of one concrete `StateReferencing` class, and parses each object from
+ * a copy of its own: a polymorphic type deserializer hands the object over mid-way, after the
+ * type id, and may replay the fields before it from a buffer whose parse context is not the
+ * object's.
+ */
+ private final class RecordingDeserializer(delegate: JsonDeserializer[_])
+ extends DelegatingDeserializer(delegate) {
+
+ override protected def newDelegatingInstance(
+ newDelegatee: JsonDeserializer[_]
+ ): JsonDeserializer[_] = new RecordingDeserializer(newDelegatee)
+
+ override def deserialize(p: JsonParser, ctxt: DeserializationContext): AnyRef =
+ if (p.hasToken(JsonToken.START_OBJECT) || p.hasToken(JsonToken.FIELD_NAME)) {
+ recorded(ownCopy(p, ctxt), ctxt)
+ } else {
+ _delegatee.deserialize(p, ctxt).asInstanceOf[AnyRef]
+ }
+
+ private def recorded(parser: JsonParser, ctxt: DeserializationContext): AnyRef = {
+ val frame = new Frame(parser)
+ val enclosing = ctxt.getAttribute(classOf[Frame])
+ ctxt.setAttribute(classOf[Frame], frame)
+ val bean =
+ try _delegatee.deserialize(parser, ctxt).asInstanceOf[AnyRef]
+ finally ctxt.setAttribute(classOf[Frame], enclosing)
+ bean.asInstanceOf[StateReferencing].stateReferences = frame.references.toMap
+ bean
+ }
+ }
+
+ /** The object `p` stands in, as a parser on the START_OBJECT of a copy; `p` ends on its end. */
+ private def ownCopy(p: JsonParser, ctxt: DeserializationContext): JsonParser = {
+ val buffer = ctxt.bufferForInputBuffering(p).overrideParentContext(null)
+ if (p.hasToken(JsonToken.START_OBJECT)) {
+ buffer.copyCurrentStructure(p)
+ } else {
+ buffer.writeStartObject()
+ while (p.hasToken(JsonToken.FIELD_NAME)) {
+ buffer.copyCurrentStructure(p)
+ p.nextToken()
+ }
+ buffer.writeEndObject()
+ }
+ val parser = buffer.asParser(p)
+ parser.nextToken()
+ parser
+ }
+}
diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/state/StateReferencing.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/state/StateReferencing.scala
new file mode 100644
index 0000000000..37c9ca3b3e
--- /dev/null
+++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/state/StateReferencing.scala
@@ -0,0 +1,81 @@
+/*
+ * 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.texera.amber.core.state
+
+import com.fasterxml.jackson.annotation.JsonProperty
+import com.fasterxml.jackson.core.JsonPointer
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+
+import scala.jdk.CollectionConverters.IteratorHasAsScala
+
+/**
+ * A descriptor whose properties may refer to loop variables.
+ *
+ * Inside a loop block (LoopStart ... LoopEnd) a property whose WHOLE value is `$K` refers to the
+ * loop variable `K`, which reaches the operator in the iteration's state message. The
+ * `stateReferences` sidecar maps each such property's JSON pointer to the variable name: the
+ * parse records the typed ones (`StateReferenceModule`), the compiler adds the string ones
+ * (`WorkflowCompiler.normalizeStateReferences`), and the worker writes the variables there
+ * (`OperatorExecutor.registerState`). The property panel never shows it.
+ */
+trait StateReferencing {
+
+ @JsonProperty(StateReferencing.SIDECAR_PROPERTY)
+ var stateReferences: Map[String, String] = Map.empty
+}
+
+object StateReferencing {
+
+ /** The JSON name of the sidecar. */
+ final val SIDECAR_PROPERTY = "stateReferences"
+
+ /** `$` followed by a name; the WHOLE string must match. */
+ private val ReferencePattern = "^\\$([A-Za-z_][A-Za-z0-9_]*)$".r
+
+ /** The loop variable `value` refers to, when the whole string is a `$name` reference. */
+ def referencedVariable(value: String): Option[String] =
+ value match {
+ case ReferencePattern(name) => Some(name)
+ case _ => None
+ }
+
+ /** Every whole-string `$name` value of `tree` outside its sidecar: its JSON pointer -> name. */
+ def literalReferences(tree: ObjectNode): Map[String, String] = {
+ def scan(node: JsonNode, at: JsonPointer): Iterator[(String, String)] =
+ if (node.isTextual) {
+ referencedVariable(node.asText()).map(at.toString -> _).iterator
+ } else if (node.isObject) {
+ node.fields().asScala.flatMap { entry =>
+ scan(entry.getValue, at.appendProperty(entry.getKey))
+ }
+ } else {
+ node.elements().asScala.zipWithIndex.flatMap {
+ case (element, i) => scan(element, at.appendIndex(i))
+ }
+ }
+ tree
+ .fields()
+ .asScala
+ .filter(_.getKey != SIDECAR_PROPERTY)
+ .flatMap(entry => scan(entry.getValue, JsonPointer.empty().appendProperty(entry.getKey)))
+ .toMap
+ }
+}
diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/util/JSONUtils.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/util/JSONUtils.scala
index 8b8d4b3c32..0443a7e74a 100644
--- a/common/workflow-core/src/main/scala/org/apache/texera/amber/util/JSONUtils.scala
+++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/util/JSONUtils.scala
@@ -25,6 +25,7 @@ import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper}
import com.fasterxml.jackson.module.noctordeser.NoCtorDeserModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
+import org.apache.texera.amber.core.state.StateReferenceModule
import org.apache.texera.amber.core.workflow.PortIdentity
import org.apache.texera.amber.util.serde.{PortIdentityKeyDeserializer, PortIdentityKeySerializer}
@@ -46,6 +47,10 @@ object JSONUtils {
@JsonIgnore def isDefined: Boolean
}
+ /** Registers what any mapper parsing workflows (Dropwizard's too) needs: Scala types and `$K`. */
+ def registerWorkflowModules(mapper: ObjectMapper): ObjectMapper =
+ mapper.registerModule(DefaultScalaModule).registerModule(new StateReferenceModule())
+
/**
* A singleton object for configuring the Jackson `ObjectMapper` to handle JSON serialization and deserialization
* in Scala. This custom `ObjectMapper` is tailored for Scala, ensuring compatibility with Scala types
@@ -68,8 +73,7 @@ object JSONUtils {
* This `ObjectMapper` provides a consistent way to serialize and deserialize JSON while adhering to Scala conventions
* and handling common patterns like `Option` and case classes.
*/
- final val objectMapper = new ObjectMapper()
- .registerModule(DefaultScalaModule)
+ final val objectMapper = registerWorkflowModules(new ObjectMapper())
.registerModule(new NoCtorDeserModule())
.registerModule(
new SimpleModule()
diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/executor/CoreExecutorReflectionSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/executor/CoreExecutorReflectionSpec.scala
index 94aa189d7c..a8ceb1f506 100644
--- a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/executor/CoreExecutorReflectionSpec.scala
+++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/executor/CoreExecutorReflectionSpec.scala
@@ -19,8 +19,10 @@
package org.apache.texera.amber.core.executor
-import org.apache.texera.amber.core.state.State
+import com.fasterxml.jackson.annotation.JsonProperty
+import org.apache.texera.amber.core.state.{State, StateReferencing}
import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple, TupleLike}
+import org.apache.texera.amber.util.JSONUtils.objectMapper
import org.scalatest.flatspec.AnyFlatSpec
class CoreExecutorReflectionSpec extends AnyFlatSpec {
@@ -136,6 +138,19 @@ class CoreExecutorReflectionSpec extends AnyFlatSpec {
assert(exec.onFinishMultiPort(0).isEmpty)
}
+ "OperatorExecutor.state" should "be None until a state is registered, then the latest one registered" in {
+ val exec = new IdentityExec
+ assert(exec.state.isEmpty)
+ val first = State(Map[String, Any]("i" -> 1))
+ val second = State(Map[String, Any]("i" -> 2))
+ exec.registerState(first)
+ assert(exec.state.contains(first))
+ exec.registerState(second)
+ assert(exec.state.contains(second))
+ // Kept per executor: another one has seen no state.
+ assert(new IdentityExec().state.isEmpty)
+ }
+
// ---------------------------------------------------------------------------
// SourceOperatorExecutor trait defaults
// ---------------------------------------------------------------------------
@@ -241,6 +256,91 @@ class CoreExecutorReflectionSpec extends AnyFlatSpec {
}
}
+ // ---------------------------------------------------------------------------
+ // ExecFactory.newExecFromJavaClassName with loop-variable references
+ // ---------------------------------------------------------------------------
+
+ private val referencingDesc = """{"limit":0,"stateReferences":{"/limit":"n"}}"""
+
+ it should "build the operator's own executor, from the descString with its placeholders, when the sidecar names a loop variable" in {
+ val exec = ExecFactory.newExecFromJavaClassName(
+ classOf[CoreExecutorReflectionSpec.LimitExec].getName,
+ referencingDesc,
+ idx = 2,
+ workerCount = 3
+ )
+ // No wrapper: the worker calls every callback on the operator itself, at the usual time.
+ assert(exec.getClass == classOf[CoreExecutorReflectionSpec.LimitExec])
+ val typed = exec.asInstanceOf[CoreExecutorReflectionSpec.LimitExec]
+ assert(typed.setting.limit == 0)
+ assert((typed.idx, typed.workerCount) == ((2, 3)))
+ // The setting it holds is the one the state writes into.
+ exec.registerState(State(Map[String, Any]("n" -> 4L)))
+ assert(typed.setting.limit == 4)
+ }
+
+ it should "leave a '$name' outside every loop block the literal it is, with nothing to write" in {
+ // Outside every loop block the sidecar is empty, and "$AAPL" is the literal the operator
+ // compares against, as it was before loop variables existed.
+ Seq("""{"name":"$AAPL"}""", """{"name":"$AAPL","stateReferences":{}}""").foreach { desc =>
+ val exec = ExecFactory.newExecFromJavaClassName(
+ classOf[CoreExecutorReflectionSpec.NameExec].getName,
+ desc
+ )
+ val typed = exec.asInstanceOf[CoreExecutorReflectionSpec.NameExec]
+ exec.registerState(State(Map[String, Any]("AAPL" -> "bound")))
+ exec.bindStateReferences()
+ assert(typed.setting.name == "$AAPL", desc)
+ }
+ }
+
+ it should "find the setting in a field its superclass declares" in {
+ val exec = ExecFactory.newExecFromJavaClassName(
+ classOf[CoreExecutorReflectionSpec.InheritedLimitExec].getName,
+ referencingDesc
+ )
+ exec.registerState(State(Map[String, Any]("n" -> 3L)))
+ assert(exec.asInstanceOf[CoreExecutorReflectionSpec.InheritedLimitExec].setting.limit == 3)
+ }
+
+ it should "count a setting held in more than one field once" in {
+ val exec = ExecFactory.newExecFromJavaClassName(
+ classOf[CoreExecutorReflectionSpec.AliasedLimitExec].getName,
+ referencingDesc
+ )
+ exec.registerState(State(Map[String, Any]("n" -> 3L)))
+ assert(exec.asInstanceOf[CoreExecutorReflectionSpec.AliasedLimitExec].alias.limit == 3)
+ }
+
+ it should "refuse, naming the operator, when it holds no setting or more than one" in {
+ val none = classOf[CoreExecutorReflectionSpec.StringArgExec].getName
+ assert(
+ intercept[IllegalStateException](
+ ExecFactory.newExecFromJavaClassName(none, referencingDesc)
+ ).getMessage ==
+ s"$none refers to loop variables (/limit -> $$n), but it holds no descriptor to write " +
+ "them into"
+ )
+ val two = classOf[CoreExecutorReflectionSpec.TwoSettingsExec].getName
+ assert(
+ intercept[IllegalStateException](
+ ExecFactory.newExecFromJavaClassName(two, referencingDesc)
+ ).getMessage ==
+ s"$two refers to loop variables (/limit -> $$n), but it holds 2 descriptors, so which " +
+ "one is its setting is unclear"
+ )
+ }
+
+ it should "look for references only in a descString that is a JSON object" in {
+ Seq("hello", "[1]", "{not json", "null").foreach { desc =>
+ val exec = ExecFactory.newExecFromJavaClassName(
+ classOf[CoreExecutorReflectionSpec.StringArgExec].getName,
+ desc
+ )
+ assert(exec.asInstanceOf[CoreExecutorReflectionSpec.StringArgExec].desc == desc)
+ }
+ }
+
// ---------------------------------------------------------------------------
// ExecFactory.newExecFromJavaCode
//
@@ -281,6 +381,14 @@ class CoreExecutorReflectionSpec extends AnyFlatSpec {
assert(first.getClass.getName == second.getClass.getName)
}
+ it should "register a state on a Java class implementing the trait, which holds no fields for it" in {
+ val exec = ExecFactory.newExecFromJavaCode(echoUDFSource)
+ val state = State(Map[String, Any]("i" -> 1))
+ exec.registerState(state)
+ exec.bindStateReferences()
+ assert(exec.state.contains(state))
+ }
+
it should "surface the compiler diagnostics when the java source does not compile" in {
// A class that claims the trait but never implements `processTuple` is
// rejected by javac, so no instance is ever constructed.
@@ -349,6 +457,69 @@ private object CoreExecutorReflectionSpec {
): Iterator[org.apache.texera.amber.core.tuple.TupleLike] = Iterator.empty
}
+ /** A setting with one Int property. */
+ class LimitSetting extends StateReferencing {
+ @JsonProperty var limit: Int = _
+ }
+
+ /** A setting with one String property. */
+ class NameSetting extends StateReferencing {
+ @JsonProperty var name: String = _
+ }
+
+ /** Parses its setting in the class body; only a `(String, Int, Int)` constructor. */
+ class LimitExec(descString: String, val idx: Int, val workerCount: Int) extends OperatorExecutor {
+ val setting: LimitSetting = objectMapper.readValue(descString, classOf[LimitSetting])
+ override def processTuple(
+ tuple: org.apache.texera.amber.core.tuple.Tuple,
+ port: Int
+ ): Iterator[org.apache.texera.amber.core.tuple.TupleLike] = Iterator.empty
+ }
+
+ class NameExec(descString: String) extends OperatorExecutor {
+ val setting: NameSetting = objectMapper.readValue(descString, classOf[NameSetting])
+ override def processTuple(
+ tuple: org.apache.texera.amber.core.tuple.Tuple,
+ port: Int
+ ): Iterator[org.apache.texera.amber.core.tuple.TupleLike] = Iterator.empty
+ }
+
+ /** Equal to every setting of its class with the same limit, as a descriptor's equals is. */
+ class EqualLimitSetting extends LimitSetting {
+ override def equals(other: Any): Boolean =
+ other match {
+ case that: EqualLimitSetting => that.limit == limit
+ case _ => false
+ }
+ override def hashCode(): Int = limit
+ }
+
+ /** Parses its descString twice, so it has two candidate settings, equal but not the same. */
+ class TwoSettingsExec(descString: String) extends OperatorExecutor {
+ val first: EqualLimitSetting = objectMapper.readValue(descString, classOf[EqualLimitSetting])
+ val second: EqualLimitSetting = objectMapper.readValue(descString, classOf[EqualLimitSetting])
+ override def processTuple(
+ tuple: org.apache.texera.amber.core.tuple.Tuple,
+ port: Int
+ ): Iterator[org.apache.texera.amber.core.tuple.TupleLike] = Iterator.empty
+ }
+
+ abstract class LimitExecBase(descString: String) extends OperatorExecutor {
+ val setting: LimitSetting = objectMapper.readValue(descString, classOf[LimitSetting])
+ override def processTuple(
+ tuple: org.apache.texera.amber.core.tuple.Tuple,
+ port: Int
+ ): Iterator[org.apache.texera.amber.core.tuple.TupleLike] = Iterator.empty
+ }
+
+ /** Its setting is declared only in its superclass. */
+ class InheritedLimitExec(descString: String) extends LimitExecBase(descString)
+
+ /** Its setting is declared in its superclass, and held once more under another name. */
+ class AliasedLimitExec(descString: String) extends LimitExecBase(descString) {
+ val alias: LimitSetting = setting
+ }
+
/** Only a `(Long)` constructor — neither factory branch matches. */
class LongArgExec(val n: Long) extends OperatorExecutor {
override def processTuple(
diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/executor/StateReferenceBindingSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/executor/StateReferenceBindingSpec.scala
new file mode 100644
index 0000000000..81a2bd23e2
--- /dev/null
+++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/executor/StateReferenceBindingSpec.scala
@@ -0,0 +1,288 @@
+/*
+ * 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.texera.amber.core.executor
+
+import com.fasterxml.jackson.annotation.JsonProperty
+import org.apache.texera.amber.core.state.{State, StateReferencing}
+import org.apache.texera.amber.core.tuple.{Tuple, TupleLike}
+import org.apache.texera.amber.util.JSONUtils.objectMapper
+import org.scalatest.flatspec.AnyFlatSpec
+
+/**
+ * `StateReferenceBinding`, driven the way the worker drives it: `registerState` for each state
+ * message, then `bindStateReferences` before the first tuple, on an executor `ExecFactory` built.
+ */
+class StateReferenceBindingSpec extends AnyFlatSpec {
+
+ import StateReferenceBindingSpec._
+
+ private val allReferences = Map(
+ "/name" -> "i",
+ "/limit" -> "n",
+ "/tags/1" -> "t",
+ "/predicates/1/value" -> "v",
+ "/predicates/1/threshold" -> "h"
+ )
+
+ /** The descString as the compiler hands it over: placeholders, and the sidecar naming them. */
+ private def descString(references: Map[String, String] = allReferences): String =
+ s"""{"name":"$$i","limit":0,"ratio":0.0,"enabled":false,"tags":["a","$$t"],
+ |"predicates":[{"attribute":"x","value":"kept","threshold":1.5,"count":0},
+ |{"attribute":"y","value":"$$v","threshold":0.0,"count":0}],
+ |"stateReferences":${objectMapper.writeValueAsString(references)}}""".stripMargin
+
+ private def build(references: Map[String, String] = allReferences): SettingExec =
+ ExecFactory
+ .newExecFromJavaClassName(classOf[SettingExec].getName, descString(references))
+ .asInstanceOf[SettingExec]
+
+ private def missing(pointer: String, name: String): String =
+ s"property $pointer refers to loop variable $name, but no state message carried it"
+
+ "StateReferenceBinding" should "write each variable a registered message carries into the setting the executor holds, in place" in {
+ val exec = build()
+ val setting = exec.setting
+ val kept = setting.predicates.head
+ exec.registerState(State(Map("n" -> 2L, "v" -> "x1", "h" -> 2.5, "unrelated" -> 1)))
+
+ // The executor keeps reading the very object its constructor parsed.
+ assert(exec.setting eq setting)
+ assert(setting.limit == 2)
+ assert(setting.predicates.map(_.value) == List("kept", "x1"))
+ assert(setting.predicates.map(_.threshold) == List(1.5, 2.5))
+ assert(setting.predicates.head.attribute == "x" && setting.predicates(1).attribute == "y")
+ // A property the message does not carry keeps its placeholder, and so does everything else.
+ assert(setting.name == "$i")
+ assert(setting.tags == List("a", "$t"))
+ assert((setting.ratio, setting.enabled) == ((0.0, false)))
+ assert(kept.value == "kept")
+ // The sidecar is what the executor's own parse recorded; nothing writes it.
+ assert(setting.stateReferences.isEmpty)
+ }
+
+ it should "let a more deeply nested loop's value replace an outer one's, even one that did not fit, and keep it" in {
+ // In a nested loop the inner body first receives the outer loop's state, one loop out, then
+ // the inner one's: an inner variable shadows an outer one of the same name.
+ val exec = build()
+ val outer = State(Map("i" -> 1L, "n" -> 2, "t" -> "outer", "v" -> "o", "h" -> "not a number"))
+ exec.registerState(outer, loopCounter = 1)
+ exec.registerState(State(Map("i" -> 5L, "t" -> "inner", "h" -> 1)), loopCounter = 0)
+ // A later copy of the outer loop's state, from another upstream worker, does not undo it.
+ exec.registerState(outer, loopCounter = 1)
+ exec.bindStateReferences()
+
+ val setting = exec.setting
+ assert((setting.name, setting.limit, setting.tags) == (("5", 2, List("a", "inner"))))
+ assert(setting.predicates(1).value == "o")
+ assert(setting.predicates(1).threshold == 1.0)
+ assert(exec.state.contains(outer))
+ }
+
+ it should "accept copies from one loop that agree, and fail on one that gives a variable another value, bound or not" in {
+ def conflict(earlier: Any, later: Any): String =
+ s"loop variable n got two different values in one iteration, $earlier and $later: " +
+ "a loop's variables must not change inside its body"
+ val exec = build(Map("/limit" -> "n", "/name" -> "i"))
+ // Copies from several upstream workers or branches: the same number whatever its boxed type,
+ // and a variable no property refers to may differ.
+ exec.registerState(State(Map("n" -> 1L, "unrelated" -> 1)), loopCounter = 1)
+ val copy = State(Map("n" -> 1, "unrelated" -> 2))
+ exec.registerState(copy, loopCounter = 1)
+
+ assert(
+ intercept[IllegalStateException](
+ exec.registerState(State(Map("i" -> "x", "n" -> 2L)), loopCounter = 1)
+ ).getMessage == conflict(1, 2)
+ )
+ // Nothing of the refused message is written, not even its i, which no message carried yet and
+ // which sorts before n; nor is the message registered.
+ assert((exec.setting.limit, exec.setting.name) == ((1, "$i")))
+ assert(exec.state.contains(copy))
+ exec.registerState(State(Map("i" -> "y")), loopCounter = 1)
+ exec.bindStateReferences()
+ assert(
+ intercept[IllegalStateException](
+ exec.registerState(State(Map("n" -> "x")), loopCounter = 1)
+ ).getMessage == conflict(1, "x")
+ )
+ assert((exec.setting.limit, exec.setting.name) == ((1, "y")))
+ }
+
+ it should "fail at binding, naming every reference no state message carried, until one does" in {
+ val exec = build()
+ exec.registerState(State(Map("i" -> 1L)))
+ val message = intercept[IllegalStateException](exec.bindStateReferences()).getMessage
+ assert(
+ message == Seq(
+ missing("/limit", "n"),
+ missing("/predicates/1/threshold", "h"),
+ missing("/predicates/1/value", "v"),
+ missing("/tags/1", "t")
+ ).mkString("; ")
+ )
+ assert(exec.setting.name == "1")
+ assert(exec.setting.limit == 0)
+ // A failed binding does not end the writing.
+ assert(intercept[IllegalStateException](exec.bindStateReferences()).getMessage == message)
+ exec.registerState(State(Map("n" -> 4, "h" -> 1, "v" -> "x", "t" -> "y")))
+ exec.bindStateReferences()
+ assert(exec.setting.limit == 4)
+ }
+
+ it should "stop writing once bound: a later message is still registered, but the setting keeps its values" in {
+ // Workers are recreated for each iteration, so a bound setting never needs rebinding.
+ val exec = build(Map("/limit" -> "n", "/name" -> "i"))
+ exec.registerState(State(Map("n" -> 2L, "i" -> "x")), loopCounter = 1)
+ exec.bindStateReferences()
+ // Even a more deeply nested loop's, which would have replaced them before.
+ val later = State(Map("n" -> 9L, "i" -> "y"))
+ exec.registerState(later, loopCounter = 0)
+ exec.bindStateReferences()
+ assert(exec.state.contains(later))
+ assert((exec.setting.limit, exec.setting.name) == ((2, "x")))
+ }
+
+ it should "write a variable into every property that refers to it" in {
+ val exec = build(Map("/name" -> "i", "/tags/1" -> "i", "/limit" -> "i"))
+ exec.registerState(State(Map("i" -> 3L)))
+ exec.bindStateReferences()
+ assert((exec.setting.name, exec.setting.tags, exec.setting.limit) == (("3", List("a", "3"), 3)))
+ }
+
+ it should "report a sidecar pointer that names no value of the setting at binding" in {
+ // "limit" is not a JSON pointer at all: it does not start with "/".
+ Seq("/nothing", "/tags/5", "/predicates", "/predicates/1", "/stateReferences/x", "", "limit")
+ .foreach { pointer =>
+ assert(
+ bindOneFails(pointer, 1) == s"property $pointer refers to loop variable k, but " +
+ s"${classOf[SettingExec].getName} parsed a setting with no value there",
+ pointer
+ )
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Coercion: the placeholder's JSON type wins
+ // ---------------------------------------------------------------------------
+
+ private def bindOne(pointer: String, value: Any): Setting = {
+ val exec = build(Map(pointer -> "k"))
+ exec.registerState(State(Map("k" -> value)))
+ exec.bindStateReferences()
+ exec.setting
+ }
+
+ /** A value that cannot be written is reported at binding, not when its message arrives. */
+ private def bindOneFails(pointer: String, value: Any): String = {
+ val exec = build(Map(pointer -> "k"))
+ exec.registerState(State(Map("k" -> value)))
+ intercept[IllegalStateException](exec.bindStateReferences()).getMessage
+ }
+
+ it should "bind each placeholder from a value its JSON type accepts" in {
+ def accepts[T](pointer: String, read: Setting => T)(cases: (Any, T)*): Unit =
+ cases.foreach {
+ case (value, expected) => assert(read(bindOne(pointer, value)) == expected, value)
+ }
+ accepts("/limit", _.limit)(7 -> 7, 7L -> 7, 7.0 -> 7, "7" -> 7, " 7 " -> 7)
+ accepts("/ratio", _.ratio)(3 -> 3.0, 2.5 -> 2.5, "1.5" -> 1.5, 7L -> 7.0)
+ accepts("/enabled", _.enabled)(true -> true, "false" -> false, "TRUE" -> true)
+ accepts("/name", _.name)(5L -> "5", 2.5 -> "2.5", true -> "true", "text" -> "text", "" -> "")
+ accepts("/tags/1", _.tags)("ünïcödé" -> List("a", "ünïcödé"))
+ }
+
+ it should "report a value its placeholder's JSON type does not accept, naming the property" in {
+ Seq[(String, Any, String)](
+ ("/limit", 7.5, "an integer"),
+ ("/limit", "seven", "an integer"),
+ ("/limit", true, "an integer"),
+ ("/limit", "", "an integer"),
+ ("/ratio", "abc", "a number"),
+ ("/ratio", false, "a number"),
+ ("/enabled", 1, "a boolean"),
+ ("/enabled", "yes", "a boolean"),
+ // A Python None arrives as null; a list, a map or bytes has no text to bind.
+ ("/name", null, "a scalar"),
+ ("/name", List("a", "b"), "a scalar"),
+ ("/name", Map("a" -> 1), "a scalar"),
+ ("/name", Array[Byte](1, 2), "a scalar")
+ ).foreach {
+ case (pointer, value, kind) =>
+ assert(
+ bindOneFails(pointer, value) ==
+ s"property $pointer refers to loop variable k, but its value $value is not $kind"
+ )
+ }
+ }
+
+ it should "report an integer that does not fit the property, naming the property" in {
+ val message = bindOneFails("/limit", 3000000000L)
+ assert(
+ message.startsWith(
+ "property /limit refers to loop variable k, but its value 3000000000 does not fit it: "
+ ),
+ message
+ )
+ }
+
+ it should "report a nested value that does not fit against its own property, and still write the ones after it" in {
+ // Both fall under /predicates, which is handed to Jackson whole for each write: the value that
+ // did not fit must not ride along with the next one.
+ val exec = build(Map("/predicates/0/count" -> "c", "/predicates/1/value" -> "v"))
+ exec.registerState(State(Map("c" -> 3000000000L, "v" -> "x1")))
+ val message = intercept[IllegalStateException](exec.bindStateReferences()).getMessage
+ assert(
+ message.startsWith(
+ "property /predicates/0/count refers to loop variable c, but its value 3000000000 does " +
+ "not fit it: "
+ ),
+ message
+ )
+ assert(!message.contains("/predicates/1/value"), message)
+ assert(exec.setting.predicates.map(_.value) == List("kept", "x1"))
+ assert(exec.setting.predicates.map(_.count) == List(0, 0))
+ }
+}
+
+private object StateReferenceBindingSpec {
+
+ class Predicate {
+ @JsonProperty var attribute: String = _
+ @JsonProperty var value: String = _
+ @JsonProperty var threshold: Double = _
+ @JsonProperty var count: Int = _
+ }
+
+ /** One property of each JSON scalar type, a list of strings and a list of beans. */
+ class Setting extends StateReferencing {
+ @JsonProperty var name: String = _
+ @JsonProperty var limit: Int = _
+ @JsonProperty var ratio: Double = _
+ @JsonProperty var enabled: Boolean = _
+ @JsonProperty var tags: List[String] = List.empty
+ @JsonProperty var predicates: List[Predicate] = List.empty
+ }
+
+ /** Parses its setting in the class body, as operator executors do. Public, for the factory. */
+ class SettingExec(descString: String) extends OperatorExecutor {
+ val setting: Setting = objectMapper.readValue(descString, classOf[Setting])
+ override def processTuple(tuple: Tuple, port: Int): Iterator[TupleLike] = Iterator.single(tuple)
+ }
+}
diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/state/StateReferenceModuleSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/state/StateReferenceModuleSpec.scala
new file mode 100644
index 0000000000..e5ef3fd69e
--- /dev/null
+++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/state/StateReferenceModuleSpec.scala
@@ -0,0 +1,262 @@
+/*
+ * 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.texera.amber.core.state
+
+import com.fasterxml.jackson.annotation.JsonSubTypes.Type
+import com.fasterxml.jackson.annotation.{JsonProperty, JsonSubTypes, JsonTypeInfo}
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize
+import com.fasterxml.jackson.databind.exc.InvalidFormatException
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.module.scala.DefaultScalaModule
+import org.apache.texera.amber.core.state.StateReferencing.{literalReferences, referencedVariable}
+import org.apache.texera.amber.core.tuple.AttributeType
+import org.apache.texera.amber.util.JSONUtils.objectMapper
+import org.scalatest.flatspec.AnyFlatSpec
+
+/**
+ * `StateReferenceModule`, registered on `JSONUtils.objectMapper`: a typed placeholder where a
+ * `$name` reference cannot be converted, and its pointer relative to the object.
+ */
+class StateReferenceModuleSpec extends AnyFlatSpec {
+
+ import StateReferenceModuleSpec._
+
+ private def parse(json: String): Bean = objectMapper.readValue(json, classOf[Bean])
+
+ private def typed(json: String): TypedBean =
+ objectMapper.readValue(json, classOf[Base]).asInstanceOf[TypedBean]
+
+ private val plainMapper: ObjectMapper = new ObjectMapper().registerModule(DefaultScalaModule)
+
+ "StateReferenceModule" should "put 0 / 0.0 / false where a typed property holds '$name', and record its pointer" in {
+ val bean = parse(
+ """{"int":"$a","long":"$b","double":"$c","bool":"$d","boxed":"$e","opt":"$f","float":"$g"}"""
+ )
+ assert(bean.int == 0)
+ assert(bean.long == 0L)
+ assert(bean.double == 0.0)
+ assert(!bean.bool)
+ assert(bean.boxed == Integer.valueOf(0))
+ assert(bean.opt.contains(0))
+ assert(bean.float == 0f)
+ assert(
+ bean.stateReferences == Map(
+ "/int" -> "a",
+ "/long" -> "b",
+ "/double" -> "c",
+ "/bool" -> "d",
+ "/boxed" -> "e",
+ "/opt" -> "f",
+ "/float" -> "g"
+ )
+ )
+ }
+
+ it should "record a reference inside a list of beans under its full pointer" in {
+ val bean = parse(
+ """{"nested":[{"label":"x","threshold":1.5},{"label":"$l","threshold":"$t","count":"$n"}]}"""
+ )
+ assert(bean.nested.map(_.threshold) == List(1.5, 0.0))
+ assert(bean.nested.map(_.count) == List(0, 0))
+ assert(bean.nested(1).label == "$l")
+ assert(bean.stateReferences == Map("/nested/1/threshold" -> "t", "/nested/1/count" -> "n"))
+ }
+
+ it should "keep '$s' in a String property and record nothing: the compiler finds the strings" in {
+ val bean = parse("""{"name":"$s","items":["$t"],"int":"$a"}""")
+ assert(bean.name == "$s")
+ assert(bean.items == List("$t"))
+ assert(bean.stateReferences == Map("/int" -> "a"))
+ }
+
+ it should "leave every value that is not a whole '$name' to Jackson" in {
+ // In a typed property they fail as they always did; so does a reference padded with blanks,
+ // which Jackson trims before converting but which is not a reference as a string either.
+ Seq("$1", "$", "cost is $5", "$a b", " $a", "$a ").foreach { value =>
+ assertThrows[InvalidFormatException](parse(s"""{"int":"$value"}"""))
+ }
+ }
+
+ it should "let '$c' into an enum property fail with Jackson's ordinary error" in {
+ val ex = intercept[InvalidFormatException](parse("""{"color":"$c"}"""))
+ assert(ex.getMessage.contains("not one of the values accepted"))
+ }
+
+ it should "not touch a '$n' outside every StateReferencing object" in {
+ assertThrows[InvalidFormatException](
+ objectMapper.readValue("""{"count":"$n"}""", classOf[Wrapper])
+ )
+ }
+
+ it should "parse a reference-free object exactly as a mapper without the module does" in {
+ Seq(
+ """{"name":"n","int":3,"double":0.5,"bool":true,"items":["a"],"color":"integer"}""",
+ """{"name":1.10,"int":3,"nested":[{"label":"x","threshold":2}],"stateReferences":{}}"""
+ ).foreach { json =>
+ val withModule = parse(json)
+ assert(withModule.stateReferences.isEmpty)
+ assert(
+ objectMapper.writeValueAsString(withModule) ==
+ objectMapper.writeValueAsString(plainMapper.readValue(json, classOf[Bean])),
+ json
+ )
+ }
+ val json = """{"items":["a"],"type":"typed","limit":3,"name":1.10}"""
+ assert(
+ objectMapper.writeValueAsString(typed(json)) ==
+ objectMapper.writeValueAsString(plainMapper.readValue(json, classOf[Base]))
+ )
+ }
+
+ it should "set the sidecar to what the parse recorded, whatever the JSON carried" in {
+ assert(parse("""{"int":0,"stateReferences":{"/int":"a"}}""").stateReferences.isEmpty)
+ assert(
+ parse("""{"int":"$b","stateReferences":{"/int":"a"}}""").stateReferences == Map("/int" -> "b")
+ )
+ }
+
+ // ---------------------------------------------------------------------------
+ // How the object is handed over: the pointer is relative to it every time
+ // ---------------------------------------------------------------------------
+
+ it should "record the same pointers whether the type id comes first, in the middle or last" in {
+ // In the middle, the frontend's order: its properties, then operatorType, then the ports.
+ // Jackson replays the fields before the type id from a buffer, here starting with a list.
+ Seq(
+ """{"type":"typed","items":["$x"],"limit":"$i","ratio":"$r"}""",
+ """{"items":["$x"],"limit":"$i","type":"typed","ratio":"$r"}""",
+ """{"limit":"$i","items":["$x"],"ratio":"$r","type":"typed"}""",
+ """{"items":["$x"],"limit":"$i","ratio":"$r","type":"typed"}"""
+ ).foreach { json =>
+ val bean = typed(json)
+ assert(bean.limit == 0, json)
+ assert(bean.ratio == 0.0, json)
+ assert(bean.items == List("$x"), json)
+ assert(bean.stateReferences == Map("/limit" -> "i", "/ratio" -> "r"), json)
+ }
+ }
+
+ it should "parse an object whose only field is the type id" in {
+ assert(typed("""{"type":"typed"}""").stateReferences.isEmpty)
+ }
+
+ it should "record pointers relative to each operator of a whole plan, even one Jackson buffered" in {
+ // As the websocket request carries a plan: the operators sit at /plan/operators/i, and the
+ // request's own type id comes last, so Jackson replays the whole plan from a buffer.
+ val request = objectMapper.readValue(
+ """{"plan":{"operators":[{"type":"typed","limit":1},
+ |{"items":["a"],"limit":"$i","type":"typed","ratio":"$r"}]},"kind":"envelope"}""".stripMargin,
+ classOf[Request]
+ )
+ val operators = request.asInstanceOf[Envelope].plan.operators.map(_.asInstanceOf[TypedBean])
+ assert(operators.map(_.limit) == List(1, 0))
+ assert(operators.head.stateReferences.isEmpty)
+ assert(operators(1).stateReferences == Map("/limit" -> "i", "/ratio" -> "r"))
+ }
+
+ it should "record a StateReferencing object nested in another in its own sidecar" in {
+ val outer = objectMapper.readValue("""{"inner":{"int":"$b"},"limit":"$c"}""", classOf[Outer])
+ assert(outer.stateReferences == Map("/limit" -> "c"))
+ assert(outer.inner.stateReferences == Map("/int" -> "b"))
+ }
+
+ // ---------------------------------------------------------------------------
+ // The helpers the compiler and the worker share
+ // ---------------------------------------------------------------------------
+
+ "StateReferencing.referencedVariable" should "match only a whole '$name' string" in {
+ assert(referencedVariable("$K").contains("K"))
+ assert(referencedVariable("$_ok").contains("_ok"))
+ assert(referencedVariable("$a1_B2").contains("a1_B2"))
+ Seq("cost is $5", "$1", "a$b", "$", "", "K", "$K ", " $K", "$$K", "$K-1", "$K.x", "$K\n")
+ .foreach(value => assert(referencedVariable(value).isEmpty, s"'$value' is not a reference"))
+ }
+
+ "StateReferencing.literalReferences" should "find every whole-string '$name' outside the sidecar, escaping pointer segments" in {
+ val tree = objectMapper
+ .readTree(
+ """{"name":"$i","limit":0,"tags":["a","$t"],"a/b~c":{"deep":[{"v":"$z"}]},
+ |"note":"cost is $5","stateReferences":{"/name":"$j"}}""".stripMargin
+ )
+ .asInstanceOf[ObjectNode]
+ assert(
+ literalReferences(tree) ==
+ Map("/name" -> "i", "/tags/1" -> "t", "/a~1b~0c/deep/0/v" -> "z")
+ )
+ }
+}
+
+object StateReferenceModuleSpec {
+
+ class Nested {
+ @JsonProperty var label: String = _
+ @JsonProperty var threshold: Double = _
+ @JsonProperty var count: Int = _
+ }
+
+ /** One property of each scalar type, a boxed Integer, an Option, lists and an enum. */
+ class Bean extends StateReferencing {
+ @JsonProperty var name: String = _
+ @JsonProperty var int: Int = _
+ @JsonProperty var long: Long = _
+ @JsonProperty var double: Double = _
+ @JsonProperty var float: Float = _
+ @JsonProperty var bool: Boolean = _
+ @JsonProperty var boxed: java.lang.Integer = _
+ // The Option's value type is erased on the JVM: Jackson needs the hint to see an Int.
+ @JsonProperty
+ @JsonDeserialize(contentAs = classOf[java.lang.Integer])
+ var opt: Option[Int] = None
+ @JsonProperty var items: List[String] = List.empty
+ @JsonProperty var nested: List[Nested] = List.empty
+ @JsonProperty var color: AttributeType = _ // a Java enum
+ }
+
+ /** A StateReferencing object holding another one. */
+ class Outer extends StateReferencing {
+ @JsonProperty var inner: Bean = _
+ @JsonProperty var limit: Int = _
+ }
+
+ /** Not a StateReferencing object. */
+ class Wrapper {
+ @JsonProperty var count: Int = _
+ }
+
+ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
+ @JsonSubTypes(Array(new Type(value = classOf[TypedBean], name = "typed")))
+ abstract class Base extends StateReferencing
+
+ class TypedBean extends Base {
+ @JsonProperty var items: List[String] = List.empty
+ @JsonProperty var limit: Int = _
+ @JsonProperty var ratio: Double = _
+ @JsonProperty var name: String = _
+ }
+
+ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind")
+ @JsonSubTypes(Array(new Type(value = classOf[Envelope], name = "envelope")))
+ trait Request
+
+ case class Plan(operators: List[Base])
+
+ case class Envelope(plan: Plan) extends Request
+}
diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/LogicalOp.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/LogicalOp.scala
index efa4614418..7143e59dc0 100644
--- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/LogicalOp.scala
+++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/LogicalOp.scala
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes.Type
import com.fasterxml.jackson.annotation._
import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
import org.apache.texera.amber.core.executor.OperatorExecutor
+import org.apache.texera.amber.core.state.StateReferencing
import org.apache.texera.amber.core.tuple.Schema
import org.apache.texera.amber.core.virtualidentity.{
ExecutionIdentity,
@@ -431,7 +432,7 @@ trait StateTransferFunc
new Type(value = classOf[SklearnTestingOpDesc], name = "SklearnTesting")
)
)
-abstract class LogicalOp extends PortDescriptor with Serializable {
+abstract class LogicalOp extends PortDescriptor with StateReferencing with Serializable {
@JsonProperty(PropertyNameConstants.OPERATOR_ID)
private var operatorId: String = getClass.getSimpleName + "-" + UUID.randomUUID.toString
diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExec.scala
index 2d4eaf612e..13e62ec780 100644
--- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExec.scala
+++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExec.scala
@@ -55,8 +55,9 @@ class DictionaryMatcherOpExec(descString: String) extends MapOpExec {
/**
* first prepare the dictionary by splitting the values using a comma delimiter then tokenize the split values
+ * at the first tuple: inside a loop block the loop state may write the dictionary after open()
*/
- override def open(): Unit = {
+ private def prepareDictionary(): Unit = {
// create the dictionary by splitting the values first
dictionaryEntries = desc.dictionary.split(",").toList.map(_.toLowerCase)
if (desc.matchingType == MatchingType.CONJUNCTION_INDEXBASED) {
@@ -149,6 +150,7 @@ class DictionaryMatcherOpExec(descString: String) extends MapOpExec {
* @return A TupleLike object containing the original fields of the tuple and a boolean indicating the match status.
*/
private def labelTupleIfMatched(tuple: Tuple): TupleLike = {
+ if (dictionaryEntries == null) prepareDictionary()
val isMatched =
Option(tuple.getField[Any](desc.attribute)).exists(_ => isTupleInDictionary(tuple))
TupleLike(tuple.getFields ++ Seq(isMatched))
diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/metadata/OperatorMetadataGenerator.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/metadata/OperatorMetadataGenerator.scala
index 3086ad851c..fb649cbf0b 100644
--- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/metadata/OperatorMetadataGenerator.scala
+++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/metadata/OperatorMetadataGenerator.scala
@@ -25,6 +25,7 @@ import com.fasterxml.jackson.databind.jsontype.NamedType
import com.fasterxml.jackson.databind.node.{ArrayNode, ObjectNode}
import com.kjetland.jackson.jsonSchema.JsonSchemaConfig.html5EnabledSchema
import com.kjetland.jackson.jsonSchema.{JsonSchemaConfig, JsonSchemaDraft, JsonSchemaGenerator}
+import org.apache.texera.amber.core.state.StateReferencing
import org.apache.texera.amber.core.workflow.OutputPort.OutputMode
import org.apache.texera.amber.core.workflow.{InputPort, OutputPort}
import org.apache.texera.amber.operator.LogicalOp
@@ -126,6 +127,8 @@ object OperatorMetadataGenerator {
jsonSchema.get("properties").asInstanceOf[ObjectNode].remove("operatorType")
// remove operatorVersion from json schema
jsonSchema.get("properties").asInstanceOf[ObjectNode].remove("operatorVersion")
+ // remove the loop-variable sidecar (StateReferencing.stateReferences): the backend fills it in
+ jsonSchema.get("properties").asInstanceOf[ObjectNode].remove(StateReferencing.SIDECAR_PROPERTY)
// remove inputPorts/outputPorts from json schema
jsonSchema.get("properties").asInstanceOf[ObjectNode].remove("inputPorts")
jsonSchema.get("properties").asInstanceOf[ObjectNode].remove("outputPorts")
diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/reservoirsampling/ReservoirSamplingOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/reservoirsampling/ReservoirSamplingOpExec.scala
index 3ec8d017c8..4c802bdb9f 100644
--- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/reservoirsampling/ReservoirSamplingOpExec.scala
+++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/reservoirsampling/ReservoirSamplingOpExec.scala
@@ -30,14 +30,14 @@ class ReservoirSamplingOpExec(descString: String, idx: Int, workerCount: Int)
extends OperatorExecutor {
private val desc: ReservoirSamplingOpDesc =
objectMapper.readValue(descString, classOf[ReservoirSamplingOpDesc])
- private val count: Int = equallyPartitionGoal(desc.k, workerCount)(idx)
+ // Read at first use: inside a loop block `k` may be written into the setting after open().
+ private lazy val count: Int = equallyPartitionGoal(desc.k, workerCount)(idx)
private var n: Int = _
private var reservoir: Array[Tuple] = _
private val rand: Random = new Random(workerCount)
override def open(): Unit = {
n = 0
- reservoir = Array.ofDim(count)
}
override def close(): Unit = {
@@ -45,7 +45,7 @@ class ReservoirSamplingOpExec(descString: String, idx: Int, workerCount: Int)
}
override def processTuple(tuple: Tuple, port: Int): Iterator[TupleLike] = {
-
+ if (reservoir == null) reservoir = Array.ofDim(count)
if (n < count) {
reservoir(n) = tuple
} else {
@@ -60,6 +60,9 @@ class ReservoirSamplingOpExec(descString: String, idx: Int, workerCount: Int)
// Only the first n slots are filled when the input is smaller than the reservoir;
// take(n) keeps the trailing unfilled (null) slots from being emitted.
- override def onFinish(port: Int): Iterator[TupleLike] = reservoir.iterator.take(n)
+ override def onFinish(port: Int): Iterator[TupleLike] = {
+ if (reservoir == null) reservoir = Array.ofDim(count)
+ reservoir.iterator.take(n)
+ }
}
diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/split/SplitOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/split/SplitOpExec.scala
index 3d3e869091..ed30c0c353 100644
--- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/split/SplitOpExec.scala
+++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/split/SplitOpExec.scala
@@ -32,8 +32,10 @@ class SplitOpExec(
val desc: SplitOpDesc = objectMapper.readValue(descString, classOf[SplitOpDesc])
var random: Random = _
+ // Seeded at the first tuple, not in open(): inside a loop block the seed may refer to a loop
+ // variable, which the loop state writes into the setting after open(). Reopening reseeds.
override def open(): Unit = {
- random = if (desc.random) new Random() else new Random(desc.seed)
+ random = null
}
override def close(): Unit = {
@@ -44,6 +46,7 @@ class SplitOpExec(
tuple: Tuple,
port: Int
): Iterator[(TupleLike, Option[PortIdentity])] = {
+ if (random == null) random = if (desc.random) new Random() else new Random(desc.seed)
val isTraining = random.nextInt(100) < desc.k
// training output port: 0, testing output port: 1
val port = if (isTraining) PortIdentity(0) else PortIdentity(1)
diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExecSpec.scala
index 8f71c54a36..9eb2cdf627 100644
--- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExecSpec.scala
+++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExecSpec.scala
@@ -56,10 +56,12 @@ class DictionaryMatcherOpExecSpec extends AnyFlatSpec with BeforeAndAfter {
outputSchema = opDesc.getExternalOutputSchemas(Map(PortIdentity() -> tupleSchema)).values.head
}
- it should "open" in {
+ it should "prepare the dictionary at the first tuple, not at open()" in {
opExec = new DictionaryMatcherOpExec(objectMapper.writeValueAsString(opDesc))
opExec.open()
- assert(opExec.dictionaryEntries != null)
+ assert(opExec.dictionaryEntries == null)
+ opExec.processTuple(tuple, 0).next()
+ assert(opExec.dictionaryEntries == List(dictionaryScan))
}
/**
@@ -319,6 +321,7 @@ class DictionaryMatcherOpExecSpec extends AnyFlatSpec with BeforeAndAfter {
opDesc.matchingType = MatchingType.CONJUNCTION_INDEXBASED
opExec = new DictionaryMatcherOpExec(objectMapper.writeValueAsString(opDesc))
opExec.open()
+ opExec.processTuple(tuple, 0).next()
assert(opExec.tokenizedDictionaryEntries.nonEmpty)
opExec.close()
// Asserts emptiness only, never null: close() nulls the other two fields but
diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/metadata/OperatorMetadataGeneratorSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/metadata/OperatorMetadataGeneratorSpec.scala
index 1bf38af6a4..2a370c5fc2 100644
--- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/metadata/OperatorMetadataGeneratorSpec.scala
+++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/metadata/OperatorMetadataGeneratorSpec.scala
@@ -19,10 +19,14 @@
package org.apache.texera.amber.operator.metadata
+import org.apache.texera.amber.core.state.StateReferencing
import org.apache.texera.amber.operator.LogicalOp
+import org.apache.texera.amber.operator.filter.SpecializedFilterOpDesc
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
+import scala.jdk.CollectionConverters.IteratorHasAsScala
+
class OperatorMetadataGeneratorSpec extends AnyFlatSpec with Matchers {
"OperatorMetadataGenerator.generateOperatorMetadata" should
@@ -37,4 +41,15 @@ class OperatorMetadataGeneratorSpec extends AnyFlatSpec with Matchers {
ex.getMessage should include(classOf[LogicalOp].toString)
ex.getMessage should include("is not registered")
}
+
+ "OperatorMetadataGenerator.generateOperatorJsonSchema" should
+ "hide the loop-variable sidecar from the property panel" in {
+ val schema =
+ OperatorMetadataGenerator.generateOperatorJsonSchema(classOf[SpecializedFilterOpDesc])
+ val properties = schema.get("properties")
+ properties.has("predicates") shouldBe true
+ properties.has(StateReferencing.SIDECAR_PROPERTY) shouldBe false
+ val required = schema.get("required").elements().asScala.map(_.asText()).toList
+ required should not contain StateReferencing.SIDECAR_PROPERTY
+ }
}
diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/reservoirsampling/ReservoirSamplingOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/reservoirsampling/ReservoirSamplingOpExecSpec.scala
index a4cb103ea7..d6a9bcd8d5 100644
--- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/reservoirsampling/ReservoirSamplingOpExecSpec.scala
+++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/reservoirsampling/ReservoirSamplingOpExecSpec.scala
@@ -20,6 +20,8 @@
package org.apache.texera.amber.operator.reservoirsampling
import com.fasterxml.jackson.databind.node.ObjectNode
+import org.apache.texera.amber.core.executor.ExecFactory
+import org.apache.texera.amber.core.state.{State, StateReferencing}
import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple}
import org.apache.texera.amber.util.JSONUtils.objectMapper
import org.scalatest.flatspec.AnyFlatSpec
@@ -62,18 +64,29 @@ class ReservoirSamplingOpExecSpec extends AnyFlatSpec {
}
// `k` is renamed by @JsonProperty, so resolve the JSON key from the annotation
- // rather than hard-coding it, then overwrite that slot with null on a real desc.
+ // rather than hard-coding it.
+ private val keyForK: String =
+ classOf[ReservoirSamplingOpDesc]
+ .getDeclaredField("k")
+ .getAnnotation(classOf[com.fasterxml.jackson.annotation.JsonProperty])
+ .value()
+
+ // Overwrite the `k` slot with null on a real desc.
private def descWithNullK: String = {
val node = objectMapper.valueToTree[ObjectNode](new ReservoirSamplingOpDesc())
- val keyForK =
- classOf[ReservoirSamplingOpDesc]
- .getDeclaredField("k")
- .getAnnotation(classOf[com.fasterxml.jackson.annotation.JsonProperty])
- .value()
node.putNull(keyForK)
objectMapper.writeValueAsString(node)
}
+ // As the compiler hands the descriptor over inside a loop block when `k` holds "$k": the
+ // placeholder 0, and the sidecar naming the loop variable.
+ private def descWithReferencedK: String = {
+ val node = objectMapper.valueToTree[ObjectNode](new ReservoirSamplingOpDesc())
+ node.put(keyForK, 0)
+ node.putObject(StateReferencing.SIDECAR_PROPERTY).put("/" + keyForK, "k")
+ objectMapper.writeValueAsString(node)
+ }
+
private def newExec(k: Int, idx: Int = 0, workerCount: Int = 1): ReservoirSamplingOpExec = {
val exec = new ReservoirSamplingOpExec(desc(k), idx, workerCount)
exec.open()
@@ -182,10 +195,33 @@ class ReservoirSamplingOpExecSpec extends AnyFlatSpec {
assert(emitted.distinct.size == emitted.size, "each input tuple is sampled at most once")
}
- "ReservoirSamplingOpExec with a bad k" should "reject a negative k with a negative-sized reservoir" in {
- // equallyPartitionGoal(-1, 1) -> count = -1, so open() allocates Array.ofDim(-1).
+ "ReservoirSamplingOpExec inside a loop block" should
+ "size its reservoir from the k written into its setting after construction and open()" in {
+ val exec = ExecFactory
+ .newExecFromJavaClassName(
+ classOf[ReservoirSamplingOpExec].getName,
+ descWithReferencedK,
+ idx = 0,
+ workerCount = 3
+ )
+ .asInstanceOf[ReservoirSamplingOpExec]
+ exec.open()
+ exec.registerState(State(Map("k" -> 10L)))
+ exec.bindStateReferences()
+ // Worker 0 of 3 keeps 4 of k = 10; the placeholder 0 would keep none.
+ val emitted = runFinish(exec, 0 until 50)
+ assert(emitted.size == 4)
+ assert(emitted.forall((0 until 50).map(tuple).toSet.contains))
+ }
+
+ "ReservoirSamplingOpExec with a bad k" should "reject a negative k with a negative-sized reservoir, at the first tuple or at finish" in {
+ // equallyPartitionGoal(-1, 1) -> count = -1, so the reservoir is Array.ofDim(-1). It is
+ // allocated at first use, when a k that refers to a loop variable has been written in.
+ assertThrows[NegativeArraySizeException] {
+ newExec(k = -1).processTuple(tuple(0), 0)
+ }
assertThrows[NegativeArraySizeException] {
- newExec(k = -1)
+ newExec(k = -1).onFinish(0)
}
}
diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/split/SplitOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/split/SplitOpExecSpec.scala
index b14021b237..ba07aa092d 100644
--- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/split/SplitOpExecSpec.scala
+++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/split/SplitOpExecSpec.scala
@@ -19,6 +19,9 @@
package org.apache.texera.amber.operator.split
+import com.fasterxml.jackson.databind.node.ObjectNode
+import org.apache.texera.amber.core.executor.ExecFactory
+import org.apache.texera.amber.core.state.{State, StateReferencing}
import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple}
import org.apache.texera.amber.core.workflow.PortIdentity
import org.apache.texera.amber.util.JSONUtils.objectMapper
@@ -43,6 +46,13 @@ class SplitOpExecSpec extends AnyFlatSpec {
objectMapper.writeValueAsString(d)
}
+ /** As the compiler hands `descJson` over inside a loop block, `pointer` referring to `name`. */
+ private def referencing(desc: String, pointer: String, name: String): String = {
+ val node = objectMapper.readTree(desc).asInstanceOf[ObjectNode]
+ node.putObject(StateReferencing.SIDECAR_PROPERTY).put(pointer, name)
+ objectMapper.writeValueAsString(node)
+ }
+
private def emittedPorts(
exec: SplitOpExec,
count: Int
@@ -119,11 +129,50 @@ class SplitOpExecSpec extends AnyFlatSpec {
"SplitOpExec.close" should "clear the random reference (null-out)" in {
val exec = new SplitOpExec(descJson(k = 50, seed = 1))
exec.open()
+ emittedPorts(exec, 1)
assert(exec.random != null)
exec.close()
assert(exec.random == null)
}
+ "SplitOpExec.open" should "reseed, so a reopened executor repeats its sequence" in {
+ val exec = new SplitOpExec(descJson(k = 50, seed = 7))
+ exec.open()
+ val first = emittedPorts(exec, 100)
+ exec.open()
+ assert(emittedPorts(exec, 100) == first)
+ exec.close()
+ }
+
+ // ---------------------------------------------------------------------------
+ // Inside a loop block: the setting is written after open()
+ // ---------------------------------------------------------------------------
+
+ "SplitOpExec inside a loop block" should
+ "seed its random from the seed written into its setting after construction and open()" in {
+ def plain(seed: Int): IndexedSeq[Option[PortIdentity]] = {
+ val exec = new SplitOpExec(descJson(k = 50, seed = seed))
+ exec.open()
+ try emittedPorts(exec, 200)
+ finally exec.close()
+ }
+ val exec = ExecFactory
+ .newExecFromJavaClassName(
+ classOf[SplitOpExec].getName,
+ referencing(descJson(k = 50, seed = 0), "/seed", "s")
+ )
+ .asInstanceOf[SplitOpExec]
+ exec.open()
+ exec.registerState(State(Map("s" -> 7L)))
+ exec.bindStateReferences()
+ try {
+ val ports = emittedPorts(exec, 200)
+ // The seed written in, not the placeholder 0 it held at open().
+ assert(ports == plain(7))
+ assert(ports != plain(0))
+ } finally exec.close()
+ }
+
// ---------------------------------------------------------------------------
// processTuple (single-port overload) — unsupported
// ---------------------------------------------------------------------------
diff --git a/workflow-compiling-service/src/main/scala/org/apache/texera/service/WorkflowCompilingService.scala b/workflow-compiling-service/src/main/scala/org/apache/texera/service/WorkflowCompilingService.scala
index 46649647a0..71aff7800d 100644
--- a/workflow-compiling-service/src/main/scala/org/apache/texera/service/WorkflowCompilingService.scala
+++ b/workflow-compiling-service/src/main/scala/org/apache/texera/service/WorkflowCompilingService.scala
@@ -19,12 +19,11 @@
package org.apache.texera.service
-import com.fasterxml.jackson.module.scala.DefaultScalaModule
import io.dropwizard.configuration.{EnvironmentVariableSubstitutor, SubstitutingSourceProvider}
import io.dropwizard.core.Application
import io.dropwizard.core.setup.{Bootstrap, Environment}
import org.apache.texera.common.config.StorageConfig
-import org.apache.texera.amber.util.ObjectMapperUtils
+import org.apache.texera.amber.util.{JSONUtils, ObjectMapperUtils}
import org.apache.texera.auth.{AuthFeatures, RoleAnnotationEnforcer}
import org.apache.texera.dao.SqlServer
import org.apache.texera.service.resource.{
@@ -45,8 +44,7 @@ class WorkflowCompilingService extends Application[WorkflowCompilingServiceConfi
new EnvironmentVariableSubstitutor(false)
)
)
- // register scala module to dropwizard default object mapper
- bootstrap.getObjectMapper.registerModule(DefaultScalaModule)
+ JSONUtils.registerWorkflowModules(bootstrap.getObjectMapper)
}
override def run(
diff --git a/workflow-compiling-service/src/test/scala/org/apache/texera/service/WorkflowCompilingServiceRunSpec.scala b/workflow-compiling-service/src/test/scala/org/apache/texera/service/WorkflowCompilingServiceRunSpec.scala
index 840685ba16..26234222a9 100644
--- a/workflow-compiling-service/src/test/scala/org/apache/texera/service/WorkflowCompilingServiceRunSpec.scala
+++ b/workflow-compiling-service/src/test/scala/org/apache/texera/service/WorkflowCompilingServiceRunSpec.scala
@@ -30,6 +30,7 @@ import io.dropwizard.jetty.MutableServletContextHandler
import io.dropwizard.jetty.setup.ServletEnvironment
import jakarta.servlet.{DispatcherType, Filter, FilterChain}
import jakarta.servlet.http.{HttpServletRequest, HttpServletResponse}
+import org.apache.texera.amber.operator.LogicalOp
import org.apache.texera.auth.{RoleAnnotationEnforcer, UnauthorizedExceptionMapper}
import org.apache.texera.service.WorkflowCompilingServiceRunSpec.SpecPayload
import org.apache.texera.service.resource.{
@@ -255,7 +256,7 @@ class WorkflowCompilingServiceRunSpec extends AnyFlatSpec with Matchers {
resolve(unsetConfigPath) shouldBe "unset: ${TEXERA_WORKFLOW_COMPILING_SERVICE_SPEC_UNSET}\n"
}
- it should "register the Scala module on Dropwizard's object mapper" in {
+ it should "register the Scala and loop-variable modules on Dropwizard's object mapper" in {
val mapper = initializedBootstrap().getObjectMapper
// The whole module, not only the Option support that `Some("x")` alone would prove: this is
// the mapper Dropwizard hands to Jersey, so every payload the API returns goes through it —
@@ -271,6 +272,10 @@ class WorkflowCompilingServiceRunSpec extends AnyFlatSpec with Matchers {
json shouldBe """{"operatorId":"op-1","outputSchemas":{"port0":[1,2],"port1":null}}"""
// Reading, too: this is also the mapper Dropwizard parses the YAML configuration with.
mapper.readValue(json, classOf[SpecPayload]) shouldBe payload
+ // Jersey parses the editor's POST /compile body, a typed '$n' included, with this mapper.
+ mapper
+ .readValue("""{"limit":"$n","operatorType":"Limit"}""", classOf[LogicalOp])
+ .stateReferences shouldBe Map("/limit" -> "n")
}
}