Skip to content

feat(tac): add tac with -s and -b - #287

Open
ferdingler wants to merge 3 commits into
strands-agents:mainfrom
ferdingler:feat/tac
Open

ferdingler wants to merge 3 commits into
strands-agents:mainfrom
ferdingler:feat/tac

Conversation

@ferdingler

Copy link
Copy Markdown
Collaborator

Description

There's no tac in the shell, so an agent that wants a log or a file newest-line-first gets command not found.

This adds tac. It reverses each file in turn, reads stdin when there are no files or for -, and supports -s for a custom separator string and -b to attach it before each record instead of after. A missing file is reported and skipped, and the exit status is 1, like GNU. Regex separators (-r) are left out.

I compared it byte for byte against GNU tac 8.32 on this machine, including an unterminated last line, empty input, multi-character separators and a missing file, and stdout and exit status all match. I added a recorded differential case and integration tests. The full Rust suite passes. I didn't run the Python or Node suites since the bindings are unchanged. This touches the same command lists as the other new-command PRs for #207, so whichever lands second will need a small rebase.

Related Issues

Part of #207

Documentation PR

Type of Change

New feature

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce new warnings.

  • I ran the relevant test suites for the bindings I touched (cargo test --workspace --all-targets, pytest tests/python, npm test)
  • If I touched Rust, I ran cargo fmt and cargo clippy

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@ferdingler
ferdingler requested a review from a team as a code owner November 13, 2026 05:18
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent Please review this PR

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested. The happy paths match GNU tac byte for byte, but a second missing file makes tac exit early and silently drop the rest of its output. The fix is small; I left it inline, and built and re-tested it.

  • 🔴 tac.rs:62,70: stdin and stderr are taken inside the per-file loop, and each fd can only be taken once. tac nope1 f nope2 f prints f once and loses the nope2 error. tac - - fails with bad fd 0 and exits 1, where GNU exits 0.
  • 🟡 tac.rs:67: piped stdin is read with no size cap. sed and jq use read_to_end_limited for this.
  • Tests: tac_reports_a_missing_file_and_continues only has one missing file, so it can't catch the 🔴. Adding tac /tmp/nope /tmp/nope2 /tmp/t1 and printf 'a\n' | tac - - would.

CI is green at 7569308.

What I verified
  • Head 756930829c. cargo test --test shell_integration --test differential: 1969 + 1 passed. All 6 new tac_* tests pass, and the recorded differential case matches GNU tac 9.1.
  • I ran about 27 hand cases plus random fuzzing against /usr/bin/tac (stdin, -, unterminated last line, empty input, -b, multi-byte -s, -bs,, --separator=, a directory operand, -r, --, broken pipe, a 20 MB input with a 1000-byte separator). Everything matched except the items here.
  • I applied the suggested fix locally and rebuilt. tac nope1 f nope2 f now prints 2 1 2 1 with both errors, and tac - - exits 0, both as in GNU. The repro log is uploaded as proof of work (strands-agents/shell/pr/287/tac-repro.log).
Appendix: non-blocking (3)
  • ⚪ tac.rs:18-29: the scan runs left to right, so a separator that overlaps itself splits differently from GNU, which scans right to left. Example: printf 'xaaay' | tac -s aa gives ayxaa here and yxaaa in GNU. It also shows up with -s $'\n\n' on uneven blank lines. Fix: scan from the end and step back sep.len() after each match. The reviewer pass checked this approach against GNU on 3000 random cases with no differences.
  • Pre-existing, filed #299: the shell drops a double-quoted empty word, so tac -s "" f reports missing argument. This is not caused by this PR.
  • Pre-existing, not filed: a non-UTF-8 -s value reaches the command as U+FFFD. Every command takes args: &[String] and grep behaves the same way, so this is a shell-wide argv design question, not a tac bug.

