Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

This is the documentation of irsync 0.1.0-alpha.4.

irsync is a one-way directory synchroniser in the mould of rsync, rebuilt for today’s networks. It runs on both ends of a transfer and connects through iroh, so two machines find each other and traverse NATs and firewalls without port forwarding, dynamic DNS or SSH tunnels. The daemon side is reached by its iroh identity, not by an address.

It is designed to fill whatever bandwidth the link has, and to survive a bad one. A sync session outlives any single network connection: when hotel wifi drops, the laptop sleeps or the process is killed, the next run of the same command resumes where it stopped; when the interrupted run had finished listing and no deletion is asked for, it does so without re-walking and re-comparing the whole tree. Many files are in flight at once, scanning runs alongside the transfer, and a persistent index makes repeat runs over a large, mostly unchanged tree cheap.

Correctness comes first. How we know irsync is correct states what a completed sync promises, and how you can check it yourself.

Alpha. irsync is alpha software. The command line and the network protocol may change before the beta, and versions may then not talk to each other. Keep another copy of anything you sync with it.

Install

Pick one way. Every package contains both irsync and fileset.

The install script puts both in ~/.local/bin:

curl --proto '=https' --tlsv1.2 -LsSf https://irsync.org/install.sh | sh

It installs the newest stable release. To try a beta, add --beta straight after sh -s --. --alpha takes the newest release of any kind:

curl --proto '=https' --tlsv1.2 -LsSf https://irsync.org/install.sh | sh -s -- --beta

The first stable release will be v0.1.0. Until it is out, there are only alphas and betas, so add --alpha.

The script also writes a small receipt file, ~/.config/irsync/irsync-receipt.json. It only records what was installed. It is harmless, and you can delete it.

Homebrew (Linux and macOS), from v0.1.0 on:

brew install irsync-dev/tap/irsync

Debian, Ubuntu, Fedora and RHEL, from v0.1.0 on: the apt and dnf setup commands are on dist.irsync.org.

You can also download a tarball from the GitHub Releases page.

For anything else, build from source with Rust’s cargo. If you have no Rust yet, or an older one, get it from rustup.rs first. The build takes a few minutes.

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh   # only if you have no Rust
cargo install --git https://github.com/irsync-dev/irsync irsync

Release binaries cover Linux on x86_64 and arm64, and macOS on Apple Silicon. Other Linux and macOS machines can build from source. All of these are supported, as client and as daemon.

With ssh, the client is enough: the first sync copies irsync to the server when both run the same OS and CPU. When they differ, install irsync on both machines and set the server up by hand (Your first sync).

Quick start

If ssh myserver logs you in to the server, irsync needs to be installed on the client only. Push to any path your account there can reach:

irsync -av ~/Photos/ myserver:/srv/photos/

The first run sets the server up over ssh: it installs irsync there, grants this client access to any path (immediate mode), starts the daemon and saves myserver as a host alias. Later runs connect over iroh without ssh.

To share only named directories instead, set the server up by hand: export a directory, grant the client access to it and start the daemon. Your first sync walks through both ways.

Who this book is for

People who copy large directory trees between a client and a server, both machines they control, and who want a transfer to finish after the network has failed along the way. If you know rsync, you know most of the command line: irsync accepts many of rsync’s flags, some with a different meaning, and adds its own; the command-line reference lists them, and Known limitations lists the rsync options it does not have.

How the book is organised

The pages come in four kinds, and each kind answers a different question.

  • Tutorial. One guided run from nothing to a first transfer, for someone who has not used irsync before.
  • How-to guides. Short recipes for a task you already have in mind: troubleshooting a first sync, setting a server up over ssh, running the daemon, changing exports, choosing a connection path, cleaning up, measuring a transfer.
  • Reference. Every flag, command, configuration key, file and metric, and the wire protocol, stated as the code has it.
  • Explanation. Why irsync behaves as it does: how we know it is correct, sessions and resume, identity and trust, connections, and the transfer algorithm.

A separate part, fileset, covers a companion tool that shares no code with irsync. It checks a copy against a recorded manifest, whichever tool made the copy, and finds bitrot. Start at Introduction to fileset.

A last part, Contributing, is for people who work on irsync itself: setting up a checkout, running the tests, the stress and network-stress tools, and how this website is built.

The source is at github.com/irsync-dev/irsync.

License

irsync, and the tools in its repository, are MIT licensed; see the LICENSE file.

Your first sync

In this tutorial you push a photo library from a client to a server, resume an interrupted push, and pull the library back. First the quick way, over ssh; then the same setup by hand, for when ssh is not available or you want to share only named directories.

You need irsync on the client (see Install). The quick way installs it on the server for you; for the setup by hand, install it on the server too.

The client runs irsync. The server runs irsync daemon, the daemon, which serves its directories. The two machines find each other by the daemon’s identity, an EndpointId, not by an address: you need no port forwarding, dynamic DNS or SSH tunnel.

You write no configuration file by hand. Each machine generates its key the first time a command needs it and says so on stderr: generated identity <path>.

The quick way: over ssh

If ssh myserver already logs you in to the server, one command on the client is enough:

irsync -av ~/Photos/ myserver:/srv/photos/

myserver is not a saved alias yet, so irsync takes it as an ssh destination and sets the server up first. It says what it did:

irsync: myserver is not a saved alias; setting it up over ssh
irsync: set up myserver over ssh:
irsync:   installed irsync 0.1.0 (1a2b3c4) at ~/.local/share/irsync/bin/irsync
irsync:   generated the daemon identity
irsync:   granted this client (a3e4753e5e) access to any path
irsync:   started the daemon (log: ~/.local/state/irsync/daemon.log)
irsync:   saved host alias myserver -> 4a29f16a4f

In steps, it:

  • copies itself to the server, when the server runs the same OS and CPU as the client. Otherwise it stops and says so; then install irsync on both machines and set the server up by hand;
  • lets this client reach any path your account on the server can, read-write (an immediate grant). The first push to /srv/photos makes it an export, granted to this client only;
  • starts the daemon, which keeps running in the background;
  • saves myserver as a host alias on the client, with the daemon’s EndpointId and ssh = "myserver".

After that, irsync prints how to make the daemon a user service, so that it survives a reboot (see Run the daemon). Then the push runs over iroh. -a recurses into directories and keeps symlinks, permissions, times, group, owner and device files; -v lists each file. The trailing / on ~/Photos/ copies the directory’s contents, as in rsync. Add -P to see a live block at the bottom of the screen that shows the transfer as it runs.

Later runs use the alias and do not touch ssh. If the daemon has stopped, for example after a reboot, a sync waits about 15 seconds for an answer, then says myserver did not answer; checking it over ssh, starts the daemon again and carries on.

Set a server up over ssh covers the options: re-running the setup with --ssh after you update irsync, keeping the daemon out of the public DHT with --no-remote-dht, another ssh command with --rsh, and limiting the client to named exports.

Run it again

irsync -av ~/Photos/ myserver:/srv/photos/

Nothing has changed, so nothing is sent.

Interrupt a transfer and resume it

Add a few large files to ~/Photos, start the push, and press Ctrl-C while it runs. Then run the same command again:

irsync -av ~/Photos/ myserver:/srv/photos/

irsync finds the stopped session and says resuming session <id> from <time>. Files that were partly sent continue from the last verified chunk. The same happens after a dropped network connection, except that irsync redials on its own, for up to 24 hours by default.

Pull the library back

Pull it into a new directory on the client:

irsync -av myserver:/srv/photos/ ~/Photos-copy/

A pull is the same command with the remote side first. To see what a pull would fetch without writing anything, give the remote side alone:

irsync myserver:/srv/photos/

That is the whole quick way. The rest of this tutorial sets a server up by hand. It shows what the quick way does for you.

Set the server up by hand

Here you export two directories under names, grant the client access to them, and start the daemon yourself. Nothing goes through ssh. irsync must be installed on both machines.

This part is an alternative to the quick way, not a next step. Follow it on a server that was not set up over ssh: on one that was, a daemon is already running, so step 4 would start a second one, and step 5 would replace the myserver alias that the quick way saved.

1. Find the client’s EndpointId

On the client, print its identity:

irsync id show

Under the client: label, the first line is the public key in OpenSSH form, the second the client’s EndpointId, 64 hexadecimal characters:

client:
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKPkdT5ep05k50XpxNELD9dR2+AwSddC6w6lRciXA9+6 irsync
a3e4753e5ea74e64e745e9c4d10b0fd751dbe03049d742eb0ea545c89703dfba

If the client already has an ssh key at ~/.ssh/id_ed25519, irsync uses it instead of generating one, and reads it without changing it.

Copy the last line. You paste it on the server in step 3.

2. Export two directories on the server

On the server, create the directories and export them under a name:

sudo mkdir -p /srv/photos /backup
sudo chown "$USER" /srv/photos /backup
irsync export add photos:/srv/photos
irsync export add backup:/backup

irsync export add writes ~/.config/irsync/irsync.toml and prints the daemon’s EndpointId on stdout. Copy it. You paste it on the client in step 5.

This is the ID clients connect to. irsync id show --daemon prints it again later. Plain irsync id show on the server prints the server’s client identity, which is a different key: nothing answers to it, so a client given that one waits, then gives up with a message that points at irsync id show --daemon (see Troubleshoot a first sync).

3. Grant the client access

Still on the server, give the client’s EndpointId a readable name and grant it both exports. Replace <client-id> with the line you copied in step 1:

irsync host add myclient <client-id>
irsync grant add photos myclient
irsync grant add backup myclient

Each grant add gives read-write access. The daemon refuses every key that no grant names, before it reads any request.

4. Start the daemon

Start the daemon in the foreground, in a terminal you leave open:

irsync daemon

It prints its EndpointId and the sockets it listens on, then logs to stderr:

endpoint id: 4a29f16a4f80a3fd171ef5573c106dbda470ec24f5a97933752746b567ab9aff
listening on: 192.168.1.10:41235

The daemon publishes its addresses so that a client holding its EndpointId can find it. Leave it running for the rest of the tutorial.

5. Name the server on the client

On the client, give the server’s EndpointId the name myserver. Replace <server-id> with the line you copied in step 2:

irsync host add myserver <server-id>

The client now pins this EndpointId for myserver. If anything else answers, the connection fails; there is no trust-on-first-use prompt.

6. See what the server shares

Ask the daemon what this client may reach:

irsync myserver:

The daemon answers with one line per export, its name, its real path and your access:

backup /backup rw
photos /srv/photos rw

7. Push the library

Copy the contents of ~/Photos into the photos export:

irsync -av ~/Photos/ myserver:photos/

Resuming and pulling work as in the quick way, with myserver:photos/ in place of myserver:/srv/photos/.

8. Push by real path

You can also name a path on the server directly. The path must lie inside an export that the client has a grant for, here backup:

irsync -av ~/Documents/ myserver:/backup/myclient/Documents/

A path outside every export the client may use is refused as “no access”, whether it exists or not.

What you did

  • The quick way set the server up over ssh and saved an alias; every sync after that went over iroh.
  • By hand, you copied two EndpointIds, one in each direction: the client’s to the server, the daemon’s to the client. That exchange is the whole of the trust setup.
  • You pushed, resumed, listed and pulled with rsync’s flags and its trailing-slash rule.

The alias is optional: the raw EndpointId works in its place, as in irsync -av ~/Photos/ <server-id>:photos/, and irsync grant add photos <client-id> works without host add.

Next steps

To check that the copy arrived intact, see Verify an irsync transfer.

Troubleshoot a first sync

The errors people meet on a first sync, what they mean and what to do.

A host added by hand never answers

The sync waits, then stops with one of two messages. When no address was ever published for the ID, which is the usual case for a wrong one:

irsync: ~/Photos: gave up after 5 attempts: the daemon never answered: connecting to 4a29f16a4f80a3fd171ef5573c106dbda470ec24f5a97933752746b567ab9aff: no address found for it. Is this the daemon's EndpointId? On the server, `irsync id show --daemon` prints it (plain `irsync id show` prints the client's). Also check that the daemon is running there.

When an address is known but nothing answers there, for example a daemon that has stopped:

irsync: ~/Photos: gave up after 5 attempts: the daemon never answered: connecting to 4a29f16a4f80a3fd171ef5573c106dbda470ec24f5a97933752746b567ab9aff: timed out; if you copied this host's ID by hand, it must be the daemon's EndpointId: on the server, irsync id show --daemon prints it (plain irsync id show prints the client's). Also check that the daemon is running there

The listing, irsync myserver:, ends with the same advice.

Cause. Most often the client was given the server’s client ID instead of its daemon’s. A server has two keys: plain irsync id show prints the one it uses as a client; clients must connect to the daemon’s. Nothing answers to the wrong one, so the client can only wait. The other cause is a daemon that is not running.

Fix. On the server, print the daemon’s ID:

irsync id show --daemon

On the client, save it under the host’s name, replacing the old one:

irsync host add myserver <daemon-id>

Then check that irsync daemon is running on the server.

ssh setup stops: the server runs another OS or CPU

irsync: myserver is not a saved alias; setting it up over ssh
irsync: "myserver" is not an alias in ~/.config/irsync/irsync.toml and not an EndpointId; setting it up over ssh failed: myserver runs linux aarch64, this irsync is macos aarch64, so it cannot copy itself there. Install irsync on both machines and set the server up by hand: https://irsync.org/book/tutorial/first-sync.html#set-the-server-up-by-hand

Cause. The ssh setup installs irsync by copying the client’s own binary, which only runs on the same OS and CPU.

Fix. Install irsync on the server yourself and set the server up by hand. Installing it on the server does not make the ssh setup work, because the setup only uses its own copy of the client’s exact build. Release binaries, planned for the beta, will remove this step.

The daemon rejected this client’s key

irsync: the daemon rejected this client's key: no access to myserver:photos/. On the daemon's machine, irsync grant list a3e4753e5ea74e64e745e9c4d10b0fd751dbe03049d742eb0ea545c89703dfba shows what this key may reach; irsync grant add EXPORT a3e4753e5ea74e64e745e9c4d10b0fd751dbe03049d742eb0ea545c89703dfba grants an export, irsync export add NAME:PATH exports a directory (irsync id show prints this id)

Cause. The daemon answered, but no grant lets this client reach that path: the client was never granted an export, the path lies outside every export it may use, or a grant was removed.

Fix. On the server, grant the export to the client’s ID, which the message names:

irsync grant add photos <client-id>

A host set up over ssh is not “fixed” over ssh when this happens. The refusal is on purpose, and irsync never adds back an immediate grant you removed. See Identity and trust.

The transfer is slow and says relay

The live block (--progress), and the summary line at the end of each session (-vv), name the path the connection took: direct or relay. See Connect directly or through a relay.

Cause. The two machines could not reach each other directly (hole punching failed, often when both sit behind strict NATs), so the data goes through a relay server. Relays are a fallback and much slower than a direct path.

Fix. Connections explains when hole punching fails. When the connection has to stay on a relay, run your own relay close to both machines.

Run the daemon

irsync daemon runs in the foreground and never puts itself in the background. Let a service manager start it, restart it and collect its logs: systemd on Linux, launchd on macOS. Its flags are in Command line.

What it prints

Once startup can no longer fail, the daemon prints these lines on stdout, and prints them again after every reload:

endpoint id: <EndpointId>
listening on: <socket>
debug port: <socket>

There is one listening on: line per bound socket. The debug port: line appears only when debug_addr is set (see Telemetry). A process that starts the daemon can read these lines and dial at once.

Run it as its own account

A daemon that the service manager runs as its own account, here irsync, keeps everything in one directory: /etc/irsync/ on Linux, /usr/local/etc/irsync/ on macOS. There is no /etc lookup, so the daemon gets --config explicitly.

  1. Create the account’s directory, owned by the account:

    install -d -o irsync -g irsync -m 0755 /etc/irsync
    

    The management commands replace a file by writing a new one next to it and renaming it, so the directory must be writable by irsync.

  2. Write /etc/irsync/irsync.toml with the state directory and the daemon’s key. Without these two keys both would default to paths under the account’s home directory:

    state_dir = "/var/lib/irsync"
    
    [daemon]
    identity = "/etc/irsync/daemon_ed25519"
    
  3. Manage the exports as the daemon’s account, with the same --config the daemon gets. For the nouns the flag may stand anywhere after the noun:

    sudo -u irsync irsync export add photos:/srv/photos --config /etc/irsync/irsync.toml
    sudo -u irsync irsync grant add photos myclient --config /etc/irsync/irsync.toml
    sudo -u irsync irsync host add myclient <id> --config /etc/irsync/irsync.toml
    sudo -u irsync irsync config set daemon.listen 0.0.0.0:4433 --config /etc/irsync/irsync.toml
    sudo -u irsync irsync id show --daemon --config /etc/irsync/irsync.toml
    sudo -u irsync irsync show --config /etc/irsync/irsync.toml
    

    The first export add generates the daemon’s key and prints its EndpointId.

Without --config, a management command edits your own ~/.config/irsync/irsync.toml: irsync export add would write your file, generate a stray ~/.config/irsync/daemon_ed25519 and print that key’s id as the daemon’s. Running the commands as irsync also keeps the files owned by the account that reads them; a daemon key generated by root has mode 0600 and the daemon cannot read it. Root can run the same commands with the same flags if it fixes the ownership afterwards.

irsync show and irsync id show -a also load the client key that identity names in the same file, and generate it if it is missing.

Do not run it as root

A daemon that receives a push applies the metadata the client sends: permissions, owner, group, device nodes. As root, that lets any client with write access to an export create setuid files owned by root, files owned by other users, and device nodes in it. Run the daemon as an unprivileged account that owns the export trees. Ownership is then applied only where that account may change it, to its own groups, as rsync does without privilege.

The ssh setup warns when you sign in as root: the daemon it starts then runs as root, and the client’s immediate grant reaches every path on the server.

Keep a daemon started over ssh running

When the ssh setup starts the daemon, it runs in the background under your account until the server reboots. When a later sync gets no answer within about 15 seconds, it starts the daemon again over ssh, but only when you sync. To keep it running all the time, make it a user service. The setup prints these steps for the server’s system; they are the same here.

On Linux, put this in ~/.config/systemd/user/irsync.service:

[Unit]
Description=irsync daemon
[Service]
ExecStart=%h/.local/share/irsync/bin/irsync daemon
Restart=on-failure
[Install]
WantedBy=default.target

Then stop the daemon irsync started and let the service take over:

pid="$(sed -n 's/^pid=//p' ~/.local/state/irsync/daemon.lock)"
kill "$pid"
while kill -0 "$pid" 2>/dev/null; do sleep 0.2; done
systemctl --user enable --now irsync
loginctl enable-linger $USER

loginctl enable-linger lets your user services run when you are not logged in.

On macOS, put this in ~/Library/LaunchAgents/org.irsync.daemon.plist, with your home directory for $HOME:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>org.irsync.daemon</string>
  <key>ProgramArguments</key><array><string>$HOME/.local/share/irsync/bin/irsync</string><string>daemon</string></array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
</dict></plist>

Then stop the daemon irsync started and let the service take over:

pid="$(sed -n 's/^pid=//p' ~/.local/state/irsync/daemon.lock)"
kill "$pid"
while kill -0 "$pid" 2>/dev/null; do sleep 0.2; done
launchctl load -w ~/Library/LaunchAgents/org.irsync.daemon.plist

If the state directory is not the default one, the setup prints the path of daemon.lock to use instead. The kill is needed because the lock lets only one daemon run at a time: the service cannot start while the first daemon holds it, so the loop waits until that daemon has exited. These lines are sh syntax; from fish or tcsh, run them under sh.

Under systemd

  1. Write /etc/systemd/system/irsync.service:

    [Unit]
    Description=irsync daemon
    After=network-online.target
    Wants=network-online.target
    
    [Service]
    Type=simple
    ExecStart=/usr/local/bin/irsync daemon --config /etc/irsync/irsync.toml
    ExecReload=/bin/kill -HUP $MAINPID
    KillSignal=SIGINT
    Restart=on-failure
    RestartSec=5
    User=irsync
    Environment=RUST_LOG=info
    
    [Install]
    WantedBy=multi-user.target
    

    KillSignal=SIGINT makes systemctl stop send the signal the daemon shuts down cleanly on (see Stop it). The User= account needs read access to the export paths, write access to the read-write ones, read access to the key and to irsync.toml, hosts.toml and exports.toml, and write access to state_dir.

  2. Start it, and start it at boot:

    systemctl enable --now irsync
    
  3. Follow its log:

    journalctl -u irsync -f
    

systemctl reload irsync applies changed [daemon] settings without a restart.

Under launchd

  1. Write ~/Library/LaunchAgents/net.irsync.daemon.plist:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
      <key>Label</key>
      <string>net.irsync.daemon</string>
      <key>ProgramArguments</key>
      <array>
        <string>/usr/local/bin/irsync</string>
        <string>daemon</string>
        <string>--config</string>
        <string>/usr/local/etc/irsync/irsync.toml</string>
      </array>
      <key>EnvironmentVariables</key>
      <dict>
        <key>RUST_LOG</key>
        <string>info</string>
      </dict>
      <key>RunAtLoad</key>
      <true/>
      <key>KeepAlive</key>
      <true/>
      <key>StandardErrorPath</key>
      <string>/usr/local/var/log/irsync.log</string>
    </dict>
    </plist>
    

    For a daemon that runs as its own account, put the file in /Library/LaunchDaemons instead, add a UserName key naming the account, and manage the exports as in Run it as its own account, with the /usr/local/etc/irsync/ paths.

  2. Load it:

    launchctl load ~/Library/LaunchAgents/net.irsync.daemon.plist
    

launchd has no reload verb. To apply changed [daemon] settings without a restart, send the signal yourself:

kill -HUP $(pgrep -f 'irsync daemon')

Durability

A push writes each file to a temporary name and renames it into place. By default, as in rsync, nothing is flushed to disk explicitly: a power loss or kernel crash in the seconds after a push can leave a file at its name with the right size and time but not its content, which the next quick check does not notice. A client asks for a flush per file with --fsync; an export with fsync = true (irsync config set exports.NAME.fsync true) flushes every push into it whatever the client asked. On a slow disk this costs time: about 30% of a push of 31,000 small files to btrfs on two spinning disks. Like read_only, the setting is read on every connection.

Logs

The daemon logs to stderr; journald and launchd’s StandardErrorPath capture it. The default level is info. -v raises it to debug, -vv to trace, and -q lowers it to errors only. RUST_LOG overrides all of them, in the tracing filter syntax, for example RUST_LOG=irsync=debug.

Each line of a session carries the session’s span and its fields, as in session{session_id=… side="daemon" …}:transfer: …, which tells concurrent sessions apart.

Stop it

SIGINT (Ctrl-C) stops the daemon cleanly: it closes its endpoint and flushes its telemetry. systemctl stop sends SIGINT with the unit above. The daemon installs no handler for SIGTERM, which launchd sends to stop a job and which is systemd’s default, so SIGTERM ends the process at once, without that flush. A session cut off either way resumes like any dropped connection. SIGHUP does not stop the daemon; it reloads the settings.

See also

Set a server up over ssh

When ssh myserver logs you in to the server, the first sync to myserver:PATH sets the server up: it installs irsync there, grants this client access, starts the daemon and saves myserver as a host alias. Your first sync walks through it. This page covers the options.

Run the setup again

Pass --ssh to go through ssh on purpose, for example to update irsync on the server after you updated the client:

irsync -av --ssh ~/Photos/ myserver:/srv/photos/

It runs the same setup for a saved host, then syncs.

Without --ssh, a sync goes through ssh again only when the daemon does not answer for about 15 seconds: then irsync says myserver did not answer; checking it over ssh, starts the daemon again and carries on. A daemon that answers but refuses the client is never “fixed” over ssh: that refusal is on purpose. The check never adds back an immediate grant you removed on the server either; the sync then stops with the same “rejected this client’s key” message.

Keep the daemon out of the public DHT

The daemon publishes its addresses in the mainline DHT, so later runs find it without ssh even when its IP address changes. To keep it out of that public table, pass --no-remote-dht:

irsync -av --no-remote-dht ~/Photos/ myserver:/srv/photos/

The setup then writes dht = false under [daemon.discovery] on the server. The daemon can still be found through DNS and the relay.

Use another ssh command

Use --rsh or IRSYNC_RSH for another ssh command:

irsync -av --rsh "ssh -p 2222" ~/Photos/ myserver:/srv/photos/

ssh is used only for the setup, never for the data.

Share only named directories

By default the setup lets the client reach any path your account on the server can (an immediate grant). If the client should not reach every path, set this on the server before the first sync:

irsync config set daemon.immediate false

The setup then grants nothing, and you grant exports by hand as in Your first sync.

A server with another OS or CPU

The setup copies the client’s own binary, so it works only when both machines run the same OS and CPU. Otherwise it stops with:

irsync: myserver is not a saved alias; setting it up over ssh
irsync: "myserver" is not an alias in ~/.config/irsync/irsync.toml and not an EndpointId; setting it up over ssh failed: myserver runs linux aarch64, this irsync is macos aarch64, so it cannot copy itself there. Install irsync on both machines and set the server up by hand: https://irsync.org/book/tutorial/first-sync.html#set-the-server-up-by-hand

Install irsync on the server yourself and set the server up by hand. Installing it on the server does not make the ssh setup work: the setup only uses its own copy of the client’s exact build. Release binaries, planned for the beta, will remove this step.

Keep the daemon running

A daemon started over ssh does not survive a reboot on its own; the next sync restarts it over ssh. To make it a user service, see Run the daemon.

Change exports and settings

A running daemon picks up most changes without a restart. Exports, grants and aliases apply from the next connection. The [daemon] settings apply when you send it SIGHUP. Only a few settings wait for the next start.

Run the commands on the daemon’s machine, as the daemon’s account and with the daemon’s --config (see Run the daemon).

Exports, grants and aliases

Edit them with the management commands, or by hand:

irsync export add music:/srv/music
irsync grant add music myclient
irsync grant remove photos phone

Nothing else is needed. The daemon reads irsync.toml, and any hosts.toml or exports.toml beside it, afresh on every accepted connection, once the handshake has proved the peer’s EndpointId. It takes the aliases, exports and grants from that read.

  • A grant remove or export remove does not end a session already in progress. It refuses new connections only.
  • If the file cannot be read or parsed, in any table, the daemon logs the error at warn with the file and the line, rejects that connection and keeps running. It does not fall back to an earlier copy. A missing file counts as empty.
  • A daemon with no exports starts, logs a warning naming the config file, and serves nothing until an export exists.

At startup, by contrast, a file that does not parse stops the daemon. The management commands check the file before they write it, so an edit made with them never leaves it unparsable; an edit by hand can.

When a client is refused

The daemon refuses a client in one of two ways:

  • A key that no grant names is closed on before the daemon reads any request.
  • A key with grants that asks for a path outside what it may use is refused with no access to PATH. The answer is the same whether the path is outside every export or missing.

Either way the client says that the daemon rejected its key for that address, and prints its own EndpointId with what to run on the daemon’s machine:

irsync grant list <id>
irsync grant add EXPORT <id>
irsync export add NAME:PATH

irsync grant list <id> shows what the key may reach. The daemon’s log shows rejecting unauthorized key or rejecting session, with the first ten hex digits of the client’s EndpointId.

How a path finds its export, and why a grant on an outer export reaches the exports inside it, is in Remote addresses.

Reload the daemon settings

  1. Change a [daemon] key:

    irsync config set daemon.idle_timeout 1h
    
  2. Send the daemon SIGHUP:

    kill -HUP <pid>
    

    Under the systemd unit from Run the daemon, systemctl reload irsync does the same.

The daemon re-reads the config file and applies listen, relay, relay_mode, congestion, portmap, the [daemon.discovery] table, identity, idle_timeout and dormant_session_timeout:

  • It binds a new endpoint with the new network settings and prints endpoint id: and listening on: again.
  • Sessions in progress finish on the connection they started on. A client that dials an address the daemon has given up is refused.
  • idle_timeout applies to the sessions accepted from then on.
  • A --listen given on the command line stays in force over the file’s listen.
  • A changed identity is applied and logged at warn, since clients need the new EndpointId.

A reload that cannot be applied, because the file does not parse, a port cannot be bound or the key cannot be read, is logged at warn, and the daemon keeps running as it was.

What waits for a restart

ChangeWhen it applies
state_dirAt the next start. A reload logs that it changed.
debug_addrAt the next start.
warm_index on an export the daemon has already openedAt the next start.
Removing an exportAt once for new connections; the export’s index stays open, and its hourly collection keeps running, until the next start.

The daemon opens an export’s index, and starts its hourly collection and its warm_index warm-up, the first time the export is used: at startup for the exports already in the file, and at the first connection naming an export added later. Exports with the same path share one index.

See also

Connect directly or through a relay

By default a client finds the daemon by its EndpointId, connects through a relay and moves to a direct path when hole punching succeeds. This page shows how to see which path a sync took, and how to change that: refuse relays, use your own relay, turn the lookups off, or dial a known address. Why it works this way is in Connections.

See which path a sync took

Run the sync with -vv:

irsync -avv ~/Photos/ myserver:photos/

The first line of the summary at the end of each session names the path, direct or relay:

session 1/1  push  ~/Photos/ -> myserver:photos/  wall 3:12  direct

The live progress block (--progress) shows the same word while the sync runs.

Refuse relays

A sync that cannot get a direct path then fails instead of running through a relay.

  • For one sync, on the client:

    irsync -a --no-relay ~/Photos/ myserver:photos/
    
  • For every sync to one host, or to every host:

    irsync host add myserver <id> --relay-mode disabled
    irsync config set client.relay_mode disabled
    
  • On the daemon, which then neither uses a relay nor is reachable through one:

    irsync config set daemon.relay_mode disabled
    

The lookups stay on. A daemon’s DNS and DHT records carry only its relay address, though, so a client that refuses relays finds the daemon through mDNS on the local network, or through an address you give it (below). A daemon with relays off and dht on logs a warning at start, since its DHT records would be empty.

Use your own relay

Clients and daemons behind a symmetric NAT on both ends cannot hole-punch and stay on the relay. A relay of your own, near the daemon, serves them better than the shared public relays. iroh ships one as iroh-relay.

  1. Run iroh-relay on a host both sides can reach.

  2. Point the daemon at it, then reload:

    irsync config set daemon.relay https://relay.example.net
    
  3. Point the client at it, for one host or for all:

    irsync host add myserver <id> --relay https://relay.example.net
    irsync config set client.relay https://relay.example.net
    

    For one sync, --relay URL does the same.

Turn the lookups off

  • On the client, --no-dht skips the mainline DHT for one sync. A host’s dht and mdns keys, or [client]’s, turn either lookup off for good:

    irsync host add myserver <id> --dht no --mdns no
    
  • On the daemon, [daemon.discovery] says where it publishes its addresses:

    irsync config set daemon.discovery.dht false
    irsync config set daemon.discovery.mdns false
    
  • For a server set up over ssh, --no-remote-dht on the client sets the daemon’s dht = false for you (see Your first sync).

Dial a known address

Two irsync processes on one machine, on one LAN, or anywhere without internet access need no relay and no lookup. listen alone only pins the sockets; it does not isolate the daemon. Turn everything off explicitly.

  1. On the daemon, in irsync.toml:

    [daemon]
    listen = ["127.0.0.1:0"]   # at most one IPv4 and one IPv6 entry; port 0 = daemon picks
    relay_mode = "disabled"
    portmap = false            # no UPnP/PCP/NAT-PMP gateway probing
    
    [daemon.discovery]
    dht = false
    dns = false
    mdns = false
    

    --listen ADDR on the command line replaces the listen list.

  2. Start the daemon and read its address from stdout:

    endpoint id: <id>
    listening on: 127.0.0.1:43210
    
  3. On the client, dial that address, for one sync or for good:

    irsync -a --address localhost:43210 ./src <id>:data/
    irsync host add local <id> --address 127.0.0.1:43210
    

    The second command writes this table:

    [hosts.local]
    endpoint_id = "<id>"
    address = ["127.0.0.1:43210"]
    

--address takes ip:port, [ipv6]:port or host:port, may be repeated, and resolves host names with the system resolver. With an address the client turns its relay, DNS, DHT, mDNS and port mapper off and talks to nothing but the addresses it was given. The daemon’s EndpointId is still required and still checked. --address together with --relay is refused.

See also

Seed the index

Use this when a destination already holds a copy of the data that irsync did not make: an earlier rsync, a restore from backup, a disk you copied by hand. Seeding hashes those files into the destination’s index first, so that the first session reuses their content for renamed and copied files instead of fetching it over the network.

irsync keeps one index per root under state_dir (see Configuration). The index only knows files that irsync has hashed: files it placed, files it updated, and files read by a -c run. Without seeding, a session still finds some reuse on its own: before it fetches a whole file of 64 KiB or more, it hashes up to four destination files of exactly that size that the index does not know yet. Seeding covers the rest.

Seeding never makes a wrong decision. Content taken from a local file is verified like any other, and an index row that has gone stale falls back to a fetch.

On the client, before a pull

Index the directory that the pull writes into. For irsync -a myserver:photos/ ~/Photos/ that is ~/Photos; for irsync -a myserver:photos ~/ it is ~/photos.

  1. See how much would be read:

    irsync index -n ~/Photos
    

    It prints one line per root: ROOT: N file(s), M to hash (B bytes).

  2. Hash the files:

    irsync index ~/Photos
    

    Files whose index row is still fresh (same size, modification time, change time, device and inode) are skipped, so running it again costs only the walk.

You can name several roots in one command. If a file cannot be read or a directory cannot be listed, irsync index reports it, carries on, and exits with code 23.

On the daemon, before a push

Run these on the daemon’s machine, as the account the daemon runs as and with the same --config, so that they write to the daemon’s state_dir.

  • Hash one export, or every export:

    irsync export update photos
    irsync export update all
    

    -n counts what would be hashed, as for irsync index. The daemon uses the new rows from its next session on.

  • Or let the daemon hash an export every time it starts, which suits an export whose files change outside irsync:

    irsync config set exports.photos.warm_index true
    

    For a new export, irsync export add photos:/srv/photos --warm-index does the same. The daemon hashes the export in the background when it starts, or at the first connection for an export added while it runs, and logs index warmed when done.

See also

Clean up state

An interrupted transfer leaves state behind on purpose, so that the next run can resume: partial files beside their destinations (or under --partial-dir), and a dormant session in the index under state_dir. Garbage collection removes what nobody is coming back for. It also forgets the index entries of files that are gone or were replaced.

Most of the time you need not do anything: the client and the daemon collect on their own. Run irsync gc when you want the space back now, or after you stopped syncing a directory for good.

What runs on its own

  • The client, at the start of each sync that is not a dry run, collects under that sync’s local root. It walks the root at most once a day, or sooner once a partial-file record has gone an hour without being touched. It removes partial files and sessions older than 7 days.
  • The daemon checks each export once an hour, starting a minute after the export’s index is opened. It walks an export at most once a day, unless partial-file records have become collectable since the last walk. It removes partial files and sessions older than dormant_session_timeout, 7 days by default (see Configuration). Each walk logs a summary at info. A file it cannot remove is logged and reported, and the walk carries on.

A partial file is kept as long as a stored session still plans to write it. An export that holds another export (such as a whole home exported automatically) leaves that inner export’s tree to its own collection; irsync gc does the same for indexes whose roots lie inside one another.

Collect by hand

  1. See what would go:

    irsync gc -n
    

    It lists every partial file it would remove, then a summary line: N part file(s), N session(s), N index entries would be removed.

  2. Remove it:

    irsync gc
    

irsync gc visits every root that has an index under state_dir: each local directory this account has synced or indexed, and the exports of a daemon that runs in this account with the same config. For each root it removes partial files and dormant sessions older than 7 days, and the index entries of regular files that are gone or were replaced by another file. Use --config PATH when the state_dir you mean is set in another config file.

An entry under a directory that could not be read is kept, since the file may only be unreadable. A walk that finds no file at all removes no entries, since the root may be a mount point whose file system is not mounted.

See also

Watch a transfer with telemetry

When a sync is slow, irsync can show where the time went (walking, hashing, waiting on the peer, writing, deleting) and what it cost in CPU, memory, disk I/O and bytes on the wire. One set of spans and metrics feeds three sinks, each off until you turn it on. The names and labels are listed in Metrics.

SinkTurn it onWhat you get
Summary-vv on the clientA block at the end of each session: wall time, busy time per activity, time waiting on the peer, CPU, peak memory, bytes on the wire, RTT and loss.
Debug HTTP port--debug-addr [IP:]PORT on the client; debug_addr under [daemon] for the daemon/metrics in the Prometheus text format, /debug/timing with wall and busy time per span name, and /debug/flame with folded stacks.
OpenTelemetryOTEL_EXPORTER_OTLP_ENDPOINT, or otlp_endpoint under [telemetry]Spans and metrics over OTLP.

With all three off the cost is a few untaken branches; the measurements are in Metrics.

Read the summary

Add -vv to the client:

irsync -avv ~/Photos/ myserver:photos/

At the end of each session it prints a block like this one:

session 1/2  push  ./photos -> nas:/backup  wall 3:12  direct, 1 reconnect
  busy      walk 21.0s  hash 9.3s ×4.0  read 1:02  send 1:48  delete 1.3s
  waiting   peer 44.0s  index 0.7s ×3.0
  transfer  1,882 files  3.41G literal  12.00G matched  17.77M/s
  hashing   2,107 files  15.30G  412.00M/s
  disk      read 15.40G  write 0  fsync 0.0s
  network   sent 3.52G  recv 41.00M  rtt 12ms (max 40ms)  lost 0.02%
  process   cpu 1:12 user, 0:31 sys  peak rss 312.00M  peak fds 214

busy and waiting show the wall time during which each activity ran, followed by ×N when on average N tasks, 1.5 or more, ran it at once. waiting peer is time this side had nothing to do. What each activity covers is in Busy time and peer wait.

Open the debug port

  1. On the client, add --debug-addr with a port, or IP:PORT; a bare port binds 127.0.0.1:

    irsync -a --debug-addr 9464 ~/Photos/ myserver:photos/
    

    After the sync the client prints irsync: debug port open at ADDR; Ctrl-C to exit and keeps the port open until SIGINT or SIGHUP, so that you can fetch the final numbers. --debug-port-no-wait closes the port when the sync ends instead.

    On the daemon, set debug_addr and restart the daemon:

    irsync config set daemon.debug_addr 127.0.0.1:9464
    

    The daemon prints debug port: ADDR at start and keeps the port open as long as it runs. If the port cannot be bound, it logs a warning and runs without it.

  2. Fetch what you need:

    curl -s localhost:9464/metrics
    curl -s localhost:9464/debug/timing
    curl -s localhost:9464/debug/flame
    

The port speaks plain, unauthenticated HTTP. Keep it on loopback or behind a firewall.

Draw a flamegraph

/debug/flame serves the self time of each span stack in microseconds, in the folded form that the inferno tools read. It keeps up to 10,000 distinct stacks and adds the rest up under [other].

  1. Install inferno:

    cargo install inferno
    
  2. Run the sync with --debug-addr 9464. When it finishes, while the client waits for Ctrl-C, render the graph:

    curl -s localhost:9464/debug/flame | inferno-flamegraph > f.svg
    

The stacks are irsync’s own spans, so the graph shows time per phase and per file, not per function.

Trace single files

Per-file spans, file and its children, are off by default, because a tree of tens of thousands of files would swamp a trace. Set IRSYNC_TRACE_FILES=1 to send them to the span sinks: OTLP, /debug/timing and /debug/flame.

IRSYNC_TRACE_FILES=1 irsync -a --debug-addr 9464 ~/Photos/ myserver:photos/

Set it on the daemon’s side to get the daemon’s per-file spans.

Export over OpenTelemetry

  1. Point irsync at a collector, with the environment or in the config file:

    export OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318
    irsync config set telemetry.otlp_endpoint http://127.0.0.1:4318
    

    [telemetry] applies to the client and the daemon alike. The daemon reads it at start.

  2. Run a sync. The client’s session span starts a trace. The client sends its W3C trace context to the daemon, whose session span joins it as a child when the daemon exports too, so one sync is one trace across both machines.

Export is on when OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT or OTEL_EXPORTER_OTLP_METRICS_ENDPOINT is set, or otlp_endpoint is in the config file; the environment wins. The protocol is OTEL_EXPORTER_OTLP_PROTOCOL (grpc or http/protobuf), else otlp_protocol (grpc or http), else HTTP.

The other standard OTEL_* variables are honoured: headers, timeouts, the sampler, OTEL_SERVICE_NAME (by default irsync for the client and irsync-daemon for the daemon), OTEL_RESOURCE_ATTRIBUTES and OTEL_METRIC_EXPORT_INTERVAL. Metrics are exported every 10 seconds, unless OTEL_METRIC_EXPORT_INTERVAL says otherwise, and once more at exit. An empty OTEL_METRIC_EXPORT_INTERVAL counts as unset. The exit flush takes at most 2 seconds.

The daemon samples every session unless OTEL_TRACES_SAMPLER is set on its side: the sampled flag in the client’s trace context does not suppress the daemon’s spans, which then join the client’s trace id even when the client dropped its own. The client keeps the SDK’s default sampler, which follows the parent and is otherwise always on.

Export needs the cargo feature otel, which is on by default. A build without it warns and ignores the OTLP settings.

Local collector

The repository has a Docker Compose setup with an OpenTelemetry collector, Jaeger and Prometheus: compose.yaml, collector.yaml and prometheus.yml.

  1. In a clone of the repository, start it:

    docker compose -f docs/telemetry/compose.yaml up -d
    

    The collector listens on 4317 (gRPC) and 4318 (HTTP). Jaeger’s UI is on http://localhost:16686, Prometheus on http://localhost:9090. Prometheus scrapes host.docker.internal:9464 every 5 seconds.

  2. Run a sync that exports over OTLP and opens the debug port on 9464:

    OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 \
      irsync -a --debug-addr 9464 src/ HOST:export/
    
  3. Look at the results. Jaeger shows the session trace. Prometheus has the metrics from the debug port. The metrics sent over OTLP go to the collector’s debug exporter, in its log.

  4. Stop it:

    docker compose -f docs/telemetry/compose.yaml down
    

See also

Command line

irsync [OPTIONS] SRC... DEST
irsync [OPTIONS] HOST:[PATH]
irsync COMMAND ...

irsync --help prints the same flags with one line each; irsync COMMAND --help does so for a subcommand.

Operands

Each operand is a local path or HOST:PATH. HOST is a host alias from the configuration or an EndpointId; PATH is resolved on the daemon’s machine, as described in Remote addresses.

A HOST that is neither is taken as an ssh destination, such as myserver or me@myserver. irsync then sets that machine up over ssh before it syncs: it copies itself there when the server has no matching build, grants this client access to any path ([immediate]), starts the daemon and saves HOST as an alias with ssh = "HOST". It prints what it did. Later runs dial the alias over iroh and do not use ssh. A sync to an alias with ssh dials once and waits at most 15 seconds (--dial-retries sets how often it retries first). When the daemon does not answer, irsync checks the server over ssh once, starts the daemon again or updates the alias, and retries with the usual --dial-retries and --reconnect settings. That check never adds back an immediate grant removed on the server. When ssh itself fails, irsync says so and tries the daemon once more with the usual settings; if that fails too, it reports both errors. A daemon that answers and refuses the client is never handled over ssh. See the quick way.

  • A : before the first / makes an operand remote, as in rsync. To name a local file whose name has a colon, write ./name:with:colons.
  • Exactly one side is remote. A push (local to remote) may have several sources; each one runs as its own session, one after the other. A pull has one source.
  • rsync’s trailing-slash rule holds on both sides: Photos/ copies the directory’s contents, Photos copies the directory itself.
  • A single remote operand lists instead of copying. irsync HOST: prints the exports this client may reach, one NAME PATH ACCESS line each, where ACCESS is rw or ro with the export’s read_only applied. irsync HOST:PATH prints the files a pull would fetch and writes nothing; it recurses unless --no-recursive is given. A listing does not redial: if the connection fails, it exits instead of waiting out the reconnect window.

The daemon honours the client’s flags in both directions, filters included.

rsync-compatible flags

These have rsync’s spelling and meaning. The flags that have rsync’s spelling and a different meaning follow in the next table.

FlagMeaning
-a, --archiveArchive mode, the same as -rlptgoD.
-r, --recursiveRecurse into directories (implied by -a). Without recursion only the top-level entries are transferred, and directories are skipped.
--no-recursiveTurn off the recursion that -a implies. Also spelled --no-r.
-d, --dirsWithout recursion, transfer directories without their contents.
-l, --linksCopy symlinks as symlinks. Without it they are skipped.
-p, --permsPreserve permissions.
-t, --timesPreserve modification times.
-g, --groupPreserve the group, where the receiving user may set it.
-o, --ownerPreserve the owner, only when the receiving side runs as root.
-DThe same as --devices --specials.
--devicesPreserve character and block device nodes.
--specialsPreserve FIFOs. Sockets are never copied.
-H, --hard-linksFiles linked together in the source are linked together in the destination.
-v, --verboseList each file transferred, and end with rsync’s sent … received … and total size is … lines. -vv adds a summary of time, CPU, memory and bytes at the end of each session, and info logs; -vvv debug logs, -vvvv trace logs.
-q, --quietPrint errors only. Also turns the live progress block off.
-n, --dry-runChange nothing on either side. With -v or -i, list what would be done.
-c, --checksumCompare by content, not by size and time: every file on both sides is read, no cached hash is trusted, and the index is refreshed from what was read.
-u, --updateSkip files that are newer on the destination.
--delete-beforeDelete before the transfer, once both sides are listed.
--delete-duringDelete each directory’s extraneous entries as the run leaves that directory, so space is freed as the run goes.
--delete-afterDelete after the transfer; what --delete does.
--max-delete NStop deleting after N removals. The run exits with code 25.
--exclude PATTERNExclude paths that match an rsync pattern: *, **, ?, [...]; a leading / anchors the pattern to the root, a trailing / matches directories only.
--include PATTERNInclude paths that match, even if a later --exclude would hide them.
--exclude-from FILERead exclude patterns from FILE, one per line. Blank lines and lines that start with # or ; are skipped.
--include-from FILERead include patterns from FILE, as --exclude-from does.
--bwlimit RATELimit the rate. A bare number is KiB/s. K, M, G, T, P (also KiB to PiB) are powers of 1024, KB to PB powers of 1000, b is bytes; decimals are allowed (1.5M). 0 means no limit.
--numeric-idsApply owner and group ids as sent. By default the sender’s user and group names are mapped to the receiver’s ids where they exist, as rsync does.
--partial-dir DIRKeep the partial files of interrupted transfers under DIR, relative to the destination root, instead of beside their files. On a pull DIR may be absolute; on a push the daemon keeps them, and only a relative DIR inside the destination is allowed.
--inplaceWrite a changed file into the destination itself instead of into a temporary file renamed over it. No second copy is needed on disk, but readers see a torn file during the transfer and a crash leaves a mixture.
--appendExtend a destination file that is shorter than the source with the source’s tail, trusting what is already there. A destination that is not shorter is skipped.
--append-verifyLike --append, but the existing prefix is verified too.
--fsyncFlush each received file to disk before renaming it into place, on whichever side receives (the daemon, on a push). Off by default, as in rsync: a power loss or kernel crash in the seconds after a run can then leave a file at its name with the right size and time but not its content, which the next run’s quick check does not notice (-c does). An export’s fsync = true turns it on for every push into it.
--paranoidGuard against source files that change during the sync, including writers that leave the times alone (memory-mapped databases; tested on ZFS 2.4 clones only, see the page linked below). The sending side (on a pull, the daemon) sends each file from a reflink clone where the filesystem can make one (btrfs, xfs, ZFS 2.2 and newer with block cloning, bcachefs, APFS), and otherwise hashes the file a second time before the receiver places it. At the end it checks every listed file again and sends those that changed. Files that vanished give exit 24. Cost: one clone and one delete per sent file where cloning works; an extra full read per sent file elsewhere; one stat per listed file at the end. Clones live in .irsync-clones-<uid> in a writable directory on the file’s filesystem. See Files that change during a sync.
--ignore-errorsRun the deletion pass even when a listing was cut short by I/O errors.
--statsPrint a block of transfer statistics at the end.
-i, --itemize-changesPrint rsync’s per-file change summary, the itemize codes.
-h, --helpPrint the flags.
-V, --versionPrint the version and the commit it was built from.

Filter rules apply in command-line order, and the first rule that matches wins.

rsync spelling, different meaning

Flagirsyncrsync
--deleteDelete destination files that are gone from the source, after the transfer, the same as --delete-after. Nothing is deleted without one of the --delete flags.The same as --delete-during.
--delete-excludedAlso delete destination files that the filters exclude. Implies --delete, so the deletions run after the transfer.Implies --delete, so the deletions run during the transfer.
-S, --sparseLeave chunks that are all zeros as holes. Without it, only files that are sparse in the source are written sparse.Finds runs of zeros at write granularity, not only whole chunks.
--timeout SECSDrop a connection that moves no data and no control message for SECS seconds; the session then reconnects. 0, the default, means no timeout.A connection idle for SECS seconds ends the run with code 30.
--progressDraws the live progress block (see Output) when stdout is a terminal.Prints the progress of each file.
-PThe same as --progress. irsync always keeps partial files.The same as --partial --progress.
--info SPECOnly progress1 and progress2 are read, as --progress; the rest is ignored.Selects informational output, such as the progress of the whole transfer with --info=progress2.

Deletions

Nothing is deleted that might merely have been unreadable. When a listing on either side is incomplete, because a directory could not be read or an entry could not be examined, deletions stop from that point on: --delete-before and --delete-after then delete nothing, and --delete-during stops at the directory where the gap was found. --ignore-errors deletes anyway. Combine --delete with -n first to see what it would remove.

Output

As in rsync, a sync prints nothing on stdout by default. Errors and warnings go to stderr, each failed file as it fails. -v lists each file transferred and ends with the sent … received … and total size is … lines; -q prints errors only.

With --progress (or -P) on a terminal, the client draws a live block at the bottom of the screen: the listing walk on both sides, a transfer bar with rsync’s percent semantics, one row per file that is being hashed or has a data stream open and is not yet sent in full, and the deletion pass. The rows are as many as half the terminal’s height allows, largest file first; a last line … and N more counts the others. The transfer bar’s N in flight counts these files, including those beyond the rows drawn. It is not the session’s window of up to 4,096 files in flight described in Files in flight and streams: a file in that window that is neither being hashed nor has a stream open has no row and is not counted. While the block is drawn, failed files show in its errors section instead of scrolling, and the full list goes to stderr once the block is cleared at the end. -q turns the block off. When stdout is not a terminal, or TERM is dumb, the block is not drawn and the output is plain lines.

irsync flags

These have no rsync counterpart.

FlagMeaning
--parallel NData streams a push keeps open at once, across all files. Default: parallel from the host entry, else from [client], else 128. A pull uses the daemon’s 128. See Files in flight and streams.
--reconnect DURHow long to keep redialling after a dropped connection, as <N>[s|m|h|d]. 0 gives up at once, like rsync. Default: reconnect from the host entry, else from [client], else 24h. This window applies only once the server has answered; before that, --dial-retries applies.
--dial-retries NHow often to retry a server that has not answered yet, before the run gives up. The waits grow: about 1, 2, 4, 8 seconds and so on, capped at a minute. 0 gives up on the first failure. Default: dial_retries from the host entry, else from [client], else 4.
--relay URLUse this relay server instead of the host entry’s, [client]’s or n0’s default. Cannot be combined with --no-relay or --address.
--no-relayDirect connections only: never fall back to a relay. The address lookups stay on. Default: relay_mode from the host entry, else from [client].
--no-dhtDo not look the daemon up in the mainline DHT.
--address ADDRDial the daemon at ip:port, [ipv6]:port or host:port directly; repeatable. Turns the relay, DNS, DHT, mDNS and the port mapper off. The daemon’s EndpointId is still required and still checked.
--config PATHThe config file. Default: ~/.config/irsync/irsync.toml. A hosts.toml or exports.toml beside it is read too.
--rsh CMDThe remote shell for the ssh setup, split on spaces like rsync’s -e, for example --rsh "ssh -p 2222". Default: IRSYNC_RSH, else ssh.
--sshGo through ssh even for a saved host: install or update irsync on the server, check its daemon and the grant, then sync. Uses the host’s ssh destination, else the alias. Default: off; a saved host is reached over iroh only.
--no-remote-dhtWhen setting the server up over ssh, turn its DHT publishing off ([daemon.discovery] dht = false); a running daemon re-reads its settings. Goes through ssh for a saved host too, like --ssh. Without it the server’s setting is left alone, and new servers publish.
--identity FILEThe private key to connect with. Default: identity in the config file, else ~/.config/irsync/id_ed25519 when it exists, else ~/.ssh/id_ed25519 when it exists, else a key generated at ~/.config/irsync/id_ed25519. A named file is the whole answer: when it is missing, a key is generated there.
--passphrase-file PATHRead the passphrase of an encrypted key from the first line of this file. Without it, IRSYNC_PASSPHRASE is used, else a prompt when stdin is a terminal.
--no-resumeStart a fresh plan instead of resuming a dormant session. Partial files are still picked up.
--no-rename-detectionDo not fill files from other files on the receiving side that hold the same content or parts of it, so a moved or copied file is transferred again. A changed file still reuses its own old version.
--debug-addr ADDRServe metrics and span timings over HTTP at IP:PORT; a bare port means 127.0.0.1. The port stays open after the sync until SIGINT or SIGHUP.
--debug-port-no-waitWith --debug-addr, close the port when the sync ends instead of waiting.

The connection settings resolve in this order: the flag, then the host alias’s table, then [client], then the built-in default. See Configuration.

Subcommands

CommandWhat it does
irsync daemonRun the daemon. See below.
irsync indexHash the files under local roots into their index. See Seed the index.
irsync gcRemove abandoned partial files, dormant sessions and stale index entries. See Clean up state.
irsync host, export, grant, id, config, showManage aliases, exports, grants, identities and settings. See Management commands. irsync grant add immediate WHO lets WHO reach any path, read-write; it is what the ssh setup grants.

irsync daemon

irsync daemon [--config PATH] [--passphrase-file PATH] [--listen ADDR]... [-v|-q]

Serves the exports in the config file to the peers they are granted to, until it is interrupted. At start it prints endpoint id: <EndpointId> and one listening on: <socket> line per bound socket on stdout. Logs go to stderr at info level; -v gives debug, -vv trace, -q errors only, and RUST_LOG overrides all of them.

FlagMeaning
--config PATHThe config file. A hosts.toml or exports.toml beside it is read too.
--passphrase-file PATHRead the passphrase of an encrypted daemon key from the first line of this file.
--listen ADDRBind this socket (ip:port, [ipv6]:port or host:port; port 0 lets the system pick) instead of the config’s listen list. Repeatable, at most one IPv4 and one IPv6.
-v, --verboseLog more; repeat for more still.
-q, --quietLog errors only.

irsync index

irsync index [-n] [-v|-q] [--config PATH] ROOT...
FlagMeaning
-n, --dry-runWalk and count what would be hashed; read nothing.
-v, --verboseLog more.
-q, --quietLog errors only and print no summary.
--config PATHThe config file, for state_dir.

irsync gc

irsync gc [-n] [-v|-q] [--config PATH]
FlagMeaning
-n, --dry-runList what would be removed without removing anything.
-v, --verboseLog more.
-q, --quietLog errors only and print no summary.
--config PATHThe config file, for state_dir.

Environment

VariableEffect
IRSYNC_PASSPHRASEThe passphrase of an encrypted key, when no --passphrase-file is given.
IRSYNC_RSHThe remote shell for the ssh setup, when no --rsh is given.
RUST_LOGThe log filter, in place of the one -v and -q choose.
OTEL_EXPORTER_OTLP_ENDPOINTExport traces and metrics over OpenTelemetry to this endpoint. Overrides [telemetry] in the config file.
TERMdumb turns the live progress block off.

Exit codes

CodeMeaning
0Success.
1Nothing got through: a configuration, identity or connection error; an operand pair irsync rejects (both sides local, both remote, several sources on a pull); or every source failed.
2The command line could not be parsed: an unknown flag, a bad value, a missing operand.
23Partial transfer: some files could not be transferred, or some sources of a push failed while others synced.
24Some source files vanished. Only --paranoid, in its final re-check, gives this.
25Deletions stopped at --max-delete.

Of these, 23, 24 and 25 have rsync’s meaning; 1 and 2 do not (rsync uses 1 for a syntax or usage error and 2 for a protocol incompatibility).

When several apply, 1 wins over 25, 25 over 23, and 23 over 24. A file listing, irsync HOST:PATH, is a dry-run pull and uses the same codes; the export listing, irsync HOST:, exits 0 or 1.

The other commands exit 0 on success and 1 on an error, with these additions: irsync index and irsync export update exit 23 when a file could not be read or a directory could not be listed, and irsync config get exits 1 for a key that is not set and has no default.

Management commands

These commands read and edit the config file, ~/.config/irsync/irsync.toml (see Configuration). There are three nouns, host, export and grant, each with add, remove and list, plus export update; id for the identities; config for any key by its dotted path; and show for an overview.

Every management command takes --config PATH to use another file. For a noun the flag may stand before or after the verb: irsync export --config C add ... and irsync export add ... --config C are the same.

Editing rules

  • The commands keep the file’s comments and layout. A missing file is the same as an empty one; the first edit creates it.
  • While a command edits the file, irsync.toml.lock sits beside it, and a second editing command is refused. Delete the lock only if no irsync is running.
  • The edited file is checked before it is written. An edit that would leave a file irsync cannot load is refused, and the file stays as it was.
  • When a hosts.toml or exports.toml sits beside the config file, irsync reads it but never edits it. host, export, grant and config set refuse a table that such a file holds, and tell you to move the table into irsync.toml or to edit that file by hand.
  • An export name may not be empty, contain /, or be all. An alias may not be empty, contain : or /, be all or *, or be an EndpointId.

A running daemon picks up host, export and grant changes on its next connection; nothing needs a restart.

host

CommandEffect
irsync host add ALIAS ID [--relay URL] [--relay-mode default|disabled] [--address ADDR]... [--parallel N] [--reconnect DUR] [--dial-retries N] [--dht yes|no] [--mdns yes|no]Add an alias for an EndpointId, or change the id and the keys given for an existing alias. Keys not given stay as they are. Prints ALIAS: ID, or ALIAS: OLD -> NEW when the id changed.
irsync host remove ALIASRemove an alias.
irsync host listOne ALIAS: ID line per alias, then one indented key = value line per other key.

The flags of host add set the keys of the alias’s table; see Configuration for what each does. --address replaces the stored list and may be repeated. --dht and --mdns take yes or no (also true or false).

On a daemon’s machine the same aliases name the clients that exports are granted to.

export

CommandEffect
irsync export add NAME:PATH [--ro] [--warm-index]Export a directory under NAME. Prints the daemon’s EndpointId on stdout, generating the daemon’s key if it does not exist yet.
irsync export add PATH [--ro] [--warm-index]The same, named after the directory’s last component.
irsync export remove NAMEStop exporting a directory. Its grants go with it.
irsync export listOne block per export: NAME: PATH, then read_only, warm_index and fsync when set, then its grant lines.
irsync export update [-n] [-v|-q] NAME...Hash the files of the named exports into their indexes, so that files irsync did not place are reused from the next session on. all names every export. -n counts what would be hashed. See Seed the index.

export add joins a relative PATH onto the working directory, expands a leading ~ (irsync export add home:~ exports the home directory), and requires an existing directory. The text before the first : is a name only when it has no /. --ro sets read_only, which refuses pushes from everyone; --warm-index sets warm_index.

grant

CommandEffect
irsync grant add EXPORT WHO [--ro]Grant WHO read-write access to EXPORT, or read-only access with --ro. EXPORT may be all, for every export. An earlier grant of the same peer there is replaced.
irsync grant remove EXPORT WHORemove WHO’s grant on EXPORT. irsync grant remove all WHO removes WHO everywhere; irsync grant remove EXPORT all empties an export’s grants.
irsync grant add immediate WHOLet WHO reach any path this account can, read-write (there is no --ro here). The daemon makes an automatic export for each new path WHO uses. See Immediate grants.
irsync grant remove immediate WHOTake WHO out of [immediate]. The automatic exports already made for it stay in the file, but WHO can no longer use them.
irsync grant listEvery grant: an all: block, an immediate: block, then one block per export.
irsync grant list EXPORTOne export’s grants; all lists those that apply to every export, immediate the peers that may reach any path.
irsync grant list WHOWhat one peer may reach: immediate: rw first when it is in [immediate], then one NAME: rw or NAME: ro line per export, marked (all) when the grant comes from [all] and (read_only export) when a read-write grant is capped by read_only.

WHO is an alias, an EndpointId, a pasted ssh-ed25519 AAAA... public key line, or the path of a .pub file holding one. A key’s comment is kept as a TOML comment beside the entry. There is no open access: all and * are refused as WHO in grant add.

id

CommandEffect
irsync id show [--passphrase-file PATH]Print client:, then the client’s public key line and EndpointId, generating the key if no key serves. On a machine that also has a daemon key, a note on stderr says that clients connect to the daemon’s EndpointId and that irsync id show --daemon prints it.
irsync id show --daemonThe same for the daemon, under daemon:. Never generates the daemon’s key: without one it fails and says how to make one.
irsync id show -aBoth, each under its label.
irsync id generate [--daemon | --out PATH] [-f]Write a new Ed25519 key pair at the client’s path (default), the daemon’s path, or PATH, with the public key beside it as .pub, and print the public key line and EndpointId. Refuses to overwrite an existing key or .pub file unless given -f/--force.

The client’s key is found the way ssh picks one; see Configuration. After irsync id generate has written ~/.config/irsync/id_ed25519, ~/.ssh/id_ed25519 is no longer consulted. Replacing a key with --force is permanent: every grant made for the old key stops working.

config

CommandEffect
irsync config get KEYPrint a key: a bare scalar, one array element per line, or a table’s keys as key = value lines, all as the file holds them (a path’s ~ is not expanded). An unset setting prints its default; a key with no value and no default exits 1.
irsync config set KEY VALUE...Set a key in its type: true or false, an integer, a duration such as 30m, a path, a URL, an EndpointId. An array key takes one VALUE per element, and none for an empty array. Tables are created as needed.
irsync config unset KEYRemove a key, or a whole table (irsync config unset hosts.myserver). A table left empty goes with it.
irsync config listEvery key the files set, as dotted.key = value, in file order.

KEY is a dotted path such as daemon.listen or hosts.myserver.relay. Quote a segment that holds a dot: exports."www.example.com".path. An unknown key is an error.

config writes what you say; the nouns know what you mean. export add joins a relative path onto the working directory and checks that the directory exists, and grant add reads a pasted key line or a .pub file. In contrast, irsync config set exports.photos.path ./x is refused, because the file wants an absolute path, and irsync config set exports.photos.rw ~/myclient.pub writes that string as a grant entry that matches nobody.

show

irsync show [--passphrase-file PATH]

Prints the config file’s path, the client’s EndpointId and public key line, the file that holds the aliases and the aliases as host list prints them, the file that holds the exports, the daemon’s EndpointId, and the exports as export list prints them, followed by the [all] grants. A split file is marked (also read). show generates either key if it does not exist yet.

Remote addresses

A remote operand is HOST:PATH.

  • HOST is an alias from a [hosts.ALIAS] table (see Configuration) or an EndpointId, in hex or z-base-32 as iroh prints it. Aliases match exactly; there are no patterns. The client pins the EndpointId it dials: a daemon with another key fails the connection.
  • PATH is sent to the daemon as typed and resolved on the daemon’s machine. The client does not interpret it, apart from the trailing slash.

An operand is remote when it has a : before its first /, as in rsync. HOST may not be empty.

Resolution order

The daemon reads PATH in this order:

  1. An export name, then a path inside it. When the first component of a relative PATH names an export, the rest is resolved under that export’s directory: myserver:photos/2024 is 2024 inside the photos export.
  2. A path relative to the home directory of the account the daemon runs as. myserver:Pictures is ~/Pictures on the daemon’s machine; myserver: and myserver:~ are the home directory itself, and myserver:~/Pictures is the same as myserver:Pictures.
  3. An absolute path, as is: myserver:/backup/myclient.

. and empty components are dropped. A .. component or a NUL byte is refused.

Exports decide access

Whatever the spelling, the resolved path must lie inside an exported directory that the client has a grant for, and that export’s grants apply. A path outside every export the client may use is refused as “no access”, whether or not it exists, so the answer reveals nothing about the daemon’s file system.

Exports may be nested. A grant reaches everything below its export’s directory, exports nested inside it included. When the path lies inside several exports the client may use:

  • the export with the longest path decides the session’s root and access;
  • between exports with the same path, the one the operand named wins, then the one with the better access (read-write over read-only, read_only applied).

Exports the client has no grant for take no part. A grant on an outer export is therefore not stopped by an inner export, not even by a read_only inner one, and the answer for a path never depends on where ungranted exports sit.

To open everything the daemon’s account can reach, export the root, and grant it:

irsync export add root:/

irsync export add home:~ exports the home directory.

Trailing slashes

rsync’s trailing-slash rule holds on both sides. A source that ends in / copies the directory’s contents; one without copies the directory itself.

CommandResult on the daemon
irsync -a ~/Photos/ myserver:photos/The contents of ~/Photos in the photos export.
irsync -a ~/Photos myserver:photos/~/Photos as Photos inside the photos export.
irsync -a myserver:photos/ ~/copy/The contents of the export in ~/copy.
irsync -a myserver:photos ~/copy/The export as ~/copy/photos.

Listing

A single remote operand lists instead of copying:

  • irsync myserver: prints the exports this client may reach, one NAME PATH ACCESS line each, ACCESS being rw or ro with read_only applied.
  • irsync myserver:photos/ prints the files a pull would fetch, and writes nothing. It recurses unless --no-recursive is given.

Configuration

One file holds everything: ~/.config/irsync/irsync.toml. It is optional; a missing file is the same as an empty one, and every key has a default except where noted. The management commands edit it for you and keep its comments; irsync config reads and writes any key; you can also edit it by hand.

Every command takes --config PATH to use another file. Unknown keys and tables are errors that name the file, the line and the key.

Split files

To keep the aliases or the exports apart, put a hosts.toml holding the [hosts.*] tables, or an exports.toml holding [all] and [exports.*], beside the config file. They are read as if they were part of it. A table must then live in only one of the two files. irsync never edits a split file: host, export, grant and config set refuse a table it holds. irsync show names any split file it read.

Values

  • A duration is <N>[s|m|h|d], such as 90s, 30m, 1h or 7d; a number without a unit, as a string or as a TOML integer, is seconds.
  • A path may start with ~, which stands for the home directory.
  • An EndpointId is hex or z-base-32, as iroh prints it.
  • An address is ip:port, [ipv6]:port or host:port.

The whole file

Every table, with the defaults except where marked:

identity = "~/.config/irsync/id_ed25519"
state_dir = "~/.local/state/irsync"

[client]                     # defaults for every host
parallel = 128
reconnect = "1d"
dial_retries = 4
dht = true
mdns = true
relay = "https://relay.example.net"   # no default: n0's relays
relay_mode = "default"       # or "disabled": direct connections only
congestion = "bbr"           # or "cubic", for pushes

[daemon]
identity = "~/.config/irsync/daemon_ed25519"
idle_timeout = "30m"         # "0" disables
dormant_session_timeout = "7d"
listen = ["0.0.0.0:4000", "[::]:4000"]   # no default: any address, a port picked at start
portmap = true               # UPnP, PCP and NAT-PMP
relay = "https://relay.example.net"      # no default: n0's relays
relay_mode = "default"       # or "disabled"
congestion = "bbr"           # or "cubic", for pulls
debug_addr = "127.0.0.1:9464"            # no default: off
immediate = true             # false: ignore [immediate]

[daemon.discovery]
dht = true
dns = true
mdns = true

[telemetry]
otlp_endpoint = "http://localhost:4318"  # no default: off
otlp_protocol = "http"       # or "grpc"

# One [hosts.ALIAS] table per remote. On a daemon's machine the same tables
# name the clients that exports are granted to.
[hosts.myserver]
endpoint_id = "4a29f16a4f80a3fd171ef5573c106dbda470ec24f5a97933752746b567ab9aff"
relay = "https://relay.example.net"   # the rest is optional
relay_mode = "disabled"
congestion = "cubic"
address = ["192.168.1.10:4000"]
parallel = 64
reconnect = "1h"
dial_retries = 2
dht = false
mdns = false
ssh = "myserver"             # set by the SSH setup: the ssh destination

[hosts.myclient]
endpoint_id = "a3e4753e5ea74e64e745e9c4d10b0fd751dbe03049d742eb0ea545c89703dfba"

# What the daemon shares and with whom. Entries in rw and ro are aliases
# from [hosts.*] or EndpointIds.
[all]                        # grants for every export
rw = []
ro = []

[exports.photos]
path = "/srv/photos"
rw = ["myclient"]
warm_index = false
fsync = false

[exports.docs]
path = "/srv/docs"
read_only = true
ro = ["myclient"]

# Peers that may reach any path this account can, read-write. The SSH
# setup adds the client here.
[immediate]
rw = ["myclient"]

# Made by the daemon the first time an [immediate] peer used /srv/music.
[exports.auto-srv-music]
path = "/srv/music"
auto = true
rw = ["a3e4753e5ea74e64e745e9c4d10b0fd751dbe03049d742eb0ea545c89703dfba"]

Identity and state

KeyDefaultMeaning
identity~/.config/irsync/id_ed25519The client’s private key, an OpenSSH Ed25519 key file.
state_dir~/.local/state/irsync; $XDG_STATE_HOME/irsync when that is setWhere the client and the daemon keep their indexes, sessions and partial-file records.

The client’s key is looked up the way ssh picks one: --identity; else identity when the file sets it; else ~/.config/irsync/id_ed25519 when it exists; else ~/.ssh/id_ed25519 when it exists, read as it is and never written; else a key generated at ~/.config/irsync/id_ed25519. A key named by --identity or identity is the whole answer: when it is missing, a key is generated there. An encrypted key needs a passphrase, from --passphrase-file, IRSYNC_PASSPHRASE or a prompt on a terminal. Only file-based Ed25519 keys work.

The client and the daemon use different keys, so both can run in one account on one machine and reach each other.

Client

[client] holds the defaults for every sync. A host’s table overrides them for that host, and a command-line flag overrides both: a sync resolves each setting from the flag, then the alias’s table, then [client], then the built-in default.

KeyDefaultMeaning
parallel128Data streams a push keeps open at once. Flag: --parallel.
reconnect1dHow long a sync keeps redialling after a dropped connection; 0 gives up at once. Flag: --reconnect.
dial_retries4How often a sync retries a server that has not answered yet, waiting about 1, 2, 4, 8 seconds and so on between tries, before it gives up; 0 gives up on the first failure. reconnect applies only once the server has answered. Flag: --dial-retries.
dhttrueLook daemons up in the mainline DHT. Flag: --no-dht.
mdnstrueLook daemons up with mDNS on the local network.
relayn0’s relaysThe relay server to use, for a self-hosted relay. Flag: --relay.
relay_modedefaultdisabled: direct connections only, never through a relay; the lookups stay on. Flag: --no-relay.
congestionbbrQUIC’s congestion controller when the client sends, that is for a push: bbr or cubic.

congestion picks the congestion controller of the side that sends: the client’s (the host’s, else [client]’s) for a push, the daemon’s for a pull. When to choose cubic over bbr, with measurements, is in Connections.

Hosts

[hosts.ALIAS] names a remote by its EndpointId. On a client it names the daemons you dial; on a daemon’s machine it names the clients that grants may refer to. An alias may not be empty, contain : or /, be all or *, or be an EndpointId.

KeyDefaultMeaning
endpoint_idrequiredThe remote’s EndpointId. The client pins it.
relay[client]’sThis host’s relay server.
relay_mode[client]’sdisabled: reach this host directly only.
congestion[client]’sThe congestion controller for pushes to this host.
addressnoneDial these addresses directly, with the relay, DNS, DHT, mDNS and the port mapper off. Cannot be combined with --relay.
parallel[client]’sData streams a push to this host keeps open at once.
reconnect[client]’sHow long to keep redialling.
dial_retries[client]’sHow often to retry this host before it has answered.
dht[client]’sLook this host up in the mainline DHT.
mdns[client]’sLook this host up with mDNS.
sshnoneThe ssh destination this host was set up through, such as myserver or me@myserver. The SSH setup writes it. When a sync to a host with ssh gets no answer within about 15 seconds, irsync checks it over ssh once: it starts the daemon again, and updates endpoint_id if the server’s identity changed. It does not add back an immediate grant that was removed on the server. The export listing, irsync HOST:, is not checked this way. A host without ssh is never touched over ssh.

--address on the command line replaces the host’s address list.

Daemon

[daemon] configures irsync daemon. On SIGHUP the daemon re-reads this table and rebinds; changes to debug_addr and to the top-level state_dir take effect at the next start.

KeyDefaultMeaning
identity~/.config/irsync/daemon_ed25519The daemon’s private key, generated when missing.
idle_timeout30mDrop an authenticated connection that has had no traffic and no local progress, such as hashing or writing, for this long. The client reconnects and resumes. 0 disables it.
dormant_session_timeout7dHow long the daemon keeps an interrupted session, and its partial files, for a client to resume.
listennoneThe sockets to bind, at most one IPv4 and one IPv6; port 0 lets the system pick. Without it the daemon binds any address on a port picked at start. Flag: --listen.
portmaptrueAsk the router for a port mapping with UPnP, PCP or NAT-PMP. Set false in isolated setups.
relayn0’s relaysThe relay server to use, for a self-hosted relay.
relay_modedefaultdisabled: no relay, direct connections only.
congestionbbrThe congestion controller when the daemon sends, that is for a pull.
debug_addroffServe metrics and span timings over HTTP at IP:PORT; a bare port means 127.0.0.1.
immediatetrueHonour the [immediate] grants. false: the daemon ignores [immediate] and makes no automatic exports, so peers reach only the exports granted to them.

[daemon.discovery] says how clients may find the daemon:

KeyDefaultMeaning
dhttruePublish the daemon’s addresses in the mainline DHT. With relays disabled the records carry no addresses, and the daemon warns.
dnstruePublish them through n0’s DNS service.
mdnstrueAnnounce the daemon with mDNS on the local network.

Telemetry

[telemetry] turns on OpenTelemetry export, for the client and the daemon. The OTEL_EXPORTER_OTLP_* environment variables take precedence.

KeyDefaultMeaning
otlp_endpointoffThe collector’s base URL.
otlp_protocolhttphttp (HTTP with protobuf) or grpc.

Exports

[exports.NAME] shares a directory under NAME. The name is the first segment of a HOST:PATH, so it may not be empty or contain /, and it may not be all.

KeyDefaultMeaning
pathrequiredThe directory, an absolute path; ~ is expanded.
read_onlyfalseRefuse pushes from everyone, even from peers under rw.
warm_indexfalseHash the files already in the export into its index whenever the daemon starts, so files irsync did not place are reused.
fsyncfalseFlush every file a push writes to disk before it is renamed into place, as if the client had passed --fsync. Read on every connection.
rw[]Peers with read-write access: aliases or EndpointIds.
ro[]Peers with read-only access.
autofalseMarks an automatic export, one the daemon made for an [immediate] peer (see below).

[all] has rw and ro too; its grants apply to every export except automatic ones (auto = true).

Immediate grants

[immediate] has one key, rw: peers that may reach any path the daemon’s account can, read-write. There is no read-only form. irsync grant add immediate WHO adds a peer, irsync grant remove immediate WHO takes it out, and the SSH setup adds its client here.

When such a peer uses a path that no export covers, the daemon adds an automatic export for it, auto = true, named auto- and the path with - between its parts (/srv/music becomes auto-srv-music), granted read-write to that peer only. The export is the directory itself, or the directory that holds a file. A push to a directory that does not exist yet creates it, when its parent exists. A push to the home itself (myserver:) exports the whole home. / is never exported automatically; add that by hand. Remove an automatic export with irsync export remove.

An automatic export belongs to the [immediate] peers: [all] never reaches it, and a grant on it counts only while that peer’s immediate grant is in effect. Removing a peer from [immediate], or setting daemon.immediate = false, therefore also ends its access through the automatic exports made for it; the exports themselves stay in the file. To share such a directory with other peers, delete its auto = true line: it is then an ordinary export.

How grants combine:

  • A key that no entry names is rejected before any protocol message is read. There is no open access.
  • A peer’s entry in an export’s own table decides its access to that export; without one, its [all] entry does. An export’s ro entry therefore limits a peer that [all] grants rw.
  • Within one table, rw wins over ro.
  • read_only caps everyone at read-only.
  • An entry that names no alias and is no EndpointId matches nobody; the daemon logs a warning for it.

How a remote path finds its export, nested exports included, is described in Remote addresses.

Files and state

What irsync reads and writes outside the trees it syncs, and what it leaves inside them.

Config directory

All under ~/.config/irsync/, all optional. There is no lookup under /etc; a daemon run system-wide is given --config (see Run the daemon).

FileHolds
irsync.tomlThe whole configuration: identity, state_dir, [client], [daemon], [telemetry], the [hosts.*] aliases, the [exports.*] tables and the [all] grants. --config PATH names another file; the files below are then looked up beside it. See Configuration.
hosts.toml, exports.tomlOptional split files, read as part of irsync.toml. irsync never edits them. See Configuration.
irsync.toml.lockPresent only while a management command edits the file. See Management commands.
id_ed25519, id_ed25519.pubThe client’s key, generated when no other key serves. See Configuration.
daemon_ed25519, daemon_ed25519.pubThe daemon’s key, [daemon] identity, generated when missing by the daemon, irsync export add or irsync show, or on demand by irsync id generate --daemon.

Generated private keys are written with mode 0600, in OpenSSH format. The .pub file beside each holds the public key line. irsync id show prints the EndpointId of either key, under a client: or daemon: label; see Management commands.

State directory

state_dir defaults to ~/.local/state/irsync, or $XDG_STATE_HOME/irsync when that is set. The client and the daemon use the same layout.

PathHolds
index/<hash>.sqliteOne SQLite database per root: a local directory the client synced or indexed, or an export. <hash> is 32 hex digits of the BLAKE3 hash of the root’s canonical path; the database records the path too.
index/<hash>.sqlite-wal, -shmSQLite’s write-ahead log and shared memory, beside each database.
daemon.lockHeld by the running daemon, so a second daemon with the same state directory refuses to start. It holds the daemon’s pid, the path of its program (exe) and its version, one key=value line each. The ssh setup reads it to tell whether a daemon runs and which build it is.
daemon.addrWhere the running daemon can be reached right now: its pid, its home relay and each direct addr, one key=value line each, rewritten whenever they change. The ssh setup passes them to the client, so the first sync to a daemon it just started does not wait for the daemon to appear in the DHT or DNS.
daemon.logThe log of a daemon the ssh setup started. A daemon you start yourself logs to stderr instead.

Each database holds:

  • the file hashes of the root, which let a session skip unchanged files and reuse chunks of renamed and copied ones;
  • the progress of partial files, so that an interrupted transfer resumes where it stopped;
  • dormant sessions, so that the next run of the same sync resumes its plan;
  • the time of the last garbage collection.

Exports with the same path share one database.

The whole directory is safe to delete. The next sync rebuilds what it needs, at the cost of hashing files again and of losing the sessions that could have resumed. Clean up state removes only what nobody is coming back for.

On a server set up over ssh

The ssh setup puts its own copy of irsync on the server at ~/.local/share/irsync/bin/irsync. It replaces that copy when the client runs a different build, and leaves an irsync you installed elsewhere alone. Over ssh it then runs irsync ssh-setup, a hidden command that grants the client, makes the daemon’s key when it is missing and starts the daemon. The server’s config, keys and state are the usual ones above; the daemon it starts writes daemon.log in the state directory.

In the synced trees

A receiver writes into temporary files beside their destinations and renames them into place:

NameWhat it is
.irsync.<name>.partA file being received. An interrupted transfer leaves it behind for the next run to resume. With --partial-dir DIR these files live under DIR instead.
.irsync.<name>.tmpA symlink, hard link or special file being made, renamed into place at once.

When the full name would exceed 255 bytes, <name> is cut and ~ plus 16 hex digits of a BLAKE3 hash of the whole name is put before the suffix, so two long names with the same beginning still get different temporary files.

Names that start with .irsync. and end in .part or .tmp are never listed, never accepted from a peer and never created as destinations.

With --paranoid, the sending side keeps reflink clones in a folder named .irsync-clones-<uid> (the uid in decimal) in a writable directory on each file’s filesystem. A directory named exactly .irsync-clones- followed by digits is never listed and so never synced or deleted; a name such as .irsync-clones-backup is an ordinary directory.

Garbage collection removes .part files and their progress records once they have gone untouched for longer than dormant_session_timeout (7 days by default; the client always uses 7 days), unless a stored session still lists the file. It removes only regular files with that exact form of name, and never follows a symlink. Progress records do not remember a --partial-dir: a stale record whose .part file is not beside its destination is dropped, and the file itself, if it exists, is collected on a later pass by its age. When and how often collection runs is in Clean up state.

Metrics

The metrics and spans that irsync emits, for the client and the daemon. How to collect them is in Watch a transfer with telemetry.

Labels

Every irsync_* metric carries side (client or daemon) and role (sender or receiver). The daemon’s per-session metrics also carry export. There are no path or session-id labels, to keep the number of series small; the session id is on the session span.

The busy-time and active-time counters, the irsync_bytes_* counters, irsync_files_hashed_total and the disk counters are process-wide meters, published once a second and at exit. They add up across the exports a daemon serves and carry no export label.

The process_* metrics carry only side, and mode for CPU: they describe the process, not a session.

The Prometheus names below are also the OTLP names. OTLP units follow the Unit column.

Counters

NameUnitExtra labelsMeaning
irsync_busy_microseconds_totalmicrosecondsactivityTime spent per activity, summed over tasks: walk, plan, hash, read, send, recv, write, place, delete, index_wait, and peer_wait. See Busy time and peer wait.
irsync_active_microseconds_totalmicrosecondsactivityWall time with at least one task doing each activity, without peer_wait, added when a session ends.
irsync_sessions_totalcountoutcomeSessions ended: ok, partial, failed, max_delete. Counts connection attempts: a client session that reconnects counts failed and then ok.
irsync_files_totalcountresulttransferred, skipped, failed, created. failed counts the entries with at least one error, each once; errors about the session as a whole, such as an incomplete listing or a refused deletion pass, are not counted.
irsync_entries_listed_totalcountkindSource entries listed: regular, directory, symlink, special.
irsync_bytes_literal_totalbytesFile data sent or received as literal chunk bytes.
irsync_bytes_matched_totalbytesFile data the receiver did not take from the sender (local copies, earlier progress, files already identical), counted when each file is placed; the sender counts what the receiver’s acknowledgement reports.
irsync_bytes_hashed_totalbytesBytes the hashers read.
irsync_files_hashed_totalcountFiles the hashers read.
irsync_disk_read_bytes_totalbytesFile data irsync read from disk.
irsync_disk_write_bytes_totalbytesFile data irsync wrote to disk.
irsync_wire_bytes_totalbytesdirBytes on the QUIC connection: tx or rx.
irsync_deleted_totalcountPaths the receiver deleted.
irsync_reconnects_totalcountreasonClient reconnects: dial (no connection yet) or lost.
irsync_quic_lost_packets_totalcountQUIC packets lost, sampled once a second.

Histograms

NameUnitExtra labelsMeaning
irsync_phase_duration_secondssecondsphaseWall time of each session phase: connect, handshake, list, plan, transfer, delete, reconnect. Phases overlap.
irsync_file_transfer_secondssecondsFrom a file’s first request to its completion.
irsync_hash_wait_secondssecondsTime a role waited on a hash result.
irsync_fsync_secondssecondsTime to fsync a received file (only with --fsync, or a push into an export with fsync = true).
irsync_file_size_bytesbytesSize of each transferred file.
irsync_quic_rtt_secondssecondsQUIC path RTT, sampled once a second per connection.

Gauges

NameUnitExtra labelsMeaning
irsync_sessions_activecountSessions the daemon is serving.
irsync_streams_opencountOpen data streams.
irsync_hash_queue_depthcountHash jobs waiting for a worker.
process_cpu_seconds_totalsecondsmode (user, sys)CPU time of the process.
process_max_resident_memory_bytesbytesPeak resident set size.
process_open_fdscountOpen file descriptors.

Busy time and peer wait

irsync_busy_microseconds_total{activity} counts microseconds, not seconds, because the metrics crate has only integer counters and seconds would lose the fraction. Each activity counts the time tasks spent doing it, summed over every task.

  • send and recv include network and flow-control waits on the data streams: a stream blocked on the peer’s window, or paused by --bwlimit, is still busy sending.
  • peer_wait is wall time with no activity in progress at all: this side has no local work and waits for the peer.
  • An activity that runs on the other side shows up here as peer_wait. For example, on a push the daemon plans, so the client’s planning time is peer_wait, not plan.
  • index_wait is time spent waiting on the index: for its lock while another task holds it, or for the entries this side queued to be written. The index is one SQLite database per root. Placed and hashed files, and entries of copy sources found gone, are queued for a writer thread that writes them in batches: whatever queues up within 10 ms of the first entry, since every commit empties the read connections’ page caches. Nobody waits for that, except once at the end of a session and before a lookup that needs freshly hashed files. The rarer writes, such as saving progress, take turns behind one lock, and lookups run on read connections of their own. The waiting task’s own activity, write or place, counts the same time too.
  • hash on a receiver is the check of each arriving chunk against its hash, and the hashing of existing files. On a sender it includes encoding a chunk against the receiver’s bases, that is matching its blocks.
  • place covers every entry made or updated at the destination: placing received files, creating directories, symlinks and special files, and updating an entry’s metadata alone. Deciding what to do with an entry is plan.

Busy times can add up to more than the wall time: files are hashed, sent and written in parallel, so ten workers busy for one second each count ten seconds. They say where the work is, not how long the run took. peer_wait is the only one that cannot overlap the others.

irsync_active_microseconds_total{activity} is the other half: the wall time during which at least one task was doing the activity, so it never exceeds the wall time. Busy divided by active is how many tasks did it at once, on average. The -vv summary shows the active time, followed by ×N when that average is 1.5 or more: place 18.2s ×14.8 is 18.2 s of the run during which about fifteen files were being placed at a time. index_wait appears there as index on the waiting line.

Spans

Span names are stable. The per-file spans, file and its children, reach the span sinks only with IRSYNC_TRACE_FILES=1.

session            session_id, direction, side, role, endpoint_id, peer,
 |                 resumed, source_index (client); at the end rtt_max_ms, cwnd,
 |                 lost_packets, reconnects
 +- connect        attempt, path          (client only, one per attempt)
 +- handshake
 +- list
 +- plan
 +- transfer
 |   +- file       path, size, kind (new or delta)   [IRSYNC_TRACE_FILES=1]
 |       +- hash   (sender)
 |       +- send   (sender)
 |       +- recv   (receiver)
 |       +- place  (receiver: rename, metadata, fsync with --fsync)
 +- delete         mode                   (each deletion pass)
 +- reconnect      attempt, reason        (wait between attempts)

path on connect is direct or relay. session is a root span per source. On the client it starts a new trace. On the daemon it is a child of the client’s session span when the daemon exports over OTLP: the client’s W3C trace context travels in its first message, so one sync is one trace across both machines. The local EndpointId is the endpoint_id field on session spans, not a resource attribute, and it is recorded only while spans are exported over OTLP. Events logged inside a span pick up its context.

Log lines show that context too. The daemon’s lines, and the client’s under -vv, start with the span stack and its fields, as in session{session_id=… side="daemon" …}:transfer: ….

Overhead

The cost of the telemetry was measured as a push of a generated tree to a local daemon on the same machine: irsync -a --no-resume, an empty destination, a warm source index, release builds. The baseline is a build without the telemetry code.

The tree is filegen run --seed 1 --steps 600000 --max-total-size 2G --max-file-size 192K: 22,000 files, 1.7 GiB, on tmpfs, so that disk speed does not enter. The machine was shared and noisy, and single runs of the same binary varied by up to 2x. The runs were therefore interleaved in random order, and the table pools 23 runs per configuration over three batches. The last two columns are from the last batch, 10 runs, as medians, and add the client’s and the daemon’s CPU time, which is far steadier than wall time.

ConfigurationWall median, 23 runsvs baselineWall median, 10 runsCPU median, client + daemonvs baseline
baseline11.59 s11.97 s44.4 s
sinks off11.64 s+0.4%10.50 s43.5 s-2.1%
all sinks on11.26 s-2.8%11.45 s46.5 s+4.6%

“All sinks on” is the session summary (-vv), the debug port on the client and the daemon, and OTLP over HTTP on both sides. The OTLP endpoint was a local HTTP server that answers every request with 200, so serialising and sending are measured and a collector’s own work is not. Against sinks off, the median wall time with everything on is 3.3% lower (pooled) and the CPU time 6.8% higher (10 runs). The extra CPU is the once-a-second sampler, the 22,000 per-file lines and the exporters, running on otherwise idle cores.

Protocol

The protobuf definitions in proto/irsync/v1/ (common.proto, control.proto, data.proto, session.proto) are normative. This page summarises the constants, the streams and the messages; where it disagrees with the .proto files, they win. The Rust types are generated from them in the irsync-proto crate.

The protocol and the on-disk state (index, session records) change without compatibility paths until the first release. A client that speaks another version is refused with VERSION_MISMATCH.

Constants

ItemValue
ALPNirsync/1
PROTOCOL_VERSION3, carried in Hello.protocol_version and HelloAck.protocol_version
FramingA 4-byte big-endian length, then that many bytes of one protobuf message
MAX_FRAME16 MiB. A longer length is refused before anything is allocated for it.
Content hashBLAKE3, 32 bytes, for chunks and whole files
ChunkingFastCDC 2020, normalisation level 1; minimum 64 KiB, average 256 KiB, maximum 1 MiB
Chunk list partAt most 32,768 records
Chunk listAt most 2^24 records
List room2^24 records per connection, across all files
NeedChunksAt most 2^18 chunk indices per message
Chunk basisBlocks of 512 B to 4 KiB, at most 8,192 blocks; at most 32 MiB of bases held per session
DataChunkOne chunk per frame, at most 1 MiB of data
HeartbeatAt most one every 500 ms
Hello timeoutThe daemon waits 10 s for Hello

The chunking parameters travel in the handshake (Hello.chunk_min, chunk_avg, chunk_max); a client with others is refused with VERSION_MISMATCH. A file’s chunk list and whole-file hash are a pure function of its bytes and these parameters.

Connection

A client opens one QUIC connection to the daemon’s EndpointId. Before it accepts any stream, the daemon reads its grants afresh and looks up the verified key of the client. A key that no grant names, or a configuration that cannot be read, gets the connection closed with application code 1 (unauthorized) and no message. See Identity and trust.

Close codes:

CodeReasonClient’s response
0doneNone.
1unauthorized: the key has no grantFinal.
2rejected after an Error, or hello timeoutFinal.
3superseded: a newer connection resumed this sessionFinal.
4idle: the inactivity watchdog firedRedial and resume.

Streams

A session uses two bidirectional streams, both opened by the client, and many unidirectional ones.

  • The control stream is the first bidirectional stream. It carries Hello and the reply, then every Control frame except the listing’s.
  • The listing stream is the second. The client opens it right after HelloAck and starts it with a ListingStreamHeader naming the session. Each half then carries one side’s listing: ListingEntry frames in path order, a ListingError wherever entries are missing (a directory that could not be read, right after its own entry; an entry that could not be stat’ed), one ListingEnd with the count and an incomplete flag, and the end of the half. A side that does not list, a receiver resuming a complete plan, ends its half without a frame. The listing has its own stream so that a planner that stops taking it, while it waits for files in flight to finish, stalls only the listing and never the frames that finish those files.
  • Data streams are unidirectional, from sender to receiver, one per run of contiguous requested chunks of one file, a run being cut at 64 MiB. Each starts with a DataStreamHeader (session id, file id, offset, length, index of the first chunk) and carries one DataChunk frame per chunk. A sender keeps at most --parallel of them open, 128 by default; a daemon that sends always uses 128.

Handshake

The client sends Hello on the control stream:

  • protocol_version and the three chunking parameters;
  • session_id: 16 bytes to resume a session, empty for a new one;
  • direction: CLIENT_SENDS (a push), DAEMON_SENDS (a pull) or LIST_EXPORTS;
  • path, the remote PATH as typed, which the daemon resolves (see Remote addresses); contents_only, the trailing-slash rule; and on a push of a source without a trailing slash, name, its basename;
  • the client’s preserve flags (-l -p -t -g -o -D -H -S, -r, -d), which the daemon honours in both directions; a Hello without them means everything;
  • the include and exclude rules, compiled and in order. A sending daemon walks with them; a receiving daemon protects what they exclude from deletion;
  • the receiver-side options, which the daemon honours only when it receives: the deletion mode, --delete-excluded, --max-delete, -n, -u, -c, --inplace, --append or --append-verify, --partial-dir (relative and inside the destination, or refused), --no-rename-detection, --fsync (field 29; a daemon older than it ignores the field and flushes every file, as every version did before it, while an export’s fsync = true flushes whatever the client sent). -i, --ignore-errors and --numeric-ids apply in both directions;
  • paranoid (field 30): --paranoid. Both roles take part in the final re-check, which the receiver asks for with Settle, so a daemon honours it in both directions. Only the sending side clones or hashes each file again, so on a push the daemon does neither;
  • traceparent and tracestate, the client’s W3C trace context (empty: no trace). A daemon that exports traces makes its session span a child of it;
  • build: the client’s BuildInfo (package version, short git commit, dirty flag).

For LIST_EXPORTS the daemon answers with an ExportList, the exports this key may use with their paths and effective access, sorted by name, and closes the connection. Otherwise it answers with HelloAck (the session id, whether the session was resumed, its protocol version and its BuildInfo), or with an Error and close code 2. Each side logs the other’s build at info level once the session is up.

Errors

CodeSent when
UNKNOWNA malformed request, such as an unknown direction.
UNAUTHORIZEDThe key has grants, but none for an export that contains the path. The message is no access to PATH.
READ_ONLYA push to an export that is read_only or that this key may only read.
BAD_PATHThe path has a .. component or a NUL byte, or the session’s root cannot be prepared.
VERSION_MISMATCHAnother protocol version or other chunking parameters.
BAD_SESSIONA resume of a session the daemon does not know, that is finished, or that another key started. The client starts a fresh session at once.
INTERNALThe daemon failed, for example opening the export’s index.

Field number 2 is reserved. The answer for a path a key may not use is the same whether the path lies outside every export, inside an export without a grant, or does not exist at all, so a key cannot probe the daemon’s layout. READ_ONLY and a BAD_PATH about the root go only to a key that may use the export.

Control messages

MessageDirectionMeaning
PlanItemreceiver to senderSend this file: WHOLE (nothing to reuse at that path), DELTA (the receiver holds an old version) or APPEND (the receiver trusts its first append_from bytes).
ChunkListPartsender to receiverPart of a file’s chunk list. The first part also carries the stat the file was hashed under: mtime, mode, owner and group (with their names), change time and inode. With the size, the receiver places the file with them instead of the walk’s. The change time and inode are for the link check (CheckLink).
ListRoomreceiver to senderRoom for this many more chunk records, freed by lists the receiver dropped.
ChunkBasisreceiver to senderBlock signatures over a region of the receiver’s old file, for one chunk.
NeedChunksreceiver to senderThe chunks to send; empty means none.
MayPlacereceiver to senderThe file is verified against chunk list number gen; may it be placed?
PlaceVerdictsender to receiverThe answer: changed if the source differs from the stat it was hashed under. The receiver places the file only when it is unchanged; otherwise it drops it and waits for the new chunk list, or for SOURCE_ERROR. A MayPlace about a list older than the sender’s latest is always answered changed.
FileAckeitherFrom the receiver: DONE, HASH_MISMATCH, WRITE_ERROR. From the sender: SOURCE_ERROR, it cannot read the file. DONE carries the bytes the receiver did not take from the sender.
Itemizedreceiver to senderOne rsync -i line, for a client that pushes with -i.
HeartbeateitherThis side is busy; see below.
Settlereceiver to senderWith --paranoid (not on a dry run), once, in place of the first SessionDone: every path is planned and no file is in flight. The sender stats every file it listed again.
Replansender to receiverAfter Settle: a listed file that changed since it was listed or last hashed, with its entry as it is now. The receiver plans it again, under a new file id.
Settledsender to receiverThe re-check is over: the listed files that vanished, and those it could not stat. The receiver sends SessionDone once the re-planned files are done.
CheckLinkreceiver to senderWith -H (not on a dry run), once every path is planned, no file is in flight and the re-check (if any) is over: one per hard link about to be made to a file sent in this session, on this connection or an earlier one. It carries the name and the stat its target was hashed under.
CheckLinksEndreceiver to senderThe last CheckLink has been sent. With -H it is always sent, even with no links to check, before SessionDone.
Unlinkedsender to receiverA name that is no longer exactly the file its target was hashed as: its stat differs (inode, size, times, mode, owner or group), or it is gone or no longer a regular file the walk would list. The receiver does not link it. If it is still a regular file, entry holds it as it is now, and the receiver plans it as a file of its own, as for Replan. Otherwise that name fails.
LinksCheckedsender to receiverThe link check is over. The receiver makes the other links, then sends SessionDone.
SessionDonereceiver to senderThe session’s totals, errors and deletions.
Errordaemon to clientA refusal, as above.

Every message on the control stream is a Control frame with exactly one of these set. A file costs a PlanItem, at least one ChunkListPart, a NeedChunks, a MayPlace, a PlaceVerdict and a FileAck; the room its list took comes back in a ListRoom, which may cover several files.

Chunk lists

A chunk list travels as ChunkListPart frames of at most 32,768 records, in order, the last one flagged last; an empty file’s list is one empty last part. Every part repeats the file id, the size, the whole-file hash and the total record count. The receiver reassembles them and fails the file when a sequence skips, describes another file, or announces more records than 2^24 or than the size allows at the minimum chunk length. The first part also holds the stat the file was hashed under: mtime, mode, uid and gid, with the names of the uid and gid on the sender. These and the list’s size replace the walk’s for the file, and the names are mapped to the receiver’s ids as for a listing entry (not with --numeric-ids). An APPEND tail’s list carries the whole file’s stat.

Lists travel in room the receiver grants. Each connection starts with room for 2^24 records on both sides; a list’s first part takes its whole total of it, and a sender sends a list only once it fits. The receiver gives room back with ListRoom when it drops a list: the file was placed, failed or replaced. A first part that does not fit, or a grant above the starting room, is a protocol error. A first part for a file that already has a list replaces that list; a sender that lists a file again first sends an empty unfinished first part, so the old list is dropped without waiting for room.

For an APPEND, the list covers only the tail from append_from and carries no whole-file hash; the receiver folds the hash from the bytes it places. Every other list carries one.

Requests, bases and operations

NeedChunks names chunk indices; a request for more than 2^18 comes as several, which the sender treats as one. Before the NeedChunks that names a chunk of a DELTA file, the receiver may send a ChunkBasis for it: a region of its old file named by its offset there, cut into blocks of 512 B to 4 KiB, and per block a 32-bit rolling sum and the first 8 bytes of the block’s BLAKE3 hash. The control stream is ordered, so a basis precedes the request that uses it. The sender keeps a basis for that one request and drops it; a chunk asked for again comes raw. A malformed basis is ignored. A sender that holds more than 32 MiB of bases fails the session.

A chunk with a basis may arrive as DataChunk.ops instead of data: a list of literals and copies (offset, len in the receiver’s old file) that add up to the chunk. The sender uses operations only when they are at least a quarter smaller than the chunk. The receiver rebuilds the chunk and verifies it against the chunk’s hash like any other. How the receiver chooses and uses bases is in Receiving a changed file.

Heartbeats

A Heartbeat means “I am busy”. A side sends one every 500 ms in which it made progress: hashing, writing, finalizing, deleting, or traffic. It carries what the other side cannot otherwise see: the directory this side’s walk is in, the bytes its planner found up to date, and its deletion count. An idle side sends none, so a stuck side still times out. See Sessions and resume.

Persisted state

session.proto describes what each side stores in its index for a session that may resume: the plan (SessionPlan, with PlanEntry per file) and the progress (SessionProgress). These messages never go on the wire. Partial files are stored as RangeSets of verified bytes. See Sessions and resume.

Cross-implementation check

crates/irsync-proto/tests/golden/chunk_1mib.json is a golden vector: the whole-file hash and the exact chunk boundaries (offset, length, BLAKE3 hash) of 1 MiB from the xorshift64 generator seeded with 0x9E3779B97F4A7C15 (see crates/irsync-proto/tests/chunk.rs). An independent implementation must reproduce it exactly to interoperate, because chunk boundaries decide which chunks a client and a daemon consider equal. crates/irsync-proto/tests/golden_bytes.rs pins the exact wire bytes of several messages, so a change of field number or wire type shows.

Known limitations

  • Idle connections are dropped. The daemon drops an authenticated connection that has had no traffic and no local progress, such as hashing or writing, for idle_timeout, 30 minutes by default. The client reconnects and resumes. See Configuration.
  • Only file-based Ed25519 keys. Hardware keys and ssh-agent keys cannot be used. Of the keys under ~/.ssh, only id_ed25519 is tried, unless identity in the config file or --identity names another. See Configuration.
  • Relays are slow. The throughput target, filling a 1 Gbit/s link, applies to direct connections. Relays are a fallback and are much slower. When one end sits behind a symmetric NAT and the other behind a symmetric or port-restricted NAT, hole punching fails and the connection stays on the relay; then run a self-hosted relay and point relay in [client] and [daemon] at it. See Connections.
  • No compression. irsync has no counterpart to rsync’s -z; data crosses the link as it is stored.
  • Linux and macOS only, on x86_64 and aarch64, as client and as daemon.
  • No extended attributes or ACLs. irsync copies neither; see the next section.

rsync options irsync does not have

irsync rejects these with exit code 2. The list is not every rsync option, only those an rsync user is likely to reach for.

rsync optionIn irsync
-X, --xattrsExtended attributes are not copied.
-A, --aclsACLs are not copied.
-x, --one-file-systemThe walk does not stop at filesystem boundaries.
-R, --relativePaths are relative to the source operand; a trailing / copies a directory’s contents.
--files-fromSelect files with --include and --exclude.
--link-dest, --compare-destNo hard-link or comparison directories. Chunks of any file the receiver’s index knows are reused.
--backupReplaced and deleted files are not kept.
-eThe transport is always iroh QUIC. --rsh names the ssh command, but only for setting the server up, never for the data.
-W, --whole-fileNo switch to turn the delta off.
-z, --compressNo compression.
-L, --copy-linksSymlinks are copied as symlinks with -l, or skipped.
--partial, -PPartial files are kept and resumed without a flag; --partial-dir moves them.
--size-only, --ignore-existing, --existing, --remove-source-files, --chmodNot available.

How we know irsync is correct

For a sync tool, correctness comes first and speed second. This page states what irsync claims, what backs each part of the claim, how you can check it yourself, and where the claim stops.

The claim

A completed -a --delete sync of a source that is not changing leaves the destination exactly matching the source.

Each condition matters:

  • Completed means the run ended with exit code 0. A run that was interrupted, or that ended with exit 23 (some files failed), is not complete. See Outside the claim.
  • -a keeps permissions, times, symlinks, devices and special files. --delete removes destination files that are gone from the source.
  • Not changing means nothing writes to the source while the sync runs. Files that change during a sync says what happens otherwise.

“Exactly” covers the items below. The last column says what checks each one. fileset is a separate checking tool, described in the next section.

ItemKept byChecked by
Names, and which entries existany sync; --delete removes extrasfileset’s default check (ADD, DEL)
Type (file, directory, symlink, device, FIFO)-afileset’s default check
File contentsany syncfileset’s default check; irsync also checks every chunk and the whole file with BLAKE3
Permissions and modification times-afileset’s default check
Symlink targets-afileset’s default check
Device numbers-afileset’s default check
Hard links-H, which -a does not include (as in rsync)fileset with --require nlink or --paranoid only
Holes in sparse filesfiles sparse in the source are written sparse (see -S in the command line)the engine test sparse_file_stays_sparse and the sparse campaign row (which runs with -S) only; fileset does not record holes
Deletions--deletefileset’s default check (ADD for anything left behind)

So for hard links, the full command is -aH --delete. That is what the test loops run.

Some things irsync does not carry at all, such as extended attributes and ACLs. Owners are kept only when the receiving side runs as root (see -o in the command line), and sockets are never copied. These edges are listed in Known limitations.

Check it yourself with fileset

You do not have to take the claim on trust. fileset is a second line of defence: it records a manifest of a tree (each file’s checksum and metadata), and later checks a copy against it. It is a separate tool that shares none of irsync’s code, so a mistake in how irsync syncs does not repeat in the check. It is also the same check the test loops below run after each sync.

Record a manifest on the client, sync, then check the copy on the server:

fileset init ~/Photos
irsync -a --delete ~/Photos/ myserver:photos/
fileset check /srv/photos          # run this on myserver

The default check compares type, content, symlink target, device numbers, permissions, modification time and size. Widen it when you need to:

  • --require nlink adds the link count, so a hard link that arrived as a separate copy shows up. --paranoid adds it too, along with owner, group and extended attributes.
  • fileset does not record holes in sparse files. A sparse file and a fully written copy of it pass every tier.

Verify an irsync transfer walks through the same check step by step (with -av and without --delete). The fileset reference lists every field each tier compares.

How we check it, layer by layer

The tests run from fast and narrow to slow and broad.

Engine tests. The tests in crates/irsync/tests/ run two irsync engines in one process and sync real trees between them. A test build adds hooks that record the order of internal steps, so a test can pin, for example, that a file changed while it was sent is sent again, or that a stale local chunk is fetched over the network instead. See Testing.

The stress loop. irsync-stress runs a loop on one machine: a generator of random file changes (filegen, a tool for contributors) changes the source, fileset records it, irsync syncs with -aH --delete, and fileset checks the destination. It repeats for many iterations, so each sync starts from the last one’s result. See Stress testing.

The same loop over a bad network. irsync-netstress runs that loop with every packet passing through a simulated link: limited speed, delay, bursts of loss, and dead zones that cut the link and force a reconnect and resume. See Network stress with netstress.

Writing to the source during the sync. Both stress tools have a --concurrent mode in which the generator keeps changing the source while irsync syncs it. Each destination file is then judged against every state the source held, content and metadata, and a second sync with nothing writing must leave an exact copy. The aim: no destination file is ever a state the source never held. A self-test with the change checks switched off proves the judge catches torn files. See Writing during the sync.

Campaigns. Long runs over many random seeds, each aimed at one area: hard links, renames, sparse files, metadata, timestamps, symlinks, deletion, long names, and more. After a run the destination is also checked with --paranoid, and with du -s for sparse files. See the campaign matrix.

The evidence

The loops find real bugs, not just pass. Among them: file names near the length limit that could not be transferred, and metadata applied to a hard link reaching names the source had unlinked. Each is fixed and has a regression test. The list is in Bugs the harness has found.

Outside the claim

The claim does not cover these cases.

  • A sync without -a does not keep permissions and times.
  • A sync without --delete leaves files that are gone from the source in place.
  • An interrupted sync, or one that ends with exit 23, is incomplete. It may leave .irsync.<name>.part files behind. Running the same command again resumes it.
  • A power cut soon after a sync. By default irsync does not flush files to disk before it renames them into place (--fsync is off, as in rsync). After a power cut or a kernel crash in the seconds after a run, a file can keep its name, size and time but lose its content. The next run’s quick check does not notice; -c does. See --fsync in the command line.
  • Files that change during the sync. See the next section.

Files that change during a sync

irsync first lists the source, then reads each file that needs sending to compute its hash (a checksum of each chunk and of the whole file), then sends the chunks. Here is what happens when a file changes along the way.

  • A change while irsync hashes the file. When the pass is done, the sender checks the open file again: its size, modification time, change time and inode must be what they were when the pass began. If not, the hash may describe a mix of old and new content, so the file is hashed again. The error text is “changed while it was hashed”.

  • A change after hashing. Before the receiver puts a verified file in place, it asks the sender. The sender looks at the source again and compares it with the stat its hash was taken under. A difference gives “changed after it was hashed”. This also catches a change only in chunks the destination takes from its own copy, which the sender never reads again.

  • A change in a chunk irsync sends. Before a chunk leaves the sender, irsync reads it again and checks it against the hash.

  • One retry, then exit 23. Every check above shares one retry per file. If the file changes again, it is given up with an error that ends in “(after retry)”, the other files carry on, and the run exits 23. The destination keeps its old copy. With --inplace and --append there is no old copy to keep: they write into the destination file itself, so it already holds the written data when the change is found. The run still exits 23.

  • Deleted after it was listed. If irsync still had to read it, the file fails, the run ends with exit 23, and the destination keeps its old copy. Otherwise it is not noticed in this run; the next run with --delete removes it.

  • Created after the listing. It is not sent in this run.

  • A hard-link name that changes, with -H. irsync groups the names of a file when it lists the source, and sends the file once, under its first name. Just before it makes the other names links to the copy, the receiver asks the sender to look at each name again. A name that is no longer exactly the file that was hashed is not linked. A name replaced by a file of its own is sent as that file, in the same run, with its retry already used. A name that is gone fails, and the run exits 23. A name whose first name was not sent, because the destination was up to date, is linked as listed: both names held that content when irsync listed them.

These checks compare size, modification time, change time, inode, permissions, owner and group. Programs can reset the modification time, but nothing can set the change time back.

A sent file is placed with the size, modification time, permissions, owner and group it had when its hash was taken, not the ones the listing saw. So a chmod, or another file saved over it, between the listing and the hash cannot leave new content with old permissions: content and metadata always come from the same moment. Because they compare the change time, a change to a file’s metadata alone during the sync counts as a change, even though its content is the same: chmod or chown, extended attributes set by an indexer or a virus scanner, or a new hard link made by a snapshot tool. The file is retried, and the run exits 23 if it happens again.

With --paranoid

--paranoid closes the gaps the checks above leave.

  • Clones. Before hashing a file, irsync makes a reflink clone of it: a copy that shares the file’s disk blocks and never changes afterwards. It hashes and sends the clone. The destination then gets a state the source really held, whatever the source does meanwhile. A clone is accepted even if the source changes after it was made; irsync logs a note. Cloning works on btrfs, xfs, ZFS 2.2 and newer with block cloning, and bcachefs on Linux, and on APFS on macOS (not yet tested). Clones live in .irsync-clones-<uid>/<session>/, mode 0700, in the highest directory on the file’s filesystem that you can write to. Directories that group or others can write to, without the sticky bit, are skipped. irsync removes the clones when the run ends. Clones a crash left are removed by a later --paranoid run that clones on that filesystem. The scan skips these folders. Each file in flight keeps its clone open; if irsync runs out of file descriptors, that file is hashed a second time instead of cloned.
  • Without clones. Where the filesystem cannot clone, irsync hashes the file a second time before the receiver places it and compares the whole digests. A difference gives “changed after it was sent”.
  • A final re-check. At the end of the run, irsync looks at every file it listed once more. A file that changed is sent again, from a clone where possible. A file that is gone, or no longer a regular file, does not fail the run, but it ends with exit 24, “some source files vanished”. A file irsync cannot read gives exit 23. When several codes apply, 1 wins over 25, 25 over 23, and 23 over 24.
  • On a pull, --paranoid travels to the daemon, which does the sending and so runs all of this.

Memory-mapped writers: a program can write into a file through a memory mapping, and the file’s times do not change until the system writes the pages out. In a test on ZFS 2.4 (clone_includes_unflushed_mmap_writes), a clone made right after such a write held the new bytes. So on that filesystem a clone includes memory-mapped writes that have not reached the disk. Other filesystems have not been tested. Where irsync cannot clone, the second hash reads the file as the system holds it. Whether that includes them has not been tested.

Costs. On a filesystem that clones, --paranoid makes one clone and deletes one per sent file. Elsewhere it reads each sent file one more time. At the end it makes one stat per listed file. It also creates and removes the clone folder, which changes the modification time of the directory that holds it, on each run. Under --paranoid, the final re-check treats a changed mode or modification time as a change, because the stat differs. The file is then sent again in full as a delta, which reads both sides, even though its content is unchanged.

Limits

  • Memory-mapped writers, without --paranoid. The checks cannot see a write through a mapping before its times change. --paranoid may help; only clones on ZFS 2.4 are shown to include such writes (see the memory-mapped note above).
  • Coarse timestamps. Fine-grained change times exist on ext4, xfs, btrfs and tmpfs on Linux 6.13 and newer. Elsewhere (older kernels, other local filesystems such as ZFS, network filesystems, FAT) assume coarse timestamps: a write in the same tick as the first stat can slip through the stat checks.
  • Files that change after the listing but are not sent. Without --paranoid, irsync does not look at them again. The destination keeps the version from the time of the listing, a state the source really held. The next run sends the new one.
  • Resumed --paranoid runs. A resumed run re-checks only the files it sent itself. If the connection drops after the re-check and before the session ends, the list of vanished files can be lost, and the resumed run can exit 0 where the first would have exited 24.
  • A re-sent file has no retry left. A file sent again by the final re-check starts with its retry used, so a transient mismatch fails it at once. Its hard-link names at the destination are linked to the new copy.
  • Hard-link names, with -H. The final re-check stats only the main name of each group of hard-linked files. The link check that follows it looks at the other names again, but only those of files sent in this run. If such a name is deleted at the source, it fails rather than counting as vanished: the run exits 23 instead of 24.
  • Bind mounts share one device number, and cloning across them fails with EXDEV, so that filesystem falls back to the second hash.
  • A umask of 002 makes new directories group-writable, which may leave no safe place for the clone folder. irsync then uses the second hash.

What to do:

  • Where the source is written while you sync, --paranoid helps, within the tested limits above.
  • Better still, sync from a snapshot.
  • Run the sync again once the writes have stopped, or run it with -c, which compares contents instead of size and time.
  • Check the result with fileset.

What the tests cannot see

Every bug the test loops find has to pass three filters:

  1. The generator must provoke it. A change the generator never makes is never tested.
  2. fileset must observe it. The loops run fileset’s default check, which does not compare hard links, owners or extended attributes, and does not record holes. Campaigns widen this after a run.
  3. A known bug must not hide it. A bug that fails every iteration hides anything else underneath it.

Hunting bugs has the detail.

For contributors

Testing says which test to add or run for each kind of change.

Sessions and resume

A sync in irsync is a session, not a connection. The session is the job: the plan of which files to send and how far each one got. A connection is only the current way of moving it forward. When the connection drops, the session waits; when the process dies, the session stays on disk; the next connection, or the next run of the same command, continues it. This page explains what a session holds, how it is found again, and what a resumed session skips.

What a session is

A session has a random 128-bit id, which the daemon assigns in its HelloAck, a plan and a record of progress. Both sides keep the plan and the progress in the index of the root they work on, under state_dir (see Files and state), and write them at most every 2 seconds and once more at the end:

  • the plan: each file the receiver decided to request, with its action, size, hash and listing entry, and once the listing is over, a flag that the plan is complete, with the directories and the errors found on the way;
  • the progress: the files acknowledged as done, the bytes transferred over all connections, and the deletions so far, which count against --max-delete.

Separately from the session, the receiver records for each partly received file which byte ranges of its .part file it has verified. That record is written after every 64 newly verified chunks or every 2 seconds, and belongs to the file, not to the session. The exact messages are in Protocol.

A finished session’s record is deleted.

When the connection drops

The client dials again and sends Hello with the same session id. Both sides load what they stored and carry on. A file acknowledged as done is not touched again. A file that was partly received continues from its verified chunks: the receiver reads each recorded chunk of the .part back, checks it against its hash, and requests only the rest. Chunks that were written but not yet recorded are requested again.

The client redials with exponential backoff: 1 second, doubling up to 60 seconds, plus up to a quarter of random jitter, so that many clients do not redial in step. It keeps going for --reconnect, 24 hours by default, measured from the last time the session made progress. A connection that the daemon accepts but that moves no data and places no file does not count as progress, so a daemon that accepts and drops every connection cannot keep a client retrying forever. --reconnect 0 gives up at once, as rsync does.

Some answers end the session instead of a retry: an Error from the daemon (the key may not use the path, the export is read-only, another protocol version), and close codes 1 to 3 (see Protocol). A daemon that no longer knows the session answers BAD_SESSION, and the client starts a fresh session at once.

When the process dies

The client stores the session under a key derived from what the command means, not how it was typed: the daemon’s EndpointId (so an alias and the raw id are the same), both locations (a local one by its canonical path, a remote one as typed, each with its trailing-slash rule), the preserve flags, -c, -u, --inplace, --append or --append-verify, the deletion mode with --delete-excluded, -n, and the filter rules in order. Flags that do not change the result, such as --parallel, --bwlimit or -v, are not part of the key.

The next run of the same command computes the same key, finds the stored session and prints resuming session <id> from <time>, with the first eight hex digits of the id and the time of the last write. A command that differs in any part of the key starts its own session. There is one stored session per key: a new one replaces an old one.

--no-resume ignores the stored session and plans afresh. Partly received files are still picked up, since their records belong to the files: a .part whose record names the same expected size and hash continues from its verified chunks.

What the daemon checks

The daemon keys its copy of the session by the client’s EndpointId, the export and the path inside it as resolved, the direction, the trailing-slash rule, and the receiver-side options. A resume must match all of them.

Only the key that started a session may resume it. A Hello with the id of a session that another key started, that is finished, or that the daemon has collected, gets BAD_SESSION, with no hint which of these it was.

When a second connection resumes a session that an older connection still holds, as when the same command runs twice at once, the daemon closes the older one as superseded, waits for it to let go, and continues with the newer. The older client stops with an error rather than taking the session back.

What a resumed session skips

On a resume with a complete plan, neither side lists again: the receiver recreates the planned directories where they are missing and requests the files not yet done, and nothing else. This is what makes a resume after an interruption cheap for a large tree. Two cases list afresh even then: a run with deletions, because the stored plan holds no deletion candidates, and a dry run, which stores nothing worth resuming. They still skip the files the progress marks as done.

A resume with an incomplete plan lists both sides again and plans the files that are not done yet, using the index to skip unchanged ones.

How long a session waits

A session that nobody resumes is dormant. Garbage collection removes dormant sessions and their partial files after dormant_session_timeout, 7 days by default, on the daemon, and after 7 days on the client. A partial file that a stored session still plans to write is kept. When collection runs is in Clean up state.

Timeouts

Three timers decide when a connection is given up on, and each leads to a redial, not to the end of the session:

  • QUIC’s idle timeout, 60 seconds, with keep-alives every 5 seconds: the path is gone. See Connections.
  • The daemon’s idle_timeout, 30 minutes by default: nothing has happened on the session for that long.
  • The client’s --timeout SECS, off by default: no control message, no data and no local progress for SECS seconds. It also bounds the wait for the daemon’s reply to Hello.

Local progress (hashing, writing, finalizing, deleting) counts as activity, so that a side busy with a large file does not look dead. The busy side tells the other with a Heartbeat every 500 ms in which it made progress; an idle side sends none. Since heartbeats come every half second, a --timeout below a few seconds is unreliable.

Identity and trust

irsync has no passwords, no user accounts and no certificate authority. Each client and each daemon is an Ed25519 key pair, and its EndpointId is the public half. Who may connect is a list of EndpointIds on the daemon; whom a client connects to is the EndpointId it dials. This page explains where the keys come from, why the client trusts nothing it has not been given, and how the daemon decides what a key may reach.

Keys and EndpointIds

A key is an OpenSSH Ed25519 private key file. The EndpointId is the 32-byte public key, printed in hex or z-base-32. iroh’s QUIC handshake proves that each end holds the private key for the EndpointId it presents, so the client knows it reached the daemon it dialled, and the daemon knows which key connected, before any irsync message is exchanged.

The client and the daemon use different keys, so both can run in one account on one machine and reach each other:

  • The client’s key is looked up the way ssh picks one, ending with ~/.ssh/id_ed25519 if it exists and with a newly generated ~/.config/irsync/id_ed25519 if nothing else serves. The order is in Configuration.
  • The daemon’s key is [daemon] identity, ~/.config/irsync/daemon_ed25519 by default, generated the first time the daemon, irsync export add or irsync show needs it.

A key is the identity for good. Replacing it with irsync id generate --force gives the machine a new EndpointId: every grant made for the old one stops matching, and every client that pinned the old daemon id fails to connect. Only file-based keys work; see Known limitations.

The client pins the daemon

A remote is named by its EndpointId, or by an alias that stores one. The client dials that key and nothing else. A daemon with another key fails the connection; it is not a warning to confirm.

There is no trust on first use. The client never learns a daemon’s key from the network, has no known_hosts file to add to, and never asks whether to trust a key it has not seen. Both ids are copied by hand once, each in its own direction, as in Your first sync: the client’s id to the daemon’s machine, for the grant, and the daemon’s id to the client, for the alias. In exchange, nothing on the way can redirect a client: a DNS or DHT record, a relay or an address given by hand only says where to knock, and a wrong one leads to a failed connection, never to the wrong daemon (see Connections).

The daemon checks grants

A grant names a key and an export, read-write or read-only. Grants live in the daemon’s configuration, under each [exports.NAME] or under [all] for every export, as aliases or raw EndpointIds. irsync grant add also takes a pasted ssh-ed25519 line or a .pub file and writes the id it holds. A grant that names an alias follows the alias: pointing myclient at a new id with irsync host add moves every grant that names myclient.

The daemon reads its configuration afresh for every connection, once the handshake has proved the client’s key, and checks the key against it before it accepts any stream:

  • A key that no grant names is closed on at once, with no message. There is no open access: all and * are refused as a grantee.
  • A configuration that cannot be read rejects the connection; the daemon does not fall back to an earlier copy.
  • A change to the grants applies from the next connection; a session in progress keeps running. See Change exports and settings.

Access combines in a fixed way. A key’s entry in an export’s own table decides its access there; without one, its [all] entry does, so an export’s ro entry limits a key that [all] grants rw. Within one table, rw wins over ro. An export marked read_only, which irsync export add --ro sets, refuses pushes from everyone, whatever they are granted. The rules are listed in Configuration.

Paths, exports and “no access”

A remote path is resolved on the daemon’s machine, as an export name, a path under the daemon account’s home, or an absolute path (see Remote addresses). Then the export that contains it is chosen, among the exports the key has a grant for only. Exports may be nested:

  • The most specific export, the one with the longest path, decides the session’s root and access. Between exports with the same path, the one the operand named wins, then the one with the better access.
  • A grant on an outer export reaches everything below it, the inner exports included. An inner export the key has no grant for does not stop it, and neither does an inner read_only export, since an export without a grant takes no part in the choice.

A path that no export the key may use contains is refused with no access to PATH. The answer is the same whether the path lies outside every export, inside an export without a grant, or does not exist, so a key cannot learn the daemon’s layout by probing. Only a key that may use the export learns more: that the export is read-only, or that the path cannot be used as a session root.

A .. component or a NUL byte is refused in every path, before any lookup. Below the export’s directory, every existing component of the session’s root must be a directory and not a symlink to one, so the root cannot leave its export either.

Sessions belong to their key

A session is resumed only by the key that started it. A Hello that names the session id of another key gets BAD_SESSION, the same answer as for an id the daemon never knew. See Sessions and resume.

Connections

irsync connects a client and a daemon with iroh, over QUIC. A daemon is addressed by its EndpointId, the public half of its key, not by a host name or an IP address. This page explains how a client gets from that id to a working connection, and what keeps the connection going. The steps to change each part are in Connect directly or through a relay.

Finding the daemon

A daemon publishes where it can be reached, in up to three places, each turned on or off under [daemon.discovery]:

  • dns: n0’s DNS service, through signed pkarr records.
  • dht: the mainline DHT, with the same kind of record.
  • mdns: the local network.

A client looks the EndpointId up in the same places. DNS is always on for a client; the DHT and mDNS can be turned off per host or in [client], and --no-dht turns the DHT off for one sync.

The DNS and DHT records carry only the daemon’s relay address, never its IP addresses: that is iroh’s default, so that publishing an id does not publish where the machine is. mDNS announces the daemon’s local addresses, and only on the local network.

Whatever a lookup returns, the connection is to the key and nothing else. The QUIC handshake proves that the far end holds the key for the EndpointId the client dialled, and the daemon learns the client’s EndpointId the same way. A lookup that returns a wrong address leads to a failed connection, not to a wrong peer.

Relays

A connection starts through a relay, a server both sides can reach, and moves to a direct path when hole punching succeeds. The relay forwards QUIC packets that are encrypted end to end between the client and the daemon; it cannot read or change them. n0 runs public relays, which are the default.

Relays are the fallback. Every packet takes the detour through the relay server and shares it with other users, so a relayed transfer is slower than a direct one. When one end sits behind a symmetric NAT, as many mobile and carrier-grade NATs are, and the other behind a symmetric or port-restricted NAT, hole punching fails and the connection stays on the relay. For them a self-hosted relay near the daemon is the better choice than the shared public ones.

Relays can be refused, on either side. A client with relays off still looks the daemon up, but since the DNS and DHT records carry only a relay address, it finds a daemon through mDNS on the local network or through an address it is given. A daemon with relays off has nothing to publish in DNS or the DHT; it warns at start when dht is on.

Direct addresses

Given an address, through --address or a host’s address key, the client dials it and nothing else: no relay, no DNS, no DHT, no mDNS and no port mapper. This is how two irsync processes talk on one machine, on a LAN, or without internet access. The EndpointId is still required and still checked, so an address only says where to knock, not whom to trust. Over the connection, iroh may still learn and try further addresses of the daemon; for a daemon on loopback those are loopback too.

On the daemon’s side, listen pins the sockets it binds, at most one IPv4 and one IPv6, and portmap asks the router for a port mapping with UPnP, PCP or NAT-PMP. Pinning the sockets does not stop the publishing or the relay; an isolated daemon turns those off one by one.

Keeping a connection alive

Two timers watch a connection, at different scales:

  • QUIC’s own idle timeout, 60 seconds. Both sides send a keep-alive every 5 seconds, so this fires only when the path is gone: a laptop that sleeps, a network that drops.
  • The daemon’s idle_timeout, 30 minutes by default. The daemon drops an authenticated connection on which nothing has happened for that long. Something happening means any control message or file data on the wire, and also local progress on either side: chunks written or copied, hashing, finalizing a file (the fsync and the whole-file check of a large .part), and each deletion. Hashing counts as progress every 64 MiB read, so a large file being hashed keeps the connection alive. A side with local progress sends a heartbeat every half second, so that the other side sees it.

When a connection drops, the client redials for up to reconnect (one day by default) and resumes the session. A file that was being finalized when the connection dropped does not fail: the resumed session waits up to 60 seconds for the earlier connection’s finalize to release the .part file before it reports the file busy.

idle_timeout = "0" disables the daemon’s limit; see Configuration.

Congestion control

The side that sends picks QUIC’s congestion controller: the client for a push, the daemon for a pull. The setting is congestion, in [client], in a host’s table or in [daemon], and takes bbr, the default, or cubic.

  • BBR keeps the queue at the bottleneck short and copes with random loss, as on mobile links.
  • Cubic keeps the link busier when the return path delays the acknowledgements. That is typically an upload on a home line whose download is busy with other traffic: the queued download holds up the upload’s acknowledgements, and BBR then keeps too little data in flight to bridge the delay. Cubic fills the line’s queue instead, which adds latency for everything else on the line while it sends.

Measured in the netstress dsl-video profile, a 1 Mbit/s uplink beside a busy downlink, Cubic was 1.6 to 1.8 times faster than BBR. In the lossy 4g-vehicle profile BBR was 23 to 50% faster, and Cubic’s full queue cost other traffic on the line about 0.5 s of latency. Neither wins everywhere, so BBR stays the default. The runs are in NETSTRESS_DECISIONS.md.

The transfer algorithm

How irsync moves a changed file, set against how rsync does it. rsync facts refer to protocol 30 and later (rsync 3.x). The receiver’s side of one changed file, step by step, is in Receiving a changed file; the messages are in Protocol.

The two algorithms

rsync

The receiver keeps the old file as a basis. Its generator process cuts the basis into fixed blocks (block size about the square root of the file size, rounded to a multiple of 8, clamped to 700 bytes .. 128 KiB) and sends, per block, a 4-byte rolling checksum plus a truncated MD5 (2 to 16 bytes, chosen per file). The sender slides a one-byte window over the new file; on a weak hit it checks the strong checksum, and emits a token stream of literal bytes and block references. The receiver rebuilds the file into a temporary, computing the whole-file MD5 as it writes, then renames it into place. On a whole-file mismatch the file is redone once with full-length checksums. Everything flows in order over one TCP or SSH stream, through three pipelined processes (generator, sender, receiver).

irsync

The sender cuts the new file into content-defined chunks (FastCDC 2020, 64 KiB minimum, 256 KiB average, 1 MiB maximum) and hashes each chunk and the whole file with BLAKE3. Both sides keep these hashes in a persistent index, keyed on size, mtime, ctime and inode, so an unchanged file is never read twice.

  1. The receiver’s planner compares the two listings and requests a file with a PlanItem: WHOLE when nothing is at the path, DELTA when it holds an old version. For a DELTA it starts hashing the old version at that moment.
  2. The sender digests the new file, from its index when the file is unchanged there and by reading it otherwise, and sends the chunk list.
  3. If the old file’s hash equals the new one, the receiver applies the sender’s metadata to the file in place and is done: no write.
  4. Otherwise the receiver opens .irsync.<name>.part, as a reflink clone of the old file where the filesystem allows, and keeps the chunks the clone or an earlier interrupted attempt already holds. It looks the missing chunks up in its index: those any indexed file holds are copied locally, the rest are requested from the sender with NeedChunks at once.
  5. For a DELTA, the receiver first offers the sender a basis for each requested chunk: block signatures over the old file around the chunk’s place. The sender answers such a chunk with copies and literals instead of its bytes when that is smaller. This is rsync’s algorithm, run inside one chunk.
  6. The sender reads each requested chunk, hashes it again as it reads, and streams the chunks over parallel QUIC streams. The receiver verifies every chunk against its hash before writing it, whether it came raw, rebuilt from operations or from a local file.
  7. The receiver folds the whole-file BLAKE3 from the verified chunks, without reading the file back, applies the metadata, renames the .part into place, and acknowledges DONE.

Local copies run while the network transfer runs, and the sender’s hash runs while the receiver hashes its old file. A whole file and a moved file take the same path: for a moved or copied file, every chunk is found locally.

The delta inside a chunk

A content-defined chunk resynchronises within about one chunk after an edit, so whole-chunk reuse alone would cost one or two chunks, 64 KiB to 1 MiB, per edit. irsync narrows that to blocks:

  • For a missing chunk at offset o of length n, the basis is the old file’s bytes from o - n to o + 2n, clamped to the old file. A chunk that starts at or past the old file’s end (appended data) gets none. A file missing more than half of its chunks gets none, unless it has at most two chunks: that is a rewrite. The regions stop once they add up to the old file’s size or three maximum chunk lengths, whichever is more.
  • The block length is the square root of the region, clamped to 512 B .. 4 KiB. Each block is signed with a 32-bit rolling sum and the first 8 bytes of its BLAKE3 hash, 12 bytes per block.
  • The sender slides a window over the chunk’s bytes, checks every position against a 64 Ki-bit filter, then the signatures, then the strong hash, and emits copies of old-file ranges and literals. If the result is not at least a quarter smaller than the chunk, the chunk goes raw.
  • The receiver rebuilds the chunk and verifies its 32-byte hash. A chunk that does not verify (the old file changed in place, a hostile operation list, a collision of the 8-byte hash) is requested again, without a basis.

The integration tests in crates/irsync/tests/sub_chunk_delta.rs measure the bytes on the data path, which leave out the chunk list and the signatures:

ScenarioWhole chunks onlyWith the delta
4 MiB file, one byte changedone chunk, ~256 KiB2,100 bytes
16 MiB file, eight scattered 4 KiB writeseight chunks, ~2 MiB51,475 bytes
100 KiB file, six bytes changedthe whole file550 bytes
4 MiB file rewritten4 MiB4 MiB, no bases offered
2 MiB appended to 4 MiB~2 MiB~2 MiB, at most one basis

The signatures cost the other way about 12 bytes per block: for a 256 KiB chunk with a 768 KiB region at 886-byte blocks, 887 blocks, about 10 KiB, or 4% of the chunk.

Files in flight and streams

Two numbers bound how much a session has going at once.

  • Files in flight: at most 4,096 per session, counted from the PlanItem to the acknowledgement (MAX_INFLIGHT in crates/irsync/src/session/planner.rs). A file in flight may hold two descriptors, its .part and its old version, so the window shrinks to (soft open-file limit − 256) / 2 when that is smaller. At startup irsync raises its soft limit to the hard limit (on macOS to at most 10,240), so the window is the full 4,096 wherever the hard limit is at least 8,448. A fresh file’s .part is opened by its first write, so files waiting for the sender’s data hold no descriptor.
  • Data streams: the sender keeps at most --parallel QUIC streams open at once, across all files of the session, 128 by default (DEFAULT_PARALLEL in crates/irsync/src/send.rs). A daemon that sends always uses 128. A run of contiguous chunks longer than 64 MiB is split, so one large file spreads over several streams.

The first hides the per-file round trips; the second fills the link.

Compared with rsync

Dimensionrsyncirsync
Delta unitbasis block (700 B .. 128 KiB, ~sqrt(size)), matched at any byte offsetcontent-defined chunk (64 KiB .. 1 MiB, 256 KiB average), matched whole anywhere the index knows; inside a missing chunk of a DELTA file, blocks (512 B .. 4 KiB) matched at any byte offset of the old file’s neighbourhood
Smallest file that gets a deltaany (blocks go down to 700 B)any whose old version on the receiver is at least 1 KiB and whose new version is at least 512 B (blocks go down to 512 B)
What a 1-byte edit in a 1 GiB file sends~32 KiB literal + tokens~1 KiB literal + a few operations, with ~10 KiB of block signatures the other way
Signature directionreceiver to sender (basis blocks)sender to receiver (new file’s chunks); receiver to sender (block signatures, per missing chunk of a DELTA)
Signature size, 1 GiB file~224 KiB (32,768 blocks of 32 KiB x 7 B: 4 B rolling + 3 B strong checksum, the length rsync’s sum_sizes_sqroot picks for this file size and block size)~200 KiB (4,096 chunks x 49 B), plus ~10 KiB per missing chunk offered a basis
Signature for a new filenonefull chunk list, ~0.02% of the data
Reuse scopethe basis at the same path (--fuzzy, --link-dest, --compare-dest widen it)every chunk of every file the receiver’s index knows; before a whole file is fetched, up to four destination files of its size are hashed into the index
Rename detectionnone (name similarity only, --fuzzy)by content: a renamed or copied file’s chunks are found in the index and copied locally
Digest caching across runsnone; -c re-reads everythingpersistent SQLite index keyed on size, mtime, ctime, inode; -c trusts none of it and re-reads both sides
Content unchanged, mtime changedthe file is rebuilt and rewrittenone read on each side whose index row is stale; metadata applied in place, no write
Round trips before first data byte~0 (pipelined)1.5 (plan, chunk list, request)
Serial disk passes before first data byte, one big changed file1 (basis checksums)1 (the sender’s hash and the receiver’s old-file hash run concurrently; local copies overlap the transfer)
Extra receiver pass after last bytenone (MD5 computed while writing)none (BLAKE3 folded from the verified chunks)
Streamsone, in orderup to --parallel QUIC streams (128 by default), runs split at 64 MiB
Files in flightpipelined, bounded by the windowup to 4,096 per session, fewer when the open-file limit is low
Resume--partial keeps bytes; the next run re-checksums themchunk-granular, verified ranges persisted; plan persisted
In place, append--inplace, --append, --append-verifythe same three; by default a .part that is a reflink clone of the old file where the filesystem allows, so only changed chunks are written and the file is still renamed into place
Per-block integrity4-byte rolling + 2..16-byte MD532-byte BLAKE3, checked when the sender reads and before the receiver writes
Whole-file integrityMD5 (xxh3 negotiable in 3.2+), one redoBLAKE3, folded from the verified chunks; a mismatch re-offers the file once
Change during transfernoticed at the final whole-file check; whole file redonea change while the file is hashed, or after it, is noticed (the sender stats the file after hashing, the receiver asks the sender before placing, and each chunk is checked as it leaves), and the file is re-offered once, then given up with exit 23; --paranoid also sends from a reflink clone or hashes again, and re-checks every listed file at the end (Files that change during a sync)
Sparse files-S finds zero runs at write granularityall-zero chunks are left as holes
Compression-znone
Largest fileno protocol limit2^24 chunks per list, about 4 TiB of typical data
TransportTCP or SSHiroh QUIC, NAT traversal, pinned Ed25519 identities

Where irsync is ahead

  • Touched files. A file whose mtime changed and whose content did not (a touch, an editor that saved the same bytes, a restore) costs one read on each side whose index row is stale and four small messages; the destination keeps its inode and takes the new metadata. rsync rebuilds and rewrites it.
  • Moved, renamed and duplicated data. Any chunk anywhere in the indexed destination is reused, so a renamed 10 GiB file transfers nothing; rsync sends it again. A destination that rsync or a restore filled is hashed into the index on demand, or ahead of time by irsync index.
  • Small edits in large files. The delta block is chosen per chunk, not per file, so a one-byte edit in a 1 GiB file costs about 1 KiB of literal against rsync’s 32 KiB, and a hundred scattered 4 KiB writes about 0.6 MiB of literals and 1 MiB of signatures against rsync’s 3.2 MiB of literals and 224 KiB of signatures.
  • Atomic and cheap updates at once. Where the filesystem clones files, a changed file costs only its changed chunks in space and writes and still lands by rename. rsync gets the first only with --inplace, which gives up the second.
  • No read-back. The receiver reads a received file at most once, to verify chunks it adopted or copied locally, and writes it once; the whole-file hash is folded from what it verified.
  • Bad and fat links. Many parallel streams, large files split across them, a scan that runs alongside the transfer, and chunk-granular resume across disconnects, process deaths and reboots (see Sessions and resume). rsync’s single in-order stream is limited by one congestion window, and --partial keeps bytes that the next run checksums again.
  • Integrity. Every chunk is checked with a 32-byte BLAKE3 hash when the sender reads it and again before the receiver writes it, and the whole file against its BLAKE3 hash, against rsync’s 2- to 16-byte truncated MD5 per block. A chunk that changed after the file was hashed is caught when the sender reads it, before stale bytes leave. A change while it is being hashed, or after it in chunks the receiver takes from its own copy, is caught by a stat of the source after hashing and before placing. Writers that leave the times alone, such as memory-mapped databases, are not caught by these. --paranoid may help, but is tested on ZFS 2.4 clones only. See Files that change during a sync.
  • Sender CPU. A changed or new file costs the sender BLAKE3 hashing only: one pass for its chunk list, and each requested chunk hashed again as it is read for sending. The rolling match runs only over chunks the receiver offered a basis for, not over every byte of every changed file.
  • Reachability and identity. NAT traversal and pinned keys without SSH or port forwarding (see Identity and trust). This is irsync’s reason to exist, not a property of the algorithm.

Where rsync is ahead

  • Compression. rsync’s -z reduces the bytes on the wire for compressible data; irsync has no compression (see Known limitations).
  • Zero round trips before the first data byte. rsync’s generator runs ahead and the sender’s token stream follows without waiting. irsync spends four control messages per file and 1.5 round trips before its first data byte: PlanItem, chunk list, NeedChunks, then data, then FileAck. Up to 4,096 files in flight hide this, but do not remove it: a file holds its slot from its PlanItem until its DONE, so one slow file holds a slot for its whole life. Before NeedChunks goes out, the receiver also runs one SQLite lookup per missing chunk.
  • The first push reads the source twice. Each new file is read once for its chunk list and once to send it. rsync reads a new file once. The page cache hides the second read for files that fit in memory, and four hashing workers overlap it across files.
  • Delta reach. A missing chunk is matched only against the old file’s neighbourhood of its own offset. Content that moved by more than about a chunk, and is not a whole chunk, is sent as literal; rsync finds it anywhere in the basis. Whole chunks are found anywhere through the index.
  • Sparse files. irsync leaves only whole zero chunks as holes, so a run of zeros shorter than a chunk is written. rsync -S finds zero runs at write granularity.
  • Fixed chunk parameters. The chunk sizes are protocol constants. Changing them needs a new protocol version and invalidates every index on every machine.
  • Memory per file in flight. The receiver holds two copies of a file’s chunk list while it is in flight, about 48 bytes per chunk each, which adds up when many large files are in flight at once.
  • Opportunistic candidates. Before fetching a whole file, the receiver hashes only destination files of exactly its size, at most four, of at least 64 KiB, and only those its walk has already listed. Seeding the index with irsync index or warm_index covers the rest.
  • Largest file. A chunk list holds at most 2^24 records, about 4 TiB of typical data; rsync has no such limit.
  • Extended attributes and ACLs. rsync copies them with -X and -A; irsync copies neither (see Known limitations).

A limit both share: with --inplace reuse is forward-only, so an insertion near the start of a file loses the reuse below it, in rsync and in irsync alike. Without --inplace, irsync does not pay it.

Receiving a changed file

How the receiver fills one changed file once the sender’s chunk list is in hand: how it overlaps the passes over the file with each other and with the network, how it settles a file whose content turns out not to have changed, and how a chunk it lacks is rebuilt from block matches against the old file. Function names point at where each step lives, under crates/irsync/src/. The comparison with rsync is in The transfer algorithm; the messages are in Protocol.

The problem

A DELTA file exists on both sides as a regular file and differs in size or mtime. The sender digests the new content and sends its chunk list; the receiver must produce a file whose every chunk verifies against that list, then put it into place.

Four things have to happen for that: the sender hashes the new file, the receiver hashes the old one, chunks the receiver already holds are copied locally, and the rest cross the network. Done one after another, the first three are each a full pass over the file, and the transfer, the only part that needs the network, waits for all of them. The receiver runs them overlapped instead, and keeps these guarantees: every byte of the file is verified against the sender’s hash before it counts, local data is trusted no more than network data, and a stale local source degrades to a network fetch.

The timeline of one DELTA file

Plan time: the old file’s hash starts early

Planner (session/planner.rs) merge-joins the two listings and calls plan::decide. When the decision is Delta, at the moment the PlanItem is handed to the control stream, the planner spawns a task that runs recv_io::index_old_file on the destination path.

index_old_file takes an lstat (size, mtime, ctime, inode) and asks the session’s hasher for the file’s digest. A fresh index row answers at once; otherwise the file is read in full, cut with FastCDC, and every chunk’s BLAKE3 hash and offset is stored in the index with the whole-file hash. If the file vanished, is not regular or cannot be read, the failure is logged at debug level and nothing else follows from it: no local chunks are found, and everything comes over the network.

The task’s handle travels with the file to the receiver. Meanwhile the sender has received the PlanItem and begun its own digest of the new file, so the two full reads run on two machines at the same time.

A WHOLE file has no old content, so no task is spawned. A moved or copied file needs no step of its own: its chunks are in the index like any other file’s and surface through the lookup below, which --no-rename-detection turns off.

Chunk list arrival

The chunk list arrives as ChunkListPart frames, which Receiver::on_chunk_list_part reassembles (session/parts.rs) into one digest. A malformed sequence fails the file. A connection lost in the middle of a sequence drops the half-built list; the resumed session gets a fresh sequence.

Receiver::on_chunk_list (session/receiver.rs) bumps the file’s generation, retires any earlier writer for the file, so that no stale task can touch the .part afterwards, takes the hash task’s handle out of the file’s state, and spawns open_writer. The handle is taken, not cloned: a second chunk list for the same file, after a reconnect, finds none, and open_writer calls index_old_file itself, which by then is a cache hit.

Open and partition

recv_io::open_writer copies nothing. It:

  1. Takes the old file’s hash (DELTA only): it awaits the handle, which yields the old file’s digest with the stat it was computed under. Without a handle it calls index_old_file.

  2. Compares whole-file hashes. If the old file’s size and BLAKE3 hash equal the chunk list’s, the destination already holds the new content. The receiver opens it without following symlinks and checks with fstat that size, mtime, ctime, device and inode are those the hash was computed under (unchanged_file). If they are, it returns Opened::Identical with that descriptor, and no .part is created; see Settle in place. If the file changed meanwhile, or the hashes differ, it goes on.

  3. Opens the .part, locked (FileWriter::open_tracked). The writer adopts the progress recorded for an earlier .part of the same expected file and keeps a verified bit per chunk. When there is no .part yet and no old file to clone, the open is deferred: the writer holds no descriptor until its first write creates and locks the file. A file waiting for the sender’s data thus costs no open file.

  4. Partitions the missing chunks (local_sources). On one of the index’s read connections, find_chunks lists the files that hold each missing chunk, with the inode and size each entry records: the first alone, since it nearly always is still there, then pages of 16. The first candidate that is still the file the index describes (same inode and size on disk) gives a path and an offset, and the chunk goes into the local set. Files that are gone or were replaced are passed over and queued for removal from the index, so a deleted tree’s leftovers cost one lstat each, once. A chunk with no such file goes into the remote set. If the lookup itself fails, the whole missing set goes remote, which is always correct.

    For a WHOLE file the partition is preceded by warm_candidates: the receiver’s walk noted every regular file of at least 64 KiB without a fresh index row, by size (warm::Cold), and up to four of exactly this file’s size are hashed now, so a renamed or copied file the index did not know is found by the lookup. Each candidate is tried once per session.

  5. Picks bases (DELTA with an old file and a non-empty remote set). basis_specs chooses which remote chunks to offer a basis for, and the old-file region of each: from one chunk length before the chunk’s offset to two after, clamped to the old file. A chunk starting at or past the old file’s end gets none; no chunk gets one when more than half the chunks are missing, unless the file has at most two; a region under 1 KiB is skipped; and the regions stop once they add up to the old file’s size or three maximum chunk lengths, whichever is more. If any basis is chosen, the old file is opened without following symlinks, and that descriptor is used for the signatures and later for the copies, so a rename of the destination meanwhile changes nothing.

The result carries the writer, the two sets, the digest, the basis choices and the old file’s descriptor. The sets are disjoint and together cover exactly the missing chunks; the chunks with a basis are a subset of the remote set.

Request first, then copy

Receiver::on_opened runs on the receiver’s event loop. When both sets are empty, every chunk was adopted: the receiver sends an empty NeedChunks (every chunk list needs an answer, and an empty one tells the sender to move on) and finalizes. Otherwise it builds a route for the data streams:

FieldMeaning
genThe file’s generation; stale streams and task results carry an older one and are ignored.
slotThe one writer that both fillers share, behind a mutex.
digestThe chunk table: offset, length and hash per chunk.
pendingUnits of delivery still running; see Completion.
pathThe file’s path, for events and logs.
oldThe old file’s descriptor while bases over it are out, for rebuilding chunks from operations.

pending starts at the number of remote chunks, plus one if the local set is not empty: one unit per remote chunk and one for the whole local copy task. Then, in this order:

  1. the route goes into the routing table, so the earliest data stream finds it;
  2. NeedChunks for the remote chunks without a basis goes out;
  3. if any basis was chosen, offer_bases is spawned, which sends the bases and requests their chunks;
  4. if the local set is not empty, copy_local_chunks is spawned.

Step 2 comes before step 4 on purpose: the sender starts reading and streaming as soon as the request lands, while the receiver’s disk fills in the rest and the signatures are computed. If the remote set is empty but the local set is not, the receiver still sends an empty NeedChunks, so the sender may move on. pending counts every remote chunk from the start, whichever request carries it, so the file cannot complete before its last request has even been sent.

Bases and operations

recv_io::offer_bases runs as one task per file. For each chosen chunk it reads the region from the old file’s descriptor, outside every lock, signs it (delta::Basis::sign: blocks of sqrt(region) bytes clamped to 512 B .. 4 KiB, per block a 32-bit rolling sum and the first 8 bytes of the block’s BLAKE3 hash), and sends it as a ChunkBasis. The bases go out in batches of at most 64, each batch followed by the NeedChunks for its chunks, and a session holds at most 32 MiB of bases that are sent but not yet requested. A region that cannot be read ends the signing, and the chunks left over are requested raw. The control stream is ordered, so the sender holds every basis before it sees the request that uses it.

On the sender (sender_role::on_basis, send::payload) a basis is kept per file and chunk until the request for that chunk arrives, then handed to the data-stream task. For such a chunk the task runs delta::encode: a window of one block slides over the chunk’s bytes one byte at a time, the rolling sum is updated in place, and each position is checked against a 64 Ki-bit filter, then the signature map, then the strong hash. A hit emits a copy of that block’s range in the old file and jumps a block ahead; a miss extends the current literal. Adjacent copies and literals are coalesced. If the operations are not at least a quarter smaller than the chunk, the chunk’s bytes go instead; otherwise the DataChunk carries ops and no data. A chunk requested a second time has no basis any more and goes raw.

On the receiver, read_range sees a frame with operations and calls rebuild. The operations must add up to exactly the chunk’s length, checked before anything is read; literals are copied in, and copies are read from the old file’s descriptor with positioned reads, outside the writer lock. The result goes through the same write_chunk as every other chunk. A rebuild that fails for any reason (an operation list that does not add up, a copy past the old file’s end, a read error) or a rebuilt chunk that does not hash to its record leaves the chunk missing, and the re-request asks for it raw. Nothing in this path is trusted: the old file may have changed in place since it was signed, the strong hash is 8 bytes, the sender may be hostile, and each of these ends in a chunk that does not verify and is asked for again.

Two fillers, one writer

The network side (accept_streams, read_stream, read_range). Each data stream’s header names the session, the file and a run of chunks. The reader looks up the route, reads chunk by chunk (rebuilding one that arrived as operations), hashes each, takes the writer lock and calls FileWriter::write_chunk, which checks length and hash again and writes at the chunk’s offset.

The local side (copy_local_chunks) walks the local set in order. For each chunk it reads the bytes from the source file with a positioned read, outside the writer lock, so network chunks keep landing meanwhile; then it locks the slot, stops if the slot is empty (the writer was retired by a newer chunk list or a failure), and calls the same write_chunk.

A local chunk is thus verified against the sender’s hash exactly like a network chunk, and both fillers set the same verified bit. Writes from the two sides land at disjoint offsets; the lock serialises only the writes, never the reads or the network. A local chunk that fails (the source vanished or shrank, a read error, a hash mismatch because the source was changed in place without a new mtime) is logged at debug level and skipped; its bit stays clear.

Completion

Both fillers end through finish_unit: a stream reader with the number of chunks its run accounted for, delivered or not; the copy task once, with one unit, after its whole list. finish_unit subtracts the units from pending and notes whether this call brought it to zero, then locks the slot:

  • an empty slot means the writer was retired or already reported: nothing to do;
  • if no chunk is missing, it takes the writer out of the slot and reports the file ready, and the receiver finalizes it;
  • else, if this call drained pending, it reports the file drained;
  • else another unit is still running and will report.

Taking the writer out of the slot makes a late unit harmless: a stream that straggles in after the file is complete finds the slot empty.

Recovery

A drained file with chunks still missing reaches Receiver::on_drained. It reads the missing set from the writer, checks that pending is zero, counts a re-request against MAX_REREQUESTS (3), adds the missing count back onto pending, and sends NeedChunks for those chunks, without bases. The sender delivers them raw and the normal path verifies them.

This is the path for a data stream that ended short, and the local copy task and the rebuild from operations use it too, by being units of the same request. A stale local source or a stale basis therefore costs one round trip and the bytes of the chunks that did not verify, and the file still ends with a verified whole-file hash. The stale index row is not corrected here; the next scan of that source file replaces it. A file still incomplete after three re-requests fails with WRITE_ERROR.

Finalize

recv_io::finalize runs fsync (only with --fsync, or on a push into an export with fsync = true), compares the whole-file hash with the sender’s, applies metadata through the descriptor, renames the .part over the destination, records the file in the index and sends FileAck DONE.

The hash is not computed by reading the .part back. BLAKE3 is a Merkle tree over 1 KiB leaves at absolute offsets, and the writer folds the file’s hash from the chunks it verified (tree_hash::TreeHash): the leaf-aligned interior of each chunk is hashed as aligned power-of-two subtrees through the blake3 crate’s hazmat API, the up to 1,023 bytes at either end of a chunk wait until the neighbouring chunk completes their leaf, sibling nodes merge eagerly so that a few dozen chaining values are held at most, and the root is folded at finalize along the tree’s own split points. A chunk adopted from an earlier .part or a clone is read once to verify it and feeds the tree from that read; a sparse hole feeds its zeros. The result equals b3sum of the file. What finalize does not catch is a byte changed on disk after the verified write, which rsync does not catch either.

Settle in place

When open_writer returns Opened::Identical, the content is already there, and the file is settled in place rather than placed. The receiver sends an empty NeedChunks, which tells the sender to wait for the acknowledgement, emits the held-back -i line if any attribute differs, and spawns settle_identical. That task discards a leftover .part of an earlier attempt with its progress record, unless another writer holds it, applies the sender’s mode, ownership and times to the existing inode through the open descriptor, and records the file in the index with the sender’s digest, so that the next run’s quick check passes. The receiver then acknowledges DONE.

The file counts as a metadata-only update: no bytes, no placed file. A metadata failure fails the file like a write error, and the next run tries again. A touch on either side, or a restore from backup, comes to one read of the old file on the side whose index row was stale, four small control messages and no write. The sender takes the count of files transferred from the receiver’s SessionDone, so a push that only settles files in place reports zero files transferred. Under -c no index row is trusted on either side, so every file present on both sides takes this path, read once per side.

Where the bytes land: a cloned .part, in place, or appended

By default the .part is a separate file, renamed over the destination at the end. Three variations change where the bytes are written.

A cloned .part. open_writer hands FileWriter::open_from the old file’s descriptor and chunk list whenever the old file is still the one that was hashed. An empty .part is first cloned from it with FICLONE (recv::reflink): btrfs, XFS, bcachefs, ZFS with block cloning. On success every chunk the old list holds at an offset where the new list wants the same chunk is read, verified and fed to the tree hash (adopt_from), and neither copied nor written. Only changed and moved chunks are written, and only those take new space. A refused clone (tmpfs, ext4, another device with --partial-dir) costs only the attempt, and the .part starts empty. A .part that already holds bytes is not cloned over; its recorded chunks are adopted as in step 3 of Open and partition.

In place (--inplace). FileWriter::open_inplace locks the destination itself, checks that it is the hashed inode, adopts the old chunks at unchanged offsets the same way, grows the file at once and shrinks it only at finalize, which also skips the rename. Reads of the old content and writes of the new one share a file, so writes are ordered by a gate on the route: admit(idx) waits until every chunk before idx is settled (written, rejected, or given up by a stream that ended early), and settle(idx) advances the cursor. A chunk below the cursor is admitted at once, which is how a re-request rewrites it. Both fillers go through the gate, and a retired writer closes it, releasing every waiter. The old content is used only at or above the chunk being written: a local copy whose old offset is below the chunk’s new offset becomes a remote chunk, and a basis starts at the chunk’s own offset. That is rsync’s rule, with rsync’s consequence: a deletion near the start keeps its reuse, an insertion loses it. An in-place file gets one ascending request after its bases, so the sender opens its runs in order and the one the cursor needs is never behind the others. What --inplace costs, as in rsync: readers see a torn file during the transfer, a crash leaves a mixture of old and new, a whole-file hash mismatch leaves the destination inconsistent until the retry, hard links to the destination see the new content, and a file has one write front, the gate’s cursor.

Append (--append; planner decision Append, action APPEND). The sender’s list covers only the tail. open_writer awaits the old file’s hash, requires it to be the planned prefix (its length equals the tail’s first offset, and the inode is unchanged), and builds the full list from the old chunk list plus the tail, with no whole-file hash to compare: finalize returns the hash folded from the bytes, which goes into the index, so the next run quick-checks the file. Chunk indices on the wire are the sender’s, relative to the tail. A destination that is not the planned prefix fails the file with a message naming append. --append-verify is the ordinary DELTA path with the planner’s skip rule, so a changed head is repaired.

The itemize line of a DELTA file

The planner decides DELTA before anyone knows whether the content changed, so for a DELTA file it does not print the -i line at plan time. It computes two lines, the transfer as planned and the attributes-only line that applies if the content proves unchanged (none if no preserved attribute differs), and the receiver prints the first when it opens the .part and the second when it settles the file in place. A touched file therefore itemizes as .f..t......, as in rsync. A dry run requests nothing, so the planner itemizes at once. A file of a resumed plan carries no held-back line.

The chain

For a large file with a small change and a warm index, where S is the time of one full pass over the file on either disk:

PhaseDone one after anotherAs the receiver runs it
Sender’s digestSS, concurrent with the old file’s hash
Receiver’s hash of the old fileS (0 if cached)overlapped with the sender’s digest
Local copy into the .partS, before the requestconcurrent with the transfer
Network transferafter all of the aboveright after the index lookups
Whole-file checkS, reading the .part backnone: folded from the verified chunks
Bytes for a small change inside a chunkthe chunk (64 KiB .. 1 MiB)about a block (512 B .. 4 KiB) of literal, plus about 4% of the chunk in signatures the other way
Writes of unchanged chunksS, copied into the .partnone with a cloned .part or in place; a read of them for the tree hash
Free space for a changed fileits full sizethe changed chunks (clone) or none (in place)

Done one after another, the critical path is up to 4 S plus the transfer. As the receiver runs it: S for the concurrent hashes, plus the longer of the local copy and the transfer. The receiver reads the old file once for its hash and once more, only around the missing chunks and capped at the old file’s size, for the signatures; it writes the new one once.

Receiver I/O for the same case, in reads and writes of the file’s size:

ReadsWrites
rsync, default21
rsync --inplace1changed blocks only
irsync, cloned .part, old file’s hash cached1, verifying the clone’s chunkschanged chunks only
irsync, cloned .part, old file’s hash not cached2changed chunks only
irsync --inplace1 or 2, as abovechanged chunks only
irsync, plain .part (no clone support)1 or 2, as above1

Invariants

  • A request cannot miss its streams. The route is in the table before NeedChunks leaves the receiver.
  • Every chunk is verified once, by the same code, whatever its source. write_chunk is the only way into the .part.
  • Nobody reports twice. A ready file’s writer leaves the slot; only the call that brought pending to zero reports a drained file; a re-request raises pending before the new streams arrive.
  • The old file is read at most once per session for its hash. The early hash is awaited before the lookup; any later hash of it is a cache hit.
  • Local data is never trusted. A mismatch degrades to a network fetch, not an error, and never reaches the .part.
  • Operations are never trusted either. A chunk rebuilt from them is verified by write_chunk like any other; the old file is only read, through a descriptor opened once; a rebuild that fails leaves the chunk missing, and its re-request carries no basis.
  • A cloned chunk is verified before it counts. Each adopted chunk is read and hashed before its bit is set, as a resumed .part’s chunks are.
  • In place, nothing above the cursor is written before it is read. Writes ascend through the gate; old content is read only at or above the chunk being written; a rejected or undelivered chunk settles the gate, so the cursor never waits for it.
  • An append never guesses the prefix. The sender’s tail is accepted only when the destination is the exact inode and length that was planned; otherwise the file fails, and a run without --append repairs it.
  • Reconnects and failures are safe. A new chunk list bumps the generation and retires the writer. A copy task of the old generation finds the slot empty and stops; its late finish_unit has nothing to report.
  • The sender’s view stays simple. It answers every NeedChunks with data streams; the bases are optional extras it may use for the one request that follows them. A file settled in place looks to the sender like one whose every chunk was adopted: an empty request, then DONE.
  • Settling in place trusts the quick check, not the clock. The destination is settled only if fstat on the open descriptor matches the stat under which it was hashed, in size, mtime, ctime, device and inode; otherwise it is received as a delta.

The tests that pin these properties are listed in Testing.

Introduction to fileset

fileset checks that a copy of a directory tree is the same as the original. You use it for two things:

  • Verify transfers and backups made with other tools, such as rsync or rclone.
  • Check important data sets in storage for bitrot. Bitrot is data that changes on disk without anyone writing to it.

fileset is a separate tool. It shares no code with irsync, and you do not need irsync to use it. That is on purpose: a check made with the same code as the copy can repeat the copy’s mistakes. This part of the book assumes you have never used irsync.

The idea

You record a manifest of the tree once. A manifest is a small database that holds each file’s checksum and metadata. Later you check a tree against it. fileset lists every difference. It changes nothing.

fileset init  ~/Photos     record a manifest of the tree
fileset check <copy>       compare a copy, or the same tree later, with it
fileset update ~/Photos    bring the manifest up to date after real changes

The manifest is a file named .fileset.sqlite at the top of the tree. A copy tool that copies the whole tree copies the manifest too, so the copy can check itself.

Install

fileset comes in the same packages as irsync, so every way of installing irsync installs it too. The quickest is the install script:

curl --proto '=https' --tlsv1.2 -LsSf https://irsync.org/install.sh | sh

Until the first stable release, v0.1.0, is out, there are only alphas and betas, so add --alpha straight after sh -s --.

Homebrew (brew install irsync-dev/tap/irsync) and apt and dnf (dist.irsync.org) work the same way from v0.1.0 on. The tarballs on the GitHub Releases page work too. All of them cover Linux on x86_64 and arm64 and macOS on Apple Silicon.

On other machines, build fileset from source. This needs Rust; get it from https://rustup.rs.

cargo install --git https://github.com/irsync-dev/irsync fileset

Install it on every machine where you want to run a check.

Where to go next

Tutorial: check a copy made with rsync

You will make a small tree of three files, record a manifest of it, copy the tree with rsync -a, check the copy, and then see what a damaged copy looks like. It takes a few minutes. You need fileset (install) and rsync.

Everything happens in two throwaway directories, ~/fileset-demo and ~/fileset-demo-copy. Nothing here touches your real files or backups.

1. Make a tree and record a manifest

mkdir -p ~/fileset-demo/2026/01
printf 'first photo\n'  > ~/fileset-demo/2026/01/IMG_0001.jpg
printf 'second photo\n' > ~/fileset-demo/2026/01/IMG_0002.jpg
printf 'third photo\n'  > ~/fileset-demo/IMG_0003.jpg
find ~/fileset-demo -exec touch -d '2026-01-15T12:00:00Z' {} +
fileset init ~/fileset-demo

The touch gives every item an old modification time, as a real tree would have. (Without it, the directories’ times and the copy’s would fall in the same second, and rsync does not copy a directory’s time when only the fraction of a second differs. The check in step 3 would then show CHG lines for the directories. See the same-second note.) fileset init hashes every regular file and writes ~/fileset-demo/.fileset.sqlite. It prints a summary on stderr:

entries=7 hashed=3 reused=0 warnings=0

The seven entries are the root, two directories, three files and the manifest. The manifest lives inside the tree. That matters in the next step.

2. Copy the tree

rsync -a ~/fileset-demo/ ~/fileset-demo-copy/

The manifest is an ordinary file, so rsync copies it too. If you leave it out with --exclude .fileset.sqlite, the copy has no manifest. Then point --manifest at the original when you check (see step 3).

3. Check the copy

fileset check ~/fileset-demo-copy

A clean copy prints nothing on stdout, a summary on stderr, and exits with code 0:

added=0 deleted=0 changed=0 unchanged=7 warnings=0

If the copy has no manifest, use the original’s:

fileset check --manifest ~/fileset-demo/.fileset.sqlite ~/fileset-demo-copy

The manifest then shows up as DEL .fileset.sqlite, because the copy lacks the file. That one line is expected:

added=0 deleted=1 changed=0 unchanged=6 warnings=0
DEL .fileset.sqlite

4. See a difference

Damage the copy on purpose. This flips one byte of a file, so the size stays the same, and puts the old modification time back, as bitrot would. It also deletes a file and adds one:

printf 'X' | dd of="$HOME/fileset-demo-copy/IMG_0003.jpg" bs=1 seek=2 conv=notrunc
touch -r ~/fileset-demo/IMG_0003.jpg ~/fileset-demo-copy/IMG_0003.jpg
rm ~/fileset-demo-copy/2026/01/IMG_0002.jpg
echo n > ~/fileset-demo-copy/new.jpg
fileset check ~/fileset-demo-copy

Each difference is one line on stdout, and the exit code is 1:

CHG 2026/01 mtime=2026-01-15T12:00:00.000000000Z→2026-11-10T21:10:56.879697180Z
CHG IMG_0003.jpg blake3=d7e964217db4d891f80f8add25b9a5b1f82d11d135a7188db527f3af6cdaa802→266b8cdd39a8f500d03472f37ce533e3a4efbc9be56a4435ed771f892324bc80
ADD new.jpg kind=file
DEL 2026/01/IMG_0002.jpg

The hashes are the real ones for these file contents, so you should see the same. The time on the first line is when you ran the commands.

CHG IMG_0003.jpg shows blake3 alone: the content changed and nothing else did. That is how bitrot looks. CHG 2026/01 is a side effect of the rm: deleting a file changes its directory’s modification time. ADD is on disk but not in the manifest. DEL is in the manifest but not on disk. CHG shows each differing field as stored→observed. fileset reports and repairs nothing. To repair, copy the good files again.

When you are done, remove the two directories: rm -r ~/fileset-demo ~/fileset-demo-copy.

Next: verify an rsync or rclone transfer in daily use, or check for bitrot.

Verify an rsync or rclone transfer

Use this to prove that a copy made by rsync, rclone, cp or another tool matches the original. The examples copy ~/Photos to /mnt/backup/Photos. For a first run, see the tutorial. Every option is in the reference.

The steps

Record the manifest before you copy:

fileset init ~/Photos

Copy, and wait for the copy tool to finish:

rsync -a ~/Photos/ /mnt/backup/Photos/

Check the copy, on the machine that holds it:

fileset check /mnt/backup/Photos

Exit code 0 means the copy matches. Exit code 1 means it differs, and each difference is a line on stdout. Exit code 2 means the check itself failed.

If you changed the tree since you recorded the manifest, run fileset update ~/Photos first, then copy again. See Keep a manifest current.

The manifest is part of the tree

init writes .fileset.sqlite into the tree, so the copy tool copies it along. If you filter the copy, for example with rsync --exclude, the manifest may stay behind. Then check stops with no manifest found. Point --manifest at the original’s manifest:

fileset check --manifest ~/Photos/.fileset.sqlite /mnt/backup/Photos

The copy lacks the manifest file, so the output includes DEL .fileset.sqlite. Ignore that one line. If the original is on another machine, copy the manifest file over first.

To keep the manifest out of the tree altogether, record it elsewhere with fileset init --manifest <MPATH> ~/Photos and pass the same --manifest to every check.

Tools that do not keep all metadata

The default check compares content, type, symlink targets, device numbers, permissions, modification times and sizes. A tool that does not keep permissions or times makes every file look changed. That is not damage. It is a copy that carries less metadata.

cp -r without -p keeps neither permissions nor times. The check shows a CHG line for every file and directory:

CHG 2026 mtime=2026-11-10T19:44:21.606059787Z→2026-11-10T19:44:39.596886187Z
CHG 2026/01 mtime=2026-11-10T19:44:21.607204393Z→2026-11-10T19:44:39.596918066Z
CHG 2026/01/IMG_0001.jpg mtime=2026-11-10T19:44:21.607204393Z→2026-11-10T19:44:39.596918066Z
CHG 2026/01/IMG_0002.jpg mtime=2026-11-10T19:44:21.607204393Z→2026-11-10T19:44:39.596944775Z
CHG IMG_0003.jpg mtime=2026-11-10T19:44:21.607204393Z→2026-11-10T19:44:39.596966804Z

Here only mtime differs, because the umask on that machine left the permissions alone. On another machine mode= shows up too. rclone keeps permissions on few backends, and keeps modification times to a precision that depends on the backend, so expect the same kind of lines after an rclone copy.

Compare only what the tool can keep. Drop one field at a time:

fileset check --ignore mtime /mnt/backup/Photos
fileset check --ignore mode --ignore mtime /mnt/backup/Photos

Or use the relaxed tier, which compares type, content, symlink targets and device numbers only:

fileset check --relaxed /mnt/backup/Photos
added=0 deleted=0 changed=0 unchanged=7 warnings=0

Content is still compared in every tier, so a changed byte still shows. Add back what you can trust, such as --relaxed --require size. The tiers are explained in How fileset works.

Directory times in the same second

rsync compares a directory’s time only to the whole second. If the copy’s directory was changed in the same second as the source’s, rsync treats them as equal and never sets the time. This happens when you build a tree and copy it right away. Files are not affected: their times are compared exactly.

The check then shows lines like this, where both times share the same second:

CHG 2026/01 mtime=2026-11-10T21:10:56.123456789Z→2026-11-10T21:10:56.987654321Z

This is harmless: no content differs. Running rsync -a again does not fix it. Either leave the time out with --ignore mtime on that check, or give the source directories an older time before you copy, for example with touch -d '2026-01-15T12:00:00Z'. Write the time with the Z so that GNU, macOS and uutils touch all read it the same way.

When the copy is not on a local disk

fileset reads a local path. It cannot check an rclone copy that lives in S3 or another object store.

  • Mount the remote and check the mount point: rclone mount myremote:photos /mnt/remote, then fileset check --relaxed --manifest ~/Photos/.fileset.sqlite /mnt/remote. Every file is read over the network, so this is slow on a big tree.
  • Or run fileset check on a machine that holds the copy as ordinary files.

Object stores do not keep permissions, owners or symlinks as a file system does, so use --relaxed there.

Other things that make a check differ

  • Run the check after the copy tool has finished. An interrupted rsync leaves temporary files behind, and check reports them as ADD.
  • Copy deletions too. Without rsync --delete, files you removed from the original stay in the copy and show as ADD.
  • Between macOS and Linux, symlink permissions differ. Use --ignore mode.

Verify an irsync transfer

Use this when you want proof, from a tool that shares no code with irsync, that a tree arrived intact. (For rsync, rclone and other tools, see Verify an rsync or rclone transfer.) You record a manifest of the tree on the client, let irsync carry the tree and the manifest to the daemon, and check the copy against the manifest there. The same manifest later tells you whether either copy has rotted on disk.

The examples use the setup from Your first sync: the client has ~/Photos, and the server runs the daemon, known on the client as myserver, with the export photos at /srv/photos. Every option is listed in the fileset reference.

Install fileset

Install fileset on both machines (see Introduction):

cargo install --git https://github.com/irsync-dev/irsync fileset

1. Record a manifest on the client

On the client, create the manifest:

fileset init ~/Photos

This hashes every regular file and writes ~/Photos/.fileset.sqlite. At the end it prints a summary on stderr:

entries=1843 hashed=1790 reused=0 warnings=0

If you have recorded a manifest before, bring it up to date instead. Only files whose size, modification time or inode changed are hashed again:

fileset update ~/Photos

2. Sync

Push the tree, manifest included:

irsync -av ~/Photos/ myserver:photos/

The manifest is an ordinary file in the tree, so irsync carries it like any other. If you removed files on the client since the last sync, add --delete, or the daemon’s copy keeps them and the check reports them as ADD.

Wait until the sync has finished. An interrupted sync leaves .irsync.<name>.part files behind (see Files and state), and the check reports those too.

3. Check on the daemon’s machine

On the server, check the copy against the manifest that arrived with it. Run this as an account that can read every file, such as the account the daemon runs as:

fileset check /srv/photos

A clean copy prints nothing on stdout, a summary on stderr, and exits with code 0:

added=0 deleted=0 changed=0 unchanged=1843 warnings=0

Otherwise each difference is one line on stdout, and the exit code is 1:

CHG 2026/01/IMG_0042.jpg blake3=9f2c41e0b7a35d68c1f04e2b9a7d3c5e8f1b6a0d4c2e7f93b5a8d1c6e0f4b297→51d07a3e9c2b4f8d6e1a0c5b7f3d9e2a4c8b6f0d1e5a3c7b9f2d4e6a8c0b1d35
DEL 2026/01/IMG_0043.jpg

ADD is on disk but not in the manifest, DEL is in the manifest but not on disk, and CHG shows each differing field as stored→observed.

The default comparison covers type, content, symlink targets, device numbers, permissions, modification times and sizes. Owners are not compared by default: -a keeps the owner only when the daemon runs as root, and maps user and group names to the daemon’s ids unless you pass --numeric-ids. When both machines use the same ids, compare owners as well:

fileset check --require uid --require gid /srv/photos

If the client runs macOS and the server Linux, or the other way round, symlink permissions differ between the two systems. Leave them out:

fileset check --ignore mode /srv/photos

Repair a damaged copy

If a later bitrot check finds a damaged file, fileset repairs nothing. A normal sync does not repair such a file either, because it compares size and modification time. Copy the good version from the other machine with -c, which compares content. If the server’s copy is damaged, push again:

irsync -avc ~/Photos/ myserver:photos/

If the client’s copy is damaged, pull instead:

irsync -avc myserver:photos/ ~/Photos/

Check the other copy first, so that you do not spread the damage. To find damage in the first place, see Check data for bitrot.

Check data for bitrot

Bitrot is data that changes on disk without anyone writing it: a flipped bit, a bad sector, a faulty controller. The file’s size and modification time stay the same, so most tools do not notice. fileset reads every byte again and compares it with the checksum it recorded.

The examples use ~/Photos. Every option is in the reference.

Record, then check later

Record a manifest while you know the data is good:

fileset init ~/Photos

Months later, run check. No copy is involved:

fileset check ~/Photos

A file whose bytes changed while its size and modification time stayed the same shows up as a CHG line with blake3 alone:

CHG 2026/01/IMG_0001.jpg blake3=81c4b7f7e0549f1514e9cae97cf40cf133920418d3dc71bedbf60ec9bd6148cb→7d271ea55b6b5af8d6a863e4530228f65ffc4a33086a485d73e84ee84243463f

fileset reports; it repairs nothing. Restore the file from another copy, and check that copy first so that you do not spread the damage.

Rot or an edit?

Rot usually shows as a CHG line with blake3 alone, while an edit changes the time and size too. Check before you update explains how to tell them apart and why the order matters.

Check on a schedule

check exits 0 when clean, 1 when it found differences and 2 when the run itself failed. A cron job can use that. This line checks at 03:00 on the first of each month. It writes everything to a log, and prints a message, which cron mails to its owner, only when the check did not exit 0:

0 3 1 * * $HOME/.cargo/bin/fileset check -q $HOME/Photos > $HOME/fileset-check.log 2>&1 || echo "fileset check exited with $?; see $HOME/fileset-check.log"

Cron has a short PATH that does not include ~/.cargo/bin, so the line gives the full path to fileset. Cron runs the command with sh, which expands $HOME; it does not expand ~ everywhere, for example not in PATH= lines, so write $HOME or the full path. The mail only arrives if local mail is set up on the machine.

-q hides progress. The summary line still goes to stderr, which is why the log takes both streams. Add --fail-on-warnings when an unreadable file should count as a failure too. Warnings alone give exit 0 otherwise.

Exit 1 and exit 2 are different problems. Exit 1 means your data differs from the manifest. Exit 2 means fileset could not run, for example because the disk is not mounted or the manifest is missing.

Read-only media and snapshots

check never changes the tree. But a manifest inside a read-only tree may fail to open, with exit 2 and a message suggesting --manifest. Copy the manifest somewhere writable and point --manifest at the copy:

cp /mnt/snapshot/photos/.fileset.sqlite /tmp/photos.fileset.sqlite
fileset check --manifest /tmp/photos.fileset.sqlite /mnt/snapshot/photos

Keep a manifest current

A manifest describes the tree as it was when you recorded it. When you add, edit or remove files on purpose, bring the manifest up to date:

fileset update ~/Photos

update hashes only files whose size, modification time or inode changed, or that the manifest has no hash for. For every other file it keeps the stored hash. It forgets files that are gone. The summary shows how much work it did:

entries=8 hashed=1 reused=3 warnings=0

Check before you update

Run check first on a tree you suspect, or have not looked at for a while:

fileset check ~/Photos

update keeps the stored hash of a file whose size, modification time and inode are unchanged. So if a byte rotted in such a file, the stored hash still holds the old content and the next check still shows the damage. But an edited file is rehashed, and its new content becomes the truth. If rot and an edit hit the same file, update hides the rot.

So read the check output first. A file you edited shows several fields changed, such as blake3, mtime and size. Damage you did not cause often shows blake3 alone. When every difference is one you meant, run update.

Record the current content as correct

update --rehash hashes every file again, even when size, modification time and inode are unchanged:

fileset update --rehash ~/Photos

Use it only when you have decided the current content is right, for example after you restored a file from a good copy. It takes as long as init. It overwrites the stored hash of a damaged file, so the damage is no longer visible.

Keep a copy’s manifest in step

After update, copy the tree to the backup again with your copy tool. The updated manifest travels with it. Then check the copy. See Verify an rsync or rclone transfer.

fileset reference

fileset records the state of a directory tree in a manifest and later verifies the tree against it. It lives in crates/fileset and shares no code with irsync. For an introduction, see Introduction to fileset. The how-to pages are Verify an rsync or rclone transfer, Verify an irsync transfer, Check data for bitrot and Keep a manifest current.

Install it with:

cargo install --git https://github.com/irsync-dev/irsync fileset

Commands

fileset init   [OPTIONS] <PATH>
fileset update [OPTIONS] <PATH>
fileset check  [OPTIONS] <PATH>

<PATH> is the root of the tree and must be a directory.

init

init scans the tree and creates its manifest, at <PATH>/.fileset.sqlite by default. It refuses to run when:

  • a manifest already exists. The exception is a manifest left by an init that was interrupted (killed, or the machine went down): it holds nothing, so init replaces it with a warning.
  • the tree lies inside another fileset: a .fileset.sqlite or .fileset.fjall exists in a parent directory of <PATH>. This is checked before anything is written.
  • the tree holds a manifest in a subdirectory. This is found when the scan reaches it; init then removes the manifest it had begun.

Nested filesets are not supported. If the scan fails, init removes the manifest it began.

update

update scans the tree and brings an existing manifest up to date. It refuses to run if there is no manifest, or if the manifest was left by an interrupted init (run init again). A manifest in a subdirectory is a warning, not an error.

A regular file is hashed again only when its size, mtime or inode differ from the manifest, or when the manifest holds no hash for it. Otherwise the stored hash is kept. A file that cannot be read produces the warning cannot hash <path> and is recorded without a hash. Rows that have not changed are not rewritten. Whatever the scan did not see is removed from the manifest: deleted entries, and also everything below a directory that could not be read or a mount point that was not crossed. Each such directory and mount point produces a warning.

init and update share one engine and differ only in these preconditions.

check

check scans the tree and reports every difference between it and the manifest. It never changes the tree or the manifest’s contents. Opening a fjall manifest does touch its journal and lock files.

check hashes a regular file only when the manifest has an entry for it and content is compared. A file the manifest holds no hash for (it could not be read when it was recorded) produces the warning no stored checksum for <path>. A manifest in a subdirectory produces the warning nested manifest at <path>.

Options

All commands

OptionEffect
--manifest <MPATH>Use the manifest at MPATH instead of <PATH>/.fileset.sqlite or <PATH>/.fileset.fjall. It may lie outside the tree. A directory is read as fjall, a file as SQLite.
--fail-on-warningsExit 1 instead of 0 when the run produced warnings.
--cross-mount-pointsDescend into directories on other filesystems.
--no-dir-sortDo not sort directory entries before iterating.
-j, --jobs <N>Threads that hash file contents. Default: the number of CPUs. N is at least 1.
--walk-threads <N>Threads that list directories and read metadata. Default: 4. N is at least 1.
--no-builtin-excludesWalk the built-in excludes like any other directory.
-q, --quietSuppress progress.
-v, --verboseAlso print an INFO line for each built-in exclude skipped. Conflicts with --quiet.

More walk threads are often slower. On a 16-core machine with an APFS SSD, a no-change update of a 1.7 million entry tree took 24 s with 4 threads and 30 s with 8: the kernel serialises much of the metadata work.

Without --manifest, fileset looks for .fileset.sqlite and .fileset.fjall at the root. If both exist, it stops and asks for --manifest.

init only

OptionEffect
--store <sqlite|fjall>Backend to create. Default: sqlite.

update only

OptionEffect
--rehashHash every regular file again, even if size, mtime and inode are unchanged.
--force-xattr-readsRead every entry’s extended attributes. By default an entry whose type, inode, size, mtime and ctime match the manifest keeps the attributes recorded there (changing an attribute updates the ctime); only an entry whose attributes could not be read in full is read again.

check only

OptionEffect
--relaxedCompare the relaxed tier (below). Conflicts with --paranoid.
--paranoidCompare the paranoid tier (below). Conflicts with --relaxed.
--ignore <FIELD>Drop one field from the comparison. Repeatable.
--require <FIELD>Add one field to the comparison. Repeatable.

Comparison tiers

TierCompared
--relaxedtype, content (blake3), symlink target, device numbers (rdev)
defaultrelaxed, plus mode, mtime, size
--paranoiddefault, plus uid, gid, nlink, xattr

The type is always compared. --ignore and --require adjust whichever tier is in effect, so “default plus owner” is --require uid --require gid. Field names:

blake3 target rdev mode mtime size uid gid nlink xattr

An unknown field name is an error (exit 2).

Some fields apply only to some types:

  • blake3 applies to regular files, target to symlinks, rdev to character and block devices.
  • size and nlink are not compared for directories.
  • mtime is not compared for the root, nor for the directory that holds the manifest when the manifest lies inside the tree: writing the manifest changes both.
  • A manifest inside the tree is recorded, but only its type is compared.

Output

check writes one line per differing entry to stdout:

ADD docs/new.txt kind=file
DEL docs/old.txt
CHG docs/a.txt mode=0644→0600 size=12→13
  • ADD: on disk, not in the manifest. kind is one of dir, file, symlink, fifo, socket, chardev, blockdev, other.
  • DEL: in the manifest, not on disk. This includes everything recorded below a directory that is now a file or a symlink.
  • CHG: in both, with at least one compared field differing. Each field is shown as field=<stored>→<observed>. If the type differs, only kind= is shown.
  • CHG <path> kind=<stored kind>→unverified: recorded in the manifest, but check could not observe it. It lies below a directory that could not be read or a mount point that was not crossed, or it could not be stat’ed. Content that cannot be verified counts as a difference (exit 1), not just a warning.

Field values:

FieldShown as
blake364 hexadecimal digits; unreadable when the file could not be read
modefour octal digits, such as 0644 or 4755
mtimeUTC with nanoseconds, such as 2026-01-31T12:00:00.000000005Z
size, uid, gid, nlink, rdevdecimal
targetthe link target; - if none
xattrone xattr:<name>=<stored>→<observed> per attribute that differs; - where the attribute is absent; values longer than 64 bytes are cut and end in …

Paths, link targets and attribute names and values are escaped. Printable UTF-8 and the space pass through, \ becomes \\, control bytes, DEL and bytes that are not valid UTF-8 become \xNN, and C1 controls and the bidi formatting characters become \u{...}.

Warnings go to stderr, prefixed WARN . Progress goes to stderr only when stderr is a terminal and -q is not given. A summary line goes to stderr at the end:

added=1 deleted=1 changed=1 unchanged=40 warnings=0     (check)
entries=43 hashed=3 reused=40 warnings=0                (init, update)

Built-in excludes

macOS keeps .DocumentRevisions-V100, .Spotlight-V100, .TemporaryItems, .Trashes and .fseventsd at the top of every volume it touches, and ordinary users cannot read them. At the root of the tree, and at every mount point crossed with --cross-mount-points, entries with these names are neither recorded nor descended, on every OS: on a disk read elsewhere they are readable but still junk. Skipping one is not a warning, so it does not trip --fail-on-warnings. The same names deeper in the tree are ordinary entries.

A manifest written with --no-builtin-excludes may hold them. check without that option does not report them, and the next update without it drops them.

Files

PathContents
<PATH>/.fileset.sqliteThe manifest, SQLite backend (default). Its -wal, -shm and -journal sidecars are skipped by the scan.
<PATH>/.fileset.fjallThe manifest, fjall backend: a directory.

An update that finishes leaves the SQLite manifest as a single file. If another process holds it open, the -wal sidecar stays, with a warning; the next update folds it in.

Exit codes

CodeMeaning
0Clean.
1check found differences; or, with --fail-on-warnings, the run produced warnings. The second is the only way init and update return 1.
2The run itself failed.

Exit code 2 covers, among others: a manifest that cannot be opened or read; a root that is not a directory; a manifest schema newer than this fileset; check on a manifest schema older than this fileset (update migrates it); both manifests at the root without --manifest; init on a tree that already has a manifest, lies inside a fileset or contains a nested one; update on a tree that has none.

Read-only media

See Check data for bitrot.

Known limitations

  • Symlink permission bits differ between Linux (always 0777) and macOS (set from the umask, often 0755), so a tree carried between them shows mode= changes on symlinks. Use --ignore mode or --relaxed.
  • fjall preallocates a sparse 64 MiB journal in the manifest directory. Copy a fjall manifest with a sparse-aware tool, such as cp --sparse=always or rsync --sparse, to avoid writing 64 MiB of zeros.

Holes in sparse files, hard links, ACLs, mount points, timestamp precision and the other things a check cannot see are in What fileset cannot catch.

How fileset works

This page explains what a manifest holds, what a check compares, and what fileset cannot see. Commands and options are in the reference.

What a manifest records

fileset init walks the tree and records one entry for every file, directory, symlink and other item it finds. Each entry holds:

  • the path and the type: directory, regular file, symlink, fifo, socket, character device or block device;
  • for a regular file, a BLAKE3 checksum of its content;
  • for a symlink, its target; for a device, its device numbers;
  • permissions, owner and group, size, modification time and link count;
  • extended attributes, which are named values some file systems attach to a file.

The manifest is a SQLite file, .fileset.sqlite, at the top of the tree. A second backend, fjall, stores it as a directory. The default is the one to use unless you have a reason.

update keeps a stored checksum while a file’s size, modification time and inode are unchanged. That is what makes it fast, and why you check before you update.

Comparison tiers

check compares a tree with the manifest. How much it compares depends on the tier.

There are three tiers: relaxed (content only, plus type, symlink target and device numbers), the default (adds permissions, modification time and size) and paranoid (adds owner, group, link count and extended attributes). The table of exactly which fields each tier compares is in the reference.

Pick the tier by what the copy tool can keep. A plain cp or an rclone copy to a backend without permissions fits --relaxed. An rsync -a copy between machines that share user ids fits the default plus --require uid --require gid. --ignore and --require adjust any tier one field at a time.

The tier decides what counts as a difference. Content is compared in every tier, so changed bytes always show.

What fileset cannot catch

fileset reports differences in what it records. Some things it does not record, or does not compare, so a copy can differ from the original and still pass.

  • Holes in sparse files. fileset hashes the bytes a program reads. A hole reads as zeros, so a sparse file and a fully written copy of it have the same checksum. A check cannot tell whether a copy kept the holes.
  • Hard links. Only the link count is recorded, and it is compared only with --require nlink or --paranoid. fileset does not record which paths share a file, so a copy that turned hard links into separate files passes the default check.
  • ACLs on macOS. Access control lists are not recorded.
  • Anything it did not look at. Mount points are not crossed unless you pass --cross-mount-points. A tree with btrfs subvolumes is cut short by default. A warning names the directory. check reports what lies below as unverified, which counts as a difference. update drops it from the manifest.
  • Timestamp precision. Modification times are compared to the nanosecond. A file system with coarser timestamps shows mtime= changes on every file. Use --ignore mtime or --relaxed.
  • A manifest that is wrong from the start. fileset compares against what it recorded. If the tree was already damaged at init, the manifest records the damage.

The reference lists two more: symlink permission bits between Linux and macOS, and the sparse journal of the fjall backend.

fileset reports and repairs nothing, and it never changes the tree.

Set up a development checkout

irsync is developed at github.com/irsync-dev/irsync. Clone it and build the workspace:

git clone https://github.com/irsync-dev/irsync
cd irsync
cargo build --workspace

The workspace holds irsync itself and the tools that test it: fileset (reference), filegen (Generating test trees), irsync-stress (Stress testing) and irsync-netstress (Network stress).

Requirements

tools/dev-setup.sh sets most of this up and checks the rest. It installs what rustup and cargo can install: rustup, the toolchain with rustfmt and clippy, the musl target on Linux, and cargo-nextest, dist and mdbook at the versions CI uses. It points git at the repo’s hooks. System tools such as rsync, Python and a C compiler it only checks, naming the package to install. tools/dev-setup.sh --check reports without changing anything. Run it again whenever you like.

  • Rust. rust-toolchain.toml pins an exact Rust version, which rustup picks up; CI and releases use the same file. To move to a newer Rust, change the version there and run the full regression.
  • GNU rsync 3.1 or newer on PATH, for crates/irsync/tests/rsync_compare.rs, which compares irsync’s result with rsync’s. Without it the test prints a line and passes, which cargo test -q hides, so it checks nothing. With the CI environment variable set, the test fails instead of skipping. On macOS the bundled rsync (2.6.9 or openrsync) is too old: brew install rsync.

Continuous integration

The workflow in .github/workflows/ci.yml runs on GitHub for every push to main and every pull request, on Linux and macOS. It installs GNU rsync and runs, in this order:

cargo fmt --all --check
cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
cargo clippy --locked --workspace --all-targets --no-default-features -- -D warnings
cargo nextest run --locked --workspace --all-features --profile ci --run-ignored all
cargo test --locked --workspace --all-features --doc

--locked makes the run fail if Cargo.lock is out of date, as the release build would.

A second job, release build, runs the release build itself for the two Linux targets (x86_64 and arm64 musl): dist build, which runs packaging/dist/build.sh, on the same runners as a release. A change that would break a release fails here, before anyone tags it.

The tests run with cargo-nextest, which runs each test in its own process and tests from all files side by side. That makes the run faster than cargo test, which runs one test file after another. The ci profile in .config/nextest.toml runs every test even after a failure and kills a test that runs longer than 5 minutes, naming it. --run-ignored all adds the slow network-fault tests that an everyday cargo test skips (Testing). nextest does not run doc tests, so cargo test --doc runs those.

On macOS, CI uses the ci-macos profile instead. It leaves out a few slow tests that work the same on every OS, which Linux CI still runs (see Platform skips).

The second clippy run keeps the build without the otel feature compiling (see Cargo features).

You don’t need nextest locally: cargo test runs the same tests. To run them the way CI does, install it with cargo install cargo-nextest --locked.

The pre-push hook

.githooks/pre-push refuses a push whose commits are not rustfmt-clean, so a formatting slip is caught before CI sees it. Every commit being pushed is checked with cargo fmt --all -- --check in a throwaway worktree: what counts is what the remote receives, not the state of the working tree. Install it once per clone:

git config core.hooksPath .githooks

Before pushing

Clippy and the tests are not part of the hook. Run them yourself:

touch crates/irsync/build.rs    # re-runs the build script, which bakes in the git commit
cargo test -q --workspace --all-features --no-fail-fast -- --include-ignored
cargo fmt --all --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo clippy --workspace --all-targets --no-default-features -- -D warnings

These are the checks CI runs.

Testing

This page is the start of the testing pages. For the case made to users, that a finished sync leaves the destination exactly like the source under the conditions stated there, and what backs it, see How we know irsync is correct. This section is for people who change irsync and need to know which test to add or run.

The layers

There are four layers. They go from fast and narrow to slow and broad.

  1. Engine tests. Each runs a sender and a receiver inside one test process and checks the result. They live in crates/irsync/tests/ and run with cargo test. With the test-hooks feature (see Cargo features) a test can inject a fault, slow a step or read the receiver’s event log. They catch logic bugs in one feature: the planner, the receiver, deletes, resume, filters. Reach for them first. A fix without one is not finished.
  2. The loopback stress loop. irsync-stress changes a source tree with filegen, syncs it, and checks the copy with fileset check, over and over. It catches what no one thought to write a test for: odd mixes of files, renames, links, long names and big trees. It takes minutes.
  3. netstress. irsync-netstress runs the same loop through a simulated bad network: slow, lossy, and cut for up to a minute. It catches bugs in sessions, reconnect, resume and the transport. It takes many minutes and needs its own build.
  4. Campaigns. Hunting bugs turns the stress loop into a search: many seeds, with the settings aimed at one part of irsync per row of a matrix. It catches the bugs a default run is too gentle to hit. It takes hours, so run it before a release or after a risky change, not on every push.

Which test for which change

You changedAdd or run
The receiver, the planner, delta or chunk handlingAn engine test in crates/irsync/tests/. Existing ones to extend: delta.rs, plan.rs, recv.rs, inplace.rs, content_equal.rs. See Receiving a changed file.
Deletes, filters or optionsAn engine test: delete.rs, filter.rs, filters_e2e.rs, push_options.rs.
Code that walks or writes the tree: scan, index, metadata, links, renamesAn engine test, then a stress run in both directions: irsync-stress --direction push and --direction pull.
Sessions, reconnect, resume or the transportAn engine test (resume.rs), then a netstress run, for example --profile 4g-vehicle.
Anything risky, or something a default stress run barely touches (hard links, sparse files, odd timestamps, huge listings)A row of the campaign matrix, run with crates/stress/tools/matrix.sh.

A bug that stress or netstress finds should end as an engine test that fails before the fix and passes after it. The stress run found the bug; the engine test keeps it from coming back. CI runs the whole test suite on every push, which includes the engine tests and a short end-to-end test of each rig. The long stress, netstress and campaign runs are done by hand.

For everyday work, run the suite with the features CI uses:

cargo test -q --workspace --all-features --no-fail-fast

This skips four slow network-fault tests (marked #[ignore]) in crates/netstress/tests/e2e.rs. They run the real fault binaries on real time, take a few minutes together, and the first run also builds those binaries. The full regression, which CI and Before pushing use, runs them too:

cargo test -q --workspace --all-features --no-fail-fast -- --include-ignored

No other test is ignored, so --include-ignored adds exactly these four.

The syncs through the fault layer in crates/irsync/tests/netsim.rs are not ignored, though they need minutes of network time: they run client and daemon in one process on tokio’s paused clock, over an in-memory network (with_netsim in crates/irsync/tests/common). Whenever every task waits on a timer, the clock jumps to the next one, so they finish in about a second. Write a new test of irsync through the fault layer that way. A test that runs the real fault binaries is ignored like the four.

That relies on everything with a deadline reading tokio’s clock (tokio::time::Instant), not std::time::Instant. irsync’s reconnect, --bwlimit and persistence timers do; telemetry and loops in blocking threads keep the real clock, since paused time stands still there. iroh 1.3.0 had QUIC read the real clock; the workspace Cargo.toml patches in the fix from n0-computer/iroh#4676 until a release has it. Before pushing lists the other checks.

Cargo features

  • otel (on by default) builds the OpenTelemetry export. The clippy run with --no-default-features keeps the build without it compiling.
  • test-hooks (tests only; irsync’s dev-dependency on itself turns it on) adds the test fields of SideHooks (crates/irsync/src/session/mod.rs): injected faults, slowed steps, a cap on files in flight, and the receiver’s event log, which crates/irsync/tests/delta.rs checks the order of steps against (see Receiving a changed file below).
  • netsim builds the fault layer that irsync-netstress drives. It needs its own build; see The fault build.

To check by hand that a build without otel ignores the telemetry settings:

OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 \
  cargo run -p irsync --no-default-features -- -a src/ HOST:export/

stderr starts with irsync: built without OpenTelemetry support; ignoring [telemetry], and the sync runs as usual.

Platform skips

Tests that create non-UTF-8 file names skip when the filesystem refuses the name (APFS does); on Linux they always run. See R29 in IRSYNC_DECISIONS.md. The rsync comparison test skips without GNU rsync 3.1 or newer, and fails instead when CI is set (Requirements).

The macOS CI job leaves out crates/irsync/tests/backpressure.rs, crates/irsync/tests/blocking_pool.rs and crates/netstress/tests/e2e.rs, through the ci-macos profile in .config/nextest.toml. The macOS runners are slow and have 3 cores, and these tests take over a third of the test time there, while the code they test works the same on every OS. Linux CI runs them on every push, and a local run on a Mac runs them too. A test that checks something macOS-specific belongs in none of these files.

Workload and stress tools

Three crates in the workspace exist to test irsync: filegen, irsync-stress and irsync-netstress. They are described in the layers above and on their own pages: filegen, Stress testing and Network stress with netstress. None of them links irsync; they drive it through its command line. irsync-netstress reuses the stress crate’s library. filegen also makes reproducible trees for benchmarks (Performance).

The end-to-end tests of stress and netstress run the real binaries. cargo test -p stress does not build the other binaries it needs: run cargo build --workspace first, or use cargo test --workspace. The netstress end-to-end tests run only with -- --include-ignored; they build the fault binaries into target/netsim/debug themselves the first time, which takes a few minutes.

Receiving a changed file

The properties described in Receiving a changed file are pinned by end-to-end syncs between two engines in crates/irsync/tests/. They read the receiver’s event log (SideHooks::event, behind the test-hooks feature), which records prehash, plan, chunklist, need, chunk (a network chunk written), copied (the local copy task finished), basis, ops (a chunk verified from operations), identical, clone, inplace and append, each with the path. delta.rs checks the order of the steps (the request leaves before the local copies, which a 150 ms delay per copy makes visible), a stale local chunk that is re-requested, and that the old file is hashed once from plan time; sub_chunk.rs tests the block codec in irsync::delta on its own; sub_chunk_delta.rs measures the bytes of the sub-chunk delta and its fallbacks; inplace.rs covers the cloned .part, --inplace and --append (the clone tests skip, and say so, where target/ is on a filesystem that cannot clone); content_equal.rs covers settling in place and -c; warm.rs covers same-size candidates and irsync index; recv.rs holds the writer-level tests; plan.rs pins the planner’s --append and --append-verify decisions.

To find the code for a step: the early hash is the Delta arm of session/planner.rs; opening, comparing, partitioning and choosing bases are in session/recv_io.rs (open_writer, unchanged_file, local_sources, basis_specs, offer_bases, rebuild, copy_local_chunks, finish_unit, settle_identical, finalize, the in-place Gate); dispatch and re-requests are in session/receiver.rs (on_opened, on_drained, MAX_REREQUESTS); the sender’s use of a basis is session/sender_role.rs (on_basis) and send.rs (payload); the codec is delta.rs; the writer, cloning and adoption are recv.rs (FileWriter, reflink); the folded whole-file hash is tree_hash.rs; chunk lists in parts are session/parts.rs; the test hooks are the fields of SideHooks in session/mod.rs.

Generating test trees with filegen

Part of Testing: the tool that changes the tree in every stress loop.

filegen simulates the use of a POSIX filesystem. It walks a Markov chain of filesystem operations (create, append, truncate, rename, symlink, hard link, chmod, set mtime, punch a hole, remove a subtree, and more) and applies each one somewhere in a directory tree. Every decision, the bytes written included, comes from a seeded generator, so a run is reproducible from its seed and can be resumed from its saved state as if it had never stopped. It shares no code with irsync or fileset.

It is the mutating half of the stress loop: filegen run mutates a source tree, fileset update records it in the tree’s manifest, irsync carries tree and manifest to another host, and fileset check there confirms that every change arrived. irsync-stress runs that loop. filegen only mutates, logs and records. Every step is timed, so a run is also a performance trace of the filesystem under test.

How the chain, targets, sizes and resume work, and how to extend it, is on How filegen works.

The design is in 2026-10-20-filegen-design.md, the calls made while building it in FILEGEN_DECISIONS.md.

Generate a tree

Build it with cargo build -p filegen (or --release); the binary is target/debug/filegen. The tree must be an existing directory, empty or populated. Keep the output directory outside it:

mkdir -p ~/src-tree
filegen run --seed 42 --steps 1000 --out-dir /tmp/fg ~/src-tree

This writes /tmp/fg/filegen-42.log and /tmp/fg/filegen-42.state.yaml.

Continue the same history later, from its state file:

filegen run --resume /tmp/fg/filegen-42.state.yaml --steps 1000 ~/src-tree

Bound the tree’s size and change any configuration key on the command line:

filegen run --seed 7 --steps 1000 --max-total-size 1G --max-file-size 16M \
    --set content.pattern_fraction=0.2 --out-dir /tmp/fg ~/src-tree

Draw and log the steps without touching the tree:

filegen run --seed 42 --steps 1000 --dry-run --out-dir /tmp/fg ~/src-tree

To see every configuration key with its default, make a one-step dry run and read the config: block of its state file, as in Configuration.

Reference

Command

filegen run [OPTIONS] --steps <N> (--seed <S> | --resume <STATEFILE>) <PATH>

<PATH> must be an existing directory, empty or populated.

  • --steps <N>: operations to perform in this invocation (required)
  • --seed <S>: start a fresh run from this 64-bit seed
  • --resume <STATEFILE>: continue from a previous run’s state file; exactly one of --seed and --resume is required
  • --config <FILE>: YAML configuration file; every key is optional
  • --out-dir <DIR>: where the log and state file go (see below)
  • --prefix <PREFIX>: base name of the output files instead of filegen-<seed>; must not be empty, ., .., or contain /
  • --set <KEY=VALUE>: set any configuration key by its dotted path, value parsed as YAML (repeatable), e.g. --set content.pattern_fraction=0.2
  • --pace <PACE>: when each step starts. fast (the default) never waits; steady:<N> starts at most N steps a second; bursts:<ON_MS>:<OFF_MS> runs flat out for ON_MS milliseconds, then waits OFF_MS, and repeats. Pace only decides when a step starts, never which one, so it does not change the tree a seed makes. irsync-stress uses it for --concurrent.
  • --dry-run: draw and log every step, update the model, but touch nothing
  • --force: with --seed, truncate an existing log and state file for this prefix instead of refusing
  • -q, --quiet: no progress line and no file paths on stderr
  • -v, --verbose: echo every log line to stderr (hides the progress line)
  • --max-total-size <SIZE>, --max-file-size <SIZE>, --max-depth <N>, --max-path-len <N>, --remove-tree-max-entries <N>, --checkpoint-steps <N>, --fsync <true|false>: the top-level configuration keys of the same name. --fsync takes a value.

Sizes are plain bytes or carry a K, M, G or T suffix (powers of 1024). Precedence, lowest first: built-in defaults, the resumed state’s config (without out_dir and prefix, see below), the --config file, --set, the dedicated flags. Unknown keys are an error, max_file_size may not exceed max_total_size, the names.classes weights may not all be 0, and no names.extensions entry may contain / or NUL.

Output files

The output directory is, first that is set: --out-dir, the out_dir config key, $FILEGENTMP, $TMPDIR, /tmp. A relative directory is resolved against the current directory, and the state file records the absolute directory used. A --resume ignores the out_dir and prefix saved in its state file: unless --out-dir, --prefix, --set or a --config file given on that invocation says otherwise, it writes to the directory of the state file under the prefix taken from the state file’s name, whatever the current directory or the environment. So a resumed run keeps appending to the same history: the log is appended to across resumes, each invocation adding its own # run header. Both paths are printed to stderr at the start unless -q. With the default prefix and seed 42:

real run--dry-run
logfilegen-42.logfilegen-42.dry.log
statefilegen-42.state.yamlfilegen-42.dry.state.yaml

filegen refuses to start (exit 2) when:

  • the output directory is, or lies inside, <PATH> (after resolving symlinks);
  • a --seed run finds either output file already present; the message names the ways out: --resume to continue that history, --prefix to start a separate one, --force to truncate both. With --force the files are truncated only after the initial walk of the tree succeeded;
  • a dry-run state file is resumed without --dry-run, or a real one with it;
  • the state file’s format_version is not 3 (a version 1 file comes from an older content generator, whose bytes the same seed no longer reproduces; a version 2 file from rand 0.8, whose sampling made different choices from the same seed);
  • the canonical root length plus max_path_len reaches PATH_MAX.

Log

One line per step, key=value pairs in a fixed order:

step=<n> ts=<RFC 3339, µs, UTC> op=<kind> path="<rel>" [to="<rel>"] [dry=1] [bytes=<n>] [<detail>=<v> ...] [post=<stat>] [post_to=<stat>] [pressure=<0.xx>] dur_us=<n> [gen_us=<n>]

step counts across resumes. Paths are relative to the root, quoted and escaped (\", \\, and \xhh for control bytes and invalid UTF-8) so any name round-trips. bytes is the data written, when non-zero. Details include size, content (random, zeros, repeat_byte, repeat_block), offset/len, mode, mtime/class, target, target_kind, absolute, entries and emulated=1 (a hole written as zeros). pressure appears while the total-size reweighting is in effect. post is the stat of path right after the step, as kind:size:mode_octal:mtime_ns: f file, d directory, l symlink, p fifo, c or b device (and s for a socket); the size in bytes, the mode bits in octal, the modification time in nanoseconds since the epoch. It is - when the path is absent after the step (a delete or a rename away). post_to is the same for to, and appears only for steps that have a to. Neither appears in a dry run, which touches nothing. The stress harness reads them to rebuild what the source held. dur_us times the filesystem syscalls only (including fsync if enabled), not the choice of operation. An operation that writes drawn content (create_file, append, overwrite_range, rewrite) generates the bytes in 1 MiB chunks between its writes; that time is taken out of dur_us and reported as gen_us, so dur_us measures the filesystem whatever the generator costs. A failed step is logged as step=<n> ts=... op=<kind> path="<rel>" [to="<rel>"] error="<os error>", naming the path the failing call acted on (for a create, the new entry; to for a rename or hard link).

From a real run (paths shortened; post is f:44002:664:..., a 44002-byte file with mode 0664 whose mtime is 2026-10-20T14:24:51.571Z):

# run seed=42 start_step=0 steps=1000 log="/tmp/fg/filegen-42.log" state="/tmp/fg/filegen-42.state.yaml" config="-" dry_run=0 started=2026-10-20T14:24:51.569059Z
step=6 ts=2026-10-20T14:24:51.571654Z op=append path="2yg5uow38.jpg/f4rx i3iipl66u7pmc1e.bin" bytes=30165 size=44002 content=random post=f:44002:664:1792506291571000000 dur_us=1208 gen_us=12
...
# end steps_done=1000 outcome=ok elapsed_ms=7638
# stat op=create_file count=219 bytes=117340131 p50_us=109 p99_us=156217 max_us=156975 gen_total_us=48112
# stat op=append count=183 bytes=74836731 p50_us=27 p99_us=156299 max_us=156307 gen_total_us=30577

The # end line is followed by one # stat line per kind seen in this invocation; the percentiles are over dur_us, and kinds that write drawn content add gen_total_us, the sum of their gen_us. outcome is ok, "failed: <message>" or "interrupted: SIGINT" / "interrupted: SIGTERM". A dry run marks each step line dry=1 and logs dur_us=0 (and gen_us=0 where the kind reports it).

A step whose drawn kinds all lack a target, and where even the fallback, create_file in the root, finds no name that fits (for example with a tiny max_path_len), does nothing: it logs no step line and does not advance steps_done, but counts toward --steps. The # end line then ends in skipped=<n>, the outcome stays ok, and unless -q one warning on stderr says how many steps were skipped.

State file

A YAML document, written to a temporary file and renamed into place:

  • format_version: 3
  • seed: the seed the history started from
  • steps_done: steps completed over all runs of this history
  • rng: the ChaCha8 chain generator state (seed, stream, word_pos); file bytes come from Xoshiro256++ seeded by a draw from it, so they need no state of their own
  • chain_state: last_kind (the previous operation) and anchor (the escaped relative path of the directory it touched; '' is the root)
  • dry_run: whether a dry run wrote it
  • config: the effective configuration, fully expanded, with out_dir the absolute output directory used; usable as --config
  • tree: entries and total_bytes as filegen last knew them (advisory)
  • last_run: started, finished, steps (this invocation), outcome (as in the log, or running for a checkpoint), and summary, the per-kind statistics of the # stat lines

Resume, interrupts and checkpoints

On --resume filegen does not trust the state file’s picture of the tree: it walks the tree afresh and rebuilds its model, then continues from the saved generator state. If the tree is as the previous run left it, the result is identical to an uninterrupted run (same tree, same step lines). If the tree was altered in between, the run continues deterministically from the altered tree, reproducible but no longer identical; compare tree in the state file with the tree to notice.

SIGINT and SIGTERM let the step in flight finish, then write the log footer and the state file and exit 130 or 143; the state is resumable. A second SIGINT during that shutdown exits 130 at once without writing. Signals are handled from the end of the initial walk on.

Every checkpoint_steps steps (default 1000) the state file is rewritten with outcome running and the log is flushed, so a kill no handler can catch loses at most that many steps of generator position. The tree, and possibly the log, are then ahead of the checkpoint: a resume starts again at the checkpoint’s step (its # run line shows start_step), so the log can hold a few step numbers twice, and the tree is in the “altered” case above.

Exit codes

  • 0: all steps done
  • 1: an operation failed (the failure line, footer and state are written, with the generator rewound to before that step), or another I/O error
  • 2: usage, configuration or state-file error, or a refusal above; a --resume state file that is missing, unreadable or invalid is reported as state file <path>: <error>
  • 130 / 143: interrupted by SIGINT / SIGTERM (128 + signal number)

Safety

filegen never writes outside the root: every target comes from its model of the tree, and the output directory may not lie inside it. Some entries are off limits: never targets, never descended into, and a directory holding one is never removed or renamed. They are entries named .fileset* at any depth, entries on another filesystem (mount points), sockets and other unknown file types, and entries the start-up walk cannot stat. Unless filegen runs as root, they are also:

  • any directory it cannot list;
  • any entry not owned by its effective uid;
  • any regular file without owner read and write (mode & 0o600 != 0o600, such as the 0444 files of a git checkout);
  • any directory without owner read, write and search (mode & 0o700 != 0o700).

As root these four do not apply, and a directory that cannot be listed (because it vanished during the walk) is kept as an empty directory. filegen’s own chmod always keeps owner read and write (and search on directories), so, with a umask that keeps the owner’s bits (any usual one), nothing filegen creates ever becomes off limits. Absolute symlink targets may point outside the root, but filegen only creates the link.

Configuration

The state file always carries the effective configuration with every default filled in, so the way to see the schema is a one-step dry run (for example filegen run --seed 1 --steps 1 --dry-run --out-dir /tmp/x <DIR>) and the config: block of /tmp/x/filegen-1.dry.state.yaml. The defaults from such a run, with comments added, nested values in YAML flow style, and out_dir put back to its default null (a state file records the directory used); it loads as --config and yields the default configuration:

out_dir: null
prefix: null
max_total_size: 25G
max_file_size: 256M
max_depth: 32
max_path_len: 900
remove_tree_max_entries: 1000
fsync: false
checkpoint_steps: 1000
# A new file is empty with weight `empty`, else log-uniform within a band:
# small from 1 byte, medium from small.max, large from medium.max to max_file_size.
size_distribution:
  empty: 0.05
  small: {weight: 0.65, max: 64K}
  medium: {weight: 0.25, max: 8M}
  large_weight: 0.05
# This fraction of writes uses one of `patterns` instead of random bytes.
content:
  pattern_fraction: 0.05
  patterns: [zeros, repeat_byte, repeat_block]
  block_size: 4K
# Relative weights of the name styles. Names are unique per directory under
# case folding and NFC normalisation, on every platform.
names:
  classes: {plain: 70.0, spaces: 8.0, dotfile: 5.0, unicode: 8.0, long: 3.0, awkward: 6.0}
  extensions: [txt, bin, jpg, log, dat, md, json, '']
  max_len: 255
# file/dir/dangling weight the target kind; absolute is a probability.
symlink: {file: 0.5, dir: 0.2, dangling: 0.3, absolute: 0.2}
# Modes are quoted octal strings. special_weight is the chance of adding one
# of suid, sgid, sticky. Owner rw (rwx on directories) is always kept.
chmod:
  modes: ['0644', '0600', '0755', '0700', '0664', '0775', '0444', '0555']
  special_weight: 0.05
# Class weights. Times are drawn relative to 2026-10-20T00:00Z, not the clock.
mtime: {recent: 0.6, distant: 0.3, future: 0.1, distant_years: 40, future_years: 5}
# Where a target is drawn from: below the directory the previous step
# touched, below its parent, or anywhere.
locality: {same_dir: 0.6, parent: 0.2, anywhere: 0.2}
# Previous kind -> next kind. A kind that is 0 in every row never occurs.
weights:
  create_file: {create_file: 15, append: 30, truncate: 3, overwrite_range: 20, rewrite: 3, punch_hole: 0.7, delete_file: 2, mkdir: 3, rmdir: 1, remove_tree: 0.5, rename: 3, rename_over: 1, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 1, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  append: {create_file: 25, append: 20, truncate: 4, overwrite_range: 15, rewrite: 3, punch_hole: 1, delete_file: 4, mkdir: 5, rmdir: 3, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 1, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  truncate: {create_file: 20, append: 20, truncate: 2, overwrite_range: 15, rewrite: 5, punch_hole: 1, delete_file: 4, mkdir: 4, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 1, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  overwrite_range: {create_file: 20, append: 20, truncate: 4, overwrite_range: 15, rewrite: 3, punch_hole: 1, delete_file: 4, mkdir: 4, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 1, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  rewrite: {create_file: 20, append: 18, truncate: 4, overwrite_range: 15, rewrite: 3, punch_hole: 1, delete_file: 4, mkdir: 4, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 1, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  punch_hole: {create_file: 20, append: 18, truncate: 4, overwrite_range: 15, rewrite: 3, punch_hole: 1, delete_file: 4, mkdir: 4, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 1, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  delete_file: {create_file: 25, append: 12, truncate: 2, overwrite_range: 10, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 6, rmdir: 3, remove_tree: 2, rename: 4, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  mkdir: {create_file: 45, append: 2, truncate: 1, overwrite_range: 2, rewrite: 1, punch_hole: 0.5, delete_file: 1, mkdir: 20, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 1, symlink: 3, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.5, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  rmdir: {create_file: 20, append: 8, truncate: 2, overwrite_range: 6, rewrite: 2, punch_hole: 0.5, delete_file: 4, mkdir: 12, rmdir: 4, remove_tree: 3, rename: 4, rename_over: 2, symlink: 3, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.5, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  remove_tree: {create_file: 20, append: 8, truncate: 2, overwrite_range: 6, rewrite: 2, punch_hole: 0.5, delete_file: 4, mkdir: 12, rmdir: 3, remove_tree: 3, rename: 4, rename_over: 2, symlink: 3, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.5, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  rename: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  rename_over: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  symlink: {create_file: 15, append: 10, truncate: 2, overwrite_range: 8, rewrite: 2, punch_hole: 0.5, delete_file: 3, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 6, repoint_symlink: 5, delete_symlink: 4, hardlink: 0.5, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  repoint_symlink: {create_file: 15, append: 10, truncate: 2, overwrite_range: 8, rewrite: 2, punch_hole: 0.5, delete_file: 3, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 6, repoint_symlink: 5, delete_symlink: 4, hardlink: 0.5, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  delete_symlink: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  hardlink: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  mkfifo: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  chmod: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  set_mtime: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  set_xattr: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  chown: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
  mknod: {create_file: 20, append: 15, truncate: 4, overwrite_range: 12, rewrite: 3, punch_hole: 0.7, delete_file: 6, mkdir: 5, rmdir: 2, remove_tree: 1, rename: 3, rename_over: 2, symlink: 2, repoint_symlink: 1, delete_symlink: 1, hardlink: 0.7, mkfifo: 0.5, chmod: 3, set_mtime: 3, set_xattr: 0, chown: 0, mknod: 0}
xattr:
  names: [user.filegen.a, user.filegen.b, user.filegen.c, user.filegen.d]
  max_value: '256'
chown: {uids: [], gids: []}
mknod: {char_fraction: 0.5}

set_xattr, chown (which also needs ids in chown.uids or chown.gids, and the privilege to give files away) and mknod (skipped unless root) are off by default through zero columns in weights. Above 80% of max_total_size a pressure rises linearly from 0 to 1 at the cap, damping the kinds that grow the tree and boosting those that shrink it; the log shows it as pressure=.

How filegen works

Part of Testing: how the filegen tool chooses what to do.

This page explains how filegen decides what to do to a tree: the chain that picks the next operation, how it picks a target, how big things are and what they are called, and how a run is reproduced and resumed. It also says where to change filegen when it needs to do more. For how to run it and every option, see Generating test trees with filegen.

Why a Markov chain

Real use of a filesystem comes in patterns. A file is created and then appended to. A directory is made and then filled. A file is written and then renamed. Sync bugs tend to hide in exactly these situations.

Independent random operations rarely build them. A chain does. In a Markov chain, the next operation depends on the one before it. So filegen can make “create, then append” likely, and still be exactly repeatable from a seed.

How it works

The table

Every operation is an OpKind (in crates/filegen/src/kind.rs). There are 22 of them. The chain (crates/filegen/src/chain.rs) is a 22 by 22 table of weights. Each row is the previous kind. Each column is the next kind. To pick the next operation, filegen takes the row of the operation it just did and draws a column, with probability in proportion to the weights.

The first step starts from mkdir, so a fresh run opens as if a directory had just been made.

The defaults are in DEFAULT_TABLE in crates/filegen/src/config.rs. The full block is in the Configuration section of the filegen page, and is not repeated here.

Switching a kind off

A kind is off when its column is 0 in every row. It can then never be drawn. set_xattr, chown and mknod are off by default this way, because they need privileges or filesystem support. Turning one on means giving its column a weight, as in Tuning without code.

A row may not be all zeros, and no weight may be negative. filegen refuses to start with such a table.

Locality

Real use also stays in one place. filegen remembers the directory the last operation touched, called the anchor. The next target is chosen near it (crates/filegen/src/pick.rs):

  • with probability locality.same_dir (0.6), from below the anchor,
  • with probability locality.parent (0.2), from below its parent,
  • otherwise (0.2, locality.anywhere), from anywhere in the tree.

If the chosen scope holds nothing suitable, the search widens. If no target exists at all for the drawn kind (a rmdir in a tree with no directories, say), filegen draws another kind, up to 16 times. After that it creates a file in the root. Only if even that fails is the step skipped.

Size pressure

filegen keeps the tree under max_total_size. Below 80% of that cap nothing changes. Above it, a pressure rises in a straight line from 0 to 1 at the cap. As it rises, the kinds that grow the tree get less likely and the kinds that shrink it get more likely. Which kinds those are is set by grows and shrinks in kind.rs. At full pressure, growing kinds are never drawn. The log shows the pressure on each step as pressure=.

Sizes, names and content

  • Sizes (sizes.rs). A new file is empty, or falls in a small, medium or large band, chosen by weight. Inside the band the size is log-uniform, so small files are common and big ones rare. Appends, overwritten ranges and truncations use the same idea.
  • Names (names.rs). Each name has a style: plain, with spaces, a dotfile, unicode, long, or awkward. Names are unique in their directory even when case is ignored and unicode is normalised, so the tree is safe on any platform.
  • Content (content.rs). Most bytes are random. A fraction (content.pattern_fraction) uses a pattern instead: zeros, one repeated byte, or a repeated block.

The seed

All choices come from a generator seeded by --seed. The bytes of file content come from a second generator, seeded by one draw from the first. The functions that draw sizes and names take the same number of draws whatever they return. So two runs that differ only in what the caps allow stay in step.

Resume

The state file records the generator, the last kind and the anchor (crates/filegen/src/state.rs). On --resume, filegen does not trust its picture of the tree. It walks the tree again to rebuild its model (model.rs, walk.rs), then carries on from the saved generator. If the tree is as the last run left it, the result is the same as a run that never stopped. If someone changed the tree in between, the run goes on from the changed tree. It is still repeatable, but no longer identical.

Tuning without code

Most changes need no code. Use --config with a YAML file, or --set with a dotted key, as described on the filegen page.

One weight is one cell of the table: previous kind, then next kind. This makes a hard link much more likely right after a create_file. It is a valid one-step check:

filegen run --seed 1 --steps 1 --dry-run --out-dir ~/fg \
    --set weights.create_file.hardlink=10 ~/src-tree

irsync-stress and irsync-netstress pass the same keys through with --filegen-set. To raise a whole column you need one cell per row, so crates/stress/tools/matrix.sh has a small shell function, col, that writes them all. col hardlink 10 expands to --filegen-set weights.create_file.hardlink=10, and the same for the other 21 rows. Each campaign row there is a few of these.

Extending filegen

filegen can be changed. Two kinds of change are expected:

  • to cover a new critical user journey: a sequence of filesystem operations that matters to real users,
  • to cover a feature that only some filesystems have.

Where the change goes depends on its kind.

A new sequence of existing operations. Often no code is needed. The sequence is a pattern in the table: raise the weight from one kind to the next. If it must be the default, edit DEFAULT_TABLE in config.rs. A test in chain.rs checks the shape of the default table, so keep it passing.

A new operation. Add it in these places:

  1. A variant in OpKind in kind.rs. Update ALL, name, and the array sizes that say 22. Decide if it grows, shrinks, and whether it is default_enabled.
  2. A row and a column in DEFAULT_TABLE in config.rs. A kind that is off by default has a zero column.
  3. Its config keys, if it has any, as a new struct in config.rs, next to ChmodConfig or XattrConfig.
  4. The operation itself, a function in a file under crates/filegen/src/ops/ (file.rs, tree.rs, link.rs or meta.rs), and a line for it in dispatch in ops/mod.rs. It picks a target with the functions in pick.rs, changes the disk, and returns an Applied that says what happened, so the log and the model stay right. It must not touch the disk in a dry run, but it must make the same random draws and the same model updates as a real run (see the top of ops/mod.rs).
  5. The model. If the operation creates something the model has no node kind for, add one to NodeKind in model.rs, and teach walk.rs to see it.

A filesystem-specific feature. Make it a new OpKind, off by default. Such an operation should return NoTarget when it has nothing to do, as set_xattr does when xattr.names is empty and mknod does unless run as root. Filegen then draws another kind.

The effect must be observable

A new effect only helps if fileset check can see it. Otherwise the stress loop cannot tell whether the sync carried it.

By default, fileset check compares type, content, symlink target, device numbers, mode, mtime and size. Link count, owner, group and extended attributes are compared only with --paranoid or --require. Holes in sparse files are not recorded at all.

So before adding an operation, ask what in that list it changes. If it changes something fileset does not compare by default, either fileset needs a matching change, or the stress run must ask for the stronger check. If fileset cannot see it at all, the operation will run but prove nothing.

Stress testing

Part of Testing: the loopback stress loop.

irsync-stress runs the loop that filegen, fileset and irsync were built for. It starts an irsync daemon on loopback, fills a source tree with filegen, records it with fileset init, then repeats: sync with the irsync client, compare the two manifests, run fileset check on the destination, mutate the source with filegen and update its manifest. An iteration where the sync, the manifest comparison or the check fails is reported and, unless --keep-going is given, ends the run. It touches no network beyond loopback; irsync-netstress runs the same loop over a simulated bad network.

The design is in 2026-10-21-stress-harness-design.md, the calls made while building it and the bugs it found in IRSYNC_HARNESS_DECISIONS.md. Hunting bugs is the strategy for making it find more.

Run the loop

Build the workspace, so that irsync, filegen and fileset sit next to irsync-stress:

cargo build --release --workspace

Then run it with a root directory that does not exist yet, or is empty:

target/release/irsync-stress --direction push --iterations 20 /tmp/stress-push
target/release/irsync-stress --direction pull --seed 7 --keep-going /tmp/stress-pull -- --parallel 4
target/release/irsync-stress --direction push --max-total-size 8M --max-file-size 1M /tmp/small

The root is never deleted, on success or failure. A run without --seed draws one and prints it in the header; run.toml in the root records it with every other setting.

After a failure

Look at, in this order:

  1. ROOT/run.toml: seed, direction, sizes, extra client arguments, tool versions, and the daemon’s EndpointId, address and pid. It is enough to repeat the run.
  2. The two manifests. SRC/data/.fileset.sqlite is what the destination should have matched; DST/data/.fileset.sqlite is what was checked. Inspect them with fileset, or compare logs/iter-NNNN.manifest.blake3.
  3. logs/iter-NNNN.check.txt: what fileset check found (ADD, DEL, CHG lines and a summary).
  4. logs/iter-NNNN.client.log: the client’s output for that iteration. In logs/daemon.log the line === iteration N === marks where that iteration starts, so the daemon’s side of the same sync can be read.

The daemon and client logs contain ANSI colour codes from irsync’s tracing output. Read them with less -R, or strip them with sed 's/\x1b\[[0-9;]*m//g' before searching.

From a failed iteration to a bug report continues from here.

Campaign tools

crates/stress/tools/breadth.sh runs a breadth sweep: many seeds, short runs, both directions, several runs at a time. It deletes the root of every passing run and keeps the root of every failing one. Its environment variables, with their defaults:

VariableMeaningDefault
BINDirectory with irsync-stress, irsync, filegen and fileset.target/release
OUTWhere roots, per-run output and summary.txt go.~/work/irsync-breadth
SEEDSSeeds to run, as arguments to seq.1 50
JOBSRuns at the same time.8
ITER, STEPS, TOTAL, FILEIterations, filegen steps, --max-total-size and --max-file-size of each run.20, 200, 4G, 256M
CLIENTArguments for the irsync client, after --.--timeout 300
CHECKA command run as $CHECK <root> after each passing run; if it fails, the run counts as failed (exit=3) and its root is kept.none
DURATIONA time budget in seconds. Once it has passed, no new run starts, and the runs not started get no line in summary.txt. Runs already going finish.none

Extra arguments go to every irsync-stress run, before the root. Each run needs up to twice TOTAL on disk while it runs.

crates/stress/tools/matrix.sh runs the campaign matrix, one breadth sweep per row. The rows are hardlink, rename, rename-off, sparse, metadata, timestamps, symlinks, deletion, listing, longnames, parallel1, parallel512, checksum, minimal, bigfile, paranoid, concurrent, concurrent-paranoid, net-concurrent and net-concurrent-paranoid. The last four write to the source during the sync and take an hour each; see Writing during the sync. The two net-* rows run netstress/tools/sweep.sh and need the fault build (NETBIN names its directory). matrix.sh hardlink rename runs only those rows; with DRY=1 it only checks that filegen accepts every row’s settings. Each passing run is checked with tools/clean-check.sh, which runs tools/paranoid-check.sh (a fileset check --paranoid of the final destination against the source manifest, link counts included) and then asserts that no .irsync.*.part is left in either tree. The rows before concurrent take about three hours on a 16-core Mac; each of the four concurrent rows is capped at one hour by DURATION. The paranoid row passes --paranoid. The harness changes the source only between syncs, so this row checks that the --paranoid code paths sync a quiet tree correctly; it does not test catching a file that changes during the sync. Binaries built by cargo test --workspace have the test-hooks feature, and there --paranoid never clones, so the row tests the second-hash path; cargo build --release binaries clone where the filesystem can.

Reference

Command

irsync-stress [OPTIONS] --direction <DIRECTION> <ROOT> [-- <CLIENT_ARGS>...]

<ROOT> is created if missing; it must be empty if it exists.

OptionMeaningDefault
--direction <push|pull>Which way the client moves data (required). On a push the source tree is ROOT/SRC/data and the daemon serves ROOT/DST/data; on a pull the roles are swapped.required
--iterations <N>Sync-and-verify rounds.10
--seed <S>Seed for filegen, printed in the header.random
--steps <N>filegen operations per fill or mutation.100
--max-total-size <SIZE>, --max-file-size <SIZE>Passed to filegen verbatim. filegen refuses a per-file limit above the total, so a small --max-total-size needs a --max-file-size as well.filegen’s: 25G, 256M
--filegen-set <KEY=VALUE>An extra --set for every filegen run; repeatable. Example: --filegen-set names.max_len=200.none
--log-level <LEVEL>Log level for the daemon and the client.debug
--keep-goingCarry on after a failed iteration instead of stopping.off
--irsync <PATH>, --filegen <PATH>, --fileset <PATH>Use this binary instead of looking one up.lookup
-- <ARGS>...Appended to every irsync client command line.none

The tools are looked up next to the irsync-stress binary first, then on PATH. run.toml records the path and --version output of each.

The client runs with -a -H --delete --reconnect 0, --address set to the daemon’s loopback address, and its own --identity and an empty --config, then the arguments after --. The harness sets no inactivity timeout, so a hung sync hangs the run; -- --timeout N makes such a client fail instead, and the harness then exits 2.

Output

A header, one line per iteration, a footer:

irsync-stress
  root:      /path/to/run
  seed:      3
  direction: push
  endpoint:  716a53cc4cea6705494da4d3b72cae40cfa658440e2e1fe4afba1f1bfbc2a5bb
  address:   127.0.0.1:50357
iter 0001/0003  sync 0.2s  exit 0    manifest ok  check ok
iter 0002/0003  sync 0.3s  exit 0    manifest ok  check ok
iter 0003/0003  sync 0.2s  exit 0    manifest ok  check ok
passed=3 failed=0 elapsed=1.1s

A failed iteration looks like this, followed by the path of its check report:

iter 0002/0015  sync 1.3s  exit 23   manifest ok  check FAILED (added=0 deleted=1 changed=0)

Layout

ROOT/
  run.toml                    parameters of the run, enough to repeat it
  SRC/
    config/                   irsync.toml
    data/                     the tree filegen mutates; its manifest is data/.fileset.sqlite
  DST/
    config/                   the other side's config files
    data/                     where the tree arrives; checked here
  filegen/                    filegen's log and state file (outside both trees)
  logs/
    daemon.log                daemon output for the whole run, with iteration markers
    ping.client.log           client log of the sentinel round
    filegen.stderr.log        filegen's stderr, appended by every filegen run
    iter-0001.client.log      client log per iteration
    iter-0001.check.txt       fileset check output per iteration
    iter-0001.manifest.blake3 hashes of both manifests per iteration

Exit codes

CodeMeaning
0Every iteration passed.
1At least one iteration failed: client exit 23, manifests differ, or fileset check found differences.
2The harness could not do its job: bad arguments, a root that is not empty, a missing tool, a daemon that did not start, a tool failing, or the client exiting with anything other than 0 or 23.
130Interrupted by SIGINT or SIGTERM. The client, filegen or fileset run in progress, and the daemon, are sent SIGINT first.

With --concurrent the rules and exit codes differ; see Writing during the sync.

A client exit of 23 (partial transfer) is a failed iteration, not a harness error; the manifest comparison and the check still run for it. Any other client exit, such as 25 from --max-delete, is a harness error.

Bugs the harness has found

Each is fixed, with a regression test in the irsync crate. IRSYNC_HARNESS_DECISIONS.md has the full record of each.

BugFound byRegression tests
A file name longer than about 242 bytes could not be transferred: its staging name .irsync.<name>.part exceeded NAME_MAX.a default runtests/posix_extras.rs name_max_entries_transfer, tests/gc.rs gc_handles_shortened_part_names, the temp_names tests in tests/recv.rs
A FIFO whose only change was its modification time was never updated.the acceptance runtests/posix_extras.rs fifo_mtime_is_applied_and_updated, tests/plan.rs special_metadata_only_difference_is_meta_only
One side’s long local work, such as the daemon hashing with -c, was invisible to the other side’s inactivity watchdog.the bigfile matrix rowtests/resume.rs peer_local_progress_resets_idle_watchdog
Metadata applied to a destination file with several links reached the names the source had unlinked.the hardlink matrix rowtests/posix_extras.rs link_broken_at_source_with_equal_content_is_broken_at_destination, mode_change_does_not_reach_a_destination_link_outside_the_tree
A file whose mode, owner or group changed between the listing and the hash was placed with the listing’s.--concurrenttests/change_detection.rs *_before_hash_places_the_new_*, tests/ids_e2e.rs chunk_list_ids_are_mapped_by_name_unless_numeric_ids
With -H, a name replaced or renamed away after the listing was still linked to the copy of the file it used to name.--concurrenttests/change_detection.rs replaced_link_is_sent_as_its_own_file*, link_renamed_away_is_not_linked*, tests/posix_extras.rs links_to_files_placed_before_a_drop_are_checked

Tests

cargo test -p stress runs unit tests and an end-to-end test that starts a real daemon and the real tools. That test needs the other binaries, which cargo test -p stress alone does not build: run cargo build --workspace first, or use cargo test --workspace.

Hunting bugs

Part of Testing: campaigns, the slowest layer.

A strategy for turning irsync-stress from a loop that passes into a loop that finds bugs. It builds on what the harness has found so far (IRSYNC_HARNESS_DECISIONS.md), on the knobs that filegen, fileset and the irsync client expose, and on irsync’s list of open points (section 2 of IRSYNC_DECISIONS.md), which is a map of where the ice is thin.

Network faults (loss, delay, dead zones that force a reconnect and resume) are covered by a separate rig, irsync-netstress.

The commands assume a release build in target/release and roots on a filesystem with room for twice the size cap.

What the loop can and cannot see

Every bug the harness finds has to pass three filters. Knowing them tells you where to push.

  1. filegen must provoke it. Only operations with a non-zero weight happen. set_xattr, chown and mknod are off by default; mkfifo and punch_hole are rare (weights 0.5 and up to 1 in rows that sum to about 100). A bug in hard-link handling needs hard links in the tree, and at the default weight of about 1% a default 10-iteration run makes about 10 of them.
  2. fileset check must observe it. The harness runs the default tier: type, content, symlink target, device numbers, mode, mtime, size. It does not compare nlink, uid, gid or xattr, so a hard-link group that arrives as independent copies with the right bytes passes. Disk allocation (sparseness) is not recorded at all. Nothing checks the destination’s .part leftovers, index rows or session files.
  3. A known bug must not drown it. Some bugs compound: once their trigger exists in the source, every later iteration fails for the same reason, and anything else has to be found by hand underneath them. In the harness’s acceptance run all 1083 failed iterations came from two such bugs. Fix or neutralise a compounding bug before investing in campaigns: a harness whose default run fails most iterations on a known cause gives no signal on anything new.

A compounding bug is neutralised with --filegen-set, by keeping filegen from making its trigger. Long names off: --filegen-set names.max_len=200. An operation off: its column must be zero in every row of filegen’s transition matrix:

FG=()
for k in create_file append truncate overwrite_range rewrite punch_hole delete_file \
         mkdir rmdir remove_tree rename rename_over symlink repoint_symlink \
         delete_symlink hardlink mkfifo chmod set_mtime set_xattr chown mknod; do
  FG+=(--filegen-set "weights.$k.mkfifo=0")
done
irsync-stress --direction push "${FG[@]}" ROOT

The same loop with another weight biases an operation instead of switching it off; matrix.sh does this with its col function.

The harness never deletes a root, and both manifests survive, so the observation filter can be widened after a run at no cost:

fileset check -q --paranoid --manifest ROOT/SRC/data/.fileset.sqlite ROOT/DST/data
fileset check -q --relaxed --require nlink --manifest ROOT/SRC/data/.fileset.sqlite ROOT/DST/data
du -s ROOT/SRC/data ROOT/DST/data          # allocated blocks: sparse preservation

Do this on every finished run; crates/stress/tools/paranoid-check.sh ROOT runs the first. A destination that uses fewer blocks than the source is irsync skipping all-zero chunks (R3), not a fault; a destination that uses more blocks with -S passed would be one.

Breadth before depth: many seeds, short runs

Because failures compound, a 300-iteration run mostly re-reports its first bug. Many short runs find more distinct bugs per machine-hour:

crates/stress/tools/breadth.sh                       # seeds 1 to 50, both directions, 8 at a time
grep -v 'exit=0' ~/work/irsync-breadth/summary.txt   # runs with a failure or error

The script takes BIN, OUT, SEEDS, JOBS, the run size and the client arguments from the environment, passes extra arguments to irsync-stress, deletes the root of every passing run and keeps the root of every failing one (Campaign tools lists the variables). At the defaults, a run took about 160 s on a 32-core machine, and the eight live roots used 23 to 26 GB of disk.

It runs every seed in both directions. The same seed produces the same source tree in both, so a seed that fails on push and passes on pull puts the bug in the daemon-side receiver, and the reverse puts it in the client receiver. That is the cheapest localisation the harness offers.

Then go deep on a few seeds: 300 to 1000 iterations with --keep-going, looking for bugs that need accumulation: index growth, session and GC state, .part files left behind, and the daemon’s memory over time (ps it hourly).

The campaign matrix

Each row aims the harness at a part of irsync that the default run barely touches. Run each as a breadth sweep, in both directions. crates/stress/tools/matrix.sh runs the rows it names in the last column (Campaign tools). --filegen-set takes dotted YAML paths; weights are per transition row, so biasing an operation means setting its column in every row, as above.

Target in irsyncHow to aim the harnessWhat a failure looks likematrix.sh row
Hard-link final pass (R23); stale target content when the target failed at planning time; link groups across directorieshardlink weight 10 in every row, rename and rename_over 8; post-run --require nlinknlink= differences in paranoid, or a short-named member with old content for one iterationhardlink
Rename detection and content reuserename 15, rename_over 10, overwrite_range 5; run the same seed with and without -- --no-rename-detectionA failure only with detection on is a reuse bug; only with it off, a plain transfer bugrename, rename-off
Resume and chunk adoption of .part files-- --timeout 5 with max_file_size 2G and --bwlimit 20m, so transfers outlive the timeout; or kill the client mid-sync and re-run the same invocationClient fails (harness exit 2), or content differs after the adopted chunksnone
Sparse files (R3, -S)punch_hole 10, content.pattern_fraction=0.5 (zero blocks), -- -S; compare du -s of both treesDestination allocates more than the source, or holes become datasparse
Metadata: special mode bits, read-only files, the u+w restore pathchmod.special_weight=0.5, chmod weight 10; modes 0444 and 0555 are already in the listmode= lines; a .part stranded read-only in the destination (find DST -name '.irsync.*.part')metadata
Timestamps: future, pre-epoch, sub-secondmtime: {future: 0.5, future_years: 50} and distant_years: 70 (1956, before the epoch)mtime= lines on regular files or directoriestimestamps
Directory mtime after children changeThe default mix; mtime is in the default tier. Look for CHG <dir> mtime=Directories whose mtime a child write reset after metadata was appliednone
Symlinks: dangling, absolute, pointing at directories, repointedsymlink: {dangling: 0.5, absolute: 0.5}, repoint_symlink 10target= lines; a symlink followed instead of recreated (a file where a link should be)symlinks
Deletion passes and --max-deleteremove_tree 5 with remove_tree_max_entries=5000; -- --delete-before; separately -- --max-delete 50With --delete-before, watch daemon memory. Client exit 25 is a harness error (exit 2), so --max-delete needs a harness change firstdeletion (--delete-before only)
Listing size, ordering, out-of-order drops (R7)--steps 5000, size_distribution.small.weight=0.95, max_depth=64, names.classes.unicode=30, names.classes.awkward=30ADD/DEL pairs on names that sort differently under byte order and NFClisting
Long names and pathsnames.classes.long=30, max_depth=64; further names.max_len=255, max_path_len=3900File name too long or ENAMETOOLONG, on index paths rather than file nameslongnames
Concurrency and backpressure (R31)-- --parallel 1 (serialises; finds ordering bugs) and -- --parallel 512 with 5000-step iterations of small filesDaemon memory growth across iterations; a hang that --timeout turns into exit 2parallel1, parallel512
Inactivity watchdog against long local work (R35)Large files (max_file_size=8G, size_distribution.large_weight=1), -- -c --timeout 10, so the receiver hashes before answeringA spurious reconnect, visible as a failed client with --reconnect 0bigfile
Quick check against checksumRun the same seed with and without -- -c; a difference means the size-and-mtime shortcut skipped a changed filePass with -c, fail withoutchecksum
The --paranoid code paths (clones, second hash, final re-check) on a source that nothing writes to during the sync; the harness changes the tree only between syncs, so this does not test catching a change-- --paranoid with the default mix; run on a release build to test clones, on a test-hooks build to test the second hashA failure the same seed does not show without --paranoid; a .irsync-clones-* folder left in the source treeparanoid
Source files that change during the sync: the change checks (stat after hashing, the ask before placing, --paranoid’s clone, second hash and final re-check)--concurrent: filegen writes to the source while irsync syncs it, and every destination path is judged against the states the source held (see below); push and pull, with and without -- --paranoidA path named with the rule it broke: no state the source held, or content and times disagreeconcurrent, concurrent-paranoid
The same, over a bad networkirsync-netstress --concurrent through crates/netstress/tools/sweep.sh, on the fault buildAs above; also exit 3 when the faults never bitnet-concurrent, net-concurrent-paranoid
Minimal deltas--steps 1 --iterations 500Each failing iteration names exactly one filegen operation in filegen/filegen-<seed>.logminimal
Idle syncs--steps 0 runs, but also empties the fill, so the tree is empty; a populated idle sync needs a separate fill step count (a harness change)A sync of an unchanged tree that transfers anything (check -- --stats) is an index bugnone
xattrsset_xattr weight 5, post-run --require xattrExpected to fail: irsync has no -X. Run only to document the gapnone

Two differential patterns recur in the table and are worth stating on their own: same seed, one flag flipped (-c, --no-rename-detection, --no-resume, -S, --delete-before, --parallel 1) and same seed, other direction. A bug that appears on exactly one side of such a pair is half diagnosed before anyone reads a log.

Writing during the sync (--concurrent)

The loop above changes the source and syncs it one after the other. --concurrent, on irsync-stress and on irsync-netstress, makes filegen write to the source while irsync syncs it. The goal: no destination file is ever a state the source never held. On a pull, filegen writes to the server’s tree while the daemon sends it.

What a round does

  1. Pick a pace for filegen from the seed: fast (never pauses), steady:N (N steps a second) or bursts:ON:OFF (milliseconds of writing, then of quiet). --pace fixes it for the whole run.
  2. Copy the source tree (a reflink copy where the filesystem can).
  3. Start filegen in the background, then start the sync.
  4. When irsync exits, stop filegen between two steps.
  5. Rebuild the source’s history from the copy and filegen’s log (its post= and post_to= fields give the stat after each step), and judge every destination path against it.
  6. Run one more sync with nothing writing. It must exit 0 and leave an exact copy.

The seed fixes the random choices. How many steps filegen gets through before irsync exits depends on timing, so each round’s pace and step count go to logs/rounds.tsv. The race itself cannot be replayed: a rerun may not fail again. The kept files are the evidence.

The rules

A destination path passes when it is a state the source really held:

  • its state at the start of the round, or after any complete filegen step;
  • a state in the middle of a step, as filegen writes it: a truncated file, or the old bytes followed by a prefix of the new ones.

A path fails when:

  • it matches no such state (no state the source held). Bytes from two steps never mix: that is a torn file;
  • its size and modification time match a state but its content or mode do not (content and times disagree). The next normal sync would skip it forever;
  • it exists but the source never held it.

Mode and owner (when run as root) are judged too. Directories are judged on existence and permissions only; hard-link groups are left to the quiet sync. Exit 23 is accepted only when every file irsync gave up on is one filegen touched during that sync. The harness learns this from IRSYNC_FILE_REPORT, a variable it sets so irsync writes a small report of the files it retried and gave up on. It is for the harness only, so it is not in the command-line reference.

Exit codes

CodeMeaning
0Every round passed.
1A round failed.
2The harness itself could not do its job: filegen failed, the replay did not match filegen’s log, or a file could not be read or written.
3irsync-netstress only: the faults did not bite.
4The concurrent writes did not bite: no file changed during a sync was ever placed. The run tested nothing.

Exit 0, 23 and 24 from the sync during the writes are judged as above. Any other exit, a crash (a signal) or a hang (the client’s --timeout) fails the round, as does a quiet sync that exits anything but 0. These are failed rounds, not harness errors: the run exits 1, the round is kept and the rerun printed, and --keep-going goes on to the next round. A daemon that dies fails its round too, but then ends the run (exit 1), since nothing can sync after it. In irsync-netstress, a client log without netsim active is still a harness error (exit 2).

Files kept, and the rerun

A failed round is kept as ROOT/round-NNNN/: start/ (the source at the start of the round) and filegen’s state, beside ROOT/logs. When the judge failed a path, it also holds dest/, the destination as judged, before the quiet sync repaired it. A round that failed for another reason has no dest/; after a dead daemon, ROOT/DST/data is the destination as the round left it. The output names each failing path with its rule (the first 20), then judge report: (logs/iter-NNNN.judge.txt, one path<TAB>rule line per failure), round kept in: and rerun:. The rerun command uses a fresh root and --replay-rounds ROOT/logs/rounds.tsv, so every round starts from the same source tree with the same paces and step counts. --keep-going carries on past a failed round.

The command looks like this (the new root is the old one with .rerun added):

irsync-stress --direction pull --iterations 5 --seed 99 --steps 100 \
  --concurrent --pace fast --replay-rounds ~/work/run/logs/rounds.tsv \
  ~/work/run.rerun -- --paranoid

Bugs the concurrent rows found

The first full-pace runs found two real irsync bugs, both now fixed: a mode (or owner) taken from the walk instead of the file that was hashed, and a hard link made to a name that was replaced or renamed away after the walk. A failure of either kind is now a new failure.

One more failure is a known limit, not a bug to chase: on a filesystem with coarse timestamps, two writes in the same clock tick can leave a file’s size and modification time unchanged, so irsync’s checks cannot see the second one. The judge then reports content and times disagree. See Coarse timestamps.

The self-test: does the checker bite?

A checker that cannot fail is worth nothing. A test-hooks build of irsync has a switch, IRSYNC_TEST_NO_CHANGE_CHECKS=1, that turns all the change checks off. With it on, a concurrent run must produce a torn file and fail:

Build the release tools first (cargo build --release --workspace), then:

cargo build --release -p irsync --features test-hooks --target-dir target/selftest
IRSYNC_TEST_NO_CHANGE_CHECKS=1 target/release/irsync-stress --concurrent \
  --irsync target/selftest/release/irsync --direction push --iterations 20 ~/work/selftest

It must exit 1. Look at the report: the failure that proves the checker bites is a torn file (no state the source held). If a run fails only in other ways, try more seeds (--seed) until a torn file shows up. If the run passes, the checker is not catching what it should: stop and find out why. It depends on timing, so it is a manual step and not a cargo test; the checker’s own rules have deterministic tests.

Size and pressure

filegen damps growth above 80% of max_total_size, so a long run sits at the cap with deletions boosted. Choose the cap for the regime you want:

  • Small cap, many files (--max-total-size 512M --max-file-size 8M): metadata, naming, listing and deletion bugs; fast iterations, hundreds of seeds per hour.
  • Large cap, few files (--max-total-size 50G --max-file-size 8G): chunking, resume, sparse handling, hashing time, watchdogs.
  • Default (25G and 256M): the steady state of the acceptance run, about 3 s per sync and 30 minutes for 300 iterations on a disk-backed root.

A root on tmpfs is fast but competes with RAM; cap each concurrent run at a quarter of the free tmpfs space.

Harness extensions

These need changes to the stress crate, ordered by bugs per effort. Each should come with its own end-to-end test, like the existing one.

  1. A --check-arg passthrough (or --paranoid), so fileset check runs with --require nlink and the like inside the loop, not after it. The harness runs fileset check -q; breadth.sh’s CHECK hook with paranoid-check.sh covers only the final state of passing runs.
  2. Treat client exit 25 like 23. --max-delete cannot be stress-tested while exit 25 is a harness error.
  3. Kill and resume. --kill-after <secs> sends SIGKILL to the client once per iteration after that delay, then re-runs the identical command and verifies. This is the largest untested surface: resume, .part adoption, hash-verified chunk reuse, an orphaned finalize during a reconnect. irsync-netstress covers the network half (a dead zone that forces a reconnect and resume), not a killed client.
  4. Destination drift. Before each sync, run a second filegen (its own seed and state) on DST/data with a small step count. irsync must then repair the destination, and fileset check still expects the source. This exercises the planner’s changed-or-equal decisions on files irsync did not write, including same size with different content and the mtime shortcut (compare with and without -c).
  5. Two clients, one export. Run the same push from two client setups at once. The known cost is 60 s per overlapping file before PART_BUSY; unknown is whether the result is ever wrong.
  6. Split roots (--dst-root), so source and destination can be on different filesystems: ext4 to tmpfs, to xfs, to btrfs, and on macOS to a case-insensitive APFS volume. Timestamp granularity, case folding and NFC normalisation depend on the filesystem, and filegen draws names that are unique under folding and NFC for this reason.
  7. Disk full. A loop-mounted image of a fixed size as the destination. The run should fail cleanly with exit 23 and recover once space returns, and never leave a torn file that passes the next check.
  8. Negative checks after every iteration. No .irsync.*.part remains in the destination, and the index and session directories do not grow without bound across iterations. clean-check.sh checks the first after a passing run.

From a failed iteration to a bug report

  1. run.toml gives the seed, direction, sizes and extra arguments. Re-run with the same seed and --iterations N, where N is the failing iteration; the tree is deterministic, so it fails the same way.
  2. Shrink: same seed, --steps 1, iterations multiplied accordingly, until one iteration holds one filegen operation. Its step= line in filegen/filegen-<seed>.log is the trigger.
  3. Localise: flip the direction, then flip one client flag at a time (see the campaign matrix). Record which side and which flag.
  4. Read logs/iter-NNNN.client.log and the === iteration N === section of logs/daemon.log. Both carry colour codes; sed 's/\x1b\[[0-9;]*m//g' strips them for grep.
  5. Write the finding into IRSYNC_HARNESS_DECISIONS.md under “Known irsync bugs found by the harness”, in the form of the entries there: what filegen did, what the check reported, the hypothesis marked as such, the decision. Add a regression test to the irsync crate before fixing.

A campaign is only readable when known failures are subtracted automatically. That takes a classifier script that attributes each failure to a known cause by its signature; the repository has none. Keep it under crates/stress/tools/ and extend it with each new signature.

Cadence

  • Every change to irsync: CI runs the full regression (cargo test --workspace --all-features -- --include-ignored), which includes the harness’s end-to-end test.
  • Nightly: a breadth sweep in both directions with the matrix row of the week, 50 seeds, 20 iterations, small cap.
  • Weekly: two deep runs (push and pull, 1000 iterations, default cap) and one large-file run, with the daemon’s memory sampled per iteration.
  • Per irsync fix: the seed that found the bug, re-run as part of the fix, and its matrix row’s settings added to the harness’s end-to-end test (crates/stress/tests/e2e.rs) if they are cheap enough.

The measure is distinct root causes found per machine-hour, and the ledger is the “Known irsync bugs found by the harness” section. When a nightly sweep has run clean on a matrix row for two weeks, move that row to weekly and bring in the next harness extension.

Network stress with netstress

Part of Testing: the stress loop over a simulated bad network.

irsync-netstress tests irsync over a bad network. It runs the same sync-and-check loop as irsync-stress, but every packet between the irsync client and the daemon passes through a simulated link: limited speed, a queue that overflows, delay, bursts of loss, and on some profiles a dead zone that cuts the link for 20 to 60 seconds.

The question it answers: when the network is bad, does irsync still deliver exactly the right files, reconnect and resume when the link drops, and keep both the client and the daemon running? Slow syncs and warnings in the log are expected. Wrong files, failed syncs, crashes or leftover partial files are not.

It is a separate rig; irsync-stress tests over loopback without faults. How netstress works explains the simulated network inside. The design is in 2026-11-06-network-faults-design.md; the calls made while building it, and the results of the first real runs, are in NETSTRESS_DECISIONS.md.

Use

Quick start

# 1. Build the fault binaries (once, and after every change to irsync).
cargo build --release --workspace --features netsim --target-dir target/netsim

# 2. A short smoke run, about a minute: no shaping, one 6 s dead zone per sync.
target/netsim/release/irsync-netstress --profile test-blackout --direction push ~/work/ns-smoke

# 3. A real run: a moving vehicle on 4G, pushing. Up to about 10 to 15 minutes.
target/netsim/release/irsync-netstress --profile 4g-vehicle --direction push --seed 1 ~/work/ns-4g-push

The root directory (the last argument) must not exist yet, or must be empty. It is never deleted. Use a short path such as ~/work/...: filegen makes deep trees and refuses to run when the root’s path is long enough to push files past the system’s path length limit.

The fault build

The fault layer is compiled into irsync only when the cargo feature netsim is on. A normal build has none of it, and never reads the IRSYNC_NETSIM variable. Build the fault binaries into their own target directory:

cargo build --release --workspace --features netsim --target-dir target/netsim
  • The binaries land in target/netsim/release/: irsync, irsync-netstress, irsync-stress, filegen and fileset.
  • The separate target directory keeps target/release free of fault code, so a fault build can never be mistaken for a real one.
  • Write the command exactly as shown. --features irsync/netsim looks the same but builds irsync without the feature, because irsync lists itself as a dev-dependency.
  • Check it: target/netsim/release/irsync --version ends with [netsim]. irsync-netstress checks this itself and refuses to start with any other irsync, printing the build command.
  • A debug build works too (drop --release, binaries in target/netsim/debug/), but the link model then costs more CPU and runs take longer.

Rebuild after every change to irsync. The rig uses whatever binary it finds; an old fault build tests old code.

Repeating a run

The seed fixes the file trees exactly and fixes the random choices of the network (which speed, which packet is lost, how long the dead zone lasts). But the network runs on the real clock, and threads do not run in the same order every time, so a repeated run does not replay packet for packet. The same seed gives a run with the same character, not the same run. To repeat one:

irsync-netstress --profile <profile> --direction <dir> --seed <seed> ~/work/new-root

using the values from the failed run’s run.toml. Some hints:

  • Run it alone. Several runs at once share the CPU, which changes timing and makes syncs slower.
  • If the failure was in iteration N, keep --iterations N and let it stop at the first failure (no --keep-going).
  • Try a few seeds. A failure that shows up on one seed in ten is still a real failure.
  • Extra client options go after --, for example -- --timeout 30 to test whether a longer timeout makes a failure go away.

Sweeps

crates/netstress/tools/sweep.sh runs many seeds, both real profiles and both directions, a few runs at a time, always with --keep-going. It deletes the roots of passing runs (they can be repeated from their seed) and keeps the roots of failing ones.

crates/netstress/tools/sweep.sh                     # seeds 1 to 10, both profiles, both directions
SEEDS="1 3" PROFILES=dsl-video crates/netstress/tools/sweep.sh
JOBS=2 crates/netstress/tools/sweep.sh --iterations 3
VariableMeaningDefault
BINDirectory with irsync-netstress, irsync, filegen, fileset.target/netsim/release
OUTWhere roots, outputs and summary.txt go.~/work/irsync-netstress-<date>
SEEDSSeeds to run, as arguments to seq: "1 10" is 1 to 10, "5 5" is just 5.1 10
JOBSRuns at the same time.4
PROFILESProfiles to run, separated by spaces.4g-vehicle dsl-video
CLIENTArguments for the irsync client, after --.none
DURATIONA time budget in seconds. Once it has passed, no new run starts, and the runs not started get no line in summary.txt. Runs already going finish.none

Any arguments go to every irsync-netstress run, before the root. sweep.sh --concurrent runs the concurrent mode: filegen writes to the source during each sync. matrix.sh has two rows for it, net-concurrent and net-concurrent-paranoid, each with a one-hour budget.

It refuses to start without a fault build. For each run it writes OUT/<profile>-<direction>-<seed>.out (the rig’s output) and adds one line to OUT/summary.txt:

4g-vehicle push 3 exit=1 passed=9 failed=1 elapsed=1104.2s outages=10

It exits non-zero if any run did not exit 0.

Plan for the time. A full default sweep is 40 runs. With four sharing the CPU, a dsl-video pull run takes about 4 minutes, a 4g-vehicle run 14 to 23 minutes and a dsl-video push run about 30 (up to 37), because pushes go up the slow uplink. Expect over three hours at JOBS=4. With --congestion cubic the dsl-video runs take about half as long and the 4g-vehicle runs up to twice as long, so the total is about the same. Lower JOBS if syncs slow down enough to cause timeouts of their own.

Reading the logs

The logs contain colour codes; read them with less -R, or strip the codes before searching with grep.

The fault layer writes these lines, all at warn so they show at any log level:

LineWhereMeaning
netsim active profile=… side=… seed=… stream=…client and daemon, at startThe fault layer is on, with these settings.
netsim: dead zone open secs=NclientThe dead zone started; it lasts N seconds.
netsim: dead zone closedclientThe dead zone ended. It is logged with the first packet after the end, so it may come a little later than N seconds.
netsim: counts sent=… queue_drops=… loss_drops=… outage_drops=… send_errors=… truncated=…client and daemonWhat happened to this process’s packets so far. Every 10 s while traffic flows, and once at the end.
netsim: send failed: …client and daemonThe real socket refused a packet. The first one is at warn, later ones at debug. Should never happen.

The counts, per process, counting only packets this process sent (except outage_drops and truncated):

CountMeaning
sentPackets irsync handed to the fault layer to send.
queue_dropsDropped because the simulated queue was full: irsync sent faster than the link could carry.
loss_dropsDropped by the random loss.
outage_dropsDropped because a handover or the dead zone was on, sent or received. Client only; the daemon’s is always 0.
send_errorsThe real socket refused to send. Should be 0.
truncatedA received packet was bigger than irsync’s buffer and was dropped. Should be 0.

The counts tell you whether a failing sync saw the losses the profile should give. For example, queue_drops far above loss_drops on a push under dsl-video means irsync kept overfilling the 64 KiB uplink queue. The daemon’s last counts line is usually its last 10-second report: the rig stops the daemon without letting it write a final one.

What a normal dead zone looks like in the client log (4G, --timeout 10), in order:

  1. netsim: dead zone open secs=41
  2. about 10 s later: no activity; dropping the connection secs=10, then session failed, then connection lost; reconnecting
  3. further reconnect attempts while the zone lasts
  4. netsim: dead zone closed
  5. session started session=<same id> resumed=true

In the daemon log around the same time, expect connection failed: control stream: connection lost and, from the QUIC layer, failed closing path err=LastOpenPath. An occasional SendDatagram warning from iroh is also normal. None of these fail a run.

Useful searches (on a log with colour codes stripped):

# strip colour codes
sed 's/\x1b\[[0-9;]*m//g' logs/iter-0003.client.log > /tmp/iter3.log

# the network story of one sync
grep -E 'netsim|no activity|reconnecting|session started|session failed' /tmp/iter3.log

# every file that failed, and why
grep failed /tmp/iter3.log

# the daemon's side of iteration 3
sed -n '/=== iteration 3 ===/,/=== iteration 4 ===/p' logs/daemon.log

After a failure

Start with the first failed iteration. With --keep-going, later iterations inherit the damage (for example a .part file left by an earlier one), so only the first failure says anything clear about its cause.

  1. Read the iteration line and the reason line under it.
  2. Read run.toml for the seed, profile, direction and sizes.
  3. Read the client log of that iteration (see Reading the logs): the network story, then which files failed and with what message.
  4. Read the daemon log between === iteration N === and the next marker.
  5. For file differences, read logs/iter-NNNN.check.txt (ADD, DEL, CHG lines), as in irsync-stress.

What each kind of failure usually points at:

SymptomWhere to look
reconnect without a dead zoneThe client saw 10 s without any packet from the daemon while the link was up. Look at the counts around that time: many drops point at the profile or the link model, few drops point at irsync.
dead zone did not end in a resumed sessionThe reconnect worked but a new session started instead of the old one resuming, or the client never got back. Look at what the client logged after dead zone closed.
partial file left behindA failed or interrupted file left its .irsync.<name>.part. It usually goes with a client exit 23 earlier in the run.
Exit 2 with daemon died during iteration NThe daemon crashed. The end of daemon.log has the reason. This is always worth a bug report.
Exit 2 with irsync client exited NThe client failed in a way that is not a partial transfer: 1 (the whole sync failed, for example the reconnect window ran out), 25 (--max-delete stopped it), or a crash. The client log has the reason.
Exit 3No sync moved enough data to hit the dead zone. Use a bigger --max-total-size.

To tell an irsync problem from a problem with the simulation, change one thing and run the same seed again. If a failure goes away with gentler numbers in the profile, the profile was too harsh. If it stays even under test-blackout, which has no shaping at all, look at irsync or the transport. The first-run findings and the open questions are in NETSTRESS_DECISIONS.md.

Using the fault layer by hand

The rig is not the only way to use the fault layer. Any irsync from the fault build turns it on when the IRSYNC_NETSIM variable is set:

IRSYNC_NETSIM=profile=<name>,side=<client|daemon>,seed=<n>,stream=<n>

All four keys are required, in any order. A bad value is an error, not ignored. An optional fifth key, acks=<immediate|gentle|peer-default>, changes the ACKs this side asks of the other; see --acks under Command line.

  • Set it on both sides with the same profile and seed, side=daemon for the daemon and side=client for the client. With the variable set, irsync talks only through the fault layer: no ordinary UDP socket, no relay. A client with the variable cannot reach a daemon without it, and the other way round.
  • stream picks one of many independent fault schedules for the same seed. The rig uses 0 for the daemon and the ping, and the iteration number for each iteration’s client. Use different streams to get different schedules.
  • The fault layer only works over IPv4 on this machine. Point the client at the address the daemon prints with --address 127.0.0.1:<port>.
  • Give the client a --reconnect window longer than the dead zones (the rig uses 5m) and the profile’s --timeout. Without a reconnect window a dead zone simply fails the sync.
  • Look for netsim active in each side’s log to be sure it is on.

Changing or adding a profile

The profiles live in two places:

  • crates/irsync/src/net/netsim/profile.rs: the link in each direction (link()) and the handovers and dead zone (outages()). The fields are documented in the file and explained in How netstress works.
  • crates/netstress/src/profile.rs: the run defaults (iterations, steps, sizes), the client --timeout, and whether the profile has dead zones.

To change numbers, edit those tables and rebuild the fault build. The unit tests in crates/irsync/src/net/netsim/link.rs and outage.rs check some profile behaviour (for example that 4G loses about 1% in bursts, and that dsl-video’s video leaves room for irsync); a big change may need their bounds updated. Record why in NETSTRESS_DECISIONS.md.

To add a profile:

  1. Add a variant to ProfileName in crates/irsync/src/net/netsim/mod.rs, and its name to FromStr and Display there.
  2. Add its link and outage parameters in crates/irsync/src/net/netsim/profile.rs.
  3. Add the same name to Profile in crates/netstress/src/profile.rs, with its defaults.
  4. Add a unit test in link.rs or outage.rs that checks the behaviour the profile is meant to have.
  5. Document it under Profiles on this page.

Rules that keep a profile useful:

  • The client --timeout must be longer than the longest handover and shorter than the shortest dead zone. Then a dead zone always forces a reconnect and a handover never does. For 4g-vehicle that is 2 s < 10 s < 20 s.
  • A profile without dead zones fails on any reconnect, so its worst stall (queueing delay plus loss bursts) must stay well under the client --timeout.
  • Video-style cross traffic must hold the queue below its size (hold_bytes < queue_bytes), or irsync’s packets have no room at all and the link blacks out. Nothing checks this yet.
  • The dead zone threshold (dead_zone_after_bytes) must be well under what a typical sync moves, or most syncs never hit it.

Testing the rig

cargo test -p netstress -- --include-ignored  # the rig: unit and end-to-end tests
cargo test -p irsync --features netsim        # irsync, including the fault layer's own tests

Without --include-ignored, the rig’s slow end-to-end tests are skipped. They run the real rig under test-blackout (and one short dsl-video pull). The first time, they build the fault binaries into target/netsim/debug themselves, which takes a few minutes.

The fault layer’s own tests:

  • crates/irsync/src/net/netsim/*.rs: the link model, outages, seeds and addresses.
  • crates/irsync/tests/netsim.rs: client and daemon in one process, on tokio’s paused clock and an in-memory network, sync a 4 MiB file through a dead zone and resume, and push 3 MiB over test-slow in over a minute of network time; each takes about a second. With the real binaries and no IRSYNC_NETSIM, nothing changes.
  • crates/irsync/tests/netsim_endpoint.rs: an endpoint with the fault layer on offers no ordinary IP or relay address, so no packet can go around it.

Reference

Command line

irsync-netstress [OPTIONS] --direction <DIRECTION> --profile <PROFILE> <ROOT> [-- <CLIENT_ARGS>...]
OptionMeaningDefault
<ROOT>Working directory for the run. Created if missing; must be empty if it exists. Never deleted.required
--profile <NAME>The network to simulate: 4g-vehicle, dsl-video, long-rtt or test-blackout. See Profiles.required
--direction <push|pull>Which way the client moves data. On a push the client sends; on a pull the daemon sends.required
--iterations <N>Number of sync-and-check rounds.the profile’s
--seed <S>Seed for the file trees and for the network’s random choices. Printed in the header and saved in run.toml.random
--steps <N>filegen operations per fill and per mutation.the profile’s
--max-total-size <SIZE>Passed to filegen: the most data the tree may hold.the profile’s
--max-file-size <SIZE>Passed to filegen: the largest single file.the profile’s
--filegen-set <KEY=VALUE>An extra filegen --set for every filegen run; repeatable.none
--congestion <bbr|cubic>Write congestion = "<NAME>" into both the daemon’s and the client’s config, so both directions use that congestion control.irsync’s (bbr)
--acks <immediate|gentle|peer-default>The ACKs each side asks of the other: immediate (every packet, within 1 ms), gentle (every second packet, within 1 ms) or peer-default (nothing asked: every second packet or after 25 ms). For measuring them against each other.irsync’s (immediate)
--log-level <LEVEL>Log level for the daemon and the client.debug
--keep-goingCarry on after a failed iteration instead of stopping.off
--irsync, --filegen, --fileset <PATH>Use this binary instead of looking one up. The tools are looked up next to irsync-netstress first, then on PATH.lookup
-- <ARGS>...Everything after -- is added to every irsync client command.none

What the rig adds to the client command line by itself:

  • --reconnect 5m: the client may spend up to five minutes reconnecting after the link drops. That is far longer than the longest dead zone (60 s). irsync-stress passes --reconnect 0 instead.
  • --timeout <N>, the profile’s value: after N seconds without hearing from the daemon, the client drops the connection and reconnects. It comes before your -- <ARGS>, so -- --timeout 20 overrides it.

Examples:

# Five quick rounds of DSL in the pull direction, keep going past failures
irsync-netstress --profile dsl-video --direction pull --iterations 5 --keep-going ~/work/ns-dsl

# 4G with a smaller tree, and the client keeping four data streams open
irsync-netstress --profile 4g-vehicle --direction push --max-total-size 64M ~/work/ns-4g -- --parallel 4

# Info-level logs (debug is the default, and is large on long runs)
irsync-netstress --profile 4g-vehicle --direction pull --log-level info ~/work/ns-4g-info

Profiles

Each profile describes one kind of bad network. “Up” is client to daemon, “down” is daemon to client. On a push the file data goes up; on a pull it comes down. A slow uplink therefore hurts pushes most.

4g-vehicle: a moving vehicle on 4G

down (daemon to client)up (client to daemon)
speed2 to 30 Mbit/s0.7 to 10 Mbit/s
speed changesa new speed every 2 to 6 ssame
queue512 KiB (about 2 s at the slowest speed)256 KiB (about 3 s at the slowest speed)
delay30 ms each way, drifting by up to ±20 mssame
lossabout 1%, in bursts: normally 0.2%, but now and then the link goes bad and loses 20% for a whilesame
other0.5% of packets arrive out of order, 0.1% arrive twicesame

Outages, in both directions at once:

  • Handovers every 30 to 90 s, each cutting the link for 0.2 to 2 s, like moving from one cell tower to the next. Too short to force a reconnect.
  • One dead zone per sync, 20 to 60 s long, like a tunnel. It opens once the sync has moved 256 KiB to 4 MiB of traffic, so it always hits in the middle of a transfer. It is long enough that the client must give up on the connection, reconnect and resume.

Run defaults: 10 iterations, 100 filegen steps, trees up to 256M, files up to 32M, client --timeout 10.

What it is meant to catch: resume bugs, files left half-written, state that does not survive a reconnect, the client or daemon getting stuck or giving up.

dsl-video: a DSL line overloaded by video streaming

down (daemon to client)up (client to daemon)
speed16 Mbit/s, fixed1 Mbit/s, fixed
queue1536 KiB64 KiB (about 0.5 s)
delay10 ms each way, drifting by up to ±2 mssame
loss0.01% at randomsame
video trafficevery 2 to 4 s a burst of 1 to 2 s: the video fills the queue to 1280 KiB and then takes 10 of the 16 Mbit/s. irsync’s packets wait behind it (650 to 790 ms extra delay) and are lost only if irsync sends faster than the 6 Mbit/s left over.none

No handovers and no dead zones. The link never drops, so any reconnect fails the iteration: under this profile the client should never decide the connection is dead.

Run defaults: 10 iterations, 100 filegen steps, trees up to 32M, files up to 4M, client --timeout 10.

What it is meant to catch: timeouts that are too short for a slow or overloaded line, stalls when packets wait a long time in a queue, and irsync giving up on a peer that is merely slow.

long-rtt: a long, clean line

down (daemon to client)up (client to daemon)
speed50 Mbit/s, fixed10 Mbit/s, fixed
queue1024 KiB256 KiB
delay45 ms each way (90 ms round trip), no driftsame
lossnonenone

No reordering, no cross traffic, no outages, so any reconnect fails the iteration. Run defaults: 5 iterations, 2000 filegen steps, trees up to 64M, files up to 64K, client --timeout 10. The many small files mean many round trips.

What it is meant to show: how irsync behaves when every round trip takes a long time, and settings that only matter then, such as --acks.

test-blackout: for the rig’s own tests

No speed limit, no delay, no loss. One 6 s dead zone per sync, after 256 KiB of traffic. Client --timeout 2. Defaults: 3 iterations, 50 steps, trees up to 8M, files up to 1M.

It exists so the automated tests can check the reconnect path in seconds. It is also a quick way to check that a build and a machine work before starting a long real run. It does not simulate any real network; don’t use it for campaigns.

test-slow: for irsync’s own tests

A clean 256 kbit/s uplink with a 64 KiB queue, an unlimited downlink, no loss, no delay, no outages. irsync’s test a_slow_uplink_that_needs_more_than_a_minute_still_delivers_everything (in crates/irsync/tests/netsim.rs) uses it to push data that takes over a minute of network time, on tokio’s paused clock. irsync-netstress does not offer it.

test-wan: for measurements

A fast, clean long-distance link: 100 Mbit/s each way, 40 ms of delay in each direction (80 ms round trip), a 2 MiB queue, no loss, no outages. It was added to measure how --parallel bounds files per round trip (see docs/IRSYNC_DECISIONS.md, 2.1 item 7); set IRSYNC_NETSIM by hand, as for test-slow. irsync-netstress does not offer it.

Where the numbers come from

The numbers are a first proposal based on what these networks are known to do, not measurements. The exact values are in two places: crates/irsync/src/net/netsim/profile.rs (the link and the outages) and crates/netstress/src/profile.rs (run sizes and client timeout). See Changing or adding a profile.

What a run does

The sequence is irsync-stress’s, with the fault layer switched on:

  1. Checks the tools. Finds irsync, filegen and fileset, and refuses to go on unless irsync --version ends with [netsim]. Only then does it create the root.
  2. Writes run.toml with every setting, so the run can be repeated.
  3. Starts the daemon with IRSYNC_NETSIM set for the daemon side. It waits up to 15 s for the daemon to log netsim active, which proves the fault layer really is on.
  4. Ping round. One sync of a single small file, which must arrive byte for byte. This proves the two sides can talk through the fault layer before any real work. A failure here is a setup failure (exit 2).
  5. Fills the source tree with filegen and records its manifest with fileset init.
  6. For each iteration:
    1. Checks the daemon is still running and writes === iteration N === into the daemon log.
    2. Runs the client with IRSYNC_NETSIM set for the client side. Each iteration gets its own fault schedule (its own speeds, losses and dead zone timing).
    3. Checks the daemon survived the sync.
    4. Reads the client log: was the fault layer active, did each dead zone end in a resumed session, was there any reconnect outside a dead zone?
    5. Compares the two manifests and runs fileset check on the destination, as irsync-stress does.
    6. Prints the iteration line. Then mutates the source tree with filegen for the next round.
  7. Stops the daemon, looks for .irsync.*.part files left anywhere in either tree, prints the footer and exits.

On a push the client’s tree is the source and the daemon’s export is the destination. On a pull they swap.

What counts as a pass

An iteration passes when everything irsync-stress checks passes:

  • the client exits 0,
  • the source and destination manifests match,
  • fileset check finds no differences,

and the network side looks right too:

  • the client log says netsim active (the fault layer was on),
  • every dead zone that opened was followed by the same session resuming (session started ... resumed=true with the first session’s id),
  • there was no reconnect outside a dead zone,
  • the daemon is still running afterwards.

Across the whole run:

  • no .irsync.*.part file is left in either tree,
  • if the profile has dead zones, at least one sync must actually have hit one. Otherwise nothing was tested (exit 3).

A single sync that ends before its dead zone is due (because it moved less than the threshold) is noted with outages 0, not failed. Later iterations of a run often move little data, so this is normal for them.

Output

A header, one line per iteration, a footer:

irsync-netstress
  root:      ~/work/ns-4g-push
  seed:      1
  direction: push
  endpoint:  716a53cc4cea6705494da4d3b72cae40cfa658440e2e1fe4afba1f1bfbc2a5bb
  address:   127.0.0.1:50357
  network:   4g-vehicle
iter 0001/0010  sync 94.7s  exit 0    manifest ok  check ok  outages 1
iter 0002/0010  sync 61.2s  exit 0    manifest ok  check ok  outages 1
...
passed=10 failed=0 elapsed=812.3s outages=10
  • sync: how long the client took. Under 4g-vehicle this includes the dead zone, so 60 to 160 s is normal.
  • exit: the client’s exit code. 0 is success, 23 means some files did not transfer.
  • outages: how many dead zones opened during this sync (0 or 1).
  • The footer’s outages= is the total for the run.

A failed iteration gets an extra line under it when the network checks failed, naming the reason and the client log:

iter 0001/0010  sync 72.3s  exit 0    manifest ok  check ok  outages 0
  reconnect without a dead zone (1 time(s)); see ~/work/ns-dsl/logs/iter-0001.client.log

When the file checks failed, the path of the check report follows instead, as in irsync-stress:

iter 0003/0010  sync 104.2s  exit 23   manifest MISMATCH  check FAILED (added=1 deleted=1 changed=0)  outages 1
~/work/ns-4g-push/logs/iter-0003.check.txt

At the end, any partial files left behind are listed before the footer:

partial file left behind: ~/work/ns-4g-push/DST/data/a/b/.irsync.report.pdf.part

and a run where no dead zone ever opened ends with:

faults did not bite: no iteration had an outage

The possible reasons on the extra line:

ReasonMeaning
fault layer not activeThe client log has no netsim active line.
reconnect without a dead zone (N time(s))The client decided the connection was dead and reconnected while the link was up (no dead zone open). The link was slow or lossy, but not down.
dead zone did not end in a resumed session (D dead zone(s), R resumed)A dead zone opened, but afterwards the client did not resume the session it had before: it started a fresh one, never got back, or the sync ended.

Exit codes

CodeMeaning
0Every iteration passed.
1At least one iteration failed (file checks or network checks), or a partial file was left behind.
2The rig could not do its job: bad arguments, a root that is not empty, a missing tool, an irsync without the fault layer, the daemon did not start or died, the ping round failed, a tool failed, or the client exited with something other than 0 or 23.
3The profile has dead zones but none opened in the whole run, so the reconnect path was never tested. This is not a pass. Usually the trees were too small; raise --max-total-size.
4--concurrent only: no file changed during a sync was ever placed, so the run tested nothing.
130Interrupted (Ctrl-C or SIGTERM). The daemon and any running client are stopped first.

Files a run leaves behind

The layout is irsync-stress’s:

ROOT/
  run.toml                    every setting of the run, enough to repeat it
  SRC/config/, SRC/data/      the source side (the client on a push)
  DST/config/, DST/data/      the destination side (the daemon on a push)
  filegen/                    filegen's log and state
  logs/
    daemon.log                the daemon's log for the whole run, with === iteration N === markers
    ping.client.log           the client log of the ping round
    filegen.stderr.log        filegen's error output
    iter-0001.client.log      the client log of each iteration
    iter-0001.check.txt       what fileset check found
    iter-0001.manifest.blake3 hashes of both manifests

run.toml has one extra section:

[network]
profile = "4g-vehicle"
client_timeout_secs = 10
reconnect = "5m"

The logs are small (a few MB for a 10-iteration 4G run at debug); the data trees are what take space, up to the profile’s total size on each side. Delete roots you no longer need. The sweep script deletes the roots of passing runs for you.

Known limits

  • Not a packet-for-packet replay. See Repeating a run.
  • CPU-sensitive. The simulation runs in the irsync processes on the real clock. A busy machine delays packets on top of the simulated delay. Real runs are best done alone, or a few at a time.
  • Loopback only, IPv4 only. Both sides run on this machine.
  • Only the client has outages. The client’s fault layer drops both what it sends and what it receives during a handover or dead zone; the daemon’s never cuts the link itself. Both directions are still cut.
  • One dead zone per client process. A sync is one client process, so one per sync. A sync that moves less than the threshold gets none.
  • First-proposal numbers. The profiles have not been checked against measured networks.
  • Client kill and daemon crash are not covered. The rig neither kills the client mid-sync nor crashes the daemon.

How netstress works

Part of Testing: how the netstress rig works inside.

This page explains what happens inside the network-fault rig: how the fault layer gets between irsync and the network, how it decides what happens to each packet, and how the rig decides whether a run passed. For how to use it, see Network stress with netstress. The decisions made while building it and the first results are in NETSTRESS_DECISIONS.md.

The big picture

There are two parts:

  1. The fault layer, inside irsync itself. It is compiled in only with the cargo feature netsim, and switched on at run time by the IRSYNC_NETSIM environment variable. When it is on, every QUIC packet irsync sends or receives passes through a simulated link.
  2. The rig, irsync-netstress. It is irsync-stress’s loop (make a tree, sync it, check it, change it, repeat) with the variable set on the daemon and on every client, plus checks that read the client logs to make sure the network did what it should.
                         irsync-netstress
            (filegen, fileset, run.toml, logs, checks)
               |                                  |
     spawns once, with                  spawns once per iteration, with
     IRSYNC_NETSIM=...,side=daemon      IRSYNC_NETSIM=...,side=client,stream=<i>
               |                                  |
               v                                  v
   +-------------------------+        +-------------------------+
   | irsync daemon           |        | irsync client           |
   |   session, files        |        |   session, files        |
   |   iroh endpoint, QUIC   |        |   iroh endpoint, QUIC   |
   |   +-------------------+ |        | +-------------------+   |
   |   | netsim transport  | |        | | netsim transport  |   |
   |   |  downlink model   | |        | |  uplink model     |   |
   |   |                   | |        | |  handovers,       |   |
   |   |                   | |        | |  dead zone        |   |
   |   +---------+---------+ |        | +---------+---------+   |
   +-------------|-----------+        +-----------|-------------+
                 |     real UDP sockets on 127.0.0.1           |
                 +---------------------------------------------+

Both programs are the real irsync binaries, running as separate processes on this machine, exactly as in irsync-stress. Only the network between them is simulated, and it is simulated in real time: a 1 Mbit/s uplink really carries 1 Mbit/s.

Why a custom transport

iroh, the networking library irsync uses, lets a program add its own “custom transport”: a piece of code that carries iroh’s packets instead of an ordinary UDP socket. The fault layer is such a transport. It still uses a real UDP socket on 127.0.0.1 underneath, but it decides for every packet whether, when and how often it gets sent.

The alternatives, and why they were not used:

  • A proxy between client and daemon: ruled out in the design.
  • The operating system’s traffic shaping (pf and dummynet on macOS, tc netem on Linux): needs root, and differs per system.
  • turmoil or another whole-program simulator: needs both peers in one process on a simulated clock with simulated sockets. irsync talks through iroh and its QUIC stack with their own sockets, and does real, blocking disk I/O that a simulated clock does not cover.

The custom transport needs only a few hooks in irsync, works without root on macOS and Linux, and keeps the real binaries and the real clock. Its cost: iroh marks the hook as unstable, so an iroh upgrade may break it. Because all of it is behind the netsim feature, such a break shows up only as a failure to build the fault build, never in a normal build.

How irsync is wired to the fault layer

Everything sits behind #[cfg(feature = "netsim")]. A normal build has none of this code and never reads the variable.

  • The feature (crates/irsync/Cargo.toml) turns on iroh’s unstable-custom-transports and a few small dependencies the transport needs (iroh-base, n0-watcher, noq-udp, rand, rand_chacha).
  • The version (crates/irsync/src/build.rs): a fault build’s irsync --version ends with [netsim]. The rig and the sweep script check this before doing anything.
  • Reading the variable (netsim::active() in crates/irsync/src/net/netsim/mod.rs): read once per process and remembered. Unset means off. A value that does not parse is an error every time it is asked for, so irsync stops instead of silently running without faults.
  • Building the endpoint (build_endpoint in crates/irsync/src/net/endpoint.rs): when the variable is set, irsync logs netsim active at warn, removes iroh’s ordinary IP transport and its relay transport, and adds the fault transport. With the ordinary paths removed, iroh has no way to reach the peer except through the fault layer. A test (crates/irsync/tests/netsim_endpoint.rs) checks that such an endpoint offers no IP or relay address. The transport binds to the first IPv4 bind address irsync was given, or 127.0.0.1 on a free port.
  • The daemon’s address (listen_addrs in crates/irsync/src/daemon.rs): the daemon prints the fault transport’s socket address in its startup lines, so the rig (or a person) knows where to point the client.
  • The client’s dial (dial_addrs in crates/irsync/src/main.rs): the client turns each address it would dial into a fault-transport address. IPv6 addresses are refused.

A fault-transport address is the IPv4 address’s 4 bytes followed by the port’s 2 bytes, tagged with the transport id 0x6e65_7473_696d (“netsim” in ASCII).

Each irsync process builds its endpoint once. A client reconnecting after a dead zone reuses the same endpoint, so the same fault transport, with the same link and outage state, carries the whole sync.

The path of one packet

Each side simulates only its own outgoing direction: the client’s transport is the uplink (client to daemon), the daemon’s transport is the downlink (daemon to client). So every packet is shaped exactly once, by the side that sends it.

Outages are simulated only on the client, but in both directions: the client’s transport drops what it sends and what it receives while a handover or the dead zone is on. That cuts the whole link without the two processes having to agree on timing.

Sending (Shared::send in transport.rs):

iroh hands over a transmit (one packet, or several packed together)
  |
  split into individual packets
  |
  for each packet:
    count it as sent
    client only: is the link up (no handover, no dead zone)?    no -> drop (outage_drops)
    link model: queue full?                                     yes -> drop (queue_drops)
    link model: lost?                                           yes -> drop (loss_drops)
    link model: when does it arrive? (once, or twice if duplicated)
    put it on the delivery queue with that time

The send call always tells iroh “done” at once. The fault layer never makes iroh wait; a packet that does not fit is dropped, as on a real link.

Delivering (deliver in transport.rs): a background task keeps the waiting packets sorted by delivery time. When a packet’s time comes, it sends it on the real UDP socket to the peer. Loopback adds almost nothing, so the packet arrives when the model said it would, to within the tokio timer’s resolution of about 1 ms. On a fast link several packets fall into the same millisecond and arrive together, so the receiver sends fewer ACKs than it would on a real link where they come one at a time. Measurements of ACK traffic undercount for this reason.

Receiving (poll_recv in transport.rs):

read a packet from the real socket
  |
  bigger than iroh's buffer?                                    yes -> drop (truncated)
  client only: is the link up?                                  no -> drop (outage_drops)
  hand it to iroh

To spot packets that are too big, the transport reads into a buffer one byte larger than iroh’s; if that extra byte gets filled, the packet would have been cut short, so it is dropped and counted instead.

Link in crates/irsync/src/net/netsim/link.rs decides each packet’s fate. It has no clock of its own: it is told the current time with each packet. That keeps it simple to test: the same seed and the same packets at the same times always get the same fates.

The parameters per profile and direction are in crates/irsync/src/net/netsim/profile.rs (LinkParams). For each packet the model does the following, in this order.

1. The queue

The link has a speed and a queue in front of it, like a router’s buffer in front of a slow line. The model treats the queue as an amount of bytes, not a list of packets:

  • Between packets, the queue drains at the link’s speed.
  • A new packet is added to the queue. If that would make the queue bigger than its limit (queue_bytes), the packet is dropped.
  • Otherwise its waiting time is the bytes now in the queue (its own included) divided by the link’s speed.

So a sender that sends faster than the link sees its packets wait longer and longer, and then get dropped once the queue is full. That is “bufferbloat”, and it is what QUIC’s congestion control has to cope with.

A queue of u64::MAX (as in test-blackout) means no queue at all: no waiting, no queue drops.

2. Speed changes

When a profile gives a range of speeds (4G: 2 to 30 Mbit/s down), the model draws a new speed at random within that range every so often (4G: every 2 to 6 s). The queue drains at the old speed up to the moment of the change, then at the new one. A fixed speed (DSL) never changes.

3. Cross traffic (video)

dsl-video’s downlink shares its queue with someone else’s video stream. The video comes in bursts: every 2 to 4 s a burst starts and lasts 1 to 2 s. During a burst:

  • While the queue holds less than hold_bytes (1280 KiB), the video pours in at twice the link speed (load = 2.0), so the queue fills at the link speed.
  • Once the queue reaches hold_bytes, the video holds it there, like a real video player that backs off once its own traffic starts to queue. It takes 10 of the 16 Mbit/s (share = 0.625). Whatever irsync has added above that level drains at the 6 Mbit/s that is left.

Only irsync’s packets can fill the last 256 KiB of the queue. So irsync loses packets only if it sends faster than its 6 Mbit/s share for long enough to fill that space, not just because the video is playing. Its packets do wait behind the video: 1280 KiB at 16 Mbit/s is about 650 ms of extra delay.

Between bursts the queue drains at the full link speed.

A video that filled the queue completely would drop every irsync packet for up to about a second in every burst: a total blackout, not an overloaded line. See call 12 in NETSTRESS_DECISIONS.md.

4. Bursty loss

Real wireless links lose packets in clumps, not evenly. The model uses the standard two-state “Gilbert-Elliott” approach: the link is either in a good or a bad state, and each state has its own loss rate.

For each packet that got into the queue, the model first decides whether the state changes, then whether this packet is lost:

4G valuemeaning
to_bad0.004chance per packet that a good link turns bad
to_good0.1chance per packet that a bad link recovers
loss_good0.002loss while good (0.2%)
loss_bad0.2loss while bad (20%)

With these numbers a good spell lasts about 250 packets and a bad spell about 10, the link is bad about 4% of the time, and about 1% of packets are lost overall, many of them close together. dsl-video never goes bad and loses 0.01% at random.

A lost packet has already taken its place in the queue, as if it were lost on the wire after the bottleneck.

5. Delay, jitter, reordering, duplicates

  • Delay: every packet gets the fixed one-way delay (base_delay_ms) on top of its queueing time.
  • Jitter: an offset that drifts slowly, up to jitter_ms either way. Every 100 ms it takes a random step of up to a quarter of that amount. So delay changes smoothly over time instead of jumping per packet.
  • Order: jitter alone never changes the order of packets. A packet never arrives before the one sent just before it.
  • Reordering: a small share of packets (4G: 0.5%) gets 5 to 30 ms extra and may arrive after packets sent later.
  • Duplicates: a small share (4G: 0.1%) is delivered twice, the second copy 1 ms after the first.

Handovers and dead zones

Outages in crates/irsync/src/net/netsim/outage.rs decides when the link is down. It exists only on the client. It is asked for every packet the client sends or receives, and answers “up”, “handover” or “dead zone”.

Handovers run on a timetable: the first starts 30 to 90 s after the transport starts, each lasts 0.2 to 2 s, and the next one starts 30 to 90 s after the previous one started. They are short on purpose: shorter than the client’s 10 s --timeout, so QUIC simply resends what was lost and the sync carries on. A handover that would start during the dead zone is skipped.

The dead zone is triggered by traffic, not time. The model counts the bytes of every packet passing the client, in both directions. When the count reaches a threshold drawn at the start (4G: somewhere between 256 KiB and 4 MiB), the dead zone opens and lasts its drawn length (4G: 20 to 60 s). It happens once per client process, so once per sync.

Counting traffic instead of time means the dead zone always lands while data is moving, whether the link is fast or slow, and never while the client is still starting up or after it has finished. The cost: a sync that moves less than the threshold never gets a dead zone. The rig notes that and only complains if no sync of the whole run got one.

The client logs netsim: dead zone open secs=N when it opens. It notices the end on the first packet after the end time and then logs netsim: dead zone closed. Since the client keeps trying to reconnect during the dead zone, there is a packet soon after the end.

Time

Both models get their time handed to them: the time since the transport was created, from tokio’s clock. This has two effects:

  • The models can be tested without waiting. The unit tests feed them thousands of packets at made-up times and check the results (for example: 4G loses between 0.4% and 2% of packets, and some losses come in a row).
  • A real run depends on real timing. Which packet arrives during a dead zone, or finds the queue full, depends on when irsync sends it, which depends on CPU load and thread scheduling. That is why a seed does not replay a run packet for packet.

The daemon is one process for the whole run, so its downlink model runs for the whole run too. Its speed changes and video bursts carry on across iterations, including the time between them. Each client is a new process with a fresh uplink model and a fresh outage model.

Seeds and streams

All random choices come from seeded generators (ChaCha8), one per model: one for the link and, on the client, one for the outages. Each generator’s seed is made from four things:

  • the run’s seed (--seed),
  • the side (client or daemon),
  • the stream number,
  • the purpose (link or outages).

fault_seed in crates/irsync/src/net/netsim/mod.rs mixes these one after another with splitmix64, a standard way to scramble a number so that inputs that differ in any part give unrelated outputs.

The rig numbers streams like this:

Processsidestream
the daemondaemon0
the ping round’s clientclient0
iteration i’s clientclienti

So each iteration has its own fault schedule, and that schedule does not depend on how many iterations ran before it: iteration 5 of seed 3 gets the same draws whether the run has 5 iterations or 50. A test checks that 10 seeds times 10 streams give 100 different seeds for each purpose. Simpler mixing makes many schedules come out the same; see call 5 in NETSTRESS_DECISIONS.md.

What irsync does during a dead zone

The rig gives the client --timeout 10 (under the real profiles) and --reconnect 5m. A typical 4G dead zone of, say, 40 s then goes like this:

  0 s   dead zone opens. Every packet in both directions is dropped.
        QUIC resends and sends keep-alives (every 5 s); all are dropped.
 10 s   client: "no activity; dropping the connection secs=10"
        client: "session failed", "connection lost; reconnecting"
        The client keeps trying to connect again, inside its 5 minute window.
 40 s   dead zone ends. The next connection attempt gets through.
        client: "netsim: dead zone closed"
        client: "session started session=<same id> resumed=true"
        The sync carries on where it stopped; partly sent files are resumed.

The daemon notices the old connection is gone (it logs connection failed: control stream: connection lost) and accepts the new one. Its QUIC idle timeout is 60 s.

Why the numbers fit together:

  • --timeout 10 is longer than the longest handover (2 s), so a handover never forces a reconnect, and shorter than the shortest dead zone (20 s), so a dead zone always does.
  • --reconnect 5m is far longer than the longest dead zone (60 s), so the client never gives up because of the dead zone itself.

The sender waits for the receiver to confirm each piece of a file it sent, with no time limit of its own: on a slow link, many pieces share the line and confirmation can take minutes. A fixed limit there fails healthy pushes over slow uplinks, as the first sweeps in NETSTRESS_DECISIONS.md show. A dead peer still ends the wait, through a lost connection.

How the rig judges a run

On top of irsync-stress’s checks (client exit, manifests, fileset check), the rig reads each iteration’s client log (netlog.rs in crates/netstress/src). It removes the colour codes, then walks the lines in order:

  • netsim active: the fault layer was on.
  • netsim: dead zone open: count a dead zone; from here until the next session started, the client is “in a dead zone”.
  • connection lost; reconnecting outside a dead zone: count a stray reconnect. Inside a dead zone, reconnects are expected and not counted.
  • session started: note its session= id (the first one is the sync’s session) and its resumed= value. If it comes after a dead zone, says resumed=true and has the first session’s id, count the dead zone as resumed. Either way, the dead zone part is over.

The session started line also carries a session_id= and a resumed= in its prefix (from the logging context), which can differ from the event’s own values after a reconnect. The parser only reads what comes after the words session started.

The iteration then fails with a reason when:

  1. netsim active is missing, or
  2. there was any stray reconnect, or
  3. more dead zones opened than were resumed.

Exit codes for the whole run (report.rs):

  • 1 if any iteration failed, or a .irsync.*.part file was found anywhere in either tree after the daemon stopped;
  • otherwise 3 if the profile has dead zones but no iteration logged one;
  • otherwise 0.

Exit 2 comes from anything that stops the rig before it can judge: a missing or non-fault irsync, a daemon that does not log netsim active within 15 s or dies, a failed ping round, or a client exit other than 0 or 23.

The counts

Each transport counts what happens to its packets and logs it at warn every 10 s while traffic flows and once when the transport is dropped:

netsim: counts sent=4814 queue_drops=0 loss_drops=0 outage_drops=0 send_errors=0 truncated=0

The rig does not judge these; they are there for a person reading a failure. They answer “did the network do what the profile says, or something else?”. For example, losses far above what the profile should give point at the fault layer; a stall with no drops at all points at irsync. The meaning of each count is in the user guide.

The final line is best effort: a process that exits without closing its endpoint, like the daemon when the rig stops it, skips it, and its last 10-second line is the latest one.

Simplifications

Things the model does not do, on purpose or for now:

  • The queue is a byte count, not a list of packets. Waiting time is the bytes in the queue divided by the full link speed. While the video holds the queue, irsync’s bytes above the video’s level actually drain at irsync’s 6 Mbit/s share, so the model’s delay for them is a little lower than a strict model would give.
  • Each side shapes only what it sends, and the two directions are independent. Real links sometimes couple them (a busy downlink delaying uplink acknowledgements); this model does not.
  • The daemon’s downlink is one link for the whole run, shared by whichever client is connected. Only one client runs at a time, so this does not matter for the rig.
  • Outages are only on the client. The daemon’s transport never cuts the link; the client’s drops both directions.
  • No NAT, relays, address changes or path changes. The fault layer only decides what happens to packets on one path between two fixed addresses.
  • IPv4 and loopback only.

Where the code is

CodeWhat it does
crates/irsync/src/net/netsim/mod.rsThe variable, profile names, seeds (fault_seed), the address format, netsim active.
crates/irsync/src/net/netsim/profile.rsThe numbers of every profile.
crates/irsync/src/net/netsim/link.rsThe link model: queue, speed, video, loss, delay.
crates/irsync/src/net/netsim/outage.rsHandovers and the dead zone.
crates/irsync/src/net/netsim/transport.rsThe iroh custom transport: sending, delivering, receiving, counts.
crates/irsync/src/net/endpoint.rs, daemon.rs, main.rs, build.rsThe hooks into irsync.
crates/netstress/src/run.rsThe rig’s run: tools check, daemon, ping, iterations, partial files.
crates/netstress/src/netlog.rsReading a client log for the network story.
crates/netstress/src/report.rsHeader, iteration lines, footer, exit codes.
crates/netstress/src/profile.rsRun defaults and client timeout per profile.
crates/netstress/src/cli.rs, run_file.rsCommand line and run.toml.
crates/netstress/tools/sweep.shMany runs at once.
crates/stressThe loop, layout, daemon handling and checks the rig reuses.

Performance

How to find out where irsync spends its time, and how to tell whether a change made it faster. Watch a transfer with telemetry covers irsync’s own timings; this page adds the method and the system tools.

Method

  1. Measure before changing anything. Pick one workload that shows the problem and write down its numbers on the current commit. A guess about where the time goes is a hypothesis, not a finding: the cost is often somewhere no one expects (SQLite re-preparing a statement on every call, for example; see Known costs).
  2. Keep the workload fixed and reproducible. Generate the tree with filegen from a fixed seed, run the daemon and the client on the same machine with release builds, and reset the state the run depends on (the destination tree, and the index and resume state described in Files and state) the same way every time. Use an idle machine: on a busy one, single runs of the same binary vary by up to 2x.
  3. Compare binaries, not commits in your head. Build each version you compare into its own file (cp target/release/irsync /some/dir/irsync-old) and interleave their runs: old, new, old, new. Check that each run did the same work (-v shows files and bytes transferred) and that the trees match afterwards (diff -r), or the faster run may simply have done less. The Overhead benchmark of the telemetry is a worked example: interleaved runs, pooled medians, and CPU time reported beside wall time.
  4. Prefer counts to times. CPU time, context switches and syscall counts vary far less between runs than wall time, and they say what changed. Report wall time too, but over several runs.
  5. Find the cause before fixing it. Go from the coarse to the fine: the -vv summary for the phase, perf stat for CPU against waiting, perf record for the hot code, strace -c for the syscalls. When a profile shows a cost but not its caller, count the calls per call site with temporary code (a counter keyed by #[track_caller]’s location works well), then remove it.
  6. Change one thing, then measure again with the same workload and the same commands. Bisect when a regression’s cause is unclear: build the commits in between with git worktree and run each.
  7. Record the result in the commit message: the workload, the numbers before and after, and what did not change.

Host setup for perf

Linux restricts what an unprivileged perf may see. Two sysctls matter:

SettingValue neededWhy
kernel.perf_event_paranoid1 or lowerLets your user record kernel samples of its own processes. At 2 perf sees user space only; some distributions default higher still, which blocks unprivileged perf altogether.
kernel.kptr_restrict0Shows kernel symbol addresses in /proc/kallsyms. At 1, your user sees all-zero addresses, so perf records kernel samples but cannot name them.

Check the current values first, so you can restore them:

sysctl kernel.perf_event_paranoid kernel.kptr_restrict

One-off, until the next reboot:

sudo sysctl kernel.perf_event_paranoid=1
sudo sysctl kernel.kptr_restrict=0

Persistent, applied at every boot:

sudo tee /etc/sysctl.d/99-perf.conf <<'EOF'
kernel.perf_event_paranoid = 1
kernel.kptr_restrict = 0
EOF
sudo sysctl --system    # applies it now as well

To undo it, delete /etc/sysctl.d/99-perf.conf and reboot, or set the values you noted back with sysctl.

head -2 /proc/kallsyms shows non-zero addresses once kptr_restrict is in effect.

These settings weaken the kernel’s defences slightly. Every local user can then profile its own processes in kernel mode and read kernel addresses, which makes kernel exploits easier. That is fine on a single-user development machine. Do not leave them set on a shared or production host.

Tools

-vv summary. Add -vv to the client. The block at the end of each session shows wall time, busy time per activity (walk, plan, hash, write, waiting on the peer, …), CPU and wire bytes, for the client and the daemon. Start here to see which phase and which side to look at.

Telemetry. --debug-addr serves span timings and flamegraph input over HTTP. These are irsync’s own spans, so they show time per phase rather than per function. See Watch a transfer with telemetry.

perf stat. CPU time and context switches for a whole process:

perf stat -e task-clock,context-switches irsync daemon --config irsync.toml

High CPU points at computation. Many context switches point at threads handing work to each other (with tokio, every spawn_blocking round trip costs futex wake-ups). Wall time much longer than CPU time means the process is waiting: on disk, on the network, or on a lock.

perf record. Where the CPU time goes, with call stacks. Build with frame pointers into a separate target directory, so the normal build stays cached:

RUSTFLAGS="-C force-frame-pointers=yes" CARGO_TARGET_DIR=target/fp \
  cargo build --release -p irsync
perf record -F 999 -g -o perf.data target/fp/release/irsync daemon --config irsync.toml
perf report -i perf.data --no-children

The prebuilt standard library has no frame pointers, so stacks that pass through it can be cut short. perf record --call-graph dwarf avoids that, at the cost of much larger data files. Kernel frames need the host setup above.

strace -c. Syscall counts and errors per syscall:

strace -f -c -o strace.txt irsync daemon --config irsync.toml

The errors column is often the useful part: tens of thousands of failing calls (a mkdir getting EEXIST, a statx getting ENOENT) are work that can usually be skipped. strace slows the traced process by an order of magnitude, so use its counts, not its times.

Syscalls per call site. When strace -c shows a count worth cutting, find which code makes the calls. strace -k prints a stack for every syscall, and tools/syscall-sites.py groups the calls by syscall, result and the innermost irsync frames. Use a small workload (a few hundred files), since every call writes a full stack:

CARGO_PROFILE_RELEASE_DEBUG=line-tables-only CARGO_TARGET_DIR=target/dbg \
  cargo build --release -p irsync
strace -f -k -e trace=statx,fstat,newfstatat -o trace.txt \
  target/dbg/release/irsync daemon --config irsync.toml
# ... run the client against it, then stop the daemon ...
tools/syscall-sites.py trace.txt target/dbg/release/irsync

Each output line is a count, the syscall and where it was called from, innermost frame first (the line numbers depend on the build):

     142  statx ENOENT             part_exists (recv.rs:353) < open_from (recv.rs:560) < poll (session/recv_io.rs:461)
     142  statx (fd)               open_locked_part (recv.rs:435) < open_part_in_dir (recv.rs:464) < open_sized_part (recv.rs:1220)

Divide by the number of files to get calls per file, then look for one file paying for the same answer twice: two fstats of the same descriptor, an lstat whose result the next call would report anyway, a call whose outcome is already known. Count again after a change; the same command shows whether each site went away.

Two details the script handles:

  • strace prints a frame’s offset in the file, while addr2line wants a virtual address. The script adds the executable segment’s address minus its offset (readelf -lW), and steps each return address back by one so it lands in the call.
  • With -f, a call interrupted by another thread is printed as <unfinished ...> and later <... resumed>, with its stack after the resumed line. The script attaches it to the right call.

The line tables do not change the code, so counts from this build match the normal release build. -k needs an strace built with stack-trace support (strace -k -e trace=openat true prints stacks if it has it).

Known costs

  • SQLite re-preparing a statement. A statement whose plan depends on a bound value (?2 IS NULL OR path > ?2, LIMIT ?3) can be re-prepared on every execution. In perf report this shows up as sqlite3Reprepare. Spell such variants into the SQL text, so each one is prepared and cached once.
  • WAL commits empty other connections’ page caches. Each commit makes every other connection reread the pages it touched. Fewer, larger commits (the index writer batches what arrives within 10 ms, LINGER in crates/irsync/src/index.rs) and memory-mapped reads (PRAGMA mmap_size) keep that cheap. A larger cache_size does not help, because the misses are invalidations, not capacity.
  • Blocking-pool round trips per file. With tens of thousands of small files, the number of spawn_blocking calls per file matters more than what each one does. Doing a file’s related blocking steps in one call saves a thread hand-off, with its futex wake-ups, per step.
  • Syscalls that are expected to fail. Creating a directory that already exists, or checking a path that is not there, costs a syscall per file. Trying the operation that usually succeeds, and recovering only when it fails, removes them.

Design records

The book describes irsync as it is. Why it is that way is recorded in docs/ in the repository: one decisions file per component, each entry naming what was decided, why, and what it costs if the ruling turns out to be wrong. Where a decisions file and the code disagree, the code is what shipped.

RecordWhat it holds
IRSYNC_DECISIONS.mdirsync’s design and implementation decisions that the code does not show (its numbered rulings), and the points knowingly left open.
FILESET_DECISIONS.mdThe rulings made while building fileset.
FILEGEN_DECISIONS.mdThe rulings made while building filegen.
IRSYNC_HARNESS_DECISIONS.mdThe rulings made while building irsync-stress, the irsync bugs the harness found, its acceptance run and its sweeps.
NETSTRESS_DECISIONS.mdThe calls made while building irsync-netstress and its fault layer, and the results of the real runs.

docs/superpowers/ is history: the specs (specs/), implementation plans (plans/) and progress ledgers (ledgers/) that features were built from. They are not updated as the code changes; read them for the reasoning at the time, and the book and the code for the current state.

Open ideas, in no particular order, are in TODO.md.

Releasing

A release starts when you push a tag. The rest is done by GitHub Actions. This page says how to cut a release, what the workflows do, what to do when one fails, and what to set up once.

Only three kinds of tag release anything:

TagWhat it isWhere it goes
vX.Y.ZA stable releaseGitHub Release, Homebrew, apt, dnf
vX.Y.Z-beta.NA betaGitHub Release only
vX.Y.Z-alpha.NAn alphaGitHub Release only

Any other tag that starts with v and a digit stops with an error within seconds, before the tests. Nothing is published.

Cutting a release

  1. On an up-to-date main with no uncommitted changes, run the bump script with the new version, without the v:

    .github/scripts/bump-version.sh 1.2.3
    

    It sets the version in Cargo.toml ([workspace.package]) and packaging/dist/dist.toml, updates Cargo.lock to match, and commits the three files as Release v1.2.3. It doesn’t push or tag. It prints the commands for the next steps.

  2. Push to main: git push origin main.

  3. Wait for CI on main to go green. That includes the release build jobs, which run the Linux release build the way the release will.

  4. Tag the commit and push the tag. Use an annotated tag (-a):

    git tag -a v1.2.3 -m "irsync 1.2.3"
    git push origin v1.2.3
    

For a pre-release, use a version such as 1.2.3-beta.1 or 1.2.3-alpha.1, and the tag v1.2.3-beta.1.

If you change the version by hand instead, keep all three files in step. These checks catch a mismatch:

  • A test (crates/irsync/tests/release_version.rs) fails if Cargo.toml and dist.toml differ.
  • CI builds with --locked, so it fails if Cargo.lock is out of date. The release build uses --locked too, and would fail later.
  • The release gate stops within seconds if the two files don’t match the tag.

What the workflow does

Pushing the tag starts .github/workflows/release-gate.yml. It is the only way a release starts. It does this, in order:

  1. Check. It checks the tag name, and that the version in Cargo.toml and packaging/dist/dist.toml is the tag without the v. This takes seconds.
  2. Test. It runs ci.yml on the tagged commit, with the musl release targets added. If anything fails, it stops. Nothing is published.
  3. Release. It checks that the tag still points at the commit that was tested. Then it launches release.yml for the tag and waits for it. release.yml builds irsync and fileset for Linux x86_64, Linux arm64 and macOS on Apple Silicon. It publishes the GitHub Release with the tarballs, checksums and the install script. For stable tags it also pushes the Homebrew formula to irsync-dev/homebrew-tap.
  4. Packages (stable tags only). .github/workflows/packages.yml builds the .deb and .rpm files from the released Linux tarballs. It signs the .rpm files, adds everything to irsync-dev/packages, signs the apt and dnf metadata and pushes. It keeps the newest 3 versions. GitHub Pages serves the result at dist.irsync.org. Then it attaches the same files, signed .rpm files included, to the release.
  5. Notes. It adds GitHub’s list of changes to the release notes, under the heading ## What's changed. For a stable release the list starts at the previous stable release, so it covers the betas in between too.

The install script site/install.sh (served as irsync.org/install.sh) picks the newest release for its channel: stable by default, --beta for betas and stable, --alpha for all. Other arguments go to the installer that release.yml built. The installer puts the programs in ~/.local/bin, and has no updater. It writes a small receipt file, ~/.config/irsync/irsync-receipt.json; it is harmless. To stop it editing the shell’s PATH setup, set IRSYNC_NO_MODIFY_PATH=1.

The release workflow is generated

.github/workflows/release.yml is made by dist generate (cargo dist 0.34.0). Never edit it by hand. The settings are in dist-workspace.toml, and the package is described in packaging/dist/dist.toml. After you change dist-workspace.toml, run:

dist generate

and commit the result.

release.yml only starts when the gate launches it. Never launch it by hand from the Actions tab. That skips the tests.

If a release fails

The check failed. Nothing ran. Usually the version in the two files does not match the tag. Delete the tag (git push origin --delete v1.2.3 and git tag -d v1.2.3), fix the version on main, and tag again. With tag protection, only people on its bypass list can delete the tag.

The test step failed. Nothing was published. If it was a flaky test, use “Re-run failed jobs” on the gate run: the tag and the commit stay the same, so that is fine. If the failure is real, fix it on main, then tag a new patch version (for example v1.2.4). Don’t move the tag. If you move a tag after pushing it, the gate refuses to release it, because the tests ran on a different commit.

The release step failed. Look at the release.yml run it launched. The link is in the gate’s log. If the gate could not find the run, look in the Actions tab under the release workflow: it may still be running.

  • If the GitHub Release was not created, treat it like a failed test: fix, then tag a new patch version.
  • If the GitHub Release was created, the release is public, but the gate stopped before the packages and the notes. This happens when the Homebrew push failed, or when the gate lost track of the release.yml run. If the Homebrew push failed, fix the cause (often the HOMEBREW_TAP_TOKEN) and use “Re-run failed jobs” on that release.yml run. That runs only the Homebrew step and the jobs after it, not the release again. Then finish the release with the resume workflow (see below).

The packages step failed. Re-run that job from the gate run, or use the resume workflow. It is safe to run again. If the packages repo already has this version, it builds nothing and changes nothing there; it only attaches any files the release is still missing.

The notes step failed. Re-run that job, or use the resume workflow. It does nothing if the heading is already there.

Two traps:

  • Cancelling the gate run does not stop release.yml once it has been launched. Cancel that run too, from the Actions tab.
  • Re-running the gate’s release job launches a second release.yml. If the GitHub Release already exists, the second run fails when it tries to create it. Re-run only the packages or notes job, not release, or use the resume workflow.

Finishing a release with the resume workflow

.github/workflows/release-resume.yml finishes a release that already exists. It runs the same packages and notes steps as the gate. It never builds or publishes a release. Start it on main, in the browser (Actions, Release resume, Run workflow) or with:

gh workflow run release-resume.yml --ref main -f tag=v1.2.3

It checks that the tag is a release tag and that its GitHub Release exists and is published. For a stable release it runs the packages step and the notes. For a pre-release it only adds the notes.

With -f dry-run=true it builds and signs the packages, for any release, pre-releases too. It checks that the token may push to the packages repo, but publishes nothing: no files on the release, no push, no notes. The packages and the updated repo are kept as artifacts of the run, for you to look at.

One-time setup

Do this once, before the first release.

Repositories. Create two public repositories in the irsync-dev organisation. Create both with a README, so they have a main branch:

  • homebrew-tap, for the Homebrew formula.
  • packages, for the apt and dnf repo.

GitHub Pages. In the packages repository, turn on Pages and serve the default branch. Set the custom domain to dist.irsync.org and turn on “Enforce HTTPS”. You don’t fill the repository by hand. Each stable release copies index.html, irsync.repo and CNAME from packaging/repo/ into it, and exports the public key as irsync.asc (for dnf) and irsync.gpg (for apt).

DNS. Add a CNAME record that points dist.irsync.org at irsync-dev.github.io. If the DNS is on Cloudflare, set the record to “DNS only” (grey cloud), so GitHub can issue the HTTPS certificate.

Signing key. Make a GPG key with the user ID irsync releases <releases@irsync.org>, step by step in Making the signing key. Set up the releases@irsync.org mailbox too, so mail to that address reaches someone. The workflow uses the fingerprint of the key it imports as GPG_KEY_ID, so there is nothing else to set.

Token. Make a token that can push to homebrew-tap and packages and nothing else. A fine-grained personal access token with “Contents: read and write” on those two repositories works.

Secrets. In the irsync-dev/irsync repository, under Settings, Secrets and variables, Actions, add four secrets:

SecretWhat it holds
PACKAGES_GPG_PRIVATE_KEYThe private signing key: private-key.asc from Making the signing key
PACKAGES_GPG_PASSPHRASEThe key’s passphrase: passphrase.txt, with no newline at the end
PACKAGES_REPO_TOKENThe token, for pushing to irsync-dev/packages
HOMEBREW_TAP_TOKENThe token, for pushing to irsync-dev/homebrew-tap (cargo dist uses this name)

You can use the same token for both token secrets.

Tag protection (recommended). Add a rule that protects tags matching v*, so only maintainers can push or move release tags. Step by step in Protecting the release tags.

The first release

Do the one-time setup first. Then:

  1. Merge to main. The gate can only launch release.yml once it is on the default branch, so the merge comes first. The install steps in the README and the book go live with it. They say that Homebrew, apt and dnf start with v0.1.0, and that --alpha works before that.

  2. Put the install script on irsync.org. The merge deploys the site, with install.sh, to staging. Check that https://dev.irsync.org/install.sh is there, then promote the site (see Promoting to irsync.org).

  3. Rehearse with an alpha. Set the version in both files to 0.1.0-alpha.1, push to main, and push an annotated tag:

    git tag -a v0.1.0-alpha.1 -m "irsync 0.1.0-alpha.1"
    git push origin v0.1.0-alpha.1
    

    Check that:

    • the gate passes with the annotated tag;
    • the GitHub Release is marked as a pre-release and has the tarballs, the checksums and the installer;
    • its notes end with ## What's changed;
    • the install script with --alpha installs it, and without --alpha says there is no stable release yet;
    • nothing went to Homebrew, apt or dnf.
  4. Dry-run the packages on the alpha. An alpha skips Homebrew, apt and dnf, so the steps only stable releases run have not run yet. Run them without publishing:

    gh workflow run release-resume.yml --ref main -f tag=v0.1.0-alpha.1 -f dry-run=true
    

    This uses the GPG secrets, the packages repo token, nfpm and Ubuntu’s rpm. Check that the run passes. Download its two artifacts and look at them: the .deb files list /usr/bin/irsync and /usr/bin/fileset (dpkg-deb -c), and the .rpm files are signed (rpm -Kv, after rpm --import of irsync.asc from the repo artifact).

  5. Check the Homebrew token. Nothing has used HOMEBREW_TAP_TOKEN yet. Push a throwaway branch to the tap with it, then delete the branch. When git asks, give any user name and the token as the password. The credential.helper= setting stops git from using your own login instead:

    git clone https://github.com/irsync-dev/homebrew-tap
    cd homebrew-tap
    git -c credential.helper= push origin HEAD:refs/heads/token-check
    git -c credential.helper= push origin --delete token-check
    
  6. Cut v0.1.0. Set the version in both files to 0.1.0 and follow Cutting a release. Then check the Homebrew formula, the apt and dnf repo at dist.irsync.org, and the signed .rpm files on the release.

The packages repo grows

Every release adds a commit with new package files to irsync-dev/packages. Pruning removes old files from the tree, but git keeps them in the history, so the repository keeps growing. Pages serves only the current tree, so the history is not needed. Once in a while, when no release is running, replace it with a single commit:

git clone https://github.com/irsync-dev/packages
cd packages
git checkout --orphan fresh
git commit -m "Packages, history squashed"
git push --force origin fresh:main

If main is protected against force pushes, allow it for this push.

Protecting the release tags

Pushing a v* tag starts a release, and the release workflow trusts the commit the tag points at. Without protection, anyone with write access can push a release tag, or move or delete one after the fact. A tag ruleset limits that to the people you choose. GitHub’s older “tag protection rules” are gone; rulesets replace them.

Nothing in the release workflows creates, moves or deletes tags, so the ruleset doesn’t get in their way. They only read the tag you pushed.

1. Create the ruleset. In irsync-dev/irsync, go to Settings, then Rules, then Rulesets. Click “New ruleset”, then “New tag ruleset”.

2. Name and enforcement. Name it Release tags. Set “Enforcement status” to “Active”. (“Evaluate” only logs what it would block, and is not available on every plan.)

3. Bypass list. Click “Add bypass” and pick the “Repository admin” role. If someone should cut releases without being an admin, add the “Maintain” role too. Leave both on “Always allow”. Only people with these roles can then push, move or delete release tags.

4. Target tags. Under “Targets”, click “Add target”, then “Include by pattern”, and enter v*. This matches every tag that starts with v, which covers both v0.1.0 and v0.1.0-alpha.1.

5. Rules. Tick these four:

RuleWhat it stops
Restrict creationsPushing a new v* tag, which would start a release
Restrict updatesMoving an existing tag to another commit
Restrict deletionsDeleting a tag
Block force pushesOverwriting a tag with git push --force

Leave the other rules off. Click “Create”.

Or with the GitHub CLI. This creates the same ruleset. The number 5 is GitHub’s ID for the “Repository admin” role (4 is “Write”, 2 is “Maintain”):

gh api --method POST repos/irsync-dev/irsync/rulesets --input - <<'JSON'
{
  "name": "Release tags",
  "target": "tag",
  "enforcement": "active",
  "bypass_actors": [
    { "actor_id": 5, "actor_type": "RepositoryRole", "bypass_mode": "always" }
  ],
  "conditions": { "ref_name": { "include": ["refs/tags/v*"], "exclude": [] } },
  "rules": [
    { "type": "creation" },
    { "type": "update" },
    { "type": "deletion" },
    { "type": "non_fast_forward" }
  ]
}
JSON

Then open the ruleset in Settings, Rules, Rulesets, and check that the bypass list shows “Repository admin”.

6. Check it. List the rulesets:

gh api repos/irsync-dev/irsync/rulesets --jq '.[] | "\(.name): \(.target), \(.enforcement)"'

This should print Release tags: tag, active. Then push a tag that matches but is not a release version. The release gate starts on any tag starting with v followed by a digit, so the test tag has none:

git tag v-ruleset-check
git push origin v-ruleset-check

As an admin you can still push. Look for Bypassed rule violations for refs/tags/v-ruleset-check in the output: it shows the rule is active and you are on the bypass list. Delete the tag again:

git push origin --delete v-ruleset-check
git tag -d v-ruleset-check

Someone with only write access gets Cannot create ref due to creations being restricted for the same push.

Making the signing key

The key signs the apt and dnf repositories at dist.irsync.org. The steps below make it, test it the way the workflow uses it, and leave you with the files for the two GPG secrets. They take about ten minutes.

The key is RSA 4096, can only sign, has no subkeys and never expires:

  • RSA works with every apt and rpm we care about, including older RHEL rpm versions that can’t check newer key types.
  • The workflow signs with the first secret key it finds, so one key with no subkeys is all it needs.
  • apt users keep the public key in a file on their machine. If the key expired, apt update would fail for everyone until they downloaded it again. The revocation certificate covers a lost or leaked key instead.

The passphrase is long and random. Nobody types it; it lives only in the secret and in your backup.

1. A separate keyring. Use a machine you trust, and keep the key out of your everyday keyring. GNUPGHOME tells gpg which keyring to use, for this terminal only, so run every later step in the same terminal:

umask 077
mkdir ~/irsync-signing-key
cd ~/irsync-signing-key
export GNUPGHOME="$PWD/gnupg"
mkdir -m 700 "$GNUPGHOME"
gpg --list-secret-keys    # prints nothing: the keyring is empty

2. The passphrase. 40 random characters, with no newline at the end. The workflow uses the secret byte for byte, so a trailing newline would become part of the passphrase and signing would fail:

gpg --gen-random --armor 1 30 | tr -d '\n' > passphrase.txt
wc -c passphrase.txt      # 40

3. The key. rsa4096 is the key type, sign means it can only sign, and never is the expiry date. --pinentry-mode loopback with --passphrase-file takes the passphrase from the file instead of a password prompt:

gpg --batch --pinentry-mode loopback --passphrase-file passphrase.txt \
    --quick-generate-key 'irsync releases <releases@irsync.org>' rsa4096 sign never
FPR=$(gpg --list-secret-keys --with-colons | awk -F: '$1 == "fpr" { print $10; exit }')
echo "$FPR"
gpg --list-keys

FPR is the fingerprint, the key’s 40-character ID. gpg --list-keys shows one rsa4096 key with usage [SC], no expiry, and the user ID irsync releases <releases@irsync.org>.

4. Export the files.

gpg --batch --pinentry-mode loopback --passphrase-file passphrase.txt \
    --armor --export-secret-keys "$FPR" > private-key.asc
gpg --armor --export "$FPR" > public-key.asc
cp "$GNUPGHOME/openpgp-revocs.d/$FPR.rev" revocation.rev
head -1 private-key.asc   # -----BEGIN PGP PRIVATE KEY BLOCK-----
FileWhat it isWhere it goes
private-key.ascThe private key, still protected by the passphrasePACKAGES_GPG_PRIVATE_KEY, and your backup
passphrase.txtThe passphrasePACKAGES_GPG_PASSPHRASE, and your backup
revocation.revDeclares the key dead, even without the private keyYour backup only
public-key.ascThe public keyYour records; every stable release publishes it as irsync.asc and irsync.gpg

gpg made the revocation certificate together with the key. Anyone who has it can kill the key, so it never goes into GitHub.

5. Test the files the way the workflow uses them. The workflow imports private-key.asc into an empty keyring, takes the first fingerprint it finds and signs with the passphrase. Do the same in a second empty keyring:

export GNUPGHOME="$PWD/ci-test"
mkdir -m 700 "$GNUPGHOME"
gpg --batch --import private-key.asc
TEST_FPR=$(gpg --batch --list-secret-keys --with-colons | awk -F: '$1 == "fpr" { print $10; exit }')
[ "$TEST_FPR" = "$FPR" ] && echo "fingerprint matches"
echo test > test.txt
gpg --batch --yes --pinentry-mode loopback --passphrase-file passphrase.txt \
    --local-user "$TEST_FPR" --clearsign -o test.txt.asc test.txt
gpg --verify test.txt.asc

You should see fingerprint matches and Good signature from "irsync releases <releases@irsync.org>". A warning that the key is not certified with a trusted signature is normal. Then remove the test keyring:

gpgconf --kill gpg-agent
rm -rf "$GNUPGHOME" test.txt test.txt.asc
export GNUPGHOME="$PWD/gnupg"

6. The secrets. Reading from a file keeps the passphrase out of your shell history:

gh secret set PACKAGES_GPG_PRIVATE_KEY --repo irsync-dev/irsync < private-key.asc
gh secret set PACKAGES_GPG_PASSPHRASE  --repo irsync-dev/irsync < passphrase.txt
gh secret list --repo irsync-dev/irsync

In the browser instead, paste the whole of private-key.asc, including the BEGIN and END lines, and the 40 passphrase characters with nothing after them. GitHub never shows a secret again, so if you are unsure you pasted it right, set it again.

7. Back up, then clean up. Keep private-key.asc, passphrase.txt and revocation.rev somewhere safe outside GitHub, such as a password manager that takes attachments or an encrypted USB stick. Write the fingerprint (echo "$FPR") next to them: it is how anyone checks that a downloaded irsync.asc is the real key. Without the backup, losing the secret means a new key, and every user has to import it again.

Once you have checked that you can open the backup, delete the working folder:

gpgconf --kill gpg-agent
cd ~
rm -rf ~/irsync-signing-key
unset GNUPGHOME

8. Check it on a real run. An alpha doesn’t sign anything, so the first real use of the key is the dry run in The first release, step 4. A wrong passphrase secret fails there. After the first stable release, check that the published key is yours:

curl -fsSL https://dist.irsync.org/irsync.asc | gpg --show-keys

The fingerprint it shows must match the one you wrote down.

If the key leaks, mark it revoked where users fetch it, then rotate to a new key (below). In a throwaway keyring, import the public key and the revocation certificate, and export the result:

gpg --import public-key.asc revocation.rev
gpg --armor --export "$FPR" > irsync.asc
gpg --export "$FPR" > irsync.gpg

Commit these two files to the packages repository by hand. Anyone who fetches the key from then on gets it marked revoked, and the next stable release replaces both files with the new key. Users who already have the old key keep trusting it until they import the new one, so tell them (rotation step 4). If the key is lost with no backup, make a new key and rotate.

Rotating the signing key

  1. Make the new key, with the same user ID, as in Making the signing key.
  2. Put the new private key and passphrase into the PACKAGES_GPG_PRIVATE_KEY and PACKAGES_GPG_PASSPHRASE secrets.
  3. Cut a stable release. It signs the metadata with the new key and publishes the new public key as irsync.asc and irsync.gpg.
  4. Tell users to import the new key again. For apt, that means downloading irsync.gpg again to /etc/apt/keyrings/. For dnf, the .repo file fetches the key from irsync.asc; dnf asks to trust the new one.

Old packages stay signed with the old key until they are pruned from the repo (after 3 newer versions). Until then, users who have not re-imported the key may see signature errors on those files.

The user-facing install steps

The README, the book’s introduction and the fileset introduction list the ways to install. The apt and dnf commands are in packaging/repo/index.html (the page at dist.irsync.org). If you change them there, change them in the docs too.

This website

irsync.org has two parts, built from this repository into one directory: a landing page at / and this book at /book/.

Layout

PathWhat it holds
site/index.html, site/404.html, site/style.css, site/robots.txt, site/_headersThe landing page, the page served for an unknown URL outside /book/, and the files served next to them, copied as they are.
site/tokens.jsonThe design tokens: colours, type, spacing, radius, shadow.
site/tools/gen_tokens.py (tokens to CSS), strip_font_link.py (see Building), check.py (the checker) and their tests. Not deployed.
site/build.sh, site/serve.sh, site/deploy.shBuild, serve locally and deploy. Not deployed.
site/wrangler.jsoncThe settings both Cloudflare Workers are deployed with. Not deployed.
book/The mdbook: book.toml, the pages in book/src/, theme overrides in book/theme/.

Updating the design tokens

site/tokens.json is a verbatim copy of the design system’s project/tokens.json. To take a new version, replace the file with the design system’s file; do not edit it by hand. The build turns it into CSS custom properties named --ir-*, twice: book/theme/tokens.css (git-ignored) keyed on mdbook’s theme class, and tokens.css next to the landing page keyed on its data-theme attribute. Every colour, font stack, spacing, radius and shadow on the site comes from these properties.

Building

The build needs mdbook and Python 3:

site/build.sh

It empties target/site/, generates the token CSS, builds the book into target/site/book/ and copies the landing page files into target/site/. No font files ship: the site uses the system font stacks from the tokens. The empty book/theme/fonts/fonts.css keeps mdbook from copying its web fonts, and the build removes that stylesheet and its link from every book page. site/build.sh OUT builds into OUT instead; OUT must be under target/, because the build deletes it first. The check is on the resolved path, so a target/ that is a symlink to somewhere outside the checkout is refused too.

The checker

cargo build -p irsync
python3 site/tools/check.py --irsync target/debug/irsync target/site
python3 -m unittest discover -s site/tools -p 'test_*.py'

check.py prints one line per problem and exits non-zero if there is any. It enforces four things:

  • Links and anchors. Every relative href and src in the built HTML resolves to a file, and every #fragment to an id on the target page. External links are not fetched.
  • No fonts. No font file and no fonts/ directory is in the build.
  • Moved files. Documents that moved into the book (the list is MOVED_FILES in check.py) are not referred to, by path or by bare name, from any tracked file once they are gone. docs/superpowers/ is history and is skipped.
  • irsync flags. With --irsync, every --flag on a documented irsync command line (in a code block, or an inline code span starting with irsync ) and in the first column of the tables in Command line is one that the given binary lists in --help, of the top-level command or a subcommand. The book, site/index.html and README.md are checked.

Serving locally

site/serve.sh

It builds the site, serves target/site/ at http://localhost:9999/ and rebuilds whenever a file under book/ or site/ changes; open pages reload on their own. site/serve.sh PORT serves on another port. It needs Node.js: it runs chokidar-cli (the watcher) and browser-sync (the server) through npx, at the versions pinned at its top. Ctrl-C stops both.

The local server ignores _headers; the headers apply on Cloudflare only.

Staging and production

The site is served by two Cloudflare Workers that hold only static files, no code. Both are deployed with the settings in site/wrangler.jsonc:

WorkerDomainRole
irsync-devdev.irsync.orgStaging. Every deploy of main lands here.
irsync-pubirsync.orgProduction. Changes only when a staging build is promoted.

Promotion ships the files staging served: the staging build’s output is kept and uploaded to irsync-pub unchanged, nothing is rebuilt. Each build carries a BUILD file at its root holding the commit it was built from, so https://irsync.org/BUILD and https://dev.irsync.org/BUILD show what each one serves.

Workers rather than Cloudflare Pages, because a Cloudflare API token can be limited to a single Worker, while a Pages token can change every Pages project in the account. Each Worker gets its own deploy token, so the token that staging deploys with cannot touch production.

One-time setup

A token limited to one Worker can deploy new files to it, but cannot create the Worker or attach its domain. So these steps are done once by someone with full access to the Cloudflare account (npx wrangler login), and site/wrangler.jsonc leaves the domains out, so deploys never try to change them.

  1. Create both Workers by deploying to them once, from a checkout with a built site:

    site/build.sh
    npx wrangler deploy --config site/wrangler.jsonc --name irsync-dev --assets target/site
    npx wrangler deploy --config site/wrangler.jsonc --name irsync-pub --assets target/site
    
  2. Attach the domains: in the dashboard, Workers & Pages, the Worker, Settings, Domains & Routes, Add, Custom domain: dev.irsync.org on irsync-dev and irsync.org on irsync-pub. Cloudflare creates the DNS records; irsync.org must be a zone in the same account.

  3. Create two API tokens, each with the Workers role Editor on one Worker only: one for irsync-dev, one for irsync-pub. Editor can deploy new versions of that Worker and nothing else.

  4. Store them, with the account ID (npx wrangler whoami prints it), as repository secrets:

    gh secret set CLOUDFLARE_API_TOKEN_DEV
    gh secret set CLOUDFLARE_API_TOKEN_PUB
    gh secret set CLOUDFLARE_ACCOUNT_ID
    

Deploying from GitHub

This is the normal way. .github/workflows/site.yml has two jobs.

The staging job runs on every push to main that touches book/, site/, README.md, the workflow, or what the checker reads beyond them (crates/, proto/, docs/, .githooks/, tools/). It runs the tool tests, builds the site, runs the checker, keeps target/site as the run artifact site, and deploys it to irsync-dev. If a check fails, nothing is deployed.

The promote job runs only when the workflow is started by hand on main. It downloads the site artifact of the newest successful push run on main, deploys it to irsync-pub and writes its BUILD to the job summary.

The repository secrets CLOUDFLARE_API_TOKEN_DEV, CLOUDFLARE_API_TOKEN_PUB and CLOUDFLARE_ACCOUNT_ID hold the credentials; each deploy step sees only its own Worker’s token.

Promoting to irsync.org

Look over dev.irsync.org first, then start the promote job, either in the browser (Actions, Site, Run workflow) or with:

gh workflow run site.yml --ref main

To follow it, wait a few seconds for the run to appear, then:

gh run watch $(gh run list --workflow site.yml --event workflow_dispatch \
  --limit 1 --json databaseId --jq '.[0].databaseId')

When it has finished, check that irsync.org serves the staging build, still answers an unknown URL with a 404, and is not marked noindex:

curl https://irsync.org/BUILD                    # the same commit as the next line
curl https://dev.irsync.org/BUILD
curl -sI https://irsync.org/nope | head -1       # HTTP/2 404
curl -sI https://irsync.org/ | grep -i x-robots  # prints nothing

The last check matters most: a noindex on irsync.org would drop the site from search engines.

The job promotes the newest CI build, not whatever dev.irsync.org serves at that moment. The two differ only if someone deployed staging by hand with site/deploy.sh staging after the last CI build; the BUILD comparison above shows it. Push, or re-run the newest staging run, to bring staging back to a CI build before promoting.

Artifacts expire after the repository’s retention period (90 days by default). When the newest staging build is older than that, the job fails with “no successful staging run on main” or cannot download the build; push, or re-run the newest staging run, and promote again.

Rolling back irsync.org

Every deploy is kept as a version of the Worker. To serve an older one again, open the dashboard, Workers & Pages, irsync-pub, Deployments, pick the version and roll back to it; or, with the irsync-pub token or a full-access login:

npx wrangler deployments list --name irsync-pub
npx wrangler rollback <version-id> --name irsync-pub

A rollback takes effect at once and does not touch staging. The next promotion replaces it.

Deploying from a developer machine

For when GitHub Actions is not available. site/deploy.sh runs the same checks and deploys. It uses wrangler through npx at the version pinned at its top, and takes the credentials from CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID, or from wrangler login. A token limited to one Worker deploys only to that Worker: staging needs the irsync-dev token and promote the irsync-pub one.

site/deploy.sh staging
site/deploy.sh promote

staging refuses a working tree with uncommitted or untracked changes. It builds target/site/, writes the HEAD commit to target/site/BUILD, builds irsync (cargo build -p irsync), runs the tool tests and the checker, and refuses to deploy when either fails. Then it deploys to irsync-dev and copies the build to target/site-staging/.

promote deploys target/site-staging/ to irsync-pub and prints its BUILD. It refuses without a target/site-staging/BUILD, and when that BUILD differs from https://dev.irsync.org/BUILD or cannot be compared with it: someone else may have deployed staging since, and promotion ships only what staging serves. Run the checks under Promoting to irsync.org afterwards.

Checking a new Worker

After the first deploy to each Worker, confirm that an unknown URL gets a 404 status and not the landing page:

curl -I https://dev.irsync.org/nope
curl -I https://irsync.org/nope

The first line of each answer should read HTTP/2 404. With not_found_handling set to 404-page in site/wrangler.jsonc, Cloudflare serves 404.html with that status for any path that is not a file.

Indexing

Staging is public but not indexed; production is indexed. Both serve the same files, so the difference lives in site/_headers, which Cloudflare applies per host: responses from dev.irsync.org carry X-Robots-Tag: noindex, and responses from irsync.org do not. site/wrangler.jsonc turns off the Workers’ workers.dev hosts and preview hosts; _headers marks those noindex too, in case one is turned on. site/tools/test_headers.py pins these rules.

There is no staging-only robots.txt. Promotion uploads staging’s files unchanged, and identical files cannot carry a different robots.txt per host. A Disallow: / would not help either: a crawler that may not fetch a page never sees its noindex header, and can still list the URL. The one robots.txt allows everything.