fix(ui): kill the windowing recursion class — snapshot-sampled bands + crash-chain watchdog

Third and final hit of the 'Recursion detected' panic class
(i-slint-core properties.rs:583), this time crashing DiscoverBrowse on
startup view-restore (and crash-looping via persistence). Root cause
symbolized from the field backtrace: every .slint 'changed x =>'
compiles to a ChangeTracker whose watched expression evaluates
SYNCHRONOUSLY at component instantiation, and conditional/repeated
components instantiate from ensure_updated INSIDE whatever property
evaluation triggered them — so a windowing band that reads layout
results (viewport-y, flick.height, self.width, absolute-position) can
re-enter a property mid-evaluation. Timing-sensitive: needs the model
filling in the same pass that instantiates the grid, which startup
view-restore hits deterministically.

Class-kill, uniform on every windowed surface (owner mandate — no
survivor exceptions): band state is now plain properties written ONLY
by an 80ms sampler Timer (event-loop context, nothing on the property
stack) in the shared AlbumGrid, the horizontal Carousel and the search
grid. No changed handlers, no init-time reads; the ±1-viewport margin
absorbs the sampling cadence; consumers' declarative wiring unchanged
(inputs are polled, never observed — contract documented in-file).

Startup crash-chain watchdog ('perro policía'): a counter file armed
before risky init and cleared by the same liveness signals as the
renderer sentinel. One pre-liveness death -> next boot resets exactly
ui_prefs last_nav/last_view (the field-verified surgical bypass) with
a recovery toast; two -> additionally bypasses the session-persist
queue restore for that boot, and the exit save keeps the preserved
snapshot instead of clobbering it with the empty queue. Recovers this
incident and the #558 loop automatically. One msgid x8.

cc
This commit is contained in:
vicrodh committed 2026-07-08 13:43:50 -06:00
1 parent 11ed6c6dea
commit 671e2c4cb7
13 files changed
+272 -68

No files matched your search

