fix(filters): honor --strict when rows parameter is provided to first (#19521)

# Description

In `first_helper`, when a `rows` parameter was provided
(`return_single_element == false`), the `--strict` switch (`-s`) was
previously ignored across all input variants (`Value::List`,
`Value::Binary`, `Value::Range`, `QueryPlan`,
`PipelineData::ListStream`, and `PipelineData::ByteStream`), as well as
when `rows == 0`.

This PR updates `first_helper` so that when `--strict` is enabled and
the input is empty, `first` consistently raises
`ShellError::AccessEmptyContent` even if a `rows` count was passed (such
as `[1] | where name == 123 | first -s 1`, `[] | first -s 1`, `0x[] |
first -s 1`, etc.).

# User-facing changes (Release notes)

Fixed an issue where `first --strict` (`-s`) ignored the `--strict` flag
when a `rows` count argument was provided on empty inputs.

# Additional notes

fixes #19506

Signed-off-by: Abdul karim mia <akmia51@gmail.com>
This commit is contained in:
Abdul karim mia
2026-11-19 13:11:39 -06:00
committed by GitHub
parent 8d30d9faa2
commit 3d8a9cc6e0
4 changed files with 212 additions and 17 deletions
+91 -17
View File
@@ -184,7 +184,10 @@ fn first_helper(
// pipe, and sqlite lazy queries can still run. For "take nothing" we only produce an empty
// value: empty binary (and clear pipeline `content_type` for binary) or an empty list, with
// other metadata unchanged.
if rows == 0 {
//
// With `--strict`, `-s 0` still has to look at the first item (one byte, one row, or a
// `LIMIT 1` query) to tell an empty input apart, so it goes on to the main `match`.
if rows == 0 && !strict_mode {
return match input {
PipelineData::Value(val, _) if matches!(&val, Value::Binary { .. }) => Ok(
Value::binary(Vec::new(), val.span()).into_pipeline_data_with_metadata(
@@ -207,6 +210,11 @@ fn first_helper(
};
}
// Take this before `match` consumes the input. An external that fails without
// output then reports its exit code instead of empty content.
#[cfg(feature = "os")]
let exit_status = input.clone_exit_status_future();
match input {
PipelineData::Value(val, _) => {
let span = val.span();
@@ -222,6 +230,8 @@ fn first_helper(
// that users can pipe this through 'default' if they want to.
Ok(Value::nothing(head).into_pipeline_data_with_metadata(input_meta))
}
} else if strict_mode && vals.is_empty() {
Err(ShellError::AccessEmptyContent { span: head })
} else {
let value = if rows >= vals.len() {
Value::list_shared(vals, span)
@@ -245,6 +255,8 @@ fn first_helper(
// that users can pipe this through 'default' if they want to.
Ok(Value::nothing(head).into_pipeline_data_with_metadata(binary_meta))
}
} else if strict_mode && val.is_empty() {
Err(ShellError::AccessEmptyContent { span: head })
} else {
let mut val = val.into_owned();
val.truncate(rows);
@@ -263,6 +275,24 @@ fn first_helper(
// that users can pipe this through 'default' if they want to.
Ok(Value::nothing(head).into_pipeline_data_with_metadata(input_meta))
}
} else if strict_mode {
if let Some(first) = iter.next() {
if rows == 0 {
Ok(Value::list(Vec::new(), head)
.into_pipeline_data_with_metadata(input_meta))
} else {
Ok(std::iter::once(first)
.chain(iter)
.take(rows)
.into_pipeline_data_with_metadata(
span,
signals.clone(),
input_meta,
))
}
} else {
Err(ShellError::AccessEmptyContent { span: head })
}
} else {
Ok(iter.take(rows).into_pipeline_data_with_metadata(
span,
@@ -281,21 +311,28 @@ fn first_helper(
..
} => {
if let Some(plan) = QueryPlan::try_from_any(custom_val.as_any()) {
if return_single_element {
// For single element, limit 1
let plan = plan.with_limit(1);
if return_single_element || strict_mode {
// With `--strict` or single element, we query at least LIMIT 1 to
// verify whether the input is non-empty before returning.
let plan = plan.with_limit(rows.max(1) as i64);
let result = plan.execute(head)?;
let value = result.into_value(head)?;
if let Value::List { vals, .. } = value {
if let Some(val) = vals.into_iter().next() {
Ok(val.into_pipeline_data_with_metadata(input_meta))
} else if strict_mode {
if let Value::List { ref vals, .. } = value {
if strict_mode && vals.is_empty() {
Err(ShellError::AccessEmptyContent { span: head })
} else {
// There are no values, so return nothing instead of an error so
// that users can pipe this through 'default' if they want to.
Ok(Value::nothing(head)
} else if return_single_element {
// Without `--strict` an empty table gives nothing, so it can
// go through `default`.
let val = vals
.first()
.cloned()
.unwrap_or_else(|| Value::nothing(head));
Ok(val.into_pipeline_data_with_metadata(input_meta))
} else if rows == 0 {
Ok(Value::list(Vec::new(), head)
.into_pipeline_data_with_metadata(input_meta))
} else {
Ok(value.into_pipeline_data_with_metadata(input_meta))
}
} else {
Err(ShellError::NushellFailed {
@@ -324,7 +361,7 @@ fn first_helper(
}),
}
}
PipelineData::ListStream(stream, _) => {
PipelineData::ListStream(mut stream, _) => {
if return_single_element {
if let Some(v) = stream.into_iter().next() {
Ok(v.unwrap_error()?
@@ -336,6 +373,23 @@ fn first_helper(
// that users can pipe this through 'default' if they want to.
Ok(Value::nothing(head).into_pipeline_data_with_metadata(input_meta))
}
} else if strict_mode {
if let Some(first) = stream.next_value() {
if rows == 0 {
// The item was read to check for empty input, so its error or `exit` counts.
first.unwrap_error()?;
Ok(Value::list(Vec::new(), head)
.into_pipeline_data_with_metadata(input_meta))
} else {
Ok(PipelineData::list_stream(
stream
.modify(move |iter| std::iter::once(first).chain(iter).take(rows)),
input_meta,
))
}
} else {
Err(ShellError::AccessEmptyContent { span: head })
}
} else {
Ok(PipelineData::list_stream(
stream.modify(|iter| iter.take(rows)),
@@ -348,17 +402,35 @@ fn first_helper(
let span = stream.span();
let metadata = input_meta.map(|m| m.with_content_type(None));
if let Some(mut reader) = stream.reader() {
if return_single_element {
// Take a single byte
if return_single_element || strict_mode {
let mut byte = [0u8];
if reader
.read(&mut byte)
.map_err(|err| ShellErrorBridge::unpack(err, span))?
> 0
{
Ok(Value::int(byte[0] as i64, head)
.into_pipeline_data_with_metadata(metadata))
if return_single_element {
Ok(Value::int(byte[0] as i64, head)
.into_pipeline_data_with_metadata(metadata))
} else if rows == 0 {
Ok(Value::binary(Vec::new(), span)
.into_pipeline_data_with_metadata(metadata))
} else {
Ok(PipelineData::byte_stream(
ByteStream::read(
std::io::Cursor::new(byte).chain(reader).take(rows as u64),
head,
Signals::empty(),
ByteStreamType::Binary,
),
metadata,
))
}
} else {
#[cfg(feature = "os")]
nu_protocol::process::check_exit_status_future(vec![
exit_status.map(|status| status.with_span(span)),
])?;
Err(ShellError::AccessEmptyContent { span: head })
}
} else {
@@ -373,6 +445,8 @@ fn first_helper(
metadata,
))
}
} else if strict_mode {
Err(ShellError::AccessEmptyContent { span: head })
} else {
Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata))
}
@@ -290,3 +290,29 @@ fn open_reports_which_table_failed(
err => Err(err.into()),
}
}
#[test]
fn first_strict_empty_query_plan_errors(playground: Playground) -> Result {
let db = playground.path().join("test.db");
let conn = Connection::open(&db).expect("failed to open db");
conn.execute_batch("CREATE TABLE t (a INT);")
.expect("failed to create tables");
drop(conn);
let mut tester = test().cwd(playground.path());
match tester
.run_with_data::<Value>("open $in | get t | first -s 1", db.as_path())
.expect_shell_error()?
{
ShellError::AccessEmptyContent { .. } => {}
err => panic!("expected AccessEmptyContent, got {err:?}"),
}
match tester
.run_with_data::<Value>("open $in | get t | first -s 0", db.as_path())
.expect_shell_error()?
{
ShellError::AccessEmptyContent { .. } => Ok(()),
err => panic!("expected AccessEmptyContent, got {err:?}"),
}
}
+92
View File
@@ -215,6 +215,83 @@ fn error_on_empty_binary_in_strict_mode() -> Result {
assert_empty_content_diagnostic("0x[] | first --strict")
}
#[test]
fn error_on_empty_inputs_when_rows_given_in_strict_mode() -> Result {
for code in [
"[] | first -s 1",
"[] | first -s 0",
"[1] | where {|x| $x > 1 } | first -s 1",
"[1] | where {|x| $x > 1 } | first -s 0",
"0x[] | first -s 1",
"0x[] | first -s 0",
"1..<1 | first -s 1",
"1..<1 | first -s 0",
] {
assert_empty_content_diagnostic(code)?;
}
let const_err = test()
.run("const x = [] | first --strict 1")
.expect_parse_error()?;
assert_matches!(
const_err,
nu_protocol::ParseError::LabeledError(msg, _, _) if msg.contains("Cannot access empty content")
);
let empty_stream = PipelineData::byte_stream(
nu_protocol::ByteStream::read(
std::io::Cursor::new(Vec::<u8>::new()),
Span::test_data(),
Signals::empty(),
nu_protocol::ByteStreamType::Binary,
),
None,
);
let err = test()
.run_raw_with_data("first --strict 2", empty_stream)
.expect_err("expected empty byte stream with --strict and rows to fail");
assert!(
format!("{err:?}").contains("AccessEmptyContent"),
"expected AccessEmptyContent error, got {err:?}"
);
Ok(())
}
#[test]
fn non_empty_inputs_succeed_with_rows_in_strict_mode() -> Result {
test()
.run("[1 2 3] | first -s 2")
.expect_value_eq(vec![Value::test_int(1), Value::test_int(2)])?;
test()
.run("[1 2 3] | where {|x| $x > 1 } | first -s 1")
.expect_value_eq(vec![Value::test_int(2)])?;
test()
.run("[1 2 3] | where {|x| $x > 1 } | first -s 0")
.expect_value_eq(Vec::<Value>::new())?;
test()
.run("(0x[aa bb cc] | first -s 2) == 0x[aa bb]")
.expect_value_eq(true)?;
test()
.run("1..3 | first -s 2")
.expect_value_eq(vec![Value::test_int(1), Value::test_int(2)])?;
let stream = PipelineData::byte_stream(
nu_protocol::ByteStream::read(
std::io::Cursor::new(vec![0xaa, 0xbb, 0xcc]),
Span::test_data(),
Signals::empty(),
nu_protocol::ByteStreamType::Binary,
),
None,
);
let bytes = test()
.run_raw_with_data("first -s 2", stream)?
.body
.into_value(Span::test_data())?;
assert_eq!(bytes, Value::binary(vec![0xaa, 0xbb], Span::test_data()));
Ok(())
}
fn assert_empty_content_diagnostic(code: &str) -> Result {
test()
.run(code)
@@ -309,3 +386,18 @@ fn first_preserves_pipeline_metadata(#[case] input: InputKind, #[case] code: &st
assert_eq!(expected, out);
Ok(())
}
#[rstest]
#[case::strict_rows("first -s 2")]
#[case::strict_zero("first -s 0")]
#[case::strict("first -s")]
#[case::single("first")]
#[nu_test_support::test]
#[deps(TESTBIN_FAIL)]
fn failed_external_with_no_output_keeps_exit_code(#[case] first: &str) -> Result {
test()
.run(format!(
"try {{ fail 42 | {first} }} catch {{|e| $e.exit_code }}"
))
.expect_value_eq(42)
}
@@ -119,6 +119,8 @@ const RECOVER: &str = "each {|c| try { $c | ignore; $c } catch { 'caught' } }";
#[case::to_text_binary_chunks("failing 2 | to text | into binary | each { $in }")]
#[case::to_text_bytes_split("failing 2 | to text | into binary | bytes split 0x[0a]")]
#[case::to_text_binary_first("failing 1 | to text | into binary | first")]
#[case::first_strict_binary("failing 1 | to text | into binary | first -s 2")]
#[case::first_strict_zero("failing 1 | first -s 0")]
#[case::to_text_binary_last("failing 2 | to text | into binary | last 1")]
#[case::to_text_binary_length("failing 2 | to text | into binary | length")]
#[case::to_text_binary_chunks_n("failing 2 | to text | into binary | chunks 2")]
@@ -308,6 +310,7 @@ fn describe_still_shows_an_error_item() -> Result {
#[case::window_gap_tail_after_error(
"[1 2] | each {|x| if $x == 1 { error make {msg: boom} } else { exit 7 } } | window 3 --stride 4"
)]
#[case::first_strict_binary("exiting 1 | to text | into binary | first -s 2")]
fn exit_is_not_lost(#[case] pipeline: &str) -> Result {
let err = test()
.run(format!("{STREAMS}\n{pipeline}"))