From 2c551c5b7162765f1cd1c43a3b5cff23ccc2295e Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 19 Nov 2026 20:48:22 +0200 Subject: [PATCH] Carry the newest progress generation in outgoing playback states A browser queue item keeps the handoff hint it arrived with, which is older than the checkpoints this account has written since. Every podcast episode in a playback state the web sends to a trusted device now carries max(hint, register generation), so the device taking over writes its explicit action above everything the web has seen. Which state reads the resume position from the register is decided on the converted queue, so the bridge itself stays testable without a database. Co-Authored-By: Claude Opus 5.5 --- src/federation/devices.rs | 60 ++++++++++++++++--- src/federation/devices/gating_tests.rs | 76 +++++++++++++++++++----- src/federation/devices/postgres_tests.rs | 36 ++++++++++- src/podcasts/queries.rs | 34 +++++++++++ 4 files changed, 182 insertions(+), 24 deletions(-) diff --git a/src/federation/devices.rs b/src/federation/devices.rs index edf4b80..b73c9cf 100644 --- a/src/federation/devices.rs +++ b/src/federation/devices.rs @@ -31,7 +31,7 @@ use music_dht::device_sync::{ random_hex, relayed_protocol_version, supports_listen_history, supports_podcasts, ticket_endpoint_id, }; -use music_dht::podcast::ProgressRecord; +use music_dht::podcast::{EpisodeId, ProgressRecord}; use music_dht::{ByteStream, MusicDhtService, NetworkId, PeerTicket, SecretKey, StreamAcceptor}; use serde::Serialize; use sqlx::Row; @@ -3730,20 +3730,64 @@ async fn playback_state_from_browser_json( ) -> Result { let unknown = browser_bool(&state, queue_items::POSITION_UNKNOWN_KEY) == Some(true); let mut wire = browser_json_to_wire(pool, state).await?; - if unknown - && let Some(episode) = wire - .queue - .get(wire.queue_pos) - .and_then(PlaybackTrack::podcast_episode_ref) - { + if let Some(episode_id) = episode_needing_resume_position(unknown, &wire) { let record = PodcastStore::new(pool.clone()) - .progress(user_id, &episode.episode_id) + .progress(user_id, &episode_id) .await?; apply_resume_position(&mut wire, record.as_ref()); } + let episodes: Vec = wire + .queue + .iter() + .filter_map(PlaybackTrack::podcast_episode_ref) + .map(|episode| episode.episode_id.clone()) + .collect(); + if !episodes.is_empty() { + let generations = PodcastStore::new(pool.clone()) + .progress_generations(user_id, &episodes) + .await?; + apply_progress_generations(&mut wire, &generations); + } Ok(wire) } +/// Raises `PodcastEpisodeRef::progress_generation` of every episode in the +/// queue to the generation of its progress register here. +/// +/// The browser keeps the hint its queue item came with, which can be older +/// than what this account has seen since (its own checkpoints, operations +/// from other devices). The device taking over writes its explicit action +/// above this value (frid `PODCASTS.md`, "Handoff"). +fn apply_progress_generations( + state: &mut PlaybackStateWire, + generations: &std::collections::HashMap, +) { + for track in &mut state.queue { + if let Some(PlaybackSource::PodcastEpisode(episode)) = track.source.as_mut() + && let Some(generation) = generations.get(&episode.episode_id) + { + episode.progress_generation = Some( + episode + .progress_generation + .map_or(*generation, |seen| seen.max(*generation)), + ); + } + } +} + +/// The current episode whose position comes from its progress register: +/// only when the browser said it does not know the position. Known +/// positions (handoffs, seeks, playing) and music are never replaced. +fn episode_needing_resume_position(unknown: bool, wire: &PlaybackStateWire) -> Option { + if !unknown { + return None; + } + wire.queue + .get(wire.queue_pos) + .and_then(PlaybackTrack::podcast_episode_ref) + .map(|episode| episode.episode_id.clone()) +} + /// Sets the position of the current podcast episode to where ordinary Play /// resumes it (`ProgressRecord::resume_position_ms`, 0 without a register), /// and records the register's generation as seen for the handoff. diff --git a/src/federation/devices/gating_tests.rs b/src/federation/devices/gating_tests.rs index a072595..c12ac9f 100644 --- a/src/federation/devices/gating_tests.rs +++ b/src/federation/devices/gating_tests.rs @@ -365,7 +365,10 @@ async fn podcast_queue_survives_server_browser_server_round_trip() { assert_eq!(payload["index"], 3); assert_eq!(payload["position_seconds"], 1200.0); assert_eq!(tracks[0]["source"]["kind"], "podcast_episode"); - assert_eq!(tracks[0]["unavailable"], false, "episodes play on the web player"); + assert_eq!( + tracks[0]["unavailable"], false, + "episodes play on the web player" + ); assert_eq!(tracks[1]["source"]["kind"], "private"); // The browser keeps its queue and sends it back (plus a library track @@ -380,10 +383,10 @@ async fn podcast_queue_survives_server_browser_server_round_trip() { "release_id": 9, "release_title": "Album", })); - // browser -> server -> peer - let outgoing = playback_state_from_browser_json(&pool, 1, browser) - .await - .unwrap(); + // browser -> server -> peer (the bridge itself; the progress-register + // lookups of `playback_state_from_browser_json` need a database and + // are covered by `apply_progress_generations_*` and the Postgres tests) + let outgoing = browser_json_to_wire(&pool, browser).await.unwrap(); assert_eq!(outgoing.queue[..4], queue[..]); assert_eq!(outgoing.queue_pos, 3); assert!(outgoing.paused); @@ -400,6 +403,42 @@ async fn podcast_queue_survives_server_browser_server_round_trip() { assert!(playback_allowed_for_peer(&outgoing, 4)); } +#[test] +fn apply_progress_generations_raises_stale_handoff_hints_only() { + let mut first = test_episode(); + first.progress_generation = Some(9); + let mut second = test_episode(); + second.episode_id = EpisodeId::from_guid(&second.podcast_id, "episode-43").unwrap(); + second.progress_generation = None; + let mut third = test_episode(); + third.episode_id = EpisodeId::from_guid(&third.podcast_id, "episode-44").unwrap(); + third.progress_generation = Some(2); + let mut wire = state(vec![ + PlaybackTrack::podcast_episode(first.clone()), + PlaybackTrack::podcast_episode(second.clone()), + music_track(3), + PlaybackTrack::podcast_episode(third.clone()), + ]); + let generations = std::collections::HashMap::from([ + (first.episode_id.clone(), 4), + (second.episode_id.clone(), 6), + (third.episode_id.clone(), 5), + ]); + apply_progress_generations(&mut wire, &generations); + let hints: Vec> = wire + .queue + .iter() + .map(|track| { + track + .podcast_episode_ref() + .and_then(|e| e.progress_generation) + }) + .collect(); + // A newer carried hint stays; missing and older ones are raised. + assert_eq!(hints, vec![Some(9), Some(6), None, Some(5)]); + assert_eq!(wire.queue[2], music_track(3), "music is untouched"); +} + #[tokio::test] async fn malformed_browser_items_keep_the_position_on_its_item() { let pool = offline_pool(); @@ -555,21 +594,28 @@ async fn unknown_episode_position_resumes_from_the_progress_register() { } #[tokio::test] -async fn known_positions_and_music_never_read_the_progress_register() { - // The offline pool fails any query, so these conversions must not query. +async fn known_positions_and_music_never_take_the_register_position() { + // The bridge itself runs without queries (offline pool); which state + // reads the episode's progress register is decided on the result. let pool = offline_pool(); let mut handed_off = song_then_episode(); handed_off["index"] = serde_json::json!(1); handed_off["position_seconds"] = serde_json::json!(1200.0); - let wire = playback_state_from_browser_json(&pool, 1, handed_off) - .await - .unwrap(); + let wire = browser_json_to_wire(&pool, handed_off).await.unwrap(); assert_eq!(wire.position_secs, 1200.0); + assert_eq!(episode_needing_resume_position(false, &wire), None); + assert_eq!( + episode_needing_resume_position(true, &wire), + Some(test_episode().episode_id), + "an episode the browser did not know the position of" + ); - let mut music = song_then_episode(); - music[queue_items::POSITION_UNKNOWN_KEY] = serde_json::json!(true); - let wire = playback_state_from_browser_json(&pool, 1, music) - .await - .unwrap(); + let music = song_then_episode(); + let wire = browser_json_to_wire(&pool, music).await.unwrap(); assert_eq!(wire.position_secs, 200.0); + assert_eq!( + episode_needing_resume_position(true, &wire), + None, + "music keeps its position even when flagged" + ); } diff --git a/src/federation/devices/postgres_tests.rs b/src/federation/devices/postgres_tests.rs index 29da155..d78cd9f 100644 --- a/src/federation/devices/postgres_tests.rs +++ b/src/federation/devices/postgres_tests.rs @@ -412,6 +412,40 @@ async fn postgres_unknown_episode_position_and_rollback_cleanup() { Some(9) ); + // A known position (the web player was playing the episode) is sent + // as is, but the stale handoff hint of the browser item (7) is raised + // to the register generation this account has seen (9). + let browser = serde_json::json!({ + "tracks": [song.clone(), item.clone()], "index": 1, "track": item.clone(), + "position_seconds": 1500.0, "paused": true, + }); + record_web_active_transfer(&pool, user_id, &tui, None, browser) + .await + .unwrap(); + let sent: serde_json::Value = sqlx::query_scalar( + "SELECT payload_json FROM furumusic__fed_sync_ops + WHERE user_id = $1 AND kind = 'playback_command' ORDER BY seq DESC LIMIT 1", + ) + .bind(user_id) + .fetch_one(&pool) + .await + .unwrap(); + let SyncOpPayload::PlaybackCommand { + command: PlaybackCommand::ActiveChanged { state, .. }, + .. + } = serde_json::from_value(sent).unwrap() + else { + panic!("expected ActiveChanged"); + }; + assert_eq!(state.position_secs, 1500.0); + assert_eq!( + state.queue[1] + .podcast_episode_ref() + .unwrap() + .progress_generation, + Some(9) + ); + // Remote Next onto the episode while the TUI plays the song. let current = serde_json::json!({ "tracks": [song, item], "index": 0, "track": song, @@ -469,7 +503,7 @@ async fn postgres_unknown_episode_position_and_rollback_cleanup() { super::wire_compat_tests::legacy::SyncOpPayload::PlaybackCommand { .. } )) .count(), - 2 + 3 ); cleanup(&pool, user_id).await; diff --git a/src/podcasts/queries.rs b/src/podcasts/queries.rs index df07405..d663d87 100644 --- a/src/podcasts/queries.rs +++ b/src/podcasts/queries.rs @@ -666,6 +666,40 @@ impl PodcastStore { Ok(count(total)) } + /// Generations of the progress registers of `episode_ids` (episodes + /// without a register are missing from the map). + /// + /// Outgoing playback states carry them as + /// `PodcastEpisodeRef::progress_generation`, so the device that takes + /// over writes its explicit action after everything this account saw. + pub(crate) async fn progress_generations( + &self, + user_id: i64, + episode_ids: &[EpisodeId], + ) -> Result> { + if episode_ids.is_empty() { + return Ok(Default::default()); + } + let ids: Vec<&str> = episode_ids.iter().map(EpisodeId::as_str).collect(); + let rows = sqlx::query( + "SELECT episode_id, generation FROM furumusic__podcast_progress + WHERE user_id = $1 AND episode_id = ANY($2)", + ) + .bind(user_id) + .bind(&ids) + .fetch_all(&self.pool) + .await?; + rows.iter() + .map(|row| { + Ok(( + episode_id_col(row, "episode_id")?, + super::generation_from_sql(row.try_get("generation")?), + )) + }) + .collect::>() + .map_err(Into::into) + } + /// Audio URL and enclosure type of an episode in this account's catalog /// (`None` when the account does not know the episode). The audio proxy /// and the playback source endpoint take URLs only from here.