Repository navigation
fix file lock correctness - #18747
Conversation
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
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.
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
left a comment
There was a problem hiding this comment.
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 Claimhas a releasing destructor but is copyable - 🟡
src/cpp/core/system/PosixSystem.cpp:2292—std::sortwithout<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/beginProbeblocking protocol — no lock-ordering cycle is reachable, since path keys and inode keys can never collide pthread_atforkprepare/parent/child ordering and the constant-initialized singleton pointers- descriptor leaks on every error path in
acquire,writeLockFile,ensureClaimDirectory,inspectClaimFileAt,refreshLocks - the
LockStatemutex ordering betweenrelease()and an in-flightrefreshLocks()snapshot hasExpectedIdentityAt()ignoringmetadata.identityFollowsSymlink— harmless, it is only ever called on entries that are regular files by construction- the
/proc/<pid>/statfield re-indexing:fields[19]after the closing paren is still field 22 (starttime), matching the oldfields[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 inlastChunkOutput()and unknown extensions are skipped inenumerateChunkOutput()
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 |
There was a problem hiding this comment.
🟠 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; |
There was a problem hiding this comment.
🟡 *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.
| *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 |
There was a problem hiding this comment.
🟡 Claim releases its claim in the destructor but is implicitly copyable, so any future copy would release the same claim entry twice.
| 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()); |
There was a problem hiding this comment.
🟡 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.
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
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.
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
NEWS.md