Xiao-zhen-Liu commented on code in PR #8773: URL: https://github.com/apache/texera/pull/8773#discussion_r4485639348
########## docs/tutorials/computing-units.md: ########## @@ -0,0 +1,67 @@ +<!-- + ~ 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. +--> + +--- +title: "Computing Units" +weight: 15 +--- + +A **computing unit** is the machine that runs your workflows. You pick one in the workflow editor's top bar before clicking **Run** ([how](../guide-for-how-to-use-texera/#run-a-workflow)). You can see all of yours under **Your Work → Compute**. + +## Create one + +Click **+ Computing Unit** in the top bar, or **Create Computing Unit** on the Compute page. What you see depends on how your Texera is set up: + +- **Create Computing Unit** (hosted Texera): Texera starts a new machine for you. Choose: + + | Field | What to pick | + |---|---| + | **Select RAM Size** | Memory. Start with the smallest; pick more if a run fails on large data. | + | **Select #CPU Core(s)** | More cores help only when operators run with several workers. | + | **Select #GPU(s)** | Only for deep learning in Python. Shown only if GPUs are available. | + | **Image** | The software installed on the unit. Keep **Default** unless told otherwise. Fixed for the unit's lifetime. | + | **Advanced Settings** | Shared memory (raise it for PyTorch) and JVM heap. Leave the defaults unless an admin tells you otherwise. | + +- **Connect to a Local Computing Unit** (Texera on your own computer): enter a name and keep the suggested address. + +A new unit shows a gold dot while it starts. You can select it once the dot turns green. + +## Status dots + +| Dot | Meaning | +|---|---| +| Green | Running: ready to use | +| Gold | Starting up, or shutting down | +| Red | Unavailable. Pick or create another unit | + +## Tips + +- **Reuse one unit** for all your workflows. You don't need one per workflow. +- **A new unit usually won't fix an error in your workflow**, such as a mistake in Python code or an operator setting. Read the error first ([where to find errors](../guide-for-how-to-use-texera/#where-to-find-errors)). A different unit *can* help when the problem is the unit itself: not enough memory, CPU or GPU, or a missing Python package or software image. +- **Terminating a unit stops it. It doesn't delete anything.** Your workflows, datasets and saved results stay in storage. Results are shown per unit, though, so to see them on another unit, run the workflow again there. Review Comment: The Terminate Computing Unit dialog warns in red: "All execution results in this computing unit will be lost." This line says the opposite, so a reader gets two answers. Either way they can't open those results again, since a terminated unit leaves the list. Please match the dialog, e.g. "Terminating a unit stops it. Your workflows and datasets are kept; the results of runs on it are lost." If the dialog is wrong, that needs a code fix instead. ########## docs/tutorials/guide-to-use-python-udf/index.md: ########## @@ -0,0 +1,212 @@ +<!-- + ~ 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. +--> + +--- +title: "Guide to Use a Python UDF" +weight: 30 +--- + +A **Python UDF** (user-defined function) is an operator that runs a small piece of Python code you write. Use it when no built-in operator does what you need. + +You don't need to be a programmer. Copy the example below and change one line at a time. + +## Which Python operator should I use? + +| You want to… | Use | +|---|---| +| Add or change a column with a one-line formula, e.g. `tuple_["Units Sold"] * 2` | **Python Lambda Function** (no class to write) | +| Turn a whole table into one summary row, e.g. `table["Units Sold"].mean()` | **Python Table Reducer** (no class to write) | +| Anything else with one or more inputs | **Python UDF** | +| Apply a model (input 0) to data rows (input 1) | **2-in Python UDF** | +| Create data from nothing (no input) | **1-out Python UDF** | + +## Your first UDF in 4 steps + +This example adds a `Revenue` column (units × price) to the sales data from [the dataset tutorial](../create-dataset-upload-data/). + +**1. Add the operator.** Drag **Python UDF** (under *User-defined Functions → Python*) onto the canvas and connect your data to it. + +**2. Write the code.** Click **Edit code content**. The editor opens with a template. Its classes are commented out (their lines start with `#`), so running it unchanged fails. Uncomment one class, or replace everything with: + +```python +from pytexera import * + + +class ProcessTupleOperator(UDFOperatorV2): + + @overrides + def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + tuple_["Revenue"] = tuple_["Units Sold"] * tuple_["Unit Price"] + yield tuple_ +``` + + + +**3. Declare the new column.** In the property panel, under **Extra output column(s)**, click **+** and add `Revenue` with type `double`. Leave **Retain input columns** checked to keep the original columns. + +<img src="udf-output-columns.png" alt="Retain input columns and one extra output column named Revenue" width="260"> + +**4. Run.** Click the eye icon on the UDF, then **Run**. Click the UDF, then the **Result** tab in the result panel. + +## The 5 rules + +Almost every UDF problem comes from breaking one of these. + +| # | Rule | If you break it | +|---|---|---| +| 1 | `from pytexera import *` is at the top (the template already has it) | `name 'UDFOperatorV2' is not defined` | +| 2 | Exactly **one** class. Delete or comment out the others. | `There should be one and only one Operator defined` | +| 3 | The method name must match the class you inherit from (table below) | `... does not implement process_tuple` or `... No super class method found` | +| 4 | Send results with `yield`, never `return` a value | ``process_tuple must `yield` results, not `return` them`` | +| 5 | The columns you yield must match the output columns (step 3) | `expected but missing` or `unexpected field` | + +## How your code receives data + +Pick one row of this table. The class name in brackets and the method name must go together. + +| Class `(…)` | Method you write | You receive | Good for | +|---|---|---|---| +| `UDFOperatorV2` | `process_tuple(self, tuple_, port)` | one row at a time (use it like a dict: `tuple_["col"]`) | per-row formulas, filtering | +| `UDFBatchOperator` | `process_batch(self, batch, port)` | `BATCH_SIZE` rows at a time, as a pandas DataFrame | calling an API in chunks | +| `UDFTableOperator` | `process_table(self, table, port)` | **all** rows of one input, as a pandas DataFrame | sorting, statistics, ML training | +| `UDFSourceOperator` (1-out UDF only) | `produce(self)` | nothing; you create the data | generating or downloading data | + +What you can `yield`: + +- **A row**: a `Tuple` or a `dict`, e.g. `yield {"name": "a", "value": 1}`. +- **A table**: a pandas `DataFrame` or `Table`. Yield the DataFrame itself, not a dict that contains DataFrames. +- **`None`**: produce nothing for this input. + +To drop a row, just don't `yield` it. To output several rows, `yield` several times. + +## One-time setup (loading a model, opening a file) + +Put setup code in `open()`, which runs once before any data arrives: + +```python +from pytexera import * + + +class ProcessTupleOperator(UDFOperatorV2): + + @overrides + def open(self): + self.threshold = 100 + + @overrides + def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + if tuple_["Units Sold"] > self.threshold: + yield tuple_ +``` + +If you write `__init__` instead, make its first line `super().__init__()`. Older Texera versions fail without it (see the table below). + +To set values like `threshold` from the property panel instead of in code, see [UI parameters](/docs/reference/operators/user-defined-functions/python/#ui-parameters). + +## Output columns + +The UDF's output columns are **Retain input columns** (the input's columns, if checked) plus **Extra output column(s)**. Every row you `yield` must contain exactly these columns. + +- Adding a column? Add it under **Extra output column(s)**. +- Returning a completely new table (e.g. a summary)? Uncheck **Retain input columns** and list every output column. +- With several inputs, **Retain input columns** keeps the columns of input 0 (for the 2-in UDF: the `tuples` input, port 1). + +## Several inputs + +Add input ports with the **+** under the operator's left side. Ports are numbered from 0. Your method's `port` argument tells you which input a row came from. + +- **Inputs arrive in no fixed order.** Don't assume input 0 finishes before input 1. +- To combine inputs safely, use `UDFTableOperator`. It calls `process_table` once per input, when that input is complete. Keep each table and act when you have all of them: + +```python +from pytexera import * + +NUM_INPUTS = 2 + + +class ProcessTableOperator(UDFTableOperator): + + @overrides + def open(self): + self.tables = {} + + @overrides + def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: + self.tables[port] = table + if len(self.tables) == NUM_INPUTS: + yield self.tables[0].merge(self.tables[1], on="Country") +``` + +- To force an order, click an input port's dot. Under **dependencies**, list the ports that must finish first. For example, port 1 with dependencies `0` waits for port 0. +- The **2-in Python UDF** has this built in: port 0 (`model`) is read completely before port 1 (`tuples`) starts. + +```python +from pytexera import * + + +class ProcessTupleOperator(UDFOperatorV2): + + @overrides + def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + if port == 0: # model input: remember the model + self.model = tuple_["model"] + else: # tuples input: use it + tuple_["pred"] = self.model.predict([tuple_["text"]])[0] + yield tuple_ +``` + +## Creating data (1-out Python UDF) + +```python +from pytexera import * + + +class GenerateOperator(UDFSourceOperator): + + @overrides + def produce(self) -> Iterator[Union[TupleLike, TableLike, None]]: + for i in range(10): + yield {"number": i} +``` + +List every column (here `number`, type `integer`) under **Columns** in the property panel. More examples: [pytexera examples](https://github.com/apache/texera/tree/main/amber/src/main/python/pytexera/udf/examples). + +## Finding and fixing errors + +- `print(...)` in your code shows up in the **Console** tab. Click the UDF to see it. +- If a row fails, the UDF turns **magenta** (paused) and the error appears in its **Console**. Fix the code, then stop the run (red ⊗ next to *Pause*) and run again. + + + +- If the code can't even load (missing import, wrong class), the error appears in **Static Error**. Click the UDF, or an empty spot on the canvas, to see it. The message includes the error type and your line number, e.g. `(NameError at line 2 of the UDF code)`. See [where to find errors](../guide-for-how-to-use-texera/#where-to-find-errors). + +| Error message contains | Cause | Fix | +|---|---|---| +| `name 'UDFOperatorV2' is not defined` (or `Tuple`, `Table`, …) | Missing import | Add `from pytexera import *` at the top | +| `There should be one and only one Operator defined` | No class, or more than one. The rest of the message names the classes. | Keep exactly one class, uncommented | +| `X subclasses UDFOperatorV2 but does not implement process_tuple` | The method doesn't match the class (e.g. `process_table` in a `UDFOperatorV2`) | Rename the method, or subclass the base the message suggests | +| `X does not subclass a pytexera base class` | The class has no pytexera base | Subclass one, e.g. `class ProcessTupleOperator(UDFOperatorV2):` (`UDFSourceOperator` for a 1-out UDF) | +| `No super class method found` | A method marked `@overrides` doesn't exist in the base class | Use the pair from [the table](#how-your-code-receives-data), or remove `@overrides` from a helper method | +| ``must `yield` results, not `return` them`` (older versions: `MatchError: '_' not provided` or `'NoneType' object is not iterable`) | `return` used instead of `yield` | Replace `return x` with `yield x` | +| `_TableOperator__table_data` (older versions) | `__init__` without `super().__init__()` | Add `super().__init__()`, or use `open()` | +| `A DataFrame was put in column 'X'` | A DataFrame is in a column whose type isn't binary | To output its rows, `yield` the DataFrame itself; to keep it as one value, make the column binary | +| `expected but missing in the Tuple` | A declared output column is missing from what you yield | Yield that column, or remove it from **Extra output column(s)** (**Columns** for a 1-out UDF) | +| `contains unexpected field` | You yield a column that isn't declared | Add it under **Extra output column(s)** (**Columns** for a 1-out UDF), or stop yielding it | Review Comment: No message contains this exact text. When you yield one column that isn't declared, it says "contains an unexpected field"; with several, "contains unexpected fields" (two spaces). A reader who searches the page for their error won't find this row. Please quote `unexpected field`, as rule 5 does. ########## docs/tutorials/guide-for-how-to-use-texera/index.md: ########## @@ -0,0 +1,120 @@ +<!-- + ~ 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. +--> + +--- +title: "Guide for how to use Texera" +weight: 10 +--- + +Texera lets you analyze data by connecting boxes (**operators**) on a canvas instead of writing a program. Each box does one step, like "read a file", "keep rows where…", or "compute an average". The arrows carry data from one box to the next. + +## Sign in + +Open the Texera address you were given in your browser and sign in. + +On a Texera you installed yourself ([Docker guide](/docs/getting-started/installing-using-docker/)), the built-in admin account is username `texera`, password `texera`. + + + +## The dashboard + +After signing in you see the dashboard. The left menu has: + +- **Hub**: workflows and datasets other people have made public. +- **Your Work** + - **Workflows**: your workflows. Click **Create Workflow** to start one. + - **Datasets**: your data files ([how to upload](../create-dataset-upload-data/)). + - **Compute**: your computing units (see [below](#run-a-workflow)). + - **Warehouses** (on some setups): where your run results are stored. + - **Environments**: extra Python packages for Python operators. + - **Quota**: how much storage and compute you have used. +- **Admin**: users, executions and site settings. Admins only. + +## The workflow editor + + + +1. **Operators**: all available boxes, grouped by type. If the panel is closed, click the grid icon at the top left of the canvas. Drag a box onto the canvas, or type its name in the search box. Boxes added through search land on top of each other; drag them apart. +2. **Canvas**: connect the output dot on the right of one box to the input dot on the left of the next. +3. **Property panel**: click a box to set its options. A red outline means an option is missing or wrong. +4. **Result panel**: shows a box's output, printed messages and errors. If it's closed, open it with the square icon at the bottom left. + +## Run a workflow + +A **computing unit** is the machine that runs your workflow. Pick one in the top bar, then click **Run**. If the list is empty, click **+ Computing Unit** to create one. + + + +Some Texera setups also need a **warehouse**, the place your run's results are stored. Pick one from the **Warehouse** menu next to the computing unit. If the Run button says **+ Warehouse** instead, click it to create one. The name can use letters, digits, `-` and `_`. + +- One computing unit can run all your workflows. Reuse it. +- A new unit usually won't fix an error in the workflow itself (code or settings). It can help when the run needs more memory, CPU or GPU, or different Python packages. +- Stopping (terminating) a unit stops its machine. Your workflows and datasets are kept. To see results on another unit, run the workflow again there. + +More in [Computing Units](../computing-units/). + +## Read a running workflow + +Each box's outline color shows its state. The number on each side is how many rows went in (left) and came out (right). + + + +| Color | Meaning | +|---|---| +| Gray | Not started yet | +| Yellow-green | Ready to start | +| Orange | Running | +| Magenta | Paused. You paused it, or a row caused an error | +| Green | Finished | + +Some operators (e.g. Sort, Aggregate, and the build side of Join) must read **all** their input before they output anything. They show 0 rows out until the operator before them finishes. That's normal. See [How Texera runs your workflow](/docs/concepts/how-texera-runs-your-workflow/). + +## See the results + +1. Before running, click the box and turn on its **eye icon** (top toolbar). Texera shows results only for boxes with the eye on. +2. After the run, click the box and open the result panel (square icon, bottom left) if it's closed. The **Result** tab shows its rows. + +The result panel only shows the box you clicked. If it says *No operator is selected*, click a box. If it says *This operator has no results yet*, turn on that box's eye icon and run again. + +## Where to find errors + +- **Click the box that failed, or an empty spot on the canvas.** If the run failed, the result panel shows a **Static Error** tab with the error, including code that failed to start. With nothing selected it lists every operator's errors. A run that stops right away with every box at 0 rows usually means this. + + + +- **Click the box** to see its **Console**: messages from `print(...)` and errors on a specific row. + +Python error messages are explained in the [Python UDF guide](../guide-to-use-python-udf/#finding-and-fixing-errors). + +## Pause and stop + +While a workflow runs, **Run** becomes **Pause**. **Pause** can be resumed. The red ⊗ button to its left **stops** the run for good. Stop a run before fixing and re-running it. + + + +## My workflow looks stuck + +The run button says *Submitting* or *Pause*, the timer keeps counting, and every box stays at 0 rows. Check these in order: + +1. **Click the failed box, or an empty spot on the canvas,** and look at **Static Error**. Setup errors (for example in Python code) show up there. Review Comment: If I read #8668 right, code that fails while starting has ended the run since that PR: the button goes back to Run and Static Error shows the error, as your screenshot above does. While the button still says Submitting or Pause, the run hasn't failed, so Static Error doesn't appear. Please drop this step; line 97 already covers the failed run. ########## docs/tutorials/guide-to-use-python-udf/index.md: ########## @@ -0,0 +1,212 @@ +<!-- + ~ 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. +--> + +--- +title: "Guide to Use a Python UDF" +weight: 30 +--- + +A **Python UDF** (user-defined function) is an operator that runs a small piece of Python code you write. Use it when no built-in operator does what you need. + +You don't need to be a programmer. Copy the example below and change one line at a time. + +## Which Python operator should I use? + +| You want to… | Use | +|---|---| +| Add or change a column with a one-line formula, e.g. `tuple_["Units Sold"] * 2` | **Python Lambda Function** (no class to write) | +| Turn a whole table into one summary row, e.g. `table["Units Sold"].mean()` | **Python Table Reducer** (no class to write) | +| Anything else with one or more inputs | **Python UDF** | +| Apply a model (input 0) to data rows (input 1) | **2-in Python UDF** | +| Create data from nothing (no input) | **1-out Python UDF** | + +## Your first UDF in 4 steps + +This example adds a `Revenue` column (units × price) to the sales data from [the dataset tutorial](../create-dataset-upload-data/). + +**1. Add the operator.** Drag **Python UDF** (under *User-defined Functions → Python*) onto the canvas and connect your data to it. + +**2. Write the code.** Click **Edit code content**. The editor opens with a template. Its classes are commented out (their lines start with `#`), so running it unchanged fails. Uncomment one class, or replace everything with: + +```python +from pytexera import * + + +class ProcessTupleOperator(UDFOperatorV2): + + @overrides + def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + tuple_["Revenue"] = tuple_["Units Sold"] * tuple_["Unit Price"] + yield tuple_ +``` + + + +**3. Declare the new column.** In the property panel, under **Extra output column(s)**, click **+** and add `Revenue` with type `double`. Leave **Retain input columns** checked to keep the original columns. + +<img src="udf-output-columns.png" alt="Retain input columns and one extra output column named Revenue" width="260"> + +**4. Run.** Click the eye icon on the UDF, then **Run**. Click the UDF, then the **Result** tab in the result panel. + +## The 5 rules + +Almost every UDF problem comes from breaking one of these. + +| # | Rule | If you break it | +|---|---|---| +| 1 | `from pytexera import *` is at the top (the template already has it) | `name 'UDFOperatorV2' is not defined` | +| 2 | Exactly **one** class. Delete or comment out the others. | `There should be one and only one Operator defined` | +| 3 | The method name must match the class you inherit from (table below) | `... does not implement process_tuple` or `... No super class method found` | +| 4 | Send results with `yield`, never `return` a value | ``process_tuple must `yield` results, not `return` them`` | +| 5 | The columns you yield must match the output columns (step 3) | `expected but missing` or `unexpected field` | + +## How your code receives data + +Pick one row of this table. The class name in brackets and the method name must go together. + +| Class `(…)` | Method you write | You receive | Good for | +|---|---|---|---| +| `UDFOperatorV2` | `process_tuple(self, tuple_, port)` | one row at a time (use it like a dict: `tuple_["col"]`) | per-row formulas, filtering | +| `UDFBatchOperator` | `process_batch(self, batch, port)` | `BATCH_SIZE` rows at a time, as a pandas DataFrame | calling an API in chunks | +| `UDFTableOperator` | `process_table(self, table, port)` | **all** rows of one input, as a pandas DataFrame | sorting, statistics, ML training | +| `UDFSourceOperator` (1-out UDF only) | `produce(self)` | nothing; you create the data | generating or downloading data | + +What you can `yield`: + +- **A row**: a `Tuple` or a `dict`, e.g. `yield {"name": "a", "value": 1}`. +- **A table**: a pandas `DataFrame` or `Table`. Yield the DataFrame itself, not a dict that contains DataFrames. +- **`None`**: produce nothing for this input. + +To drop a row, just don't `yield` it. To output several rows, `yield` several times. + +## One-time setup (loading a model, opening a file) + +Put setup code in `open()`, which runs once before any data arrives: + +```python +from pytexera import * + + +class ProcessTupleOperator(UDFOperatorV2): + + @overrides + def open(self): + self.threshold = 100 + + @overrides + def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + if tuple_["Units Sold"] > self.threshold: + yield tuple_ +``` + +If you write `__init__` instead, make its first line `super().__init__()`. Older Texera versions fail without it (see the table below). + +To set values like `threshold` from the property panel instead of in code, see [UI parameters](/docs/reference/operators/user-defined-functions/python/#ui-parameters). + +## Output columns + +The UDF's output columns are **Retain input columns** (the input's columns, if checked) plus **Extra output column(s)**. Every row you `yield` must contain exactly these columns. + +- Adding a column? Add it under **Extra output column(s)**. +- Returning a completely new table (e.g. a summary)? Uncheck **Retain input columns** and list every output column. +- With several inputs, **Retain input columns** keeps the columns of input 0 (for the 2-in UDF: the `tuples` input, port 1). + +## Several inputs + +Add input ports with the **+** under the operator's left side. Ports are numbered from 0. Your method's `port` argument tells you which input a row came from. + +- **Inputs arrive in no fixed order.** Don't assume input 0 finishes before input 1. +- To combine inputs safely, use `UDFTableOperator`. It calls `process_table` once per input, when that input is complete. Keep each table and act when you have all of them: + +```python +from pytexera import * + +NUM_INPUTS = 2 + + +class ProcessTableOperator(UDFTableOperator): + + @overrides + def open(self): + self.tables = {} + + @overrides + def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: + self.tables[port] = table + if len(self.tables) == NUM_INPUTS: + yield self.tables[0].merge(self.tables[1], on="Country") +``` + +- To force an order, click an input port's dot. Under **dependencies**, list the ports that must finish first. For example, port 1 with dependencies `0` waits for port 0. +- The **2-in Python UDF** has this built in: port 0 (`model`) is read completely before port 1 (`tuples`) starts. + +```python +from pytexera import * + + +class ProcessTupleOperator(UDFOperatorV2): + + @overrides + def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + if port == 0: # model input: remember the model + self.model = tuple_["model"] + else: # tuples input: use it + tuple_["pred"] = self.model.predict([tuple_["text"]])[0] + yield tuple_ +``` + +## Creating data (1-out Python UDF) + +```python +from pytexera import * + + +class GenerateOperator(UDFSourceOperator): + + @overrides + def produce(self) -> Iterator[Union[TupleLike, TableLike, None]]: + for i in range(10): + yield {"number": i} +``` + +List every column (here `number`, type `integer`) under **Columns** in the property panel. More examples: [pytexera examples](https://github.com/apache/texera/tree/main/amber/src/main/python/pytexera/udf/examples). + +## Finding and fixing errors + +- `print(...)` in your code shows up in the **Console** tab. Click the UDF to see it. +- If a row fails, the UDF turns **magenta** (paused) and the error appears in its **Console**. Fix the code, then stop the run (red ⊗ next to *Pause*) and run again. + + + +- If the code can't even load (missing import, wrong class), the error appears in **Static Error**. Click the UDF, or an empty spot on the canvas, to see it. The message includes the error type and your line number, e.g. `(NameError at line 2 of the UDF code)`. See [where to find errors](../guide-for-how-to-use-texera/#where-to-find-errors). + +| Error message contains | Cause | Fix | +|---|---|---| +| `name 'UDFOperatorV2' is not defined` (or `Tuple`, `Table`, …) | Missing import | Add `from pytexera import *` at the top | +| `There should be one and only one Operator defined` | No class, or more than one. The rest of the message names the classes. | Keep exactly one class, uncommented | +| `X subclasses UDFOperatorV2 but does not implement process_tuple` | The method doesn't match the class (e.g. `process_table` in a `UDFOperatorV2`) | Rename the method, or subclass the base the message suggests | +| `X does not subclass a pytexera base class` | The class has no pytexera base | Subclass one, e.g. `class ProcessTupleOperator(UDFOperatorV2):` (`UDFSourceOperator` for a 1-out UDF) | +| `No super class method found` | A method marked `@overrides` doesn't exist in the base class | Use the pair from [the table](#how-your-code-receives-data), or remove `@overrides` from a helper method | +| ``must `yield` results, not `return` them`` (older versions: `MatchError: '_' not provided` or `'NoneType' object is not iterable`) | `return` used instead of `yield` | Replace `return x` with `yield x` | +| `_TableOperator__table_data` (older versions) | `__init__` without `super().__init__()` | Add `super().__init__()`, or use `open()` | +| `A DataFrame was put in column 'X'` | A DataFrame is in a column whose type isn't binary | To output its rows, `yield` the DataFrame itself; to keep it as one value, make the column binary | +| `expected but missing in the Tuple` | A declared output column is missing from what you yield | Yield that column, or remove it from **Extra output column(s)** (**Columns** for a 1-out UDF) | +| `contains unexpected field` | You yield a column that isn't declared | Add it under **Extra output column(s)** (**Columns** for a 1-out UDF), or stop yielding it | +| `Column name X already exists!` | An extra output column has the same name as an input column | Rename it, or uncheck **Retain input columns** | +| Workflow stays at 0 rows and nothing happens | Code failed while starting | See [My workflow looks stuck](../guide-for-how-to-use-texera/#my-workflow-looks-stuck) | Review Comment: Same cause as the comment on step 1 of "My workflow looks stuck": since #8668, code that fails while starting ends the run and shows its error in Static Error, so it no longer leaves a run at 0 rows. Please drop this row; the rows above for code that can't load cover that case. ########## docs/getting-started/ui-overview.md: ########## @@ -41,10 +41,15 @@ Once logged in, you should see the following page: On the left sidebar, you can switch between different resource modules: -- **Workflows** — manage workflow projects. -- **Datasets** — upload and manage data files. -- **Quota** — check usage statistics and resource consumption. -- **Admin** — manage system users (visible only to admins). +- **Hub**: workflows and datasets that others have made public. +- **Your Work → Workflows**: your workflow projects. +- **Your Work → Datasets**: upload and manage data files. +- **Your Work → Compute**: the computing units that run your workflows. Review Comment: Nit: this list and the one in the Guide for how to use Texera describe the same menu differently: this one has no Warehouses, and Admin here is only users. Please make them match, or keep one list and link to it. ########## docs/tutorials/guide-for-how-to-use-texera/index.md: ########## @@ -0,0 +1,120 @@ +<!-- + ~ 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. +--> + +--- +title: "Guide for how to use Texera" +weight: 10 +--- + +Texera lets you analyze data by connecting boxes (**operators**) on a canvas instead of writing a program. Each box does one step, like "read a file", "keep rows where…", or "compute an average". The arrows carry data from one box to the next. + +## Sign in + +Open the Texera address you were given in your browser and sign in. + +On a Texera you installed yourself ([Docker guide](/docs/getting-started/installing-using-docker/)), the built-in admin account is username `texera`, password `texera`. + + + +## The dashboard + +After signing in you see the dashboard. The left menu has: + +- **Hub**: workflows and datasets other people have made public. +- **Your Work** + - **Workflows**: your workflows. Click **Create Workflow** to start one. + - **Datasets**: your data files ([how to upload](../create-dataset-upload-data/)). + - **Compute**: your computing units (see [below](#run-a-workflow)). + - **Warehouses** (on some setups): where your run results are stored. + - **Environments**: extra Python packages for Python operators. + - **Quota**: how much storage and compute you have used. +- **Admin**: users, executions and site settings. Admins only. + +## The workflow editor + + + +1. **Operators**: all available boxes, grouped by type. If the panel is closed, click the grid icon at the top left of the canvas. Drag a box onto the canvas, or type its name in the search box. Boxes added through search land on top of each other; drag them apart. +2. **Canvas**: connect the output dot on the right of one box to the input dot on the left of the next. +3. **Property panel**: click a box to set its options. A red outline means an option is missing or wrong. +4. **Result panel**: shows a box's output, printed messages and errors. If it's closed, open it with the square icon at the bottom left. + +## Run a workflow + +A **computing unit** is the machine that runs your workflow. Pick one in the top bar, then click **Run**. If the list is empty, click **+ Computing Unit** to create one. + + + +Some Texera setups also need a **warehouse**, the place your run's results are stored. Pick one from the **Warehouse** menu next to the computing unit. If the Run button says **+ Warehouse** instead, click it to create one. The name can use letters, digits, `-` and `_`. + +- One computing unit can run all your workflows. Reuse it. +- A new unit usually won't fix an error in the workflow itself (code or settings). It can help when the run needs more memory, CPU or GPU, or different Python packages. +- Stopping (terminating) a unit stops its machine. Your workflows and datasets are kept. To see results on another unit, run the workflow again there. + +More in [Computing Units](../computing-units/). + +## Read a running workflow + +Each box's outline color shows its state. The number on each side is how many rows went in (left) and came out (right). + + + +| Color | Meaning | +|---|---| +| Gray | Not started yet | +| Yellow-green | Ready to start | +| Orange | Running | +| Magenta | Paused. You paused it, or a row caused an error | +| Green | Finished | + +Some operators (e.g. Sort, Aggregate, and the build side of Join) must read **all** their input before they output anything. They show 0 rows out until the operator before them finishes. That's normal. See [How Texera runs your workflow](/docs/concepts/how-texera-runs-your-workflow/). + +## See the results + +1. Before running, click the box and turn on its **eye icon** (top toolbar). Texera shows results only for boxes with the eye on. +2. After the run, click the box and open the result panel (square icon, bottom left) if it's closed. The **Result** tab shows its rows. + +The result panel only shows the box you clicked. If it says *No operator is selected*, click a box. If it says *This operator has no results yet*, turn on that box's eye icon and run again. + +## Where to find errors + +- **Click the box that failed, or an empty spot on the canvas.** If the run failed, the result panel shows a **Static Error** tab with the error, including code that failed to start. With nothing selected it lists every operator's errors. A run that stops right away with every box at 0 rows usually means this. + + Review Comment: Nit: #9015's description says the message loses its "java.lang.Throwable:" prefix once it lands, so this screenshot will be out of date. Since this PR waits for #9015 anyway, please retake it after that merges. ########## docs/tutorials/guide-to-use-python-udf/index.md: ########## @@ -0,0 +1,212 @@ +<!-- + ~ 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. +--> + +--- +title: "Guide to Use a Python UDF" +weight: 30 +--- + +A **Python UDF** (user-defined function) is an operator that runs a small piece of Python code you write. Use it when no built-in operator does what you need. + +You don't need to be a programmer. Copy the example below and change one line at a time. + +## Which Python operator should I use? + +| You want to… | Use | +|---|---| +| Add or change a column with a one-line formula, e.g. `tuple_["Units Sold"] * 2` | **Python Lambda Function** (no class to write) | +| Turn a whole table into one summary row, e.g. `table["Units Sold"].mean()` | **Python Table Reducer** (no class to write) | +| Anything else with one or more inputs | **Python UDF** | +| Apply a model (input 0) to data rows (input 1) | **2-in Python UDF** | +| Create data from nothing (no input) | **1-out Python UDF** | + +## Your first UDF in 4 steps + +This example adds a `Revenue` column (units × price) to the sales data from [the dataset tutorial](../create-dataset-upload-data/). + +**1. Add the operator.** Drag **Python UDF** (under *User-defined Functions → Python*) onto the canvas and connect your data to it. + +**2. Write the code.** Click **Edit code content**. The editor opens with a template. Its classes are commented out (their lines start with `#`), so running it unchanged fails. Uncomment one class, or replace everything with: + +```python +from pytexera import * + + +class ProcessTupleOperator(UDFOperatorV2): + + @overrides + def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + tuple_["Revenue"] = tuple_["Units Sold"] * tuple_["Unit Price"] + yield tuple_ +``` + + + +**3. Declare the new column.** In the property panel, under **Extra output column(s)**, click **+** and add `Revenue` with type `double`. Leave **Retain input columns** checked to keep the original columns. + +<img src="udf-output-columns.png" alt="Retain input columns and one extra output column named Revenue" width="260"> + +**4. Run.** Click the eye icon on the UDF, then **Run**. Click the UDF, then the **Result** tab in the result panel. + +## The 5 rules + +Almost every UDF problem comes from breaking one of these. + +| # | Rule | If you break it | +|---|---|---| +| 1 | `from pytexera import *` is at the top (the template already has it) | `name 'UDFOperatorV2' is not defined` | +| 2 | Exactly **one** class. Delete or comment out the others. | `There should be one and only one Operator defined` | +| 3 | The method name must match the class you inherit from (table below) | `... does not implement process_tuple` or `... No super class method found` | +| 4 | Send results with `yield`, never `return` a value | ``process_tuple must `yield` results, not `return` them`` | +| 5 | The columns you yield must match the output columns (step 3) | `expected but missing` or `unexpected field` | + +## How your code receives data + +Pick one row of this table. The class name in brackets and the method name must go together. + +| Class `(…)` | Method you write | You receive | Good for | +|---|---|---|---| +| `UDFOperatorV2` | `process_tuple(self, tuple_, port)` | one row at a time (use it like a dict: `tuple_["col"]`) | per-row formulas, filtering | +| `UDFBatchOperator` | `process_batch(self, batch, port)` | `BATCH_SIZE` rows at a time, as a pandas DataFrame | calling an API in chunks | +| `UDFTableOperator` | `process_table(self, table, port)` | **all** rows of one input, as a pandas DataFrame | sorting, statistics, ML training | +| `UDFSourceOperator` (1-out UDF only) | `produce(self)` | nothing; you create the data | generating or downloading data | + +What you can `yield`: + +- **A row**: a `Tuple` or a `dict`, e.g. `yield {"name": "a", "value": 1}`. +- **A table**: a pandas `DataFrame` or `Table`. Yield the DataFrame itself, not a dict that contains DataFrames. +- **`None`**: produce nothing for this input. + +To drop a row, just don't `yield` it. To output several rows, `yield` several times. + +## One-time setup (loading a model, opening a file) + +Put setup code in `open()`, which runs once before any data arrives: Review Comment: The old guide was the only page that described `on_finish(port)`, which runs once when an input ends and can yield rows (for example a total after the last row), and `close()`. After this PR no Python UDF page mentions either. Please add a line for each here, next to `open()`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
