Skip to content

fix(du): count a hard-linked file once, not once per link - #19020

Closed
victorhooi wants to merge 1 commit into
nushell:mainfrom
victorhooi:du-count-hard-links-once
Closed

victorhooi wants to merge 1 commit into
nushell:mainfrom
victorhooi:du-count-hard-links-once

Conversation

@victorhooi

@victorhooi victorhooi commented Sep 13, 2026 •

Copy link
Copy Markdown

Description

Disclaimer: I stole/borrowed a lot of the approach and terminology from the GNU coreutils du.c and di-set.h/di-set.c =), and also used AI to assist with the Rust coding.

nushell's du summed every directory entry it walked, so a file reachable with several hard links was added once per link, which inflated the size. Both apparent and physical columns over-reported as a result.

This is different to the POSIX standard, and the GNU coreutils, and BSD implementations of du.

We keep a set of device-inode pairs for each file whose sizes have already been counted, and count a file only the first time its pair is inserted. The device-inode 2-tuple uniquely identifies each file across filesystems/mount points.

I also added a --count-links argument to opt back in to the old behaviour. GNU and BSD also offer something similar - their short form is -l, which is taken in nushell by --long, so I've only used the long-form flag here.

Directories aren't themselves recorded, so an operand naming a directory already walked under an earlier operand still yields a row (where GNU yields none). Every file inside it is counted once regardless, so only the directory entries' own bytes differ. Left for a follow-up rather than folded in here.

Fixes #19019

User-facing changes (Release notes)

  • Fixed du counting a file once per hard link rather than once per file. Both the apparent and physical columns previously over-reported any tree containing hard links. du now counts each file once per invocation, matching GNU and BSD du.
  • Added du --count-links, which restores the previous behaviour of counting a file once per link.

Additional notes

Fixes #19019

`du` summed every directory entry it walked, so a file reachable through
several hard links was added once per link. Both the `apparent` and
`physical` columns over-reported as a result. `physical` is the clearer
defect: it is computed from allocated blocks and labelled as disk usage,
but claimed space that is not consumed. On a shared Rust
`CARGO_TARGET_DIR`, where rustc hard-links reused codegen-unit objects
out of the incremental cache into `deps/`, it read 179.1 GB against the
68.86 GB actually on disk — 2.6x, over 256,142 paths resolving to 87,142
distinct files.

Every other `du` counts a file once. POSIX requires it: "A file that
occurs multiple times shall be counted and written for only one entry,
even if the occurrences are under different file operands." GNU
documents the opt-out as `-l, --count-links`, "count sizes many times if
hard linked", and BSD's `-l` says the same. Counting once is the default
everywhere; nushell had no way to get it at all. Previously raised as
without a decision.

Keep a set of device-inode pairs for the files whose sizes have already
been counted, and count a file the first time its pair is inserted. GNU
keeps the same structure, as gnulib's `di_set`. POSIX defines the pair:
"A file identity is uniquely determined by the combination of st_dev and
st_ino." The device number belongs in it because file serial numbers are
unique only within one filesystem, so a walk spanning two mounts could
otherwise treat two different files as one. Windows has the same pair as
`(volume_serial_number(), file_index())`. Neither costs an extra
syscall, since `FileInfo::new` already calls `fs::metadata` and the
Windows accessors return `None` only for `DirEntry::metadata`.

The set spans the whole command rather than one path operand, which is
what the POSIX "different file operands" clause asks for, and which
uutils/coreutils#10241 reports as a bug in that implementation. Because
`du_for_one_pattern` returns a lazy iterator outliving `run`, the set is
shared by ownership through an `Arc` rather than borrowed, and the
`Mutex` is what keeps that iterator `Send`. It is locked once per path
operand, never once per file, and released before the iterator pauses.

Record every file rather than only those with several links. POSIX does
permit the narrower rule, but it holds only while a single operand is
walked on its own, and `du` with no arguments already expands to many
top-level paths, so the narrow rule would be wrong in the most ordinary
invocation there is. GNU arrives at the same place from the other
direction, switching its own shortcut off whenever "there are multiple
arguments, or if following non-command-line symlinks, because in either
case a file with just one hard link might be seen more than once".

Both size columns count once, which keeps two distinctions orthogonal:
apparent-versus-physical is about how many bytes one file accounts for,
while link counting is about how many times a file appears. Folding them
into one column would lose the useful "unique bytes in this tree"
reading, and GNU deduplicates for `--apparent-size` too.

Add `--count-links` to opt back out. GNU and BSD both spell the short
form `-l`, which is already `--long` here and across `ls` and `ps`, so
this one is long-only.

Directories are not themselves recorded, so an operand naming a
directory already walked under an earlier operand still yields a row
where GNU yields none. Every file inside it is counted once regardless,
so only the directory entries' own bytes differ. Left for a follow-up
rather than folded in here.

Fixes nushell#19019
@victorhooi

