feat(qt): instant cached cortinilla paint (default on, ui_prefs opt-out)

The reference shows a skeleton while loading and never paints cached rows
first, and its comments present that as the design. It is not: the instant
paint existed during development and was removed because it GLITCHED -
results visibly jumped between the cached paint and the fresh one. The
owner's reading is that the glitch was a Slint rendering problem rather than
something inherent to stale-while-revalidate, so it comes back here as a
reversible experiment: DEFAULT ON, with a ui_prefs opt-out
(cortinilla_instant_paint) that needs no rebuild to flip. The skeleton path
stays fully implemented as both the opt-out target and the cold-miss path.

What is cached is the FINISHED payload, not the API response. Reviving the
existing CAPA A result cache would have left the expensive half on the table:
a cortinilla payload is the response AFTER ranking, truncation, i18n titles,
the top-result pick and - the part no API cache can shortcut - the local
library query and its derived grouping.

qbz-app gains a generic PayloadCache<T>. The store never inspects T, which is
what lets both frontends share it despite their payload types having diverged
(one raw artwork_url vs an art_url/art_path pair). In-memory only: process
lifetime IS the TTL, because a payload embeds local rows and resolved artwork
paths and a persisted entry would resurrect albums the user has deleted.

Four properties are what should keep it from glitching, and each is a real
constraint rather than a hope:

  - Same shape in both paints. The entry is written AFTER the local sections
    are appended, so there is no mid-apply reflow left to see.
  - Equality-gated replacement. CortinillaData derives PartialEq, so an
    unchanged repeat query produces ZERO second paint.
  - The selection survives - the publish path never writes selectedIndex.
  - The scroll survives - C5's contentY latch. Without it the second paint
    yanks the user to the top, which is the glitch by another name.

There are exactly TWO write points, and the placement is load-bearing: after
pass-1 artwork resolution, and again at the pass-2 republish once downloaded
covers land. Writing earlier caches rows with empty art_path, and since the
QML draws art_path only, a hit would paint cover-less rows AND the gate would
fire on every hit - the exact repaint this exists to avoid.

Invalidation: bound per session, dropped on logout, and cleared from
reload_browse - the single chokepoint every local-library mutation passes
through, since there is no library-changed signal to subscribe to.

Also fixes the immersive skeleton's scope bug, which is the twin of the one
C4b fixed on the desktop and which I missed there: a Timer derives from
QtObject, which has no parent property, so the unqualified parent resolved
out of the block entirely - the timer ran forever, pulse never changed, and
the skeleton never pulsed. Found by qmllint, not by reading. It picks up the
reduceMotion tick with the fix.

Contract: qbz-nix-docs/qt-frontend/2026-08-03-cortinilla-parity, commit C11
(section 5.c, rulings R1/R6, R7-10).

Gate: build clean, 258/258 tests + 2 new in qbz-app, both QML audits OK,
qmllint clean on both cortinillas, offscreen smoke 0 complaints + home
published.

cc
This commit is contained in:
vicrodh committed 2026-08-03 18:09:04 -06:00
1 parent 10f249be24
commit b38b0b3d57
9 files changed
+368 -18

No files matched your search

+1
View File
@@ -7,6 +7,7 @@ pub mod favorites;
pub mod favorites_cache;
pub mod graphics;
pub mod local_favorites;
pub mod payload_cache;
pub mod pinned_items;
pub mod playback;
pub mod plex;
@@ -0,0 +1,153 @@
//! A tiny in-memory, insertion-order LRU for FRONTEND-SHAPED payloads.
//!
//! ## Why this exists, when `search_cache` already does
//!
//! `search_cache` (CAPA A) caches `SearchAllResults` — the raw API shape. It
//! has never been read by anything: `SearchService::cached` has zero non-test
//! callers in either frontend, and `git log -S` shows the read side was never
//! wired in any commit. Reviving it would still leave the expensive half on
//! the table, because a cortinilla payload is not the API response: it is the
//! response after ranking, per-category truncation, i18n section titles, the
//! top-result pick and — the part no API cache can shortcut — the local
//! library query and its derived album/artist grouping.
//!
//! So this caches the FINISHED payload instead, and it is deliberately
//! generic: the store never inspects `T`. That matters, because the two
//! frontends' payload types have diverged (the Slint carries one raw
//! `artwork_url`, the Qt port an `art_url` / `art_path` pair) and unifying
//! them is a refactor neither needs in order to share this.
//!
//! ## Deliberately NOT persisted
//!
//! Process lifetime IS the TTL. A payload embeds local-library rows and
//! resolved artwork paths, so a persisted entry would resurrect albums the
//! user has since deleted and covers that have since moved. There is no
//! timestamp and no staleness rule, and that is the point: nothing here
//! outlives the process, so nothing can go stale across one.
//!
//! The caller is responsible for clearing on the events that invalidate
//! content within a session — a user switch, and any mutation of the local
//! library.
use std::collections::HashMap;
use std::collections::VecDeque;
use crate::settings::search_cache::normalize_query;
/// Default bound. Small on purpose: the value is "the user is refining a
/// query", and a refinement session is a handful of prefixes, not a history.
pub const DEFAULT_CAPACITY: usize = 20;
/// An insertion-order LRU keyed by the normalized query.
///
/// The key goes through [`normalize_query`] — the SAME function
/// `search_cache` and `search_ranking` use — so `" Pink Floyd "` and
/// `"pink floyd"` are one entry, here and in the ranking buckets alike.
pub struct PayloadCache<T> {
capacity: usize,
entries: HashMap<String, T>,
order: VecDeque<String>,
}
impl<T> PayloadCache<T> {
pub fn new(capacity: usize) -> Self {
Self {
capacity: capacity.max(1),
entries: HashMap::new(),
order: VecDeque::new(),
}
}
/// The cached payload for `query`, if any. Does NOT reorder — this is an
/// insertion-order bound, not a true recency LRU, matching `search_cache`.
pub fn get(&self, query: &str) -> Option<&T> {
self.entries.get(&normalize_query(query))
}
/// Insert or replace. Re-inserting an existing key keeps its original
/// position, so a repeatedly refreshed query cannot pin itself forever.
pub fn put(&mut self, query: &str, value: T) {
let key = normalize_query(query);
if self.entries.insert(key.clone(), value).is_none() {
self.order.push_back(key);
}
while self.order.len() > self.capacity {
if let Some(oldest) = self.order.pop_front() {
self.entries.remove(&oldest);
}
}
}
/// Drop everything. Called on a user switch, on teardown, and on any
/// local-library mutation.
pub fn clear(&mut self) {
self.entries.clear();
self.order.clear();
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl<T> Default for PayloadCache<T> {
fn default() -> Self {
Self::new(DEFAULT_CAPACITY)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A value type with NO `PartialEq`, NO `Clone` and NO `Serialize`, to
/// prove the store never inspects `T` — which is what lets both frontends
/// share it despite their payload types having diverged.
struct Opaque(#[allow(dead_code)] u32);
#[test]
fn payload_cache_bounds_normalizes_and_evicts() {
let mut c: PayloadCache<Opaque> = PayloadCache::new(3);
assert!(c.is_empty());
c.put("alpha", Opaque(1));
c.put("beta", Opaque(2));
assert_eq!(c.len(), 2);
assert!(c.get("alpha").is_some());
// The key is normalized: whitespace collapsed, trimmed, lowercased.
c.put(" Pink Floyd ", Opaque(3));
assert!(
c.get("pink floyd").is_some(),
"the normalized key must match"
);
assert_eq!(c.len(), 3);
// Past the bound the OLDEST goes, not the newest.
c.put("gamma", Opaque(4));
assert_eq!(c.len(), 3, "never grows past the capacity");
assert!(c.get("alpha").is_none(), "the oldest key was evicted");
assert!(c.get("gamma").is_some());
// Re-inserting an existing key must not push a second order entry, or
// a refreshed query would evict the cache one slot at a time.
c.put("gamma", Opaque(5));
assert_eq!(c.len(), 3);
assert_eq!(c.order.len(), 3, "no duplicate order entry");
c.clear();
assert!(c.is_empty());
assert!(c.get("gamma").is_none());
}
#[test]
fn payload_cache_capacity_is_never_zero() {
let mut c: PayloadCache<Opaque> = PayloadCache::new(0);
c.put("only", Opaque(1));
assert_eq!(c.len(), 1, "a zero capacity would make put() a no-op");
}
}
@@ -170,19 +170,29 @@ Item {
id: bodyColumn
width: bodyFlick.width
// --- Loading skeleton (4 rows; skeleton-only, no cached
// instant-paint — the desktop Cortinilla.qml:143-194 idiom,
// glass-white boxes like ImmersiveSkeletonRow) --------------
// --- Loading skeleton (4 rows, glass-white boxes like
// ImmersiveSkeletonRow). Skeleton-only HERE: the instant
// cached paint landed on the DESKTOP cortinilla only. The
// immersive dropdown is a different surface with a much
// smaller payload, so it was left out deliberately rather
// than forgotten. ------------------------------------------
Column {
id: immSkeleton
visible: QbzImmersive.immSearchLoading
width: parent.width
topPadding: 4
property bool pulse: false
// Referenced BY ID, not through `parent`. A Timer derives
// from QtObject, which has no `parent` property, so an
// unqualified `parent` here resolved up the scope chain
// and out of this block entirely — the timer ran forever
// and `pulse` never changed, so the skeleton never
// pulsed. Same fix as the desktop twin.
Timer {
interval: 700
running: parent.visible
interval: QbzShell.reduceMotion ? 2000 : 700
running: immSkeleton.visible
repeat: true
onTriggered: parent.pulse = !parent.pulse
onTriggered: immSkeleton.pulse = !immSkeleton.pulse
}
Repeater {
model: 4
@@ -196,7 +206,7 @@ Item {
height: 40
radius: 4
color: "#ffffff"
opacity: parent.parent.pulse ? 0.32 : 0.08
opacity: immSkeleton.pulse ? 0.32 : 0.08
Behavior on opacity { NumberAnimation { duration: 650; easing.type: Easing.InOutQuad } }
}
Column {
@@ -208,7 +218,7 @@ Item {
height: 11
radius: 3
color: "#ffffff"
opacity: parent.parent.parent.pulse ? 0.32 : 0.08
opacity: immSkeleton.pulse ? 0.32 : 0.08
Behavior on opacity { NumberAnimation { duration: 650; easing.type: Easing.InOutQuad } }
}
Rectangle {
@@ -216,7 +226,7 @@ Item {
height: 9
radius: 3
color: "#ffffff"
opacity: parent.parent.parent.pulse ? 0.32 : 0.08
opacity: immSkeleton.pulse ? 0.32 : 0.08
Behavior on opacity { NumberAnimation { duration: 650; easing.type: Easing.InOutQuad } }
}
}
+7 -2
View File
@@ -245,8 +245,13 @@ Item {
id: bodyColumn
width: bodyFlick.width
// --- Loading skeleton (no cached instant-paint — one clean
// apply, Cortinilla.slint) -------------------------------
// --- Loading skeleton --------------------------------
// Shown on a cache MISS. There IS a cached instant paint now
// (rulings R1/R6, default on, ui_prefs opt-out
// `cortinilla_instant_paint`): on a hit the controller sends
// the cached rows and loading=false together, so this block
// never appears. It stays fully implemented as the opt-out
// target and the cold path — it is not dead code.
Column {
id: skeleton
visible: QbzSearch.cortinillaLoading
+3
View File
@@ -167,6 +167,7 @@ where
crate::sidebar_qt::init_pinned(&dir);
// Phase 15: intelligent-search service (cortinilla cache+ranking).
crate::search_qt::init(&dir, crate::search_qt::intelligent_search_pref());
crate::search_cache_qt::init();
// Phase 17: playlist is_owner math.
crate::playlist_qt::set_user_id(user_id);
bind_per_user_stores(&dir, user_id);
@@ -301,6 +302,7 @@ where
// Phase 15: intelligent-search service (cortinilla
// cache+ranking).
crate::search_qt::init(&dir, crate::search_qt::intelligent_search_pref());
crate::search_cache_qt::init();
// Phase 17: playlist is_owner math.
crate::playlist_qt::set_user_id(user_id);
bind_per_user_stores(&dir, user_id);
@@ -377,6 +379,7 @@ where
crate::sidebar_qt::init_pinned(&dir);
// Phase 15: intelligent-search service (cortinilla cache+ranking).
crate::search_qt::init(&dir, crate::search_qt::intelligent_search_pref());
crate::search_cache_qt::init();
// Phase 17: playlist is_owner math.
crate::playlist_qt::set_user_id(user_id);
// NOT optional on the offline path — see the helper's doc comment for
+5
View File
@@ -79,6 +79,11 @@ pub(crate) fn publish_plex_state() {
/// Reload every browse document in place (after a sync / connect / toggle).
pub(crate) fn reload_browse() {
// The cortinilla's instant-paint cache embeds LOCAL rows and their artwork
// paths, so anything that reaches here has just made those rows possibly
// wrong. This is the single chokepoint for local-library mutations, which
// is why the invalidation lives here rather than at each call site.
crate::search_cache_qt::invalidate();
load_albums();
load_artists();
load_tracks(true);
+2
View File
@@ -42,6 +42,8 @@ mod search_bridge;
// Local-library half of the cortinilla (same contract, commit C6): the pure
// + blocking mappers shared by the desktop and immersive dropdowns.
mod search_local;
// Instant cached paint for the cortinilla (contract C11, rulings R1+R6).
mod search_cache_qt;
mod local_bridge;
mod library_bridge;
mod album_bridge;
+128
View File
@@ -0,0 +1,128 @@
//! Instant cached paint for the cortinilla — the R1/R6 experiment.
//!
//! ## What this is, and why it is not "restoring" something that was rejected
//!
//! The reference deliberately shows a SKELETON while loading and never paints
//! cached rows first. Its comments present that as the design. It is not: the
//! instant paint existed during development and was removed because it
//! GLITCHED — results visibly jumped between the cached paint and the fresh
//! one. The owner's reading (2026-08-03) is that the glitch was a Slint
//! rendering problem, not something inherent to stale-while-revalidate, and
//! asked for it back here as a REVERSIBLE experiment.
//!
//! So this ships **default ON with a runtime opt-out** (`ui_prefs`
//! `cortinilla_instant_paint`), and the skeleton path stays fully implemented
//! as both the opt-out target and the cold-miss path. Flipping the pref
//! requires no rebuild, which is the point: the two behaviours can be compared
//! back to back in one session.
//!
//! ## Why it should not glitch here
//!
//! The glitch is "the rows moved under me". Four properties are what prevent
//! it, and each is a real constraint on the code, not a hope:
//!
//! 1. **Same shape in both paints.** The entry is written AFTER the local
//! sections are appended, so the local fold is already inside the cached
//! payload. There is no mid-apply reflow left to see.
//! 2. **Equality-gated replacement.** `CortinillaData` derives `PartialEq`, so
//! the fresh payload replaces the shown one only if it actually differs. An
//! unchanged repeat query produces ZERO second paint.
//! 3. **The selection survives.** The publish path never writes
//! `cortinillaSelectedIndex`.
//! 4. **The scroll survives.** The overlay latches and restores `contentY`
//! across a republish. Without that, the second paint yanks the user to the
//! top — which is the glitch by another name.
//!
//! ## Invalidation
//!
//! Process lifetime is the TTL (see `payload_cache`). Within a session the
//! cache must be cleared whenever its content could have gone stale:
//!
//! - a user switch or logout — a different library and a different account;
//! - any mutation of the LOCAL library, because a cached payload embeds local
//! rows and their artwork paths.
//!
//! There is no "library changed" signal on `QbzLocal` to subscribe to, so the
//! mutating entry points clear it directly. That is an honest bound rather
//! than a guess: if a future path mutates the library without clearing, its
//! staleness window is one query key until the next keystroke, and the fix is
//! one line at that call site.
use std::sync::Mutex;
use qbz_app::settings::payload_cache::PayloadCache;
use crate::search_qt::CortinillaData;
static CACHE: Mutex<Option<PayloadCache<CortinillaData>>> = Mutex::new(None);
/// Is the instant paint enabled? DEFAULT ON (owner ruling R6).
///
/// Read from `ui_prefs` on every call rather than mirrored in memory, and that
/// is deliberate: the whole purpose of the flag is that the owner can flip it
/// and compare both behaviours WITHOUT a rebuild, which a cached mirror would
/// defeat. The read happens on a tokio worker (`live()` is spawned), never on
/// the Qt GUI thread.
pub fn instant_paint_enabled() -> bool {
crate::settings_qt::pref_bool("cortinilla_instant_paint", true)
}
/// Bind a fresh cache for a session. Called next to the other per-user stores.
pub fn init() {
if let Ok(mut guard) = CACHE.lock() {
*guard = Some(PayloadCache::default());
}
}
/// Drop it on logout — a cached payload holds the previous account's library.
pub fn teardown() {
if let Ok(mut guard) = CACHE.lock() {
*guard = None;
}
}
/// Clear every entry without unbinding the store.
///
/// Call this from ANY path that mutates the local library: a scan, an import,
/// a delete, a Plex sync. A cached payload embeds local rows and their artwork
/// paths, so after a mutation those rows may name files that no longer exist.
pub fn invalidate() {
if let Ok(mut guard) = CACHE.lock() {
if let Some(c) = guard.as_mut() {
c.clear();
}
}
}
/// The cached payload for `query`, or `None` on a miss / when the flag is off
/// / before a session is bound.
pub fn get(query: &str) -> Option<CortinillaData> {
if !instant_paint_enabled() {
return None;
}
CACHE
.lock()
.ok()?
.as_ref()?
.get(query)
.cloned()
}
/// Store a FINISHED payload.
///
/// "Finished" is load-bearing and there are exactly TWO call sites, both in
/// `search_qt::live`: after pass-1 artwork resolution, and again at the pass-2
/// republish once the downloaded covers have landed. Writing any earlier
/// caches rows with empty artwork paths, and since the QML draws `artPath`
/// only, a hit would paint cover-less rows AND the equality gate would fire on
/// every single hit — the exact repaint this cache exists to avoid.
pub fn put(query: &str, data: &CortinillaData) {
if !instant_paint_enabled() {
return;
}
if let Ok(mut guard) = CACHE.lock() {
if let Some(c) = guard.as_mut() {
c.put(query, data.clone());
}
}
}
+50 -7
View File
@@ -100,6 +100,7 @@ pub fn teardown() {
if let Ok(mut guard) = SERVICE.lock() {
*guard = None;
}
crate::search_cache_qt::teardown();
next_cort_version();
*LAST_CORT.lock().unwrap_or_else(|e| e.into_inner()) = None;
*LAST_CORT_LOCAL.lock().unwrap_or_else(|e| e.into_inner()) = Vec::new();
@@ -795,11 +796,30 @@ pub async fn live(runtime: &Arc<AppRuntime<LoggingAdapter>>, query: &str) {
let status = crate::offline_fwd::engine().status();
let expand_local = status.is_offline() || status.offline_session;
let caps = crate::search_local::LocalCaps::for_session(expand_local);
// Query echo + loading flag ride the cortinillaLoading property and a
// minimal payload (skeleton rows are pure QML).
crate::search_bridge::ui(move |mut b| {
b.as_mut().set_cortinilla_loading(true);
});
// ---- the instant-paint probe (rulings R1 + R6) ----------------------
// Synchronous, before the debounce, so what the user sees at t~0 is
// decided here and cannot race the 220 ms sleep below.
//
// `cortinillaLoading` has exactly ONE owner: this block. On a HIT the
// cached rows and `loading = false` go out in the SAME ui() closure, so
// the skeleton never appears; on a miss the skeleton is raised. It is
// written once more at the publish, and nowhere else.
let shown: Option<CortinillaData> = crate::search_cache_qt::get(&q);
match &shown {
Some(cached) => {
let json = serde_json::to_string(cached).unwrap_or_else(|_| "{}".into());
crate::search_bridge::ui(move |mut b| {
b.as_mut().set_cortinilla_json(QString::from(json.as_str()));
b.as_mut().set_cortinilla_loading(false);
});
}
None => {
crate::search_bridge::ui(move |mut b| {
b.as_mut().set_cortinilla_loading(true);
});
}
}
// ---- end of the synchronous half; the debounce starts here ----------
// 220 ms (CORTINILLA_DEBOUNCE): one load per pause, not one per
@@ -863,13 +883,31 @@ pub async fn live(runtime: &Arc<AppRuntime<LoggingAdapter>>, query: &str) {
}
let missing = attach_urls(urls);
*LAST_CORT.lock().unwrap_or_else(|e| e.into_inner()) = Some(data.clone());
// WRITE POINT 1 of exactly two — AFTER pass-1 artwork resolution. Writing
// any earlier caches rows with empty art_path, and the QML draws art_path
// only: a hit would paint cover-less rows AND the gate below would fire on
// every hit, which is the repaint this whole thing exists to avoid.
crate::search_cache_qt::put(&q, &data);
// THE EQUALITY GATE. If the instant paint already showed this exact
// payload, there is nothing to repaint — and NOT repainting is the whole
// difference between this and the version that glitched. `loading` is
// still cleared, because a cache miss raised the skeleton.
let unchanged = shown.as_ref() == Some(&data);
if unchanged {
log::debug!("[qbz-qt] cortinilla: fresh payload == instant paint, no repaint");
}
crate::search_bridge::ui(move |mut b| {
if is_current_cort_version(version) {
let json = serde_json::to_string(&data).unwrap_or_else(|_| "{}".into());
b.as_mut().set_cortinilla_json(QString::from(json.as_str()));
if !unchanged {
let json = serde_json::to_string(&data).unwrap_or_else(|_| "{}".into());
b.as_mut().set_cortinilla_json(QString::from(json.as_str()));
}
b.as_mut().set_cortinilla_loading(false);
}
});
// The query is moved into the artwork task so write point 2 can key the
// refreshed entry the same way write point 1 did.
let q_art = q.clone();
if !missing.is_empty() {
crate::spawn(async move {
crate::artwork_qt::download_missing(missing).await;
@@ -888,6 +926,11 @@ pub async fn live(runtime: &Arc<AppRuntime<LoggingAdapter>>, query: &str) {
}
}
let _ = attach_urls(urls);
// WRITE POINT 2 of two: refresh the entry with the downloaded
// covers. Without this the NEXT hit would instant-paint the
// pass-1 payload, whose art_paths differ from the settled
// ones, and the gate would fire a repaint forever.
crate::search_cache_qt::put(&q_art, data);
let data = data.clone();
*LAST_CORT.lock().unwrap_or_else(|e| e.into_inner()) = Some(data.clone());
crate::search_bridge::ui(move |mut b| {