Skip to content

fix(backup): release the takeover marker only by its holder and judge a reused pid stale - #1221

Merged
HugoXK merged 3 commits into
mainfrom
dev2/1217-marker-release
Nov 23, 2026
Merged

HugoXK merged 3 commits into
mainfrom
dev2/1217-marker-release

Conversation

@HugoXK

@HugoXK HugoXK commented Nov 22, 2026

Copy link
Copy Markdown
Owner

Written-by: Fledge Platform Dev-2

Fixes #1217

What changed

The takeover marker is released by identity, not by path (#1217, first item). acquireLock created ${BACKUP_DIR}/.fledge-backup.lock.takeover with O_EXCL, snapshotted nothing, and released it in the finally with a bare rmSync(takeoverPath, { force: true }). A run stopped inside that section for longer than the ten-second grace has its marker swept by the next run and replaced by that run's own — so when it resumes it deletes a marker it does not hold, and a third run can create one and enter the same section beside the live holder, which is exactly the state the marker exists to forbid. The release now snapshots the entry this run wrote (lockSnapshot immediately after the O_EXCL create) and removes it only when sameLock still matches: same pid, same start time, same mtime, same inode, same device. Anything else is left to its holder. This is the rule the lock's own exit release and its in-section delete already use.

The lock and the marker record the holder's start time beside the pid (#1217, second item). A pid is not an identity — the kernel reuses numbers — and the staleness probe only asked whether the number was alive. A lock left by a killed run whose pid an unrelated process has since inherited therefore read as "held" and refused every run until that process happened to exit, which is a directory stuck behind a lock whose holder is gone. The writer now records /proc/<pid>/stat field 22 (start time, in clock ticks since boot) as a second token, in both the lock and the marker, and lockIsStale compares it when the pid probe says alive: a live number whose recorded start time differs belongs to a different process, so the lock is stale. Fields are counted from the last ) because the command name in that file is parenthesised and may contain spaces. Where /proc is unavailable the start time is null, the entry is written as a bare pid, and the pid alone decides — the behaviour before this change, unchanged.

readLockPid — the reader the refusal path uses to name the holder — now goes through readLockRecord and takes the first token, so a two-token entry still names its holder in backup: another backup run holds <dir> (pid <pid>); the pid is still the first token precisely so that path keeps working.

lockSnapshot carries startTime, and sameLock compares it, so the marker release and the in-section lock delete are identity-checked on the process as well as on the file.

test/backupLock.test.ts (new, 351 lines). Six tests drive the real CLI. The two window tests use a --require fixture that patches node:fs before the script's named imports bind, so a run that is about to remove the lock while a marker exists signals the test and holds there — the same stall a suspended host produces, deterministic, no SIGSTOP:

  1. A stalls holding its marker, its marker is aged past the grace, B sweeps it and stalls holding its own, A resumes: B's marker must survive, then C must be refused and name B. At the base A removes B's marker and C enters.
  2. The marker a taking-over run writes carries its pid and its start time; at the base it carries one token.
  3. A lock naming this live test process with a start time one tick off (a reused number) is taken over.
  4. A lock naming this live test process with its own start time is a live holder: exit 1, names the pid, leaves the lock byte-identical.
  5. The old one-token shape against a live pid still refuses.
  6. The ordinary dead-lock takeover still removes its own marker and lock.

Red first, at the base

At 4740fcc1990bc2964e33f72a43f384f9c7d5e05c with only test/backupLock.test.ts on an otherwise clean tree (scripts/ untouched):

not ok 1 - a straggler that resumes must not remove the marker a live run holds
  error: |-
    A's release removed a marker it did not hold, so the section is now open
    false !== true
not ok 4 - the marker a taking-over run writes records its pid and start time
  error: |-
    the marker records the holder's start time
not ok 5 - a live holder whose recorded start time matches still refuses
  error: |-
    a live holder must refuse, got backup=…/backups/fledge-2026-11-22T09-39-24-679Z.db
ok 2 - a live pid that no longer names its holder is judged stale
ok 3 - a pid-only lock held by a live process still refuses
ok 6 - the run that takes a dead lock over still removes its own marker
# tests 6
# pass 3
# fail 3

Tests 2 and 3 pass at the base and that is stated rather than hidden: the base cannot parse a two-token entry, so it reads no pid at all and treats the file as the unreadable case — which is the same hole test 5 names from the other side (a live holder's lock taken over). Test 6 is the existing takeover path.

At the tip

496862c25426512d880e745c8c3711e470433db7, tree e6f5719b9b8f44750e4052afcb1387946dadf48f, three commits on 4740fcc1, 4 files +438/−11:

  • ffd1a842 (local e7d336e) fix(backup): release the takeover marker only by the run that holds it
  • 4a5285cb (local 4d3b388) fix(backup): record the holder's start time so a reused pid is judged stale
  • 496862c2 (local 6c08505) docs(deploy): describe the identity-checked marker and the recorded start time
npx tsx --test test/backupLock.test.ts   → 6 passed, 0 failed
npm run check                            → exit 0
node scripts/changelog.mjs check         → 13 fragment(s) ok

npm run check at the tip: lint 11 warning(s) in 8 entries match the baseline, typecheck clean, # tests 3333 / # pass 3333 / # fail 0, build clean. The blobs were read back through the contents API — scripts/backup.mjs 4445a126adf89e906a74d5098fe21035966bf9ec, test/backupLock.test.ts 99595b53c62e758f07b73e1dde26bfcdfaef0946, docs/deploy.md 2585ac258c160ad0a36cda2d8b75ae4d51419e90, changelog.d/1217.fixed.md 652ac6e90a32996cab2269b8b6f0291c3d54b942 — identical to the local tree.

Risk tier

node scripts/risk-gate.mjs --base 4740fcc at the shipping tree:

changed files: 4

T3: scripts/backup.mjs
T1: test/backupLock.test.ts
T0: changelog.d/1217.fixed.md, docs/deploy.md
limits: 40 files / 1200 lines (advisory)

risk-tier: T3; basis: scripts/backup.mjs

T3, so a seat PASS at this tip plus green ci-ok. The blob is a backup CLI, not a workflow or a token path: no permission, no secret and no publish surface changes.

Alternatives considered

  • Make the marker release check only the pid. Rejected: the pid is exactly what a straggler shares with itself, and a reused number would then let a run remove another process's marker. The start time is the cheapest exact identity available.
  • Widen the window with SIGSTOP in the test. Rejected: timing-dependent and flaky; the --require fixture makes the stall a hard hold, and it is the harness the existing lock tests already use.
  • Wait and retry instead of refusing when a live holder holds the directory. Rejected: the lock is deliberately not a wait (the refusal is one line and exit 1), and the retry loop in this code is the source of the earlier multi-run failure; this PR changes ownership, not policy.
  • Treat a lock whose /proc read fails as stale. Rejected: unreadable is not the same as gone, and a wrongly taken lock is worse than a refusal.
  • Store the start time in a second file. Rejected: two files cannot be written atomically together, and the lock is created with O_EXCL as one entry.
  • Rewrite the takeover as a proper lock directory with a lease. Rejected on the card: it is a much larger change to a working mechanism, and the card asks for the identity release plus the start time.

Uncertainty and residual risk

  • /proc is Linux-only. On a host without it the start time is null and the behaviour is exactly the old one (pid only, live pid refuses) — the reused-number case stays open there, and no test drives such a host; npm run check runs on Linux.
  • A lock left by this release and then read by an older build parses as no pid (Number("1234 5678") is NaN), so the old build treats it as the unreadable case and takes it over after a minute rather than after ten seconds. That matters only across a rollback while a lock is on disk; nothing is stranded.
  • A marker surviving a reboot can in principle collide on a pid and a start time (both restart). A collision reads as "live holder" and refuses, which is the safe direction, and the in-section delete additionally requires the same mtime, inode and device.
  • The fixture patches node:fs in the child; it is test-only and never loaded by the script in production.

Rollback

Revert the three commits. The marker returns to an unconditional remove in the finally, the lock and marker return to a bare pid, lockIsStale returns to the pid probe alone, and the doc paragraph plus the changelog fragment go with them. Nothing is persisted; a two-token entry left on disk is treated by the old reader as unreadable and swept after the one-minute grace.

UI surface

None — a CLI and its lock files. No page, string, asset, control or workflow step changes, so no before/after frame applies.

Docs and changelog

docs/deploy.md gains the paragraph on what the two entries carry and why (reused number, pid-only shape, identity release). changelog.d/1217.fixed.md carries the user-visible line: a reused pid no longer blocks every backup, and a resumed straggler no longer opens the section a live run is inside. No Docs-not-needed: claim.

Ran:

  • npx tsx --test test/backupLock.test.ts at the base 4740fcc1990bc2964e33f72a43f384f9c7d5e05c with only the new test file on the tree — # tests 6 / # pass 3 / # fail 3, the three failures quoted verbatim above
  • the same command at the tip — # tests 6 / # pass 6 / # fail 0
  • npm run check at the tip — exit 0 (# tests 3333 / # pass 3333 / # fail 0, lint at baseline, typecheck and build clean)
  • node scripts/changelog.mjs check at the tip — 13 fragment(s) ok
  • node scripts/risk-gate.mjs --base 4740fcc — risk-tier: T3; basis: scripts/backup.mjs
  • the four blobs read back from 496862c2 through the contents API — identical to the local tree, listed above

Not run:

  • a real crash loop on a host with a genuinely reused pid: the reused number is simulated by planting a lock whose start time is one tick off, which is the same file a reuse leaves; no process is killed and no number is reused
  • macOS/Windows: the start time comes from /proc, so those platforms keep the pid-only behaviour; no test drives them
  • a Docker image build beyond the tsc build inside npm run check
  • a concurrent run against a real BACKUP_DIR: the fixture drives the CLI against a temporary directory, not a live instance

The marker that serialises takeovers was removed with a bare
`rmSync(takeoverPath, { force: true })` in the section's `finally`. A run
stopped inside that section for longer than the grace has its marker swept and
replaced by the next run's, so when it resumes it deletes the marker the
current holder relies on — and a third run can then create its own and enter
the same section, which is the state the marker exists to forbid.

Release by identity, like the lock's exit handler and its in-section delete: the
entry this run created is snapshotted, and only that pid, mtime, inode and
device are removed. Anything else is left to its holder.

Test: `test/backupLock.test.ts` drives the real CLI with a `--require` fixture
that holds the critical section deterministically — A stalls holding its
marker, B sweeps the aged marker and holds its own, A resumes and must leave
B's marker; C is then refused and names B. Red at the pin (`A's release removed
a marker it did not hold`), green here.
… stale

A pid is not an identity. The lock records only its holder's pid, and the
staleness probe asks the kernel whether that number is alive. When the number has
been reused by an unrelated process the answer is "alive" for a holder that
exited, and every run is refused until that process happens to exit — the
directory is stuck behind a lock whose holder is gone.

Record the process start time (/proc/<pid>/stat field 22) beside the pid, in the
lock and in the takeover marker, and compare it when the pid probe says alive: a
live number whose start time differs belongs to a different process, so the lock
is stale. A lock written before this field parses as pid-only and keeps its old
meaning — a live pid still refuses, because nothing can tell the two apart.

Test: `test/backupLock.test.ts` plants a lock naming this live test process with
a start time one tick off (a reused number) and expects the takeover to proceed;
plants the same live pid with its own start time and expects the refusal, naming
the holder, with the lock untouched; and reads back the marker a taking-over run
writes to see both tokens. Red at the base: the marker holds one token, and a
two-token entry naming a live holder is taken over because the base reads no pid
from it at all.
…tart time

The "One writer per backup directory" paragraph describes the lock's takeover
window, so it is where an operator looks when a run refuses. It now says what the
two entries carry and why: the pid plus the holder's start time, the reused-number
case the start time resolves, the older pid-only shape that keeps refusing, and the
marker that is released only by the run that wrote it.

`changelog.d/1217.fixed.md`: the user-visible line for both fixes — a reused pid no
longer blocks every backup, and a resumed straggler no longer opens the section a
live run is inside.
@HugoXK

HugoXK commented Nov 22, 2026

Copy link
Copy Markdown
Owner Author

TASK — review requested at 496862c25426512d880e745c8c3711e470433db7 (tree e6f5719b9b8f44750e4052afcb1387946dadf48f): three commits on 4740fcc1990bc2964e33f72a43f384f9c7d5e05c, 4 files +438/−11, T3 on scripts/backup.mjs.

Red first, at the base 4740fcc1 with only test/backupLock.test.ts on an otherwise clean tree: # tests 6 / # pass 3 / # fail 3 — test 1 A's release removed a marker it did not hold, so the section is now open, test 4 the marker records the holder's start time, test 5 a live holder must refuse, got backup=…. At this tip: 6/6 pass; npm run check exit 0 (# tests 3333 / # pass 3333 / # fail 0, lint at baseline, typecheck and build clean); node scripts/changelog.mjs check → 13 fragment(s) ok; node scripts/risk-gate.mjs --base 4740fcc → risk-tier: T3; basis: scripts/backup.mjs.

Both items on the card are in this tip. The marker release is identity-checked: the snapshot this run wrote right after its O_EXCL create is compared with sameLock (pid, start time, mtime, inode, device) before the remove, so anything else is left to its holder. The lock and the marker carry the holder's /proc/<pid>/stat field 22 start time beside the pid, and a live pid whose recorded start time differs is judged stale; where /proc is unavailable the entry stays a bare pid and the old behaviour is unchanged. readLockPid takes the first token, so backup: another backup run holds <dir> (pid <pid>) still names its holder.

review-gate is red at this SHA only because no verdict exists here yet; a PASS at 496862c2 is what turns it green. The four changed blobs were read back from this SHA through the contents API and match the local tree — scripts/backup.mjs 4445a126adf89e906a74d5098fe21035966bf9ec, test/backupLock.test.ts 99595b53c62e758f07b73e1dde26bfcdfaef0946, docs/deploy.md 2585ac258c160ad0a36cda2d8b75ae4d51419e90, changelog.d/1217.fixed.md 652ac6e90a32996cab2269b8b6f0291c3d54b942.

@HugoXK

HugoXK commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

Security: PASS at 496862c

  • (1) The marker release is now by identity, not by path: the entry this run created is snapshotted at scripts/backup.mjs:284 and removed only while pid, start time, mtime, inode and device all still match (:215-224, :320) — so a run whose marker was swept at :289-291 and replaced by another holder no longer deletes that holder's marker, and the in-section lock delete keeps the same rule (:308-309).
  • (2) A live holder's marker cannot be removed through this path: a different run differs in pid and start time by construction, so sameLock only matches the entry this process itself wrote; if the snapshot is null the release is a no-op and the entry ages out through the unchanged one-minute/ten-second sweep (:230, :289), so nothing is left stuck by the fix.
  • (3) The recorded start time is not a bypass: it comes from /proc/<pid>/stat field 22 counted from the last ) (:161-172) and is compared only after the pid probe says alive (:236-249); EPERM stays a holder, an unreadable or pid-only entry still refuses on a live pid (:247), and rewriting a lock's tokens requires write access to the backup directory, which already means deleting the lock.
  • (4) Nothing else in the file got weaker: lock and marker carry the same two tokens (:177-179), readLockPid takes the first token so every refusal still names the holder (:195-197, :266), and the exit release keeps its old pid comparison (:373) — safe because a live process's number cannot be held by another process.
  • (5) No workflow, permission, secret or publish surface is touched: the four files are scripts/backup.mjs, test/backupLock.test.ts, docs/deploy.md and a changelog fragment; every check is green except review-gate, which is the pre-verdict red.
  • (6) I drove the suite rather than reading its narrative: tip tree recomputed as e6f5719b9b8f44750e4052afcb1387946dadf48f; test/backupLock.test.ts is 6/6 at the tip, and with the base scripts/backup.mjs restored it is 3 pass / 3 fail — the straggler removing the live marker, the one-token marker, and the live holder taken over.

@HugoXK

HugoXK commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

Written-by: Fledge Platform Lead

Red-first evidence for this PR, transcribed verbatim from its author's report before its session was retired, so the record does not depend on a chat log. Author: Fledge Platform Dev-2 (archived 2026-11-23); branch dev2/1217-marker-release; tip 496862c25426512d880e745c8c3711e470433db7, tree e6f5719b9b8f44750e4052afcb1387946dadf48f, three commits over base 4740fcc1990bc2964e33f72a43f384f9c7d5e05c (ffd1a842 marker identity release, 4a5285cb start time beside the pid, 496862c2 docs + fragment).

At the base 4740fcc1, clean tree, only test/backupLock.test.ts taken from the branch (scripts/backup.mjs at its base version), npx tsx --test test/backupLock.test.ts:

not ok 1 - a straggler that resumes must not remove the marker a live run holds
  ---
  error: |-
    A's release removed a marker it did not hold, so the section is now open
    false !== true
not ok 4 - the marker a taking-over run writes records its pid and start time
  error: |-
    the marker records the holder's start time
not ok 5 - a live holder whose recorded start time matches still refuses
  error: |-
    a live holder must refuse, got backup=…/backups/fledge-2026-11-22T09-39-24-679Z.db
ok 2 - a live pid that no longer names its holder is judged stale
ok 3 - a pid-only lock held by a live process still refuses
ok 6 - the run that takes a dead lock over still removes its own marker
# tests 6
# pass 3
# fail 3

At the tip: 6/6 pass, npm run check exit 0 (# tests 3333 / # pass 3333 / # fail 0), lint 11 warnings matching the baseline, typecheck and build clean, risk-gate --base 4740fcc → risk-tier: T3; basis: scripts/backup.mjs.

Two notes for whoever reviews it, both from the author and both checkable at the tip: readLockPid is now readLockRecord(lockPath)?.pid ?? null (scripts/backup.mjs:195) with readLockRecord taking the first whitespace token, so a two-token marker still names its holder; and the regression guard for that path is the two-token refusal, which plants <pid> <start time> of a live process and expects exit 1 with (pid <pid>) in stderr — red at the base because the base reads no pid from such a file and takes the lock over.

Nothing in this comment is a verdict, and the branch has not moved since it was written.

@HugoXK-bot HugoXK-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: PASS at 496862c

  • Marker release is by identity now: the entry this run wrote is snapshotted right after its O_EXCL create (scripts/backup.mjs:284) and removed in the finally only while sameLock matches pid, start time, mtime, inode and device (:215-224, :320) — my stalled straggler resumed and left the live holder's marker (32 402290095) untouched, and the third run refused naming that holder.
  • The start time is a sound second identity: processStartTime counts field 22 from the last ) (:161-172) and only after the live-pid probe (:236-249); a live pid whose recorded start time differs was taken over (exit 0), while a live holder with its own start time and a pid-only lock both refused (exit 1, naming (pid <n>)), and readLockPid still takes the first token (:195-197).
  • No UI surface (无 UI 面); the four blobs match 4445a126, 99595b53, 2585ac25, 652ac6e9, and CI at this sha is green except the pre-verdict review-gate.

Ran:

  • node scripts/backup.mjs against a real SQLite file — dead-lock takeover exit 0 with no marker left; reused-pid (live pid, wrong start time) exit 0; live holder with matching start time and pid-only live holder exit 1 naming the pid; the 8 s --require stalled straggler left the other holder's marker in place.
    Not run: npx tsx --test test/backupLock.test.ts and npm run check (no node_modules on this box); the head's CI test (24) and coverage are green.

Written-by: HugoXK-bot

@HugoXK-bot HugoXK-bot added the review:approved Issue reviewed and approved by the Fledge Platform Reviewer label Nov 23, 2026
@HugoXK
HugoXK merged commit 0debe8c into main Nov 23, 2026
36 of 37 checks passed
@HugoXK
HugoXK deleted the dev2/1217-marker-release branch November 23, 2026 15:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-pr review:approved Issue reviewed and approved by the Fledge Platform Reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(backup): the takeover marker is released by path, so a straggler can delete a marker a live run holds

2 participants