← writings

Two servers, one save file

Last night I went looking for a bug in Herdr. Not a typo. Not a lint warning. Not a feature request wearing a bug costume. I wanted something real: a bug the maintainers would be glad someone found, in a part of the program they care about, that I could show happening on the version people actually download.

I found two. This is the story of how, and what I learned about hunting bugs in a big codebase you have never seen before.

First, what Herdr is. It is a program for running coding agents in a terminal. There are three parts. A server is a program that runs in the background and does the real work. Here, the server owns the terminals. A client is the window you look at. Herdr's client attaches to the server, so you can close the window and the terminals keep running. And there is an API, a way for other programs to talk to the server by sending it short messages. Agents and scripts use it to open workspaces, make tabs, and create git branches. It is written in Rust, and the public repository has more than 5,000 issues and a very busy triage pipeline.

Herdr's three parts. A server in the middle owns the terminals. A client window attaches to it from the left. Agents and scripts talk to it from the right through a socket, which is a little file that two programs on the same machine use to pass messages. client window what you look at attaches server owns the terminals tab tab tab saves its state to session.json socket agents, scripts send JSON messages a socket is a small file two programs on one machine use to pass notes
The shape of Herdr. Both bugs live at the edges of the server: one where it saves, one where it takes orders.

Here is what came out of the evening.

IssueAreaWhat goes wrongTriage
#5217 saving and restoring Two servers can share one save file. A whole session's workspaces can vanish with no warning. p2, sessions, maintainer-needed
#5219 API / git worktree.create says "success" after creating an empty repository. p2, api

Both were triaged within minutes of filing. Both have tested fixes sitting on my fork, on branches named issue/5217-session-data-lock and issue/5219-worktree-base-separator. Why the fixes are on my fork and not in a pull request is the first interesting thing about this project.

The rules, before the code

Most open source projects will take a pull request from anyone. Herdr will not. Its contributing guide says, in short:

  • Pull requests are accepted only from maintainers and from people on a short approved list. Everyone else's are closed automatically, no matter how good they are.
  • For everyone else, the way to contribute is a bug report. It has to be something you personally reproduced, in the exact template, and it must not include a root cause or a proposed fix.
  • Feature ideas go to Discussions.
  • The guide speaks to coding agents directly and tells them to follow these rules even if their human asks otherwise.

Their reason is practical. Unsolicited pull requests, many written by agents looking for anything to change, had pushed all the checking work onto the maintainers. So they closed that door. Fixes come from agents the maintainers run themselves, working from good reports.

A decision picture. Who are you? If you are a maintainer or on the approved list, you may open a pull request. If you are anyone else, you file a bug report with no root cause and no fix. If you have a feature idea, it goes to Discussions. who are you? the contributing guide maintainer or on the approved list anyone else (that was me) someone with a feature idea pull request bug report reproduced, no fix inside Discussions
Herdr's door policy. For me the deliverable was never a merged change. It was a report good enough that their own pipeline picks it up.

This changed the job. The bug had to be visibly real on the released program, and the report had to describe what happens, not why. I kept a fix on my fork anyway, as a reference for whoever ends up writing the real one. It turns out that writing a fix is the best way to be sure you understand the bug, even if nobody merges it.

Audit broad, verify narrow

The codebase is large. Reading it top to bottom would have taken days. So I split it into four places where bugs tend to be expensive, and audited all four at the same time, each with the same narrow brief: follow real code paths, write down an exact way it could fail, rank by how bad that would be, try to make the worst one actually happen, and report nothing you cannot back up.

  1. Saving and restoring. How the session file gets written, what happens on a crash, how a running server hands off to a new one.
  2. The API and its socket. Who is allowed to connect, how big a message can be, what a bad message can do.
  3. Self-update and install. Whether downloads are checked, whether versions are compared correctly.
  4. Git and remote commands. How the program builds the commands it hands to git and ssh.

