From 35e9252c82d71035f33cfd6b725e3c189a468912 Mon Sep 17 00:00:00 2001 From: dbuddha Date: Fri, 2 Oct 2026 03:42:05 -0700 Subject: [PATCH 1/6] fix(macos): finish in-flight frames and closes without display-link updates A 40 ms frame-progress timer polls completion and drains a close when updates stop; drawables release at command completion and a close always invalidates. --- crates/alpine-platform-macos/src/lib.rs | 85 +++ crates/alpine-platform-macos/src/native.rs | 489 ++++++++++++++---- .../tests/native_lifecycle.rs | 77 +++ .../tests/native_presentation.rs | 17 +- .../tests/native_recovery.rs | 78 ++- 5 files changed, 644 insertions(+), 102 deletions(-) diff --git a/crates/alpine-platform-macos/src/lib.rs b/crates/alpine-platform-macos/src/lib.rs index 6ff5dd31..6c85bdbd 100644 --- a/crates/alpine-platform-macos/src/lib.rs +++ b/crates/alpine-platform-macos/src/lib.rs @@ -1551,6 +1551,91 @@ pub mod native_validation { surface.implementation.completion_diagnostic() } + /// Drops display-link updates while a frame is in flight, modeling a link + /// that stops delivering updates. Pass `false` to restore delivery. + pub fn inject_display_link_silence(surface: &NativeSurface, silenced: bool) { + surface.implementation.inject_display_link_silence(silenced); + } + + /// Validation-only counters for the frame-progress timer. + #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] + pub struct FrameProgressEvidence { + silenced_updates: u64, + timer_schedules: u64, + timer_ticks: u64, + timer_terminals: u64, + timer_close_drains: u64, + timer_armed: bool, + } + + impl FrameProgressEvidence { + pub(crate) const fn new( + silenced_updates: u64, + timer_schedules: u64, + timer_ticks: u64, + timer_terminals: u64, + timer_close_drains: u64, + timer_armed: bool, + ) -> Self { + Self { + silenced_updates, + timer_schedules, + timer_ticks, + timer_terminals, + timer_close_drains, + timer_armed, + } + } + + /// Returns display-link updates dropped by injected silence. + #[must_use] + pub const fn silenced_updates(self) -> u64 { + self.silenced_updates + } + + /// Returns frame-progress timers scheduled for in-flight frames. + #[must_use] + pub const fn timer_schedules(self) -> u64 { + self.timer_schedules + } + + /// Returns frame-progress timer callbacks. + #[must_use] + pub const fn timer_ticks(self) -> u64 { + self.timer_ticks + } + + /// Returns frames whose terminal state the timer recorded. + #[must_use] + pub const fn timer_terminals(self) -> u64 { + self.timer_terminals + } + + /// Returns closes that the timer drained and finished. + #[must_use] + pub const fn timer_close_drains(self) -> u64 { + self.timer_close_drains + } + + /// Returns whether a frame-progress timer is scheduled now. + #[must_use] + pub const fn timer_armed(self) -> bool { + self.timer_armed + } + } + + /// Returns frame-progress timer and injected-silence evidence. + #[must_use] + pub fn frame_progress_evidence(surface: &NativeSurface) -> FrameProgressEvidence { + surface.implementation.frame_progress_evidence() + } + + /// Returns ownership and cleanup counts without closing the surface. + #[must_use] + pub fn owner_evidence(surface: &NativeSurface) -> Option { + surface.implementation.owner_evidence() + } + /// Last display-link directive observed by native pause qualification. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum PauseDirectiveEvidence { diff --git a/crates/alpine-platform-macos/src/native.rs b/crates/alpine-platform-macos/src/native.rs index b6745084..36229d68 100644 --- a/crates/alpine-platform-macos/src/native.rs +++ b/crates/alpine-platform-macos/src/native.rs @@ -32,13 +32,13 @@ use objc2_core_foundation::{CFRunLoop, kCFRunLoopCommonModes}; use objc2_core_graphics::{CGColorSpace, kCGColorSpaceSRGB}; #[cfg(alpine_native_validation)] use objc2_core_graphics::{CGEvent, CGEventFlags, CGScrollEventUnit}; +#[cfg(alpine_native_validation)] +use objc2_foundation::NSDate; use objc2_foundation::{ NSArray, NSAttributedString, NSAttributedStringKey, NSNotification, NSObject, NSObjectProtocol, - NSPoint, NSRange, NSRect, NSRunLoop, NSRunLoopCommonModes, NSSize, NSString, + NSPoint, NSRange, NSRect, NSRunLoop, NSRunLoopCommonModes, NSSize, NSString, NSTimer, NSUTF8StringEncoding, }; -#[cfg(alpine_native_validation)] -use objc2_foundation::{NSDate, NSTimer}; use objc2_metal::{MTLCreateSystemDefaultDevice, MTLDevice, MTLDrawable, MTLPixelFormat}; use objc2_quartz_core::{ CACurrentMediaTime, CAMetalDisplayLink, CAMetalDisplayLinkDelegate, CAMetalDisplayLinkUpdate, @@ -651,11 +651,9 @@ struct ActiveFrame { token: FrameToken, lease: FrameSlotLease, submission: platform_spi::DrawableSubmission, - #[allow( - dead_code, - reason = "the callback drawable must remain retained until terminal presentation evidence" - )] - drawable: Retained>, + // Released once the command is terminal so the display link can reuse it; + // presented handlers receive the drawable from Metal, not from this owner. + drawable: Option>>, frame: Option, observation: PresentationObservation, command_terminal: bool, @@ -992,37 +990,45 @@ impl PresentationDriver { match self.try_update(update, counters) { Ok(directive) => directive, Err(error) => { - let recovery = render_recovery(&error); - if discards_pending_work(recovery) { - self.pending = None; - } - self.last_error = Some(error); - counters.failed.fetch_add(1, Ordering::Relaxed); - let active = self.active.take(); - let timing = active.as_ref().map_or_else( - || AttemptTiming::from_update(update, None), - |active| active.timing, - ); - let token = active - .as_ref() - .map(|active| active.token) - .or_else(|| self.state.active_token()); - if let Some(token) = token { - self.state - .apply(PresentationAction::FailActive(token)) - .ok() - .and_then(|transition| { - self.record_terminal(transition, timing, 0, recovery, counters) - .ok() - }) - .unwrap_or(DisplayLinkDirective::Pause) - } else { - DisplayLinkDirective::Pause - } + self.fail_after_error(error, AttemptTiming::from_update(update, None), counters) } } } + fn fail_after_error( + &mut self, + error: SurfaceError, + fallback_timing: AttemptTiming, + counters: &FrameCounters, + ) -> DisplayLinkDirective { + let recovery = render_recovery(&error); + if discards_pending_work(recovery) { + self.pending = None; + } + self.last_error = Some(error); + counters.failed.fetch_add(1, Ordering::Relaxed); + let active = self.active.take(); + let timing = active + .as_ref() + .map_or(fallback_timing, |active| active.timing); + let token = active + .as_ref() + .map(|active| active.token) + .or_else(|| self.state.active_token()); + if let Some(token) = token { + self.state + .apply(PresentationAction::FailActive(token)) + .ok() + .and_then(|transition| { + self.record_terminal(transition, timing, 0, recovery, counters) + .ok() + }) + .unwrap_or(DisplayLinkDirective::Pause) + } else { + DisplayLinkDirective::Pause + } + } + fn try_update( &mut self, update: &CAMetalDisplayLinkUpdate, @@ -1031,15 +1037,23 @@ impl PresentationDriver { if self.lifecycle.load(Ordering::Acquire) != SURFACE_LIVE { return Ok(DisplayLinkDirective::Invalidate); } - if let Some(directive) = self.reconcile_active_presentation(counters)? { + if let Some(directive) = self.reconcile_active_presentation(counters, true)? { return Ok(directive); } + // A queued update can arrive after the timer paused the link. Return + // None so the caller confirms the pause instead of failing Prepare. + if !matches!(self.state.display_link(), DisplayLinkState::Running) { + return Ok(DisplayLinkDirective::None); + } self.submit_pending(update, counters) } + // `in_callback` keeps the physical link running when a newer frame waits; + // the frame-progress timer reconciles that resume itself. fn reconcile_active_presentation( &mut self, counters: &FrameCounters, + in_callback: bool, ) -> Result, SurfaceError> { if let Some(directive) = self.poll_active_command(counters)? { return Ok(Some(directive)); @@ -1074,7 +1088,7 @@ impl PresentationDriver { counters.failed.fetch_add(1, Ordering::Relaxed); let transition = self.state.apply(PresentationAction::FailActive(token))?; let directive = self.record_terminal(transition, active.timing, 0, None, counters)?; - if self.pending.is_some() { + if in_callback && self.pending.is_some() { // A newer immutable frame is genuine work, not a replay of the // dropped attempt. The physical link is still running in this // callback, so reconcile the portable pause before allowing @@ -1111,7 +1125,7 @@ impl PresentationDriver { .state .apply(PresentationAction::FailActive(active.token))?; let directive = self.record_terminal(transition, active.timing, 0, None, counters)?; - if self.pending.is_some() { + if in_callback && self.pending.is_some() { self.state.apply(PresentationAction::Resume)?; return Ok(Some(DisplayLinkDirective::None)); } @@ -1181,9 +1195,41 @@ impl PresentationDriver { .ok_or(SurfaceError::invariant(SurfaceOperation::Presentation))?; active.command_terminal = true; active.presentation_polls = 0; + drop(active.drawable.take()); Ok(None) } + // Frame-progress timer step: polls completion every tick, but counts a + // presentation poll and may fall back only when no display-link update + // arrived since the previous tick. It never acquires a drawable. + fn progress_without_display_link( + &mut self, + counters: &FrameCounters, + link_silent: bool, + ) -> DisplayLinkDirective { + let prior_link = self.state.display_link(); + let progressed = if link_silent { + self.reconcile_active_presentation(counters, false) + } else { + self.poll_active_command(counters) + }; + let resumed = progressed.and_then(|_| { + // A newer frame still waits for a display-link drawable. + if self.active.is_none() && self.pending.is_some() && self.state.needs_resume() { + self.state.apply(PresentationAction::Resume)?; + } + Ok(()) + }); + if let Err(error) = resumed { + return self.fail_after_error(error, AttemptTiming::default(), counters); + } + match (prior_link, self.state.display_link()) { + (DisplayLinkState::Paused, DisplayLinkState::Running) => DisplayLinkDirective::Resume, + (DisplayLinkState::Running, DisplayLinkState::Paused) => DisplayLinkDirective::Pause, + _ => DisplayLinkDirective::None, + } + } + fn submit_pending( &mut self, update: &CAMetalDisplayLinkUpdate, @@ -1246,7 +1292,7 @@ impl PresentationDriver { token, lease, submission, - drawable, + drawable: Some(drawable), frame: Some(frame), observation: PresentationObservation::new(presentation), command_terminal: false, @@ -2866,6 +2912,45 @@ struct DisplayLinkDelegateIvars { active_frame_observer: RefCell>>, #[cfg(alpine_native_validation)] validation_probe: Option, + display_link_updates: Cell, + frame_progress_seen_updates: Cell, + frame_progress_timer: Cell>, + display_link_invalidated: Cell, + native_close_finished: Cell, + #[cfg(alpine_native_validation)] + display_link_silence: Cell, + #[cfg(alpine_native_validation)] + frame_progress: FrameProgressCounters, +} + +// One display turn of a 30 Hz link is 33.3 ms. A live link therefore updates +// between two ticks, and only a silent one lets the timer count presentation +// polls. A silent frame still reaches a terminal state within three ticks. +const FRAME_PROGRESS_INTERVAL: Duration = Duration::from_millis(40); +const FRAME_PROGRESS_TOLERANCE: Duration = Duration::from_millis(4); + +// Owns the scheduled frame-progress timer; releasing it invalidates the timer. +struct FrameProgressTimer(Retained); + +impl Drop for FrameProgressTimer { + fn drop(&mut self) { + self.0.invalidate(); + } +} + +#[cfg(alpine_native_validation)] +#[derive(Default)] +struct FrameProgressCounters { + silenced_updates: Cell, + schedules: Cell, + ticks: Cell, + terminals: Cell, + close_drains: Cell, +} + +#[cfg(alpine_native_validation)] +fn increment_cell(cell: &Cell) { + cell.set(cell.get().saturating_add(1)); } #[cfg(alpine_native_validation)] @@ -3022,6 +3107,10 @@ define_class!( link: &CAMetalDisplayLink, update: &CAMetalDisplayLinkUpdate, ) { + #[cfg(alpine_native_validation)] + if self.display_link_update_silenced() { + return; + } let lifecycle = self.ivars().lifecycle.load(Ordering::Acquire); if lifecycle == SURFACE_LIVE { if !admit_callback( @@ -3048,6 +3137,7 @@ define_class!( (DisplayLinkDirective::Pause, DisplayLinkState::Paused) }, |mut driver| { + self.record_display_link_update(); let directive = if lifecycle == SURFACE_CLOSING { driver.drain_shutdown(&self.ivars().counters) } else { @@ -3069,31 +3159,17 @@ define_class!( if lifecycle == SURFACE_CLOSING && matches!(directive, DisplayLinkDirective::Invalidate) { - link.setPaused(true); - stop_event_loop(&self.ivars().application); + self.finish_native_close(); } else { - apply_display_link_directive(link, directive); + self.apply_link_directive(directive); #[cfg(alpine_native_validation)] self.ivars() .pause_confirmation .last_native_paused_after .store(link.isPaused(), Ordering::Release); - if should_schedule_display_link_pause_confirmation( - directive, - display_link_state, - link.isPaused(), - ) && let Some(display_link) = &self.ivars().display_link - { - #[cfg(alpine_native_validation)] - schedule_display_link_pause_confirmation( - display_link, - driver, - Arc::clone(&self.ivars().pause_confirmation), - ); - #[cfg(not(alpine_native_validation))] - schedule_display_link_pause_confirmation(display_link, driver); - } + self.confirm_link_pause(directive, display_link_state, link.isPaused()); } + self.reconcile_frame_progress_timer(); #[cfg(alpine_native_validation)] if self.ivars().lifecycle.load(Ordering::Acquire) != SURFACE_LIVE && !self.ivars().window_close_started.load(Ordering::Acquire) @@ -3270,9 +3346,7 @@ impl DisplayLinkDelegate { .reject_configuration(error.clone()) .unwrap_or(DisplayLinkDirective::Pause) }); - if let Some(display_link) = &self.ivars().display_link { - apply_display_link_directive(display_link, directive); - } + self.apply_link_directive(directive); } result } @@ -3291,7 +3365,7 @@ impl DisplayLinkDelegate { SurfaceOperation::NativeConfiguration, )); } - let (Some(window), Some(view), Some(layer), Some(display_link), Some(driver)) = ( + let (Some(window), Some(view), Some(layer), Some(_), Some(driver)) = ( &self.ivars().window, &self.ivars().view, &self.ivars().layer, @@ -3308,7 +3382,7 @@ impl DisplayLinkDelegate { .try_borrow_mut() .map_err(|_| SurfaceError::owner_conflict(SurfaceOperation::NativeConfiguration))? .apply_configuration(configuration)?; - apply_display_link_directive(display_link, directive); + self.apply_link_directive(directive); let extent = crate::SurfaceExtent::new( configuration.logical_width, configuration.logical_height, @@ -3472,12 +3546,10 @@ impl DisplayLinkDelegate { .try_borrow_mut() .map_err(|_| SurfaceError::owner_conflict(operation))? .request_frame(scene, clear)?; - let display_link = self - .ivars() - .display_link - .as_ref() - .ok_or(SurfaceError::invariant(operation))?; - apply_display_link_directive(display_link, directive); + if self.ivars().display_link.is_none() { + return Err(SurfaceError::invariant(operation)); + } + self.apply_link_directive(directive); Ok(()) } @@ -3529,12 +3601,10 @@ impl DisplayLinkDelegate { .try_borrow_mut() .map_err(|_| SurfaceError::owner_conflict(SurfaceOperation::Input))? .request_frame_with_event(scene, clear, Some(event_timing))?; - let display_link = self - .ivars() - .display_link - .as_ref() - .ok_or(SurfaceError::invariant(SurfaceOperation::Input))?; - apply_display_link_directive(display_link, directive); + if self.ivars().display_link.is_none() { + return Err(SurfaceError::invariant(SurfaceOperation::Input)); + } + self.apply_link_directive(directive); } if let Some(write) = clipboard_write { @@ -3731,17 +3801,206 @@ impl DisplayLinkDelegate { } if drained { self.finish_native_close(); + } else { + // The link may never update again; the timer drains and finishes. + self.ensure_frame_progress_timer(); } } fn finish_native_close(&self) { + if self.ivars().native_close_finished.replace(true) { + return; + } + self.cancel_frame_progress_timer(); + self.invalidate_display_link(); if let Some(display_link) = &self.ivars().display_link { - display_link.setPaused(true); - display_link.invalidate(); display_link.setDelegate(None); } stop_event_loop(&self.ivars().application); } + + fn apply_link_directive(&self, directive: DisplayLinkDirective) { + let Some(display_link) = &self.ivars().display_link else { + return; + }; + match directive { + DisplayLinkDirective::None => {} + DisplayLinkDirective::Resume => display_link.setPaused(false), + DisplayLinkDirective::Pause => display_link.setPaused(true), + DisplayLinkDirective::Invalidate => self.invalidate_display_link(), + } + } + + // Idempotent, so the validation probe counts only a real invalidate(). + fn invalidate_display_link(&self) { + if self.ivars().display_link_invalidated.replace(true) { + return; + } + if let Some(display_link) = &self.ivars().display_link { + display_link.setPaused(true); + display_link.invalidate(); + #[cfg(alpine_native_validation)] + if let Some(probe) = &self.ivars().validation_probe { + probe.record_link_invalidation(); + } + } + } + + fn confirm_link_pause( + &self, + directive: DisplayLinkDirective, + display_link_state: DisplayLinkState, + native_paused: bool, + ) { + if !should_schedule_display_link_pause_confirmation( + directive, + display_link_state, + native_paused, + ) { + return; + } + let (Some(display_link), Some(driver)) = (&self.ivars().display_link, &self.ivars().driver) + else { + return; + }; + #[cfg(alpine_native_validation)] + schedule_display_link_pause_confirmation( + display_link, + driver, + Arc::clone(&self.ivars().pause_confirmation), + ); + #[cfg(not(alpine_native_validation))] + schedule_display_link_pause_confirmation(display_link, driver); + } + + fn record_display_link_update(&self) { + let updates = &self.ivars().display_link_updates; + updates.set(updates.get().wrapping_add(1)); + } + + fn reconcile_frame_progress_timer(&self) { + let Some(frame_in_flight) = self.ivars().driver.as_ref().and_then(|driver| { + driver + .try_borrow() + .ok() + .map(|driver| driver.active.is_some()) + }) else { + return; + }; + if frame_in_flight { + self.ensure_frame_progress_timer(); + } else { + self.cancel_frame_progress_timer(); + } + } + + fn ensure_frame_progress_timer(&self) { + let slot = &self.ivars().frame_progress_timer; + let current = slot.take(); + if current.as_ref().is_some_and(|timer| timer.0.isValid()) { + slot.set(current); + return; + } + drop(current); + self.ivars() + .frame_progress_seen_updates + .set(self.ivars().display_link_updates.get()); + let delegate = Weak::new(self); + let tick: RcBlock)> = + RcBlock::new(move |timer: NonNull| { + if let Some(delegate) = delegate.load() { + delegate.frame_progress_tick(); + } else { + // SAFETY: Foundation supplies a valid borrowed timer for + // the complete callback, and the reference does not escape. + unsafe { timer.as_ref() }.invalidate(); + } + }); + // SAFETY: The block captures only a weak main-thread delegate. + // Foundation copies it for the timer lifetime and passes a valid + // NSTimer on each call. + let timer = unsafe { + NSTimer::timerWithTimeInterval_repeats_block( + FRAME_PROGRESS_INTERVAL.as_secs_f64(), + true, + &tick, + ) + }; + timer.setTolerance(FRAME_PROGRESS_TOLERANCE.as_secs_f64()); + // SAFETY: The delegate is main-thread-only, so this registers on the + // main run loop; the common-mode identifier is a process constant. + unsafe { NSRunLoop::mainRunLoop().addTimer_forMode(&timer, NSRunLoopCommonModes) }; + slot.set(Some(FrameProgressTimer(timer))); + #[cfg(alpine_native_validation)] + increment_cell(&self.ivars().frame_progress.schedules); + } + + fn cancel_frame_progress_timer(&self) { + drop(self.ivars().frame_progress_timer.take()); + } + + fn frame_progress_tick(&self) { + #[cfg(alpine_native_validation)] + increment_cell(&self.ivars().frame_progress.ticks); + let updates = self.ivars().display_link_updates.get(); + let link_silent = self.ivars().frame_progress_seen_updates.replace(updates) == updates; + let Some(driver) = &self.ivars().driver else { + self.cancel_frame_progress_timer(); + return; + }; + let lifecycle = self.ivars().lifecycle.load(Ordering::Acquire); + if lifecycle == SURFACE_CLOSING { + let Ok(mut borrowed) = driver.try_borrow_mut() else { + return; + }; + let directive = borrowed.drain_shutdown(&self.ivars().counters); + drop(borrowed); + if matches!(directive, DisplayLinkDirective::Invalidate) { + #[cfg(alpine_native_validation)] + increment_cell(&self.ivars().frame_progress.close_drains); + self.finish_native_close(); + } + return; + } + if lifecycle != SURFACE_LIVE { + self.cancel_frame_progress_timer(); + return; + } + let Ok(mut borrowed) = driver.try_borrow_mut() else { + return; + }; + #[cfg(alpine_native_validation)] + let was_active = borrowed.active.is_some(); + let directive = borrowed.progress_without_display_link(&self.ivars().counters, link_silent); + let display_link_state = borrowed.display_link_state(); + let still_active = borrowed.active.is_some(); + drop(borrowed); + #[cfg(alpine_native_validation)] + if was_active && !still_active { + increment_cell(&self.ivars().frame_progress.terminals); + } + self.apply_link_directive(directive); + if let Some(display_link) = &self.ivars().display_link { + self.confirm_link_pause(directive, display_link_state, display_link.isPaused()); + } + if !still_active { + self.cancel_frame_progress_timer(); + } + } + + #[cfg(alpine_native_validation)] + fn display_link_update_silenced(&self) -> bool { + let silenced = self.ivars().display_link_silence.get() + && self.ivars().driver.as_ref().is_some_and(|driver| { + driver + .try_borrow() + .is_ok_and(|driver| driver.active.is_some()) + }); + if silenced { + increment_cell(&self.ivars().frame_progress.silenced_updates); + } + silenced + } } fn validate_clipboard_text_bytes(bytes: usize) -> Result<(), ClipboardError> { @@ -3843,18 +4102,6 @@ fn validation_screen_configuration( ) } -fn apply_display_link_directive(link: &CAMetalDisplayLink, directive: DisplayLinkDirective) { - match directive { - DisplayLinkDirective::None => {} - DisplayLinkDirective::Resume => link.setPaused(false), - DisplayLinkDirective::Pause => link.setPaused(true), - DisplayLinkDirective::Invalidate => { - link.setPaused(true); - link.invalidate(); - } - } -} - const fn should_confirm_display_link_pause(state: DisplayLinkState) -> bool { matches!(state, DisplayLinkState::Paused) } @@ -4432,6 +4679,15 @@ impl NativeSurface { active_frame_observer: RefCell::new(None), #[cfg(alpine_native_validation)] validation_probe: builder.validation_probe.clone(), + display_link_updates: Cell::new(0), + frame_progress_seen_updates: Cell::new(0), + frame_progress_timer: Cell::new(None), + display_link_invalidated: Cell::new(false), + native_close_finished: Cell::new(false), + #[cfg(alpine_native_validation)] + display_link_silence: Cell::new(false), + #[cfg(alpine_native_validation)] + frame_progress: FrameProgressCounters::default(), }, ); builder.delegate = Some(delegate); @@ -5147,7 +5403,7 @@ impl NativeSurface { .try_borrow_mut() .map_err(|_| SurfaceError::owner_conflict(SurfaceOperation::Presentation))? .request_frame(scene, clear)?; - apply_display_link_directive(&self.display_link, directive); + self.delegate.apply_link_directive(directive); Ok(revision) } @@ -5334,6 +5590,37 @@ impl NativeSurface { ) } + #[cfg(alpine_native_validation)] + pub(crate) fn inject_display_link_silence(&self, silenced: bool) { + self.delegate.ivars().display_link_silence.set(silenced); + } + + #[cfg(alpine_native_validation)] + pub(crate) fn frame_progress_evidence( + &self, + ) -> crate::native_validation::FrameProgressEvidence { + let ivars = self.delegate.ivars(); + let timer = ivars.frame_progress_timer.take(); + let armed = timer.as_ref().is_some_and(|timer| timer.0.isValid()); + ivars.frame_progress_timer.set(timer); + let counters = &ivars.frame_progress; + crate::native_validation::FrameProgressEvidence::new( + counters.silenced_updates.get(), + counters.schedules.get(), + counters.ticks.get(), + counters.terminals.get(), + counters.close_drains.get(), + armed, + ) + } + + #[cfg(alpine_native_validation)] + pub(crate) fn owner_evidence(&self) -> Option { + self.validation_probe + .as_ref() + .map(InitializationProbe::evidence) + } + #[allow( clippy::too_many_lines, reason = "the handle-free snapshot copies independent native evidence without abstraction" @@ -5571,7 +5858,7 @@ impl NativeSurface { .try_borrow_mut() .map_err(|_| SurfaceError::validation(SurfaceOperation::Validation))? .reject_configuration(error.clone())?; - apply_display_link_directive(&self.display_link, directive); + self.delegate.apply_link_directive(directive); return Err(error); } }; @@ -5581,7 +5868,7 @@ impl NativeSurface { .try_borrow_mut() .map_err(|_| SurfaceError::validation(SurfaceOperation::Validation))? .apply_configuration(configuration)?; - apply_display_link_directive(&self.display_link, directive); + self.delegate.apply_link_directive(directive); Ok(()) } @@ -5798,23 +6085,20 @@ impl Drop for NativeSurface { self.wake_bridge.revoke(); self.view.revoke_accessibility(); self.application.setDelegate(None); - let native_close_started = self.lifecycle.load(Ordering::Acquire) != SURFACE_LIVE; + self.delegate.cancel_frame_progress_timer(); let must_close_window = !self.window_close_started.load(Ordering::Acquire); - if !native_close_started { + if self.lifecycle.load(Ordering::Acquire) == SURFACE_LIVE { begin_close_observer_state(&self.lifecycle); - self.display_link.setPaused(true); - self.display_link.invalidate(); } + // A close whose drain never finished still owns a live link. This is a + // no-op after a finished close, so every path invalidates exactly once. + self.delegate.invalidate_display_link(); // A reentrant windowWillClose callback may be unable to borrow the // driver while it still revokes callback admission. Owner teardown is // therefore the final idempotent shutdown boundary in both paths. if let Ok(mut driver) = self.driver.try_borrow_mut() { driver.shutdown(&self.counters); } - #[cfg(alpine_native_validation)] - if let Some(probe) = &self.validation_probe { - probe.record_link_invalidation(); - } self.display_link.setDelegate(None); #[cfg(alpine_native_validation)] if let Some(probe) = &self.validation_probe { @@ -6421,6 +6705,13 @@ mod tests { Ok(()) } + #[test] + fn frame_progress_tick_outlasts_a_live_thirty_hertz_display_turn() { + let thirty_hertz_turn = Duration::from_micros(33_334); + assert!(FRAME_PROGRESS_INTERVAL > thirty_hertz_turn); + assert!(FRAME_PROGRESS_TOLERANCE * 10 <= FRAME_PROGRESS_INTERVAL); + } + #[test] fn missing_presentation_wait_is_post_command_bounded_and_latest_first() { assert!(should_wait_for_presentation_observation( diff --git a/crates/alpine-platform-macos/tests/native_lifecycle.rs b/crates/alpine-platform-macos/tests/native_lifecycle.rs index 01d770f8..3a521bc7 100644 --- a/crates/alpine-platform-macos/tests/native_lifecycle.rs +++ b/crates/alpine-platform-macos/tests/native_lifecycle.rs @@ -14,6 +14,7 @@ mod validation { io::Write, path::Path, process::{self, Command, ExitStatus}, + rc::Rc, thread, time::{Duration, Instant}, }; @@ -75,6 +76,7 @@ mod validation { const CHILD_BOOTSTRAP_TIMEOUT: Duration = Duration::from_secs(8); const MISSING_CLOSE_SCENARIO: &str = "missing-close-control"; const POST_COMMIT_CLOSE_SCENARIO: &str = "post-commit-close"; + const SILENT_CLOSE_SCENARIO: &str = "silent-close"; const RESIDENT_POLICY_SCENARIO: &str = "resident-policy-controls"; pub(super) fn run() -> TestResult { @@ -88,6 +90,7 @@ mod validation { validate_resident_policy_controls()?; validate_bounded_child(MISSING_CLOSE_SCENARIO, Duration::from_secs(2))?; validate_bounded_child(POST_COMMIT_CLOSE_SCENARIO, Duration::from_secs(8))?; + validate_bounded_child(SILENT_CLOSE_SCENARIO, Duration::from_secs(8))?; let hosted_direct = hosted_direct()?; let (scene, clear) = validation_scene()?; @@ -141,6 +144,10 @@ mod validation { let (scene, clear) = validation_scene()?; return validate_post_commit_close(scene, clear, hosted_direct()?); } + if scenario == OsStr::new(SILENT_CLOSE_SCENARIO) { + let (scene, clear) = validation_scene()?; + return validate_silent_close(scene, clear, hosted_direct()?); + } if scenario == OsStr::new(RESIDENT_POLICY_SCENARIO) { return validate_resident_policy_controls(); } @@ -266,6 +273,11 @@ mod validation { assert_eq!(after.current_retained_bytes(), 0); validate_bounded_accounting(after); assert!(after.display_link_paused()); + // The frame-progress timer exists only while a frame is in flight. + assert_eq!( + native_validation::frame_progress_evidence(&surface), + native_validation::FrameProgressEvidence::default() + ); assert_exact_teardown(native_validation::close_with_owner_evidence(surface)?); Ok(()) @@ -377,6 +389,71 @@ mod validation { Ok(()) } + fn validate_silent_close(scene: Scene, clear: LinearRgba, hosted_direct: bool) -> TestResult { + let descriptor = SurfaceDescriptor::new("Alpine silent close", 96.0, 64.0, 1.0)?; + let surface = Rc::new(native_validation::new_surface(&descriptor)?); + let observer = surface.observer(); + surface.show()?; + if hosted_direct || !surface.snapshot().is_presentation_visible() { + native_validation::inject_surface_configuration(&surface, 96.0, 64.0, 1.0, 0, true)?; + } + native_validation::inject_display_link_silence(&surface, true); + // Close from the callback that commits the frame: the close starts with + // the command in flight, and no later display-link update is delivered. + let closing = Rc::downgrade(&surface); + native_validation::set_active_frame_observer( + &surface, + Some(Box::new(move || { + if let Some(surface) = closing.upgrade() { + native_validation::close_window(&surface); + } + })), + )?; + assert_eq!(surface.request_frame(scene, clear)?.get(), 1); + signal_child_ready()?; + let timeout = native_validation::arm_run_timeout(&surface, Duration::from_secs(5)); + surface.run()?; + let progress = native_validation::frame_progress_evidence(&surface); + let owners = + native_validation::owner_evidence(&surface).ok_or("silent-close owner evidence")?; + assert!( + !timeout.expired(), + "a close with a frame in flight did not finish under display-link silence: progress={progress:?}, owners={owners:?}, completion={}, snapshot={:?}", + native_validation::completion_diagnostic(&surface), + surface.snapshot() + ); + timeout.cancel(); + + assert_eq!(observer.lifecycle(), SurfaceLifecycle::Closing); + assert_eq!(owners.link_invalidations(), 1, "{owners:?}"); + assert_eq!(owners.window_closes(), 1, "{owners:?}"); + assert_eq!(progress.timer_close_drains(), 1, "{progress:?}"); + assert!(!progress.timer_armed(), "{progress:?}"); + assert_eq!(surface.take_error()?, None); + let snapshot = surface.snapshot(); + let terminal = snapshot + .last_cancelled() + .ok_or("silent-close cancelled terminal evidence")?; + assert_eq!(terminal.attempt(), 1); + assert_eq!(terminal.requested_revision().get(), 1); + assert_eq!(terminal.outcome(), PresentationOutcome::Cancelled); + assert_eq!(terminal.submission_count(), 1); + assert_eq!(terminal.present_call_count(), 1); + assert_eq!(terminal.retained_bytes(), 0); + assert_eq!(snapshot.submission_count(), 1); + assert_eq!(snapshot.cancelled_count(), 1); + assert_eq!(snapshot.occupied_frame_slots(), 0); + assert_eq!(snapshot.submitted_frame_slots(), 0); + assert_eq!(snapshot.current_retained_bytes(), 0); + validate_bounded_accounting(snapshot); + assert!(snapshot.display_link_paused()); + + let surface = Rc::try_unwrap(surface).map_err(|_| "the close observer kept the surface")?; + assert_exact_teardown(native_validation::close_with_owner_evidence(surface)?); + assert_eq!(observer.lifecycle(), SurfaceLifecycle::Closed); + Ok(()) + } + fn collect_owner_soak() -> TestResult { let descriptor = SurfaceDescriptor::new("Alpine owner soak", 32.0, 24.0, 1.0)?; for _ in 0..QUALIFICATION_WARMUP_ITERATIONS { diff --git a/crates/alpine-platform-macos/tests/native_presentation.rs b/crates/alpine-platform-macos/tests/native_presentation.rs index 31300008..ec68bdb9 100644 --- a/crates/alpine-platform-macos/tests/native_presentation.rs +++ b/crates/alpine-platform-macos/tests/native_presentation.rs @@ -202,7 +202,10 @@ mod validation { assert!(snapshot.submitted_frame_slots() <= snapshot.occupied_frame_slots()); assert_eq!(snapshot.last_presented_time_bits(), 0); assert!(snapshot.failed_count() >= 1); - assert!(snapshot.callback_count() >= 2); + assert!( + terminal_polled_after_commit(surface, &snapshot), + "{snapshot:?}" + ); eprintln!( "hosted-direct evidence: the latest callback drawable was committed, directly presented, reported not presented by Core Animation, and released" ); @@ -220,11 +223,21 @@ mod validation { assert_eq!(snapshot.submitted_frame_slots(), 0); assert_ne!(snapshot.last_presented_time_bits(), 0); assert_eq!(snapshot.failed_count(), 0); - assert!(snapshot.callback_count() >= 2); + assert!( + terminal_polled_after_commit(surface, &snapshot), + "{snapshot:?}" + ); assert!(snapshot.display_link_paused()); Ok(Some(snapshot)) } + // The committing callback cannot observe its own terminal. A later + // display-link update or, once updates stop, the frame-progress timer does. + fn terminal_polled_after_commit(surface: &NativeSurface, snapshot: &SurfaceSnapshot) -> bool { + snapshot.callback_count() >= 2 + || native_validation::frame_progress_evidence(surface).timer_terminals() >= 1 + } + fn validate_failure_and_recovery( surface: &NativeSurface, first: &SurfaceSnapshot, diff --git a/crates/alpine-platform-macos/tests/native_recovery.rs b/crates/alpine-platform-macos/tests/native_recovery.rs index 812170d1..e1a8ae07 100644 --- a/crates/alpine-platform-macos/tests/native_recovery.rs +++ b/crates/alpine-platform-macos/tests/native_recovery.rs @@ -17,7 +17,8 @@ mod validation { use alpine_metal::{BackendState, RecoveryClassification, RenderError}; use alpine_platform::PresentationOutcome; use alpine_platform_macos::{ - NativeSurface, SurfaceDescriptor, SurfaceError, SurfaceSnapshot, native_validation, + CloseDisposition, NativeSurface, SurfaceDescriptor, SurfaceError, SurfaceEvent, + SurfaceFrame, SurfaceResponse, SurfaceSnapshot, SurfaceWakeAdmission, native_validation, }; use alpine_scene::{Primitive, Scene, SceneBuilder, SceneRevision}; use objc2::rc::autoreleasepool; @@ -40,10 +41,85 @@ mod validation { let (scene, clear) = validation_scene()?; validate_dropped_presentation(scene.clone(), clear, hosted_direct)?; validate_missing_presentation(scene.clone(), clear, hosted_direct)?; + validate_silent_display_link(scene.clone(), clear, hosted_direct)?; validate_supersession(scene.clone(), clear, hosted_direct)?; validate_device_loss(scene, clear, hosted_direct) } + fn validate_silent_display_link( + scene: Scene, + clear: LinearRgba, + hosted_direct: bool, + ) -> TestResult { + let descriptor = SurfaceDescriptor::new("Alpine silent display link", 96.0, 64.0, 1.0)?; + let surface = native_validation::new_surface(&descriptor)?; + let _backing_scale = prepare_visible_surface(&surface, hosted_direct)?; + let baseline = surface.snapshot(); + + // Only the missing-presentation fallback can end this frame: its + // presented handler is suppressed and, once it is in flight, no + // display-link update reaches the driver. + native_validation::inject_post_commit_omission(&surface); + native_validation::inject_display_link_silence(&surface, true); + let mut frame = Some(SurfaceFrame::new(scene, clear)); + assert_eq!(surface.waker().wake(), SurfaceWakeAdmission::Scheduled); + native_validation::run_until_frame_terminal_with_handler( + &surface, + Duration::from_secs(1), + move |event| match event { + SurfaceEvent::Wake { .. } => { + SurfaceResponse::new(frame.take(), None, CloseDisposition::NotRequested) + } + _ => SurfaceResponse::default(), + }, + )?; + native_validation::inject_display_link_silence(&surface, false); + + assert_eq!(surface.take_error()?, None); + let snapshot = surface.snapshot(); + let progress = native_validation::frame_progress_evidence(&surface); + let terminal = snapshot.last_terminal().ok_or_else(|| { + format!( + "silent display link left the frame in flight: progress={progress:?}, completion={}, snapshot={snapshot:?}", + native_validation::completion_diagnostic(&surface) + ) + })?; + assert_eq!(snapshot.occupied_frame_slots(), 0, "{snapshot:?}"); + assert_eq!(snapshot.submitted_frame_slots(), 0, "{snapshot:?}"); + assert!(snapshot.display_link_paused(), "{snapshot:?}"); + assert_eq!(terminal.outcome(), PresentationOutcome::Failed); + assert_eq!(terminal.submission_count(), 1); + assert_eq!(terminal.present_call_count(), 1); + assert!(terminal.eligible_at_commit()); + assert_eq!(terminal.observed_presentation_time_bits(), 0); + assert_eq!(terminal.retained_bytes(), 0); + assert_eq!(terminal.recovery(), None); + let latency = terminal + .latency() + .ok_or("silent display link lost event latency evidence")?; + assert!( + latency.event_to_gpu_terminal_observed_ns().is_some(), + "the fallback must record when the GPU terminal was observed: {terminal:?}" + ); + // AppKit configuration churn can requeue the frame for a second attempt + // that the one-shot omission does not cover; that attempt may report a + // zero-time (skipped) presentation instead of reaching the fallback. + let submissions = snapshot.submission_count() - baseline.submission_count(); + assert!(submissions >= 1, "{snapshot:?}"); + assert_eq!( + snapshot.failed_count() - baseline.failed_count(), + submissions, + "{snapshot:?}" + ); + assert!(snapshot.skipped_count() - baseline.skipped_count() < submissions); + // Updates are silenced while any attempt is in flight, so only the + // frame-progress timer can have recorded these terminals. + assert_eq!(progress.timer_terminals(), submissions, "{progress:?}"); + assert!(progress.timer_schedules() >= 1, "{progress:?}"); + assert!(!progress.timer_armed(), "{progress:?}"); + close_recovery_surface(surface, "silent display link") + } + fn validate_dropped_presentation( scene: Scene, clear: LinearRgba, From ae4b9e113ed8fe827afec244bf389cd3f35b1dfb Mon Sep 17 00:00:00 2001 From: dbuddha Date: Fri, 2 Oct 2026 03:42:05 -0700 Subject: [PATCH 2/6] test(editor): drop the hosted command-stall retry and keep omission errors whole The retry masked the #622 stall. Omission errors now keep 8 KiB so the native completion diagnostic survives. --- apps/alpine-editor/src/lib.rs | 6 +- .../accessibility_process.rs | 91 +------------------ apps/alpine-editor/tests/native_process.rs | 32 +------ 3 files changed, 7 insertions(+), 122 deletions(-) diff --git a/apps/alpine-editor/src/lib.rs b/apps/alpine-editor/src/lib.rs index 1819b082..ba03dfee 100644 --- a/apps/alpine-editor/src/lib.rs +++ b/apps/alpine-editor/src/lib.rs @@ -8845,9 +8845,9 @@ pub mod native_validation { mod accessibility_process; pub use accessibility_process::{ - NativeEditorAccessibilityEvidence, hosted_terminal_stall_retry_allowed, - qualify_editor_accessibility_process, validate_native_accessibility_omission_failure, - validate_native_language_startup_prefix, validate_native_language_startup_trace, + NativeEditorAccessibilityEvidence, qualify_editor_accessibility_process, + validate_native_accessibility_omission_failure, validate_native_language_startup_prefix, + validate_native_language_startup_trace, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/apps/alpine-editor/src/native_validation/accessibility_process.rs b/apps/alpine-editor/src/native_validation/accessibility_process.rs index 906f0e6b..e2ce3384 100644 --- a/apps/alpine-editor/src/native_validation/accessibility_process.rs +++ b/apps/alpine-editor/src/native_validation/accessibility_process.rs @@ -33,7 +33,9 @@ const FRAME_TERMINAL_POLL: Duration = Duration::from_millis(100); const DIAGNOSTIC_READY_TIMEOUT: Duration = Duration::from_secs(10); const DIAGNOSTIC_READY_POLL: Duration = Duration::from_millis(5); const MAX_LANGUAGE_TRACE_BYTES: u64 = 4_096; -const MAX_OMISSION_ERROR_BYTES: usize = 512; +// A frame-terminal timeout with both snapshots and the native completion probe +// measured about 2.7 KB on hosted CI; keep it whole with room to spare. +const MAX_OMISSION_ERROR_BYTES: usize = 8_192; const REQUIRED_LANGUAGE_PHASES: [&str; 8] = [ "qualification-child", "wrapper-invoked", @@ -929,31 +931,6 @@ fn should_arm_hosted_observation( && armed_at_submission != Some(submission_count) } -/// Returns whether one failed hosted child is the exact retryable command stall. -/// -/// The retry belongs to the outer process harness. It never changes frame -/// ownership, the correctness deadline, physical evidence, or terminal state. -#[must_use] -pub fn hosted_terminal_stall_retry_allowed( - evidence_mode: &str, - attempt: u8, - status_succeeded: bool, - stdout: &str, - stderr: &str, - language_trace_complete: bool, -) -> bool { - evidence_mode == "hosted-direct" - && attempt == 0 - && !status_succeeded - && stdout.is_empty() - && language_trace_complete - && stderr.contains("dirty-close native frame failed") - && stderr.contains("frame-terminal correctness-timeout failed after 1 observed submissions") - && stderr - .contains("frame ownership did not become terminal before the correctness deadline") - && stderr.contains("current=(occupied=1 submitted=1 paused=false") -} - const fn action_frame_bound_exceeded(frames: u64) -> bool { frames > 1 } @@ -2120,68 +2097,6 @@ mod process_contract_tests { )); } - #[test] - fn hosted_terminal_retry_requires_every_exact_stall_fact() { - let stall = "dirty-close native frame failed: frame-terminal correctness-timeout failed after 1 observed submissions: frame ownership did not become terminal before the correctness deadline; current=(occupied=1 submitted=1 paused=false submissions=19)"; - assert!(hosted_terminal_stall_retry_allowed( - "hosted-direct", - 0, - false, - "", - stall, - true - )); - assert!(!hosted_terminal_stall_retry_allowed( - "physical", 0, false, "", stall, true - )); - assert!(!hosted_terminal_stall_retry_allowed( - "hosted-direct", - 1, - false, - "", - stall, - true - )); - assert!(!hosted_terminal_stall_retry_allowed( - "hosted-direct", - 0, - true, - "", - stall, - true - )); - assert!(!hosted_terminal_stall_retry_allowed( - "hosted-direct", - 0, - false, - "unexpected output", - stall, - true - )); - assert!(!hosted_terminal_stall_retry_allowed( - "hosted-direct", - 0, - false, - "", - stall, - false - )); - for non_stall in [ - stall.replace("dirty-close", "initial"), - stall.replace("correctness-timeout", "event-loop"), - stall.replace("occupied=1", "occupied=0"), - ] { - assert!(!hosted_terminal_stall_retry_allowed( - "hosted-direct", - 0, - false, - "", - &non_stall, - true - )); - } - } - #[test] fn omission_failure_requires_the_exact_named_step_and_bounds_diagnostics() { for step in [ diff --git a/apps/alpine-editor/tests/native_process.rs b/apps/alpine-editor/tests/native_process.rs index 15ce6ec2..a1169da2 100644 --- a/apps/alpine-editor/tests/native_process.rs +++ b/apps/alpine-editor/tests/native_process.rs @@ -160,37 +160,7 @@ fn qualify_accessibility_child() -> Result<(), Box> { Ok::<_, Box>((status, stdout, stderr, trace)) }; - let evidence_mode = std::env::var("ALPINE_PRESENTATION_EVIDENCE_MODE") - .unwrap_or_else(|_| String::from("physical")); - let (first_status, first_stdout, first_stderr, first_trace) = - run_child(None, &root.join("home-normal"))?; - let first_trace_complete = - alpine_editor::native_validation::validate_native_language_startup_trace(&first_trace) - .is_ok(); - let (status, stdout, stderr, trace) = - if alpine_editor::native_validation::hosted_terminal_stall_retry_allowed( - &evidence_mode, - 0, - first_status.success(), - &first_stdout, - &first_stderr, - first_trace_complete, - ) { - eprintln!( - "alpine-hosted-native-command-stall-retry attempt=1 status={first_status} stderr={first_stderr:?} language_trace={first_trace:?}" - ); - let retry = run_child(None, &root.join("home-normal-retry"))?; - if !retry.0.success() { - return Err(format!( - "native Studio accessibility hosted retry failed; first=(status={first_status} stdout={first_stdout:?} stderr={first_stderr:?} language_trace={first_trace:?}) retry=(status={} stdout={:?} stderr={:?} language_trace={:?})", - retry.0, retry.1, retry.2, retry.3 - ) - .into()); - } - retry - } else { - (first_status, first_stdout, first_stderr, first_trace) - }; + let (status, stdout, stderr, trace) = run_child(None, &root.join("home-normal"))?; if !status.success() { return Err(format!( "native Studio accessibility child failed with {status}; stdout={stdout:?}; stderr={stderr:?}; language_trace={trace:?}" From fe529cd2b60d2788d556ac3873fbcba47f3da277 Mon Sep 17 00:00:00 2001 From: dbuddha Date: Fri, 2 Oct 2026 03:51:32 -0700 Subject: [PATCH 3/6] docs: record M0e.1 and relabel the drain-window flake next: re-scopes M0e.2 to drain diagnostics and #533 capture; the suspected windowWillClose defect is fixed here; the drain flake is not #622. --- AGENTS.md | 6 +++--- crates/AGENTS.md | 7 +++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 38436cc5..eedfda72 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ budgets: language_servers: reported per server, not gated milestones: - {id: M0, name: "reset: docs, CI, hygiene", status: done} - - {id: M0e, name: "fix hosted native flakes #533, #622", status: active} + - {id: M0e, name: "fix hosted native flakes", status: active} - {id: M1, name: "measurement: perf recorder and bench", status: "next, design approval pending"} - {id: M2, name: "presentation latency and real 120 Hz", status: planned} - {id: M3, name: "daily-use defects and durability", status: planned} @@ -38,8 +38,8 @@ milestones: - {id: M8, name: "real application and parity sweep, phase 5", status: planned} autonomy: "Deepak: agents may push branches, open PRs, merge, and delete their own merged PR branches, except ask_first" next: - - "M0e.1 #622 family: frames and close drains advance without display-link callbacks" - - "M0e.2 #533: crash stack from hosted CI, then fix what it shows" + - "M0e.1 #622: frames and closes finish without display-link callbacks" + - "M0e.2 drain-window flake and #533: pump diagnostics, CI crash capture, 2,000 hosted iterations, then fix what they show" - "M0e.3 require known-flaky-native after 10 clean hosted runs plus a 300-iteration native_wake run, then stop" ask_first: [dependency changes, destructive actions, milestone design kickoff, new subsystem or public API or relaxed invariant, unsafe boundary or allowlist change, license or copied-source change, weakening a CI gate or threshold, anything that costs money] --- diff --git a/crates/AGENTS.md b/crates/AGENTS.md index adfbe4db..975ae07d 100644 --- a/crates/AGENTS.md +++ b/crates/AGENTS.md @@ -3,10 +3,9 @@ scope: framework crates under crates/ parent: ../AGENTS.md updated: 2026-10-02 known_defects: - - "native_wake can SIGSEGV in teardown after close.armed on hosted runners (was #533); 0 of 25 locally" - - "an accessibility omission control in native_process can miss its 10 s frame deadline under hosted Metal validation (was #622)" - - "native_lifecycle missing-close drain can fail to run on hosted runners (drain.executed); listed under the #622 family, a re-run is allowed" - - "suspected: windowWillClose with work in flight pauses the display link without invalidate() (alpine-platform-macos/src/native.rs near 3070)" + - "native_wake can SIGSEGV in teardown after close.armed on hosted runners (was #533); none in 800 hosted iterations on 2026-10-02" + - "an accessibility omission control in native_process can miss its 10 s frame deadline under hosted Metal validation (was #622); M0e.1 fixes it, remove after 10 clean hosted runs" + - "run-loop drain markers can miss their 250 ms pump window on hosted runners (native_lifecycle missing-close, native_wake under NSZombie); not #622, cause unproven, a re-run is allowed" known_flaky_ci: "#533 and #622 run in the known-flaky-native job, which ci-pass does not require; fix next, then require it" --- From da2e14d4e7f133314b3b15e0bdeac0928601cd45 Mon Sep 17 00:00:00 2001 From: dbuddha Date: Fri, 2 Oct 2026 07:34:52 -0700 Subject: [PATCH 4/6] fix(macos): count link silence only after a quiet interval A tick pulled early by a delayed one no longer reads a live link as silent. Review fixes: 5 s recovery bound, timer cancelled on every close, hosted-only timer allowance in native_presentation, timer contract in crates/AGENTS.md. --- AGENTS.md | 1 - crates/AGENTS.md | 4 ++ crates/alpine-platform-macos/src/native.rs | 42 +++++++++++++++---- .../tests/native_presentation.rs | 17 +++++--- .../tests/native_recovery.rs | 2 +- 5 files changed, 50 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index eedfda72..9fa7825c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,6 @@ milestones: - {id: M8, name: "real application and parity sweep, phase 5", status: planned} autonomy: "Deepak: agents may push branches, open PRs, merge, and delete their own merged PR branches, except ask_first" next: - - "M0e.1 #622: frames and closes finish without display-link callbacks" - "M0e.2 drain-window flake and #533: pump diagnostics, CI crash capture, 2,000 hosted iterations, then fix what they show" - "M0e.3 require known-flaky-native after 10 clean hosted runs plus a 300-iteration native_wake run, then stop" ask_first: [dependency changes, destructive actions, milestone design kickoff, new subsystem or public API or relaxed invariant, unsafe boundary or allowlist change, license or copied-source change, weakening a CI gate or threshold, anything that costs money] diff --git a/crates/AGENTS.md b/crates/AGENTS.md index 975ae07d..aca29b61 100644 --- a/crates/AGENTS.md +++ b/crates/AGENTS.md @@ -34,6 +34,10 @@ budgets; this file owns how the framework keeps them. `waitUntilCompleted` outside offscreen readback, no `presentAtTime` with CAMetalDisplayLink, no fourth command buffer when the three slots are busy. - Presentation telemetry never owns slot release. +- In-flight frames and closes finish without display-link updates: a 40 ms + frame-progress timer, alive only while a frame is in flight, polls + completion, falls back once the link is silent and drains a close. + Drawables are released at GPU completion. - Each surface owns its revisions, epochs, display link and slots. One blocked or occluded surface must not stall another (panes, windows, later the terminal). diff --git a/crates/alpine-platform-macos/src/native.rs b/crates/alpine-platform-macos/src/native.rs index 36229d68..ae6233ea 100644 --- a/crates/alpine-platform-macos/src/native.rs +++ b/crates/alpine-platform-macos/src/native.rs @@ -2913,6 +2913,7 @@ struct DisplayLinkDelegateIvars { #[cfg(alpine_native_validation)] validation_probe: Option, display_link_updates: Cell, + last_display_link_update: Cell>, frame_progress_seen_updates: Cell, frame_progress_timer: Cell>, display_link_invalidated: Cell, @@ -2923,12 +2924,16 @@ struct DisplayLinkDelegateIvars { frame_progress: FrameProgressCounters, } -// One display turn of a 30 Hz link is 33.3 ms. A live link therefore updates -// between two ticks, and only a silent one lets the timer count presentation -// polls. A silent frame still reaches a terminal state within three ticks. +// A live 30 Hz link updates every 33.3 ms. A delayed tick pulls the next one +// early, so silence needs no update since the last tick and none for a full +// interval. A silent frame still ends within three ticks. const FRAME_PROGRESS_INTERVAL: Duration = Duration::from_millis(40); const FRAME_PROGRESS_TOLERANCE: Duration = Duration::from_millis(4); +fn link_silent_for_tick(no_update_since_tick: bool, since_update: Option) -> bool { + no_update_since_tick && since_update.is_none_or(|since| since >= FRAME_PROGRESS_INTERVAL) +} + // Owns the scheduled frame-progress timer; releasing it invalidates the timer. struct FrameProgressTimer(Retained); @@ -3808,10 +3813,10 @@ impl DisplayLinkDelegate { } fn finish_native_close(&self) { + self.cancel_frame_progress_timer(); if self.ivars().native_close_finished.replace(true) { return; } - self.cancel_frame_progress_timer(); self.invalidate_display_link(); if let Some(display_link) = &self.ivars().display_link { display_link.setDelegate(None); @@ -3876,6 +3881,9 @@ impl DisplayLinkDelegate { fn record_display_link_update(&self) { let updates = &self.ivars().display_link_updates; updates.set(updates.get().wrapping_add(1)); + self.ivars() + .last_display_link_update + .set(Some(Instant::now())); } fn reconcile_frame_progress_timer(&self) { @@ -3916,9 +3924,9 @@ impl DisplayLinkDelegate { unsafe { timer.as_ref() }.invalidate(); } }); - // SAFETY: The block captures only a weak main-thread delegate. - // Foundation copies it for the timer lifetime and passes a valid - // NSTimer on each call. + // SAFETY: objc2 asks for a sendable block and this one holds a non-Send + // Weak. That is sound because the timer is added only to the main run + // loop, so it fires and is invalidated on the main thread. let timer = unsafe { NSTimer::timerWithTimeInterval_repeats_block( FRAME_PROGRESS_INTERVAL.as_secs_f64(), @@ -3943,7 +3951,14 @@ impl DisplayLinkDelegate { #[cfg(alpine_native_validation)] increment_cell(&self.ivars().frame_progress.ticks); let updates = self.ivars().display_link_updates.get(); - let link_silent = self.ivars().frame_progress_seen_updates.replace(updates) == updates; + let no_update_since_tick = + self.ivars().frame_progress_seen_updates.replace(updates) == updates; + let since_update = self + .ivars() + .last_display_link_update + .get() + .map(|at| at.elapsed()); + let link_silent = link_silent_for_tick(no_update_since_tick, since_update); let Some(driver) = &self.ivars().driver else { self.cancel_frame_progress_timer(); return; @@ -4680,6 +4695,7 @@ impl NativeSurface { #[cfg(alpine_native_validation)] validation_probe: builder.validation_probe.clone(), display_link_updates: Cell::new(0), + last_display_link_update: Cell::new(None), frame_progress_seen_updates: Cell::new(0), frame_progress_timer: Cell::new(None), display_link_invalidated: Cell::new(false), @@ -6705,6 +6721,16 @@ mod tests { Ok(()) } + #[test] + fn frame_progress_counts_silence_only_after_a_quiet_interval() { + assert!(!link_silent_for_tick(false, None)); + assert!(!link_silent_for_tick(false, Some(FRAME_PROGRESS_INTERVAL))); + // A tick pulled early by a delayed one, 9 ms after a live update. + assert!(!link_silent_for_tick(true, Some(Duration::from_millis(9)))); + assert!(link_silent_for_tick(true, Some(FRAME_PROGRESS_INTERVAL))); + assert!(link_silent_for_tick(true, None)); + } + #[test] fn frame_progress_tick_outlasts_a_live_thirty_hertz_display_turn() { let thirty_hertz_turn = Duration::from_micros(33_334); diff --git a/crates/alpine-platform-macos/tests/native_presentation.rs b/crates/alpine-platform-macos/tests/native_presentation.rs index ec68bdb9..ec64f658 100644 --- a/crates/alpine-platform-macos/tests/native_presentation.rs +++ b/crates/alpine-platform-macos/tests/native_presentation.rs @@ -203,7 +203,7 @@ mod validation { assert_eq!(snapshot.last_presented_time_bits(), 0); assert!(snapshot.failed_count() >= 1); assert!( - terminal_polled_after_commit(surface, &snapshot), + terminal_polled_after_commit(surface, &snapshot, hosted_direct), "{snapshot:?}" ); eprintln!( @@ -224,18 +224,23 @@ mod validation { assert_ne!(snapshot.last_presented_time_bits(), 0); assert_eq!(snapshot.failed_count(), 0); assert!( - terminal_polled_after_commit(surface, &snapshot), + terminal_polled_after_commit(surface, &snapshot, hosted_direct), "{snapshot:?}" ); assert!(snapshot.display_link_paused()); Ok(Some(snapshot)) } - // The committing callback cannot observe its own terminal. A later - // display-link update or, once updates stop, the frame-progress timer does. - fn terminal_polled_after_commit(surface: &NativeSurface, snapshot: &SurfaceSnapshot) -> bool { + // The committing callback cannot observe its own terminal. A later update + // does; on hosted runners, where updates can stop, the timer may instead. + fn terminal_polled_after_commit( + surface: &NativeSurface, + snapshot: &SurfaceSnapshot, + hosted_direct: bool, + ) -> bool { snapshot.callback_count() >= 2 - || native_validation::frame_progress_evidence(surface).timer_terminals() >= 1 + || hosted_direct + && native_validation::frame_progress_evidence(surface).timer_terminals() >= 1 } fn validate_failure_and_recovery( diff --git a/crates/alpine-platform-macos/tests/native_recovery.rs b/crates/alpine-platform-macos/tests/native_recovery.rs index e1a8ae07..bfde6294 100644 --- a/crates/alpine-platform-macos/tests/native_recovery.rs +++ b/crates/alpine-platform-macos/tests/native_recovery.rs @@ -65,7 +65,7 @@ mod validation { assert_eq!(surface.waker().wake(), SurfaceWakeAdmission::Scheduled); native_validation::run_until_frame_terminal_with_handler( &surface, - Duration::from_secs(1), + Duration::from_secs(5), move |event| match event { SurfaceEvent::Wake { .. } => { SurfaceResponse::new(frame.take(), None, CloseDisposition::NotRequested) From 001f935429a6990e6c21524b8c80fe53fa349923 Mon Sep 17 00:00:00 2001 From: dbuddha Date: Fri, 2 Oct 2026 07:38:17 -0700 Subject: [PATCH 5/6] docs: record the #533 stack and the same-VM A/B result The crash is a QuartzCore display-change fault after invalidate() during window close, at the same rate on main and this branch. --- AGENTS.md | 2 +- crates/AGENTS.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9fa7825c..a1b14f81 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ milestones: - {id: M8, name: "real application and parity sweep, phase 5", status: planned} autonomy: "Deepak: agents may push branches, open PRs, merge, and delete their own merged PR branches, except ask_first" next: - - "M0e.2 drain-window flake and #533: pump diagnostics, CI crash capture, 2,000 hosted iterations, then fix what they show" + - "M0e.2 #533: fix the QuartzCore display-change race the A/B stacks show, then a 5,000-run hosted A/B; drain-window bound awaits Deepak" - "M0e.3 require known-flaky-native after 10 clean hosted runs plus a 300-iteration native_wake run, then stop" ask_first: [dependency changes, destructive actions, milestone design kickoff, new subsystem or public API or relaxed invariant, unsafe boundary or allowlist change, license or copied-source change, weakening a CI gate or threshold, anything that costs money] --- diff --git a/crates/AGENTS.md b/crates/AGENTS.md index aca29b61..dcd9772a 100644 --- a/crates/AGENTS.md +++ b/crates/AGENTS.md @@ -3,7 +3,7 @@ scope: framework crates under crates/ parent: ../AGENTS.md updated: 2026-10-02 known_defects: - - "native_wake can SIGSEGV in teardown after close.armed on hosted runners (was #533); none in 800 hosted iterations on 2026-10-02" + - "native_wake can SIGSEGV on hosted runners (was #533): during window close, after our invalidate(), QuartzCore +[CADisplayLink notifyDisplayChange:] faults at 0x20 on a dispatch thread; 3 of 2,400 runs, same rate on main and M0e.1 (same-VM A/B, 2026-10-02)" - "an accessibility omission control in native_process can miss its 10 s frame deadline under hosted Metal validation (was #622); M0e.1 fixes it, remove after 10 clean hosted runs" - "run-loop drain markers can miss their 250 ms pump window on hosted runners (native_lifecycle missing-close, native_wake under NSZombie); not #622, cause unproven, a re-run is allowed" known_flaky_ci: "#533 and #622 run in the known-flaky-native job, which ci-pass does not require; fix next, then require it" From ea22eed89cea6d838ee9e0233025523f9dff9f40 Mon Sep 17 00:00:00 2001 From: dbuddha Date: Fri, 2 Oct 2026 07:39:55 -0700 Subject: [PATCH 6/6] fix(macos): never arm the progress timer after close; map Invalid link Hardening from review: no timer once a close finished, and the timer path turns an invalid portable link into Invalidate like the callback path. --- crates/alpine-platform-macos/src/native.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/alpine-platform-macos/src/native.rs b/crates/alpine-platform-macos/src/native.rs index ae6233ea..3318c26d 100644 --- a/crates/alpine-platform-macos/src/native.rs +++ b/crates/alpine-platform-macos/src/native.rs @@ -1224,6 +1224,7 @@ impl PresentationDriver { return self.fail_after_error(error, AttemptTiming::default(), counters); } match (prior_link, self.state.display_link()) { + (_, DisplayLinkState::Invalid) => DisplayLinkDirective::Invalidate, (DisplayLinkState::Paused, DisplayLinkState::Running) => DisplayLinkDirective::Resume, (DisplayLinkState::Running, DisplayLinkState::Paused) => DisplayLinkDirective::Pause, _ => DisplayLinkDirective::None, @@ -3903,6 +3904,10 @@ impl DisplayLinkDelegate { } fn ensure_frame_progress_timer(&self) { + // A finished close has nothing left to progress; a timer would leak. + if self.ivars().native_close_finished.get() { + return; + } let slot = &self.ivars().frame_progress_timer; let current = slot.take(); if current.as_ref().is_some_and(|timer| timer.0.isValid()) {