diff --git a/changelog.d/1217.fixed.md b/changelog.d/1217.fixed.md new file mode 100644 index 00000000..652ac6e9 --- /dev/null +++ b/changelog.d/1217.fixed.md @@ -0,0 +1 @@ +Both fixes are about the backup lock that keeps one run per `BACKUP_DIR`. A lock or takeover marker now names its holder's process start time beside the pid, so a lock left by a killed run whose pid the kernel has since reused is taken over instead of refusing every backup until that unrelated process exits; a lock written before the field existed keeps its old meaning and still refuses on a live pid. The takeover marker is also released only by the run that wrote it: a run that is stopped inside the takeover for longer than the grace, and resumes after another run has swept its marker and taken its own, no longer deletes that marker — so a third run can no longer create one and write beside a live holder. diff --git a/docs/deploy.md b/docs/deploy.md index 8cdb640b..2585ac25 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -1214,8 +1214,18 @@ and the recreate: several runs that judge the same dead lock stale can therefore not delete each other's fresh lock and all write in the directory — the concurrent-run defect the lock exists to stop. A lock file that exists but cannot be read is only taken over once it is a minute old, so a run that is mid-creation -is never robbed. The -directory is also read as a directory of files: an entry that is not a regular +is never robbed. The lock and the marker both name their holder twice: the pid, +and the process start time the kernel gives that pid. The start time is what makes +a reused number harmless — a dead run's lock whose pid some unrelated process has +since inherited is alive by pid alone and refuses every run until that process +exits, while with the start time recorded the number is judged stale and the +takeover proceeds. A lock written before the field existed carries the pid only +and keeps the old meaning, so a live pid still refuses; nothing can tell a reused +number from its holder without it. The marker is released by identity for the +same reason: a run stopped inside the takeover for longer than the grace has its +marker swept and replaced, and when it resumes it removes only the entry it +wrote, leaving the current holder's marker — and the section it guards — alone. +The directory is also read as a directory of files: an entry that is not a regular file (a directory or a symlink named like a copy) is never treated as a copy and is never deleted — the writer and the dry run now use the same classifier, so a copy the console counts is a copy the writer may prune. diff --git a/scripts/backup.mjs b/scripts/backup.mjs index 8be5d026..4445a126 100644 --- a/scripts/backup.mjs +++ b/scripts/backup.mjs @@ -151,22 +151,65 @@ const LOCK_TAKEOVER_GRACE_MS = 10_000 // write rather than a run in the middle of those two calls. const LOCK_UNREADABLE_GRACE_MS = 60_000 -function readLockPid(lockPath) { +// Field 22 of /proc//stat: the process start time, in clock ticks since +// boot. A pid is not an identity — the kernel reuses the number — so the holder's +// start time is recorded beside its pid, and a live pid whose start time differs +// is a different process that inherited the number (#1217). The command name is +// parenthesised and may contain spaces, so fields are counted from the last `)`. +// Where /proc is unavailable this answers null and the pid alone decides, exactly +// as before. +function processStartTime(pid) { try { - const pid = Number(readFileSync(lockPath, 'utf8').trim()) - return Number.isInteger(pid) && pid > 0 ? pid : null + const stat = readFileSync(`/proc/${String(pid)}/stat`, 'utf8') + const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ') + const start = Number(fields[19]) + return Number.isFinite(start) && start > 0 ? start : null } catch { return null } } +// What the lock and the marker carry: the holder's pid and start time. The pid +// stays the first token, so a lock written before this field still parses and +// every refusal keeps naming it. +const SELF_START_TIME = processStartTime(process.pid) + +function lockText() { + return SELF_START_TIME === null ? String(process.pid) : `${String(process.pid)} ${String(SELF_START_TIME)}` +} + +function readLockRecord(lockPath) { + try { + const [pidToken, startToken] = readFileSync(lockPath, 'utf8').trim().split(/\s+/) + const pid = Number(pidToken) + const startTime = Number(startToken) + return { + pid: Number.isInteger(pid) && pid > 0 ? pid : null, + startTime: Number.isFinite(startTime) && startTime > 0 ? startTime : null, + } + } catch { + return null + } +} + +function readLockPid(lockPath) { + return readLockRecord(lockPath)?.pid ?? null +} + // One read of the entry: the pid it names and the identity of the file itself. // The identity is what tells "the same dead lock I judged" from "a lock another // run created since". function lockSnapshot(lockPath) { const stat = statOrNull(lockPath) if (stat === null) return null - return { pid: readLockPid(lockPath), mtimeMs: stat.mtimeMs, ino: stat.ino, dev: stat.dev } + const record = readLockRecord(lockPath) + return { + pid: record?.pid ?? null, + startTime: record?.startTime ?? null, + mtimeMs: stat.mtimeMs, + ino: stat.ino, + dev: stat.dev, + } } function sameLock(left, right) { @@ -174,6 +217,7 @@ function sameLock(left, right) { left !== null && right !== null && left.pid === right.pid && + left.startTime === right.startTime && left.mtimeMs === right.mtimeMs && left.ino === right.ino && left.dev === right.dev @@ -187,14 +231,22 @@ function lockIsStale(snapshot) { // A young lock is never stale, dead pid or not: its holder may be one // instruction from writing its pid, and its exit handler releases it. if (age <= LOCK_TAKEOVER_GRACE_MS) return false + let gone = false try { process.kill(snapshot.pid, 0) - return false } catch (error) { // ESRCH: no such process, so the lock outlived its holder. EPERM: the process // exists under another account, which is still a holder. - return error?.code === 'ESRCH' + if (error?.code === 'ESRCH') gone = true } + if (gone) return true + // Alive, but a live number is not the same process: if the holder recorded its + // start time and the process behind that pid now has another, the number was + // reused and the lock is a dead run's. A pid-only lock cannot say either way, + // so it keeps refusing, as it always did. + if (snapshot.startTime === null) return false + const liveStart = processStartTime(snapshot.pid) + return liveStart !== null && liveStart !== snapshot.startTime } function acquireLock(dir) { @@ -203,7 +255,7 @@ function acquireLock(dir) { for (let attempt = 0; attempt < 3; attempt += 1) { try { // O_CREAT|O_EXCL: the first run to create the entry holds the directory. - writeFileSync(lockPath, String(process.pid), { flag: 'wx', mode: 0o600 }) + writeFileSync(lockPath, lockText(), { flag: 'wx', mode: 0o600 }) return lockPath } catch (error) { if (error?.code !== 'EEXIST') fail(2, `cannot lock the backup directory: ${error instanceof Error ? error.message : String(error)}`) @@ -222,8 +274,14 @@ function acquireLock(dir) { // The marker makes the remove-then-create a critical section; a run that // cannot take it lets the holder do the takeover and comes back to see the // lock it created. + // The marker this run wrote, read back as the identity its release must + // match. A successful `O_EXCL` create is this run's; the snapshot is taken + // immediately so a later release cannot confuse "the marker I made" with + // "a marker another run made at the same path" (#1217). + let markerSnapshot = null try { - writeFileSync(takeoverPath, String(process.pid), { flag: 'wx', mode: 0o600 }) + writeFileSync(takeoverPath, lockText(), { flag: 'wx', mode: 0o600 }) + markerSnapshot = lockSnapshot(takeoverPath) } catch (error) { if (error?.code !== 'EEXIST') fail(2, `cannot lock the backup directory: ${error instanceof Error ? error.message : String(error)}`) // The marker is held only across the two calls below, so an old one is a @@ -252,7 +310,14 @@ function acquireLock(dir) { } catch (error) { takeoverError = error } finally { - rmSync(takeoverPath, { force: true }) + // #1217: release by identity, not by path. A run stopped inside this + // section for longer than the grace has had its marker swept and + // replaced, so an unconditional remove here deletes the marker the + // current holder is relying on, and a third run can then create its own + // and enter the same section. The rule is the lock's exit release: only + // the entry this run wrote is removed; anything else is left for its + // holder to release. + if (sameLock(markerSnapshot, lockSnapshot(takeoverPath))) rmSync(takeoverPath, { force: true }) } if (takeoverError !== null) { fail(2, `cannot take the backup lock ${lockPath}: ${takeoverError instanceof Error ? takeoverError.message : String(takeoverError)}`) diff --git a/test/backupLock.test.ts b/test/backupLock.test.ts new file mode 100644 index 00000000..99595b53 --- /dev/null +++ b/test/backupLock.test.ts @@ -0,0 +1,351 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { spawn, spawnSync } from 'node:child_process' +import type { ChildProcess } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, utimesSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { Store } from '../src/db.js' +import { makeUser } from './helpers.js' + +// #1217: the takeover marker is serialised by path, not by ownership. The run +// that creates it writes its pid, but the release is a bare +// `rmSync(takeoverPath, { force: true })`, so a run that no longer holds the +// marker still removes whatever is there — including the marker a later run +// holds inside the same critical section. The lock it stands in for already +// releases by identity (pid read back at exit, `sameLock` inside the section); +// this file proves the marker does not. +// +// The window is sub-millisecond, so it is widened from the test side rather than +// with SIGSTOP: a `--require` fixture patches `node:fs` before the script's +// named imports bind, and a run that is about to remove the lock while a marker +// exists signals the test and holds there. That is the same stall a suspended +// host produces, but deterministic. +// +// The second half of the card is the same mistake one layer down: a pid is not an +// identity, and the lock recorded only a number. A dead holder whose number the +// kernel has since reused reads as alive, so the directory refuses every run until +// that unrelated process happens to exit. The holder also records its start time, +// and a reader compares it — a two-token entry is judged on the process it names, +// not on being unparseable. + +const backupScript = fileURLToPath(new URL('../scripts/backup.mjs', import.meta.url)) + +const LOCK = '.fledge-backup.lock' +const MARKER = '.fledge-backup.lock.takeover' +// Outside the kernel's pid range: a pid that cannot be alive, i.e. the lock a +// SIGKILLed run leaves. The file is aged past the takeover grace for the same +// reason — a lock created milliseconds ago is never a takeover candidate. +const DEAD_PID = '2147483647' +const LONG_AGO = (): number => Date.now() / 1000 - 60 + +// Runs before `scripts/backup.mjs` imports `node:fs`, so the binding the script +// calls is this function. It holds the first time a process is about to remove +// the lock while a takeover marker exists — the critical section the marker +// guards — and never again, so the process can still release its own lock at +// exit without a second hold. +const FIXTURE = ` +const fs = require('node:fs') +const { basename, dirname, join } = require('node:path') +const realRmSync = fs.rmSync +const stallMs = Number(process.env.FLEDGE_TEST_STALL_MS || 0) +let held = false +fs.rmSync = function rmSync(target, options) { + if (!held && stallMs > 0 && typeof target === 'string' && basename(target) === '${LOCK}') { + if (fs.existsSync(join(dirname(target), '${MARKER}'))) { + held = true + const signalDir = process.env.FLEDGE_TEST_SIGNAL_DIR + if (signalDir) fs.writeFileSync(join(signalDir, 'stalled-' + process.pid), '') + const until = Date.now() + stallMs + while (Date.now() < until) { + // Hold the critical section, exactly as a stopped host would. + } + } + } + return realRmSync(target, options) +} +` + +function seed(dbPath: string): void { + const store = new Store(dbPath) + try { + const user = makeUser(store, { login: 'marker-user', status: 'approved' }) + store.createRepo({ + id: 'repo_marker', + userId: user.id, + owner: 'o', + name: 'marker', + defaultBranch: 'main', + tokenEnc: 'x', + permission: 'admin', + repoRole: 'maintainer', + goal: '', + autoIterate: false, + intervalMinutes: 1440, + }) + } finally { + store.close() + } +} + +function copies(dir: string): string[] { + return existsSync(dir) + ? readdirSync(dir) + .filter((name) => name.startsWith('fledge-') && name.endsWith('.db')) + .sort() + : [] +} + +function childEnv(env: Record): Record { + const inherited: Record = {} + for (const [name, value] of Object.entries(process.env)) { + if (value === undefined) continue + if (name === 'NODE_OPTIONS' || name.startsWith('FLEDGE_TEST_')) continue + inherited[name] = value + } + return { ...inherited, ...env } +} + +interface Run { + pid: number + child: ChildProcess + done: Promise<{ code: number | null; signal: string | null; stdout: string; stderr: string }> +} + +function startBackup(dbPath: string, backupDir: string, env: Record = {}): Run { + const child = spawn(process.execPath, [backupScript, '--db', dbPath, '--backup-dir', backupDir, '--keep', '10'], { + stdio: ['ignore', 'pipe', 'pipe'], + env: childEnv(env), + }) + let stdout = '' + let stderr = '' + child.stdout?.setEncoding('utf8').on('data', (chunk: string) => { + stdout += chunk + }) + child.stderr?.setEncoding('utf8').on('data', (chunk: string) => { + stderr += chunk + }) + const done = new Promise<{ code: number | null; signal: string | null; stdout: string; stderr: string }>((resolve) => { + child.on('close', (code, signal) => resolve({ code, signal, stdout, stderr })) + }) + return { pid: child.pid ?? -1, child, done } +} + +// The fixture writes `stalled-` when it holds. A run that exits first is a +// failure of the harness, not of the code, and its stderr says why. +async function waitForSignal(dir: string, run: Run, label: string): Promise { + const path = join(dir, `stalled-${run.pid}`) + const exited = run.done.then((result) => ({ result })) + for (let attempt = 0; attempt < 2000; attempt += 1) { + if (existsSync(path)) return + const early = await Promise.race([exited, new Promise((resolve) => setTimeout(() => resolve(null), 5))]) + if (early !== null) { + throw new Error(`${label} exited before reaching the section (exit ${String(early.result.code)}): ${early.result.stderr}`) + } + } + throw new Error(`${label} never signalled while holding the marker`) +} + +function plantDeadLock(backupDir: string, content: string = DEAD_PID): void { + const path = join(backupDir, LOCK) + writeFileSync(path, content, { mode: 0o600 }) + utimesSync(path, LONG_AGO(), LONG_AGO()) +} + +function assertRefusal(result: { code: number | null; stdout: string; stderr: string }, label: string): void { + assert.equal(result.code, 1, `${label} must refuse, got exit ${String(result.code)}: ${result.stdout}`) + assert.match(result.stderr, /^backup: another backup run holds /m, `${label} names the refusal: ${result.stderr}`) + assert.doesNotMatch(result.stderr, /\n\s+at /, `${label} died with an uncaught stack: ${result.stderr}`) +} + +test('a straggler that resumes must not remove the marker a live run holds', async () => { + const root = mkdtempSync(join(tmpdir(), 'fledge-marker-')) + const dbPath = join(root, 'fledge.db') + const backupDir = join(root, 'backups') + const signals = join(root, 'signals') + seed(dbPath) + mkdirSync(backupDir, { recursive: true, mode: 0o700 }) + mkdirSync(signals) + writeFileSync(join(root, 'hook.cjs'), FIXTURE) + plantDeadLock(backupDir) + + // A judges the dead lock stale, creates its marker and stalls inside the + // section — the stopped host of the issue's sequence. + const a = startBackup(dbPath, backupDir, { + NODE_OPTIONS: `--require ${join(root, 'hook.cjs')}`, + FLEDGE_TEST_STALL_MS: '2000', + FLEDGE_TEST_SIGNAL_DIR: signals, + }) + await waitForSignal(signals, a, 'run A') + assert.ok(existsSync(join(backupDir, MARKER)), 'A holds a marker while it is stalled') + + // A stall longer than the grace is what makes A's marker abandoned; the test + // does not wait 10 s to get there, it ages the file instead. + utimesSync(join(backupDir, MARKER), LONG_AGO(), LONG_AGO()) + + // B sweeps A's abandoned marker, takes its own and stalls in the same section, + // holding that marker while the dead lock is still in place. + const b = startBackup(dbPath, backupDir, { + NODE_OPTIONS: `--require ${join(root, 'hook.cjs')}`, + FLEDGE_TEST_STALL_MS: '15000', + FLEDGE_TEST_SIGNAL_DIR: signals, + }) + await waitForSignal(signals, b, 'run B') + + // A resumes and reaches its release while B is inside the section. Today it + // removes B's marker; the release must be a no-op when the file is not A's. + const aResult = await a.done + assert.equal(aResult.code, 0, `A's run is honest: ${aResult.stderr}`) + assert.equal( + existsSync(join(backupDir, MARKER)), + true, + "A's release removed a marker it did not hold, so the section is now open", + ) + // A crashed run's lock, so the third run has a stale lock to judge — the + // ordinary reason a run reaches the marker at all. + plantDeadLock(backupDir) + const before = copies(backupDir) + + const c = startBackup(dbPath, backupDir) + const cResult = await c.done + + assertRefusal(cResult, 'run C') + assert.match( + cResult.stderr, + new RegExp(`\\(pid ${String(b.pid)}\\)`), + `the refusal must name B, the live holder: ${cResult.stderr}`, + ) + assert.deepEqual(copies(backupDir), before, 'C must not write a copy beside a live holder in the section') + + b.child.kill('SIGKILL') + await b.done +}) + +// A pid is not an identity: the kernel reuses numbers, and a lock left by a dead +// run could name a pid that some unrelated process now has. `process.kill(pid, 0)` +// says "alive" and the directory refuses every run until that process exits. The +// holder records its start time beside its pid so a reused number is judged stale; +// a lock written before that field keeps its old meaning and still refuses. +function selfStartTime(pid: number): number { + const stat = readFileSync(`/proc/${String(pid)}/stat`, 'utf8') + const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ') + return Number(fields[19]) +} + +test('a live pid that no longer names its holder is judged stale', () => { + const root = mkdtempSync(join(tmpdir(), 'fledge-marker-')) + const dbPath = join(root, 'fledge.db') + const backupDir = join(root, 'backups') + seed(dbPath) + mkdirSync(backupDir, { recursive: true, mode: 0o700 }) + // This test process is alive, so the pid probe says "alive"; the recorded start + // time is one tick off, so the number was reused by something unrelated. + plantDeadLock(backupDir, `${String(process.pid)} ${String(selfStartTime(process.pid) + 1)}`) + + const run = spawnSync(process.execPath, [backupScript, '--db', dbPath, '--backup-dir', backupDir], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + env: childEnv({}), + }) + + assert.equal(run.status, 0, `a reused pid must not block the takeover: ${run.stderr}`) + assert.match(run.stdout, /^backup: OK$/m) + assert.equal(existsSync(join(backupDir, MARKER)), false, 'the takeover leaves no marker') + assert.equal(existsSync(join(backupDir, LOCK)), false, 'the run releases its own lock') +}) + +test('a pid-only lock held by a live process still refuses', () => { + const root = mkdtempSync(join(tmpdir(), 'fledge-marker-')) + const dbPath = join(root, 'fledge.db') + const backupDir = join(root, 'backups') + seed(dbPath) + mkdirSync(backupDir, { recursive: true, mode: 0o700 }) + // The old file shape: one token, no start time. Nothing can tell a live holder + // from a reused pid here, so the safe answer stays the refusal. + plantDeadLock(backupDir, String(process.pid)) + + const run = spawnSync(process.execPath, [backupScript, '--db', dbPath, '--backup-dir', backupDir], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + env: childEnv({}), + }) + + assert.equal(run.status, 1, `a live pid-only holder must refuse, got ${run.stdout}`) + assert.match(run.stderr, new RegExp(`\\(pid ${String(process.pid)}\\)`), run.stderr) + assert.equal(existsSync(join(backupDir, LOCK)), true, 'a refusal leaves the holder\'s lock alone') +}) + +test('the marker a taking-over run writes records its pid and start time', async () => { + const root = mkdtempSync(join(tmpdir(), 'fledge-marker-')) + const dbPath = join(root, 'fledge.db') + const backupDir = join(root, 'backups') + const signals = join(root, 'signals') + seed(dbPath) + mkdirSync(backupDir, { recursive: true, mode: 0o700 }) + mkdirSync(signals) + writeFileSync(join(root, 'hook.cjs'), FIXTURE) + plantDeadLock(backupDir) + + const a = startBackup(dbPath, backupDir, { + NODE_OPTIONS: `--require ${join(root, 'hook.cjs')}`, + FLEDGE_TEST_STALL_MS: '15000', + FLEDGE_TEST_SIGNAL_DIR: signals, + }) + await waitForSignal(signals, a, 'run A') + + // The entry names the holder twice: the pid every reader and every refusal + // message already used, and the start time that tells a reused number from the + // process that wrote it. A one-token entry cannot be told either way, and the + // base writes one. + const [pid, startTime, ...rest] = readFileSync(join(backupDir, MARKER), 'utf8').trim().split(/\s+/) + assert.equal(Number(pid), a.pid, `the marker names its holder: ${String(pid)}`) + assert.equal(Number(startTime), selfStartTime(a.pid), "the marker records the holder's start time") + assert.deepEqual(rest, [], 'the marker carries no third field') + + a.child.kill('SIGKILL') + await a.done +}) + +test('a live holder whose recorded start time matches still refuses', () => { + const root = mkdtempSync(join(tmpdir(), 'fledge-marker-')) + const dbPath = join(root, 'fledge.db') + const backupDir = join(root, 'backups') + seed(dbPath) + mkdirSync(backupDir, { recursive: true, mode: 0o700 }) + // A live process, recorded as itself: a real holder, not a reused number. The + // base cannot parse the second token, so it reads no pid at all and takes the + // lock over — the reason this refusal has to be asserted rather than assumed. + const content = `${String(process.pid)} ${String(selfStartTime(process.pid))}` + plantDeadLock(backupDir, content) + + const run = spawnSync(process.execPath, [backupScript, '--db', dbPath, '--backup-dir', backupDir], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + env: childEnv({}), + }) + + assert.equal(run.status, 1, `a live holder must refuse, got ${run.stdout}`) + assert.match(run.stderr, new RegExp(`\\(pid ${String(process.pid)}\\)`), run.stderr) + assert.equal(readFileSync(join(backupDir, LOCK), 'utf8'), content, "a refusal leaves the holder's lock byte-identical") +}) + +test('the run that takes a dead lock over still removes its own marker', () => { + const root = mkdtempSync(join(tmpdir(), 'fledge-marker-')) + const dbPath = join(root, 'fledge.db') + const backupDir = join(root, 'backups') + seed(dbPath) + mkdirSync(backupDir, { recursive: true, mode: 0o700 }) + plantDeadLock(backupDir) + + const run = spawnSync(process.execPath, [backupScript, '--db', dbPath, '--backup-dir', backupDir], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + env: childEnv({}), + }) + + assert.equal(run.status, 0, run.stderr) + assert.match(run.stdout, /^backup: OK$/m) + assert.equal(existsSync(join(backupDir, MARKER)), false, 'a completed takeover leaves no marker') + assert.equal(existsSync(join(backupDir, LOCK)), false, 'a completed run leaves no lock') +})