Three of the four came back saying roughly "this area is well guarded, here is the one thing that is not." That is what you want to hear. The API audit in particular found that the socket is locked down to the owner right after it is created, that a single request line is capped at 1 MiB, that messages carry a length and the length has a hard limit, that ssh targets are checked for a leading dash, and that remote commands go through a quoting step. When the easy wins are all gone, the findings that remain deserve attention.

Four audits run side by side on four areas: persistence, API, update, git. They produce five candidates. The candidates go one at a time through reproduction on the real 0.9.3 binary. Two pass and are filed. Three are set aside. audit broad (in parallel) verify narrow (one at a time) saving and restoring API and socket self-update and install git and remote commands 5 candidates ranked reproduce on the real 0.9.3 binary isolated config dir 2 filed 3 kept three audits came back mostly clean; the absence of easy wins is itself a signal
The method. Breadth first, so no one idea anchors the search. Then the slow part that cannot be parallel: making each candidate actually happen.

Then came the part that cannot be done in parallel: reproducing each candidate on the real thing. I downloaded the 0.9.3 release from GitHub, the same file a user gets, and ran it with its own throwaway config folder so nothing touched my real setup. Building the latest source needed Zig 0.16.0 for the vendored terminal core, which Homebrew does not ship, so the stable download was also simply the fastest way to get a baseline I could trust.

Bug 1: two servers, one save file

Herdr saves your layout, which workspaces are open, which tabs, which panes, into a file called session.json. Think of it as a notebook the server writes in every few seconds and reads from when it starts. If two servers are writing in the same notebook, you have a problem, and that is the bug.

Two answers to one question

A server needs to know which session it belongs to. That decides two things: which socket it listens on, and which folder it keeps its notebook in. Herdr answers these two questions in two different places, and the answers do not always agree.

// src/session.rs
pub fn data_dir() -> PathBuf {
    // keyed on HERDR_SESSION only
    data_dir_for(active_name().as_deref())
}

pub fn active_api_socket_path() -> PathBuf {
    if explicit_session_requested() {
        return api_socket_path_for(active_name().as_deref());
    }
    // HERDR_SOCKET_PATH
    if let Ok(path) = std::env::var(crate::api::SOCKET_PATH_ENV_VAR) {
        return PathBuf::from(path);
    }
    api_socket_path_for(active_name().as_deref())
}

The socket path listens to a setting called HERDR_SOCKET_PATH. The data folder, where the notebook lives, does not. It only looks at the session name. And the only check in the server's startup that stops a second copy from running is the moment it tries to claim the socket:

// src/server/headless/bootstrap.rs
Err(err) if err.kind() == io::ErrorKind::AddrInUse => {
    eprintln!("error: herdr server is already running");
    std::process::exit(1);
}

So: start a second server with a different socket path. It claims a fresh socket, the "already running" check passes, and it opens the same notebook the first server is still writing in.

Two servers, A and B. Each asks two questions: which socket, and which data folder. The socket question honors the HERDR_SOCKET_PATH override, so A and B get different sockets. The data folder question ignores it, so A and B get the same folder and the same session.json. server A server B HERDR_SOCKET_PATH set which socket? honors the override which socket? honors the override which folder? ignores the override socket A socket B (different) one session.json shared by both
Two resolvers for one identity. They agree by default and split under an override. Different sockets, same notebook.

Is this a realistic thing to do? Yes. HERDR_SOCKET_PATH is called a "low-level override" in the docs, but it is documented, it is in the lookup order on the socket API page, and the server puts it into the environment of every terminal it opens. Pointing a second server at a shorter socket path is not an exotic move.

What actually happens

I scripted it against both the 0.9.3 release and a fresh build of the latest source. Server A has two workspaces, A1 and A2. Server B starts with a different socket path and the same config home.

A workspaces: ['A1', 'A2']
session.json after A autosave: ['A1', 'A2']
B workspaces right after start: ['A1', 'A2']
    <- B restored a copy of A's live session
B workspaces now: ['B-only']
A workspaces still live: ['A1', 'A2']
session.json now (A still running): ['B-only']
    <- B's autosave replaced A's layout
== kill -9 A, stop B
A workspaces after restart: ['B-only']
    <- A1 and A2 are gone
