carlos / platform Public

Guard team commits and recover an interrupted witness write

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev c44ec92b7adc6de80a0d16a492e88044efa2574a parent e2112ac
7 files changed, +459 −71
  • docs/superpowers/plans/2026-11-01-team-service.md +15 −6
  • internal/team/commit_recovery_test.go +189 −0
  • internal/team/store.go +112 −65
  • internal/team/storeguard.go +68 −0
  • internal/team/storelock_other.go +16 −0
  • internal/team/storelock_unix.go +28 −0
  • internal/team/storelock_windows.go +31 −0
diff --git a/docs/superpowers/plans/2026-11-01-team-service.md b/docs/superpowers/plans/2026-11-01-team-service.md
index 5097b37ec..53ae7a47b 100644
--- a/docs/superpowers/plans/2026-11-01-team-service.md
+++ b/docs/superpowers/plans/2026-11-01-team-service.md
@@ -47,12 +47,21 @@ claiming the uncertain action succeeded. Retrying an undispatched attempt
remains supported.
Schema 2 adds an external transaction position to detect snapshots restored
-within the same process incarnation. Reads also advance this position in the
-prototype. Missing or mismatched history stays quarantined across reopens,
-even if no outstanding action survives in the snapshot. There is no automatic
-restore release or operator override in this slice. A hosted restore needs
-an explicit recovery protocol; the local witness is not a host-loss durability
-claim. Migration from schema 1 preserves records and quarantines its history.
+within the same process incarnation. A process-shared guard covers the SQL
+commit and the following witness write, including replacement Open calls.
+If the witness write fails, that handle refuses further work. Startup repairs
+exactly one unpublished commit before advancing again; repeated process
+crashes cannot accumulate a larger gap. Reads also advance the position.
+
+Missing history, database rollback and other mismatches stay quarantined
+across reopens, even if no outstanding action survives in the snapshot.
+There is no automatic restore release or operator override in this slice.
+A hosted restore needs an explicit recovery protocol; the local witness is
+not a host-loss durability claim. Migration from schema 1 preserves records
+but remains quarantined until that recovery protocol exists. Store files,
+including the permanent lock file, require trusted local storage; hard-linked
+database aliases and restoring the witness together with the database are
+unsupported. The witness must remain outside the backup being restored.
Before live adapters, bind evidence to authenticated runners, enforce provider
request ceilings in the adapter, flag measured usage above its reservation,
diff --git a/internal/team/commit_recovery_test.go b/internal/team/commit_recovery_test.go
new file mode 100644
index 000000000..deea2ff9d
--- /dev/null
+++ b/internal/team/commit_recovery_test.go
@@ -0,0 +1,189 @@
+package team
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+)
+
+// The helper exits without Close, defers, or test cleanup: SQLite and the
+// kernel must recover the abandoned transaction and lock themselves.
+func TestCommitCrashHelper(t *testing.T) {
+ path := os.Getenv("TEAM_COMMIT_CRASH_PATH")
+ if path == "" {
+ return
+ }
+ clock := NewFakeClock(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC))
+ opts := Options{Clock: clock, Authority: NewFakeAuthority(clock, 5*time.Second)}
+ stage := os.Getenv("TEAM_COMMIT_CRASH_STAGE")
+ hook := func(at string) error {
+ if at == stage {
+ os.Exit(73)
+ }
+ return nil
+ }
+ if os.Getenv("TEAM_COMMIT_CRASH_OPEN") == "1" {
+ opts.commitHook = hook
+ }
+ s, err := Open(context.Background(), path, opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if os.Getenv("TEAM_COMMIT_CRASH_OPEN") != "1" {
+ _, err = s.Resume(context.Background())
+ if err == nil {
+ s.commitHook = hook
+ err = s.tx(context.Background(), func(tx *sql.Tx) error { return nil })
+ }
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.Exit(74)
+}
+
+func TestProcessCrashAtCommitBoundary(t *testing.T) {
+ for _, mode := range []string{"transaction", "reopen", "first_open"} {
+ opening := mode != "transaction"
+ for _, stage := range []string{"before_commit", "after_commit"} {
+ name := mode + "/" + stage
+ t.Run(name, func(t *testing.T) {
+ e := newEnv(t)
+ e.crash()
+ if mode == "first_open" {
+ e.path = filepath.Join(e.dir, "fresh.db")
+ }
+ for round := 0; round < 2; round++ {
+ exe, err := os.Executable()
+ must(t, err)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ cmd := exec.CommandContext(ctx, exe, "-test.run=^TestCommitCrashHelper$")
+ cmd.Dir = e.dir
+ cmd.Env = append(os.Environ(), "TEAM_COMMIT_CRASH_PATH="+e.path, "TEAM_COMMIT_CRASH_STAGE="+stage)
+ if opening {
+ cmd.Env = append(cmd.Env, "TEAM_COMMIT_CRASH_OPEN=1")
+ }
+ out, err := cmd.CombinedOutput()
+ cancel()
+ var exit *exec.ExitError
+ if !errors.As(err, &exit) || exit.ExitCode() != 73 {
+ t.Fatalf("helper did not reach crash boundary: %v\n%s", err, out)
+ }
+ }
+ e.openNoResume()
+ rr, err := e.store.Resume(e.ctx)
+ must(t, err)
+ if !rr.Resumed || rr.Quarantine {
+ t.Fatalf("ordinary process crash treated as restore: %+v", rr)
+ }
+ })
+ }
+ }
+}
+
+func TestWitnessFailureStopsHandleUntilReopen(t *testing.T) {
+ e := newEnv(t)
+ inc, revision, _, err := readMarker(e.store.marker)
+ must(t, err)
+ // A directory at the temporary-file path forces a real write failure.
+ must(t, os.Mkdir(e.store.marker+".tmp", 0o700))
+ _, err = e.store.Status(e.ctx)
+ wantCode(t, err, CodeInvalid)
+ var dbRevision int64
+ must(t, e.store.db.QueryRow(`SELECT revision FROM service WHERE id=1`).Scan(&dbRevision))
+ if dbRevision != revision+1 {
+ t.Fatalf("database advanced from %d to %d", revision, dbRevision)
+ }
+ mInc, mRevision, _, err := readMarker(e.store.marker)
+ must(t, err)
+ if mInc != inc || mRevision != revision {
+ t.Fatal("failed witness changed the published position")
+ }
+ _, err = e.store.CreateJob(e.ctx, softwareSpec(SoftwareSteps(false)))
+ wantCode(t, err, CodeStaleStore)
+ _, err = e.store.Status(e.ctx)
+ wantCode(t, err, CodeStaleStore)
+ must(t, e.store.db.QueryRow(`SELECT revision FROM service WHERE id=1`).Scan(&dbRevision))
+ if dbRevision != revision+1 {
+ t.Fatal("poisoned handle widened the unpublished gap")
+ }
+ must(t, os.Remove(e.store.marker+".tmp"))
+ // Even once storage is writable again, this handle cannot continue.
+ wantCode(t, e.store.Close(), CodeStaleStore)
+ e.store = nil
+ e.openNoResume()
+ rr, err := e.store.Resume(e.ctx)
+ must(t, err)
+ if !rr.Resumed || rr.Quarantine {
+ t.Fatalf("single unpublished commit did not recover: %+v", rr)
+ }
+ e.createJob(softwareSpec(SoftwareSteps(false)))
+}
+
+func TestCommitGuardExcludesReplacementOpen(t *testing.T) {
+ e := newEnv(t)
+ committed, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1)
+ var once sync.Once
+ finish := func() { once.Do(func() { close(release) }) }
+ e.store.commitHook = func(stage string) error {
+ if stage == "after_commit" {
+ close(committed)
+ <-release
+ }
+ return nil
+ }
+ go func() {
+ done <- e.store.tx(e.ctx, func(*sql.Tx) error { return nil })
+ }()
+ t.Cleanup(finish)
+ <-committed
+ ctx, cancel := context.WithTimeout(e.ctx, 50*time.Millisecond)
+ replacement, err := Open(ctx, e.path, e.options())
+ cancel()
+ if replacement != nil {
+ _ = replacement.Close()
+ t.Fatal("replacement opened during an unpublished commit")
+ }
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("replacement did not wait on the shared guard: %v", err)
+ }
+ finish()
+ must(t, <-done)
+ e.store.commitHook = nil
+ old := e.store
+ e.openNoResume()
+ _, err = old.Status(e.ctx)
+ wantCode(t, err, CodeStaleStore)
+ _ = old.Close()
+ rr, err := e.store.Resume(e.ctx)
+ must(t, err)
+ if !rr.Resumed {
+ t.Fatalf("replacement failed recovery: %+v", rr)
+ }
+}
+
+func TestRestoreDoesNotReuseWitnessIncarnation(t *testing.T) {
+ e := newEnv(t)
+ backup := e.snapshot()
+ e.crash()
+ e.open()
+ st, err := e.store.Status(e.ctx)
+ must(t, err)
+ must(t, e.store.Close())
+ e.store = nil
+ raw, err := os.ReadFile(backup)
+ must(t, err)
+ must(t, os.WriteFile(e.path, raw, 0o600))
+ e.openNoResume()
+ restored, err := e.store.Status(e.ctx)
+ must(t, err)
+ if restored.Incarnation <= st.Incarnation || !restored.Quarantine {
+ t.Fatalf("restored store reused an owner: old %+v, restored %+v", st, restored)
+ }
+}
diff --git a/internal/team/store.go b/internal/team/store.go
index 11b09a8ed..1a5bf71bc 100644
--- a/internal/team/store.go
+++ b/internal/team/store.go
@@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
"fmt"
+ "net/url"
"os"
"path/filepath"
"strconv"
@@ -37,17 +38,16 @@ type Adapter interface {
// the incarnation marker kept outside the database; it defaults to the
// database path plus ".incarnation".
type Options struct {
- Clock Clock
- Authority Authority
- Adapters map[Operation]Adapter
- Marker string
+ Clock Clock
+ Authority Authority
+ Adapters map[Operation]Adapter
+ Marker string
+ commitHook func(string) error // tests terminate a process at exact commit boundaries
}
-// Store is the durable core. One Store owns one SQLite database (the
-// platform's single-writer contract); its connection pool lets concurrent
-// callers run transactions on separate connections, serialised by SQLite's
-// own locking, not by a Go mutex. Open launches no goroutine and opens no
-// network connection.
+// Store is the durable core. A process-shared guard serializes each SQLite
+// commit with its external witness. Open launches no goroutine or network
+// connection. The database, witness and lock live in trusted local storage.
type Store struct {
db *sql.DB
path string
@@ -57,6 +57,9 @@ type Store struct {
adapters map[Operation]Adapter
incarnation int64
recoveryMu sync.Mutex
+ commitHook func(string) error
+ writeMu sync.Mutex
+ broken error // guarded by writeMu; only a new Open can recover it
}
// Open opens or creates the database at path. Admission is paused on every
@@ -67,10 +70,19 @@ func Open(ctx context.Context, path string, o Options) (*Store, error) {
if o.Clock == nil || o.Authority == nil {
return nil, fail(CodeInvalid, "open needs a clock and an authority")
}
+ path, err := canonicalStorePath(path)
+ if err != nil {
+ return nil, err
+ }
if o.Marker == "" {
o.Marker = path + ".incarnation"
}
- dsn := "file:" + path + "?_txlock=immediate&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(1)"
+ o.Marker, err = filepath.Abs(o.Marker)
+ if err != nil {
+ return nil, err
+ }
+ u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), OmitHost: true}
+ dsn := u.String() + "?_txlock=immediate&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(1)"
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fail(CodeInvalid, "open: %v", err)
@@ -84,6 +96,7 @@ func Open(ctx context.Context, path string, o Options) (*Store, error) {
db.Close()
return nil, err
}
+ s.commitHook = o.commitHook
if err := s.start(ctx); err != nil {
db.Close()
return nil, err
@@ -109,10 +122,12 @@ func (s *Store) Close() error {
func (s *Store) Status(ctx context.Context) (Status, error) {
var st Status
var paused, quarantine int
- err := s.db.QueryRowContext(ctx, `SELECT schema_version, incarnation, admission_paused, quarantine, quarantine_why FROM service WHERE id=1`).
- Scan(&st.SchemaVersion, &st.Incarnation, &paused, &quarantine, &st.QuarantineWhy)
+ err := s.tx(ctx, func(tx *sql.Tx) error {
+ return tx.QueryRowContext(ctx, `SELECT schema_version, incarnation, admission_paused, quarantine, quarantine_why FROM service WHERE id=1`).
+ Scan(&st.SchemaVersion, &st.Incarnation, &paused, &quarantine, &st.QuarantineWhy)
+ })
if err != nil {
- return st, fail(CodeInvalid, "status: %v", err)
+ return st, err
}
st.AdmissionPaused = paused != 0
st.Quarantine = quarantine != 0
@@ -298,24 +313,37 @@ func (s *Store) migrate(ctx context.Context) error {
// from the marker outside the database.
func (s *Store) start(ctx context.Context) error {
var next int64
- err := s.tx(ctx, func(tx *sql.Tx) error {
+ err := s.transaction(ctx, false, true, func(tx *sql.Tx) error {
var inc, revision int64
var previousRestore int
if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision, restore_uncertain FROM service WHERE id=1`).Scan(&inc, &revision, &previousRestore); err != nil {
return err
}
why, restore := "", previousRestore
+ mInc, mRevision, clean, markerErr := readMarker(s.marker)
if inc == 0 {
- if _, err := os.Stat(s.marker); err == nil {
- return fail(CodeStaleStore, "database is empty but its external witness exists")
- } else if !errors.Is(err, os.ErrNotExist) {
- return err
+ // Establish an empty predecessor before the first commit. A
+ // crash during the first Open then has the same one-step gap.
+ if errors.Is(markerErr, os.ErrNotExist) && revision == 0 {
+ if err := writeMarker(s.marker, 0, 0, false); err != nil {
+ return err
+ }
+ mInc, mRevision, markerErr = 0, 0, nil
+ }
+ if markerErr != nil || mInc != 0 || mRevision != 0 || revision != 0 {
+ return fail(CodeStaleStore, "empty database has no matching empty witness")
}
} else {
- mInc, mRevision, clean, err := readMarker(s.marker)
switch {
- case err != nil:
- why, restore = "marker missing or unreadable: "+err.Error(), 1
+ case markerErr != nil:
+ why, restore = "marker missing or unreadable: "+markerErr.Error(), 1
+ case revision > 0 && mRevision == revision-1 && (mInc == inc || (inc > 0 && mInc == inc-1)):
+ // SQL committed but its witness did not. Repair the witness
+ // before another commit, so repeated crashes never widen the gap.
+ if err := writeMarker(s.marker, inc, revision, false); err != nil {
+ return err
+ }
+ why = "unclean shutdown after database commit"
case mInc != inc || mRevision != revision:
why, restore = fmt.Sprintf("marker position %d/%d, database %d/%d: restored snapshot", mInc, mRevision, inc, revision), 1
case !clean:
@@ -326,17 +354,10 @@ func (s *Store) start(ctx context.Context) error {
why = "restored history requires operator recovery"
}
var err error
- next, err = addChecked(inc, 1)
- if err != nil {
- return err
- }
- nextRevision, err := addChecked(revision, 1)
+ next, err = addChecked(max(inc, mInc), 1)
if err != nil {
return err
}
- if err := writeMarker(s.marker, next, nextRevision, false); err != nil {
- return err
- }
q := 0
if why != "" {
q = 1
@@ -346,7 +367,7 @@ func (s *Store) start(ctx context.Context) error {
return err
}
}
- _, err = tx.ExecContext(ctx, `UPDATE service SET incarnation=?, revision=?, admission_paused=1, quarantine=?, quarantine_why=?, restore_uncertain=? WHERE id=1`, next, nextRevision, q, why, restore)
+ _, err = tx.ExecContext(ctx, `UPDATE service SET incarnation=?, admission_paused=1, quarantine=?, quarantine_why=?, restore_uncertain=? WHERE id=1`, next, q, why, restore)
return err
})
if err == nil {
@@ -400,53 +421,79 @@ func writeMarker(path string, inc, revision int64, clean bool) error {
return nil
}
-// Every transaction advances an external position before committing. A
-// rollback or an older database snapshot therefore leaves a detectable
-// mismatch, including snapshots taken within the same writer incarnation.
-// Reads also advance the position in this bounded prototype; optimizing
-// that requires retaining the same witness for every mutation path.
+// A successful operation commits SQL and then publishes the same position
+// externally, under one process-shared guard. A failed witness write poisons
+// this handle. Thus a crash leaves either equal positions or exactly one
+// unpublished commit; start repairs that gap before advancing again.
+// Reads also advance the position in this bounded prototype.
func (s *Store) tx(ctx context.Context, fn func(*sql.Tx) error) error {
return s.transact(ctx, false, fn)
}
func (s *Store) transact(ctx context.Context, clean bool, fn func(*sql.Tx) error) error {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return fail(CodeInvalid, "begin: %v", err)
- }
- defer tx.Rollback()
- if s.incarnation != 0 {
- var current int64
- if err := tx.QueryRowContext(ctx, `SELECT incarnation FROM service WHERE id=1`).Scan(&current); err != nil {
- return err
+ return s.transaction(ctx, clean, s.incarnation != 0, fn)
+}
+
+func (s *Store) transaction(ctx context.Context, clean, witnessed bool, fn func(*sql.Tx) error) error {
+ return s.withStoreGuard(ctx, func() error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return fail(CodeInvalid, "begin: %v", err)
}
- if current != s.incarnation {
- return fail(CodeStaleStore, "incarnation %d replaced by %d", s.incarnation, current)
+ defer tx.Rollback()
+ if s.incarnation != 0 {
+ var current, revision int64
+ if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision FROM service WHERE id=1`).Scan(&current, &revision); err != nil {
+ return err
+ }
+ if current != s.incarnation {
+ return fail(CodeStaleStore, "incarnation %d replaced by %d", s.incarnation, current)
+ }
+ mInc, mRevision, _, err := readMarker(s.marker)
+ if err != nil || mInc != current || mRevision != revision {
+ s.broken = fail(CodeStaleStore, "database and witness differ; reopen for recovery")
+ return s.broken
+ }
}
- }
- if err := fn(tx); err != nil {
- return err
- }
- if s.incarnation != 0 {
- var revision int64
- if err := tx.QueryRowContext(ctx, `SELECT revision FROM service WHERE id=1`).Scan(&revision); err != nil {
+ if err := fn(tx); err != nil {
return err
}
- next, err := addChecked(revision, 1)
- if err != nil {
- return err
+ var inc, revision int64
+ if witnessed {
+ if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision FROM service WHERE id=1`).Scan(&inc, &revision); err != nil {
+ return err
+ }
+ revision, err = addChecked(revision, 1)
+ if err != nil {
+ return err
+ }
+ if _, err := tx.ExecContext(ctx, `UPDATE service SET revision=? WHERE id=1`, revision); err != nil {
+ return err
+ }
}
- if _, err := tx.ExecContext(ctx, `UPDATE service SET revision=? WHERE id=1`, next); err != nil {
- return err
+ if s.commitHook != nil {
+ if err := s.commitHook("before_commit"); err != nil {
+ return err
+ }
}
- if err := writeMarker(s.marker, s.incarnation, next, clean); err != nil {
- return err
+ if err := tx.Commit(); err != nil {
+ s.broken = err // a commit error may leave its outcome unknown
+ return fail(CodeInvalid, "commit: %v", err)
}
- }
- if err := tx.Commit(); err != nil {
- return fail(CodeInvalid, "commit: %v", err)
- }
- return nil
+ if s.commitHook != nil {
+ if err := s.commitHook("after_commit"); err != nil {
+ s.broken = err
+ return err
+ }
+ }
+ if witnessed {
+ if err := writeMarker(s.marker, inc, revision, clean); err != nil {
+ s.broken = err
+ return err
+ }
+ }
+ return nil
+ })
}
// admissionOpen fails closed while the service is paused or quarantined.
diff --git a/internal/team/storeguard.go b/internal/team/storeguard.go
new file mode 100644
index 000000000..6d119124e
--- /dev/null
+++ b/internal/team/storeguard.go
@@ -0,0 +1,68 @@
+package team
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "time"
+)
+
+// withStoreGuard serializes the database commit and the following witness
+// write, including replacement handles and processes. The lock file is
+// permanent; unlinking it would let another opener lock a different inode.
+func (s *Store) withStoreGuard(ctx context.Context, fn func() error) error {
+ s.writeMu.Lock()
+ defer s.writeMu.Unlock()
+ if s.broken != nil {
+ return fail(CodeStaleStore, "store must be reopened after incomplete commit: %v", s.broken)
+ }
+ f, err := os.OpenFile(s.path+".lock", os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ for {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ locked, err := tryStoreLock(f)
+ if err != nil {
+ return err
+ }
+ if locked {
+ defer unlockStoreFile(f)
+ return fn()
+ }
+ timer := time.NewTimer(10 * time.Millisecond)
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ return ctx.Err()
+ case <-timer.C:
+ }
+ }
+}
+
+// The database and its lock must have one path even when a caller uses a
+// relative path or a symlink. Hard-linked SQLite databases are unsupported.
+func canonicalStorePath(path string) (string, error) {
+ abs, err := filepath.Abs(path)
+ if err != nil {
+ return "", err
+ }
+ resolved, err := filepath.EvalSymlinks(abs)
+ if err == nil {
+ return resolved, nil
+ }
+ if !os.IsNotExist(err) {
+ return "", err
+ }
+ if _, statErr := os.Lstat(abs); !os.IsNotExist(statErr) {
+ return "", err // an existing dangling symlink cannot name a second lock
+ }
+ dir, err := filepath.EvalSymlinks(filepath.Dir(abs))
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(dir, filepath.Base(abs)), nil
+}
diff --git a/internal/team/storelock_other.go b/internal/team/storelock_other.go
new file mode 100644
index 000000000..e1c5806f8
--- /dev/null
+++ b/internal/team/storelock_other.go
@@ -0,0 +1,16 @@
+//go:build !unix && !windows
+
+package team
+
+import (
+ "fmt"
+ "os"
+ "runtime"
+)
+
+// tryStoreLock refuses to run: no supported file locking on this platform.
+func tryStoreLock(f *os.File) (bool, error) {
+ return false, fmt.Errorf("team store locking is not supported on %s/%s", runtime.GOOS, runtime.GOARCH)
+}
+
+func unlockStoreFile(f *os.File) {}
diff --git a/internal/team/storelock_unix.go b/internal/team/storelock_unix.go
new file mode 100644
index 000000000..eef6805fe
--- /dev/null
+++ b/internal/team/storelock_unix.go
@@ -0,0 +1,28 @@
+//go:build unix
+
+package team
+
+import (
+ "errors"
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+// tryStoreLock takes a non-blocking exclusive flock on f. It reports false
+// with a nil error when another holder owns the lock.
+func tryStoreLock(f *os.File) (bool, error) {
+ err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
+ if err == nil {
+ return true, nil
+ }
+ if errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) {
+ return false, nil
+ }
+ return false, err
+}
+
+// unlockStoreFile releases the flock; the caller closes the descriptor next.
+func unlockStoreFile(f *os.File) {
+ _ = unix.Flock(int(f.Fd()), unix.LOCK_UN)
+}
diff --git a/internal/team/storelock_windows.go b/internal/team/storelock_windows.go
new file mode 100644
index 000000000..459bc0b4d
--- /dev/null
+++ b/internal/team/storelock_windows.go
@@ -0,0 +1,31 @@
+//go:build windows
+
+package team
+
+import (
+ "errors"
+ "os"
+
+ "golang.org/x/sys/windows"
+)
+
+// tryStoreLock takes a non-blocking exclusive lock on byte 0 of f. It reports
+// false with a nil error when another holder owns the lock.
+func tryStoreLock(f *os.File) (bool, error) {
+ ol := new(windows.Overlapped)
+ err := windows.LockFileEx(windows.Handle(f.Fd()),
+ windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, ol)
+ if err == nil {
+ return true, nil
+ }
+ if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
+ return false, nil
+ }
+ return false, err
+}
+
+// unlockStoreFile releases the byte-range lock; the caller closes the handle next.
+func unlockStoreFile(f *os.File) {
+ ol := new(windows.Overlapped)
+ _ = windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, ol)
+}