@@ -4479,3 +4479,6 @@ msgid "On by default"
msgstr "Standardmäßig ein"
msgid "Off by default"
msgstr "Standardmäßig aus"
msgid "QBZ recovered from repeated startup crashes — some restored state was reset"
msgstr "QBZ hat sich von wiederholten Startabstürzen erholt — einige wiederhergestellte Zustände wurden zurückgesetzt"
@@ -248,3 +248,6 @@ msgstr "Off by default"
msgid "Remove album from collection"
msgstr "Remove album from collection"
msgid "QBZ recovered from repeated startup crashes — some restored state was reset"
msgstr "QBZ recovered from repeated startup crashes — some restored state was reset"
@@ -4509,3 +4509,6 @@ msgid "On by default"
msgstr "Activado de forma predeterminada"
msgid "Off by default"
msgstr "Desactivado de forma predeterminada"
msgid "QBZ recovered from repeated startup crashes — some restored state was reset"
msgstr "QBZ se recuperó de fallos repetidos al iniciar — se restableció parte del estado guardado"
@@ -4479,3 +4479,6 @@ msgid "On by default"
msgstr "Activé par défaut"
msgid "Off by default"
msgstr "Désactivé par défaut"
msgid "QBZ recovered from repeated startup crashes — some restored state was reset"
msgstr "QBZ s'est remis de plantages répétés au démarrage — une partie de l'état restauré a été réinitialisée"
@@ -4468,3 +4468,6 @@ msgid "On by default"
msgstr "デフォルトでオン"
msgid "Off by default"
msgstr "デフォルトでオフ"
msgid "QBZ recovered from repeated startup crashes — some restored state was reset"
msgstr "QBZ は起動時の連続クラッシュから復旧しました — 復元された状態の一部がリセットされました"
@@ -4491,3 +4491,6 @@ msgid "On by default"
msgstr "Standaard aan"
msgid "Off by default"
msgstr "Standaard uit"
msgid "QBZ recovered from repeated startup crashes — some restored state was reset"
msgstr "QBZ is hersteld van herhaalde crashes bij het opstarten — een deel van de herstelde staat is gereset"
@@ -4479,3 +4479,6 @@ msgid "On by default"
msgstr "Ligado por padrão"
msgid "Off by default"
msgstr "Desligado por padrão"
msgid "QBZ recovered from repeated startup crashes — some restored state was reset"
msgstr "O QBZ se recuperou de falhas repetidas na inicialização — parte do estado restaurado foi redefinida"
@@ -4492,3 +4492,6 @@ msgid "On by default"
msgstr "Включено по умолчанию"
msgid "Off by default"
msgstr "Выключено по умолчанию"
msgid "QBZ recovered from repeated startup crashes — some restored state was reset"
msgstr "QBZ восстановился после повторных сбоев при запуске — часть восстановленного состояния была сброшена"
@@ -28,6 +28,11 @@ component AlbumGrid inherits Rectangle {
// `visible-top`/`visible-height` arrive in the surrounding Flickable's
// CONTENT coordinates; `content-offset` is this grid's approximate y
// inside that content — small errors are absorbed by the margin.
//
// CONTRACT: these inputs are POLLED, never observed. The grid reads them
// only from its sampler Timer (see below); wiring them to live layout
// expressions (-flick.viewport-y / flick.height) is safe BECAUSE nothing
// here evaluates them from a binding or `changed` handler.
in property <bool> windowed: false;
in property <length> visible-top: 0px;
in property <length> visible-height: 0px;
@@ -47,17 +52,41 @@ component AlbumGrid inherits Rectangle {
? self.rows * root.card-height + Math.max(0, self.rows - 1) * root.card-gap
: 0px;
// Target band = visible rows ± one full viewport. Row-granular ints, so
// the `changed` handlers only fire when a row boundary is crossed (~every
// 270px of scroll), not per scrolled pixel.
// ------------------------------------------------------------------
// WINDOWING ENGINE — POST-LAYOUT SNAPSHOT SAMPLING. Read this before
// touching anything below; this is the THIRD hit of the "Recursion
// detected" panic class (i-slint-core properties.rs:583) and the sampler
// is the class-kill.
//
// The mechanism that crashes (field-hit 2026-07-07 on LL grouped via an
// absolute-position binding, and 2026-07-08 on DiscoverBrowse at startup
// view-restore when the album model filled): a `changed x => {}` handler
// compiles to a ChangeTracker whose watched expression is evaluated
// SYNCHRONOUSLY inside `user_init` at component instantiation — and a
// conditional/repeated component instantiates from `ensure_updated`,
// which runs INSIDE whatever property evaluation triggered it (a layout
// cache, a layout_info/preferred-height chain, the render pass). If the
// watched expression reads layout-RESULT properties (flick.viewport-y /
// flick.height / self.width / absolute-position), that read can land on
// a property that is mid-evaluation higher up the same stack → re-entry
// → panic. It is timing-sensitive: it needs the model to fill in the
// same pass that instantiates the grid (startup view-restore hits it
// deterministically; warm navigation usually mounts the grid empty
// first and survives).
//
// The kill: the band state below consists of PLAIN properties written
// ONLY by the sampler Timer. Timer callbacks run from the event loop
// with no property evaluation on the stack, so reading the live layout
// inputs there cannot re-enter anything. There are deliberately NO
// `changed` handlers and NO init-time reads of the inputs in this
// component. Do not "optimize" this back to reactive bindings.
// ------------------------------------------------------------------
property <length> row-stride: root.card-height + root.card-gap;
property <length> local-top: root.visible-top - root.content-offset;
property <int> target-first-row: root.windowed
? Math.max(0, Math.floor((root.local-top - root.visible-height) / root.row-stride))
: 0;
property <int> target-last-row: root.windowed
? Math.max(0, Math.floor((root.local-top + 2 * root.visible-height) / root.row-stride))
: 0;
// Snapshot band — plain values, sampler-written. The pre-seed [0, 3]
// keeps roughly the first viewport of cards mounted for the <=80ms
// between mount and the first tick (placeholder tiles cover the rest).
property <int> target-first-row: 0;
property <int> target-last-row: 3;
// Mounted band = target band + contract hysteresis. Expansion follows the
// target immediately (a card must be mounted before it can reach the
// visible area); contraction lags by `hysteresis-rows`, so a few-px
@@ -65,7 +94,10 @@ component AlbumGrid inherits Rectangle {
// cards on every direction change.
property <int> hysteresis-rows: 1;
property <int> first-window-row: 0;
property <int> last-window-row: 0;
property <int> last-window-row: 3;
// Last column count reported through window-changed (columns shift on
// resize, which re-keys the band's ITEM indices).
property <int> notified-columns: 0;
pure function desired-first-row() -> int {
if (root.target-first-row < root.first-window-row) {
return root.target-first-row;
@@ -92,30 +124,33 @@ component AlbumGrid inherits Rectangle {
root.notify-window();
}
}
changed target-first-row => { root.apply-window(); }
changed target-last-row => { root.apply-window(); }
// Column count changes on first layout and on window resize — the band's
// ITEM indices depend on it, so re-notify.
changed columns => { root.notify-window(); }
// Post-layout seed. Reading the target bindings from `init` would pull
// `absolute-position` (a grouped section's content-offset) while layout
// is still evaluating — the documented "Recursion detected" panic. A
// one-shot Timer a tick after mount is the sanctioned probe (same
// pattern as the modal focus timers); until it fires, the default [0,0]
// band keeps at most the first row mounted for one frame. The `changed`
// handlers run from the post-layout change queue, so they stay direct.
property <bool> seeded: false;
Timer {
interval: 16ms;
running: root.windowed && !root.seeded;
triggered => {
self.running = false;
root.seeded = true;
root.first-window-row = root.target-first-row;
root.last-window-row = root.target-last-row;
// The sampler: reads the live inputs (safe here — event-loop context),
// recomputes the target band, applies hysteresis, and notifies on
// change. ~12.5 Hz is enough: the band carries a full-viewport margin,
// so a fling would have to cross more than one viewport in 80ms to
// outrun it — and then the placeholder tiles (the designed fast-scroll
// fallback) cover until the next tick.
function sample-window() {
if (!root.windowed) {
return;
}
root.target-first-row = Math.max(0, Math.floor(
((root.visible-top - root.content-offset) - root.visible-height)
/ root.row-stride));
root.target-last-row = Math.max(0, Math.floor(
((root.visible-top - root.content-offset) + 2 * root.visible-height)
/ root.row-stride));
root.apply-window();
if (root.columns != root.notified-columns) {
root.notified-columns = root.columns;
root.notify-window();
}
}
Timer {
interval: 80ms;
running: root.windowed;
triggered => { root.sample-window(); }
}
function notify-window() {
if (root.windowed) {
root.window-changed(
+32 -18
View File
@@ -98,19 +98,21 @@ export component Carousel inherits VerticalLayout {
// dispatches artwork for the whole strip up front and it lands on the
// model, so a card mounting later picks its cover up instantly.
// The strip starts at x=0 inside the Flickable's content (no leading
// padding), so local-left is just the negated viewport-x.
// Target band = visible columns ± one full viewport. Column-granular
// ints, so the `changed` handlers only fire when a column boundary is
// crossed (~every 232px of scroll), not per scrolled pixel — and a page
// jump from the nav buttons is just a big boundary crossing.
// padding), so the local left edge is just the negated viewport-x.
//
// POST-LAYOUT SNAPSHOT SAMPLING — same discipline as AlbumGrid in
// AlbumCollectionView.slint (read the long comment there; third hit of
// the "Recursion detected" class). The band state is PLAIN properties
// written only by the sampler Timer: `changed` handlers and init-time
// reads of flick.viewport-x / flick.width are forbidden here because
// carousels instantiate from `ensure_updated` inside layout/render
// property evaluation, where such reads can re-enter a mid-flight
// property and panic. Do not wire these back to reactive bindings.
property <length> col-stride: root.card-width + root.gap;
property <length> local-left: -flick.viewport-x;
property <int> target-first-col: Math.max(
0,
Math.floor((root.local-left - flick.width) / root.col-stride));
property <int> target-last-col: Math.max(
0,
Math.floor((root.local-left + 2 * flick.width) / root.col-stride));
// Pre-seed [0, 6]: roughly one viewport of cards mounted for the <=80ms
// between mount and the first sampler tick.
property <int> target-first-col: 0;
property <int> target-last-col: 6;
// Mounted band = target band + contract hysteresis. Expansion follows
// the target immediately (a card must be mounted before it can reach the
// visible area); contraction lags by `hysteresis-cols`, so a few-px
@@ -118,7 +120,7 @@ export component Carousel inherits VerticalLayout {
// every direction change.
property <int> hysteresis-cols: 1;
property <int> first-window-col: 0;
property <int> last-window-col: 0;
property <int> last-window-col: 6;
pure function desired-first-col() -> int {
if (root.target-first-col < root.first-window-col) {
return root.target-first-col;
@@ -144,11 +146,23 @@ export component Carousel inherits VerticalLayout {
root.last-window-col = root.desired-last-col();
}
}
changed target-first-col => { root.apply-window(); }
changed target-last-col => { root.apply-window(); }
init => {
root.first-window-col = root.target-first-col;
root.last-window-col = root.target-last-col;
// The sampler: reads viewport-x / width live (safe — event-loop
// context), recomputes the target band, applies hysteresis. The
// one-viewport margin absorbs the 80ms cadence; a page jump from the
// nav buttons shows placeholder slots for at most one tick.
function sample-window() {
root.target-first-col = Math.max(
0,
Math.floor((-flick.viewport-x - flick.width) / root.col-stride));
root.target-last-col = Math.max(
0,
Math.floor((-flick.viewport-x + 2 * flick.width) / root.col-stride));
root.apply-window();
}
Timer {
interval: 80ms;
running: root.count > 0;
triggered => { root.sample-window(); }
}
spacing: 12px;
+34 -16
View File
@@ -208,17 +208,21 @@ component AlbumGrid inherits Rectangle {
? root.row-count * root.card-h + (root.row-count - 1) * root.gap
: 0px;
// Target band = visible rows ± one full viewport. Row-granular ints, so
// the `changed` handlers only fire when a row boundary is crossed, not
// per scrolled pixel.
// POST-LAYOUT SNAPSHOT SAMPLING — same discipline as the shared
// AlbumGrid in AlbumCollectionView.slint (read the long comment there;
// third hit of the "Recursion detected" class). Band state is PLAIN
// properties written only by the sampler Timer below: `changed`
// handlers and init-time reads of the windowing inputs are forbidden
// here because this grid instantiates from `ensure_updated` inside
// layout/render property evaluation, where reading layout results
// (visible-top <- -flick.viewport-y, visible-height <- flick.height)
// can re-enter a mid-flight property and panic. Do not wire these back
// to reactive bindings.
property <length> row-stride: root.card-h + root.gap;
property <length> local-top: root.visible-top - root.content-offset;
property <int> target-first-row: root.windowed
? Math.max(0, Math.floor((root.local-top - root.visible-height) / root.row-stride))
: 0;
property <int> target-last-row: root.windowed
? Math.max(0, Math.floor((root.local-top + 2 * root.visible-height) / root.row-stride))
: 0;
// Pre-seed [0, 3]: roughly one viewport of cards mounted for the <=80ms
// between mount and the first sampler tick.
property <int> target-first-row: 0;
property <int> target-last-row: 3;
// Mounted band = target band + contract hysteresis. Expansion follows the
// target immediately (a card must be mounted before it can reach the
// visible area); contraction lags by `hysteresis-rows`, so a few-px
@@ -226,7 +230,7 @@ component AlbumGrid inherits Rectangle {
// cards on every direction change.
property <int> hysteresis-rows: 1;
property <int> first-window-row: 0;
property <int> last-window-row: 0;
property <int> last-window-row: 3;
pure function desired-first-row() -> int {
if (root.target-first-row < root.first-window-row) {
return root.target-first-row;
@@ -252,11 +256,25 @@ component AlbumGrid inherits Rectangle {
root.last-window-row = root.desired-last-row();
}
}
changed target-first-row => { root.apply-window(); }
changed target-last-row => { root.apply-window(); }
init => {
root.first-window-row = root.target-first-row;
root.last-window-row = root.target-last-row;
// The sampler: reads the live inputs (safe here — event-loop context),
// recomputes the target band, applies hysteresis. The one-viewport
// margin absorbs the 80ms cadence.
function sample-window() {
if (!root.windowed) {
return;
}
root.target-first-row = Math.max(0, Math.floor(
((root.visible-top - root.content-offset) - root.visible-height)
/ root.row-stride));
root.target-last-row = Math.max(0, Math.floor(
((root.visible-top - root.content-offset) + 2 * root.visible-height)
/ root.row-stride));
root.apply-window();
}
Timer {
interval: 80ms;
running: root.windowed;
triggered => { root.sample-window(); }
}
for album[i] in root.albums: card-slot := Rectangle {
+104 -2
View File
@@ -443,7 +443,12 @@ async fn enter_shell(
// refresh its metadata explicitly. No audio is loaded — playback stays
// stopped until the user hits play (Phase B then seeks to the saved
// position when `resume_playback_position` is on).
if session_persist::restore(&runtime).await {
if crash_chain_level() >= 3 {
// Crash-chain level >=3: two consecutive starts died even after the
// view-restore reset — bypass the queue restore for THIS boot only
// (the persisted queue stays on disk; a healthy boot restores it).
log::warn!("[crash-chain] session-persist queue restore bypassed this boot");
} else if session_persist::restore(&runtime).await {
playback::refresh_now_playing_meta(&runtime, &weak).await;
// Repaint the queue sidebar/list — set_queue_with_order emits
// QueueUpdated, but the queue UI repaints from explicit refreshes.
@@ -479,7 +484,21 @@ async fn enter_shell(
// — which loads the view's data, NOT a blank set_view (the Tauri precedent).
{
let prefs = crate::ui_prefs::load();
if prefs.startup_page == "remember" {
// Crash-chain gate: at level >=2 the persisted view restore was
// already reset by `arm_startup_probe` (last_nav "{}" / last_view
// "home"), so there is nothing valid to restore — skip the block
// explicitly, tell the user what happened, and stay on Home.
if crash_chain_level() >= 2 {
log::warn!("[crash-chain] persisted view restore skipped (recovery)");
let _ = weak.upgrade_in_event_loop(|w| {
crate::toast::info(
&w,
qbz_i18n::t(
"QBZ recovered from repeated startup crashes — some restored state was reset",
),
);
});
} else if prefs.startup_page == "remember" {
// Legacy top-level fallback (id-free surfaces) — the only thing that
// can be restored offline (these load from local/offline data).
let legacy = |key: &str| match key {
@@ -5711,6 +5730,79 @@ fn renderer_sentinel_armed() -> bool {
renderer_sentinel_path().map(|p| p.exists()).unwrap_or(false)
}
/// Startup crash-chain watchdog — the renderer-sentinel pattern generalized
/// to the whole startup path (incident 2026-07-08: a "Recursion detected"
/// render panic inside the RESTORED view fired before first input, so every
/// start re-restored the crashing view and died — a crash-loop the renderer
/// ladder could not see). A counter file is incremented at every launch
/// BEFORE risky init and cleared by the same liveness proof that disarms
/// the renderer sentinel; the value it had already reached at launch is the
/// number of consecutive starts that died before liveness.
///
/// Recovery ladder (surgical: state is reset or bypassed, never deleted):
/// - level 2 (one prior start died): reset the persisted view restore —
/// `last_nav` -> "{}", `last_view` -> "home" — so this and future boots
/// start on Home.
/// - level >=3: additionally BYPASS the session-persist queue restore for
/// this boot only (the persisted queue file is kept untouched).
fn startup_probe_path() -> Option<std::path::PathBuf> {
Some(dirs::data_dir()?.join("qbz").join("startup_probe"))
}
/// This boot's crash-chain level (1 = clean previous shutdown/liveness).
static CRASH_CHAIN_LEVEL: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
fn crash_chain_level() -> u8 {
CRASH_CHAIN_LEVEL.load(std::sync::atomic::Ordering::Relaxed)
}
fn arm_startup_probe() {
let Some(path) = startup_probe_path() else { return };
let prev: u8 = std::fs::read_to_string(&path)
.ok()
.and_then(|s| s.trim().parse().ok())
.unwrap_or(0);
let level = prev.saturating_add(1);
CRASH_CHAIN_LEVEL.store(level, std::sync::atomic::Ordering::Relaxed);
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Err(e) = std::fs::write(&path, level.to_string()) {
log::warn!("[crash-chain] could not arm the startup probe: {e}");
}
if level < 2 {
return;
}
log::warn!(
"[crash-chain] {} consecutive start(s) died before liveness — recovery level {level}",
level - 1
);
// Level 2: the persisted view restore is the prime suspect — reset it so
// the app starts on Home. This edits exactly last_nav/last_view; nothing
// else in ui_prefs is touched.
let mut prefs = crate::ui_prefs::load();
if prefs.last_nav.as_deref() != Some("{}") || prefs.last_view != "home" {
prefs.last_nav = Some("{}".to_string());
prefs.last_view = "home".to_string();
crate::ui_prefs::save(&prefs);
log::warn!(
"[crash-chain] reset persisted view restore: last_nav -> {{}}, last_view -> home"
);
}
if level >= 3 {
log::warn!(
"[crash-chain] level {level} — the session-persist queue restore will be \
bypassed this boot (queue data kept on disk)"
);
}
}
fn clear_startup_probe() {
if let Some(path) = startup_probe_path() {
let _ = std::fs::remove_file(path);
}
}
/// Disarm the sentinel on proof of LIVENESS: the first real user input (or
/// a close request — a crash never emits one), with a 30s timer as the
/// no-touch fallback. Once-guarded so the hot input path costs one relaxed
@@ -5720,6 +5812,9 @@ fn disarm_renderer_sentinel_on_liveness(signal: &str) {
if !DISARMED.swap(true, std::sync::atomic::Ordering::Relaxed) {
log::info!("[renderer] startup sentinel disarmed ({signal})");
clear_renderer_sentinel();
// Same liveness proof clears the startup crash-chain probe.
clear_startup_probe();
log::info!("[crash-chain] startup probe cleared ({signal})");
// The surviving rung must OUTLIVE the process: when this session ran
// on the ALTERNATE wgpu adapter, version-stamp that success so the
// next start arms the alt rung directly — otherwise the rung-2 win
@@ -6389,6 +6484,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
return Ok(());
}
// STARTUP CRASH-CHAIN WATCHDOG — armed after the single-instance guard
// (a raise-and-exit must not count as a crash) and BEFORE any risky init
// (renderer probing, window creation, view restore). Cleared by the same
// liveness proof that disarms the renderer sentinel. See
// `arm_startup_probe` for the recovery ladder.
arm_startup_probe();
// RENDERER SELECTION — pick wgpu (GPU) vs femtovg GL vs Slint's software
// renderer BEFORE the first window is created. All three use the winit backend,
// so the tray/miniplayer WinitWindowAccessor stays valid either way.
+11
View File
@@ -206,6 +206,17 @@ pub async fn capture_and_save(runtime: &Runtime) {
return;
}
let (tracks, current_index) = runtime.core().get_all_queue_tracks().await;
// Crash-chain level >=3 bypassed the restore this boot, so the queue on
// disk is the GOOD copy the user wants back on a healthy start — don't
// clobber it with this session's empty queue at exit. A queue the user
// actually built during the recovered boot still saves normally.
if tracks.is_empty() && crate::crash_chain_level() >= 3 {
log::info!(
"[qbz-slint] session_persist: crash-chain recovery boot with empty queue — \
keeping the preserved snapshot on disk"
);
return;
}
let full = runtime.core().get_queue_state_full().await;
let pb = runtime.core().get_playback_state();
let snapshot = PersistedSessionSnapshot {