← Back to Pull requests

Make UI hang detector activation and teardown lifetime-safe #99

Closed
unknown closed this pull request without merging on Nov 23, 2026 17:37 UTC
View on GitHub
unknown unknown commented on Nov 19, 2026 20:30 UTC
Author

Description


Make UiHangDetector activation transactional and its teardown lifetime-safe: a hook notification never reaches a partially initialized or destroyed detector, and Stop never holds _instanceMutex while it joins the watchdog or removes the hook.

  • The constructor no longer sets the static _instance or creates the stop event. _instance and _instanceMutex are now private.

  • MonitorWindowHangs runs the activation stages in order and sets _instance last. A failed stage or an exception releases the earlier stages, and the same detector can be activated again. While another detector is active, activation is rejected before anything is acquired.

  • Stop stops the watchdog, removes the hook, then clears _instance. It is idempotent, final and noexcept, and the destructor calls it.

  • Windows calls go through a new IUiHangDetectorRuntime seam. The public constructor uses a file-scope production runtime; the private injected constructor is reserved for UiHangDetectorLifetimeTests. The runtime owns the WH_GETMESSAGE hook: its hook procedure passes each removed MSG to the detector and always calls CallNextHookEx.

  • The watchdog exits when its wait fails, and also when signaling the stop event fails.

  • Out of scope: session/sequence probe tokens and terminal active-hang samples, which belong to PROF-16788.
  • Activation stages

    | Stage | Acquires | Released on a later failure by |
    |---|---|---|
    | 1 | Stop event | CloseHandle |
    | 2 | Window and thread validation: IsWindow, GetWindowThreadProcessId, same process, monitored ThreadInfo | Clearing _hWnd and _pThreadInfo |
    | 3 | Message hook on the window thread | RemoveMessageHook |
    | 4 | Watchdog thread (a null or non-joinable thread is a failure) | Not needed: the last stage cannot fail |
    | 5 | _instance = this | Not needed |

    The watchdog posts its first probe only once _instance is set. A probe processed earlier would never be observed, so the watchdog would report a hang that never ends.

    Teardown order (Stop, destructor and activation rollback)


    1. Request the stop, signal the stop event, then join the watchdog. Hook notifications keep reaching the detector until the watchdog has exited, so a probe in flight is still acknowledged.
    2. Remove the hook.
    3. Clear _instance under _instanceMutex, only if it points to this detector. The hook callback holds this lock while it calls into the detector, so this waits for a notification that is being processed. Later notifications, which Windows can still deliver after the hook is removed, find no detector.
    4. Close the stop event, then clear the window and thread references. Stop also clears the provider references.

    _instanceMutex is never held while joining or removing the hook. Each step is skipped when already done, which makes Stop and destruction idempotent. Only one detector is active at a time, and MonitorWindowHangs and Stop calls must not overlap, on any detector; Profiler guarantees this with its lifecycle mutex.

    Motivation


    Previously:
  • The constructor published _this before the event, hook or watchdog existed.

  • A failed activation left _this published and kept partial state. For example, _hWnd stayed set when the window thread was not monitored, so a retry was rejected as a second window.

  • A watchdog thread creation failure threw out of MonitorWindowHangs instead of failing cleanly.

  • Stop held _instanceMutex while it joined the watchdog, closed the event and unhooked, and _this was cleared unconditionally.
  • Testing


  • Built successfully on Windows

  • Existing tests pass

  • New tests added (if applicable)

  • Manually tested
  • Local results at 865b6fa: Debug and Release with the Visual Studio generator (MSVC 19.35), and an ASan Debug build with Ninja (MSVC 14.51) and the CI ASAN_OPTIONS:

  • Tests.exe --gtest_filter=UiHangDetectorLifetimeTests.* passes 26/26. Shuffled repeats also pass: 40 in Debug and 20 in Release.

  • The full Tests.exe passes 263/263 in Debug, Release and under ASan.

  • test_ui_hangs.ps1 passes 23/23 checks with both -Config Debug and -Config Release.

  • check-format passes with clang-format 20.1.8.
  • Race and failure tests (UiHangDetectorLifetimeTests)


    The tests are deterministic. A fake runtime records each call together with what a hook notification would find at that moment: whether _instanceMutex is free and which detector _instance points to. It also injects failures and parks callers at points chosen by the test. Its clock never advances, and the watchdog only ticks when the test grants a tick.
  • Activation failures: each failure (event, invalid window, no window thread, foreign process, unmonitored thread, hook failure or exception, watchdog exception, null or non-joinable watchdog thread) releases exactly the earlier stages, in order and without _instanceMutex. Nothing is left behind, the providers are kept, and the same detector then activates. A null ThreadList, and a second detector while one is active, are rejected without any runtime call.

  • Activation order: no activation call sees _instance set. The watchdog runs one loop iteration before _instance is set without posting a probe, and posts once it is set.

  • Stop order: SetEvent, watchdog exit, RemoveMessageHook, then CloseHandle, each with _instanceMutex free. A message delivered during the hook removal still reaches the live detector.

  • Hook notification versus Stop and destruction: while a notification is parked inside the detector, holding _instanceMutex, Stop and destruction stop the watchdog and remove the hook, then wait. The notification completes on the live detector before anything is released. Later notifications never reach the destroyed detector, and ASan covers the use-after-free.

  • Probe post versus Stop: while the watchdog is parked in PostMessageW, Stop has signaled and waits in join, with _instanceMutex free and the detector still receiving notifications.

  • Failures while running: a failed stop-event signal still stops the watchdog (reverting this fallback makes the test time out), a failed wait exits it, and a failed probe post is retried on the next tick.

  • Messages: only the probe message for the monitored window is observed.

  • Idempotency: repeated Stop, Stop on an unused detector, and destruction after Stop make no runtime calls. Destroying an active detector runs the full teardown, and a stopped detector refuses to monitor.
  • Checklist


  • Code follows existing style

  • Documentation updated (if needed)

  • No breaking changes (or clearly documented)
  • UiHangDetector is internal, and Profiler uses the public constructor. Behavior changes: a stopped detector cannot monitor again, which matches how Profiler already creates one detector per MonitorWindowHangs call; and activation is rejected instead of taking over when another detector is active.

    https://datadoghq.atlassian.net/browse/PROF-16779

    [PROF-16788]: https://datadoghq.atlassian.net/browse/PROF-16788?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: fuzzybinary Review duration: 5587m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #99"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%