mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-27 07:58:01 +01:00
* fix(meetings): recover recordings lost to a quit or update restart Rune ends a quitting app with `_exit` unless it is told the app has work after its loop, so every in-app quit (Quit Hex, `hex quit`, Restart to update) skipped Hex's drain since the Nov 14 Rune bump. A meeting recording was killed mid-write: zeroed WAV headers, no `final.pending`, and nothing to recover at the next launch. - `rune::orderly_exit()` in the macOS, Windows, and Linux app loops, so the existing teardown runs on every quit; the AppKit terminate path still drains from its will-terminate notification. - macOS joins the meeting controller before installing a staged update and before the other workers, and a recording gets 30 s to finalise rather than 5. - `meeting::recording()` is a process-wide flag the updater reads. Restart to update refuses with a reason, re-checks before swapping, and keeps the release staged. - Launch recovery selects every unlocked unfinished meeting, not just `final.pending`; repairs zeroed or wrong WAV RIFF/data sizes from the file length, fills sample counts and duration from the audio, and runs the existing final pass so the transcript, Markdown export, and notes are written. Failed and completed meetings are untouched. Checks: `a_zeroed_wav_header_is_repaired_from_its_file_length`, `a_stranded_recording_is_selected_for_recovery`, `recovery_fills_the_manifest_from_the_repaired_audio`, `the_flag_holds_until_the_recorder_drops_it`, `restart_to_update_waits_while_a_meeting_records`. * fix(meetings): settle recovery attempts and keep retention honest Reviews of #1900: - a recovery that dies during the final pass leaves recovery.attempt; the next launch marks the meeting Interrupted ("recovery did not finish") and never retries that audio. final.pending folders that already have a transcript are finished too. - a repaired, unfinalised track overwrites list_all's relabel with the audio's real duration and ended_at. - retention only waits for stranded meetings while recovery can run (Meetings on, model installed); the MCP query uses the same rule. - repair only rewrites a zero or overlong data chunk, so a trailing chunk or pad byte is never read as audio. - the macOS status item dims Restart to update while a meeting records. - finish_restart keeps Ready only when an update is staged. - macOS installs a staged update before joining the controller when nothing records; Windows arms a 20 s teardown deadline; Linux writes its reopen marker only after a restart is accepted. - the recording flag is a counter, tested without assuming idleness. * fix(meetings): bound recovery retries and harden quits - recovery.attempt now counts attempts: a pass that dies is retried once, then the meeting is marked Interrupted ("recovery did not finish") and that audio is never handed to Hex again. The pass holds the meeting busy flag, so the quit deadline and Restart to update wait for it. - a finished meeting with a stale attempt marker keeps its final.pending, which the ordinary final pass then exports; settling no longer deletes it. - pending recoveries stop between meetings when a recording starts and are offered again once Hex is idle. - an empty finalised track is not "unfinalised"; the audio's duration wins whenever repair changed the manifest's track counts. - can_recover reads meetings.enabled and the model from settings.json in readers (`hex mcp`, `hex meetings`), matching the app. - updater: State::Applied is never overwritten by a later check, and a restart check that races a quit never swaps a second time. - macOS installs the staged bundle before joining the meeting controller, marks quitting before any drain, and extends the 5 s exit deadline to 30 s from the quit's start while meeting audio is in flight. `meeting::record` refuses once quitting. - Windows marks quitting after the loop, bounds teardown at 20 s (30 s while meeting audio is in flight) and exits 1 when the window failed; Linux marks quitting before joining meetings and removes a reopen marker when a restart is refused. * fix(updater): keep the staged update installable when a late download is dropped - check() now returns the state the locks actually show when it discards a release during a quit: Applied only if one was installed, else Ready while an older update is staged, else Current. install_on_quit therefore still installs the staged update a plain quit is about to apply. - after waiting for meeting audio, the macOS exit deadline gives the rest of the drain up to 5 s more, inside the 30 s bound from the quit's start. Windows polls meeting audio to 30 s instead of choosing a bound once. - the Restart to update refusal reads "Hex is finishing a meeting; restart to update when it's done", true for a recording and a launch recovery. - a recording refused because Hex is quitting removes the empty folder it created (and only when it holds nothing but the lock file). - docs: the macOS drain installs before joining the controller, and the deadline/discarded-release wording matches the code.
404 lines
14 KiB
Rust
404 lines
14 KiB
Rust
//! How a desktop app process ends.
|
|
//!
|
|
//! `exit` (what `-[NSApplication terminate:]` and returning from `main` call)
|
|
//! runs C++ static destructors and `atexit` handlers while threads Hex does
|
|
//! not join are still running: CoreAudio's IO threads or ggml's residency-set
|
|
//! keep-alive. Those destructors tear down native globals under them; ggml's
|
|
//! Metal device list aborts in `ggml_metal_rsets_free` unless every Metal
|
|
//! buffer was already freed. So Hex drains its own work first, then ends with
|
|
//! `_exit`, which runs none of them. Nothing Hex keeps relies on them: the
|
|
//! drain flushes the event log, and settings, history, and meetings are saved
|
|
//! atomically when they change. A meeting recording at quit keeps its audio
|
|
//! and finishes its transcript at the next launch.
|
|
//!
|
|
//! The drain runs on the main thread, so a worker that never stops would hang
|
|
//! quit, logout, and updates. After [`DEADLINE`] the process ends anyway; a
|
|
//! meeting still recording gets [`MEETING_DEADLINE`] to finalise its audio.
|
|
//! Dropping the transcription engine cancels its job and normally returns at
|
|
//! once; only a wedged native run reaches either bound, and `_exit` is what
|
|
//! makes leaving it running safe.
|
|
//!
|
|
//! Linux's service stop has the same shape with a longer bound: the host arms
|
|
//! [`arm_deadline`] when stopping begins, and a drain still running after
|
|
//! [`STOP_DEADLINE`] ends with the same `_exit`, logging what was pending.
|
|
//! Windows' teardown arms [`arm_windows_deadline`] with the same kind of
|
|
//! bound, since it runs after the loop and has no other deadline.
|
|
|
|
use std::io::Write;
|
|
use std::sync::Mutex;
|
|
#[cfg(any(target_os = "linux", target_os = "windows"))]
|
|
use std::sync::Once;
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
use std::time::Duration;
|
|
|
|
/// How long quitting waits for the drain before ending the process anyway.
|
|
const DEADLINE: Duration = Duration::from_secs(5);
|
|
|
|
/// How long an in-flight meeting recording gets from the quit's start to
|
|
/// finalise its audio and write `final.pending`. Its capture threads can take
|
|
/// longer to stop than the rest of the drain, and ending early loses the
|
|
/// recording.
|
|
const MEETING_DEADLINE: Duration = Duration::from_secs(30);
|
|
|
|
/// How long a Linux stop may drain before the process ends anyway. Shorter
|
|
/// than the unit's `TimeoutStopSec=30`, with room for a CPU transcription to
|
|
/// finish.
|
|
#[cfg(target_os = "linux")]
|
|
const STOP_DEADLINE: Duration = Duration::from_secs(20);
|
|
|
|
/// How long a Windows exit may drain before the process ends anyway: the
|
|
/// same bound as Linux's stop, with room for a meeting recording to finalise.
|
|
#[cfg(target_os = "windows")]
|
|
const WINDOWS_DEADLINE: Duration = Duration::from_secs(20);
|
|
|
|
static QUITTING: AtomicBool = AtomicBool::new(false);
|
|
|
|
/// Whether the process has begun quitting. Work that would outlast the
|
|
/// drain, such as loading a model, checks this and stops instead.
|
|
pub(crate) fn quitting() -> bool {
|
|
QUITTING.load(Ordering::Acquire)
|
|
}
|
|
|
|
/// Marks the process as quitting without ending it: the Linux and Windows
|
|
/// apps, which end by returning from `main` once their workers stop.
|
|
#[cfg(not(target_os = "macos"))]
|
|
pub(crate) fn begin_quitting() {
|
|
QUITTING.store(true, Ordering::Release);
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) fn begin_quitting_for_test() {
|
|
QUITTING.store(true, Ordering::Release);
|
|
}
|
|
|
|
/// Work that must finish before the process ends, run once by whichever
|
|
/// quit path gets there first.
|
|
pub(crate) struct Drain(Mutex<Option<Box<dyn FnOnce() + Send>>>);
|
|
|
|
impl Drain {
|
|
pub(crate) const fn new() -> Self {
|
|
Self(Mutex::new(None))
|
|
}
|
|
|
|
pub(crate) fn set(&self, work: impl FnOnce() + Send + 'static) {
|
|
*self.lock() = Some(Box::new(work));
|
|
}
|
|
|
|
/// Runs the drain if nothing has yet; reports whether this call ran it.
|
|
pub(crate) fn run(&self) -> bool {
|
|
let work = self.lock().take();
|
|
let ran = work.is_some();
|
|
if let Some(work) = work {
|
|
work();
|
|
}
|
|
ran
|
|
}
|
|
|
|
fn lock(&self) -> std::sync::MutexGuard<'_, Option<Box<dyn FnOnce() + Send>>> {
|
|
self.0.lock().unwrap_or_else(|error| error.into_inner())
|
|
}
|
|
}
|
|
|
|
/// Drains, then ends the process without running static destructors.
|
|
pub(crate) fn finish(drain: &Drain) -> ! {
|
|
finish_within(drain, DEADLINE, 0)
|
|
}
|
|
|
|
/// `finish`, ending with `code`: a launch whose window never started exits 1.
|
|
pub(crate) fn finish_with(drain: &Drain, code: i32) -> ! {
|
|
finish_within(drain, DEADLINE, code)
|
|
}
|
|
|
|
fn finish_within(drain: &Drain, deadline: Duration, code: i32) -> ! {
|
|
QUITTING.store(true, Ordering::Release);
|
|
let started = std::time::Instant::now();
|
|
let _ = std::thread::Builder::new()
|
|
.name("hex-exit-deadline".into())
|
|
.spawn(move || {
|
|
std::thread::sleep(deadline);
|
|
// A recording in flight may have started just before quitting was
|
|
// marked (or be finalising its audio now). It gets the meeting
|
|
// bound from the quit's start, so the recorder can write its WAV
|
|
// headers and `final.pending` before `_exit`.
|
|
let bound = started + MEETING_DEADLINE;
|
|
let mut waiting = false;
|
|
while crate::meeting::recording() && std::time::Instant::now() < bound {
|
|
if !waiting {
|
|
waiting = true;
|
|
tracing::info!("waiting for a meeting recording to finish before stopping");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
}
|
|
if waiting {
|
|
// The meeting finished, but the drain still has joins, audio
|
|
// restore, and the event-log flush left. Give it the ordinary
|
|
// deadline again, capped by the meeting bound from the quit.
|
|
let grace = bound
|
|
.saturating_duration_since(std::time::Instant::now())
|
|
.min(DEADLINE);
|
|
if !grace.is_zero() {
|
|
std::thread::sleep(grace);
|
|
}
|
|
}
|
|
tracing::warn!("Hex stopped before its workers finished");
|
|
end_process(code);
|
|
});
|
|
drain.run();
|
|
tracing::info!("Hex stopped");
|
|
end_process(code)
|
|
}
|
|
|
|
fn end_process(code: i32) -> ! {
|
|
let _ = std::io::stdout().flush();
|
|
let _ = std::io::stderr().flush();
|
|
// SAFETY: `_exit` ends the process immediately; nothing runs after it.
|
|
unsafe { libc::_exit(code) }
|
|
}
|
|
|
|
/// What a stopping Linux process is still waiting on, named in the deadline's
|
|
/// log so a stuck stop shows its last stage.
|
|
#[cfg(target_os = "linux")]
|
|
#[derive(Clone, Copy)]
|
|
pub(crate) enum PendingWork {
|
|
/// The host still drains the listener, an uncommitted shortcut edit, or
|
|
/// model preparation; the window and meetings may also be stopping.
|
|
Draining = 1,
|
|
/// The listener drained; the socket server, window, meetings, local API,
|
|
/// or tray are still stopping.
|
|
Teardown = 2,
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
static PENDING_WORK: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
|
|
|
|
/// Records what a stopping Linux process is doing, for the deadline's log.
|
|
#[cfg(target_os = "linux")]
|
|
pub(crate) fn set_pending_work(work: PendingWork) {
|
|
PENDING_WORK.store(work as u8, Ordering::Release);
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
fn pending_work() -> &'static str {
|
|
match PENDING_WORK.load(Ordering::Acquire) {
|
|
1 => {
|
|
"the listener, a shortcut edit, or model preparation (the window and meetings may also be stopping)"
|
|
}
|
|
2 => {
|
|
"the listener drained; the socket server, window, meetings, local API, or tray are still stopping"
|
|
}
|
|
_ => "the host had not noticed the stop yet",
|
|
}
|
|
}
|
|
|
|
/// Ends a stopping Linux process even if its orderly shutdown wedges, naming
|
|
/// what was still pending. Only the first call arms it, so every shutdown
|
|
/// trigger can call it.
|
|
#[cfg(target_os = "linux")]
|
|
pub(crate) fn arm_deadline() {
|
|
static ARMED: Once = Once::new();
|
|
ARMED.call_once(|| {
|
|
if let Err(error) = run_deadline(STOP_DEADLINE, false, pending_work, || end_process(0)) {
|
|
tracing::warn!(%error, "could not arm Hex's exit deadline");
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Bounds a Windows exit's teardown on the main thread, as Linux's stop is
|
|
/// bounded: a worker that never stops cannot hold the process open. Meeting
|
|
/// audio still in flight extends the bound to [`MEETING_DEADLINE`]. Only the
|
|
/// first call arms it.
|
|
#[cfg(target_os = "windows")]
|
|
pub(crate) fn arm_windows_deadline(code: i32) {
|
|
static ARMED: Once = Once::new();
|
|
ARMED.call_once(|| {
|
|
if let Err(error) = run_deadline(
|
|
WINDOWS_DEADLINE,
|
|
true,
|
|
|| "the runtime, meetings, local API, or tray",
|
|
move || end_process(code),
|
|
) {
|
|
tracing::warn!(%error, "could not arm Hex's exit deadline");
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Starts the detached named thread that runs `exit` after `deadline`; the
|
|
/// result reports whether it started. With `wait_for_meeting`, meeting audio
|
|
/// still in flight extends the wait to [`MEETING_DEADLINE`], polled rather
|
|
/// than read once so audio that starts during the drain is covered.
|
|
#[cfg(any(target_os = "linux", target_os = "windows"))]
|
|
fn run_deadline(
|
|
deadline: Duration,
|
|
wait_for_meeting: bool,
|
|
pending: impl Fn() -> &'static str + Send + 'static,
|
|
exit: impl FnOnce() + Send + 'static,
|
|
) -> std::io::Result<()> {
|
|
std::thread::Builder::new()
|
|
.name("hex-exit-deadline".into())
|
|
.spawn(move || {
|
|
let started = std::time::Instant::now();
|
|
std::thread::sleep(deadline);
|
|
if wait_for_meeting {
|
|
let bound = started + MEETING_DEADLINE;
|
|
let mut waiting = false;
|
|
while crate::meeting::recording() && std::time::Instant::now() < bound {
|
|
if !waiting {
|
|
waiting = true;
|
|
tracing::info!("waiting for meeting audio to finish before stopping");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
}
|
|
}
|
|
tracing::warn!(
|
|
pending = pending(),
|
|
"Hex's shutdown did not finish before its exit deadline"
|
|
);
|
|
exit();
|
|
})
|
|
.map(|_| ())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::sync::Arc;
|
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
|
|
#[test]
|
|
fn a_drain_runs_once_whichever_path_comes_first() {
|
|
let drain = Drain::new();
|
|
let runs = Arc::new(AtomicUsize::new(0));
|
|
let counted = runs.clone();
|
|
drain.set(move || {
|
|
counted.fetch_add(1, Ordering::SeqCst);
|
|
});
|
|
assert!(drain.run());
|
|
assert!(!drain.run());
|
|
assert_eq!(runs.load(Ordering::SeqCst), 1);
|
|
}
|
|
|
|
const CHILD: &str = "HEX_PROCESS_EXIT_CHILD";
|
|
|
|
/// The child half of `finishing_stops_the_listener_and_skips_static_destructors`.
|
|
#[test]
|
|
fn finishing_child() {
|
|
if std::env::var_os(CHILD).is_none() {
|
|
return;
|
|
}
|
|
extern "C" fn static_destructor() {
|
|
// What ggml's Metal teardown does with a live buffer.
|
|
std::process::abort();
|
|
}
|
|
/// A native session the listener frees when it stops.
|
|
struct Session;
|
|
impl Drop for Session {
|
|
fn drop(&mut self) {
|
|
print!("freed ");
|
|
}
|
|
}
|
|
static DRAIN: Drain = Drain::new();
|
|
static STOP: AtomicBool = AtomicBool::new(false);
|
|
// SAFETY: registers a plain C function with no captured state.
|
|
unsafe { libc::atexit(static_destructor) };
|
|
let listener = std::thread::spawn(|| {
|
|
let _session = Session;
|
|
while !STOP.load(Ordering::SeqCst) {
|
|
std::thread::yield_now();
|
|
}
|
|
});
|
|
DRAIN.set(move || {
|
|
STOP.store(true, Ordering::SeqCst);
|
|
listener.join().unwrap();
|
|
print!("drained");
|
|
});
|
|
finish(&DRAIN);
|
|
}
|
|
|
|
/// The child half of `a_stuck_drain_still_ends_the_process`.
|
|
#[test]
|
|
fn stuck_child() {
|
|
if std::env::var_os(CHILD).is_none() {
|
|
return;
|
|
}
|
|
static DRAIN: Drain = Drain::new();
|
|
DRAIN.set(|| {
|
|
loop {
|
|
std::thread::park();
|
|
}
|
|
});
|
|
finish_within(&DRAIN, Duration::from_millis(50), 0);
|
|
}
|
|
|
|
/// The child half of `a_failed_launch_ends_with_its_code`.
|
|
#[test]
|
|
fn failing_child() {
|
|
if std::env::var_os(CHILD).is_none() {
|
|
return;
|
|
}
|
|
static DRAIN: Drain = Drain::new();
|
|
finish_with(&DRAIN, 1);
|
|
}
|
|
|
|
fn run_child(name: &str) -> std::process::Output {
|
|
std::process::Command::new(std::env::current_exe().unwrap())
|
|
.args([
|
|
"--exact",
|
|
&format!("desktop::process_exit::tests::{name}"),
|
|
"--nocapture",
|
|
])
|
|
.env(CHILD, "1")
|
|
.output()
|
|
.unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn finishing_stops_the_listener_and_skips_static_destructors() {
|
|
let output = run_child("finishing_child");
|
|
assert!(
|
|
output.status.success(),
|
|
"the child ran an atexit handler: {:?}",
|
|
output.status
|
|
);
|
|
assert!(
|
|
String::from_utf8_lossy(&output.stdout).contains("freed drained"),
|
|
"the listener did not stop and free its session before the process ended"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_stuck_drain_still_ends_the_process() {
|
|
assert!(run_child("stuck_child").status.success());
|
|
}
|
|
|
|
#[test]
|
|
fn a_failed_launch_ends_with_its_code() {
|
|
let output = run_child("failing_child");
|
|
assert_eq!(
|
|
output.status.code(),
|
|
Some(1),
|
|
"a launch whose window never started must not report success"
|
|
);
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
#[test]
|
|
fn exit_deadline_fires_only_after_its_deadline() {
|
|
let (fired, received) = std::sync::mpsc::channel();
|
|
run_deadline(
|
|
Duration::from_millis(100),
|
|
false,
|
|
|| "test",
|
|
move || {
|
|
let _ = fired.send(());
|
|
},
|
|
)
|
|
.unwrap();
|
|
assert!(
|
|
received.recv_timeout(Duration::from_millis(20)).is_err(),
|
|
"the exit deadline fired before its deadline"
|
|
);
|
|
received
|
|
.recv_timeout(Duration::from_secs(5))
|
|
.expect("the exit deadline did not fire");
|
|
}
|
|
}
|