Skip to content

fix file lock correctness - #18747

Merged
kevinushey merged 32 commits into
mainfrom
bugfix/file-lock-correctness
Sep 15, 2026
Merged

kevinushey merged 32 commits into
mainfrom
bugfix/file-lock-correctness

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Fix correctness and security defects in advisory and link-based file locks. Same-process advisory probes could release an active process-scoped lock, while stale link-lock cleanup and release could affect a successor lock. Malformed link metadata and filesystem inspection errors could also produce unsafe stale or unlocked results.

Approach

  • Keep advisory lock files on a stable inode and coordinate all same-process operations through a canonical-path registry.
  • Retain the exact link-lock inode through acquisition, refresh, and release; use inode validation and an atomic cleanup claim before replacing stale locks.
  • Parse PIDs without a shell, preserve the existing PID-only on-disk format, and support legacy owner files during cleanup.
  • Give each symlink lock a unique owner file, handle aliased parents and broken links, and treat incomplete lock publication as held until timeout.
  • Preserve inspection and creation errors so callers can fail closed, including the Posit Assistant installation-lock probe.
  • Reject lock timeout and refresh settings below one second or with non-finite values.

Automated Tests

Expanded the core file-lock tests with concurrent thread/process acquisition, stale takeover, successor safety, symlink aliasing, metadata compatibility, malformed metadata, destructor cleanup, and error-propagation coverage. Posit Assistant installation-lock integration tests cover non-destructive and fail-closed probes.

  • Core: 672 tests run; 664 passed and 8 skipped (3 disabled).
  • Posit Assistant installation locks: 25 tests passed.

QA Notes

The automated tests exercise the advisory and link-based implementations directly, including concurrent and cross-process behavior.

Documentation

No user-facing documentation changes; this updates internal lock behavior.

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards (no UI changes)
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
2975 0 196 4
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 10 0
✅ desktop-linux 750 0 38 1
✅ desktop-macos 747 0 42 1
✅ desktop-windows 751 0 42 2
✅ server-linux 697 0 44 0
✅ setup 28 0 20 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit 0f5d53fc104aa5223e2fe59dd6a09c7be33d3978 - Run #1028

Link-based locks:

- Remove lock entries only via rename-aside, inode check, then unlink (or
  link back), so a stale-lock takeover, a claim replacement, or a release
  can never delete a newer inode published at the same path.
- Use one claim name per public lock path, keep the claim open, and
  re-check its identity before acting on it.
- Detect PID reuse: a live PID whose process started after the lock's last
  refresh (plus the timeout, for clock skew) is not the owner, so orphaned
  locks no longer stay pinned while an unrelated process holds that PID.
- Create owner, claim and fallback lock files 0644 (umask applies) and
  treat an unreadable lock as one that expires by age, so a collaborator's
  lock in a shared project can be inspected and eventually taken over.
- Make release() remove the public path and owner file (identity-checked)
  and mark the inode released; cleanUp() does the same for locks still
  registered at shutdown. Sweep stale owner and claim files left in the
  directory after each acquisition, restoring the old cleanup of orphans.

Advisory locks:

- Track per-path holder/acquiring/probe state instead of a flat reservation
  set: an in-flight probe no longer reads as contention for acquire(),
  which waits for the probe's descriptor to close instead.
- Resolve a symlinked lock path to its target when building the
  same-process key, so the key is stable whether or not the target exists.

Both:

- The bool isLocked() overload returns false (and logs) on an inspection
  error again; the Error overload remains for callers that fail closed and
  is now virtual on FileLock.
- Reject lock timeout and refresh settings above one year, which would
  otherwise overflow boost::posix_time::seconds and abort startup.
- ChatInstallLock no longer unlinks a probed session lock file after
  releasing it, which orphaned link-based owner files and, for advisory
  locks, could hide a lock a same-named session acquired in between.
- Add a NEWS entry.
- release() no longer renames a public lock entry aside to check it. It
  takes the takeover claim, so no contender can be between judging the
  inode stale and replacing it, then unlinks the public path and owner
  only if they still refer to the released inode. An expired owner's
  release therefore never disturbs a successor's live entry, even briefly.
  If a contender holds the claim, release leaves the files to it.
- Inspection reads identity, mtime and contents from one opened
  descriptor, so a lock replaced between the pathname stat and the open
  cannot be judged by another inode's age. The unreadable-lock fallback
  takes identity and mtime from the same stat call.
- removeIfSameIdentity() checks identity before renaming aside, so the
  rename only ever moves an entry already known to match.
- Both lock registries derive from a shared ForkAwareRegistry that holds
  its mutex across fork() via pthread_atfork (as EnvironmentLock does) and
  resets state in the child, replacing the PID-comparison reset that could
  never run if the mutex was inherited locked. Tests fork repeatedly while
  threads keep each registry busy; they deadlock without the handlers.
…ocks inert

- ForkAwareRegistry no longer lists itself from its constructor. The
  singleton accessors publish the fully constructed registry via
  ForkAwareRegistry::publish(), under the list mutex the prepare handler
  takes, so a concurrent fork() either sees a complete registry or none.
- An AdvisoryFileLock released in a process other than the one that
  acquired it (inherited across fork) no longer unlocks, closes or
  deregisters: the kernel lock is the parent's, and closing the inherited
  descriptor would drop any lock the child has since taken on the same
  inode. The descriptor is parked for the life of the process instead.
- Document the residual window in removeIfSameIdentity: identity check
  and rename are two system calls, every other step is an atomic
  election, and public-lock removals run under the claim.
…el lock from parent

- The descriptor of an advisory lock object released in a child is parked
  in an object that is deliberately never freed, instead of a process-wide
  vector that concurrent releases could race on.
- InheritedAdvisoryLockObjectIsInertInChild now has the parent attempt
  acquisition while the child holds the lock (must fail) and after the
  child releases it (must succeed), so the check covers the kernel lock
  and not only the child's registry.
- The advisory same-process registry now reserves the lock file's
  device/inode (once the file exists) in addition to the path used while
  creating it, so hard links to one inode share a registration: a probe or
  acquire through an alias sees the lock as held instead of opening and
  closing the inode, which under fcntl would drop this process's lock.
- Add system::isProcessZombie() (Linux /proc state, macOS sysctl p_stat)
  and treat a zombie owner as gone: kill(pid, 0) still succeeds for an
  exited but unreaped process, which would otherwise pin its lock and any
  abandoned claim indefinitely now that a live PID bypasses the timeout.
…wners alive

- On Windows inodeKey() falls back to the path key, so the second
  AcquireScope waited on the reservation this same call already held and
  every advisory acquisition deadlocked. The inode reservation is now taken
  only when the key differs, with matching release bookkeeping.
- On Linux /proc/<pid>/stat describes the thread group leader, which reads
  as a zombie once the main thread exits while worker threads run on.
  isProcessZombie() now scans /proc/<pid>/task and reports a zombie only
  when no thread is left alive, so a lock held by a surviving worker is not
  reclaimed. Test: LockHeldByWorkerAfterMainThreadExitIsLive.
- isProcessZombie() on Linux now treats an unreadable task state as alive
  and re-lists /proc/<pid>/task after scanning, reporting a zombie only if
  the thread set was stable; a worker that replaced itself mid-scan no
  longer lets its process's lock be reclaimed.
- The main-thread-exit test waits (bounded) for the leader to read as Z on
  Linux before asserting, so it exercises the zombie check for real rather
  than racing pthread_exit.
The Linux ProcessInfo::creationTime() split the whole stat line on spaces
and read field 22, so a command name containing spaces shifted the fields
and produced a bogus start time. The lock PID-reuse check relies on that
time, so such a process inheriting a crashed owner's PID could pin the
orphaned lock. The parser now splits only what follows the parenthesized
name. Test: PosixTests.CreationTimeParsesCommandNameWithSpaces (Linux).
…read

Snyk flagged both intentional leaks. The inherited advisory descriptor is
now parked inside the fork-aware registry (a mutex-protected container the
child clears at fork time, when it holds no fcntl locks) rather than in an
unreachable heap object, and the main-thread-exit test detaches its worker
instead of heap-allocating it.
kevinushey and others added 12 commits September 9, 2026 17:00
Advisory isLocked() reported every missing lock file as an error (boost
exists() sets ENOENT), which the bool overload reads as "locked"; it now
relies on the inode key alone. A lock file the process cannot open for
writing is probed through a read-only descriptor (F_RDLCK / LockFileEx on
a read handle) instead of reading as permanently held.

Link-based locks: futimes() failure is a once-logged degradation rather
than an acquisition failure; release falls back to an unprotected unlink
when the claim cannot be created (ENOSPC); the released marker is written
before truncating so a failed write keeps the owner PID; a misreported
link() is recognised by public-path equivalence in every failure branch;
release verifies the lock still names this process, not just the inode;
the renamed-aside temp link is removed after a linkat() restore; the
live-owner grace is configurable (live-owner-grace-multiplier) and
tested; contention and O_EXCL fallback log again.

Addresses #18747.
Leave failed fallback and claim publications for timeout cleanup, and validate fallback ownership after initialization. Expire released inodes for legacy load-balanced readers. Create new persistent advisory lock files with shared write permissions through their descriptors.

Validated 53 core file-lock tests, 29 Assistant lock tests, mixed-version handoffs, and injected publication and permission failures on macOS.
applyClaimDirectoryPermissions() uses fchown/fchmod/mode_t and is only called from the POSIX branch of ensureClaimDirectory(), but the definition itself was unguarded and broke the MSVC build.

Claude-Session: https://claude.ai/code/session_016eTbpTevx3FuEWDQYyRdBy

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

No blocking defects found. 1 follow-up, 3 nits (+1 pre-existing-style FYI, not commented)

Requesting changes on the ✨ item only because it needs an answer from you rather than a code fix I can verify myself — if the premise holds, say so and this is a straight approve.

🟠 is real but not merge-blocking — either address it here or open an issue. 🟡 is optional.

  • 🟠 src/cpp/core/file_lock/LinkBasedFileLock.cpp:207 — the "legacy" claim protocol has never shipped, so every acquire pays a second claim round-trip for nothing
  • 🟡 src/cpp/core/file_lock/LinkBasedFileLock.cpp:2499 — *pHeld = !error; if (error || !*pHeld) is self-cancelling dead logic
  • 🟡 src/cpp/core/file_lock/LinkBasedFileLock.cpp:1318 — struct Claim has a releasing destructor but is copyable
  • 🟡 src/cpp/core/system/PosixSystem.cpp:2292 — std::sort without <algorithm>

Scope of this review

I read every non-test hunk and traced the acquire / release / refresh / fork / stale-takeover paths. Things I checked and cleared rather than reported, in case they save you a round trip:

  • the beginAcquire/beginProbe blocking protocol — no lock-ordering cycle is reachable, since path keys and inode keys can never collide
  • pthread_atfork prepare/parent/child ordering and the constant-initialized singleton pointers
  • descriptor leaks on every error path in acquire, writeLockFile, ensureClaimDirectory, inspectClaimFileAt, refreshLocks
  • the LockState mutex ordering between release() and an in-flight refreshLocks() snapshot
  • hasExpectedIdentityAt() ignoring metadata.identityFollowsSymlink — harmless, it is only ever called on entries that are regular files by construction
  • the /proc/<pid>/stat field re-indexing: fields[19] after the closing paren is still field 22 (starttime), matching the old fields[21]
  • whether the new persistent .rstudio-lock-claims-41c29/ directories confuse notebook chunk-output enumeration — they do not; dot-prefixed stems parse to ordinal 0 in lastChunkOutput() and unknown extensions are skipped in enumerateChunkOutput()

Additional findings

⚪ src/cpp/core/file_lock/LinkBasedFileLock.cpp:1004 — inspectClaimFileAt() returns a hard error when the claim name is not a regular file, and sweepStaleClaims() skips entries whose inspection errors, so a stray symlink or directory at that exact name would wedge acquisition for that lock path with no self-healing. Recorded only for completeness: claims are always created with O_CREAT|O_EXCL as regular files, so there is no path to this state short of someone editing the claims directory by hand.


