From 641ba143a583dd359ea1701efa2466e6f6925251 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 15:59:41 +0300 Subject: [PATCH 1/8] The platform states where the account's records live: tv::Services.storage The session, the install's preferences and the consent record live in the LS2/DB8 storage helper on a webOS television and in files everywhere else. The persistence layers chose between the two with `all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))`, which is "32-bit ARM Linux", not "a television": a Tizen ARM build would select the helper with none behind it. `tv::Services` gains a fifth group, `storage: StorageHooks { authority }`, in the new `os/src/tv/authority.rs`. `Authority::Helper` is webOS (`port.rs`); `Authority::Files` is the desktop platform, `Services::HOST_TEST` and any platform with no helper (`StorageHooks::NONE`). `tv::authority::authority()` reads the installed table, and an uninstalled process reads `Files` like every other group's host-test answer. There is deliberately no test override: the layers that read it take the authority as a parameter, so a test passes whichever one it grades. Nothing reads the value yet; the plex and telemetry lanes re-key their fences to it next. Tests pin the host-test answer in the destructuring test of `tv.rs`, the webOS and desktop tables, and the order `run_application` installs the services before it enters the application: an uninstalled television would read `Files` and write a plaintext session file. Co-Authored-By: Claude --- docs/module-layers.md | 2 +- docs/platform-ports.md | 4 ++ rust-modules/os/src/tv.rs | 10 ++++- rust-modules/os/src/tv/authority.rs | 65 ++++++++++++++++++++++++++++ rust-modules/src/platform_desktop.rs | 12 ++++- rust-modules/src/port.rs | 44 ++++++++++++++++++- 6 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 rust-modules/os/src/tv/authority.rs diff --git a/docs/module-layers.md b/docs/module-layers.md index 06df7a3e2..714e30989 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -350,7 +350,7 @@ L15's 44 entries, 205 references of which 95 were in production code. The port's their layers, so none of this held up the split. L15 moved every one of those references behind an interface in `os`'s new `tv` module that -the port fills at boot. `tv::Services` is a table of function pointers in four groups (`identity`, `secure`, `system` and `legacy_webos_media`), installed once by `app::run_application` (from the `Platform` its entry hands it) before anything +the port fills at boot. `tv::Services` is a table of function pointers and stated values in five groups (`identity`, `secure`, `system`, `storage` and `legacy_webos_media`), installed once by `app::run_application` (from the `Platform` its entry hands it) before anything that reads it. With nothing installed (host unit tests, where nothing calls `plex_run`) `tv::Services::HOST_TEST` answers what the host arms answered before; a shipping build that reaches it logs `tv: port not installed - using the no-port defaults` once. diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 45f9329ff..477fa0d54 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -848,6 +848,10 @@ split by who reads it (critic M4): `devcaps` parses through, `Files::NONE` for a platform with none); - `secure { seal, open, remove, mode }` (Target shape 4; until W2 `mode` is W3a's own once-set value); - `system { go_home, poll_home, deliver_toast }`; + - `storage { authority }` (W8a): `Authority::Helper` (webOS: the LS2/DB8 storage helper owns the session, the + install's preferences and the consent record) or `Authority::Files` (desktop, Tizen, a host test), read through + `tv::authority::authority()`. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence + layers chose their store by; the helper's wake-up (`storage::client::install_activator`) joins it after W7b; - `legacy_webos_media { sink, display_sink, uri_media }`: the Starfish, ACB and `com.webos.media` verbs (F31), named for what they are (critic M3). Every hook is required (Decision 2, C): a platform states each field, a named `NONE` being a statement and a `Default`-filled gap not allowed. The one exemption is this group: diff --git a/rust-modules/os/src/tv.rs b/rust-modules/os/src/tv.rs index 4d372c779..4a2264b99 100644 --- a/rust-modules/os/src/tv.rs +++ b/rust-modules/os/src/tv.rs @@ -1,4 +1,5 @@ //! The television, as everything outside the port sees it (step L15, docs/module-layers.md). +pub mod authority; pub mod device; pub mod home; pub mod launch; @@ -10,13 +11,15 @@ pub mod sound; pub mod toast; pub mod uri; +pub use authority::StorageHooks; + use std::sync::OnceLock; /// What the platform's settings service said about the locale. i18n owns the parse and the log lines. #[cfg_attr(any(feature = "hostsim", test, feature = "test-support"), allow(dead_code))] // Reply/Unavailable: TV arm only pub enum LocaleReply { NoPlatform, Unavailable, Reply(String) } -/// What the lower layers read from the platform, in four groups. Installed once ([`install`]) before +/// What the lower layers read from the platform, in five groups. Installed once ([`install`]) before /// anything reads it, and read only by `tv`'s own modules, so no other module can issue a verb the /// interfaces below do not offer. The window, the bus pump and the frame probe are NOT here: only /// the loop reads them, so they belong to the application's own `Platform`. @@ -28,6 +31,7 @@ pub struct Services { pub identity: IdentityHooks, pub secure: SecureHooks, pub system: SystemHooks, + pub storage: StorageHooks, pub legacy_webos_media: LegacyWebosMedia, } @@ -117,6 +121,7 @@ impl Services { identity: IdentityHooks::NONE, secure: SecureHooks::NONE, system: SystemHooks::NONE, + storage: StorageHooks::NONE, legacy_webos_media: LegacyWebosMedia::NONE, }; } @@ -159,6 +164,7 @@ mod tests { identity: IdentityHooks { probe_device, start_capability_probe, repair_native_video, device_files, system_locale, sound_output }, secure: SecureHooks { seal, open, remove, mode }, system: SystemHooks { go_home, poll_home, deliver_toast }, + storage: StorageHooks { authority }, legacy_webos_media: LegacyWebosMedia { sink, display_sink, uri_media }, } = Services::HOST_TEST; @@ -193,6 +199,8 @@ mod tests { toast::Sent { reply: None, outcome: toast::Outcome::NoBus } ); + assert_eq!(authority, authority::Authority::Files, "no storage helper: the app keeps its records in files"); + assert!(!sink.feed_abi_is_cow(), "the refusing sink, not a native one"); assert_eq!(display_sink.window_mode(), sink::VP_NONE); assert_eq!(display_sink.window_id(), c""); diff --git a/rust-modules/os/src/tv/authority.rs b/rust-modules/os/src/tv/authority.rs new file mode 100644 index 000000000..85d8dd6a2 --- /dev/null +++ b/rust-modules/os/src/tv/authority.rs @@ -0,0 +1,65 @@ +//! Where the account's canonical state lives: the platform's storage helper, or plain files. +//! +//! The session record, the install's preferences and the consent record each have two homes. On a +//! webOS television the LS2/DB8 storage helper owns them ([`Authority::Helper`]): the app never +//! reads or writes a file of its own for them. Everywhere else the app keeps them in files under its +//! persistent state root ([`Authority::Files`]): the desktop simulator, a host test, and a platform +//! with no helper at all (Tizen). The layers that persist these records (`plex::session`, +//! `telemetry`) choose their store from this value, once per operation, instead of from the build's +//! CPU and OS, which is what picked it before: a 32-bit ARM Linux binary is not necessarily a +//! television. +//! +//! The platform states it once, as the `authority` of its [`StorageHooks`](super::StorageHooks), and +//! [`authority`] reads it. A process that installed no platform (a host test) reads +//! [`StorageHooks::NONE`], which is `Files`, like every other group's host-test answer. A shipping +//! process must install its services before anything persists: an uninstalled television would read +//! `Files` and write a plaintext session file, which is why `run_application` installs them first +//! (`port::tests` pins the order). +//! +//! This group is the home of the platform's other storage statements as well. The helper's wake-up +//! (`storage::client::install_activator`, which `port::plex_main` installs for webOS today) belongs +//! here as a later member and moves with the os lane after W7b; it is not moved yet. + +/// Where the account's canonical state lives. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Authority { + /// The platform's storage helper (webOS: the LS2/DB8 service). No file of the app's own holds + /// the record, and a helper that cannot answer is never papered over with one. + Helper, + /// Files under the app's persistent state root, written by the app itself. + #[default] + Files, +} + +/// The storage group of [`Services`](super::Services): what a platform states about where the app's +/// own records live. +pub struct StorageHooks { + pub authority: Authority, +} + +impl StorageHooks { + /// A platform with no storage helper: the app keeps its records in files. + pub const NONE: Self = Self { authority: Authority::Files }; +} + +/// The installed platform's [`Authority`], or `Files` when nothing is installed. +pub fn authority() -> Authority { + super::services().storage.authority +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_authority_is_files() { + assert_eq!(Authority::default(), Authority::Files); + assert_eq!(StorageHooks::NONE.authority, Authority::Files, "a platform with no helper keeps files"); + } + + /// Nothing is installed in a test process, so the reader answers the host-test group's `Files`. + #[test] + fn an_uninstalled_process_reads_files() { + assert_eq!(authority(), Authority::Files); + } +} diff --git a/rust-modules/src/platform_desktop.rs b/rust-modules/src/platform_desktop.rs index b4cb8f580..3a412fb05 100644 --- a/rust-modules/src/platform_desktop.rs +++ b/rust-modules/src/platform_desktop.rs @@ -18,6 +18,8 @@ //! no compositor to hint and no bus to pump. The secure store is `SecureHooks::NONE`: nothing seals, //! so a session is the 0600 plaintext file the session layer writes itself, which the simulator's //! harnesses plant and read. +//! The storage group is `StorageHooks::NONE`: there is no storage helper, so the account's records +//! live in files under the persistent state root. //! //! This module never names `port`, `system`, `webos` or `keymanager`, so a desktop executable //! references none of the television's code. It still COMPILES it (the television arms of those @@ -28,7 +30,7 @@ use crate::app::platform::{FrameProbe, Platform, Shell}; use plx_os::devcaps::dv::{self, DvCapability, DvProbe, ProbeSource}; use plx_os::tv::toast::{Identity, Outcome, Sent}; -use plx_os::tv::{IdentityHooks, LegacyWebosMedia, SecureHooks, Services, SystemHooks}; +use plx_os::tv::{IdentityHooks, LegacyWebosMedia, SecureHooks, Services, StorageHooks, SystemHooks}; use std::ffi::CStr; use std::os::raw::{c_int, c_void}; @@ -56,6 +58,7 @@ static SERVICES: Services = Services { }, secure: SecureHooks::NONE, system: SystemHooks { go_home, poll_home: SystemHooks::NONE.poll_home, deliver_toast }, + storage: StorageHooks::NONE, legacy_webos_media: LegacyWebosMedia { sink: SINK, display_sink: DISPLAY, @@ -141,6 +144,13 @@ pub fn run(pms_host: &CStr, pms_port: u16) -> c_int { mod tests { use super::*; + /// A desktop has no storage helper: the session, the install's preferences and the consent record + /// are files. The same value a host test reads from `Services::HOST_TEST`. + #[test] + fn the_desktop_table_keeps_the_account_in_files() { + assert_eq!(SERVICES.storage.authority, plx_os::tv::authority::Authority::Files); + } + /// The app's plane boot resolves the display through `display_installed()` (this table's /// `display_sink`), where media's old `acb_init` resolved it through `player::display()`. In /// the simulator both must be the host sink, never `NoSink`: a boot that read `NoSink` would diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 7f717ca52..800c426a8 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -20,8 +20,8 @@ const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = &plx_os::webos::video_sink:: #[cfg(test)] const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = SINK; -/// What the lower layers read: the webOS identity, key manager, Home key and toast, and the native -/// playback seam. The window, the bus pump and the frame probe are the loop's own, in [`PLATFORM`]. +/// What the lower layers read: the webOS identity, key manager, Home key and toast, the storage helper +/// and the native playback seam. The window, the bus pump and the frame probe are the loop's own, in [`PLATFORM`]. static SERVICES: plx_os::tv::Services = plx_os::tv::Services { identity: plx_os::tv::IdentityHooks { probe_device: plx_os::webos::probe, @@ -42,6 +42,7 @@ static SERVICES: plx_os::tv::Services = plx_os::tv::Services { poll_home: plx_os::webos::poll_home, deliver_toast: plx_os::webos::toast::deliver, }, + storage: plx_os::tv::StorageHooks { authority: plx_os::tv::authority::Authority::Helper }, legacy_webos_media: plx_os::tv::LegacyWebosMedia { sink: SINK, display_sink: DISPLAY, @@ -148,3 +149,42 @@ pub unsafe extern "C" fn plx_launch_args(json: *const c_char) { let raw = unsafe { std::ffi::CStr::from_ptr(json) }.to_string_lossy(); plx_os::tv::launch::offer(&raw); } + +#[cfg(test)] +mod tests { + use super::SERVICES; + use plx_os::tv::authority::Authority; + + /// The webOS table states the storage helper as the home of the session, the install's preferences + /// and the consent record. The persistence layers choose their store from this value, so a table + /// that stated anything else would move a television's account out of DB8. + #[test] + fn the_webos_table_states_the_storage_helper_as_the_authority() { + assert_eq!(SERVICES.storage.authority, Authority::Helper); + assert_eq!(SERVICES.secure.mode, plx_os::tv::secure::StoreMode::Durable); + } + + /// `run_application` installs the services before anything else runs. The authority is read by + /// whatever persists first, and an uninstalled television reads `Files` and would write a + /// plaintext session file, so the install has to come before `exit::entry` runs `enter_application`. + /// Reads the source, like `app::boot`'s `seam_order_tests`, because no host test can run the entry. + #[test] + fn the_services_are_installed_before_the_application_enters() { + let source = include_str!("app/mod.rs"); + let body = source + .split_once("fn run_application(") + .expect("run_application") + .1 + .split_once("\n}\n") + .expect("end of run_application") + .0; + let install = body.find("platform.install_services();").expect("run_application installs the services"); + let enter = body.find("exit::entry(").expect("run_application enters through exit::entry"); + assert!(install < enter, "install_services must run before exit::entry"); + assert_eq!( + source.matches("install_services()").count(), + 1, + "one production install; a second would be refused by tv and could hide a missing first" + ); + } +} From 176aabd57e7e875023c19fbbfa0c8a06b894a2b1 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 16:15:36 +0300 Subject: [PATCH 2/8] plex's persistence layer reads the platform's storage authority instead of the build's CPU The session record, the install's preferences and the sign-out sweep chose between the LS2/DB8 storage helper and the record files with `all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))`: "32-bit ARM Linux", not "a television". A Tizen ARM build would have selected the helper with none behind it, and the helper's real transport waits 12 s on a Linux host before it answers `Unavailable`. The 21 sites now read `plx_os::tv::authority::authority()` (webOS states `Helper`; the desktop, a host test and a platform with no helper state `Files`). `persistence.rs`'s dispatchers (`load`, `commit_data`, `commit_cleared`, `write_session`, `migrate_session`, `bootstrap`, `cleanup_after_confirmed_clear`, `cleanup_temporaries`) keep their public signatures and read the authority once, then call a `*_via(authority, helper, ..)` form that takes the authority and the helper's transport as parameters. The helper arm therefore runs on every host over an in-memory backend or a closure, and the files arm over a transport that fails the test if it is touched; there is no process-global override. The previous canonical JSON wrapper is a migration source only under `Helper` (`migration_candidates`, replacing `insert_arm_canonical_wrapper`); under `Files` it is the store itself. `FileMigration` calls the file arms directly. The private `load_helper`, `commit_session`, `commit_clear` and the unused `commit_session_with_authority` are gone with the only cfg arm that called them. In `session.rs` the `ACCOUNT_CLEAR_CLEANUP` hook and its installer are compiled everywhere, and `clear_for_erase` runs the telemetry sweep only under `Helper`: an unset hook still reads as retired, so `app/boot.rs` and telemetry follow in their own changes. `install_preferences` asks `keeps_language_file(authority, mode, redirected)`, the same expression with the same answer under every authority and mode that existed. `ci/allow/forks/plex.txt` falls from 33 lines to 12 (deleted lines only). The `hostsim` feature stays declared in plex's `Cargo.toml` until W8c; nothing in plex reads it any more. Co-Authored-By: Claude --- ci/allow/forks/plex.txt | 23 +- docs/platform-ports.md | 6 +- rust-modules/plex/src/plex/CLAUDE.md | 13 +- rust-modules/plex/src/plex/session.rs | 39 +- .../src/plex/session/install_preferences.rs | 38 +- .../plex/src/plex/session/migration_tests.rs | 103 ++++ .../plex/src/plex/session/persistence.rs | 470 +++++++++--------- 7 files changed, 411 insertions(+), 281 deletions(-) diff --git a/ci/allow/forks/plex.txt b/ci/allow/forks/plex.txt index ef9ce4bba..232dcca53 100644 --- a/ci/allow/forks/plex.txt +++ b/ci/allow/forks/plex.txt @@ -1,4 +1,4 @@ -# count: 33 +# count: 12 # Test/production forks (docs/sans-io.md), area `plex`: one line per production-visible `#[cfg(..)]` / `cfg!(..)` whose predicate reads `test` or `feature = "test-support"` # (`not(test)`, `not(any(test, feature = "test-support"))`, ...) in every machine crate (data/, plex/, media/, session/, screens/, ui/, appkit/ and machine/), keyed `::` (an attribute on an item), `::` (a statement or an inline `cfg!`) or `::` (a field). # Logic is one thing in production and tests deliver it events: there is no cfg(test) fork. Spec: ci/check-deps.sh `forks`. @@ -8,31 +8,10 @@ rust-modules/plex/src/plex/identity.rs::version rust-modules/plex/src/plex/origin.rs::latched_flag! rust-modules/plex/src/plex/origin.rs::store_policy_forced rust-modules/plex/src/plex/servers.rs::register_captured_origin_with_connection -rust-modules/plex/src/plex/session.rs::ACCOUNT_CLEAR_CLEANUP rust-modules/plex/src/plex/session.rs::auth_paths rust-modules/plex/src/plex/session.rs::clear_for_erase -rust-modules/plex/src/plex/session.rs::clear_for_erase -rust-modules/plex/src/plex/session.rs::clear_for_erase -rust-modules/plex/src/plex/session.rs::install_account_clear_cleanup rust-modules/plex/src/plex/session.rs::publish rust-modules/plex/src/plex/session.rs::read_into_cache_locked -rust-modules/plex/src/plex/session.rs::read_into_cache_locked -rust-modules/plex/src/plex/session/install_preferences.rs::candidates rust-modules/plex/src/plex/session/install_preferences.rs::candidates rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::cleanup_after_confirmed_clear rust-modules/plex/src/plex/session/persistence.rs::cleanup_after_confirmed_clear -rust-modules/plex/src/plex/session/persistence.rs::cleanup_temporaries -rust-modules/plex/src/plex/session/persistence.rs::cleanup_temporaries -rust-modules/plex/src/plex/session/persistence.rs::commit_cleared -rust-modules/plex/src/plex/session/persistence.rs::commit_cleared -rust-modules/plex/src/plex/session/persistence.rs::commit_data -rust-modules/plex/src/plex/session/persistence.rs::commit_data -rust-modules/plex/src/plex/session/persistence.rs::load -rust-modules/plex/src/plex/session/persistence.rs::load -rust-modules/plex/src/plex/session/persistence.rs::migrate_session -rust-modules/plex/src/plex/session/persistence.rs::migrate_session -rust-modules/plex/src/plex/session/persistence.rs::write_session -rust-modules/plex/src/plex/session/persistence.rs::write_session diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 477fa0d54..463d956f2 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -458,9 +458,11 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N `load_login_client_id`, `:4336-4349`), reusing one process-local id when storage is unavailable. `install_preferences::Saved` is `deny_unknown_fields`, version 1 (`:28-38`): it cannot carry the id without a new version. - - The authority is chosen by `target_arch = "arm"`, not by a platform value (`session/persistence.rs:1400-1425`, + - The authority was chosen by `target_arch = "arm"`, not by a platform value (`session/persistence.rs:1400-1425`, `commit_data` `:288-308`); a Tizen ARM build would select the DB8 arm with no helper behind it (F12). The - `MemoryOnly` gate sits above that selection, and W8a re-keys it. + `MemoryOnly` gate sits above that selection. W8a re-keyed plex's 21 sites to `tv::authority::authority()`: + `persistence.rs`'s dispatchers take the authority and the helper's transport, so a host test drives the helper + arm with a fake one; telemetry's sites follow in its own PR. ### Evidence from the second reviews: F40-F46 (each citation checked in the tree) diff --git a/rust-modules/plex/src/plex/CLAUDE.md b/rust-modules/plex/src/plex/CLAUDE.md index 58e41e386..8292b8d0a 100644 --- a/rust-modules/plex/src/plex/CLAUDE.md +++ b/rust-modules/plex/src/plex/CLAUDE.md @@ -627,6 +627,17 @@ a dead source is **absent** from Home and states itself in its own library secti struct, and a new field follows the omit rule. 6. **The Settings row** (labels, i18n, picker) is a screens edit, and `Choice` gains a variant (T-settings). +- **Which store holds the session is the platform's statement, `plx_os::tv::authority::authority()`** + (`Helper`: the LS2/DB8 storage helper, webOS; `Files`: the 0600 record files, the desktop, a host test and + any platform with no helper), never the build's CPU or OS. `session/persistence.rs` reads it once per + public call (`load`, `commit_data`, `commit_cleared`, `write_session`, `migrate_session`, `bootstrap`, + `cleanup_after_confirmed_clear`, `cleanup_temporaries`) and hands it to the `*_via(authority, helper, ..)` + form, so a test passes the authority it grades and, for `Helper`, a transport of its own (an in-memory + `Backend` or a closure); the real `NativeTransport` is named by the public forms only, because on a Linux + host it waits out a 12 s start deadline with no helper behind it. There is no process-global override. A + helper that cannot answer is a blocked read, never a reason to use files. `clear_for_erase`, + `read_into_cache_locked` and `install_preferences::keeps_language_file` read the same value; the + telemetry sweep after a durable clear runs only under `Helper`. - **The DB8 document may not pass `MAX_LOGICAL_BYTES` (256 KiB), and per-profile memory is what grows it.** Past the cap EVERY write fails (`LogicalTooLarge`, reported as `InvalidSchema`), so `persistence::commit_session_with` measures the projected document (the os layer's own @@ -688,7 +699,7 @@ a dead source is **absent** from Home and states itself in its own library secti copy** (`session/memory_only.rs`): reads, guarded edits, revocation and clear all resolve against it, and no credential is committed anywhere, canonical store, sealed or plaintext fallback or revocation marker. The gate sits in `read_live_locked`, `save_locked_with_authority` - and `clear_for_erase`, above every `TEST_FILE` and `target_arch` branch, so nothing behind them + and `clear_for_erase`, above every `TEST_FILE` and storage-authority branch, so nothing behind them is reachable. A write answers `PersistOutcome::Memory`, which classifies as `CompletionOutcome::Ephemeral`: signed in for this run, so the auth owner goes on to Home, but never a saved-login claim and never a warning. `drop_cache_locked` must not run in this mode diff --git a/rust-modules/plex/src/plex/session.rs b/rust-modules/plex/src/plex/session.rs index 698d864e2..109c42182 100644 --- a/rust-modules/plex/src/plex/session.rs +++ b/rust-modules/plex/src/plex/session.rs @@ -65,6 +65,7 @@ pub use prefs::{IntroSkipPref, CreditsSkipPref, DolbyVisionModePref, InstantDpad ProfilePrefsRecord, ProfileSetting, ProfileWrite, QualityPref, Row, Setting, SkipIntervalPref, SubtitlePositionPref, SubtitleSizePref, SubtitleTonePref, TrailerAutoplayPref, HudEndTimePref, UiResolutionPref, UnderPostersPref}; use prefs::ProfileMemory; +use plx_os::tv::authority::{authority as storage_authority, Authority}; use serde::de::DeserializeOwned; use serde::{Deserialize, Deserializer, Serialize}; use std::sync::Mutex; @@ -3225,8 +3226,9 @@ fn read_into_cache_locked(expected: Option) -> (std::sync::Arc, let state = std::sync::Arc::new(CACHE_READ_FOR_TEST.with(|read| { read.get().unwrap_or(read_live_locked)() })); - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - plx_base::eventlog::log("session: authority read reason=miss"); + if storage_authority() == Authority::Helper { + plx_base::eventlog::log("session: authority read reason=miss"); + } if !replace_cache(cached_arm(state.clone()), expected, false) { return (state, false); } if let ReadState::Ready { session, .. } = &*state { publish_identities(session); } (state, true) @@ -4282,17 +4284,16 @@ fn auto_quality_ready() -> bool { } /// **The telemetry/consent legacy-file sweep that follows a durable canonical clear** -/// ([`clear_for_erase`]'s ARM arm): `telemetry` owns the files and sits above `plex`, so the app -/// installs its `cleanup_after_account_clear` as a hook ([`install_account_clear_cleanup`]; -/// `app::boot::install_plex_seams`). It answers whether every candidate was retired. Unset there is -/// nothing registered to retire, which reads as retired, so the "could not be retired" branch is -/// never taken without a sweep that failed. Compiled where the sweep is: ARM, not the simulator, -/// not a test build. -#[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +/// ([`clear_for_erase`] where the storage helper is canonical): `telemetry` owns the files and sits +/// above `plex`, so the app installs its `cleanup_after_account_clear` as a hook +/// ([`install_account_clear_cleanup`]; `app::boot::install_plex_seams`). It answers whether every +/// candidate was retired. Unset there is nothing registered to retire, which reads as retired, so +/// the "could not be retired" branch is never taken without a sweep that failed. The sweep runs +/// only where the platform states [`Authority::Helper`]; elsewhere the files it retires are not +/// deferred to a sign-out, so an installed hook is never asked. static ACCOUNT_CLEAR_CLEANUP: std::sync::OnceLock bool> = std::sync::OnceLock::new(); /// Install the sweep [`ACCOUNT_CLEAR_CLEANUP`] runs. Once; later calls are ignored. -#[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] pub fn install_account_clear_cleanup(sweep: fn() -> bool) { let _ = ACCOUNT_CLEAR_CLEANUP.set(sweep); } @@ -5332,7 +5333,7 @@ fn clear_cleanup_outcome(outcome: persistence::ClearCleanupOutcome) -> ClearOutc /// load. The old-path copy goes too, or the migration fallback would resurrect the stale session. /// **And commits an explicit Cleared record to the canonical authority** — the legacy-file sweep /// below only ever touches pre-DB8 candidates; on a build where `persistence::load`/`write_session` -/// actually read/write the canonical store (DB8 or its host/ARM equivalent), that store is a +/// actually read/write the canonical store (DB8 or its host equivalent), that store is a /// SEPARATE copy of the account token and roster, and clearing only the legacy files would leave a /// clean-looking sign-out that the canonical authority still hands back on the next boot. /// @@ -5368,7 +5369,7 @@ pub fn clear_for_erase(all_local: bool, retry: Option) -> Erasure { return memory_only::clear_locked(all_local, retry); } let kept = retry.unwrap_or_else(|| Retained::of(&session_from_read(&read_live_locked()))); - let native = cfg!(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))); + let native = storage_authority() == Authority::Helper; // File backends need a credential-free resource before the credential file disappears. let mut preference_failures = Vec::new(); if !all_local && !native && !install_preferences::save(kept) { @@ -5420,22 +5421,20 @@ pub fn clear_for_erase(all_local: bool, retry: Option) -> Erasure { // `auth_paths()` above only ever covered `paths::session_candidates()` — the legacy // sign-in file and its pre-relocation predecessor. The recognized migration source set // is bigger (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON - // wrapper on ARM), and a candidate this sweep never visits is a live account token left + // wrapper where the helper is canonical), and a candidate this sweep never visits is a live account token left // on a rooted, world-readable install prefix after a sign-out that otherwise looked // clean. `cleanup_after_confirmed_clear` re-reads the authority to confirm it really is // Cleared before retiring anything, so this can only ever remove residue, never data a // concurrent re-login just wrote. - #[allow(unused_mut)] // only mutated on the ARM cfg arm below let mut outcome = clear_cleanup_outcome(persistence::cleanup_after_confirmed_clear()); // Telemetry/consent's own legacy files are a SEPARATE candidate set from the session // auth-token sweep above (`persistence::cleanup_after_confirmed_clear` never touches // them — see `paths::telemetry_candidates` vs `paths::session_migration_candidates`). - // On ARM, `telemetry::persistence::forget_at` defers their removal to exactly this - // moment, once this canonical commit is confirmed durable (Copilot review on PR #105, - // finding 7; ported from `release/v0.6`'s `telemetry::cleanup_after_account_clear`, - // called here in that release). - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - if !ACCOUNT_CLEAR_CLEANUP.get().is_none_or(|sweep| sweep()) { + // Where the storage helper is canonical, `telemetry::persistence::forget_at` defers their + // removal to exactly this moment, once this canonical commit is confirmed durable + // (Copilot review on PR #105, finding 7; ported from `release/v0.6`'s + // `telemetry::cleanup_after_account_clear`, called here in that release). + if native && !ACCOUNT_CLEAR_CLEANUP.get().is_none_or(|sweep| sweep()) { plx_base::eventlog::log( "session: canonical clear is durable but a telemetry/consent legacy \ candidate could not be retired — it remains on disk and will be swept \ diff --git a/rust-modules/plex/src/plex/session/install_preferences.rs b/rust-modules/plex/src/plex/session/install_preferences.rs index 6cc21def1..4d62f22c6 100644 --- a/rust-modules/plex/src/plex/session/install_preferences.rs +++ b/rust-modules/plex/src/plex/session/install_preferences.rs @@ -1,11 +1,13 @@ //! Credential-free install-wide choices (the UI language and the Interface resolution) retained by -//! host stores and explicitly supported file fallbacks. -//! Native DB8 remains authoritative whenever it answers; these files cannot authorize login. +//! file stores and explicitly supported file fallbacks. +//! The storage helper (DB8) remains authoritative whenever the platform states one +//! ([`Authority::Helper`]) and it answers; these files cannot authorize login. //! //! On a [`StoreMode::MemoryOnly`] platform this file is also where the install's own client id //! lives (version 2): the one thing a launch must know before anyone signs in and that no credential //! store is there to keep. The id is an install label, not a secret, and cannot authorize a login. use super::*; +use plx_os::tv::authority::{authority, Authority}; use plx_os::tv::secure::{mode, StoreMode}; use std::path::PathBuf; @@ -59,6 +61,13 @@ impl Saved { } } +/// Whether the install's own state root holds a `language.json`. webOS keeps these choices in DB8 +/// and never in this root; a memory-only platform has no DB8, so its root is where they live. A +/// redirected test fixture names its own files instead. +fn keeps_language_file(authority: Authority, mode: StoreMode, redirected: bool) -> bool { + (authority == Authority::Files || mode == StoreMode::MemoryOnly) && !redirected +} + fn candidates() -> Vec { #[cfg(any(test, feature = "test-support"))] let redirected = TEST_FILE.lock().unwrap_or_else(|e| e.into_inner()).is_some() @@ -66,9 +75,7 @@ fn candidates() -> Vec { #[cfg(not(any(test, feature = "test-support")))] let redirected = false; let mut paths = Vec::new(); - // webOS keeps these choices in DB8 and never in this root; a memory-only platform has no DB8. - if (!cfg!(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))) - || mode() == StoreMode::MemoryOnly) && !redirected { + if keeps_language_file(authority(), mode(), redirected) { paths.push(plx_base::paths::persistent_state_root().join("language.json")); } paths.extend(auth_paths().into_iter().map(|path| path.with_extension("language.json"))); @@ -131,3 +138,24 @@ pub(super) fn erase() -> Vec { .err().map(|error| format!("{}: {error}", path.display())) }).collect() } + +#[cfg(test)] +mod authority_tests { + use super::*; + + /// The install's own `language.json` is where a file platform keeps its choices and where a + /// memory-only platform keeps the only thing that outlives the process. A television whose + /// storage helper holds them has none, and a redirected fixture names its own files. + #[test] + fn the_language_file_is_kept_unless_the_helper_holds_the_choices() { + use Authority::{Files, Helper}; + use StoreMode::{Durable, MemoryOnly}; + assert!(keeps_language_file(Files, Durable, false), "the desktop and Tizen keep the file"); + assert!(keeps_language_file(Files, MemoryOnly, false)); + assert!(!keeps_language_file(Helper, Durable, false), "webOS keeps these choices in DB8, never in this root"); + assert!(keeps_language_file(Helper, MemoryOnly, false), "a memory-only platform has no DB8 to hold them"); + for (authority, mode) in [(Files, Durable), (Files, MemoryOnly), (Helper, MemoryOnly)] { + assert!(!keeps_language_file(authority, mode, true), "a redirected fixture never reaches the real root"); + } + } +} diff --git a/rust-modules/plex/src/plex/session/migration_tests.rs b/rust-modules/plex/src/plex/session/migration_tests.rs index 14e856f63..1e7880406 100644 --- a/rust-modules/plex/src/plex/session/migration_tests.rs +++ b/rust-modules/plex/src/plex/session/migration_tests.rs @@ -1,6 +1,7 @@ //! Canonical schema and the shipping client/coordinator path, using synthetic helper transport. use super::*; use plx_os::storage::{client, state, wire::*}; +use plx_os::tv::authority::Authority; use persistence::CanonicalRead; fn fixture() -> Session { @@ -1389,3 +1390,105 @@ fn pending_revocation_prevents_missing_canonical_from_importing_a_marked_snapsho assert_eq!(store.commits, 0); assert!(source.path.exists()); } + +// Which store is canonical is the platform's statement (`plx_os::tv::authority`). The dispatchers +// take the authority and the helper's transport, so every host runs the helper arm over a +// transport of its own, and the files arm over one that fails the test if it is reached. + +/// The transport the files arm must never reach. +fn no_helper(_: Request) -> Result { + panic!("a files authority never talks to the storage helper") +} + +/// The helper arm over the production backend, which holds the record the way DB8 does: the app's +/// own state root stays empty. +#[test] +fn a_helper_authority_reads_and_clears_through_the_helper_and_keeps_no_file() { + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-helper"); + let mut backend = plx_os::storage::backend::Backend::new( + Db8::default(), state::Flavor::Stable, "com.beb.plxnative.storage".into()); + let mut transport = |request: Request| Ok(backend.dispatch(request)); + assert!(matches!(persistence::load_via(Authority::Helper, &mut transport), CanonicalRead::Missing)); + commit_fresh(&fixture(), &mut transport); + let CanonicalRead::Opened { session, .. } = persistence::load_via(Authority::Helper, &mut transport) else { + panic!("the helper holds the session") + }; + assert_eq!(session.account_token, "synthetic-account"); + assert!(matches!(persistence::commit_cleared_via(Authority::Helper, &mut transport), + persistence::CanonicalCommit::Durable { .. })); + assert!(matches!(persistence::load_via(Authority::Helper, &mut transport), CanonicalRead::Cleared { .. })); + assert_eq!( + with_io_for_test(|| persistence::cleanup_after_confirmed_clear_via(Authority::Helper, &mut transport, Vec::new())), + persistence::ClearCleanupOutcome::Confirmed); + assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "the helper arm never writes a file of the app's own"); +} + +/// The files arm for a platform with no helper (the desktop, a host test, Tizen): the record is the +/// 0600 file under the state root, and the helper is never asked. +#[test] +fn a_files_authority_keeps_the_record_in_files_and_never_asks_the_helper() { + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-files"); + let session = fixture(); + let payload = serde_json::to_string(&session).unwrap(); + assert!(matches!(persistence::load_via(Authority::Files, &mut no_helper), CanonicalRead::Missing)); + assert!(matches!(persistence::commit_data_via(Authority::Files, &mut no_helper, payload), + persistence::CanonicalCommit::Durable { revision: 1, .. })); + assert!(matches!( + persistence::write_session_via(Authority::Files, &mut no_helper, &session, SaveAuthority::Routine), + persistence::CanonicalCommit::Durable { revision: 2, .. })); + assert!(matches!(persistence::migrate_session_via(Authority::Files, &mut no_helper, &session), + persistence::CanonicalCommit::Durable { revision: 3, .. })); + let CanonicalRead::Data { revision: 3, payload: stored } = persistence::load_via(Authority::Files, &mut no_helper) else { + panic!("the files hold the session") + }; + assert_eq!(serde_json::from_str::(&stored).unwrap().account_token, "synthetic-account"); + assert!(state.dir.join("session.json").exists()); + assert!(matches!(persistence::commit_cleared_via(Authority::Files, &mut no_helper), + persistence::CanonicalCommit::Durable { revision: 4, .. })); + assert!(matches!(persistence::load_via(Authority::Files, &mut no_helper), CanonicalRead::Cleared { revision: 4, .. })); + assert_eq!( + with_io_for_test(|| persistence::cleanup_after_confirmed_clear_via(Authority::Files, &mut no_helper, Vec::new())), + persistence::ClearCleanupOutcome::Confirmed); + let boot = persistence::bootstrap_via(Authority::Files, &mut no_helper, &mut opener(), Vec::new()); + assert!(matches!(boot.state, CanonicalRead::Cleared { revision: 4, .. }), "the record the files hold is read as it is"); +} + +/// A helper that cannot answer is a blocked canonical store, never a licence to use files: not for a +/// read, not for a write, not for a migration, and a legacy file is neither imported nor retired. +#[test] +fn a_helper_authority_never_falls_back_to_files_when_the_helper_cannot_answer() { + use plx_os::storage::StoreError; + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-helper-down"); + let legacy = LegacyFile::new("authority-helper-down", &serde_json::to_value(fixture()).unwrap()); + let session = fixture(); + let requests = std::cell::Cell::new(0usize); + let mut down = |_: Request| { + requests.set(requests.get() + 1); + Err(client::ClientError::Unavailable) + }; + let unavailable = persistence::CanonicalCommit::Failed(StoreError::HelperUnavailable); + assert!(matches!(persistence::load_via(Authority::Helper, &mut down), + CanonicalRead::Blocked(StoreError::HelperUnavailable))); + assert_eq!(persistence::commit_data_via(Authority::Helper, &mut down, serde_json::to_string(&session).unwrap()), + unavailable); + assert_eq!(requests.get(), 2); + assert_eq!(persistence::commit_data_via(Authority::Helper, &mut down, "not a session".into()), + persistence::CanonicalCommit::Failed(StoreError::InvalidSchema), + "a payload the helper cannot take is refused before it is sent"); + assert_eq!(requests.get(), 2); + assert_eq!(persistence::write_session_via(Authority::Helper, &mut down, &session, SaveAuthority::Routine), unavailable); + assert_eq!(persistence::migrate_session_via(Authority::Helper, &mut down, &session), unavailable); + assert_eq!(persistence::commit_cleared_via(Authority::Helper, &mut down), unavailable); + assert_eq!(requests.get(), 5, "each of those asked the helper, and only the helper"); + let boot = persistence::bootstrap_via(Authority::Helper, &mut down, &mut opener(), vec![legacy.path.clone()]); + assert!(matches!(boot.state, CanonicalRead::Blocked(StoreError::HelperUnavailable))); + assert!(boot.migration.is_none(), "a helper that is down authorizes no import"); + assert_eq!( + persistence::cleanup_after_confirmed_clear_via(Authority::Helper, &mut down, vec![legacy.path.clone()]), + persistence::ClearCleanupOutcome::AuthorityNotConfirmed); + assert!(legacy.path.exists(), "an unconfirmed clear retires nothing"); + assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "no file of the app's own was created"); +} diff --git a/rust-modules/plex/src/plex/session/persistence.rs b/rust-modules/plex/src/plex/session/persistence.rs index 4cfb5d968..5398fa4d1 100644 --- a/rust-modules/plex/src/plex/session/persistence.rs +++ b/rust-modules/plex/src/plex/session/persistence.rs @@ -3,6 +3,14 @@ //! This module owns the distinction between the versioned canonical record and the legacy //! filename candidates. Canonical helper loads, typed migration, and exact readback share this //! adapter; no unavailable helper response authorizes a file-backend fallback. +//! +//! **Which store is canonical is the platform's statement**, [`plx_os::tv::authority::authority`]: +//! the storage helper ([`Authority::Helper`], webOS) or the 0600 record files ([`Authority::Files`], +//! the desktop, a host test and a platform with no helper). Every dispatcher here reads it once per +//! call, in its public form, and hands it to a `*_via(authority, helper, ..)` form that takes the +//! authority and the helper's transport as parameters, so a host test grades the helper arm with a +//! fake transport and the files arm with a transport that fails the test if it is touched. The +//! helper's real transport (`NativeTransport`) is only ever named by the public forms. use plx_os::storage::{ CommitReceipt, CommitStage, Record, RecordKey, RecordState, RecordStore, StoreError, @@ -15,6 +23,7 @@ use plx_os::storage::{ state::{self, Generation, MigrationProgress, Status}, wire::{AuthLoad, CommitStatus, MigrationMutation, Response, WireMutation}, }; +use plx_os::tv::authority::{authority as storage_authority, Authority}; pub enum CanonicalRead { Missing, @@ -84,26 +93,16 @@ pub fn path() -> PathBuf { } pub fn cleanup_temporaries() -> Result<(), StoreError> { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { + cleanup_temporaries_for(storage_authority()) +} + +fn cleanup_temporaries_for(authority: Authority) -> Result<(), StoreError> { + match authority { // DB8 has no app-owned rename temporaries. Legacy paths are retired explicitly after the // helper has verified the committed destination; absence of the old app/state directory // is normal on a fresh install and must not turn sign-out into a cleanup failure. - Ok(()) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - store()?.cleanup(RecordKey::Session) + Authority::Helper => Ok(()), + Authority::Files => store()?.cleanup(RecordKey::Session), } } @@ -158,45 +157,44 @@ std::thread_local! { const { std::cell::Cell::new(None) }; } +/// The canonical record from the platform's store. pub fn load() -> CanonicalRead { + load_via(storage_authority(), &mut client::NativeTransport) +} + +/// [`load`] with the authority and the helper's transport as parameters. The transport is touched +/// only by [`Authority::Helper`]. +pub(super) fn load_via(authority: Authority, helper: &mut dyn client::Transport) -> CanonicalRead { + match authority { + Authority::Helper => load_helper_with(helper), + Authority::Files => load_file(), + } +} + +/// The record files' read. A test may substitute it (`READ_FOR_TEST`), which only ever stands in +/// for this store: the helper arm is read through its transport. +fn load_file() -> CanonicalRead { #[cfg(any(test, feature = "test-support"))] if let Some(read) = READ_FOR_TEST.with(|hook| hook.get()) { return read(); } - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - return load_helper(); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let store = match store() { - Ok(store) => store, - Err(error) => return CanonicalRead::Blocked(error), - }; - match store.load(RecordKey::Session) { - Ok(None) => CanonicalRead::Missing, - Ok(Some(record)) => match record.state { - RecordState::Data { payload } => CanonicalRead::Data { - revision: record.revision, - payload, - }, - RecordState::Cleared => CanonicalRead::Cleared { - revision: record.revision, - kept: super::install_preferences::load().unwrap_or_default(), - }, + let store = match store() { + Ok(store) => store, + Err(error) => return CanonicalRead::Blocked(error), + }; + match store.load(RecordKey::Session) { + Ok(None) => CanonicalRead::Missing, + Ok(Some(record)) => match record.state { + RecordState::Data { payload } => CanonicalRead::Data { + revision: record.revision, + payload, }, - Err(error) => CanonicalRead::Blocked(error), - } + RecordState::Cleared => CanonicalRead::Cleared { + revision: record.revision, + kept: super::install_preferences::load().unwrap_or_default(), + }, + }, + Err(error) => CanonicalRead::Blocked(error), } } @@ -221,10 +219,6 @@ fn helper_rejection(code: plx_os::storage::wire::ErrorCode) -> StoreError { } } -fn load_helper() -> CanonicalRead { - load_helper_with(&mut client::NativeTransport) -} - pub fn load_helper_with(transport: &mut dyn client::Transport) -> CanonicalRead { match client::load_with(transport) { Ok(HelperLoad::Missing) => CanonicalRead::Missing, @@ -286,75 +280,81 @@ fn commit(record: Record) -> CanonicalCommit { } pub fn commit_data(payload: String) -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - let session = match serde_json::from_str::(&payload) { - Ok(session) => session, - Err(_) => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }; - return commit_session(&session, false, super::SaveAuthority::Routine); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let revision = match load() { - CanonicalRead::Data { revision, .. } - | CanonicalRead::Opened { revision, .. } - | CanonicalRead::Cleared { revision, .. } - | CanonicalRead::Locked { revision, .. } - | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { - Some(revision) => revision, - None => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }, - CanonicalRead::Missing => 1, - CanonicalRead::Blocked(error) => return CanonicalCommit::Failed(error), - }; - commit(Record::data(revision, payload)) + commit_data_via(storage_authority(), &mut client::NativeTransport, payload) +} + +/// [`commit_data`] with the authority and the helper's transport as parameters. The helper takes +/// the decoded session as a routine write; the files take the payload as it is. +pub(super) fn commit_data_via( + authority: Authority, + helper: &mut dyn client::Transport, + payload: String, +) -> CanonicalCommit { + match authority { + Authority::Helper => { + let session = match serde_json::from_str::(&payload) { + Ok(session) => session, + Err(_) => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }; + commit_session_with( + &session, + false, + super::SaveAuthority::Routine, + plx_os::tv::device::info().major, + helper, + ) + } + Authority::Files => commit_data_file(payload), } } +fn commit_data_file(payload: String) -> CanonicalCommit { + let revision = match load_file() { + CanonicalRead::Data { revision, .. } + | CanonicalRead::Opened { revision, .. } + | CanonicalRead::Cleared { revision, .. } + | CanonicalRead::Locked { revision, .. } + | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { + Some(revision) => revision, + None => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }, + CanonicalRead::Missing => 1, + CanonicalRead::Blocked(error) => return CanonicalCommit::Failed(error), + }; + commit(Record::data(revision, payload)) +} + pub fn commit_cleared() -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - return commit_clear(); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let revision = match load() { - CanonicalRead::Data { revision, .. } - | CanonicalRead::Opened { revision, .. } - | CanonicalRead::Cleared { revision, .. } - | CanonicalRead::Locked { revision, .. } - | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { - Some(revision) => revision, - None => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }, - CanonicalRead::Missing => 1, - CanonicalRead::Blocked(_) => 1, - }; - commit(Record::cleared(revision)) + commit_cleared_via(storage_authority(), &mut client::NativeTransport) +} + +/// [`commit_cleared`] with the authority and the helper's transport as parameters. +pub(super) fn commit_cleared_via( + authority: Authority, + helper: &mut dyn client::Transport, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_clear_with(helper), + Authority::Files => commit_cleared_file(), } } +fn commit_cleared_file() -> CanonicalCommit { + let revision = match load_file() { + CanonicalRead::Data { revision, .. } + | CanonicalRead::Opened { revision, .. } + | CanonicalRead::Cleared { revision, .. } + | CanonicalRead::Locked { revision, .. } + | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { + Some(revision) => revision, + None => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }, + CanonicalRead::Missing => 1, + CanonicalRead::Blocked(_) => 1, + }; + commit(Record::cleared(revision)) +} + /// Exact-payload migration. The caller owns keymanager semantics and legacy cleanup; this helper /// only commits the bytes and reports whether cleanup may proceed. pub fn migrate_exact(source: &Path, payload: &[u8]) -> (CanonicalCommit, PathBuf) { @@ -372,13 +372,25 @@ pub fn migrate_exact(source: &Path, payload: &[u8]) -> (CanonicalCommit, PathBuf /// Import an already decoded migration input through the same backend used by bootstrap. pub fn migrate_session(session: &super::Session) -> CanonicalCommit { - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - { - commit_session(session, true, super::SaveAuthority::Routine) - } - #[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] - { - write_session(session, super::SaveAuthority::Routine) + migrate_session_via(storage_authority(), &mut client::NativeTransport, session) +} + +/// [`migrate_session`] with the authority and the helper's transport as parameters. Only the helper +/// distinguishes a migration from a routine write (it advances the migration ledger). +pub(super) fn migrate_session_via( + authority: Authority, + helper: &mut dyn client::Transport, + session: &super::Session, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_session_with( + session, + true, + super::SaveAuthority::Routine, + plx_os::tv::device::info().major, + helper, + ), + Authority::Files => write_session_file(session), } } @@ -754,20 +766,6 @@ fn expected(snapshot: &client::Snapshot) -> Option<(&str, state::Expected)> { Some((&snapshot.db_rev, snapshot.state.expected())) } -fn commit_session( - session: &super::Session, - migration: bool, - authority: super::SaveAuthority, -) -> CanonicalCommit { - commit_session_with( - session, - migration, - authority, - plx_os::tv::device::info().major, - &mut client::NativeTransport, - ) -} - pub fn commit_session_with( session: &super::Session, migration: bool, @@ -901,17 +899,6 @@ pub fn commit_session_with( helper_commit_for_app_with(transport, expectation, operation, mutation) } -pub fn commit_session_with_authority( - session: &super::Session, - authority: super::SaveAuthority, -) -> CanonicalCommit { - commit_session(session, false, authority) -} - -fn commit_clear() -> CanonicalCommit { - commit_clear_with(&mut client::NativeTransport) -} - pub(super) fn commit_clear_with(transport: &mut dyn client::Transport) -> CanonicalCommit { let loaded = match client::load_with(transport) { Ok(loaded) => loaded, @@ -1185,21 +1172,37 @@ mod db8_policy_tests { } /// `bootstrap()` and `cleanup_after_confirmed_clear()` must search and sweep the pre-DB8 - /// canonical JSON wrapper identically on ARM, so both funnel through this one helper rather - /// than each carrying its own `insert(0, path())`. This is callable unconditionally (it is - /// pure path arithmetic), so a host test can prove the shared assembly directly instead of - /// only trusting that the two ARM-gated call sites still agree. + /// canonical JSON wrapper identically where the helper is canonical, so both funnel through + /// this one helper rather than each carrying its own `insert(0, path())`. It is pure path + /// arithmetic, so a host test proves the shared assembly directly for either authority. Under + /// `Files` the wrapper is the store itself, so it is no migration source. + /// A television's helper keeps no app-owned rename temporaries, so there is nothing to sweep and + /// the root is left as it is; a files platform sweeps the abandoned ones its own commits left. + #[test] + fn the_helper_keeps_no_app_temporaries_and_the_files_sweep_theirs() { + let _serial = plx_base::testlock::serial(); + let root = TempPersistenceRoot::new("cleanup-temporaries"); + plx_base::paths::ensure_persistent_state_root().expect("a writable state root"); + let abandoned = root.dir.join(".session.json.new-0123456789abcdef0123456789abcdef"); + std::fs::write(&abandoned, b"temporary").unwrap(); + std::fs::set_permissions(&abandoned, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(cleanup_temporaries_for(Authority::Helper), Ok(())); + assert!(abandoned.exists(), "the helper arm sweeps nothing in the app's root"); + assert_eq!(cleanup_temporaries_for(Authority::Files), Ok(())); + assert!(!abandoned.exists(), "the files arm removes the abandoned temporary"); + } + #[test] - fn arm_candidate_assembly_puts_the_canonical_wrapper_first() { + fn the_candidates_a_platform_searches_follow_its_authority() { // `path()` reads the process-global persistent state root, which every redirecting test in // this binary moves under the lock. Two unlocked reads can straddle one of those moves, so // this takes the same lock: both reads then see one root. let _serial = plx_base::testlock::serial(); - let mut candidates = vec![PathBuf::from("/some/legacy/auth.json")]; - insert_arm_canonical_wrapper(&mut candidates); - assert_eq!(candidates[0], path()); - assert_eq!(candidates.len(), 2); - assert_eq!(candidates[1], PathBuf::from("/some/legacy/auth.json")); + let legacy = vec![PathBuf::from("/some/legacy/auth.json")]; + let helper = migration_candidates(Authority::Helper, legacy.clone()); + assert_eq!(helper, vec![path(), PathBuf::from("/some/legacy/auth.json")]); + let files = migration_candidates(Authority::Files, legacy.clone()); + assert_eq!(files, legacy, "the files platform's own store is never one of its migration sources"); } /// Point the canonical persistence root at a directory of this test's own; restore the @@ -1397,32 +1400,39 @@ pub fn write_session_timed( commit } -/// The authority-selected write used by the shared worker. ARM has exactly one authority: DB8. +/// The authority-selected write used by the shared worker. The platform has exactly one canonical +/// store at a time: the storage helper where it states one, the record files everywhere else. pub fn write_session( session: &super::Session, authority: super::SaveAuthority, ) -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - commit_session_with_authority(session, authority) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let _ = authority; - match serde_json::to_string(session) { - Ok(payload) => commit_data(payload), - Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), - } + write_session_via(storage_authority(), &mut client::NativeTransport, session, authority) +} + +/// [`write_session`] with the storage authority and the helper's transport as parameters. `save` is +/// how the caller may write ([`super::SaveAuthority`]); only the helper's protection rules read it. +pub(super) fn write_session_via( + authority: Authority, + helper: &mut dyn client::Transport, + session: &super::Session, + save: super::SaveAuthority, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_session_with( + session, + false, + save, + plx_os::tv::device::info().major, + helper, + ), + Authority::Files => write_session_file(session), + } +} + +fn write_session_file(session: &super::Session) -> CanonicalCommit { + match serde_json::to_string(session) { + Ok(payload) => commit_data_file(payload), + Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), } } @@ -1580,16 +1590,13 @@ impl MigrationStore for HelperMigration<'_> { struct FileMigration; impl MigrationStore for FileMigration { fn load(&mut self) -> CanonicalRead { - load() + load_file() } fn import(&mut self, session: &super::Session) -> CanonicalCommit { - match serde_json::to_string(session) { - Ok(payload) => commit_data(payload), - Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), - } + write_session_file(session) } fn clear(&mut self) -> CanonicalCommit { - commit_cleared() + commit_cleared_file() } } @@ -1722,13 +1729,17 @@ fn retire_exact_candidate(path: &Path, expected: &[u8]) -> bool { .is_some_and(|directory| directory.sync_all().is_ok()) } -/// The previous canonical JSON wrapper (`path()`, the pre-DB8 `session.json`) outranks older -/// bare candidates on ARM: it is a recognized migration source in its own right and must be -/// searched (on boot) and swept (on sign-out) ahead of the plain legacy files. Both call sites -/// that assemble an ARM candidate list must go through this one function so the two lists -/// cannot drift apart again. -fn insert_arm_canonical_wrapper(candidates: &mut Vec) { - candidates.insert(0, path()); +/// The migration sources a platform searches (on boot) and sweeps (on sign-out), given the legacy +/// files `base` names. Where the storage helper is canonical, the previous canonical JSON wrapper +/// (`path()`, the pre-DB8 `session.json`) outranks the older bare candidates: it is a recognized +/// migration source in its own right. Where the files are canonical it IS the store, never a +/// source. Both call sites that assemble a candidate list go through this one function so the two +/// lists cannot drift apart again. +fn migration_candidates(authority: Authority, mut base: Vec) -> Vec { + if authority == Authority::Helper { + base.insert(0, path()); + } + base } pub fn bootstrap(opener: &mut dyn LegacyOpener) -> Bootstrap { @@ -1736,32 +1747,25 @@ pub fn bootstrap(opener: &mut dyn LegacyOpener) -> Bootstrap { let candidates = plx_base::paths::session_migration_candidates(); #[cfg(any(test, feature = "test-support"))] let candidates = super::auth_paths(); - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - let mut candidates = candidates; - insert_arm_canonical_wrapper(&mut candidates); - bootstrap_with( - &mut HelperMigration { - transport: &mut client::NativeTransport, - major: plx_os::tv::device::info().major, - }, + bootstrap_via(storage_authority(), &mut client::NativeTransport, opener, candidates) +} + +/// [`bootstrap`] with the authority, the helper's transport and the legacy files `base` as +/// parameters. The canonical store is chosen here, before the loop, and never by a failed read. +pub(super) fn bootstrap_via( + authority: Authority, + helper: &mut dyn client::Transport, + opener: &mut dyn LegacyOpener, + base: Vec, +) -> Bootstrap { + let candidates = migration_candidates(authority, base); + match authority { + Authority::Helper => bootstrap_with( + &mut HelperMigration { transport: helper, major: plx_os::tv::device::info().major }, opener, &candidates, - ) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - bootstrap_with(&mut FileMigration, opener, &candidates) + ), + Authority::Files => bootstrap_with(&mut FileMigration, opener, &candidates), } } @@ -1793,24 +1797,28 @@ pub enum ClearCleanupOutcome { /// residues. Failed retirement remains visible: canonical Cleared shadows a residue only while /// the authority can answer, so a marked fallback must also be removed or neutralized. pub fn cleanup_after_confirmed_clear() -> ClearCleanupOutcome { - if !matches!(load(), CanonicalRead::Cleared { .. }) { - return ClearCleanupOutcome::AuthorityNotConfirmed; - } #[cfg(not(any(test, feature = "test-support")))] let candidates = plx_base::paths::session_migration_candidates(); #[cfg(any(test, feature = "test-support"))] let candidates = super::auth_paths(); - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - let candidates = { - let mut candidates = candidates; - insert_arm_canonical_wrapper(&mut candidates); - candidates - }; + cleanup_after_confirmed_clear_via( + storage_authority(), + &mut client::NativeTransport, + candidates, + ) +} + +/// [`cleanup_after_confirmed_clear`] with the authority, the helper's transport and the legacy +/// files `base` as parameters. +pub(super) fn cleanup_after_confirmed_clear_via( + authority: Authority, + helper: &mut dyn client::Transport, + base: Vec, +) -> ClearCleanupOutcome { + if !matches!(load_via(authority, helper), CanonicalRead::Cleared { .. }) { + return ClearCleanupOutcome::AuthorityNotConfirmed; + } + let candidates = migration_candidates(authority, base); let mut complete = super::retry_pending_retirements_locked(); for candidate in candidates { match plx_os::storage::read_owned_bytes(&candidate) { From 655bd8d6dd80a12c111269d7b3e4992e66acc168 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 16:17:54 +0300 Subject: [PATCH 3/8] Two prose claims that named the ARM cfg as plex's store fence now say what reads it `session_persistence_tests.rs` described the migration-candidate set as "plus the pre-DB8 canonical JSON wrapper on ARM", and `docs/platform-ports.md` F44 said `install_preferences::candidates` and `clear_for_erase` key on the ARM cfg and that the ARM canonical write is cfg'd out of host tests. Both are the pre-W8a state: plex reads `tv::authority::authority()`, and the helper arm is the one every host runs over a fake transport. Co-Authored-By: Claude --- docs/platform-ports.md | 8 +++++--- rust-modules/plex/src/plex/session_persistence_tests.rs | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 463d956f2..dec608a97 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -504,9 +504,11 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N - `CompletionOutcome` (`plex/src/plex/session/async_persistence.rs:112`) and `LiveWrite` are matched in `session.rs`, `session/{persistence,async_persistence,prefs/profile_prefs}.rs`, `session/src/auth/owner.rs`, `telemetry/src/telemetry/incident.rs:592-600`, `src/app/adapters/session.rs` and three test files. - - `install_preferences::candidates` (`:40`) and `clear_for_erase` (`session.rs:5341`) key on the ARM cfg, so - Tizen ARM reads `native = true`; `load` accepts `version == 1` only (`:59`) and `Saved` is - `deny_unknown_fields`. The ARM canonical write is cfg'd out of host tests (`session/persistence.rs:1400-1425`). + - `install_preferences::candidates` (`:40`) and `clear_for_erase` (`session.rs:5341`) keyed on the ARM cfg, so + Tizen ARM read `native = true` (W8a re-keyed them to `tv::authority::authority()`); `load` accepts + `version == 1` only (`:59`) and `Saved` is `deny_unknown_fields`. The ARM canonical write was cfg'd out of + host tests (`session/persistence.rs:1400-1425`); it is now the `Helper` arm of `persistence::*_via`, which every + host runs over a fake transport. - `ci/check-deps.sh`: `plex/` is in `FORK_SCOPE`, `session.rs` in `MACHINES` (`:1406-1408`): a new `cfg(test)` branch there is a `forks` line, a new static a `statics` line. `platform/` is not in `FORK_SCOPE`, and only `platform/src/tv/plane.rs` is in `MACHINES` (`:1406-1408`; the scan `find` at `:1439` lists it too). The diff --git a/rust-modules/plex/src/plex/session_persistence_tests.rs b/rust-modules/plex/src/plex/session_persistence_tests.rs index 779cfbcc6..d6925e12b 100644 --- a/rust-modules/plex/src/plex/session_persistence_tests.rs +++ b/rust-modules/plex/src/plex/session_persistence_tests.rs @@ -584,7 +584,7 @@ fn clear_under_a_redirected_legacy_fixture_never_touches_the_canonical_authority /// `signout-leaves-token-in-unswept-candidates`: `clear()` must actually reach /// `persistence::cleanup_after_confirmed_clear()` after a durable canonical commit — the step /// that retires the full recognized migration-candidate set -/// (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON wrapper on ARM), +/// (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON wrapper where the helper is canonical), /// which is a strict superset of the legacy `auth_paths()` list `clear()`'s own loop sweeps. /// /// **On the honesty of this test**: `persistence::bootstrap`/`cleanup_after_confirmed_clear` From 9914c2dec10506e551959d6469cc837d9f395aed Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 16:30:00 +0300 Subject: [PATCH 4/8] The storage authority's docs say what the helper and the files are on a television, and the order pin is exact Review of the foundation found three things the first commit got wrong or left weak. On webOS the helper is the canonical store, but the app's own files are not absent there: the session layer writes a marked fallback (`save_legacy_fallback_locked`) whenever a commit to the helper is not durable, serves it as transient state while the helper cannot answer (`read_legacy_filtered_locked`), and the legacy files an older build left are migration inputs. `tv::authority`'s module doc and the `Helper` variant said no file is ever written and a helper outage is never papered over; they now say what the code does. The platform-ports bullet follows. The order pin in `port.rs` asserted only that the install precedes `exit::entry`. It now asserts that `platform.install_services();` is `run_application`'s first non-comment statement, counts the call and `tv::install(` across every source file of the application crate (not just `app/mod.rs`), and fails when a statement is inserted above the install, when a second call is added, and when `tv::install` is called a second time. Each of those three mutations was run and fails for its own assertion. `authority.rs` and the `port.rs` test docs spoke as if a reader of the value already existed. They now state what the value says and what it is for. Co-Authored-By: Claude --- docs/platform-ports.md | 6 ++- rust-modules/os/src/tv/authority.rs | 37 +++++++++------- rust-modules/src/port.rs | 67 +++++++++++++++++++++-------- 3 files changed, 76 insertions(+), 34 deletions(-) diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 477fa0d54..49fe3eb59 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -848,8 +848,10 @@ split by who reads it (critic M4): `devcaps` parses through, `Files::NONE` for a platform with none); - `secure { seal, open, remove, mode }` (Target shape 4; until W2 `mode` is W3a's own once-set value); - `system { go_home, poll_home, deliver_toast }`; - - `storage { authority }` (W8a): `Authority::Helper` (webOS: the LS2/DB8 storage helper owns the session, the - install's preferences and the consent record) or `Authority::Files` (desktop, Tizen, a host test), read through + - `storage { authority }` (W8a): `Authority::Helper` (webOS: the LS2/DB8 storage helper is the canonical store of + the session, the install's preferences and the consent record; the app's own files there are the legacy + migration inputs and the marked fallback of a helper outage) or `Authority::Files` (desktop, Tizen, a host + test: the app's own record files are the store), read through `tv::authority::authority()`. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence layers chose their store by; the helper's wake-up (`storage::client::install_activator`) joins it after W7b; - `legacy_webos_media { sink, display_sink, uri_media }`: the Starfish, ACB and `com.webos.media` verbs (F31), diff --git a/rust-modules/os/src/tv/authority.rs b/rust-modules/os/src/tv/authority.rs index 85d8dd6a2..629a19410 100644 --- a/rust-modules/os/src/tv/authority.rs +++ b/rust-modules/os/src/tv/authority.rs @@ -1,21 +1,27 @@ //! Where the account's canonical state lives: the platform's storage helper, or plain files. //! -//! The session record, the install's preferences and the consent record each have two homes. On a -//! webOS television the LS2/DB8 storage helper owns them ([`Authority::Helper`]): the app never -//! reads or writes a file of its own for them. Everywhere else the app keeps them in files under its -//! persistent state root ([`Authority::Files`]): the desktop simulator, a host test, and a platform -//! with no helper at all (Tizen). The layers that persist these records (`plex::session`, -//! `telemetry`) choose their store from this value, once per operation, instead of from the build's -//! CPU and OS, which is what picked it before: a 32-bit ARM Linux binary is not necessarily a -//! television. +//! The session record, the install's preferences and the consent record each have one canonical +//! store, and the platform states which. On a webOS television it is the LS2/DB8 storage helper +//! ([`Authority::Helper`]). Everywhere else it is the app's own record files under its persistent +//! state root ([`Authority::Files`]): the desktop simulator, a host test, and a platform with no +//! helper at all (Tizen). //! -//! The platform states it once, as the `authority` of its [`StorageHooks`](super::StorageHooks), and -//! [`authority`] reads it. A process that installed no platform (a host test) reads +//! Under `Helper` the app's own files are not the store. They are the legacy migration inputs an +//! older build left, and the marked fallback the session layer writes when a commit to the helper is +//! not durable (a helper outage): while the helper cannot answer, that file is served as transient +//! state, and it never replaces the helper's record. +//! +//! The platform states the value once, as the `authority` of its [`StorageHooks`](super::StorageHooks), +//! and [`authority`] reads it. A process that installed no platform (a host test) reads //! [`StorageHooks::NONE`], which is `Files`, like every other group's host-test answer. A shipping -//! process must install its services before anything persists: an uninstalled television would read -//! `Files` and write a plaintext session file, which is why `run_application` installs them first +//! process has to install its services before anything persists, because an uninstalled television +//! would be told it has no helper; `run_application` installs them as its first statement //! (`port::tests` pins the order). //! +//! The value exists so that the layers that persist these records can choose their canonical store +//! from what the platform states, not from the build's CPU and OS (a 32-bit ARM Linux binary is not +//! necessarily a television). +//! //! This group is the home of the platform's other storage statements as well. The helper's wake-up //! (`storage::client::install_activator`, which `port::plex_main` installs for webOS today) belongs //! here as a later member and moves with the os lane after W7b; it is not moved yet. @@ -23,10 +29,11 @@ /// Where the account's canonical state lives. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Authority { - /// The platform's storage helper (webOS: the LS2/DB8 service). No file of the app's own holds - /// the record, and a helper that cannot answer is never papered over with one. + /// The platform's storage helper (webOS: the LS2/DB8 service) is the canonical store. The app's + /// own files are only the legacy migration inputs and the session layer's marked fallback, which + /// is written during a helper outage and is never the record. Helper, - /// Files under the app's persistent state root, written by the app itself. + /// The app's own record files under its persistent state root are the canonical store. #[default] Files, } diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 800c426a8..ec914547a 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -155,36 +155,69 @@ mod tests { use super::SERVICES; use plx_os::tv::authority::Authority; - /// The webOS table states the storage helper as the home of the session, the install's preferences - /// and the consent record. The persistence layers choose their store from this value, so a table - /// that stated anything else would move a television's account out of DB8. + /// The webOS table states the storage helper as the canonical home of the session, the install's + /// preferences and the consent record: on a television that is DB8, and a table that stated + /// `Files` would say the app's own files are. #[test] fn the_webos_table_states_the_storage_helper_as_the_authority() { assert_eq!(SERVICES.storage.authority, Authority::Helper); assert_eq!(SERVICES.secure.mode, plx_os::tv::secure::StoreMode::Durable); } - /// `run_application` installs the services before anything else runs. The authority is read by - /// whatever persists first, and an uninstalled television reads `Files` and would write a - /// plaintext session file, so the install has to come before `exit::entry` runs `enter_application`. - /// Reads the source, like `app::boot`'s `seam_order_tests`, because no host test can run the entry. + /// Every `.rs` file under the application crate's `src`, as text. + fn crate_sources() -> Vec { + fn walk(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read a source directory") { + let path = entry.expect("a directory entry").path(); + if path.is_dir() { + walk(&path, out); + } else if path.extension().is_some_and(|ext| ext == "rs") { + out.push(std::fs::read_to_string(&path).expect("read a source file")); + } + } + } + let mut out = Vec::new(); + walk(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut out); + out + } + + /// `run_application` installs the services as its first statement, before anything can read + /// them: a process that has installed none reads the host-test answers, which for the storage + /// group is `Files`, so a television that persisted ahead of its install would be told it has no + /// helper. One production install, and the only caller of `tv::install` is the `Platform` method + /// it goes through. Reads the source, like `app::boot`'s `seam_order_tests`, because no host test + /// can run the entry. #[test] - fn the_services_are_installed_before_the_application_enters() { - let source = include_str!("app/mod.rs"); - let body = source + fn the_services_are_installed_first_and_only_there() { + let body = include_str!("app/mod.rs") .split_once("fn run_application(") .expect("run_application") .1 - .split_once("\n}\n") - .expect("end of run_application") - .0; - let install = body.find("platform.install_services();").expect("run_application installs the services"); - let enter = body.find("exit::entry(").expect("run_application enters through exit::entry"); - assert!(install < enter, "install_services must run before exit::entry"); + .split_once('{') + .expect("run_application's body") + .1; + let first = body + .lines() + .map(str::trim) + .find(|line| !line.is_empty() && !line.starts_with("//")) + .expect("a first statement"); + let first = first.split_once("//").map_or(first, |(code, _)| code).trim(); + assert_eq!( + first, + concat!("platform.install_", "services();"), + "the install must be run_application's first statement" + ); + let sources = crate_sources(); + let count = |needle: &str| sources.iter().map(|text| text.matches(needle).count()).sum::(); assert_eq!( - source.matches("install_services()").count(), + count(concat!(".install_", "services()")), 1, "one production install; a second would be refused by tv and could hide a missing first" ); + assert_eq!( + count(concat!("tv::", "install(")), + 1, + "`tv::install` is called by `Platform::install_services` and nowhere else" + ); } } From 619561930414d6063a5956bb1de0c9cc24311b98 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 16:31:59 +0300 Subject: [PATCH 5/8] The plex prose says where files still stand under the storage helper Under the storage helper the persistence dispatchers never answer from the canonical record files, but session.rs keeps its marked fallback (written when a commit is not durable, served as transient while the helper is down) and the legacy migration inputs, exactly as before. The module guide and the helper-down test said no file is ever used; they now say what the dispatcher layer does and name the fallback as the one file a television writes beside DB8. The test is renamed to match: a_helper_authority_never_answers_from_the_record_files_when_ the_helper_cannot_answer. Co-Authored-By: Claude --- rust-modules/plex/src/plex/CLAUDE.md | 11 +++++++---- .../plex/src/plex/session/migration_tests.rs | 12 +++++++----- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/rust-modules/plex/src/plex/CLAUDE.md b/rust-modules/plex/src/plex/CLAUDE.md index 8292b8d0a..474eb02fd 100644 --- a/rust-modules/plex/src/plex/CLAUDE.md +++ b/rust-modules/plex/src/plex/CLAUDE.md @@ -634,10 +634,13 @@ a dead source is **absent** from Home and states itself in its own library secti `cleanup_after_confirmed_clear`, `cleanup_temporaries`) and hands it to the `*_via(authority, helper, ..)` form, so a test passes the authority it grades and, for `Helper`, a transport of its own (an in-memory `Backend` or a closure); the real `NativeTransport` is named by the public forms only, because on a Linux - host it waits out a 12 s start deadline with no helper behind it. There is no process-global override. A - helper that cannot answer is a blocked read, never a reason to use files. `clear_for_erase`, - `read_into_cache_locked` and `install_preferences::keeps_language_file` read the same value; the - telemetry sweep after a durable clear runs only under `Helper`. + host it waits out a 12 s start deadline with no helper behind it. There is no process-global override. + Under `Helper` the dispatchers never answer for a helper that cannot answer (a blocked read stays blocked, + and a legacy file is neither imported nor retired on its word); the files a television does keep beside DB8 + are `session.rs`'s own: the marked fallback `save_legacy_fallback_locked` writes when a commit is not + durable, which `read_legacy_filtered_locked` serves as transient state, and the legacy migration inputs. + `clear_for_erase`, `read_into_cache_locked` and `install_preferences::keeps_language_file` read the same + value; the telemetry sweep after a durable clear runs only under `Helper`. - **The DB8 document may not pass `MAX_LOGICAL_BYTES` (256 KiB), and per-profile memory is what grows it.** Past the cap EVERY write fails (`LogicalTooLarge`, reported as `InvalidSchema`), so `persistence::commit_session_with` measures the projected document (the os layer's own diff --git a/rust-modules/plex/src/plex/session/migration_tests.rs b/rust-modules/plex/src/plex/session/migration_tests.rs index 1e7880406..1c61a7f7a 100644 --- a/rust-modules/plex/src/plex/session/migration_tests.rs +++ b/rust-modules/plex/src/plex/session/migration_tests.rs @@ -1421,7 +1421,7 @@ fn a_helper_authority_reads_and_clears_through_the_helper_and_keeps_no_file() { assert_eq!( with_io_for_test(|| persistence::cleanup_after_confirmed_clear_via(Authority::Helper, &mut transport, Vec::new())), persistence::ClearCleanupOutcome::Confirmed); - assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "the helper arm never writes a file of the app's own"); + assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "the helper arm leaves no record file under the state root"); } /// The files arm for a platform with no helper (the desktop, a host test, Tizen): the record is the @@ -1455,10 +1455,12 @@ fn a_files_authority_keeps_the_record_in_files_and_never_asks_the_helper() { assert!(matches!(boot.state, CanonicalRead::Cleared { revision: 4, .. }), "the record the files hold is read as it is"); } -/// A helper that cannot answer is a blocked canonical store, never a licence to use files: not for a -/// read, not for a write, not for a migration, and a legacy file is neither imported nor retired. +/// At this layer a helper that cannot answer is a blocked canonical store: no read, write or +/// migration is answered from the record files, and a legacy file is neither imported nor retired. +/// (The session layer above writes its own marked fallback after a non-durable commit; that file is +/// not the record and is not exercised here.) #[test] -fn a_helper_authority_never_falls_back_to_files_when_the_helper_cannot_answer() { +fn a_helper_authority_never_answers_from_the_record_files_when_the_helper_cannot_answer() { use plx_os::storage::StoreError; let _serial = plx_base::testlock::serial(); let state = TempCanonicalState::new("authority-helper-down"); @@ -1490,5 +1492,5 @@ fn a_helper_authority_never_falls_back_to_files_when_the_helper_cannot_answer() persistence::cleanup_after_confirmed_clear_via(Authority::Helper, &mut down, vec![legacy.path.clone()]), persistence::ClearCleanupOutcome::AuthorityNotConfirmed); assert!(legacy.path.exists(), "an unconfirmed clear retires nothing"); - assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "no file of the app's own was created"); + assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "no record file was created under the state root"); } From f6eb57753fb53a564c27e861ed47f7fe7c4d2975 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 16:46:30 +0300 Subject: [PATCH 6/8] The storage authority's docs name the third file under the helper and the mode that decides first Under the storage helper a sign-out whose helper clear is not durable also writes the install-preferences file (an unmarked language.json beside a session candidate, read back into the Locked and Cleared states), so the app's own files there are three kinds, not two. And the authority is not the whole answer for the session record: secure::mode() decides it first, so under MemoryOnly (where Tizen starts) the session lives in memory and no credential store is touched, whatever the authority says. Prose only; no code changed. Co-Authored-By: Claude --- docs/platform-ports.md | 7 +++++-- rust-modules/os/src/tv/authority.rs | 26 +++++++++++++++++++------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/docs/platform-ports.md b/docs/platform-ports.md index decc16db4..e37e44a58 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -854,9 +854,12 @@ split by who reads it (critic M4): - `system { go_home, poll_home, deliver_toast }`; - `storage { authority }` (W8a): `Authority::Helper` (webOS: the LS2/DB8 storage helper is the canonical store of the session, the install's preferences and the consent record; the app's own files there are the legacy - migration inputs and the marked fallback of a helper outage) or `Authority::Files` (desktop, Tizen, a host + migration inputs, the marked fallback of a helper outage and the install-preferences file a sign-out writes + when the helper's clear is not durable) or `Authority::Files` (desktop, Tizen, a host test: the app's own record files are the store), read through - `tv::authority::authority()`. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence + `tv::authority::authority()`. `secure::mode()` decides the session record ahead of it: under `MemoryOnly` + (where Tizen starts, W9) the session lives in memory and no credential store is read or written, whatever the + authority says; only the install's own preference file persists. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence layers chose their store by; the helper's wake-up (`storage::client::install_activator`) joins it after W7b; - `legacy_webos_media { sink, display_sink, uri_media }`: the Starfish, ACB and `com.webos.media` verbs (F31), named for what they are (critic M3). Every hook is required (Decision 2, C): a platform states each field, diff --git a/rust-modules/os/src/tv/authority.rs b/rust-modules/os/src/tv/authority.rs index 629a19410..7d865f24d 100644 --- a/rust-modules/os/src/tv/authority.rs +++ b/rust-modules/os/src/tv/authority.rs @@ -6,10 +6,20 @@ //! state root ([`Authority::Files`]): the desktop simulator, a host test, and a platform with no //! helper at all (Tizen). //! -//! Under `Helper` the app's own files are not the store. They are the legacy migration inputs an -//! older build left, and the marked fallback the session layer writes when a commit to the helper is -//! not durable (a helper outage): while the helper cannot answer, that file is served as transient -//! state, and it never replaces the helper's record. +//! The authority is not the whole answer for the session record: the platform's persistence mode +//! ([`secure::mode()`](super::secure::mode)) decides it first. Under `StoreMode::MemoryOnly`, where +//! Tizen starts (W9), the session lives in memory and no credential store is read or written, +//! whatever the authority says; only the install's own preference file (client id, language and +//! Interface resolution) persists. +//! +//! Under `Helper` the app's own files are not the store. Three kinds remain: +//! - the legacy migration inputs an older build left; +//! - the marked fallback the session layer writes when a commit to the helper is not durable (a +//! helper outage): while the helper cannot answer, that file is served as transient state, and it +//! never replaces the helper's record; +//! - the install-preferences file a sign-out writes when the helper's clear is not durable +//! (`install_preferences::save`): an unmarked `….language.json` file beside a session candidate, which +//! `install_preferences::load` reads back into the `Locked` and `Cleared` states. //! //! The platform states the value once, as the `authority` of its [`StorageHooks`](super::StorageHooks), //! and [`authority`] reads it. A process that installed no platform (a host test) reads @@ -30,10 +40,12 @@ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Authority { /// The platform's storage helper (webOS: the LS2/DB8 service) is the canonical store. The app's - /// own files are only the legacy migration inputs and the session layer's marked fallback, which - /// is written during a helper outage and is never the record. + /// own files are only the legacy migration inputs, the session layer's marked fallback (written + /// during a helper outage, never the record) and the install-preferences file a sign-out writes + /// when the helper's clear is not durable. Helper, - /// The app's own record files under its persistent state root are the canonical store. + /// The app's own record files under its persistent state root are the canonical store. A process + /// in `StoreMode::MemoryOnly` still keeps the session record in memory (see the module doc). #[default] Files, } From 41b53e35db74e2e6c0b8b43eed58344b30145e9b Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 16:46:48 +0300 Subject: [PATCH 7/8] The plex guide lists the three files a television keeps beside DB8 and the mode read before the authority The guide's storage-authority bullet named the marked fallback and the legacy migration inputs. clear_for_erase also writes the install-preferences file when a sign-out's helper clear is not durable, and secure::mode()'s MemoryOnly is read before the authority; both are said now, to match the authority's own docs. Co-Authored-By: Claude --- rust-modules/plex/src/plex/CLAUDE.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/rust-modules/plex/src/plex/CLAUDE.md b/rust-modules/plex/src/plex/CLAUDE.md index 474eb02fd..7d38f2115 100644 --- a/rust-modules/plex/src/plex/CLAUDE.md +++ b/rust-modules/plex/src/plex/CLAUDE.md @@ -638,7 +638,10 @@ a dead source is **absent** from Home and states itself in its own library secti Under `Helper` the dispatchers never answer for a helper that cannot answer (a blocked read stays blocked, and a legacy file is neither imported nor retired on its word); the files a television does keep beside DB8 are `session.rs`'s own: the marked fallback `save_legacy_fallback_locked` writes when a commit is not - durable, which `read_legacy_filtered_locked` serves as transient state, and the legacy migration inputs. + durable, which `read_legacy_filtered_locked` serves as transient state, the legacy migration inputs, and the + install-preferences file (`install_preferences::save`, an unmarked `….language.json` beside a session + candidate) that `clear_for_erase` writes when a sign-out's helper clear is not durable. `secure::mode()`'s + `MemoryOnly` is read before the authority: it holds the session in memory and touches no credential store. `clear_for_erase`, `read_into_cache_locked` and `install_preferences::keeps_language_file` read the same value; the telemetry sweep after a durable clear runs only under `Helper`. - **The DB8 document may not pass `MAX_LOGICAL_BYTES` (256 KiB), and per-profile memory is what From a637194424f62587fa5e0333d973f0c0b6f4e0b3 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 17:23:10 +0300 Subject: [PATCH 8/8] The persistence prose names every site that reaches for the helper's real transport, and the test docs sit on their tests The module doc and the plex guide said NativeTransport is only ever named by the dispatchers' public forms. Two helpers with no _via seam name it too: reset_cleared_language(), which clear_for_erase calls under the storage helper and which only a device exercises, and helper_commit, which no longer has a caller in this crate. Both sentences now say so. The paragraph about the shared candidate assembly had been left above the temporaries test; it is back on the_candidates_a_platform_searches_follow_its_authority, and the temporaries test carries its own sentence. base::paths::persistent_state_root's doc said "the canonical ARM adapter uses helper-owned DB8"; the choice is the platform's statement, so it says that. Prose only; no code changed. Co-Authored-By: Claude --- rust-modules/base/src/paths.rs | 7 +++++-- rust-modules/plex/src/plex/CLAUDE.md | 6 ++++-- rust-modules/plex/src/plex/session/persistence.rs | 14 ++++++++------ 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/rust-modules/base/src/paths.rs b/rust-modules/base/src/paths.rs index b38fd88eb..8c93833ab 100644 --- a/rust-modules/base/src/paths.rs +++ b/rust-modules/base/src/paths.rs @@ -1336,8 +1336,11 @@ mod tests { } } -/// Legacy JSON/host-simulator persistence root. The canonical ARM adapter uses helper-owned DB8; -/// this path exists for old-record migration and for host tests that must never touch the checkout. +/// Legacy JSON/host-simulator persistence root. Where the platform states the storage helper as the +/// canonical store (a webOS television, `plx_os::tv::authority`) the canonical record is +/// helper-owned DB8; where it states plain files (the desktop simulator) the canonical record files +/// are kept here. This path also exists for old-record migration and for host tests that must never +/// touch the checkout. /// /// **Test builds never resolve this to the machine-wide runtime dir by accident.** A test that /// calls [`redirect_persistent_state_root_for_test`] gets the directory it asked for; a test that diff --git a/rust-modules/plex/src/plex/CLAUDE.md b/rust-modules/plex/src/plex/CLAUDE.md index 7d38f2115..a5f97c54d 100644 --- a/rust-modules/plex/src/plex/CLAUDE.md +++ b/rust-modules/plex/src/plex/CLAUDE.md @@ -633,8 +633,10 @@ a dead source is **absent** from Home and states itself in its own library secti public call (`load`, `commit_data`, `commit_cleared`, `write_session`, `migrate_session`, `bootstrap`, `cleanup_after_confirmed_clear`, `cleanup_temporaries`) and hands it to the `*_via(authority, helper, ..)` form, so a test passes the authority it grades and, for `Helper`, a transport of its own (an in-memory - `Backend` or a closure); the real `NativeTransport` is named by the public forms only, because on a Linux - host it waits out a 12 s start deadline with no helper behind it. There is no process-global override. + `Backend` or a closure); the real `NativeTransport` is named by those public forms and by two helpers + with no `_via` seam (`reset_cleared_language()`, which `clear_for_erase` calls under `Helper` and which is + device-only, and `helper_commit`, which has no caller here), because on a Linux host it waits out a 12 s + start deadline with no helper behind it. There is no process-global override. Under `Helper` the dispatchers never answer for a helper that cannot answer (a blocked read stays blocked, and a legacy file is neither imported nor retired on its word); the files a television does keep beside DB8 are `session.rs`'s own: the marked fallback `save_legacy_fallback_locked` writes when a commit is not diff --git a/rust-modules/plex/src/plex/session/persistence.rs b/rust-modules/plex/src/plex/session/persistence.rs index 5398fa4d1..249a105b5 100644 --- a/rust-modules/plex/src/plex/session/persistence.rs +++ b/rust-modules/plex/src/plex/session/persistence.rs @@ -10,7 +10,9 @@ //! call, in its public form, and hands it to a `*_via(authority, helper, ..)` form that takes the //! authority and the helper's transport as parameters, so a host test grades the helper arm with a //! fake transport and the files arm with a transport that fails the test if it is touched. The -//! helper's real transport (`NativeTransport`) is only ever named by the public forms. +//! helper's real transport (`NativeTransport`) is named by the dispatchers' public forms and by +//! two helpers that have no `_via` seam: `reset_cleared_language()`, which `clear_for_erase` calls +//! under `Helper` (device-only), and `helper_commit`, which has no caller in this crate. use plx_os::storage::{ CommitReceipt, CommitStage, Record, RecordKey, RecordState, RecordStore, StoreError, @@ -1171,11 +1173,6 @@ mod db8_policy_tests { let _ = std::fs::remove_dir_all(root); } - /// `bootstrap()` and `cleanup_after_confirmed_clear()` must search and sweep the pre-DB8 - /// canonical JSON wrapper identically where the helper is canonical, so both funnel through - /// this one helper rather than each carrying its own `insert(0, path())`. It is pure path - /// arithmetic, so a host test proves the shared assembly directly for either authority. Under - /// `Files` the wrapper is the store itself, so it is no migration source. /// A television's helper keeps no app-owned rename temporaries, so there is nothing to sweep and /// the root is left as it is; a files platform sweeps the abandoned ones its own commits left. #[test] @@ -1192,6 +1189,11 @@ mod db8_policy_tests { assert!(!abandoned.exists(), "the files arm removes the abandoned temporary"); } + /// `bootstrap()` and `cleanup_after_confirmed_clear()` must search and sweep the pre-DB8 + /// canonical JSON wrapper identically where the helper is canonical, so both funnel through + /// this one helper rather than each carrying its own `insert(0, path())`. It is pure path + /// arithmetic, so a host test proves the shared assembly directly for either authority. Under + /// `Files` the wrapper is the store itself, so it is no migration source. #[test] fn the_candidates_a_platform_searches_follow_its_authority() { // `path()` reads the process-global persistent state root, which every redirecting test in