openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(credentials): recover from leaked auth-profile lock on Windows (Sentry OPENHUMAN-TAURI-H1)

Open YellowSnnowmann opened this issue 6 months ago • 1 comments

Summary

  • Retry fs::remove_file in AuthProfileLockGuard::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 than STALE_LOCK_AGE_MS = 30_000 are treated as leaked even when the recorded PID is still alive.
  • Updated acquire_lock to re-check stale locks once per second during busy-wait so leaked locks can recover before the 10s timeout.
  • Deduplicated the app_state_snapshot hot 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 to openhuman.app_state_snapshot timing out around LOCK_TIMEOUT_MS = 10_000.
  • AuthProfileLockGuard::drop previously ignored fs::remove_file failures. On Windows, AV/indexer processes can briefly hold handles on newly written files, causing PermissionDenied and 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_snapshot independently called build_session_state(&config) and get_session_token(&config), doubling lock acquisition frequency on the hottest RPC path.

Solution

  • Added retry-on-drop logic in AuthProfileLockGuard::drop:

    • Retries fs::remove_file 5 times with exponential backoff (~1.55s max).
    • Handles transient AV/indexer locks without changing the file-lock protocol.
  • Added age-based stale-lock reclaim:

    • clear_lock_if_stale now 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_lock now re-runs clear_lock_if_stale once 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_profile
      • session_state_from_profile
      • session_token_from_profile
    • snapshot() now loads the profile once and derives both views from memory.
  • Design tradeoff:

    • Considered replacing file locks with an in-process mutex, but retained the existing cross-process-safe lock protocol because standalone openhuman-core debug mode still supports multi-process execution.
    • Chose targeted hardening over larger locking architecture changes.

Submission Checklist

If a section does not apply to this change, mark the item as N/A with 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. Run pnpm test:coverage and pnpm test:rust locally; 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 #NNN in the ## Related section — 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::metadata checks during stale-lock probing).
  • 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

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.

Review Change Stack

YellowSnnowmann avatar May 18 '26 09:05 YellowSnnowmann

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.rs
  • src/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.rs lock 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.

coderabbitai[bot] avatar May 18 '26 09:05 coderabbitai[bot]