codeburn/app/electron/tray-settings-lock.test.ts
iamtoruk a1b4b22f51 fix(windows): close three holes in the cross-process preference lock
writeDockEnabled still did its own read, mutate and atomic write of
windows-dock.json, outside the lock the rest of the module takes. It is
the Node side of the dock's enabled switch, reached from the desktop
app's Sidebar toggle, so a toggle there could still land between the
tray app's read and its rename and erase whatever it had just stored,
which in practice is the rail's placement. It now merges through
patchTrayFile, which takes the lock for the whole cycle; enabled is
already an accepted dock key, so nothing is dropped on the way.

Stale-lock recovery could hand out two owners at once. Both sides did
"if abandoned, unlink and retry", and nothing stood between the check
and the unlink: contender A could already have removed the stale lock
and created a fresh one of its own, and B's unlink then deleted A's
fresh lock, leaving both of them holding the file. Windows' share mode
hides this most of the time, because a lock a live holder still has open
will not unlink at all, but the same protocol runs on Linux and macOS,
where the unlink always succeeds. Removing an abandoned lock is now
itself arbitrated, by the same exclusive create the lock uses, on a
sibling <lock>.takeover file. Only its winner may unlink, and only after
re-checking staleness under that right, so a rival that reclaimed first
keeps the lock it now holds. A takeover file is dropped on every path
out, never held across the wait, and one left behind by a reclaimer that
died is freed by the same staleness rule as the lock itself.

The cross-process test asserted only each side's final value, so it
noticed a lost update only when the last writes happened to collide: on
a deliberately broken lock it passed about one run in three, which is
weak evidence for the property it exists to prove. Each side now writes
a counter that only rises, and a reader thread watches the file for the
whole run. A separate reader is the point: neither writer can see its
own counter rolled back, because in the unlocked cycle each carries the
other side's value forward itself, so what it reads back is never older
than what it last read. With the lock both counters only ever rise in
the file; without it one falls. It now fails on every unlocked run.

Also: a placement that cannot be saved is logged instead of discarded
silently, since losing the lock under contention is a new way for the
rail to revert at the next launch; and the Codex sameLogin comment now
states outright that a replacement document carrying none of the three
identifying fields reads as the same login and is written over, which is
the deliberate side to err on.
2026-09-03 10:28:05 -07:00

112 lines
5.4 KiB
TypeScript

// @vitest-environment node
// The cross-process lock that serializes the read/modify/write of the tray app's files. These
// are the single-process unit tests (taken and released, a stale lock taken over, a dead
// holder's lock taken over, a live lock waited for, an abandoned lock left alone while someone
// else holds the right to reclaim it, and the merge preserving the other side's keys); the real
// Node-against-Rust contention test lives in windows/src-tauri/src/dock.rs.
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { acquireTrayFileLock, patchTrayFile, releaseTrayFileLock } from './tray-settings'
let home: string
const dockTarget = () => join(home, '.config', 'codeburn', 'windows-dock.json')
const lockPath = () => join(home, '.config', 'codeburn', '.windows-dock.lock')
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), 'tray-lock-'))
mkdirSync(join(home, '.config', 'codeburn'), { recursive: true })
})
afterEach(() => { rmSync(home, { recursive: true, force: true }) })
describe('the cross-process preference lock', () => {
it('takes the lock and releases it again', () => {
const fd = acquireTrayFileLock(dockTarget())
expect(existsSync(lockPath())).toBe(true)
expect(JSON.parse(readFileSync(lockPath(), 'utf8')).pid).toBe(process.pid)
releaseTrayFileLock(dockTarget(), fd)
expect(existsSync(lockPath())).toBe(false)
})
it('takes over a lock whose mtime is past the stale window', () => {
// A live pid (our own), so only the age gate can free it. Backdate the mtime rather than
// sleeping for the whole window.
writeFileSync(lockPath(), JSON.stringify({ pid: process.pid, at: 1 }))
const old = new Date(Date.now() - 60_000)
utimesSync(lockPath(), old, old)
const fd = acquireTrayFileLock(dockTarget(), { staleMs: 30_000, waitMs: 500 })
expect(JSON.parse(readFileSync(lockPath(), 'utf8')).pid).toBe(process.pid)
releaseTrayFileLock(dockTarget(), fd)
})
it('takes over a dead holder without waiting out the budget', () => {
// A pid that is not us and is almost certainly gone, with a fresh mtime: only the pid probe,
// not the age gate, can free this one.
writeFileSync(lockPath(), JSON.stringify({ pid: 2_147_483_646, at: Date.now() }))
const started = Date.now()
const fd = acquireTrayFileLock(dockTarget(), { staleMs: 60_000, waitMs: 1_000, pollMs: 20 })
expect(Date.now() - started).toBeLessThan(400)
releaseTrayFileLock(dockTarget(), fd)
})
it('waits for a live lock and then fails loudly rather than writing behind it', () => {
const held = acquireTrayFileLock(dockTarget())
const started = Date.now()
// Our own pid reads as alive and the mtime is fresh, so the lock is never abandoned.
expect(() => acquireTrayFileLock(dockTarget(), { staleMs: 60_000, waitMs: 150, pollMs: 20 }))
.toThrow(/could not lock/)
expect(Date.now() - started).toBeGreaterThanOrEqual(130)
releaseTrayFileLock(dockTarget(), held)
})
it('leaves an abandoned lock alone while another process holds the takeover right', () => {
// Abandoned by the age gate, so without the takeover right any contender would remove it.
writeFileSync(lockPath(), JSON.stringify({ pid: process.pid, at: 1 }))
const old = new Date(Date.now() - 60_000)
utimesSync(lockPath(), old, old)
// A reclaim already in progress: a fresh mtime and a live pid, so the takeover file is not
// itself abandoned. The contender that finds it must not touch the lock, because the
// reclaimer may already have replaced it with a fresh lock of its own, and removing that
// would leave the two of them holding the file at once.
const takeover = `${lockPath()}.takeover`
writeFileSync(takeover, JSON.stringify({ pid: process.pid, at: Date.now() }))
expect(() => acquireTrayFileLock(dockTarget(), { staleMs: 30_000, waitMs: 100, pollMs: 20 }))
.toThrow(/could not lock/)
expect(existsSync(lockPath())).toBe(true)
// With nobody reclaiming, the same abandoned lock is taken over as it always was, and the
// takeover file is not left behind.
rmSync(takeover)
const fd = acquireTrayFileLock(dockTarget(), { staleMs: 30_000, waitMs: 500, pollMs: 20 })
expect(JSON.parse(readFileSync(lockPath(), 'utf8')).pid).toBe(process.pid)
expect(existsSync(takeover)).toBe(false)
releaseTrayFileLock(dockTarget(), fd)
})
it('leaves a successor lock alone on release', () => {
const fd = acquireTrayFileLock(dockTarget())
// Simulate a successor that took over after us (only possible past the stale window).
writeFileSync(lockPath(), JSON.stringify({ pid: process.pid + 1, at: Date.now() }))
releaseTrayFileLock(dockTarget(), fd)
expect(existsSync(lockPath())).toBe(true)
expect(JSON.parse(readFileSync(lockPath(), 'utf8')).pid).toBe(process.pid + 1)
})
it('still merges keys the other side owns, and cleans up its lock', () => {
writeFileSync(dockTarget(), JSON.stringify({ enabled: true, placement: { docked: 'right' } }))
expect(patchTrayFile('dock', { scale: 1.1 }, home)).toEqual({
enabled: true,
placement: { docked: 'right' },
scale: 1.1,
})
// No lock file is left behind once the patch returns.
expect(existsSync(lockPath())).toBe(false)
expect(() => statSync(lockPath())).toThrow()
})
})