FilePath legacyClaimPathForLock(const FilePath& lockFilePath)
{
// Keep taking the claim used by deployed versions so a rolling upgrade

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🟠 This comment says the hashed claim exists for rolling upgrades, but no released build takes any claim — so every acquisition does a second claim round-trip for nothing.

If I'm right, drop legacyClaimPathForLock(), acquireLegacyClaim(), validateClaims() and the legacy Claim in acquire(), and keep only the exact-name claim.

Why

.rstudio-lock-claim-41c29 appears nowhere in origin/main's history. The only commits that introduce it are b3dc52cf5c and a62d6dbce3, both on this PR's own branches:

$ git log --oneline origin/main -S'rstudio-lock-claim' -- .
(no output)

$ git branch -a --contains b3dc52cf5c
  pr18747
  remotes/origin/bugfix/18747-lock-acl-permissions
  remotes/origin/bugfix/18747-review-fixes
  remotes/origin/bugfix/file-lock-correctness

The merge-base LinkBasedFileLock.cpp has no claim concept at all — the old stale-removal path just called isLockFileStale() and removed by name. So an old session running beside a new one never contends on this file either way, and taking it buys no serialization against anything.

The cost on the current code is a full extra protocol per acquire: open the lock directory with O_NOFOLLOW|O_DIRECTORY, O_EXCL-create the claim, descriptorIdentity(), validateClaim(), plus a removeIfSameIdentityAt() rename/unlink on release — and a second validateClaims() call at each of the three checkpoints in acquire() and writeLockFile().

Worth separating from the genuinely-legacy handling: kLegacyFileLockPrefix (.rstudio-lock-41c29) in isOwnerFile() is the deployed owner-file prefix and does belong here. It's only the claim that looks unmotivated.

If "deployed versions" means an internal daily built from this branch rather than a release, say so and I'll withdraw this — the comment just doesn't record which.


#ifndef _WIN32
error = validateClaim(*pClaim, lockFilePath);
*pHeld = !error;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🟡 *pHeld = !error makes the || !*pHeld disjunct unreachable and the *pHeld = false inside the block a no-op, so the guard reads as if it handles a case it cannot.

Suggested change
*pHeld = !error;
error = validateClaim(*pClaim, lockFilePath);
if (error)
{
// Identity-checked, so a contender's replacement is left in place but
// our own claim does not linger to block every later takeover.
*pHeld = false;
releaseClaim(pClaim);
}
Why

After *pHeld = !error, !*pHeld is exactly error, so the condition is just if (error), and inside it *pHeld is already false. The following if (!error && *pHeld && sweepClaims) then reduces to if (!error && sweepClaims).

Behaviour is unchanged either way — this is only about the next reader not having to prove that to themselves. Note the two ways this function reports "not held" stay asymmetric after the edit: claimLockFile() returning *pClaimed == false gives Success() plus *pHeld == false, while a failed validateClaim() returns noLockAvailableError. Both callers handle both, so that part is fine as-is.

// A claim in the private namespace elects one acquirer through removal and
// publication. Both it and the namespace stay open so their identities can be
// re-checked without traversing a replaced directory name.
struct Claim

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🟡 Claim releases its claim in the destructor but is implicitly copyable, so any future copy would release the same claim entry twice.

Suggested change
struct Claim
struct Claim : boost::noncopyable
{
Why

No current code copies a Claim — acquireClaimAt() and claimLockFile() take Claim*, and validateClaims() takes const references — so nothing is broken today. But the two members that matter (descriptor, directoryDescriptor) are raw ints, and ~Claim() calls releaseClaim(), which does removeIfSameIdentityAt() and closes both. A copy made by accident later (pushing into a container, returning by value) would run that twice: the second removeIfSameIdentityAt() would rename-aside and unlink whatever a successor had since published at the claim name, and the close() calls would double-close descriptors this process may have reused.

The surrounding code already uses boost::noncopyable for exactly this (ForkAwareRegistry, ProbeScope, AcquireScope), so this just brings Claim in line.

if (error)
return false;

std::sort(tasks.begin(), tasks.end());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🟡 std::sort is used here but <algorithm> is never included, so this compiles only through whatever transitive include happens to supply it.

Add #include <algorithm> to the standard-header block near the top (beside <iostream>, <string>, <vector>).

Why

The file's own standard includes are <stdio.h>, <iostream>, <string>, <vector>. std::sort is currently reaching this translation unit via Boost or gsl-lite headers pulled in further down, which is why it builds. That's fragile in the usual way — a Boost bump or an include-what-you-use pass elsewhere can break this file with an error that points nowhere near the cause.

This branch was successfully deployed

1 active deployment
e2e-playwright — 0f5d53fc Deployed Sep 15, 2026 by kevinushey via windows / e2e-desktop-windows (2) #1028
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants