rcp-tools-common 0.41.0

Internal library for RCP file operation tools - shared utilities and core operations (not intended for direct use)
Documentation

RCP Tools — Fast file operations for Linux. Explore the tools and performance reports.

RCP TOOLS

This repo contains tools to efficiently copy, remove and link large filesets, both locally and across remote hosts.

Website · Performance reports · Installation

Build status Chaos Tests Crates.io License: MIT Documentation Radicle

Demo

  • rcp is for copying files; similar to cp but generally MUCH faster when dealing with large filesets.

    Supports both local and remote copying using host:/path syntax (similar to scp).

    Inspired by tools like dsync(1) and pcp(2).

  • rrm is for removing large filesets.

  • rchm is for recursively changing permissions and ownership of large filesets; a fast replacement for dchmod(3).

  • rlink allows hard-linking filesets with optional update path; typically used for hard-linking datasets with a delta.

  • rcmp tool is for comparing filesets.

  • filegen tool generates sample filesets, useful for testing.

Benchmarks

The performance report compares rcp with dcp, GNU cp, and rsync across Lustre, Weka, NFS, XFS, and ZFS, remote transfers, and a Linux source tree. It includes default settings, concurrency sweeps, SVG figures, and the complete measurement evidence. See RCP reports for the hosted report index, or browse the reports in this repository, including the performance report source.

For contributors running measurements, see the benchmarking guide for datasets, measurement rules, CI history, and manual commands.

Documentation

API documentation for the command-line tools is available on docs.rs:

For contributors: Internal library crates used by the tools above:

Design and reference documents (in the docs/ directory):

Examples

Basic local copy with progress-bar and summary at the end:

> rcp <foo> <bar> --progress --summary

Copy while preserving metadata, overwrite/update destination if it already exists:

> rcp <foo> <bar> --preserve-settings=all --progress --summary --overwrite

all covers uid, gid, timestamps and the full mode, but not POSIX ACLs -- detecting an ACL costs an extra syscall on every entry, so it is opt-in. Use all+acl where a source ACL is security-relevant:

> rcp <foo> <bar> --preserve-settings=all+acl --progress --summary --overwrite

See POSIX ACLs for the model, the measured costs, and the two ways a copy can end up more permissive than its source.

Remote copy from one host to another:

> rcp user@host1:/path/to/source user@host2:/path/to/dest --progress --summary

Copies files from host1 to host2. The rcpd process is automatically started on both hosts via SSH.

Copy from remote host to local machine:

> rcp host:/remote/path /local/path --progress --summary

Copy from local machine to remote host and preserve metadata:

> rcp /local/path host:/remote/path --progress --summary --preserve-settings=all

(all+acl works the same way for a remote copy; the ACL probe runs on the source host.)

Remote copy with automatic rcpd deployment:

> rcp /local/data remote-host:/backup --auto-deploy-rcpd --progress

Automatically deploys rcpd to the remote host if not already installed. Useful for dynamic infrastructure, development environments, or when rcpd is not pre-installed on remote hosts.

Log tool output to a file while using progress bar:

> rcp <foo> <bar> --progress --summary > copy.log

Progress bar is sent to stderr while log messages go to stdout. This allows us to pipe stdout to a file to preserve the tool output while still viewing the interactive progress bar. This works for all RCP tools.

Remove a path recursively:

> rrm <bar> --progress --summary

Recursively change group and permissions:

# join group 'data'; add group rwx + setgid to dirs, group rw to files
> rchm --group data --mode "f:g+rw d:g+rwxs" <path> --progress --summary

# dchmod-style: one mode for everything (bare value, no type prefix)
> rchm --mode g+rwX <path> --progress

--mode, --group and --owner take a per-type DSL: a bare value applies to all applicable types, f:/d:/l: prefixes target one. See Permissions and ownership (rchm) for the full rules and Security for privileged use (sudo, --no-setid).

Hard-link contents of one path to another:

> rlink <foo> <bar> --progress --summary

Roughly equivalent to: cp -p --link <foo> <bar>.

Hard-link contents of <foo> to <baz> if they are identical to <bar>:

> rlink <foo> --update <bar> <baz> --update-exclusive --progress --summary

Using --update-exclusive means that if a file is present in <foo> but not in <bar> it will be ignored. Roughly equivalent to: rsync -a --link-dest=<foo> <bar> <baz>.

Control which metadata is preserved with --preserve-settings:

# preserve everything except POSIX ACLs (uid, gid, time, full mode)
> rlink <foo> <bar> --preserve-settings=all

# ...and POSIX ACLs too
> rlink <foo> <bar> --preserve-settings=all+acl

# preserve nothing (directories get default mode, no uid/gid/time)
> rlink <foo> <bar> --preserve-settings=none

# custom: preserve uid, gid, and time on files and dirs
> rlink <foo> <bar> --preserve-settings="f:uid,gid,time,0777 d:uid,gid,time,0777 l:uid,gid,time"

# custom, including ACLs on files and directories
> rlink <foo> <bar> --preserve-settings="f:uid,gid,time,acl,7777 d:uid,gid,time,acl,7777 l:uid,gid,time"

all does not preserve POSIX ACLs. Detecting an ACL costs an extra syscall on every entry -- there is no bit in stat for it -- so it is opt-in via the +acl preset modifier or the per-type acl attribute. Two combinations are rejected at parse time rather than silently ignored: l:acl (the kernel has no symlink ACL) and acl alongside a mode mask that narrows the rwx bits (an ACL is the permission state, so the two contradict each other). See POSIX ACLs for the model, the measured costs, and the two ways a copy can end up more permissive than its source.

Hard-linked files always share metadata with their source via the inode -- preserve settings affect directories and symlinks in all modes, and additionally files that are copied (not linked) during --update operations. By default rlink uses --preserve-settings=all.

When using --update with --preserve-settings that does not cover all compared attributes (e.g. --preserve-settings=none while --update-compare=size,mtime), rlink will error to prevent silent data integrity issues. Use --allow-lossy-update to override.

Compare <foo> vs. <bar>:

# differences are printed to stdout by default
> rcmp <foo> <bar> --progress --summary

# use --log to write differences to a file instead
> rcmp <foo> <bar> --progress --summary --log compare.log

# use --quiet to suppress stdout output (exit code only)
> rcmp <foo> <bar> --quiet

# --quiet with --log: silent stdout but differences still written to file
> rcmp <foo> <bar> --quiet --log compare.log

Installation

RCP supports Linux on x86_64 and AArch64. Musl is the primary build, test, and distribution target; CI additionally checks an x86_64 GNU/glibc release build. Native macOS, BSD, and Windows builds are unsupported.

nixpkgs

All tools are available via nixpkgs under rcp package name.

The following command will install all the tools on your system:

> nix-env -iA nixpkgs.rcp

crates.io

All tools are available on crates.io. Individual tools can be installed using cargo install:

> cargo install rcp-tools-rcp

debian / rhel

Starting with release v0.10.1, .deb and .rpm packages are available as part of each release.

Linux musl builds

For development on Linux, use Just or Nix. just build and the default nix develop shell select the host architecture's musl target: x86_64-unknown-linux-musl on x86_64 and aarch64-unknown-linux-musl on AArch64. The Nix shell supplies exactly the matching Rust target and musl C toolchain; explicit nix develop .#x86_64-musl and nix develop .#aarch64-musl shells are available for cross/distribution builds.

Raw Cargo has a deliberately different interface: .cargo/config.toml defaults it to the x86_64-unknown-linux-musl distribution target on every host. Both supported musl target sections select their ${target}-gcc linker and enable static CRT linking. The resulting binaries live under target/<target>/debug/ or target/<target>/release/.

# Runnable host-musl development build on supported Linux hosts
./scripts/cargo-host.sh build --release

# Raw-Cargo x86_64-musl distribution build, regardless of host architecture
cargo build --release

# Explicit caller-selected target; the wrapper preserves CARGO_BUILD_TARGET
CARGO_BUILD_TARGET=aarch64-unknown-linux-musl ./scripts/cargo-host.sh build --release
CARGO_BUILD_TARGET=x86_64-unknown-linux-gnu ./scripts/cargo-host.sh build --release

Outside Nix, install the Rust target you select and provide the matching prefixed linker named in .cargo/config.toml.

General controls

Copy semantics

The copy semantics for RCP tools differ slightly from how e.g. the cp tool works. This is because of the ambiguity in the result of a cp operation that we wanted to avoid.

Specifically, the result of cp foo/x bar/x depends on bar/x being a directory. If so, the resulting path will be bar/x/x (which is usually undesired), otherwise it will be bar/x.

To avoid this confusion, RCP tools:

  • will NOT overwrite data by default (use --overwrite to change)
  • do assume that a path WITHOUT a trailing slash is the final name of the destination and
  • path ending in slash is a directory into which we want to copy the sources (without renaming)

The following examples illustrate this (those rules apply to both rcp and rlink):

  • rcp A/B C/D - copy A/B into C/ and name it D; if C/D exists fail immediately
  • rcp A/B C/D/ - copy B into D WITHOUT renaming i.e., the resulting path will be C/D/B; if C/D/B exists fail immediately

Using rcp it's also possible to copy multiple sources into a single destination, but the destination MUST have a trailing slash (/):

  • rcp A B C D/ - copy A, B and C into D WITHOUT renaming i.e., the resulting paths will be D/A, D/B and D/C; if any of which exist fail immediately

Local copy acceleration (--reflink)

--reflink=auto|never controls the local regular-file data path in rcp and copies performed by rlink --update, and defaults to auto. It does not affect which files rlink chooses to hard-link. In auto mode, the copy first uses copy_file_range, allowing the kernel and filesystem to accelerate it with a reflink, another in-kernel copy, or an NFS server-side copy. If that operation is unsupported, it falls back automatically to the userspace read/write path.

--reflink=never bypasses copy_file_range and goes directly to that userspace path. This is useful for benchmarks that must exclude all copy_file_range acceleration, including non-reflink kernel copies and NFS offload. The fallback preserves sparse regions by walking SEEK_DATA/SEEK_HOLE when the filesystem supports them, and otherwise performs a dense read/write copy. Thus never still may produce a sparse destination: the option controls the data path, not physical disk usage, and reported bytes are logical file bytes rather than allocated disk bytes.

An always mode is intentionally deferred. There is no demonstrated use case for requiring a clone to succeed, and adding it now would introduce clone-specific failure semantics without a user need. It can be revisited when a concrete requirement exists.

Remote transfers already stream file bytes between rcpd processes, so auto and never have the same effect for remote copies. The option does not change the remote wire protocol.

Local copy scheduling (--local-copy-handoff)

--local-copy-handoff=never|fresh controls destination-create to payload-copy scheduling in rcp and files copied by rlink --update. The default is never: creation and payload copying remain separate blocking jobs, retaining the queue boundary between them.

fresh is experimental. After a successful first vacant-slot create, the same blocking worker can continue into the payload, saving one submission per fresh file. Large copies can occupy workers that would otherwise return to queued metadata work. Throughput and CPU benefits remain unverified; compare representative workloads before enabling it. Creation's operation gates and probe still finish before the cancellable payload claim, and EEXIST retries retain the separate-job path.

This policy is independent of --reflink, worker counts, and logical concurrency. It does not affect remote transfers or which files rlink hard-links. For example:

rcp --local-copy-handoff=fresh --reflink=never SOURCE DESTINATION

Path handling (tilde ~ support)

  • Local paths: leading ~ or ~/... expands to your local $HOME.
  • Remote paths: leading ~/... expands to the remote user’s $HOME (resolved over SSH). Other ~user forms are not supported.
  • Remote paths may be absolute, start with ~/, or be relative. Relative remote paths are resolved against the local current working directory before being used remotely.

Throttling

Two complementary mechanisms: static caps that you set once based on budget or policy, and adaptive metadata throttling that watches filesystem latency and adjusts concurrency on the fly.

Static caps

  • set --ops-throttle to limit the maximum number of operations per second

    • useful if you want to avoid interfering with other work on the storage / host
  • set --iops-throttle to limit the maximum number of I/O operations per second

    • MUST be used with --chunk-size, which is used to calculate I/O operations per file
  • set --max-files-in-flight=N|unlimited to control applicable file-like copy, link, comparison, removal, chmod, and generation work

    • a positive N sets a finite ceiling; unlimited removes the user ceiling, while numeric 0 is rejected. When omitted, the default is max(std::thread::available_parallelism(), 4). For a remote copy, the source rcpd computes that automatic default from the source host; an explicit value remains controlled by the initiating rcp
    • this is a ceiling on applicable work, not a literal count of process descriptors or a promise that the workload will achieve that much parallelism
    • startup attempts to raise soft RLIMIT_NOFILE to the inherited hard limit; file-work concurrency remains independently bounded. Local runtime setup intersects that ceiling with its effective soft-RLIMIT_NOFILE safety ceiling for each of two pools: OpenFile for fd-bearing leaf work and PendingMeta for spawned metadata work. The pools receive the same effective numerical ceiling, but are not a combined total; recursive directory, network socket, and process-support descriptors remain outside them
    • for normal remote copies, daemons jointly budget leaf work and directory lifetimes before startup readiness, then negotiate scan and pending-work bounds that retain room for directory progress. Dry runs use local metadata admission without reserving data streams or directory lifetimes. See the remote resource model
    • if querying RLIMIT_NOFILE fails, a finite value explicitly supplied through either flag remains usable as a logical ceiling and produces a visible warning. Automatic and unlimited admission still fail because they have no independent descriptor-safety bound. An effective zero soft limit fails closed for every policy
    • during one compatibility release, the hidden --max-open-files=N spelling remains accepted and warns. It conflicts with the new name; positive values map to the new ceiling, while legacy 0 maps to --max-files-in-flight=unlimited, removing only the user ceiling and leaving descriptor safety in effect; it therefore cannot recover from an RLIMIT_NOFILE query failure

Adaptive metadata throttling (--auto-meta-throttle)

Pass --auto-meta-throttle to enable a latency-ratio controller that watches per-op latency and grows or shrinks the in-flight concurrency cap (cwnd) on the fly. The controller stays just below the saturation point of whatever metadata path the tool is hitting — useful on shared distributed filesystems (Weka, Lustre, NFS, etc.) where a fixed --ops-throttle is hard to pick: too low and the job takes all day, too high and the filesystem suffers.

# Adaptive throttling alone — recommended default for distributed FS.
> rcp --auto-meta-throttle src/ dst/

# Compose with a hard rate ceiling: ops-throttle is the static
# upper bound, auto-meta backs off further under transient load.
# When both are set, --ops-throttle must be >= 10 (auto-meta uses a
# fixed 100ms internal cadence, so rates below 10 ops/sec round to
# zero tokens per interval).
> rcp --auto-meta-throttle --ops-throttle=5000 src/ dst/

Remote copies propagate --auto-meta-* flags to both rcpd processes (source and destination) automatically, so each side runs its own controller against the local part of the filesystem it actually observes.

Tuning knobs (all listed under --help-all on each binary): the initial / minimum / maximum cwnd, the grow/shrink ratio thresholds (alpha, beta), the baseline / current percentiles used to summarize the long and short windows, the long / short window durations, per-tick step sizes, and the control-loop tick cadence. The defaults ship a cross-percentile signal (baseline p10, current p50) with alpha = 1.3 and beta = 1.8 bracketing the typical inter-quantile spread of metadata syscalls, and are a good starting point.

For the design rationale (why concurrency is the lever, what cwnd is, the exact control law including worked ratio→action examples, and how the controller stays robust to load it generates itself), see docs/congestion_control.md.

Error handling

  • rcp tools will log non-terminal errors and continue by default
  • to stop on the first error use the --fail-early flag. In the shared hardened and rlink traversals, recursively spawned async work is cancelled and dropped before the operation returns, and blocking work that has not started is discarded. A blocking job that already won the start/cancel race cannot be interrupted and may contain later filesystem operations, so process shutdown gives blocking workers a bounded grace period instead of waiting forever on dead storage

Remote copy configuration

When using remote paths (host:/path syntax), rcp automatically starts rcpd daemons on remote hosts via SSH.

Requirements:

  • SSH access to remote hosts (uses your SSH config and keys)
  • rcpd binary available on remote hosts (see Auto-deployment below for automatic setup)

Auto-deployment: Starting with v0.22.0, rcp can automatically deploy rcpd to remote hosts using the --auto-deploy-rcpd flag. This eliminates the need to manually install rcpd on each remote host.

# automatic deployment - no manual setup required
> rcp --auto-deploy-rcpd host1:/source host2:/dest --progress

When auto-deployment is enabled:

  • rcp finds the local rcpd binary (same directory or PATH)
  • Local rcpd --protocol-version probes have a two-second deadline, while remote probes use the configurable remote connection timeout, so a hanging candidate can fall back to deployment; local timeout cleanup is retained and reaped by the invocation cleanup supervisor
  • Deploys it to ~/.cache/rcp/bin/rcpd-{version} on remote hosts via SSH
  • Verifies integrity using SHA-256 checksums
  • Keeps the last 3 versions and cleans up older ones
  • Reuses deployed binaries for subsequent operations (cached until version changes)

Remote endpoints must run Linux. Auto-deployment additionally relies on GNU/BusyBox mv -T; macOS and BSD are not supported as rcpd hosts, whether deployment is automatic or manual.

Manual deployment is still supported and may be preferred for:

  • Air-gapped environments where auto-deployment is not feasible
  • Production systems with strict change control
  • Situations where you want to verify the binary before deployment

Configuration options:

  • --port-ranges - restrict TCP data ports to specific ranges (e.g., "8000-8999")
  • --remote-copy-conn-timeout-sec - remote SSH setup, tilde-expansion HOME lookup, discovery, version-probe, deployment-readiness/write-idle, daemon-readiness, and TCP connection timeout in seconds (default: 15; 60 with --auto-deploy-rcpd; deployment verification gets at least 60)
  • --remote-keepalive-sec - liveness budget for every rcp TCP connection in seconds, 0 disables (default: 120); idle connections everywhere, unacknowledged data on control connections only

Architecture: The remote copy uses a three-node architecture:

  • Master (rcp) orchestrates the copy operation
  • Source rcpd reads files from source host
  • Destination rcpd writes files to destination host
  • Data flows directly from source to destination (not through master)

For detailed network connectivity and troubleshooting information, see docs/remote_copy.md.

Security

Remote copy uses SSH for authentication and TLS 1.3 for encrypted data transfer.

Security Model:

  • SSH Authentication: All remote operations require SSH authentication first
  • TLS Encryption: Data transfers are encrypted by default using TLS 1.3 with certificate pinning
  • Mutual Authentication: Both source and destination verify each other's certificates

What's Protected:

  • ✅ Unauthorized access (SSH authentication required)
  • ✅ Data encryption (TLS 1.3 with AES-256-GCM)
  • ✅ Man-in-the-middle attacks (certificate fingerprint verification)

Performance Option: For trusted networks where encryption overhead is undesirable, use --no-encryption:

> rcp --no-encryption source:/path dest:/path

Warning: This disables both encryption and authentication on all rcp TCP connections (master↔rcpd control and tracing, plus source↔destination control and data) — not just the file-data path. Every rcpd listener then accepts connections from anyone who can reach its port; only SSH still authenticates rcpd startup.

Best Practices:

  • Use SSH key-based authentication
  • Keep encryption enabled (default) for sensitive data
  • Only use --no-encryption on isolated, trusted networks

TOCTOU-safe mutation (rrm, rchm, rcp, rlink):

On Linux, for default non--L invocations, the mutating tools harden their directory walk against symlink/path-swap races (fd-relative openat/O_NOFOLLOW; see the TOCTOU documentation). --toctou-check prints whether a given invocation is hardened and exits (0 = safe), while --require-toctou-safe rejects non-hardened invocations and additionally enforces a strict operand contract: operands must be absolute and lexically normal (realpath output), and every operand open resolves RESOLVE_NO_SYMLINKS (Linux 5.6+), so a symlink spliced into any directory component of an operand path fails closed (a symlink operand itself is never followed). Which paths are acceptable remains policy — lock that down in the sudo rule or wrapper.

Set-ID suppression for privileged rchm (--no-setid): For a privileged policy wrapper (e.g. a sudo rule), add --no-setid. For every selected non-symlink whose type has an applicable --mode, --owner, or --group rule, it guarantees that the final mode has both set-user-ID (04000) and set-group-ID (02000) cleared. This also removes pre-existing set-ID bits, including set-group-ID on directories, even when the requested rule does not mention them; the sticky bit (01000) is unaffected. Filters and per-type rules still determine which entries are selected, and --no-setid by itself is not an operation. Without the flag, rchm retains its normal behavior, including preserving existing set-ID bits across ownership changes.

This is a successful-final-state guarantee, not an atomic lock against a concurrent owner changing the mode between rchm's metadata syscalls — privileged wrappers must exclude adversarial concurrent mode mutation during ownership changes. --no-setid is also necessary but not sufficient for delegating privileged rchm: a wrapper must constrain target paths, allowed owners/groups and modes, pin --require-toctou-safe, and prevent caller-controlled file arguments. See the privileged-use guidance.

For detailed security architecture and threat model, see docs/security.md.

Terminal output

Log messages

  • sent to stdout
  • by default only errors are logged
  • verbosity controlled using -v/-vv/-vvv for INFO/DEBUG/TRACE and -q/--quiet to disable

Progress

  • sent to stderr (both ProgressBar and TextUpdates)
  • by default disabled
  • enabled using -p/--progress with optional --progress-type=... override

Summary

  • sent to stdout
  • by default disabled
  • enabled using --summary

Filtering

All tools support pattern-based filtering with --include and --exclude flags.

Pattern Syntax

  • * matches anything except /
  • ** matches anything including / (crosses directories)
  • ? matches a single character (except /)
  • [...] character classes (e.g., [abc], [0-9])
  • Leading / anchors the pattern to the source root
  • Trailing / matches only directories

Precedence

  • Only --exclude: include everything except matches
  • Only --include: include only matches (exclude everything else)
  • Both: excludes are checked first, then includes

Examples

# Copy only .rs files
> rcp --include '*.rs' src/ dst/

# Copy everything except log files and the target directory
> rcp --exclude '*.log' --exclude 'target/' src/ dst/

# Copy only files in the src directory at root level
> rcp --include '/src/**' project/ backup/

# Use a filter file for complex patterns
> rcp --filter-file=filters.txt src/ dst/

Filter file format (filters.txt):

# Comments start with #
--include *.rs
--include Cargo.toml
--exclude target/
--exclude *.log

Pattern Semantics

Simple patterns (like *.txt, *_dir/) apply to all files at any level, including the source root itself.

