Skip to content

LockRoster: write atomically and fail on corrupt roster JSON - #10659

Open
underiya-ai wants to merge 1 commit into
borgbackup:masterfrom
underiya-ai:fix-lockroster-atomic-save
Open

underiya-ai wants to merge 1 commit into
borgbackup:masterfrom
underiya-ai:fix-lockroster-atomic-save

Conversation

@underiya-ai

Copy link
Copy Markdown
Contributor

What does this PR fix?

Previously, LockRoster.save() wrote directly to the roster file using open("w"), which truncates the file before writing. If the process is killed, interrupted, or runs out of disk space mid-write, the roster is left as truncated/corrupt JSON. Furthermore, LockRoster.load() caught ValueError and silently returned {}, treating a corrupt roster as "no active locks" and potentially allowing an exclusive lock while readers are still active.

Solution

  • Write the lock roster atomically via a temporary file in the same directory (tempfile.mkstemp), flush() + os.fsync(), and os.replace().
  • In LockRoster.load(), continue treating missing or 0-byte empty files as {}, but raise LockFailed on corrupt JSON instead of silently ignoring active lockers.
  • Add unit tests in src/borg/testsuite/fslocking_test.py for corrupt roster loading and preserving the existing roster if save() fails mid-write.

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 89.48%. Comparing base (49d0bbe) to head (0700284).
⚠️ Report is 9 commits behind head on master.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/borg/fslocking.py 95.65% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master   #10659   +/-   ##
=======================================
  Coverage   89.48%   89.48%           
=======================================
  Files         105      105           
  Lines       20343    20347    +4     
  Branches     3199     3199           
=======================================
+ Hits        18203    18208    +5     
+ Misses       1486     1485    -1     
  Partials      654      654           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@underiya-ai

Copy link
Copy Markdown
Contributor Author

Hi @ThomasWaldmann,

Could you please review this PR when you have a moment?

It makes LockRoster.save() atomic (via temp file + fsync + os.replace) so an interrupted write doesn't leave a truncated JSON file, and updates LockRoster.load() to raise LockFailed on corrupt JSON instead of silently treating it as empty {}. All CI test suites have passed and there are no conflicts with master.

Let me know if you'd like any changes!

@ThomasWaldmann ThomasWaldmann left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks! Note: on master, fslocking is only used by the legacy borg 1.x repository code (legacy/repository.py, e.g. for borg transfer), see also docs/internals/frontends.rst.

1. File mode regression (must fix): tempfile.mkstemp() creates the file with mode 0600 (ignoring the umask), and os.replace() keeps that mode. With umask 002, the old open("w") gave 0664, the new code gives 0600. In a repository shared by multiple users, this breaks locking:

  • while user A holds a lock, user B's load() fails with an uncaught PermissionError (before, B could get a shared lock);
  • if A's process dies, the 0600 roster stays behind and stale-lock cleanup can't fix it, because B can't read it.

Please use the existing SaveFile from platform/base.py instead:

with SaveFile(self.path) as f:
    json.dump(data, f)

It creates the temp file with mkstemp_mode(..., mode=0o666) (so the umask is respected), syncs the file and the directory, does the atomic os.replace and cleans up the temp file on errors.

2. Possible orphaned lock: now that load() can raise, Lock.release() for an exclusive lock can fail in self._roster.modify(EXCLUSIVE, REMOVE) before reaching self._lock.release(), leaving the exclusive lock behind. Please release _lock in a try/finally there.

3. 0-byte special case vs. the rationale: the PR says a corrupt roster must not be treated as "no lockers", but a 0-byte roster still returns {}. A 0-byte file is the most likely result of a crash with the old non-atomic write (which is how borg 1.x writes it), and with atomic saves borg2 does not produce corrupt rosters at all. So the new LockFailed branch only triggers for partially written files. Please either treat both the same, or explain in the comment why 0 bytes is OK.

Also, if it raises, the error message should tell the user how to recover (e.g. remove lock.roster, or borg break-lock with borg 1.x).

4. Tests (minor):

  • monkeypatch.setattr("borg.fslocking.json.dump", ...) patches dump on the global json module, not just in fslocking.
  • Please add a test that the saved roster respects the umask (e.g. 0o664 with umask 002), skipped if BORG_TESTS_IGNORE_MODES is set.

@underiya-ai

underiya-ai commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

@ThomasWaldmann Thanks for the thorough review! I've updated the PR to address all four points:

  1. Replaced tempfile.mkstemp + os.replace with SaveFile(self.path) so the saved roster respects the process umask, syncs both the file and directory, and avoids 0600 permission lockouts in shared multi-user repositories.
  2. Wrapped Lock.release() for exclusive locks in try / finally so _lock.release() is always called even if _roster.modify() raises LockFailed.
  3. Removed the 0-byte special case so both empty and truncated/corrupt roster files raise LockFailed, and included recovery instructions (remove it or run 'borg break-lock') in the error message.
  4. Updated the tests to patch borg.fslocking.SaveFile instead of json.dump, added a 0-byte corrupt roster test, a test for releasing the underlying exclusive lock on a corrupt roster, and a test verifying that the saved roster file mode respects the umask (0o664 with umask 002).

Also, I've really enjoyed contributing to BorgBackup so far—if there are any other bugs, edge cases, or smaller features on master that you'd recommend tackling next, I'd love to take a look at them!

@ThomasWaldmann ThomasWaldmann left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update! SaveFile, the try/finally in Lock.release(), the 0-byte handling and the umask test all look good now. Two things left:

1. Recovery hint: on master, fslocking is only used for borg 1.x repositories, but borg 2's borg break-lock only works on borg 2 repositories (it has no --from-borg1), so it can't fix this. Please make the hint point to borg 1.x, e.g.:

corrupt lock roster ({err}); if no borg process is using this borg 1.x repository, remove it or run 'borg break-lock' with borg 1.x

2. test_atomic_save_preserves_existing_on_error: the fake SaveFile raises in __enter__ before anything is written, so the test passes no matter what save() does and never exercises the real SaveFile. Please let the real SaveFile run and make the write fail halfway instead. To do that without patching the global json module, replace only the json name in borg.fslocking:

def test_save_keeps_old_roster_on_write_error(self, rosterpath, monkeypatch):
    roster = LockRoster(rosterpath, id=ID1)
    roster.modify(SHARED, ADD)

    def failing_dump(data, f):
        f.write('{"shared": [')  # partial write
        raise OSError("simulated disk full")

    monkeypatch.setattr("borg.fslocking.json", SimpleNamespace(load=json.load, dump=failing_dump))
    with pytest.raises(OSError):
        roster.save({"shared": []})
    assert roster.get(SHARED) == {ID1}  # old roster still intact
    assert [p.name for p in rosterpath.parent.iterdir()] == [rosterpath.name]  # no temp file left behind

(I ran this locally against the PR, it passes.)

Minor: please squash the two commits into one.

@underiya-ai
underiya-ai force-pushed the fix-lockroster-atomic-save branch from ebc65c7 to 0700284 Compare December 3, 2026 12:42
@underiya-ai

Copy link
Copy Markdown
Contributor Author

Thanks! I've updated the recovery hint to specifically reference borg 1.x, replaced the fake SaveFile test with test_save_keeps_old_roster_on_write_error using SimpleNamespace, and squashed everything into a single commit.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants