tp: end a run at the batch its source knows is last

**Why**

A SQLite join runs the inner table's plan once per outer row, and each
run usually returns one batch of a row or two. After reading it, the
cursor still pulled again through the pipeline and the source to learn
the run was over, then read the status. That round trip was a large
part of the executor's extra cost per lookup next to the interpreter,
which only bumps an index.

**Changes**

- A `RowBatch` can be marked as the last of its run. The dataframe
  readers mark the batch which reads their last row.
- `RowCursor` ends the run after a marked batch instead of pulling
  again.
- A pipeline whose transforms empty a marked batch ends the run instead
  of pulling the next one.
- `Filter` leaves the selection alone when it drops no rows.

**Testing**

- New `SinkTest.LastBatchEndsTheRun` and
  `SinkTest.EmptiedLastBatchEndsTheRun`.
- On `_sched_with_thread_state_join` this removes about a third of the
  extra instructions the executor ran over the interpreter.
- `perfetto_unittests` and all diff tests pass.
diff --git a/src/trace_processor/core/exec/dataframe_windows.h b/src/trace_processor/core/exec/dataframe_windows.h
index b96b0b7..49332df 100644
--- a/src/trace_processor/core/exec/dataframe_windows.h
+++ b/src/trace_processor/core/exec/dataframe_windows.h
@@ -98,6 +98,7 @@
     uint32_t count = std::min(kMaxBatchRows, range_.e - next_);
     windows_.Fill(next_, count, out);
     next_ += count;
+    out.set_last(next_ == range_.e);
     return true;
   }
 
@@ -143,6 +144,7 @@
         first,
         base::Span<const uint32_t>(offsets_.data(), offsets_.data() + count),
         out);
+    out.set_last(next_ == end_);
     return true;
   }
 
diff --git a/src/trace_processor/core/exec/filter.cc b/src/trace_processor/core/exec/filter.cc
index 75b2fad..f73fbfb 100644
--- a/src/trace_processor/core/exec/filter.cc
+++ b/src/trace_processor/core/exec/filter.cc
@@ -411,7 +411,8 @@
                    s.sparse_values.data(),
                    s.globs.empty() ? nullptr : &s.globs[i], r);
   }
-  if (r.contiguous && r.count == selection.size()) {
+  // The rows kept are in order, so as many as before are the same rows.
+  if (r.count == selection.size()) {
     return true;
   }
   Materialize(r);
diff --git a/src/trace_processor/core/exec/operator_unittest.cc b/src/trace_processor/core/exec/operator_unittest.cc
index 9c88a58..5f0b3c5 100644
--- a/src/trace_processor/core/exec/operator_unittest.cc
+++ b/src/trace_processor/core/exec/operator_unittest.cc
@@ -200,6 +200,89 @@
   EXPECT_THAT(read_computed, ElementsAre(90, 91));
 }
 
+// Emits `rows` rows in one batch which it marks last, counting its pulls.
+class LastBatchSource final : public Source {
+ public:
+  static constexpr char kType = 0;
+  const void* type() const override { return &kType; }
+
+  explicit LastBatchSource(uint32_t rows) : rows_(rows) {}
+
+  std::unique_ptr<OperatorState> MakeState(Context&) const override {
+    return std::make_unique<State>();
+  }
+  void Rewind(OperatorState& state) const override {
+    state.Cast<State>().emitted = false;
+  }
+  bool GetData(RowBatch& out, OperatorState& state) const override {
+    ++pulls;
+    State& s = state.Cast<State>();
+    if (s.emitted) {
+      return false;
+    }
+    out.Reset();
+    out.AddBorrowedColumn(
+        ColumnView::Reference(StorageType{Id{}}, nullptr, nullptr));
+    out.SetRowCount(rows_);
+    out.set_last(true);
+    s.emitted = true;
+    return true;
+  }
+
+  mutable uint32_t pulls = 0;
+
+ private:
+  struct State : OperatorState {
+    bool emitted = false;
+  };
+  uint32_t rows_;
+};
+
+// Drops every row.
+class DropAll final : public Transform {
+ public:
+  static constexpr char kType = 0;
+  const void* type() const override { return &kType; }
+  void DescribeColumns(StepColumns*) const override {}
+  std::unique_ptr<OperatorState> MakeState(Context&) const override {
+    return std::make_unique<OperatorState>();
+  }
+  bool Process(RowBatch& batch, OperatorState&) const override {
+    batch.mutable_selection().KeepRows({});
+    return true;
+  }
+};
+
+// Once a source marks a batch last, the run ends when it is read, with no
+// pull to find there is nothing more.
+TEST(SinkTest, LastBatchEndsTheRun) {
+  LastBatchSource source(2);
+  Pipeline pipeline(source, {});
+  RowCursor cursor(pipeline);
+  for (uint32_t run = 0; run < 2; ++run) {
+    std::vector<uint32_t> rows;
+    for (cursor.Open(); !cursor.eof(); cursor.Next()) {
+      rows.push_back(cursor.Value<uint32_t>(0));
+    }
+    EXPECT_THAT(rows, ElementsAre(0, 1));
+    EXPECT_TRUE(cursor.status().ok());
+  }
+  EXPECT_EQ(source.pulls, 2u);
+}
+
+// A last batch which the transforms empty ends the run too.
+TEST(SinkTest, EmptiedLastBatchEndsTheRun) {
+  LastBatchSource source(2);
+  std::vector<Pipeline::Step> steps;
+  steps.push_back(std::make_unique<DropAll>());
+  Pipeline pipeline(source, std::move(steps));
+  RowCursor cursor(pipeline);
+  EXPECT_FALSE(cursor.Open());
+  EXPECT_TRUE(cursor.status().ok());
+  EXPECT_FALSE(cursor.Open());
+  EXPECT_EQ(source.pulls, 2u);
+}
+
 // A cursor is at eof until it is opened. Once it reports eof, advancing again
 // must still report eof.
 TEST(SinkTest, EofStaysEof) {
diff --git a/src/trace_processor/core/exec/pipeline.cc b/src/trace_processor/core/exec/pipeline.cc
index be97fde..0ce706e 100644
--- a/src/trace_processor/core/exec/pipeline.cc
+++ b/src/trace_processor/core/exec/pipeline.cc
@@ -155,7 +155,7 @@
     }
     // A batch with no rows left has nothing for later transforms to do.
     if (PERFETTO_UNLIKELY(!batch->size())) {
-      return NextSlow(s);
+      return EmptyBatch(*batch, s);
     }
   }
   return batch;