A timeline in five steps. Step 1: A saves A1 and A2 to the notebook. Step 2: B starts and reads the notebook, so B now also has A1 and A2. Step 3: B's workspaces become B-only and B writes that to the notebook. Step 4: A is killed without saving. Step 5: A restarts, reads the notebook, and gets B-only. A1 and A2 are gone. A file B A1, A2 A1, A2 1. A saves A1, A2 A1, A2 2. B starts, copies A B-only B-only A1, A2 3. B saves over A's layout kill -9 4. A dies, no final save B-only B-only 5. A restarts. A1, A2 gone
The same run as a picture. Nothing warns anyone. The only trace is one line in B's log saying it restored two workspaces.

Three separate failures are stacked in that output:

  1. A double restore. B wakes up holding a copy of A's workspaces while A is still running them. If the option to resume agents on restore is on, that relaunches A's agents a second time with the same session IDs.
  2. Mutual overwriting. Every autosave from either server replaces the other's layout in the one file.
  3. Data loss. If A exits without a clean shutdown after B's last save, A comes back with B's layout. No warning appears in either window.

Why had no test caught this? Because the project's own integration tests always pair HERDR_SOCKET_PATH with a fresh config folder. The two overrides move together in the tests and separately in the wild.

The fix

The thing that matters for saving is the data folder, not the socket. So the data folder should be the thing that decides whether a second server may start. The tool for that is a lock: a small file that one program holds, and that the operating system refuses to hand to a second program while the first is alive. Like a key on a hook. If the hook is empty, you take the key. If not, someone is already inside.

I added a small module, src/server/data_dir_lock.rs, that takes a lock on a file called server.lock inside the session's data folder:

pub(crate) fn try_acquire(data_dir: &Path)
    -> Result<DataDirLock, DataDirLockError>
{
    std::fs::create_dir_all(data_dir)?;
    let path = lock_path(data_dir);
    let file = OpenOptions::new()
        .read(true).write(true).create(true).truncate(false)
        .open(&path)?;
    match file.try_lock() {
        Ok(()) => Ok(DataDirLock { path, _file: file }),
        Err(TryLockError::WouldBlock) =>
            Err(DataDirLockError::Held { path }),
        Err(TryLockError::Error(err)) => Err(DataDirLockError::Io(err)),
    }
}

File::try_lock is part of Rust's standard library since 1.89, works on both Unix and Windows, and was already used elsewhere in this codebase for the plugin registry. So: no new dependency, no platform-specific code, and a fix that looks like it was always there. Because the lock is held by the operating system, it is released the instant the process dies. A crash never leaves a stale lock behind.

With the fix. Server A holds server.lock inside the data folder. Server B starts, claims its own socket, then tries the lock, is refused, drops its socket, prints an error naming the session path, and exits with code 1. A side note: if A crashes, the operating system releases the lock by itself. data folder server.lock (held by A) server A running, holds lock server B asks, is refused drops its socket, prints the path, exits 1 if A crashes, the OS lets go of the lock on its own
The lock makes the data folder the single authority. The error message names the session path and points at the flag for starting a named session instead.

The server takes the lock after claiming its socket, so the familiar "already running" message still appears in the plain duplicate case, and before restoring anything, so a refused server never touches the notebook. On refusal it lets go of the socket it just claimed, prints an error naming the session path, suggests --session <name>, and exits with code 1.

There is one subtle case. Herdr can replace a running server in place: the old server hands its open terminals to a new process over a socket, so your sessions survive an upgrade. During that handoff two servers legitimately share a data folder for a moment. The old one stops saving the instant it commits the handoff and exits soon after. So the new server waits up to ten seconds for the lock after the commit. If the old server is slow to leave, the new one logs a warning and carries on rather than failing a handoff whose terminals it already owns.

The handoff window. The old server hands its terminals to the new server, commits, and stops saving. The new server then waits up to ten seconds for the lock. Normally the old server exits and the lock is released well within that window. If not, the new server warns and continues. old server holds the lock hands over the terminals new server owns the terminals now stops saving, exits waits up to 10 s for lock got it: normal start timed out: warn, go on the lock arrives after the commit, so an in-place replace still works
The one place two servers may share a folder on purpose, and how the fix stays out of its way.