Copy link
Copy Markdown
Author

Also - I did actually test my code =), aha - using it on the same directory that triggered this whole rabbit hole for me:

let patched = ($env.CARGO_TARGET_DIR | path join "debug" "nu")

󰀵 foobar in nushell on  du-count-hard-links-once [!] via 🦀
✦ ❯ ^$patched -c 'du ~/.cache/cargo-target/debug'
╭───┬─────────────────────────────────────────────┬──────────┬──────────╮
│ # │                    path                     │ apparent │ physical │
├───┼─────────────────────────────────────────────┼──────────┼──────────┤
│ 0 │ /Users/victorhooi/.cache/cargo-target/debug │  68.6 GB │  68.8 GB │
╰───┴─────────────────────────────────────────────┴──────────┴──────────╯

󰀵 foobar in nushell on  du-count-hard-links-once [!] via 🦀 took 9s
✦ ❯ du ~/.cache/cargo-target/debug
╭───┬─────────────────────────────────────────────┬──────────┬──────────╮
│ # │                    path                     │ apparent │ physical │
├───┼─────────────────────────────────────────────┼──────────┼──────────┤
│ 0 │ /Users/victorhooi/.cache/cargo-target/debug │ 178.6 GB │ 179.1 GB │
╰───┴─────────────────────────────────────────────┴──────────┴──────────╯

󰀵 foobar in nushell on  du-count-hard-links-once [!] via 🦀
✦ ❯ ^du -sh ~/.cache/cargo-target/debug
 64G    /Users/victorhooi/.cache/cargo-target/debug

@fdncred

fdncred commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

It's unfortunate but I don't believe we can use the PR if since it came from GNU coreutils. They are GPL 3.0 licensed which is not compatible with our MIT license.

Maybe we could just use uutils/coreutils du crate uu_du like we do with other uutils/coreutils commands.

@fdncred fdncred closed this Sep 13, 2026
@victorhooi

Copy link
Copy Markdown
Author

I think there's been a mixup here - and honestly that's on my wording in the description (I was being self-deprecating), so let me be precise.

No code was copied or ported. The Rust in this PR was written against nushell's own crates/nu-command/src/platform/dir_info.rs. What I took from coreutils was the approach - keep a set keyed on the device-inode pair, and count a file the first time its pair goes into the set - plus their vocabulary in the comments ("device-inode pair"), specifically so it'd be obvious I wasn't inventing new behaviour (insert meme of Mugatu from Zoolander...)

And that approach isn't coreutils' invention eiher. It's what POSIX specifies, which I linked in #19019: "A file that occurs multiple times shall be counted and written for only one entry, even if the occurrences are under different file operands." The implementation is about fifty lines — a HashSet<(u64, u64)> and an insert whose bool return tells you whether the pair was new. There isn't really a second way to write that in Rust.

If the coreutils references in the comments are the sticking point, I'm glad to strip them and cite only POSIX — happy to push that now if it helps.

On uu_du — I did look at it, and I don't think it fits here, for two reasons:

  1. It has no library API. uu_du exposes uumain(args: impl uucore::Args) and uu_app() -> Command - a CLI entry point that parses argv and prints text to stdout. The uutils crates nushell already depends on (uu_cp, uu_mv, uu_mkdir, uu_mktemp, uu_touch, uu_uname, uu_whoami) are all imperative side-effecting commands, where "run it, report errors" is the whole contract. In constrast du is a data-producing command, and the entire value of nushell's du is the structured {path, apparent, physical} table you can pipe into sort-by or where. (Side-note - that's the whole reason I first got into nushell, the rich structured data thing). Getting that out of uu_du would mean scraping its stdout, or upstreaming a library API to uutils first.

  2. It wouldn't fully fix this anyway — uu_du has the cross-operand version of this same bug open as du: double-counting hard links when multiple arguments specified uutils/coreutils#10241, which is one of the cases this PR handles.

Happy to go whichever way you'd prefer. I just wanted to clear up the licensing question first, since that's the actual blocker. =)

victorhooi added a commit to victorhooi/nushell that referenced this pull request Sep 14, 2026
Three doc comments in dir_info.rs quoted a sentence each from GNU
du.c and gnulib's di-set.c as citations for the device-inode set.
Those were the only words of GPL origin in the change, and the
review on nushell#19020 turned on provenance, so they go: the FileId doc
now attributes the identity rule to <sys/stat.h>, where it in fact
lives, rather than to POSIX at large; the file_id doc cites the du
RATIONALE sentence that requires tracking one-link files under
multiple operands, which says what the du.c comment said and is
the authority du.c was implementing; and insert_into names
HashSet::insert as its contract, which is what it is.

No code changes. The remaining mentions of GNU and BSD du describe
the observable behaviour behind --count-links and are kept, since
they are why the flag has that name.
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.

du counts hard-linked files once per path, so both size columns over-report

2 participants