@@ -198,12 +198,21 @@
     }
     // A batch with no rows left has nothing for later transforms to do.
     if (PERFETTO_UNLIKELY(!batch->size())) {
-      return NextSlow(s);
+      return EmptyBatch(*batch, s);
     }
   }
   return batch;
 }
 
+PERFETTO_NO_INLINE RowBatch* Pipeline::EmptyBatch(const RowBatch& batch,
+                                                  State& s) const {
+  if (batch.last()) {
+    SourceDone(s);
+    return nullptr;
+  }
+  return NextSlow(s);
+}
+
 PERFETTO_NO_INLINE RowBatch* Pipeline::NextSlow(State& s) const {
   auto last = static_cast<uint32_t>(segments_.size() - 1);
   RowBatch* batch = SegmentNext(last, s.output, s);
diff --git a/src/trace_processor/core/exec/pipeline.h b/src/trace_processor/core/exec/pipeline.h
index 828e2a0..ea532bb 100644
--- a/src/trace_processor/core/exec/pipeline.h
+++ b/src/trace_processor/core/exec/pipeline.h
@@ -149,6 +149,9 @@
 
   // Pulling batches.
   RowBatch* NextSlow(State&) const;
+  // Continues past a batch the transforms emptied, ending the run if the
+  // source marked it last.
+  RowBatch* EmptyBatch(const RowBatch& batch, State& s) const;
   // The next non-empty batch of `segment`, after its transforms.
   RowBatch* SegmentNext(uint32_t segment, RowBatch& scratch, State&) const;
   RowBatch* PullSlow(uint32_t segment, RowBatch& scratch, State&) const;
diff --git a/src/trace_processor/core/exec/row_batch.cc b/src/trace_processor/core/exec/row_batch.cc
index c0c0ce1..c48da42 100644
--- a/src/trace_processor/core/exec/row_batch.cc
+++ b/src/trace_processor/core/exec/row_batch.cc
@@ -49,6 +49,7 @@
   own_buffers_.assign(other.buffers_, other.buffers_ + other.buffer_count_);
   Repoint();
   selection_.CopyFrom(other.selection_);
+  last_ = other.last_;
 }
 
 void RowBatch::Project(const RowBatch& other,
@@ -58,6 +59,7 @@
     AddColumn(other.column(column), other.buffer(column));
   }
   selection_.CopyFrom(other.selection_);
+  last_ = other.last_;
 }
 
 void RowBatch::AddColumn(const ColumnView& view, ColumnBuffer buffer) {
@@ -81,6 +83,7 @@
   own_buffers_.clear();
   Repoint();
   selection_.Reset(0);
+  last_ = false;
 }
 
 void RowBatch::Own() {
diff --git a/src/trace_processor/core/exec/row_batch.h b/src/trace_processor/core/exec/row_batch.h
index 3a54202..f097276 100644
--- a/src/trace_processor/core/exec/row_batch.h
+++ b/src/trace_processor/core/exec/row_batch.h
@@ -131,6 +131,11 @@
   // Removes every column and row.
   void Reset();
 
+  // Whether the run has no batch after this one. Only a source which knows
+  // marks it, so a batch not marked may still be the last.
+  bool last() const { return last_; }
+  void set_last(bool last) { last_ = last; }
+
  private:
   static ColumnView NullView(StorageType type, const ColumnBuffer& nulls) {
     // An Id column has no storage for nulls, so use Uint32, which holds the
@@ -173,6 +178,7 @@
   const ColumnBuffer* buffers_ = nullptr;
   uint32_t buffer_count_ = 0;
   bool owned_ = true;
+  bool last_ = false;
   std::vector<ColumnView> own_columns_;
   std::vector<ColumnBuffer> own_buffers_;
   Selection selection_;
diff --git a/src/trace_processor/core/exec/row_cursor.h b/src/trace_processor/core/exec/row_cursor.h
index ff5135c..ac2635a 100644
--- a/src/trace_processor/core/exec/row_cursor.h
+++ b/src/trace_processor/core/exec/row_cursor.h
@@ -54,7 +54,7 @@
       return false;
     }
     size_ = batch_->size();
-    return PERFETTO_LIKELY(size_) || Pull();
+    return PERFETTO_LIKELY(size_) || (!batch_->last() && Pull());
   }
 
   // Moves to the next row, pulling a new batch if this one is exhausted. At
@@ -63,7 +63,7 @@
     if (index_ == size_) {
       return false;
     }
-    return ++index_ != size_ || Pull();
+    return ++index_ != size_ || (!batch_->last() && Pull());
   }
 
   bool eof() const { return index_ == size_; }