Tests: four small ones on the lock itself, and a new integration test that starts two real server processes and checks that the second exits with code 1 and the right message, leaves no socket behind, and that the first server's session.json is untouched. A second integration test checks that a named session (HERDR_SESSION=other) still starts beside the default one, since named sessions get their own folders. The whole suite: 3875 tests passing, and the linter clean with warnings treated as errors.

Bug 2: the missing --

The second bug is small to describe and a classic of its kind.

A worktree is git's way of checking out a second branch of the same repository into a second folder, so you can work on two things side by side. Herdr's API has a call, worktree.create, that makes one. To do that it builds a git command. A command to a program is just a list of words, and this is how Herdr builds the list:

// src/worktree.rs
args.extend([
    "worktree".to_string(),
    "add".to_string(),
    "-b".to_string(),
    branch.to_string(),
    path.display().to_string(),
    base.to_string(),       // caller input, defaults to "HEAD"
]);

The last word, base, is whatever the caller sent. Herdr does nothing to it beyond what git does. And git, for this command, does not stop reading options when it hits the first ordinary word. Any word that starts with a dash is treated as an instruction, no matter where in the list it sits.

Programs that take options usually understand a special word, two dashes on their own: --. It means "everything after this is a name, not an instruction." It is how you delete a file called -rf. Herdr's command did not have one.

Two rows of words. Top row, before: git worktree add -b feat path --orphan. Git reads --orphan as an instruction and makes an empty branch. Bottom row, after: git worktree add -b feat -- path --orphan. Everything after the two dashes is a name, so git looks up a branch called --orphan, finds none, and refuses. before git worktree add -b feat <path> --orphan git: "that is an instruction" makes an empty branch, says ok after git worktree add -b feat -- <path> --orphan "everything after this is a name" git: "no branch called --orphan" refuses, nothing is created
One word changes what git thinks the last word is. Without it, the caller's input can become an instruction.

What actually happens

Against the 0.9.3 release, over the socket API, I sent a base of --orphan, which is a real git option meaning "start a branch with no history at all":

{"method":"worktree.create",
 "params":{"workspace_id":"w1","branch":"feat","base":"--orphan"}}
{"result":{"type":"worktree_created", ...
           "checkout_path":".../repo/feat" ...}}

Success, says Herdr. Then I looked at what it had made:

$ git -C .../repo/feat log --oneline
fatal: your current branch 'feat' does not have any commits yet
$ git -C repo worktree list
repo            716099d [main]
.../repo/feat   0000000 [feat]
$ ls -A .../repo/feat
.git

Git took --orphan as an instruction, made a branch with no commits, and Herdr reported success. The folder contains nothing but a .git entry. As a control, I sent "base":"no-such-ref", and that was correctly refused with fatal: invalid reference. So the API does check bases. It just does not check ones shaped like options.

Left: the sidebar in the app shows a workspace called feat with a green dot, looking healthy. Right: the folder on disk contains only a .git entry, no files and no history. An agent starting work here starts from nothing. what the sidebar shows main feat ready looks fine what is on disk $ ls -A repo/feat .git $ git log no commits yet an agent told to "branch off this" starts working from an empty folder
The practical damage. The sidebar says healthy. The folder is empty.

The command line version of Herdr happens to be safe, because its argument parser (clap) rejects --base=--orphan as an unknown option before git ever sees it. The socket API, and anything that passes user or agent text into it, is not. An agent told to "branch off whatever the user typed" can end up in a workspace that looks healthy in the sidebar and is actually an empty repository, and will start working from nothing.

The fix

One word, in the two places the command is built:

"-b".to_string(),
branch.to_string(),
"--".to_string(),
path.display().to_string(),
base.to_string(),

git worktree add [opts] -- <path> [<commit-ish>] is the documented form. The same request now returns:

{"error":{"code":"worktree_create_failed",
          "message":"fatal: invalid reference: --orphan"}}

