tp: start a RowCursor run in one call

**Why**

In a SQLite join the inner table's query runs once per outer row and
usually finds one row or a few. Opening a cursor restarted every
operator and then pulled through the pipeline, which cost more than
reading the rows.

**Changes**

- `Source::Start()` restarts a run and returns its first batch. By
  default it calls `Restart()` then `Next()`.
- `IndexScan` and `SortedScan` override it to search and fill the first
  batch directly. `Pipeline` passes it to its source when it only has
  transforms and holds no rows.
- `RowCursor::Open()` uses it.
- The code which gives SQLite a cursor's cells moves from
  `pipeline_module.cc` to `column_results.h`, so the dataframe module
  can use it too. Strings are passed as zero-terminated.

**Testing**

`perfetto_unittests` and all diff tests pass. The next PR uses this and
has the benchmarks.
diff --git a/BUILD b/BUILD
index 4ae4723..f0586d2 100644
--- a/BUILD
+++ b/BUILD
@@ -3933,6 +3933,7 @@
 perfetto_filegroup(
     name = "src_trace_processor_perfetto_sql_engine_engine",
     srcs = [
+        "src/trace_processor/perfetto_sql/engine/column_results.h",
         "src/trace_processor/perfetto_sql/engine/connection_catalog.cc",
         "src/trace_processor/perfetto_sql/engine/connection_catalog.h",
         "src/trace_processor/perfetto_sql/engine/created_function.cc",
diff --git a/src/trace_processor/core/exec/index_scan.cc b/src/trace_processor/core/exec/index_scan.cc
index c14ab31..0648b33 100644
--- a/src/trace_processor/core/exec/index_scan.cc
+++ b/src/trace_processor/core/exec/index_scan.cc
@@ -123,6 +123,14 @@
   return base::Span<const uint32_t>(entries.b, entries.e);
 }
 
+RowBatch* IndexScan::Start(RowBatch& scratch, OperatorState& state) const {
+  state.EndRun();
+  State& s = state.Cast<State>();
+  s.reader.Start(Find(s));
+  s.searched = true;
+  return s.reader.Read(scratch) ? &scratch : nullptr;
+}
+
 bool IndexScan::GetData(RowBatch& out, OperatorState& state) const {
   State& s = state.Cast<State>();
   if (PERFETTO_UNLIKELY(!s.searched)) {
diff --git a/src/trace_processor/core/exec/index_scan.h b/src/trace_processor/core/exec/index_scan.h
index 61ba32f..383c2d2 100644
--- a/src/trace_processor/core/exec/index_scan.h
+++ b/src/trace_processor/core/exec/index_scan.h
@@ -58,6 +58,7 @@
 
   std::unique_ptr<OperatorState> MakeState(Context& context) const override;
   bool GetData(RowBatch& out, OperatorState& state) const override;
+  RowBatch* Start(RowBatch& scratch, OperatorState& state) const override;
   void Rewind(OperatorState& state) const override;
 
  private:
diff --git a/src/trace_processor/core/exec/operator.h b/src/trace_processor/core/exec/operator.h
index fc56ef9..e1f77f1 100644
--- a/src/trace_processor/core/exec/operator.h
+++ b/src/trace_processor/core/exec/operator.h
@@ -208,6 +208,10 @@
     return GetData(scratch, state) ? &scratch : nullptr;
   }
 
+  // Restarts the run and returns its first batch, as Restart() then Next()
+  // would, in one call.
+  virtual RowBatch* Start(RowBatch& scratch, OperatorState& state) const;
+
   // Restarts from the first batch.
   virtual void Rewind(OperatorState& state) const = 0;
 
@@ -238,6 +242,11 @@
   source.Rewind(state);
 }
 
+inline RowBatch* Source::Start(RowBatch& scratch, OperatorState& state) const {
+  Restart(*this, state);
+  return Next(scratch, state);
+}
+
 // A step changing the batch it is given in place. Unlike an Operator it never
 // holds rows back, so a pipeline runs it with nothing copied or buffered.
 class Transform {
diff --git a/src/trace_processor/core/exec/pipeline.cc b/src/trace_processor/core/exec/pipeline.cc
index b6b6a59..97db9cd 100644
--- a/src/trace_processor/core/exec/pipeline.cc
+++ b/src/trace_processor/core/exec/pipeline.cc
@@ -131,6 +131,32 @@
   source_.Rewind(*s.source_state);
 }
 
+// Holding nothing and with only transforms after the source, a run starts
+// with its source's: there is nothing else to restart.
+RowBatch* Pipeline::Start(RowBatch& scratch, OperatorState& state) const {
+  auto& s = state.Cast<State>();
+  if (PERFETTO_UNLIKELY((plan_flags_ & State::kSegmented) || s.holds_any ||
+                        state.holds() || (s.flags & State::kFailed))) {
+    Restart(*this, state);
+    return Next(scratch, state);
+  }
+  ++s.run;
+  s.flags = plan_flags_;
+  s.ended_segments = 0;
+  RowBatch* batch = s.source->Start(s.output, *s.source_state);
+  if (PERFETTO_UNLIKELY(!batch)) {
+    SourceDone(s);
+    return nullptr;
+  }
+  for (const State::Link& link : *s.output_links) {
+    if (PERFETTO_UNLIKELY(!link.op->Process(*batch, *link.state))) {
+      TransformFailed(link, s);
+      return nullptr;
+    }
+  }
+  return PERFETTO_LIKELY(batch->size()) ? batch : NextSlow(s);
+}
+
 // A batch is one pull, from the source or the operator starting the last
 // segment, and that segment's transforms. Limits, combining, cancellation and
 // failure are NextSlow()'s.
diff --git a/src/trace_processor/core/exec/pipeline.h b/src/trace_processor/core/exec/pipeline.h
index a988546..828e2a0 100644
--- a/src/trace_processor/core/exec/pipeline.h
+++ b/src/trace_processor/core/exec/pipeline.h
@@ -52,6 +52,7 @@
 
   std::unique_ptr<OperatorState> MakeState(Context&) const override;
   RowBatch* Next(RowBatch& scratch, OperatorState& state) const override;
+  RowBatch* Start(RowBatch& scratch, OperatorState& state) const override;
   bool GetData(RowBatch& out, OperatorState& state) const override;
   void Rewind(OperatorState& state) const override;
   base::Status status(const OperatorState& state) const override;
diff --git a/src/trace_processor/core/exec/row_cursor.h b/src/trace_processor/core/exec/row_cursor.h
index dcf2836..ff5135c 100644
--- a/src/trace_processor/core/exec/row_cursor.h
+++ b/src/trace_processor/core/exec/row_cursor.h
@@ -47,11 +47,14 @@
   // `params` (see Context::SetParams).
   bool Open(base::Span<const ParamValue> params = {}) {
     context_.SetParams(params);
-    Restart(source_, *state_);
-    batch_ = nullptr;
+    batch_ = source_.Start(scratch_, *state_);
     index_ = 0;
-    size_ = 0;
-    return Pull();
+    if (PERFETTO_UNLIKELY(!batch_)) {
+      size_ = 0;
+      return false;
+    }
+    size_ = batch_->size();
+    return PERFETTO_LIKELY(size_) || Pull();
   }
 
   // Moves to the next row, pulling a new batch if this one is exhausted. At
diff --git a/src/trace_processor/core/exec/sorted_scan.cc b/src/trace_processor/core/exec/sorted_scan.cc
index 79ec40a..1fb4ec8 100644
--- a/src/trace_processor/core/exec/sorted_scan.cc
+++ b/src/trace_processor/core/exec/sorted_scan.cc
@@ -150,6 +150,14 @@
   return range;
 }
 
+RowBatch* SortedScan::Start(RowBatch& scratch, OperatorState& state) const {
+  state.EndRun();
+  State& s = state.Cast<State>();
+  s.reader.Start(only_id_eq_ ? FindIdEq(*s.context) : Find(*s.context));
+  s.searched = true;
+  return s.reader.Read(scratch) ? &scratch : nullptr;
+}
+
 bool SortedScan::GetData(RowBatch& out, OperatorState& state) const {
   State& s = state.Cast<State>();
   if (PERFETTO_UNLIKELY(!s.searched)) {
diff --git a/src/trace_processor/core/exec/sorted_scan.h b/src/trace_processor/core/exec/sorted_scan.h
index c80160e..721e4e6 100644
--- a/src/trace_processor/core/exec/sorted_scan.h
+++ b/src/trace_processor/core/exec/sorted_scan.h
@@ -70,6 +70,7 @@
 
   std::unique_ptr<OperatorState> MakeState(Context& context) const override;
   bool GetData(RowBatch& out, OperatorState& state) const override;
+  RowBatch* Start(RowBatch& scratch, OperatorState& state) const override;
   void Rewind(OperatorState& state) const override;
 
  private:
diff --git a/src/trace_processor/perfetto_sql/engine/BUILD.gn b/src/trace_processor/perfetto_sql/engine/BUILD.gn
index 920e092..183bc29 100644
--- a/src/trace_processor/perfetto_sql/engine/BUILD.gn
+++ b/src/trace_processor/perfetto_sql/engine/BUILD.gn
@@ -18,6 +18,7 @@
 
 source_set("engine") {
   sources = [
+    "column_results.h",
     "connection_catalog.cc",
     "connection_catalog.h",
     "created_function.cc",
diff --git a/src/trace_processor/perfetto_sql/engine/column_results.h b/src/trace_processor/perfetto_sql/engine/column_results.h
new file mode 100644
index 0000000..e18d7c8
--- /dev/null
+++ b/src/trace_processor/perfetto_sql/engine/column_results.h
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2026 The Android Open Source Project
+ *
+ * Licensed 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.
+ */
+
+#ifndef SRC_TRACE_PROCESSOR_PERFETTO_SQL_ENGINE_COLUMN_RESULTS_H_
+#define SRC_TRACE_PROCESSOR_PERFETTO_SQL_ENGINE_COLUMN_RESULTS_H_
+
+#include <sqlite3.h>
+
+#include <cstdint>
+#include <type_traits>
+
+#include "perfetto/base/logging.h"
+#include "src/trace_processor/containers/string_pool.h"
+#include "src/trace_processor/core/common/storage_types.h"
+#include "src/trace_processor/core/exec/column_view.h"
+#include "src/trace_processor/core/exec/variant.h"
+#include "src/trace_processor/sqlite/bindings/sqlite_result.h"
+
+namespace perfetto::trace_processor {
+
+using ColumnResultFn = void (*)(sqlite3_context*,
+                                StringPool*,
+                                const core::exec::ColumnView&,
+                                uint32_t);
+
+namespace column_results_internal {
+
+using core::exec::ColumnView;
+using core::exec::Variant;
+
+inline void ResultString(sqlite3_context* ctx,
+                         StringPool* pool,
+                         StringPool::Id id) {
+  if (id.is_null()) {
+    sqlite::result::Null(ctx);
+    return;
+  }
+  // Interned strings live as long as the pool, and end in a zero byte.
+  auto str = pool->Get(id);
+  sqlite::result::StaticTerminatedString(ctx, str.c_str(), str.size());
+}
+
+template <typename T>
+void ResultValue(sqlite3_context* ctx, StringPool* pool, T value) {
+  if constexpr (std::is_same_v<T, double>) {
+    sqlite::result::Double(ctx, value);
+  } else if constexpr (std::is_same_v<T, StringPool::Id>) {
+    ResultString(ctx, pool, value);
+  } else {
+    sqlite::result::Long(ctx, value);
+  }
+}
+
+inline void ResultVariant(sqlite3_context* ctx,
+                          StringPool* pool,
+                          const ColumnView& view,
+                          uint32_t row) {
+  Variant cell = view.At<Variant>(row);
+  switch (cell.type) {
+    case Variant::Type::kNull:
+      return sqlite::result::Null(ctx);
+    case Variant::Type::kInt64:
+      return sqlite::result::Long(ctx, cell.AsInt64());
+    case Variant::Type::kDouble:
+      return sqlite::result::Double(ctx, cell.AsDouble());
+    case Variant::Type::kString:
+      return ResultString(ctx, pool, cell.AsString());
+  }
+  PERFETTO_FATAL("For GCC");
+}
+
+// Checks for nulls per row: a column can have them in one batch but not
+// another.
+template <typename T>
+void ResultFlat(sqlite3_context* ctx,
+                StringPool* pool,
+                const ColumnView& view,
+                uint32_t row) {
+  uint32_t index = view.Index(row);
+  if (!view.IsValid(row)) {
+    return sqlite::result::Null(ctx);
+  }
+  ResultValue(ctx, pool, static_cast<const T*>(view.data())[index]);
+}
+
+inline void ResultSequence(sqlite3_context* ctx,
+                           StringPool*,
+                           const ColumnView& view,
+                           uint32_t row) {
+  uint32_t index = view.Index(row);
+  if (!view.IsValid(row)) {
+    return sqlite::result::Null(ctx);
+  }
+  sqlite::result::Long(ctx, index);
+}
+
+inline ColumnResultFn ColumnResultFor(const ColumnView& view) {
+  if (view.kind() == ColumnView::Kind::kVariant) {
+    return &ResultVariant;
+  }
+  if (view.kind() == ColumnView::Kind::kSequence) {
+    return &ResultSequence;
+  }
+  core::StorageType type = view.type();
+  if (type.Is<core::Uint32>())
+    return &ResultFlat<uint32_t>;
+  if (type.Is<core::Int32>())
+    return &ResultFlat<int32_t>;
+  if (type.Is<core::Int64>())
+    return &ResultFlat<int64_t>;
+  if (type.Is<core::Double>())
+    return &ResultFlat<double>;
+  if (type.Is<core::String>())
+    return &ResultFlat<StringPool::Id>;
+  PERFETTO_FATAL("Unexpected column type");
+}
+
+}  // namespace column_results_internal
+
+using column_results_internal::ColumnResultFor;
+
+}  // namespace perfetto::trace_processor
+
+#endif  // SRC_TRACE_PROCESSOR_PERFETTO_SQL_ENGINE_COLUMN_RESULTS_H_
diff --git a/src/trace_processor/perfetto_sql/engine/pipeline_module.cc b/src/trace_processor/perfetto_sql/engine/pipeline_module.cc
index b3434db..20534fb 100644
--- a/src/trace_processor/perfetto_sql/engine/pipeline_module.cc
+++ b/src/trace_processor/perfetto_sql/engine/pipeline_module.cc
@@ -23,7 +23,6 @@
 #include <memory>
 #include <string>
 #include <string_view>
-#include <type_traits>
 #include <utility>
 #include <vector>
 
@@ -38,8 +37,8 @@
 #include "src/trace_processor/core/dataframe/runtime_dataframe_builder.h"
 #include "src/trace_processor/core/exec/column_view.h"
 #include "src/trace_processor/core/exec/row_cursor.h"
-#include "src/trace_processor/core/exec/variant.h"
 #include "src/trace_processor/core/util/bit_vector.h"
+#include "src/trace_processor/perfetto_sql/engine/column_results.h"
 #include "src/trace_processor/perfetto_sql/engine/perfetto_sql_connection.h"
 #include "src/trace_processor/perfetto_sql/engine/sqlite_dataframe_builder.h"
 #include "src/trace_processor/perfetto_sql/pipeline/physical_plan.h"
@@ -52,7 +51,6 @@
 namespace {
 
 using core::exec::ColumnView;
-using core::exec::Variant;
 
 // The pointer types of what __intrinsic_dataframe_agg and
 // __intrinsic_dataframes give.
@@ -87,66 +85,6 @@
   return "CREATE TABLE x(" + base::Join(columns, ", ") + ")";
 }
 
-void ResultString(sqlite3_context* ctx, StringPool* pool, StringPool::Id id) {
-  if (id.is_null()) {
-    sqlite::result::Null(ctx);
-    return;
-  }
-  // Interned strings live as long as the pool.
-  auto str = pool->Get(id);
-  sqlite::result::StaticString(ctx, str.c_str(), static_cast<int>(str.size()));
-}
-
-void ResultVariant(sqlite3_context* ctx,
-                   StringPool* pool,
-                   const ColumnView& view,
-                   uint32_t row) {
-  Variant cell = view.At<Variant>(row);
-  switch (cell.type) {
-    case Variant::Type::kNull:
-      return sqlite::result::Null(ctx);
-    case Variant::Type::kInt64:
-      return sqlite::result::Long(ctx, cell.AsInt64());
-    case Variant::Type::kDouble:
-      return sqlite::result::Double(ctx, cell.AsDouble());
-    case Variant::Type::kString:
-      return ResultString(ctx, pool, cell.AsString());
-  }
-  PERFETTO_FATAL("For GCC");
-}
-
-// Checks for nulls per row: a column can have them in one batch but not
-// another.
-template <typename T>
-void ResultFlat(sqlite3_context* ctx,
-                StringPool* pool,
-                const ColumnView& view,
-                uint32_t row) {
-  uint32_t index = view.Index(row);
-  if (!view.IsValid(row)) {
-    return sqlite::result::Null(ctx);
-  }
-  T value = static_cast<const T*>(view.data())[index];
-  if constexpr (std::is_same_v<T, double>) {
-    sqlite::result::Double(ctx, value);
-  } else if constexpr (std::is_same_v<T, StringPool::Id>) {
-    ResultString(ctx, pool, value);
-  } else {
-    sqlite::result::Long(ctx, value);
-  }
-}
-
-void ResultSequence(sqlite3_context* ctx,
-                    StringPool*,
-                    const ColumnView& view,
-                    uint32_t row) {
-  uint32_t index = view.Index(row);
-  if (!view.IsValid(row)) {
-    return sqlite::result::Null(ctx);
-  }
-  sqlite::result::Long(ctx, index);
-}
-
 void ResultNull(sqlite3_context* ctx,
                 StringPool*,
                 const ColumnView&,
@@ -161,27 +99,6 @@
   sqlite::utils::SetError(ctx, "__intrinsic_pipeline: no such column");
 }
 
-PipelineModule::Cursor::ResultFn ReaderFor(const ColumnView& view) {
-  if (view.kind() == ColumnView::Kind::kVariant) {
-    return &ResultVariant;
-  }
-  if (view.kind() == ColumnView::Kind::kSequence) {
-    return &ResultSequence;
-  }
-  core::StorageType type = view.type();
-  if (type.Is<core::Uint32>())
-    return &ResultFlat<uint32_t>;
-  if (type.Is<core::Int32>())
-    return &ResultFlat<int32_t>;
-  if (type.Is<core::Int64>())
-    return &ResultFlat<int64_t>;
-  if (type.Is<core::Double>())
-    return &ResultFlat<double>;
-  if (type.Is<core::String>())
-    return &ResultFlat<StringPool::Id>;
-  PERFETTO_FATAL("Unexpected column type");
-}
-
 // Surfaces the executor's error, if any, once rows stop.
 int CheckStatus(PipelineModule::Cursor* cursor) {
   // status() walks every node so only check it once rows stop.
@@ -416,7 +333,7 @@
   const ColumnView& view = c->rows->batch().column(column.index);
   if (PERFETTO_UNLIKELY(!column.result || view.kind() != column.kind ||
                         view.type().index() != column.type)) {
-    column.result = ReaderFor(view);
+    column.result = ColumnResultFor(view);
     column.kind = view.kind();
     column.type = view.type().index();
   }
diff --git a/src/trace_processor/perfetto_sql/engine/pipeline_module.h b/src/trace_processor/perfetto_sql/engine/pipeline_module.h
index 297e171..21f5770 100644
--- a/src/trace_processor/perfetto_sql/engine/pipeline_module.h
+++ b/src/trace_processor/perfetto_sql/engine/pipeline_module.h
@@ -30,6 +30,7 @@
 #include "src/trace_processor/core/dataframe/dataframe.h"
 #include "src/trace_processor/core/dataframe/runtime_dataframe_builder.h"
 #include "src/trace_processor/core/exec/row_cursor.h"
+#include "src/trace_processor/perfetto_sql/engine/column_results.h"
 #include "src/trace_processor/perfetto_sql/pipeline/logical_plan.h"
 #include "src/trace_processor/perfetto_sql/pipeline/physical_plan.h"
 #include "src/trace_processor/perfetto_sql/pipeline/pipeline_sql.h"
@@ -89,16 +90,12 @@
     Context* context = nullptr;
   };
   struct Cursor : sqlite::Module<PipelineModule>::Cursor {
-    using ResultFn = void (*)(sqlite3_context*,
-                              StringPool*,
-                              const core::exec::ColumnView&,
-                              uint32_t);
     struct ColumnReader {
       static constexpr uint32_t kNoView = std::numeric_limits<uint32_t>::max();
       // In the plan's batches, or kNoView for a column the plan does not
       // output.
       uint32_t index = kNoView;
-      ResultFn result = nullptr;
+      ColumnResultFn result = nullptr;
       // The view `result` was chosen for.
       core::exec::ColumnView::Kind kind{};
       uint32_t type = 0;