Anchored patterns (starting with /, like /src/** or /bar/*.txt) match paths inside the source, not the source root itself. This allows you to copy a directory while filtering its contents:

# Copy project/ but only include the src subdirectory and its contents
> rcp --include '/src/**' project/ backup/
# Results in: backup/src/...

# Exclude the build directory inside the source
> rcp --exclude '/build/' project/ backup/

Note: /src matches only the src directory entry itself, while /src/** matches the directory and all files inside it.

Path patterns (containing / but not starting with /, like bar/*.txt) match relative paths inside the source directory.

Dry-Run Mode

Preview what would happen without making changes:

# Show only what would be copied
> rcp --dry-run=brief --exclude '*.log' src/ dst/

# Also show skipped files
> rcp --dry-run=all --exclude '*.log' src/ dst/

# Show skipped files with the pattern that caused the skip
> rcp --dry-run=explain --exclude '*.log' src/ dst/

Note: Dry-run mode is primarily useful for previewing --include/--exclude filtering. It bypasses --overwrite checks and does not check whether files already exist at the destination. --progress and --summary are suppressed in dry-run mode (use -v to still see summary output).

Age-based filtering (rrm, rchm)

rrm and rchm additionally support time-based entry filters: --modified-before <DURATION> acts only on entries whose mtime is at least that old, and --created-before <DURATION> does the same on birth time (btime). Durations use humantime syntax — note that M means months and lowercase m means minutes. The filter is per-entry: it applies to each file, directory, and symlink by that entry's own timestamp (directories are always traversed regardless of their own). For rrm specifically, a directory is then removed only when its own timestamp is old enough and it ends up empty after its children are processed — a directory left non-empty by a spared child is kept and logged, not an error. (rchm changes a matching directory's mode/owner based on its own timestamp regardless of its children.) --created-before is not available on musl static builds (btime is unreadable there) — use --modified-before or a glibc build.

# remove only files not modified in the last 30 days
> rrm --modified-before 30d old-cache/

# chmod only entries older than 6 months (M = months, not minutes)
> rchm --mode g-w --modified-before 6M archive/

Overwrite

rcp tools will not-overwrite pre-existing data unless used with the --overwrite flag.

Delete (mirror)

rcp --delete makes the destination a mirror of the source: any entry under the destination with no counterpart in the source is removed. --delete implies --overwrite, requires a single source, and cannot be combined with --dereference (-L). rlink --delete works the same way for hard-linked trees.

Known limitation: delete matching compares source and destination names byte-for-byte. On a destination that folds case, normalizes Unicode, or rewrites names (for example, by stripping trailing dots), an entry copied into or retained under a different spelling can appear extraneous and be deleted. This can happen even when the destination starts empty. For a directory, the whole subtree this run just populated can be removed while the run still reports success. Avoid --delete on such destinations until this matching limitation is fixed; it affects both rcp and rlink.

# make dst an exact mirror of src (removing anything in dst not present in src)
> rcp --delete src dst --progress --summary

Excluded files are protected from deletion by default; pass --delete-excluded to remove them too. --dry-run previews deletions without performing them. --delete is supported for local operations (remote support is planned).

Exclude-protection applies to pruning extraneous entries — those with no source counterpart. When --overwrite (implied by --delete) replaces a destination entry whose source counterpart changed type — e.g. a directory that is now a file in the source — removing the old destination entry is part of that overwrite, not an exclude-filtered deletion.

Pruning happens incrementally as the parallel copy proceeds, and a directory's extraneous entries are removed only once that directory's subtree has been processed without error — so deletions never act on an incomplete source listing. Unlike rsync, rcp/rlink do not cancel all deletions when a single error occurs elsewhere: subtrees that were processed cleanly are still mirrored.

Permissions and ownership (rchm)

The --group and --owner options take a per-type DSL: a bare value applies to all entries (files, directories, and symlinks via lchown); f:/d:/l: prefixes target one type. --mode uses the same DSL but covers only files and directories (a bare value sets both) — symlink mode bits aren't settable on Linux, so l: is rejected for --mode.

Compatibility with chmod/chown/chgrp: mode expressions are a subset of chmod ([ugoa][+-=][rwxXst], octal, and conditional X), omitting who-copy references like g=u. Omitted-who clauses ignore umask (deliberate for a bulk tool). For ordinary operands rchm does not dereference symlinks (like -h): it applies group/owner to the symlink itself via lchown and never changes symlink mode bits. mtime is preserved; ctime necessarily changes (the kernel stamps it on any metadata change) and cannot be preserved.

Directories are changed before their contents by default (like chmod -R), so --mode d:u+rwx can repair an unreadable directory. Pass --defer-dir-changes to change directories after their contents — needed when recursively removing your own read/execute permission from directories, where the default would lock itself out.

For the hardened walk, sudo policies, and set-ID suppression (--no-setid), see Security.

Performance Tuning

For maximum throughput, especially with remote copies over high-speed networks, consider these optimizations.

System-Level Tuning (Linux)

TCP Socket Buffers

rcp automatically requests larger TCP socket buffers for high-throughput transfers, but the kernel caps these to system limits. Increase the limits to allow full utilization of high-bandwidth links:

# Check current limits
sysctl net.core.rmem_max net.core.wmem_max

# Increase to 16 MiB (requires root, temporary until reboot)
sudo sysctl -w net.core.rmem_max=16777216
sudo sysctl -w net.core.wmem_max=16777216

# Make permanent (add to /etc/sysctl.d/99-rcp-perf.conf)
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216

The default is often insufficient for 10+ Gbps links.

Open File Limits

All tools, including the remote master and daemons, attempt to raise soft RLIMIT_NOFILE to the inherited hard limit before runtime and admission setup. The hard limit is unchanged. If the raise fails, startup warns with the operating-system cause and uses the original soft limit.

Check both limits in the affected host's session:

# Check soft limit and hard ceiling
ulimit -Sn
ulimit -Hn

# Example session policy (/etc/security/limits.conf, where applied)
* soft nofile 65536
* hard nofile 65536

Remote rcpd inherits its hard limit from the SSH session. Configure that host's SSH/session policy if it is too low; changing only the initiating shell's limit does not change the remote limit.

Local operations derive a descriptor safety ceiling from 80% of the effective soft limit, five modeled descriptor units, and a 4096-operation cap; that ceiling is independently intersected with --max-files-in-flight for each file-work pool. Normal remote copies jointly budget leaf work, directory lifetimes, data connections, and support descriptors before readiness; dry runs retain local metadata admission. See the remote resource model. A higher descriptor limit does not change the CPU-based default file-work ceiling. Recursive removal retains directory handles outside file-work admission, so low hard ceilings or extreme trees can still exhaust descriptors. Neither setting is a literal count of every descriptor in the process.

Network Backlog (10+ Gbps)

For very high-speed networks, increase the kernel's packet processing capacity:

sudo sysctl -w net.core.netdev_max_backlog=16384
sudo sysctl -w net.core.netdev_budget=600

Application-Level Tuning

Worker Threads

Control parallelism with --max-workers:

# Use all CPU cores (default)
rcp --max-workers=0 /source /dest

# Limit to 4 workers (reduce I/O contention)
rcp --max-workers=4 /source /dest

Remote Copy Buffer Size

For remote copies, --remote-copy-buffer-size sets the maximum transfer buffer and file I/O request size (default: 16 MiB for datacenter, 2 MiB for internet). The configured value must fit usize on the master and each daemon; otherwise argument validation or daemon startup fails. The source's owned read buffer, destination Tokio file I/O limit, and receiver scratch requests use the same per-file limit, capped to the file size and the host's isize::MAX, with a one-byte minimum. The source reuses one buffer per nonempty file across reads and network writes; empty payloads need no source buffer. Individual disk and network operations can be shorter; this does not set TCP packet or TLS record sizes.

These integer bounds ensure representable sizes, not available memory. There is no practical allocation budget check: excessively large settings can exhaust memory and abort a daemon. At the destination, Tokio's internal file buffer and outer transfer scratch can coexist, so choose the size with available memory and concurrent transfers in mind. The configured size is not a process memory bound.

# Allow up to 32 MiB per transfer buffer/file I/O request
rcp --remote-copy-buffer-size=32MiB host1:/data host2:/data

# Smaller buffers for constrained memory
rcp --remote-copy-buffer-size=4MiB host1:/data host2:/data

Receivers lazily reuse initialized scratch per data connection, retaining up to the smaller of the copy chunk size and 2 MiB by default. This avoids repeated allocation and initialization for eligible files, at the cost of memory held until the connection closes. Retained storage can be larger than a later file's scratch request. Use --remote-copy-buffer-retention-limit=16MiB to retain full datacenter chunks, a smaller limit to reduce idle memory, or 0 to disable reuse. Chunks above the limit still use the configured I/O size with temporary storage. At 100 connections the default retained-scratch ceiling is 200 MiB for either profile; see connection reuse for the full memory accounting.

Network Profile

Use --network-profile to optimize for your network type:

# For datacenter/local networks (aggressive settings)
rcp --network-profile=datacenter host1:/data host2:/data

# For internet transfers (conservative settings)
rcp --network-profile=internet host1:/data host2:/data

Concurrent Connections

Remote data streams are min(--max-files-in-flight, --max-connections). --max-connections is a separately configurable ceiling with a default of 100. Configured pending capacity P is the effective stream count times --pending-writes-multiplier; descriptor admission can reduce source scans W and pending work to Q. The source reports its logical file limit and stream count before the master starts the destination with matching values. Each endpoint installs a joint leaf/directory resource plan, then the source intersects their directory lifetime limits. See resource admission for the bounds. Wire revision 11 requires matching binaries, including receiver-buffer retention startup configuration.

Explicit limits are validated before remote ~ expansion. For automatic limits, the master validates the configured connection upper bound before remote side effects, then the source resolves and validates its actual CPU-selected capacity before it announces readiness; effective-stream and pending capacities above Tokio's semaphore maximum are rejected. A default-visible notice names the requested and effective values when an explicit file ceiling is reduced by the connection ceiling, an automatic file ceiling is reduced by an explicit connection ceiling, an explicit connection ceiling is reduced by the source file ceiling, or an explicit file limit is reduced by descriptor safety. The ordinary automatic/default intersection remains quiet. To raise remote parallelism above the source's CPU-derived file-work default, raise both ceilings explicitly:

# Increase for many small files on high-bandwidth links
rcp --max-files-in-flight=200 --max-connections=200 host1:/many-small-files host2:/dest

# Decrease both ceilings to reduce file work and stream resource usage
rcp --max-files-in-flight=16 --max-connections=16 host1:/data host2:/dest

Diagnosing Performance Issues

Check TCP Buffer Sizes

When rcp starts, it logs the actual buffer sizes achieved (visible with -v). If the actual sizes are much smaller than requested, increase your system's rmem_max/wmem_max.

Check for Network Issues

# Network interface drops
ip -s link show eth0 | grep -A1 RX | grep dropped

# TCP retransmissions (high values indicate network congestion)
ss -ti | grep retrans

Quick Checklist

For optimal performance on high-speed networks:

  1. ☐ Increase rmem_max/wmem_max to 16+ MiB
  2. ☐ Check the hard descriptor limit on each host if copying many files
  3. ☐ Use --network-profile=datacenter for local/datacenter networks
  4. ☐ Use --progress to monitor throughput in real-time
  5. ☐ Check -v output to verify buffer sizes and connection setup

filegen Performance

The filegen tool generates random test data, which is CPU-intensive. Unlike other rcp tools that are typically I/O-bound, filegen's bottleneck is often the CPU generating random bytes.

Default behavior: filegen shares the common --max-files-in-flight default: max(std::thread::available_parallelism(), 4). This respects the CPU parallelism available to the process (including affinity/resource constraints) while retaining enough work to cover I/O latency.

Tuning for your workload:

# Use the common CPU-based default - optimal for fast storage
filegen /tmp 3,2 10 1M --progress

# Increase for slow storage where I/O latency dominates
filegen /tmp 3,2 10 1M --max-files-in-flight=64 --progress

Profiling

rcp supports several profiling and debugging options.

Scoped Timings

Collect elapsed durations for named stages without enabling verbose logging:

rcp --timings=/tmp/timing /source /dest
rcp --timings=/tmp/timing host1:/source host2:/dest

Each process writes {prefix}-{identifier}-{hostname}-{pid}-{timestamp}.timings.json on its own host. The parent directory must exist. Explicit timing collection also works with --quiet. Version 1 summaries contain the process identifier, PID, and a scopes array. Each scope records name, count, finished, interrupted, and total_seconds, mean_seconds, p50_seconds, p95_seconds, max_seconds. Percentiles use bounded histograms with two significant figures at microsecond resolution; totals and maxima retain the measured duration precision.

The default scopes cover the operation, local copy, and remote source traversal, scanning, directory-credit waits, dispatch, and drain. Add --timings-detail to include per-file waits, opening, sending, receiver completion, and shared metadata operations. Detailed collection costs more and is intended for diagnosis; collection can affect scheduling and lock contention. The benchmark harness collects coarse summaries by default and includes stage tables in its reports; see benchmarking.

Shared metadata scopes use source.metadata.<operation>.<phase> or destination.metadata.<operation>.<phase>. Operations are stat, read-link, mkdir, rmdir, unlink, hard-link, symlink, chmod, and open-create. These are congestion buckets, not individual syscalls: for example, chmod also covers ownership, timestamps, and ACL updates, while stat can include opens.

Phase Measured interval
wait_rate Waiting for a metadata rate token, when the caller requests one.
wait_admission Waiting for metadata concurrency admission.
wait_worker Blocking helper only: preparing and submitting work through its start on a worker.
execute Running the blocking closure or awaiting the async metadata future.

Both metadata helpers record rate and concurrency admission. Calls that already consumed a rate token omit wait_rate. Async execution includes suspension and any worker scheduling inside the awaited API; it has no separate wait_worker sample. Admission samples are recorded even when the operation can proceed immediately, so their counts represent visits to that stage.

Cancellation while waiting for a worker interrupts wait_worker and produces no execute sample. Once work starts, execute follows the worker through completion even if its async waiter is cancelled. Cancelling an async metadata future interrupts its execution scope. A returned error finishes the execution scope; unwinding interrupts it. These scopes measure elapsed time, not individual syscall latency. See remote timings for source traversal and receiver scope boundaries.

Detailed collection adds work at worker startup inside the congestion probe interval. Execution completion is recorded after the probe ends and its concurrency permit is released. Collection can still change the latency observed by --auto-meta-throttle; use detail reports for diagnosis, and measure throughput separately with detail disabled.

Durations include time suspended at an async wait. Nested and concurrent scopes overlap: their totals are cumulative elapsed time, not CPU time or additive command wall time. A finished scope reached its explicit endpoint; it does not imply the copy succeeded. Early exits and cancellation before that endpoint count as interrupted, and both kinds contribute to duration statistics. Reports include scopes recorded before artifact finalization. A blocking worker still stuck after the runtime's ten-second shutdown timeout has no recorded completion or interruption and is omitted.

To add a measurement in code, use a stable name and finish it at the intended boundary:

let scan = common::timing_scope!("source.directory.scan");
// scan this directory, including any async waits
scan.finish();

// measures through return (including Err); cancellation records an interruption
let permit = common::timing_scope!(trace, "source.file.wait_open")
    .measure(acquire_permit())
    .await?;

These are tracing spans on the dedicated rcp::timing target. Logical completion is independent of span clones and child tasks. Do not hold an entered span guard across an .await. Keep names independent of paths or identifiers; aggregation is capped at 256 names, including an overflow bucket, and does not retain individual samples.

Chrome Tracing

Produces JSON trace files viewable in Perfetto UI or chrome://tracing.

# Profile a local copy
rcp --chrome-trace=/tmp/trace /source /dest

# Profile a remote copy (traces produced on all hosts)
rcp --chrome-trace=/tmp/trace host1:/path host2:/path

Output files are named: {prefix}-{identifier}-{hostname}-{pid}-{timestamp}.json

Example output:

  • /tmp/trace-rcp-master-myhost-12345-2025-01-15T10-30-45Z.json
  • /tmp/trace-rcpd-source-host1-23456-2025-01-15T10-30-46Z.json
  • /tmp/trace-rcpd-destination-host2-34567-2025-01-15T10-30-46Z.json

Artifact timestamps use UTC with filename-safe separators so reports can be uploaded to CI storage.

Artifact paths, Tokio-console addresses, legacy-option warnings, and explicit concurrency-clamp warnings are emitted through the normal notice logging target. In remote mode, daemon artifact notices are forwarded to the master after its tracing connection is established; they never precede the daemon's readiness record on raw stderr.

View traces by opening https://ui.perfetto.dev and dragging the JSON file into the browser.

Chrome tracing also writes {prefix}-{identifier}-{hostname}-{pid}-{timestamp}.scopes.json with the elapsed timing scopes above. The existing .json file records span enter/exit intervals, which can split an async operation across polls; the .scopes.json file records its logical elapsed lifetime, including waits. Concurrent elapsed scopes use separate lanes, reused after completion. Use --timings-detail for file, metadata, and tracker elapsed scopes. --profile-level controls the existing poll trace only; elapsed scopes use their own coarse/detail selection. Chrome output is disabled by --quiet. Summaries and both trace files can safely use the same prefix.

Flamegraph

Produces folded stack files convertible to SVG flamegraphs using inferno.

# Install Inferno for this host when working from the repository checkout
./scripts/cargo-install-host.sh inferno

# Profile and generate flamegraph data
rcp --flamegraph=/tmp/flame /source /dest

# Convert to SVG
cat /tmp/flame-*.folded | inferno-flamegraph > flamegraph.svg

# Or use inferno-flamechart to preserve chronological order
cat /tmp/flame-*.folded | inferno-flamechart > flamechart.svg

Output files are named: {prefix}-{identifier}-{hostname}-{pid}-{timestamp}.folded

Profile Level

Control which spans are captured with --profile-level (default: trace):

# Capture only info-level and above spans
rcp --chrome-trace=/tmp/trace --profile-level=info /source /dest

Only spans from rcp crates are captured (not tokio internals).

Tokio Console

Enable tokio-console for real-time async task inspection:

# Start rcp with tokio-console enabled
rcp --tokio-console /source /dest

# Or specify a custom port
rcp --tokio-console --tokio-console-port=6670 /source /dest

# Connect with tokio-console CLI
tokio-console http://127.0.0.1:6669

Trace events are retained for 60s by default. This can be modified with RCP_TOKIO_TRACING_CONSOLE_RETENTION_SECONDS=120.

Combined profiling

All profiling options can be used together:

rcp --chrome-trace=/tmp/trace --flamegraph=/tmp/flame --tokio-console /source /dest

References

  1. https://mpifileutils.readthedocs.io/en/v0.11.1/dsync.1.html
  2. https://github.com/wtsi-ssg/pcp
  3. https://mpifileutils.readthedocs.io/en/v0.11/dchmod.1.html