fix(credentials): recover from leaked auth-profile lock on Windows (Sentry OPENHUMAN-TAURI-H1)
Summary
- Retry
fs::remove_fileinAuthProfileLockGuard::drop(5 attempts, 50ms→800ms backoff) so transient Windows AV/indexer file locks do not permanently orphan auth-profile lock files. - Added age-based stale-lock reclaim in
clear_lock_if_stale: lock files older thanSTALE_LOCK_AGE_MS = 30_000are treated as leaked even when the recorded PID is still alive. - Updated
acquire_lockto re-check stale locks once per second during busy-wait so leaked locks can recover before the 10s timeout. - Deduplicated the
app_state_snapshothot path by loading the app-session profile once instead of twice per RPC, reducing lock contention on the most-polled endpoint. - Added unit tests covering stale-lock reclaim for both live-PID and malformed-PID lock scenarios.
Problem
- Sentry issue
OPENHUMAN-TAURI-H1(“Timed out waiting for auth profile lock”) generated 990 Windows events over 3 days, all tied toopenhuman.app_state_snapshottiming out aroundLOCK_TIMEOUT_MS = 10_000. AuthProfileLockGuard::droppreviously ignoredfs::remove_filefailures. On Windows, AV/indexer processes can briefly hold handles on newly written files, causingPermissionDeniedand leaving stale lock files behind.- Existing stale-lock recovery only handled dead-PID scenarios, so leaked locks with still-alive PIDs appeared valid and caused every subsequent lock acquisition to spin for the full timeout window.
app_state_snapshotindependently calledbuild_session_state(&config)andget_session_token(&config), doubling lock acquisition frequency on the hottest RPC path.
Solution
-
Added retry-on-drop logic in
AuthProfileLockGuard::drop:- Retries
fs::remove_file5 times with exponential backoff (~1.55s max). - Handles transient AV/indexer locks without changing the file-lock protocol.
- Retries
-
Added age-based stale-lock reclaim:
clear_lock_if_stalenow reclaims any lock older than 30 seconds regardless of PID liveness.- Threshold chosen well above realistic auth-profile operation time (<100ms typical).
-
Added mid-wait stale-lock probing:
acquire_locknow re-runsclear_lock_if_staleonce per second during contention.- Prevents leaked locks from forcing the full timeout path.
-
Reduced lock contention on the snapshot hot path:
- Added:
load_app_session_profilesession_state_from_profilesession_token_from_profile
snapshot()now loads the profile once and derives both views from memory.
- Added:
-
Design tradeoff:
- Considered replacing file locks with an in-process mutex, but retained the existing cross-process-safe lock protocol because standalone
openhuman-coredebug mode still supports multi-process execution. - Chose targeted hardening over larger locking architecture changes.
- Considered replacing file locks with an in-process mutex, but retained the existing cross-process-safe lock protocol because standalone
Submission Checklist
If a section does not apply to this change, mark the item as
N/Awith a one-line reason. Do not delete items.
- Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
- Diff coverage ≥ 80% — changed lines (Vitest + cargo-llvm-cov merged via
diff-cover) meet the gate enforced by.github/workflows/coverage.yml. Runpnpm test:coverageandpnpm test:rustlocally; PRs below 80% on changed lines will not merge. - Coverage matrix updated —
N/A: bug-fix on existing credentials/auth-profile feature; no new user-facing feature rows - All affected feature IDs from the matrix are listed in the PR description under
## Related—N/A: no matrix rows touched - No new external network dependencies introduced (mock backend used per Testing Strategy)
- Manual smoke checklist updated if this touches release-cut surfaces (
docs/RELEASE-MANUAL-SMOKE.md) —N/A: internal lock-recovery hardening; no UI/behavior surface change - Linked issue closed via
Closes #NNNin the## Relatedsection —N/A: tracked in Sentry (OPENHUMAN-TAURI-H1), not GitHub Issues
Impact
-
Platform/runtime impact:
- Primarily benefits Windows desktop users where AV/indexer file locks cause the observed failure mode.
- macOS/Linux behavior remains effectively unchanged in healthy cases.
-
Performance impact:
- Reduces auth-profile lock contention by halving lock acquisitions in
app_state_snapshot. - Adds negligible overhead (
fs::metadatachecks during stale-lock probing).
- Reduces auth-profile lock contention by halving lock acquisitions in
-
Security impact:
- No changes to credential storage, encryption, or token handling.
- Existing cross-process lock semantics remain intact.
-
Compatibility/migration impact:
- No persisted format changes.
- Existing APIs and signatures remain backward-compatible.
- New helper functions are additive only.
-
Observability impact:
- Structured logging added for stale-lock reclaim reasons and retry exhaustion paths.
Related
- Closes: OPENHUMAN-TAURI-H1 and #2072
Summary by CodeRabbit
-
Bug Fixes
- Improved stale lock recovery with age-based detection and clearer reclaim logging.
- Added robust retry behavior for lock cleanup to handle transient system interference.
-
Performance
- Reduced redundant session profile access by consolidating profile loading and token/state derivation.
-
Tests
- Added tests for stale-lock recovery and for whitespace-only session token normalization.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d5f8b2bd-4816-4c94-8d87-b9b799d4f5e7
📥 Commits
Reviewing files that changed from the base of the PR and between 8282825ea82f6884edd61d628d9530ad540f6288 and d39854f952e6757c6868b2638472b92a3676a11b.
📒 Files selected for processing (2)
src/openhuman/credentials/profiles.rssrc/openhuman/credentials/profiles_tests.rs
🚧 Files skipped from review as they are similar to previous changes (2)
- src/openhuman/credentials/profiles_tests.rs
- src/openhuman/credentials/profiles.rs
📝 Walkthrough
Walkthrough
Adds age-based stale lock detection with periodic re-probing and retry-on-drop cleanup, and consolidates session profile loading so snapshot() derives auth state and session token from a single loaded app-session profile.
Changes
Lock File Staleness Recovery
| Layer / File(s) | Summary |
|---|---|
Stale lock constant and detection src/openhuman/credentials/profiles.rs |
Adds STALE_LOCK_AGE_MS and refactors clear_lock_if_stale to determine staleness from lock-file mtime and PID liveness, producing a structured reclaim_reason. |
Acquire busy-wait with periodic stale rechecks src/openhuman/credentials/profiles.rs |
acquire_lock now uses wall-clock elapsed time and next_stale_recheck_ms to periodically call clear_lock_if_stale during busy-wait so stale locks can be reclaimed before timeout. |
Lock guard unlink retry on Drop src/openhuman/credentials/profiles.rs |
AuthProfileLockGuard::drop now retries unlink with bounded exponential backoff and logs a warning if final attempts fail. |
Stale lock recovery tests src/openhuman/credentials/profiles_tests.rs |
Two tests added validating reclaim behavior for aged locks: one with a live PID entry and one with a malformed/missing pid= line. |
Session Profile Consolidation
| Layer / File(s) | Summary |
|---|---|
Ops import and snapshot integration src/openhuman/app_state/ops.rs |
Updates imports and snapshot() to call load_app_session_profile once and derive both auth and session_token from that single profile. |
Shared session profile helpers src/openhuman/credentials/session_support.rs |
Adds load_app_session_profile, session_state_from_profile, and session_token_from_profile; refactors build_session_state and get_session_token to delegate to these helpers and normalizes whitespace-only tokens to None. |
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related issues
- tinyhumansai/openhuman#2072: Changes to age-based stale lock detection, periodic re-probing, and unlink retry address the stale-lock and acquire-hang symptoms described in that issue.
Possibly related PRs
- tinyhumansai/openhuman#2180: Modifies
credentials/profiles.rslock acquisition diagnostics and is closely related to the lock/reclaim changes here.
Suggested labels
working
Suggested reviewers
- graycyrus
Poem
🐰 One profile load, no double knock,
Stale locks chased by age and clock,
Retry the unlink, probe and see,
A tidy snapshot, token and key,
Hopping through code — hooray for me!
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title directly addresses the main change: recovering from leaked auth-profile locks on Windows with clear reference to the Sentry issue (OPENHUMAN-TAURI-H1). |
| Docstring Coverage | ✅ Passed | Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
Comment @coderabbitai help to get the list of available commands and usage tips.