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

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


The following commit(s) were added to refs/heads/main by this push:
     new e1d676d10f feat: keep a table's declared columns when it has no rows 
(#8766)
e1d676d10f is described below

commit e1d676d10f723e251aadf9b3fb6f2147a6a1dd82
Author: Kary Zheng <[email protected]>
AuthorDate: Sat Oct 24 05:57:08 2026 +0000

    feat: keep a table's declared columns when it has no rows (#8766)
    
    ### What changes were proposed in this PR?
    
    A port or result with no rows lost its columns in two places, both
    because the column names were read off the first row.
    
    - **Python engine.** A port that finished with no rows reached a Python
    table operator as a table with no columns, so any operator naming one of
    its columns raised `KeyError`: Sort, the visualization operators, and
    any user-written `UDFTableOperator`. `Operator` gains an `input_schemas`
    mapping that `DataProcessor` fills with the finishing port's declared
    schema, and `TableOperator.on_finish` hands the operator those columns
    with no rows under them. `Table.empty_of` builds that frame through
    Arrow, so each column keeps the dtype it would have had with rows in it.
    - **Result panel.** A result with no rows showed "Empty result set"
    instead of its columns. `ExecutionResultService` now reports the stored
    schema when a page has no rows, and the result table builds its header
    from that schema when the whole result is empty. An empty page past the
    end of a non-empty result still leaves the table already shown in place.
    
    ### Any related issues, documentation, discussions?
    
    Closes #8735, which settled on this design (option 3) and asked for the
    frontend to show a table with no records. The engine half was first
    proposed in #8488.
    
    ### How was this PR tested?
    
    -
    `TestTableOperator.test_on_finish_with_no_rows_keeps_the_declared_columns`
    and
    `TestMainLoop.test_second_input_port_with_no_rows_finishes_as_itself`.
    Both fail when the operator is handed the old columnless table. The rest
    of `amber/src/test/python` passes, except the tests under
    `core/storage/iceberg`, which need a running Postgres and Iceberg REST
    catalog.
    - `ExecutionResultServiceSpec` gains a case for a stored result with no
    rows, and the past-the-end case now expects the stored schema. All 41
    pass.
    - `ResultTableFrameComponent` gains two cases: the header of an empty
    result, and an empty page of a non-empty result keeping its table. All
    53 pass.
    - Manually: Text Input → Filter matching nothing → Sort. The run
    completes, and Sort's result panel shows the `line` header with no rows.
    
    Before and after. The first pair is the result panel of a Filter that
    matches nothing. The second adds Sort after it, which used to fail with
    `KeyError: 'line'`.
    
    <img width="2056" height="1045" alt="8766-empty-result-table"
    
src="https://github.com/user-attachments/assets/3adba4b5-3ee4-40cc-ae1a-908f5dca2db1";
    />
    <img width="2056" height="1045" alt="8766-sort-after-empty-filter"
    
src="https://github.com/user-attachments/assets/a547f04b-3633-4dc1-ad02-a1510805094d";
    />
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Opus 5.5)
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
    Co-authored-by: Xinyuan Lin <[email protected]>
---
 amber/src/main/python/core/models/operator.py      |  25 ++-
 amber/src/main/python/core/models/table.py         |  17 ++
 .../main/python/core/runnables/data_processor.py   |  22 ++
 .../web/service/ExecutionResultService.scala       |   4 +-
 amber/src/test/python/core/models/test_operator.py |  19 ++
 .../python/core/runnables/test_data_processor.py   |   3 +
 .../test/python/core/runnables/test_main_loop.py   | 221 ++++++++++++++++++++-
 .../web/service/ExecutionResultServiceSpec.scala   |  20 +-
 .../result-table-frame.component.html              |   2 +-
 .../result-table-frame.component.spec.ts           |  39 ++++
 .../result-table-frame.component.ts                |  27 ++-
 11 files changed, 383 insertions(+), 16 deletions(-)

diff --git a/amber/src/main/python/core/models/operator.py 
b/amber/src/main/python/core/models/operator.py
index bbba116da5..1b6ff18c49 100644
--- a/amber/src/main/python/core/models/operator.py
+++ b/amber/src/main/python/core/models/operator.py
@@ -22,7 +22,7 @@ from abc import ABC, abstractmethod
 from collections import defaultdict
 from typing import Iterator, List, Mapping, Optional, Union, MutableMapping, 
Protocol
 
-from . import Table, TableLike, Tuple, TupleLike, Batch, BatchLike
+from . import Table, TableLike, Tuple, TupleLike, Batch, BatchLike, Schema
 from .state import State
 from .table import all_output_to_tuple
 
@@ -108,6 +108,23 @@ class Operator(ABC):
     def is_source(self, value: bool) -> None:
         self.__internal_is_source = value
 
+    __internal_input_schemas: Optional[MutableMapping[int, Schema]] = None
+
+    @property
+    @overrides.final
+    def input_schemas(self) -> MutableMapping[int, Schema]:
+        """
+        What each input port was declared to carry, keyed by port index and
+        written by the runtime before that port's data is handed over.
+
+        The tuples themselves say this too, so an operator only needs to ask
+        when there are none: a port can finish having carried no rows at all,
+        and its schema is then the only record of what its columns were.
+        """
+        if self.__internal_input_schemas is None:
+            self.__internal_input_schemas = {}
+        return self.__internal_input_schemas
+
     def open(self) -> None:
         """
         Open a context of the operator. Usually can be used for 
loading/initiating some
@@ -306,7 +323,11 @@ class TableOperator(TupleOperatorV2):
         yield
 
     def on_finish(self, port: int) -> Iterator[Optional[TableLike]]:
-        table = Table(self._get_table_data()[port])
+        rows = self._get_table_data()[port]
+        schema = self.input_schemas.get(port)
+        # A port that carried no rows has no tuples to read column names off,
+        # and a table of no columns fails every operator that names one.
+        table = Table(rows) if rows or schema is None else 
Table.empty_of(schema)
         yield from require_yielded(self.process_table(table, port), 
"process_table")
 
     @abstractmethod
diff --git a/amber/src/main/python/core/models/table.py 
b/amber/src/main/python/core/models/table.py
index 4716e0eba0..708e0580f8 100644
--- a/amber/src/main/python/core/models/table.py
+++ b/amber/src/main/python/core/models/table.py
@@ -16,6 +16,7 @@
 # under the License.
 
 import pandas
+import pyarrow as pa
 from pampy import match
 from typing import Iterator, TypeVar, List
 
@@ -25,6 +26,22 @@ TableLike = TypeVar("TableLike", pandas.DataFrame, 
List[TupleLike])
 
 
 class Table(pandas.DataFrame):
+    @staticmethod
+    def empty_of(schema) -> "Table":
+        """
+        The declared columns with no rows under them.
+
+        ``from_tuple_likes`` reads the column names off the tuples it is given,
+        so with none to read it produces a frame of no columns at all, and an
+        operator naming any of its own columns raises KeyError. A port that
+        carried no rows still has a schema, and this is what it looks like as a
+        table. Building it through Arrow gives each column the dtype it would
+        have had with rows in it.
+        """
+        return Table(
+            pa.Table.from_pylist([], 
schema=schema.as_arrow_schema()).to_pandas()
+        )
+
     @staticmethod
     def from_table(table):
         return table
diff --git a/amber/src/main/python/core/runnables/data_processor.py 
b/amber/src/main/python/core/runnables/data_processor.py
index 4466cc6adb..54192e1cf5 100644
--- a/amber/src/main/python/core/runnables/data_processor.py
+++ b/amber/src/main/python/core/runnables/data_processor.py
@@ -79,10 +79,32 @@ class DataProcessor(Runnable, Stoppable):
                 # Flush the state to MainLoop before producing tuples so the
                 # state and the tuple stream don't share a single switch.
                 self._switch_context()
+                self._declare_input_schema(executor, port_id)
                 self._set_output_tuple(
                     require_yielded(executor.on_finish(port_id), "on_finish")
                 )
 
+    def _declare_input_schema(self, executor, port_id: int) -> None:
+        """
+        Tell the executor what the finishing port was declared to carry, so an
+        operator handed no rows can still say what its columns were.
+
+        The marker names the port by number, but a port is registered under its
+        whole identity, so the channel the marker arrived on is what can name
+        the port object holding the schema.
+        """
+        channel_id = self._context.current_input_channel_id
+        if channel_id is None:
+            return
+        try:
+            port_identity = self._context.input_manager.get_port_id(channel_id)
+        except KeyError:
+            # A channel the input manager does not know is no port of ours.
+            return
+        executor.input_schemas[port_id] = self._context.input_manager.get_port(
+            port_identity
+        ).get_schema()
+
     def process_state(self, state: State) -> None:
         """
         Process an input marker by invoking appropriate state
diff --git 
a/amber/src/main/scala/org/apache/texera/web/service/ExecutionResultService.scala
 
b/amber/src/main/scala/org/apache/texera/web/service/ExecutionResultService.scala
index 2fa63f6b86..30c845ed0f 100644
--- 
a/amber/src/main/scala/org/apache/texera/web/service/ExecutionResultService.scala
+++ 
b/amber/src/main/scala/org/apache/texera/web/service/ExecutionResultService.scala
@@ -510,7 +510,9 @@ class ExecutionResultService(
         val mappedResults = convertTuplesToJson(paginationIterable)
         val attributes = paginationIterable.headOption
           .map(_.getSchema.getAttributes)
-          .getOrElse(List.empty)
+          // A page with no rows has no tuple to read the columns off, but the
+          // stored result still declares them.
+          .getOrElse(columns.get.map(schemaOption.get.getAttribute))
         PaginatedResultEvent.apply(request, mappedResults, attributes)
 
       case None =>
diff --git a/amber/src/test/python/core/models/test_operator.py 
b/amber/src/test/python/core/models/test_operator.py
index 6ca9ed5658..cf0fb17f27 100644
--- a/amber/src/test/python/core/models/test_operator.py
+++ b/amber/src/test/python/core/models/test_operator.py
@@ -22,6 +22,7 @@ import pytest
 
 from core.models import (
     BatchOperator,
+    Schema,
     SourceOperator,
     State,
     Table,
@@ -386,6 +387,24 @@ class TestTableOperator:
         assert len(op.received_tables) == 1
         assert list(op.received_tables[0].as_tuples()) == []
 
+    def test_on_finish_with_no_rows_keeps_the_declared_columns(self):
+        # The column names are read off the tuples, so a port that carried none
+        # left the operator a frame of no columns and every operator naming one
+        # of its own raised KeyError. The port's schema is the only record 
left.
+        op = _ConcreteTable()
+        op.input_schemas[0] = Schema(raw_schema={"x": "INTEGER", "y": 
"STRING"})
+
+        list(op.on_finish(port=0))
+
+        table = op.received_tables[0]
+        # Still a Table, so an operator reading it with as_tuples() keeps 
working.
+        assert isinstance(table, Table)
+        assert list(table.as_tuples()) == []
+        assert list(table.columns) == ["x", "y"]
+        assert table.empty
+        # The dtype each column would have had with rows under it.
+        assert table["x"].dtype == "int32"
+
     def test_buffers_are_keyed_by_port(self):
         # Each input port has its own tuple buffer; on_finish for one port
         # must not surface tuples written through a different port.
diff --git a/amber/src/test/python/core/runnables/test_data_processor.py 
b/amber/src/test/python/core/runnables/test_data_processor.py
index 6b321dd299..3ac98e7362 100644
--- a/amber/src/test/python/core/runnables/test_data_processor.py
+++ b/amber/src/test/python/core/runnables/test_data_processor.py
@@ -69,6 +69,9 @@ class _StubExecutor:
 
     def __init__(self):
         self.calls = []
+        # A real Operator carries this, and a finishing port declares its 
schema
+        # into it so an operator handed no rows can still say what it read.
+        self.input_schemas = {}
 
     def produce_state_on_start(self, port_id):
         self.calls.append(("produce_state_on_start", port_id))
diff --git a/amber/src/test/python/core/runnables/test_main_loop.py 
b/amber/src/test/python/core/runnables/test_main_loop.py
index a7ad83cf27..93a7a38536 100644
--- a/amber/src/test/python/core/runnables/test_main_loop.py
+++ b/amber/src/test/python/core/runnables/test_main_loop.py
@@ -91,7 +91,7 @@ from proto.org.apache.texera.amber.engine.architecture.worker 
import (
 from proto.org.apache.texera.amber.engine.common import 
DirectControlMessagePayloadV2
 from pytexera.udf.examples.count_batch_operator import CountBatchOperator
 from pytexera.udf.examples.echo_operator import EchoOperator
-from pytexera.udf.udf_operator import UDFOperatorV2
+from pytexera.udf.udf_operator import UDFOperatorV2, UDFTableOperator
 
 
 class _FalseLoopEnd(LoopEndOperator):
@@ -115,6 +115,14 @@ class EmptyOnFinishOperator(UDFOperatorV2):
         yield
 
 
+class PortColumnsTableOperator(UDFTableOperator):
+    # Reports which port it was finished on and what the table it was handed
+    # carried, one tuple per port. A port that received no rows has to arrive
+    # under its own id and with the columns it was declared to carry.
+    def process_table(self, table, port):
+        yield {"test-1": ",".join(map(str, table.columns)), "test-2": port}
+
+
 class TestMainLoop:
     @pytest.fixture
     def command_sequence(self):
@@ -215,6 +223,10 @@ class TestMainLoop:
         # from `produce_state_on_finish` so EndChannel handling can be
         # observed.
         class StateProcessingExecutor:
+            # What Operator gives a real executor, for DataProcessor to record
+            # the finishing port's declared schema in.
+            input_schemas: dict = {}
+
             @staticmethod
             def process_tuple(tuple_, port):
                 yield tuple_
@@ -342,6 +354,127 @@ class TestMainLoop:
         )
         return DCMElement(tag=mock_control_input_channel, payload=payload)
 
+    # A second input port, and a channel of its own feeding it. Everything
+    # below mirrors the port-0 fixtures; only the port id and the sender 
differ.
+    @pytest.fixture
+    def mock_second_port_id(self):
+        return PortIdentity(1, internal=False)
+
+    @pytest.fixture
+    def mock_second_data_input_channel(self, mock_receiver_actor):
+        return ChannelIdentity(
+            ActorVirtualIdentity("second-sender"),
+            mock_receiver_actor,
+            False,
+        )
+
+    @pytest.fixture
+    def mock_assign_second_input_port(
+        self,
+        mock_raw_schema,
+        mock_control_input_channel,
+        mock_second_port_id,
+        command_sequence,
+    ):
+        command = set_one_of(
+            ControlRequest,
+            AssignPortRequest(
+                port_id=mock_second_port_id, input=True, schema=mock_raw_schema
+            ),
+        )
+        payload = set_one_of(
+            DirectControlMessagePayloadV2,
+            ControlInvocation(
+                method_name="AssignPort", command_id=command_sequence, 
command=command
+            ),
+        )
+        return DCMElement(tag=mock_control_input_channel, payload=payload)
+
+    @pytest.fixture
+    def mock_add_second_input_channel(
+        self,
+        mock_control_input_channel,
+        mock_second_data_input_channel,
+        mock_second_port_id,
+        command_sequence,
+    ):
+        command = set_one_of(
+            ControlRequest,
+            AddInputChannelRequest(
+                mock_second_data_input_channel, port_id=mock_second_port_id
+            ),
+        )
+        payload = set_one_of(
+            DirectControlMessagePayloadV2,
+            ControlInvocation(
+                method_name="AddInputChannel",
+                command_id=command_sequence,
+                command=command,
+            ),
+        )
+        return DCMElement(tag=mock_control_input_channel, payload=payload)
+
+    @pytest.fixture
+    def mock_second_start_channel(self, mock_second_data_input_channel):
+        return self._channel_ecm(
+            mock_second_data_input_channel,
+            "StartChannel",
+            EmbeddedControlMessageType.NO_ALIGNMENT,
+        )
+
+    @pytest.fixture
+    def mock_second_end_of_upstream(self, mock_second_data_input_channel):
+        return self._channel_ecm(
+            mock_second_data_input_channel,
+            "EndChannel",
+            EmbeddedControlMessageType.PORT_ALIGNMENT,
+        )
+
+    @pytest.fixture
+    def mock_initialize_port_columns_executor(
+        self, mock_control_input_channel, command_sequence
+    ):
+        operator_code = "from pytexera import *\n" + inspect.getsource(
+            PortColumnsTableOperator
+        )
+        command = set_one_of(
+            ControlRequest,
+            InitializeExecutorRequest(
+                op_exec_init_info=set_one_of(
+                    OpExecInitInfo, OpExecWithCode(operator_code, "python")
+                ),
+                is_source=False,
+            ),
+        )
+        payload = set_one_of(
+            DirectControlMessagePayloadV2,
+            ControlInvocation(
+                method_name="InitializeExecutor",
+                command_id=command_sequence,
+                command=command,
+            ),
+        )
+        return DCMElement(tag=mock_control_input_channel, payload=payload)
+
+    @staticmethod
+    def _channel_ecm(channel_id, method_name, alignment):
+        return ECMElement(
+            tag=channel_id,
+            payload=EmbeddedControlMessage(
+                EmbeddedControlMessageIdentity(method_name),
+                alignment,
+                [],
+                {
+                    channel_id.to_worker_id.name: ControlInvocation(
+                        method_name,
+                        ControlRequest(empty_request=EmptyRequest()),
+                        AsyncRpcContext(ActorVirtualIdentity(), 
ActorVirtualIdentity()),
+                        -1,
+                    )
+                },
+            ),
+        )
+
     @pytest.fixture
     def input_queue(self):
         return InternalQueue()
@@ -1969,6 +2102,92 @@ class TestMainLoop:
 
         reraise()
 
+    @staticmethod
+    def _columns_reported_per_port(items):
+        # {port -> the columns the table handed to that port carried}, read off
+        # the tuples PortColumnsTableOperator emits from process_table.
+        reported = {}
+        for item in items:
+            if not isinstance(item, DataElement) or not isinstance(
+                item.payload, DataFrame
+            ):
+                continue
+            for _, row in item.payload.frame.to_pandas().iterrows():
+                reported[int(row["test-2"])] = row["test-1"]
+        return reported
+
+    @pytest.mark.timeout(30)
+    def test_second_input_port_with_no_rows_finishes_as_itself(
+        self,
+        mock_control_output_channel,
+        mock_data_element,
+        input_queue,
+        output_queue,
+        main_loop,
+        main_loop_thread,
+        mock_assign_input_port,
+        mock_assign_second_input_port,
+        mock_assign_output_port,
+        mock_add_input_channel,
+        mock_add_second_input_channel,
+        mock_add_partitioning,
+        mock_initialize_port_columns_executor,
+        mock_start_channel,
+        mock_second_start_channel,
+        mock_end_of_upstream,
+        mock_second_end_of_upstream,
+        command_sequence,
+        reraise,
+    ):
+        # Port 0 carries a row, port 1 carries nothing at all. A marker belongs
+        # to the port whose channel delivered it, not to whichever port last
+        # had a tuple, so port 1 has to finish as port 1 and arrive with the
+        # columns it was declared to carry. Read the port off the tuple rather
+        # than off the order the two arrive in.
+        main_loop_thread.daemon = True
+        main_loop_thread.start()
+
+        for setup_msg in [
+            mock_assign_input_port,
+            mock_assign_second_input_port,
+            mock_assign_output_port,
+            mock_add_input_channel,
+            mock_add_second_input_channel,
+            mock_add_partitioning,
+            mock_initialize_port_columns_executor,
+        ]:
+            input_queue.put(setup_msg)
+            assert output_queue.get() == DCMElement(
+                tag=mock_control_output_channel,
+                payload=DirectControlMessagePayloadV2(
+                    return_invocation=ReturnInvocation(
+                        command_id=command_sequence,
+                        return_value=ControlReturn(empty_return=EmptyReturn()),
+                    )
+                ),
+            )
+
+        input_queue.put(mock_start_channel)
+        input_queue.put(mock_data_element)
+        input_queue.put(mock_end_of_upstream)
+        input_queue.put(mock_second_start_channel)
+        input_queue.put(mock_second_end_of_upstream)
+
+        collected = self._drain_until(
+            output_queue,
+            lambda items: len(self._columns_reported_per_port(items)) == 2,
+        )
+        reported = self._columns_reported_per_port(collected)
+
+        # Port 1 reporting nothing at all means its marker was read as port 
0's,
+        # which finishes port 0 twice and leaves the empty port unfinished.
+        assert reported == {
+            0: "test-1,test-2",
+            1: "test-1,test-2",
+        }, f"collected={collected}"
+
+        reraise()
+
     @pytest.mark.timeout(30)
     def test_empty_on_finish_after_tuples_completes_worker(
         self,
diff --git 
a/amber/src/test/scala/org/apache/texera/web/service/ExecutionResultServiceSpec.scala
 
b/amber/src/test/scala/org/apache/texera/web/service/ExecutionResultServiceSpec.scala
index 3d9ed9fcf8..5e4975d17f 100644
--- 
a/amber/src/test/scala/org/apache/texera/web/service/ExecutionResultServiceSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/web/service/ExecutionResultServiceSpec.scala
@@ -844,7 +844,7 @@ class ExecutionResultServiceSpec
     event.table.map(_.get("id").asInt()) shouldBe List(6)
   }
 
-  it should "return an empty page with no schema past the end of the result" 
in {
+  it should "return an empty page with the stored schema past the end of the 
result" in {
     val executionId = newExecution()
     val schema = new Schema(List(new Attribute("id", AttributeType.INTEGER)))
     storeResult(
@@ -859,9 +859,21 @@ class ExecutionResultServiceSpec
     )
 
     event.table shouldBe empty
-    // The reported schema comes from the first row of the page, so a page 
with no
-    // rows reports no schema at all -- there is no fallback to the stored 
schema.
-    event.schema shouldBe empty
+    event.schema.map(_.getName) shouldBe List("id")
+  }
+
+  it should "report the stored columns of a result with no rows" in {
+    val executionId = newExecution()
+    val schema = new Schema(
+      List(new Attribute("id", AttributeType.INTEGER), new Attribute("label", 
AttributeType.STRING))
+    )
+    storeResult(executionId, "erss-no-rows", schema, List.empty)
+
+    val event = paginate(paginationRequest.copy(operatorID = "erss-no-rows"))
+
+    event.table shouldBe empty
+    event.schema.map(a => (a.getName, a.getType)) shouldBe
+      List(("id", AttributeType.INTEGER), ("label", AttributeType.STRING))
   }
 
   it should "match a column search case-insensitively" in {
diff --git 
a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.html
 
b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.html
index be6b1c06b1..aadb1775a7 100644
--- 
a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.html
+++ 
b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.html
@@ -18,7 +18,7 @@
 -->
 
 <div
-  *ngIf="!currentResult || currentResult.length === 0"
+  *ngIf="(!currentResult || currentResult.length === 0) && 
!currentColumns?.length"
   style="text-align: center">
   <h4>Empty result set</h4>
   <p>Tip: enable the eye icon on the operator and execute the workflow to view 
its results.</p>
diff --git 
a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.spec.ts
 
b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.spec.ts
index 9afb07d04c..327fd1ecdd 100644
--- 
a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.spec.ts
+++ 
b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.spec.ts
@@ -262,6 +262,45 @@ describe("ResultTableFrameComponent", () => {
       expect(component.getCellMediaType(row, 0)).toBe("video");
     });
 
+    it("shows the schema's columns with no rows when the whole result is 
empty", () => {
+      component.operatorId = "op1";
+
+      component.setupResultTable([], 0, [
+        { attributeName: "name", attributeType: "string" },
+        { attributeName: "score", attributeType: "integer" },
+      ]);
+
+      expect(component.currentResult).toEqual([]);
+      expect(component.currentColumns?.map(c => c.header)).toEqual(["name", 
"score"]);
+      expect(component.totalNumTuples).toBe(0);
+    });
+
+    it("keeps the existing table for an empty page of a non-empty result, 
schema or not", () => {
+      component.operatorId = "op1";
+      component.setupResultTable([SAMPLE_ROW], 5);
+
+      component.setupResultTable([], 7, [{ attributeName: "other", 
attributeType: "string" }]);
+
+      expect(component.currentResult).toEqual([SAMPLE_ROW]);
+      expect(component.currentColumns?.map(c => c.header)).toEqual(["name", 
"score"]);
+    });
+
+    it("drops the old headers and stops loading when a search matches no 
column of an empty result", () => {
+      component.operatorId = "op1";
+      component.setupResultTable([], 0, [{ attributeName: "name", 
attributeType: "string" }]);
+      makePaginatedResultService({
+        getCurrentTotalNumTuples: vi.fn().mockReturnValue(0),
+        selectPage: 
vi.fn().mockReturnValue(of(makePageEvent(component.currentPageIndex, []))),
+      });
+
+      const input: HTMLInputElement = 
fixture.nativeElement.querySelector("input[nz-input]");
+      input.value = "missing";
+      input.dispatchEvent(new Event("input"));
+
+      expect(component.isLoadingResult).toBe(false);
+      expect(component.currentColumns).toEqual([]);
+    });
+
     it("builds columns from the first row and drops the internal _id column", 
() => {
       component.operatorId = "op1";
       component.isLoadingResult = true;
diff --git 
a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.ts
 
b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.ts
index a329161369..d0c45efe36 100644
--- 
a/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.ts
+++ 
b/frontend/src/app/workspace/component/result-panel/result-table-frame/result-table-frame.component.ts
@@ -34,6 +34,7 @@ import { WorkflowResultService } from 
"../../../service/workflow-result/workflow
 import { PanelResizeService } from 
"../../../service/workflow-result/panel-resize/panel-resize.service";
 import { isWebPaginationUpdate, OperatorState } from 
"../../../types/execute-workflow.interface";
 import { IndexableObject, TableColumn } from 
"../../../types/result-table.interface";
+import { SchemaAttribute } from "../../../types/workflow-compiling.interface";
 import { RowModalComponent } from "../result-panel-modal.component";
 import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy";
 import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@@ -405,7 +406,7 @@ export class ResultTableFrameComponent implements OnInit, 
OnChanges {
       .pipe(untilDestroyed(this))
       .subscribe(pageData => {
         if (this.currentPageIndex === pageData.pageIndex) {
-          this.setupResultTable(pageData.table, 
paginatedResultService.getCurrentTotalNumTuples());
+          this.setupResultTable(pageData.table, 
paginatedResultService.getCurrentTotalNumTuples(), pageData.schema);
           this.changeDetectorRef.detectChanges();
         }
       });
@@ -418,17 +419,26 @@ export class ResultTableFrameComponent implements OnInit, 
OnChanges {
    * @param resultData rows of the result (may not be all rows if displaying 
result for workflow completed event)
    * @param totalRowCount
    */
-  setupResultTable(resultData: ReadonlyArray<IndexableObject>, totalRowCount: 
number) {
+  setupResultTable(
+    resultData: ReadonlyArray<IndexableObject>,
+    totalRowCount: number,
+    schema: ReadonlyArray<SchemaAttribute> = []
+  ) {
     if (!this.operatorId) {
       return;
     }
-    if (resultData.length < 1) {
-      return;
-    }
-
+    // Every page that arrives ends the fetch, including one that changes 
nothing below.
     this.isLoadingResult = false;
     this.changeDetectorRef.detectChanges();
 
+    // A result with no rows still has columns, and showing them tells the 
user what the
+    // operator would have produced. A column search can leave none, and the 
old headers must
+    // not stay. An empty page of a non-empty result is only a page index past 
the end, so the
+    // table already shown stays.
+    if (resultData.length < 1 && totalRowCount > 0) {
+      return;
+    }
+
     // creates a shallow copy of the readonly response.result,
     //  this copy will be has type object[] because MatTableDataSource's input 
needs to be object[]
     this.currentResult = resultData.slice();
@@ -439,7 +449,10 @@ export class ResultTableFrameComponent implements OnInit, 
OnChanges {
 
     let columns: { columnKey: any; columnText: string }[];
 
-    const columnKeys = Object.keys(resultData[0]).filter(x => x !== "_id");
+    const columnKeys =
+      resultData.length > 0
+        ? Object.keys(resultData[0]).filter(x => x !== "_id")
+        : schema.map(attribute => attribute.attributeName);
     columns = columnKeys.map(v => ({ columnKey: v, columnText: v }));
 
     // generate columnDef from first row, column definition is in order

Reply via email to