The branch name did not need the same treatment, because it is passed as the value of -b, and git never re-reads the value of an option as a new option. I added a test that runs real git and checks that an option-shaped base fails, makes no folder, and makes no branch, and updated the two tests that check the shape of the command. Full suite: 3865 passing.

What I did not file, and why

The audits turned up three more candidates. None were filed, for three different reasons, and the reasons matter more than the candidates. "Found by an audit" and "ready to report" are not the same thing.

  • A broken config file silently resets the update channel. If config.toml fails to parse, the program falls back to defaults, and the default channel is stable even for preview builds. The stable path installs whenever the running program is a preview. So a stray typo in your config turns the next herdr update into a quiet downgrade. I verified this by reading the code, not by running it on a preview build. Good candidate for next time.
  • The remote bridge socket sits in shared /tmp with a guessable name that includes the ssh target. On a Linux machine with many users, that reveals which hosts you connect to and lets someone block you by creating the names first. It is Linux-only and multi-user. I could not reproduce it on my Mac, so it stays unfiled.
  • Preview builds install without a checksum if the manifest leaves it out. The stable path demands a digest. The preview path treats it as optional. Today every manifest carries one, so this is a missing belt, not a current fall.

The rule "report only what you personally reproduced" looked like a hurdle and turned out to be a filter. It forced one question, "can I show this on the shipped program?", and two of five candidates passed it cleanly.

Things I would tell someone doing this next

Read the contribution policy before the code. It decides what the deliverable is. Here it ruled out a pull request entirely and defined exactly what a good report looks like.

Audit broad, verify narrow. Parallel audits with tight briefs found candidates fast. Reproducing each one in series, on the real download, decided which were true.

Negative results are evidence. When an audit of the API comes back with "sizes are capped, the socket is owner-only, ssh targets are checked," that tells you how much to trust the one thing it did flag.

Look for two sources of truth. Bug 1 is the classic shape: two independent answers to the same question (which socket, which folder) that agree by default and split under an override. Any time you see a documented override, ask what else should have moved with it.

Look for --. Bug 2 is the other classic. Any list of words built from someone else's input and handed to a program that reads options anywhere on the line needs a separator. Git, ssh, rm, and many others qualify.

Fix with the grain of the codebase. File::try_lock was already in use. The lock follows the shape of the existing plugin registry lock. The handoff wait reuses an existing wait-and-warn pattern. A fix that looks like it belongs is far more likely to be adopted, even when someone else ends up writing it.

Keep home clean. My first worktree reproduction used the default ~/.herdr/worktrees folder and left an empty checkout in my real home directory. Configure every path you can when testing against a real program.

The two bugs side by side. Bug 1: two answers to one question, the socket path and the data folder, agree by default and split under an override. Bug 2: a word from the caller lands where the program reads instructions, because no separator was placed before it. bug 1: two sources of truth bug 2: input where orders go by default socket and folder point the same way by default the base is a branch name, works fine under an override they split, and the notebook is shared with a dash in front it becomes an instruction, and git obeys
Both bugs are fine in the normal case. Both go wrong when an input nobody tested arrives.

Appendix: the reproduction scripts

Both reproductions are shell scripts. Each starts herdr server with no window, inside a throwaway config folder, drives it over the socket with a few lines of Python, and then looks at the files and the git state afterwards. Each takes the path to a Herdr program as its first argument, which is what made comparing the release build and a build of the latest source cheap. They live in my checkout under .local/blog/ as repro_shared_session.sh and repro_worktree_base.sh. The issue reports contain shorter manual versions anyone can type.

# the shape of both scripts
HERDR=$1
export XDG_CONFIG_HOME=$(mktemp -d)       # keep home clean
"$HERDR" server --headless &              # start A
python3 drive.py "$SOCKET" '{"method":"..."}'   # send requests
# inspect: session.json, git worktree list, ls -A

The branches with the fixes are issue/5217-session-data-lock (commit c0c0a2e) and issue/5219-worktree-base-separator on my fork. If you are on the approved list and want to carry either one upstream, they are yours.

← more writings