beads/cmd/bd/backup_lock.go
Julian Knutsen 4e4ebdb443
feat(backup): proxied auto-backup on managed-local, serialized with bd backup sync (#6879)
* feat(backup): run opted-in auto-backup on a managed-local proxied server

#6584 routed the five `bd backup` verbs over the proxied provider on
managed-local, and #6694 made `bd backup status` admit the remaining gap:
the proxied arm of PersistentPostRunE never called runPostRunAutoBackup,
so backup.enabled=true was inert on every proxied workspace. Close it.

The proxied arm now calls the auto-backup hook before it closes the
provider, under the direct arm's maintenance gate (strict --readonly,
`bd serve`, a migration freeze) plus previews. maybeAutoBackup picks a
backend for the command: the direct store as before, or the proxied
provider's RunNonTx seam, which `bd backup sync` already uses.

The proxied backend is honored exactly where `bd backup sync` is: the
"backup sync" capability row's rule for this workspace's topology, so
managed-local only. Auto-backup registers a server-side backup remote,
which on a server bd does not own is global to every client; an implicit
trigger must not get further than the explicit verb. It never opens a
provider of its own: a command that opened none (`bd dolt stop`) or
closed it (restore) backs nothing up rather than relaunching the server.
The default stays OFF, as on every server-mode workspace.

The register/sync-to-a-local-dir sequence that DoltStore and
EmbeddedDoltStore each carried a copy of moves to
versioncontrolops.BackupToDir (and HEAD lookup to CurrentCommit), so the
proxied backend reuses it instead of adding a third copy.

Tests: TestManagedLocalProxiedAutoBackup (default off, opt-in writes a
restorable backup, change detection, `bd dolt stop` stays quiescent,
restore round trip with issue-set equality; fails against origin/main);
TestManagedLocalProxiedBackupRestoreRefusedWhileAttached pins the restore
design (refused while another bd client holds the workspace, serving
child untouched, succeeds once it detaches); unit tests for the backend
locality gate, the post-run wiring, the status note and BackupToDir.
Both managed-local tests, and the existing round trip, are added to the
proxied-local smoke lane's compiled-in list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(backup): serialize auto-backup and bd backup sync with a workspace backup lock

Review follow-up on #6879. Auto-backup and an explicit bd backup sync
both run under the command's SHARED workspace gate, so nothing stopped
them overlapping, and auto-backup's remove -> add -> sync on one fixed
remote name races a concurrent copy of itself.

A per-workspace flock (.beads/backup.lock, already gitignored by
*.lock) now serializes them in every mode. Auto-backup takes it
non-blocking and skips when held (the throttle is left alone, so a
later command retries). bd backup sync waits up to exclusiveGateWait -
the bound restore's exclusive gate acquisition uses - then fails with
"another backup is running for this workspace" before touching the
store. Restore needs no part in it: its exclusive workspace gate
already excludes every command that could hold the lock.

Tests: lock semantics (refusal while held, bounded wait, release),
auto-backup skipping while held and running once released, and sync
failing loudly without reaching the store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 02:45:58 -07:00

71 lines
2.6 KiB
Go

package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/lockfile"
)
// The backup lock serializes the two writers of a workspace's Dolt backup:
// post-command auto-backup and an explicit `bd backup sync`. Both run under the
// command's SHARED workspace gate, so the gate alone lets them overlap, and the
// auto-backup body does remove → add → sync on one fixed remote name — two
// concurrent runs race each other's registration and full-sync the database
// twice. Restore needs no part in it: it holds the workspace gate EXCLUSIVELY,
// which already excludes every command that could take this lock.
//
// The two callers wait differently, and deliberately:
// - auto-backup does not wait. Another backup running means one is already
// happening; it skips, and the throttle picks it up on a later command.
// - `bd backup sync` waits up to backupLockWait — the same bound an exclusive
// workspace-gate acquisition (restore) uses — and then fails with an error
// naming the busy lock, so an operator is never told it synced when it
// did not.
const backupLockFileName = "backup.lock"
// backupLockWait bounds how long `bd backup sync` waits for another backup.
// A var so tests can shorten it.
var backupLockWait = exclusiveGateWait
// errBackupBusy is returned when another backup holds the lock past the wait.
var errBackupBusy = errors.New("another backup is running for this workspace")
const backupLockPoll = 50 * time.Millisecond
// acquireBackupLock takes the workspace's backup lock, polling up to wait
// (zero means one non-blocking attempt). The returned release must be called.
func acquireBackupLock(wait time.Duration) (release func(), err error) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return nil, fmt.Errorf("backup lock: %s", activeWorkspaceNotFoundError())
}
path := filepath.Join(beadsDir, backupLockFileName)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) //nolint:gosec // path is the workspace's own lock file
if err != nil {
return nil, fmt.Errorf("backup lock: open %s: %w", path, err)
}
deadline := time.Now().Add(wait)
for {
err := lockfile.FlockExclusiveNonBlocking(f)
if err == nil {
return func() {
_ = lockfile.FlockUnlock(f)
_ = f.Close()
}, nil
}
if !lockfile.IsLocked(err) {
_ = f.Close()
return nil, fmt.Errorf("backup lock: %s: %w", path, err)
}
if !time.Now().Before(deadline) {
_ = f.Close()
return nil, errBackupBusy
}
time.Sleep(backupLockPoll)
}
}