Comment thread src/commands/tac.rs
Comment on lines +56 to +71
let mut w = io::stdout()?;
let mut status = 0;
for path in &files {
let mut data = Vec::new();
let read = async {
let mut reader: Box<dyn tokio::io::AsyncRead + Unpin + Send> = if path == "-" {
Box::new(io::stdin()?)
} else {
let fd = io::open(os, path, OpenFlags::read()).await?;
Box::new(io::take_reader(fd)?)
};
reader.read_to_end(&mut data).await
};
if let Err(e) = read.await {
let mut ew = io::stderr()?;
wprintln!(ew, "tac: {path}: {e}")?;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A second missing file (or a second -) makes tac exit early and silently drop the remaining output. io::stderr() and io::stdin() remove the fd from the table (os.rs:665-673). The second call returns bad fd, and the ? exits cmd_tac.

$ tac nope1 f nope2 f   # GNU: 2 1 2 1, two errors
2
1
tac: nope1: ...          # second f and nope2 error missing

An agent hits this when it runs tac over a guessed list of log files. grep.rs:697 handles this by taking stderr once. A second - reads empty, as in GNU.

Suggestion (built and re-tested; both cases now match GNU):

Suggested change
let mut w = io::stdout()?;
let mut status = 0;
for path in &files {
let mut data = Vec::new();
let read = async {
let mut reader: Box<dyn tokio::io::AsyncRead + Unpin + Send> = if path == "-" {
Box::new(io::stdin()?)
} else {
let fd = io::open(os, path, OpenFlags::read()).await?;
Box::new(io::take_reader(fd)?)
};
reader.read_to_end(&mut data).await
};
if let Err(e) = read.await {
let mut ew = io::stderr()?;
wprintln!(ew, "tac: {path}: {e}")?;
let mut w = io::stdout()?;
// stdin and stderr can each be taken only once per process.
let mut ew = io::stderr()?;
let mut stdin_taken = false;
let mut status = 0;
for path in &files {
let mut data = Vec::new();
let read = async {
let mut reader: Box<dyn tokio::io::AsyncRead + Unpin + Send> = if path == "-" {
if std::mem::replace(&mut stdin_taken, true) {
Box::new(tokio::io::empty())
} else {
Box::new(io::stdin()?)
}
} else {
let fd = io::open(os, path, OpenFlags::read()).await?;
Box::new(io::take_reader(fd)?)
};
reader.read_to_end(&mut data).await
};
if let Err(e) = read.await {
wprintln!(ew, "tac: {path}: {e}")?;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7cbd91a and 2245ca0. Stderr is now taken once, on the first error, rather than up front, so an error later in the run can still be reported by the shell. A second - reads nothing, like GNU. The test now has two missing files, and there's a new one for - -. I checked that the two-missing-files test fails on the old code.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified at 2245ca0: both errors are reported, all files are printed, and tac - - / tac - f - match GNU.

Comment thread src/commands/tac.rs
let fd = io::open(os, path, OpenFlags::read()).await?;
Box::new(io::take_reader(fd)?)
};
reader.read_to_end(&mut data).await

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Piped stdin is read into memory with no cap, then copied again into reversed. max_file_size bounds file operands, but nothing bounds a pipe. In the reviewer pass, cat a×40 | tac | wc -c (93 MB) peaked at 292 MB RSS, against 21 MB without tac. sed.rs:518 and jq.rs:260 cap reads with crate::os::read_to_end_limited(&mut r, io::with_process(|p| p.max_output)).

sort.rs has the same uncapped read, so I'm not blocking on this. Question: should stdin be capped at max_output here, as in sed/jq? Writing each record straight to w instead of collecting reversed would also avoid holding a second full copy.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm leaving the size cap off. Unlike sed and jq, tac gives back exactly as many bytes as it reads, and tac big.log > out is a fair thing to run on a file bigger than the output limit. Files are already bounded by the file size limit, and a pipe by the timeout. sort reads the same way. I did drop the second full copy in 2245ca0: records are now written out in chunks.

@ferdingler

Copy link
Copy Markdown
Collaborator Author

Thanks. Pushed fixes for the two blocking items and the overlap nit (replies inline). The separator is now searched from the end like GNU, so printf 'xaaay' | tac -s aa prints yxaaa, and I added a test for it. I compared about 25 cases against GNU tac again and they all match. The two pre-existing items (empty quoted words, non-UTF-8 argv) are outside this PR.

@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent Please review this PR

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve. All three fixes hold up at 2245ca0.

  • 🔴 Missing files and a second -: fixed. tac nope1 f nope2 f now prints 2 1 2 1 and reports both errors, and tac - f - matches GNU.
  • 🟡 Size cap: withdrawn. Your reasoning holds, since tac writes out exactly as many bytes as it reads. Writing in chunks also removes the second full copy.
  • ⚪ Overlapping separator: fixed. The scan now runs from the end, as in GNU.

CI is green.

What I verified
  • cargo test --test shell_integration --test differential at 2245ca0: 1971 + 1 passed, including all 8 tac_* tests.
  • I ran a differential fuzz against GNU tac 9.1: 600 random inputs, with separators \n, aa, aaa, aba, abab, \n\n, , and others, half of them with -b. There were 0 differences.
  • A 30,000-line file (larger than one 8 KiB output chunk) reversed byte-identical to GNU.
  • Scripts and logs are uploaded under strands-agents/shell/pr/287/followup-*.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants