thing-tui: the guard's owner is the thread that last entered or drew through it

A guard moved to a render thread follows its user: that thread's panic restores before its
message, and a panic on the thread that gave it away leaves it to the owner.

Per the steward's decision on thing2:finding:cut-tui-host.s2.guard-owner-is-the-constructing-thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-29 02:29:08 +01:00
commit 0b58fd729c
2 changed files with 57 additions and 6 deletions

View file

@ -27,13 +27,21 @@ struct Shared<W> {
out: Mutex<W>,
entered: AtomicBool,
raw: bool,
/// The thread that last entered or drew through the guard: a panic there is a panic in the guard's
/// user, and a guard moved to another thread is owned by whoever uses it.
owner: Mutex<ThreadId>,
}
trait Restore: Send + Sync {
fn owner(&self) -> ThreadId;
fn restore(&self);
}
impl<W: Write + Send> Restore for Shared<W> {
fn owner(&self) -> ThreadId {
*self.owner.lock().unwrap_or_else(PoisonError::into_inner)
}
fn restore(&self) {
// The lock is held across a write: a panic inside one (on this thread) reaches the hook with
// it taken. The escape bytes are left to `Drop`, which runs once the unwinding has released
@ -61,10 +69,10 @@ impl<W: Write + Send> Restore for Shared<W> {
/// The guards that are entered, each with the thread that entered it: the only terminals a panic
/// hook may give back, and only to a panic on the thread that owns one.
static GUARDS: Mutex<Vec<(ThreadId, Arc<dyn Restore>)>> = Mutex::new(Vec::new());
static GUARDS: Mutex<Vec<Arc<dyn Restore>>> = Mutex::new(Vec::new());
static HOOK: Once = Once::new();
fn guards() -> MutexGuard<'static, Vec<(ThreadId, Arc<dyn Restore>)>> {
fn guards() -> MutexGuard<'static, Vec<Arc<dyn Restore>>> {
GUARDS.lock().unwrap_or_else(PoisonError::into_inner)
}
@ -110,8 +118,8 @@ impl<W: Write + Send + 'static> Terminal<W> {
enable_raw_mode()?;
}
// Registered before anything is written, so a failure part-way still restores on drop.
let shared = Arc::new(Shared { out: Mutex::new(out), entered: AtomicBool::new(true), raw });
guards().push((thread::current().id(), shared.clone()));
let shared = Arc::new(Shared { out: Mutex::new(out), entered: AtomicBool::new(true), raw, owner: Mutex::new(thread::current().id()) });
guards().push(shared.clone());
let terminal = Self { shared };
{
let mut out = terminal.out();
@ -127,6 +135,7 @@ impl<W: Write + Send + 'static> Terminal<W> {
/// Serialize `ops` as one synchronized update and flush once. No ops write nothing.
pub fn draw(&mut self, ops: &[Op]) -> io::Result<()> {
*self.shared.owner.lock().unwrap_or_else(PoisonError::into_inner) = thread::current().id();
if ops.is_empty() {
return Ok(());
}
@ -153,7 +162,7 @@ impl<W: Write + Send + 'static> Terminal<W> {
impl<W: Write + Send + 'static> Drop for Terminal<W> {
fn drop(&mut self) {
guards().retain(|(_, guard)| !std::ptr::addr_eq(Arc::as_ptr(guard), Arc::as_ptr(&self.shared)));
guards().retain(|guard| !std::ptr::addr_eq(Arc::as_ptr(guard), Arc::as_ptr(&self.shared)));
self.shared.restore();
}
}
@ -211,7 +220,7 @@ fn install_panic_hook() {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let here = thread::current().id();
let owned: Vec<Arc<dyn Restore>> = guards().iter().filter(|(owner, _)| restores_here(cfg!(panic = "abort"), *owner, here)).map(|(_, guard)| guard.clone()).collect();
let owned: Vec<Arc<dyn Restore>> = guards().iter().filter(|guard| restores_here(cfg!(panic = "abort"), guard.owner(), here)).cloned().collect();
for guard in owned {
guard.restore();
}

View file

@ -322,3 +322,45 @@ fn a_panic_restores_on_the_owners_thread_and_on_any_thread_when_nothing_unwinds(
assert!(restores_here(true, here, here));
assert!(restores_here(true, here, elsewhere));
}
#[test]
fn a_guard_moved_to_a_render_thread_follows_its_user() {
let out = Shared::default();
let terminal = guard(&out);
let watched = out.clone();
let at_hook = std::thread::spawn(move || {
WATCH.with(|watch| *watch.borrow_mut() = Some(watched));
AT_HAND_OVER.with(|seen| *seen.borrow_mut() = None);
let mut terminal = terminal;
terminal.draw(&[Op::MoveTo(0, 0), Op::Print("x".into())]).unwrap();
let _ = catch_unwind(AssertUnwindSafe(move || {
let _terminal = terminal;
panic!("forced on the render thread");
}));
at_hand_over()
})
.join()
.unwrap();
assert_eq!(count(&at_hook.expect("the previous hook was reached"), LEAVE), 1, "the thread that drew restores before its message");
assert_eq!(count(&out.bytes(), LEAVE), 1);
}
#[test]
fn a_panic_on_the_thread_that_built_a_guard_it_gave_away_leaves_it_alone() {
let out = Shared::default();
let mut terminal = guard(&out);
let terminal = std::thread::spawn(move || {
terminal.draw(&[Op::MoveTo(0, 0), Op::Print("x".into())]).unwrap();
terminal
})
.join()
.unwrap();
let caught = catch_unwind(AssertUnwindSafe(move || {
let _terminal = terminal;
panic!("forced on the thread that built it");
}));
assert!(caught.is_err());
let seen = at_hand_over().expect("the previous hook was reached");
assert_eq!(count(&seen, LEAVE), 0, "the render thread owns it now; this panic's unwinding drop restores");
assert_eq!(count(&out.bytes(), LEAVE), 1);
}