From dd33209722784bc5685ea6afc44b0e5222e85ce6 Mon Sep 17 00:00:00 2001 From: JosamHany Date: Sat, 14 Nov 2026 18:47:19 +0200 Subject: [PATCH] GH-55295: Reject negative num_rows in Dataset head --- cpp/src/arrow/dataset/scanner.cc | 4 ++++ python/pyarrow/tests/test_dataset.py | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/cpp/src/arrow/dataset/scanner.cc b/cpp/src/arrow/dataset/scanner.cc index 222e1323d4a8..a14f66bae8b2 100644 --- a/cpp/src/arrow/dataset/scanner.cc +++ b/cpp/src/arrow/dataset/scanner.cc @@ -593,6 +593,10 @@ Result> AsyncScanner::TakeRows(const Array& indices) { } Result> AsyncScanner::Head(int64_t num_rows) { + if (num_rows < 0) { + return Status::Invalid("num_rows must be non-negative"); + } + if (num_rows == 0) { return Table::FromRecordBatches(options()->projected_schema, {}); } diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index e80786cb94f0..418f10fd6abb 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -661,6 +661,19 @@ def test_head(dataset, dataset_reader): result = fragment.head(1024, columns=['i64']).to_pydict() assert result == {'i64': list(range(5))} +# ARROW-#55295: Check for negative num_rows +@pytest.mark.parquet +def test_head_negative_num_rows(dataset): + with pytest.raises(pa.ArrowInvalid, match="num_rows must be non-negative"): + dataset.head(-1) + + with pytest.raises(pa.ArrowInvalid, match="num_rows must be non-negative"): + dataset.scanner().head(-1) + + fragment = next(dataset.get_fragments()) + with pytest.raises(pa.ArrowInvalid, match="num_rows must be non-negative"): + fragment.head(-1) + @pytest.mark.parquet def test_take(dataset, dataset_reader):