feat(windows): log who holds the window manager lock, and step timings of replace-configuration

Instrumentation for the stalls of the stall analysis; no behaviour change.

lock_holder.rs: a place that has just locked the window manager calls
lock_holder::held("site") and keeps the returned guard next to the lock
guard; the holder (what, thread, since) is recorded in a slot of its own
(a mutex held only for a copy; the window manager lock itself is unchanged),
a hold of 200 ms or more is logged at warn when it ends ("window manager
lock held by X (thread T) for N ms"), and lock_holder::describe() names the
holder for the waiters: the border manager's "stuck for N ms" warning and
the listener's "could not acquire window manager lock" warning now end with
the holder. Sites: every command (held as "command <message>"), process_event,
reaper, monitor reconciliator, border manager, transparency and stackbar
managers. komorebi-transport: ConnectionPolicy::lock_holder() (default None),
used in that warning; the Windows policy implements it, KDE and macOS keep the
text they had.

replace-configuration logs info lines "replace-configuration: <step> took N
ms" for restore, preload, init, restore of the new wm, reload, swap, the
process scan for komorebi-bar and the bar restart; every command logs at
debug how long the command, update_known_hwnds and notify_subscribers took.

Verified: tools/fast-check: native, Windows clippy -D warnings, KDE check +
lib tests PASS; the macOS step of fast-check fails to select a package on this
merged tree (tool issue: -p komorebi), the macOS check run by hand with -p
komorebi-macos -p komorebic-macos -p komorebi-client-macos -p
komorebi-bar-macos passes. Not run: e2e.
This commit is contained in:
LGUG2Z committed 2026-11-05 15:03:26 -08:00
1 parent 4e2c50e526
commit 5eaa5fcfa2
10 files changed
+162 -3

No files matched your search

+11 -1
View File
@@ -86,6 +86,12 @@ pub trait ConnectionPolicy<S>: Clone + Send + Sync + 'static {
fn on_accept(&self, _stream: &S) {}
fn on_message(&self, _message: &SocketMessage, _stream: &S) {}
/// Who holds the window manager lock now, for the warning when it could not be acquired.
/// Defaults to nothing: only a daemon that records its holders can say.
fn lock_holder(&self) -> Option<String> {
None
}
}
/// The policy that does nothing at either point
@@ -190,7 +196,11 @@ where
None => {
tracing::warn!(
target: LOG_TARGET,
"could not acquire window manager lock, not processing message: {message}"
"could not acquire window manager lock, not processing message: {message}{}",
policy
.lock_holder()
.map(|holder| format!(" (held by {holder})"))
.unwrap_or_default()
);
}
Some(ended) => {
+6 -2
View File
@@ -375,8 +375,11 @@ fn watch_steps() {
&& warned != Some(since)
{
tracing::warn!(
"border manager: stuck for {} ms in `{name}`",
since.elapsed().as_millis()
"border manager: stuck for {} ms in `{name}`{}",
since.elapsed().as_millis(),
crate::lock_holder::describe()
.map(|holder| format!(" (window manager lock held by {holder})"))
.unwrap_or_default()
);
warned = Some(since);
}
@@ -419,6 +422,7 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result
let _waiting = Waiting;
// Check the wm state every time we receive a notification
let state = wm.lock();
let _held = crate::lock_holder::held("border manager");
let is_paused = state.is_paused;
let focused_monitor_idx = state.focused_monitor_idx();
let focused_workspace_idx =
+1
View File
@@ -20,6 +20,7 @@ pub mod pan;
pub mod process_command;
pub mod process_event;
pub mod process_movement;
pub mod lock_holder;
pub mod reaper;
pub mod scrolling;
pub mod set_window_position;
+108
View File
@@ -0,0 +1,108 @@
//! Who holds the window manager lock, and for how long.
//!
//! The window manager is one `Arc<Mutex<WindowManager>>` that every thread locks. When a hold
//! runs long, the other threads can only say that they are waiting ("could not acquire", "stuck
//! for"), not for whom. A place that locks it calls [`held`] right after it has the guard and
//! keeps the returned [`Held`] next to the guard: the holder is recorded in a slot of its own
//! (a mutex that is only ever held for the time of a copy, never while anything else is done),
//! a hold that lasts longer than [`SLOW`] is logged when it ends, and [`describe`] tells the
//! waiters who it is.
use parking_lot::Mutex;
use std::borrow::Cow;
use std::thread::Thread;
use std::time::Duration;
use std::time::Instant;
/// A hold longer than this is logged when it ends
pub const SLOW: Duration = Duration::from_millis(200);
struct Holder {
what: Cow<'static, str>,
thread: Thread,
since: Instant,
}
static HOLDER: Mutex<Option<Holder>> = Mutex::new(None);
/// Records the calling thread as the holder of the window manager lock, until it is dropped
#[must_use = "the hold ends when this is dropped: keep it next to the lock guard"]
pub struct Held {
what: Cow<'static, str>,
thread: Thread,
since: Instant,
}
/// Says who has just locked the window manager: `what` is the call site or the command
pub fn held(what: impl Into<Cow<'static, str>>) -> Held {
let what = what.into();
let thread = std::thread::current();
let since = Instant::now();
*HOLDER.lock() = Some(Holder {
what: what.clone(),
thread: thread.clone(),
since,
});
Held {
what,
thread,
since,
}
}
impl Drop for Held {
fn drop(&mut self) {
let elapsed = self.since.elapsed();
// only clear the slot if it is still this hold's (another thread may have locked and
// recorded itself in the instant between this guard's release and this drop)
{
let mut slot = HOLDER.lock();
if slot
.as_ref()
.is_some_and(|holder| holder.since == self.since)
{
*slot = None;
}
}
if elapsed >= SLOW {
tracing::warn!(
"window manager lock held by {} (thread {}) for {} ms",
self.what,
self.thread.name().unwrap_or("unnamed"),
elapsed.as_millis()
);
}
}
}
/// Who holds the lock now and for how long so far, for the warnings of the threads that wait
pub fn describe() -> Option<String> {
HOLDER.lock().as_ref().map(|holder| {
format!(
"{} (thread {}) for {} ms so far",
holder.what,
holder.thread.name().unwrap_or("unnamed"),
holder.since.elapsed().as_millis()
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_holder_is_described_while_held_and_not_after() {
let hold = held("a test");
let described = describe().expect("a holder is recorded");
assert!(described.starts_with("a test (thread "), "{described}");
drop(hold);
// another test may hold at the same time: only check that this one is gone
assert!(describe().is_none_or(|d| !d.starts_with("a test (")));
}
}
@@ -277,6 +277,7 @@ where
// Keep reference to Arc for potential re-locking
let wm_arc = Arc::clone(&wm);
let mut wm = wm.lock();
let _held = crate::lock_holder::held("monitor reconciliator");
let initial_state = State::from(wm.as_ref());
+31
View File
@@ -128,6 +128,10 @@ impl ConnectionPolicy<UnixStream> for WindowsConnectionPolicy {
}
}
fn lock_holder(&self) -> Option<String> {
crate::lock_holder::describe()
}
fn on_message(&self, message: &SocketMessage, stream: &UnixStream) {
// the fingers of a gesture can be still for longer than a command is waited for, and
// what they do next is told on this connection: it is closed when they have lifted
@@ -221,6 +225,8 @@ impl WindowManager {
message: SocketMessage,
mut reply: impl std::io::Write,
) -> eyre::Result<()> {
let _held = crate::lock_holder::held(format!("command {message}"));
let command_started = std::time::Instant::now();
if let Some(virtual_desktop_id) = &self.virtual_desktop_id
&& let Some(id) = current_virtual_desktop()
&& id != *virtual_desktop_id
@@ -1458,7 +1464,9 @@ impl WindowManager {
};
// Update list of known_hwnds and their monitor/workspace index pair
let after_command = std::time::Instant::now();
self.update_known_hwnds();
let after_hwnds = std::time::Instant::now();
notify_subscribers(
Notification {
@@ -1467,6 +1475,12 @@ impl WindowManager {
},
initial_state.has_been_modified(self.as_ref()),
)?;
tracing::debug!(
"processed `{message}`: command {} ms, known hwnds {} ms, notify subscribers {} ms",
after_command.duration_since(command_started).as_millis(),
after_hwnds.duration_since(after_command).as_millis(),
after_hwnds.elapsed().as_millis()
);
if force_update_borders {
border_manager::send_force_update();
@@ -1572,6 +1586,15 @@ impl WindowManager {
pub fn replace_configuration(&mut self, config: &std::path::PathBuf) -> eyre::Result<bool> {
let mut force_update_borders = false;
let mut last = std::time::Instant::now();
let mut lap = |step: &str| {
let now = std::time::Instant::now();
tracing::info!(
"replace-configuration: {step} took {} ms",
now.duration_since(last).as_millis()
);
last = now;
};
// Check that this is a valid static config file first
if StaticConfig::read(config).is_ok() {
// Clear workspace rules; these will need to be replaced
@@ -1580,6 +1603,7 @@ impl WindowManager {
self.is_paused = true;
// Bring all windows to the foreground
self.restore_all_windows(false)?;
lap("restore all windows");
// Create a new wm from the config path
let mut wm = StaticConfig::preload(
@@ -1587,17 +1611,22 @@ impl WindowManager {
winevent_listener::event_rx(),
self.command_listener.try_clone().ok(),
)?;
lap("preload");
// Initialize the new wm
wm.init()?;
lap("init");
wm.restore_all_windows(true)?;
lap("restore all windows of the new wm");
// This is equivalent to StaticConfig::postload for this use case
StaticConfig::reload(config, &mut wm)?;
lap("reload");
// Set self to the new wm instance
*self = wm;
lap("swap");
// check if there are any bars
let mut system = sysinfo::System::new_all();
@@ -1607,6 +1636,7 @@ impl WindowManager {
.processes_by_name("komorebi-bar.exe".as_ref())
.next()
.is_some();
lap("process scan for komorebi-bar");
// stop bar(s)
if has_bar {
@@ -1656,6 +1686,7 @@ if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue))
}
}
lap("bar restart");
force_update_borders = true;
}
Ok(force_update_borders)
+1
View File
@@ -124,6 +124,7 @@ pub fn listen_for_events(wm: Arc<Mutex<WindowManager>>) {
loop {
if let Ok(event) = receiver.recv() {
let mut guard = wm.lock();
let _held = crate::lock_holder::held("process_event");
match guard.process_event(event) {
Ok(()) => {}
Err(error) => {
+1
View File
@@ -78,6 +78,7 @@ fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result<()>
for notification in receiver {
let orphan_hwnds = notification.0;
let mut wm = wm.lock();
let _held = crate::lock_holder::held("reaper");
let mut update_borders = false;
+1
View File
@@ -96,6 +96,7 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result
// Check the wm state every time we receive a notification
let mut state = wm.lock();
let _held = crate::lock_holder::held("stackbar manager");
// If stackbars are disabled
if matches!(STACKBAR_MODE.load(), StackbarMode::Never)
+1
View File
@@ -85,6 +85,7 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> color_eyre::Result
// Check the wm state every time we receive a notification
let state = wm.lock();
let _held = crate::lock_holder::held("transparency manager");
let focused_monitor_idx = state.focused_monitor_idx();