diff --git a/CHANGELOG.md b/CHANGELOG.md index d743e783e0..58142cecfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,16 +5,19 @@ **Skills start at once on Windows again: the workflow lease lock no longer depends on symlinks (#3330).** `bin/gstack-lease` took its lock with `ln -s "" .lock`. In Git for Windows' default symlink mode (`MSYS` unset), `ln -s` cannot link to a target that does not exist, so the lock was never taken. Every skill start then waited out all 300 tries (0.1 s apart, plus process start costs) before `gstack-skill-start` printed anything, and still wrote no lease. One report measured 499 s per skill start. The error also blamed a "live process" with an empty pid. ### Fixed -- **`bin/gstack-lease`**: the lock is now a `.lock` directory taken with `mkdir`, which is atomic on every host gstack runs on, with an `owner` file naming the holder's pid and start identity. A taker writes a claim (`.lock.claim.`) before its `mkdir` and renames it in as the owner after, so a lock left ownerless by a taker killed between the two steps is broken once every claimant is dead, never by age. A lock is removed by renaming it aside first, so nobody sees it half-removed. Stale-holder semantics are unchanged: a lock is broken only when its holder is dead or its pid now belongs to another process, breakers still serialize on `.lock.break` and reread before removing, and unlock removes only the caller's own lock. A symlink `.lock` left by an older gstack is still read and broken the same way, and it excludes the new lock at the same path, so mixed versions never both hold it. +- **`bin/gstack-lease`**: the lock is now a `.lock` directory taken with `mkdir`, which is atomic on every host gstack runs on, with an `owner` file naming the holder's pid and start identity. A taker writes a claim (`.lock.claim.`) before its `mkdir` and renames it in as the owner after, so a lock left ownerless by a taker killed between the two steps is broken once every claimant is dead and the lock is at least 2 s old (a live taker between its two steps is never mistaken for a crash). A lock whose owner is empty or names no valid pid, or a stray file at `.lock`, counts as ownerless instead of wedging every skill start. A lock is removed by renaming it aside first, so nobody sees it half-removed; once renamed it is released even if the renamed copy cannot be deleted, and `touch` prunes leftover copies. Stale-holder semantics are unchanged: a lock is broken only when its holder is dead or its pid now belongs to another process, breakers still serialize on `.lock.break` and reread before removing, and unlock removes only the caller's own lock. A symlink `.lock` left by an older gstack is still read and broken the same way, and it excludes the new lock at the same path. The reverse does not hold: an older gstack's `ln -s` onto the directory lock links inside it, so a process that started before an upgrade of the same checkout can briefly share the lock (documented as a known limit). +- A dead holder's lock that cannot be renamed aside (a Windows file in use) is removed in place under `.lock.break`, and when that fails too the try is counted, so `touch` ends with exit 3 instead of spinning without sleeping. The message no longer calls a dead holder live. +- The 120-minute prune in `touch` no longer reaches into the lock: it removed the `owner` file of a holder that resumed past the window, which then left its own lock behind. - When the lock cannot be taken although nobody holds it, `touch` now fails after three quick retries with `gstack-lease: cannot take the lease directory lock ` instead of waiting out every try and naming an empty pid. `gstack-skill-start` stays fail-open, as before. - `docs/capy-install.md` describes the directory lock. ### Tests - `test/gstack-lease-git-bash.test.ts` (new, in the curated windows-free-tests lane, launched through `lib/script-invocation.ts`, so Git Bash on `windows-latest`): `touch` with the default 300 tries takes the lock on its first try (no sleep between tries), writes its lease and leaves no lock. On `windows-latest` the old bin fails this case; a host whose `ln -s` fails like Git Bash's still takes the lock (with a control that the shim really fails `ln -s`); a lock held by a live Git Bash process is kept and named, and a dead holder's lock is broken. The last two fail against the old bin. - `test/gstack-lease.test.ts`: the dead-holder, live-holder and dead-breaker cases run against both the directory lock and the legacy symlink lock. The race cases inject at `mkdir` instead of `ln`. New cases: a lock held by a running gstack-lease excludes a second taker, which names it; 16 parallel touches all land and leave nothing behind; an ownerless lock is kept while a claimant lives and broken once none does; a lock that cannot be taken while nobody holds it fails without sleeping between tries. Seven of these fail against the old bin. +- From /ship's coverage audit and review: the 16 parallel touches now also prove no two are inside the lock at once (a mutant whose `mkdir` always succeeds fails it); the exclusion case holds the lock until the test releases it instead of for a 3 s sleep; a young ownerless lock is kept and malformed locks (empty owner, pid 0, stray file) are broken; the prune keeps a resumed holder's lock; a renamed-aside lock that cannot be deleted never takes a new taker's lock with it; a dead holder's lock that cannot be renamed aside ends `touch` instead of spinning. The last four fail against the bin before their fix. Also covered: a live or ownerless `.lock.break`, a failed owner rename, a lock released between a failed take and its check, and unlock's fallback. The Git Bash case now also checks that the live holder still owns the lock after a blocked `touch`. ### Gate integrity -- No threshold, budget, timeout, trial count, case kind or assertion was weakened. Three existing race tests moved their fault injection from `ln` to `mkdir`, because the lock no longer calls `ln`. Their assertions are unchanged. +- No threshold, budget, timeout, trial count, case kind or assertion was weakened. Three existing race tests moved their fault injection from `ln` to `mkdir`, because the lock no longer calls `ln`. Their assertions are unchanged. Under /ship review, the exclusion case's wait for the holder's owner file rose from 2 s to 10 s and its fixed 3 s hold became a release file (no assertion changed), and the ownerless-lock cases backdate their planted lock by a minute because an ownerless lock is now broken only once 2 s old (their assertions are unchanged; the new young-lock case pins the guard). ## [1.91.221.0] - 2026-10-25 diff --git a/bin/gstack-lease b/bin/gstack-lease index 2c65185c4d..cccae420f7 100755 --- a/bin/gstack-lease +++ b/bin/gstack-lease @@ -14,7 +14,8 @@ # (bin/gstack-harness-pid.sh, the same derivation the session marker # uses), or behind --from (a caller whose own parent is short-lived # passes its parent pid); leases older than 120 min are pruned. Exits 3 -# and writes nothing when a live process holds the directory lock +# and writes nothing when a live process holds the directory lock or +# the lock cannot be taken # gstack-lease live [--root ] [--exclude-ancestry-of ] # print ` m ` per lease held by a live process that # is neither the given pid nor one of its ancestors (the caller's own @@ -106,16 +107,21 @@ state() { # as a claim (.lock.claim.) before its mkdir and renames the claim into # the lock as its owner after, so a lock without an owner is either being # taken by a live claimant or orphaned by a dead one. A lock is broken only -# when its holder (or, ownerless, every claimant) is dead or its pid now -# belongs to another process, never by age, and unlock removes only the -# caller's own lock. A symlink .lock left by an older gstack names its holder -# the same way and excludes a directory lock at the same path. A live holder +# when its holder is dead or its pid now belongs to another process, never by +# age, and unlock removes only the caller's own lock. An ownerless lock is +# broken once no claimant lives and it is at least 2 s old, so a taker between +# its mkdir and its owner rename is never taken for a crash, even when its +# claim landed after the claims were read. A symlink .lock left by an older +# gstack names its holder the same way and excludes a directory lock at the +# same path. Known limit: the reverse does not hold, since an older gstack's +# ln -s onto a directory lock links inside it and succeeds; only a process +# that started before an upgrade of this checkout can run that code. A live holder # makes lock() give up after GSTACK_LEASE_LOCK_TRIES tries 0.1 s apart # (default 300). LOCK="$DIR/.lock" TOKEN="" # take PATH — create the lock PATH owned by TOKEN; 1 when it exists. take() { - printf '%s\n' "$TOKEN" > "$1.claim.$$" || return 1 + printf '%s\n' "$TOKEN" > "$1.claim.$$" || { rm -f "$1.claim.$$"; return 1; } if mkdir "$1" 2>/dev/null; then mv -f "$1.claim.$$" "$1/owner" && return 0 rm -rf "$1" @@ -125,23 +131,29 @@ take() { } # owner_of PATH — the token the lock PATH names, empty when it names none. owner_of() { if [ -L "$1" ]; then readlink "$1" 2>/dev/null; else head -1 "$1/owner" 2>/dev/null; fi; } -# orphaned PATH — PATH is a lock directory without an owner and no live -# claimant. Claims are read before the owner, so a taker that renames its -# claim in between is seen as the owner. An empty claim is a taker that has -# not reached its mkdir, so it never made this lock. +# orphaned PATH — PATH is a lock (not a legacy symlink) that names no owner, +# has no live claimant and is at least 2 s old. Claims are read before the +# owner, so a taker that renames its claim in between is seen as the owner; +# the age is read last, so a lock made since is too new. An empty claim is a +# taker that has not reached its mkdir, so it never made this lock. orphaned() { - [ -d "$1" ] && [ ! -L "$1" ] || return 1 + [ -e "$1" ] && [ ! -L "$1" ] || return 1 for _c in "$1".claim.*; do _t=$(head -1 "$_c" 2>/dev/null) [ -n "$_t" ] && ! holder_gone "$_t" && return 1 done - [ ! -e "$1/owner" ] + [ -z "$(owner_of "$1")" ] || return 1 + _m=$(stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null) || return 1 + [ $(( $(date +%s) - _m )) -ge 2 ] } # drop PATH — remove a lock in one step: a directory is renamed aside first, -# so nobody sees it ownerless on the way out. +# so nobody sees it ownerless on the way out. Once renamed the lock is +# released, whether or not the renamed copy can be deleted (touch prunes it). drop() { if [ -L "$1" ]; then rm -f "$1"; return; fi - mv "$1" "$1.gone.$$" 2>/dev/null && rm -rf "$1.gone.$$" + mv "$1" "$1.gone.$$" 2>/dev/null || return 1 + rm -rf "$1.gone.$$" 2>/dev/null + return 0 } lock() { [ -n "$TOKEN" ] || TOKEN="$$ $(identity $$)" @@ -163,7 +175,10 @@ lock() { sleep 0.1 done } -holder_gone() { case "$(state "${1%% *}" "${1#* }" 0)" in dead|stale) return 0 ;; esac; return 1; } +holder_gone() { + case "${1%% *}" in ''|*[!0-9]*|0|1) return 0 ;; esac + case "$(state "${1%% *}" "${1#* }" 0)" in dead|stale) return 0 ;; esac; return 1 +} # break_lock OWNER — remove the lock only if it still names OWNER (empty: is # still orphaned). Breakers take a second lock, .lock.break, and reread the # lock under it, so a lock taken since the verdict is never removed; a @@ -171,9 +186,9 @@ holder_gone() { case "$(state "${1%% *}" "${1#* }" 0)" in dead|stale) return 0 ; # aside is removed in place (other breakers wait on .lock.break meanwhile). # Returns 1 when another breaker holds .lock.break or the lock could not be # removed, so lock() counts the try instead of spinning. Known limit: that -# clear is not atomic, so two gstack-lease processes killed in a row (one -# holding .lock, the next inside this function) can let a reclaim delete a -# renewal; one crash is always safe. +# clear is check-then-remove, so a breaker killed while holding .lock.break, +# followed by two live breakers clearing it at once, can let both break and a +# reclaim delete a renewal. break_lock() { if ! take "$LOCK.break"; then _b=$(owner_of "$LOCK.break") @@ -219,7 +234,8 @@ case "$VERB" in } _tmp="$DIR/.$PID.$$" identity "$PID" > "$_tmp" && mv -f "$_tmp" "$DIR/$PID" || { rm -f "$_tmp"; unlock; exit 2; } - find "$DIR" -mmin +120 -type f -exec rm -f {} + 2>/dev/null + find "$DIR" -maxdepth 1 -mmin +120 -type f ! -name '.lock*' -exec rm -f {} + 2>/dev/null + rm -rf "$DIR"/.lock*.gone.* 2>/dev/null unlock exit 0 ;; list) diff --git a/docs/capy-install.md b/docs/capy-install.md index 4ab9e65e3d..2d14542fa5 100644 --- a/docs/capy-install.md +++ b/docs/capy-install.md @@ -126,14 +126,19 @@ deleted and a live lease never disappears from a concurrent scan. The lock is a directory because `mkdir` is atomic on every host, while Git Bash on Windows cannot `ln -s` to a target that does not exist (#3330). A taker publishes a claim before its `mkdir` and renames it in as the owner after, so an ownerless -lock is broken only once every claimant is dead. The lock is broken only when -its holder is dead or its pid was reused, never by age, and breakers serialize -on a second lock and reread the lock before removing it. A symlink `.lock` left -by an older gstack is honored the same way. One killed gstack-lease process -is always safe; two killed in a row, one holding the lock and the next while -breaking it, can still let a reclaim delete a renewal. While a live process holds it, -`touch` exits 3 without writing (`gstack-skill-start` reports that the -session holds no lease) and a reclaim keeps the lease. `bin/gstack-lease list` shows `alive|dead|stale`, and +lock (or one whose owner is empty or names no valid pid) is broken only once +every claimant is dead and the lock is at least 2 s old, which keeps a taker +between its two steps safe. The lock is broken only when its holder is dead or +its pid was reused, never by age, and breakers serialize on a second lock and +reread the lock before removing it. A symlink `.lock` left by an older gstack +is honored the same way. Two known limits remain. An older gstack's `ln -s` +onto a directory lock links inside it and succeeds, so a process that started +before an upgrade of this checkout can share the lock with a newer one. And a +breaker killed while holding the second lock, followed by two live breakers +clearing it at once, can let a reclaim delete a renewal. While a live process +holds the lock, or it cannot be taken at all, `touch` exits 3 without writing +(`gstack-skill-start` reports that the session holds no lease) and a reclaim +keeps the lease. `bin/gstack-lease list` shows `alive|dead|stale`, and `GSTACK_UPGRADE_FORCE=1` overrides. ## What the installer does diff --git a/test/gstack-lease-git-bash.test.ts b/test/gstack-lease-git-bash.test.ts index 8f2429c5ff..61cc68c185 100644 --- a/test/gstack-lease-git-bash.test.ts +++ b/test/gstack-lease-git-bash.test.ts @@ -73,7 +73,7 @@ describe('gstack-lease under Git Bash semantics (#3330)', () => { const script = [ 'set -u', 'mkdir -p "$LEASES/.lock" && printf "%s \\n" "$$" > "$LEASES/.lock/owner"', - 'GSTACK_LEASE_LOCK_TRIES=2 bash "$LEASE" touch --root "$ROOT" --pid 4244; echo "held=$? holder=$$"', + 'GSTACK_LEASE_LOCK_TRIES=2 bash "$LEASE" touch --root "$ROOT" --pid 4244; echo "held=$? holder=$$ owner=$(head -1 "$LEASES/.lock/owner")"', '( exit 0 ) & dead=$!; wait "$dead"', 'printf "%s \\n" "$dead" > "$LEASES/.lock/owner"', 'GSTACK_LEASE_LOCK_TRIES=2 bash "$LEASE" touch --root "$ROOT" --pid 4245; echo "dead=$?"', @@ -84,8 +84,9 @@ describe('gstack-lease under Git Bash semantics (#3330)', () => { }); const out = `${r.error ?? ''}${r.stdout}${r.stderr}`; expect(r.status, out).toBe(0); - const holder = /held=(\d+) holder=(\d+)/.exec(r.stdout); + const holder = /held=(\d+) holder=(\d+) owner=(\d+)/.exec(r.stdout); expect(holder?.[1], out).toBe('3'); + expect(holder?.[3], out).toBe(holder?.[2]); expect(r.stderr).toContain(`locked by live process ${holder?.[2]}`); expect(r.stdout, out).toContain('dead=0'); expect(fs.readdirSync(leases).sort()).toEqual(['4245']); diff --git a/test/gstack-lease.test.ts b/test/gstack-lease.test.ts index 35494b4454..a9ba000686 100644 --- a/test/gstack-lease.test.ts +++ b/test/gstack-lease.test.ts @@ -65,6 +65,11 @@ function plantLock(lockPath: string, token: string) { fs.writeFileSync(path.join(lockPath, 'owner'), token + '\n'); } const ownerOf = (lockPath: string) => fs.readFileSync(path.join(lockPath, 'owner'), 'utf8').trim(); +/** Backdate a lock a minute: an ownerless lock is broken only once it is 2 s old. */ +function age(lockPath: string) { + const minuteAgo = new Date(Date.now() - 60_000); + fs.utimesSync(lockPath, minuteAgo, minuteAgo); +} /** Each lock layout a holder can leave: the directory lock, and the symlink lock an older gstack took. */ const LAYOUTS: Array<[string, (lockPath: string, token: string) => void]> = [ @@ -273,15 +278,17 @@ describe('gstack-lease', () => { test('a lock held by a running gstack-lease excludes a second taker, which names it; both leases land once it is released', async () => { const { dir, leases } = checkout(); const [first, second] = [sleeper(), sleeper()]; - // The first touch holds the lock across its prune (find runs under the lock). - const slow = bashEnv(dir, 'find() { sleep 3; command find "$@"; }\n'); + // The first touch holds the lock across its prune (find runs under the lock) until the test releases it. + const release = path.join(dir, 'release'); + const slow = bashEnv(dir, `find() { until [ -e "${release}" ]; do sleep 0.05; done; command find "$@"; }\n`); const holder = spawn('bash', [LEASE, 'touch', '--root', dir, '--pid', String(first)], { env: { ...baseEnv, BASH_ENV: slow }, stdio: 'ignore' }); children.push(holder); const exited = new Promise((resolve) => holder.on('exit', resolve)); const owner = path.join(leases, '.lock', 'owner'); - for (let i = 0; i < 100 && !fs.existsSync(owner); i++) await Bun.sleep(20); + for (let i = 0; i < 500 && !fs.existsSync(owner); i++) await Bun.sleep(20); expect(fs.readFileSync(owner, 'utf8')).toMatch(new RegExp(`^${holder.pid} `)); const blocked = run(['touch', '--root', dir, '--pid', String(second)], { GSTACK_LEASE_LOCK_TRIES: '3' }); + fs.writeFileSync(release, ''); expect(blocked.status, blocked.stdout + blocked.stderr).toBe(3); expect(blocked.stderr).toContain(`locked by live process ${holder.pid};`); expect(await exited).toBe(0); @@ -292,12 +299,17 @@ describe('gstack-lease', () => { test('parallel touches all take the lock in turn and leave no lock, claim or temp file behind', async () => { const { dir, leases } = checkout(); const pids = Array.from({ length: 16 }, (_, i) => 4300 + i); + // The prune runs under the lock: a second process inside it at the same time logs an overlap. + const inside = path.join(dir, 'inside'); + const overlaps = path.join(dir, 'overlaps.log'); + const probe = bashEnv(dir, `find() { command mkdir "${inside}" 2>/dev/null || echo overlap >> "${overlaps}"; sleep 0.05; command rmdir "${inside}" 2>/dev/null; command find "$@"; }\n`); const codes = await Promise.all(pids.map((p) => new Promise((resolve) => { - const c = spawn('bash', [LEASE, 'touch', '--root', dir, '--pid', String(p)], { env: baseEnv, stdio: 'ignore' }); + const c = spawn('bash', [LEASE, 'touch', '--root', dir, '--pid', String(p)], { env: { ...baseEnv, BASH_ENV: probe }, stdio: 'ignore' }); children.push(c); c.on('exit', resolve); }))); expect(codes).toEqual(pids.map(() => 0)); + expect(fs.existsSync(overlaps), 'two touches were inside the lock at once').toBe(false); expect(fs.readdirSync(leases).sort()).toEqual(pids.map(String).sort()); }); @@ -307,6 +319,7 @@ describe('gstack-lease', () => { const holder = sleeper(); const lockPath = path.join(leases, '.lock'); fs.mkdirSync(lockPath, { recursive: true }); + age(lockPath); fs.writeFileSync(path.join(leases, `.lock.claim.${holder}`), `${holder} \n`); const kept = run(['touch', '--root', dir, '--pid', String(holder)], { GSTACK_LEASE_LOCK_TRIES: '3' }); expect(kept.status, kept.stdout + kept.stderr).toBe(3); @@ -318,6 +331,7 @@ describe('gstack-lease', () => { fs.renameSync(path.join(leases, `.lock.claim.${holder}`), path.join(leases, `.lock.claim.${dead}`)); fs.writeFileSync(path.join(leases, `.lock.claim.${dead}`), `${dead} \n`); fs.writeFileSync(path.join(leases, '.lock.claim.1'), ''); + age(lockPath); const broken = run(['touch', '--root', dir, '--pid', String(holder)], { GSTACK_LEASE_LOCK_TRIES: '3' }); expect(broken.status, broken.stdout + broken.stderr).toBe(0); expect(fs.existsSync(path.join(leases, String(holder)))).toBe(true); @@ -325,11 +339,71 @@ describe('gstack-lease', () => { fs.rmSync(path.join(leases, `.lock.claim.${dead}`)); fs.mkdirSync(lockPath); + age(lockPath); const unclaimed = run(['touch', '--root', dir, '--pid', String(holder)], { GSTACK_LEASE_LOCK_TRIES: '3' }); expect(unclaimed.status, unclaimed.stdout + unclaimed.stderr).toBe(0); expect(fs.existsSync(lockPath)).toBe(false); }); + // Value: protects=an ownerless lock younger than 2 s is never broken, so a live taker whose claim landed after the breaker read the claims keeps + // the lock it is about to publish; a malformed lock (empty owner, pid 0, or a stray file) is broken once old instead of wedging every touch; + // fails_when=orphaned() drops its age check, or treats only a missing owner file (not an empty or invalid one) as ownerless; + // why_new=the ownerless cases above all backdate the lock; nothing pins the young-lock guard or the malformed shapes; + // seam=none; no_claim=the claim-read race itself (a young unclaimed lock stands in for a taker whose claim the breaker missed) + test('an ownerless lock is broken only once it is 2 s old, and a malformed lock is treated as ownerless', () => { + const { dir, leases } = checkout(); + const holder = sleeper(); + const lockPath = path.join(leases, '.lock'); + fs.mkdirSync(lockPath, { recursive: true }); + const young = run(['touch', '--root', dir, '--pid', String(holder)], { GSTACK_LEASE_LOCK_TRIES: '3' }); + expect(young.status, young.stdout + young.stderr).toBe(3); + expect(fs.existsSync(lockPath)).toBe(true); + expect(fs.existsSync(path.join(leases, String(holder)))).toBe(false); + + const shapes: Array<[string, () => void]> = [ + ['an empty owner file', () => plantLock(lockPath, '')], + ['owner pid 0', () => plantLock(lockPath, '0 ')], + ['a stray file', () => { fs.rmSync(lockPath, { recursive: true, force: true }); fs.writeFileSync(lockPath, ''); }], + ]; + for (const [shape, plant] of shapes) { + fs.rmSync(lockPath, { recursive: true, force: true }); + fs.rmSync(path.join(leases, String(holder)), { force: true }); + plant(); + age(lockPath); + const r = run(['touch', '--root', dir, '--pid', String(holder)], { GSTACK_LEASE_LOCK_TRIES: '3' }); + expect(r.status, `${shape}: ${r.stdout}${r.stderr}`).toBe(0); + expect(fs.readdirSync(leases), shape).toEqual([String(holder)]); + } + }); + + // Value: protects=a holder that resumes past the 120-minute prune window keeps its own lock metadata, so unlock still recognizes and removes it; + // fails_when=touch's prune recurses into .lock (deleting owner) or matches lock files at the top level; + // why_new=the prune test plants only lease files; none ages the lock's owner file before the prune runs; + // seam=none; no_claim=a real suspension (a BASH_ENV find shim backdates the owner file just before the prune) + test('the 120-minute prune never deletes the lock it runs under', () => { + const { dir, leases } = checkout(); + const holder = sleeper(); + const shim = bashEnv(dir, 'find() { command touch -d "3 hours ago" "$1/.lock/owner" 2>/dev/null || command touch -t 197001010000 "$1/.lock/owner"; command find "$@"; }\n'); + const r = run(['touch', '--root', dir, '--pid', String(holder)], { BASH_ENV: shim }); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(fs.readdirSync(leases)).toEqual([String(holder)]); + }); + + // Value: protects=once a lock is renamed aside it is released: a failed delete of the renamed copy never removes a lock a new taker made at .lock; + // fails_when=drop() reports failure after a successful rename, so unlock's in-place rm -rf fallback runs on the new taker's lock; + // why_new=the rename-aside tests fail the rename itself; none lets the rename succeed and the delete fail; + // seam=none; no_claim=a real new taker in that window (the rm shim plants one, then fails like a Windows file in use) + test('a renamed-aside lock that cannot be deleted never takes a new taker\'s lock with it', () => { + const { dir, leases } = checkout(); + const [holder, taker] = [sleeper(), sleeper()]; + const lockPath = path.join(leases, '.lock'); + const shim = bashEnv(dir, `rm() { case "$*" in *".lock.gone."*) command mkdir "${lockPath}" && printf '%s \\n' "${taker}" > "${lockPath}/owner"; return 1 ;; esac; command rm "$@"; }\n`); + const r = run(['touch', '--root', dir, '--pid', String(holder)], { BASH_ENV: shim }); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(ownerOf(lockPath)).toBe(String(taker)); + expect(fs.existsSync(path.join(leases, String(holder)))).toBe(true); + }); + test('a lock that cannot be taken while nobody holds it fails at once instead of waiting out the tries', () => { const { dir, leases } = checkout(); const holder = sleeper(); @@ -363,6 +437,7 @@ describe('gstack-lease', () => { fs.rmSync(breakPath, { recursive: true }); fs.mkdirSync(breakPath); + age(breakPath); fs.writeFileSync(path.join(leases, `.lock.break.claim.${breaker}`), `${breaker} \n`); const claimed = run(['touch', '--root', dir, '--pid', String(holder)], { GSTACK_LEASE_LOCK_TRIES: '3' }); expect(claimed.status, claimed.stdout + claimed.stderr).toBe(3); @@ -371,6 +446,7 @@ describe('gstack-lease', () => { expect(fs.existsSync(path.join(leases, String(holder)))).toBe(false); fs.rmSync(path.join(leases, `.lock.break.claim.${breaker}`)); + age(breakPath); const orphaned = run(['touch', '--root', dir, '--pid', String(holder)], { GSTACK_LEASE_LOCK_TRIES: '5' }); expect(orphaned.status, orphaned.stdout + orphaned.stderr).toBe(0); expect(fs.readdirSync(leases)).toEqual([String(holder)]);