diff --git a/ci/allow/forks/session.txt b/ci/allow/forks/session.txt index 523181ea18..49cdab2347 100644 --- a/ci/allow/forks/session.txt +++ b/ci/allow/forks/session.txt @@ -1,8 +1,7 @@ -# count: 3 +# count: 2 # Test/production forks (docs/sans-io.md), area `session`: 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`. # The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. rust-modules/session/src/auth.rs::admit -rust-modules/session/src/auth/owner.rs::replace_publication rust-modules/session/src/auth/scripted.rs::signinfail_spec diff --git a/ci/allow/globals/data-metadata.txt b/ci/allow/globals/data-metadata.txt index e152731a01..3211ac2b3b 100644 --- a/ci/allow/globals/data-metadata.txt +++ b/ci/allow/globals/data-metadata.txt @@ -1,11 +1,5 @@ -# count: 5 +# count: 0 # Process-global reads inside machines (docs/sans-io.md), area `data-metadata`: one line per production read of a registry in a machine — # (the spellings are ci/check-deps.sh's `globals` rule) — keyed `::::`. # A machine reads no registry: the value arrives in an event or an argument. Spec: ci/check-deps.sh `globals`. # The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. - -rust-modules/data/src/metadata.rs::pump_alt_sources_with_library::server_facts_gen -rust-modules/data/src/metadata.rs::pump_alt_sources_with_library::server_roster_gen -rust-modules/data/src/metadata.rs::pump_detail_with_gate::tape::active -rust-modules/data/src/metadata.rs::request_alt_sources::server_ids -rust-modules/data/src/metadata.rs::request_alt_sources::server_roster_gen diff --git a/ci/allow/globals/data-person.txt b/ci/allow/globals/data-person.txt index 13d91d1fa7..c797378c12 100644 --- a/ci/allow/globals/data-person.txt +++ b/ci/allow/globals/data-person.txt @@ -1,16 +1,2 @@ -# count: 11 -# Process-global reads inside machines (docs/sans-io.md), area `data-person`: one line per production read of a registry in a machine — -# (the spellings are ci/check-deps.sh's `globals` rule) — keyed `::::`. -# A machine reads no registry: the value arrives in an event or an argument. Spec: ci/check-deps.sh `globals`. -# The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. -rust-modules/data/src/person.rs::maybe_spawn::session::peek_settled -rust-modules/data/src/person.rs::maybe_spawn::tape::active -rust-modules/data/src/person.rs::open::server_roster_gen -rust-modules/data/src/person.rs::open::session::peek_settled -rust-modules/data/src/person.rs::open::tape::active -rust-modules/data/src/person.rs::open::tape::active -rust-modules/data/src/person.rs::pump_with_gate::session::peek_settled -rust-modules/data/src/person.rs::pump_with_gate::tape::active -rust-modules/data/src/person.rs::seed_dev_credits::tape::active -rust-modules/data/src/person.rs::sources::server_ids -rust-modules/data/src/person.rs::sync_roster::server_roster_gen +# count: 0 +# Person receives its complete registered-slot roster, session, control/provider policy and dev seeds as PersonInput. diff --git a/ci/allow/globals/data-pms.txt b/ci/allow/globals/data-pms.txt index 8e39bf5d14..3f16951510 100644 --- a/ci/allow/globals/data-pms.txt +++ b/ci/allow/globals/data-pms.txt @@ -1,8 +1,5 @@ -# count: 3 +# count: 0 # Process-global reads inside machines (docs/sans-io.md), area `data-pms`: one line per production read of a registry in a machine — # (the spellings are ci/check-deps.sh's `globals` rule) — keyed `::::`. # A machine reads no registry: the value arrives in an event or an argument. Spec: ci/check-deps.sh `globals`. # The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. -rust-modules/data/src/pms.rs::facts_key::server_facts_gen -rust-modules/data/src/pms.rs::roster_key_with_scope::server_roster_gen -rust-modules/data/src/pms.rs::roster_with_scope::server_ids diff --git a/ci/allow/globals/data-search.txt b/ci/allow/globals/data-search.txt index fd9f077580..193225f8e5 100644 --- a/ci/allow/globals/data-search.txt +++ b/ci/allow/globals/data-search.txt @@ -1,19 +1,5 @@ -# count: 14 +# count: 0 # Process-global reads inside machines (docs/sans-io.md), area `data-search`: one line per production read of a registry in a machine — # (the spellings are ci/check-deps.sh's `globals` rule) — keyed `::::`. # A machine reads no registry: the value arrives in an event or an argument. Spec: ci/check-deps.sh `globals`. # The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. -rust-modules/data/src/search.rs::pump_with_optional_directory::server_roster_gen -rust-modules/data/src/search.rs::reset::server_roster_gen -rust-modules/data/src/search.rs::run_with_optional_directory::session::current_gen -rust-modules/data/src/search.rs::slots::server_ids -rust-modules/data/src/search/recents.rs::with_store::session::current_gen -rust-modules/data/src/search/recents.rs::with_store::session::peek_settled -rust-modules/data/src/search/scope.rs::build::server_ids -rust-modules/data/src/search/scope.rs::build::server_ids -rust-modules/data/src/search/scope.rs::build_with_directory::server_ids -rust-modules/data/src/search/scope.rs::build_with_directory::server_ids -rust-modules/data/src/search/scope.rs::read_registry_key::server_facts_gen -rust-modules/data/src/search/scope.rs::read_registry_key::server_ids -rust-modules/data/src/search/scope.rs::read_registry_key::server_roster_gen -rust-modules/data/src/search/scope.rs::read_registry_key::session::current_gen diff --git a/ci/allow/globals/data-viewstate.txt b/ci/allow/globals/data-viewstate.txt index 590de609b1..67da882cc4 100644 --- a/ci/allow/globals/data-viewstate.txt +++ b/ci/allow/globals/data-viewstate.txt @@ -1,7 +1,5 @@ -# count: 2 +# count: 0 # Process-global reads inside machines (docs/sans-io.md), area `data-viewstate`: one line per production read of a registry in a machine — # (the spellings are ci/check-deps.sh's `globals` rule) — keyed `::::`. # A machine reads no registry: the value arrives in an event or an argument. Spec: ci/check-deps.sh `globals`. # The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. -rust-modules/data/src/viewstate.rs::fan_out::server_ids -rust-modules/data/src/viewstate.rs::fan_out_origin_watched::server_ids diff --git a/ci/allow/globals/data-watchlist.txt b/ci/allow/globals/data-watchlist.txt index 4edfc56b88..c43623e91e 100644 --- a/ci/allow/globals/data-watchlist.txt +++ b/ci/allow/globals/data-watchlist.txt @@ -1,12 +1,5 @@ -# count: 7 +# count: 0 # Process-global reads inside machines (docs/sans-io.md), area `data-watchlist`: one line per production read of a registry in a machine — # (the spellings are ci/check-deps.sh's `globals` rule) — keyed `::::`. # A machine reads no registry: the value arrives in an event or an argument. Spec: ci/check-deps.sh `globals`. # The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. -rust-modules/data/src/watchlist.rs::copy_rank::current_server -rust-modules/data/src/watchlist.rs::facts_gen::server_facts_gen -rust-modules/data/src/watchlist.rs::find::client_for -rust-modules/data/src/watchlist.rs::guid_of::client_for -rust-modules/data/src/watchlist.rs::reachable::server_probe_result -rust-modules/data/src/watchlist.rs::roster::server_ids -rust-modules/data/src/watchlist.rs::roster_gen::server_roster_gen diff --git a/ci/allow/globals/screens.txt b/ci/allow/globals/screens.txt index 14e1b6cf17..280a7b2d3c 100644 --- a/ci/allow/globals/screens.txt +++ b/ci/allow/globals/screens.txt @@ -1,23 +1,5 @@ -# count: 18 +# count: 0 # Process-global reads inside machines (docs/sans-io.md), area `screens`: one line per production read of a registry in a machine — # (the spellings are ci/check-deps.sh's `globals` rule) — keyed `::::`. # A machine reads no registry: the value arrives in an event or an argument. Spec: ci/check-deps.sh `globals`. # The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. -rust-modules/screens/src/account_menu.rs::build::session::peek_settled -rust-modules/screens/src/clock_readout.rs::refresh::keypin::blocked_for -rust-modules/screens/src/clock_readout.rs::refresh::keypin::revision -rust-modules/screens/src/home/mod.rs::tick::client_for -rust-modules/screens/src/home/mod.rs::tick::current_server -rust-modules/screens/src/library/status.rs::watch_readout::client_for -rust-modules/screens/src/plaintext_question.rs::refresh::grant::offers -rust-modules/screens/src/preferences.rs::now::current_snapshot -rust-modules/screens/src/preferences.rs::now::session::peek -rust-modules/screens/src/preferences.rs::resolve_value::session::peek -rust-modules/screens/src/preferences.rs::step::session::current_gen -rust-modules/screens/src/preferences/picker.rs::durable::peek -rust-modules/screens/src/profiles.rs::avatar_art::current_server -rust-modules/screens/src/settings.rs::plaintext_inputs::grant::offers -rust-modules/screens/src/settings.rs::plaintext_inputs::grant::offers -rust-modules/screens/src/settings.rs::rebuild::session::peek_settled -rust-modules/screens/src/settings.rs::step::session::peek_settled -rust-modules/screens/src/settings.rs::step::session::peek_settled diff --git a/ci/allow/workers/data-watchlist.txt b/ci/allow/workers/data-watchlist.txt index 34381721e8..3a6d7b0852 100644 --- a/ci/allow/workers/data-watchlist.txt +++ b/ci/allow/workers/data-watchlist.txt @@ -1,6 +1,5 @@ -# count: 1 +# count: 0 # Worker starts inside machines (docs/sans-io.md), area `data-watchlist`: one line per production call that starts a worker in a machine — # `task::spawn`, `spawn_small*`, `spawn_off_frame*`, `storage_worker::submit`, `submit_retained`, a command worker's `.submit_ticket` — keyed `::::`. # A machine starts no worker: its work leaves as a typed effect the app's runners execute, and the result returns as one addressed event. Spec: ci/check-deps.sh `workers`. # The gate compares this list to the tree as an exact multiset: a new site fails it, and so does a line whose site is gone, so it only shrinks. A migration lands by deleting its lines; do not add one to make a new site pass. -rust-modules/data/src/stores/watchlist.rs::spawn_worker::spawn_small diff --git a/ci/check-deps.sh b/ci/check-deps.sh index fdcf70d436..e249d40688 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -620,22 +620,8 @@ done <<< "$libm_lines" if [ "$libm_bad" -eq 0 ]; then ok "libm"; else fail "libm: $libm_bad line(s) outside ci/allow/libm.txt"; fi gate ticks 'SDL_GetTicks\(' "$SRC" "$SRC_BASE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" -# wall (widened phase 12, D4): the scope grows from ui/+app/+route/plan.rs to also cover -# screens/ and stores/ (screens/player/ is a subdirectory of screens/ and so already -# included) — every screen migrated out of ui/ carries the same "instrument only" -# rule its old home had. Re-verified clean on 2026-09-10 with no new violation. -# wall (widened Sans-IO P1, 2026-10-24): also plex/session.rs and the session owner files -# (session/src/auth/owner*.rs). session.rs's peek is a pure read and its refresh is the owner's -# `RefreshCache` effect, so a clock read there is an instrument or a defect; the write timing -# lives in persistence::write_session_timed, an IO body outside this scan. -# wall (widened Sans-IO store lane, Collection, 2026-10-24): also data/src/collection.rs, whose step emits its request as a store job and starts nothing, so a clock read there is an instrument or a defect (no hit when it joined). -# wall (widened Sans-IO lifecycle PR B, 2026-10-24): also media/src/player/lifecycle.rs, the foreground machine, once its drivers (which carry `CycleScope::enter`) became player/foreground.rs. `step` is a function of (state, event) and the pause it parks with arrives on the event, so a clock read there is an instrument or a defect (no hit when it joined). -# wall (widened Sans-IO store lane, subtitle search, 2026-10-24): also data/src/subsearch.rs, whose step emits its request as a store job and starts nothing, so a clock read there is an instrument or a defect (no hit when it joined; stores/viewreconcile.rs is already inside data/src/stores). -# wall (widened Sans-IO store lane, Browse section hubs, 2026-10-24): also data/src/browse/section_hubs.rs, whose steps emit their reads as store jobs and start nothing, so a clock read there is an instrument or a defect (no hit when it joined; the rest of browse/ is not in scope yet, its directory and page reads still start their own workers). -# wall (widened Sans-IO store lane, Search, 2026-10-24): also data/src/search.rs and data/src/search/, whose step emits its fetches as store jobs and starts nothing (its debounce and backoff count the `dt` the pump is handed), so a clock read there is an instrument or a defect (no hit when they joined). -# wall (widened Sans-IO store lane, Browse directory and page reads, 2026-10-25): also data/src/browse/listing_jobs.rs, the requests, ports and completion paths of the directory and listing-page reads whose steps now emit them as store jobs, so a clock read there is an instrument or a defect (no hit when it joined; the rest of browse/ is not in scope yet, its source reads and pins still read the registry and the roster). -# wall (widened Sans-IO store lane, Browse source discovery, 2026-10-28): also data/src/browse/discovery_job.rs, the request, port and completion path of the source discovery whose step now emits it as a store job, so a clock read there is an instrument or a defect (no hit when it joined; the rest of browse/ is not in scope yet). -gate wall '(Instant::now|SystemTime::now|\.elapsed\(\))' "$SRC_UI" "$SRC_MACHINE" "$SRC_APPKIT" "$SRC/app" "$SRC_MEDIA/route/backend_policy.rs" "$SRC_MEDIA/route/plan.rs" "$SRC_MEDIA/route/plan_memory.rs" "$SRC_SCREENS" "$SRC_DATA/stores" "$SRC_PLEX/plex/session.rs" "$SRC_SESSION"/auth/owner*.rs "$SRC_DATA/collection.rs" "$SRC_DATA/subsearch.rs" "$SRC_DATA/search.rs" "$SRC_DATA/search" "$SRC_DATA/browse/section_hubs.rs" "$SRC_DATA/browse/listing_jobs.rs" "$SRC_DATA/browse/discovery_job.rs" "$SRC_MEDIA/player/lifecycle.rs" +# Every data/session module is logic unless its exact reviewed IO/instrument file is in ports.ini. +if python3 ci/check-ports.py; then ok "wall"; else fail "wall: outside exact ci/ports.ini files"; fi if grep -rnE 'fp-contract|fast-math|\+fma' rust-modules/Cargo.toml rust-modules/build.rs rust-modules/net/Cargo.toml rust-modules/plex/Cargo.toml rust-modules/telemetry/Cargo.toml rust-modules/data/Cargo.toml rust-modules/session/Cargo.toml rust-modules/media/Cargo.toml rust-modules/appkit/Cargo.toml rust-modules/screens/Cargo.toml rust-modules/platform/Cargo.toml rust-modules/platform/build.rs rust-modules/gfx/Cargo.toml rust-modules/gfx/build.rs rust-modules/ui/Cargo.toml rust-modules/ui/build.rs rust-modules/appkit/build.rs rust-modules/screens/build.rs rust-modules/storage/Cargo.toml rust-modules/storage/build.rs rust-modules/.cargo Makefile 2>/dev/null | grep -v '^[[:space:]]*#'; then fail "fpflags: a floating-point contraction flag is set (spec §4.2 assumes none)" @@ -1047,7 +1033,7 @@ while IFS= read -r f; do if ! allowed threads "$f"; then echo " $f:$line"; threads_bad=$((threads_bad+1)); fi done < <(awk ' skip>0 { n=gsub(/\{/,"{"); m=gsub(/\}/,"}"); depth+=n-m; if (depth<=0) skip=0; prev=$0; next } - prev ~ /^[[:space:]]*#\[cfg\((test|any\(test, feature = "test-support"\))\)\][[:space:]]*$/ && /^[[:space:]]*mod / { skip=1; depth=gsub(/\{/,"{")-gsub(/\}/,"}"); if (depth<=0) skip=0; prev=$0; next } + prev ~ /^[[:space:]]*#\[cfg\((test|any\(test, feature = "test-support"\))\)\][[:space:]]*$/ && /^[[:space:]]*(pub(\([^)]*\))?[[:space:]]+)?mod[[:space:]]/ { skip=1; depth=gsub(/\{/,"{")-gsub(/\}/,"}"); if (depth<=0) skip=0; prev=$0; next } { print NR":"$0; prev=$0 }' "$f" | grep -E "$pat" | grep -vE '^[0-9]+:\s*//' || true) # ...over the files that spell `spawn(` at all — a superset of both matched spellings, and the `awk` # below only drops `#[cfg(test)] mod` blocks, so the count is unchanged. @@ -1245,7 +1231,7 @@ fork_scope_re=$(scope_re "${FORK_SCOPE[@]}") # has a line that could hold a site of that rule, and ci/ledger.awk then decides what is really one; a # file the pattern misses cannot hold one. W and G read the machines, F the fork scope. workers_pat='spawn_small|spawn_off_frame|submit_retained|submit_ticket|task::(spawn|\{|\*)|storage_worker::(submit|\{|\*)|(task|storage_worker)[[:space:]]+as[[:space:]]' -globals_pat='client_for|current_server|current_snapshot|keypin::(revision|blocked_for|\{|\*)|session::(peek|current_gen|\{|\*)|grant::(offers|\{|\*)|(^|[^A-Za-z0-9_])transport::(viewer_paused|\{|\*)|(^|[^A-Za-z0-9_])preview::(paused|\{|\*)|player::TX|devcaps::(caps|\{|\*)|is_dp_audio|(^|[^A-Za-z0-9_])tape::(active|\{|\*)|(^|[^A-Za-z0-9_])(sidecar|ass_source)::(takes_colour|selected|\{|\*)|server_ids|server_roster_gen|server_facts_gen|server_probe_result|peek_settled|(session|keypin|grant|player|transport|preview|devcaps|tape|sidecar|ass_source|caps|is_dp_audio|is_dp_audio_track|peek|peek_settled|current_gen|revision|blocked_for|offers|paused|viewer_paused|TX|server_ids|server_roster_gen|server_facts_gen|server_probe_result)[[:space:]]+as[[:space:]]' +globals_pat='client_for|current_server|current_snapshot|keypin::(revision|blocked_for|\{|\*)|session::(peek|current_gen|screen_input_revision|\{|\*)|grant::(offers|\{|\*)|(^|[^A-Za-z0-9_])transport::(viewer_paused|\{|\*)|(^|[^A-Za-z0-9_])preview::(paused|\{|\*)|player::TX|devcaps::(caps|\{|\*)|is_dp_audio|(^|[^A-Za-z0-9_])tape::(active|\{|\*)|(^|[^A-Za-z0-9_])(sidecar|ass_source)::(takes_colour|selected|\{|\*)|server_ids|server_roster_gen|server_facts_gen|server_probe_result|peek_settled|screen_input_revision|(session|keypin|grant|player|transport|preview|devcaps|tape|sidecar|ass_source|caps|is_dp_audio|is_dp_audio_track|peek|peek_settled|current_gen|screen_input_revision|revision|blocked_for|offers|paused|viewer_paused|TX|server_ids|server_roster_gen|server_facts_gen|server_probe_result)[[:space:]]+as[[:space:]]' # a cfg line: one with `test` on it, or an attribute / `cfg!` that opens on one line and closes on a later # one, where `test` may sit on the second. A line that is a test-only attribute outright — `#[cfg(test)]`, # `#[cfg(any(test, feature = "test-support"))]`, or an `all(, )` of them — is no @@ -1346,10 +1332,10 @@ globals_sites=$( { ledger_candidates G printf '%s\n' rust-modules/plex/src/plex/session.rs "$SRC_MEDIA/player/lifecycle.rs"; } \ | LG_MODE=call LG_KEYSPELL=1 LG_USE_OK=1 LG_REF_USE_ONLY=1 \ - LG_SITE='(^|[^A-Za-z0-9_.])(client_for|current_server|current_snapshot|keypin::revision|keypin::blocked_for|session::peek|session::peek_settled|session::current_gen|grant::offers|transport::viewer_paused|preview::paused|devcaps::caps|is_dp_audio_track|is_dp_audio|tape::active|sidecar::takes_colour|sidecar::selected|ass_source::takes_colour|ass_source::selected|server_ids|server_roster_gen|server_facts_gen|server_probe_result|peek_settled)([^A-Za-z0-9_]|$)' \ - LG_DEF='fn[[:space:]]+(client_for|current_server|current_snapshot|peek|peek_settled|current_gen|revision|blocked_for|offers|paused|viewer_paused|caps|is_dp_audio|is_dp_audio_track|active|server_ids|server_roster_gen|server_facts_gen|server_probe_result)[[:space:]]*[(<]' \ - LG_REF='(^|[^A-Za-z0-9_])(client_for|current_server|current_snapshot|peek|peek_settled|current_gen|revision|blocked_for|offers|paused|viewer_paused|caps|is_dp_audio|is_dp_audio_track|server_ids|server_roster_gen|server_facts_gen|server_probe_result|tape::active|TX|session|keypin|grant|player|transport|preview|devcaps|tape|sidecar|ass_source)[[:space:]]+as[[:space:]]|(^|[^A-Za-z0-9_])tape::\{([^}]*[^A-Za-z0-9_])?active[[:space:]]+as[[:space:]]|(^|[^A-Za-z0-9_])(sidecar|ass_source)::\{([^}]*[^A-Za-z0-9_])?(takes_colour|selected)[[:space:]]+as[[:space:]]' \ - LG_BARE='session::(peek([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?peek([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])peek([^A-Za-z0-9_]|$);;keypin::(revision([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?revision([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])revision([^A-Za-z0-9_]|$);;keypin::(blocked_for([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?blocked_for([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])blocked_for([^A-Za-z0-9_]|$);;grant::(offers([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?offers([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])offers([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])transport::(viewer_paused([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?viewer_paused([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])viewer_paused([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])preview::(paused([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?paused([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])paused([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])devcaps::(caps([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?caps([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])caps[[:space:]]*\(;;(^|[^A-Za-z0-9_])(plex|transcoder)::(is_dp_audio([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?is_dp_audio([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])is_dp_audio([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])(plex|transcoder)::(is_dp_audio_track([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?is_dp_audio_track([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])is_dp_audio_track([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])session::(current_gen([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?current_gen([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])current_gen[[:space:]]*\(;;(^|[^A-Za-z0-9_])tape::(active([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?active([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])active[[:space:]]*\(;;(^|[^A-Za-z0-9_])(sidecar|ass_source)::(selected([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?selected([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])selected[[:space:]]*\(;;(^|[^A-Za-z0-9_])(sidecar|ass_source)::(takes_colour([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?takes_colour([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])takes_colour[[:space:]]*\(' \ + LG_SITE='(^|[^A-Za-z0-9_.])(client_for|current_server|current_snapshot|keypin::revision|keypin::blocked_for|session::peek|session::peek_settled|session::current_gen|session::screen_input_revision|grant::offers|transport::viewer_paused|preview::paused|devcaps::caps|is_dp_audio_track|is_dp_audio|tape::active|sidecar::takes_colour|sidecar::selected|ass_source::takes_colour|ass_source::selected|server_ids|server_roster_gen|server_facts_gen|server_probe_result|peek_settled|screen_input_revision)([^A-Za-z0-9_]|$)' \ + LG_DEF='fn[[:space:]]+(client_for|current_server|current_snapshot|peek|peek_settled|current_gen|screen_input_revision|revision|blocked_for|offers|paused|viewer_paused|caps|is_dp_audio|is_dp_audio_track|active|server_ids|server_roster_gen|server_facts_gen|server_probe_result)[[:space:]]*[(<]' \ + LG_REF='(^|[^A-Za-z0-9_])(client_for|current_server|current_snapshot|peek|peek_settled|current_gen|screen_input_revision|revision|blocked_for|offers|paused|viewer_paused|caps|is_dp_audio|is_dp_audio_track|server_ids|server_roster_gen|server_facts_gen|server_probe_result|tape::active|TX|session|keypin|grant|player|transport|preview|devcaps|tape|sidecar|ass_source)[[:space:]]+as[[:space:]]|(^|[^A-Za-z0-9_])tape::\{([^}]*[^A-Za-z0-9_])?active[[:space:]]+as[[:space:]]|(^|[^A-Za-z0-9_])(sidecar|ass_source)::\{([^}]*[^A-Za-z0-9_])?(takes_colour|selected)[[:space:]]+as[[:space:]]' \ + LG_BARE='session::(peek([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?peek([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])peek([^A-Za-z0-9_]|$);;keypin::(revision([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?revision([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])revision([^A-Za-z0-9_]|$);;keypin::(blocked_for([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?blocked_for([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])blocked_for([^A-Za-z0-9_]|$);;grant::(offers([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?offers([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])offers([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])transport::(viewer_paused([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?viewer_paused([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])viewer_paused([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])preview::(paused([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?paused([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])paused([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])devcaps::(caps([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?caps([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])caps[[:space:]]*\(;;(^|[^A-Za-z0-9_])(plex|transcoder)::(is_dp_audio([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?is_dp_audio([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])is_dp_audio([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])(plex|transcoder)::(is_dp_audio_track([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?is_dp_audio_track([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])is_dp_audio_track([^A-Za-z0-9_]|$);;(^|[^A-Za-z0-9_])session::(current_gen([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?current_gen([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])current_gen[[:space:]]*\(;;(^|[^A-Za-z0-9_])tape::(active([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?active([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])active[[:space:]]*\(;;(^|[^A-Za-z0-9_])(sidecar|ass_source)::(selected([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?selected([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])selected[[:space:]]*\(;;(^|[^A-Za-z0-9_])(sidecar|ass_source)::(takes_colour([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?takes_colour([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])takes_colour[[:space:]]*\(;;(^|[^A-Za-z0-9_])session::(screen_input_revision([^A-Za-z0-9_]|$)|\*|\{([^}]*[^A-Za-z0-9_])?screen_input_revision([^A-Za-z0-9_}][^}]*)?\})@@(^|[^A-Za-z0-9_.:])screen_input_revision[[:space:]]*\(' \ LG_FILE_SITE='rust-modules/plex/src/plex/session.rs@@(^|[^A-Za-z0-9_.:])peek([^A-Za-z0-9_]|$);;rust-modules/plex/src/plex/session.rs@@(^|[^A-Za-z0-9_.:])current_gen[[:space:]]*\(;;rust-modules/media/src/player/lifecycle.rs@@(^|[^A-Za-z0-9_.])(player::TX|super::TX|shared::FEED_TX|shared::FEED_SHARED)([^A-Za-z0-9_]|$)|(^|[^A-Za-z0-9_.:])(TX|FEED_TX|FEED_SHARED)([^A-Za-z0-9_]|$)' \ ledger_scan | sort ) diff --git a/ci/check-ledger-ratchet.py b/ci/check-ledger-ratchet.py index 64b42882ed..6a04cd1a46 100644 --- a/ci/check-ledger-ratchet.py +++ b/ci/check-ledger-ratchet.py @@ -49,6 +49,7 @@ from __future__ import annotations import argparse +import configparser import ast import os import subprocess @@ -192,6 +193,15 @@ def message(rows: list[tuple[str, int, int]], base: str, how: str) -> str: return "\n".join(lines) +def port_paths(text: str, where: str) -> set[str]: + parser = configparser.ConfigParser(interpolation=None, strict=True) + try: + parser.read_string(text) + except configparser.Error as error: + raise Unavailable(f"{where} does not parse: {error}") from error + if parser.defaults(): raise Unavailable(f"{where}: DEFAULT exemptions are not permitted") + return set(parser.sections()) + def check(repo: Path, env=None) -> tuple[int, str]: """(exit status, the line(s) to print).""" env = os.environ if env is None else env @@ -209,6 +219,16 @@ def check(repo: Path, env=None) -> tuple[int, str]: raise Unavailable(f"{HARNESS} no longer defines {', '.join(lost)}: the ratchet reads those pin tables") head_counts = {**counts(head_files), **flat(head_tables)} rows, new = compare({**counts(base_files), **flat(base_tables)}, head_counts) + # ports.ini is a file exemption SET: replacing one path is growth even at equal count. + ports_file = "ci/ports.ini" + old_ports = git(repo, "show", f"{base}:{ports_file}", check=False) + current_ports = repo / ports_file + head_ports = port_paths(current_ports.read_text(encoding="utf-8"), ports_file) if current_ports.exists() else set() + if old_ports.returncode == 0: + base_ports = port_paths(old_ports.stdout, f"{base[:9]}:{ports_file}") + rows.extend((f"{ports_file} [{path}]", 0, 1) for path in sorted(head_ports - base_ports)) + elif current_ports.exists(): + new.append((ports_file, len(head_ports))) if rows: return 1, message(rows, base, how) skipped = "; new, not compared: " + ", ".join(f"{name} ({value})" for name, value in new) if new else "" diff --git a/ci/check-machine-shape.py b/ci/check-machine-shape.py index a4b9416a65..cd38c9440d 100755 --- a/ci/check-machine-shape.py +++ b/ci/check-machine-shape.py @@ -1,21 +1,13 @@ #!/usr/bin/env python3 -"""The machine-shape gate: every state machine listed in `ci/machines.ini` keeps its state private. +"""Mandatory registry-backed privacy, single-writer and enum-lint contracts. -A Sans-IO machine has one writer, `step(&mut self, event, &mut effects)`; its state is private so a -caller cannot poke it, and a new way in is a new event (docs/sans-io.md). This gate makes that a -fact the build checks instead of a habit: - - * FAILS on any `pub`, `pub(crate)`, `pub(super)` or `pub(in ..)` field of a listed struct, and on a - section whose file or struct is gone, so the registry cannot go stale. - * REPORTS, never fails: one line per machine with the number of `bool` and `Option<..>` fields. - A pile of flags and optionals is how a state machine decays into a bag of booleans; the count is - there to be read in review. It is a report-only ratchet: nothing here turns it red. - - ci/check-machine-shape.py +Every listed machine has a validated strict writer binding and an enum policy. Bool/Option counts +remain report-only. See machines.ini for the conservative proof limits; Clippy classifies enums. """ from pathlib import Path import configparser import sys +from machine_readonly import macro_invocation sys.path.insert(0, str(Path(__file__).resolve().parent)) import rust_test_modules as rtm # noqa: E402 @@ -29,7 +21,7 @@ def struct_fields(source, name): """[(is_pub, field name or index, type tokens)] of the braced or tuple struct `name`, or None when the source declares no such struct. Comments and strings are gone after lexing.""" - tokens = [text for kind, text in rtm.lex(source) if kind == 'code'] + tokens = [t for t in source if t != ''] if isinstance(source, list) else rust_tokens(source) start = next((i for i in range(len(tokens) - 1) if tokens[i] == 'struct' and tokens[i + 1] == name), None) if start is None: return None body, angle = start + 2, 0 @@ -42,12 +34,14 @@ def struct_fields(source, name): token = tokens[k] if depth == 0 and token in ('}', ')'): break if depth == 0 and token == ',': - fields.append(current); current = [] + if current: fields.append(current) + current = [] continue depth += (token in OPEN) - (token in SHUT and tokens[k - 1] != '-') current.append(token) if current: fields.append(current) - return [shape(index, field) for index, field in enumerate(fields)] + fields = [field[next((i for i, t in enumerate(field) if t not in ('', ';')), len(field)):] for field in fields] + return [shape(index, field) for index, field in enumerate(f for f in fields if f)] def shape(index, tokens): @@ -67,8 +61,801 @@ def shape(index, tokens): return is_pub, str(index), tokens # a tuple struct's field +def rust_tokens(source): + """Code tokens with raw identifiers normalized; literals cannot join adjacent code.""" + raw = [text if kind == 'code' else '' for kind, text in rtm.lex(source)] + out, i = [], 0 + while i < len(raw): + if raw[i:i + 2] == ['r', '#'] and i + 2 < len(raw): + identifier = raw[i + 2] + if identifier in ('if', 'while', 'return', 'match', 'let', 'else', 'for', 'yield', 'break', 'continue') and raw[i + 3:i + 4] == ['!']: + identifier = '_raw_macro_' + identifier + out.append(identifier); i += 3 + else: + out.append(raw[i]); i += 1 + return out + + +def ends_of(tokens): + return rtm.group_ends([('code', token) for token in tokens]) + + +def production_tokens(source): + """Erase items proven cfg(test)-only, keeping item boundaries.""" + tokens = rust_tokens(source) + ends = ends_of(tokens) + i = 0 + while i + 1 < len(tokens): + if tokens[i:i + 2] != ['#', '['] or i + 1 not in ends: + i += 1; continue + end = ends[i + 1] + attr = tokens[i + 2:end] + if len(attr) < 3 or attr[:2] != ['cfg', '('] or attr[-1] != ')': + i = end + 1; continue + if rtm.cfg_without_tests([('code', t) for t in attr[2:-1]]) != {False}: + i = end + 1; continue + j = end + 1 + while j < len(tokens): + if tokens[j] == '#' and j + 1 in ends and tokens[j + 1] == '[': + j = ends[j + 1] + 1; continue + if tokens[j] == '{' and j in ends: + j = ends[j] + 1; break + if tokens[j] in (';', ','): + j += 1; break + if tokens[j] == '}': break + if tokens[j] in ('(', '[') and j in ends: + j = ends[j] + 1; continue + j += 1 + boundary = ',' if tokens[j - 1:j] == [','] else ';' + tokens[i:j] = [''] * (j - i) + if j > i: tokens[j - 1] = boundary # retain an item boundary for the following production impl + i = j + return [token for token in tokens if token != ''] + + +def item_bodies(tokens): + """Return inherent impl and function spans; nested functions remain separate.""" + ends = ends_of(tokens) + impls, functions = [], [] + for i, token in enumerate(tokens): + if token not in ('impl', 'fn'): continue + if token == 'impl' and i and tokens[i - 1] not in ('}', ';', ']', '{', 'unsafe', 'default'): continue + j = i + 1 + if token == 'fn': + if j >= len(tokens) or not tokens[j].isidentifier(): continue + name = tokens[j] + while j < len(tokens) and tokens[j] not in ('(', ';', '{'): + j += 1 + if j not in ends or tokens[j] != '(': continue + j = ends[j] + 1 + else: + name = None + while j < len(tokens) and tokens[j] not in ('{', ';'): + if tokens[j] in ('(', '[') and j in ends: + j = ends[j] + 1 + else: + j += 1 + if j >= len(tokens) or tokens[j] != '{' or j not in ends: continue + if token == 'impl': impls.append((j, ends[j], tokens[i + 1:j])) + else: functions.append((j, ends[j], name, tokens[i + 2:j])) + return impls, functions, ends + + +def impl_type(header): + """The implemented Rust type, without impl parameters or an implemented trait.""" + header = list(header) + if header[:1] == ['<']: + depth, stop = 1, 1 + while stop < len(header) and depth: + depth += (header[stop] == '<') - (header[stop] == '>'); stop += 1 + header = header[stop:] + if 'for' in header: header = header[header.index('for') + 1:] + if 'where' in header: header = header[:header.index('where')] + return header + + +def inherent_target(header, name): + """Accept only an unambiguous inherent impl of the registered type.""" + if 'for' in header: return False + if header and header[0] == '<': + depth, pos = 0, 0 + while pos < len(header): + depth += (header[pos] == '<') - (header[pos] == '>') + pos += 1 + if not depth: break + header = header[pos:] + return bool(header and header[0] == name and + (len(header) == 1 or header[1] in ('<', 'where'))) + + +def mutation_in_tail(tokens): + """Reject writes and calls on a state projection; calls may hide a mutable receiver.""" + for i, token in enumerate(tokens): + if token in (';', '{', '}'): break + if token == '=': + before = tokens[i - 1] if i else '' + after = tokens[i + 1] if i + 1 < len(tokens) else '' + shift = i >= 2 and tokens[i - 2:i] in (['<', '<'], ['>', '>']) + if shift or (before not in ('=', '!', '<', '>') and after not in ('=', '>')): return True + if token == '(' and i and tokens[i - 1] not in (')', ']'): return True + return False + + +def builtin_macro(tokens, bang, macro): + """Accept an unqualified builtin only when no local definition/import can shadow it.""" + if bang < 1 or tokens[bang - 1] != macro: return False + if bang >= 3 and tokens[bang - 3:bang - 1] == [':', ':']: return False + if any(tokens[j:j + 3] == ['macro_rules', '!', macro] for j in range(len(tokens) - 2)): + return False + for j, token in enumerate(tokens): + if token == 'use': + end = j + 1 + while end < len(tokens) and tokens[end] != ';': end += 1 + if macro in tokens[j + 1:end] or '*' in tokens[j + 1:end]: return False + return True + + +def readonly_match(tokens, bang, ends, field): + """Recognize a builtin matches! with a direct scrutinee and no bindings or guard.""" + if bang + 1 not in ends or not builtin_macro(tokens, bang, 'matches'): + return None + start, stop = bang + 2, ends[bang + 1] + comma = start + 1 + if tokens[start:start + 3] == ['self', '.', field]: comma = start + 3 + elif tokens[start:start + 1] != ['self']: return None + if tokens[comma:comma + 1] != [',']: return None + pattern = tokens[comma + 1:stop] + if not pattern: return None + for j, token in enumerate(pattern): + if token.isidentifier() and token != '_': + if token in ('self', 'ref', 'mut', 'if'): return None + if not token[0].isupper() and pattern[j + 1:j + 2] != [':']: + return None + elif token not in (':', '{', '}', '(', ')', '[', ']', ',', '.', '|', '_') and not token.isdigit(): + return None + return start, comma + + +def copy_enum_types(tokens): + """Recognize derived-Copy fieldless enums; payloads and aliases stay conservative.""" + ends = ends_of(tokens) + safe = set() + for i in range(len(tokens) - 2): + if tokens[i] != 'enum' or tokens[i + 2] != '{' or i + 2 not in ends: continue + before = i - 1 + if tokens[before:before + 1] == ['pub']: before -= 1 + if before < 0 or tokens[before] != ']': continue + attr = next((j for j, end in ends.items() if end == before and tokens[j] == '['), None) + if attr is None or attr == 0 or tokens[attr - 1] != '#': continue + derive = tokens[attr + 1:before] + if len(derive) < 4 or derive[:2] != ['derive', '('] or derive[-1] != ')' or 'Copy' not in derive: + continue + variants = tokens[i + 3:ends[i + 2]] + enum_name = tokens[i + 1] + declarations = sum(tokens[j] in ('enum', 'struct', 'type', 'union') and tokens[j + 1] == enum_name + for j in range(len(tokens) - 1)) + imported = False + for j, token in enumerate(tokens): + if token == 'use': + end = j + 1 + while end < len(tokens) and tokens[end] != ';': end += 1 + if enum_name in tokens[j + 1:end] or '*' in tokens[j + 1:end]: + imported = True + break + if declarations == 1 and not imported and variants and all( + t == ',' or (t.isidentifier() and t[0].isupper()) for t in variants): + safe.add(enum_name) + return safe + + +def closure_spans(tokens, ends): + """Conservatively delimit closures so a nested writer never inherits method authority.""" + spans = [] + for i, token in enumerate(tokens): + if token != '|' or i and tokens[i - 1] not in ('=', '(', ',', '{', 'move', 'return', ':'): continue + stop = i + 1 + while stop < len(tokens) and tokens[stop] not in ('|', ';', '{', '}'): stop += 1 + if tokens[stop:stop + 1] != ['|']: continue + body = stop + 1 + if tokens[body:body + 1] == ['{'] and body in ends: + spans.append((i, ends[body])); continue + end = body + while end < len(tokens) and tokens[end] not in (';', ',', '}', ')', ']'): + end = ends[end] + 1 if end in ends else end + 1 + spans.append((i, end)) + return spans + + +# Closed semantic fact slots required by the current canonical headers, not type-name exemptions. +AUX_FACTS = { + 'play-uri/src/uriprobe.rs::UriProbe': 'now_ms:monotonic_ms_u64', + 'session/src/auth/owner.rs::SessionMachine': 'tick_ms:monotonic_ms_u32', + 'playback-contract/src/state.rs::BackendState': 'capabilities:playback_capabilities', +} +CAPABILITY_FIELDS = ('progressive_uri', 'hls_uri', 'packet_feed', 'pause', 'seek', + 'audio_track', 'subtitle_track', 'audio_off', 'subtitle_off') + + +def primitive_fact(proof, path, typ, primitive, headers=()): + """Require a by-value primitive spelling with no lexical shadow or alias.""" + tokens, _, definitions, uses = proof.module(path) + if any(alias == '*' for alias, _ in uses): return False + if any(primitive in header for header in headers): return False + if typ == [primitive]: + if primitive in definitions or any(alias == primitive for alias, _ in uses): return False + if any(tokens[i] in ('union', 'trait', 'mod') and tokens[i + 1] == primitive for i in range(len(tokens) - 1)): return False + return proof.resolve(path, [primitive]) == ('std', primitive) + for namespace in ('core', 'std'): + canonical = [':', ':', namespace, ':', ':', 'primitive', ':', ':', primitive] + if typ not in (canonical, canonical[2:]): continue + if namespace in definitions or any(alias == namespace for alias, _ in uses): return False + if any(tokens[i] in ('mod', 'union', 'trait', 'extern', 'as') and tokens[i + 1] == namespace for i in range(len(tokens) - 1)): return False + return not any(namespace in header for header in headers) + return False + + +def auxiliary_argument(proof, path, param, declaration, headers=()): + """Two clock widths and one exact nine-boolean capability record; no open model whitelist.""" + if not declaration or len(param) < 3 or param[1] != ':': return False + name, kind = declaration.split(':') + if param[0] != name: return False + typ = param[2:] + if kind in ('monotonic_ms_u32', 'monotonic_ms_u64'): + return primitive_fact(proof, path, typ, kind.rsplit('_', 1)[1], headers) + if kind != 'playback_capabilities' or typ != ['Option', '<', 'Capabilities', '>']: return False + expected_path = (proof.root / 'playback-contract/src/lib.rs').resolve() + if any(n in header for header in headers for n in ('Option', 'Capabilities')): return False + if any(alias == '*' for alias, _ in proof.module(path)[3]): return False + if proof.resolve(path, ['Option']) != ('std', 'Option'): return False + if proof.resolve(path, ['Capabilities']) != (expected_path, 'Capabilities'): return False + target = proof.nominal(path, typ) + if target is None or target[:3] != ('std', 'Option', 'std') or len(target[3]) != 1: return False + item = proof.nominal(target[4], target[3][0]) + + if item is None or item[:3] != (expected_path, 'Capabilities', 'struct') or item[3]: return False + tokens, _, definitions, uses = proof.module(expected_path) + fields = struct_fields(tokens, 'Capabilities') + if definitions['Capabilities'][0][0] or fields is None: return False + if [n for _, n, _ in fields] != list(CAPABILITY_FIELDS): return False + return proof.inert(expected_path, ['Capabilities']) and all( + primitive_fact(proof, expected_path, t, 'bool') for _, _, t in fields) + + +def writer_problems(source, name, field, transition, constructor, label, require_methods=True, + reader=None, event=None, effect=None, proof=None, shared_reads=False, owned_fields=None, owner_path=None, aux_facts=""): + """Literal Event/Effects authority covers EVERY owned field, never a selected-state whitelist.""" + tokens = production_tokens(source) + impls, functions, ends = item_bodies(tokens) + fields = struct_fields(tokens, name) or owned_fields or [] + owned = [(a, b) for a, b, h in impls if inherent_target(h, name)] + declared = [(a, b, n, sig) for a, b, n, sig in functions + if any(x < a < b < y for x, y in owned) + and not any(x < a < y for x, y, _, _ in functions)] + problems = [] + if transition != 'transition': problems.append(f'{label}: canonical method must be named transition') + if event is None or effect is None or proof is None: + problems.append(f'{label}: missing validated event/effect bindings') + source_path = proof.root / label if proof is not None else None + state_path = Path(owner_path) if owner_path is not None else source_path + from machine_readonly import split + def parameters(sig): + end = ends_of(sig).get(0) + return split(sig[1:end]) if end is not None else [] + def typ(param): + return param[param.index(':') + 1:] if ':' in param else [] + def leading(a, method): + fn = max(i for i in range(a) if tokens[i:i + 2] == ['fn', method]) + start = fn - 1 + while start >= 0 and tokens[start] not in (';', '{', '}'): start -= 1 + return tokens[start + 1:fn] + if require_methods: + matches = [(a, b, sig) for a, b, n, sig in declared if n == transition] + if len(matches) != 1: problems.append(f'{label}: canonical transition must be unique') + for a, b, sig in matches: + if 'pub' in leading(a, transition): problems.append(f'{label}: canonical transition must be private') + params = parameters(sig) + if not params or params[0] != ['&', 'mut', 'self']: + problems.append(f'{label}: transition must take &mut self') + if proof is not None and event and effect: + headers = [h for x, y, h in impls if x < a < b < y] + names = [p[0] for p in params[1:] if len(p) >= 3 and p[1] == ':' and p[0].isidentifier()] + if len(names) != len(params) - 1 or len(set(names)) != len(names): + problems.append(f'{label}: transition arguments require unique simple bindings') + aux_params = [p for p in params[1:] if aux_facts and p[:2] == [aux_facts.split(':')[0], ':']] + if aux_facts and (len(aux_params) != 1 or not auxiliary_argument(proof, source_path, aux_params[0], aux_facts, headers)): + problems.append(f'{label}: transition requires exact auxiliary fact {aux_facts}') + return problems # Invalid/opaque facts cannot enter nominal resolution as authority. + expected = proof.nominal(source_path, rust_tokens(event)) + event_params = [p for p in params[1:] if proof.nominal(source_path, typ(p)) is not None + and expected is not None and proof.nominal(source_path, typ(p))[:3] == expected[:3]] + if expected is None or expected[2] != 'enum' or len(event_params) != 1 or any(typ(p)[:2] == ['&', 'mut'] for p in event_params): + problems.append(f'{label}: transition must take registered event enum {event}') + elif any(proof.nominal(source_path, t) is not None and proof.nominal(source_path, t)[:3] == expected[:3] for _, _, t in fields): + problems.append(f'{label}: event enum must not be an owned raw state setter') + effect_params = [p for p in params[1:] if effect != 'none' and proof.effect_output(source_path, typ(p), rust_tokens(effect))] + for p in params[1:]: + if p not in event_params and p not in effect_params and p not in aux_params: + problems.append(f'{label}: unbound transition argument {" ".join(p)}') + required = 1 + (effect != 'none') + bool(aux_facts) + if len(params) != required + 1 or len(effect_params) != (effect != 'none'): + problems.append(f'{label}: transition argument arity must be self + Event + exact Fx/fact slots') + if effect == 'none': + if any('mut' in p or 'FnMut' in p for p in params[1:]): + problems.append(f'{label}: effect = none forbids an effect output') + elif not any(proof.effect_output(source_path, typ(p), rust_tokens(effect)) for p in params[1:]): + problems.append(f'{label}: transition requires &mut Vec<{effect}> or its concrete alias') + if any('FnMut' in p or 'Fn' in p or 'FnOnce' in p or 'fn' in p or '*' in p for p in params[1:]): + problems.append(f'{label}: transition cannot delegate writes/effects to a callback or pointer') + for a, b, method, sig in declared: + if method != constructor: continue + params = parameters(sig) + if any('Self' in p or name in p or proof is not None and + (target := proof.nominal(source_path, typ(p))) is not None and target[1] == name for p in params): + problems.append(f'{label}: constructor accepts existing machine authority (fresh values only)') + if any(tokens[i:i + 2] == ['.', '.'] for i in range(a + 1, b)): + problems.append(f'{label}: constructor must initialize fresh fields without struct updates') + if not require_methods and any(n in (transition, constructor) for _, _, n, _ in declared): + problems.append(f'{label}: a production child cannot define an alternate canonical writer/constructor') + if proof is not None: + for _, _, header in impls: + target_type = impl_type(header) + target = proof.nominal(source_path, target_type) + if target is not None and target[1] == name and target_type[:1] != [name]: + problems.append(f'{label}: a machine type alias cannot introduce another authority impl') + substitutions = proof.generic_context(state_path, name) if proof is not None and fields else {} + readers = {} + for _, key, typ_tokens in fields: + resolved = [part for token in typ_tokens for part in (substitutions or {}).get(token, [token])] + readers[key] = (proof, state_path, resolved) if proof is not None and shared_reads else None + if isinstance(reader, tuple): readers[field] = reader + elif isinstance(reader, dict): readers.update(reader) + if proof is not None: + field_types = {k: [part for token in t for part in (substitutions or {}).get(token, [token])] for _, k, t in fields} + for a, b, method, sig in declared: + if parameters(sig)[:1] != [['&', 'self']]: continue + opaque = False + for i in range(a + 1, b - 2): + if tokens[i:i + 2] != ['self', '.'] or tokens[i + 2] not in field_types: continue + position, resolved = i + 2, (state_path, field_types[tokens[i + 2]]) + while tokens[position + 1:position + 2] == ['.'] and tokens[position + 3:position + 4] != ['(']: + resolved = proof.field(*resolved, tokens[position + 2]) if resolved else None + position += 2 + if resolved is None or not proof.inert(*resolved): opaque = True + if opaque and not proof.discriminant_method(source_path, name, method): + problems.append(f'{label}::{method}: shared opaque payload requires a bounded inert/discriminant proof') + targets = fields or [(False, field, [])] + contexts = {} + for _, key, _ in targets: + problems.extend(_field_writer_problems(source, name, key, transition, constructor, label, + require_methods=require_methods, reader=readers.get(key), analysis=(tokens, impls, functions, ends, contexts))) + for _, _, method, sig in declared: + params = parameters(sig) + if params and 'self' in params[0] and '&' not in params[0]: + problems.append(f'{label}::{method}: consuming the machine must use an owner event') + machine_methods = {n: [(a, b, sig) for a, b, m, sig in declared if m == n] for _, _, n, _ in declared} + all_inert = proof is not None and substitutions is not None and all(proof.inert(state_path, [part for token in t for part in substitutions.get(token, [token])]) for _, _, t in fields) + def machine_body(i): return any(a < i < b and inherent_target(h[h.index('for') + 1:] if 'for' in h else h, name) for a, b, h in impls) + for i, token in enumerate(tokens): + if not machine_body(i): continue + if token == 'unsafe': problems.append(f'{label}: unsafe machine authority cannot be proved') + if token == 'self' and tokens[i + 1:i + 2] == ['.'] and tokens[i + 3:i + 4] == ['(']: + method = tokens[i + 2] + if method == transition: continue + candidates = machine_methods.get(method, []) + shared = len(candidates) == 1 and parameters(candidates[0][2])[:1] == [['&', 'self']] + bounded = proof is not None and proof.discriminant_method(source_path, name, method) if shared and not all_inert else False + if not shared or not (all_inert or bounded) or 'unsafe' in tokens[candidates[0][0]:candidates[0][1]]: + problems.append(f'{label}: live machine call {method} is not the canonical event reducer or a proved shared decision') + if token == '!' and macro_invocation(tokens, i, ends): + args = tokens[i + 2:ends[i + 1]] + if 'self' in args and not (tokens[i - 1] in ('matches', 'assert', 'debug_assert', 'vec', 'format', 'format_args', 'write', 'writeln', 'panic') + and proof is not None and proof.builtin(source_path, tokens[i - 1]) and builtin_macro(tokens, i, tokens[i - 1])): + problems.append(f'{label}: unknown macro may capture live machine authority') + if proof is not None: + for a, b, method, sig in functions: + for p in parameters(sig): + if '&' not in p or 'mut' not in p or ':' not in p: continue + target = proof.nominal(source_path, typ(p)) + if target is not None and target[1] == name and target[0] == source_path.resolve(): + problems.append(f'{label}::{method}: mutable machine alias may replace owned fields') + return list(dict.fromkeys(problems)) + + +def _field_writer_problems(source, name, field, transition, constructor, label, require_methods=True, reader=None, analysis=None): + if analysis is None: + tokens = production_tokens(source) + impls, functions, ends = item_bodies(tokens) + else: tokens, impls, functions, ends, contexts = analysis + if analysis is None: contexts = {} + owned = [(a, b) for a, b, h in impls if inherent_target(h, name)] + closures = closure_spans(tokens, ends) + + def compute_context(index): + if any(a <= index < b for a, b in closures): return None + containing = [(a, b, n) for a, b, n, _ in functions if a < index < b] + if not containing: return None + a, b, method = min(containing, key=lambda x: x[1] - x[0]) + parents = [(x, y) for x, y, _, _ in functions if x < a < y] + return method if not parents and any(x < a < b < y for x, y in owned) else None + + def context(index): + if index not in contexts: contexts[index] = compute_context(index) + return contexts[index] + + problems = [] + fields = struct_fields(tokens, name) or [] + field_types = [typ for _, field_name, typ in fields if field_name == field] + plain_struct = any(tokens[j:j + 3] == ['struct', name, '{'] for j in range(len(tokens) - 2)) + copy_field = (plain_struct and len(field_types) == 1 and len(field_types[0]) == 1 + and field_types[0][0] in copy_enum_types(tokens)) + safe_matches = {i: span for i, token in enumerate(tokens) if token == '!' + and (span := readonly_match(tokens, i, ends, field)) is not None} + # These wrappers consume only the bool result, with no formatting expressions. + safe_asserts = set() + for i, token in enumerate(tokens): + if token != '!' or i + 1 not in ends: continue + if not any(builtin_macro(tokens, i, macro) for macro in ('assert', 'debug_assert')): continue + inner = i + 3 + if inner not in safe_matches or inner + 1 not in ends: continue + rest = tokens[ends[inner + 1] + 1:ends[i + 1]] + if rest in ([], [',']): safe_asserts.add(i) + + def copy_argument(index, prefix): + # A fieldless Copy enum cannot contain a mutable alias. No other bindings are relaxed. + if not copy_field or tokens[index + 1:index + 2] != [')'] or len(prefix) < 7: return False + call = prefix[-7:] + if call[:3] != ['Self', ':', ':'] or call[4:] != ['(', 'self', '.']: return False + helper = call[3] + for a, b, method, sig in functions: + if method != helper or not any(x < a < b < y for x, y in owned): continue + if len(sig) >= 7 and sig[0] == '(' and sig[2:5] == [':', field_types[0][0], ')']: + result = sig[5:] + if result[:2] == ['-', '>'] and '&' not in result and 'DerefMut' not in result: + return True + return False + + def location(index): + containing = [(a, b, method) for a, b, method, _ in functions if a < index < b] + method = min(containing, key=lambda item: item[1] - item[0])[2] if containing else None + return f'{label}::{method}' if method else label + + # Only a direct associated Self struct literal is an authorized constant constructor. + constants = [] + for i in range(len(tokens) - 6): + if tokens[i:i + 6] != ['const', constructor, ':', 'Self', '=', 'Self']: + continue + brace = i + 6 + if brace not in ends or tokens[brace] != '{' or tokens[ends[brace] + 1:ends[brace] + 2] != [';']: + continue + parents = [(a, b) for a, b in ends.items() if tokens[a] == '{' and a < i < b] + if parents and min(parents, key=lambda pair: pair[1] - pair[0]) in owned: + constants.append((i + 5, brace, ends[brace])) + if require_methods: + declared = [(a, b, n, sig) for a, b, n, sig in functions + if any(x < a < b < y for x, y in owned) + and not any(x < a < y for x, y, _, _ in functions)] + matches = [sig for _, _, n, sig in declared if n == transition] + if not matches: + problems.append(f'{label}: missing inherent method {transition} (stale strict contract)') + for sig in matches: + if not any(sig[i:i + 3] == ['&', 'mut', 'self'] for i in range(len(sig) - 2)): + problems.append(f'{label}: transition {transition} must take &mut self') + constructors = [(a, b, sig) for a, b, n, sig in declared if n == constructor] + if not constructors and not constants: + problems.append(f'{label}: missing inherent constructor {constructor} (stale strict contract)') + if len(constructors) + len(constants) > 1: + problems.append(f'{label}: constructor {constructor} must be unique') + for a, b, sig in constructors: + if 'self' in sig: + problems.append(f'{label}: constructor {constructor} must not take self') + initialized = any(tokens[i] in (name, 'Self') and i + 1 in ends and tokens[i + 1] == '{' + and ends[i + 1] < b and field in tokens[i + 2:ends[i + 1]] + for i in range(a + 1, b)) + if not initialized: + problems.append(f'{label}: constructor {constructor} must initialize {field} in a struct literal') + for _, brace, end in constants: + if field not in tokens[brace + 1:end]: + problems.append(f'{label}: constructor {constructor} must initialize {field} in a struct literal') + # A whole-machine mutable reference can replace the state without naming the field. + # Reject such helper parameters, including in production child modules. Receivers are + # checked separately below: the public step may borrow self only to call transition. + for a, b, method, sig in functions: + self_type = 'Self' in sig and any(x < a < b < y for x, y in owned) + if (name in sig or self_type) and '&' in sig and 'mut' in sig: + problems.append(f'{label}::{method}: mutable machine reference may replace state') + + def self_is_machine(index): + containing = [(a, b, h) for a, b, h in impls if a < index < b] + if not containing: return False + _, _, header = min(containing, key=lambda item: item[1] - item[0]) + return inherent_target(header[header.index('for') + 1:] if 'for' in header else header, name) + + def unrelated_projection(index): + if reader is None: return False + if tokens[index + 1:index + 2] == ['('] and tokens[index - 2:index] == ['self', '.'] and reader[0].shared_method(reader[0].root / label, [name], field): return True + root = index - 2 + while root >= 2 and tokens[root - 1] == '.': root -= 2 + if root >= 0 and tokens[root] == 'self' and root + 2 < index and self_is_machine(index): return True + receiver = tokens[index - 2] if index >= 2 else '' + if receiver == 'self': + if self_is_machine(index): return False + proof = reader[0] + enclosing = [(a, b, h) for a, b, h in impls if a < index < b] + if not enclosing: return False + header = impl_type(min(enclosing, key=lambda item: item[1] - item[0])[2]) + return proof.field(proof.root / label, header, field) is not None + proof, state_path, state_type = reader + source_path = proof.root / label + enclosing = [(a, b, sig) for a, b, _, sig in functions if a < index < b] + if not enclosing: return False + a, b, signature = min(enclosing, key=lambda item: item[1] - item[0]) + for j in range(len(signature) - 1): + if signature[j:j + 2] == [receiver, ':']: + stop = j + 2 + while stop < len(signature) and signature[stop] not in (',', ')'): stop += 1 + return proof.field(source_path, signature[j + 2:stop], field) is not None and name not in signature[j + 2:stop] + # A local borrowed from a different, structurally resolved machine field belongs to that field's owner. + for j in range(a + 1, index): + if tokens[j] != 'let': continue + equal = j + 1 + while equal < index and tokens[equal] not in ('=', ';', '{'): equal += 1 + if tokens[equal:equal + 1] != ['='] or receiver not in tokens[j:equal]: continue + binding = tokens[j + 1:equal] + if ':' in binding: + declared_type = binding[binding.index(':') + 1:] + target = proof.nominal(source_path, declared_type) + if target is not None and target[1] != name and proof.field(source_path, declared_type, field) is not None: return True + pos = equal + 1 + if tokens[pos:pos + 1] == ['&']: pos += 1 + if tokens[pos:pos + 2] != ['self', '.'] or tokens[pos + 2:pos + 3] == [field]: continue + resolved = (state_path, [name]) + pos += 1 + while tokens[pos:pos + 1] == ['.'] and tokens[pos + 2:pos + 3] != ['(']: + resolved = proof.field(resolved[0], resolved[1], tokens[pos + 1]) if resolved else None + pos += 2 + if resolved and name not in resolved[1] and proof.field(resolved[0], resolved[1], field) is not None: return True + return False + + def shared_read(index): + if reader is None: return False + proof, state_path, state_type = reader + position, resolved = index, (state_path, state_type) + while True: + if tokens[position + 1:position + 2] == ['['] and position + 1 in ends: + target = proof.nominal(*resolved) if resolved else None + if target is None or target[:3] not in (('std', 'Vec', 'std'), ('std', 'VecDeque', 'std'), ('std', 'BTreeMap', 'std')): return False + resolved = (target[4], target[3][-1]) + position = ends[position + 1] + elif tokens[position + 1:position + 2] == ['.'] and tokens[position + 3:position + 4] != ['(']: + resolved = proof.field(resolved[0], resolved[1], tokens[position + 2]) if resolved else None + position += 2 + else: break + if resolved is None or not proof.inert(*resolved): return False + if tokens[position + 1:position + 3] in (['=', '='], ['!', '='], ['<', '='], ['>', '=']): return True + for j in range(position + 1, len(tokens)): + token = tokens[j] + if token in (';', '{', '}', ','): break + if token == '=' and (j == 0 or tokens[j - 1] not in ('=', '!', '<', '>')) and tokens[j + 1:j + 2] not in (['='], ['>']): return False + if tokens[position + 1:position + 2] == ['.'] and tokens[position + 3:position + 4] == ['(']: + return proof.shared_method(resolved[0], resolved[1], tokens[position + 2]) + if tokens[index - 5:index] in (['!', '=', '*', 'self', '.'], ['=', '=', '*', 'self', '.']): + target = proof.nominal(*resolved) + if target is not None and target[0] == 'std' and target[1] == 'Arc': return True + if tokens[index - 3:index] != ['&', 'self', '.']: + return proof.copy_value(*resolved) + if tokens[index - 4:index - 3] == [':'] and tokens[index - 5].isidentifier(): + braces = [(a, b) for a, b in ends.items() if tokens[a] == '{' and a < index < b] + if not braces: return False + begin, _ = min(braces, key=lambda pair: pair[1] - pair[0]) + start = begin - 1 + while start > 1 and tokens[start - 2:start] == [':', ':']: start -= 3 + return proof.shared_field(resolved[0], resolved[1], proof.root / label, tokens[start:begin], tokens[index - 5]) + return True + + def owned_take(index, owner): + if reader is None or owner != transition: return False + # The borrow is consumed by the standard intrinsic, never exposed to a callback. + for method in ('replace', 'take'): + expected = ['std', ':', ':', 'mem', ':', ':', method, '(', '&', 'mut', 'self', '.'] + if tokens[max(0, index - len(expected)):index] == expected: + if any(tokens[j:j + 2] in (['mod', 'std'], ['as', 'std']) for j in range(len(tokens) - 1)): return False + return True + return False + + def owned_bool_match(index, owner): + """An in-place enum bool binding may only receive a literal in this reducer arm.""" + if reader is None or owner != transition or tokens[index - 5:index] != ['match', '&', 'mut', 'self', '.']: return False + brace = index + 1 + if brace not in ends or tokens[brace] != '{': return False + proof, state_path, state_type = reader + target = proof.nominal(state_path, state_type) + if target is None or target[2] != 'enum' or not proof.inert(state_path, state_type): return False + enum_path, enum_name = target[:2] + enum_tokens, enum_ends, _, _ = proof.module(enum_path) + declaration = next((i for i in range(len(enum_tokens) - 1) if enum_tokens[i:i + 2] == ['enum', enum_name]), None) + if declaration is None: return False + begin = declaration + 2 + while begin < len(enum_tokens) and enum_tokens[begin] != '{': begin += 1 + if begin not in enum_ends: return False + bool_fields = set() + pos = begin + 1 + while pos < enum_ends[begin]: + variant = enum_tokens[pos] + if enum_tokens[pos + 1:pos + 2] == ['{'] and pos + 1 in enum_ends: + stop = enum_ends[pos + 1] + for j in range(pos + 2, stop - 2): + if enum_tokens[j + 1:j + 3] == [':', 'bool']: bool_fields.add((variant, enum_tokens[j])) + pos = stop + 1 + elif pos + 1 in enum_ends: pos = enum_ends[pos + 1] + 1 + else: pos += 1 + if enum_tokens[pos:pos + 1] == [',']: pos += 1 + pos, bound = brace + 1, False + while pos < ends[brace]: + start = pos + while pos < ends[brace] and tokens[pos:pos + 2] != ['=', '>']: + pos = ends[pos] + 1 if pos in ends else pos + 1 + if pos >= ends[brace]: return False + pattern = tokens[start:pos] + pos += 2 + body_start = pos + if pos in ends: pos = ends[pos] + 1 + else: + while pos < ends[brace] and tokens[pos] != ',': pos += 1 + body = tokens[body_start:pos] + if '@' in pattern: + if len(pattern) != 14 or pattern[:3] != [enum_name, ':', ':'] or pattern[4] != '{' or pattern[6] != ':' or pattern[8] != '@' or pattern[9] not in ('false', 'true') or pattern[10:] != [',', '.', '.', '}']: return False + variant, field_name, alias = pattern[3], pattern[5], pattern[7] + if (variant, field_name) not in bool_fields or body not in (['*', alias, '=', 'true'], ['*', alias, '=', 'false']): return False + if context(body_start) != transition: return False + bound = True + elif any(t.isidentifier() and t[0].islower() and t != '_' for t in pattern): return False + if tokens[pos:pos + 1] == [',']: pos += 1 + return bound + + for i, token in enumerate(tokens): + if token not in ('self', field, name, 'Self', '!', '*'): continue + owner = context(i) + if token == 'self' and (owner is not None or self_is_machine(i) and any(a < i < b for a, b, _, _ in functions)): + if tokens[i + 1:i + 2] != ['.'] and not any(start == i for start, _ in safe_matches.values()): + problems.append(f'{location(i)}: machine reference may escape the authorized writer') + if token == field and i and tokens[i - 1] == '.' and not unrelated_projection(i): + start = i - 1 + while start > 0 and tokens[start - 1] not in (';', '{', '}'): + start -= 1 + prefix = tokens[start:i] + # A shared reference can also escape and mutate interior-mutable state later. + root = i - 2 + while root and tokens[root - 1] == '(': root -= 1 + logical_and = tokens[max(0, root - 2):root] == ['&', '&'] and root > 2 and (tokens[root - 3].isidentifier() or tokens[root - 3] in (')', ']', '}')) + borrowed = (tokens[root - 1:root] == ['&'] and not logical_and or tokens[max(0, root - 2):root] == ['&', 'mut'] or + any(prefix[j:j + 2] == ['ref', 'mut'] for j in range(len(prefix) - 1))) + enclosing = [(a, b, sig) for a, b, _, sig in functions if a < i < b] + signature = min(enclosing, key=lambda x: x[1] - x[0])[2] if enclosing else [] + arrow = next((j for j in range(len(signature) - 1) if signature[j:j + 2] == ['-', '>']), len(signature)) + result = signature[arrow + 2:] + reference_result = '&' in result or 'DerefMut' in result + forwarded = '=' in prefix or '(' in prefix + matched_read = any(start + 2 == i and comma == i + 1 for start, comma in safe_matches.values()) + copied_argument = copy_argument(i, prefix) + mutable_borrow = tokens[max(0, root - 2):root] == ['&', 'mut'] or any(prefix[j:j + 2] == ['ref', 'mut'] for j in range(len(prefix) - 1)) + proven_read = not mutable_borrow and shared_read(i) + intrinsic = owned_take(i, owner) or owned_bool_match(i, owner) + mutable_result = any(result[j:j + 2] == ['&', 'mut'] for j in range(len(result) - 1)) + if ((reference_result and not proven_read or mutable_result) or (not matched_read and not intrinsic and not proven_read and (borrowed or 'addr_of_mut' in prefix or + (owner != transition and ((forwarded and not copied_argument) or '!' in prefix or mutation_in_tail(tokens[i + 1:])))))): + problems.append(f'{location(i)}: owned field {field} projection may mutate or escape the authorized writer (scope={owner})') + # Destructuring may bind by reference; constructing a machine is restricted to its constructor. + if token in (name, 'Self') and (token == name or reader is None or self_is_machine(i)) and i + 1 in ends and tokens[i + 1] == '{': + if i and tokens[i - 1] in ('struct', 'enum', 'impl'): continue + if any(a == i + 1 for a, _, _, _ in functions) or any(a == i + 1 for a, _, _ in impls): continue + stop = ends[i + 1] + pattern = tokens[stop + 1:stop + 2] == ['='] or tokens[stop + 1:stop + 3] == ['=', '>'] + if field in tokens[i + 2:stop] and ((pattern and owner != transition) or (not pattern and owner != constructor and not (require_methods and any(i == start for start, _, _ in constants)))): + problems.append(f'{location(i)}: state construction/destructuring outside {constructor} or {transition}') + if token == '!' and macro_invocation(tokens, i, ends) and owner != transition: + args = tokens[i + 2:ends[i + 1]] + if (((reader is None or self_is_machine(i)) and any(t == 'self' and args[j + 1:j + 2] != ['.'] for j, t in enumerate(args))) or any(t == field and j and args[j - 1] == '.' for j, t in enumerate(args))) and i not in safe_matches and i not in safe_asserts and not (reader is not None and (i < 3 or tokens[i - 3:i - 1] != [':', ':']) and tokens[i - 1] in ('matches', 'assert', 'debug_assert', 'vec', 'format', 'format_args', 'write', 'writeln', 'panic') and reader[0].builtin(reader[0].root / label, tokens[i - 1])): + problems.append(f'{location(i)}: macro may hide a state mutation outside {transition}') + if token == '*' and tokens[i + 1:i + 3] == ['self', '='] and owner != transition and (reader is None or self_is_machine(i)): + problems.append(f'{location(i)}: replacement of self outside {transition}') + return problems + + + + + +def wildcard_problems(source, label, require_header=True): + tokens = production_tokens(source) + ends = ends_of(tokens) + lint = ['clippy', ':', ':', 'wildcard_enum_match_arm'] + found = False + i = 0 + while tokens[i:i + 3] == ['#', '!', '['] and i + 2 in ends: + end = ends[i + 2] + attr = tokens[i + 3:end] + if attr in (['deny', '('] + lint + [')'], ['forbid', '('] + lint + [')']): found = True + i = end + 1 + problems = [] if found or not require_header else [f'{label}: module must have #![deny(clippy::wildcard_enum_match_arm)]'] + for i in range(len(tokens) - 2): + bracket = i + 2 if tokens[i:i + 3] == ['#', '!', '['] else i + 1 + if tokens[i] != '#' or bracket not in ends or tokens[bracket] != '[': continue + attr = tokens[bracket + 1:ends[bracket]] + if any(level in attr for level in ('allow', 'expect', 'warn')) and any(x in attr for x in ('wildcard_enum_match_arm', 'warnings', 'all')): + problems.append(f'{label}: wildcard enum lint may not be locally suppressed') + return problems + + +def production_sources(path, root): + """Exhaust the registered production closure; never guess conditional/generated paths.""" + root = Path(root).resolve() + pending, seen = [Path(path).resolve()], set() + while pending: + current = pending.pop() + if not current.is_relative_to(root): + raise ValueError(f'production include escapes rust-modules: {current}') + if current in seen: continue + seen.add(current) + source = current.read_text(encoding='utf-8') + tokens = rtm.lex(source) + ends = rtm.group_ends(tokens) + module_dir = current.parent if current.name in ('mod.rs', 'lib.rs', 'main.rs') else current.with_suffix('') + def walk(start, stop, directory, attribute_base, inherited_test=False): + i, attrs = start, [] + while i < stop: + kind, text = tokens[i] + if kind != 'code': i += 1; continue + if text == '#' and i + 1 < stop and tokens[i + 1][1] == '[': + end = ends.get(i + 1) + if end is None: raise ValueError(f'{current}: unresolved attribute') + attrs.append(tokens[i + 2:end]); i = end + 1; continue + test = inherited_test or any(a and a[0][1] == 'cfg' and rtm.cfg_without_tests(a[2:-1]) == {False} for a in attrs) + conditional_path = any(a and a[0][1] == 'cfg_attr' and any(t == ('code', 'path') for t in a) for a in attrs) + paths = [a[2][1] for a in attrs if len(a) == 3 and a[:2] == [('code', 'path'), ('code', '=')] and a[2][0] == 'string'] + if not test and conditional_path: + raise ValueError(f'{current}: production cfg_attr(path) is unresolved') + if text == 'mod' and i + 2 < stop: + name, form = tokens[i + 1][1], tokens[i + 2][1] + if form in (';', '{'): + if not test and (len(paths) > 1 or any(a and a[0][1] == 'path' for a in attrs) and not paths): + raise ValueError(f'{current}: unresolved module path') + if form == ';': + candidates = [attribute_base / paths[0]] if paths else [directory / (name + '.rs'), directory / name / 'mod.rs'] + targets = [p.resolve() for p in candidates if p.is_file()] + if not test: + if len(targets) != 1: raise ValueError(f'{current}: unresolved production module {name}') + pending.extend(targets) + i += 3 + else: + end = ends.get(i + 2) + if end is None: raise ValueError(f'{current}: unresolved inline module {name}') + nested = attribute_base / paths[0] if paths else directory / name + walk(i + 3, end, nested, nested, test) + i = end + 1 + attrs = []; continue + if text == 'include' and tokens[i + 1:i + 2] == [('code', '!')]: + end = ends.get(i + 2) + if not test: + if end != i + 4 or tokens[i + 2][1] != '(' or tokens[i + 3][0] != 'string': + raise ValueError(f'{current}: opaque production include!') + target = (current.parent / tokens[i + 3][1]).resolve() + if not target.is_file(): raise ValueError(f'{current}: unresolved production include!') + pending.append(target) + i = end + 1 if end is not None else stop + attrs = []; continue + if text in ('{', '(', '['): + end = ends.get(i) + if end is None: raise ValueError(f'{current}: unbalanced production group') + if text == '{': walk(i + 1, end, directory, attribute_base, test) + i = end + 1 + attrs = []; continue + if text in (';', ','): attrs = [] + i += 1 + walk(0, len(tokens), module_dir, current.parent) + yield current + + def check(modules=MODULES, ini=INI): - """([problem], [report line]) for every machine in the registry.""" + """([problem], [report line]) for every machine and module in the registry.""" parser = configparser.ConfigParser(interpolation=None, comment_prefixes=('#',), inline_comment_prefixes=None) try: with open(ini, encoding='utf-8') as f: @@ -76,34 +863,103 @@ def check(modules=MODULES, ini=INI): except (OSError, configparser.Error) as error: return [f'{Path(ini).name} does not parse: {error}'], [] problems, report = [], [] + if parser.defaults(): + problems.append('machines.ini: DEFAULT keys are not permitted') + strict_keys = {'writer_policy', 'state_field', 'transition', 'constructor'} + if not parser.sections(): + problems.append('machines.ini: registry must not be empty') for section in parser.sections(): + entry = parser[section] + is_module = section.startswith('module ') file, _, name = section.partition('::') - path = Path(modules) / file - if not name or not path.is_file(): + if is_module: file = section[len('module '):] + root = Path(modules).resolve() + path = (root / file).resolve() + if not file or not path.is_relative_to(root) or not path.is_file() or (not is_module and not name): problems.append(f'machines.ini [{section}]: no such file under rust-modules/ (stale entry: fix or remove it)') continue - fields = struct_fields(path.read_text(), name) + file = path.relative_to(root).as_posix() + if is_module: + if set(entry) != {'wildcard_enum_match_arm'} or entry.get('wildcard_enum_match_arm') != 'deny': + problems.append(f'machines.ini [{section}]: module requires wildcard_enum_match_arm = deny') + continue + try: + for child in production_sources(path, root): + problems.extend(wildcard_problems(child.read_text(encoding='utf-8'), + f'module {child.relative_to(root).as_posix()}', require_header=child == path)) + except (OSError, ValueError) as error: + problems.append(f'machines.ini [{section}]: cannot analyze enum policy: {error}') + report.append(f'enum policy {file}: clippy::wildcard_enum_match_arm deny') + continue + if 'module ' + file not in parser: + problems.append(f'machines.ini [{section}]: missing enum policy [module {file}]') + unknown = set(entry) - {'event', 'effect', 'step', 'state_reads', 'aux_facts'} - strict_keys + if unknown: + problems.append(f'machines.ini [{section}]: unknown keys: {", ".join(sorted(unknown))}') + aux_facts = entry.get('aux_facts', '').strip() + if aux_facts != AUX_FACTS.get(section, ''): + problems.append(f'{section}: auxiliary fact contract must be {AUX_FACTS.get(section, "none")}') + continue + source = path.read_text(encoding='utf-8') + fields = struct_fields(source, name) if fields is None: problems.append(f'machines.ini [{section}]: {file} declares no struct {name} (stale entry: fix or remove it)') continue for is_pub, field, _ in fields: if is_pub: - problems.append(f'{file}::{name}.{field} is public: a machine\'s state is private and its one ' - f'writer is `step`; a new way to change it is a new event (docs/sans-io.md)') + problems.append(f"{file}::{name}.{field} is public: a machine's state is private and its one " + f"writer is transition; a new way to change it is a new event (docs/sans-io.md)") bools = sum(1 for _, _, t in fields if t == ['bool']) options = sum(1 for _, _, t in fields if t[:2] == ['Option', '<']) - entry = parser[section] report.append(f'machine {section} ({entry.get("event", "?")} -> {entry.get("effect", "?")}): ' f'{len(fields)} fields, {bools} bool, {options} Option') + values = {key: entry.get(key, '').strip() for key in strict_keys} + if values['writer_policy'] != 'strict' or any(not values[k].isidentifier() for k in ('state_field', 'transition', 'constructor')): + problems.append(f'machines.ini [{section}]: strict contract requires writer_policy = strict and nonempty state_field, transition and constructor identifiers') + continue + field, transition, constructor = (values[k] for k in ('state_field', 'transition', 'constructor')) + if transition == constructor: + problems.append(f'machines.ini [{section}]: transition and constructor must differ') + continue + if field not in {f for _, f, _ in fields}: + problems.append(f'machines.ini [{section}]: no state field {field} (stale strict contract)') + continue + if transition != 'transition': + problems.append(f'{section}: canonical method must be named transition') + event, effect = entry.get('event', '').strip(), entry.get('effect', '').strip() + if not event or not all(part.isidentifier() for part in event.split('::')) or not effect or not all(part.isidentifier() for part in effect.split('::')): + problems.append(f'{section}: event/effect require exact Rust type paths (or effect = none)') + continue + from machine_readonly import Proof + from types import SimpleNamespace + proof = Proof(root, SimpleNamespace(production_tokens=production_tokens, ends_of=ends_of, + shape=shape, struct_fields=struct_fields, item_bodies=item_bodies, inherent_target=inherent_target)) + if entry.get('state_reads') is not None and entry['state_reads'] != 'immutable': + problems.append(f'{section}: state_reads must be immutable') + continue + if entry.get('state_reads') == 'immutable' and proof.generic_context(path, name) is None: + problems.append(f'{section}: generic state bounds do not prove immutable identities') + try: + for child in production_sources(path, root): + child_source = source if child == path else child.read_text(encoding='utf-8') + problems.extend(writer_problems(child_source, name, field, transition, constructor, + child.relative_to(root).as_posix(), + require_methods=child == path, event=event, effect=effect, proof=proof, shared_reads=entry.get('state_reads') == 'immutable', owned_fields=fields, owner_path=path, aux_facts=aux_facts)) + except (OSError, ValueError) as error: + problems.append(f'machines.ini [{section}]: cannot analyze production sources: {error}') + if proof.audit: + report.append(f'immutable state read audit {section}: ' + ', '.join(sorted(proof.audit))) return problems, report + def main(): problems, report = check() for line in report: print(line) for problem in problems: print(f'check-machine-shape: {problem}', file=sys.stderr) if problems: return 1 - print(f'check-machine-shape: ok ({len(report)} machine{"" if len(report) == 1 else "s"}; ' + machines = sum(line.startswith('machine ') for line in report) + print(f'check-machine-shape: ok ({machines} machine{"" if machines == 1 else "s"}; ' f'flag counts are report-only)') return 0 diff --git a/ci/check-plex-requests.py b/ci/check-plex-requests.py index b6acf9eaf9..bf5649ab63 100644 --- a/ci/check-plex-requests.py +++ b/ci/check-plex-requests.py @@ -98,16 +98,34 @@ def code(tokens, i): def item_end(tokens, ends, j): - """The index that closes the item beginning at token j: its `;`, or the `}` of its body.""" + """The last token of a cfg-gated item or field, without consuming its enclosing scope.""" n = len(tokens) + start = j + while code(tokens, start) == '#' and code(tokens, start + 1) == '[' and start + 1 in ends: + start = ends[start + 1] + 1 + if code(tokens, start) == 'pub': + start += 1 + if code(tokens, start) == '(': + start = ends.get(start, n - 1) + 1 + field = bool(WORD.match(code(tokens, start) or '')) and code(tokens, start + 1) == ':' \ + and code(tokens, start + 2) != ':' + angle = 0 while j < n: if tokens[j][0] == 'code': text = tokens[j][1] if text == '#' and code(tokens, j + 1) == '[' and (j + 1) in ends: j = ends[j + 1] + 1; continue if text == ';': return j - if text == '{': return ends.get(j, n - 1) - if text in ('(', '['): j = ends.get(j, n - 1) + 1; continue + if text == '=' and code(tokens, j + 1) == '>': field = True + if field: + # Commas inside generic field types are not field separators. A following named + # field still ends a comparison expression such as hidden: x < 2, live: value. + if text == '}': return j - 1 + if text == ',' and (angle == 0 or code(tokens, j + 2) == ':'): return j + if text == '<': angle += 1 + elif text == '>': angle = max(0, angle - 1) + if text == '{' and not field: return ends.get(j, n - 1) + if text in ('(', '[', '{'): j = ends.get(j, n - 1) + 1; continue j += 1 return n - 1 diff --git a/ci/check-ports.py b/ci/check-ports.py new file mode 100644 index 0000000000..f799bb17b4 --- /dev/null +++ b/ci/check-ports.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Exact-file wall-clock ports; no directories, stale paths, or machine modules.""" +import argparse +import configparser +import importlib.util +import re +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import rust_test_modules as rtm +spec = importlib.util.spec_from_file_location('machine_shape', Path(__file__).with_name('check-machine-shape.py')) +shape = importlib.util.module_from_spec(spec) +spec.loader.exec_module(shape) +ROOT = Path(__file__).resolve().parent.parent +SCOPES = ('rust-modules/data/src', 'rust-modules/session/src', 'rust-modules/ui/src', + 'rust-modules/machine/src', 'rust-modules/appkit/src', 'rust-modules/screens/src', + 'rust-modules/src/app', 'rust-modules/plex/src/plex/session.rs', + 'rust-modules/media/src/route/backend_policy.rs', 'rust-modules/media/src/route/plan.rs', + 'rust-modules/media/src/route/plan_memory.rs', 'rust-modules/media/src/player/lifecycle.rs') +WALL = re.compile(r'(?:Instant|SystemTime)::(?:now|elapsed)|\.elapsed\(') +def wall_sites(tokens): + alias = any(tokens[i] in ('Instant', 'SystemTime') and tokens[i + 1:i + 2] == ['as'] for i in range(len(tokens) - 1)) + return alias or bool(WALL.search(''.join(tokens))) +def ports(root, ini): + config = configparser.ConfigParser(interpolation=None, strict=True) + config.read_string(ini.read_text(encoding='utf-8')) + if config.defaults(): raise ValueError('ports.ini: DEFAULT exemptions are not permitted') + registry = root / 'ci/machines.ini' + machines = configparser.ConfigParser(interpolation=None) + if registry.exists(): machines.read(registry, encoding='utf-8') + listed = {'rust-modules/' + section.split('::')[0] for section in machines.sections() + if not section.startswith('module ')} + result = set() + for name in config.sections(): + path = Path(name) + if (path.is_absolute() or not name.startswith('rust-modules/') or path.suffix != '.rs' + or any(part in ('.', '..') for part in name.split('/')) + or any(c in name for c in '\\*?[]:') or name != path.as_posix()): + raise ValueError(f'{name}: port must be one exact repo-relative Rust file') + if set(config[name]) != {'kind', 'reason'} or config[name]['kind'] not in ('worker', 'adapter', 'instrument'): + raise ValueError(f'{name}: expected kind (worker/adapter/instrument) and reason only') + if not config[name]['reason'].strip(): raise ValueError(f'{name}: missing reason') + target = root / path + if not target.is_file() or target.is_symlink() or not target.resolve().is_relative_to(root.resolve()): + raise ValueError(f'{name}: stale or escaping port path') + tokens = shape.production_tokens(target.read_text(encoding='utf-8')) + code = ' '.join(tokens) + if name in listed or re.search(r'\bfn (?:step|transition)\b|\bimpl [^{;]*\bMachine\b', code): + raise ValueError(f'{name}: machine logic cannot be exempted as a port') + if not wall_sites(tokens): raise ValueError(f'{name}: stale port without a wall-clock operation') + result.add(name) + return result + +def check(root=ROOT, ini=None): + exempt = ports(root, ini or root / 'ci/ports.ini') + tests = set() + for scope in SCOPES: + path = root / scope + if path.is_dir(): tests.update(rtm.wholly_test_files(path)) + problems = [] + files = set() + for scope in SCOPES: + path = root / scope + files.update(path.rglob('*.rs') if path.is_dir() else ([path] if path.exists() else [])) + for path in sorted(files): + name = path.relative_to(root).as_posix() + if name in exempt or path.resolve() in tests: continue + if wall_sites(shape.production_tokens(path.read_text(encoding='utf-8'))): + problems.append(f'{name}: wall clock outside ci/ports.ini') + return problems + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', type=Path, default=ROOT) + args = parser.parse_args() + try: problems = check(args.root) + except (ValueError, configparser.Error, OSError) as error: problems = [str(error)] + if problems: + print('\n'.join(problems), file=sys.stderr) + return 1 + print('wall: all data/session and machine scopes; exact ports only') + return 0 +if __name__ == '__main__': sys.exit(main()) diff --git a/ci/check-python-steps.txt b/ci/check-python-steps.txt index 6ff435f595..6017d0aa3b 100644 --- a/ci/check-python-steps.txt +++ b/ci/check-python-steps.txt @@ -335,6 +335,7 @@ python3 ci/check-rust-inputs.py # way to change it is a new event. It also REPORTS, and never fails on, each machine's `bool` and `Option<..>` field counts: a # report-only flag ratchet. Pure lexing, no cargo; the self-tests run on synthetic trees in a private temp dir. python3 ci/test_check_machine_shape.py +python3 ci/test_check_machine_writer.py python3 ci/check-machine-shape.py # tools/pr-land.py (gate / wait / merge / restack) against a fake `gh` on PATH and an injected sleeper: a failed, pending, missing, draft, behind # or head-moved PR never reaches `gh pr merge` (#387), the polling and backoff, the head-oid race, the verify against a temporary @@ -391,6 +392,14 @@ python3 tests/test_hud_bundle.py python3 tests/test_hud_release.py python3 ci/test_sim_backend.py python3 tests/test_hud_dev.py + +python3 ci/test_check_ports.py +python3 ci/test_step_scope.py +python3 ci/test_machine_readonly.py +python3 ci/test_readonly_dependencies.py +python3 ci/test_readonly_generated.py +python3 ci/test_transition_arguments.py + # tools/cold-store.py, the opt-in cold store that parks idle build trees on a second volume: unconfigured it creates no file anywhere; each # reason `available()` can give (no config, no ditto, an unmounted /Volumes root, the same device as the build tree, under min_free_gib, a # failing probe write); park then unpark restores every path, size, nanosecond mtime, mode and hard-link group; unpark fills only an absent @@ -401,3 +410,4 @@ python3 tests/test_hud_dev.py # free-space/clock override refused unless every root is named. Temp dirs, a faked two-volume device check and a shutil stand-in for `ditto` # (one darwin-only test drives the real one); touches no real cache, config or volume. python3 ci/test_cold_store.py +python3 ci/test_verdict_data_captured_inputs_source_oracle.py \ No newline at end of file diff --git a/ci/check-statics.sh b/ci/check-statics.sh index d5d7989a0f..d08dfec75e 100755 --- a/ci/check-statics.sh +++ b/ci/check-statics.sh @@ -19,7 +19,9 @@ # wider spelling (`^\s*(pub(\(crate\))? )?static `, not just `static mut`) because that module # holds `recents.rs`'s two `Mutex`-guarded persistence-seam statics (STORE, PENDING) — real # process-wide state the narrower pattern cannot see. The wider pattern is NOT applied to the -# other gated directories: run tree-wide it also matches every `thread_local! { static … }` +# other gated directories. The Search scan uses the ledger lexer to exclude comments, literals +# and cfg(test)-only items (including the test global allocator); production-visible immutable +# statics still count. Run tree-wide it would also match every `thread_local! { static … }` # interior declaration (a different, safe, per-thread idiom used all over ui/ and screens/ for # render caches and test doubles), which would surface on the order of 80 unrelated hits in one # gate change. That widening is deliberately out of scope here — see the PR discussion — and @@ -70,7 +72,7 @@ done # matches: `pathNAME` for every gated static declaration. matches() { { grep -rnE --include='*.rs' '^\s*static mut [A-Za-z_][A-Za-z_0-9]*' "${GATED_MUT_PATHS[@]}" - grep -rnE --include='*.rs' '^\s*(pub(\(crate\))? )?static (mut )?[A-Za-z_][A-Za-z_0-9]*' "${GATED_WIDE_PATHS[@]}" + printf '%s\n' "$wide" grep -nE '^\s*static mut SESSION\b' "$MEDIA/route/decision.rs" | sed "s|^|$MEDIA/route/decision.rs:|" grep -nE '^\s*static mut ENGINE\b' "$MEDIA/player/engine.rs" | sed "s|^|$MEDIA/player/engine.rs:|" grep -nE '^\s*static mut S\b' "$UI/press.rs" | sed "s|^|$UI/press.rs:|" @@ -78,6 +80,7 @@ matches() { } echo "== check-statics ==" +wide=$(find "${GATED_WIDE_PATHS[@]}" -name '*.rs' -type f -exec env LG_MODE=static awk -f ci/ledger.awk {} +) || fail "Search static scanner failed" all=$(matches) # once: under pipefail a piped grep -q fails on the early close # pathNAMEtype — why. A crashed detector must be red, not an empty list the loop below calls ok. heap=$(python3 -I ci/check-statics-heap.py) || fail "ci/check-statics-heap.py failed — the heap rule below read nothing" diff --git a/ci/ledger.awk b/ci/ledger.awk index 25692965b3..0254f369ea 100644 --- a/ci/ledger.awk +++ b/ci/ledger.awk @@ -10,7 +10,7 @@ # (an alias the call-site grep cannot count). Everything is configured through the environment, # because awk's -v would process the backslashes of a regex: # -# LG_MODE call (default) | fork | arm +# LG_MODE call (default) | fork | arm | static (production static declarations as pathname) # -- call: every occurrence of LG_SITE on a code line is a site -- # LG_SITE ERE of one call site, `(^|[^A-Za-z0-9_])name\(` style (awk has no \b) # LG_DEF ERE of a definition header (`fn name(`): blanked before matching, so it is neither a @@ -220,9 +220,16 @@ function contname(code, s) { function enclosing() { return (top > 0) ? stack[top] : ((pending != "") ? pending : ((ctop > 0) ? cstack[ctop] : "?")) } function pop_to(d) { while (top > 0 && sdepth[top] > d) top--; while (ctop > 0 && csdepth[ctop] > d) ctop-- } -function emit_calls(code, hit, rest, m) { +function emit_calls(code, hit, rest, m, label) { rest = code while (match(rest, SITE)) { + # A field declaration/label names data, not a function value. Keep scanning its RHS, + # and do not suppress a namespace separator (`::`) or a bare callback reference. + label = substr(rest, RSTART + RLENGTH - 1) ~ /^[[:space:]]*:([^:]|$)/ + if (label) { + rest = substr(rest, RLENGTH > 1 ? RSTART + RLENGTH - 1 : RSTART + 1) + continue + } if (KEYSPELL != "") { m = substr(rest, RSTART, RLENGTH) gsub(/^[^A-Za-z0-9_]+/, "", m); gsub(/[^A-Za-z0-9_]+$/, "", m) @@ -375,6 +382,12 @@ function scan_file( i, code, scan, uline, name, k, hit, rest, p, txt, v, n, o if (pending != "" && code ~ /fn[[:space:]]/ && code ~ /\{/) hit = pending emit_calls(scan, hit) } + } else if (MODE == "static") { + if (match(code, /^[[:space:]]*(pub(\([^)]*\))?[[:space:]]+)?static[[:space:]]+(mut[[:space:]]+)?[A-Za-z_][A-Za-z0-9_]*/)) { + name = substr(code, RSTART, RLENGTH) + sub(/.*static[[:space:]]+(mut[[:space:]]+)?/, "", name) + print file "\t" name + } } else if (MODE == "fork") { p = index(code, "cfg!(") while (p > 0) { diff --git a/ci/list-caps.ini b/ci/list-caps.ini index 8865ccbeb0..178f444af3 100644 --- a/ci/list-caps.ini +++ b/ci/list-caps.ini @@ -20,6 +20,10 @@ # Do not class a site `work` or `preview` on a guess: read the code until you know whether content # past the bound is reachable. The list only shrinks: removing a cap removes its section. +[plex/src/plex/client_keys.rs::refill] +class = not-a-list +reason = Refill retains every current source in the clock-facts cache, then truncates only stale rows left from the previous roster; no source or browsable content is capped. + [plex/src/plex/client_keys.rs::refill_roster_with_stream_policy] class = not-a-list reason = The truncate trims reusable metadata storage to the number of slots visited after the full roster walk, omitting no registered slot or reachable content. @@ -322,10 +326,6 @@ reason = Window size of a shelf (the card row's spring capacity); every truncati class = work reason = On a profile switch a paged shelf is reset to its preview (offset 0) so the next ask starts at the head; the window re-pages from there. -[data/src/pms.rs::seed_two_library_home_for_test] -class = not-a-list -reason = Test seeding helper slicing the first two sections. - [data/src/search.rs::LIMIT] class = work reason = First ask per hub of /hubs/search; rows page by typed listing or grow the limit (tail.rs), so hits past it are reached. @@ -1359,9 +1359,13 @@ reason = CAP_NOTE_RESERVE: uI timing, geometry, recorder or frame-budget bound; class = not-a-list reason = DATA_CAP_BYTES: uI timing, geometry, recorder or frame-budget bound; not a list. -[ui/src/rec.rs::create] -class = not-a-list -reason = create: uI timing, geometry, recorder or frame-budget bound; not a list. +[ui/src/rec.rs::MAX_METRICS] +class = work +reason = Bounds the number of distinct captured measurement queries in the recorder and replay table; overflow fails capture or loading, not access to browsable content. + +[ui/src/rec.rs::MAX_METRIC_BYTES] +class = work +reason = Bounds retained measurement-key bytes in the recorder; overflow fails capture instead of retaining a partial recording, not a browsable list. [ui/src/table.rs::menu_panel_width] class = not-a-list @@ -1469,10 +1473,6 @@ reason = Bounded local diagnostic summaries; lifetime aggregate counts and durat class = work reason = Bounds local typed backend notice history to 32 results; the reducer keeps aggregate request counts and durations when older details are evicted. -[play-feed/src/ff_fixture_bytes.rs::rpu_fixture_nal] -class = format -reason = Replace the four-byte Annex-B start code with the two-byte HEVC NAL header in the wire fixture. - [data/src/hudpacks.rs::MAX_PACKAGE_ID_BYTES] class = format reason = Shared package and installed-index identifier byte limit, bounding persisted metadata and diagnostic names independently of transport size. diff --git a/ci/machine_readonly.py b/ci/machine_readonly.py new file mode 100644 index 0000000000..ac53f0d9e4 --- /dev/null +++ b/ci/machine_readonly.py @@ -0,0 +1,610 @@ +"""Bounded structural proof for shared reads of a registered owned state. + +Only immutable standard containers are axioms. Local fields and aliases are followed through +module imports; opaque/ambiguous types, callbacks, raw pointers and interior authority fail closed. +Safe Rust then prevents an &self method from changing the proved owned state. +""" +from pathlib import Path +import re + +PRIMITIVES = set('bool char str u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize f32 f64'.split()) +WRAPPERS = {'Vec', 'Option', 'Arc', 'String', 'VecDeque', 'BTreeMap', 'BTreeSet', 'Result', 'PathBuf'} +STD = {'std::vec::Vec', 'alloc::vec::Vec', 'std::option::Option', 'core::option::Option', + 'std::sync::Arc', 'alloc::sync::Arc', 'std::string::String', 'alloc::string::String', + 'std::collections::VecDeque', 'std::collections::BTreeMap', 'std::collections::BTreeSet', 'std::path::PathBuf', + 'std::result::Result', 'core::result::Result'} + +def cache_proof(method): + """Memoize one immutable Proof snapshot, not repository authority or a writer exemption.""" + def freeze(value): + if isinstance(value, (list, tuple)): return tuple(freeze(v) for v in value) + if isinstance(value, dict): return tuple(sorted((k, freeze(v)) for k, v in value.items())) + if isinstance(value, set): return frozenset(freeze(v) for v in value) + return value + def cached(self, *args, **kwargs): + if not hasattr(self, 'memo'): self.memo = {} + key = method.__name__, freeze(args), freeze(kwargs) + if key not in self.memo: self.memo[key] = method(self, *args, **kwargs) + return self.memo[key] + return cached + +def macro_invocation(tokens, bang, ends): + """A bang after an identifier is a macro, unlike logical negation after if/return.""" + return (bang > 0 and bang + 1 in ends and tokens[bang - 1].isidentifier() and + tokens[bang - 1] not in {'if', 'while', 'for', 'return', 'match', 'let', 'else', 'yield', 'break', 'continue'}) + +def split(tokens, delimiter=','): + result, current, depth = [], [], 0 + for index, token in enumerate(tokens): + if token == delimiter and not depth: + result.append(current); current = []; continue + depth += (token in '([{<') - (token in ')]}>' and not (token == '>' and index and tokens[index - 1] == '-')) + current.append(token) + if current: result.append(current) + return result + +def imports(tokens, prefix=()): + if '{' in tokens: + start = tokens.index('{'); depth, stop = 1, start + 1 + while depth and stop < len(tokens): + depth += (tokens[stop] == '{') - (tokens[stop] == '}'); stop += 1 + base = tuple(t for t in tokens[:start] if t != ':') + return [entry for item in split(tokens[start + 1:stop - 1]) for entry in imports(item, prefix + base)] + if 'as' in tokens: + at = tokens.index('as'); alias = tokens[at + 1]; tokens = tokens[:at] + else: alias = (prefix[-1] if prefix else '') if tokens == ['self'] else tokens[-1] if tokens else '' + target = prefix if tokens == ['self'] else prefix + tuple(t for t in tokens if t != ':') + return [(alias, target)] + + +class Proof: + def __init__(self, root, shape): + self.root, self.shape = Path(root), shape + self.cache, self.visiting, self.audit = {}, set(), set() + self.crates = {} + for manifest in self.root.glob('*/Cargo.toml'): + text = manifest.read_text(encoding='utf-8') + sections = dict(re.findall(r'(?ms)^\[([^\]]+)\]\s*$(.*?)(?=^\[|\Z)', text)) + match = re.search(r'(?m)^name\s*=\s*"([A-Za-z0-9_-]+)"', sections.get('lib', '')) + if match is None: match = re.search(r'(?m)^name\s*=\s*"([A-Za-z0-9_-]+)"', sections.get('package', '')) + name = match[1].replace('-', '_') if match else '' + if name: self.crates[name] = manifest.parent / 'src/lib.rs' + + def module(self, path): + path = Path(path).resolve() + if path in self.cache: return self.cache[path] + from readonly_generated import declarations + generated = declarations(self.root, path) + tokens = self.shape.production_tokens(path.read_text(encoding='utf-8') + '\n' + generated) + if generated: self.audit.add('source-backed generated data ' + path.relative_to(self.root.resolve()).as_posix()) + ends = self.shape.ends_of(tokens) + reverse = {end: begin for begin, end in ends.items()} + definitions, uses = {}, [] + def field_type(index, item): + remaining = item + while remaining[:2] == ['#', '[']: + groups = self.shape.ends_of(remaining) + stop = groups.get(1) + if stop is None or remaining[2:3] not in (['serde'], ['doc'], ['cfg'], ['allow'], ['deny'], ['forbid']): return [''] + remaining = remaining[stop + 1:] + return self.shape.shape(index, item)[2] + for i, token in enumerate(tokens[:-1]): + if token == 'use': + end = i + 1 + while end < len(tokens) and tokens[end] != ';': end += 1 + uses.extend(imports(tokens[i + 1:end])) + if token not in ('struct', 'enum', 'type'): continue + name, j = tokens[i + 1], i + 2 + parameters = [] + if tokens[j:j + 1] == ['<']: + depth, stop = 1, j + 1 + while depth and stop < len(tokens): + depth += (tokens[stop] == '<') - (tokens[stop] == '>'); stop += 1 + parameters = [part[0] for part in split(tokens[j + 1:stop - 1]) if part and part[0] != "'"] + j = stop + if token == 'type': + if tokens[j:j + 1] != ['=']: continue + stop = j + 1 + while stop < len(tokens) and tokens[stop] != ';': stop += 1 + payload = [tokens[j + 1:stop]] + else: + if tokens[j:j + 1] == [';']: payload = [] + elif j not in ends or tokens[j] not in ('{', '('): continue + elif token == 'struct': payload = [field_type(k, item) for k, item in enumerate(split(tokens[j + 1:ends[j]]))] + else: + payload = [] + for variant in split(tokens[j + 1:ends[j]]): + while variant[:2] == ['#', '[']: + stop = variant.index(']'); variant = variant[stop + 1:] + if len(variant) > 1 and variant[1] in ('(', '{'): + items = split(variant[2:-1]) + payload.extend(field_type(k, item) for k, item in enumerate(items)) + # Attribute macros (including conditional ones) can rewrite the original layout. + start = i + if start and tokens[start - 1] == 'pub': start -= 1 + elif start and tokens[start - 1] == ')' and start - 1 in reverse: + begin = reverse[start - 1] + if begin and tokens[begin - 1] == 'pub': start = begin - 1 + attributes = [] + while start and tokens[start - 1] == ']' and start - 1 in reverse: + begin = reverse[start - 1] + if not begin or tokens[begin - 1] != '#': break + attributes.append(tokens[begin + 1:start - 1]) + start = begin - 1 + for attribute in attributes: + if attribute[0] == 'serde': + derives = [a for a in attributes if a[0] == 'derive'] + serde_derive = any('serde' in a and any(n in a for n in ('Serialize', 'Deserialize')) for a in derives) + serde_derive |= any(any(n in a for n in ('Serialize', 'Deserialize')) and + any(alias in a and target in (('serde', 'Serialize'), ('serde', 'Deserialize')) for alias, target in uses) for a in derives) + if serde_derive: continue + if attribute[0] not in ('derive', 'repr', 'cfg', 'doc', 'allow', 'deny', 'forbid', 'non_exhaustive'): + payload = [['']] + definitions.setdefault(name, []).append((parameters, payload, token)) + self.cache[path] = (tokens, ends, definitions, uses) + return self.cache[path] + + + + + + + + + @cache_proof + def child(self, path, name): + """Resolve one declared child, including a literal path attribute; conditional paths fail.""" + import rust_test_modules as rtm + path = Path(path).resolve() + tokens = rtm.lex(path.read_text(encoding='utf-8')) + ends = rtm.group_ends(tokens) + reverse = {b: a for a, b in ends.items()} + matches = [i for i in range(len(tokens) - 2) if tokens[i:i + 3] == [('code', 'mod'), ('code', name), ('code', ';')]] + if len(matches) != 1: return None + before = matches[0] - 1 + if tokens[before:before + 1] == [('code', 'pub')]: before -= 1 + paths = [] + while before in reverse and tokens[before] == ('code', ']'): + begin = reverse[before] + if tokens[begin - 1:begin] != [('code', '#')]: break + attr = tokens[begin + 1:before] + if attr[:1] == [('code', 'cfg_attr')] and ('code', 'path') in attr: return None + if attr[:1] == [('code', 'path')]: + if len(attr) != 3 or attr[1] != ('code', '=') or attr[2][0] != 'string': return None + paths.append(attr[2][1]) + if attr[:1] == [('code', 'cfg')] and rtm.cfg_without_tests(attr[2:-1]) == {False}: return None + before = begin - 2 + directory = path.parent if path.name in ('lib.rs', 'mod.rs', 'main.rs') else path.with_suffix('') + candidates = [path.parent / paths[0]] if len(paths) == 1 else [directory / (name + '.rs'), directory / name / 'mod.rs'] if not paths else [] + found = [p.resolve() for p in candidates if p.is_file() and p.resolve().is_relative_to(self.root.resolve())] + if len(found) != 1: return None + from readonly_generated import canonical_child + if not canonical_child(self.root, path, name, found[0]): return None + if not hasattr(self, 'parent_paths'): self.parent_paths = {} + self.parent_paths[found[0]] = path + return found[0] + + def parent(self, path): + path = Path(path).resolve() + if path in getattr(self, 'parent_paths', {}): return self.parent_paths[path] + directory = path.parent if path.name not in ('lib.rs', 'mod.rs', 'main.rs') else path.parent.parent + candidates = [directory.with_suffix('.rs'), directory / 'mod.rs'] + if directory.name == 'src': candidates = [directory / 'lib.rs', directory / 'main.rs'] + return next((p.resolve() for p in candidates if p.is_file() and p.resolve() != path.resolve()), None) + + @cache_proof + def resolve(self, path, names, seen=None): + path, names = Path(path).resolve(), tuple(names) + key = (path, names) + seen = set() if seen is None else seen + if key in seen: return None + seen = seen | {key} + if not names: return None + if names[0] in ('std', 'core', 'alloc'): + local = self.module(path) + if any(local[0][i:i + 2] in (['mod', names[0]], ['as', names[0]]) for i in range(len(local[0]) - 1)): return None + return ('std', names[-1]) if '::'.join(names) in STD else None + if names[0] in self.crates: + local = self.module(path) + if names[0] in local[2] or any(alias == names[0] for alias, _ in local[3]) or any(local[0][i:i + 2] in (['mod', names[0]], ['crate', names[0]]) for i in range(len(local[0]) - 1)): return None + return self.resolve(self.crates[names[0]], names[1:], seen) + if names[0] == 'self': return self.resolve(path, names[1:], seen) + if names[0] == 'super': + parent = self.parent(path) + return self.resolve(parent, names[1:], seen) if parent else None + if names[0] == 'crate': + for ancestor in path.parents: + if (ancestor / 'Cargo.toml').is_file(): + return self.resolve(ancestor / 'src/lib.rs', names[1:], seen) + return None + tokens, ends, definitions, uses = self.module(path) + if len(names) == 1 and names[0] in definitions: + if len(definitions[names[0]]) != 1: return None + return (path, names[0]) + explicit = [target for alias, target in uses if alias == names[0]] + if len(explicit) == 1: return self.resolve(path, explicit[0] + names[1:], seen) + if len(explicit) > 1: return None + if len(names) > 1: + child = self.child(path, names[0]) + if child is not None: return self.resolve(child, names[1:], seen) + found = [self.resolve(path, target[:-1] + names, seen) for alias, target in uses if alias == '*'] + found = {value for value in found if value is not None} + if len(found) == 1: return found.pop() + if len(names) == 1 and names[0] in PRIMITIVES | {'Vec', 'Option', 'String', 'Result'}: + return ('std', names[0]) + return None + + def generic_context(self, path, name): + """Prove each machine parameter through a closed, private sealing module, not Copy alone.""" + tokens, ends, _, uses = self.module(path) + start = next((i + 2 for i in range(len(tokens) - 2) + if tokens[i:i + 2] == ['struct', name]), None) + if start is None or tokens[start:start + 1] != ['<']: return {} + stop, depth = start + 1, 1 + while stop < len(tokens) and depth: + depth += (tokens[stop] == '<') - (tokens[stop] == '>'); stop += 1 + result = {} + for parameter in split(tokens[start + 1:stop - 1]): + if '=' in parameter: + default = parameter[parameter.index('=') + 1:] + if not self.inert(path, default): return None + parameter = parameter[:parameter.index('=')] + if len(parameter) != 3 or parameter[1] != ':': return None + generic, _, bound = parameter + if not self.closed_bound(path, bound): return None + result[generic] = ['u64'] # proof certificate: no mutable authority, not a Rust substitution + return result + + def closed_bound(self, path, bound): + tokens, ends, _, uses = self.module(path) + matches = [i for i in range(len(tokens) - 1) if tokens[i:i + 2] == ['trait', bound]] + if len(matches) != 1 or any(alias in (bound, '*') for alias, _ in uses): return False + at = matches[0] + # The empty public bound has no associated types, callbacks or defaults. + signature = tokens[at + 2:at + 12] + if len(signature) != 10 or signature[:5] != [':', 'Copy', '+', 'Ord', '+'] or signature[6:8] != [':', ':'] or signature[9] != '{': return False + module, seal = signature[5], signature[8] + before = at - 2 if tokens[at - 1:at] == ['pub'] else at - 1 + def outer_attribute(index): + opening = next((a for a, b in ends.items() if b == index and tokens[a] == '['), None) + return opening is not None and tokens[opening - 1:opening] == ['#'] + if outer_attribute(before): return False + if sum(tokens[i:i + 4] == [module, ':', ':', seal] for i in range(len(tokens) - 3)) != 1: return False + if ends.get(at + 11) != at + 12: return False + mods = [i for i in range(len(tokens) - 2) if tokens[i:i + 3] == ['mod', module, '{']] + if len(mods) != 1: return False + begin = mods[0] + if begin and (tokens[begin - 1] in ('pub', ')') or outer_attribute(begin - 1)): return False + if any(a < begin < b for a, b in ends.items() if tokens[a] == '{'): return False + # Additional modules/includes or top-level macros could hide another sealing impl. + if any(t == 'mod' and i != begin or t == 'include' for i, t in enumerate(tokens)): return False + for i, t in enumerate(tokens): + if t == '!' and macro_invocation(tokens, i, ends): + if (tokens[i - 1] not in ('matches', 'assert', 'debug_assert', 'vec', 'format', 'format_args', 'write', 'writeln', 'panic') + or tokens[max(0, i - 3):i - 1] == [':', ':'] + or not self.builtin(path, tokens[i - 1])): return False + if tokens[i:i + 2] == ['derive', '('] and i + 1 in ends: + if any(t not in ('Clone', 'Copy', 'Debug', 'PartialEq', 'Eq', 'PartialOrd', 'Ord', 'Default', ',') for t in tokens[i + 2:ends[i + 1]]): return False + pos, end = begin + 3, ends[begin + 2] + if tokens[pos:pos + 5] != ['pub', 'trait', seal, '{', '}']: return False + pos += 5 + count = 0 + while pos < end: + if tokens[pos:pos + 3] != ['impl', seal, 'for']: return False + body = pos + 3 + while body < end and tokens[body] != '{': body += 1 + if body >= end or ends[body] != body + 1: return False + target = tokens[pos + 3:body] + # Resolve from the inline module's lexical parent; no generics, aliases or blanket impls. + if target[:3] == ['super', ':', ':']: target = target[3:] + if '<' in target or not self.inert(path, target): return False + count += 1 + pos = body + 2 + return count > 0 + + def inert(self, path, tokens, substitutions=None): + # Cache only completed roots: recursive coinductive successes are provisional. + substitutions = substitutions or {} + concrete = tuple(part for token in tokens for part in substitutions.get(token, [token])) + key = (Path(path).resolve(), concrete) + if self.visiting: return self._inert(path, list(concrete)) + if not hasattr(self, 'inert_roots'): self.inert_roots = {} + if key not in self.inert_roots: + self.inert_roots[key] = self._inert(path, list(concrete)) + return self.inert_roots[key] + + def _inert(self, path, tokens, substitutions=None): + substitutions = substitutions or {} + tokens = [part for token in tokens for part in substitutions.get(token, [token])] + if not tokens: return True + if any(t in tokens for t in ('mut', '*', 'unsafe', 'dyn', 'fn', 'impl', '!', '=')): return False + if tokens[0] == '&': + tokens = tokens[1:] + if tokens[:1] == ["'"]: tokens = tokens[2:] + return self.inert(path, tokens, substitutions) + if tokens[0] == '(' and tokens[-1] == ')': return all(self.inert(path, t, substitutions) for t in split(tokens[1:-1])) + if tokens[0] == '[' and tokens[-1] == ']': return self.inert(path, split(tokens[1:-1], ';')[0], substitutions) + if '<' in tokens: + start = tokens.index('<') + if tokens[-1] != '>': return False + names = [t for t in tokens[:start] if t != ':'] + args = [arg for arg in split(tokens[start + 1:-1]) if arg and arg[0] != "'"] + else: names, args = [t for t in tokens if t != ':'], [] + target = self.resolve(path, names) + if target is None: + # Foreign names stay opaque. Only the independently source-backed locked certificate + # may prove an absolute dependency type; missing certificate support fails closed. + if tokens[:2] != [':', ':']: return False + if not self.dependency_certificate(path, tokens): return False + self.audit.add('locked source certificate ' + ' '.join(tokens)) + return True + owner, name = target + if owner == 'std': + return (name in PRIMITIVES and not args or name in ('String', 'PathBuf') and not args + or name in WRAPPERS - {'String', 'PathBuf'} and len(args) == (2 if name in ('Result', 'BTreeMap') else 1) + and all(self.inert(path, arg, substitutions) for arg in args)) + if not all(self.inert(path, arg, substitutions) for arg in args): return False + parameters, payloads, kind = self.module(owner)[2][name][0] + if len(parameters) != len(args): return False + key = (owner, name, tuple(tuple(a) for a in args)) + if key in self.visiting: return True + self.visiting.add(key) + sub = dict(zip(parameters, args)) + result = all(self.inert(owner, field, sub) for field in payloads) + self.visiting.remove(key) + if result: self.audit.add(owner.relative_to(self.root.resolve()).as_posix() + '::' + name) + return result + + @cache_proof + def dependency_certificate(self, path, tokens): + """Cache exact dependency evidence only within this immutable source snapshot.""" + try: + from readonly_dependencies import certify, provenance + except ModuleNotFoundError as error: + if error.name == 'readonly_dependencies': return None + raise + namespace = self.module(path) + context = {'imports': namespace[3], 'definitions': list(namespace[2])} + if not certify(self.root, Path(path), tokens, namespace_context=context): return None + return provenance(self.root, Path(path), tokens, namespace_context=context) + + def shared_method(self, path, state_type, method): + names = [t for t in state_type[:state_type.index('<')] if t != ':'] if '<' in state_type else [t for t in state_type if t != ':'] + resolved = self.nominal(path, state_type) + target = resolved[:2] if resolved else None + if target and target[0] == 'std': + methods = { + 'Option': {'as_ref', 'is_some', 'is_none'}, + 'String': {'as_str', 'as_bytes', 'len', 'is_empty', 'clone'}, + 'Vec': {'as_slice', 'iter', 'len', 'is_empty', 'first', 'last', 'get', 'clone'}, + 'VecDeque': {'iter', 'len', 'is_empty', 'front', 'back', 'get', 'clone'}, + 'BTreeMap': {'iter', 'keys', 'values', 'len', 'is_empty', 'get', 'contains_key', 'clone'}, + 'Arc': {'as_ref', 'clone'}, + 'PathBuf': {'as_path', 'clone'}, + } + if target[1] in PRIMITIVES: + return method in {'min', 'max', 'saturating_add', 'saturating_sub', 'saturating_mul', 'wrapping_add', 'wrapping_sub', 'checked_add', 'checked_sub', 'then_some', 'then'} and self.inert(path, state_type) + if target[1] == 'Arc' and method not in methods['Arc'] and '<' in state_type: + return self.shared_method(path, state_type[state_type.index('<') + 1:-1], method) + copied_option = target[1] == 'Option' and method in {'map', 'map_or', 'map_or_else', 'and_then', 'or_else', 'or', 'and', 'filter', 'flatten', 'zip', 'unwrap_or', 'unwrap_or_else', 'is_some_and', 'is_none_or'} and self.copy_value(path, state_type) + return (method in methods.get(target[1], set()) or copied_option) and self.inert(path, state_type) + if not target or target[0] == 'std' or not self.inert(path, state_type): return False + owner, name = target + tokens, ends, _, _ = self.module(owner) + impls, functions, _ = self.shape.item_bodies(tokens) + matches = [(a, b, sig) for a, b, n, sig in functions if n == method + and any(x < a < b < y and self.shape.inherent_target(h, name) for x, y, h in impls)] + if len(matches) != 1: return False + if any('unsafe' in tokens[x:y] for x, y, h in impls if self.shape.inherent_target(h, name)): return False + a, b, sig = matches[0] + for i in range(a + 1, b): + if tokens[i] == '!' and macro_invocation(tokens, i, ends): + if (i < 1 or tokens[i - 1] not in ('matches', 'assert', 'debug_assert', 'vec', 'format', 'format_args', 'write', 'writeln', 'panic') + or tokens[max(0, i - 3):i - 1] == [':', ':'] or not self.builtin(owner, tokens[i - 1])): + return False + shared = sig[:4] in (['(', '&', 'self', ')'], ['(', '&', 'self', ',']) + copied = sig[:3] in (['(', 'self', ')'], ['(', 'self', ',']) and self.copy_value(path, state_type) + if 'unsafe' in tokens[a:b] or not (shared or copied): return False + if not any(sig[i:i + 2] == ['-', '>'] for i in range(len(sig) - 1)): return True + arrow = next(i for i in range(len(sig) - 1) if sig[i:i + 2] == ['-', '>']) + result = [part for token in sig[arrow + 2:] for part in (state_type if token == 'Self' else [token])] + if result[:6] == ['impl', 'Iterator', '<', 'Item', '=', '&'] and result[-1:] == ['>']: + # No opaque iterator authority: prove the entire expression from standard field iterators. + if not shared or any(alias in ('Iterator', '*') for alias, _ in self.module(owner)[3]): return False + if any(tokens[i] in ('trait', 'type', 'struct', 'enum', 'mod', 'as') and tokens[i + 1:i + 2] == ['Iterator'] for i in range(len(tokens) - 1)): return False + item = result[6:-1] + if not item or not self.inert(owner, item): return False + body = tokens[a + 1:b] + leaves = [body] if len(body) == 7 else [body[:7], body[10:-1]] if body[7:10] == ['.', 'chain', '('] and body[-1:] == [')'] else [] + if not leaves: return False + for leaf in leaves: + if leaf[:2] != ['self', '.'] or leaf[3:] != ['.', 'iter', '(', ')']: return False + field = self.field(owner, [name], leaf[2]) + target = self.nominal(*field) if field else None + if target is None or target[0] != 'std' or target[1] not in ('Option', 'Vec', 'VecDeque', 'BTreeSet') or len(target[3]) != 1: return False + if not self.inert(*field) or self.nominal(target[4], target[3][0]) != self.nominal(owner, item): return False + return True + return self.inert(owner, result) + + + def shared_field(self, state_path, state_type, view_path, view_type, field): + target = self.nominal(view_path, view_type) + if target is None or target[0] == 'std': return False + owner, name = target[:2] + tokens, _, definitions, _ = self.module(owner) + if any('' in payload for _, payloads, _ in definitions[name] for payload in payloads): return False + fields = self.shape.struct_fields(' '.join(tokens), name) + found = [typ for _, key, typ in fields or [] if key == field] + if len(found) != 1: return False + typ = found[0] + if typ[:1] != ['&'] or 'mut' in typ or '*' in typ: return False + typ = typ[1:] + if typ[:1] == ["'"]: typ = typ[2:] + return (self.resolve(owner, [t for t in typ if t != ':']) == self.resolve(state_path, [t for t in state_type if t != ':']) + and self.inert(owner, typ)) + + + def builtin(self, path, name, seen=None): + path = Path(path).resolve() + seen = set() if seen is None else seen + if path in seen: return True + seen = seen | {path} + tokens, _, _, uses = self.module(path) + if 'macro_use' in tokens: return False + if any(tokens[i:i + 3] == ['macro_rules', '!', name] or tokens[i:i + 2] == ['macro', name] for i in range(len(tokens) - 2)): + return False + if any(alias == name for alias, _ in uses): return False + for alias, target in uses: + if alias != '*': continue + if target[:-1] == ('super',): + parent = self.parent(path) + if parent is None or not self.builtin(parent, name, seen): return False + else: return False + return True + + @cache_proof + def discriminant_method(self, path, name, method): + """A bounded match-only reader may discard opaque generic payloads, never expose them.""" + tokens, ends, _, _ = self.module(path) + impls, functions, _ = self.shape.item_bodies(tokens) + matches = [(a, b, sig) for a, b, n, sig in functions if n == method and + any(x < a < b < y and self.shape.inherent_target(h, name) for x, y, h in impls)] + if len(matches) != 1: return False + a, b, sig = matches[0] + params_end = self.shape.ends_of(sig).get(0) + params = split(sig[1:params_end]) if params_end is not None else [] + if not params or params[0] != ['&', 'self']: return False + if any(':' not in p or not self.inert(path, p[p.index(':') + 1:]) for p in params[1:]): return False + result = sig[params_end + 1:] + if result[:2] != ['-', '>'] or '&' in result or not self.inert(path, result[2:]): return False + body = tokens[a + 1:b] + if body[:3] != ['match', 'self', '.'] or len(body) < 6 or body[4] != '{': return False + if any(t in body for t in ('unsafe', 'mut', 'ref', 'let', 'fn', 'move', '!')): return False + if body.count('self') != 1: return False + if any(t == '.' and i != 2 and body[i - 1:i] != ['.'] and body[i + 1:i + 2] != ['.'] for i, t in enumerate(body)): return False + field = self.field(path, [name], body[3]) + if field is None: return False + target = self.nominal(*field) + if target is None or target[2] != 'enum': return False + owner, enum_name = target[:2] + enum_tokens, enum_ends, _, _ = self.module(owner) + declaration = next(i for i in range(len(enum_tokens) - 1) if enum_tokens[i:i + 2] == ['enum', enum_name]) + begin = declaration + 2 + while begin < len(enum_tokens) and enum_tokens[begin] != '{': begin += 1 + if begin not in enum_ends: return False + known_fields = {} + for variant in split(enum_tokens[begin + 1:enum_ends[begin]]): + if len(variant) < 3 or variant[1] != '{': continue + for part in split(variant[2:-1]): + if len(part) > 2 and part[1] == ':': known_fields.setdefault(part[0], []).append(part[2:]) + local_ends = self.shape.ends_of(body) + if local_ends.get(4) not in (len(body) - 1, len(body) - 2): return False + for arm in split(body[5:local_ends[4]]): + arrow = next((i for i in range(len(arm) - 1) if arm[i:i + 2] == ['=', '>']), None) + if arrow is None or 'if' in arm[:arrow]: return False + pattern = arm[:arrow] + for i, token in enumerate(pattern): + if not token.isidentifier() or not token[0].islower() or token == '_': continue + if pattern[i + 1:i + 2] == [':']: continue + field_name = pattern[i - 2] if i >= 2 and pattern[i - 1] == ':' else token + types = known_fields.get(field_name, []) + if not types or not all(self.inert(owner, t) for t in types): return False + for i, token in enumerate(body): + if token != '(' or not i or not body[i - 1].isidentifier(): continue + if body[i - 1] != 'Some' or not self.builtin(path, 'Some'): return False + if any(tokens[j:j + 2] == ['fn', 'Some'] for j in range(len(tokens) - 1)): return False + return True + + def copy_value(self, path, typ, seen=None): + """Closed layout proof for value reads; a user Copy bound alone proves nothing.""" + typ = list(typ) + if not self.inert(path, typ): return False + if typ[:1] == ['('] and typ[-1:] == [')']: + return all(self.copy_value(path, p, seen) for p in split(typ[1:-1])) + if typ[:1] == ['['] and typ[-1:] == [']']: + return self.copy_value(path, split(typ[1:-1], ';')[0], seen) + target = self.nominal(path, typ) + if target is None: return False + owner, name, kind, args, context = target + if owner == 'std': + return name in PRIMITIVES and not args or name in ('Option', 'Result') and all(self.copy_value(context, a, seen) for a in args) + tokens, ends, definitions, _ = self.module(owner) + declaration = next((i for i in range(len(tokens) - 1) if tokens[i] in ('struct', 'enum') and tokens[i + 1] == name), None) + if declaration is None: return False + reverse = {b: a for a, b in ends.items()} + before = declaration - 1 + if tokens[before:before + 1] == ['pub']: before -= 1 + elif before in reverse and tokens[reverse[before] - 1:reverse[before]] == ['pub']: before = reverse[before] - 2 + derived = False + while before in reverse and tokens[before] == ']': + begin = reverse[before] + if tokens[begin - 1:begin] != ['#']: break + attr = tokens[begin + 1:before] + derived |= attr[:2] == ['derive', '('] and 'Copy' in attr + before = begin - 2 + if not derived: return False + seen = set() if seen is None else seen + key = owner, name + if key in seen: return False + parameters, payloads, _ = definitions[name][0] + substitutions = dict(zip(parameters, args)) + return all(self.copy_value(owner, [part for t in p for part in substitutions.get(t, [t])], seen | {key}) for p in payloads) + + @cache_proof + def field(self, path, typ, field): + typ = list(typ) + while typ[:1] == ['&']: + typ = typ[1:] + if typ[:1] == ["'"]: typ = typ[2:] + if typ[:1] == ['mut']: typ = typ[1:] + if '<' in typ: + at = typ.index('<') + if typ[0] in ('Option', 'Arc', 'Box') and typ[-1] == '>': return self.field(path, typ[at + 1:-1], field) + target = self.nominal(path, typ) + if not target or target[0] == 'std': return None + owner, name, kind, args, context = target + tokens, _, definitions, _ = self.module(owner) + fields = self.shape.struct_fields(tokens, name) + found = [t for _, n, t in fields or [] if n == field] + if len(found) != 1: return None + parameters = definitions[name][0][0] + substitutions = dict(zip(parameters, args)) + return owner, [part for token in found[0] for part in substitutions.get(token, [token])] + + @cache_proof + def nominal(self, path, typ, seen=None): + """Resolve a real declaration (including transparent aliases), never a prose type name.""" + typ = list(typ) + if not typ or any(t in typ for t in ('*', 'dyn', 'fn', 'impl', '!')): return None + while typ[:1] == ['&']: + typ = typ[1:] + if typ[:1] == ["'"]: typ = typ[2:] + if typ[:1] == ['mut']: typ = typ[1:] + at = typ.index('<') if '<' in typ else len(typ) + args = [p for p in split(typ[at + 1:-1]) if p and p[0] != "'"] if at < len(typ) and typ[-1:] == ['>'] else [] + target = self.resolve(path, [t for t in typ[:at] if t != ':']) + if target is None: return None + owner, name = target + if owner == 'std': return owner, name, 'std', args, path + parameters, payloads, kind = self.module(owner)[2][name][0] + if kind != 'type': return owner, name, kind, args, path + if len(parameters) != len(args): return None + seen = set() if seen is None else seen + key = (owner, name) + if key in seen: return None + substitutions = dict(zip(parameters, args)) + concrete = [p for t in payloads[0] for p in substitutions.get(t, [t])] + return self.nominal(owner, concrete, seen | {key}) + + def effect_output(self, path, typ, effect): + """The output is a mutable standard Vec of the registered effect enum, possibly aliased.""" + typ = list(typ) + if typ[:1] != ['&']: return False + typ = typ[1:] + if typ[:1] == ["'"]: typ = typ[2:] + if typ[:1] != ['mut']: return False + target = self.nominal(path, typ[1:]) + if target is None or target[:3] != ('std', 'Vec', 'std') or len(target[3]) != 1: return False + item = self.nominal(target[4], target[3][0]) + expected = self.nominal(path, effect) + return item is not None and expected is not None and item[:3] == expected[:3] and item[2] == 'enum' diff --git a/ci/machines.ini b/ci/machines.ini index 4306c48920..99e071b7c1 100644 --- a/ci/machines.ini +++ b/ci/machines.ini @@ -1,56 +1,156 @@ -# The state machines whose shape ci/check-machine-shape.py guards: one section per machine, keyed -# `[file::Struct]`, file relative to rust-modules/. The gate fails on any `pub`, `pub(crate)` or -# `pub(super)` field of the listed struct (a machine's state is private and its one writer is `step`, -# so a caller cannot poke it: a new way in is a new event) and REPORTS, never fails on, how many of -# its fields are `bool` and how many are `Option<..>`: a flag ratchet to read, not a limit. -# -# event the machine's event type (what `step` takes) -# effect the machine's effect type (what `step` pushes for the driver to execute) -# step prose for a reader: how `step` is exposed, which module drives it, who owns the machine -# -# The gate reads the section name (the file and the struct it grades) and prints `event` and `effect` in its report; -# it checks neither against the source, and `step` is read by nobody (docs/sans-io.md): keep all three true by hand. +# Registered literal Event/Effects reducers. Every owned field is private and guarded by default. +# transition is always the private inherent transition(&mut self, Event, &mut Vec) +# (borrowed events and concrete Vec aliases are supported); effect = none is a pure-view reducer. +# All arguments are bound exactly once: no extra context/model/state/callback parameters. +# aux_facts names a closed source-validated semantic slot, not an arbitrary Rust type allowlist. +# Current slots: URI now_ms:u64, Session tick_ms:u32, backend optional nine-boolean capabilities. +# event/effect bind to actual Rust enum declarations and the canonical signature, not prose. +# state_field selects a variant view only. It NEVER limits write coverage: counters, pending +# work, outboxes, caches and nested owners are equally guarded. No writer/helper exemptions. +# A distinct constructor accepts fresh data only and initializes all fields in a fresh literal. +# All later physical field writes occur inside transition, never mutSelf helpers or closures. +# Public wrappers may dispatch events; inert shared decision helpers may only read. +# state_reads = immutable requests closed structural generic proof, never broad Copy trust. +# Unknown calls/macros, callbacks, raw pointers, unsafe and live aliases fail closed. +# Each source also registers an enum policy and unconditionally denies the Clippy lint. +# Production children/static includes are traversed. Conditional paths, opaque includes and +# missing/generated modules fail closed. Numeric and open-wire wildcards remain legal. +# This bounded token proof does not replace Rust type checking or semantic behavior review. [media/src/player/lifecycle.rs::ForegroundLifecycle] event = ForegroundEvent effect = ForegroundEffect step = inherent; driver media/src/player/foreground.rs; owner media/src/player/machine.rs::Player.lifecycle +writer_policy = strict +state_field = state +transition = transition +constructor = IDLE + +[module media/src/player/lifecycle.rs] +wildcard_enum_match_arm = deny [media/src/player/recovery.rs::OpenRecovery] event = RecoveryEvent effect = RecoveryEffect step = inherent; driver media/src/player/pump.rs (and media/src/player/engine.rs, which raises LoadStarted for every Engine start); owner media/src/route/decision.rs::PlaybackSession.recovery +writer_policy = strict +state_field = state +transition = transition +constructor = new +state_reads = immutable + +[module media/src/player/recovery.rs] +wildcard_enum_match_arm = deny + [play-uri/src/uriprobe.rs::UriProbe] event = UriEvent +aux_facts = now_ms:monotonic_ms_u64 effect = UriEffect step = inherent; driver play-uri/src/uriprobe_drive.rs, opened by the application's src/dev/uriprobe.rs behind media's UriProbeSession port; route adapter media/src/player/uriprobe_drive.rs; owner media/src/player/adapter.rs::PlayerAdapter.uri +writer_policy = strict +state_field = phase +transition = transition +constructor = new +state_reads = immutable + +[module play-uri/src/uriprobe.rs] +wildcard_enum_match_arm = deny + [play-uri/src/picture_gate.rs::PictureGate] event = Event effect = Fx step = inherent; driver play-uri/src/backend.rs (`UriBackend::picture_step`, fed the service's playing and clock and the plane owner's `Shown`); owner play-uri/src/backend.rs::UriBackend.picture +writer_policy = strict +state_field = stage +transition = transition +constructor = new +state_reads = immutable + +[module play-uri/src/picture_gate.rs] +wildcard_enum_match_arm = deny [data/src/hudpacks.rs::HudStore] event = HudEvent effect = HudEffect step = inherent; driver src/app/adapters/huds.rs (the runners that execute its ScanDir/ReadFile/WriteFile/Delete on the storage worker and answer Validate with appkit::hud_format); owner the Bridge (`Bridge::huds`) +writer_policy = strict +state_field = op +transition = transition +constructor = new +state_reads = immutable + +[module data/src/hudpacks.rs] +wildcard_enum_match_arm = deny + [playback-contract/src/state.rs::BackendState] event = Event +aux_facts = capabilities:playback_capabilities effect = Fx step = inherent; driver media/src/player/backend.rs::BackendRunner; concrete resource ownership stays in the injected driver +writer_policy = strict +state_field = snapshot +transition = transition +constructor = new +state_reads = immutable + +[module playback-contract/src/state.rs] +wildcard_enum_match_arm = deny + [media/src/player/attempt_metrics.rs::AttemptMetrics] event = Event effect = Fx step = inherent; local measurement model, not yet wired to product reporting; the caller supplies canonical request/attempt identities and monotonic ticks +writer_policy = strict +state_field = request +transition = transition +constructor = new +state_reads = immutable + +[module media/src/player/attempt_metrics.rs] +wildcard_enum_match_arm = deny + [media/src/player/readout.rs::PlayerReadout] event = ReadoutEvent -effect = none (L3b adds a feed command) +effect = none +# PlayerReadout is a pure view reducer; no effect channel (L3b adds a feed command). step = inherent (`PlayerReadout::step`); owner media/src/route/decision.rs::PlaybackSession.readout, written only through `PlaybackSession::step_readout`; not yet fed by the pump (L3a-2 steps 3 and 4) +writer_policy = strict +state_field = state +transition = transition +constructor = IDLE +state_reads = immutable + +[module media/src/player/readout.rs] +wildcard_enum_match_arm = deny [data/src/hudpacks/catalog.rs::Catalog] event = Event effect = CatalogEffect step = inherent; nested in HudStore; driver src/app/adapters/huds.rs (bounded cache IO and conditional no-redirect GET); owner HudStore.catalog +writer_policy = strict +state_field = phase +transition = transition +constructor = new +state_reads = immutable + +[module data/src/hudpacks/catalog.rs] +wildcard_enum_match_arm = deny + + +[session/src/auth/owner.rs::SessionMachine] +event = SessionEvent +aux_facts = tick_ms:monotonic_ms_u32 +effect = SessionFx +step = trait Machine; owner SessionMachine; the app executes addressed SessionFx jobs +writer_policy = strict +state_field = state +transition = transition +constructor = from_init +state_reads = immutable + +[module session/src/auth/owner.rs] +wildcard_enum_match_arm = deny diff --git a/ci/module-layers.ini b/ci/module-layers.ini index b1d6e17239..143b606760 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -34,7 +34,7 @@ # helpers every layer's tests use. uses = members = - eventlog paths process clock task cbuf sha256 sha1 b64 spki dynlib checkpoint storage_worker fontcov surface tile hold detail_parts window + eventlog paths process clock step task cbuf sha256 sha1 b64 spki dynlib checkpoint storage_worker fontcov surface tile hold detail_parts window diag::zlib diag::spans diag::heartbeat devtrig testlock testnet testscratch testrace @@ -121,7 +121,9 @@ members = ui # dev-dependency only: one fixture test calls it). # The content stores and their data modules. uses = base machine platform net plex telemetry playback_contract -members = stores browse metadata person collection search sortfacts subsearch viewstate viewledger pms watchlist catalog hudpacks watchlist_guid_tests +members = instruments stores browse metadata person collection search sortfacts subsearch viewstate viewledger pms watchlist catalog hudpacks watchlist_guid_tests + captured_store_fixture +# Value-only cfg(test) harness, like watchlist_guid_tests; no production dependency edge. [session] # plex.tv sign-in, discovery, who's-watching and install. diff --git a/ci/ports.ini b/ci/ports.ini new file mode 100644 index 0000000000..04ba278f16 --- /dev/null +++ b/ci/ports.ini @@ -0,0 +1,28 @@ +# Exact FILES only. Job/adaptor/instrument bodies, never machine logic or directories. +[rust-modules/session/src/auth/ports.rs] +kind = worker +reason = Live account/retry/PIN/probe job bodies; the owner and pure retry policy remain outside. + +[rust-modules/data/src/instruments.rs] +kind = instrument +reason = Timers for metadata publication and PMS merge diagnostics, with no logic. + +[rust-modules/src/app/recorder.rs] +kind = instrument +reason = Recorder measures its own spend. + +[rust-modules/src/app/adapters/poster.rs] +kind = adapter +reason = Worker-safe residency loss log throttle. + +[rust-modules/src/app/window_activity.rs] +kind = instrument +reason = WSLg host frame pacing measurement. + +[rust-modules/data/src/catalog_ports.rs] +kind = adapter +reason = Captured Catalog worker fetch/calendar adapter; no machine logic. + +[rust-modules/src/app/adapters/stores.rs] +kind = adapter +reason = Watchlist calendar input capture and addressed job execution outside machine steps. diff --git a/ci/proofs/platform-generated-enums.json b/ci/proofs/platform-generated-enums.json new file mode 100644 index 0000000000..7e968b089d --- /dev/null +++ b/ci/proofs/platform-generated-enums.json @@ -0,0 +1,84 @@ +{ + "schema": "plx.readonly.generated-unit-enums.v1", + "package": "plx_platform", + "module": "platform/src/i18n/mod.rs", + "include": "include!(concat!(env!(\"OUT_DIR\"), \"/languages.rs\"));", + "sources": { + "platform/Cargo.toml": "4181b79fa53a7ff6e8b0157f4d1ffe258737896603d267b4802551dee0812472", + "platform/src/lib.rs": "0836abd640849f56afbe66af39632b28648609e6464fda0bd4c51087c1070acb", + "platform/src/i18n/mod.rs": [ + "40a13d07a43c772b10587e510a69502684abfa1f582ce355b22fd935a8c46f45", + "2c978e3aa3a9215a2e96ebaec9dd5ae3cf3ee85cf1afb43a36b5f42f17ff4d52" + ], + "platform/build.rs": "58a7a2f8d8851b995648f40fb0a179c3ae743fb0e4e92dd3e19b93f9b86940c8", + "platform/build_support/catalog.rs": "b02769b2de34bf6cf53a60d05bc9fc3080e6012778e30b400b13f772b43f7083", + "build_support/install_identities.rs": "8039b85c09d27c1f9a80aded1245dd4a0c7b7ac3b633e28cb9b7a0f6d62ed621", + "machine/src/lib.rs": "105afdbb05fb762e6752cef260b6d928b1d828993350aaa71651f96cee0c3188", + "machine/src/machine.rs": [ + "571415d64a9885248f852b402153feedd4660acbe03606e4796c59659726049f", + "03a6e18f576dcbaff66c3d7405923b155302bfb2996bb373dac115ece055a5bf" + ] + }, + "text_hashing": "sha256-utf8-bytes-crlf-to-lf-local-root-version-v1", + "manifests": { + "Cargo.toml": "fbeb900767c6d3a7091b0366cdaf79753f45384be9b39a649dd8e7decbf40fb6", + "appkit/Cargo.toml": "1e3a33f392110f269537b12f12879c6bc15309aca304b189d6b0346edf8a1186", + "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", + "data/Cargo.toml": "dc246544384d3cfe5648b13cfcbd67edff69f027d22a268dd6fdca53bdf1e794", + "gfx/Cargo.toml": "c8889dd95a481938966c41635f85702695ce9c59956381768e6c56d215d8fc0e", + "machine/Cargo.toml": "0bc99e95272916b8d00e1a8dad81440bc4998de12ccd9a00e7853f438c813d03", + "media/Cargo.toml": "2b3bb41264db9b9f30869015dfe0dd6656147c432728c9ea9301988c710a4202", + "media-codecs/Cargo.toml": "503c8681289314b5c8a63195aad6796cbad93fcb3eedd8d7cba9e8ed0233783f", + "net/Cargo.toml": "bfdb3a08200642eeeafc9762733718c407529f26dce8a7b90665bc77ac928171", + "platform/Cargo.toml": "4181b79fa53a7ff6e8b0157f4d1ffe258737896603d267b4802551dee0812472", + "play-feed/Cargo.toml": "b85320257da74a1affd81238b8fb6caa7f28960181d5ea0e07704ceef4800515", + "play-uri/Cargo.toml": "107832fa33c96b7d2a4150c294aea9cd40954c3aabf66f809fc771bb52f5c280", + "playback-contract/Cargo.toml": "bde335ea645552d4f7481b007b80204ecb5bb592caaca22af58a8361cd050dcf", + "plex/Cargo.toml": "886ef07d7de8881d1a01666ea6aea70f228b5e0c8b8bbfc79b8693c59e1c8af7", + "screens/Cargo.toml": "ebe7f8c0d22492de6bd494cfa760dd99999bfd616b7952e753fe5a26dafc6a73", + "session/Cargo.toml": "331a64ed32fbc88988e4c1c33c7b9aa954deab219d1e74fbdec70a4c30690e61", + "storage/Cargo.toml": "8865be804f87c69c5ab6fdf3f3f5388b8bfc254195329623c7b1f5cf614e3e81", + "telemetry/Cargo.toml": "19ccd3f933efcda0052c8f0fdd9c9275c566f6d445e77a1049d0c3bd16e71b36", + "ui/Cargo.toml": "0957d2057cadbd522ae2ee2446727c9c4022c75fba9cfb2347fd341a10fdacf4" + }, + "configs": { + ".cargo/config": null, + ".cargo/config.toml": "82f061c716740e16cfee63a74d87159e0e0dc253e1092b87c54190c603515b14", + "../.cargo/config": null, + "../.cargo/config.toml": null + }, + "lock": "a1e4a5b1dc4a4ae661f41b037dc040caf348136efa23976da56786259897383f", + "grammar": { + "Preference": { + "prefix": [ + "System" + ], + "catalogue_unit_variants": true + }, + "Language": { + "catalogue_unit_variants": true, + "suffix": [ + "Pseudo" + ] + } + }, + "machine_newtype": "reviewed local newtype macro emits pub struct Name(pub u32); doc attributes only", + "review": [ + "build.rs -> catalog::build(locales, OUT_DIR), no cfg-dependent producer", + "parse_registry derives variant solely from validated ASCII tag", + "discover preserves validated LanguageSpec; compile sorts by row", + "languages_rs emits only unit variants; Pseudo cfg_attr only allows dead_code", + "string slots use Rust Debug escaping; numeric slots are integers", + "install_identities writes only install_identities.rs, never languages.rs" + ], + "assumptions": [ + "Offline source-backed unit-enum proof; certificate changes require source review.", + "", + "No Cargo, cached output, generator execution, Copy axiom or type-name exemption.", + "The certificate pins the entire production pipeline and include namespace, not the", + "language list. Its reviewed template emits unit variants in every configuration.", + "Only enum values are certified: LocaleContext/OnceLock and methods are not.", + "Assumes ordinary Cargo/Rust/std/serde execution, no external build/config/compiler", + "overrides, output tampering or unsafe-code/compiler unsoundness attestation." + ] +} diff --git a/ci/proofs/serde-json-immutable.json b/ci/proofs/serde-json-immutable.json new file mode 100644 index 0000000000..9ddb7a46b3 --- /dev/null +++ b/ci/proofs/serde-json-immutable.json @@ -0,0 +1,610 @@ +{ + "archive": { + "bytes": 158079, + "sha256": "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6", + "url": "https://static.crates.io/crates/serde_json/serde_json-1.0.154.crate", + "verified_before_inspection": true + }, + "declarations": { + "Map": { + "path": "src/map.rs", + "tokens": [ + "pub", + "struct", + "Map", + "<", + "K", + ",", + "V", + ">", + "{", + "map", + ":", + "MapImpl", + "<", + "K", + ",", + "V", + ">", + ",", + "}" + ] + }, + "Map_ordered_UNSUPPORTED": { + "path": "src/map.rs", + "tokens": [ + "#", + "[", + "cfg", + "(", + "feature", + "=", + "\"preserve_order\"", + ")", + "]", + "type", + "MapImpl", + "<", + "K", + ",", + "V", + ">", + "=", + "IndexMap", + "<", + "K", + ",", + "V", + ",", + "BuildHasherImpl", + ">", + ";" + ] + }, + "Map_tree": { + "path": "src/map.rs", + "tokens": [ + "#", + "[", + "cfg", + "(", + "not", + "(", + "feature", + "=", + "\"preserve_order\"", + ")", + ")", + "]", + "type", + "MapImpl", + "<", + "K", + ",", + "V", + ">", + "=", + "BTreeMap", + "<", + "K", + ",", + "V", + ">", + ";" + ] + }, + "N_numeric": { + "path": "src/number.rs", + "tokens": [ + "#", + "[", + "cfg", + "(", + "not", + "(", + "feature", + "=", + "\"arbitrary_precision\"", + ")", + ")", + "]", + "#", + "[", + "derive", + "(", + "Copy", + ",", + "Clone", + ")", + "]", + "enum", + "N", + "{", + "PosInt", + "(", + "u64", + ")", + ",", + "NegInt", + "(", + "i64", + ")", + ",", + "Float", + "(", + "f64", + ")", + ",", + "}" + ] + }, + "N_string": { + "path": "src/number.rs", + "tokens": [ + "#", + "[", + "cfg", + "(", + "feature", + "=", + "\"arbitrary_precision\"", + ")", + "]", + "type", + "N", + "=", + "String", + ";" + ] + }, + "Number": { + "path": "src/number.rs", + "tokens": [ + "pub", + "struct", + "Number", + "{", + "n", + ":", + "N", + ",", + "}" + ] + }, + "Value": { + "path": "src/value/mod.rs", + "tokens": [ + "pub", + "enum", + "Value", + "{", + "Null", + ",", + "Bool", + "(", + "bool", + ")", + ",", + "Number", + "(", + "Number", + ")", + ",", + "String", + "(", + "String", + ")", + ",", + "Array", + "(", + "Vec", + "<", + "Value", + ">", + ")", + ",", + "Object", + "(", + "Map", + "<", + "String", + ",", + "Value", + ">", + ")", + ",", + "}" + ] + } + }, + "features": { + "definitions": { + "alloc": [ + "serde_core/alloc" + ], + "arbitrary_precision": [], + "default": [ + "std" + ], + "float_roundtrip": [], + "preserve_order": [ + "indexmap", + "alloc", + "dep:foldhash" + ], + "raw_value": [], + "std": [ + "memchr/std", + "serde_core/std" + ], + "unbounded_depth": [] + }, + "guard": "all local manifest/config bytes and complete Cargo.lock pinned except coherent non-resolving root release version; no indexmap/foldhash lock edges", + "locked_dependencies": [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij" + ], + "supported": [ + "alloc", + "arbitrary_precision", + "default", + "float_roundtrip", + "raw_value", + "std", + "unbounded_depth" + ], + "unsupported": [ + "preserve_order" + ] + }, + "grammar": { + "Map": { + "fields": { + "map": "MapImpl" + } + }, + "MapImpl": { + "not(preserve_order)": "alloc::collections::BTreeMap", + "preserve_order": { + "unsupported": "indexmap::IndexMap" + } + }, + "N": { + "arbitrary_precision": "alloc::string::String", + "not(arbitrary_precision)": { + "enum": { + "Float": [ + "f64" + ], + "NegInt": [ + "i64" + ], + "PosInt": [ + "u64" + ] + } + } + }, + "Number": { + "fields": { + "n": "N" + } + }, + "Value": { + "enum": { + "Array": [ + "alloc::vec::Vec" + ], + "Bool": [ + "bool" + ], + "Null": [], + "Number": [ + "Number" + ], + "Object": [ + "Map" + ], + "String": [ + "alloc::string::String" + ] + } + }, + "axioms": [ + "bool", + "u64", + "i64", + "f64", + "alloc::string::String", + "alloc::vec::Vec", + "alloc::collections::BTreeMap" + ], + "closure": "least finite owned JSON tree; all recursive edges cross owned containers" + }, + "package": { + "checksum": "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6", + "name": "serde_json", + "source": "registry+https://github.com/rust-lang/crates.io-index", + "version": "1.0.154" + }, + "schema": "plx.readonly.locked-json.v1", + "source_files": { + "Cargo.toml": { + "bytes": 3142, + "sha256": "548aafeb7c702b69b9de950033f10b59f70baf38592d275d8ca8cff19f7750c3" + }, + "build.rs": { + "bytes": 1206, + "sha256": "a681e754be844c7dbef957f5d2d00b01f37c5dca160ef1055a8d8f975697a881" + }, + "src/lib.rs": { + "bytes": 14369, + "sha256": "e3c3f2864cea66bac10c78dfc312ed8e1de43d2b7410d83bdd352a1c4b339104" + }, + "src/map.rs": { + "bytes": 35610, + "sha256": "1ba8afd6c643740462171713fd523966920bd726af37963cb8f21e76e9beb69f" + }, + "src/number.rs": { + "bytes": 25319, + "sha256": "1730b1c1a9b2a75f9e52b165191ca77cb3dbd82fec3b23f41f097f4f07f3410e" + }, + "src/value/mod.rs": { + "bytes": 30963, + "sha256": "6331d59ea362a74b6cd3d302d08114a63a73a384ff56fef737de29edea2f8d91" + } + }, + "trust_boundary": [ + "reviewed archive bytes and canonical crates.io Cargo identity", + "Rust/std sound owned container axioms; arbitrary_precision is owned String", + "preserve_order and unknown features/types/configurations rejected", + "no attestation of environment/global Cargo config, --config/--extern overrides or compiler unsoundness", + "no foreign code execution; runtime requires neither archive/cache/Cargo nor network" + ], + "workspace": { + "configs": { + "../.cargo/config": null, + "../.cargo/config.toml": null, + ".cargo/config": null, + ".cargo/config.toml": "82f061c716740e16cfee63a74d87159e0e0dc253e1092b87c54190c603515b14" + }, + "lock_sha256": "a1e4a5b1dc4a4ae661f41b037dc040caf348136efa23976da56786259897383f", + "manifests": { + "Cargo.toml": "fbeb900767c6d3a7091b0366cdaf79753f45384be9b39a649dd8e7decbf40fb6", + "appkit/Cargo.toml": "1e3a33f392110f269537b12f12879c6bc15309aca304b189d6b0346edf8a1186", + "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", + "data/Cargo.toml": "dc246544384d3cfe5648b13cfcbd67edff69f027d22a268dd6fdca53bdf1e794", + "gfx/Cargo.toml": "c8889dd95a481938966c41635f85702695ce9c59956381768e6c56d215d8fc0e", + "machine/Cargo.toml": "0bc99e95272916b8d00e1a8dad81440bc4998de12ccd9a00e7853f438c813d03", + "media-codecs/Cargo.toml": "503c8681289314b5c8a63195aad6796cbad93fcb3eedd8d7cba9e8ed0233783f", + "media/Cargo.toml": "2b3bb41264db9b9f30869015dfe0dd6656147c432728c9ea9301988c710a4202", + "net/Cargo.toml": "bfdb3a08200642eeeafc9762733718c407529f26dce8a7b90665bc77ac928171", + "platform/Cargo.toml": "4181b79fa53a7ff6e8b0157f4d1ffe258737896603d267b4802551dee0812472", + "play-feed/Cargo.toml": "b85320257da74a1affd81238b8fb6caa7f28960181d5ea0e07704ceef4800515", + "play-uri/Cargo.toml": "107832fa33c96b7d2a4150c294aea9cd40954c3aabf66f809fc771bb52f5c280", + "playback-contract/Cargo.toml": "bde335ea645552d4f7481b007b80204ecb5bb592caaca22af58a8361cd050dcf", + "plex/Cargo.toml": "886ef07d7de8881d1a01666ea6aea70f228b5e0c8b8bbfc79b8693c59e1c8af7", + "screens/Cargo.toml": "ebe7f8c0d22492de6bd494cfa760dd99999bfd616b7952e753fe5a26dafc6a73", + "session/Cargo.toml": "331a64ed32fbc88988e4c1c33c7b9aa954deab219d1e74fbdec70a4c30690e61", + "storage/Cargo.toml": "8865be804f87c69c5ab6fdf3f3f5388b8bfc254195329623c7b1f5cf614e3e81", + "telemetry/Cargo.toml": "19ccd3f933efcda0052c8f0fdd9c9275c566f6d445e77a1049d0c3bd16e71b36", + "ui/Cargo.toml": "0957d2057cadbd522ae2ee2446727c9c4022c75fba9cfb2347fd341a10fdacf4" + }, + "owners": { + "Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "src/lib.rs", + "lib_sha256": "c3e5773952ed1dc138ed7806383bda16d88d3c3d470729aa011d7b645738852d" + }, + "data/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "data/src/lib.rs", + "lib_sha256": "13b19b51177935c316df61913c418233f371b2faf6e7d993cbdbe539e2d4360f" + }, + "media/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "media/src/lib.rs", + "lib_sha256": "37046486175719577d4ea0fda178dfc577b63c49ba70f472b5fccdd56ce3f3c7" + }, + "net/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "optional": true, + "version": "1" + }, + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "net/src/lib.rs", + "lib_sha256": "d9f24001852917fb61bb790e2b3276b7d7bd589a0646fb7bf10e01bbd8324755" + }, + "platform/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + }, + { + "version": "1" + } + ], + "edition": "2021", + "lib": "platform/src/lib.rs", + "lib_sha256": "0836abd640849f56afbe66af39632b28648609e6464fda0bd4c51087c1070acb" + }, + "play-feed/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "play-feed/src/lib.rs", + "lib_sha256": "0696be5d9415fe4e8139470340ed9d92371a5bb90517baeac2ccee90eefd90f3" + }, + "play-uri/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "play-uri/src/lib.rs", + "lib_sha256": "8de76dc167d22d8e4c4302a5efb5b1963b9da32632580c026ebf2ff89047a212" + }, + "plex/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "plex/src/lib.rs", + "lib_sha256": "b90aa3a18b5a6479734ff0fc7143308657bb0d24eceb0b128375037c3b3a6f68" + }, + "screens/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "screens/src/lib.rs", + "lib_sha256": "818e1db96db49dc81341ccd6515a5b33565dd73398b6ad06b1b272b0cd4056d3" + }, + "session/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "session/src/lib.rs", + "lib_sha256": "aabf46f0171754643b3e7f246a4270b388a0f205b9263705eadb1e033d03066d" + }, + "storage/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + }, + { + "version": "1" + } + ], + "edition": "2021", + "lib": "storage/src/main.rs", + "lib_sha256": "94278ac8964b3825227f444691995278474e97b0802c4fec6dbddba6fe9a29e7" + }, + "telemetry/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "telemetry/src/lib.rs", + "lib_sha256": "7fd06b717cbe02de1a755dcf0bb3c6098335768854898fba343ccc79484098a7" + }, + "ui/Cargo.toml": { + "dependency": [ + { + "default-features": false, + "features": [ + "alloc", + "std" + ], + "version": "1" + } + ], + "edition": "2021", + "lib": "ui/src/lib.rs", + "lib_sha256": "1b5373566db1931371a191b5e0619d48fbc7cec93d07d95669668e481187517e" + } + }, + "text_hashing": "sha256-utf8-bytes-crlf-to-lf-local-root-version-v1" + } +} diff --git a/ci/readonly_dependencies.py b/ci/readonly_dependencies.py new file mode 100644 index 0000000000..5898ea084b --- /dev/null +++ b/ci/readonly_dependencies.py @@ -0,0 +1,480 @@ +"""Reviewed locked-source certificates, not an external-type name allowlist. + +Runtime is Python 3.10 stdlib-only, offline, and executes no Cargo or crate code. +The producer reads a SHA256-verified crate archive as data BEFORE inspecting it. +The pinned certificate is a review boundary: regeneration also requires reviewing +its source/grammar and updating CERTIFICATE_SHA256 here. Unknown types stay opaque. + +Assumptions match the local structural checker: sound Rust/std owned containers, +Cargo honoring the checked-in locked graph/config, and no out-of-tree compiler or +Cargo overrides. This cannot attest an arbitrary build environment or unsafe code. +""" +from pathlib import Path +import argparse +import hashlib +import json +import re +import tarfile + +CERTIFICATE_PATH = Path(__file__).with_name('proofs') / 'serde-json-immutable.json' +CERTIFICATE_SHA256 = 'd73dc7b1fabf6fd4ab2b4db52f7a7d72d618f329b91290c50cfc82dcd822c5c0' +SCHEMA = 'plx.readonly.locked-json.v1' +REGISTRY = 'registry+https://github.com/rust-lang/crates.io-index' +SUPPORTED = ['alloc', 'arbitrary_precision', 'default', 'float_roundtrip', 'raw_value', 'std', 'unbounded_depth'] +GRAMMAR = { + 'Value': {'enum': {'Null': [], 'Bool': ['bool'], 'Number': ['Number'], + 'String': ['alloc::string::String'], 'Array': ['alloc::vec::Vec'], + 'Object': ['Map']}}, + 'Number': {'fields': {'n': 'N'}}, + 'N': {'not(arbitrary_precision)': {'enum': {'PosInt': ['u64'], 'NegInt': ['i64'], 'Float': ['f64']}}, + 'arbitrary_precision': 'alloc::string::String'}, + 'Map': {'fields': {'map': 'MapImpl'}}, + 'MapImpl': {'not(preserve_order)': 'alloc::collections::BTreeMap', + 'preserve_order': {'unsupported': 'indexmap::IndexMap'}}, + 'axioms': ['bool', 'u64', 'i64', 'f64', 'alloc::string::String', + 'alloc::vec::Vec', 'alloc::collections::BTreeMap'], + 'closure': 'least finite owned JSON tree; all recursive edges cross owned containers', +} +SOURCE_PATHS = ['Cargo.toml', 'src/lib.rs', 'src/value/mod.rs', 'src/number.rs', 'src/map.rs', 'build.rs'] + + +def _sha(data): + return hashlib.sha256(data).hexdigest() + + +def _local_sha(data): + # Git checkouts may use CRLF on Windows and LF in CI; no other byte is ignored. + return _sha(data.replace(b'\r\n', b'\n')) + + +def _json(data): + return json.dumps(data, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode('ascii') + + +def _tokens(text): + """Lex comments/literals before examining Rust identifiers; never expand macros.""" + result, i = [], 0 + while i < len(text): + if text[i].isspace(): + i += 1 + elif text.startswith('//', i): + stop = text.find('\n', i); i = len(text) if stop < 0 else stop + elif text.startswith('/*', i): + depth, i = 1, i + 2 + while depth: + if i >= len(text): raise ValueError('unclosed Rust comment') + if text.startswith('/*', i): depth += 1; i += 2 + elif text.startswith('*/', i): depth -= 1; i += 2 + else: i += 1 + else: + raw = re.match(r'(?:b|c)?r(#+)?"', text[i:]) + if raw: + end = '"' + (raw[1] or '') + stop = text.find(end, i + raw.end()) + if stop < 0: raise ValueError('unclosed raw string') + result.append('""'); i = stop + len(end); continue + literal = re.match(r'(?:b|c)?"(?:\\.|[^"\\])*"|(?:b)?\'(?:\\.|[^\'\\])\'', text[i:]) + if literal: + result.append(literal[0]); i += literal.end(); continue + token = re.match(r'r#[A-Za-z_]\w*|[A-Za-z_]\w*|::|[^\s]', text[i:]) + result.append(token[0].removeprefix('r#')); i += token.end() + return result + + +def _table(text): + """Bounded TOML key/value tables used by Cargo dependency/feature metadata. + + Unsupported TOML (multiline strings, dotted assignments, quoted keys) fails + closed; this is not a replacement for a general TOML parser. + """ + clean, quote, escaped = [], None, False + i = 0 + while i < len(text): + c = text[i] + if quote: + clean.append(c) + if c == quote and not escaped: quote = None + escaped = c == '\\' and not escaped + elif c in ('"', "'"): + if text[i:i + 3] == c * 3: raise ValueError('multiline TOML string unsupported') + quote = c; clean.append(c) + elif c == '#': + end = text.find('\n', i); i = len(text) if end < 0 else end; continue + else: clean.append(c) + i += 1 + if quote: raise ValueError('unclosed TOML string') + tokens = re.findall(r'"(?:\\.|[^"\\])*"|\'[^\']*\'|[A-Za-z0-9_+.-]+|[^\s]', ''.join(clean)) + pos = 0 + def value(): + nonlocal pos + if pos >= len(tokens): raise ValueError('missing TOML value') + t = tokens[pos]; pos += 1 + if t == '[': + items = [] + while pos < len(tokens) and tokens[pos] != ']': + items.append(value()) + if tokens[pos] != ',': break + pos += 1 + if pos >= len(tokens) or tokens[pos] != ']': raise ValueError('unsupported TOML array') + pos += 1; return items + if t == '{': + items = {} + while pos < len(tokens) and tokens[pos] != '}': + key = tokens[pos]; pos += 1 + if not re.fullmatch(r'[A-Za-z0-9_-]+', key) or key in items or tokens[pos] != '=': + raise ValueError('unsupported inline TOML table') + pos += 1; items[key] = value() + if tokens[pos] != ',': break + pos += 1 + if pos >= len(tokens) or tokens[pos] != '}': raise ValueError('unsupported inline TOML table') + pos += 1; return items + if t.startswith('"'): return json.loads(t) + if t.startswith("'"): return t[1:-1] + if t in ('true', 'false'): return t == 'true' + if re.fullmatch(r'[0-9]+', t): return int(t) + raise ValueError('unsupported TOML value: ' + t) + result = {} + while pos < len(tokens): + key = tokens[pos]; pos += 1 + if not re.fullmatch(r'[A-Za-z0-9_-]+', key) or key in result or tokens[pos] != '=': + raise ValueError('unsupported TOML assignment') + pos += 1; result[key] = value() + return result + + +def _sections(text): + matches = list(re.finditer(r'(?m)^\[(\[?)([^\]\n]+)\]\]?[ \t]*(?:#[^\n]*)?$', text)) + result = {} + for i, match in enumerate(matches): + if match[1]: continue + name = match[2] + if name in result: raise ValueError('duplicate TOML section') + result[name] = text[match.end():matches[i + 1].start() if i + 1 < len(matches) else len(text)] + return result + + +def _locked(root): + text = (root / 'Cargo.lock').read_text(encoding='utf-8') + if _table(text.split('[[package]]')[0]).get('version') not in (3, 4): + raise ValueError('unsupported Cargo.lock format') + packages = [_table(part) for part in text.split('[[package]]')[1:]] + matches = [p for p in packages if p.get('name') == 'serde_json'] + if len(matches) != 1: raise ValueError('ambiguous locked serde_json package') + package = matches[0] + if package.get('source') != REGISTRY or not re.fullmatch('[0-9a-f]{64}', package.get('checksum', '')): + raise ValueError('not the canonical crates.io archive identity') + if any(x.split(' ')[0] in ('indexmap', 'foldhash') for x in package.get('dependencies', [])): + raise ValueError('preserve_order dependency branch is not certified') + return {k: package[k] for k in ('name', 'version', 'source', 'checksum')}, package.get('dependencies', []) + + +def _manifest_paths(root): + root_sections = _sections((root / 'Cargo.toml').read_text(encoding='utf-8')) + workspace = _table(root_sections['workspace']) + members = workspace['members'] + if not isinstance(members, list) or any(not isinstance(m, str) or not re.fullmatch(r'[A-Za-z0-9_-]+', m) for m in members): + raise ValueError('unsupported workspace member pattern') + return ['Cargo.toml'] + [m + '/Cargo.toml' for m in sorted(set(members))] + + +WORKSPACE_HASHING = 'sha256-utf8-bytes-crlf-to-lf-local-root-version-v1' + + +def _mask_local_version(text, section, version): + matches = list(re.finditer(r'(?m)^version[ \t]*=[ \t]*"([^"\n]+)"[ \t]*(?:#[^\n]*)?$', section)) + if len(matches) != 1 or matches[0][1] != version or text.count(section) != 1: + raise ValueError('unsupported local root version assignment') + match = matches[0] + start = text.index(section) + match.start(1) + end = start + len(version) + return text[:start] + '' + text[end:] + + +def _workspace_hashes(root, paths): + """Pin all bytes except the root app's coherent, non-resolving release number. + + The app build.rs reports this number; it does not select the locked JSON + source or the platform enum producer. Member/dependency versions, features, + source identities, comments and all other metadata remain byte-pinned. + """ + manifest = (root / 'Cargo.toml').read_bytes().replace(b'\r\n', b'\n').decode('utf-8') + section = _sections(manifest)['package'] + package = _table(section) + name, version = package['name'], package['version'] + if not isinstance(name, str) or not isinstance(version, str) or not re.fullmatch(r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)', version): + raise ValueError('unsupported local root package version') + lock = (root / 'Cargo.lock').read_bytes().replace(b'\r\n', b'\n').decode('utf-8') + entries = [(body, _table(body)) for body in lock.split('[[package]]')[1:]] + local = [(body, entry) for body, entry in entries if entry.get('name') == name] + if len(local) != 1 or local[0][1].get('version') != version or {'source', 'checksum'} & set(local[0][1]): + raise ValueError('ambiguous/nonlocal root lock identity or version mismatch') + if any(dep.split(' ')[0] == name for _, entry in entries for dep in entry.get('dependencies', [])): + raise ValueError('root version participates in dependency resolution') + manifests = {p: _local_sha((root / p).read_bytes()) for p in paths} + manifests['Cargo.toml'] = _sha(_mask_local_version(manifest, section, version).encode('utf-8')) + return {'manifests': manifests, + 'lock_sha256': _sha(_mask_local_version(lock, local[0][0], version).encode('utf-8'))} + + +def _configs(root): + return {name: _local_sha((root / name).read_bytes()) if (root / name).exists() else None + for name in ('.cargo/config', '.cargo/config.toml', '../.cargo/config', '../.cargo/config.toml')} + + +def _version_matches(requirement, version): + if not isinstance(requirement, str): return False + if requirement.startswith('='): return requirement[1:] == version + requirement = requirement.removeprefix('^') + if not re.fullmatch(r'[1-9][0-9]*(?:\.[0-9]+){0,2}', requirement): return False + wanted, actual = [int(x) for x in requirement.split('.')], [int(x) for x in version.split('.')] + return actual[0] == wanted[0] and actual >= wanted + [0] * (3 - len(wanted)) + + +def _bindings(root, paths, package): + ws = _sections((root / 'Cargo.toml').read_text(encoding='utf-8')) + inherited = _table(ws.get('workspace.dependencies', '')) + owners = {} + for path in paths: + sections = _sections((root / path).read_text(encoding='utf-8')) + if any(s.startswith(('patch', 'replace', 'source')) for s in sections): + raise ValueError('source override requires independent review') + dependencies = {} + for section, body in sections.items(): + if section == 'workspace.dependencies': continue + if section in ('dependencies', 'dev-dependencies', 'build-dependencies') or re.fullmatch(r'target\..+\.(?:dev-|build-)?dependencies', section): + for alias, entry in _table(body).items(): + entry = {'version': entry} if isinstance(entry, str) else dict(entry) + if entry.get('workspace') is True: + if set(entry) - {'workspace', 'features', 'optional', 'default-features'}: + raise ValueError('unsupported workspace inheritance') + base = inherited[alias] + base = {'version': base} if isinstance(base, str) else dict(base) + features = base.get('features', []) + entry.get('features', []) + base.update({k: v for k, v in entry.items() if k not in ('workspace', 'features')}) + base['features'] = features; entry = base + actual = entry.get('package', alias) + if alias == 'serde_json' or actual == 'serde_json': + if alias != 'serde_json' or actual != 'serde_json' or set(entry) - {'package', 'version', 'default-features', 'features', 'optional'}: + raise ValueError('noncanonical/renamed serde_json dependency') + if not _version_matches(entry.get('version'), package['version']): + raise ValueError('dependency requirement does not select locked source') + if not set(entry.get('features', [])) <= set(SUPPORTED): + raise ValueError('unsupported serde_json feature') + dependencies.setdefault(alias, []).append(entry) + elif re.search(r'(?:^|\.)(?:dev-|build-)?dependencies\.serde_json$', section): + raise ValueError('dependency subtable form unsupported; review required') + if not dependencies: continue + for items in _table(sections.get('features', '')).values(): + if not isinstance(items, list): raise ValueError('unsupported feature definition') + for feature in items: + if feature.startswith(('serde_json/', 'serde_json?/')) and feature.split('/', 1)[1] not in SUPPORTED: + raise ValueError('unsupported forwarded serde_json feature') + pkg = _table(sections['package']) + edition = pkg.get('edition') + if edition == {'workspace': True}: edition = _table(ws.get('workspace.package', '')).get('edition') + if edition not in ('2018', '2021', '2024'): raise ValueError('absolute external prelude requires Rust 2018+') + parent = Path(path).parent + default = 'src/lib.rs' if (root / parent / 'src/lib.rs').is_file() else 'src/main.rs' + lib = _table(sections.get('lib', '')).get('path', default) + if lib not in ('src/lib.rs', 'src/main.rs'): raise ValueError('nonstandard crate root requires review') + lib_path = (parent / lib).as_posix() + owners[path] = {'dependency': dependencies['serde_json'], 'edition': edition, + 'lib': lib_path, 'lib_sha256': _local_sha((root / lib_path).read_bytes())} + return owners + + +def _item(tokens, prefix): + starts = [i for i in range(len(tokens)) if tokens[i:i + len(prefix)] == prefix] + if len(starts) != 1: raise ValueError('missing or ambiguous source declaration') + start = starts[0]; depth = 0 + for end in range(start, len(tokens)): + token = tokens[end] + depth += (token == '{') - (token == '}') + if (token == '}' and not depth) or (token == ';' and not depth): return tokens[start:end + 1] + raise ValueError('unclosed source declaration') + + +def _review(sources): + expected = { + 'Value': ('src/value/mod.rs', 'pub enum Value', 'pub enum Value { Null, Bool(bool), Number(Number), String(String), Array(Vec), Object(Map), }'), + 'Number': ('src/number.rs', 'pub struct Number', 'pub struct Number { n: N, }'), + 'N_numeric': ('src/number.rs', '#[cfg(not(feature = "arbitrary_precision"))] #[derive(Copy, Clone)] enum N', '#[cfg(not(feature = "arbitrary_precision"))] #[derive(Copy, Clone)] enum N { PosInt(u64), NegInt(i64), Float(f64), }'), + 'N_string': ('src/number.rs', '#[cfg(feature = "arbitrary_precision")] type N', '#[cfg(feature = "arbitrary_precision")] type N = String;'), + 'Map': ('src/map.rs', 'pub struct Map', 'pub struct Map { map: MapImpl, }'), + 'Map_tree': ('src/map.rs', '#[cfg(not(feature = "preserve_order"))] type MapImpl', '#[cfg(not(feature = "preserve_order"))] type MapImpl = BTreeMap;'), + 'Map_ordered_UNSUPPORTED': ('src/map.rs', '#[cfg(feature = "preserve_order")] type MapImpl', '#[cfg(feature = "preserve_order")] type MapImpl = IndexMap;'), + } + declarations = {} + for name, (path, prefix, declaration) in expected.items(): + found = _item(_tokens(sources[path]), _tokens(prefix)) + if found != _tokens(declaration): raise ValueError('source structural closure changed: ' + name) + declarations[name] = {'path': path, 'tokens': found} + imports = { + 'src/value/mod.rs': ['use alloc::string::String;', 'use alloc::vec::Vec;', 'pub use crate::map::Map;', 'pub use crate::number::Number;'], + 'src/number.rs': ['#[cfg(feature = "arbitrary_precision")] use alloc::string::{String, ToString};'], + 'src/map.rs': ['#[cfg(not(feature = "preserve_order"))] use alloc::collections::{btree_map, BTreeMap};'], + 'src/lib.rs': ['extern crate alloc;', 'pub use crate::value::{from_value, to_value, Map, Number, Value};'], + } + for path, entries in imports.items(): + tokens = _tokens(sources[path]) + for entry in entries: + needle = _tokens(entry) + if sum(tokens[i:i + len(needle)] == needle for i in range(len(tokens))) != 1: + raise ValueError('canonical source import changed: ' + entry) + features = _table(_sections(sources['Cargo.toml'])['features']) + if set(features) != set(SUPPORTED) | {'preserve_order'}: + raise ValueError('unknown source feature branch') + if features['preserve_order'] != ['indexmap', 'alloc', 'dep:foldhash']: + raise ValueError('unknown ordered map branch') + return declarations, features + + +def produce_certificate(root, archive): + """Data-only producer; its output is NOT trusted until reviewed and hash-pinned.""" + root, archive = Path(root).resolve(), Path(archive) + package, dependencies = _locked(root) + data = archive.read_bytes() + if _sha(data) != package['checksum']: raise ValueError('crate archive checksum mismatch BEFORE inspection') + # Never extract or execute archive members. Only bounded regular named files are read. + sources = {} + with tarfile.open(archive, 'r:gz') as crate: + members = crate.getmembers() + if len(members) > 4096 or len({m.name for m in members}) != len(members): + raise ValueError('ambiguous/oversized archive') + for path in SOURCE_PATHS: + member = crate.getmember(package['name'] + '-' + package['version'] + '/' + path) + if not member.isfile() or member.size > 2000000: raise ValueError('unsafe source member') + sources[path] = crate.extractfile(member).read().decode('utf-8') + declared = _table(_sections(sources['Cargo.toml'])['package']) + if (declared.get('name'), declared.get('version')) != (package['name'], package['version']): + raise ValueError('archive package identity mismatch') + declarations, features = _review(sources) + paths = _manifest_paths(root) + hashes = _workspace_hashes(root, paths) + for name, digest in _configs(root).items(): + if digest is not None: + text = (root / name).read_text(encoding='utf-8') + if re.search(r'(?m)^\s*\[(?:source|patch|replace|registries)(?:\.|\])', text) or '--extern' in text or '--cfg' in text: + raise ValueError('Cargo source/compiler override requires review') + return {'schema': SCHEMA, 'package': package, + 'archive': {'sha256': _sha(data), 'bytes': len(data), 'verified_before_inspection': True, + 'url': 'https://static.crates.io/crates/{0}/{0}-{1}.crate'.format(package['name'], package['version'])}, + 'source_files': {p: {'sha256': _sha(sources[p].encode('utf-8')), 'bytes': len(sources[p].encode('utf-8'))} for p in SOURCE_PATHS}, + 'declarations': declarations, 'grammar': GRAMMAR, + 'features': {'definitions': features, 'supported': SUPPORTED, 'unsupported': ['preserve_order'], + 'locked_dependencies': dependencies, + 'guard': 'all local manifest/config bytes and complete Cargo.lock pinned except coherent non-resolving root release version; no indexmap/foldhash lock edges'}, + 'workspace': {'text_hashing': WORKSPACE_HASHING, 'manifests': hashes['manifests'], + 'lock_sha256': hashes['lock_sha256'], + 'configs': _configs(root), 'owners': _bindings(root, paths, package)}, + 'trust_boundary': ['reviewed archive bytes and canonical crates.io Cargo identity', + 'Rust/std sound owned container axioms; arbitrary_precision is owned String', + 'preserve_order and unknown features/types/configurations rejected', + 'no attestation of environment/global Cargo config, --config/--extern overrides or compiler unsoundness', + 'no foreign code execution; runtime requires neither archive/cache/Cargo nor network']} + + +def _load_certificate(): + certificate = json.loads(CERTIFICATE_PATH.read_text(encoding='utf-8')) + if _sha(_json(certificate)) != CERTIFICATE_SHA256: raise ValueError('unreviewed certificate') + if certificate['workspace']['text_hashing'] != WORKSPACE_HASHING: + raise ValueError('unsupported workspace text hashing') + if certificate['schema'] != SCHEMA or certificate['grammar'] != GRAMMAR: + raise ValueError('unsupported certificate grammar/schema') + if certificate['features']['supported'] != SUPPORTED or certificate['features']['unsupported'] != ['preserve_order']: + raise ValueError('unsupported certificate feature boundary') + if set(certificate['source_files']) != set(SOURCE_PATHS): raise ValueError('incomplete source evidence') + if certificate['archive']['sha256'] != certificate['package']['checksum'] or certificate['package']['source'] != REGISTRY: + raise ValueError('certificate archive/identity mismatch') + return certificate + + +def _root_modules_only(text): + tokens = _tokens(text) + i = 0 + while i < len(tokens): + if tokens[i] == 'pub': i += 1 + if i + 2 >= len(tokens) or tokens[i] != 'mod' or not re.fullmatch(r'[A-Za-z_]\w*', tokens[i + 1]) or tokens[i + 2] != ';': + return False + if tokens[i + 1] == 'serde_json': return False + i += 3 + return True + + +def _namespace_safe(crate, source, context): + if context is not None: + if not isinstance(context, dict) or set(context) - {'imports', 'definitions'}: return False + if 'serde_json' in context.get('definitions', ()): return False + if any(entry[0] == 'serde_json' for entry in context.get('imports', ())): return False + for path in sorted((crate / 'src').rglob('*.rs')): + if path.is_symlink() or not path.resolve().is_relative_to(crate.resolve()): return False + tokens = _tokens(path.read_text(encoding='utf-8')) + for i, token in enumerate(tokens): + if token == 'serde_json' and i and tokens[i - 1] in ('mod', 'type', 'struct', 'enum', 'union', 'trait', 'as', 'crate'): + return False + if token == 'use': + end = i + 1 + while end < len(tokens) and tokens[end] != ';': end += 1 + used = tokens[i + 1:end] + if 'serde_json' in used: + at = used.index('serde_json') + if used[:at] not in ([], ['::']) or used[at + 1:at + 2] != ['::']: + return False + return source.is_file() and not source.is_symlink() + + +def provenance(rust_modules_root, source_file, type_tokens, namespace_context=None): + """Return reviewed evidence only for an unambiguous absolute external Value. + + source_file is the declaration's actual owner, NOT the caller's module. + Relative paths/import aliases are deliberately not resolved by this helper. + """ + try: + if isinstance(type_tokens, str) or list(type_tokens) not in (["::", 'serde_json', '::', 'Value'], [':', ':', 'serde_json', ':', ':', 'Value']): + return None + root = Path(rust_modules_root).resolve() + supplied = Path(source_file) + source = supplied.resolve() if supplied.is_absolute() else (root / supplied).resolve() + if not source.is_relative_to(root) or supplied.is_symlink(): return None + certificate = _load_certificate() + workspace = certificate['workspace'] + if set(_manifest_paths(root)) != set(workspace['manifests']): return None + hashes = _workspace_hashes(root, _manifest_paths(root)) + if hashes['manifests'] != workspace['manifests']: return None + if hashes['lock_sha256'] != workspace['lock_sha256'] or _configs(root) != workspace['configs']: + return None + package, dependencies = _locked(root) + if package != certificate['package'] or dependencies != certificate['features']['locked_dependencies']: return None + owner = source.parent + while owner != root and not (owner / 'Cargo.toml').is_file(): owner = owner.parent + manifest = (owner / 'Cargo.toml').relative_to(root).as_posix() + binding = workspace['owners'].get(manifest) + if binding is None or not source.is_relative_to(owner / 'src'): return None + lib_bytes = (root / binding['lib']).read_bytes() + if _local_sha(lib_bytes) != binding['lib_sha256']: return None + # A macro/include at crate root could synthesize an extern-prelude binding. + # Only literal module declarations are understood here; other roots fail closed. + if not _root_modules_only(lib_bytes.decode('utf-8')): return None + if not _namespace_safe(owner, source, namespace_context): return None + return {'schema': SCHEMA, 'certificate_sha256': CERTIFICATE_SHA256, + 'package': package, 'owner_manifest': manifest, 'external_path': '::serde_json::Value', + 'source_files': certificate['source_files'], 'grammar': certificate['grammar'], + 'supported_features': SUPPORTED, 'unsupported_features': ['preserve_order']} + except (OSError, ValueError, KeyError, TypeError, IndexError, UnicodeError, RecursionError): + return None + + +def certify(rust_modules_root, source_file, type_tokens, namespace_context=None): + return provenance(rust_modules_root, source_file, type_tokens, namespace_context) is not None + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--produce', type=Path, required=True, metavar='VERIFIED_CRATE_ARCHIVE') + parser.add_argument('--root', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + proof = produce_certificate(args.root, args.produce) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(proof, indent=2, sort_keys=True) + '\n', encoding='utf-8') + print('REVIEW REQUIRED; canonical certificate SHA256:', _sha(_json(proof))) diff --git a/ci/readonly_generated.py b/ci/readonly_generated.py new file mode 100644 index 0000000000..9943a3a830 --- /dev/null +++ b/ci/readonly_generated.py @@ -0,0 +1,154 @@ +"""Offline source-backed unit-enum proof; certificate changes require source review. + +No Cargo, cached output, generator execution, Copy axiom or type-name exemption. +The certificate pins the entire production pipeline and include namespace, not the +language list. Its reviewed template emits unit variants in every configuration. +Only enum values are certified: LocaleContext/OnceLock and methods are not. +Assumes ordinary Cargo/Rust/std/serde execution, no external build/config/compiler +overrides, output tampering or unsafe-code/compiler unsoundness attestation. +""" +from pathlib import Path +import json +import re +from readonly_dependencies import _local_sha, _sha, _json, _manifest_paths, _configs, _workspace_hashes, WORKSPACE_HASHING + +CERTIFICATE_PATH = Path(__file__).with_name('proofs') / 'platform-generated-enums.json' +CERTIFICATE_SHA256 = '0f020e2791e3b371373bad85574363295fca450b1f9c2f46321bae72391a6dc5' +SOURCES = ['platform/Cargo.toml', 'platform/src/lib.rs', 'platform/src/i18n/mod.rs', + 'platform/build.rs', 'platform/build_support/catalog.rs', 'build_support/install_identities.rs', + 'machine/src/lib.rs', 'machine/src/machine.rs'] +GRAMMAR = {'Preference': {'prefix': ['System'], 'catalogue_unit_variants': True}, + 'Language': {'catalogue_unit_variants': True, 'suffix': ['Pseudo']}} + + +MACHINE_SOURCES = ['571415d64a9885248f852b402153feedd4660acbe03606e4796c59659726049f', + '03a6e18f576dcbaff66c3d7405923b155302bfb2996bb373dac115ece055a5bf'] + + +I18N_SOURCES = ['40a13d07a43c772b10587e510a69502684abfa1f582ce355b22fd935a8c46f45', + '2c978e3aa3a9215a2e96ebaec9dd5ae3cf3ee85cf1afb43a36b5f42f17ff4d52'] + +def source_hashes(root): + sources = {p: _local_sha((root / p).read_bytes()) for p in SOURCES} + # Reviewed checkout variants differ only in NavOp::SelectTabWithChild, not the ID macro. + if sources['machine/src/machine.rs'] not in MACHINE_SOURCES: raise ValueError('unreviewed machine source') + sources['machine/src/machine.rs'] = MACHINE_SOURCES + # Existing consumer variants differ in clock formatting, not include/enum identity. + if sources['platform/src/i18n/mod.rs'] not in I18N_SOURCES: raise ValueError('unreviewed include namespace') + sources['platform/src/i18n/mod.rs'] = I18N_SOURCES + return sources + +def produce_certificate(root): + """Review all executable sources on regeneration; catalogue additions need no pin.""" + root = Path(root).resolve() + hashes = _workspace_hashes(root, _manifest_paths(root)) + return {'schema': 'plx.readonly.generated-unit-enums.v1', 'package': 'plx_platform', + 'module': 'platform/src/i18n/mod.rs', + 'include': 'include!(concat!(env!("OUT_DIR"), "/languages.rs"));', + 'sources': source_hashes(root), + 'text_hashing': WORKSPACE_HASHING, 'manifests': hashes['manifests'], + 'configs': _configs(root), 'lock': hashes['lock_sha256'], + 'grammar': GRAMMAR, 'machine_newtype': 'reviewed local newtype macro emits pub struct Name(pub u32); doc attributes only', + 'review': ['build.rs -> catalog::build(locales, OUT_DIR), no cfg-dependent producer', + 'parse_registry derives variant solely from validated ASCII tag', + 'discover preserves validated LanguageSpec; compile sorts by row', + 'languages_rs emits only unit variants; Pseudo cfg_attr only allows dead_code', + 'string slots use Rust Debug escaping; numeric slots are integers', + 'install_identities writes only install_identities.rs, never languages.rs'], + 'assumptions': __doc__.splitlines()} + + + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: raise ValueError('duplicate catalogue key') + result[key] = value + return result + + +def language_variants(text): + entries = json.loads(text, object_pairs_hook=unique_object) + if not isinstance(entries, list) or not entries: raise ValueError('language array required') + variants, tags, rows = [], set(), set() + required = {'tag', 'native_name', 'region', 'script', 'plurals', 'row'} + last = 0 + for item in entries: + if not isinstance(item, dict) or not required <= set(item) or set(item) - required - {'excluded_regions'}: + raise ValueError('language schema') + tag = item['tag'] + if not isinstance(tag, str) or not re.fullmatch('[a-z]{2,3}', tag) or tag in {'system', 'qps', 'und'} | tags: + raise ValueError('language tag') + variant = tag[0].upper() + tag[1:] + if not re.fullmatch('[A-Z][a-z]{1,2}', variant): raise ValueError('variant identifier') + native = item['native_name'] + if not isinstance(native, str) or not native.strip() or any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in native): + raise ValueError('native name') + if not isinstance(item['region'], str) or not re.fullmatch(re.escape(tag) + '-[A-Z]{2}', item['region']): + raise ValueError('region') + if item['script'] not in ('Latn', 'Cyrl'): raise ValueError('script') + plurals = item['plurals'] + if not isinstance(plurals, list) or any(not isinstance(p, str) for p in plurals) or len(set(plurals)) != len(plurals) or 'other' not in plurals or set(plurals) - {'zero', 'one', 'two', 'few', 'many', 'other'}: + raise ValueError('plurals') + excluded = item.get('excluded_regions', []) + if not isinstance(excluded, list) or any(not isinstance(r, str) or not re.fullmatch('[A-Z]{2}', r) for r in excluded) or len(set(excluded)) != len(excluded): + raise ValueError('excluded regions') + row = item['row'] + if type(row) is not int or not last < row < 1000 or row in rows: raise ValueError('row') + tags.add(tag); rows.add(row); variants.append(variant); last = row + if 'en' not in tags: raise ValueError('English fallback required') + return variants + + +def provenance(rust_modules_root, source_file): + """Return evidence only at the exact reviewed include, never by enum name.""" + try: + root = Path(rust_modules_root).resolve() + path = Path(source_file) + if not path.is_absolute(): path = root / path + if path.resolve() not in (root / 'platform/src/i18n/mod.rs', root / 'machine/src/machine.rs') or path.is_symlink(): return None + cert = json.loads(CERTIFICATE_PATH.read_text(encoding='utf-8')) + if _sha(_json(cert)) != CERTIFICATE_SHA256 or cert != produce_certificate(root): return None + for relative in SOURCES: + p = root / relative + if p.is_symlink() or not p.resolve().is_relative_to(root): return None + if cert['include'] not in (root / cert['module']).read_text(encoding='utf-8'): return None + catalogue = root.parent / 'locales/languages.json' + if catalogue.is_symlink() or not catalogue.resolve().is_relative_to(root.parent): return None + variants = language_variants(catalogue.read_text(encoding='utf-8')) + return {'certificate_sha256': CERTIFICATE_SHA256, 'sources': cert['sources'], 'grammar': GRAMMAR, + 'variants': {'Preference': ['System'] + variants, 'Language': variants + ['Pseudo']}} + except (OSError, ValueError, KeyError, TypeError, IndexError, UnicodeError, RecursionError): + return None + + + + +def canonical_child(root, parent, name, child): + """An include's OUT_DIR belongs to its crate, not a foreign #[path] importer.""" + root = Path(root).resolve() + bindings = {root / 'platform/src/i18n/mod.rs': (root / 'platform/src/lib.rs', 'i18n'), + root / 'machine/src/machine.rs': (root / 'machine/src/lib.rs', 'machine')} + expected = bindings.get(Path(child).resolve()) + return expected is None or expected == (Path(parent).resolve(), name) + +def declarations(root, path): + evidence = provenance(root, path) + if evidence is None: return '' + if Path(path).resolve() == Path(root).resolve() / 'machine/src/machine.rs': + from rust_test_modules import lex + tokens = lex(Path(path).read_text(encoding='utf-8')) + names = [] + for i in range(len(tokens) - 4): + if tokens[i:i + 3] != [('code', 'newtype'), ('code', '!'), ('code', '(')]: continue + j = i + 3 + while tokens[j:j + 2] == [('code', '#'), ('code', '[')]: + # Only documentation meta is part of this reviewed invocation grammar. + if tokens[j + 2:j + 4] != [('code', 'doc'), ('code', '=')] or tokens[j + 4][0] != 'string' or tokens[j + 5] != ('code', ']'): return '' + j += 6 + if tokens[j][0] != 'code' or not re.fullmatch('[A-Za-z_][A-Za-z_0-9]*', tokens[j][1]) or tokens[j + 1:j + 3] != [('code', ')'), ('code', ';')]: return '' + names.append(tokens[j][1]) + return '\n'.join('#[derive(Clone, Copy)] pub struct ' + name + '(pub u32);' for name in names) + return '\n'.join('#[derive(Clone, Copy)] pub enum ' + name + ' { ' + ', '.join(variants) + ' }' + for name, variants in evidence['variants'].items()) diff --git a/ci/rust_test_modules.py b/ci/rust_test_modules.py index b9a8ac028a..2bc68f3fc7 100644 --- a/ci/rust_test_modules.py +++ b/ci/rust_test_modules.py @@ -94,6 +94,8 @@ def expr(i): return {op(values) for values in itertools.product(*children)}, i return {False, True}, i if i < len(tokens) and tokens[i][1] == '=': + if name == 'feature' and i + 1 < len(tokens) and tokens[i + 1] == ('string', 'test-support'): + return {False}, i + 2 return {False, True}, min(i + 2, len(tokens)) return ({False} if name == 'test' else {False, True}), i return expr(0)[0] diff --git a/ci/test_build_bench.py b/ci/test_build_bench.py index f2e4b05885..9f81557d68 100644 --- a/ci/test_build_bench.py +++ b/ci/test_build_bench.py @@ -63,10 +63,11 @@ def read(p): sys.stderr.write("error: fake cargo failed on the edited tree\n") sys.exit(101) if "--no-run" in args: - # cargo judges a path package by mtime: stale when a source file is NEWER than what the last build - # wrote (the state file's own mtime stands for the dependency info), fresh otherwise + # Model active benchmark edits by their controlled marker too: coarse clocks can give an edit + # the same mtime as the last build. Restored bytes + original mtime still read fresh. state = os.environ["FAKE_STATE"] + "." + (os.environ.get("CARGO_TARGET_DIR") or "target").replace("/", "_") fresh = (os.path.exists(state) and all(os.stat(p).st_mtime_ns <= os.stat(state).st_mtime_ns for p in EDITED if os.path.exists(p)) + and not any("// build-bench edit " in read(p) for p in EDITED) and not os.environ.get("FAKE_ALWAYS_DIRTY")) open(state, "w").write("built") if os.environ.get("FAKE_COUNT_BUILDS"): @@ -365,6 +366,42 @@ def test_an_edit_row_really_rebuilds(self): self.assertTrue(all(s["app_rebuilt"] for s in by_id["ui"]["samples"])) self.assertFalse(any(s["app_rebuilt"] for s in by_id["noop"]["samples"])) + def test_equal_mtimes_do_not_hide_active_edits(self): + with Sandbox() as sb: + old = 1_700_000_000_000_000_000 + for rel in SRC_FILES: + os.utime(sb.repo / rel, ns=(old, old)) + counts = sb.repo.parent / "builds.txt" + env = dict(os.environ, FAKE_LOG=str(sb.log), FAKE_STATE=str(sb.state), + FAKE_COUNT_BUILDS=str(counts)) + for key in ("CARGO_TARGET_DIR", "FAKE_ALWAYS_DIRTY", "FAKE_FAIL_ON_EDIT"): + env.pop(key, None) + + def build(): + proc = subprocess.run([sys.executable, str(sb.home / ".cargo/bin/cargo"), "+1.0.0", + *bb.HOST_TEST_BUILD_ARGS], cwd=sb.repo / "rust-modules", + capture_output=True, text=True, env=env) + self.assertEqual(proc.returncode, 0, proc.stderr) + return [json.loads(line)["fresh"] for line in proc.stdout.splitlines() + if line.startswith("{") and "path+file:" in line] + + self.assertTrue(all(not fresh for fresh in build())) + self.assertTrue(all(build())) + guard = bb.EditGuard(sb.repo) + state = Path(str(sb.state) + ".target") + for _ in range(2): + for rel in (LEAF, UI_LEAF): + with self.subTest(round=_, rel=rel): + with guard.edited(rel): + stamp = state.stat().st_mtime_ns + os.utime(sb.repo / rel, ns=(stamp, stamp)) + self.assertEqual((sb.repo / rel).stat().st_mtime_ns, state.stat().st_mtime_ns) + self.assertTrue(all(not fresh for fresh in build()), "active edit reported fresh") + self.assertEqual((sb.repo / rel).stat().st_mtime_ns, old) + self.assertTrue(all(build()), "restored tree reported dirty") + self.assertEqual(counts.read_text().split(), ["rebuilt", "fresh"] + ["rebuilt", "fresh"] * 4) + sb.assert_sources_untouched(self) + class RedTests(unittest.TestCase): """A red unit test is a failed scenario with names, not a timing, and not the end of the run.""" diff --git a/ci/test_build_not_always_dirty.py b/ci/test_build_not_always_dirty.py index a305173207..cf40c440f8 100644 --- a/ci/test_build_not_always_dirty.py +++ b/ci/test_build_not_always_dirty.py @@ -193,7 +193,9 @@ def test_script_stamp_only_for_this_package(self): self.assertEqual(script_stamp(freeze_stamps(json_records(other))), {}) # A later rewrite of the file shows up in the NEXT build's stamp, not the earlier one. records = freeze_stamps(json_records(ours)) + stamp = (build / "output").stat() (build / "output").write_text("cargo:rustc-env=X=2\n") + os.utime(build / "output", ns=(stamp.st_atime_ns, stamp.st_mtime_ns + 2_000_000_000)) self.assertEqual(script_stamp(records), first) self.assertNotEqual(script_stamp(freeze_stamps(json_records(ours))), first) diff --git a/ci/test_check_list_caps.py b/ci/test_check_list_caps.py index a67e329a97..aaf5f44f9b 100644 --- a/ci/test_check_list_caps.py +++ b/ci/test_check_list_caps.py @@ -116,6 +116,45 @@ def test_cfg_test_items_files_and_names_are_skipped(self): }) self.assertEqual(tree.keys(), []) + def test_cfg_fields_do_not_consume_enclosing_scopes_or_live_fields(self): + for field in ('None', 'Some({ v.iter().take(2) })', 'v.len() < 2'): + for tail in ('', ','): + with self.subTest(field=field, tail=tail): + body = ('fn snapshot(v: &[u8]) { let _ = Row { ' + '#[cfg(any(test, feature = "test-support"))] hidden: ' + + field + tail + ' }; } const MAX_ROWS: usize = 9;') + self.assertEqual(Tree({SCREEN: body}).keys(), [f'{SCREEN}::MAX_ROWS']) + body = ('struct Row { #[cfg(test)] pub(crate) hidden: Map, live: [u8; MAX_ROWS] } ' + 'fn snapshot(v: &[u8]) { let _ = Row { ' + '#[cfg(test)] hidden: v.len() < 2, live: v.iter().take(3) }; } ' + 'const MAX_OTHER: usize = 9;') + self.assertEqual(Tree({SCREEN: body}).keys(), + [f'{SCREEN}::MAX_OTHER', f'{SCREEN}::Row', f'{SCREEN}::snapshot']) + + def test_cfg_match_arms_preserve_live_arms_and_enclosing_function(self): + body = ('fn plan_rebase(v: &[u8]) { match owner { ' + '#[cfg(any(test, feature = "test-support"))] ' + 'RebaseFor::Inline if open() => return Err(Refused), ' + '_ => { v.iter().take(3); } } ' + 'let _ = match owner { ' + '#[cfg(test)] RebaseFor::Inline => begin(), ' + '_ => v.iter().take(4), }; } ' + 'const SIDE_MAX_PART_KBPS: i64 = 30_000;') + self.assertEqual(Tree({SCREEN: body}).keys(), + [f'{SCREEN}::SIDE_MAX_PART_KBPS', f'{SCREEN}::plan_rebase']) + + def test_test_support_helpers_are_excluded_but_shared_production_is_not(self): + tree = Tree({ + 'screens/src/lib.rs': '#[cfg(any(test, feature = "test-support"))] mod fixture;\n' + 'mod shared;\n' + '#[cfg(test)] #[path = "shared.rs"] mod shared_test;\n', + 'screens/src/fixture.rs': 'fn fixture(v: &[u8]) { v.iter().take(3); }', + 'screens/src/shared.rs': 'fn live(v: &[u8]) { v.iter().take(3); }', + SCREEN: '#[cfg(any(test, feature = "test-support"))] ' + 'fn seed(v: &[u8]) { v.iter().take(2); }', + }) + self.assertEqual(tree.keys(), ['screens/src/shared.rs::live']) + def test_the_app_crate_is_scanned_too(self): tree = Tree({'src/app/run.rs': 'fn a(v: &[u8]) { v.iter().take(3); }'}) self.assertEqual(tree.keys(), ['src/app/run.rs::a']) diff --git a/ci/test_check_machine_shape.py b/ci/test_check_machine_shape.py index db9ff3d5b9..7fff72e6aa 100644 --- a/ci/test_check_machine_shape.py +++ b/ci/test_check_machine_shape.py @@ -3,7 +3,10 @@ (`pub`, `pub(crate)`, `pub(super)`, `pub(in ..)`, a tuple field), a stale entry fails, the `bool` and `Option<..>` counts are reported and never fail, and the real registry is green and wired into check-python-steps.txt. Each case writes a tiny tree to a private temp dir.""" +import configparser import importlib.util +import shutil +import io import tempfile import unittest from pathlib import Path @@ -17,15 +20,23 @@ INI = f'[{FILE}::Machine]\nevent = Ev\neffect = Fx\nstep = inherent\n' -def verdict(source, ini=INI, file=FILE): +def verdict(source, ini=None, file=FILE): """(problems, report) for a one-file tree holding `source` at `file`.""" + if ini is None: + fields = gate.struct_fields(source, 'Machine') or [] + field = fields[0][1] if fields else 'state' + ini = INI + f'writer_policy = strict\nstate_field = {field}\ntransition = transition\nconstructor = new\n\n[module {FILE}]\nwildcard_enum_match_arm = deny\n' + source = '#![deny(clippy::wildcard_enum_match_arm)]\n' + source + initial = ', '.join(f'{key}: 0' for _, key, _ in fields) + source += f'\nenum Ev {{ Set }} enum Fx {{ Changed }} impl Machine {{ fn new() -> Self {{ Self {{ {initial} }} }} fn transition(&mut self, event: Ev, fx: &mut Vec) {{ match event {{ Ev::Set => {{ self.{field} = 1; fx.push(Fx::Changed); }} }} }} }}' with tempfile.TemporaryDirectory() as temp: modules = Path(temp) / 'rust-modules' (modules / file).parent.mkdir(parents=True) (modules / file).write_text(source) registry = Path(temp) / 'machines.ini' registry.write_text(ini) - return gate.check(modules=modules, ini=registry) + problems, report = gate.check(modules=modules, ini=registry) + return problems, [line for line in report if line.startswith('machine ')] class Visibility(unittest.TestCase): @@ -47,7 +58,7 @@ def test_a_pub_field_behind_an_attribute_or_doc_comment_fails(self): def test_a_tuple_field_is_graded_by_index(self): problems, _ = verdict('pub struct Machine(u8, pub u64);') - self.assertEqual(len(problems), 1, problems) + self.assertTrue(problems) self.assertIn('Machine.1 is public', problems[0]) def test_pub_in_a_comment_or_a_string_is_no_field(self): @@ -78,14 +89,14 @@ def test_bool_and_option_fields_are_counted_and_never_fail(self): def test_a_unit_struct_has_no_fields(self): problems, report = verdict('pub struct Machine;') - self.assertEqual(problems, []) + self.assertTrue(problems) self.assertIn('0 fields, 0 bool, 0 Option', report[0]) class Registry(unittest.TestCase): def test_a_missing_file_is_a_stale_entry(self): problems, _ = verdict('pub struct Machine { x: u8 }', file='media/src/player/elsewhere.rs') - self.assertEqual(len(problems), 1, problems) + self.assertTrue(problems) self.assertIn('stale entry', problems[0]) def test_a_missing_struct_is_a_stale_entry(self): @@ -111,5 +122,121 @@ def test_the_gate_and_its_test_are_wired_into_check_python_steps(self): self.assertTrue(line in steps, f'{line!r} is not a line of ci/check-python-steps.txt') +class MandatoryCohort(unittest.TestCase): + def test_future_machine_cannot_opt_out(self): + source = 'struct Machine { state: u8 } impl Machine { fn rogue(&mut self) { self.state = 2; } }' + problems, _ = verdict(source, ini=INI) + self.assertTrue(problems, 'a newly registered private machine must not opt out') + + def test_every_actual_entry_mutation_matrix(self): + registry = configparser.ConfigParser(interpolation=None) + registry.read(ROOT / 'ci/machines.ini') + entries = [s for s in registry.sections() if not s.startswith('module ')] + self.assertTrue(entries, 'registry is the only normative cohort list') + with tempfile.TemporaryDirectory() as temp: + modules = Path(temp) / 'rust-modules' + for crate in (ROOT / 'rust-modules').iterdir(): + if not crate.is_dir() or not (crate / 'Cargo.toml').is_file(): continue + destination = modules / crate.name + destination.mkdir(parents=True) + shutil.copyfile(crate / 'Cargo.toml', destination / 'Cargo.toml') + if (crate / 'src').is_dir(): + shutil.copytree(crate / 'src', destination / 'src') + # The dependency proof checks the exact locked workspace, even in mutation fixtures. + for relative in ('Cargo.toml', 'Cargo.lock', '.cargo/config', '.cargo/config.toml'): + source = ROOT / 'rust-modules' / relative + if source.is_file(): + destination = modules / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + # Source-backed generated layouts require the actual producers and dynamic input. + for relative in ('platform/build.rs', 'platform/build_support/catalog.rs', 'build_support/install_identities.rs', '../locales/languages.json'): + destination = modules / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / 'rust-modules' / relative, destination) + ini = Path(temp) / 'machines.ini' + for section in entries: + file, name = section.split('::') + policy = 'module ' + file + path = modules / file + original = path.read_text(encoding='utf-8') + contract = dict(registry[section]) + field = contract.get('state_field', 'state') + def check(entry=contract, module=True, source=original): + config = configparser.ConfigParser(interpolation=None) + config[section] = entry + if module: + config[policy] = dict(registry[policy]) if policy in registry else {'wildcard_enum_match_arm': 'deny'} + out = io.StringIO() + config.write(out) + ini.write_text(out.getvalue(), encoding='utf-8') + path.write_text(source, encoding='utf-8') + return gate.check(modules, ini)[0] + mutations = { + 'all-writer-keys': ({k: v for k, v in contract.items() if k not in ('writer_policy', 'state_field', 'transition', 'constructor')}, True, original), + 'enum-section': (contract, False, original), + 'enum-header': (contract, True, original.replace('#![deny(clippy::wildcard_enum_match_arm)]', '').replace('#![forbid(clippy::wildcard_enum_match_arm)]', '')), + 'rogue-writer': (contract, True, original + f'\nimpl {name} {{ fn contract_rogue(&mut self) {{ self.{field} = panic!("rogue"); }} }}\n'), + 'state-escape': (contract, True, original + f'\nimpl {name} {{ fn contract_escape(&mut self) {{ let escape = &mut self.{field}; }} }}\n'), + 'suppression': (contract, True, '#![allow(clippy::wildcard_enum_match_arm)]\n' + original), + } + for level in ('expect', 'warn'): + mutations['suppression-' + level] = (contract, True, f'#![{level}(clippy::wildcard_enum_match_arm)]\n' + original) + for key in ('writer_policy', 'state_field', 'transition', 'constructor'): + mutations['missing-' + key] = ({k: v for k, v in contract.items() if k != key}, True, original) + for mutation, args in mutations.items(): + with self.subTest(machine=section, mutation=mutation): + self.assertTrue(check(*args), f'{section}: {mutation} escaped enforcement') + with self.subTest(machine=section, mutation='baseline'): + self.assertEqual(check(), []) + path.write_text(original, encoding='utf-8') + conditional = original + '#[cfg_attr(feature = "shipping", path = "alternate.rs")] mod contract_child;' + with self.subTest(machine=section, mutation='conditional-production-child'): + self.assertTrue(check(source=conditional)) + path.write_text(original, encoding='utf-8') + + + +class CompleteOwnedCohort(unittest.TestCase): + def test_every_actual_owned_field_extra_writer_matrix(self): + from machine_readonly import Proof + registry = configparser.ConfigParser(interpolation=None) + registry.read(ROOT / 'ci/machines.ini') + entries = [s for s in registry.sections() if not s.startswith('module ')] + self.assertTrue(entries) + total_fields = total_mutations = 0 + for section in entries: + file, name = section.split('::') + contract = registry[section] + root = ROOT / 'rust-modules' + original = (root / file).read_text(encoding='utf-8') + proof = Proof(root, gate) + fields = gate.struct_fields(gate.production_tokens(original), name) or [] + self.assertTrue(fields) + bodies = ( + 'self.{field} = panic!("rogue");', + 'self.{field} += panic!("rogue");', + 'let alias = &mut self.{field}; unknown(alias);', + 'self.{field}.clear();', + 'unknown!(self.{field});', + 'std::mem::take(&mut self.{field});', + 'let ptr = core::ptr::addr_of_mut!(self.{field});', + ) + for _, owned_field, actual_type in fields: + self.assertTrue(actual_type, (section, owned_field)) + total_fields += 1 + for body in bodies: + mutation = body.replace('{field}', owned_field) + child = f'impl {name} {{ fn contract_field_rogue(&mut self) {{ {mutation} }} }}' + with self.subTest(machine=section, owned_field=owned_field, mutation=mutation): + self.assertTrue(gate.writer_problems(child, name, contract['state_field'], + contract['transition'], contract['constructor'], file, + require_methods=False, event=contract['event'], effect=contract['effect'], + proof=proof, shared_reads=contract.get('state_reads') == 'immutable', + owned_fields=fields), f'{section}.{owned_field}: extra writer escaped') + total_mutations += 1 + print(f'owned-field matrix: {len(entries)} machines, {total_fields} fields, {total_mutations} rejected writers') + + if __name__ == '__main__': unittest.main() diff --git a/ci/test_check_machine_writer.py b/ci/test_check_machine_writer.py new file mode 100644 index 0000000000..06e3d6923f --- /dev/null +++ b/ci/test_check_machine_writer.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python3 +"""Strict writer and enum-lint contracts, exercised only on private synthetic trees.""" +import importlib.util +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +spec = importlib.util.spec_from_file_location('shape', ROOT / 'ci/check-machine-shape.py') +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) + +FILE = 'fixture/src/machine.rs' +STRICT = f'[{FILE}::Machine]\nevent = Event\neffect = Fx\nwriter_policy = strict\nstate_field = state\ntransition = transition\nconstructor = new\n' +TYPES = 'enum Event { Set } enum Fx { Changed }\n' +HEADER = TYPES + 'struct Machine { state: u8 }\n' +GOOD = '''impl Machine { + fn new() -> Self { Self { state: 0 } } + fn transition(&mut self, event: Event, fx: &mut Vec) { match event { Event::Set => { self.state = 1; fx.push(Fx::Changed); } } } + fn read(&self) -> u8 { self.state } +} +''' + + +def verdict(source, ini=STRICT, extra=None): + if '::Machine]' in ini and '[module ' + FILE + ']' not in ini: + ini += f'\n[module {FILE}]\nwildcard_enum_match_arm = deny\n' + source = '#![deny(clippy::wildcard_enum_match_arm)]\n' + source + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / 'rust-modules' + path = root / FILE + path.parent.mkdir(parents=True) + path.write_text(source, encoding='utf-8') + for name, text in (extra or {}).items(): + child = root / name + child.parent.mkdir(parents=True, exist_ok=True) + child.write_text(text, encoding='utf-8') + registry = Path(tmp) / 'machines.ini' + registry.write_text(ini, encoding='utf-8') + return gate.check(root, registry)[0] + + +class Writer(unittest.TestCase): + def test_constructor_transition_read_and_test_only(self): + src = HEADER + GOOD + ''' +#[cfg(test)] mod tests { fn helper(m: &mut super::Machine) { m.state = 2; } } +impl Machine { #[cfg(test)] fn fixture() -> Self { Self { state: 2 } } } +// self.state = 99; +const TEXT: &str = "self.state = 99;"; +''' + self.assertEqual(verdict(src), []) + + def test_associated_self_constant_constructor(self): + ini = STRICT.replace('constructor = new', 'constructor = IDLE') + source = HEADER + '''impl Machine { + pub const IDLE: Self = Self { state: 0 }; + fn transition(&mut self, event: Event, fx: &mut Vec) { self.state = 1; } +} +''' + self.assertEqual(verdict(source, ini), []) + self.assertEqual(verdict(source + '#[cfg(test)] mod tests { fn fixture() -> super::Machine { super::Machine { state: 3 } } }', ini), []) + for replacement in ( + 'const IDLE: Self = Self { other: 0 };', + 'const IDLE: Machine = Self { state: 0 };', + 'const IDLE: Self = make();', + 'const WRONG: Self = Self { state: 0 };', + ): + with self.subTest(replacement=replacement): + self.assertTrue(verdict(source.replace('pub const IDLE: Self = Self { state: 0 };', replacement), ini)) + self.assertTrue(verdict(source + ' impl Other { const IDLE: Self = Self { state: 0 }; }', ini)) + self.assertTrue(verdict(source + ' impl Machine { const OTHER: Self = Self { state: 0 }; }', ini)) + self.assertTrue(verdict(source + ' impl Machine { fn helper(&mut self) { self.state = 7; } }', ini)) + self.assertTrue(verdict(source.replace('pub const IDLE: Self = Self { state: 0 };', + 'fn fake() { const IDLE: Self = Self { state: 0 }; }'), ini)) + self.assertTrue(verdict(source.replace('pub const IDLE: Self = Self { state: 0 };', '') + + ' impl Trait for Machine { const IDLE: Self = Self { state: 0 }; }', ini)) + + def test_production_mutations_and_escapes_fail(self): + examples = [ + 'self.state = 3;', 'self.state += 1;', 'self.state <<= 1;', 'self.state >>= 1;', 'self.state.inner.value = 1;', + '(self.state, other) = (1, 2);', 'let x = &mut self.state;', + 'let x = &mut self.state.inner;', 'std::mem::replace(&mut self.state, 0);', + 'std::mem::take(&mut self.state);', 'std::mem::swap(&mut self.state, x);', + 'self.state.borrow_mut().push(1);', 'self.state.push(1);', + 'let Machine { state: ref mut x, .. } = self;', + 'let Machine { ref mut state, .. } = self;', + 'let Machine { state, .. } = self;', + 'let x = Self { state: 0 };', '*self = Self::new();', + 'let x = &mut self.r#state;', 'let ref mut alias = self.state;', + 'let ptr = core::ptr::addr_of_mut!(self.state);', + 'let alias = &self.state; alias.borrow_mut();', + 'let alias = self.state; alias.borrow_mut();', 'mutate(self.state);', + ] + for code in examples: + with self.subTest(code=code): + src = HEADER + GOOD + 'impl Machine { fn helper(&mut self) { ' + code + ' } }' + self.assertTrue(verdict(src), code) + + def test_other_impl_does_not_authorize_writer_or_constructor(self): + for method in ('fn transition(&mut self, event: Event, fx: &mut Vec) { self.state = 2; }', + 'fn new() -> Machine { Machine { state: 2 } }'): + self.assertTrue(verdict(HEADER + GOOD + 'struct Other; impl Other { ' + method + ' }')) + + def test_free_helper_cannot_write(self): + src = HEADER + GOOD + 'fn helper(m: &mut Machine) { m.state = 1; }' + self.assertTrue(verdict(src)) + + def test_machine_alias_cannot_replace_or_escape_state(self): + examples = ( + 'fn helper(m: &mut Machine) { *m = Machine::new(); }', + 'fn helper(m: &mut Machine) { std::mem::replace(m, Machine::new()); }', + 'fn helper(m: &mut super::Machine) { *m = Machine::new(); }', + 'impl Machine { fn helper(m: &mut Self) { *m = Self::new(); } }', + 'impl Machine { fn helper(&mut self) { replace_elsewhere(self); } }', + 'impl Machine { fn helper(&mut self) { let alias = &mut *self; replace_elsewhere(alias); } }', + ) + for code in examples: + with self.subTest(code=code): + self.assertTrue(verdict(HEADER + GOOD + code), code) + leaked = GOOD.replace('self.state = 1;', 'replace_elsewhere(self);') + self.assertTrue(verdict(HEADER + leaked)) + + def test_macro_cannot_hide_a_field_name(self): + src = HEADER + GOOD + 'impl Machine { fn helper(&mut self) { mutate!(self, state); } }' + self.assertTrue(verdict(src)) + + def test_readonly_matches_and_copy_enum_helper(self): + src = TYPES + '''#[derive(Clone, Copy)] enum State { Idle, Active } +struct Machine { state: State } +impl Machine { + fn new() -> Self { Self { state: State::Idle } } + fn transition(&mut self, event: Event, fx: &mut Vec) { self.state = State::Active; } + fn is_idle(snapshot: State) -> bool { matches!(snapshot, State::Idle) } + fn snapshot(&self) -> bool { Self::is_idle(self.state) } + fn read(&self) -> bool { matches!(self.state, State::Idle | State::Active) } + fn assert_snapshot(&self) { assert!(matches!(self.state, State::Idle)); } + fn debug_snapshot(&self) { debug_assert!(matches!(self.state, State::Active),); } +} +enum Effect { Prepare, Load } +impl Effect { fn awaits(&self) -> bool { matches!(self, Self::Prepare | Self::Load) } } +''' + self.assertEqual(verdict(src), []) + self.assertTrue(verdict(src + 'impl Machine { fn leak(&mut self) -> &mut State { self.state } }')) + self.assertTrue(verdict(src + 'impl Machine { fn alias(&mut self) { let x = self.state; x.mutate(); } }')) + self.assertTrue(verdict(src + 'impl Machine { fn mutate(&mut self) { self.state.mutate(); } }')) + self.assertTrue(verdict(src.replace('enum State { Idle, Active }', 'enum State { Idle, Active(&\'static Cell) }'))) + + def test_readonly_macro_does_not_hide_writes_or_aliases(self): + examples = ( + 'matches!({ self.state = 3; self.state }, 3);', + 'matches!({ self.state += 1; self.state }, 3);', + 'matches!({ let x = &mut self.state; *x = 3; self.state }, 3);', + 'matches!(std::mem::replace(&mut self.state, 3), 0);', + 'matches!(self.state, ref mut alias);', + 'matches!(self.state, x if { x.mutate(); true });', + 'matches!(self.state, _ if { self.state = 1; true });', + 'assert!(matches!({ self.state = 3; self.state }, 3));', + 'assert!(matches!(self.state, 0), "{}", { self.state = 1; 0 });', + 'unknown!(self.state);', + 'unknown!(self, state);', + 'evil::matches!(self.state, _);', + ) + for code in examples: + with self.subTest(code=code): + problems = verdict(HEADER + GOOD + 'impl Machine { fn helper(&mut self) { ' + code + ' } }') + self.assertTrue(problems, code) + self.assertTrue(any(FILE + '::helper:' in problem for problem in problems), problems) + shadow = 'macro_rules! matches { ($($x:tt)*) => { mutate(self) } }\n' + self.assertTrue(verdict(shadow + HEADER + GOOD + + 'impl Machine { fn helper(&self) { matches!(self.state, 0); } }')) + imported = 'use other::matches;\n' + self.assertTrue(verdict(imported + HEADER + GOOD + + 'impl Machine { fn helper(&self) { matches!(self.state, 0); } }')) + + def test_nested_helper_is_not_writer(self): + src = HEADER + GOOD.replace('self.state = 1;', 'fn helper(m: &mut Machine) { m.state = 2; }') + self.assertTrue(verdict(src)) + + def test_mutable_accessor_cannot_escape_without_explicit_borrow(self): + src = HEADER + GOOD + 'impl Machine { fn leak(&mut self) -> &mut u8 { self.state } }' + self.assertTrue(verdict(src)) + src = HEADER + GOOD + "impl Machine { fn leak<'a>(&'a mut self) -> &'a mut u8 { self.state } }" + self.assertTrue(verdict(src)) + + def test_visibility_does_not_define_writer(self): + src = HEADER + GOOD + 'impl Machine { pub(crate) fn step(&mut self, event: Event, fx: &mut Vec) { self.transition(event, fx); } }' + self.assertEqual(verdict(src), []) + self.assertTrue(verdict(src + 'impl Machine { pub fn update(&mut self) { self.state = 4; } }')) + self.assertTrue(verdict(HEADER + GOOD.replace('fn transition', 'pub(crate) fn transition'))) + + def test_strict_keys_and_stale_contract(self): + for ini in (f'[{FILE}::Machine]\nstate_field = state\n', + STRICT.replace('transition = transition\n', ''), + STRICT.replace('constructor = new', 'constructor = '), + STRICT.replace('state_field = state', 'state_field = missing'), + STRICT.replace('transition = transition', 'transition = missing'), + STRICT.replace('constructor = new', 'constructor = missing')): + with self.subTest(ini=ini): + self.assertTrue(verdict(HEADER + GOOD, ini)) + + def test_raw_field_and_invalid_writer_signatures(self): + raw = HEADER.replace('state:', 'r#state:') + GOOD.replace('.state', '.r#state').replace('{ state:', '{ r#state:') + self.assertEqual(verdict(raw), []) + self.assertTrue(verdict(HEADER + GOOD.replace('fn new() -> Self', 'fn new(&mut self) -> Self'))) + self.assertTrue(verdict(HEADER + GOOD.replace('fn transition(&mut self, event: Event, fx: &mut Vec)', 'fn transition(&self)'))) + src = HEADER + GOOD + '#[cfg(any(test, feature = "extra"))] fn helper(m: &mut Machine) { m.state = 5; }' + self.assertTrue(verdict(src)) + + def test_writer_cannot_leak_mutable_field_borrow(self): + src = HEADER + GOOD.replace('self.state = 1;', 'let leaked = &mut self.state; give_away(leaked);') + self.assertTrue(verdict(src)) + + def test_production_child_module_is_checked_but_test_module_is_not(self): + child = 'fixture/src/machine/helper.rs' + src = HEADER + GOOD + '\nmod helper;' + self.assertTrue(verdict(src, extra={child: 'fn poke(m: &mut super::Machine) { m.state = 3; }'})) + self.assertEqual(verdict(src.replace('mod helper;', '#[cfg(test)] mod helper;'), + extra={child: 'fn poke(m: &mut super::Machine) { m.state = 3; }'}), []) + + +class WildcardPolicy(unittest.TestCase): + def test_module_must_really_deny_the_clippy_lint(self): + ini = f'[module {FILE}]\nwildcard_enum_match_arm = deny\n' + for src in ('', '// #![deny(clippy::wildcard_enum_match_arm)]', + 'const S: &str = "#![deny(clippy::wildcard_enum_match_arm)]";', + '#![allow(clippy::wildcard_enum_match_arm)]', + '#![cfg_attr(test, deny(clippy::wildcard_enum_match_arm))]', + '#![deny(clippy::wildcard_enum_match_arm)]\n#[allow(clippy::wildcard_enum_match_arm)] fn x() {}'): + with self.subTest(src=src): + self.assertTrue(verdict(src, ini)) + self.assertEqual(verdict('#![deny(clippy::wildcard_enum_match_arm)]\n' + 'fn numeric(n: u8) { match n { 0 => (), _ => () } }', ini), []) + def test_policy_cannot_be_downgraded_in_root_child_or_include(self): + ini = f'[module {FILE}]\nwildcard_enum_match_arm = deny\n' + header = '#![deny(clippy::wildcard_enum_match_arm)]\n' + for level in ('allow', 'expect', 'warn'): + for attribute in (f'#[{level}(clippy::wildcard_enum_match_arm)]', + f'#[cfg_attr(feature = "shipping", {level}(clippy::wildcard_enum_match_arm))]'): + weak = attribute + ' fn weak() {}' + with self.subTest(level=level, attribute=attribute): + self.assertTrue(verdict(header + weak, ini)) + self.assertTrue(verdict(header + 'mod child;', ini, {'fixture/src/machine/child.rs': weak})) + self.assertTrue(verdict(header + 'include!("included.rs");', ini, {'fixture/src/included.rs': weak})) + wire = 'fn wire(s: &str) { match s { "known" => (), _ => () } }' + self.assertEqual(verdict(header + wire, ini), []) + + def test_missing_stale_or_unknown_policy_fails(self): + for ini in (f'[module {FILE}]\n', f'[module {FILE}]\nwildcard_enum_match_arm = maybe\n', + '[module missing.rs]\nwildcard_enum_match_arm = deny\n'): + self.assertTrue(verdict('', ini)) + + + +class EventContract(unittest.TestCase): + def test_event_binding_rejects_setters_missing_and_prose_metadata(self): + self.assertEqual(verdict(HEADER + GOOD), []) + for source, ini in ( + (HEADER + GOOD.replace('event: Event', 'event: u8'), STRICT), + (HEADER + GOOD.replace('event: Event', 'event: State'), STRICT), + (HEADER + GOOD.replace('event: Event', 'event: &mut Event'), STRICT), + (HEADER + GOOD, STRICT.replace('event = Event', 'event = State')), + (HEADER + GOOD, STRICT.replace('event = Event', 'event = Event (prose)')), + (HEADER + GOOD, STRICT.replace('event = Event\n', '')), + (HEADER + GOOD, STRICT.replace('effect = Fx\n', '')), + (HEADER.replace('enum Event { Set }', 'struct Event;') + GOOD, STRICT), + ): + with self.subTest(source=source, ini=ini): self.assertTrue(verdict(source, ini)) + raw = HEADER.replace('state: u8', 'state: Event') + GOOD + self.assertTrue(verdict(raw), 'an owned state enum is not an admission event') + + def test_effect_binding_requires_real_mutable_registered_enum_output(self): + for typ in ('u8', 'Vec', '&Vec', '&mut Vec', '&mut impl FnMut(Fx)', '&mut Unknown'): + with self.subTest(typ=typ): + self.assertTrue(verdict(HEADER + GOOD.replace('&mut Vec', typ))) + self.assertTrue(verdict(HEADER.replace('enum Fx { Changed }', 'struct Fx;') + GOOD)) + self.assertTrue(verdict(HEADER + GOOD, STRICT.replace('effect = Fx', 'effect = none (later)'))) + + def test_borrowed_event_and_real_effect_alias_are_bound(self): + for alias in ('type Effects = Vec;', 'type Effects = std::vec::Vec;'): + self.assertEqual(verdict(alias + HEADER + GOOD.replace('event: Event', 'event: &Event').replace('&mut Vec', '&mut Effects')), []) + child = 'fixture/src/machine/output.rs' + source = 'mod output; use output::Effects;' + HEADER.replace('enum Fx { Changed }', 'use output::Fx;') + GOOD.replace('&mut Vec', '&mut Effects') + self.assertEqual(verdict(source, extra={child: 'pub enum Fx { Changed } pub type Effects = Vec;'}), []) + self.assertTrue(verdict('type Vec = Unknown;' + HEADER + GOOD)) + + def test_pure_view_exact_none_has_no_effect_channel(self): + source = HEADER + GOOD.replace(', fx: &mut Vec', '').replace(' fx.push(Fx::Changed);', '') + ini = STRICT.replace('effect = Fx', 'effect = none') + self.assertEqual(verdict(source, ini), []) + self.assertTrue(verdict(HEADER + GOOD, ini)) + + def test_every_owned_field_and_production_child_is_guarded(self): + source = HEADER.replace('state: u8', 'state: u8, pending: Vec, next_command: u64, cache: String') + GOOD.replace('state: 0', 'state: 0, pending: Vec::new(), next_command: 0, cache: String::new()') + self.assertEqual(verdict(source), []) + for field in ('state', 'pending', 'next_command', 'cache'): + for body in (f'self.{field} = panic!("rogue");', f'let alias = &mut self.{field}; unknown(alias);', f'unknown!(self.{field});'): + with self.subTest(field=field, body=body): + self.assertTrue(verdict(source + 'impl Machine { fn rogue(&mut self) { ' + body + ' } }')) + self.assertTrue(verdict(source + 'mod child;', extra={'fixture/src/machine/child.rs': 'fn rogue(m: &mut super::Machine) { ' + body.replace('self.', 'm.') + ' }'})) + self.assertTrue(verdict(source + 'impl Machine { fn drain(&mut self) { self.pending.clear(); self.next_command = 0; } }')) + + def test_mutating_helpers_do_not_inherit_reducer_authority(self): + for helper in ('fn helper(&mut self) { self.state = 5; }', 'fn helper(&mut self) { unknown(self); }'): + source = HEADER + GOOD.replace('self.state = 1;', 'self.helper();') + 'impl Machine { ' + helper + ' }' + self.assertTrue(verdict(source)) + self.assertTrue(verdict(HEADER + GOOD.replace('self.state = 1;', 'self.unknown();'))) + for body in ('let mut nested = || { self.state = 5; }; nested();', + 'let mut nested = || self.state = 5; nested();', + 'let mut nested = move || { *self = Self::new(); }; nested();', + 'fn nested(m: &mut Machine) { m.state = 5; } nested(self);', + 'unknown!(self);', 'unknown!(self.state);'): + with self.subTest(body=body): self.assertTrue(verdict(HEADER + GOOD.replace('self.state = 1;', body))) + + def test_whole_self_alias_and_unknown_calls_cannot_escape(self): + for body in ('let alias = self; unknown(alias);', 'let alias = &mut *self; unknown(alias);', + 'unknown(self);', '*self = Self::new();', 'Self::setter(self, 0);'): + with self.subTest(body=body): self.assertTrue(verdict(HEADER + GOOD + 'impl Machine { fn rogue(&mut self) { ' + body + ' } }')) + source = 'type Alias = Machine;' + HEADER + GOOD + 'fn rogue(m: &mut Alias) { *m = Machine::new(); }' + self.assertTrue(verdict(source)) + + def test_constructors_are_fresh_not_machine_factories(self): + for signature in ('fn new(other: Self) -> Self', 'fn new(other: Machine) -> Self', 'fn new(other: &Machine) -> Self'): + self.assertTrue(verdict(HEADER + GOOD.replace('fn new() -> Self', signature))) + self.assertTrue(verdict('type Alias = Machine;' + HEADER + GOOD.replace('fn new() -> Self', 'fn new(other: Alias) -> Self'))) + self.assertTrue(verdict(HEADER + GOOD.replace('Self { state: 0 }', 'Self { state: 0, ..other }'))) + + def test_proved_shared_decision_is_not_a_mutself_helper(self): + source = HEADER + GOOD.replace('self.state = 1;', 'self.state = self.decide();') + 'impl Machine { fn decide(&self) -> u8 { 1 } }' + self.assertEqual(verdict(source), []) + self.assertTrue(verdict(source.replace('fn decide(&self)', 'fn decide(&mut self)'))) + + +class ProductionClosure(unittest.TestCase): + def test_conditional_paths_nested_paths_and_unresolved_modules_fail_closed(self): + for attribute in ('#[cfg_attr(feature = "shipping", path = "alternate.rs")]', + '#[cfg_attr(feature = "shipping", cfg_attr(feature = "other", path = "alternate.rs"))]'): + source = HEADER + GOOD + attribute + ' mod child;' + with self.subTest(attribute=attribute): + self.assertTrue(verdict(source, extra={'fixture/src/machine/child.rs': '', 'fixture/src/alternate.rs': 'fn rogue(m: &mut super::Machine) { m.state = 2; }'})) + self.assertEqual(verdict(HEADER + GOOD + '#[cfg(test)]' + attribute + ' mod missing;'), []) + self.assertTrue(verdict(HEADER + GOOD + 'mod generated;')) + self.assertTrue(verdict(HEADER + GOOD + '#[path = "absent.rs"] mod generated;')) + self.assertEqual(verdict(HEADER + GOOD + '#[cfg_attr(feature = "shipping", allow(dead_code))] mod child;', extra={'fixture/src/machine/child.rs': ''}), []) + + def test_static_includes_are_checked_opaque_missing_includes_are_rejected(self): + for include in ('include!(concat!(env!("OUT_DIR"), "/generated.rs"));', 'include!(NAME);', 'include!("missing.rs");'): + with self.subTest(include=include): + self.assertTrue(verdict(HEADER + GOOD + include)) + self.assertEqual(verdict(HEADER + GOOD + '#[cfg(test)] mod tests { ' + include + ' }'), []) + included = 'fixture/src/included.rs' + self.assertEqual(verdict(HEADER + GOOD + 'include!("included.rs");', extra={included: ''}), []) + self.assertTrue(verdict(HEADER + GOOD + 'include!("included.rs");', extra={included: 'fn rogue(m: &mut Machine) { m.state = 2; }'})) + self.assertTrue(verdict(HEADER + GOOD + 'include!("included.rs");', extra={included: 'include!(NAME);'})) + + def test_explicit_and_nested_child_paths_are_exhausted(self): + source = HEADER + GOOD + '#[path = "alternate.rs"] mod child;' + self.assertEqual(verdict(source, extra={'fixture/src/alternate.rs': ''}), []) + self.assertTrue(verdict(source, extra={'fixture/src/alternate.rs': '#![warn(clippy::wildcard_enum_match_arm)]'})) + for level in ('allow', 'expect', 'warn'): + source = HEADER + GOOD + 'mod outer { mod child; }' + self.assertTrue(verdict(source, extra={'fixture/src/machine/outer/child.rs': f'#![{level}(clippy::wildcard_enum_match_arm)]'})) + + +class AlternateAuthorityRegression(unittest.TestCase): + def test_type_alias_impl_and_child_named_transition_are_not_authorities(self): + self.assertTrue(verdict('type Alias = Machine;' + HEADER + GOOD + 'impl Alias { fn rogue(&mut self) { self.state = 3; } }')) + self.assertTrue(verdict('type Alias = Machine;' + HEADER + GOOD + 'impl SomeTrait for Alias { fn rogue(&mut self) { unknown(self); } }')) + source = HEADER + GOOD + 'mod child;' + self.assertTrue(verdict(source, extra={'fixture/src/machine/child.rs': 'use super::Machine; impl Machine { fn transition(&mut self, next: u8) { self.state = next; } }'})) + + +if __name__ == '__main__': + unittest.main() diff --git a/ci/test_check_ports.py b/ci/test_check_ports.py new file mode 100644 index 0000000000..0323917733 --- /dev/null +++ b/ci/test_check_ports.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Wall scope and exact-file ports: negative controls cannot exempt machine logic.""" +import importlib.util +import tempfile +import unittest +from pathlib import Path +spec = importlib.util.spec_from_file_location('check_ports', Path(__file__).with_name('check-ports.py')) +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) +class Ports(unittest.TestCase): + def fixture(self, name='rust-modules/data/src/job_ports.rs', source='fn run() { Instant::now(); }', ini=None): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + root = Path(temp.name) + path = root / name + path.parent.mkdir(parents=True) + path.write_text(source, encoding='utf-8') + (root / 'ci').mkdir() + (root / 'ci/ports.ini').write_text(ini if ini is not None else f'[{name}]\nkind = worker\nreason = Captured job transport\n', encoding='utf-8') + return root + def test_exact_job_file_is_exempt_but_neighbor_is_not(self): + root = self.fixture() + other = root / 'rust-modules/data/src/store.rs' + other.write_text('fn run() { SystemTime :: now(); }') + self.assertEqual(gate.check(root), ['rust-modules/data/src/store.rs: wall clock outside ci/ports.ini']) + def test_all_data_and_session_subdirectories_are_covered(self): + for area in ('data', 'session'): + root = self.fixture(name=f'rust-modules/{area}/src/nested/logic.rs', ini='') + self.assertTrue(gate.check(root)) + def test_test_items_and_comments_are_not_clock_reads(self): + root = self.fixture(ini='', source='// Instant::now()\nconst S: &str = "SystemTime::now()";\n#[cfg(test)] mod tests { fn f() { Instant::now(); } }') + self.assertEqual(gate.check(root), []) + def test_external_test_modules_are_classified_not_named(self): + root = self.fixture(name='rust-modules/session/src/lib.rs', ini='', source='#[cfg(test)] mod fixture;') + (root / 'rust-modules/session/src/fixture.rs').write_text('fn test() { Instant::now(); }') + self.assertEqual(gate.check(root), []) + def test_spacing_and_noncall_clock_references_are_reads(self): + for source in ('fn f() { let now = Instant :: now; }', 'fn f() { i . elapsed ( ); }'): + root = self.fixture(ini='', source=source) + self.assertTrue(gate.check(root)) + def test_directories_globs_traversal_and_absolute_paths_are_rejected(self): + for name in ('rust-modules/data/src', 'rust-modules/data/src/*.rs', '../outside.rs', + '/absolute.rs', 'rust-modules/data/src/../x.rs', 'rust-modules/data/src/./x.rs'): + root = self.fixture(ini=f'[{name}]\nkind = worker\nreason = nope\n') + with self.assertRaises(ValueError): gate.check(root) + def test_machine_logic_cannot_be_exempted(self): + for source in ('struct S { state: u8 } impl S { fn step(&mut self) { Instant::now(); } }', + 'impl Machine for S { fn run() { Instant::now(); } }', + 'fn transition() { Instant::now(); }'): + root = self.fixture(source=source) + with self.assertRaisesRegex(ValueError, 'machine logic'): gate.check(root) + def test_registered_machine_file_is_not_a_port_even_without_step_name(self): + root = self.fixture(source='struct Owner; fn event() { Instant::now(); }') + (root / 'ci/machines.ini').write_text('[data/src/job_ports.rs::Owner]\nevent = Ev\n') + with self.assertRaisesRegex(ValueError, 'machine logic'): gate.check(root) + def test_stale_path_and_clock_free_exemptions_fail(self): + root = self.fixture(source='fn run() {}') + with self.assertRaisesRegex(ValueError, 'stale port'): gate.check(root) + (root / 'rust-modules/data/src/job_ports.rs').unlink() + with self.assertRaisesRegex(ValueError, 'stale'): gate.check(root) + def test_unknown_keys_and_missing_reasons_fail(self): + for extra in ('kind = directory\nreason = bad', 'kind = worker\nreason =', + 'kind = worker\nreason = x\nscope = data/'): + root = self.fixture(ini=f'[rust-modules/data/src/job_ports.rs]\n{extra}\n') + with self.assertRaises(ValueError): gate.check(root) +if __name__ == '__main__': unittest.main() diff --git a/ci/test_ledger_ratchet.py b/ci/test_ledger_ratchet.py index bca9a1fd55..e4cd065930 100644 --- a/ci/test_ledger_ratchet.py +++ b/ci/test_ledger_ratchet.py @@ -118,6 +118,28 @@ def head(self, files): # -- the ledger counts ----------------------------------------------------------------------- + def test_ports_registry_bootstrap_is_new_but_future_added_paths_fail(self): + text = '[rust-modules/data/src/ports.rs]\nkind = worker\nreason = IO\n' + code, out = self.head({'ci/ports.ini': text}) + self.assertEqual(code, 0, out) + self.assertIn('ci/ports.ini (1)', out) + base = self.repo.git('rev-parse', 'HEAD') + self.repo.commit({'ci/ports.ini': text + '[rust-modules/session/src/ports.rs]\nkind = worker\nreason = IO\n'}) + code, out = self.repo.run(PLX_LEDGER_BASE=base) + self.assertEqual(code, 1, out) + self.assertIn('ci/ports.ini [rust-modules/session/src/ports.rs]', out) + + def test_equal_count_port_path_replacement_fails_and_removal_passes(self): + text = '[rust-modules/data/src/ports.rs]\nkind = worker\nreason = IO\n' + self.repo.commit({'ci/ports.ini': text}) + base = self.repo.git('rev-parse', 'HEAD') + self.repo.commit({'ci/ports.ini': text.replace('/data/', '/session/')}) + code, out = self.repo.run(PLX_LEDGER_BASE=base) + self.assertEqual(code, 1, out) + self.repo.commit({'ci/ports.ini': ''}) + code, out = self.repo.run(PLX_LEDGER_BASE=base) + self.assertEqual(code, 0, out) + def test_an_unchanged_tree_passes_and_names_nothing_as_new(self): code, out = self.head({}) self.assertEqual(code, 0, out) diff --git a/ci/test_machine_readonly.py b/ci/test_machine_readonly.py new file mode 100644 index 0000000000..c9776231e3 --- /dev/null +++ b/ci/test_machine_readonly.py @@ -0,0 +1,218 @@ +"""Shared state readers are accepted only after resolving their immutable payload graph.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_check_machine_writer import verdict, STRICT +import unittest +INI = STRICT + 'state_reads = immutable\n' +SOURCE = ''' +enum Event { Set } enum Fx { Changed } +struct Payload { value: String } +enum State { Idle, Active(Payload) } +impl State { + fn active(&self) -> bool { matches!(self, Self::Active(_)) } + fn payload(&self) -> Option<&Payload> { match self { Self::Idle => None, Self::Active(p) => Some(p) } } + fn consume(self) -> Self { Self::Idle } +} +struct View<'a> { state: &'a State } +struct Machine { state: State } +impl Machine { + fn new() -> Self { Self { state: State::Idle } } + fn transition(&mut self, event: Event, fx: &mut Vec) { self.state = State::Idle; } + fn read(&self) -> bool { self.state.active() } + fn view(&self) -> View<'_> { View { state: &self.state } } +} +''' +GENERIC = ''' +enum Event { Set } enum Fx { Changed } +pub trait Identity: Copy + Ord + sealed::Sealed {} +mod sealed { pub trait Sealed {} impl Sealed for u64 {} } +impl Identity for u64 {} +struct Payload { id: T } +struct Machine { state: Option> } +impl Machine { + fn new() -> Self { Self { state: None } } + fn transition(&mut self, event: Event, fx: &mut Vec) { let owned = std::mem::take(&mut self.state); self.state = owned; } + fn view(&self) -> Option<&Payload> { self.state.as_ref() } +} +''' +class Readonly(unittest.TestCase): + def test_shared_getter_view_and_owned_intrinsic_transition(self): + self.assertEqual(verdict(SOURCE, INI), []) + source = SOURCE.replace('self.state = State::Idle;', 'let old = std::mem::replace(&mut self.state, State::Idle); self.state = old.consume();') + self.assertEqual(verdict(source, INI), []) + def test_generic_identity_requires_a_closed_inert_bound(self): + self.assertEqual(verdict(GENERIC, INI), []) + for source in ( + GENERIC.replace('R: Identity', 'R: Copy + Ord'), + GENERIC.replace('mod sealed', 'pub mod sealed'), + GENERIC.replace('mod sealed', '#[rewrite] mod sealed'), + GENERIC.replace('pub trait Identity', '#[rewrite] pub trait Identity'), + GENERIC.replace('impl Sealed for u64 {}', 'impl Sealed for *mut u8 {}'), + GENERIC.replace('impl Sealed for u64 {}', 'impl Sealed for std::cell::Cell {}'), + GENERIC + 'impl sealed::Sealed for Bad {} struct Bad { value: std::cell::Cell }', + GENERIC + 'fn hidden() { make_impl!(); }', + GENERIC + 'mod child;', + ): + with self.subTest(source=source): self.assertTrue(verdict(source, INI)) + + def test_owned_data_containers_do_not_admit_mutable_authority(self): + for typ in ('std::collections::VecDeque', 'std::collections::BTreeMap', + 'Result'): + self.assertEqual(verdict(SOURCE.replace('value: String', 'value: ' + typ), INI), []) + self.assertTrue(verdict(SOURCE.replace('value: String', 'value: ' + typ.replace('String', 'std::cell::Cell').replace('PathBuf', 'PathBuf')), INI)) if 'String' in typ else None + + def test_test_only_tail_does_not_hide_a_later_registered_impl(self): + for tail in ('#[cfg(test)] mod tests { fn x() {} }', '#[cfg(test)] mod tests;'): + self.assertTrue(verdict(SOURCE + tail + ' impl Machine { fn rogue(&mut self) { self.state = State::Idle; } }', INI)) + def test_receiver_mutation_consumption_and_mutable_reference_are_not_readers(self): + for change in ('fn active(&mut self)', 'fn active(self)'): + self.assertTrue(verdict(SOURCE.replace('fn active(&self)', change), INI)) + self.assertTrue(verdict(SOURCE.replace('self.state.active()', 'self.state.consume()'), INI)) + self.assertTrue(verdict(SOURCE + 'impl Machine { fn leak(&mut self) -> &mut State { &mut self.state } }', INI)) + def test_nested_interior_authority_and_aliases_fail_closed(self): + for typ, prefix in [('Cell', 'use std::cell::Cell;'), ('Hidden', 'type Hidden = std::sync::Arc>;'), + ('Mutex', 'use std::sync::Mutex;'), ('*mut u8', ''), ('fn()', ''), + ('Unknown', ''), ('Foreign', 'use foreign::Foreign;')]: + source = prefix + SOURCE.replace('value: String', 'value: ' + typ) + self.assertTrue(verdict(source, INI), typ) + def test_alias_to_plain_data_and_standard_wrapper_is_resolved(self): + source = 'type Text = String; type Values = Vec>;' + SOURCE.replace('value: String', 'value: Values') + self.assertEqual(verdict(source, INI), []) + def test_immutable_shared_alias_cannot_launder_cell(self): + source = SOURCE + 'impl Machine { fn alias(&self) { let alias = &self.state; alias.active(); } }' + self.assertEqual(verdict(source, INI), []) + self.assertTrue(verdict('use std::cell::Cell;' + source.replace('value: String', 'value: Cell'), INI)) + def test_mutable_alias_and_hidden_macro_still_fail(self): + for code in ('let alias = &mut self.state;', 'mutate!(self, state);', 'give_away(self);', + 'self.state = State::Idle;', 'let alias = self.state;', 'replace_elsewhere(&mut self.state);'): + self.assertTrue(verdict(SOURCE + 'impl Machine { fn helper(&mut self) { ' + code + ' } }', INI), code) + def test_child_alias_payload_is_resolved_and_checked(self): + source = SOURCE.replace('struct Payload { value: String }', 'mod payload; use payload::Payload;') + child = 'fixture/src/machine/payload.rs' + self.assertEqual(verdict(source, INI, {child: 'pub struct Payload { pub value: String }'}), []) + self.assertTrue(verdict(source, INI, {child: 'pub struct Payload { pub value: std::sync::atomic::AtomicU8 }'})) + def test_standard_type_name_shadow_cannot_become_an_axiom(self): + self.assertTrue(verdict('type String = std::cell::Cell;' + SOURCE, INI)) + def test_unsafe_accessor_and_opaque_result_are_rejected(self): + self.assertTrue(verdict(SOURCE.replace('matches!(self, Self::Active(_))', 'unsafe { mutate(self); true }'), INI)) + self.assertTrue(verdict(SOURCE.replace('fn active(&self) -> bool', 'fn active(&self) -> Unknown'), INI)) +class Regression(unittest.TestCase): + def test_test_only_fields_and_impl_trait_parameters_do_not_hide_writers(self): + source = SOURCE.replace('struct Machine { state: State }', 'struct Machine { state: State, #[cfg(test)] counter: u32 }') + self.assertEqual(verdict(source, INI), []) + source += 'impl Machine { fn helper(&mut self, callback: &mut impl FnMut()) { self.state = State::Idle; } }' + self.assertTrue(verdict(source, INI)) + def test_qualified_or_shadowed_macros_cannot_rewrite_shared_places(self): + for code in ('evil::matches!(&self.state, _);', 'rewrite!(&self.state);'): + self.assertTrue(verdict(SOURCE + 'impl Machine { fn helper(&self) { ' + code + ' } }', INI)) + source = 'macro_rules! matches { ($($x:tt)*) => {} }' + SOURCE + self.assertTrue(verdict(source, INI)) + def test_shared_view_guarded_field_must_remain_immutable(self): + for field in ("state: &'a mut State", "state: *mut State"): + self.assertTrue(verdict(SOURCE.replace("state: &'a State", field), INI)) + self.assertTrue(verdict(SOURCE.replace("struct View<'a>", "#[rewrite_view] struct View<'a>"), INI)) + def test_procedural_attributes_cannot_change_proved_payload_layout(self): + source = SOURCE.replace('struct Payload', '#[rewrite_payload] struct Payload') + self.assertTrue(verdict(source, INI)) + source = SOURCE.replace('struct Payload', '#[cfg_attr(feature = "shipping", rewrite_payload)] struct Payload') + self.assertTrue(verdict(source, INI)) + def test_standard_module_and_intrinsic_shadow_fail_closed(self): + source = 'mod std { mod sync { type Arc = Hidden; } }' + SOURCE.replace('value: String', 'value: std::sync::Arc') + self.assertTrue(verdict(source, INI)) + source = 'use evil as std;' + SOURCE.replace('self.state = State::Idle;', 'std::mem::replace(&mut self.state, State::Idle);') + self.assertTrue(verdict(source, INI)) + def test_caller_generic_argument_cannot_resolve_to_another_inert_type(self): + source = SOURCE.replace('struct Payload { value: String }', 'mod wrappers; struct Hidden { v: std::cell::Cell } struct Payload { value: wrappers::Wrap }') + child = 'fixture/src/machine/wrappers.rs' + self.assertTrue(verdict(source, INI, {child: 'struct Hidden { v: u8 } pub type Wrap = Vec;'})) + def test_unrelated_state_owner_is_resolved_not_module_exempted(self): + source = SOURCE + 'struct Other { state: u8 } impl Other { fn change(&mut self) { self.state = 3; } }' + self.assertEqual(verdict(source, INI), []) + source += 'fn bad(m: &mut Machine) { m.state = State::Idle; }' + self.assertTrue(verdict(source, INI)) + def test_test_support_children_are_test_only_but_other_features_are_not(self): + child = 'fixture/src/machine/helper.rs' + module = '#[cfg(any(test, feature = "test-support"))] mod helper;' + self.assertEqual(verdict(SOURCE + module, INI, {child: 'fn poke(m: &mut super::Machine) { m.state = State::Idle; }'}), []) + self.assertTrue(verdict(SOURCE + module.replace('test-support', 'shipping'), INI, {child: 'fn poke(m: &mut super::Machine) { m.state = State::Idle; }'})) +class CompleteReaderRegression(unittest.TestCase): + def test_closed_scalar_reads_do_not_allow_mutable_aliases_or_consuming_drains(self): + source = SOURCE.replace('struct Machine { state: State }', 'struct Machine { state: State, counter: u64 }').replace('Self { state: State::Idle }', 'Self { state: State::Idle, counter: 0 }') + self.assertEqual(verdict(source, INI), []) + for body in ('let alias = &mut self.counter; unknown(alias);', + 'let alias = &mut (self.counter); unknown(alias);', + 'let ref mut alias = self.counter; unknown(alias);', + 'let nested = || { self.counter = 1; };', + 'let nested = || { self.counter += 1; };'): + with self.subTest(body=body): + self.assertTrue(verdict(source + 'impl Machine { fn rogue(&mut self) { ' + body + ' } }', INI)) + self.assertTrue(verdict(source + 'impl Machine { fn drain(self) { let value = self.state; } }', INI)) + + def test_unrelated_copy_derive_does_not_certify_a_noncopy_value(self): + source = 'enum Event { Set } enum Fx { Changed } #[derive(Copy, Clone)] struct Other { value: u8 } struct Payload { value: u8 } struct Machine { state: Payload } impl Machine { fn new() -> Self { Self { state: Payload { value: 0 } } } fn transition(&mut self, event: Event, fx: &mut Vec) {} fn rogue(&mut self) { let alias = self.state; unknown(alias); } }' + self.assertTrue(verdict(source, INI)) + +class TypeBindingRegression(unittest.TestCase): + def test_static_path_payload_is_resolved_and_conditional_path_remains_closed(self): + source = SOURCE.replace('struct Payload { value: String }', '#[path = "payload_data.rs"] mod payload; use payload::Payload;') + extra = {'fixture/src/payload_data.rs': 'pub struct Payload { pub value: String }'} + self.assertEqual(verdict(source, INI, extra), []) + extra['fixture/src/payload_data.rs'] = 'pub struct Payload { pub value: std::cell::Cell }' + self.assertTrue(verdict(source, INI, extra)) + self.assertTrue(verdict(source.replace('#[path = "payload_data.rs"]', '#[cfg_attr(feature = "shipping", path = "payload_data.rs")]'), INI, extra)) + + def test_inert_btreeset_elements_do_not_admit_authority(self): + self.assertEqual(verdict(SOURCE.replace('value: String', 'value: std::collections::BTreeSet'), INI), []) + self.assertTrue(verdict(SOURCE.replace('value: String', 'value: std::collections::BTreeSet>'), INI)) + + def test_copy_payload_getter_is_not_a_closed_generic_proof(self): + source = 'enum Event { Set } enum Fx { Changed } struct Machine { state: T } impl Machine { fn new(state: T) -> Self { Self { state } } fn transition(&mut self, event: Event, fx: &mut Vec) {} fn expose(&self) -> T { self.state } }' + self.assertTrue(verdict(source)) + self.assertTrue(verdict(source.replace('T: Copy', 'T: Copy + Ord'))) + + def test_foreign_json_and_local_replacements_are_not_name_whitelisted(self): + for prefix, typ in (('use serde_json::Value;', 'Value'), + ('mod serde_json { pub struct Value { x: std::cell::Cell } }', 'serde_json::Value'), + ('struct Value { x: *mut u8 }', 'Value')): + self.assertTrue(verdict(prefix + SOURCE.replace('value: String', 'value: ' + typ), INI)) + +class SyntaxRegression(unittest.TestCase): + def test_logical_negation_does_not_become_a_macro_certificate_hole(self): + self.assertEqual(verdict(GENERIC + 'fn pure() { if !(true) {} }', INI), []) + self.assertTrue(verdict(SOURCE + 'impl Machine { fn rogue(&mut self) { r#if!(self.state); } }', INI)) + self.assertTrue(verdict(SOURCE + 'impl Machine { fn rogue(&mut self) { unknown!(self.state); } }', INI)) + +class ConvergenceProjectionRegression(unittest.TestCase): + ARC = '''enum Event { Set } enum Fx { Changed } struct Payload { value: String } struct Machine { state: std::sync::Arc } impl Machine { fn new() -> Self { Self { state: std::sync::Arc::new(Payload { value: String::new() }) } } fn transition(&mut self, event: Event, fx: &mut Vec) {} fn same(&self, other: &Payload) -> bool { *other != *self.state } }''' + ITER = '''enum Event { Set } enum Fx { Changed } struct Payload { left: Option, right: Option } impl Payload { fn items(&self) -> impl Iterator { self.left.iter().chain(self.right.iter()) } } struct Machine { state: Payload } impl Machine { fn new() -> Self { Self { state: Payload { left: None, right: None } } } fn transition(&mut self, event: Event, fx: &mut Vec) {} fn any(&self) -> bool { self.state.items().next().is_some() } }''' + MATCH = '''enum Event { Set } enum Fx { Changed } enum State { Idle, Active { value: String, loaded: bool } } struct Machine { state: State } impl Machine { fn new() -> Self { Self { state: State::Idle } } fn transition(&mut self, event: Event, fx: &mut Vec) { match &mut self.state { State::Active { loaded: flag @ false, .. } => *flag = true, State::Active { .. } => self.state = State::Idle, State::Idle => {} } } }''' + def test_arc_comparison_is_shared_but_not_a_value_escape(self): + self.assertEqual(verdict(self.ARC, INI), []) + for body in ('unknown(*self.state); false', 'let alias = &mut self.state; unknown(alias); false'): + self.assertTrue(verdict(self.ARC.replace('*other != *self.state', body), INI)) + self.assertTrue(verdict(self.ARC.replace('value: String', 'value: std::cell::Cell'), INI)) + def test_only_direct_standard_inert_iterator_chains_are_proved(self): + self.assertEqual(verdict(self.ITER, INI), []) + for change in ('unknown(self.left.iter())', 'self.left.iter().map(callback)', 'self.left.iter_mut().chain(self.right.iter_mut())'): + self.assertTrue(verdict(self.ITER.replace('self.left.iter().chain(self.right.iter())', change), INI)) + self.assertTrue(verdict(self.ITER.replace('Option', 'Option>'), INI)) + self.assertTrue(verdict('trait Iterator {} ' + self.ITER, INI)) + def test_mutable_match_alias_is_confined_to_a_direct_bool_write(self): + self.assertEqual(verdict(self.MATCH, INI), []) + for body in ('unknown(flag)', '{ let alias = flag; unknown(alias); }', '{ let nested = || *flag = true; nested(); }', '*flag = callback()'): + self.assertTrue(verdict(self.MATCH.replace('*flag = true', body), INI)) + self.assertTrue(verdict(self.MATCH.replace('fn transition(', 'fn rogue('), INI)) + def test_declared_backend_path_and_reexport_are_resolved_without_sibling_guess(self): + source = GENERIC.replace('impl Sealed for u64 {}', 'impl Sealed for super::super::backend::LogicalRequestId {}') + extra = {'fixture/src/lib.rs': 'mod machine; mod backend;', 'fixture/src/backend.rs': '#[path = "backend_metrics.rs"] mod metrics; pub use metrics::LogicalRequestId;', 'fixture/src/backend_metrics.rs': '#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct LogicalRequestId(u64);'} + self.assertEqual(verdict(source, INI, extra), []) + self.assertTrue(verdict(source.replace('super::super::backend::', 'super::super::backend_metrics::'), INI, extra)) + extra['fixture/src/backend_metrics.rs'] = 'pub struct LogicalRequestId(std::cell::Cell);' + def test_generated_opaque_layout_is_not_a_name_or_copy_certificate(self): + source = SOURCE.replace('struct Payload { value: String }', 'mod payload; use payload::Payload;') + extra = {'fixture/src/machine/payload.rs': 'include!(concat!(env!("OUT_DIR"), "/payload.rs"));', 'fixture/src/machine/payload/guess.rs': '#[derive(Copy, Clone)] pub struct Payload { value: u64 }'} + self.assertTrue(verdict(source, INI, extra)) + self.assertTrue(verdict(source, INI, extra)) + +if __name__ == '__main__': unittest.main() diff --git a/ci/test_readonly_dependencies.py b/ci/test_readonly_dependencies.py new file mode 100644 index 0000000000..0c1340de3c --- /dev/null +++ b/ci/test_readonly_dependencies.py @@ -0,0 +1,419 @@ +"""Native/offline adversaries for the reviewed locked-source proof (no Cargo).""" +from pathlib import Path +import copy +import importlib.util +import json +import os +import shutil +import tempfile +import unittest +from unittest import mock + +import readonly_dependencies as proof + +ROOT = Path(__file__).resolve().parents[1] +ABSOLUTE = ['::', 'serde_json', '::', 'Value'] + + +class LockedJsonProofTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='locked-json-proof-') + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) / 'rust-modules' + self.certificate = proof._load_certificate() + workspace = self.certificate['workspace'] + for relative in list(workspace['manifests']) + ['Cargo.lock']: + destination = self.root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / 'rust-modules' / relative, destination) + for relative, digest in workspace['configs'].items(): + if digest is not None: + destination = self.root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / 'rust-modules' / relative, destination) + binding = workspace['owners']['plex/Cargo.toml'] + destination = self.root / binding['lib'] + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / 'rust-modules' / binding['lib'], destination) + self.source = self.root / 'plex/src/probe.rs' + self.source.write_text('pub struct Owned(pub ::serde_json::Value);\n', encoding='utf-8') + + def valid(self, tokens=ABSOLUTE, context=None): + return proof.certify(self.root, self.source, tokens, context) + + def alter(self, relative, old, new): + path = self.root / relative + text = path.read_text(encoding='utf-8') + self.assertIn(old, text) + path.write_text(text.replace(old, new, 1), encoding='utf-8') + + def cert_mutation(self, mutate): + certificate = copy.deepcopy(self.certificate) + mutate(certificate) + path = Path(self.temp.name) / 'certificate.json' + path.write_text(json.dumps(certificate), encoding='utf-8') + with mock.patch.object(proof, 'CERTIFICATE_PATH', path): + self.assertFalse(self.valid()) + + def test_current_canonical_locked_json(self): + self.assertTrue(self.valid()) + evidence = proof.provenance(self.root, self.source, ABSOLUTE) + self.assertEqual(evidence['package'], self.certificate['package']) + self.assertEqual(evidence['owner_manifest'], 'plex/Cargo.toml') + self.assertEqual(evidence['certificate_sha256'], proof.CERTIFICATE_SHA256) + + def test_separate_colon_tokens(self): + self.assertTrue(self.valid([':', ':', 'serde_json', ':', ':', 'Value'])) + + def test_root_relative_source(self): + self.assertTrue(proof.certify(self.root, 'plex/src/probe.rs', ABSOLUTE)) + + def test_current_workspace_source_and_features(self): + self.assertTrue(proof.certify(ROOT / 'rust-modules', ROOT / 'rust-modules/plex/src/plex/session.rs', ABSOLUTE)) + self.assertEqual(self.certificate['features']['definitions']['arbitrary_precision'], []) + self.assertEqual(self.certificate['grammar']['N']['arbitrary_precision'], 'alloc::string::String') + self.assertEqual(self.certificate['grammar']['Value']['enum']['Array'], ['alloc::vec::Vec']) + self.assertEqual(self.certificate['grammar']['MapImpl']['not(preserve_order)'], 'alloc::collections::BTreeMap') + + def test_offline_without_cargo_cache_or_network(self): + with mock.patch.dict(os.environ, {'PATH': '', 'CARGO_HOME': '/nonexistent', 'RUSTUP_HOME': '/nonexistent'}), \ + mock.patch('socket.create_connection', side_effect=AssertionError('network forbidden')), \ + mock.patch('subprocess.run', side_effect=AssertionError('process forbidden')): + self.assertTrue(self.valid()) + + def test_relative_external_path_rejected(self): + self.assertFalse(self.valid(['serde_json', '::', 'Value'])) + + def test_local_value_with_cell_rejected(self): + self.source.write_text('use std::cell::Cell; struct Value(Cell);', encoding='utf-8') + self.assertFalse(self.valid(['Value'])) + self.assertFalse(self.valid(['crate', '::', 'Value'])) + + def test_unknown_foreign_type_and_container_rejected(self): + self.assertFalse(self.valid(['::', 'evil', '::', 'Value'])) + self.assertFalse(self.valid(['::', 'serde_json', '::', 'Map', '<', 'String', ',', 'Value', '>'])) + + def test_callback_raw_reference_and_generic_claims_rejected(self): + for tokens in (['fn', '(', ')'], ['*', 'mut', 'Value'], ['&'] + ABSOLUTE, ABSOLUTE + ['<', 'T', '>']): + with self.subTest(tokens=tokens): self.assertFalse(self.valid(tokens)) + + def test_type_string_not_tokens_rejected(self): + self.assertFalse(self.valid('::serde_json::Value')) + + def test_same_named_local_module_rejected(self): + self.source.write_text('mod serde_json { struct Value(std::cell::Cell); }', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_same_named_local_type_alias_rejected(self): + self.source.write_text('type serde_json = evil::Authority;', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_same_named_import_alias_rejected(self): + self.source.write_text('use evil as serde_json;', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_grouped_same_named_import_rejected(self): + self.source.write_text('use evil::{serde_json};', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_extern_crate_rename_rejected(self): + self.source.write_text('extern crate evil as serde_json;', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_raw_identifier_shadow_rejected(self): + self.source.write_text('mod r#serde_json {}', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_context_does_not_grant_identity(self): + self.assertFalse(self.valid(context={'definitions': ['serde_json']})) + self.assertFalse(self.valid(context={'imports': [('serde_json', ('evil',))]})) + self.assertFalse(self.valid(context={'trust_me': True})) + self.assertTrue(self.valid(context={'definitions': ['Owned'], 'imports': [('Value', ('serde_json', 'Value'))]})) + + def test_comments_and_literals_do_not_create_shadows(self): + self.source.write_text('/* outer /* nested */ mod serde_json {} */\n// use evil as serde_json;\nconst S: &str = r###"mod serde_json {}"###;\n', encoding='utf-8') + self.assertTrue(self.valid()) + + def test_shadow_in_other_source_file_rejected(self): + (self.source.parent / 'other.rs').write_text('use evil as serde_json;', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_changed_crate_root_rejected(self): + with (self.source.parent / 'lib.rs').open('a', encoding='utf-8') as out: out.write('\nextern crate evil as serde_json;\n') + self.assertFalse(self.valid()) + + def test_wrong_source_crate_rejected_even_when_json_elsewhere(self): + other = self.root / 'machine/src/probe.rs' + other.parent.mkdir(parents=True, exist_ok=True) + other.write_text('struct Value(std::cell::Cell);', encoding='utf-8') + self.assertFalse(proof.certify(self.root, other, ABSOLUTE)) + + def test_outside_workspace_and_missing_source_rejected(self): + self.assertFalse(proof.certify(self.root, Path(self.temp.name) / 'elsewhere.rs', ABSOLUTE)) + self.assertFalse(proof.certify(self.root, self.source.with_name('absent.rs'), ABSOLUTE)) + + def test_manifest_dependency_renamed_to_evil_rejected(self): + self.alter('plex/Cargo.toml', 'serde_json = { version = "1"', 'serde_json = { package = "evil", version = "1"') + self.assertFalse(self.valid()) + + def test_canonical_package_under_wrong_alias_rejected(self): + self.alter('plex/Cargo.toml', 'serde_json = { version = "1"', 'evil = { package = "serde_json", version = "1"') + self.assertFalse(self.valid()) + + def test_manifest_comment_change_requires_review(self): + with (self.root / 'plex/Cargo.toml').open('a', encoding='utf-8') as out: out.write('\n# changed\n') + self.assertFalse(self.valid()) + + def test_path_dependency_rejected(self): + self.alter('plex/Cargo.toml', 'serde_json = { version = "1"', 'serde_json = { path = "../evil", version = "1"') + self.assertFalse(self.valid()) + + def test_git_dependency_rejected(self): + self.alter('plex/Cargo.toml', 'serde_json = { version = "1"', 'serde_json = { git = "https://example.org/evil", version = "1"') + self.assertFalse(self.valid()) + + def test_workspace_patch_rejected(self): + with (self.root / 'Cargo.toml').open('a', encoding='utf-8') as out: out.write('\n[patch.crates-io]\nserde_json = { path = "evil" }\n') + self.assertFalse(self.valid()) + + def test_cargo_source_replacement_rejected(self): + with (self.root / '.cargo/config.toml').open('a', encoding='utf-8') as out: out.write('\n[source.crates-io]\nreplace-with = "evil"\n') + self.assertFalse(self.valid()) + + def test_new_repo_config_rejected(self): + path = self.root.parent / '.cargo/config.toml' + path.parent.mkdir(exist_ok=True) + path.write_text('[source.crates-io]\nreplace-with = "evil"\n', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_checksum_change_rejected(self): + self.alter('Cargo.lock', self.certificate['package']['checksum'], '0' * 64) + self.assertFalse(self.valid()) + + def test_version_change_rejected(self): + self.alter('Cargo.lock', 'name = "serde_json"\nversion = "1.0.154"', 'name = "serde_json"\nversion = "1.0.155"') + self.assertFalse(self.valid()) + + def test_registry_source_change_rejected(self): + self.alter('Cargo.lock', 'name = "serde_json"\nversion = "1.0.154"\nsource = "' + proof.REGISTRY + '"', 'name = "serde_json"\nversion = "1.0.154"\nsource = "git+https://example.org/json"') + self.assertFalse(self.valid()) + + def test_duplicate_locked_package_rejected(self): + with (self.root / 'Cargo.lock').open('a', encoding='utf-8') as out: + out.write('\n[[package]]\nname = "serde_json"\nversion = "1.0.154"\nsource = "' + proof.REGISTRY + '"\nchecksum = "' + '0' * 64 + '"\n') + self.assertFalse(self.valid()) + with self.assertRaises(ValueError): proof._locked(self.root) + + def test_unknown_feature_rejected(self): + self.alter('plex/Cargo.toml', 'features = ["alloc", "std"]', 'features = ["alloc", "std", "mutable_value"]') + self.assertFalse(self.valid()) + + def test_preserve_order_rejected(self): + self.alter('plex/Cargo.toml', 'features = ["alloc", "std"]', 'features = ["alloc", "std", "preserve_order"]') + self.assertFalse(self.valid()) + + def test_transitive_preserve_order_lock_edge_rejected(self): + self.alter('Cargo.lock', 'name = "serde_json"\n', 'name = "serde_json"\n') + path = self.root / 'Cargo.lock' + text = path.read_text(encoding='utf-8') + at = text.index('dependencies = [', text.index('name = "serde_json"')) + len('dependencies = [') + path.write_text(text[:at] + '\n "indexmap",' + text[at:], encoding='utf-8') + self.assertFalse(self.valid()) + with self.assertRaises(ValueError): proof._locked(self.root) + + def test_certificate_mutable_field_rejected(self): + self.cert_mutation(lambda cert: cert['grammar']['Value']['enum'].update({'Cell': ['std::cell::Cell']})) + + def test_certificate_callback_field_rejected(self): + self.cert_mutation(lambda cert: cert['grammar']['Number']['fields'].update({'callback': 'fn()'})) + + def test_certificate_unknown_schema_field_rejected(self): + self.cert_mutation(lambda cert: cert.update({'authority': 'trust me'})) + + def test_certificate_feature_boundary_change_rejected(self): + self.cert_mutation(lambda cert: cert['features']['supported'].append('preserve_order')) + + def test_certificate_source_evidence_change_rejected(self): + self.cert_mutation(lambda cert: cert['source_files']['src/map.rs'].update({'sha256': '0' * 64})) + + def test_bad_archive_rejected_before_inspection(self): + archive = Path(self.temp.name) / 'evil.crate' + archive.write_bytes(b'not the locked archive') + with mock.patch.object(proof.tarfile, 'open', side_effect=AssertionError('must verify checksum first')): + with self.assertRaisesRegex(ValueError, 'BEFORE inspection'): proof.produce_certificate(self.root, archive) + + def test_workspace_inheritance_resolves_actual_package(self): + fixture = Path(self.temp.name) / 'inheritance' + (fixture / 'member/src').mkdir(parents=True) + (fixture / 'Cargo.toml').write_text('[workspace.dependencies]\nserde_json = { version = "1", features = ["alloc"] }\n', encoding='utf-8') + (fixture / 'member/Cargo.toml').write_text('[package]\nname = "member"\nedition = "2021"\n[dependencies]\nserde_json = { workspace = true, features = ["std"] }\n', encoding='utf-8') + (fixture / 'member/src/lib.rs').write_text('pub mod probe;\n', encoding='utf-8') + bindings = proof._bindings(fixture, ['member/Cargo.toml'], self.certificate['package']) + self.assertEqual(bindings['member/Cargo.toml']['dependency'][0]['features'], ['alloc', 'std']) + (fixture / 'Cargo.toml').write_text('[workspace.dependencies]\nserde_json = { package = "evil", version = "1" }\n', encoding='utf-8') + with self.assertRaisesRegex(ValueError, 'noncanonical'): proof._bindings(fixture, ['member/Cargo.toml'], self.certificate['package']) + + def test_ordinary_std_owned_data_stays_structurally_inert(self): + spec = importlib.util.spec_from_file_location('locked_json_shape_fixture', ROOT / 'ci/check-machine-shape.py') + shape = importlib.util.module_from_spec(spec) + spec.loader.exec_module(shape) + import machine_readonly + checker = machine_readonly.Proof(self.root, shape) + tokens = shape.production_tokens('std::collections::BTreeMap>>') + self.assertTrue(checker.inert(self.source, tokens)) + self.assertFalse(checker.inert(self.source, shape.production_tokens('std::cell::Cell'))) + self.assertFalse(checker.inert(self.source, shape.production_tokens('evil::OwnedMap'))) + + def test_lf_and_crlf_checkouts_have_identical_identity(self): + workspace = self.certificate['workspace'] + paths = list(workspace['manifests']) + ['Cargo.lock', workspace['owners']['plex/Cargo.toml']['lib']] + paths += [p for p, digest in workspace['configs'].items() if digest is not None] + for path in paths: + file = self.root / path + file.write_bytes(file.read_bytes().replace(b'\r\n', b'\n')) + self.assertTrue(self.valid()) + for path in paths: + file = self.root / path + file.write_bytes(file.read_bytes().replace(b'\n', b'\r\n')) + self.assertTrue(self.valid()) + + def change_root_release(self, version, manifest=True, lock=True): + path = self.root / 'Cargo.toml' + text = path.read_text(encoding='utf-8') + package = proof._table(proof._sections(text)['package']) + old, name = package['version'], package['name'] + if manifest: + path.write_text(text.replace('version = "' + old + '"', 'version = "' + version + '"', 1), encoding='utf-8') + if lock: + path = self.root / 'Cargo.lock' + old_entry = 'name = "' + name + '"\nversion = "' + old + '"' + text = path.read_text(encoding='utf-8') + self.assertEqual(text.count(old_entry), 1) + path.write_text(text.replace(old_entry, 'name = "' + name + '"\nversion = "' + version + '"'), encoding='utf-8') + + def test_coherent_local_root_release_versions_keep_source_identity(self): + for version in ('0.9.0', '0.10.0', '2.34.56'): + with self.subTest(version=version): + self.change_root_release(version) + self.assertTrue(self.valid()) + + def test_local_root_release_must_match_lock(self): + self.change_root_release('4.5.6', lock=False) + self.assertFalse(self.valid()) + + def test_local_root_lock_must_match_manifest(self): + self.change_root_release('4.5.6', manifest=False) + self.assertFalse(self.valid()) + + def test_local_root_release_is_not_dependency_or_source_approval(self): + self.change_root_release('4.5.6') + path = self.root / 'Cargo.lock' + original = path.read_text(encoding='utf-8') + package = proof._table(proof._sections((self.root / 'Cargo.toml').read_text(encoding='utf-8'))['package']) + entry = 'name = "' + package['name'] + '"\nversion = "4.5.6"' + for extra in ('\nsource = "git+https://example.org/evil"', '\nchecksum = "' + '0' * 64 + '"'): + with self.subTest(extra=extra): + path.write_text(original.replace(entry, entry + extra), encoding='utf-8') + self.assertFalse(self.valid()) + path.write_text(original, encoding='utf-8') + path = self.root / 'Cargo.toml' + path.write_text(path.read_text(encoding='utf-8') + '\n# unreviewed metadata\n', encoding='utf-8') + self.assertFalse(self.valid()) + + def test_local_root_prerelease_and_noncanonical_versions_fail_closed(self): + originals = {p: (self.root / p).read_bytes() for p in ('Cargo.toml', 'Cargo.lock')} + for version in ('01.2.3', '1.2.3-rogue', '1.2.3+rogue', '1.2'): + with self.subTest(version=version): + for p, data in originals.items(): + (self.root / p).write_bytes(data) + self.change_root_release(version) + self.assertFalse(self.valid()) + + def test_bare_carriage_return_is_not_checkout_normalization(self): + for relative in ('Cargo.toml', 'Cargo.lock'): + path = self.root / relative + original = path.read_bytes() + path.write_bytes(original.replace(b'\r\n', b'\n').replace(b'\n', b'\r')) + self.assertFalse(self.valid()) + path.write_bytes(original) + + def test_local_root_duplicate_lock_identity_fails_closed(self): + self.change_root_release('4.5.6') + name = proof._table(proof._sections((self.root / 'Cargo.toml').read_text(encoding='utf-8'))['package'])['name'] + path = self.root / 'Cargo.lock' + path.write_text(path.read_text(encoding='utf-8') + '\n[[package]]\nname = "' + name + '"\nversion = "4.5.6"\n', encoding='utf-8') + with self.assertRaisesRegex(ValueError, 'ambiguous/nonlocal'): + proof._workspace_hashes(self.root, proof._manifest_paths(self.root)) + self.assertFalse(self.valid()) + + def test_local_root_version_cannot_participate_in_resolution(self): + name = proof._table(proof._sections((self.root / 'Cargo.toml').read_text(encoding='utf-8'))['package'])['name'] + path = self.root / 'Cargo.lock' + text = path.read_text(encoding='utf-8') + path.write_text(text.replace('dependencies = [', 'dependencies = [\n "' + name + '",', 1), encoding='utf-8') + with self.assertRaisesRegex(ValueError, 'participates in dependency resolution'): + proof._workspace_hashes(self.root, proof._manifest_paths(self.root)) + self.assertFalse(self.valid()) + + def test_local_root_release_does_not_unpin_dependency_version(self): + self.change_root_release('4.5.6') + path = self.root / 'Cargo.lock' + original = path.read_text(encoding='utf-8') + old = 'name = "serde_json"\nversion = "1.0.154"' + self.assertIn(old, original) + path.write_text(original.replace(old, 'name = "serde_json"\nversion = "1.0.155"'), encoding='utf-8') + self.assertFalse(self.valid()) + + +class SourceClosureTests(unittest.TestCase): + def setUp(self): + certificate = proof._load_certificate() + self.sources = {path: '' for path in proof.SOURCE_PATHS} + for declaration in certificate['declarations'].values(): + self.sources[declaration['path']] += ' '.join(declaration['tokens']) + '\n' + self.sources['src/value/mod.rs'] += 'use alloc::string::String; use alloc::vec::Vec; pub use crate::map::Map; pub use crate::number::Number;' + self.sources['src/number.rs'] += '#[cfg(feature = "arbitrary_precision")] use alloc::string::{String, ToString};' + self.sources['src/map.rs'] += '#[cfg(not(feature = "preserve_order"))] use alloc::collections::{btree_map, BTreeMap};' + self.sources['src/lib.rs'] = 'extern crate alloc; pub use crate::value::{from_value, to_value, Map, Number, Value};' + self.sources['Cargo.toml'] = '[features]\n' + '\n'.join(key + ' = ' + json.dumps(value) for key, value in certificate['features']['definitions'].items()) + + def test_complete_recursive_source_grammar(self): + declarations, features = proof._review(self.sources) + self.assertEqual(len(declarations), 7) + self.assertIn('arbitrary_precision', features) + self.assertIn('preserve_order', features) + + def test_value_interior_cell_source_rejected(self): + self.sources['src/value/mod.rs'] = self.sources['src/value/mod.rs'].replace('Bool ( bool )', 'Bool ( Cell < bool > )') + with self.assertRaisesRegex(ValueError, 'structural closure'): proof._review(self.sources) + + def test_number_callback_source_rejected(self): + self.sources['src/number.rs'] = self.sources['src/number.rs'].replace('n : N ,', 'n : N , callback : fn ( ) ,') + with self.assertRaisesRegex(ValueError, 'structural closure'): proof._review(self.sources) + + def test_arbitrary_precision_interior_cell_source_rejected(self): + self.sources['src/number.rs'] = self.sources['src/number.rs'].replace('type N = String ;', 'type N = Cell < String > ;') + with self.assertRaisesRegex(ValueError, 'structural closure'): proof._review(self.sources) + + def test_unresolved_foreign_container_source_rejected(self): + self.sources['src/map.rs'] = self.sources['src/map.rs'].replace('= BTreeMap < K , V >', '= EvilMap < K , V >') + with self.assertRaisesRegex(ValueError, 'structural closure'): proof._review(self.sources) + + def test_container_import_identity_source_rejected(self): + self.sources['src/value/mod.rs'] = self.sources['src/value/mod.rs'].replace('use alloc::vec::Vec;', 'use evil::Vec;') + with self.assertRaisesRegex(ValueError, 'canonical source import'): proof._review(self.sources) + + def test_unknown_source_feature_rejected(self): + self.sources['Cargo.toml'] += '\nmutable_values = []\n' + with self.assertRaisesRegex(ValueError, 'unknown source feature'): proof._review(self.sources) + + def test_crate_root_macro_or_alias_expansion_not_assumed(self): + self.assertTrue(proof._root_modules_only('pub mod http; mod plex;')) + self.assertFalse(proof._root_modules_only('inject_authority!(); pub mod plex;')) + self.assertFalse(proof._root_modules_only('include!("generated.rs");')) + self.assertFalse(proof._root_modules_only('extern crate evil as serde_json;')) + self.assertFalse(proof._root_modules_only('pub mod serde_json;')) + + +if __name__ == '__main__': + unittest.main() diff --git a/ci/test_readonly_generated.py b/ci/test_readonly_generated.py new file mode 100644 index 0000000000..47b6979f9f --- /dev/null +++ b/ci/test_readonly_generated.py @@ -0,0 +1,229 @@ +"""Source-backed generated data adversaries, native/offline with no Cargo cache.""" +from pathlib import Path +import importlib.util +import json +import shutil +import tempfile +import unittest +import readonly_generated as generated +import readonly_dependencies as dependency +from machine_readonly import Proof, imports + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('generated_gate', ROOT / 'ci/check-machine-shape.py') +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) + + +class GeneratedProofTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='generated-data-proof-') + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) / 'rust-modules' + certificate = json.loads(generated.CERTIFICATE_PATH.read_text(encoding='utf-8')) + paths = set(certificate['manifests']) | set(certificate['sources']) | {'Cargo.lock'} + paths |= {p for p, value in certificate['configs'].items() if value is not None} + paths.add('../locales/languages.json') + for relative in paths: + out = self.root / relative + out.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / 'rust-modules' / relative, out) + self.module = self.root / 'platform/src/i18n/mod.rs' + self.catalogue = self.root.parent / 'locales/languages.json' + + def evidence(self): + return generated.provenance(self.root, self.module) + + def test_actual_pipeline_and_closed_layout(self): + evidence = self.evidence() + self.assertIsNotNone(evidence) + self.assertEqual(evidence['variants']['Preference'][0], 'System') + self.assertEqual(evidence['variants']['Language'][-1], 'Pseudo') + proof = Proof(self.root, gate) + for name in ('Preference', 'Language'): + self.assertTrue(proof.inert(self.module, [name])) + self.assertTrue(proof.copy_value(self.module, [name])) + for name in ('LocaleContext', 'OnceLock'): + self.assertFalse(proof.inert(self.module, [name])) + + def test_machine_macro_source_layout(self): + module = self.root / 'machine/src/machine.rs' + proof = Proof(self.root, gate) + for name in ('StoreOrd', 'RequestId', 'InstanceId', 'MachineId'): + self.assertTrue(proof.inert(module, [name]), name) + original = module.read_text(encoding='utf-8') + module.write_text(original.replace('pub u32', 'pub std::cell::Cell', 1), encoding='utf-8') + self.assertFalse(Proof(self.root, gate).inert(module, ['StoreOrd'])) + + def test_additional_language_remains_data_only(self): + entries = json.loads(self.catalogue.read_text(encoding='utf-8')) + entries.append(dict(tag='sv', native_name='Svenska', region='sv-SE', script='Latn', plurals=['one', 'other'], row=entries[-1]['row'] + 1)) + self.catalogue.write_text(json.dumps(entries), encoding='utf-8') + self.assertIn('Sv', self.evidence()['variants']['Preference']) + entries[-1]['native_name'] = 'text "); Cell { // escaped data' + self.catalogue.write_text(json.dumps(entries), encoding='utf-8') + self.assertIsNotNone(self.evidence()) # Rust Debug-escaped string, never a source slot. + + def test_wrong_module_and_same_name_are_not_certified(self): + wrong = self.root / 'platform/src/wrong.rs' + wrong.write_text('pub enum Preference { Payload(std::cell::Cell) }', encoding='utf-8') + self.assertIsNone(generated.provenance(self.root, wrong)) + self.assertFalse(Proof(self.root, gate).inert(wrong, ['Preference'])) + consumer = self.root / 'session/src/shadow.rs' + consumer.parent.mkdir(parents=True, exist_ok=True) + consumer.write_text('#[path="../../platform/src/i18n/mod.rs"] mod language;', encoding='utf-8') + self.assertFalse(Proof(self.root, gate).inert(consumer, ['language', ':', ':', 'Preference'])) + + def test_all_producer_namespace_and_feature_mutations_fail_closed(self): + mutations = [ + ('platform/src/i18n/mod.rs', '/languages.rs', '/other.rs'), + ('platform/src/i18n/mod.rs', 'include!', '#[cfg(feature="rogue")] include!'), + ('platform/src/i18n/mod.rs', 'include!', 'pub enum Preference { Payload(std::cell::Cell) } include!'), + ('platform/src/lib.rs', 'pub mod i18n;', '#[path="other.rs"] pub mod i18n;'), + ('platform/build.rs', 'catalog::build', 'other::build'), + ('platform/build_support/catalog.rs', 'System,\\n', 'System(std::cell::Cell),\\n'), + ('platform/build_support/catalog.rs', 's.variant', 'callback()'), + ('platform/build_support/catalog.rs', 'write("languages.rs"', 'write("rogue.rs"'), + ('build_support/install_identities.rs', 'pub fn emit', '#[cfg(feature="rogue")] pub fn emit'), + ('platform/Cargo.toml', '[package]', '[features]\nrogue = []\n[package]'), + ] + for relative, old, new in mutations: + with self.subTest(path=relative, mutation=new): + path = self.root / relative + original = path.read_text(encoding='utf-8') + self.assertIn(old, original) + path.write_text(original.replace(old, new, 1), encoding='utf-8') + self.assertIsNone(self.evidence()) + path.write_text(original, encoding='utf-8') + self.assertIsNotNone(self.evidence()) + + def test_catalogue_injection_schema_and_identifiers_fail_closed(self): + original = self.catalogue.read_text(encoding='utf-8') + cases = [('tag', 'en), Payload(Cell), Evil('), ('tag', 'r#en'), ('tag', 'qps'), + ('tag', 'EN'), ('variant', 'Cell'), ('row', True), ('row', 1000), + ('script', 'Latn); callback()'), ('plurals', ['other', 'other']), + ('excluded_regions', ['BR', 'BR']), ('native_name', '\x00')] + for key, value in cases: + with self.subTest(key=key, value=value): + entries = json.loads(original) + entries[0][key] = value + self.catalogue.write_text(json.dumps(entries), encoding='utf-8') + self.assertIsNone(self.evidence()) + self.catalogue.write_text('[{"tag":"en","tag":"es"}]', encoding='utf-8') + self.assertIsNone(self.evidence()) + + def test_conditional_field_attribute_is_opaque(self): + self.module = self.root / 'platform/src/rogue.rs' + self.module.write_text('enum Holder { Value(#[cfg_attr(feature="rogue", payload)] u32) }', encoding='utf-8') + self.assertFalse(Proof(self.root, gate).inert(self.module, ['Holder'])) + + def test_grouped_self_import_binds_module_not_self(self): + self.assertEqual(imports(['plx_plex', ':', ':', 'probe', ':', ':', '{', 'self', '}']), [('probe', ('plx_plex', 'probe'))]) + + def test_consumer_namespace_shadow_is_not_canonical(self): + path = self.root / 'session/src/shadow.rs' + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('mod plx_platform { pub mod i18n { pub enum Preference { Payload(std::cell::Cell) } } }', encoding='utf-8') + self.assertFalse(Proof(self.root, gate).inert(path, ['plx_platform', ':', ':', 'i18n', ':', ':', 'Preference'])) + self.assertEqual(imports(['plx_plex', ':', ':', 'probe', ':', ':', '{', 'self', '}']), [('probe', ('plx_plex', 'probe'))]) + + def change_root_release(self, version, manifest=True, lock=True): + path = self.root / 'Cargo.toml' + text = path.read_text(encoding='utf-8') + package = dependency._table(dependency._sections(text)['package']) + old, name = package['version'], package['name'] + if manifest: + path.write_text(text.replace('version = "' + old + '"', 'version = "' + version + '"', 1), encoding='utf-8') + if lock: + path = self.root / 'Cargo.lock' + old_entry = 'name = "' + name + '"\nversion = "' + old + '"' + text = path.read_text(encoding='utf-8') + self.assertEqual(text.count(old_entry), 1) + path.write_text(text.replace(old_entry, 'name = "' + name + '"\nversion = "' + version + '"'), encoding='utf-8') + + def test_coherent_local_root_release_versions_keep_source_identity(self): + for version in ('0.9.0', '0.10.0', '2.34.56'): + with self.subTest(version=version): + self.change_root_release(version) + self.assertTrue(self.evidence() is not None) + + def test_local_root_release_must_match_lock(self): + self.change_root_release('4.5.6', lock=False) + self.assertFalse(self.evidence() is not None) + + def test_local_root_lock_must_match_manifest(self): + self.change_root_release('4.5.6', manifest=False) + self.assertFalse(self.evidence() is not None) + + def test_local_root_release_is_not_dependency_or_source_approval(self): + self.change_root_release('4.5.6') + path = self.root / 'Cargo.lock' + original = path.read_text(encoding='utf-8') + package = dependency._table(dependency._sections((self.root / 'Cargo.toml').read_text(encoding='utf-8'))['package']) + entry = 'name = "' + package['name'] + '"\nversion = "4.5.6"' + for extra in ('\nsource = "git+https://example.org/evil"', '\nchecksum = "' + '0' * 64 + '"'): + with self.subTest(extra=extra): + path.write_text(original.replace(entry, entry + extra), encoding='utf-8') + self.assertFalse(self.evidence() is not None) + path.write_text(original, encoding='utf-8') + path = self.root / 'Cargo.toml' + path.write_text(path.read_text(encoding='utf-8') + '\n# unreviewed metadata\n', encoding='utf-8') + self.assertFalse(self.evidence() is not None) + + def test_local_root_prerelease_and_noncanonical_versions_fail_closed(self): + originals = {p: (self.root / p).read_bytes() for p in ('Cargo.toml', 'Cargo.lock')} + for version in ('01.2.3', '1.2.3-rogue', '1.2.3+rogue', '1.2'): + with self.subTest(version=version): + for p, data in originals.items(): + (self.root / p).write_bytes(data) + self.change_root_release(version) + self.assertFalse(self.evidence() is not None) + + def test_bare_carriage_return_is_not_checkout_normalization(self): + for relative in ('Cargo.toml', 'Cargo.lock'): + path = self.root / relative + original = path.read_bytes() + path.write_bytes(original.replace(b'\r\n', b'\n').replace(b'\n', b'\r')) + self.assertFalse(self.evidence() is not None) + path.write_bytes(original) + + def test_local_root_duplicate_lock_identity_fails_closed(self): + self.change_root_release('4.5.6') + name = dependency._table(dependency._sections((self.root / 'Cargo.toml').read_text(encoding='utf-8'))['package'])['name'] + path = self.root / 'Cargo.lock' + path.write_text(path.read_text(encoding='utf-8') + '\n[[package]]\nname = "' + name + '"\nversion = "4.5.6"\n', encoding='utf-8') + with self.assertRaisesRegex(ValueError, 'ambiguous/nonlocal'): + dependency._workspace_hashes(self.root, dependency._manifest_paths(self.root)) + self.assertFalse(self.evidence() is not None) + + def test_local_root_version_cannot_participate_in_resolution(self): + name = dependency._table(dependency._sections((self.root / 'Cargo.toml').read_text(encoding='utf-8'))['package'])['name'] + path = self.root / 'Cargo.lock' + text = path.read_text(encoding='utf-8') + path.write_text(text.replace('dependencies = [', 'dependencies = [\n "' + name + '",', 1), encoding='utf-8') + with self.assertRaisesRegex(ValueError, 'participates in dependency resolution'): + dependency._workspace_hashes(self.root, dependency._manifest_paths(self.root)) + self.assertFalse(self.evidence() is not None) + + def test_local_root_release_does_not_unpin_dependency_version(self): + self.change_root_release('4.5.6') + path = self.root / 'Cargo.lock' + original = path.read_text(encoding='utf-8') + old = 'name = "serde_json"\nversion = "1.0.154"' + self.assertIn(old, original) + path.write_text(original.replace(old, 'name = "serde_json"\nversion = "1.0.155"'), encoding='utf-8') + self.assertFalse(self.evidence() is not None) + + def test_lf_and_crlf_producer_inputs_keep_identity(self): + certificate = json.loads(generated.CERTIFICATE_PATH.read_text(encoding='utf-8')) + paths = set(certificate['sources']) | set(certificate['manifests']) | {'Cargo.lock'} + paths |= {p for p, digest in certificate['configs'].items() if digest is not None} + for ending in (b'\n', b'\r\n'): + for relative in paths: + path = self.root / relative + path.write_bytes(path.read_bytes().replace(b'\r\n', b'\n').replace(b'\n', ending)) + self.assertIsNotNone(self.evidence()) + + +if __name__ == '__main__': + unittest.main() diff --git a/ci/test_step_scope.py b/ci/test_step_scope.py new file mode 100644 index 0000000000..d957eec13b --- /dev/null +++ b/ci/test_step_scope.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Pins actual Sans-IO runtime boundary sites; behavior is exercised by Rust negative tests.""" +import unittest +from pathlib import Path +ROOT = Path(__file__).resolve().parent.parent +class StepBoundaries(unittest.TestCase): + def source(self, path): return (ROOT / 'rust-modules' / path).read_text(encoding='utf-8') + def test_screen_scope_covers_only_the_step_not_drain_or_instruments(self): + source = self.source('ui/src/dispatch.rs') + start = source.index('let handled = plx_base::diag::spans::span("dstep"') + end = source.index('drop(fx);', start) + window = source[start:end] + self.assertEqual(window.count('StepScope::enter()'), 1) + self.assertLess(window.index('StepScope::enter()'), window.index('inst.screen.step(')) + self.assertTrue(window.rstrip().endswith('});')) + self.assertEqual(source.count('StepScope::enter()'), 1) + def test_all_actual_io_funnels_have_step_assertions(self): + for path, operations in [ + ('base/src/task.rs', ('task::try_spawn', 'task::beside_with')), + ('base/src/storage_worker.rs', ('storage_worker::submit', 'storage_worker::submit_retained', + 'storage_worker::pump_retained', 'storage_worker::Executor::submit', 'storage_worker::Writer::submit')), + ('base/src/clock.rs', ('clock::vclock_ms', 'clock::vclock_us', 'clock::wall_now')), + ('src/app/clock.rs', ('app::clock::now', 'app::clock::unix_ms', 'app::clock::today'))]: + source = self.source(path) + for operation in operations: + self.assertIn('assert_io_allowed("' + operation + '")', source) + source = self.source('base/src/task/blocking.rs') + body = source[source.index('pub fn assert_may_block('):] + self.assertLess(body.index('assert_io_allowed('), body.index('ALLOWED.with(')) + def test_store_guards_never_wrap_job_drain(self): + source = self.source('data/src/stores/mod.rs') + start = source.index('pub fn take_jobs(') + end = source.index('pub fn metadata_pump(', start) + self.assertNotIn('StepScope', source[start:end]) + self.assertGreaterEqual(source.count('StepScope::enter()'), 20) + def test_scope_has_no_release_tls_and_cannot_cross_threads(self): + source = self.source('base/src/step.rs') + self.assertIn('#[cfg(any(test, feature = "test-support"))]\nthread_local!', source) + self.assertIn('PhantomData>', source) + self.assertIn('impl Drop for StepScope', source) +if __name__ == '__main__': unittest.main() diff --git a/ci/test_transition_arguments.py b/ci/test_transition_arguments.py new file mode 100644 index 0000000000..59c3a83ec2 --- /dev/null +++ b/ci/test_transition_arguments.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Complete transition arguments, including the actual ten-machine HUD bypass.""" +import configparser +import importlib.util +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parent.parent +spec = importlib.util.spec_from_file_location('shape', ROOT / 'ci/check-machine-shape.py') +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) +REGISTRY = configparser.ConfigParser(interpolation=None) +REGISTRY.read(ROOT / 'ci/machines.ini') +ENTRIES = [s for s in REGISTRY if s != 'DEFAULT' and not s.startswith('module ')] +COUNTS = {'synthetic': 0, 'accepted': 0, 'rejected': 0} +FACTS = { + 'play-uri/src/uriprobe.rs::UriProbe': ('now_ms', 'u64', 'monotonic_ms_u64'), + 'session/src/auth/owner.rs::SessionMachine': ('tick_ms', 'u32', 'monotonic_ms_u32'), + 'playback-contract/src/state.rs::BackendState': ('capabilities', 'Option', 'playback_capabilities'), +} +CAPS = 'pub struct Capabilities { ' + ''.join('pub ' + n + ': bool,' for n in ( + 'progressive_uri', 'hls_uri', 'packet_feed', 'pause', 'seek', 'audio_track', + 'subtitle_track', 'audio_off', 'subtitle_off')) + ' }' + + +def fixture(section, extra='', prefix='', aux=None, modify=None, ini_change=None, caps=CAPS): + file, name = section.split('::') + entry = dict(REGISTRY[section]) + event, effect = entry['event'], entry['effect'] + fact = FACTS.get(section) + if fact: + entry['aux_facts'] = fact[0] + ':' + fact[2] + arguments = 'event: ' + event + if fact: + arguments += ', ' + fact[0] + ': ' + (fact[1] if aux is None else aux) + if effect != 'none': + arguments += ', effects: &mut Vec<' + effect + '>' + if extra: + arguments += ', ' + extra + source = '#![deny(clippy::wildcard_enum_match_arm)]\n' + prefix + if fact and fact[2] == 'playback_capabilities': + source += 'use crate::Capabilities;\n' + source += 'enum ' + event + ' { Input }\n' + if effect != 'none': + source += 'enum ' + effect + ' { Output }\n' + source += 'enum RawState { Idle } type RawAlias = RawState; struct Context { next: RawState }\n' + source += 'struct ' + name + ' { ' + entry['state_field'] + ': RawState }\n' + source += 'impl ' + name + ' {\n' + if entry['constructor'].isupper(): + source += 'const ' + entry['constructor'] + ': Self = Self { ' + entry['state_field'] + ': RawState::Idle };\n' + else: + source += 'fn ' + entry['constructor'] + '() -> Self { Self { ' + entry['state_field'] + ': RawState::Idle } }\n' + source += 'fn transition(&mut self, ' + arguments + ') { self.' + entry['state_field'] + ' = RawState::Idle; }\n}' + if modify: + source = modify(source) + if ini_change: + ini_change(entry) + with tempfile.TemporaryDirectory() as temp: + modules = Path(temp) / 'rust-modules' + path = modules / file + path.parent.mkdir(parents=True) + path.write_text(source, encoding='utf-8') + if fact and fact[2] == 'playback_capabilities': + (modules / 'playback-contract/Cargo.toml').write_text('[package]\nname = "plx_playback_contract"\nversion = "0.0.0"\n', encoding='utf-8') + (modules / 'playback-contract/src/lib.rs').write_text(caps, encoding='utf-8') + registry = configparser.ConfigParser(interpolation=None) + registry[section] = entry + registry['module ' + file] = {'wildcard_enum_match_arm': 'deny'} + ini = Path(temp) / 'machines.ini' + with ini.open('w', encoding='utf-8') as stream: + registry.write(stream) + problems = gate.check(modules, ini)[0] + COUNTS['synthetic'] += 1 + COUNTS['rejected' if problems else 'accepted'] += 1 + return problems + + +class TransitionArguments(unittest.TestCase): + @classmethod + def tearDownClass(cls): + print('transition-argument fixture verdicts:', COUNTS) + + def test_actual_hud_full_gate_raw_state_repro(self): + target = (ROOT / 'rust-modules/data/src/hudpacks.rs').resolve() + old = Path.read_text + original = old(target, encoding='utf-8') + source = original.replace( + 'fn transition(&mut self, ev: HudEvent, fx: &mut Vec) -> Handled {', + 'fn transition(&mut self, ev: HudEvent, fx: &mut Vec, next: Op) -> Handled { self.op = next;', 1 + ).replace('self.transition(ev, fx) }', 'self.transition(ev, fx, Op::Idle) }', 1) + self.assertIn('self.op = next;', source) + self.assertIn('self.transition(ev, fx, Op::Idle)', source) + def read(path, *args, **kwargs): + return source if path.resolve() == target else old(path, *args, **kwargs) + with patch.object(Path, 'read_text', read): + problems, report = gate.check(ROOT / 'rust-modules', ROOT / 'ci/machines.ini') + self.assertEqual(sum(line.startswith('machine ') for line in report), 10) + self.assertTrue(any('unbound transition argument' in p for p in problems), problems) + + def test_every_cohort_machine_rejects_unbound_arguments(self): + self.assertEqual(len(ENTRIES), 10) + for section in ENTRIES: + for extra in ('next: RawState', 'renamed: RawAlias', 'ctx: Context', 'extra: u64', + 'next: &RawState', 'next: &mut RawState', 'cb: fn(RawState)', + 'cb: impl FnOnce()', 'next: *mut RawState', 'bag: Option'): + with self.subTest(machine=section, extra=extra): + self.assertTrue(fixture(section, extra), (section, extra)) + + def test_synthetic_canonical_signatures(self): + for section in ENTRIES: + with self.subTest(machine=section): + self.assertEqual(fixture(section), []) + + def test_duplicate_event_or_effect(self): + for section in ENTRIES: + entry = REGISTRY[section] + for extra in ('another: ' + entry['event'], 'event: ' + entry['event']): + with self.subTest(machine=section, extra=extra): + self.assertTrue(fixture(section, extra)) + if entry['effect'] != 'none': + self.assertTrue(fixture(section, 'other: &mut Vec<' + entry['effect'] + '>')) + + def test_closed_fact_slots(self): + for section, (name, typ, kind) in FACTS.items(): + for bad in ('RawState', 'RawAlias', '&' + typ, '&mut ' + typ, 'Context', 'fn()', 'T'): + with self.subTest(machine=section, typ=bad): + self.assertTrue(fixture(section, aux=bad)) + self.assertTrue(fixture(section, name + ': ' + typ)) + self.assertTrue(fixture(section, ini_change=lambda e: e.pop('aux_facts'))) + for value in (name + ':unknown', name + ':RawState', 'renamed:' + kind, + name + ':' + kind + ',' + name + ':' + kind, 'event:' + kind, + 'effects:' + kind): + with self.subTest(machine=section, declaration=value): + self.assertTrue(fixture(section, ini_change=lambda e: e.update(aux_facts=value))) + + def test_unknown_auxiliary_declarations_fail_closed(self): + section = 'data/src/hudpacks.rs::HudStore' + for value in ('ctx:Context', 'next:RawState', 'next:monotonic_ms_u32'): + self.assertTrue(fixture(section, 'next: RawState', ini_change=lambda e: e.update(aux_facts=value))) + + def test_primitive_shadow_and_alias_are_not_clock_facts(self): + for section, (name, typ, kind) in FACTS.items(): + if typ not in ('u32', 'u64'): + continue + for prefix in ('type ' + typ + ' = RawState;', 'use crate::RawState as ' + typ + ';', + 'mod shadow { pub type ' + typ + ' = super::RawState; } use shadow::*;'): + with self.subTest(machine=section, prefix=prefix): + self.assertTrue(fixture(section, prefix=prefix)) + self.assertTrue(fixture(section, prefix='type Clock = ' + typ + ';', aux='Clock')) + self.assertTrue(fixture(section, modify=lambda s: s.replace('fn transition(', 'fn transition('))) + + def test_fact_layout_and_canonical_primitive_identity(self): + for section, (name, typ, _) in FACTS.items(): + if typ in ('u32', 'u64'): + self.assertEqual(fixture(section, aux='::core::primitive::' + typ), []) + self.assertEqual(fixture(section, aux='std::primitive::' + typ), []) + self.assertTrue(fixture(section, aux='core::primitive::' + typ, + prefix='mod core { pub mod primitive { pub type ' + typ + ' = super::super::RawState; } }')) + self.assertTrue(fixture(section, modify=lambda s: s.replace('impl ', 'impl<' + typ + '> ', 1))) + section = 'playback-contract/src/state.rs::BackendState' + for caps in (CAPS.replace('pause: bool', 'pause: u64'), CAPS.replace('pause: bool,', ''), + CAPS.replace('pause: bool', 'pause: Context'), + CAPS + ' type bool = u8;', 'pub type Capabilities = RawState;'): + with self.subTest(caps=caps): + self.assertTrue(fixture(section, caps=caps)) + self.assertTrue(fixture(section, prefix='type Capabilities = RawState;')) + self.assertTrue(fixture(section, prefix='type Hidden = &mut Option;', aux='Hidden')) + self.assertTrue(fixture(section, prefix='type Hidden = &mut Capabilities;', aux='Option')) + self.assertTrue(fixture(section, prefix='type Option = &mut T;')) + + def test_uri_wildcard_replacements_are_complete_and_equivalent(self): + import re + source = (ROOT / 'rust-modules/play-uri/src/uriprobe.rs').read_text(encoding='utf-8') + protocol = (ROOT / 'rust-modules/play-uri/src/uri_protocol.rs').read_text(encoding='utf-8') + enum = protocol.split('enum Method {', 1)[1].split('}', 1)[0] + variants = set(re.findall(r'\b(\w+)\s*,', enum)) + inner = source.split('call {} ok", match method {', 1)[1].split('})))', 1)[0] + fallback = inner.split('Method::Subscribe => "subscribe",', 1)[1].split('=> "play"', 1)[0] + inner_variants = set(re.findall(r'Method::(\w+)', fallback)) + self.assertEqual(inner_variants, variants - {'Load', 'Subscribe'}) + outer = source.split('Work::ServiceAfterVideo { method, ok, message } => {', 1)[1].split('if self.media_id.is_none() && !denied', 1)[0] + tail = outer.rsplit('=> {}', 1)[0].rsplit('})));', 1)[1] + outer_variants = set(re.findall(r'Method::(\w+)', tail)) + self.assertEqual(outer_variants, {'Register', 'Load', 'Subscribe', 'Play', 'Unload', 'Dropped', 'Other'}) + unconditional = {'NotifyForeground', 'Pause', 'Seek', 'SelectTrack', 'SetSubtitleEnable', 'SetWindowId'} + for method in variants: + for denied in (False, True): + for confirmed in (False, True): + for has_events in (False, True): + guarded = method in {'Load', 'Subscribe', 'Play'} and (denied or confirmed and not has_events) + earlier = method in unconditional or guarded + self.assertEqual(not earlier, method in outer_variants and not earlier) + old = 'load' if method == 'Load' else 'subscribe' if method == 'Subscribe' else 'play' + new = 'load' if method == 'Load' else 'subscribe' if method == 'Subscribe' else 'play' if method in inner_variants else None + self.assertEqual(old, new) + + def test_actual_session_tick_and_entire_cohort(self): + source = (ROOT / 'rust-modules/session/src/auth/owner.rs').read_text(encoding='utf-8') + self.assertIn('tick_ms: u32', source) + problems, report = gate.check(ROOT / 'rust-modules', ROOT / 'ci/machines.ini') + self.assertEqual(sum(line.startswith('machine ') for line in report), 10) + self.assertEqual(problems, []) + + +if __name__ == '__main__': + unittest.main() diff --git a/ci/test_verdict_data_captured_inputs_source_oracle.py b/ci/test_verdict_data_captured_inputs_source_oracle.py new file mode 100644 index 0000000000..39d4b7551b --- /dev/null +++ b/ci/test_verdict_data_captured_inputs_source_oracle.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Source-only regressions for the captured-input oracle; no Rust build required.""" +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import unittest + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location( + "captured_inputs_oracle", + ROOT / "docs/design-briefs/verdict-data-captured-inputs-source-oracle.py") +ORACLE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ORACLE) +READ = "plx_plex::plex::session::server_ids()" + + +def adversarial(count): + return "#[cfg(test)]#[" + "]#[" * count + "\nfn live() { " + READ + "; }" + + +def probe(count, timeout=2): + start = time.perf_counter() + try: + result = subprocess.run( + [sys.executable, str(Path(__file__).resolve()), "--adversarial", str(count)], + capture_output=True, text=True, timeout=timeout, check=True) + except subprocess.TimeoutExpired: + return {"repetitions": count, "timeout_seconds": timeout, + "elapsed_seconds": time.perf_counter() - start, "status": "timeout"} + return {"repetitions": count, "timeout_seconds": timeout, + "elapsed_seconds": time.perf_counter() - start, "status": "pass", + "child": json.loads(result.stdout)} + + +class ProductionSourceTests(unittest.TestCase): + def reads(self, source): + return len(list(ORACLE.AMBIENT.finditer(ORACLE.production(source)))) + + def test_test_items_do_not_mask_later_production(self): + for item in ("fn helper()", "mod checks", "impl Helper"): + with self.subTest(item=item): + source = f"fn before() {{ {READ}; }} #[cfg(test)] {item} {{ {READ}; }} fn after() {{ {READ}; }}" + self.assertEqual(self.reads(source), 2) + + def test_repeated_nested_attributes_and_visibility(self): + for attrs in ( + '#[cfg(test)] #[allow(dead_code)] #[doc = "[}]"]', + '#[allow(clippy::lint(reason = "nested [ ]"))] /* comment */ #[cfg(test)]', + '#[cfg(any(test, feature = "test-support"))] #[allow(unused)]', + '#[cfg(test)]' + '#[allow(dead_code)]' * 1000, + ): + with self.subTest(attrs=attrs[:100]): + self.assertEqual(self.reads(f'{attrs} pub(crate) fn helper() {{ {READ}; }} fn live() {{ {READ}; }}'), 1) + + def test_balanced_body_ignores_strings_characters_and_nested_comments(self): + source = r'''#[cfg(test)] mod checks { + const RAW: &str = r###"} /* #[cfg(test)]"###; + const TEXT: &str = "} \" {"; + const CHAR: char = '}'; + /* } /* nested } */ still } */ + fn helper() { if true { READ; } } + } + fn live() { READ; }'''.replace("READ", READ) + self.assertEqual(self.reads(source), 1) + + def test_comments_and_literals_do_not_forge_test_ownership(self): + for prefix in ( + '// #[cfg(test)] mod fake {}\n', + '/* #[cfg(test)] /* nested */ mod fake {} */', + 'const EXAMPLE: &str = r#"#[cfg(test)] mod fake {}"#;', + 'const EXAMPLE: &str = "#[cfg(test)] mod fake {}";', + ): + with self.subTest(prefix=prefix): + self.assertEqual(self.reads(prefix + f" fn live() {{ {READ}; }}"), 1) + + def test_non_test_cfg_and_unrelated_items_keep_real_reads(self): + for prefix in ('#[cfg(not(test))]', '#[cfg(any(test, feature="real"))]', + '#[cfg(test)] use example;'): + with self.subTest(prefix=prefix): + self.assertEqual(self.reads(prefix + f" fn live() {{ {READ}; }}"), 1) + + def test_external_test_module_does_not_mask_following_item(self): + self.assertEqual(self.reads(f"#[cfg(test)] mod checks; fn live() {{ {READ}; }}"), 1) + + def test_unterminated_test_body_fails_closed(self): + self.assertEqual(self.reads(f"#[cfg(test)] fn broken() {{ {READ};"), 1) + + def test_all_ambient_families_still_detected(self): + for call in (READ, "plx_plex::plex::client_for()", "crate::stores::tape::active()"): + with self.subTest(call=call): + self.assertEqual(self.reads(f"#[cfg(test)] mod checks {{}} fn live() {{ {call}; }}"), 1) + + def test_original_oracle_and_real_read_mutation(self): + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(ORACLE.main(), 0) + with tempfile.TemporaryDirectory(prefix="captured-oracle-") as temp: + root = Path(temp) + for family in ORACLE.FAMILIES: + dest = root / "rust-modules/data/src" / family + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text((ROOT / "rust-modules/data/src" / family).read_text(encoding="utf-8"), encoding="utf-8") + for family in ("search", "metadata", "pms", "viewstate"): + dest = root / "ci/allow/globals" / f"data-{family}.txt" + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text("") + with (root / "rust-modules/data/src/search.rs").open("a", encoding="utf-8") as out: + out.write(f"\n#[cfg(test)] mod oracle_checks {{}}\nfn real_ambient_read() {{ {READ}; }}\n") + old_root = ORACLE.ROOT + try: + ORACLE.ROOT = root + output = io.StringIO() + with contextlib.redirect_stdout(output): + self.assertEqual(ORACLE.main(), 1) + self.assertIn("search.rs: ambient machine read:", output.getvalue()) + finally: + ORACLE.ROOT = old_root + + def test_long_malformed_attributes_finish_and_keep_real_read(self): + for count in (32, 20000, 80000): + with self.subTest(count=count): + result = probe(count) + self.assertEqual(result["status"], "pass", result) + self.assertEqual(result["child"]["ambient_reads"], 1) + + +if __name__ == "__main__": + if len(sys.argv) == 3 and sys.argv[1] == "--adversarial": + source = adversarial(int(sys.argv[2])) + start = time.perf_counter() + result = ORACLE.production(source) + print(json.dumps({"characters": len(source), "production_seconds": time.perf_counter() - start, + "ambient_reads": len(list(ORACLE.AMBIENT.finditer(result)))})) + elif len(sys.argv) == 2 and sys.argv[1] == "--timings": + print(json.dumps([probe(count) for count in (32, 20000, 80000)])) + else: + unittest.main() diff --git a/docs/design-briefs/verdict-data-captured-inputs-audit.json b/docs/design-briefs/verdict-data-captured-inputs-audit.json new file mode 100644 index 0000000000..3f92d81626 --- /dev/null +++ b/docs/design-briefs/verdict-data-captured-inputs-audit.json @@ -0,0 +1,137 @@ +{ + "schema": 1, + "status": "SOURCE COMPLETE / TEST READY: runtime and full gates pending parent serialization", + "authority": "C:/Users/gleb_/Developer/plx-native", + "targets": [ + ".", + ".worktrees/sans_io-6a4bcd6a42", + ".worktrees/verdict-integration" + ], + "families": { + "Search": { + "retired_globals": 14, + "remaining_globals": 0 + }, + "Metadata": { + "retired_globals": 5, + "remaining_globals": 0 + }, + "PMS": { + "retired_globals": 3, + "remaining_globals": 0 + }, + "ViewState": { + "retired_globals": 2, + "remaining_globals": 0 + } + }, + "aggregate_counts": [ + { + "tree": ".", + "counts": { + "workers": 4, + "globals": 19, + "forks": 62, + "fxlanes": 11 + } + }, + { + "tree": ".worktrees/sans_io-6a4bcd6a42/", + "counts": { + "workers": 4, + "globals": 19, + "forks": 62, + "fxlanes": 11 + } + }, + { + "tree": ".worktrees/verdict-integration/", + "counts": { + "workers": 4, + "globals": 19, + "forks": 62, + "fxlanes": 11 + } + } + ], + "shared_sync": { + "symbols_per_mirror": 27, + "owned_symbol_copies": 54, + "root_owned_hunks_mirrored": true, + "person_owned_symbols_preserved": true, + "session_capture": "ONE retained StoreSessionCapture plus ONE existing ClientKeys; capture before command/pump/publication; separate captured tape-active and controlled policy; explicit account tenure" + }, + "integration_preserved_differences": { + "rust-modules/data/src/pms.rs": "pre-existing clearLogo and secondary-genre fields/projection/tests", + "rust-modules/data/src/metadata.rs": "pre-existing clearLogo/NowPlaying UI additions and credit documentation", + "rust-modules/screens/src/library/deferred_tests.rs": "pre-existing closing_sources_menu_does_not_replace_a_newer_library_choice regression" + }, + "verification": { + "pre_fix_source_oracle": "FAIL: ambient roster/generation/session facts determined behavior despite captured keys", + "four_family_python_oracle": "PASS in all 3 trees", + "person_python_oracle": "7/7 PASS in all 3 trees", + "tree_sitter_source_syntax": "28 owned ROOT Rust files plus 12 mirror main/shared files: no parse errors", + "rust_compilation": "NOT RUN: reserved for parent", + "runtime_replay_clippy_full_gates": "NOT RUN: reserved for parent", + "staging_commits": "NONE by this lane", + "new_rust_regression_cases": 8 + }, + "protected": { + "historical_audit": "docs/design-briefs/verdict-runtime-correction-sync-32e-audit.json untouched", + "source_bootstrap_replay_fixtures_v5_v6_goldens": "untouched; Detail.source_credit is serde(skip, default)", + "historical_ui_fp": "5612583773909772043", + "v6_ui_fp": "14623229906352324261", + "unix_ms": "no field introduced", + "other_user_changes": "preserved; no reset/stash/clean/staging/commit" + }, + "logical_path_count": 39, + "logical_paths": [ + "ci/allow/globals/data-metadata.txt", + "ci/allow/globals/data-pms.txt", + "ci/allow/globals/data-search.txt", + "ci/allow/globals/data-viewstate.txt", + "docs/design-briefs/verdict-data-captured-inputs-audit.json", + "docs/design-briefs/verdict-data-captured-inputs-source-oracle.py", + "docs/sans-io-guide.md", + "docs/sans-io.md", + "rust-modules/data/src/captured_store_fixture.rs", + "rust-modules/data/src/lib.rs", + "rust-modules/data/src/metadata.rs", + "rust-modules/data/src/metadata/captured_inputs_tests.rs", + "rust-modules/data/src/metadata_detail_mailbox_tests.rs", + "rust-modules/data/src/metadata_watch_state_tests.rs", + "rust-modules/data/src/pms.rs", + "rust-modules/data/src/pms/captured_inputs_tests.rs", + "rust-modules/data/src/search.rs", + "rust-modules/data/src/search/captured_inputs_tests.rs", + "rust-modules/data/src/search/recents.rs", + "rust-modules/data/src/search/scope.rs", + "rust-modules/data/src/search_account_scope_tests.rs", + "rust-modules/data/src/search_job_tests.rs", + "rust-modules/data/src/search_paging_tests.rs", + "rust-modules/data/src/search_query_debounce_tests.rs", + "rust-modules/data/src/search_test_support.rs", + "rust-modules/data/src/stores/metadata.rs", + "rust-modules/data/src/stores/mod.rs", + "rust-modules/data/src/stores/search.rs", + "rust-modules/data/src/stores/viewreconcile_parents_tests.rs", + "rust-modules/data/src/stores/viewreconcile_tests.rs", + "rust-modules/data/src/viewstate.rs", + "rust-modules/data/src/viewstate_captured_inputs_tests.rs", + "rust-modules/plex/src/plex/client_keys.rs", + "rust-modules/plex/src/plex/mod.rs", + "rust-modules/screens/src/library/deferred_tests.rs", + "rust-modules/src/app/bridge.rs", + "rust-modules/src/app/search_owned_tests.rs", + "rust-modules/src/app/search_publication_tests.rs", + "tests/test_harness.py" + ], + "source_oracle_commands": [ + "python docs/design-briefs/verdict-data-captured-inputs-source-oracle.py", + "python docs/design-briefs/verdict-person-captured-inputs-source-oracle.py", + "python .worktrees/sans_io-6a4bcd6a42/docs/design-briefs/verdict-data-captured-inputs-source-oracle.py", + "python .worktrees/sans_io-6a4bcd6a42/docs/design-briefs/verdict-person-captured-inputs-source-oracle.py", + "python .worktrees/verdict-integration/docs/design-briefs/verdict-data-captured-inputs-source-oracle.py", + "python .worktrees/verdict-integration/docs/design-briefs/verdict-person-captured-inputs-source-oracle.py" + ] +} diff --git a/docs/design-briefs/verdict-data-captured-inputs-source-oracle.py b/docs/design-briefs/verdict-data-captured-inputs-source-oracle.py new file mode 100644 index 0000000000..f4de341d62 --- /dev/null +++ b/docs/design-briefs/verdict-data-captured-inputs-source-oracle.py @@ -0,0 +1,76 @@ +"""Source-only oracle for the four remaining data captured-input families (not Rust gates).""" +from pathlib import Path +import re +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "ci")) +from rust_test_modules import group_ends, lex + +ROOT = Path(__file__).resolve().parents[2] +FAMILIES = ("search.rs", "search/scope.rs", "search/recents.rs", "pms.rs", "metadata.rs", "viewstate.rs") +AMBIENT = re.compile(r"(?:plx_plex::plex::(?:session::)?(?:server_ids|server_roster_gen|server_facts_gen|server_facts|client_for|current_server|current_snapshot|current_gen|peek|peek_settled|visible_generation|current_profile_key|tenure)|crate::stores::tape::active)\s*\(") + +def production(text): + # Reuse the Rust lexer so comments/literals cannot forge attributes or braces. + tokens = lex(text) + ends = group_ends(tokens) + test_cfgs = (lex('cfg(test)'), lex('cfg(any(test, feature = "test-support"))')) + kept, i, size = [], 0, len(tokens) + while i < size: + start, test_only = i, False + # Each balanced attribute is consumed once, including nested token groups. + while (i + 1 < size and tokens[i] == ('code', '#') + and tokens[i + 1] == ('code', '[') and i + 1 in ends): + end = ends[i + 1] + test_only |= tokens[i + 2:end] in test_cfgs + i = end + 1 + item = i + if item < size and tokens[item] == ('code', 'pub'): + item += 1 + if item < size and tokens[item] == ('code', '(') and item in ends: + item = ends[item] + 1 + if test_only and item < size and tokens[item] in ( + ('code', 'fn'), ('code', 'mod'), ('code', 'impl')): + end = item + 1 + while end < size and tokens[end] not in (('code', '{'), ('code', ';')): + if tokens[end] in (('code', '('), ('code', '[')): + if end not in ends: + break + end = ends[end] + 1 + else: + end += 1 + if end < size and tokens[end] == ('code', ';'): + i = end + 1 + continue + if end < size and tokens[end] == ('code', '{') and end in ends: + i = ends[end] + 1 + continue + # Malformed items fail closed; keep their reads and never rescan a header. + i = end + if i == start: + i += 1 + kept.extend(tokens[start:i]) + # Keep path punctuation adjacent for AMBIENT; literals remain opaque separators. + return ''.join(value if kind == 'code' else '""' for kind, value in kept) + +def main(): + failures = [] + for family in FAMILIES: + text = production((ROOT / "rust-modules/data/src" / family).read_text(encoding="utf-8")) + for match in AMBIENT.finditer(text): + failures.append(f"{family}: ambient machine read: {match.group()}") + for family in ("search", "metadata", "pms", "viewstate"): + ledger = ROOT / "ci/allow/globals" / f"data-{family}.txt" + if any(line.strip() and not line.lstrip().startswith("#") for line in ledger.read_text().splitlines()): + failures.append(f"{family}: retired ledger still has entries") + metadata = (ROOT / "rust-modules/data/src/metadata.rs").read_text(encoding="utf-8") + if not re.search(r"#\[serde\(skip, default\)\]\s*pub source_credit: String", metadata): + failures.append("metadata: captured presentation credit must not enter recorded Detail JSON") + if failures: + print("\n".join(failures)) + return 1 + print("PASS: Search/Metadata/PMS/ViewState captured-input source boundary; runtime gates not run") + return 0 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/design-briefs/verdict-person-captured-inputs-audit.json b/docs/design-briefs/verdict-person-captured-inputs-audit.json new file mode 100644 index 0000000000..4dd568229e --- /dev/null +++ b/docs/design-briefs/verdict-person-captured-inputs-audit.json @@ -0,0 +1,644 @@ +{ + "schema": 1, + "status": "Historical checkpoint, superseded by verdict-person-final-boundary-audit.json; previous unchanged PersonPort/refused claims do not describe the final authority boundary.", + "as_of": "2026-11-11T19:23:03.315Z", + "root": "C:/Users/gleb_/Developer/plx-native", + "checkout_heads": { + "root": "379b239ab489929c0bda9c5d13ab1c7b28e03afe", + "integration": "da0c4f4f09e22b9a37ab59e61c111c6d15dd4e7c", + "sans_io": "d06ed4f5ca0bd43e68df4c030d80cb6b76d28ce6" + }, + "prior_sync_audit": "docs/design-briefs/verdict-runtime-correction-sync-32e-audit.json", + "root_cause": "Person sources used ambient registered slots while admission used captured keys. Open/pump/roster synchronization also consulted ambient session-watch/session, tape/control, provider and dev seeds, allowing one captured pass to be redirected. Stable pumps copied roster/page/session strings.", + "contract": "PersonInput borrows the ONE complete ClientKeys roster, settled Arc, visible generation, controlled/provider decisions and dev seeds. Host capture precedes Open and each pump. All registered slots survive missing keys; origin appended once. Stable logical pumps compare borrowed instance/grant and identity strings. Only admitted jobs copy request data. Fixed refusal settles same turn. Inputless Open/pump refuse explicitly; Close/Reset/view edits remain independent.", + "scope": [ + "rust-modules/data/src/person.rs", + "rust-modules/data/src/person/captured_inputs_tests.rs", + "rust-modules/data/src/stores/person.rs", + "rust-modules/data/src/stores/mod.rs", + "rust-modules/data/src/stores/held_keys_tests.rs", + "rust-modules/data/src/search_account_scope_tests.rs", + "rust-modules/src/app/bridge.rs", + "rust-modules/src/app/adapters/stores.rs", + "rust-modules/screens/src/person.rs", + "rust-modules/screens/src/person/cards_harness.rs", + "rust-modules/screens/src/filmography.rs", + "ci/allow/globals/data-person.txt", + "tests/test_harness.py", + "docs/sans-io.md", + "docs/sans-io-guide.md", + "docs/design-briefs/verdict-person-captured-inputs-source-oracle.py", + "docs/design-briefs/verdict-person-captured-inputs-audit.json" + ], + "shared_regions": { + "rust-modules/data/src/stores/mod.rs": [ + "Stores::person_run", + "Stores::person_pump" + ], + "rust-modules/src/app/bridge.rs": [ + "PersonCapture and impl", + "Bridge.person_capture field/default", + "Bridge::person_run", + "Bridge::person_pump" + ], + "rust-modules/src/app/adapters/stores.rs": [ + "tests::person_requests", + "tests::a_person_job_whose_client_is_still_held_is_admitted_and_answered_once" + ], + "rust-modules/data/src/search_account_scope_tests.rs": [ + "Person caller suffix only; ROOT edit supplied by other data lane" + ], + "rust-modules/screens/src/person.rs": [ + "test-host run_person_fixture helper and existing Person Open fixture calls only" + ], + "tests/test_harness.py": [ + "PINNED_LEDGER_TOTALS.globals only" + ] + }, + "counts": { + "before": { + "person_globals": 11, + "workers": 4, + "globals": 54, + "forks": 62, + "fxlanes": 11 + }, + "person_only_checkpoint": { + "person_globals": 0, + "workers": 4, + "globals": 43, + "forks": 62, + "fxlanes": 11 + }, + "current_combined_globals": 19, + "other_lane_delta": "Remaining data lane independently retires 24 sites (43 -> 19); it owns combined repinning/mirroring." + }, + "verification": { + "reproducer_before_fix": { + "code": 1, + "summary": [ + "FAIL: test_inputless_machine_pump_is_refused (__main__.PersonCapturedInputs)\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='server_ids(')\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='server_roster_gen(')\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='session::peek')\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='session_watch')\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='tape::active(')\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='tape::credits(')\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='devtrig::read(')\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='discover::person_profile_refused(')\r", + "FAIL: test_machine_has_no_ambient_inputs (__main__.PersonCapturedInputs) (spelling='discover::person_credits_refused(')\r", + "FAIL: test_roster_uses_registered_slots_not_only_active_keys (__main__.PersonCapturedInputs)\r", + "Ran 3 tests in 0.004s\r", + "FAILED (failures=11)\r" + ] + }, + "final_person_source_cases": [ + { + "base": "", + "exit": 0, + "summary": "......\r\n----------------------------------------------------------------------\r\nRan 6 tests in 0.006s\r\n\r\nOK" + }, + { + "base": ".worktrees/sans_io-6a4bcd6a42/", + "exit": 0, + "summary": "......\r\n----------------------------------------------------------------------\r\nRan 6 tests in 0.006s\r\n\r\nOK" + }, + { + "base": ".worktrees/verdict-integration/", + "exit": 0, + "summary": "......\r\n----------------------------------------------------------------------\r\nRan 6 tests in 0.006s\r\n\r\nOK" + } + ], + "full_7_case_oracle": "PASS: all 7 native source cases in ROOT and both mirrors, including actual ledger/pin equality after combined 19-global repin.", + "regressions": { + "file": "rust-modules/data/src/person/captured_inputs_tests.rs", + "count": 10, + "added_before_fix": 8, + "added_followup": 2, + "cases": [ + "captured roster and settled identity beat conflicting ambient values", + "origin missing/unregistered and duplicate appears once", + "same capture stable generation/revision/source and identity string pointers", + "roster-only/no-client slots retained; token refresh preserves loaded page", + "suspended session defers jobs and supplied recovery emits", + "controlled mode ignores session edges and uses supplied credit seed", + "fixed provider refusal settled in same turn with no job/retry", + "profile edge stale answer cannot clear new claim", + "retained borrowed publication immune to another owner pump", + "new grant rebuilds while live retoken keeps loaded shelves" + ] + }, + "unchanged_existing_assertions": true, + "unchanged_typed_contracts": [ + { + "symbol": "PersonReq", + "unchanged": true + }, + { + "symbol": "PersonPort", + "unchanged": true + }, + { + "symbol": "emit", + "unchanged": true + }, + { + "symbol": "finish_person_job", + "unchanged": true + }, + { + "symbol": "person_addr", + "unchanged": true + }, + { + "symbol": "land", + "unchanged": true + }, + { + "symbol": "refused", + "unchanged": true + }, + { + "symbol": "apply_landing", + "unchanged": true + } + ], + "syntax": [ + { + "path": "rust-modules/data/src/person.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/data/src/person/captured_inputs_tests.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/data/src/stores/person.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/data/src/stores/mod.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/data/src/stores/held_keys_tests.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/data/src/search_account_scope_tests.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/src/app/bridge.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/src/app/adapters/stores.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/screens/src/person.rs", + "backend": "tree-sitter", + "findings": [ + { + "line": 1034, + "column": 14, + "endLine": 1034, + "endColumn": 16, + "snippet": "\"\"", + "missing": false + } + ] + }, + { + "path": "rust-modules/screens/src/person/cards_harness.rs", + "backend": "tree-sitter", + "findings": [] + }, + { + "path": "rust-modules/screens/src/filmography.rs", + "backend": "tree-sitter", + "findings": [] + } + ], + "syntax_note": "Only existing c\"\" literal tree-sitter finding in unchanged Screens draw_shelf_heading; no task syntax findings.", + "diff_check": "PASS ROOT, sans_io, verdict-integration task scope", + "staged_or_committed": false, + "final_full_oracles": [ + { + "base": "", + "exit": 0, + "summary": [ + "Ran 7 tests in 0.167s\r", + "OK\r" + ] + }, + { + "base": ".worktrees/sans_io-6a4bcd6a42/", + "exit": 0, + "summary": [ + "Ran 7 tests in 0.171s\r", + "OK\r" + ] + }, + { + "base": ".worktrees/verdict-integration/", + "exit": 0, + "summary": [ + "Ran 7 tests in 0.172s\r", + "OK\r" + ] + } + ], + "rust_runtime": "Not run by this lane: parent reserved WSL Cargo target lease." + }, + "mirrors": [ + { + "base": ".worktrees/sans_io-6a4bcd6a42/", + "checks": [ + { + "path": "rust-modules/data/src/person.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/data/src/person/captured_inputs_tests.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/data/src/stores/person.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/data/src/stores/held_keys_tests.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/screens/src/person/cards_harness.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/screens/src/filmography.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/src/app/adapters/stores.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/data/src/stores/mod.rs", + "scope": "person_run", + "equal": true + }, + { + "path": "rust-modules/data/src/stores/mod.rs", + "scope": "person_pump", + "equal": true + }, + { + "path": "rust-modules/src/app/bridge.rs", + "scope": "PersonCapture", + "equal": true + }, + { + "path": "rust-modules/src/app/bridge.rs", + "scope": "person_run", + "equal": true + }, + { + "path": "rust-modules/src/app/bridge.rs", + "scope": "person_pump", + "equal": true + }, + { + "path": "rust-modules/screens/src/person.rs", + "scope": "run_person_fixture", + "equal": true + } + ] + }, + { + "base": ".worktrees/verdict-integration/", + "checks": [ + { + "path": "rust-modules/data/src/person.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/data/src/person/captured_inputs_tests.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/data/src/stores/person.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/data/src/stores/held_keys_tests.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/screens/src/person/cards_harness.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/screens/src/filmography.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/src/app/adapters/stores.rs", + "scope": "file", + "equal": true + }, + { + "path": "rust-modules/data/src/stores/mod.rs", + "scope": "person_run", + "equal": true + }, + { + "path": "rust-modules/data/src/stores/mod.rs", + "scope": "person_pump", + "equal": true + }, + { + "path": "rust-modules/src/app/bridge.rs", + "scope": "PersonCapture", + "equal": true + }, + { + "path": "rust-modules/src/app/bridge.rs", + "scope": "person_run", + "equal": true + }, + { + "path": "rust-modules/src/app/bridge.rs", + "scope": "person_pump", + "equal": true + }, + { + "path": "rust-modules/screens/src/person.rs", + "scope": "run_person_fixture", + "equal": true + } + ] + } + ], + "mirroring_policy": "Exclusive files copied only after exact baseline equality guard. Shared source files updated by named symbols/field hunks; Root census/UI compatibility, prior sync audits, .gitignore/tmp/.empryo and other lane work retained. StoreSessionCapture is the other data lane shared helper: provisional versions mirrored for Person, final tenure/household refresh belongs to its owner.", + "runtime_test_ready": { + "data_package": "plx_data", + "data_filters": [ + "person::", + "stores::held_keys_tests::person_holds_its_shelves_for_that_person_only", + "forty_one_servers_are_asked_by_search_and_by_a_person_page" + ], + "screens_package": "plx_screens", + "screens_filters": [ + "person::", + "filmography::" + ], + "app_filters": [ + "app::person_admission_tests::", + "app::person_lifecycle_tests::", + "app::store_admission_tests::", + "app::viewstate_directory_policy_tests::" + ], + "not_run": [ + "Rust/Cargo/Clippy", + "stage/build/replay/full gates" + ], + "reason": "Parent explicitly retained WSL Cargo target lease; Cargo availability is not a blocker." + }, + "source_refs": [ + { + "path": "rust-modules/data/src/person.rs", + "line": 337 + }, + { + "path": "rust-modules/data/src/person.rs", + "line": 777 + }, + { + "path": "rust-modules/data/src/person.rs", + "line": 1230 + }, + { + "path": "rust-modules/src/app/bridge.rs", + "line": 1791 + } + ], + "observed_blob_oids": [ + { + "path": "rust-modules/data/src/person.rs", + "git_blob": "f674b6ec25382779facbfb714098cadec4a9517a" + }, + { + "path": "rust-modules/data/src/person/captured_inputs_tests.rs", + "git_blob": "02da4e3c5e0494872383a2fc57c60b1e8e98a389" + }, + { + "path": "rust-modules/data/src/stores/person.rs", + "git_blob": "cca472b159513911426be8653de3f6b687b1d70c" + }, + { + "path": "rust-modules/data/src/stores/mod.rs", + "git_blob": "3f4d5a865e2be9345146c900539478b349d47f6b" + }, + { + "path": "rust-modules/data/src/stores/held_keys_tests.rs", + "git_blob": "0f85adffd4143a02654a223b866a7bb3149f176a" + }, + { + "path": "rust-modules/data/src/search_account_scope_tests.rs", + "git_blob": "87fb0b80239f0dfef7ab214b856f242fc4d796ef" + }, + { + "path": "rust-modules/src/app/bridge.rs", + "git_blob": "8633bb1ec8d9d79e21205fd213270cc5f11038a9" + }, + { + "path": "rust-modules/src/app/adapters/stores.rs", + "git_blob": "a5fc9b1883e12902e7a28f596a01228665551203" + }, + { + "path": "rust-modules/screens/src/person.rs", + "git_blob": "f3367a90836f534be2e225b223ecfcf23514f798" + }, + { + "path": "rust-modules/screens/src/person/cards_harness.rs", + "git_blob": "53638eb3d14f49ff235f8483835dd7288119e878" + }, + { + "path": "rust-modules/screens/src/filmography.rs", + "git_blob": "8f36d02d6c124374007497d53f4b314a62b2e249" + }, + { + "path": "ci/allow/globals/data-person.txt", + "git_blob": "c797378c1256f4f936b59ff1214f6b94ef682e30" + }, + { + "path": "tests/test_harness.py", + "git_blob": "2f8373fe6c3af7df62d040f3f6f975bb433e36a8" + }, + { + "path": "docs/sans-io.md", + "git_blob": "6bec9d787c192d11a9e54cc8981d5b490d73d495" + }, + { + "path": "docs/sans-io-guide.md", + "git_blob": "595d3a8a1a6b783d6ecf293e4cc9eef15329992f" + }, + { + "path": "docs/design-briefs/verdict-person-captured-inputs-source-oracle.py", + "git_blob": "777d26a82bdec930b83793ae287403bc95cc7f44" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/data/src/person.rs", + "git_blob": "f674b6ec25382779facbfb714098cadec4a9517a" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/data/src/person/captured_inputs_tests.rs", + "git_blob": "02da4e3c5e0494872383a2fc57c60b1e8e98a389" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/data/src/stores/person.rs", + "git_blob": "cca472b159513911426be8653de3f6b687b1d70c" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/data/src/stores/mod.rs", + "git_blob": "20e5426ac88cab6a5e5297a78e93631f18562a42" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/data/src/stores/held_keys_tests.rs", + "git_blob": "0f85adffd4143a02654a223b866a7bb3149f176a" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/data/src/search_account_scope_tests.rs", + "git_blob": "87fb0b80239f0dfef7ab214b856f242fc4d796ef" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/src/app/bridge.rs", + "git_blob": "7a4f56b07789a3b2c757b31740e3d4af3841f313" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/src/app/adapters/stores.rs", + "git_blob": "a5fc9b1883e12902e7a28f596a01228665551203" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/screens/src/person.rs", + "git_blob": "074e78eb88bd46903695b031f4a93bcf4192fada" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/screens/src/person/cards_harness.rs", + "git_blob": "53638eb3d14f49ff235f8483835dd7288119e878" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/rust-modules/screens/src/filmography.rs", + "git_blob": "8f36d02d6c124374007497d53f4b314a62b2e249" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/ci/allow/globals/data-person.txt", + "git_blob": "c797378c1256f4f936b59ff1214f6b94ef682e30" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/tests/test_harness.py", + "git_blob": "2f8373fe6c3af7df62d040f3f6f975bb433e36a8" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/docs/sans-io.md", + "git_blob": "3de256453599fd1206c3a85a3dfeaba319652fe1" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/docs/sans-io-guide.md", + "git_blob": "e204ca23036c0bb2f99e072aaa757d3087bbbbf7" + }, + { + "path": ".worktrees/sans_io-6a4bcd6a42/docs/design-briefs/verdict-person-captured-inputs-source-oracle.py", + "git_blob": "777d26a82bdec930b83793ae287403bc95cc7f44" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/data/src/person.rs", + "git_blob": "f674b6ec25382779facbfb714098cadec4a9517a" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/data/src/person/captured_inputs_tests.rs", + "git_blob": "02da4e3c5e0494872383a2fc57c60b1e8e98a389" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/data/src/stores/person.rs", + "git_blob": "cca472b159513911426be8653de3f6b687b1d70c" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/data/src/stores/mod.rs", + "git_blob": "20e5426ac88cab6a5e5297a78e93631f18562a42" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/data/src/stores/held_keys_tests.rs", + "git_blob": "0f85adffd4143a02654a223b866a7bb3149f176a" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/data/src/search_account_scope_tests.rs", + "git_blob": "87fb0b80239f0dfef7ab214b856f242fc4d796ef" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/src/app/bridge.rs", + "git_blob": "ca39bd84e89a1176343e2028a38ae0b82441bec7" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/src/app/adapters/stores.rs", + "git_blob": "a5fc9b1883e12902e7a28f596a01228665551203" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/screens/src/person.rs", + "git_blob": "074e78eb88bd46903695b031f4a93bcf4192fada" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/screens/src/person/cards_harness.rs", + "git_blob": "53638eb3d14f49ff235f8483835dd7288119e878" + }, + { + "path": ".worktrees/verdict-integration/rust-modules/screens/src/filmography.rs", + "git_blob": "8f36d02d6c124374007497d53f4b314a62b2e249" + }, + { + "path": ".worktrees/verdict-integration/ci/allow/globals/data-person.txt", + "git_blob": "c797378c1256f4f936b59ff1214f6b94ef682e30" + }, + { + "path": ".worktrees/verdict-integration/tests/test_harness.py", + "git_blob": "2f8373fe6c3af7df62d040f3f6f975bb433e36a8" + }, + { + "path": ".worktrees/verdict-integration/docs/sans-io.md", + "git_blob": "8668b374e7c13a4f32cc6f7e7e00ca600bb6bea1" + }, + { + "path": ".worktrees/verdict-integration/docs/sans-io-guide.md", + "git_blob": "e204ca23036c0bb2f99e072aaa757d3087bbbbf7" + }, + { + "path": ".worktrees/verdict-integration/docs/design-briefs/verdict-person-captured-inputs-source-oracle.py", + "git_blob": "777d26a82bdec930b83793ae287403bc95cc7f44" + } + ], + "final_verification_at": "2026-11-11T19:25:56.489Z", + "observed_blob_oids_at": "2026-11-11T19:26:55.058Z" +} diff --git a/docs/design-briefs/verdict-person-captured-inputs-source-oracle.py b/docs/design-briefs/verdict-person-captured-inputs-source-oracle.py new file mode 100644 index 0000000000..3fa2d76a3c --- /dev/null +++ b/docs/design-briefs/verdict-person-captured-inputs-source-oracle.py @@ -0,0 +1,86 @@ +"""Person machine boundary source oracle; no Rust execution or shared target lease.""" +from pathlib import Path +import re +import unittest +ROOT = Path(__file__).resolve().parents[2] +class PersonCapturedInputs(unittest.TestCase): + def test_machine_has_no_ambient_inputs(self): + text = (ROOT / 'rust-modules/data/src/person.rs').read_text(encoding='utf-8').split('#[cfg(test)]\nmod tests')[0] + for spelling in ('server_ids(', 'server_roster_gen(', 'session::peek', 'session_watch', 'tape::active(', 'tape::credits(', 'devtrig::read(', 'discover::person_profile_refused(', 'discover::person_credits_refused('): + with self.subTest(spelling=spelling): + self.assertFalse(spelling in text, spelling) + def test_roster_uses_registered_slots_not_only_active_keys(self): + text = (ROOT / 'rust-modules/data/src/person.rs').read_text(encoding='utf-8') + self.assertTrue('keys.slots().chain(std::iter::once(origin))' in text) + self.assertTrue('input.keys.roster_gen()' in text) + def test_inputless_machine_pump_is_refused(self): + text = (ROOT / 'rust-modules/data/src/stores/person.rs').read_text(encoding='utf-8') + self.assertFalse('&ClientKeys::default()' in text) + self.assertTrue('Person pump requires captured inputs' in text) + def test_host_capture_precedes_open_and_pump(self): + text = (ROOT / 'rust-modules/src/app/bridge.rs').read_text(encoding='utf-8') + for name in ('person_run_from', 'person_pump_with_seed_read'): + body = text.split('fn ' + name + '(', 1)[1].split('\n }', 1)[0] + self.assertEqual(body.count('self.capture_store_session()'), 1) + self.assertLess(body.index('self.capture_store_session()'), body.index('refill_client_keys')) + self.assertNotIn('.clone()', body) + self.assertNotIn('.collect', body) + delivery = text.split('fn deliver_person_open_with_seed_read(', 1)[1].split('\n }', 1)[0] + self.assertIn('self.pending_person_open.take()', delivery) + self.assertLess(delivery.index('pending.scope != owner.scope.0'), delivery.index('self.stores.person_run')) + self.assertLess(delivery.index('pending.tenure != capture.tenure'), delivery.index('self.person_capture.refresh')) + self.assertIn('self.deliver_person_open_with_seed_read(read)', body) + self.assertLess(body.index('if let Some(person) = self.stores.person_view().current()'), body.index('self.person_capture.refresh')) + self.assertIn('self.person_pump_with_seed_read(&mut plx_base::devtrig::read)', text) + self.assertIn('self.deliver_person_open_with_seed_read(&mut plx_base::devtrig::read)', text) + self.assertIn('AppMsg::PersonCommand { from, command }', text) + def test_stable_roster_sync_does_not_copy_page_or_roster(self): + text = (ROOT / 'rust-modules/data/src/person.rs').read_text(encoding='utf-8') + body = text.split('fn sync_roster(', 1)[1].split('fn src_of(', 1)[0] + self.assertNotIn('.clone()', body) + self.assertIn('old.iter().copied().eq(', body) + self.assertIn('input.keys.slots()', body) + def test_person_ledger_is_empty_and_global_pin_matches_actual_entries(self): + import ast + ledger = ROOT / 'ci/allow/globals/data-person.txt' + self.assertEqual([s for s in ledger.read_text(encoding='utf-8').splitlines() if s.strip() and not s.startswith('#')], []) + total = sum(int(p.read_text(encoding='utf-8').splitlines()[0].split(':')[1]) for p in ledger.parent.glob('*.txt')) + tree = ast.parse((ROOT / 'tests/test_harness.py').read_text(encoding='utf-8')) + pins = [ast.literal_eval(n.value) for n in ast.walk(tree) if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'PINNED_LEDGER_TOTALS' for t in n.targets)] + self.assertEqual(len(pins), 1) + self.assertEqual(pins[0]['globals'], total) + def test_explicit_scope_precedes_controlled_shortcut(self): + text = (ROOT / 'rust-modules/data/src/person.rs').read_text(encoding='utf-8') + fields = text.split('pub struct PersonInput', 1)[1].split('pub struct PersonState', 1)[0] + for field in ('profile_scope', 'owner_epoch', 'profile_generation', 'profile_key', 'tenure'): + self.assertIn(field, fields) + body = text.split('fn observe_session(', 1)[1].split('fn current(', 1)[0] + self.assertLess(body.index('scope_changed'), body.index('input.controlled')) + def test_requested_behavior_regressions_are_present(self): + text = (ROOT / 'rust-modules/data/src/person/captured_inputs_tests.rs').read_text(encoding='utf-8') + self.assertEqual(text.count('#[test]'), 12) + self.assertIn('Arc::ptr_eq(&s, &session)', text) + self.assertIn('an orphan cannot release', text) + self.assertIn('assert!(state.pump(&adapter, &facts))', text) + boundary = (ROOT / 'rust-modules/data/src/person/boundary_tests.rs').read_text(encoding='utf-8') + self.assertEqual(boundary.count('#[test]'), 5) + self.assertIn('explicit_scope_edges_retire_claims_and_evidence_before_any_landing_even_controlled', boundary) + self.assertIn('same_generation_retry_rejects_old_refusal_success_address_and_key', boundary) + def test_refusal_is_addressed_and_observed_in_runner_drain(self): + text = (ROOT / 'rust-modules/data/src/person.rs').read_text(encoding='utf-8') + body = text.split('fn refused(&self, addr: Addr)', 1)[1].split('impl PersonState', 1)[0] + self.assertIn('self.matches(addr, pending)', body) + self.assertIn('PersonLaunchRefused { addr, request:', body) + self.assertNotIn('release_for', body) + self.assertIn('addr == self.addr && addr == pending.addr && *self.request == *pending.request', text) + bridge = (ROOT / 'rust-modules/src/app/bridge.rs').read_text(encoding='utf-8') + drain = bridge.split('fn start_jobs(', 1)[1].split('fn start_late_store_jobs', 1)[0] + self.assertIn('self.stores.person.land_launch_refusals()', drain) + def test_session_capture_commits_only_after_closing_publication_fence(self): + text = (ROOT / 'rust-modules/src/app/bridge.rs').read_text(encoding='utf-8') + body = text.split('fn refill_store_session(', 1)[1].split('fn search_input', 1)[0] + self.assertLess(body.index('if revision() != before'), body.index('self.session = settled')) + self.assertNotIn('Arc::new', body) + self.assertNotIn('collect', body) +if __name__ == '__main__': + unittest.main() diff --git a/docs/design-briefs/verdict-person-final-boundary-audit.json b/docs/design-briefs/verdict-person-final-boundary-audit.json new file mode 100644 index 0000000000..9ea0cf51f8 --- /dev/null +++ b/docs/design-briefs/verdict-person-final-boundary-audit.json @@ -0,0 +1,335 @@ +{ + "schema": 1, + "status": "Person authority/terminal boundary implemented and runtime-tested; full plx_data retains 9 independently reproduced pre-existing Metadata/Search failures.", + "supersedes": "docs/design-briefs/verdict-person-captured-inputs-audit.json", + "fixture_commits": { + "root": "26010b69", + "integration": "c540fdee6cab5020f324a895f717e04800c10fd3" + }, + "requirements": { + "coherent_capture": "Retained StoreSessionCapture::refill_store_session validates screen_input_revision before/after settled Arc, visible generation, profile and tenure reads; rejected attempts do not mutate the retained publication. Person callers defer the pass on rejection. No per-frame payload allocation or Session deep clone.", + "explicit_scope": "PersonInput carries SessionMachine scope/flow epoch plus captured profile generation/key/tenure. observe_session checks explicit edges before controlled recovery suppression and before any landing; supersede retires requests, terminals, stamps, outbox, backoffs and seed latches. Only mounted header is held; account/server evidence is cleared with unchanged roster.", + "addressed_terminal": "PersonPort checks full Addr and complete pending PersonReq (including slot/generation/args/identity/client keys) before either completion or launch refusal. A typed PersonLaunchRefused queues exactly one addressed terminal. Bridge::start_jobs consumes it before returning; owner releases its claim, arms 120-frame retry and marks attempted profile. No same-drain retry loop. Permanent Landing::Refused and tape mail/admission layouts are unchanged." + }, + "regressions": { + "data": "rust-modules/data/src/person/boundary_tests.rs", + "data_cases": 5, + "host": "rust-modules/src/app/person_boundary_tests.rs", + "host_cases": 3, + "red": "Two runtime refusal tests failed before product edits. Missing scope input oracle also failed before product edits.", + "host_runtime": "3 passed, including real runner retired-client launch refusal in same drain and adversarial Ready A→B publication.", + "existing_captured_input_cases": 12, + "source_oracles": "10 passed in each of ROOT, SansIO and integration" + }, + "rust": { + "tested_tree": "0047ccf5838568a227e7c9a680b16c5329e70dad", + "target": "/home/glinnik/.cache/plxnative-sim/m4-target-cfa3cba39826", + "full_data": { + "summary": "test result: FAILED. 1612 passed; 9 failed; 0 ignored; 0 measured; 0 filtered out; finished in 14.75s", + "failures": [ + "metadata::detail_mailbox_tests::an_alt_sources_landing_for_another_servers_copy_with_the_same_key_is_refused", + "metadata::dump_tests::dump_mode_a_superseded_alt_requests_stale_answer_does_not_end_the_wait", + "metadata::dump_tests::dump_mode_an_alt_request_out_lands_on_the_pump_that_runs_whatever_the_worker", + "metadata::metadata_alt_sources_job_tests::a_stale_writer_blocked_on_the_slot_cannot_replace_a_newer_ready_result", + "metadata::metadata_alt_sources_job_tests::exact_job_addr_whole_snapshot_and_origin_inclusive_roster_start_nothing", + "metadata::metadata_alt_sources_job_tests::no_guid_or_one_roster_slot_settles_without_a_job", + "metadata::metadata_alt_sources_job_tests::ready_real_result_wins_registration_in_the_same_pass_and_next_pass_sees_new_roster", + "metadata::metadata_alt_sources_job_tests::reset_rotates_alt_identity_and_a_retired_completion_cannot_reach_the_same_item", + "search::view::tests::rebuilding_a_source_answer_replaces_only_the_new_publication" + ], + "baselineIdentical": true + }, + "pre_fix_baseline": { + "summary": "test result: FAILED. 1607 passed; 11 failed; 0 ignored; 0 measured; 0 filtered out; finished in 14.71s", + "failures": [ + "metadata::detail_mailbox_tests::an_alt_sources_landing_for_another_servers_copy_with_the_same_key_is_refused", + "metadata::dump_tests::dump_mode_a_superseded_alt_requests_stale_answer_does_not_end_the_wait", + "metadata::dump_tests::dump_mode_an_alt_request_out_lands_on_the_pump_that_runs_whatever_the_worker", + "metadata::metadata_alt_sources_job_tests::a_stale_writer_blocked_on_the_slot_cannot_replace_a_newer_ready_result", + "metadata::metadata_alt_sources_job_tests::exact_job_addr_whole_snapshot_and_origin_inclusive_roster_start_nothing", + "metadata::metadata_alt_sources_job_tests::no_guid_or_one_roster_slot_settles_without_a_job", + "metadata::metadata_alt_sources_job_tests::ready_real_result_wins_registration_in_the_same_pass_and_next_pass_sees_new_roster", + "metadata::metadata_alt_sources_job_tests::reset_rotates_alt_identity_and_a_retired_completion_cannot_reach_the_same_item", + "person::boundary_tests::launch_refusal_is_an_addressed_event_not_a_claim_release", + "person::boundary_tests::wrong_request_address_cannot_refuse_the_live_job", + "search::view::tests::rebuilding_a_source_answer_replaces_only_the_new_publication" + ] + }, + "logs": [ + ".worktrees/verdict-integration/.empryo/person-boundary-baseline-plx_data-all.log", + ".worktrees/verdict-integration/.empryo/person-boundary-green-data-plx_data-all-v1.log", + ".worktrees/verdict-integration/.empryo/person-boundary-green-data-app-person_boundary_tests-v2.log", + ".worktrees/verdict-integration/.empryo/person-boundary-green-data-plx_data-person-v1.log", + ".worktrees/verdict-integration/.empryo/person-boundary-green-data-plx_screens-person-v1.log", + ".worktrees/verdict-integration/.empryo/person-boundary-green-data-app-owned_search-v1.log", + ".worktrees/verdict-integration/.empryo/person-boundary-green-data-app-search_publication-v1.log" + ], + "focused": [ + { + "name": "plx_data-person", + "summary": "test result: ok. 86 passed; 0 failed; 0 ignored; 0 measured; 1535 filtered out; finished in 1.18s" + }, + { + "name": "plx_screens-person", + "summary": "test result: ok. 57 passed; 0 failed; 0 ignored; 0 measured; 2077 filtered out; finished in 0.07s" + }, + { + "name": "app-owned_search", + "summary": "test result: ok. 21 passed; 0 failed; 0 ignored; 0 measured; 1326 filtered out; finished in 0.42s" + }, + { + "name": "app-search_publication", + "summary": "test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1345 filtered out; finished in 0.05s" + } + ], + "final_staged_tree_before_audit_update": "07ccbd2a0fdcb309bf7282e2a8de709cce770a49" + }, + "mirrors": { + "normalized_lf_sha256": { + "rust-modules/data/src/person.rs": { + "hashes": { + "": "d90b3a349834c7156a7cf36d4d9dfffccf91bfa7c0239309f55d21224959ce82", + ".worktrees/sans_io-6a4bcd6a42/": "d90b3a349834c7156a7cf36d4d9dfffccf91bfa7c0239309f55d21224959ce82", + ".worktrees/verdict-integration/": "d90b3a349834c7156a7cf36d4d9dfffccf91bfa7c0239309f55d21224959ce82" + }, + "equal": true + }, + "rust-modules/data/src/person/captured_inputs_tests.rs": { + "hashes": { + "": "0b73408b06a61027e217a345f095f3efe70ae12c2481c68a72bf70129c1236b2", + ".worktrees/sans_io-6a4bcd6a42/": "0b73408b06a61027e217a345f095f3efe70ae12c2481c68a72bf70129c1236b2", + ".worktrees/verdict-integration/": "0b73408b06a61027e217a345f095f3efe70ae12c2481c68a72bf70129c1236b2" + }, + "equal": true + }, + "rust-modules/data/src/person/boundary_tests.rs": { + "hashes": { + "": "1901b1e1188dcc056f5dad1418f01db397d4c3d53b235f6f94b166ccf14bc84f", + ".worktrees/sans_io-6a4bcd6a42/": "1901b1e1188dcc056f5dad1418f01db397d4c3d53b235f6f94b166ccf14bc84f", + ".worktrees/verdict-integration/": "1901b1e1188dcc056f5dad1418f01db397d4c3d53b235f6f94b166ccf14bc84f" + }, + "equal": true + }, + "rust-modules/data/src/stores/person.rs": { + "hashes": { + "": "fe86b8de685496d37c159818deacc67f11cd420a34b57cab71f9b9de39ea7c5c", + ".worktrees/sans_io-6a4bcd6a42/": "fe86b8de685496d37c159818deacc67f11cd420a34b57cab71f9b9de39ea7c5c", + ".worktrees/verdict-integration/": "fe86b8de685496d37c159818deacc67f11cd420a34b57cab71f9b9de39ea7c5c" + }, + "equal": true + }, + "rust-modules/data/src/stores/held_keys_tests.rs": { + "hashes": { + "": "de14ab4026ed1b44fc5337c2ffea37d0ad465ff158a8befcf4afad4efa730245", + ".worktrees/sans_io-6a4bcd6a42/": "de14ab4026ed1b44fc5337c2ffea37d0ad465ff158a8befcf4afad4efa730245", + ".worktrees/verdict-integration/": "de14ab4026ed1b44fc5337c2ffea37d0ad465ff158a8befcf4afad4efa730245" + }, + "equal": true + }, + "rust-modules/data/src/search_account_scope_tests.rs": { + "hashes": { + "": "defba5bdb8d182797b37f4eefe78187413e27713c5752193a496d1c9096a8037", + ".worktrees/sans_io-6a4bcd6a42/": "defba5bdb8d182797b37f4eefe78187413e27713c5752193a496d1c9096a8037", + ".worktrees/verdict-integration/": "defba5bdb8d182797b37f4eefe78187413e27713c5752193a496d1c9096a8037" + }, + "equal": true + }, + "rust-modules/screens/src/person.rs": { + "hashes": { + "": "5cf39a4ccc4993af2bf136c534c91ec1000c2516ecd76c5b34616d338787b2a6", + ".worktrees/sans_io-6a4bcd6a42/": "5cf39a4ccc4993af2bf136c534c91ec1000c2516ecd76c5b34616d338787b2a6", + ".worktrees/verdict-integration/": "5cf39a4ccc4993af2bf136c534c91ec1000c2516ecd76c5b34616d338787b2a6" + }, + "equal": true + }, + "rust-modules/src/app/adapters/stores.rs": { + "hashes": { + "": "ed5e981260518e75c9adf1727ba666258c58d0e0c9e5abd1c1c4046320882f6c", + ".worktrees/sans_io-6a4bcd6a42/": "ed5e981260518e75c9adf1727ba666258c58d0e0c9e5abd1c1c4046320882f6c", + ".worktrees/verdict-integration/": "ed5e981260518e75c9adf1727ba666258c58d0e0c9e5abd1c1c4046320882f6c" + }, + "equal": true + }, + "rust-modules/src/app/person_boundary_tests.rs": { + "hashes": { + "": "38889f1cc0b6979ef1ad9c7fdd9f5568fcf89af24b37e710fc516b621ad216f5", + ".worktrees/sans_io-6a4bcd6a42/": "38889f1cc0b6979ef1ad9c7fdd9f5568fcf89af24b37e710fc516b621ad216f5", + ".worktrees/verdict-integration/": "38889f1cc0b6979ef1ad9c7fdd9f5568fcf89af24b37e710fc516b621ad216f5" + }, + "equal": true + }, + "rust-modules/src/app/search_owned_tests.rs": { + "hashes": { + "": "f4e17ab641cf9015328c0b5eaed9e20311126633a06e15e420b3fce7b63890f3", + ".worktrees/sans_io-6a4bcd6a42/": "f4e17ab641cf9015328c0b5eaed9e20311126633a06e15e420b3fce7b63890f3", + ".worktrees/verdict-integration/": "f4e17ab641cf9015328c0b5eaed9e20311126633a06e15e420b3fce7b63890f3" + }, + "equal": true + }, + "rust-modules/src/app/search_publication_tests.rs": { + "hashes": { + "": "5ad18e9bef2bcb918bfae4dfa03d8f0103daf115ae8c2b662590685fed9920da", + ".worktrees/sans_io-6a4bcd6a42/": "5ad18e9bef2bcb918bfae4dfa03d8f0103daf115ae8c2b662590685fed9920da", + ".worktrees/verdict-integration/": "5ad18e9bef2bcb918bfae4dfa03d8f0103daf115ae8c2b662590685fed9920da" + }, + "equal": true + }, + "rust-modules/screens/src/alt_sources_tests.rs": { + "hashes": { + "": "6cecb2e42eac9b96eadcdfe6f2069980021d5007da4ca61a7d77603435389847", + ".worktrees/sans_io-6a4bcd6a42/": "6cecb2e42eac9b96eadcdfe6f2069980021d5007da4ca61a7d77603435389847", + ".worktrees/verdict-integration/": "6cecb2e42eac9b96eadcdfe6f2069980021d5007da4ca61a7d77603435389847" + }, + "equal": true + }, + "rust-modules/screens/src/detail/tests.rs": { + "hashes": { + "": "ca03ecdb28990a3a3cfbe0e6010bfd4398f2ffe269355ed3f3944d7c48bd8c57", + ".worktrees/sans_io-6a4bcd6a42/": "ca03ecdb28990a3a3cfbe0e6010bfd4398f2ffe269355ed3f3944d7c48bd8c57", + ".worktrees/verdict-integration/": "f41686702519d13ac7d276a0bb47c48c3a923917fdebf7fa189a6d19eeaadba2" + }, + "equal": false, + "fixture_hunks": { + "hashes": { + "": "fb85aa06d78f68fc30782a25ca2ca4d2c1b0b4d2c6e39d7a14f831a2edbd947c", + ".worktrees/sans_io-6a4bcd6a42/": "fb85aa06d78f68fc30782a25ca2ca4d2c1b0b4d2c6e39d7a14f831a2edbd947c", + ".worktrees/verdict-integration/": "fb85aa06d78f68fc30782a25ca2ca4d2c1b0b4d2c6e39d7a14f831a2edbd947c" + }, + "equal": true + }, + "preserved_unrelated_ui_difference": "Integration has pre-existing modern hero/trailer/identity tests; ROOT/SansIO UI expectations untouched." + }, + "rust-modules/src/app/detail_panel_tests.rs": { + "hashes": { + "": "b830c5a5b6381dc6a3e9fb643cfbe389eb5f8f0d591230a6764ec1e59dfe625d", + ".worktrees/sans_io-6a4bcd6a42/": "b830c5a5b6381dc6a3e9fb643cfbe389eb5f8f0d591230a6764ec1e59dfe625d", + ".worktrees/verdict-integration/": "b830c5a5b6381dc6a3e9fb643cfbe389eb5f8f0d591230a6764ec1e59dfe625d" + }, + "equal": true + }, + "docs/design-briefs/verdict-person-captured-inputs-source-oracle.py": { + "hashes": { + "": "541cc3df32febff9957c6fa447c0acbc93fb583f61f95b76f20523b5428cb876", + ".worktrees/sans_io-6a4bcd6a42/": "541cc3df32febff9957c6fa447c0acbc93fb583f61f95b76f20523b5428cb876", + ".worktrees/verdict-integration/": "541cc3df32febff9957c6fa447c0acbc93fb583f61f95b76f20523b5428cb876" + }, + "equal": true + }, + "docs/design-briefs/verdict-person-captured-inputs-audit.json": { + "hashes": { + "": "5eef41dd5bb955b90e9f9108be2c1c36d52f2fb01bb9a20e783c92a27965244b", + ".worktrees/sans_io-6a4bcd6a42/": "5eef41dd5bb955b90e9f9108be2c1c36d52f2fb01bb9a20e783c92a27965244b", + ".worktrees/verdict-integration/": "5eef41dd5bb955b90e9f9108be2c1c36d52f2fb01bb9a20e783c92a27965244b" + }, + "equal": true + } + }, + "bridge_regions": { + "refill_store_session": { + "regions": { + "": { + "sha256": "f0a067a8da54cb770ef54d0c1602e3d13adf0889c9ec1a632b04839e20282ae9", + "line": 98 + }, + ".worktrees/sans_io-6a4bcd6a42/": { + "sha256": "f0a067a8da54cb770ef54d0c1602e3d13adf0889c9ec1a632b04839e20282ae9", + "line": 518 + }, + ".worktrees/verdict-integration/": { + "sha256": "f0a067a8da54cb770ef54d0c1602e3d13adf0889c9ec1a632b04839e20282ae9", + "line": 527 + } + }, + "equal": true + }, + "capture_store_session": { + "regions": { + "": { + "sha256": "ecf79beb1a08edd983a57e20628bb1775d25bc9498db510a3e5c0e1e3d884ee6", + "line": 1440 + }, + ".worktrees/sans_io-6a4bcd6a42/": { + "sha256": "ecf79beb1a08edd983a57e20628bb1775d25bc9498db510a3e5c0e1e3d884ee6", + "line": 1805 + }, + ".worktrees/verdict-integration/": { + "sha256": "ecf79beb1a08edd983a57e20628bb1775d25bc9498db510a3e5c0e1e3d884ee6", + "line": 1899 + } + }, + "equal": true + }, + "person_run": { + "regions": { + "": { + "sha256": "efd90ab90131cae0de8c5ef13c23cde024314b87ff8d462b78e2417a2600ff42", + "line": 1808 + }, + ".worktrees/sans_io-6a4bcd6a42/": { + "sha256": "efd90ab90131cae0de8c5ef13c23cde024314b87ff8d462b78e2417a2600ff42", + "line": 1770 + }, + ".worktrees/verdict-integration/": { + "sha256": "efd90ab90131cae0de8c5ef13c23cde024314b87ff8d462b78e2417a2600ff42", + "line": 1864 + } + }, + "equal": true + }, + "person_pump": { + "regions": { + "": { + "sha256": "97babb5514cc34835ad5d4ad0a0d63bb7d16bdb983dcfed016fec0bbc885e889", + "line": 1825 + }, + ".worktrees/sans_io-6a4bcd6a42/": { + "sha256": "97babb5514cc34835ad5d4ad0a0d63bb7d16bdb983dcfed016fec0bbc885e889", + "line": 1787 + }, + ".worktrees/verdict-integration/": { + "sha256": "97babb5514cc34835ad5d4ad0a0d63bb7d16bdb983dcfed016fec0bbc885e889", + "line": 1881 + } + }, + "equal": true + }, + "start_jobs": { + "regions": { + "": { + "sha256": "5ad1dee7fea716c5022f4e1081e844898a6c44ced076151c471dcdadd9f6595f", + "line": 1968 + }, + ".worktrees/sans_io-6a4bcd6a42/": { + "sha256": "5ad1dee7fea716c5022f4e1081e844898a6c44ced076151c471dcdadd9f6595f", + "line": 1966 + }, + ".worktrees/verdict-integration/": { + "sha256": "5ad1dee7fea716c5022f4e1081e844898a6c44ced076151c471dcdadd9f6595f", + "line": 2060 + } + }, + "equal": true + }, + "PersonCapture.input": { + "regions": { + "": { + "sha256": "a4c914add2b3bddda7eb62ab687b113d766c990d888cd899b8d927f1850fe7cc", + "line": 536 + }, + ".worktrees/sans_io-6a4bcd6a42/": { + "sha256": "a4c914add2b3bddda7eb62ab687b113d766c990d888cd899b8d927f1850fe7cc", + "line": 488 + }, + ".worktrees/verdict-integration/": { + "sha256": "a4c914add2b3bddda7eb62ab687b113d766c990d888cd899b8d927f1850fe7cc", + "line": 497 + } + }, + "equal": true + } + }, + "all_equal": true + }, + "preserved": "No ledger/pin increase; no ambient production fallback/cfg(test) split; old assertions and golden tape shapes retained. ROOT/SansIO UI, unrelated integration modern UI, .gitignore, tmp and prior evidence untouched.", + "fixture_compatibility": "Three obsolete Search app fixture calls now derive household from captured AppViews, not a restored ambient Bridge helper; assertions unchanged." +} diff --git a/docs/design-briefs/watchlist-jobs.md b/docs/design-briefs/watchlist-jobs.md new file mode 100644 index 0000000000..a919480a72 --- /dev/null +++ b/docs/design-briefs/watchlist-jobs.md @@ -0,0 +1,70 @@ +# Watchlist W2: addressed jobs and captured facts + +**Status:** design for independent critique and the next judge; no runtime change authorized by this document. Checkout: `sansio/watchlist-jobs-w2`, based exactly on Notify head `cf987a6391bd370eb4e054f204cbac41ad727e59`. Notify PR #1322 subsequently squash-landed as `283f536d11bde907c49661dd0e9e1231ce668014`; that is not this checkout's base. Do not silently substitute it or restack a dirty design. Any later restack after an appropriate clean checkpoint must use `tools/pr-land.py restack` and record the actual base. + +**Implementation restack:** the design checkpoint was restacked onto landed Notify squash `283f536d11bde907c49661dd0e9e1231ce668014` using `tools/pr-land.py restack`; the resulting clean head was `37fb5624706f4a3b40bbbd2d89fd49c92d4ab347`. The status above records the earlier design stage, not a restriction on the authorized implementation. The six fixture blobs in the pre-code audit match the original `cf987a6391bd` base; the restacked head instead contains the six blobs already present in the landed squash. W2 introduces no fixture changes relative to that landed base. + +## Boundary and invariants + +W1 already captures the seated `CurrentProfile` and `WatchlistAuth` in `WatchlistInput`; keep that contract, including no account on Open and the profile id, uuid and generation check. The store owns the rows, `IntentLedger`, match table, view state, claims, retry counters, outbox and epoch. The app owns roster/profile/date capture, job admission, registry lookup and worker scheduling. The existing `StoreRunner`, `Job`, `Addr`, `Port`, `StoreId::Watchlist` and `landgate` are the runtime; do not add a second executor, tape, global injection slot, or production/test `cfg` fork. + +A step or view may neither read `LiveIo`, the process registry nor the wall clock. Account transport stays off-frame and receives the captured credential. PMS lookup is through `KeyedClients` constructed by the app from the job's `ClientKeys` snapshot and host `client_for` function; it rechecks instance, token and grant when each request is built. A changed key is unanswered, not an empty server answer. This does not retract a request already on the wire. Never log credentials, GUIDs, rating keys or titles. Preserve the existing plex Watchlist write guard, including its discover stand-in and live-switch rules; tests must never write to a real account or create the live switch. + +## Inputs at every decision and capture + +Proposed borrowed input (names may follow local conventions): + +```rust +pub struct WatchlistFacts<'a> { + pub keys: &'a ClientKeys, + pub today: Option<&'a str>, // caller-captured UTC YYYY-MM-DD; None if unavailable +} +``` + +The Bridge refills keys and captures the date once per relevant call, then passes the same input through the entire call: `pump_with_gate(gate, profile, facts)`, command paths that can rederive, `notify_map`/`rematch_on`, view and feed capture, `held_keys`/`held_copy`/`copy_of`, and `art_server`. Update all transitive callers, including immutable capture/held paths; if an immutable Bridge entry cannot refill, change its caller to capture and hand the facts in, not to reuse a stale or ambient registry. Date conversion remains pure and the app reads the clock. Carry `None` faithfully; do not synthesize a date. A capture must not hand out references beyond the snapshot's lifetime; materialized views retain values, not a borrowed mutable Bridge. + +Implement `Reach` as a pure adapter over `ClientKeys`: roster from `slots()` in captured order; reachable only when captured `facts(sid).source` has `Some(Outcome::Reachable)`; missing/incoherent source is not reachable; rank current server first, then described `owned`, then shared/unknown, preserving existing tie/order behavior. Use `keys.current()`, `roster_gen()` and `facts_gen()`, and never infer a current or owned server from a key-only fixture. `match_rows`, matched-known selection, tile derivation, released fallback, and art/copy selection use these same captured semantics. Missing date/release remains Unknown as today. Every list/rematch/delta job owns a clone of the captured keys used for both its roster and its generation; roster changes during a worker cause the next pump to see the mismatch and rematch, rather than attaching a fresh generation to old answers. Capture the date used for each landing/derivation on the consuming pass, not an ambient worker clock. Verify whether a date rollover needs a rederive trigger: preserve existing observable behavior unless a separately approved change is needed. + +## Typed jobs, addresses and ownership + +Add five distinct `StoreJob` variants with `Job` and typed ports, wired to `store()`, `take_jobs_of`, `has_jobs_of`, live and held `StoreRunner` arms. Each job's address and `Tag { profile_gen, epoch, req }` travel in every post/terminal. `req` is allocated for **every** claim, including resolves; track the active request per lane and per `(sid, rk)` resolve. Validate address, epoch, profile and the exact request for its own claim before applying state, never compare a write against the latest unrelated list/resolve request. A retired port cannot settle a new claim even if a key is reused. Resolve may run without an account: capture the current profile generation and epoch independently of `auth`, and fence it on profile change/reset as well. Keep identity values out of Debug. + +| Kind | Owned request values | Posts | Exactly one terminal | +|---|---|---|---| +| Write | tag, captured auth, `PendingWrite` (hex, intent, stamp) | none | `Written { write, outcome }` or `NotStarted { write }` | +| List | tag, auth, keys, `known` GUID set and its roster generation, page-zero ETag, read stamp/write snapshot as store claim state | page, page failure, not-modified, released set, in order | `ListDone`, `NotStarted`, or `Panicked` | +| Rematch | tag, keys, full `(guid, Kind)` rows | `Rematch { answers, roster_gen }` | done, not-started, or panicked | +| Delta | tag, keys, sid, deduplicated `(guid, Kind)` asks and notification debt identity | `Delta { answers }` | done, not-started, or panicked | +| Resolve | tag, keys, sid and rating key | none | answered `Option>`, not-started, or panicked | + +Use `Addr { to: MachineId::Store(StoreId::Watchlist.ord()), req: RequestId(...) }`, with `Tag.req` matching that request and a checked, non-reused allocation for the lifetime of potentially retained ports; epoch/profile remain additional fences. Concrete boundary: `enum WatchlistStreamEvent { Page(..), PageFailed(..), NotModified, Released(..), Rematch(..), Delta(..) }`; `enum StreamEnd { Done, NotStarted, Panicked, Cancelled }`; `WatchlistStreamPort::post(addr, tag, event)` and `Port::done(addr, end)` / `refused(addr)`; `Port` and `Port` answer the two one-shot jobs. The port binds the immutable tag at creation and validates the supplied address; where `Port::done` has no tag parameter, the bound tag accompanies the terminal in its mailbox. `ListDone` is the list's `Done` terminal and is applied once, not also posted as an event. Resolve results include sid/rk in the bound request. `refused` maps only to `NotStarted`. Exact type names can change during implementation, not these shapes or guarantees. + +Ports expose an ordered `post(addr, tag, event)` and an idempotent terminal operation for streams; after the first terminal, reject further posts/terminals. Writes and resolves are one-answer ports with the same first-terminal rule. Keep per-attempt messages and terminal ordered even when drained separately; terminal must not overtake a page or an inline admission refusal. Store/port locking atomically couples terminal publication with claim completion so a pump cannot observe idle before the last post is visible. Wake idle after each accepted post or terminal. Terminal publication is guaranteed in a `catch_unwind`/RAII boundary outside the fallible body, including panic during account transport, lookup, decoding or producer code; no panic path may merely drop a flag. If the consumer reset/cancelled, the retired port still completes exactly once but its landing cannot mutate the new epoch. + +`NotStarted` means strictly no worker body ran and no request could have reached the wire (missing/stale key before admission where applicable, admission refusal, or cancelled while still parked). A started write panic/error is `Failed`, never `NotStarted`: it may have reached the account. For a refused write requeue the exact `PendingWrite` through `IntentLedger::requeue`, preserve press order/coalescing and set `write_retry = 120`; no other write overtakes it. The decrement/eligibility order and exact retry pump must match the current 120-pump behavior. `writes_seen` and ETag invalidation at claim remain conservative as today, even on refusal; `Landed` and `Failed` retain current optimistic ledger/reread behavior. + +List refusal retains `list_wanted`, clears the claim, and applies the current 120-pump list retry; it is not a page error. Rematch refusal likewise clears its lane and backs off; the unchanged roster mismatch retries. Delta refusal must restore its exact notification obligation as described below. Resolve refusal, missing/stale client or panic clears `resolving` without caching, so a later menu can ask again; a successful nonportable GUID is cached as `Some(None)`, while an unanswered PMS is outer `None` and is not cached. A panic in list produces an addressed failure followed by one terminal, disqualifies the in-progress read's validator, and unwinds a partial incoming reread without committing it; retain the previous complete list's ETag and rows on a failed reread, and preserve already displayed first-load pages/truncation rather than publishing an incomplete reread as complete. Rematch/delta panic retains the prior match table; it still terminates and releases its claim. Avoid silently dropping a delta on panic: return its still-owed notification debt for a bounded retry. + +On reset/profile change, retire the old mailbox and outbox claims; discard queued work that has not started and its retired settlements, signal any supported cooperative cancellation, and fence all old results. Use a per-claim shared admission state with an atomic transition `Queued -> Started` or `Queued -> Cancelled`: the owner cancels the queued state on retirement, and the runner must win `Queued -> Started` before spawning/doing IO; if spawn itself refuses, it publishes `NotStarted`. This capability is not a read of mutable store state from a worker. A parked job released after cancellation cannot start. Once `Started` wins, cancellation is cooperative and cannot say no IO occurred. Do not claim that cancellation undoes a started account write or automatically retry it under the next profile. A started write never publishes `NotStarted` or an early cancellation that would permit a second write while its outcome is unknown: it publishes `Written(Landed|Failed)` on return/panic; a reset retires its old claim without waiting on it or launching it under another profile. For a started read, whichever of completion/cooperative cancellation wins publishes the sole terminal, suppressing later posts. Scope cancellation per claim, not a shared global token. + +## Landing, owed and notification fan-out + +Preserve `StoreId::Watchlist` and existing landing gate/replay behavior. The owner claims before outbox emission. Maintain per-request outstanding state across drain calls: pages alone do not discharge a stream; one accepted terminal does. For the two existing gated mailbox families, the `take_landings_owed` predicate must count outstanding list/rematch/delta/write terminals and each resolving terminal, including terminal-only refusal/panic/cancel; aggregate already-drained progress instead of comparing only a single take's event count with all claims. A stale terminal settles only its own retired claim and cannot unblock or clear a current one. Do not block the main thread on live workers outside the existing gate; dump/armed replay waits only on actual owed claims, and a terminal always makes progress. Do not count merely emitted/parked work as complete. A refused admission is an observable addressed settlement and must be delivered before a gate could wait for it. Tests must exercise normal, dump and held/inline runner paths and demonstrate that every terminal/refusal/panic makes the owed predicate false exactly once. + +`Bridge::watchlist_pump` captures profile, keys and date, steps, then drains Watchlist jobs **in that same call**. Add Watchlist to `Stores::NOTIFY_FILLS`; `Bridge::notify_pump_captured` must drain it in the same fan-out call after `notify_map`, alongside existing Browse/Hubs, not at the late-job backstop. Wire all other entry points that can emit a Watchlist job to an immediate drain. Preserve the existing per-connection Notify admission/settlement ordering and do not add Watchlist work before Notify has produced its map. + +`spend_library_owed` currently removes a debt only if `rematch_on` really starts, and spaces subsequent work only then. Outbox emission alone cannot prove admission. Change it to reserve the exact `(sid, kind, owe)` and ask snapshot under the delta request id without losing concurrently arriving `added`, `gone`, or `sweep` debt. Settle admission in the originating Bridge call for a live runner, before the fan-out returns: on actual admission mark the reserved debt spent and apply the existing nonempty spacing once; on `NotStarted`, restore/merge it and do not mark spent. A held job stays reserved, not spent, until its real admission or refusal; completion and later notifications merge independently, so neither is erased. Expose an addressed admission outcome separate from the sole stream terminal if necessary; it is not itself a terminal and must be ordered before one. For panic after start, re-owe the reserved affected asks without undoing later notifications; apply a bounded retry to avoid a hot loop. Empty asks or an unreachable captured sid retain the current `rematch_on == true` no-worker semantics and existing spacing rules. Preserve `read_in_flight` semantics: an emitted, parked, or active list/rematch/delta counts as in flight until its terminal; changes that arrive while it is out remain owed. + +## Wire behavior and test matrix + +* Keep page-zero `If-None-Match`, 304 plus released fetch, raw wire-count advancement, no page-count cap, page-0/released/later-page ordering and one terminal. An initial later-page failure leaves visible partial rows truncated; a reread failure keeps the previous complete rows and validator. Only a complete quiet read stores its ETag; any write invalidates it, including a write overtaking the read. `NotModified` does not suppress released refresh. +* Unit-test every job's payload, address and exact tag; mixed list/write/resolve request IDs; stale profile, reset, duplicated or late posts/terminals; same key reused in a new epoch; no-auth resolves; retired parked work; and only-one terminal under completion/cancellation races. Check a stale worker cannot affect the new profile, and account writes never use a new profile's credential. +* Script transport via explicit per-test runner/account and PMS ports, not an ambient mocked registry or test-only production branch. Exercise real worker body/port with inert local fakes and production runner admission separately; assert write guard refuses unarmed live writes without issuing a network request. No real-account writes, no live-switch file. Exercise both worker panic and spawn/admission refusal for all five kinds, including after a partial list page and before/after resolve response. +* Test `NotStarted` vs started `Failed`, 120-pump retry boundary, FIFO/coalescing with two IDs and changes while refused, write overtaking list, reread owed once, list/rematch backoff, resolve unanswered vs nonportable result, no hot resend, and exact once release of list/write/resolve claims. +* Drive notify-map created/deleted/sweep and resync while a read is in flight; assert delta starts in the originating `notify_pump` with zero late jobs, and refusal/held/stale-key/panic restores only its own debt, preserves simultaneous new debt and spacing, and eventually retries. Verify empty/unreachable paths, retained match table, partial server replies and `GUIDS_PER_REQUEST` chunking: unanswered is not `Absent`. +* Hand distinct `ClientKeys`/dates to pump, feed/capture, `held_keys`, `held_copy`, `art_server` and notify paths; test current > owned > shared, missing/incoherent evidence, reachability/facts generation changes, changed roster while a list is running, midnight/unavailable date and captured-vs-live key races. Include key retoken/revoke after capture, and a profile reset while parked/on wire. No registry fallback in tests. +* Arm the actual dump/replay gate and force terminal-only refusal, panic and cancellation for each family; observe termination, ordered partial posts, no stranded busy flag and no double settlement. Preserve recorded landing ordering/frame semantics; compare inline, held and live scheduling. Existing watchlist, notification and Bridge wiring tests stay green; add targeted store, runner, Bridge/fan-out, gate and feature-set tests before broad gates. + +## Ledger and checkpoint + +Only after sites actually disappear: `ci/allow/workers/data-watchlist.txt` line 6 **-1**; `ci/allow/globals/data-watchlist.txt` lines 6–12 **-7** (`copy_rank/current_server`, `facts_gen/server_facts_gen`, `find/client_for`, `guid_of/client_for`, `reachable/server_probe_result`, `roster/server_ids`, `roster_gen/server_roster_gen`). No known production fork deletion; fxlanes unchanged. The specified isolated post-B-E/Notify/W2 pinned checkpoint is **4/74/62/11** (workers/globals/forks/fxlanes), conditional on those exact upstream deletions and no concurrent ledger changes. Recount the actual base and apply the ratchet when implementing; do not invent a historical baseline or claim this design changed any ledger. diff --git a/docs/sans-io-guide.md b/docs/sans-io-guide.md index e423ae2ba0..c20df3df39 100644 --- a/docs/sans-io-guide.md +++ b/docs/sans-io-guide.md @@ -21,14 +21,40 @@ release failure is an ordinary terminal at the observation frame, never a second admission. Production streams always run off-frame, including held real release; `Bridge::for_test` selects refusal, and finite scripts supply explicit eligibility. No stream callback runs inside data or while borrowing Stores across the runner. -The coordinator reports post-retirement ledger totals of 5 workers / 81 globals / +The Notify-only checkpoint had 5 workers / 81 globals / 62 forks / 11 fxlanes, down from the S4 pre-Notify 6/89/65/11. The source-only stale-key test passed in orun-27; runtime tests, capture comparisons and full gates remain pending. These contracts are not runtime or replay acceptance; see `.empryo/reviews/verdict-notify-integration.md` for the handoff limits. +The combined Session/W2/enforcement/Screens source checkpoint now has actual +ledger totals **4 workers / 19 globals / 62 forks / 11 fxlanes** after Person and the +remaining data captures, with exact pins. +Session uses the strict `state`/`transition`/`from_init` binding and structurally +proved immutable reads. Watchlist and Screens inputs are captured outside their +machine windows. Source/Python checks are not Rust/runtime/Clippy acceptance; +see the combined checkpoint in `docs/sans-io.md` for merge details and filters. + +## Person complete capture (source checkpoint; runtime acceptance pending) + +Person now takes `PersonInput` before Open and every pump: the host's ONE retained complete +`ClientKeys` roster, settled session and visible generation, controlled/provider decisions, and +dev biography/credits seeds. Never infer registered slots from key presence; append the origin +once even if unregistered. Stable pumps borrow inputs; only emitted jobs copy request strings. +Inputless Open/pump refuse, while Close, Reset and view edits remain independent. All 11 Person +global sites are retired: the Person-only checkpoint is **4 workers / 43 globals / 62 forks / +11 fxlanes**, down from 4/54/62/11. Source/Python checks do not claim Rust/replay acceptance. + ## Which code is a machine +Every entry in `ci/machines.ini` must bind its private state field, sole transition and constructor +with `writer_policy = strict`; none of the ten registered machines has a privacy-only exemption. +Add the matching module enum policy and an unconditional `deny`/`forbid` header for +`clippy::wildcard_enum_match_arm`. Local `allow`, `expect` and `warn` (including `cfg_attr` and +production children/includes) fail the source gate. Numeric/wire-string fallbacks are still valid. +Shared state reads need structural immutable-payload proof; generic identities need a closed private +seal, not a broad `Copy` bound. See "Machine shape" in `docs/sans-io.md`. + `ci/check-deps.sh` (the `MACHINES` array) scans these for `workers` and `globals`: - `rust-modules/data/src`, `session/src`, `screens/src`, `ui/src`, `appkit/src`, `machine/src`; @@ -54,12 +80,10 @@ actuator (`ForegroundActuator` in `media/src/player/foreground.rs`) and a seam t (`LiveCatalogIo`, called inside `finish_catalog_job`'s `catch_unwind` in `data/src/stores/catalog.rs`). CI still reads a body that sits in a scanned file, so give it what it needs as arguments too. -Two leftovers look like that list and are not models. `LiveIo` (`data/src/watchlist.rs`) is a seam the -Watchlist STEP calls (`reachable`, `roster`, `copy_rank`, `today`, `facts_gen`, `roster_gen`), and its -methods hold the `ci/allow/globals/data-watchlist.txt` lines (its `client_for` and `current_server` -reads, and the roster readers `server_ids`, `server_probe_result`, `server_roster_gen` and -`server_facts_gen`) and the `today()` clock read `docs/sans-io.md` lists (W-2). `build_stream`'s registry reads and its fork are ledger lines too -(`ci/allow/globals/media.txt`, `ci/allow/forks/media.txt`). Do not copy either. +The old Watchlist `LiveIo` step readers were retired by W2; `WatchlistSnapshot` is the captured +input, not a model for hiding registry access behind a trait. `build_stream`'s registry reads and +its fork remain IO-boundary ledger lines (`ci/allow/globals/media.txt`, `ci/allow/forks/media.txt`), +outside this data-step migration. Do not copy them into a machine. ## What counts as IO in a step @@ -146,8 +170,9 @@ input too: the Collection step asks `keys.key(sid)` of the `ClientKeys` it is ha in `data/src/collection.rs`), never `client_for`. A screen gets a session read the same way: the Bridge reads it and folds it into what a store -publishes (`Bridge::household_ids` into `Stores::search_snapshot`). The screens' own `peek` and -`client_for` reads are ledger lines (`ci/allow/globals/screens.txt`), not a pattern. +publishes (`Bridge::household_ids` into `Stores::search_snapshot`). Screens also consume retained +host-captured `ScreenInputs` through `Cx`; their former `peek` and `client_for` ledger entries +are retired, and `ci/allow/globals/screens.txt` is empty. **(c) A stepped machine: `step` returns effects, a runner executes them.** The player lifecycle (#1003) is `step(&mut self, ev, fx: &mut Vec) -> Handled` (`lifecycle.rs`). @@ -185,8 +210,10 @@ Never `Instant::now` or `SystemTime::now` in a step. The `wall` rule (`ci/check- instruments are listed in `ci/allow/wall.txt`) fails a clock read in most machine scope: `ui/`, `screens/`, `data/src/stores/`, the session owner and the migrated store files. Outside it, CI does not count the ones that remain (a diagnostic timer in `step_landings_with_scope` in `data/src/pms.rs`, -one in the fetch body `fetch_full` in `data/src/metadata.rs`), and `WatchlistIo::today` is a -documented remaining read; do not add to them. +one in the fetch body `fetch_full` in `data/src/metadata.rs`); do not add to them. W2 retired +the Watchlist step's ambient date read: the host captures the UTC date, worker ports return the +captured value, and the step consumes the snapshot. `WatchlistIo::today` is not a remaining +ambient step read. **(e) A test needs different behaviour: a seam or an argument, never a `cfg` branch.** A body takes the one call that reaches the world as a parameter. `finish_browse_page_job` passes the real read @@ -200,8 +227,9 @@ fn finish_page_with(port: &BrowsePagePort, addr: Addr, client: &'static Client, read: impl FnOnce(&Client, ServerId, &SectionQuery<'_>, bool, Option<&Restore>) -> ListingPage) { ``` -An IO trait works the same way when only the job body calls it (`CatalogIo`, `data/src/catalog.rs`); -a trait the step calls (`WatchlistIo`) is a registry read with one more hop. The shape to avoid is +An IO trait works the same way when only the job body calls it (`CatalogIo`, `data/src/catalog.rs`). +`WatchlistIo` is worker transport over captured facts; W2 retired its former ambient step readers. +A trait must not hide registry or clock access in a step. The shape to avoid is `#[cfg(not(test))]` or `if cfg!(test) { fake } else { real }` in production code: `ci/allow/forks/*.txt` list the ones that remain, to be deleted, not copied. An item only a test can see (`#[cfg(test)] fn`) is no fork. diff --git a/docs/sans-io.md b/docs/sans-io.md index 3d70cc99b8..721bf16b2c 100644 --- a/docs/sans-io.md +++ b/docs/sans-io.md @@ -7,7 +7,91 @@ player machine: `player/lifecycle.rs` is the machine alone (private state, one w `player/foreground.rs` its drivers and `player/transport.rs` the transport-pause contract; its shape is gated by `ci/machines.ini` (see "Machine shape" below). -## Notify integration checkpoint (not acceptance) +## Combined verdict source checkpoint (historical; not acceptance) + +The integration tree retains full ancestry from base `f8f6dbb7`, Session `33f18e52`, +Watchlist W2 `abd26d21`, enforcement `dd1664f7`, and Screens `10bd53db`. Actual +ledger entries are **4 workers / 19 globals / 61 forks / 11 fxlanes** after Person and +remaining data captured-input retirement; the pins +match those entries. Watchlist workers/globals and Screens globals are zero. +No remaining allowance was removed merely to reach a target count. + +Follow-up `0a98b17e` retains Watchlist captures as an immutable `Arc` handle +shared by both host capture paths. The cache compares the full `ClientKeys` +value and primitive UTC day before cloning keys, collecting reach or formatting +a date. It also removes the per-pump key clone and defers auth copying until +write/stream work is owed, preserving write-before-stream order. Two added +Rust regression sources cover a populated stable capture +(`watchlist_snapshot_cache_retains_populated_capture_and_buffers_on_stable_passes`) +and same-generation key/fact/eligibility changes, day changes and old in-flight +snapshot immutability. At this historical checkpoint they had not been compiled +or run; the later exact-head milestone below supersedes that execution status. The scoped follow-up +touches `stores/watchlist{,_ports,_stream_job}.rs`, app store adapter and Bridge. + +A terminal-edge follow-up records list read-start/progress in the addressed +stream kind: held rows, awaiting a first page, or publishing a first load. A +panic before page zero is not a later-page failure merely because old rows are +held. Held complete/partial rows retain their own completeness, while a first +load that published page zero remains truncated. Two additional Rust regression +sources cover those cases before/after page zero; execution was pending at that +historical checkpoint (see the later milestone below). +The write-ledger stamps are not used as list-read identities. + +Session now binds the actual `SessionMachine.state` (`attempt::Attempt`) to +`transition` and `from_init` with `state_reads = immutable`. The structural +read-only proof, not a getter-name exception, validates shared reads. The +registry contains ten machines, four with strict writer contracts. Exact wall +ports include the 17-line Catalog fetch/calendar worker adapter and Watchlist +calendar capture in the app store adapter; neither exemption contains a +machine. `ports.ini` is a new gate relative to the base, not a grown old list. + +The only textual merge conflicts were in `app/bridge.rs`: Watchlist pump keeps +W2 key/profile/snapshot capture before the machine-only `StepScope`, then drains +Watchlist jobs after it; the end-of-file resolve-drain test and Screens input +publication/cache test modules are both retained. Stores merged without a +textual conflict, preserving all twenty scope sites and captured arguments. +The reader-negative regression and both ledger pin reductions coexist in the +Python harness. Source-gate follow-up fixes two lexical false positives: visible +`#[cfg(test)]` modules are still test-only, and captured field labels are not +registry function values. Added regressions retain production-thread rejection, +RHS getter calls and bare callback-reference rejection; no allowance was added. +All replay fixtures and V5/V6 JSON goldens are unchanged from the base. + +Source verification uses the committed tree: `ci/check-machine-shape.py`, +`ci/check-ports.py`, `ci/check-ledger-ratchet.py`, the seven CI Python suites +for shape/writers/read-only proof/scopes/ports/ratchet/test-module discovery, +and the harness ledger and reader regressions. These are source checks only. +Rust compilation, runtime/replay tests, Clippy and independent review remain +acceptance prerequisites; no Rust stage/build was performed for this checkpoint. + +After the shared Rust lease, exercise owning-crate filters `step` (base), +`assert_fx` (machine), `step_scope_tests` (ui), +`lifecycle_obligation_tests` (media), `auth::owner` (session, including Attempt +and codecs), `watchlist` (data and app, including `watchlist_snapshot_cache`), and `screen_input` +(app), plus the full +plex and screens suites. Run Clippy with `clippy::wildcard_enum_match_arm` +enforced for ForegroundLifecycle, PictureGate, PlayerReadout and SessionMachine; +filtered tests do not replace the parent full gates or independent review. + +## Verified integration milestone (before steady-state cost fixes) + +On exact commit `4a4f0b258e05df9f0d94fbadab0e51100fafac7f`, tree +`e156bab180042b3e372a28b34089c86c674fe0b4`, the coordinator's run 350 +compiled and ran the full Data suite (**1621 passed**), including all **145 +Watchlist** tests and the capture/terminal-edge regressions above. The focused +Session (**333**), Screens (**2142**), app Session (**149**) and app screen-input +(**10**) tests also passed, as did the no-default-features and lint gates. +These are results for that exact pre-fix commit, not acceptance of a later head. + +The same full `make check` reported three Python failures: the unclassified +test-only `captured_store_fixture` module, the build-bench `app_rebuilt` +fixture assertion, and the TV-lock self-test timing. The fixture classification +is corrected in this follow-up without adding layer edges or allowances. The +other two are separate tooling/environment investigations. No full-check pass +or new-head acceptance is claimed here; publication still requires its actual +gates, independent review and benchmark evidence. + +## Notify integration checkpoint (historical; not acceptance) Notify's typed Direct stream lane and app per-connection cursor are written; the frozen API and integration evidence are in `.empryo/reviews/verdict-notify-core.md` @@ -20,7 +104,7 @@ Production opens off-frame; test boot refuses unless explicitly scripted. The three Notify allow-area files have been retired. The coordinator reports actual ledger totals of 5 workers / 81 globals / 62 forks / 11 fxlanes, down from the -S4 pre-Notify checkpoint of 6/89/65/11; the pins now match. The source-only stale-key +S4 pre-Notify checkpoint of 6/89/65/11; the pins matched that checkpoint. The source-only stale-key check passed in orun-27; runtime tests, capture comparisons and full gates remain pending. Per-connection source ordering is preserved; asynchronous worker wall-time is not pinned, and disabled-state repair is explicitly intentional. @@ -149,13 +233,65 @@ widening recorded the 17 forks that were already there (three in `screens/`: `le ## Machine shape -`ci/machines.ini` lists the state machines whose shape is gated, one `[file::Struct]` section each -(paths relative to `rust-modules/`), with the machine's `event` and `effect` types and a `step` -line saying how it is exposed, driven and owned. `ci/check-machine-shape.py` (in `make check`) -fails on a `pub`, `pub(crate)` or `pub(super)` field of a listed struct, so its state stays -private and its one writer stays `step`, and on an entry whose file or struct is gone. It also -prints one line per machine with the number of its `bool` and `Option<..>` fields: a report-only -flag ratchet, read in review and never red. The first entry is `ForegroundLifecycle`. +`ci/machines.ini` is the sole machine registry. Every entry binds a real event enum, a real +mutable effect-vector channel (or exact `effect = none` for a pure view), and one private inherent +`transition` reducer. The checker binds the complete argument list: exactly `&mut self`, one +registered event enum (possibly borrowed), one concrete mutable effect vector (absent for +`effect = none`), and only the explicitly declared closed `aux_facts` slot where required. +No additional state/model, context bag, reference, generic or callback argument is admitted, +regardless of its parameter name. Duplicate, missing and unknown bindings fail closed. +Concrete effect-vector aliases are resolved; an owned-state alias is not an event or an +auxiliary-fact certificate, and an opaque setter cannot become a writer through a renamed +frame/root wrapper. + +The actual canonical headers require three auxiliary inputs, not just Session time: +`tick_ms: u32` for Session, `now_ms: u64` for URI, and backend +`capabilities: Option`. Clock facts require unshadowed primitive identities +(or canonical primitive paths), by value, with the exact declared name and width. The backend +fact is pinned to the actual playback-contract declaration with exactly nine named boolean +fields; neither an arbitrary immutable model nor a familiar type name is sufficient. The +closed semantic slots cannot be extended by adding a type name to the registry. Reducer logic +may legitimately change phase based on these facts; the checker does not prove monotonic +clock history or semantic event admission. An event wrapping raw state and ignoring admission +is not made sound by its signature. Rust type checking and behavior review remain required. + +Every owned struct field is private and write-guarded by default: pending work, counters, outboxes, +caches and nested owners are not exemptions. `state_field` selects a variant view, never the write +coverage boundary. Fresh constructors initialize all fields and cannot accept an existing machine. +All subsequent physical writes belong inside `transition` itself, not a helper merely called by it. +Public adapters may dispatch typed owner events; consuming drains must do the same. Whole-machine +aliases/replacement, live mutable projections, nested mutating functions/closures and unknown +machine-capturing calls/macros fail closed. Detached owned values may have their own pure helpers. + +Shared readers require closed structural proof for the data they expose. A user `Copy` bound is +not an inertness certificate: generic identities need a private closed seal covering only proved +inert actual types. Numeric/discriminant reads may use bounded structural proof without exposing +opaque payloads. Foreign types remain opaque without reproducible source-backed dependency proof; +a familiar dependency name is not a certificate. + +`ci/readonly_generated.py` and `ci/proofs/platform-generated-enums.json` separately certify +the actual platform language include: pinned package/module/include, complete production +build scripts, generator/templates, manifests/configuration and locked graph. The reviewed +pipeline emits only unit enum variants in every configuration; strict catalogue/schema and +ASCII variant validation permit new languages without a count/list pin. The same evidence +pins the machine ID macro source and proves its concrete `u32` fields, not a `Copy` promise. +Reviewed machine snapshots differ only in `NavOp::SelectTabWithChild`, i18n snapshots only in clock formatting/helpers; either +source changing requires review. No generator or Cargo/cache code executes in native CI. +The certificate assumes ordinary Cargo/Rust/std/serde execution and no out-of-band output, +compiler or external configuration overrides. It certifies values only, never locale contexts, +locks, callbacks or generated method authority. Unknown layouts/includes remain opaque. + +Every source also registers a matching `[module file]` enum policy and unconditionally denies (or +forbids) `clippy::wildcard_enum_match_arm`. Local `allow`, `expect` and `warn` cannot weaken it. +Production child modules and literal includes are traversed exhaustively. Conditional +`cfg_attr(path)`, opaque/generated includes and unresolved production modules are rejected rather +than guessed; proven test-only code is excluded. Numeric and open wire-string wildcard matches +remain legal; the compiler/Clippy classify enum exhaustiveness, not a textual underscore ban. + +The native tests derive the cohort and every owned field from this registry, retain the original +writer/alias/macro negatives, and add typed-event/effect, full-field and production-closure matrices. +Fixture and mutation passes are not full-cohort Rust, Clippy, behavior or performance acceptance. +Bool/Option field counts are report-only. ## Layout @@ -219,8 +355,7 @@ re-point. It never mixes clients within one page: the opening season's episodes The Collection page's request is the second: its worker start and its three `client_for` reads are gone from `data/src/collection.rs`. The Person page's requests are the third: its two worker starts and its one `client_for` read are gone from `data/src/person.rs`, but unlike the two before it the -Person step is not pure (the bullet headed "What the Person step still reads" lists what it still -reads). Person has up to six requests out at once, so a pump emits several jobs, one per fetch slot, +Person step now takes complete captured inputs (the bullet headed "Person's complete captured inputs"). Person has up to six requests out at once, so a pump emits several jobs, one per fetch slot, in ascending slot order. The catalog page's read is the fourth: its one worker start is gone from `data/src/stores/catalog.rs`. Unlike the other three it names no server and no client (it is a plex.tv read as the captured identity), so it takes no `ClientKeys` and no tape admission, and the @@ -344,9 +479,8 @@ worker start and the `client_for` read inside that worker are gone too. The hous not drain: a `RequestDetail` stepped through it leaves its job on the outbox and nothing starts it. The same holds for the `pub` `Stores::metadata_run`. The owner drains in the same call, as `Bridge::metadata_run` does; no type enforces it, the counter below catches the lapse. - `CollectionStore`'s, `PersonStore`'s and `BrowseStore`'s `Machine::step` are unreached for these - reads and pass empty keys (a Browse step with no keys decides no section-hubs, directory or page read): a future - sender must pass the host's keys and drain. The same holds for the public + Person's inputless `Machine::step` refuses Open/pump explicitly, while Close, Reset and view edits + remain usable. Other store senders must likewise supply captured inputs and drain their jobs. The same holds for the public `CatalogStore::open` and `CatalogStore::pump`: `catalog_feed` and `catalog_reread` call `Bridge::catalog_open` and `Bridge::catalog_pump`, which drain in the same call. And for `HubsStore::run_with_directory`, `land_with_directory` and `tick_with_directory`: the @@ -385,17 +519,18 @@ worker start and the `client_for` read inside that worker are gone too. The hous Person jobs are out at once and `Addr.req` is only a per-job sequence there (`RequestId` stays unique per addressee): `done` and `refused` use the port's slot and generation, never the address, so a refusal gives back only its own generation's claim. -- **What the Person step still reads.** Person starts no worker and reads no `client_for`, but its - step is NOT pure. It still reads `tape::active()` (which decides whether a job exists and carries - the controlled identity), `session::peek_settled()` (the settled plex.tv account the two global - reads are made as; a `globals` site of its own, in `ci/allow/globals/data-person.txt`), the session watch, the - refused-discover check (`discover::person_profile_refused` / `person_credits_refused`, which - lands the refusal in the step with no job, because routing it through the runner would release - and respawn it every ~2 s), `plx_base::devtrig::read("personcredits")` (dev-trigger builds only: - `seed_dev_credits` reads it on every pump while a person is open and no tape is armed), - `server_ids()` (the source roster) and `server_roster_gen()`. Its - two fetch bodies, `fetch_profile` and `fetch_credits`, stay in `data/person.rs`, so their `forks` - ledger lines stay. A source whose server holds no key backs off in the step and emits no job. +- **Person's complete captured inputs.** The host captures before Open and every pump, borrowing + its ONE retained `ClientKeys` including every registered slot, not only slots holding a key. + `PersonInput` supplies settled session, visible generation, controlled mode, provider refusal + decisions and dev biography/credits seeds. The origin is appended once even when unregistered. + No step reads the roster/session/tape/dev provider; all 11 Person global ledger sites are gone. + Stable pumps compare borrowed instance/grant signatures and session strings without cloning + request data; token-only refresh preserves shelves. Local missing-client backoff, full-key job + admission, rotated adapters, generation-addressed claims and ascending gated landing order stay. + A captured fixed provider refusal settles in the emission turn without a job or retry; controlled + jobs still carry Controlled and answer the failure value through their unchanged typed ports. + Inputless Open/pump refuse explicitly; Close, Reset and view edits remain usable independently. + Worker-body fork allowances are unchanged. Python source acceptance is not Rust/replay acceptance. - **What the Catalog lane does, and does not, change.** Catalog is a plex.tv read: the job carries the captured `WatchlistAuth` and the title, and the read goes through the store's `CatalogIo` seam, which rides on the job's `CatalogPort` (so the request is a comparable value). The body is @@ -432,10 +567,11 @@ worker start and the `client_for` read inside that worker are gone too. The hous can capture nothing: it clears the identity and records the title as owed a read (`take_reopen`). `Bridge::catalog_pump` takes it and calls `catalog_open`, which reads the input then and starts the job, all in the pump's own call. An `open` or a `reset` clears the owed title. - - **What stays.** The Watchlist's `copy_rank::current_server`, `find::client_for` and `guid_of::client_for` - (W-2), `server_ids` / `server_probe_result` / `server_roster_gen` / `server_facts_gen`, and the - `today()` clock read. The test entries (`WatchlistStore::pump`, `run_for_test`, `WatchlistInput::for_test`) - hand a generation-1 seat. + - **W1 leftovers (retired by W2).** At W1, the Watchlist still read `copy_rank::current_server`, + `find::client_for`, `guid_of::client_for`, `server_ids` / `server_probe_result` / `server_roster_gen` / + `server_facts_gen`, and `today()`. These are not current step exceptions: W2 moved client lookup to + worker transport and roster, ranking and UTC-date facts to host-captured snapshots. At W1, the test + entries (`WatchlistStore::pump`, `run_for_test`, `WatchlistInput::for_test`) handed a generation-1 seat. - **A refusal the step can observe.** The runner may decline to start a job: the thread ceiling, a registry that moved on between the step and the launch (the client the job names is no longer the one the slot holds), or a `Held` runner whose client is gone. It then calls the port's `refused`, @@ -539,9 +675,10 @@ worker start and the `client_for` read inside that worker are gone too. The hous nothing, asks for a drain once more (as the queue-full retry that edit already had). The runner cannot be made to refuse a launch on a host (`spawn_small` has no failure knob), so its refused branch is pinned at the port (`a_refused_save_is_asked_again_at_the_next_edit_once`). - What the Search step still reads: `server_ids()` (the roster), `server_roster_gen()`, - `session::current_gen()` for a scoped query, and the recents cache's session reads, which stay in - `recents.rs` with the statics `STORE` and `PENDING`. A test drives it with `Owner::run_jobs` + Search now receives `SearchInput` before commands, pumps and publications: the same complete + `ClientKeys` as the other stores plus captured session/profile/tenure and recents facts. The + scope compares borrowed exact facts on stable frames; recents keeps `STORE` and `PENDING` + without reading the session registry. A test drives it with `Owner::run_jobs` (`search_test_support.rs`), a fixture that plays the runner against a served fake, in place of the inline fake-IO fork the old spawn carried. - **The section hubs lane.** A library's shelves (`data/src/browse/section_hubs.rs`) are the ninth @@ -654,9 +791,10 @@ worker start and the `client_for` read inside that worker are gone too. The hous registry: each is handed the `&Session` the app read. This is the second consumer of the pattern Search's household scope began (`Bridge::household_ids`, the Bridge reads, the store takes the value), and of the controlled run's `preferences`, which is the same value handed under the `""` key. No job kind and no - runner arm is added; every replay fixture is byte-identical. One path is not yet handed: the roster - reconcile (`sync_roster_owned` -> `reconcile_pins_from` -> `pin_record_for`) is given - `sync_roster_owned`'s own in-machine `peek()`, which stays on the ledger until B-E. + runner arm was added at this checkpoint; every replay fixture was byte-identical. The roster reconcile + (`sync_roster_owned` -> `reconcile_pins_from` -> `pin_record_for`) still used an in-machine `peek()` + then. S4 retired that ledger entry: `sync_roster_owned` now consumes `BrowseRosterInput`, and pin + reconciliation receives the captured `input.session` and `input.profile_key`. - **Observe, then read.** `Bridge::browse_session` is the one production reader: it calls `BrowseStore::observe_pin_write` FIRST, then `session::peek()`. The write's receipt is sent after the storage worker installed the written session, so a session read after seeing the receipt contains the @@ -671,12 +809,14 @@ worker start and the `client_for` read inside that worker are gone too. The hous `Discovery` (a `debug_assert`, and a dropped command with a log line in a release build) rather than read the registry; both reach `run_with_session`. The `Machine` arms hand the step no keys and no session. - - **What stays.** `current_profile_key` (the profile is a published key, not a session read), the - `queue_update` / `queue_update_ticket` merge under IO, `peek_settled`, and B-E's reads - (`discovery_needs_pump`, `sync_roster_owned`). The first-run gate's session is read by its two - callers, boot and `follow_auth_landing`, where each asks. The test entry points (`*_for_test`, the - `#[cfg(test)]` `resolve_pins` / `apply_pins` / `record_pins` shims) read the registry as of now, after - observing the pin write, as the Bridge does. + - **Historical leftovers (machine reads retired by S4).** This checkpoint still listed + `current_profile_key`, `peek_settled`, and B-E's reads (`discovery_needs_pump`, `sync_roster_owned`). + S4 retired the Browse globals ledger: roster reconciliation and discovery now consume captured + roster, session, settled and profile facts through `BrowseRosterInput`. The `queue_update` / + `queue_update_ticket` session merge remains IO-boundary work. The first-run gate's session is read + by its callers, boot and `follow_auth_landing`. At this checkpoint, the test entry points + (`*_for_test`, the `#[cfg(test)]` `resolve_pins` / `apply_pins` / `record_pins` shims) read the registry + after observing the pin write, as the Bridge did. - **The Metadata reads.** The season tabs, the long-season page window and the Related row's tail window (`data/src/metadata.rs`) are the tenth store reads on the lane. `load_season` flips the tab and emits `StoreJob::MetaSeason(Job, MetaSeasonPort)`, addressed by the season generation it diff --git a/rust-modules/base/src/clock.rs b/rust-modules/base/src/clock.rs index 358a6d6cb0..e1df66af01 100644 --- a/rust-modules/base/src/clock.rs +++ b/rust-modules/base/src/clock.rs @@ -12,14 +12,22 @@ use std::time::Instant; /// Monotonic milliseconds from the origin fixed at the first call (wrapping at `u32`). pub fn vclock_ms() -> u32 { + crate::step::assert_io_allowed("clock::vclock_ms"); origin().elapsed().as_millis() as u32 } /// [`vclock_ms`] in microseconds, on the same origin. pub fn vclock_us() -> u64 { + crate::step::assert_io_allowed("clock::vclock_us"); origin().elapsed().as_micros() as u64 } +/// Wall time is an IO port too; machine inputs carry already-sampled time. +#[inline] +pub fn wall_now() -> std::time::SystemTime { + crate::step::assert_io_allowed("clock::wall_now"); + std::time::SystemTime::now() +} fn origin() -> &'static Instant { static T0: OnceLock = OnceLock::new(); T0.get_or_init(Instant::now) diff --git a/rust-modules/base/src/lib.rs b/rust-modules/base/src/lib.rs index 232b6154d2..341b2f9fab 100644 --- a/rust-modules/base/src/lib.rs +++ b/rust-modules/base/src/lib.rs @@ -14,6 +14,7 @@ pub mod eventlog; // THE event log: `eventlog::log` is the one sink every module writes through pub mod paths; // where the app's own files live — /proc/self/exe, not a hardcoded install prefix pub mod process; // `exit_now`: the one way the app's own exits end the process (`_exit`, never libc `exit`, #1115) +pub mod step; // test-time Sans-IO scope, shared by every layer pub mod clock; // `vclock_ms`/`vclock_us`: the one monotonic clock for stamps that are only differenced pub mod task; // the one spawn: a refused thread is a return value, not a panic that kills the app pub mod cbuf; // fixed NUL-terminated C-string buffer read/write diff --git a/rust-modules/base/src/step.rs b/rust-modules/base/src/step.rs new file mode 100644 index 0000000000..068f88c7ca --- /dev/null +++ b/rust-modules/base/src/step.rs @@ -0,0 +1,85 @@ +//! Test-time Sans-IO boundary. FrameScope forbids waits; this scope forbids starting IO. +use std::{marker::PhantomData, rc::Rc}; +#[cfg(any(test, feature = "test-support"))] +thread_local! { + static DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; +} +/// Keep this thread-bound guard around the machine call, never its runner or drain. +#[must_use = "keep the guard for the machine step"] +pub struct StepScope(PhantomData>); +impl StepScope { + #[inline(always)] + pub fn enter() -> Self { + #[cfg(any(test, feature = "test-support"))] + DEPTH.with(|depth| depth.set(depth.get().checked_add(1).expect("StepScope depth"))); + Self(PhantomData) + } +} +impl Drop for StepScope { + #[inline(always)] + fn drop(&mut self) { + #[cfg(any(test, feature = "test-support"))] + DEPTH.with(|depth| depth.set(depth.get() - 1)); + } +} +/// A frame's AllowBlocking exception cannot grant a machine IO capabilities. +#[inline(always)] +#[track_caller] +pub fn assert_io_allowed(operation: &str) { + #[cfg(any(test, feature = "test-support"))] + DEPTH.with(|depth| assert_eq!(depth.get(), 0, "IO during machine step: {operation}")); + #[cfg(not(any(test, feature = "test-support")))] + let _ = operation; +} +#[cfg(test)] +mod tests { + use super::*; + use std::panic::{catch_unwind, AssertUnwindSafe}; + #[test] + fn step_guard_cannot_be_sent_or_shared_between_threads() { + trait AmbiguousIfSend { fn check() {} } + impl AmbiguousIfSend<()> for T {} + impl AmbiguousIfSend for T {} + let _ = >::check; + trait AmbiguousIfSync { fn check() {} } + impl AmbiguousIfSync<()> for T {} + impl AmbiguousIfSync for T {} + let _ = >::check; + } + #[test] + fn nested_steps_restore_after_unwind_and_are_thread_local() { + let outer = StepScope::enter(); + assert!(catch_unwind(|| { let _inner = StepScope::enter(); panic!("unwind"); }).is_err()); + assert!(catch_unwind(|| assert_io_allowed("outer still active")).is_err()); + std::thread::spawn(|| assert_io_allowed("other thread")).join().unwrap(); + drop(outer); + assert_io_allowed("runner after step"); + } + #[test] + fn real_io_entries_refuse_even_under_allow_blocking() { + let writer = crate::storage_worker::Writer::start("step-test", 1, |n: u8| n).unwrap(); + let executor = crate::storage_worker::Executor::start(1).unwrap(); + let _allowed = crate::task::allow_blocking(const { &crate::task::BlockingLabel::new("fixture") }); + let step = StepScope::enter(); + let checks: Vec> = vec![ + Box::new(|| { let _ = crate::task::spawn("forbidden", || {}); }), + Box::new(|| { std::thread::scope(|s| { crate::task::beside(s, "forbidden", || ()).finish(); }); }), + Box::new(|| { let _ = crate::storage_worker::submit(|| ()); }), + Box::new(|| { let _ = crate::storage_worker::submit_retained(|| ()); }), + Box::new(|| { let _ = executor.submit(|| ()); }), + Box::new(|| { let _ = writer.submit_ticket(1); }), + Box::new(crate::storage_worker::pump_retained), + Box::new(|| { let _ = crate::task::assert_may_block(const { &crate::task::BlockingLabel::new("PMS HTTP") }); }), + Box::new(|| { crate::clock::vclock_ms(); }), + Box::new(|| { crate::clock::vclock_us(); }), + Box::new(|| { crate::clock::wall_now(); }), + ]; + for check in checks { assert!(catch_unwind(AssertUnwindSafe(check)).is_err()); } + drop(step); + crate::task::spawn("runner", || {}).unwrap().join().unwrap(); + assert_eq!(executor.submit(|| 42).unwrap().wait_blocking().unwrap(), 42); + assert_eq!(writer.submit_ticket(7).ok().unwrap().wait_blocking().unwrap(), 7); + crate::clock::vclock_ms(); + crate::clock::wall_now(); + } +} diff --git a/rust-modules/base/src/storage_worker.rs b/rust-modules/base/src/storage_worker.rs index f36ca4965d..e6f7ab5f80 100644 --- a/rust-modules/base/src/storage_worker.rs +++ b/rust-modules/base/src/storage_worker.rs @@ -71,6 +71,7 @@ fn submit_shared( start: impl FnOnce() -> Result, operation: impl FnOnce() -> R + Send + 'static, ) -> Result, SubmitError> { + crate::step::assert_io_allowed("storage_worker::submit"); // This lock protects queue construction/admission only, never a callback or disk I/O. // The worker releases it before taking session::IO (whose nested order is IO -> CACHE). let mut slot = shared.lock().unwrap_or_else(|error| error.into_inner()); @@ -96,6 +97,7 @@ static RETAINED: Mutex = Mutex::new(Retained { pub fn submit_retained(operation: impl FnOnce() -> R + Send + 'static) -> TypedTicket { + crate::step::assert_io_allowed("storage_worker::submit_retained"); let (reply, result) = mpsc::channel(); let (done, worker) = mpsc::channel(); let job: Job = Box::new(move || { @@ -109,6 +111,7 @@ pub fn submit_retained(operation: impl FnOnce() -> R + Send + } pub fn pump_retained() { + crate::step::assert_io_allowed("storage_worker::pump_retained"); pump_retained_locked(&mut RETAINED.lock().unwrap_or_else(|e| e.into_inner())); } @@ -169,6 +172,7 @@ impl Executor { &self, operation: impl FnOnce() -> R + Send + 'static, ) -> Result, SubmitError> { + crate::step::assert_io_allowed("storage_worker::Executor::submit"); let (reply, result) = mpsc::channel(); let job: Job = Box::new(move || { let _ = reply.send(operation()); @@ -275,6 +279,7 @@ impl Writer { command: C, tx: mpsc::Sender, ) -> Result<(), SubmitErrorGeneric> { + crate::step::assert_io_allowed("storage_worker::Writer::submit"); match self.sender.try_send((command, tx)) { Ok(()) => Ok(()), Err(TrySendError::Full((command, _))) => Err(SubmitErrorGeneric::Full(command)), diff --git a/rust-modules/base/src/task.rs b/rust-modules/base/src/task.rs index 3bfc448241..763cf7e729 100644 --- a/rust-modules/base/src/task.rs +++ b/rust-modules/base/src/task.rs @@ -171,6 +171,7 @@ fn thread_name(what: &str) -> String { } fn try_spawn(what: &str, stack: Option, f: impl FnOnce() + Send + 'static) -> io::Result> { + crate::step::assert_io_allowed("task::try_spawn"); let mut b = Builder::new().name(thread_name(what)); if let Some(n) = stack { b = b.stack_size(n); @@ -404,6 +405,7 @@ where T: Send + 'scope, F: FnOnce() -> T + Send + 'scope, { + crate::step::assert_io_allowed("task::beside_with"); use std::sync::{Arc, Mutex}; debug_assert!(!blocking::in_frame(), "beside was asked for on the frame thread"); // The lock is never held while `f` runs, so a panic in `f` cannot poison it. diff --git a/rust-modules/base/src/task/blocking.rs b/rust-modules/base/src/task/blocking.rs index dc6b5c5a5e..4e0f313d56 100644 --- a/rust-modules/base/src/task/blocking.rs +++ b/rust-modules/base/src/task/blocking.rs @@ -102,6 +102,7 @@ pub struct BlockingGuard { /// Formatting happens in [`BlockingGuard`]'s drop, which is already the slow branch. #[track_caller] pub fn assert_may_block(label: &'static BlockingLabel) -> BlockingGuard { + crate::step::assert_io_allowed(label.text); let at = Location::caller(); let in_frame = in_frame(); if cfg!(any(test, feature = "test-support")) && in_frame && !ALLOWED.with(|depth| depth.get() != 0) { diff --git a/rust-modules/data/src/browse/browse_discovery_lifecycle_tests.rs b/rust-modules/data/src/browse/browse_discovery_lifecycle_tests.rs index 5f93222581..8992abfc6c 100644 --- a/rust-modules/data/src/browse/browse_discovery_lifecycle_tests.rs +++ b/rust-modules/data/src/browse/browse_discovery_lifecycle_tests.rs @@ -32,7 +32,7 @@ fn a_settled_query_change_with_unknown_total_is_still_page_work() { browse.sync_roster(); let session = plx_plex::plex::session::peek(); let profile_key = plx_plex::plex::session::current_profile_key(); - let input = BrowseRosterInput { + let input = BrowseRosterInput { tenure: 0, keys: &browse.keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), profile_key: &profile_key, diff --git a/rust-modules/data/src/browse/browse_home_and_tabs_tests.rs b/rust-modules/data/src/browse/browse_home_and_tabs_tests.rs index 9c690cf2f7..286cc0015f 100644 --- a/rust-modules/data/src/browse/browse_home_and_tabs_tests.rs +++ b/rust-modules/data/src/browse/browse_home_and_tabs_tests.rs @@ -1472,7 +1472,7 @@ fn a_home_roster_arriving_late_re_resolves_the_pin_table() { source.counts_done = true; } assert!( - !browse.state.discovery_needs_pump(&browse.adapter, &BrowseRosterInput { + !browse.state.discovery_needs_pump(&browse.adapter, &BrowseRosterInput { tenure: 0, keys: &browse.keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -1495,7 +1495,7 @@ fn a_home_roster_arriving_late_re_resolves_the_pin_table() { ); assert!( - browse.state.discovery_needs_pump(&browse.adapter, &BrowseRosterInput { + browse.state.discovery_needs_pump(&browse.adapter, &BrowseRosterInput { tenure: 0, keys: &browse.keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -1530,7 +1530,7 @@ fn a_home_roster_arriving_late_re_resolves_the_pin_table() { // Idempotent: a second sync against the same roster is not a change. assert!( - !browse.state.discovery_needs_pump(&browse.adapter, &BrowseRosterInput { + !browse.state.discovery_needs_pump(&browse.adapter, &BrowseRosterInput { tenure: 0, keys: &browse.keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), diff --git a/rust-modules/data/src/browse/browse_test_support.rs b/rust-modules/data/src/browse/browse_test_support.rs index 3d9b0f789c..16144afdb3 100644 --- a/rust-modules/data/src/browse/browse_test_support.rs +++ b/rust-modules/data/src/browse/browse_test_support.rs @@ -10,6 +10,18 @@ pub(super) struct TestBrowse { /// The jobs the steps this rig ran have left on the outbox, as `BrowseStore::jobs` holds them. pub(super) jobs: Vec, } + +pub(super) fn run_preference_jobs(jobs: Vec) { + for job in jobs { + let crate::stores::StoreJob::BrowsePreferences(job, port) = job else { panic!("not a preference write") }; + let refusal = port.clone(); + let addr = job.addr; + if plx_base::storage_worker::submit(move || + preferences_job::finish_browse_preferences_job(&port, addr, job.req)).is_err() { + plx_machine::job::Port::refused(&refusal, addr); + } + } +} impl Default for TestBrowse { fn default() -> Self { Self { @@ -23,6 +35,7 @@ impl Default for TestBrowse { impl TestBrowse { /// The registry's answer as of NOW, as the Bridge fills it immediately before each step. pub(super) fn refill(&mut self) { + self.state.preference_writes.prepare(&plx_plex::plex::session::peek(), plx_plex::plex::session::tenure()); self.keys.refill_roster( plx_plex::plex::current_server(), plx_plex::plex::server_roster_gen(), plx_plex::plex::server_facts_gen(), plx_plex::plex::server_ids(), @@ -31,6 +44,10 @@ impl TestBrowse { ); } + pub(super) fn run_preference_jobs(&mut self) { + run_preference_jobs(self.state.take_preference_jobs()); + } + /// `hubs_kick` on the registry as of now: the section's read leaves on `jobs`. pub(super) fn hubs_kick(&mut self, sec: usize) { self.refill(); @@ -48,6 +65,7 @@ impl TestBrowse { /// `finish_browse_directory_job`) if the registry still holds the client its step decided on, /// and refused otherwise. Any other job stays on the outbox. Returns how many ran. pub(super) fn run_listing_jobs(&mut self) -> usize { + self.run_preference_jobs(); let mut ran = 0; for job in std::mem::take(&mut self.jobs) { let held = |sid: ServerId, key: plx_plex::plex::ClientKey| plx_plex::plex::client_for(sid) @@ -114,7 +132,7 @@ impl TestBrowse { let session = plx_plex::plex::session::peek(); self.refill(); let profile_key = plx_plex::plex::session::current_profile_key(); - let input = BrowseRosterInput { + let input = BrowseRosterInput { tenure: plx_plex::plex::session::tenure(), keys: &self.keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -178,7 +196,7 @@ impl TestBrowse { self.refill(); let session = plx_plex::plex::session::peek(); let profile_key = plx_plex::plex::session::current_profile_key(); - let input = BrowseRosterInput { + let input = BrowseRosterInput { tenure: plx_plex::plex::session::tenure(), keys: &self.keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -275,7 +293,9 @@ impl TestBrowse { /// The editor's commit, stepped with `session`. pub(super) fn apply_pins_with(&mut self, answers: &[(usize, bool)], session: &plx_plex::plex::session::Session) { self.state.profile_key = plx_plex::plex::session::current_profile_key(); + self.state.preference_writes.prepare(session, plx_plex::plex::session::tenure()); self.state.apply_pins_from(answers, session); + self.run_preference_jobs(); } /// A live discovery landing's section append, stepped with `session`. diff --git a/rust-modules/data/src/browse/browse_view_memory_tests.rs b/rust-modules/data/src/browse/browse_view_memory_tests.rs index b4c75a68b5..c21eb8d66b 100644 --- a/rust-modules/data/src/browse/browse_view_memory_tests.rs +++ b/rust-modules/data/src/browse/browse_view_memory_tests.rs @@ -128,6 +128,7 @@ fn a_chosen_sort_survives_a_restart() { select: false, choice: false, query: Some(crate::stores::browse::QueryEdit::Sort { key: "viewCount".into(), desc: true }), }, &ClientKeys::default(), &mut Vec::new())); + browse.run_preference_jobs(); pump_until_landed(&mut browse); let first_run: Vec = (0..2).map(|_| pms.requests.recv().unwrap()).collect(); assert!(first_run[1].contains("sort=viewCount%3Adesc"), "{}", first_run[1]); @@ -242,6 +243,7 @@ fn choosing_the_default_order_forgets_the_entry() { select: false, choice: false, query: Some(crate::stores::browse::QueryEdit::Sort { key: key.into(), desc }), }, &ClientKeys::default(), &mut Vec::new())); + browse.run_preference_jobs(); plx_base::storage_worker::drain_for_test(); }; let held = |browse: &TestBrowse| { @@ -398,6 +400,7 @@ fn switch_unwatched_on(browse: &mut TestBrowse, pms: &Pms) { select: false, choice: false, query: Some(crate::stores::browse::QueryEdit::Unwatched(true)), }, &ClientKeys::default(), &mut Vec::new())); + browse.run_preference_jobs(); } /// A saved sort whose restore FAILED transiently (the menu came back, the sorted re-ask did not) @@ -568,6 +571,7 @@ fn unwatched_and_genre_survive_a_restart() { crate::stores::browse::LibraryWork::Commit { select: false, choice: false, query: Some(edit), }, &ClientKeys::default(), &mut Vec::new())); + browse.run_preference_jobs(); } plx_base::storage_worker::drain_for_test(); drop(browse); diff --git a/rust-modules/data/src/browse/listing_jobs_tests.rs b/rust-modules/data/src/browse/listing_jobs_tests.rs index 5339e58c51..e016040b6c 100644 --- a/rust-modules/data/src/browse/listing_jobs_tests.rs +++ b/rust-modules/data/src/browse/listing_jobs_tests.rs @@ -754,7 +754,7 @@ fn a_failed_letters_read_keeps_the_rail_owed_and_is_retried_after_the_backoff() browse.refill(); let session = plx_plex::plex::session::peek(); let profile_key = plx_plex::plex::session::current_profile_key(); - let input = BrowseRosterInput { + let input = BrowseRosterInput { tenure: 0, keys: &browse.keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), profile_key: &profile_key, diff --git a/rust-modules/data/src/browse/mod.rs b/rust-modules/data/src/browse/mod.rs index 2301c64106..22e1701811 100644 --- a/rust-modules/data/src/browse/mod.rs +++ b/rust-modules/data/src/browse/mod.rs @@ -269,6 +269,8 @@ pub struct BrowseRosterInput<'a> { pub keys: &'a ClientKeys, pub session: &'a plx_plex::plex::session::Session, pub visible_generation: u64, + /// Revocation lease captured beside the session, before the machine window. + pub tenure: u64, pub settled: bool, pub profile_key: &'a str, } @@ -589,6 +591,7 @@ mod letters; pub mod listing_jobs; pub mod record; mod saved_view; +pub mod preferences_job; pub mod section_hubs; pub mod view; @@ -1043,35 +1046,16 @@ pub struct BrowseState { /// another's view. view_memory: plx_plex::plex::session::LibraryViews, recorded: Option, + preference_writes: preferences_job::Preferences, pending_pins: Option<(String, std::sync::Arc>)>, } /// Shared by a cloned Browse snapshot, so consuming a receipt never makes another clone /// mistake a successful write for a disconnected worker. Failed writes keep the local choice. /// -/// The poll and its use are split. [`observe`](Self::observe) polls the receipt once and latches -/// it; `Bridge::browse_session` is the only production caller, and it calls it BEFORE it reads the -/// session it hands the step. [`saved`](Self::saved) only reads the latch, so a step never pairs a -/// receipt it polled itself with a session read before it (the receipt is sent after the worker -/// installed the written session, so a read taken after seeing it contains the write). -struct PinWrite { - ticket: plx_base::storage_worker::TypedTicket, - saved: Option, -} -impl PinWrite { - fn observe(&mut self) { - if self.saved.is_none() { - self.saved = match self.ticket.try_recv() { - Ok(saved) => Some(saved), - Err(std::sync::mpsc::TryRecvError::Empty) => None, - Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(false), - }; - } - } - fn saved(&self) -> bool { - self.saved == Some(true) - } -} +/// Observation and use are split: the host observes the addressed completion BEFORE capturing +/// the session for the next step. Logic reads only that latch, never a worker's newer completion. +type PinWrite = preferences_job::Receipt; /// Worker-facing half of one Browse store. Every read's port holds this adapter, so a result /// can only land in the store that emitted the job even when another Bridge is alive. @@ -1163,6 +1147,7 @@ impl Default for BrowseState { view_memory: Default::default(), recorded: None, pending_pins: None, + preference_writes: Default::default(), session_generation: 0, current_sid: ServerId::UNSET, profile_key: String::new(), @@ -1175,6 +1160,7 @@ impl Default for BrowseState { impl BrowseState { /// Commands use the explicitly captured profile/current even if they do not walk the roster. pub(crate) fn observe_roster_context(&mut self, input: &BrowseRosterInput<'_>) { + self.preference_writes.prepare(input.session, input.tenure); if self.profile_key != input.profile_key { self.profile_key.clear(); self.profile_key.push_str(input.profile_key); @@ -1685,27 +1671,8 @@ impl BrowseState { if !machine.is_empty() { self.remembered.push((kind, machine.clone(), key)); } - let wire = kind.wire(); - plx_plex::plex::session::queue_update(move |current| { - let mut next = current.clone(); - let slot = match next - .prefs - .last_library - .iter_mut() - .find(|library| library.user == user) - { - Some(library) => library, - None => { - next.prefs.last_library.push(plx_plex::plex::session::LastLibrary { - user: user.clone(), - libs: Vec::new(), - extensions: Default::default(), - }); - next.prefs.last_library.last_mut()? - } - }; - slot.set(wire, &machine, key); - Some(next) + let _ = self.preference_writes.emit(&user, preferences_job::Edit::Library { + kind: kind.wire().to_owned(), machine, key, }); } /// Remember section `i`'s view across restarts (GitHub #278 the sort, #441 the rest) — the @@ -1756,20 +1723,7 @@ impl BrowseState { &snapshot, edit); self.view_memory.set(local); let user = self.profile_key.clone(); - plx_plex::plex::session::queue_update(move |current| { - let stored = current.views_for(&user).and_then(|views| views.get(&machine, key)); - let next_view = saved_view::merge(stored, &machine, key, &snapshot, edit); - let unchanged = match stored { - Some(stored) => *stored == next_view, - None => next_view.is_default(), - }; - if unchanged { - return None; - } - let mut next = current.clone(); - next.set_view_for(&user, next_view); - Some(next) - }); + let _ = self.preference_writes.emit(&user, preferences_job::Edit::View { machine, key, snapshot, field: edit }); } /// Apply section `i`'s remembered listing type and Unwatched switch, once, as the section is /// created. Neither needs the server to vouch for it — the type is checked against what the @@ -2302,6 +2256,8 @@ impl BrowseState { } } fn load_remembered(&mut self, session: &plx_plex::plex::session::Session, user: &str) { + let overlaid = self.preference_writes.overlay(session, user); + let session = &overlaid; if self.visited_user != user { self.visited.clear(); self.visited_user = user.to_owned(); @@ -2361,10 +2317,16 @@ impl BrowseState { /// before it reads the session it hands the step (`Bridge::browse_session`), so a write seen as /// saved is never paired with a session read from before it. pub fn observe_pin_write(&self) { + self.preference_writes.observe(); if let Some((_, write)) = &self.pending_pins { write.lock().unwrap_or_else(|e| e.into_inner()).observe(); } } + + pub(crate) fn take_preference_jobs(&mut self) -> Vec { + self.preference_writes.take_jobs() + } + pub(crate) fn has_preference_jobs(&self) -> bool { self.preference_writes.has_jobs() } /// A directory refresh must not replace the pending (or failed) local choice with the /// older persisted snapshot. A receipt observed before the caller read `session` takes the /// record from `session`, which contains the write; a receipt not yet observed answers with the @@ -2484,8 +2446,11 @@ impl BrowseState { -> Option { self.observe_pin_write(); let snapshot = plx_plex::plex::session::peek(); + self.preference_writes.prepare(&plx_plex::plex::session::peek(), plx_plex::plex::session::tenure()); self.profile_key = plx_plex::plex::session::current_profile_key(); - self.record_pins_from(asked, touched, &snapshot) + let result = self.record_pins_from(asked, touched, &snapshot); + test_support::run_preference_jobs(self.take_preference_jobs()); + result } /// Write this profile's answer down. `touched` is indexed like the section table and marks /// the rows the VIEWER answered — as the editor reported them, never as a comparison against @@ -2514,18 +2479,11 @@ impl BrowseState { (lib.machine_id.to_owned(), lib.key, lib.household, lib.household_type)).collect(); let touched = touched.to_vec(); let pending_user = user.clone(); - let ticket = plx_plex::plex::session::queue_update_ticket(move |session| { - let libraries: Vec<_> = owned.iter().map(|(machine_id, key, household, household_type)| - plx_plex::plex::pins::LibRef { machine_id, key: *key, household: *household, household_type: *household_type }).collect(); - let previous = session.pins_for(&user); - let answers = plx_plex::plex::pins::answers(&libraries, &on, &touched, previous); - let fresh = plx_plex::plex::pins::record(&user, asked, &libraries, &answers); - let merged = plx_plex::plex::pins::carry_forward(fresh, previous, &libraries); - let mut next = session.clone(); - next.set_pins_for(&user, merged); - Some(next) - }).ok()?; - self.pending_pins = Some((pending_user, std::sync::Arc::new(std::sync::Mutex::new(PinWrite { ticket, saved: None })))); + self.preference_writes.prepare_account(snapshot); + let receipt = self.preference_writes.emit(&user, preferences_job::Edit::Pins { + libraries: owned, on, touched, asked, + })?; + self.pending_pins = Some((pending_user, receipt)); self.recorded = Some(record.clone()); Some(record) } @@ -2533,8 +2491,10 @@ impl BrowseState { fn apply_pins(&mut self, answers: &[(usize, bool)]) { self.observe_pin_write(); let session = plx_plex::plex::session::peek(); + self.preference_writes.prepare(&plx_plex::plex::session::peek(), plx_plex::plex::session::tenure()); self.profile_key = plx_plex::plex::session::current_profile_key(); self.apply_pins_from(answers, &session); + test_support::run_preference_jobs(self.take_preference_jobs()); } /// The editor's one commit: apply the rows it ANSWERED, and record exactly those. /// @@ -2735,6 +2695,7 @@ impl BrowseState { self.reset_with(|| adapter.clear()); } pub fn sync_roster_owned(&mut self, input: &BrowseRosterInput<'_>) -> RosterSync { + self.preference_writes.prepare(input.session, input.tenure); let keys = input.keys; let session_changed = self.session_generation != input.visible_generation || self.roster_profile_key != input.profile_key || self.session_settled != input.settled; @@ -2889,6 +2850,7 @@ impl BrowseState { session: &plx_plex::plex::session::Session, jobs: &mut Vec, ) -> bool { + self.preference_writes.prepare_account(session); use crate::stores::browse::BrowseCmd; match cmd { BrowseCmd::Discovery(result) => { @@ -3606,7 +3568,7 @@ fn ensure_sections_with( ); let session = plx_plex::plex::session::peek(); let profile_key = plx_plex::plex::session::current_profile_key(); - let input = BrowseRosterInput { + let input = BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), profile_key: &profile_key, @@ -3984,7 +3946,7 @@ pub fn queue_discovery_for_owner_test( plx_plex::plex::server_facts_gen(), plx_plex::plex::server_ids(), plx_plex::plex::client_for, plx_plex::plex::server_facts, plx_plex::plex::server_probe_result); let session = plx_plex::plex::session::peek(); - let _ = state.sync_roster_owned(&BrowseRosterInput { + let _ = state.sync_roster_owned(&BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), profile_key: &plx_plex::plex::session::current_profile_key(), diff --git a/rust-modules/data/src/browse/preferences_job.rs b/rust-modules/data/src/browse/preferences_job.rs new file mode 100644 index 0000000000..b55b0d84b0 --- /dev/null +++ b/rust-modules/data/src/browse/preferences_job.rs @@ -0,0 +1,374 @@ +//! Browse preference writes: pure requests, addressed receipts, worker-side atomic merges. +use std::sync::{Arc, Mutex}; +use plx_machine::{job::{Job, Port}, machine::{Addr, MachineId, RequestId}}; +use plx_plex::plex::session::{self, Session}; +use super::saved_view::{self, ViewField, ViewSnapshot}; +#[derive(Clone, Default, PartialEq, Eq)] +struct Account { client_id: String, token: String } +impl Account { + fn of(s: &Session) -> Self { Self { client_id: s.client_id.clone(), token: s.account_token.clone() } } + fn matches(&self, s: &Session) -> bool { !self.client_id.is_empty() && self.client_id == s.client_id && self.token == s.account_token } +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum Edit { + Library { kind: String, machine: String, key: i64 }, + View { machine: String, key: i64, snapshot: ViewSnapshot, field: ViewField }, + Pins { libraries: Vec<(String, i64, bool, bool)>, on: Vec, touched: Vec, asked: bool }, +} +impl Edit { + fn merge(&self, current: &Session, user: &str) -> Option { + let mut next = current.clone(); + match self { + Self::Library { kind, machine, key } => { + if !next.prefs.last_library.iter().any(|slot| slot.user == user) { + next.prefs.last_library.push(session::LastLibrary { user: user.to_owned(), libs: Vec::new(), extensions: Default::default() }); + } + next.prefs.last_library.iter_mut().find(|slot| slot.user == user)?.set(kind, machine, *key); + } + Self::View { machine, key, snapshot, field } => { + let stored = current.views_for(user).and_then(|views| views.get(machine, *key)); + let view = saved_view::merge(stored, machine, *key, snapshot, *field); + if stored.map_or_else(|| view.is_default(), |stored| *stored == view) { return None; } + next.set_view_for(user, view); + } + Self::Pins { libraries, on, touched, asked } => { + let libraries: Vec<_> = libraries.iter().map(|(machine_id, key, household, household_type)| + plx_plex::plex::pins::LibRef { machine_id, key: *key, household: *household, household_type: *household_type }).collect(); + let previous = current.pins_for(user); + let answers = plx_plex::plex::pins::answers(&libraries, on, touched, previous); + let fresh = plx_plex::plex::pins::record(user, *asked, &libraries, &answers); + next.set_pins_for(user, plx_plex::plex::pins::carry_forward(fresh, previous, &libraries)); + } + } + Some(next) + } + fn replaces(&self, other: &Self) -> bool { + // Partial view edits must retain their order, including an earlier listing's sort. + match (self, other) { + (Self::Library { kind: a, .. }, Self::Library { kind: b, .. }) => a == b, + _ => false, + } + } +} +#[derive(Clone, PartialEq, Eq)] +pub struct BrowsePreferencesReq { account: Account, user: String, edit: Arc, tenure: u64 } +impl std::fmt::Debug for BrowsePreferencesReq { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("BrowsePreferencesReq").field("user", &self.user).field("edit", &self.edit).finish_non_exhaustive() } +} +impl BrowsePreferencesReq { + pub fn matches_account(&self, s: &Session) -> bool { self.account.matches(s) } + pub fn matches_tenure(&self, tenure: u64) -> bool { self.tenure == tenure } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WriteOutcome { NotStarted, Finished(bool) } +#[derive(Default)] +pub(super) struct Receipt { result: Option, observed: Option } +impl Receipt { + pub(super) fn observe(&mut self) { self.observed = self.result; } + pub(super) fn saved(&self) -> bool { self.observed == Some(WriteOutcome::Finished(true)) } +} +#[derive(Clone)] +pub struct BrowsePreferencesPort { addr: Addr, receipt: Arc> } +impl PartialEq for BrowsePreferencesPort { + fn eq(&self, other: &Self) -> bool { self.addr == other.addr && Arc::ptr_eq(&self.receipt, &other.receipt) } +} +impl std::fmt::Debug for BrowsePreferencesPort { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("BrowsePreferencesPort").field(&self.addr).finish() } +} +impl Port for BrowsePreferencesPort { + fn done(&self, addr: Addr, out: WriteOutcome) { + if addr != self.addr { return; } + let mut receipt = self.receipt.lock().unwrap_or_else(|e| e.into_inner()); + if receipt.result.is_none() { receipt.result = Some(out); } + } + fn refused(&self, addr: Addr) { self.done(addr, WriteOutcome::NotStarted); } +} +#[derive(Clone)] +struct Pending { account: Account, tenure: u64, user: String, edit: Arc, receipt: Arc> } +#[derive(Clone, Default)] +pub(super) struct Preferences { + account: Account, + tenure: u64, + next: u32, + jobs: Vec<(Job, BrowsePreferencesPort)>, + pending: Vec, +} +impl Preferences { + pub(super) fn prepare(&mut self, session: &Session, tenure: u64) { + self.prepare_account(session); + self.tenure = tenure; + } + + pub(super) fn prepare_account(&mut self, session: &Session) { if self.account.client_id != session.client_id || self.account.token != session.account_token { + self.account = Account::of(session); + } } + pub(super) fn emit(&mut self, user: &str, edit: Edit) -> Option>> { + if self.account.client_id.is_empty() { return None; } + self.next = self.next.wrapping_add(1); + let addr = Addr { to: MachineId::Store(crate::stores::StoreId::Browse.ord()), req: RequestId(self.next) }; + let receipt = Arc::new(Mutex::new(Receipt::default())); + let edit = Arc::new(edit); + let req = BrowsePreferencesReq { account: self.account.clone(), user: user.to_owned(), edit: Arc::clone(&edit), tenure: self.tenure }; + self.jobs.push((Job { addr, req }, BrowsePreferencesPort { addr, receipt: receipt.clone() })); + self.pending.retain(|p| !p.receipt.lock().unwrap_or_else(|e| e.into_inner()).saved() + && p.tenure == self.tenure + && (p.account != self.account || p.user != user || !edit.replaces(&p.edit))); + if !matches!(edit.as_ref(), Edit::Pins { .. }) { + self.pending.push(Pending { account: self.account.clone(), tenure: self.tenure, user: user.to_owned(), edit, receipt: receipt.clone() }); + } + Some(receipt) + } + pub(super) fn take_jobs(&mut self) -> Vec { + std::mem::take(&mut self.jobs).into_iter().map(|(job, port)| crate::stores::StoreJob::BrowsePreferences(job, port)).collect() + } + pub(super) fn has_jobs(&self) -> bool { !self.jobs.is_empty() } + pub(super) fn observe(&self) { + for pending in &self.pending { pending.receipt.lock().unwrap_or_else(|e| e.into_inner()).observe(); } + } + pub(super) fn overlay<'a>(&self, session: &'a Session, user: &str) -> std::borrow::Cow<'a, Session> { + let mut next = std::borrow::Cow::Borrowed(session); + for pending in self.pending.iter().filter(|p| p.user == user && p.tenure == self.tenure && p.account.matches(session) + && !p.receipt.lock().unwrap_or_else(|e| e.into_inner()).saved()) { + if let Some(merged) = pending.edit.merge(next.as_ref(), user) { next = std::borrow::Cow::Owned(merged); } + } + next + } +} +pub fn finish_browse_preferences_job(port: &BrowsePreferencesPort, addr: Addr, req: BrowsePreferencesReq) { + let tenure = req.tenure; + let saved = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut unchanged = false; + let write = session::update_guarded_with_outcome(|current| { + if !req.matches_account(current) || session::tenure() != tenure { return None; } + let next = req.edit.merge(current, &req.user); + unchanged = next.is_none(); + next + }, || session::tenure() == tenure); + unchanged || write.is_some_and(|write| write.outcome.persisted()) + })).unwrap_or(false); + port.done(addr, WriteOutcome::Finished(saved)); +} + +#[cfg(test)] +mod tests { + use super::*; + fn account() -> Session { Session { client_id: "preferences-client".into(), account_token: "preferences-account".into(), ..Default::default() } } + fn library(key: i64) -> Edit { Edit::Library { kind: super::super::SecKind::Movie.wire().into(), machine: "machine".into(), key } } + fn key(s: &Session, user: &str) -> i64 { s.prefs.last_library.iter().find(|l| l.user == user).unwrap().libs[0].key } + #[test] + fn preference_steps_emit_jobs_and_only_the_exact_address_can_settle_once() { + let mut writes = Preferences::default(); + writes.prepare(&account(), 0); + let step = plx_base::step::StepScope::enter(); + let receipt = writes.emit("viewer", library(7)).unwrap(); + let mut jobs = writes.take_jobs(); + assert_eq!(jobs.len(), 1); + let crate::stores::StoreJob::BrowsePreferences(job, port) = jobs.remove(0) else { panic!("preference job") }; + assert_eq!(job.addr.to, MachineId::Store(crate::stores::StoreId::Browse.ord())); + let wrong = Addr { req: RequestId(job.addr.req.0.wrapping_add(1)), ..job.addr }; + port.refused(wrong); + assert_eq!(receipt.lock().unwrap().result, None); + port.refused(job.addr); + port.done(job.addr, WriteOutcome::Finished(true)); + assert_eq!(receipt.lock().unwrap().result, Some(WriteOutcome::NotStarted)); + drop(step); + writes.observe(); + assert!(!receipt.lock().unwrap().saved()); + assert_eq!(key(&writes.overlay(&account(), "viewer"), "viewer"), 7); + } + + #[test] + fn pins_request_keeps_supplied_vector_allocations_without_retaining_an_overlay() { + let captured = account(); + let mut writes = Preferences::default(); + writes.prepare(&captured, 42); + let libraries = vec![("machine-a".to_owned(), 7, true, false), ("machine-b".to_owned(), 9, false, true)]; + let on = vec![true, false]; + let touched = vec![false, true]; + let library_rows = libraries.as_ptr(); + let machine = libraries[0].0.as_ptr(); + let on_rows = on.as_ptr(); + let touched_rows = touched.as_ptr(); + let expected = Edit::Pins { libraries: libraries.clone(), on: on.clone(), touched: touched.clone(), asked: true }; + let _ = writes.emit("viewer", Edit::Pins { libraries, on, touched, asked: true }); + let crate::stores::StoreJob::BrowsePreferences(job, _) = writes.take_jobs().remove(0) else { panic!("preference job") }; + let Edit::Pins { libraries, on, touched, asked } = job.req.edit.as_ref() else { panic!("pins") }; + assert_eq!(libraries.as_ptr(), library_rows); + assert_eq!(libraries[0].0.as_ptr(), machine); + assert_eq!(on.as_ptr(), on_rows); + assert_eq!(touched.as_ptr(), touched_rows); + assert!(*asked); + assert_eq!(job.req.edit.as_ref(), &expected); + assert!(writes.pending.is_empty(), "pins keep their existing separate receipt, not an overlay"); + let cloned = job.req.clone(); + assert!(Arc::ptr_eq(&job.req.edit, &cloned.edit)); + let mut equal = cloned; + equal.edit = Arc::new(expected); + assert_eq!(job.req, equal, "request equality compares edits, not allocation identity"); + assert!(!Arc::ptr_eq(&job.req.edit, &equal.edit)); + assert!(job.req.matches_account(&captured)); + assert!(job.req.matches_tenure(42)); + assert!(!job.req.matches_tenure(43)); + let debug = format!("{:?}", job.req); + assert!(!debug.contains(&captured.account_token)); + assert!(!debug.contains(&captured.client_id)); + } + + #[test] + fn library_and_view_requests_share_original_edits_with_the_retained_overlay() { + use super::super::LibraryType; + let captured = account(); + let mut writes = Preferences::default(); + writes.prepare(&captured, 42); + let snapshot = ViewSnapshot { listing: LibraryType::Primary, sort_resolved: true, genre_resolved: true, + sort: Some(("titleSort".into(), false)), unwatched: false, genre: Some("genre".into()) }; + for edit in [library(7), Edit::View { machine: "machine".into(), key: 7, snapshot, field: ViewField::Sort }] { + let original_machine = match &edit { + Edit::Library { machine, .. } | Edit::View { machine, .. } => machine.as_ptr(), + Edit::Pins { .. } => unreachable!(), + }; + let expected = edit.clone(); + let _ = writes.emit("viewer", edit); + let crate::stores::StoreJob::BrowsePreferences(job, _) = writes.take_jobs().remove(0) else { panic!("preference job") }; + let pending = writes.pending.last().unwrap(); + assert!(Arc::ptr_eq(&pending.edit, &job.req.edit)); + assert_eq!(job.req.edit.as_ref(), &expected); + let machine = match job.req.edit.as_ref() { + Edit::Library { machine, .. } | Edit::View { machine, .. } => machine, + Edit::Pins { .. } => unreachable!(), + }; + assert_eq!(machine.as_ptr(), original_machine); + assert!(job.req.matches_account(&captured)); + assert!(job.req.matches_tenure(42)); + let mut equal = job.req.clone(); + equal.edit = Arc::new(expected); + assert_eq!(job.req, equal); + assert!(!Arc::ptr_eq(&job.req.edit, &equal.edit)); + } + let overlaid = writes.overlay(&captured, "viewer"); + assert_eq!(key(&overlaid, "viewer"), 7); + assert_eq!(overlaid.views_for("viewer").unwrap().get("machine", 7).unwrap().primary_sort(), Some(("titleSort", false))); + } + + #[test] + fn real_browse_commands_with_a_captured_account_emit_all_three_writes_under_step_scope() { + use crate::stores::browse::{BrowseCmd, LibraryWork, QueryEdit, SectionAddress}; + use super::super::{BrowseAdapter, BrowseState, SecKind, a_source}; + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("browse-preference-step"); + let captured = account(); + let mut state = BrowseState::default(); + let mut source = a_source("machine", "", true); + let sid = plx_plex::plex::ServerId::from_raw(7); source.sid = sid; + state.sources.push(source); + state.append_sections_for_test(0, vec![(1, "Movies".into(), SecKind::Movie)]); + state.sections[0].pinned = true; + state.profile_key = "captured-profile".into(); + let target = SectionAddress { epoch: state.table_epoch(), sid, section: 1 }; + let adapter = Arc::new(BrowseAdapter::default()); + let keys = plx_plex::plex::ClientKeys::default(); + let mut other_jobs = Vec::new(); + state.preference_writes.prepare(&captured, session::tenure()); + let step = plx_base::step::StepScope::enter(); + assert!(state.run_owned(&adapter, BrowseCmd::Addressed { target, work: LibraryWork::Commit { + select: true, choice: true, query: Some(QueryEdit::Unwatched(true)), + } }, &keys, &captured, &mut other_jobs)); + assert!(state.run_owned(&adapter, BrowseCmd::ApplyPins(vec![(0, true)]), &keys, &captured, &mut other_jobs)); + let jobs = state.take_preference_jobs(); + assert_eq!(jobs.len(), 3, "library, query and pin persistence all leave as jobs"); + assert!(other_jobs.is_empty()); + assert!(state.states[0].unwatched, "the UI applies its edit before persistence"); + assert!(state.pending_pins.is_some()); + for job in jobs { + let crate::stores::StoreJob::BrowsePreferences(job, port) = job else { panic!("preference job") }; + assert_eq!(job.req.user, "captured-profile"); + assert!(job.req.matches_account(&captured)); + port.refused(job.addr); + } + drop(step); + } + #[test] + fn newer_choices_and_other_profiles_survive_old_completions_and_stale_captures() { + let session = account(); + let mut writes = Preferences::default(); + writes.prepare(&session, 0); + writes.emit("viewer-a", library(1)).unwrap(); + writes.emit("viewer-b", library(2)).unwrap(); + writes.emit("viewer-a", library(3)).unwrap(); + let jobs = writes.take_jobs(); + assert_eq!(jobs.len(), 3); + let crate::stores::StoreJob::BrowsePreferences(job, port) = &jobs[0] else { panic!("preference job") }; + port.done(job.addr, WriteOutcome::Finished(true)); + writes.observe(); + assert_eq!(key(&writes.overlay(&session, "viewer-a"), "viewer-a"), 3); + assert_eq!(key(&writes.overlay(&session, "viewer-b"), "viewer-b"), 2); + let crate::stores::StoreJob::BrowsePreferences(job, port) = &jobs[2] else { panic!("preference job") }; + port.done(job.addr, WriteOutcome::Finished(true)); + assert_eq!(key(&writes.overlay(&session, "viewer-a"), "viewer-a"), 3, + "a completed worker does not pair itself with an older captured session"); + writes.observe(); + assert!(writes.overlay(&session, "viewer-a").prefs.last_library.is_empty()); + let mut replacement = session.clone(); replacement.account_token = "replacement".into(); + assert!(writes.overlay(&replacement, "viewer-b").prefs.last_library.is_empty()); + } + + #[test] + fn pending_view_edits_merge_in_order_across_a_listing_change() { + use super::super::LibraryType; + let stored = account(); + let mut writes = Preferences::default(); writes.prepare(&stored, 0); + let primary = ViewSnapshot { listing: LibraryType::Primary, sort_resolved: true, genre_resolved: true, + sort: Some(("viewCount".into(), true)), unwatched: false, genre: None }; + let collections = ViewSnapshot { listing: LibraryType::Collections, sort_resolved: false, + sort: None, ..primary.clone() }; + let collection_sort = ViewSnapshot { sort_resolved: true, sort: Some(("titleSort".into(), false)), ..collections.clone() }; + for (snapshot, field) in [(primary, ViewField::Sort), (collections, ViewField::Listing), (collection_sort, ViewField::Sort)] { + let _ = writes.emit("viewer", Edit::View { machine: "machine".into(), key: 1, snapshot, field }); + } + let overlaid = writes.overlay(&stored, "viewer"); + let view = overlaid.views_for("viewer").unwrap().get("machine", 1).unwrap(); + assert_eq!(view.primary_sort(), Some(("viewCount", true)), "the unresolved listing must merge over earlier pending edits"); + assert_eq!(view.listing_sort, "titleSort"); + } + #[test] + fn worker_merges_the_original_profile_over_current_authority_without_losing_other_edits() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("browse-preference-merge"); + let stored = account(); + session::save(&stored); + let mut writes = Preferences::default(); writes.prepare(&stored, session::tenure()); + let _ = writes.emit("original-profile", library(1)); + let _ = writes.emit("original-profile", library(2)); + session::save(&stored.with_auto_sign_in(true)); + for job in writes.take_jobs() { + let crate::stores::StoreJob::BrowsePreferences(job, port) = job else { panic!("preference job") }; + assert!(job.req.matches_tenure(session::tenure())); + finish_browse_preferences_job(&port, job.addr, job.req); + } + let persisted = session::peek(); + assert_eq!(key(&persisted, "original-profile"), 2); + assert!(persisted.auto_sign_in(), "the worker merges, never replaces its captured record"); + writes.observe(); + assert!(writes.pending.iter().all(|p| p.receipt.lock().unwrap().saved())); + } + #[test] + fn an_obsolete_account_or_revocation_lease_never_writes() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("browse-preference-stale"); + let stored = account(); session::save(&stored); + let mut writes = Preferences::default(); writes.prepare(&stored, session::tenure()); + let receipt = writes.emit("viewer", library(4)).unwrap(); + let crate::stores::StoreJob::BrowsePreferences(mut job, port) = writes.take_jobs().remove(0) else { panic!("preference job") }; + job.req.tenure = session::tenure().wrapping_add(1); + finish_browse_preferences_job(&port, job.addr, job.req); + assert_eq!(receipt.lock().unwrap().result, Some(WriteOutcome::Finished(false))); + assert!(session::peek().prefs.last_library.is_empty()); + let receipt = writes.emit("viewer", library(5)).unwrap(); + let crate::stores::StoreJob::BrowsePreferences(job, port) = writes.take_jobs().remove(0) else { panic!("preference job") }; + assert!(job.req.matches_tenure(session::tenure())); + let mut replacement = stored; replacement.account_token = "other-account".into(); session::save(&replacement); + finish_browse_preferences_job(&port, job.addr, job.req); + assert_eq!(receipt.lock().unwrap().result, Some(WriteOutcome::Finished(false))); + assert!(session::peek().prefs.last_library.is_empty()); + } +} diff --git a/rust-modules/data/src/browse/roster_input_tests.rs b/rust-modules/data/src/browse/roster_input_tests.rs index 901b554283..30821d9746 100644 --- a/rust-modules/data/src/browse/roster_input_tests.rs +++ b/rust-modules/data/src/browse/roster_input_tests.rs @@ -13,7 +13,7 @@ fn fill(keys: &mut ClientKeys, current: ServerId, facts: Option<&'static plx_ple |_| None, |_| facts, |_| None); } fn input<'a>(keys: &'a ClientKeys, session: &'a plx_plex::plex::session::Session) -> BrowseRosterInput<'a> { - BrowseRosterInput { keys, session, visible_generation: 0, settled: false, profile_key: "profile" } + BrowseRosterInput { tenure: 0, keys, session, visible_generation: 0, settled: false, profile_key: "profile" } } #[test] diff --git a/rust-modules/data/src/browse/saved_view.rs b/rust-modules/data/src/browse/saved_view.rs index b333d6d137..1d82acc858 100644 --- a/rust-modules/data/src/browse/saved_view.rs +++ b/rust-modules/data/src/browse/saved_view.rs @@ -28,7 +28,7 @@ pub(super) enum ViewField { } /// The section's live state, as far as the record cares. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(super) struct ViewSnapshot { /// The listing shown. pub(super) listing: LibraryType, diff --git a/rust-modules/data/src/browse/section_hubs_job_tests.rs b/rust-modules/data/src/browse/section_hubs_job_tests.rs index 011385359d..a79aaa2e94 100644 --- a/rust-modules/data/src/browse/section_hubs_job_tests.rs +++ b/rust-modules/data/src/browse/section_hubs_job_tests.rs @@ -198,7 +198,7 @@ fn a_read_out_with_no_claim_wakes_the_pump_that_settles_it() { ); let session = plx_plex::plex::session::peek(); let profile_key = plx_plex::plex::session::current_profile_key(); - let input = BrowseRosterInput { + let input = BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), profile_key: &profile_key, diff --git a/rust-modules/data/src/browse/view_roster_tests.rs b/rust-modules/data/src/browse/view_roster_tests.rs index 9fcc908373..a1dceb25e3 100644 --- a/rust-modules/data/src/browse/view_roster_tests.rs +++ b/rust-modules/data/src/browse/view_roster_tests.rs @@ -17,7 +17,7 @@ fn directory_noop_reuses_arc_and_facts_change_replaces_it_without_mutating_old_r let session = Default::default(); let mut state = BrowseState::default(); let mut snapshot = DirectorySnapshot::default(); - let input = BrowseRosterInput { keys: &keys, session: &session, visible_generation: 0, settled: false, profile_key: "p" }; + let input = BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation: 0, settled: false, profile_key: "p" }; state.sync_roster_owned(&input); snapshot.capture_from(&mut state, &keys); let old = snapshot.clone(); @@ -29,7 +29,7 @@ fn directory_noop_reuses_arc_and_facts_change_replaces_it_without_mutating_old_r assert!(snapshot.same_publication(&old)); } keys.refill_roster(sid, 1, 1, [sid], |_| None, |_| Some(second), |_| None); - state.sync_roster_owned(&BrowseRosterInput { keys: &keys, session: &session, visible_generation: 0, settled: false, profile_key: "p" }); + state.sync_roster_owned(&BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation: 0, settled: false, profile_key: "p" }); snapshot.capture_from(&mut state, &keys); assert_ne!(Arc::as_ptr(&snapshot.data), allocation); assert_eq!(old.view().sources()[0].1.name, "Before"); @@ -40,7 +40,7 @@ fn directory_noop_reuses_arc_and_facts_change_replaces_it_without_mutating_old_r assert!(!state.sources()[0].owned); let changed = snapshot.clone(); let generation = state.source_list_gen(); - assert!(!state.sync_roster_owned(&BrowseRosterInput { keys: &keys, session: &session, visible_generation: 0, settled: false, profile_key: "p" }).changed); + assert!(!state.sync_roster_owned(&BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation: 0, settled: false, profile_key: "p" }).changed); snapshot.capture_from(&mut state, &keys); assert_eq!(state.source_list_gen(), generation); assert!(snapshot.same_publication(&changed)); diff --git a/rust-modules/data/src/captured_store_fixture.rs b/rust-modules/data/src/captured_store_fixture.rs new file mode 100644 index 0000000000..b1fdaff9f2 --- /dev/null +++ b/rust-modules/data/src/captured_store_fixture.rs @@ -0,0 +1,12 @@ +//! Value-only fixtures: scripted observations never mutate the process registry. +use plx_plex::plex::{ClientFacts, ClientKey, ClientKeys, ServerFacts, ServerId}; +pub(crate) fn key(token: u32) -> ClientKey { ClientKey { instance: 101, token, grant: 1 } } +pub(crate) fn roster(rows: &[(u16, Option, &str)], generation: u32, facts: u32) -> ClientKeys { + ClientKeys::captured(rows.first().map_or(ServerId::UNSET, |row| ServerId::from_raw(row.0)), generation, facts, + rows.iter().map(|&(raw, key, handle)| { + let described = Box::leak(Box::new(ServerFacts { name: format!("script-{raw}"), handle: handle.into(), + owned: handle.is_empty(), home: false, owner_id: 42 })); + (ServerId::from_raw(raw), key, ClientFacts { machine_id: format!("script-{raw}"), + described: Some(described), source: Some((None, None)), stream_allowed: false }) + })) +} diff --git a/rust-modules/data/src/catalog.rs b/rust-modules/data/src/catalog.rs index d099fa63fb..e47fe9fb84 100644 --- a/rust-modules/data/src/catalog.rs +++ b/rust-modules/data/src/catalog.rs @@ -11,7 +11,7 @@ use crate::watchlist::model::Kind; use crate::watchlist::WatchlistAuth; -use plx_plex::plex::account::AccountClient; + use plx_plex::plex::watchlist::{CatalogItem, WatchKind, WatchlistError}; /// Is the title on the signed-in profile's Watchlist? Read from `WatchlistStore` (never fetched by @@ -92,20 +92,9 @@ pub trait CatalogIo: Send + Sync { fn today(&self) -> Option; } -/// The production seam: libcurl through `plex::watchlist`, as the identity the job carries. -pub struct LiveCatalogIo; - -impl CatalogIo for LiveCatalogIo { - fn fetch(&self, auth: &WatchlistAuth, hex: &str) -> Result { - let client = AccountClient::new(&auth.client_id, Some(&auth.credential)); - let mut transport = client.watchlist_transport(); - let answer = client.catalog_item(hex, &mut transport); - answer - } - fn today(&self) -> Option { - ::today(&crate::watchlist::LiveIo) - } -} +#[path = "catalog_ports.rs"] +mod ports; +pub use ports::LiveCatalogIo; /// The page's record from the service's item. The page opens for a title no reachable server /// holds, so a released title reads "not on any server" and one whose date is still ahead reads diff --git a/rust-modules/data/src/catalog_ports.rs b/rust-modules/data/src/catalog_ports.rs new file mode 100644 index 0000000000..94bf32ed74 --- /dev/null +++ b/rust-modules/data/src/catalog_ports.rs @@ -0,0 +1,17 @@ +//! Catalog worker transport; the store never calls these methods while stepping. +use crate::catalog::CatalogIo; +use crate::watchlist::WatchlistAuth; +use plx_plex::plex::account::AccountClient; +use plx_plex::plex::watchlist::{CatalogItem, WatchlistError}; +pub struct LiveCatalogIo; +impl CatalogIo for LiveCatalogIo { + fn fetch(&self, auth: &WatchlistAuth, hex: &str) -> Result { + let client = AccountClient::new(&auth.client_id, Some(&auth.credential)); + let mut transport = client.watchlist_transport(); + client.catalog_item(hex, &mut transport) + } + fn today(&self) -> Option { + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(); + Some(crate::watchlist::ymd_of_unix_days((secs / 86_400) as i64)) + } +} diff --git a/rust-modules/data/src/hudpacks.rs b/rust-modules/data/src/hudpacks.rs index d491db4ca9..ef659fb1d0 100644 --- a/rust-modules/data/src/hudpacks.rs +++ b/rust-modules/data/src/hudpacks.rs @@ -1,3 +1,4 @@ +#![deny(clippy::wildcard_enum_match_arm)] //! The player-HUD package store: which packages are installed, which one is selected, and the rules //! that admit a new one (`docs/hud-plugins.md`, "Storage per install mode", "Trust and safety"). //! @@ -519,6 +520,9 @@ impl Record { Record { sha, source, at, package_format: package_format.into(), hud_format: hud_format.into(), from: None } } + /// Move the previous operation out so its payload and cancellation debt stay owned. + + /// This record with the development source `from` names, when a record of `self.source` may carry one. fn from_dev_source(mut self, from: Option<&address::Address>) -> Self { self.from = from.filter(|address| self.source == Source::Address && address.dev_source()).cloned(); @@ -688,134 +692,11 @@ impl HudStore { } } - // -------- readers -------- - - /// The current gallery view, including dated cache status and revocation reasons. - pub fn catalog(&self) -> &catalog::Snapshot { self.catalog.snapshot() } - - /// Whether a listing, install or removal is running (installing and removing wait for the idle). - pub fn busy(&self) -> bool { - !matches!(self.op, Op::Idle) - } - - /// The selection as the profile holds it; it may name a package that is gone or cannot load. - pub fn selected(&self) -> &str { - &self.selected - } - - /// What a playback starts with: the selection when it is listed and loadable, else the built-in. - pub fn resolved(&self) -> &str { - if self.selected != BUILTIN_CLASSIC - && self.winners().get(self.selected.as_str()).is_some_and(|w| w.loaded.loadable.is_ok() && self.catalog.snapshot().revoked(w.record.sha).is_none()) - { - &self.selected - } else { - BUILTIN_CLASSIC - } - } - - /// The package list: the built-in first, then one row per installed id, by id. - pub fn entries(&self) -> Vec { - let mut out = vec![Entry { - id: BUILTIN_CLASSIC.to_string(), - meta: None, - sha: None, - source: None, - trust: Trust::BuiltIn, - loadable: Ok(()), - until_restart: false, - selected: self.selected == BUILTIN_CLASSIC, - dev_source: None, - }]; - for (id, win) in self.winners() { - out.push(Entry { - id: id.to_string(), - meta: Some(win.loaded.meta.clone()), - sha: Some(win.record.sha), - source: Some(win.record.source), - trust: win.record.source.trust(), - loadable: if self.catalog.snapshot().revoked(win.record.sha).is_some() { Err(Unloadable::Revoked) } else { win.loaded.loadable }, - until_restart: win.loaded.volatile, - selected: self.selected == id, - dev_source: win.record.from.clone(), - }); - } - out - } - - /// Whether a fetch from an address is in flight: waiting for the network, or for the validator's verdict on what - /// came back. An offer waiting for the viewer is not (it is [`offer`](Self::offer)). - pub fn fetching(&self) -> bool { - matches!( - &self.op, - Op::Installing(Installing { step: Step::Fetching { .. }, .. }) - | Op::Installing(Installing { step: Step::Validating(Offer { from: Some(_), .. }), .. }) - ) - } - - /// The validated fetch waiting for the viewer's answer, if any: [`HudEvent::InstallOffer`] installs - /// it, [`HudEvent::DeclineOffer`] drops it, and a `Refresh` ends it with [`Notice::NotWritten`]. - pub fn offer(&self) -> Option { - match &self.op { - Op::Installing(Installing { step: Step::Offered { offer, meta }, .. }) => Some(OfferView { - sha: offer.sha, - meta: meta.clone(), - source: offer.source, - from: offer.from.clone(), - }), - _ => None, - } - } - - /// The files found in `drop/`, one row per distinct sha, with whether installing them would be - /// accepted now. - pub fn drops(&self) -> Vec { - let mut seen = Vec::new(); - let mut out = Vec::new(); - for dropped in &self.drops { - match &dropped.found { - Found::TooLarge => out.push(DropFile { - name: dropped.name.clone(), - sha: None, - meta: None, - status: Err(Refusal::TooLarge), - }), - Found::Parsed { sha, verdict } => { - if seen.contains(sha) { - continue; - } - seen.push(*sha); - let meta = match verdict { - Verdict::Loadable(meta) | Verdict::Unloadable(meta, _) => Some(meta.clone()), - Verdict::Invalid => None, - }; - out.push(DropFile { - name: dropped.name.clone(), - sha: Some(*sha), - meta, - status: self.judge(*sha, verdict).map(|_| ()), - }); - } - } - } - out - } - - // -------- the one writer -------- - - /// The one writer. The table is in the module doc; a pair it does not list answers - /// [`Handled::No`] and changes nothing. - pub fn step(&mut self, ev: HudEvent, fx: &mut Vec) -> Handled { - let handled = self.reduce(ev, fx); - // The cache can land before the installed-pack listing: apply the same rule after either. - if self.winners().get(self.selected.as_str()).is_some_and(|w| self.catalog.snapshot().revoked(w.record.sha).is_some()) { - self.selected = BUILTIN_CLASSIC.into(); - fx.push(HudEffect::Selection { id: self.selected.clone() }); - } - handled - } + /// Move the old operation out with its payload and cancellation debt. +fn transition(&mut self, ev: HudEvent, fx: &mut Vec) -> Handled { +let handled = 'reduce: { +let (ev,): (HudEvent,) = (ev,); - fn reduce(&mut self, ev: HudEvent, fx: &mut Vec) -> Handled { match ev { HudEvent::Catalog(event) => { let mut work = Vec::new(); @@ -828,312 +709,316 @@ impl HudStore { Op::Installing(Installing { step: Step::Fetching { expected: Some(p), .. }, .. }) => p.sha() == sha, Op::Installing(Installing { step: Step::Validating(offer) | Step::Offered { offer, .. }, .. }) => offer.source == Source::Registry && offer.sha == sha && offer.now.is_none(), - _ => false, + Op::Idle | Op::Listing(_) | Op::Installing(_) | Op::Removing(_) => false, }; - if cancels { self.op = Op::Idle; Handled::Yes } else { Handled::No } + if cancels { drop(std::mem::replace(&mut self.op, Op::Idle)); Handled::Yes } else { Handled::No } } HudEvent::FetchRegistry { sha, app, language } => { - if self.busy() || self.catalog.snapshot().revoked(sha).is_some() { return Handled::No } + if self.busy() || self.catalog.snapshot().revoked(sha).is_some() { break 'reduce Handled::No } let Some(package) = self.catalog.snapshot().index.as_ref().and_then(|i| i.entries.iter().find(|p| p.sha() == sha)) - .filter(|p| p.compatible(&app, &language, self.setup.max_pack_bytes)).cloned() else { return Handled::No }; - let Ok(address) = address::parse(&package.url) else { return Handled::No }; - let tag = self.tag(); + .filter(|p| p.compatible(&app, &language, self.setup.max_pack_bytes)).cloned() else { break 'reduce Handled::No }; + let Ok(address) = address::parse(&package.url) else { break 'reduce Handled::No }; + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; fx.push(HudEffect::FetchRegistry { tag, package: package.clone(), max_bytes: self.setup.max_pack_bytes }); - self.op = Op::Installing(Installing { tag, step: Step::Fetching { address, expected: Some(package) } }); + drop(std::mem::replace(&mut self.op, Op::Installing(Installing { tag, step: Step::Fetching { address, expected: Some(package) } }))); Handled::Yes } HudEvent::Refresh { setup, selected } => { // Always taken: it is how a store whose runner lost an answer recovers. Whatever it // displaces wrote atomically and put the index last, so disk is consistent, and the // answers the displaced work is still owed carry a stale tag. - self.begin_listing(setup, selected, fx); + { +let (setup, selected,): (Setup, String,) = (setup, selected,); + + let stray = { + + let at = |candidates: &[Candidate], dir: usize, sha: Sha| candidates.get(dir).map(|c| (c.dir.clone(), sha)); + let mut stray = Vec::new(); + match std::mem::replace(&mut self.op, Op::Idle) { + Op::Idle | Op::Listing(_) => {} + Op::Installing(Installing { step, .. }) => { + let sha = match step { + Step::Reading { sha, .. } => Some(sha), + // A fetch that has not answered has no bytes, so no sha. + Step::Fetching { .. } => None, + Step::Validating(offer) | Step::Offered { offer, .. } => Some(offer.sha), + Step::Writing { offer, dir, what, .. } => { + // The pack is down or on its way. If the index write reached the disk the id's + // old pack is the unlisted one, if not the new one is: only a re-read says. + stray.extend(at(&self.setup.candidates, dir, offer.sha)); + if let Write::Index { replaced: Some(old), .. } = what { + stray.extend(at(&self.setup.candidates, dir, old).filter(|_| old != offer.sha)); + } + Some(offer.sha) + } + }; + Self::notice(fx, Notice::NotWritten { sha }); + } + Op::Removing(Removing { id, flight, .. }) => { + if let Some(Rewrite { dir, gone, .. }) = flight { + // The rewrite may have reached the disk: the packs it unlisted are the stray ones. + stray.extend(gone.into_iter().filter_map(|sha| at(&self.setup.candidates, dir, sha))); + } + Self::notice(fx, Notice::RemoveIncomplete { id }); + } + } + stray + +}; + let n = setup.candidates.len(); + self.dirs = vec![Dir::default(); n]; + self.packs.clear(); + self.drops.clear(); + self.selected = if selected.is_empty() { BUILTIN_CLASSIC.to_string() } else { selected }; + self.setup = setup; + let mut todo: VecDeque = (0..n).map(Job::Index).collect(); + todo.push_back(Job::Plan); + todo.extend((0..n).map(Job::Scan)); + // Issue the next listing request, or finish. + let next = 'advance: { +let (mut listing,): (Listing,) = (Listing { todo, flight: None, stray },); + + while let Some(job) = listing.todo.pop_front() { + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; + let effect = match &job { + Job::Plan => { + self.reclaim(std::mem::take(&mut listing.stray), fx); + for planned in self.plan_packs().into_iter().rev() { + listing.todo.push_front(planned); + } + continue; + } + Job::Index(dir) => self.read(tag, *dir, INDEX_FILE.to_string()), + Job::Pack { sha, dirs } => match dirs.front() { + Some(dir) => self.read(tag, *dir, pack_rel(*sha)), + None => continue, + }, + Job::Scan(dir) => HudEffect::ScanDir { tag, at: self.loc(*dir, DROP_DIR.to_string()) }, + Job::Drop { dir, name } => self.read(tag, *dir, format!("{DROP_DIR}/{name}")), + }; + fx.push(effect); + listing.flight = Some(Flight { tag, job, stage: Stage::Io }); + break 'advance Op::Listing(listing); + } + Op::Idle + +}; + drop(std::mem::replace(&mut self.op, next)); + +}; Handled::Yes } - HudEvent::Selected { id } => self.select(id, fx), + HudEvent::Selected { id } => 'select: { +let (id,): (String,) = (id,); + + let allowed = id == BUILTIN_CLASSIC + || self.winners().get(id.as_str()).is_some_and(|w| w.loaded.loadable.is_ok() && self.catalog.snapshot().revoked(w.record.sha).is_none()); + if !allowed { + break 'select Handled::No; + } + self.selected = id.clone(); + fx.push(HudEffect::Selection { id }); + Handled::Yes + +}, HudEvent::Install { bytes, source, now } => { if self.busy() { - return Handled::No; + break 'reduce Handled::No; } let sha = Sha::of(&bytes); if bytes.len() > self.setup.max_pack_bytes { fx.push(HudEffect::Notice(Notice::Refused { sha, reason: Refusal::TooLarge })); } else { - self.op = self.validate(Offer { sha, source, now: Some(now), from: None, bytes: bytes.into(), expected: None }, fx); + // Ask the runner whether these bytes are a package this app can run. + let next = { +let (offer,): (Offer,) = (Offer { sha, source, now: Some(now), from: None, bytes: bytes.into(), expected: None },); + + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; + fx.push(HudEffect::Validate { tag, sha: offer.sha, bytes: offer.bytes.clone() }); + Op::Installing(Installing { tag, step: Step::Validating(offer) }) + +}; + drop(std::mem::replace(&mut self.op, next)); } Handled::Yes } HudEvent::Fetch { address } => { if self.busy() { - return Handled::No; + break 'reduce Handled::No; } - let tag = self.tag(); + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; fx.push(HudEffect::Fetch { tag, address: address.clone(), max_bytes: self.setup.max_pack_bytes }); - self.op = Op::Installing(Installing { tag, step: Step::Fetching { address, expected: None } }); + drop(std::mem::replace(&mut self.op, Op::Installing(Installing { tag, step: Step::Fetching { address, expected: None } }))); Handled::Yes } HudEvent::InstallOffer { sha, now } => match std::mem::replace(&mut self.op, Op::Idle) { Op::Installing(Installing { step: Step::Offered { mut offer, meta }, .. }) if offer.sha == sha => { if self.catalog.snapshot().revoked(sha).is_some() { Self::notice(fx, Notice::Refused { sha, reason: Refusal::Unloadable(Unloadable::Revoked) }); - return Handled::Yes; + break 'reduce Handled::Yes; } offer.now = Some(now); - self.op = self.write_pack(offer, meta, 0, fx); + // Write the pack to candidate `dir`; with no candidate left, nothing was installed. + let next = 'write_pack: { +let (offer, meta, dir,): (Offer, Meta, usize,) = (offer, meta, 0,); + + // A candidate whose index is read-only cannot list the new package, so it is not a candidate. + let Some(dir) = (dir..self.dirs.len()).find(|d| self.dirs[*d].access == Access::Writable) else { + Self::notice(fx, Notice::NotWritten { sha: Some(offer.sha) }); + break 'write_pack Op::Idle; + }; + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; + fx.push(HudEffect::WriteFile { + tag, + at: self.loc(dir, pack_rel(offer.sha)), + bytes: offer.bytes.clone(), + }); + Op::Installing(Installing { tag, step: Step::Writing { offer, meta, dir, what: Write::Pack } }) + +}; + drop(std::mem::replace(&mut self.op, next)); Handled::Yes } - other => { - self.op = other; + other @ (Op::Idle | Op::Listing(_) | Op::Installing(_) | Op::Removing(_)) => { + drop(std::mem::replace(&mut self.op, other)); Handled::No } }, HudEvent::DeclineOffer { sha } => match std::mem::replace(&mut self.op, Op::Idle) { Op::Installing(Installing { step: Step::Offered { offer, .. }, .. }) if offer.sha == sha => Handled::Yes, - other => { - self.op = other; + other @ (Op::Idle | Op::Listing(_) | Op::Installing(_) | Op::Removing(_)) => { + drop(std::mem::replace(&mut self.op, other)); Handled::No } }, HudEvent::InstallDrop { sha, now } => { if self.busy() { - return Handled::No; + break 'reduce Handled::No; } let Some((dir, name)) = self.drops.iter().find_map(|d| match &d.found { Found::Parsed { sha: s, .. } if *s == sha => Some((d.dir, d.name.clone())), - _ => None, + Found::TooLarge | Found::Parsed { .. } => None, }) else { - return Handled::No; - }; - let tag = self.tag(); - fx.push(self.read(tag, dir, format!("{DROP_DIR}/{name}"))); - self.op = Op::Installing(Installing { tag, step: Step::Reading { sha, now } }); - Handled::Yes - } - HudEvent::Removed { id } => self.begin_removal(id, fx), - result @ (HudEvent::Scanned { .. } - | HudEvent::Read { .. } - | HudEvent::Validated { .. } - | HudEvent::Written { .. } - | HudEvent::Fetched { .. }) => { - let (op, handled) = match std::mem::replace(&mut self.op, Op::Idle) { - Op::Idle => (Op::Idle, Handled::No), - Op::Listing(listing) => self.listing_result(listing, result, fx), - Op::Installing(installing) => self.installing_result(installing, result, fx), - Op::Removing(removing) => self.removing_result(removing, result, fx), + break 'reduce Handled::No; }; - self.op = op; - handled - } - } - } - - // -------- helpers -------- + let tag = { - fn tag(&mut self) -> Tag { self.tags = self.tags.wrapping_add(1); Tag(self.tags) - } - fn loc(&self, dir: usize, rel: String) -> Loc { - Loc { root: self.setup.candidates.get(dir).map(|c| c.dir.clone()).unwrap_or_default(), rel } - } +}; + fx.push(self.read(tag, dir, format!("{DROP_DIR}/{name}"))); + drop(std::mem::replace(&mut self.op, Op::Installing(Installing { tag, step: Step::Reading { sha, now } }))); + Handled::Yes + } + HudEvent::Removed { id } => 'begin_removal: { +let (id,): (String,) = (id,); - fn read(&self, tag: Tag, dir: usize, rel: String) -> HudEffect { - HudEffect::ReadFile { tag, at: self.loc(dir, rel), max_bytes: self.setup.max_pack_bytes } - } - - fn volatile(&self, dir: usize) -> bool { - self.setup.candidates.get(dir).is_some_and(|c| c.volatile) - } - - fn select(&mut self, id: String, fx: &mut Vec) -> Handled { - let allowed = id == BUILTIN_CLASSIC - || self.winners().get(id.as_str()).is_some_and(|w| w.loaded.loadable.is_ok() && self.catalog.snapshot().revoked(w.record.sha).is_none()); - if !allowed { - return Handled::No; + if self.busy() || id == BUILTIN_CLASSIC { + break 'begin_removal Handled::No; } - self.selected = id.clone(); - fx.push(HudEffect::Selection { id }); - Handled::Yes - } - - /// The installed package of each id: across candidates the higher version wins, and on a tie the - /// earlier candidate. An entry whose pack was not read, or whose pack declares another id, is not a - /// package. - fn winners(&self) -> BTreeMap<&str, Winner<'_>> { - let mut best: BTreeMap<&str, Winner<'_>> = BTreeMap::new(); - for dir in &self.dirs { - for (id, record) in &dir.index { - let Some(loaded) = self.packs.get(&record.sha) else { continue }; - if loaded.meta.id != *id || loaded.meta.package_format != record.package_format || loaded.meta.hud_format != record.hud_format { - continue; - } - let win = Winner { record, loaded }; - let better = best.get(id.as_str()).map_or(true, |have| { - Semver::parse(&win.loaded.meta.version) > Semver::parse(&have.loaded.meta.version) - }); - if better { - best.insert(id.as_str(), win); - } - } + if !self.dirs.iter().any(|dir| dir.index.contains_key(&id)) { + break 'begin_removal Handled::No; } - best - } + let dirs: VecDeque = (0..self.dirs.len()) + .filter(|dir| self.dirs[*dir].access == Access::ReadOnly || self.dirs[*dir].index.contains_key(&id)) + .collect(); + let next = 'advance_removal: { +let (mut removing,): (Removing,) = (Removing { id, dirs, incomplete: false, flight: None },); - /// Whether `verdict` for `sha` may be installed now, and the package it describes. - fn judge(&self, sha: Sha, verdict: &Verdict) -> Result { - if self.catalog.snapshot().revoked(sha).is_some() { return Err(Refusal::Unloadable(Unloadable::Revoked)) } - let (meta, unloadable) = match verdict { - Verdict::Invalid => return Err(Refusal::Invalid), - Verdict::Loadable(meta) => (meta, None), - Verdict::Unloadable(meta, why) => (meta, Some(*why)), - }; - if meta.id == BUILTIN_CLASSIC { - return Err(Refusal::BuiltinId); - } - if let Some(why) = unloadable { - return Err(Refusal::Unloadable(why)); - } - let Some(new) = Semver::parse(&meta.version) else { return Err(Refusal::Invalid) }; - if let Some(have) = self.winners().get(meta.id.as_str()) { - if have.record.sha == sha { - return Err(Refusal::AlreadyInstalled); - } - if Semver::parse(&have.loaded.meta.version).is_some_and(|old| new <= old) { - return Err(Refusal::NotNewer); + while let Some(dir) = removing.dirs.pop_front() { + if self.dirs[dir].access == Access::ReadOnly { + // Cannot be taken out of an index nobody may write: the package stays listed. + removing.incomplete = true; + continue; } - } - Ok(meta.clone()) - } - - /// Whether an index of candidate `dir` names the pack, in a record this build reads or one it keeps. - fn referenced(&self, dir: usize, sha: Sha) -> bool { - self.dirs.get(dir).is_some_and(|d| { - d.index.values().any(|r| r.sha == sha) - }) - } - - fn notice(fx: &mut Vec, notice: Notice) { - fx.push(HudEffect::Notice(notice)); - } + let mut index = self.dirs[dir].index.clone(); + let Some(record) = index.remove(&removing.id) else { continue }; + let gone = vec![record.sha]; + let tag = { - // -------- listing -------- + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) - /// End the install or removal a `Refresh` displaces with its notice, and return the packs it may - /// have left behind. It must run before the new `Setup` replaces the candidates it indexes. - fn displaced(&mut self, fx: &mut Vec) -> Vec<(PathBuf, Sha)> { - let at = |store: &Self, dir: usize, sha: Sha| store.setup.candidates.get(dir).map(|c| (c.dir.clone(), sha)); - let mut stray = Vec::new(); - match std::mem::replace(&mut self.op, Op::Idle) { - Op::Idle | Op::Listing(_) => {} - Op::Installing(Installing { step, .. }) => { - let sha = match step { - Step::Reading { sha, .. } => Some(sha), - // A fetch that has not answered has no bytes, so no sha. - Step::Fetching { .. } => None, - Step::Validating(offer) | Step::Offered { offer, .. } => Some(offer.sha), - Step::Writing { offer, dir, what, .. } => { - // The pack is down or on its way. If the index write reached the disk the id's - // old pack is the unlisted one, if not the new one is: only a re-read says. - stray.extend(at(self, dir, offer.sha)); - if let Write::Index { replaced: Some(old), .. } = what { - stray.extend(at(self, dir, old).filter(|_| old != offer.sha)); - } - Some(offer.sha) - } - }; - Self::notice(fx, Notice::NotWritten { sha }); - } - Op::Removing(Removing { id, flight, .. }) => { - if let Some(Rewrite { dir, gone, .. }) = flight { - // The rewrite may have reached the disk: the packs it unlisted are the stray ones. - stray.extend(gone.into_iter().filter_map(|sha| at(self, dir, sha))); - } - Self::notice(fx, Notice::RemoveIncomplete { id }); - } +}; + fx.push(HudEffect::WriteFile { + tag, + at: self.loc(dir, INDEX_FILE.to_string()), + bytes: index_bytes(&index), + }); + removing.flight = Some(Rewrite { tag, dir, index, gone }); + break 'advance_removal Op::Removing(removing); } - stray - } - - fn begin_listing(&mut self, setup: Setup, selected: String, fx: &mut Vec) { - let stray = self.displaced(fx); - let n = setup.candidates.len(); - self.dirs = vec![Dir::default(); n]; - self.packs.clear(); - self.drops.clear(); - self.selected = if selected.is_empty() { BUILTIN_CLASSIC.to_string() } else { selected }; - self.setup = setup; - let mut todo: VecDeque = (0..n).map(Job::Index).collect(); - todo.push_back(Job::Plan); - todo.extend((0..n).map(Job::Scan)); - self.op = self.advance(Listing { todo, flight: None, stray }, fx); - } - - /// Delete the packs a displaced operation may have left that no index names now that every index - /// has been read again. A candidate whose index could not be read whole is left alone: it may name - /// them. - fn reclaim(&self, stray: Vec<(PathBuf, Sha)>, fx: &mut Vec) { - for (root, sha) in stray { - let Some(dir) = self.setup.candidates.iter().position(|c| c.dir == root) else { continue }; - if self.dirs[dir].access == Access::Writable && !self.referenced(dir, sha) { - fx.push(HudEffect::Delete { at: self.loc(dir, pack_rel(sha)) }); - } + // Whatever no candidate lists any more is forgotten, and the selection follows the package. + let dirs = &self.dirs; + self.packs.retain(|sha, _| dirs.iter().any(|d| d.index.values().any(|r| r.sha == *sha))); + let listed = self.winners().contains_key(removing.id.as_str()); + if !listed && self.selected == removing.id { + self.selected = BUILTIN_CLASSIC.to_string(); + fx.push(HudEffect::Selection { id: self.selected.clone() }); } - } + let id = removing.id; + Self::notice( + fx, + if removing.incomplete || listed { Notice::RemoveIncomplete { id } } else { Notice::Removed { id } }, + ); + Op::Idle - /// The `Pack` jobs for every distinct sha the indexes name, each trying its candidates in order. - fn plan_packs(&self) -> Vec { - let mut by_sha: BTreeMap> = BTreeMap::new(); - for (dir, state) in self.dirs.iter().enumerate() { - for record in state.index.values() { - let dirs = by_sha.entry(record.sha).or_default(); - if dirs.back() != Some(&dir) { - dirs.push_back(dir); - } - } - } - by_sha.into_iter().map(|(sha, dirs)| Job::Pack { sha, dirs }).collect() - } +}; + drop(std::mem::replace(&mut self.op, next)); + Handled::Yes - /// Issue the next listing request, or finish. - fn advance(&mut self, mut listing: Listing, fx: &mut Vec) -> Op { - while let Some(job) = listing.todo.pop_front() { - let tag = self.tag(); - let effect = match &job { - Job::Plan => { - self.reclaim(std::mem::take(&mut listing.stray), fx); - for planned in self.plan_packs().into_iter().rev() { - listing.todo.push_front(planned); - } - continue; - } - Job::Index(dir) => self.read(tag, *dir, INDEX_FILE.to_string()), - Job::Pack { sha, dirs } => match dirs.front() { - Some(dir) => self.read(tag, *dir, pack_rel(*sha)), - None => continue, - }, - Job::Scan(dir) => HudEffect::ScanDir { tag, at: self.loc(*dir, DROP_DIR.to_string()) }, - Job::Drop { dir, name } => self.read(tag, *dir, format!("{DROP_DIR}/{name}")), - }; - fx.push(effect); - listing.flight = Some(Flight { tag, job, stage: Stage::Io }); - return Op::Listing(listing); - } - Op::Idle - } +}, + result @ (HudEvent::Scanned { .. } + | HudEvent::Read { .. } + | HudEvent::Validated { .. } + | HudEvent::Written { .. } + | HudEvent::Fetched { .. }) => { + let (op, handled) = match std::mem::replace(&mut self.op, Op::Idle) { + Op::Idle => (Op::Idle, Handled::No), + Op::Listing(listing) => 'listing_result: { +let (mut listing, ev,): (Listing, HudEvent,) = (listing, result,); - fn listing_result(&mut self, mut listing: Listing, ev: HudEvent, fx: &mut Vec) -> (Op, Handled) { - let Some(flight) = listing.flight.take() else { return (Op::Listing(listing), Handled::No) }; + let Some(flight) = listing.flight.take() else { break 'listing_result (Op::Listing(listing), Handled::No) }; let Flight { tag, job, stage } = flight; let addressed = match &ev { HudEvent::Scanned { tag: t, .. } | HudEvent::Read { tag: t, .. } | HudEvent::Validated { tag: t, .. } | HudEvent::Written { tag: t, .. } => *t == tag, - _ => false, + HudEvent::Catalog(_) | HudEvent::FetchRegistry { .. } | HudEvent::CancelRegistry { .. } + | HudEvent::Refresh { .. } | HudEvent::Install { .. } | HudEvent::Fetch { .. } + | HudEvent::Fetched { .. } | HudEvent::InstallOffer { .. } | HudEvent::DeclineOffer { .. } + | HudEvent::InstallDrop { .. } | HudEvent::Selected { .. } | HudEvent::Removed { .. } => false, }; if !addressed { listing.flight = Some(Flight { tag, job, stage }); - return (Op::Listing(listing), Handled::No); + break 'listing_result (Op::Listing(listing), Handled::No); } match (job, stage, ev) { (Job::Index(dir), Stage::Io, HudEvent::Read { result, .. }) => { @@ -1153,10 +1038,15 @@ impl HudStore { } (Job::Pack { sha, mut dirs }, Stage::Io, HudEvent::Read { result, .. }) => match result { Ok(bytes) if Sha::of(&bytes) == sha => { - let tag = self.tag(); + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; fx.push(HudEffect::Validate { tag, sha, bytes: bytes.into() }); listing.flight = Some(Flight { tag, job: Job::Pack { sha, dirs }, stage: Stage::Validation(sha) }); - return (Op::Listing(listing), Handled::Yes); + break 'listing_result (Op::Listing(listing), Handled::Yes); } _ => { // Missing, unreadable, too large or not what its name says: try the next copy. @@ -1183,10 +1073,15 @@ impl HudStore { (Job::Drop { dir, name }, Stage::Io, HudEvent::Read { result, .. }) => match result { Ok(bytes) => { let sha = Sha::of(&bytes); - let tag = self.tag(); + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; fx.push(HudEffect::Validate { tag, sha, bytes: bytes.into() }); listing.flight = Some(Flight { tag, job: Job::Drop { dir, name }, stage: Stage::Validation(sha) }); - return (Op::Listing(listing), Handled::Yes); + break 'listing_result (Op::Listing(listing), Handled::Yes); } Err(ReadError::TooLarge) => self.drops.push(Dropped { dir, name, found: Found::TooLarge }), Err(ReadError::Missing | ReadError::Failed) => {} @@ -1198,22 +1093,47 @@ impl HudStore { } (job, stage, _) => { listing.flight = Some(Flight { tag, job, stage }); - return (Op::Listing(listing), Handled::No); + break 'listing_result (Op::Listing(listing), Handled::No); } } - (self.advance(listing, fx), Handled::Yes) - } + (('advance: { +let (mut listing,): (Listing,) = (listing,); - // -------- install -------- + while let Some(job) = listing.todo.pop_front() { + let tag = { - /// Ask the runner whether these bytes are a package this app can run. - fn validate(&mut self, offer: Offer, fx: &mut Vec) -> Op { - let tag = self.tag(); - fx.push(HudEffect::Validate { tag, sha: offer.sha, bytes: offer.bytes.clone() }); - Op::Installing(Installing { tag, step: Step::Validating(offer) }) - } + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; + let effect = match &job { + Job::Plan => { + self.reclaim(std::mem::take(&mut listing.stray), fx); + for planned in self.plan_packs().into_iter().rev() { + listing.todo.push_front(planned); + } + continue; + } + Job::Index(dir) => self.read(tag, *dir, INDEX_FILE.to_string()), + Job::Pack { sha, dirs } => match dirs.front() { + Some(dir) => self.read(tag, *dir, pack_rel(*sha)), + None => continue, + }, + Job::Scan(dir) => HudEffect::ScanDir { tag, at: self.loc(*dir, DROP_DIR.to_string()) }, + Job::Drop { dir, name } => self.read(tag, *dir, format!("{DROP_DIR}/{name}")), + }; + fx.push(effect); + listing.flight = Some(Flight { tag, job, stage: Stage::Io }); + break 'advance Op::Listing(listing); + } + Op::Idle + +}), Handled::Yes) + +}, + Op::Installing(installing) => 'installing_result: { +let (installing, ev,): (Installing, HudEvent,) = (installing, result,); - fn installing_result(&mut self, installing: Installing, ev: HudEvent, fx: &mut Vec) -> (Op, Handled) { let Installing { tag, step } = installing; let addressed = match &ev { HudEvent::Scanned { tag: t, .. } @@ -1221,15 +1141,30 @@ impl HudStore { | HudEvent::Validated { tag: t, .. } | HudEvent::Written { tag: t, .. } | HudEvent::Fetched { tag: t, .. } => *t == tag, - _ => false, + HudEvent::Catalog(_) | HudEvent::FetchRegistry { .. } | HudEvent::CancelRegistry { .. } + | HudEvent::Refresh { .. } | HudEvent::Install { .. } | HudEvent::Fetch { .. } + | HudEvent::InstallOffer { .. } | HudEvent::DeclineOffer { .. } + | HudEvent::InstallDrop { .. } | HudEvent::Selected { .. } | HudEvent::Removed { .. } => false, }; if !addressed { - return (Op::Installing(Installing { tag, step }), Handled::No); + break 'installing_result (Op::Installing(Installing { tag, step }), Handled::No); } let op = match (step, ev) { (Step::Reading { sha, now }, HudEvent::Read { result, .. }) => match result { Ok(bytes) if Sha::of(&bytes) == sha => { - self.validate(Offer { sha, source: Source::Drop, now: Some(now), from: None, bytes: bytes.into(), expected: None }, fx) + { +let (offer,): (Offer,) = (Offer { sha, source: Source::Drop, now: Some(now), from: None, bytes: bytes.into(), expected: None },); + + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; + fx.push(HudEffect::Validate { tag, sha: offer.sha, bytes: offer.bytes.clone() }); + Op::Installing(Installing { tag, step: Step::Validating(offer) }) + +} } _ => { Self::notice(fx, Notice::Refused { sha, reason: Refusal::Changed }); @@ -1252,14 +1187,26 @@ impl HudStore { } else { let source = if expected.is_some() { Source::Registry } else { Source::Address }; let offer = Offer { sha, source, now: None, from: Some(address), bytes: bytes.into(), expected }; - self.validate(offer, fx) - } - } - }, - (Step::Validating(offer), HudEvent::Validated { sha, verdict, .. }) if sha == offer.sha => { - let checked = self.judge(offer.sha, &verdict).and_then(|meta| { - if offer.expected.as_ref().is_some_and(|p| p.id != meta.id || p.name != meta.name || p.version != meta.version - || p.package_format != meta.package_format || p.hud_format != meta.hud_format) { Err(Refusal::Changed) } else { Ok(meta) } + { +let (offer,): (Offer,) = (offer,); + + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; + fx.push(HudEffect::Validate { tag, sha: offer.sha, bytes: offer.bytes.clone() }); + Op::Installing(Installing { tag, step: Step::Validating(offer) }) + +} + } + } + }, + (Step::Validating(offer), HudEvent::Validated { sha, verdict, .. }) if sha == offer.sha => { + let checked = self.judge(offer.sha, &verdict).and_then(|meta| { + if offer.expected.as_ref().is_some_and(|p| p.id != meta.id || p.name != meta.name || p.version != meta.version + || p.package_format != meta.package_format || p.hud_format != meta.hud_format) { Err(Refusal::Changed) } else { Ok(meta) } }); match checked { Err(reason) => { @@ -1267,7 +1214,28 @@ impl HudStore { Op::Idle } // The viewer has confirmed already (a drop file, `Install`): write it. - Ok(meta) if offer.now.is_some() => self.write_pack(offer, meta, 0, fx), + Ok(meta) if offer.now.is_some() => 'write_pack: { +let (offer, meta, dir,): (Offer, Meta, usize,) = (offer, meta, 0,); + + // A candidate whose index is read-only cannot list the new package, so it is not a candidate. + let Some(dir) = (dir..self.dirs.len()).find(|d| self.dirs[*d].access == Access::Writable) else { + Self::notice(fx, Notice::NotWritten { sha: Some(offer.sha) }); + break 'write_pack Op::Idle; + }; + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; + fx.push(HudEffect::WriteFile { + tag, + at: self.loc(dir, pack_rel(offer.sha)), + bytes: offer.bytes.clone(), + }); + Op::Installing(Installing { tag, step: Step::Writing { offer, meta, dir, what: Write::Pack } }) + +}, // A fetch: nothing is written until the viewer has seen what it is. Ok(meta) => Op::Installing(Installing { tag, step: Step::Offered { offer, meta } }), } @@ -1280,7 +1248,12 @@ impl HudStore { .insert(meta.id.clone(), Record::new(offer.sha, offer.source, offer.now.unwrap_or_default(), &meta.package_format, &meta.hud_format) .from_dev_source(offer.from.as_ref())) .map(|old| old.sha); - let tag = self.tag(); + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; fx.push(HudEffect::WriteFile { tag, at: self.loc(dir, INDEX_FILE.to_string()), @@ -1291,7 +1264,28 @@ impl HudStore { step: Step::Writing { offer, meta, dir, what: Write::Index { index, replaced } }, }) } - (Write::Pack, WriteOutcome::Refused) => self.write_pack(offer, meta, dir + 1, fx), + (Write::Pack, WriteOutcome::Refused) => 'write_pack: { +let (offer, meta, dir,): (Offer, Meta, usize,) = (offer, meta, dir + 1,); + + // A candidate whose index is read-only cannot list the new package, so it is not a candidate. + let Some(dir) = (dir..self.dirs.len()).find(|d| self.dirs[*d].access == Access::Writable) else { + Self::notice(fx, Notice::NotWritten { sha: Some(offer.sha) }); + break 'write_pack Op::Idle; + }; + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; + fx.push(HudEffect::WriteFile { + tag, + at: self.loc(dir, pack_rel(offer.sha)), + bytes: offer.bytes.clone(), + }); + Op::Installing(Installing { tag, step: Step::Writing { offer, meta, dir, what: Write::Pack } }) + +}, (Write::Index { index, replaced }, WriteOutcome::Done) => { self.dirs[dir].index = index; let until_restart = self.volatile(dir); @@ -1313,47 +1307,53 @@ impl HudStore { if !self.referenced(dir, offer.sha) { fx.push(HudEffect::Delete { at: self.loc(dir, pack_rel(offer.sha)) }); } - self.write_pack(offer, meta, dir + 1, fx) - } - }, - (step, _) => return (Op::Installing(Installing { tag, step }), Handled::No), - }; - (op, Handled::Yes) - } + 'write_pack: { +let (offer, meta, dir,): (Offer, Meta, usize,) = (offer, meta, dir + 1,); - /// Write the pack to candidate `dir`; with no candidate left, nothing was installed. - fn write_pack(&mut self, offer: Offer, meta: Meta, dir: usize, fx: &mut Vec) -> Op { // A candidate whose index is read-only cannot list the new package, so it is not a candidate. let Some(dir) = (dir..self.dirs.len()).find(|d| self.dirs[*d].access == Access::Writable) else { Self::notice(fx, Notice::NotWritten { sha: Some(offer.sha) }); - return Op::Idle; + break 'write_pack Op::Idle; }; - let tag = self.tag(); + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; fx.push(HudEffect::WriteFile { tag, at: self.loc(dir, pack_rel(offer.sha)), bytes: offer.bytes.clone(), }); Op::Installing(Installing { tag, step: Step::Writing { offer, meta, dir, what: Write::Pack } }) - } - // -------- removal -------- +} + } + }, + (step, _) => break 'installing_result (Op::Installing(Installing { tag, step }), Handled::No), + }; + (op, Handled::Yes) - fn begin_removal(&mut self, id: String, fx: &mut Vec) -> Handled { - if self.busy() || id == BUILTIN_CLASSIC { - return Handled::No; - } - if !self.dirs.iter().any(|dir| dir.index.contains_key(&id)) { - return Handled::No; - } - let dirs: VecDeque = (0..self.dirs.len()) - .filter(|dir| self.dirs[*dir].access == Access::ReadOnly || self.dirs[*dir].index.contains_key(&id)) - .collect(); - self.op = self.advance_removal(Removing { id, dirs, incomplete: false, flight: None }, fx); - Handled::Yes - } +}, + Op::Removing(removing) => 'removing_result: { +let (mut removing, ev,): (Removing, HudEvent,) = (removing, result,); + + let HudEvent::Written { tag, outcome } = ev else { break 'removing_result (Op::Removing(removing), Handled::No) }; + match removing.flight.take() { + Some(Rewrite { tag: awaited, dir, index, gone }) if awaited == tag => { + match outcome { + WriteOutcome::Done => { + self.dirs[dir].index = index; + for sha in gone.into_iter().filter(|sha| !self.referenced(dir, *sha)) { + fx.push(HudEffect::Delete { at: self.loc(dir, pack_rel(sha)) }); + } + } + WriteOutcome::Refused => removing.incomplete = true, + } + (('advance_removal: { +let (mut removing,): (Removing,) = (removing,); - fn advance_removal(&mut self, mut removing: Removing, fx: &mut Vec) -> Op { while let Some(dir) = removing.dirs.pop_front() { if self.dirs[dir].access == Access::ReadOnly { // Cannot be taken out of an index nobody may write: the package stays listed. @@ -1363,14 +1363,19 @@ impl HudStore { let mut index = self.dirs[dir].index.clone(); let Some(record) = index.remove(&removing.id) else { continue }; let gone = vec![record.sha]; - let tag = self.tag(); + let tag = { + + self.tags = self.tags.wrapping_add(1); + Tag(self.tags) + +}; fx.push(HudEffect::WriteFile { tag, at: self.loc(dir, INDEX_FILE.to_string()), bytes: index_bytes(&index), }); removing.flight = Some(Rewrite { tag, dir, index, gone }); - return Op::Removing(removing); + break 'advance_removal Op::Removing(removing); } // Whatever no candidate lists any more is forgotten, and the selection follows the package. let dirs = &self.dirs; @@ -1386,29 +1391,287 @@ impl HudStore { if removing.incomplete || listed { Notice::RemoveIncomplete { id } } else { Notice::Removed { id } }, ); Op::Idle - } - fn removing_result(&mut self, mut removing: Removing, ev: HudEvent, fx: &mut Vec) -> (Op, Handled) { - let HudEvent::Written { tag, outcome } = ev else { return (Op::Removing(removing), Handled::No) }; - match removing.flight.take() { - Some(Rewrite { tag: awaited, dir, index, gone }) if awaited == tag => { - match outcome { - WriteOutcome::Done => { - self.dirs[dir].index = index; - for sha in gone.into_iter().filter(|sha| !self.referenced(dir, *sha)) { - fx.push(HudEffect::Delete { at: self.loc(dir, pack_rel(sha)) }); - } - } - WriteOutcome::Refused => removing.incomplete = true, - } - (self.advance_removal(removing, fx), Handled::Yes) +}), Handled::Yes) } other => { removing.flight = other; (Op::Removing(removing), Handled::No) } } + +}, + }; + drop(std::mem::replace(&mut self.op, op)); + handled + } + } + +}; +// The cache can land before the installed-pack listing: apply the same rule after either. + if self.winners().get(self.selected.as_str()).is_some_and(|w| self.catalog.snapshot().revoked(w.record.sha).is_some()) { + self.selected = BUILTIN_CLASSIC.into(); + fx.push(HudEffect::Selection { id: self.selected.clone() }); + } + handled + +} + + // -------- readers -------- + + /// The current gallery view, including dated cache status and revocation reasons. + pub fn catalog(&self) -> &catalog::Snapshot { self.catalog.snapshot() } + + /// Whether a listing, install or removal is running (installing and removing wait for the idle). + pub fn busy(&self) -> bool { + !matches!(self.op, Op::Idle) } + + /// The selection as the profile holds it; it may name a package that is gone or cannot load. + pub fn selected(&self) -> &str { + &self.selected + } + + /// What a playback starts with: the selection when it is listed and loadable, else the built-in. + pub fn resolved(&self) -> &str { + if self.selected != BUILTIN_CLASSIC + && self.winners().get(self.selected.as_str()).is_some_and(|w| w.loaded.loadable.is_ok() && self.catalog.snapshot().revoked(w.record.sha).is_none()) + { + &self.selected + } else { + BUILTIN_CLASSIC + } + } + + /// The package list: the built-in first, then one row per installed id, by id. + pub fn entries(&self) -> Vec { + let mut out = vec![Entry { + id: BUILTIN_CLASSIC.to_string(), + meta: None, + sha: None, + source: None, + trust: Trust::BuiltIn, + loadable: Ok(()), + until_restart: false, + selected: self.selected == BUILTIN_CLASSIC, + dev_source: None, + }]; + for (id, win) in self.winners() { + out.push(Entry { + id: id.to_string(), + meta: Some(win.loaded.meta.clone()), + sha: Some(win.record.sha), + source: Some(win.record.source), + trust: win.record.source.trust(), + loadable: if self.catalog.snapshot().revoked(win.record.sha).is_some() { Err(Unloadable::Revoked) } else { win.loaded.loadable }, + until_restart: win.loaded.volatile, + selected: self.selected == id, + dev_source: win.record.from.clone(), + }); + } + out + } + + /// Whether a fetch from an address is in flight: waiting for the network, or for the validator's verdict on what + /// came back. An offer waiting for the viewer is not (it is [`offer`](Self::offer)). + pub fn fetching(&self) -> bool { + matches!( + &self.op, + Op::Installing(Installing { step: Step::Fetching { .. }, .. }) + | Op::Installing(Installing { step: Step::Validating(Offer { from: Some(_), .. }), .. }) + ) + } + + /// The validated fetch waiting for the viewer's answer, if any: [`HudEvent::InstallOffer`] installs + /// it, [`HudEvent::DeclineOffer`] drops it, and a `Refresh` ends it with [`Notice::NotWritten`]. + pub fn offer(&self) -> Option { + match &self.op { + Op::Installing(Installing { step: Step::Offered { offer, meta }, .. }) => Some(OfferView { + sha: offer.sha, + meta: meta.clone(), + source: offer.source, + from: offer.from.clone(), + }), + Op::Idle | Op::Listing(_) | Op::Installing(_) | Op::Removing(_) => None, + } + } + + /// The files found in `drop/`, one row per distinct sha, with whether installing them would be + /// accepted now. + pub fn drops(&self) -> Vec { + let mut seen = Vec::new(); + let mut out = Vec::new(); + for dropped in &self.drops { + match &dropped.found { + Found::TooLarge => out.push(DropFile { + name: dropped.name.clone(), + sha: None, + meta: None, + status: Err(Refusal::TooLarge), + }), + Found::Parsed { sha, verdict } => { + if seen.contains(sha) { + continue; + } + seen.push(*sha); + let meta = match verdict { + Verdict::Loadable(meta) | Verdict::Unloadable(meta, _) => Some(meta.clone()), + Verdict::Invalid => None, + }; + out.push(DropFile { + name: dropped.name.clone(), + sha: Some(*sha), + meta, + status: self.judge(*sha, verdict).map(|_| ()), + }); + } + } + } + out + } + + // -------- the one writer -------- + + /// The one writer. The table is in the module doc; a pair it does not list answers + /// [`Handled::No`] and changes nothing. + pub fn step(&mut self, ev: HudEvent, fx: &mut Vec) -> Handled { self.transition(ev, fx) } + + + + // -------- helpers -------- + + + + fn loc(&self, dir: usize, rel: String) -> Loc { + Loc { root: self.setup.candidates.get(dir).map(|c| c.dir.clone()).unwrap_or_default(), rel } + } + + fn read(&self, tag: Tag, dir: usize, rel: String) -> HudEffect { + HudEffect::ReadFile { tag, at: self.loc(dir, rel), max_bytes: self.setup.max_pack_bytes } + } + + fn volatile(&self, dir: usize) -> bool { + self.setup.candidates.get(dir).is_some_and(|c| c.volatile) + } + + + + /// The installed package of each id: across candidates the higher version wins, and on a tie the + /// earlier candidate. An entry whose pack was not read, or whose pack declares another id, is not a + /// package. + fn winners(&self) -> BTreeMap<&str, Winner<'_>> { + let mut best: BTreeMap<&str, Winner<'_>> = BTreeMap::new(); + for dir in &self.dirs { + for (id, record) in &dir.index { + let Some(loaded) = self.packs.get(&record.sha) else { continue }; + if loaded.meta.id != *id || loaded.meta.package_format != record.package_format || loaded.meta.hud_format != record.hud_format { + continue; + } + let win = Winner { record, loaded }; + let better = best.get(id.as_str()).map_or(true, |have| { + Semver::parse(&win.loaded.meta.version) > Semver::parse(&have.loaded.meta.version) + }); + if better { + best.insert(id.as_str(), win); + } + } + } + best + } + + /// Whether `verdict` for `sha` may be installed now, and the package it describes. + fn judge(&self, sha: Sha, verdict: &Verdict) -> Result { + if self.catalog.snapshot().revoked(sha).is_some() { return Err(Refusal::Unloadable(Unloadable::Revoked)) } + let (meta, unloadable) = match verdict { + Verdict::Invalid => return Err(Refusal::Invalid), + Verdict::Loadable(meta) => (meta, None), + Verdict::Unloadable(meta, why) => (meta, Some(*why)), + }; + if meta.id == BUILTIN_CLASSIC { + return Err(Refusal::BuiltinId); + } + if let Some(why) = unloadable { + return Err(Refusal::Unloadable(why)); + } + let Some(new) = Semver::parse(&meta.version) else { return Err(Refusal::Invalid) }; + if let Some(have) = self.winners().get(meta.id.as_str()) { + if have.record.sha == sha { + return Err(Refusal::AlreadyInstalled); + } + if Semver::parse(&have.loaded.meta.version).is_some_and(|old| new <= old) { + return Err(Refusal::NotNewer); + } + } + Ok(meta.clone()) + } + + /// Whether an index of candidate `dir` names the pack, in a record this build reads or one it keeps. + fn referenced(&self, dir: usize, sha: Sha) -> bool { + self.dirs.get(dir).is_some_and(|d| { + d.index.values().any(|r| r.sha == sha) + }) + } + + fn notice(fx: &mut Vec, notice: Notice) { + fx.push(HudEffect::Notice(notice)); + } + + // -------- listing -------- + + /// End the install or removal a `Refresh` displaces with its notice, and return the packs it may + /// have left behind. It must run before the new `Setup` replaces the candidates it indexes. + + + + + /// Delete the packs a displaced operation may have left that no index names now that every index + /// has been read again. A candidate whose index could not be read whole is left alone: it may name + /// them. + fn reclaim(&self, stray: Vec<(PathBuf, Sha)>, fx: &mut Vec) { + for (root, sha) in stray { + let Some(dir) = self.setup.candidates.iter().position(|c| c.dir == root) else { continue }; + if self.dirs[dir].access == Access::Writable && !self.referenced(dir, sha) { + fx.push(HudEffect::Delete { at: self.loc(dir, pack_rel(sha)) }); + } + } + } + + /// The `Pack` jobs for every distinct sha the indexes name, each trying its candidates in order. + fn plan_packs(&self) -> Vec { + let mut by_sha: BTreeMap> = BTreeMap::new(); + for (dir, state) in self.dirs.iter().enumerate() { + for record in state.index.values() { + let dirs = by_sha.entry(record.sha).or_default(); + if dirs.back() != Some(&dir) { + dirs.push_back(dir); + } + } + } + by_sha.into_iter().map(|(sha, dirs)| Job::Pack { sha, dirs }).collect() + } + + + + + + + // -------- install -------- + + + + + + + + + + // -------- removal -------- + + + + + + } /// The installed package of one id, as the list shows it. @@ -1502,6 +1765,7 @@ where D: serde::Deserializer<'de> { fn parse_index(bytes: &[u8]) -> Dir { let readonly = || Dir { access: Access::ReadOnly, ..Dir::default() }; let Ok(JsonObject(file)) = serde_json::from_slice::>(bytes) else { return readonly() }; + let file: IndexFile = file; if file.v != INDEX_FORMAT { return readonly(); } let mut index = Index::new(); for (id, record) in file.packs { diff --git a/rust-modules/data/src/hudpacks/catalog.rs b/rust-modules/data/src/hudpacks/catalog.rs index d9991103df..3dffb5031b 100644 --- a/rust-modules/data/src/hudpacks/catalog.rs +++ b/rust-modules/data/src/hudpacks/catalog.rs @@ -1,3 +1,4 @@ +#![deny(clippy::wildcard_enum_match_arm)] //! The registry contract and gallery cache policy. No clock, transport, filesystem or profile IO. //! //! Only `Open` may begin a request: booting the package store cannot contact the registry. @@ -445,7 +446,7 @@ impl CacheRecord { let (body, index): (Arc, _) = if cache.body.is_empty() && cache.checked_at.is_none() { (cache.body.into(), None) } else { - let verified = verify(cache.body.as_bytes(), keys)?; + let verified: Verified = verify(cache.body.as_bytes(), keys)?; (verified.body, Some(verified.index)) }; Ok(Self { @@ -555,7 +556,11 @@ pub struct Catalog { } impl Default for Catalog { - fn default() -> Self { + fn default() -> Self { Self::new() } +} + +impl Catalog { + pub fn new() -> Self { Self { snapshot: Snapshot::default(), candidates: Vec::new(), @@ -568,20 +573,79 @@ impl Default for Catalog { allow_fetch: false, } } -} -impl Catalog { - pub fn snapshot(&self) -> &Snapshot { - &self.snapshot - } +fn transition(&mut self, ev: Event, fx: &mut Vec) -> bool { - pub fn step(&mut self, ev: Event, fx: &mut Vec) -> bool { match ev { Event::Load { candidates } if matches!(self.phase, Phase::Idle) => { self.generation = self.generation.wrapping_add(1); self.candidates = candidates; self.allow_fetch = false; - self.read(0, fx); + { +let (at,): (usize,) = (0,); + + if let Some(candidate) = self.candidates.get(at) { + let root = candidate.dir.clone(); + { self.phase = Phase::Reading(at); }; + fx.push(CatalogEffect::Read { + tag: self.generation, + at: Loc { + root, + rel: CACHE_FILE.into(), + }, + }); + } else if self.allow_fetch + && self + .attempted_at + .is_none_or(|at| self.now < at || self.now - at >= REFRESH_SECONDS) + { + self.attempted_at = Some(self.now); + self.snapshot.fetching = true; + // Persist the attempt before dialing, so a restart during the request keeps backoff. + { +let (at, fetch,): (usize, bool,) = (0, true,); + + if let Some(candidate) = self.candidates.get(at) { + let root = candidate.dir.clone(); + let record = CacheRecord { + checked_at: self.snapshot.checked_at, + attempted_at: self.attempted_at, + etag: self.etag.clone(), + body: Arc::clone(&self.body), + index: self.snapshot.index.clone(), + }; + { self.phase = Phase::Writing(at, fetch); }; + fx.push(CatalogEffect::Write { + tag: self.generation, + at: Loc { + root, + rel: CACHE_FILE.into(), + }, + record, + }); + } else { + { +let (fetch,): (bool,) = (fetch,); + + if fetch { + { self.phase = Phase::Fetching; }; + fx.push(CatalogEffect::Get { + tag: self.generation, + etag: self.etag.clone(), + }); + } else { + { self.phase = Phase::Idle; }; + } + +}; + } + +}; + } else { + { self.phase = Phase::Idle; }; + } + +}; true } Event::Open { candidates, now } => { @@ -597,13 +661,77 @@ impl Catalog { self.generation = self.generation.wrapping_add(1); self.now = now; self.candidates = candidates; - self.read(0, fx); + { +let (at,): (usize,) = (0,); + + if let Some(candidate) = self.candidates.get(at) { + let root = candidate.dir.clone(); + { self.phase = Phase::Reading(at); }; + fx.push(CatalogEffect::Read { + tag: self.generation, + at: Loc { + root, + rel: CACHE_FILE.into(), + }, + }); + } else if self.allow_fetch + && self + .attempted_at + .is_none_or(|at| self.now < at || self.now - at >= REFRESH_SECONDS) + { + self.attempted_at = Some(self.now); + self.snapshot.fetching = true; + // Persist the attempt before dialing, so a restart during the request keeps backoff. + { +let (at, fetch,): (usize, bool,) = (0, true,); + + if let Some(candidate) = self.candidates.get(at) { + let root = candidate.dir.clone(); + let record = CacheRecord { + checked_at: self.snapshot.checked_at, + attempted_at: self.attempted_at, + etag: self.etag.clone(), + body: Arc::clone(&self.body), + index: self.snapshot.index.clone(), + }; + { self.phase = Phase::Writing(at, fetch); }; + fx.push(CatalogEffect::Write { + tag: self.generation, + at: Loc { + root, + rel: CACHE_FILE.into(), + }, + record, + }); + } else { + { +let (fetch,): (bool,) = (fetch,); + + if fetch { + { self.phase = Phase::Fetching; }; + fx.push(CatalogEffect::Get { + tag: self.generation, + etag: self.etag.clone(), + }); + } else { + { self.phase = Phase::Idle; }; + } + +}; + } + +}; + } else { + { self.phase = Phase::Idle; }; + } + +}; true } Event::Read { tag, result } if tag == self.generation && matches!(self.phase, Phase::Reading(_)) => { - let Phase::Reading(at) = self.phase else { + let &Phase::Reading(at) = &self.phase else { unreachable!() }; if let Ok(cache) = result { @@ -617,7 +745,71 @@ impl Catalog { self.body = cache.body; } } - self.read(at + 1, fx); + { +let (at,): (usize,) = (at + 1,); + + if let Some(candidate) = self.candidates.get(at) { + let root = candidate.dir.clone(); + { self.phase = Phase::Reading(at); }; + fx.push(CatalogEffect::Read { + tag: self.generation, + at: Loc { + root, + rel: CACHE_FILE.into(), + }, + }); + } else if self.allow_fetch + && self + .attempted_at + .is_none_or(|at| self.now < at || self.now - at >= REFRESH_SECONDS) + { + self.attempted_at = Some(self.now); + self.snapshot.fetching = true; + // Persist the attempt before dialing, so a restart during the request keeps backoff. + { +let (at, fetch,): (usize, bool,) = (0, true,); + + if let Some(candidate) = self.candidates.get(at) { + let root = candidate.dir.clone(); + let record = CacheRecord { + checked_at: self.snapshot.checked_at, + attempted_at: self.attempted_at, + etag: self.etag.clone(), + body: Arc::clone(&self.body), + index: self.snapshot.index.clone(), + }; + { self.phase = Phase::Writing(at, fetch); }; + fx.push(CatalogEffect::Write { + tag: self.generation, + at: Loc { + root, + rel: CACHE_FILE.into(), + }, + record, + }); + } else { + { +let (fetch,): (bool,) = (fetch,); + + if fetch { + { self.phase = Phase::Fetching; }; + fx.push(CatalogEffect::Get { + tag: self.generation, + etag: self.etag.clone(), + }); + } else { + { self.phase = Phase::Idle; }; + } + +}; + } + +}; + } else { + { self.phase = Phase::Idle; }; + } + +}; true } Event::Reply { tag, result } @@ -629,7 +821,7 @@ impl Catalog { if reply.status == 304 && self.snapshot.index.is_some() && self.etag.is_some() { self.snapshot.checked_at = Some(self.now); self.snapshot.refresh_failed = false; - self.etag = etag(reply.etag).or_else(|| self.etag.take()); + if let Some(validator) = etag(reply.etag) { self.etag = Some(validator); } } else if let Some(signed) = reply.signed { // The one rule that needs the cache: an index may not be older than the verified one held. let cached = self.snapshot.index.as_ref().and_then(|index| index.serial); @@ -646,64 +838,74 @@ impl Catalog { } } } - self.write(0, false, fx); - true - } - Event::Written { tag, outcome } - if tag == self.generation && matches!(self.phase, Phase::Writing(..)) => - { - let Phase::Writing(at, fetch) = self.phase else { - unreachable!() - }; - if outcome == WriteOutcome::Done { - self.after_write(fetch, fx) - } else { - self.write(at + 1, fetch, fx) - } - true - } - _ => false, - } - } + { +let (at, fetch,): (usize, bool,) = (0, false,); - fn read(&mut self, at: usize, fx: &mut Vec) { if let Some(candidate) = self.candidates.get(at) { - self.phase = Phase::Reading(at); - fx.push(CatalogEffect::Read { + let root = candidate.dir.clone(); + let record = CacheRecord { + checked_at: self.snapshot.checked_at, + attempted_at: self.attempted_at, + etag: self.etag.clone(), + body: Arc::clone(&self.body), + index: self.snapshot.index.clone(), + }; + { self.phase = Phase::Writing(at, fetch); }; + fx.push(CatalogEffect::Write { tag: self.generation, at: Loc { - root: candidate.dir.clone(), + root, rel: CACHE_FILE.into(), }, + record, + }); + } else { + { +let (fetch,): (bool,) = (fetch,); + + if fetch { + { self.phase = Phase::Fetching; }; + fx.push(CatalogEffect::Get { + tag: self.generation, + etag: self.etag.clone(), }); - } else if self.allow_fetch - && self - .attempted_at - .is_none_or(|at| self.now < at || self.now - at >= REFRESH_SECONDS) - { - self.attempted_at = Some(self.now); - self.snapshot.fetching = true; - // Persist the attempt before dialing, so a restart during the request keeps backoff. - self.write(0, true, fx); } else { - self.phase = Phase::Idle; + { self.phase = Phase::Idle; }; + } + +}; } - } - fn after_write(&mut self, fetch: bool, fx: &mut Vec) { +}; + true + } + Event::Written { tag, outcome } + if tag == self.generation && matches!(self.phase, Phase::Writing(..)) => + { + let &Phase::Writing(at, fetch) = &self.phase else { + unreachable!() + }; + if outcome == WriteOutcome::Done { + { +let (fetch,): (bool,) = (fetch,); + if fetch { - self.phase = Phase::Fetching; + { self.phase = Phase::Fetching; }; fx.push(CatalogEffect::Get { tag: self.generation, etag: self.etag.clone(), }); } else { - self.phase = Phase::Idle; + { self.phase = Phase::Idle; }; } - } - fn write(&mut self, at: usize, fetch: bool, fx: &mut Vec) { +} + } else { + { +let (at, fetch,): (usize, bool,) = (at + 1, fetch,); + if let Some(candidate) = self.candidates.get(at) { + let root = candidate.dir.clone(); let record = CacheRecord { checked_at: self.snapshot.checked_at, attempted_at: self.attempted_at, @@ -711,19 +913,51 @@ impl Catalog { body: Arc::clone(&self.body), index: self.snapshot.index.clone(), }; - self.phase = Phase::Writing(at, fetch); + { self.phase = Phase::Writing(at, fetch); }; fx.push(CatalogEffect::Write { tag: self.generation, at: Loc { - root: candidate.dir.clone(), + root, rel: CACHE_FILE.into(), }, record, }); } else { - self.after_write(fetch, fx); + { +let (fetch,): (bool,) = (fetch,); + + if fetch { + { self.phase = Phase::Fetching; }; + fx.push(CatalogEffect::Get { + tag: self.generation, + etag: self.etag.clone(), + }); + } else { + { self.phase = Phase::Idle; }; + } + +}; } + +} + } + true + } + Event::Load { .. } | Event::Read { .. } | Event::Reply { .. } | Event::Written { .. } => false, + } + +} + pub fn snapshot(&self) -> &Snapshot { + &self.snapshot } + + pub fn step(&mut self, ev: Event, fx: &mut Vec) -> bool { self.transition(ev, fx) } + + + + + + } #[cfg(test)] diff --git a/rust-modules/data/src/hudpacks/catalog/tests.rs b/rust-modules/data/src/hudpacks/catalog/tests.rs index bf0e43d7d6..55b40c8128 100644 --- a/rust-modules/data/src/hudpacks/catalog/tests.rs +++ b/rust-modules/data/src/hudpacks/catalog/tests.rs @@ -273,7 +273,7 @@ fn boot_never_dials_and_a_crash_during_get_keeps_the_persisted_attempt_backoff() ); let record = match &fx[0] { CatalogEffect::Write { record, .. } => record.clone(), - _ => panic!("attempt persisted before network"), + CatalogEffect::Read { .. } | CatalogEffect::Get { .. } | CatalogEffect::Refused { .. } => panic!("attempt persisted before network"), }; fx.clear(); catalog.step( diff --git a/rust-modules/data/src/hudpacks/tests.rs b/rust-modules/data/src/hudpacks/tests.rs index 1d607900f7..18c1b22e03 100644 --- a/rust-modules/data/src/hudpacks/tests.rs +++ b/rust-modules/data/src/hudpacks/tests.rs @@ -272,7 +272,7 @@ fn tag_of(effect: &HudEffect) -> Tag { | HudEffect::WriteFile { tag, .. } | HudEffect::Fetch { tag, .. } | HudEffect::Validate { tag, .. } => *tag, - other => panic!("{other:?} carries no tag"), + other @ (HudEffect::Catalog(_) | HudEffect::FetchRegistry { .. } | HudEffect::Delete { .. } | HudEffect::Selection { .. } | HudEffect::Notice(_)) => panic!("{other:?} carries no tag"), } } @@ -1499,7 +1499,7 @@ fn an_address_the_store_would_not_have_recorded_is_not_a_dev_source() { } fn registry_fixture(bytes: &[u8], revoked: bool) -> Vec { - let meta = match validator(bytes) { Verdict::Loadable(meta) => meta, _ => panic!("fixture") }; + let meta = match validator(bytes) { Verdict::Loadable(meta) => meta, Verdict::Unloadable(..) | Verdict::Invalid => panic!("fixture") }; let sha = Sha::of(bytes).hex(); let art = "b".repeat(64); let base = catalog::ORIGIN; @@ -1515,7 +1515,7 @@ fn registry_fixture(bytes: &[u8], revoked: bool) -> Vec { fn publish_catalog(store: &mut HudStore, bytes: Vec) -> Vec { let mut fx=vec![]; store.step(HudEvent::Catalog(catalog::Event::Open {candidates:vec![],now:10}),&mut fx); - let tag=fx.iter().find_map(|e| match e {HudEffect::Catalog(catalog::CatalogEffect::Get {tag,..})=>Some(*tag),_=>None}).unwrap(); + let tag=fx.iter().find_map(|e| match e {HudEffect::Catalog(catalog::CatalogEffect::Get {tag,..})=>Some(*tag),HudEffect::Catalog(_) | HudEffect::FetchRegistry { .. } | HudEffect::ScanDir { .. } | HudEffect::ReadFile { .. } | HudEffect::WriteFile { .. } | HudEffect::Delete { .. } | HudEffect::Fetch { .. } | HudEffect::Validate { .. } | HudEffect::Selection { .. } | HudEffect::Notice(_) => None}).unwrap(); fx.clear(); let signed=catalog::testing::sign(&bytes); store.step(HudEvent::Catalog(catalog::Event::Reply {tag,result:Ok(catalog::Reply::http(200,None,&signed,&catalog::testing::keys()))}),&mut fx); @@ -1550,7 +1550,7 @@ fn registry_fetch_binds_download_bytes_and_manifest_before_offering_and_never_se let mut rig=Rig::new();rig.refresh();publish_catalog(&mut rig.m,registry_fixture(&bytes,false)); let mut fx=vec![]; rig.m.step(HudEvent::FetchRegistry {sha,app:"0.10.0".into(),language:"en".into()},&mut fx); - let tag=match &fx[0] {HudEffect::FetchRegistry {tag,package,..}=> {assert_eq!(package.sha(),sha);*tag},_=>panic!("registry GET")}; + let tag=match &fx[0] {HudEffect::FetchRegistry {tag,package,..}=> {assert_eq!(package.sha(),sha);*tag},HudEffect::Catalog(_) | HudEffect::ScanDir { .. } | HudEffect::ReadFile { .. } | HudEffect::WriteFile { .. } | HudEffect::Delete { .. } | HudEffect::Fetch { .. } | HudEffect::Validate { .. } | HudEffect::Selection { .. } | HudEffect::Notice(_) => panic!("registry GET")}; let mut answer=vec![]; rig.m.step(HudEvent::Fetched {tag,result:Ok(if changed {pack("com.example.other","1.0.0")} else {bytes.clone()})},&mut answer); if changed { diff --git a/rust-modules/data/src/instruments.rs b/rust-modules/data/src/instruments.rs new file mode 100644 index 0000000000..f30f0297a1 --- /dev/null +++ b/rust-modules/data/src/instruments.rs @@ -0,0 +1,4 @@ +//! Diagnostic timers only; these readings never enter machine state. +use std::time::{Duration, Instant}; +pub(crate) fn start() -> Instant { Instant::now() } +pub(crate) fn elapsed(started: Instant) -> Duration { started.elapsed() } diff --git a/rust-modules/data/src/lib.rs b/rust-modules/data/src/lib.rs index 8a91a7a7fa..041d3c81a6 100644 --- a/rust-modules/data/src/lib.rs +++ b/rust-modules/data/src/lib.rs @@ -22,6 +22,7 @@ pub mod pms; // the Home catalog: hubs merged across every source pub mod sortfacts; // one name and one direction wording per sort fact, for the Library's and the Watchlist's Sort & Filter panels pub mod subsearch; // the player's subtitle search & download: agent search, install, install poll pub mod search; // Search data layer: /hubs/search fanned out across every source, merged into typed shelves +mod instruments; pub mod stores; // stores as machines (restructure phase 4): one command vocabulary + one step per data store pub mod viewstate; // watched / unwatched / remove-from-deck: the PMS view-state WRITES, off the SDL thread pub mod watchlist; // plex.tv Watchlist: rows, match table, tile states, intent ledger, sort/filter @@ -29,3 +30,6 @@ pub mod viewledger; // the publish order of view-state edits, so a read in fligh #[cfg(test)] mod watchlist_guid_tests; + +#[cfg(test)] +mod captured_store_fixture; diff --git a/rust-modules/data/src/metadata.rs b/rust-modules/data/src/metadata.rs index 24fa466b43..4972bbc71e 100644 --- a/rust-modules/data/src/metadata.rs +++ b/rust-modules/data/src/metadata.rs @@ -1575,6 +1575,8 @@ pub struct Detail { /// Host-captured dev input; never recorded and neutral on decode. Some(empty) forces no credit. #[serde(skip, default)] pub source_override: Option, + #[serde(skip, default)] + pub source_credit: String, /// Which SERVER this item was fetched from, as the OWNER'S HANDLE ("friend") — empty whenever /// it came from the signed-in user's own server, which is every item today. /// @@ -1804,11 +1806,7 @@ impl Detail { /// value at live launch/held execution in the host, not at draw time. Controlled host entry /// creates a fresh owner and controlled installation neutralizes the retained override. pub fn source(&self) -> String { - self.source_override.clone().unwrap_or_else(|| { - plx_plex::plex::server_facts(self.sid) - .map(|f| f.handle.clone()) - .unwrap_or_default() - }) + self.source_override.as_ref().unwrap_or(&self.source_credit).clone() } /// How many tiles the Cast & Crew shelf holds: every actor, then every crew credit. @@ -2269,6 +2267,7 @@ fn fetch_detail(client: &'static plx_plex::plex::Client, sid: plx_plex::plex::Se let mut d = Detail { sid, source_override: None, + source_credit: String::new(), rk: rk.to_string(), // the portable identity — what "Also available" resolves across the other sources guid: it.guid.clone(), @@ -3730,7 +3729,7 @@ pub fn fetch_full(client: &'static plx_plex::plex::Client, sid: plx_plex::plex:: // `ms=` is the whole chain's wall clock. It is the exact cost `request_detail` moves off the // SDL loop, so it is the number to read when judging whether a call site can afford to block // — note the framedrop breakdown CANNOT show it (fd_pc0 starts after event handling). - let t0 = std::time::Instant::now(); + let t0 = crate::instruments::start(); // The ONE line that says a detail page was asked for and got nothing — the summary at the end // of this function prints on success only, and nothing downstream can speak for the failure. // Its worst shape is the page opened through `detail::open_rk`, which clears before requesting: @@ -3838,7 +3837,7 @@ pub fn fetch_full(client: &'static plx_plex::plex::Client, sid: plx_plex::plex:: plx_base::eventlog::log(&format!( "detail: sid={} rk={} show={} genres={} cast={} crew={} seasons={} eps={} related={} collection={} audio={} subs={} trailer={} extras={} ms={}", d.sid.raw(), d.rk, d.is_show, d.genres.len(), d.cast.len(), d.crew.len(), d.seasons.len(), d.episodes.len(), - d.related.len(), d.collection.as_ref().map_or(0, |c| c.members.len()), d.audio.len(), d.subs.len(), u8::from(d.trailer().is_some()), extras_src, t0.elapsed().as_millis() + d.related.len(), d.collection.as_ref().map_or(0, |c| c.members.len()), d.audio.len(), d.subs.len(), u8::from(d.trailer().is_some()), extras_src, crate::instruments::elapsed(t0).as_millis() )); Some(d) } @@ -4130,8 +4129,13 @@ pub fn finish_detail_fetch( /// `#[cfg(test)]` arms (`AltInstall`, `AltRestampOwners`) exist only so tests can seed the /// alt-sources store the way a landed resolve or a facts-epoch move would — production reaches /// both through `pump_alt_sources`, a same-file call, never as a dispatched `Cmd`. +#[cfg(any(test, feature = "test-support"))] pub fn run(state: &mut MetadataState, adapter: &std::sync::Arc, cmd: crate::stores::metadata::MetadataCmd) -> bool { + run_with_keys(state, adapter, cmd, Some(&crate::pms::registry_keys_for_test())) +} +pub fn run_with_keys(state: &mut MetadataState, adapter: &std::sync::Arc, cmd: crate::stores::metadata::MetadataCmd, keys: Option<&plx_plex::plex::ClientKeys>) -> bool { use crate::stores::metadata::MetadataCmd; + let _ = keys; match cmd { MetadataCmd::RequestDetail { sid, rk } => { let prefer = selected_season_number(state, sid, &rk); @@ -4201,9 +4205,15 @@ pub fn run(state: &mut MetadataState, adapter: &std::sync::Arc, true } #[cfg(any(test, feature = "test-support"))] - MetadataCmd::AltInstall { sid, rk, copies } => alt_install(state, sid, &rk, copies), + MetadataCmd::AltInstall { sid, rk, copies } => { + let Some(keys) = keys else { debug_assert!(false, "Metadata AltInstall requires captured keys"); return false; }; + alt_install(state, sid, &rk, copies, keys) + }, #[cfg(any(test, feature = "test-support"))] - MetadataCmd::AltRestampOwners => alt_restamp_owners(state), + MetadataCmd::AltRestampOwners => { + let Some(keys) = keys else { debug_assert!(false, "Metadata AltRestampOwners requires captured keys"); return false; }; + alt_restamp_owners(state, keys) + }, } } @@ -4221,7 +4231,7 @@ pub fn pump_detail_with_gate(state: &mut MetadataState, adapter: &std::sync::Arc // Under a replay this drains on the frame the recording drained it on (§3.3 step 3, // `plx_machine::landgate`); off one it is the same call. The gate wraps the QUEUE drain and not the // supersede/install below, so a held frame leaves the record in the landing untouched. - let out = if crate::stores::tape::active() { + let out = if controlled { crate::stores::take_landings(gate, crate::stores::StoreId::Metadata, || { crate::stores::tape::poll_apply("metadata", 0, || record::drain_live(adapter, &want), |replies| record::supply(adapter, replies, &want)) @@ -4244,7 +4254,7 @@ pub fn pump_detail_with_gate(state: &mut MetadataState, adapter: &std::sync::Arc out }) }; - let mut fresh = false; + let mut fresh = restamp_detail_source(state, keys); for rec in out { let gen = rec.addr.req.0; if gen != adapter.detail_gen.load(Ordering::SeqCst) { @@ -4274,10 +4284,21 @@ pub fn pump_detail(state: &mut MetadataState, /// reached `fetch_full`'s line. `task`'s panic logger names the thread and the source location, /// so the failure is in the log — it just is not in these words, and a `None` here with no /// `detail:` line above it is that case. +fn restamp_detail_source(state: &mut MetadataState, keys: &plx_plex::plex::ClientKeys) -> bool { + let Some(detail) = state.current.as_mut() else { return false }; + let credit = keys.facts(detail.sid).and_then(|facts| facts.described) + .map_or("", |facts| facts.handle.as_str()); + if detail.source_credit == credit { return false; } + detail.source_credit.clear(); + detail.source_credit.push_str(credit); + true +} fn install_landed_detail(state: &mut MetadataState, adapter: &std::sync::Arc, d: Option, keys: &plx_plex::plex::ClientKeys, controlled: bool) -> bool { let Some(mut d) = d else { return false }; if controlled { d.source_override = None; } + d.source_credit = keys.facts(d.sid).and_then(|facts| facts.described) + .map(|facts| facts.handle.clone()).unwrap_or_default(); // The LANDING is what defines which show's episodes are current, so the season supersede has // to happen here as well as at request time: a tab hop issued while this load was in flight // spawned a fetch against the OLD item, and its landing would patch these fresh episodes. @@ -4468,6 +4489,7 @@ struct AltStore { /// Which item the stand-in has already had its one chance at, so it is built ONCE per item /// rather than on every frame. stand_in_rk: String, + clients: plx_plex::plex::ClientKeys, } /// The copies held for `(sid, rk)` — EMPTY for any other item, and for an item nothing has landed @@ -4509,13 +4531,14 @@ fn alt_install( item_sid: plx_plex::plex::ServerId, item_rk: &str, list: Vec, + keys: &plx_plex::plex::ClientKeys, ) -> bool { let mut list = list; // **The worker's stamp is not trusted.** `resolve_alt_sources` reads the credit on a background // thread, and a resolve dispatched before a roster refresh re-grades that credit lands after // it — past `pump_alt_sources`' facts epoch, which it has already consumed. Regrading here is // the only point that sees both the list and the current answer. - alt_regrade(&mut list, false); + alt_regrade(&mut list, false, keys); let held = &mut state.alt; let same = plx_plex::plex::same_item((held.sid, held.rk.as_str()), (item_sid, item_rk)) && held.copies == list @@ -4543,10 +4566,10 @@ fn alt_install( /// **MAIN THREAD**, like every other reader and writer of this store — [`pump_alt_sources`] is its /// only caller and runs on the SDL loop. The workers in this chain touch the mutex-protected /// result slot and never the store. -fn alt_restamp_owners(state: &mut MetadataState) -> bool { +fn alt_restamp_owners(state: &mut MetadataState, keys: &plx_plex::plex::ClientKeys) -> bool { let held = &mut state.alt; let stand_in = held.stand_in; - alt_regrade(&mut held.copies, stand_in) + alt_regrade(&mut held.copies, stand_in, keys) } /// **Re-read a copy list's CREDITS from the registry**, `true` when any of them moved. @@ -4566,13 +4589,13 @@ fn alt_restamp_owners(state: &mut MetadataState) -> bool { /// what it was for one round, and is a different statement. A real resolve can land over a stand-in /// list, and an armed-but-EMPTY trigger builds no stand-in at all; on both, "armed" would have gone /// on suppressing the regrade for a list the stand-in does not own. -fn alt_regrade(list: &mut [AltCopy], stand_in_owns: bool) -> bool { +fn alt_regrade(list: &mut [AltCopy], stand_in_owns: bool, keys: &plx_plex::plex::ClientKeys) -> bool { if stand_in_owns { return false; } let mut moved = false; for c in list.iter_mut() { - let credit = plx_plex::plex::server_facts(c.sid) + let credit = keys.facts(c.sid).and_then(|facts| facts.described) .map(|f| f.handle.clone()) .unwrap_or_default(); // `None` is the absence of an owner and must not become `Some("")` — the same guard @@ -4681,14 +4704,15 @@ fn request_alt_sources( use std::sync::atomic::Ordering; let mut slot = adapter.alt_slot.lock().unwrap_or_else(|e| e.into_inner()); let gen = adapter.alt_gen.fetch_add(1, Ordering::SeqCst) + 1; - let roster_gen = plx_plex::plex::server_roster_gen(); + let roster_gen = keys.roster_gen(); + if state.alt.clients != *keys { state.alt.clients.clone_from(keys); } adapter.alt_roster_gen.store(roster_gen, Ordering::SeqCst); *slot = None; if guid.is_empty() { adapter.alt_done.fetch_max(gen, Ordering::SeqCst); return; } - let others: Vec = plx_plex::plex::server_ids().collect(); + let others: Vec = keys.slots().collect(); if others.len() < 2 { adapter.alt_done.fetch_max(gen, Ordering::SeqCst); return; @@ -4745,7 +4769,7 @@ fn resolve_alt_sources_with( let Some(mc) = read(id, c, guid) else { continue; }; - let handle = plx_plex::plex::server_facts(id) + let handle = clients.facts(id).and_then(|facts| facts.described) .map(|f| f.handle.clone()) .unwrap_or_default(); out.extend(alt_copies_from(id, &handle, &mc)); @@ -4874,7 +4898,7 @@ impl AltSourcesPass<'_> { pub fn take_request(&mut self) -> Option { self.request.take() } pub fn finish(self, answer: Option, gate: &plx_machine::landgate::Gate) -> bool { use std::sync::atomic::Ordering; - let Self { state, adapter, roster_gen, gen, mut changed, identity, .. } = self; + let Self { state, adapter, _keys: keys, roster_gen, gen, mut changed, identity, .. } = self; if gen != adapter.alt_gen.load(Ordering::SeqCst) { return false; } if let Some(answer) = answer { if !identity.as_ref().is_some_and(|id| std::sync::Arc::ptr_eq(id, &answer.identity)) { return false; } @@ -4898,7 +4922,7 @@ impl AltSourcesPass<'_> { let Some(r) = taken else { return changed }; adapter.alt_done.fetch_max(r.gen, Ordering::SeqCst); if r.gen != adapter.alt_gen.load(Ordering::SeqCst) || r.roster_gen != roster_gen { return changed; } - changed | alt_install(state, r.sid, &r.rk, r.list) + changed | alt_install(state, r.sid, &r.rk, r.list, keys) } } @@ -4910,8 +4934,9 @@ fn pump_alt_sources_with_library<'a>( ) -> AltSourcesPass<'a> { use std::sync::atomic::Ordering; let mut changed = false; - let roster_gen = plx_plex::plex::server_roster_gen(); - if adapter.alt_roster_gen.swap(roster_gen, Ordering::SeqCst) != roster_gen { + let roster_gen = keys.roster_gen(); + if adapter.alt_roster_gen.swap(roster_gen, Ordering::SeqCst) != roster_gen + || !state.alt.clients.slots().eq(keys.slots()) || !state.alt.clients.iter().eq(keys.iter()) { // Same lock protocol as request generation/clear and port publication. let mut slot = adapter.alt_slot.lock().unwrap_or_else(|e| e.into_inner()); let gen = adapter.alt_gen.fetch_add(1, Ordering::SeqCst) + 1; @@ -4919,10 +4944,12 @@ fn pump_alt_sources_with_library<'a>( *slot = None; changed |= alt_prune_inactive(state, keys); } - let facts_gen = plx_plex::plex::server_facts_gen(); - if adapter.alt_facts_gen.swap(facts_gen, Ordering::SeqCst) != facts_gen { - changed |= alt_restamp_owners(state); + let facts_gen = keys.facts_gen(); + if adapter.alt_facts_gen.swap(facts_gen, Ordering::SeqCst) != facts_gen || state.alt.clients != *keys { + changed |= alt_restamp_owners(state, keys); } + if state.alt.clients != *keys { state.alt.clients.clone_from(keys); } + changed |= restamp_detail_source(state, keys); // Allocate pass identity only for a due request; ordinary/not-due frames allocate nothing. // Controlled suppression precedes chance consumption and ALL host IO/cache access. let request = if controlled { None } else { @@ -6767,3 +6794,7 @@ mod alt_runtime_tests { } } } + +#[cfg(test)] +#[path = "metadata/captured_inputs_tests.rs"] +mod captured_inputs_tests; diff --git a/rust-modules/data/src/metadata/captured_inputs_tests.rs b/rust-modules/data/src/metadata/captured_inputs_tests.rs new file mode 100644 index 0000000000..15dc580b4b --- /dev/null +++ b/rust-modules/data/src/metadata/captured_inputs_tests.rs @@ -0,0 +1,43 @@ +use super::*; +use crate::captured_store_fixture::{key, roster}; +use plx_machine::job::Port; +use std::sync::atomic::Ordering; +fn copy(sid: plx_plex::plex::ServerId, owner: &str) -> AltCopy { + AltCopy { sid, library: "Library".into(), owner: Some(owner.into()), rk: "4".into(), + dur_ms: 1000, res: "1080".into(), width: 1920, height: 1080 } +} +#[test] +fn captured_alt_scope_regrades_facts_without_retiring_work_and_fences_same_generation_key_moves() { + let _serial = plx_base::testlock::serial(); + let a = roster(&[(61, Some(key(1)), "captured"), (101, None, "unkeyed")], 3, 4); + let sid = plx_plex::plex::ServerId::from_raw(61); + let mut state = MetadataState::default(); + state.current = Some(Detail { sid, rk: "4".into(), ..Default::default() }); + let adapter = std::sync::Arc::new(MetadataAdapter::default()); + request_alt_sources(&mut state, &adapter, sid, "4", "plex://movie/script", &a); + let crate::stores::StoreJob::MetaAltSources(job, port) = state.jobs.pop().unwrap() else { panic!("alt job") }; + assert_eq!(job.req.others.iter().map(|s| s.raw()).collect::>(), [61, 101], "all registered slots, not Browse's partial projection"); + assert_eq!(job.req.keys.iter().count(), 1, "eligibility is still a full-key lookup"); + let generation = adapter.alt_gen.load(Ordering::SeqCst); + let b = roster(&[(61, Some(key(1)), "corrected"), (101, None, "unkeyed")], 3, 4); + let gate = plx_machine::landgate::Gate::default(); + pump_alt_sources_with_library(&mut state, &adapter, &b, true).finish(None, &gate); + assert_eq!(adapter.alt_gen.load(Ordering::SeqCst), generation, "facts-only regrading does not discard a valid resolve"); + assert_eq!(state.current.as_ref().unwrap().source(), "corrected"); + port.done(job.addr, vec![copy(sid, "stale worker credit")]); + assert!(pump_alt_sources_with_library(&mut state, &adapter, &b, true).finish(None, &gate)); + assert_eq!(state.alt.copies[0].owner.as_deref(), Some("corrected"), "landing regrades even after the facts epoch was consumed"); + request_alt_sources(&mut state, &adapter, sid, "4", "plex://movie/script", &b); + let crate::stores::StoreJob::MetaAltSources(old, old_port) = state.jobs.pop().unwrap() else { panic!("alt job") }; + let c = roster(&[(61, Some(key(2)), "corrected"), (101, None, "unkeyed")], 3, 4); + pump_alt_sources_with_library(&mut state, &adapter, &c, true).finish(None, &gate); + assert_ne!(adapter.alt_gen.load(Ordering::SeqCst), old.addr.req.0); + old_port.done(old.addr, vec![copy(sid, "late")]); + assert!(adapter.alt_slot.lock().unwrap_or_else(|e| e.into_inner()).is_none(), "the old full key cannot fill the replacement mailbox"); + request_alt_sources(&mut state, &adapter, sid, "4", "plex://movie/script", &c); + let crate::stores::StoreJob::MetaAltSources(refused, refused_port) = state.jobs.pop().unwrap() else { panic!("alt job") }; + refused_port.refused(refused.addr); + pump_alt_sources_with_library(&mut state, &adapter, &c, true).finish(None, &gate); + assert_eq!(adapter.alt_done.load(Ordering::SeqCst), adapter.alt_gen.load(Ordering::SeqCst), "refusal settles the addressed request"); + assert!(state.jobs.is_empty()); +} diff --git a/rust-modules/data/src/metadata_alt_sources_job_tests.rs b/rust-modules/data/src/metadata_alt_sources_job_tests.rs index 66325cbf09..709cba2f60 100644 --- a/rust-modules/data/src/metadata_alt_sources_job_tests.rs +++ b/rust-modules/data/src/metadata_alt_sources_job_tests.rs @@ -9,7 +9,7 @@ fn roster() -> (ServerId, ServerId, ClientKeys) { plx_plex::plex::reset_servers_for_test(); let a = plx_plex::plex::register_for_test("m4-a", "127.0.0.1", 9, "a", "cid"); let b = plx_plex::plex::register_for_test("m4-b", "127.0.0.1", 9, "b", "cid"); - (a, b, ClientKeys::of([a, b].map(|s| (s, plx_plex::plex::client_for(s).unwrap())))) + (a, b, crate::pms::registry_keys_for_test()) } fn ask(state: &mut MetadataState, adapter: &Arc, sid: ServerId, keys: &ClientKeys) -> (plx_machine::machine::Addr, MetaAltSourcesReq, MetaAltSourcesPort) { @@ -30,7 +30,7 @@ fn exact_job_addr_whole_snapshot_and_origin_inclusive_roster_start_nothing() { let _serial = plx_base::testlock::serial(); let (a, b, mut keys) = roster(); let extra = ServerId::from_raw(999); - keys.refill(keys.clone().iter().chain([(extra, plx_plex::plex::ClientKey { instance: 7, token: 8, grant: 9 })])); + keys.replace_keys_for_test(keys.clone().iter().chain([(extra, plx_plex::plex::ClientKey { instance: 7, token: 8, grant: 9 })])); let mut state = MetadataState::default(); let adapter = Arc::new(MetadataAdapter::default()); let (addr, req, port) = ask(&mut state, &adapter, a, &keys); @@ -57,6 +57,7 @@ fn no_guid_or_one_roster_slot_settles_without_a_job() { assert_eq!(adapter.alt_done.load(Ordering::SeqCst), 1); plx_plex::plex::reset_servers_for_test(); let a = plx_plex::plex::register_for_test("one", "127.0.0.1", 9, "a", "cid"); + let keys = crate::pms::registry_keys_for_test(); request_alt_sources(&mut state, &adapter, a, "x", "guid", &keys); assert!(state.jobs.is_empty()); assert_eq!(adapter.alt_done.load(Ordering::SeqCst), 2); @@ -188,6 +189,7 @@ fn ready_real_result_wins_registration_in_the_same_pass_and_next_pass_sees_new_r assert_eq!(adapter.alt_gen.load(Ordering::SeqCst), addr.req.0, "no invalidation between begin/finish"); assert_eq!(state.alt.copies[0].rk, "real", "real replaces stand-in in SAME pass"); assert!(!state.alt.stand_in); + let keys = crate::pms::registry_keys_for_test(); begin_alt_sources(&mut state, &adapter, &keys, false).finish(None, plx_machine::landgate::fixture_gate()); assert!(adapter.alt_gen.load(Ordering::SeqCst) > addr.req.0, "NEXT pass observes registration"); } @@ -284,6 +286,7 @@ fn reset_rotates_alt_identity_and_a_retired_completion_cannot_reach_the_same_ite assert!(!alt_sources_owed_for_test(store.adapter_ref())); assert!(!alt_sources_ready_for_test(store.adapter_ref())); let mut witness = MetadataState::default(); + witness.alt.clients.clone_from(&keys); assert!(pump_alt_sources(&mut witness, &old, &keys, true, None)); assert_eq!(alt_copies(&witness, sid, "item")[0].rk, "retired"); assert!(!alt_sources_owed_for_test(&old)); diff --git a/rust-modules/data/src/metadata_detail_mailbox_tests.rs b/rust-modules/data/src/metadata_detail_mailbox_tests.rs index 81252cb418..1ece749462 100644 --- a/rust-modules/data/src/metadata_detail_mailbox_tests.rs +++ b/rust-modules/data/src/metadata_detail_mailbox_tests.rs @@ -298,6 +298,8 @@ fn a_server_without_the_film_contributes_no_row() { fn an_alt_sources_landing_for_another_servers_copy_with_the_same_key_is_refused() { let _serial = plx_base::testlock::serial(); alt_clear(test_state()); + let keys = crate::pms::registry_keys_for_test(); + test_state().alt.clients.clone_from(&keys); // two copies on two sources — enough for the gate, which counts distinct SOURCES let copies = || { vec![ @@ -314,10 +316,10 @@ fn an_alt_sources_landing_for_another_servers_copy_with_the_same_key_is_refused( ] }; let land = |gen: u32, sid: plx_plex::plex::ServerId, rk: &str| { - test_adapter().alt_roster_gen.store(plx_plex::plex::server_roster_gen(), Ordering::SeqCst); + test_adapter().alt_roster_gen.store(keys.roster_gen(), Ordering::SeqCst); *test_adapter().alt_slot.lock().unwrap() = Some(AltResult { gen, - roster_gen: plx_plex::plex::server_roster_gen(), + roster_gen: keys.roster_gen(), sid, rk: rk.to_string(), list: copies(), @@ -328,7 +330,7 @@ fn an_alt_sources_landing_for_another_servers_copy_with_the_same_key_is_refused( let gen = test_adapter().alt_gen.fetch_add(1, Ordering::SeqCst) + 1; // …and while it is out the user lands on the SHARE's film 4 land(gen, SRV_A, "4"); - pump_alt_sources(test_state(), test_adapter(), &plx_plex::plex::ClientKeys::default(), false, None); + pump_alt_sources(test_state(), test_adapter(), &keys, false, None); assert!( !alt_available(test_state(), SRV_B, "4"), "our copies are not news about the share's film" @@ -342,7 +344,7 @@ fn an_alt_sources_landing_for_another_servers_copy_with_the_same_key_is_refused( let stale = test_adapter().alt_gen.fetch_add(1, Ordering::SeqCst) + 1; test_adapter().alt_gen.fetch_add(1, Ordering::SeqCst); land(stale, SRV_A, "4"); - pump_alt_sources(test_state(), test_adapter(), &plx_plex::plex::ClientKeys::default(), false, None); + pump_alt_sources(test_state(), test_adapter(), &keys, false, None); assert!( !alt_available(test_state(), SRV_A, "4"), "a landing from a superseded resolve is dropped" @@ -370,7 +372,7 @@ fn an_alt_source_from_a_revoked_slot_is_pruned_and_its_inflight_result_is_discar }, ]; alt_clear(test_state()); - alt_install(test_state(), a, "4", copies.clone()); + alt_install(test_state(), a, "4", copies.clone(), &crate::pms::registry_keys_for_test()); assert!(alt_available(test_state(), a, "4")); let old_roster = plx_plex::plex::server_roster_gen(); diff --git a/rust-modules/data/src/metadata_dump_tests.rs b/rust-modules/data/src/metadata_dump_tests.rs index ba767e435d..9b81b80915 100644 --- a/rust-modules/data/src/metadata_dump_tests.rs +++ b/rust-modules/data/src/metadata_dump_tests.rs @@ -139,7 +139,9 @@ fn dump_mode_an_alt_request_out_lands_on_the_pump_that_runs_whatever_the_worker( plx_plex::plex::reset_servers_for_test(); alt_clear(test_state()); let adapter = Arc::clone(test_adapter()); - let roster = plx_plex::plex::server_roster_gen(); + let keys = crate::pms::registry_keys_for_test(); + test_state().alt.clients.clone_from(&keys); + let roster = keys.roster_gen(); adapter.alt_roster_gen.store(roster, Ordering::SeqCst); let gen = adapter.alt_gen.fetch_add(1, Ordering::SeqCst) + 1; // a request is out: not settled let worker = Arc::clone(&adapter); @@ -150,7 +152,7 @@ fn dump_mode_an_alt_request_out_lands_on_the_pump_that_runs_whatever_the_worker( }); }); let gate = dump_gate(std::time::Duration::from_secs(20)); - assert!(pump_alt_sources_with_gate(test_state(), &adapter, &plx_plex::plex::ClientKeys::default(), false, None, &gate), + assert!(pump_alt_sources_with_gate(test_state(), &adapter, &keys, false, None, &gate), "the answer the pump owed must be taken by the pump that asked"); assert!(alt_available(test_state(), SRV_A, "4")); assert_eq!(adapter.alt_done.load(Ordering::SeqCst), gen, "the take settled the request"); @@ -165,7 +167,9 @@ fn dump_mode_a_superseded_alt_requests_stale_answer_does_not_end_the_wait() { plx_plex::plex::reset_servers_for_test(); alt_clear(test_state()); let adapter = Arc::clone(test_adapter()); - let roster = plx_plex::plex::server_roster_gen(); + let keys = crate::pms::registry_keys_for_test(); + test_state().alt.clients.clone_from(&keys); + let roster = keys.roster_gen(); adapter.alt_roster_gen.store(roster, Ordering::SeqCst); let stale = adapter.alt_gen.fetch_add(1, Ordering::SeqCst) + 1; let gen = adapter.alt_gen.fetch_add(1, Ordering::SeqCst) + 1; // supersedes the first @@ -181,7 +185,7 @@ fn dump_mode_a_superseded_alt_requests_stale_answer_does_not_end_the_wait() { }); }); let gate = dump_gate(std::time::Duration::from_secs(20)); - assert!(pump_alt_sources_with_gate(test_state(), &adapter, &plx_plex::plex::ClientKeys::default(), false, None, &gate), + assert!(pump_alt_sources_with_gate(test_state(), &adapter, &keys, false, None, &gate), "the current request was out when the pump ran, so its answer lands on this pump"); assert!(alt_available(test_state(), SRV_A, "4")); join.join().unwrap(); diff --git a/rust-modules/data/src/metadata_watch_state_tests.rs b/rust-modules/data/src/metadata_watch_state_tests.rs index d83faaf34e..dd2abc3cf0 100644 --- a/rust-modules/data/src/metadata_watch_state_tests.rs +++ b/rust-modules/data/src/metadata_watch_state_tests.rs @@ -35,14 +35,16 @@ fn a_mounted_detail_page_follows_a_corrected_credit() { rk: "42".into(), ..Default::default() })); + pump_detail(test_state(), test_adapter(), &crate::pms::registry_keys_for_test(), false); assert_eq!(current(test_state()).unwrap().source(), "admin"); // the roster refresh re-grades it, with nothing touching the mounted page plx_plex::plex::describe_server(house, "Mac mini", "", plx_plex::plex::GrantEvidence::outside()); + pump_detail(test_state(), test_adapter(), &crate::pms::registry_keys_for_test(), false); assert_eq!( current(test_state()).unwrap().source(), "", - "the page re-asks the registry rather than carrying a copy taken at fetch time" + "the page follows captured facts rather than carrying a stale worker credit" ); // and a share is still credited, so this is not a blanket clear @@ -53,6 +55,7 @@ fn a_mounted_detail_page_follows_a_corrected_credit() { rk: "318".into(), ..Default::default() })); + pump_detail(test_state(), test_adapter(), &crate::pms::registry_keys_for_test(), false); assert_eq!(current(test_state()).unwrap().source(), "friend"); set_current_for_test(test_state(), None); diff --git a/rust-modules/data/src/person.rs b/rust-modules/data/src/person.rs index 7cbc84c124..2ded58985a 100644 --- a/rust-modules/data/src/person.rs +++ b/rust-modules/data/src/person.rs @@ -274,7 +274,7 @@ pub struct Person { /// re-registered at the same origin and a live token is refreshed in place; every fetched shelf /// is still true then, so [`sync_roster`] keeps the page instead of drawing its skeleton again. /// `None` until a pump has read the registry's answer. - roster_sig: Option>, + roster_sig: Option)>>, } impl Person { @@ -331,6 +331,25 @@ impl<'a> PersonView<'a> { /// Main-thread logical state for one Person owner. Generation, retry ladders and the dev-seed /// latch move with the model instead of selecting process state. +/// All authority used by one Person pass, captured by the host before Open or pump. +/// The complete registered-slot roster is borrowed from the host's ONE retained ClientKeys. +#[derive(Clone, Copy)] +pub struct PersonInput<'a> { + pub keys: &'a ClientKeys, + pub session: Option<&'a Arc>, + pub visible_generation: u64, + pub profile_scope: u32, + pub owner_epoch: u64, + pub profile_generation: u32, + pub tenure: u64, + pub profile_key: &'a str, + pub controlled: bool, + pub profile_refused: bool, + pub credits_refused: bool, + pub dev_bio: Option<&'a str>, + pub dev_credits: Option<&'a str>, +} + pub struct PersonState { /// The publish order of view-state edits, shared by `stores::Stores`. pub(crate) ledger: crate::viewledger::ViewLedger, @@ -343,8 +362,10 @@ pub struct PersonState { revision: u64, retry_cd: Backoffs, dev_held: usize, - session_watch: plx_plex::plex::session::VisibleSessionWatch, + dev_seed: String, session_identity: (String, String), + profile_scope: Option<(u32, u64, u32, u64)>, + profile_key: String, /// Which servers may have a request out this pump ([`crate::stores::fanout`]). fanout: crate::stores::fanout::Fanout, /// The requests the pump has emitted and its owner has not yet taken, in the order they were @@ -367,8 +388,10 @@ impl Default for PersonState { revision: 0, retry_cd: Backoffs::default(), dev_held: usize::MAX, - session_watch: Default::default(), + dev_seed: String::new(), session_identity: Default::default(), + profile_scope: None, + profile_key: String::new(), fanout: Default::default(), jobs: Vec::new(), next_job: 0, @@ -380,6 +403,44 @@ impl PersonState { pub fn view(&self) -> PersonView<'_> { PersonView { current: self.current.as_ref(), revision: self.revision } } + /// Explicit owner/profile edges are authority changes even during controlled playback. + /// Unsettled recovery alone does not invent a signed-out identity. + fn observe_session(&mut self, adapter: &PersonAdapter, input: &PersonInput<'_>) -> bool { + let scope = (input.profile_scope, input.owner_epoch, input.profile_generation, input.tenure); + let scope_changed = self.profile_scope.is_some_and(|old| old != scope || self.profile_key != input.profile_key); + self.profile_scope = Some(scope); + if self.profile_key != input.profile_key { + self.profile_key.clear(); + self.profile_key.push_str(input.profile_key); + } + let identity_changed = !input.controlled && input.session.is_some_and(|session| + self.session_identity.0 != session.client_id || self.session_identity.1 != session.account_token); + if !input.controlled { + if let Some(session) = input.session { + self.session_identity.0.clone_from(&session.client_id); + self.session_identity.1.clone_from(&session.account_token); + } + } + if !scope_changed && !identity_changed { return false; } + self.supersede(adapter); + let Some(person) = &mut self.current else { return false }; + // Hold only the mounted header. All account/server-derived facts must be re-established. + person.srcs = sources(person.sid, &person.key, &person.name, input.keys); + person.roster_gen = input.keys.roster_gen(); + person.roster_sig = Some(roster_sig(input.keys)); + person.shelves = Default::default(); + person.bio.clear(); + person.roles.clear(); + person.born.clear(); + person.died.clear(); + person.birthplace.clear(); + person.credits.clear(); + person.profiled = false; + person.profile_tried = false; + person.credited = false; + resettle(person); + true + } fn current(&self) -> Option<&Person> { self.current.as_ref() @@ -651,7 +712,25 @@ type Fetch = crate::stores::Fetch; /// Cross-thread transport for one physical owner. Every worker captures this exact `Arc`; reset /// rotates the store to a fresh adapter, so a detached old worker can only fill retired slots. +struct PendingPerson { + addr: Addr, + request: Arc, + terminal: bool, +} + +struct PersonLaunchRefused { + addr: Addr, + request: Arc, +} + +#[derive(Default)] +struct PersonTerminals { + pending: std::collections::BTreeMap, + refused: Vec, +} + pub struct PersonAdapter { + terminals: std::sync::Mutex, /// One mailbox per fetch index ever used, created on first use by [`PersonAdapter::mailbox`]. /// Behind a lock because the workers share the table, and a mailbox has to exist before its /// first landing can reach it. @@ -660,7 +739,7 @@ pub struct PersonAdapter { impl Default for PersonAdapter { fn default() -> Self { - Self { fetch: Default::default() } + Self { fetch: Default::default(), terminals: Default::default() } } } @@ -690,9 +769,12 @@ impl PersonAdapter { self.table().iter().filter(|(_, f)| f.outstanding()).map(|(&i, _)| i).collect() } - /// Drop every mailbox with its claim. A worker that lands afterwards recreates its entry, which - /// [`PersonAdapter::outstanding`] then reports until the pump discards the stale answer. + /// Retire every request identity and mailbox together. A detached old port can no longer + /// post into this adapter, even if a replacement has reclaimed the same slot. fn clear_all(&self) { + let mut terminals = self.terminals.lock().unwrap_or_else(|e| e.into_inner()); + terminals.pending.clear(); + terminals.refused.clear(); let mut table = self.table(); for f in table.values() { f.clear(); @@ -723,6 +805,10 @@ impl PersonState { .expect("person generation exhausted"); adapter.clear_all(); self.retry_cd.clear(); + self.stamps.clear(); + self.jobs.clear(); + self.dev_held = usize::MAX; + self.dev_seed.clear(); } } @@ -740,9 +826,9 @@ impl PersonState { /// credential they hold change ([`sync_roster`]; a generation that moved over none of these keeps /// the sources). The roster is tiny; rebuilding only at that explicit boundary prevents an open /// page retaining a revoked share or missing a new one. -fn sources(origin: ServerId, key: &str, name: &str) -> Vec { +fn sources(origin: ServerId, key: &str, name: &str, keys: &ClientKeys) -> Vec { let mut out: Vec = Vec::new(); - for sid in plx_plex::plex::server_ids().chain(std::iter::once(origin)) { + for sid in keys.slots().chain(std::iter::once(origin)) { if fx(sid, K_RESOLVE).is_none() || out.iter().any(|s| s.sid == sid) { continue; } @@ -971,25 +1057,26 @@ fn open( guid: &str, name: &str, thumb: &str, + input: &PersonInput<'_>, ) { + let scope_changed = state.observe_session(adapter, input); if state .current .as_ref() .is_some_and(|p| plx_plex::plex::same_item((p.sid, p.key.as_str()), (sid, key))) { + state.revision += u64::from(scope_changed); return; } - // Controlled content uses captured authority and supplied provider replies. The ambient - // session cache recovers asynchronously and is not an input in that transcript. - if !crate::stores::tape::active() { - let _ = state.session_watch.changed(); - if let Some(session) = plx_plex::plex::session::peek_settled() { - state.session_identity = (session.client_id.clone(), session.account_token.clone()); + if !input.controlled { + if let Some(session) = input.session { + state.session_identity.0.clone_from(&session.client_id); + state.session_identity.1.clone_from(&session.account_token); } } state.supersede(adapter); state.revision += 1; - let srcs = sources(sid, key, name); + let srcs = sources(sid, key, name, input.keys); state.current = Some(Person { sid, key: key.to_string(), @@ -1008,15 +1095,15 @@ fn open( profile_tried: false, credits: Vec::new(), credited: false, - roster_gen: plx_plex::plex::server_roster_gen(), - roster_sig: None, + roster_gen: input.keys.roster_gen(), + roster_sig: Some(roster_sig(input.keys)), }); // A page with NO source at all has already answered — see `resettle`'s fold. Deriving it // here rather than hardcoding `landed: false` is what keeps that rule in one place. if let Some(p) = state.current.as_mut() { resettle(p); - if !crate::stores::tape::active() { - seed_dev_profile(p); + if !input.controlled { + seed_dev_profile(p, input.dev_bio); } } } @@ -1049,14 +1136,14 @@ fn open( /// they are as fictional as the rest of the trigger and never reach a release build (`devtrig::read` is /// `None` at compile time without `devtriggers`). #[allow(unused_variables)] -fn seed_dev_profile(p: &mut Person) { - let Some(text) = plx_base::devtrig::read("personbio") else { +fn seed_dev_profile(p: &mut Person, text: Option<&str>) { + let Some(text) = text else { return; }; p.bio = if text.is_empty() { DEV_BIO.trim().replace("\\n", "\n").to_string() } else { - text + text.to_string() }; if p.roles.is_empty() { p.roles = vec![ @@ -1129,34 +1216,28 @@ fn reset(state: &mut PersonState, adapter: &PersonAdapter) { /// module boundary. Relocating it here is what lets those three go private — `set_watched_local` /// was already `pub` for the same reason and joins them. impl PersonState { - pub fn run( - &mut self, - adapter: &Arc, - cmd: crate::stores::person::PersonCmd, - ) -> bool { +pub fn run(&mut self, adapter: &Arc, cmd: crate::stores::person::PersonCmd) -> bool { use crate::stores::person::PersonCmd; match cmd { - PersonCmd::Open { - sid, - key, - guid, - name, - thumb, - } => { - open(self, adapter, sid, &key, &guid, &name, &thumb); - true - } - PersonCmd::Close => { - close(self, adapter); - true - } - PersonCmd::Reset => { - reset(self, adapter); - true + PersonCmd::Open { .. } => { + plx_base::eventlog::log("person: Open requires captured inputs — refused"); + debug_assert!(false, "Person Open requires captured inputs"); + false } + PersonCmd::Close => { close(self, adapter); true } + PersonCmd::Reset => { reset(self, adapter); true } PersonCmd::ApplyView { at, edit } => apply_view(self, &at, edit), } } + pub fn run_with_input(&mut self, adapter: &Arc, cmd: crate::stores::person::PersonCmd, + input: &PersonInput<'_>) -> bool { + if let crate::stores::person::PersonCmd::Open { sid, key, guid, name, thumb } = cmd { + open(self, adapter, sid, &key, &guid, &name, &thumb, input); + true + } else { + self.run(adapter, cmd) + } + } } /// Whether one server's contribution to this person's shelves is still unresolved. @@ -1200,23 +1281,10 @@ impl PersonState { /// pump (`tape::person_completion` is keyed by slot and generation), and the admissions stay in /// emission order. pub fn pump_with_gate(&mut self, adapter: &Arc, gate: &plx_machine::landgate::Gate, - keys: &ClientKeys) -> bool { - let mut session_changed = false; - if !crate::stores::tape::active() && self.session_watch.changed() { - if let Some(session) = plx_plex::plex::session::peek_settled() { - let identity = (session.client_id.clone(), session.account_token.clone()); - if self.session_identity != identity { - self.session_identity = identity; - self.supersede(adapter); - if let Some(person) = &mut self.current { - person.profiled = false; - person.credited = false; - session_changed = true; - } - } - } - } - let mut changed = sync_roster(self, adapter, keys) || session_changed; + input: &PersonInput<'_>) -> bool { + let session_changed = self.observe_session(adapter, input); + let mut changed = sync_roster(self, adapter, input) || session_changed; + changed |= self.take_launch_refusals(adapter); self.retry_cd.tick(); // Ascending, which is the order replay supplies recorded landings in. The work follows the // open page's sources plus whatever is outstanding, never the highest server id. @@ -1246,26 +1314,27 @@ impl PersonState { // wait for the next keypress to become visible. plx_machine::idle::invalidate(); if reply.gen == self.generation { + adapter.terminals.lock().unwrap_or_else(|e| e.into_inner()).pending.remove(&i); changed |= apply_landing(self, i, reply.what); } // A superseded landing is news about neither person. In particular, its failure // must not arm a retry delay for the replacement identity. } - maybe_spawn(self, adapter, i, &mut turn, keys); + changed |= maybe_spawn(self, adapter, i, &mut turn, input); } // The credits seed runs HERE rather than at `open`, unlike the biography's, and the difference // is what it needs: it joins itself against the shelves so the availability column and the // trailing chevron are actually visible, and the shelves do not exist until a landing. if self.current.is_some() { - changed |= seed_dev_credits(self); + changed |= seed_dev_credits(self, input.dev_credits); } self.revision += u64::from(changed); changed } #[cfg(any(test, feature = "test-support"))] - pub fn pump(&mut self, adapter: &Arc, keys: &ClientKeys) -> bool { - self.pump_with_gate(adapter, plx_machine::landgate::fixture_gate(), keys) + pub fn pump(&mut self, adapter: &Arc, input: &PersonInput<'_>) -> bool { + self.pump_with_gate(adapter, plx_machine::landgate::fixture_gate(), input) } } @@ -1289,10 +1358,7 @@ impl PersonState { /// and enough ABOVE it that the department strip overflows its column, which is the only way a /// headless capture reaches the strip's scroll and the left edge fade over its cut. #[allow(unused_variables)] -fn seed_dev_credits(state: &mut PersonState) -> bool { - let arg = if crate::stores::tape::active() { - crate::stores::tape::credits().map(|v| v.to_string()) - } else { plx_base::devtrig::read("personcredits") }; +fn seed_dev_credits(state: &mut PersonState, arg: Option<&str>) -> bool { let Some(arg) = arg else { return false; }; @@ -1320,10 +1386,12 @@ fn seed_dev_credits(state: &mut PersonState) -> bool { // it has nothing to work with until a source lands. A COUNT rather than a "have I seeded" flag, // because the real `/media` landing fills `Src::matches` itself and a flag keyed on that cannot // tell the source's own index apart from a seeded one. - if p.credited && state.dev_held == held.len() { + if p.credited && state.dev_held == held.len() && state.dev_seed == arg { return false; } state.dev_held = held.len(); + state.dev_seed.clear(); + state.dev_seed.push_str(arg); let n: usize = arg.trim().parse().unwrap_or(9); let row = |i: usize, dept: &str| { let (title, id, thumb) = match held.get(i) { @@ -1392,39 +1460,26 @@ fn seed_dev_credits(state: &mut PersonState) -> bool { /// a token rotation keeps it) and whose credential it holds (`ClientKey::grant`: a live token /// refreshed in place keeps it, a revocation moves it): what a page's sources and shelves /// depend on. -fn roster_sig(keys: &ClientKeys) -> Vec<(ServerId, u32, u32)> { - keys.iter().map(|(sid, key)| (sid, key.instance, key.grant)).collect() +fn roster_sig(keys: &ClientKeys) -> Vec<(ServerId, Option<(u32, u32)>)> { + keys.slots().map(|sid| (sid, keys.key(sid).map(|key| (key.instance, key.grant)))).collect() } /// Rebuild an open page's per-source projection at an exact registry identity boundary. Header /// profile facts survive; server-derived shelves and every old worker/mailbox do not. -fn sync_roster(state: &mut PersonState, adapter: &PersonAdapter, keys: &ClientKeys) -> bool { - let gen = plx_plex::plex::server_roster_gen(); - let Some((old, sid, key, name)) = - state.current().map(|p| (p.roster_gen, p.sid, p.key.clone(), p.name.clone())) - else { - return false; - }; - if old == gen { - if let Some(p) = state.current.as_mut().filter(|p| p.roster_sig.is_none()) { - p.roster_sig = Some(roster_sig(keys)); - } - return false; - } - // The generation also moves for a server re-registered at the same origin, which refreshes a - // live token in place: the same client, the same identity. Nothing fetched is stale then, and - // rebuilding would blank a loaded page. A revocation moves the grant, so a token for another - // identity does not get this far. - let sig = roster_sig(keys); - if let Some(p) = state.current.as_mut().filter(|p| p.roster_sig.as_ref() == Some(&sig)) { - p.roster_gen = gen; +fn sync_roster(state: &mut PersonState, adapter: &PersonAdapter, input: &PersonInput<'_>) -> bool { + let gen = input.keys.roster_gen(); + let Some(p) = state.current() else { return false }; + // Compare borrowed registered slots, not just keys. Retokens preserve instance/grant. + let unchanged = p.roster_sig.as_ref().is_some_and(|old| old.iter().copied().eq( + input.keys.slots().map(|sid| (sid, input.keys.key(sid).map(|key| (key.instance, key.grant)))))); + if unchanged { + if let Some(p) = state.current.as_mut() { p.roster_gen = gen; } return false; } + let srcs = sources(p.sid, &p.key, &p.name, input.keys); + let sig = roster_sig(input.keys); state.supersede(adapter); - let srcs = sources(sid, &key, &name); - let Some(p) = state.current.as_mut() else { - return false; - }; + let Some(p) = state.current.as_mut() else { return false }; p.srcs = srcs; p.shelves = Default::default(); p.landed = false; @@ -1683,6 +1738,19 @@ pub fn pretty_department(raw: &str) -> String { /// /// Called every frame for the page's whole life, once per mailbox, so it allocates only when it /// will actually spawn. +fn wants(i: usize, p: &Person) -> bool { + if i == F_PROFILE { return !p.profiled && !p.guid.is_empty(); } + if i == F_CREDITS { return !p.credited && !p.guid.is_empty(); } + let Some((sid, kind)) = un_fx(i) else { return false }; + let Some(s) = p.srcs.iter().find(|s| s.sid == sid) else { return false }; + match kind { + K_RESOLVE => !s.resolved, + K_MEDIA => s.resolved && !s.landed && s.local.is_some(), + K_ROLES => s.landed && !s.roled && s.shelves.iter().flat_map(|sh| &sh.items).any(|m| !m.rk.is_empty()), + _ => false, + } +} + fn address(i: usize, p: &Person) -> Option> { if i == F_PROFILE { return (!p.profiled && !p.guid.is_empty()).then(|| vec![p.guid.clone()]); @@ -1709,7 +1777,7 @@ fn address(i: usize, p: &Person) -> Option> { fn fanout_standing(state: &PersonState, adapter: &PersonAdapter, i: usize) -> crate::stores::fanout::Standing { use crate::stores::fanout::Standing; if adapter.mailbox(i).busy() { Standing::Running } - else if state.retry_cd[i] == 0 && state.current().is_some_and(|p| address(i, p).is_some()) { Standing::Wanting } + else if state.retry_cd[i] == 0 && state.current().is_some_and(|p| wants(i, p)) { Standing::Wanting } else { Standing::Idle } } @@ -1719,74 +1787,48 @@ fn fanout_standing(state: &PersonState, adapter: &PersonAdapter, i: usize) -> cr /// network error simply retries after the backoff instead of latching the page on a spinner /// forever. /// -/// Every decision is made HERE, on the pump's thread, and the request leaves as a job -/// ([`PersonState::emit`]); the runner starts it. What stays in the step and why: the tape and the -/// settled session decide whether a job exists and which identity it carries (both are -/// thread-local to the pump), and a refused plex.tv read lands synchronously with no worker -/// (a refusal is fixed at boot; routing it through the runner would turn it into a release and -/// respawn every ~2 s). +/// The step decides only from its captured PersonInput and emits a typed job; the runner +/// starts it. The host already chose controlled/provider behavior and supplied the settled +/// identity. A fixed provider refusal settles synchronously, without a worker or retry. fn maybe_spawn(state: &mut PersonState, adapter: &Arc, i: usize, - turn: &mut crate::stores::fanout::FanoutTurn, keys: &ClientKeys) { - if adapter.mailbox(i).busy() || state.retry_cd[i] > 0 { - return; - } - let Some(p) = state.current() else { return }; - let Some(arg) = address(i, p) else { return }; + turn: &mut crate::stores::fanout::FanoutTurn, input: &PersonInput<'_>) -> bool { + if adapter.mailbox(i).busy() || state.retry_cd[i] > 0 { return false; } + let Some(p) = state.current() else { return false }; + if !wants(i, p) { return false; } let generation = state.generation; - // the person's global id rides along: the resolve joins its search answer on it, and the roles - // worker matches a credit row by either id space - let guid = p.guid.clone(); if i == F_PROFILE || i == F_CREDITS { - let controlled = crate::stores::tape::active(); - let session = if controlled { None } else { plx_plex::plex::session::peek_settled() }; - if !controlled && session.as_ref().is_none_or(|s| s.client_id.is_empty()) { return; } + if !input.controlled && input.session.is_none_or(|s| s.client_id.is_empty()) { return false; } let profile = i == F_PROFILE; - adapter.mailbox(i).claim(generation); - // **A refused read is the end of the question, so it is answered HERE, on the pump's thread, - // and no worker exists to be respawned.** The refusal is fixed at boot (a dev-token boot with - // no Discover stand-in armed, `plex::account::permit_read`); landing it as the failure it - // used to be re-armed the backoff and spawned again every ~2 s for as long as the page was - // open. It goes through the mailbox like any answer: the pump takes it on a later frame. - if !controlled && (if profile { - plx_plex::plex::discover::person_profile_refused(&arg[0]) - } else { - plx_plex::plex::discover::person_credits_refused(&arg[0]) - }) { - adapter.land(i, generation, Landing::Refused); - return; + if !input.controlled && (if profile { input.profile_refused } else { input.credits_refused }) { + // A fixed provider refusal is terminal in this drain, with no job, claim or retry. + plx_machine::idle::invalidate(); + return apply_landing(state, i, Landing::Refused); } - let identity = session.map_or(Identity::Controlled, Identity::Settled); + let identity = if input.controlled { Identity::Controlled } else { + Identity::Settled(Arc::clone(input.session.expect("settled Person request"))) + }; + let arg = address(i, p).expect("wanted Person request"); + let guid = p.guid.clone(); let work = if profile { PersonWork::Profile(identity) } else { PersonWork::Credits(identity) }; + adapter.mailbox(i).claim(generation); state.emit(adapter, PersonReq { slot: i, generation, arg, guid, work }); - return; + return false; } - let Some((sid, kind)) = un_fx(i) else { return }; - let Some(kind) = LocalKind::of(kind) else { return }; - // The client THIS server holds, as the registry answered when the host filled `keys`. The job - // names it, and the runner starts the request only if the registry still holds that very - // client at the launch. A source whose slot holds no client has nothing to contribute right - // now: back off rather than re-asking every frame; `pump` retries by itself. - let Some(key) = keys.key(sid) else { + let Some((sid, kind)) = un_fx(i) else { return false }; + let Some(kind) = LocalKind::of(kind) else { return false }; + let Some(key) = input.keys.key(sid) else { state.retry_cd[i] = RETRY_FRAMES; - return; + return false; }; - // …and the SOURCE's own local id, for the roles worker's credit filter. The origin's `key` is - // meaningless on any other machine, so filtering with it blanked every borrowed caption while - // still paying for the batch. - let local = p - .srcs - .iter() - .find(|s| s.sid == sid) - .and_then(|s| s.local.clone()) - .unwrap_or_default(); - // One request per server is a fan-out: at most a few are out at once and the rest stay wanted - // until a later pump (the two plex.tv fetches above are not per server and are not counted). - if !turn.admit(i) { - return; - } + if !turn.admit(i) { return false; } + // Only admitted jobs own copies; stable/waiting pumps borrow the retained capture. + let arg = address(i, p).expect("wanted Person request"); + let guid = p.guid.clone(); + let local = p.srcs.iter().find(|s| s.sid == sid).and_then(|s| s.local.clone()).unwrap_or_default(); adapter.mailbox(i).claim(generation); state.stamps.insert(i, state.ledger.stamp()); state.emit(adapter, PersonReq { slot: i, generation, arg, guid, work: PersonWork::Local { sid, kind, local, key } }); + false } impl PersonState { @@ -1794,7 +1836,9 @@ impl PersonState { fn emit(&mut self, adapter: &Arc, req: PersonReq) { let addr = person_addr(self.next_job); self.next_job = self.next_job.wrapping_add(1); - let port = PersonPort::to(adapter, req.slot, req.generation); + let port = PersonPort::to(adapter, addr, &req); + adapter.terminals.lock().unwrap_or_else(|e| e.into_inner()).pending.insert(req.slot, + PendingPerson { addr, request: Arc::clone(&port.request), terminal: false }); self.jobs.push(crate::stores::StoreJob::Person(Job { addr, req }, port)); } } @@ -1901,54 +1945,95 @@ impl PersonReq { /// [`Landing`]. pub struct PersonAnswer(Landing); -/// Where a person request's ONE answer goes: the mailbox of its slot in the adapter the request -/// was made from, under the listing generation it was made for. Captured with the job when it was -/// emitted, so a store that has since been `Reset` (a new adapter) never receives it: the port -/// still lands into the retired adapter nobody pumps. Two ports are equal when they reach the same -/// slot of the same adapter at the same generation. -/// -/// The job's [`Addr::req`] is its sequence number and names nothing here: several slots of one -/// listing are out at once, so the slot and the generation travel in the port. +/// One addressed request's terminal port. Both success and launch refusal are accepted only +/// while this full request still owns its slot; generation alone cannot identify a retry. #[derive(Clone)] pub struct PersonPort { adapter: Arc, - slot: usize, - generation: u32, + addr: Addr, + request: Arc, } impl PersonPort { - /// The port to slot `slot` of `adapter`, under listing generation `generation`. - fn to(adapter: &Arc, slot: usize, generation: u32) -> Self { - Self { adapter: Arc::clone(adapter), slot, generation } + fn to(adapter: &Arc, addr: Addr, request: &PersonReq) -> Self { + Self { adapter: Arc::clone(adapter), addr, request: Arc::new(request.clone()) } + } + + fn matches(&self, addr: Addr, pending: &PendingPerson) -> bool { + addr == self.addr && addr == pending.addr && *self.request == *pending.request + } + + #[cfg(test)] + fn expected(adapter: &Arc, slot: usize, generation: u32) -> Self { + let terminals = adapter.terminals.lock().unwrap_or_else(|e| e.into_inner()); + let pending = terminals.pending.get(&slot).expect("expected emitted request"); + assert_eq!(pending.request.generation, generation); + Self { adapter: Arc::clone(adapter), addr: pending.addr, request: Arc::clone(&pending.request) } } } impl PartialEq for PersonPort { fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.adapter, &other.adapter) && self.slot == other.slot && self.generation == other.generation + Arc::ptr_eq(&self.adapter, &other.adapter) && self.addr == other.addr && self.request == other.request } } impl std::fmt::Debug for PersonPort { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "PersonPort({:p}, slot {}, gen {})", Arc::as_ptr(&self.adapter), self.slot, self.generation) + write!(f, "PersonPort({:p}, {:?}, slot {}, gen {})", Arc::as_ptr(&self.adapter), self.addr, + self.request.slot, self.request.generation) } } impl Port for PersonPort { - /// The request's answer (a failed read answers with its failure value). Stamped with the - /// request's generation, so the pump discards an answer for a listing it has since superseded. - fn done(&self, _addr: Addr, out: PersonAnswer) { - self.adapter.land(self.slot, self.generation, out.0); + fn done(&self, addr: Addr, out: PersonAnswer) { + let mut terminals = self.adapter.terminals.lock().unwrap_or_else(|e| e.into_inner()); + let Some(pending) = terminals.pending.get_mut(&self.request.slot) else { return }; + if pending.terminal || !self.matches(addr, pending) { return; } + pending.terminal = true; + self.adapter.land(self.request.slot, self.request.generation, out.0); + } + + /// Temporary runner failure is an addressed owner event, NOT the boot-fixed Discover + /// Landing::Refused. Do not free a claim here: the same drain observes it and arms backoff. + fn refused(&self, addr: Addr) { + let mut terminals = self.adapter.terminals.lock().unwrap_or_else(|e| e.into_inner()); + let Some(pending) = terminals.pending.get_mut(&self.request.slot) else { return }; + if pending.terminal || !self.matches(addr, pending) { return; } + pending.terminal = true; + terminals.refused.push(PersonLaunchRefused { addr, request: Arc::clone(&self.request) }); + } +} + +impl PersonState { + /// Consume only launch refusals, never normal/taped completions and never emit more work. + /// The runner drain calls this before returning; pump also covers direct fixture runners. + pub fn land_launch_refusals(&mut self, adapter: &PersonAdapter) -> bool { + let changed = self.take_launch_refusals(adapter); + self.revision += u64::from(changed); + changed } - /// The request was never started, so nothing will land and nothing will release its claim: - /// hand it back, so the next pump asks again. A refusal that comes after a newer request has - /// claimed the slot leaves that claim alone ([`Fetch::release_for`](crate::stores::Fetch::release_for)). - /// This is NOT `Landing::Refused`: the step reads that as the permanent discover refusal and - /// stops asking. - fn refused(&self, _addr: Addr) { - self.adapter.mailbox(self.slot).release_for(self.generation); + fn take_launch_refusals(&mut self, adapter: &PersonAdapter) -> bool { + let mut changed = false; + let mut terminals = adapter.terminals.lock().unwrap_or_else(|e| e.into_inner()); + let refused = std::mem::take(&mut terminals.refused); + for event in refused { + let req = &event.request; + let matches = terminals.pending.get(&req.slot).is_some_and(|pending| + pending.addr == event.addr && *pending.request == **req); + if !matches { continue; } + terminals.pending.remove(&req.slot); + adapter.mailbox(req.slot).clear(); + if req.generation != self.generation { continue; } + changed = true; + self.retry_cd[req.slot] = RETRY_FRAMES; + if req.slot == F_PROFILE { + if let Some(person) = &mut self.current { person.profile_tried = true; } + } + plx_machine::idle::invalidate(); + } + changed } } @@ -2458,8 +2543,8 @@ pub fn install_source_for_test(&mut self, sid: ServerId, movies: Vec, } /// Open a person page through the store's own `open`, for suites outside this module. -pub fn open_for_test(&mut self, adapter: &PersonAdapter, sid: ServerId, key: &str, guid: &str, name: &str) { - open(self, adapter, sid, key, guid, name, ""); +pub fn open_for_test(&mut self, adapter: &PersonAdapter, sid: ServerId, key: &str, guid: &str, name: &str, input: &PersonInput<'_>) { + open(self, adapter, sid, key, guid, name, "", input); } /// Would the open page ask server `sid` for something right now? True once it is a source with a @@ -2518,6 +2603,13 @@ pub struct OwnershipFixture { } // --------------------------------------------------------------------------------------- +#[cfg(test)] +#[path = "person/captured_inputs_tests.rs"] +mod captured_inputs_tests; +#[cfg(test)] +#[path = "person/boundary_tests.rs"] +mod boundary_tests; + #[cfg(test)] mod tests { use super::*; @@ -2542,9 +2634,41 @@ mod tests { /// The registry's answer as of now, as the host fills it (`adapters::stores::refill_client_keys`). /// Test code only: the data layer's step reads no registry. - fn registry_keys() -> ClientKeys { - ClientKeys::of(plx_plex::plex::server_ids() - .filter_map(|sid| plx_plex::plex::client_for(sid).map(|c| (sid, c)))) +fn registry_keys() -> ClientKeys { + let mut keys = ClientKeys::default(); + keys.refill_roster(plx_plex::plex::current_server(), plx_plex::plex::server_roster_gen(), + plx_plex::plex::server_facts_gen(), plx_plex::plex::server_ids(), + plx_plex::plex::client_for, plx_plex::plex::server_facts, plx_plex::plex::server_probe_result); + keys + } + /// This fixture is the host: the machine never recaptures its process values. + struct Captured { + session: Option>, + visible_generation: u64, + controlled: bool, + profile_refused: bool, + credits_refused: bool, + bio: Option, + credits: Option, + } + impl Captured { + fn new(guid: &str) -> Self { + let controlled = crate::stores::tape::active(); + Self { + session: if controlled { None } else { plx_plex::plex::session::peek_settled() }, + visible_generation: plx_plex::plex::session::visible_generation(), controlled, + profile_refused: !controlled && plx_plex::plex::discover::person_profile_refused(guid), + credits_refused: !controlled && plx_plex::plex::discover::person_credits_refused(guid), + bio: if controlled { None } else { plx_base::devtrig::read("personbio") }, + credits: if controlled { crate::stores::tape::credits().map(|n| n.to_string()) } else { plx_base::devtrig::read("personcredits") }, + } + } + fn input<'a>(&'a self, keys: &'a ClientKeys) -> PersonInput<'a> { + PersonInput { keys, session: self.session.as_ref(), visible_generation: self.visible_generation, + profile_scope: 0, owner_epoch: 0, profile_generation: 0, tenure: 0, profile_key: "", + controlled: self.controlled, profile_refused: self.profile_refused, credits_refused: self.credits_refused, + dev_bio: self.bio.as_deref(), dev_credits: self.credits.as_deref() } + } } /// A Roles landing recorded before chunking has no `incomplete` key. The tape check re-encodes @@ -2583,7 +2707,9 @@ mod tests { fn current(&self) -> Option<&Person> { self.state.current() } fn gen(&self) -> u32 { self.state.generation } fn open(&mut self, sid: ServerId, key: &str, guid: &str, name: &str, thumb: &str) { - open(&mut self.state, &self.adapter, sid, key, guid, name, thumb); + let keys = registry_keys(); + let captured = Captured::new(guid); + open(&mut self.state, &self.adapter, sid, key, guid, name, thumb, &captured.input(&keys)); } fn close(&mut self) { close(&mut self.state, &self.adapter); } fn reset(&mut self) { @@ -2600,7 +2726,13 @@ mod tests { /// for [`Owner::jobs`] / [`Owner::run_jobs`]: the step starts nothing. fn step(&mut self) -> bool { self.step_with(®istry_keys()) } /// One pump over `keys` instead of the registry's answer. - fn step_with(&mut self, keys: &ClientKeys) -> bool { self.state.pump(&self.adapter, keys) } +fn step_with(&mut self, keys: &ClientKeys) -> bool { + self.step_with_gate(plx_machine::landgate::fixture_gate(), keys) + } + fn step_with_gate(&mut self, gate: &plx_machine::landgate::Gate, keys: &ClientKeys) -> bool { + let captured = Captured::new(self.current().map_or("", |p| p.guid.as_str())); + self.state.pump_with_gate(&self.adapter, gate, &captured.input(keys)) + } /// The requests on the outbox, taken, in the order they were emitted. fn jobs(&mut self) -> Vec { std::mem::take(&mut self.state.jobs) } /// Run the whole outbox on THIS thread through the production completion path @@ -2624,7 +2756,11 @@ mod tests { self.run_jobs(); changed } - fn sync_roster(&mut self) -> bool { sync_roster(&mut self.state, &self.adapter, ®istry_keys()) } +fn sync_roster(&mut self) -> bool { + let keys = registry_keys(); + let captured = Captured::new(self.current().map_or("", |p| p.guid.as_str())); + sync_roster(&mut self.state, &self.adapter, &captured.input(&keys)) + } fn loading(&self) -> bool { self.state.view().loading() } /// Park every spawn: a backoff on each index the original layout had and on all three /// kinds of every registered server. @@ -3585,7 +3721,7 @@ mod tests { std::thread::sleep(std::time::Duration::from_millis(25)); worker.land(at(S0, K_MEDIA), gen, media(vec![PmsMovie::default()], Vec::new())); }); - assert!(owner.state.pump_with_gate(&owner.adapter, &gate, &ClientKeys::default()), + assert!(owner.step_with_gate(&gate, &ClientKeys::default()), "the answer the pump owed must be taken by the pump that asked"); assert_eq!(owner.current().unwrap().shelf(0).len(), 1); assert!(!owner.adapter.mailbox(at(S0, K_MEDIA)).busy(), "the TAKE released the claim"); @@ -3616,7 +3752,7 @@ mod tests { std::thread::sleep(std::time::Duration::from_millis(25)); worker.land(at(S0, K_MEDIA), current, media(vec![PmsMovie::default()], Vec::new())); }); - assert!(owner.state.pump_with_gate(&owner.adapter, &gate, &ClientKeys::default()), + assert!(owner.step_with_gate(&gate, &ClientKeys::default()), "B was out when the pump ran, so B's answer must land on this pump"); assert_eq!(owner.current().unwrap().shelf(0).len(), 1); assert!(!owner.adapter.mailbox(at(S0, K_MEDIA)).busy(), "B's own answer released B's claim"); @@ -4631,7 +4767,7 @@ mod tests { owner.step_with(&holding()); let (g, adapter) = (owner.gen(), Arc::clone(&owner.adapter)); - let port = |slot| PersonPort::to(&adapter, slot, g); + let port = |slot| PersonPort::expected(&adapter, slot, g); let media = at(S0, K_MEDIA); plx_machine::assert_fx!(owner.jobs(), [ job(0, port(media), req(media, g, &["7"], "plex://person/7", local(S0, LocalKind::Media, "7"))), @@ -4666,7 +4802,7 @@ mod tests { let slots: Vec = locals.iter().map(|(job, _)| job.req.slot).collect(); assert!(slots.windows(2).all(|w| w[0] < w[1]), "ascending slots, got {slots:?}"); for (job, port) in &locals { - assert_eq!(*port, PersonPort::to(&owner.adapter, job.req.slot, job.req.generation)); + assert_eq!(*port, PersonPort::expected(&owner.adapter, job.req.slot, job.req.generation)); let (sid, key) = job.req.server().unwrap(); assert_eq!(Some(key), registry_keys().key(sid), "the key is the registry's answer for that server"); } @@ -4753,7 +4889,7 @@ mod tests { let (job, port) = media_job(&mut owner); let old = Arc::clone(&owner.adapter); owner.reset(); - assert_ne!(port, PersonPort::to(&owner.adapter, media, job.req.generation)); + assert_ne!(port, PersonPort::to(&owner.adapter, job.addr, &job.req)); port.done(job.addr, PersonAnswer(Landing::Media(None))); assert!(old.mailbox(media).has_mail(), "the answer reached the adapter the request came from"); @@ -4772,7 +4908,9 @@ mod tests { assert!(owner.adapter.mailbox(media).busy()); port.refused(job.addr); + assert!(owner.state.land_launch_refusals(&owner.adapter)); assert!(!owner.adapter.mailbox(media).busy(), "the refusal released its own claim"); + for _ in 1..RETRY_FRAMES { owner.step_with(&holding()); assert!(owner.jobs().is_empty()); } owner.step_with(&holding()); assert!(person_jobs(owner.jobs()).iter().any(|(job, _)| job.req.slot == media), "and the next pump asks again"); @@ -4840,6 +4978,7 @@ mod tests { let media = at(S0, K_MEDIA); let (job, port) = media_job(&mut owner); finish_person_job(&port, job.addr, None, job.req); + assert!(owner.state.land_launch_refusals(&owner.adapter)); assert!(!owner.adapter.mailbox(media).has_mail(), "a refusal answers nothing"); assert!(!owner.adapter.mailbox(media).busy(), "and gives the claim back"); owner.close(); diff --git a/rust-modules/data/src/person/boundary_tests.rs b/rust-modules/data/src/person/boundary_tests.rs new file mode 100644 index 0000000000..b139fd11e1 --- /dev/null +++ b/rust-modules/data/src/person/boundary_tests.rs @@ -0,0 +1,155 @@ +use super::*; +fn facts(keys: &ClientKeys) -> PersonInput<'_> { + PersonInput { keys, session: None, visible_generation: 0, controlled: true, + profile_scope: 0, owner_epoch: 0, profile_generation: 0, tenure: 0, profile_key: "", + profile_refused: false, credits_refused: false, dev_bio: None, dev_credits: None } +} +fn profile_job(state: &mut PersonState, adapter: &Arc) -> (Job, PersonPort) { + let keys = ClientKeys::default(); + if state.current().is_none() { open(state, adapter, ServerId::UNSET, "7", "plex://person/7", "Actor", "", &facts(&keys)); } + state.pump(adapter, &facts(&keys)); + std::mem::take(&mut state.jobs).into_iter().find_map(|j| match j { + crate::stores::StoreJob::Person(job, port) if job.req.slot == F_PROFILE => Some((job, port)), + _ => None, + }).expect("profile job") +} +#[test] +fn launch_refusal_is_an_addressed_event_not_a_claim_release() { + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + let (job, port) = profile_job(&mut state, &adapter); + port.refused(job.addr); + assert!(adapter.mailbox(F_PROFILE).busy(), "only the owner may consume the terminal and release its claim"); +} +#[test] +fn wrong_request_address_cannot_refuse_the_live_job() { + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + let (job, port) = profile_job(&mut state, &adapter); + port.refused(person_addr(job.addr.req.0.wrapping_add(1))); + assert!(adapter.mailbox(F_PROFILE).busy(), "a different request cannot release this claim"); +} + +#[test] +fn explicit_scope_edges_retire_claims_and_evidence_before_any_landing_even_controlled() { + let sid = ServerId::from_raw(71); + let keys = ClientKeys::from_keys([(sid, ClientKey { instance: 1, token: 2, grant: 3 })]); + for controlled in [false, true] { + for edge in 0..5 { + let session = Arc::new(plx_plex::plex::session::Session { client_id: "same".into(), account_token: "same".into(), ..Default::default() }); + let mut input = facts(&keys); + input.controlled = controlled; + input.session = Some(&session); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open(&mut state, &adapter, sid, "7", "plex://person/7", "Actor", "", &input); + state.pump(&adapter, &input); + let old_generation = state.generation; + let jobs = std::mem::take(&mut state.jobs); + let old_ports: Vec<_> = jobs.into_iter().map(|j| match j { + crate::stores::StoreJob::Person(job, port) => (job, port), + _ => unreachable!(), + }).collect(); + apply_landing(&mut state, fx(sid, K_MEDIA).unwrap(), Landing::Media(Some(MediaLanding { + shelves: [Shelf { items: vec![PmsMovie { sid, rk: "private".into(), ..Default::default() }], total: 1, roles: vec![] }, Shelf::default()], + matches: vec![("private-guid".into(), "private".into())], + }))); + seed_dev_credits(&mut state, Some("3")); + let person = state.current.as_mut().unwrap(); + person.bio = "old private biography".into(); + person.roles.push("old department".into()); + person.born = "old date".into(); + person.profiled = true; + person.profile_tried = true; + match edge { + 0 => input.profile_scope += 1, + 1 => input.owner_epoch += 1, + 2 => input.profile_generation += 1, + 3 => input.tenure += 1, + _ => input.profile_key = "different-tenant", + } + // Queue the old result BEFORE the pass: scope must win before the first take. + for (job, port) in &old_ports { + let out = if job.req.slot == F_PROFILE { + PersonAnswer(Landing::Profile(Some(plx_plex::plex::discover::PersonProfile { + summary: "must not land".into(), ..Default::default() + }))) + } else if job.req.slot == F_CREDITS { PersonAnswer(Landing::Credits(None)) } + else { PersonAnswer(Landing::Media(None)) }; + port.done(job.addr, out); + } + assert!(state.pump(&adapter, &input)); + assert!(state.generation > old_generation); + let person = state.current().unwrap(); + assert_eq!(person.name, "Actor", "the mounted header may be held"); + assert!(person.bio.is_empty() && person.roles.is_empty() && person.born.is_empty()); + assert!(person.credits.is_empty() && !person.credited && !person.profile_tried); + assert!(person.shelves.iter().all(|s| s.items.is_empty())); + assert!(person.srcs.iter().all(|s| s.matches.is_empty())); + assert!(state.stamps.values().all(|stamp| *stamp == state.ledger.stamp())); + assert!(state.jobs.iter().all(|j| matches!(j, crate::stores::StoreJob::Person(job, _) if job.req.generation == state.generation))); + for (job, port) in old_ports { port.refused(job.addr); } + assert!(!state.land_launch_refusals(&adapter)); + assert!(adapter.mailbox(F_PROFILE).busy(), "old scope cannot retire the replacement"); + } + } +} + +#[test] +fn same_generation_retry_rejects_old_refusal_success_address_and_key() { + let keys = ClientKeys::default(); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + let (old, old_port) = profile_job(&mut state, &adapter); + old_port.done(old.addr, PersonAnswer(Landing::Profile(None))); + state.pump(&adapter, &facts(&keys)); + state.retry_cd[F_PROFILE] = 0; + let (new, new_port) = profile_job(&mut state, &adapter); + assert_eq!(old.req.generation, new.req.generation); + assert_ne!(old.addr, new.addr); + old_port.refused(old.addr); + old_port.done(old.addr, PersonAnswer(Landing::Profile(None))); + new_port.refused(old.addr); + assert!(!state.land_launch_refusals(&adapter)); + assert!(adapter.mailbox(F_PROFILE).busy()); + assert!(!adapter.mailbox(F_PROFILE).has_mail()); + let mut wrong = new.req.clone(); + wrong.guid.push_str("-wrong"); + PersonPort::to(&adapter, new.addr, &wrong).refused(new.addr); + assert!(!state.land_launch_refusals(&adapter)); + assert!(adapter.mailbox(F_PROFILE).busy()); + new_port.refused(new.addr); + new_port.refused(new.addr); + assert!(state.land_launch_refusals(&adapter)); + assert!(!state.land_launch_refusals(&adapter), "one terminal only"); + assert!(!adapter.mailbox(F_PROFILE).busy()); + assert_eq!(state.retry_cd[F_PROFILE], RETRY_FRAMES); + assert!(!state.current().unwrap().profiled, "temporary refusal cannot permanently settle Discover"); + state.jobs.clear(); + state.pump(&adapter, &facts(&keys)); + assert!(state.jobs.is_empty(), "no same-drain retry or next-frame launch spin"); +} + +#[test] +fn complete_request_including_client_key_must_match_the_claim() { + let sid = ServerId::from_raw(71); + let key = ClientKey { instance: 1, token: 2, grant: 3 }; + let keys = ClientKeys::from_keys([(sid, key)]); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open(&mut state, &adapter, sid, "7", "plex://person/7", "Actor", "", &facts(&keys)); + state.pump(&adapter, &facts(&keys)); + let (job, port) = std::mem::take(&mut state.jobs).into_iter().find_map(|j| match j { + crate::stores::StoreJob::Person(job, port) if job.req.server().is_some() => Some((job, port)), _ => None, + }).unwrap(); + let mut wrong = job.req.clone(); + if let PersonWork::Local { key, .. } = &mut wrong.work { key.grant += 1; } + let stale = PersonPort::to(&adapter, job.addr, &wrong); + stale.refused(job.addr); + stale.done(job.addr, PersonAnswer(Landing::Media(None))); + assert!(!state.land_launch_refusals(&adapter)); + assert!(adapter.mailbox(job.req.slot).busy()); + assert!(!adapter.mailbox(job.req.slot).has_mail()); + port.refused(job.addr); + assert!(state.land_launch_refusals(&adapter)); +} diff --git a/rust-modules/data/src/person/captured_inputs_tests.rs b/rust-modules/data/src/person/captured_inputs_tests.rs new file mode 100644 index 0000000000..948b20777a --- /dev/null +++ b/rust-modules/data/src/person/captured_inputs_tests.rs @@ -0,0 +1,239 @@ +use super::*; + +const ORIGIN: ServerId = ServerId::from_raw(71); +const SHARE: ServerId = ServerId::from_raw(72); + +fn input<'a>(keys: &'a ClientKeys, session: Option<&'a Arc>) -> PersonInput<'a> { + PersonInput { keys, session, visible_generation: 9, controlled: false, + profile_scope: 0, owner_epoch: 0, profile_generation: 0, tenure: 0, profile_key: "", + profile_refused: false, credits_refused: false, dev_bio: None, dev_credits: None } +} + +fn open_page(state: &mut PersonState, adapter: &Arc, input: &PersonInput<'_>) { + open(state, adapter, ORIGIN, "7", "plex://person/captured", "Actor", "", input); +} + +fn roster(slots: &[ServerId], generation: u32) -> ClientKeys { + let mut keys = ClientKeys::default(); + keys.refill_roster(ServerId::UNSET, generation, 0, slots.iter().copied(), |_| None, |_| None, |_| None); + keys +} + +#[test] +fn captured_roster_and_settled_identity_override_conflicting_process_state() { + let _serial = plx_base::testlock::serial(); + let _session = plx_plex::plex::session::TempSession::new("person-captured-vs-ambient"); + plx_plex::plex::reset_servers_for_test(); + let ambient = plx_plex::plex::register_for_test("ambient-person", "127.0.0.1", 1, "a", "cid"); + let keys = roster(&[SHARE, SHARE], 400); + let session = Arc::new(plx_plex::plex::session::Session { + client_id: "captured-client".into(), account_token: "captured-token".into(), ..Default::default() + }); + let facts = input(&keys, Some(&session)); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &facts); + assert_eq!(state.current().unwrap().srcs.iter().map(|s| s.sid).collect::>(), [SHARE, ORIGIN]); + assert!(!state.current().unwrap().srcs.iter().any(|s| s.sid == ambient)); + state.pump(&adapter, &facts); + let jobs = std::mem::take(&mut state.jobs); + assert_eq!(jobs.len(), 2, "roster-only slots cannot emit local jobs"); + for job in jobs { + let crate::stores::StoreJob::Person(job, _) = job else { panic!("wrong store") }; + match job.req.work { + PersonWork::Profile(Identity::Settled(s)) | PersonWork::Credits(Identity::Settled(s)) => assert!(Arc::ptr_eq(&s, &session)), + _ => panic!("captured identity was lost"), + } + } +} + +#[test] +fn origin_is_appended_once_even_without_a_registered_client() { + for slots in [vec![], vec![SHARE], vec![ORIGIN, SHARE, ORIGIN]] { + let keys = roster(&slots, 1); + let srcs = sources(ORIGIN, "7", "Actor", &keys); + assert_eq!(srcs.iter().filter(|s| s.sid == ORIGIN).count(), 1); + assert_eq!(srcs.len(), if slots.is_empty() { 1 } else { 2 }); + assert!(srcs.iter().find(|s| s.sid == ORIGIN).unwrap().resolved); + } +} + +#[test] +fn unchanged_capture_keeps_generation_publication_and_identity_string_allocations() { + let keys = roster(&[SHARE], 33); + let session = Arc::new(plx_plex::plex::session::Session { client_id: "client".into(), account_token: "token".into(), ..Default::default() }); + let facts = input(&keys, Some(&session)); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &facts); + state.pump(&adapter, &facts); + let generation = state.generation; + let revision = state.view().revision(); + let pointers = (state.session_identity.0.as_ptr(), state.session_identity.1.as_ptr(), state.current().unwrap().srcs.as_ptr()); + for _ in 0..8 { assert!(!state.pump(&adapter, &facts)); } + assert_eq!((state.generation, state.view().revision()), (generation, revision)); + assert_eq!((state.session_identity.0.as_ptr(), state.session_identity.1.as_ptr(), state.current().unwrap().srcs.as_ptr()), pointers); +} + +#[test] +fn roster_only_changes_rebuild_but_a_live_token_refresh_does_not() { + let key = ClientKey { instance: 10, token: 1, grant: 3 }; + let mut keys = ClientKeys::from_keys([(ORIGIN, key)]); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &input(&keys, None)); + let generation = state.generation; + keys.refill([(ORIGIN, ClientKey { token: 2, ..key })]); + assert!(!sync_roster(&mut state, &adapter, &input(&keys, None))); + assert_eq!(state.generation, generation); + keys = roster(&[ORIGIN, SHARE], 2); + assert!(sync_roster(&mut state, &adapter, &input(&keys, None))); + assert_eq!(state.current().unwrap().srcs.len(), 2, "a no-client registered share is not dropped"); +} + +#[test] +fn suspended_session_defers_global_jobs_and_recovery_uses_supplied_identity() { + let keys = roster(&[], 0); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &input(&keys, None)); + state.pump(&adapter, &input(&keys, None)); + assert!(state.jobs.is_empty()); + let session = Arc::new(plx_plex::plex::session::Session { client_id: "recovered".into(), ..Default::default() }); + state.pump(&adapter, &input(&keys, Some(&session))); + assert_eq!(state.jobs.len(), 2); +} + +#[test] +fn controlled_capture_ignores_session_edges_and_uses_supplied_dev_seed() { + let keys = roster(&[], 0); + let mut facts = input(&keys, None); + facts.controlled = true; + facts.dev_bio = Some("must not seed controlled biography"); + facts.dev_credits = Some("3"); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &facts); + let generation = state.generation; + facts.visible_generation += 1; + state.pump(&adapter, &facts); + assert_eq!(state.generation, generation); + assert!(state.current().unwrap().bio.is_empty()); + assert!(state.current().unwrap().credited); + assert_eq!(state.current().unwrap().credits[0].credits.len(), 3); + assert!(!state.jobs.is_empty()); + assert!(state.jobs.iter().all(|j| matches!(j, crate::stores::StoreJob::Person(Job { req: PersonReq { work: PersonWork::Profile(Identity::Controlled) | PersonWork::Credits(Identity::Controlled), .. }, .. }, _)))); +} + +#[test] +fn changed_seed_rebuilds_credits_without_a_holdings_change() { + let keys = roster(&[], 0); + let mut facts = input(&keys, None); + facts.controlled = true; + facts.dev_credits = Some("3"); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &facts); + state.pump(&adapter, &facts); + assert_eq!(state.current().unwrap().credits[0].credits.len(), 3); + facts.dev_credits = Some("5"); + assert!(state.pump(&adapter, &facts)); + assert_eq!(state.current().unwrap().credits[0].credits.len(), 5); + let rows = state.current().unwrap().credits.as_ptr(); + assert!(!state.pump(&adapter, &facts)); + assert_eq!(state.current().unwrap().credits.as_ptr(), rows); +} + +#[test] +fn changed_identity_at_the_same_generation_retires_its_claim() { + let keys = roster(&[], 0); + let a = Arc::new(plx_plex::plex::session::Session { client_id: "a".into(), ..Default::default() }); + let b = Arc::new(plx_plex::plex::session::Session { client_id: "b".into(), ..Default::default() }); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &input(&keys, Some(&a))); + state.pump(&adapter, &input(&keys, Some(&a))); + let old = state.generation; + state.pump(&adapter, &input(&keys, Some(&b))); + assert!(state.generation > old); +} + +#[test] +fn captured_refusal_settles_in_this_turn_without_a_job_or_retry() { + let keys = roster(&[], 0); + let session = Arc::new(plx_plex::plex::session::Session { client_id: "client".into(), ..Default::default() }); + let mut facts = input(&keys, Some(&session)); + facts.profile_refused = true; + facts.credits_refused = true; + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &facts); + assert!(state.pump(&adapter, &facts)); + let person = state.current().unwrap(); + assert!(person.profiled && person.profile_tried && person.credited); + assert!(state.jobs.is_empty()); + assert!(!adapter.mailbox(F_PROFILE).busy()); + assert!(!state.pump(&adapter, &facts)); +} + +#[test] +fn profile_edge_retires_old_answer_without_releasing_the_new_claim() { + let keys = roster(&[], 0); + let a = Arc::new(plx_plex::plex::session::Session { client_id: "a".into(), account_token: "a".into(), ..Default::default() }); + let b = Arc::new(plx_plex::plex::session::Session { client_id: "b".into(), account_token: "b".into(), ..Default::default() }); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &input(&keys, Some(&a))); + state.pump(&adapter, &input(&keys, Some(&a))); + let old = state.generation; + let mut next = input(&keys, Some(&b)); + next.visible_generation += 1; + state.pump(&adapter, &next); + assert_ne!(old, state.generation); + assert!(adapter.mailbox(F_PROFILE).busy()); + adapter.land(F_PROFILE, old, Landing::Profile(None)); + state.pump(&adapter, &next); + assert!(adapter.mailbox(F_PROFILE).busy(), "an orphan cannot release its replacement's claim"); + assert!(!state.current().unwrap().profile_tried); +} +#[test] +fn a_retained_publication_cannot_be_changed_by_another_owners_capture_or_pump() { + let keys = roster(&[], 0); + let facts = input(&keys, None); + let mut first = PersonState::default(); + let first_adapter = Arc::new(PersonAdapter::default()); + open_page(&mut first, &first_adapter, &facts); + let retained = first.view(); + let revision = retained.revision(); + let person = retained.current().unwrap(); + let identity = (person as *const Person, person.key.as_str(), person.name.as_str()); + let mut second = PersonState::default(); + let second_adapter = Arc::new(PersonAdapter::default()); + open_page(&mut second, &second_adapter, &facts); + second.pump(&second_adapter, &facts); + close(&mut second, &second_adapter); + assert_eq!(retained.revision(), revision); + let held = retained.current().unwrap(); + assert_eq!((held as *const Person, held.key.as_str(), held.name.as_str()), identity); +} + +#[test] +fn a_new_grant_rebuilds_while_token_only_refresh_keeps_loaded_shelves() { + let original = ClientKey { instance: 5, token: 7, grant: 11 }; + let mut keys = ClientKeys::from_keys([(ORIGIN, original)]); + let mut state = PersonState::default(); + let adapter = Arc::new(PersonAdapter::default()); + open_page(&mut state, &adapter, &input(&keys, None)); + let generation = state.generation; + apply_landing(&mut state, fx(ORIGIN, K_MEDIA).unwrap(), Landing::Media(Some(MediaLanding { + shelves: [Shelf { items: vec![PmsMovie { sid: ORIGIN, rk: "movie".into(), ..Default::default() }], total: 1, roles: Vec::new() }, Shelf::default()], matches: Vec::new(), + }))); + keys.refill([(ORIGIN, ClientKey { token: 8, ..original })]); + assert!(!sync_roster(&mut state, &adapter, &input(&keys, None))); + assert_eq!(state.current().unwrap().shelf(0).len(), 1); + assert_eq!(state.generation, generation); + keys.refill([(ORIGIN, ClientKey { token: 9, grant: 12, ..original })]); + assert!(sync_roster(&mut state, &adapter, &input(&keys, None))); + assert!(state.current().unwrap().shelf(0).is_empty()); + assert!(state.generation > generation); +} diff --git a/rust-modules/data/src/pms.rs b/rust-modules/data/src/pms.rs index 7933f43a00..d425832af1 100644 --- a/rust-modules/data/src/pms.rs +++ b/rust-modules/data/src/pms.rs @@ -356,6 +356,8 @@ pub struct PmsState { seen: u64, /// …and what the roster SAID at the time. See the retired `SEEN_FACTS` static's doc. seen_facts: u32, + seen_clients: ClientKeys, + scope_pins: Vec<(ServerId, i64, bool)>, /// Bumped by every authoritative fetch. See the retired `HUB_GEN` static's doc. hub_gen: u32, /// The retained Browse directory's semantic pin fingerprint as of the last merge. See the @@ -414,6 +416,8 @@ impl Default for PmsState { srcs: Vec::new(), seen: u64::MAX, seen_facts: u32::MAX, + seen_clients: ClientKeys::default(), + scope_pins: Vec::new(), hub_gen: 0, last_sections_gen: 0, catalog_gen: 0, @@ -2941,7 +2945,7 @@ fn feeds_home(sid: ServerId, pinned: &[ServerId], known: &[ServerId]) -> bool { /// policy remains in force for them. struct BrowseScope<'a> { sections_gen: u32, - pins: Vec<(ServerId, i64, bool)>, + pins: &'a [(ServerId, i64, bool)], /// Borrowed from the host's one buffer ([`BrowseScope::retained`]), so an idle per-frame step /// allocates nothing for it; a standalone fixture owns the keys it read. clients: std::borrow::Cow<'a, ClientKeys>, @@ -2952,13 +2956,13 @@ impl<'a> BrowseScope<'a> { /// code only: a production step is handed them ([`BrowseScope::retained`]). #[cfg(any(test, feature = "test-support"))] fn standalone() -> Self { - Self { sections_gen: 0, pins: Vec::new(), clients: std::borrow::Cow::Owned(registry_keys_for_test()) } + Self { sections_gen: 0, pins: &[], clients: std::borrow::Cow::Owned(registry_keys_for_test()) } } - fn retained(directory: crate::stores::browse::DirectoryView<'_>, clients: &'a ClientKeys) -> Self { + fn retained(directory: crate::stores::browse::DirectoryView<'a>, clients: &'a ClientKeys) -> Self { Self { sections_gen: directory.sections_gen(), - pins: directory.favorite_sections().to_vec(), + pins: directory.favorite_sections(), clients: std::borrow::Cow::Borrowed(clients), } } @@ -2968,9 +2972,8 @@ impl<'a> BrowseScope<'a> { /// are fixed-width atomics; fold the actual `(server, section, pin)` input into that existing /// shape instead of adding a global owner selector. fn cache_key(&self) -> u32 { - if self.pins.is_empty() { - return 0; - } + // An empty pin table carries no new Home membership, even when discovery advances. + if self.pins.is_empty() { return 0; } let mut hash = 0x811c_9dc5u32; let mut fold = |bytes: &[u8]| { for byte in bytes { @@ -2979,7 +2982,7 @@ impl<'a> BrowseScope<'a> { }; fold(&self.sections_gen.to_le_bytes()); fold(&(self.pins.len() as u64).to_le_bytes()); - for (sid, section, pinned) in &self.pins { + for (sid, section, pinned) in self.pins { fold(&sid.raw().to_le_bytes()); fold(§ion.to_le_bytes()); fold(&[*pinned as u8]); @@ -2993,8 +2996,11 @@ impl<'a> BrowseScope<'a> { /// call and hands it in. Test code only, so it is no read of the registry by a machine. #[cfg(any(test, feature = "test-support"))] pub fn registry_keys_for_test() -> ClientKeys { - ClientKeys::of(plx_plex::plex::server_ids() - .filter_map(|sid| plx_plex::plex::client_for(sid).map(|client| (sid, client)))) + let mut keys = ClientKeys::default(); + keys.refill_roster(plx_plex::plex::current_server(), plx_plex::plex::server_roster_gen(), + plx_plex::plex::server_facts_gen(), plx_plex::plex::server_ids(), + plx_plex::plex::client_for, plx_plex::plex::server_facts, plx_plex::plex::server_probe_result); + keys } /// May this row appear on Home? **Per LIBRARY, which is the grain the switch offers.** @@ -3048,11 +3054,11 @@ fn roster_with_scope(scope: &BrowseScope) -> Vec<(ServerId, String)> { let (pinned, known) = home_server_sets(&scope.pins); let mut own: Vec<(ServerId, String)> = Vec::new(); let mut shared: Vec<(ServerId, String)> = Vec::new(); - for sid in plx_plex::plex::server_ids() { + for sid in scope.clients.slots() { if scope.clients.key(sid).is_none() || !feeds_home(sid, &pinned, &known) { continue; } - let handle = plx_plex::plex::server_facts(sid) + let handle = scope.clients.facts(sid).and_then(|facts| facts.described) .map(|f| f.handle.clone()) .unwrap_or_default(); if handle.is_empty() { @@ -3081,12 +3087,13 @@ fn roster_key() -> u64 { } fn roster_key_with_scope(scope: &BrowseScope) -> u64 { - ((plx_plex::plex::server_roster_gen() as u64) << 32) | u64::from(scope.cache_key()) + ((scope.clients.roster_gen() as u64) << 32) | u64::from(scope.cache_key()) } #[cfg(any(test, feature = "test-support"))] fn remember_roster(state: &mut PmsState, scope: &BrowseScope) { state.seen = roster_key_with_scope(scope); + if state.seen_clients != *scope.clients { state.seen_clients.clone_from(&scope.clients); } } #[allow(dead_code)] // Retained for symmetry with `remember_roster`; no production caller today. @@ -3096,13 +3103,16 @@ fn forget_roster(state: &mut PmsState) { fn browse_scope_moved(state: &mut PmsState, scope: &BrowseScope) -> bool { let key = scope.cache_key(); - let moved = state.last_sections_gen != key; + let moved = state.last_sections_gen != key || state.scope_pins.as_slice() != scope.pins; + if moved { state.scope_pins.clear(); state.scope_pins.extend_from_slice(scope.pins); } state.last_sections_gen = key; moved } fn adopt_browse_scope(state: &mut PmsState, scope: &BrowseScope) { state.last_sections_gen = scope.cache_key(); + state.scope_pins.clear(); + state.scope_pins.extend_from_slice(scope.pins); } /// The other half of the fingerprint, kept as its OWN counter rather than folded into the 64 bits @@ -3113,8 +3123,8 @@ fn adopt_browse_scope(state: &mut PmsState, scope: &BrowseScope) { /// servers there are. `Src::handle` is a copy of the "Shared by …" credit and `merge` stamps that /// copy onto every shelf and hero row, so a credit re-graded by a roster refresh is exactly a /// change this table must rebuild for — and the roster epoch alone cannot see one. -fn facts_key() -> u32 { - plx_plex::plex::server_facts_gen() +fn facts_key(scope: &BrowseScope) -> u32 { + scope.clients.facts_gen() } /// Bring the source table in line with the roster: a surviving source keeps everything it has @@ -3127,7 +3137,7 @@ fn sync_roster(state: &mut PmsState) { } fn sync_roster_with_scope(state: &mut PmsState, scope: &BrowseScope) { - let (k, fk) = (roster_key_with_scope(scope), facts_key()); + let (k, fk) = (roster_key_with_scope(scope), facts_key(scope)); let scope_moved = browse_scope_moved(state, scope); // Both, and both swapped every time: a frame on which only one moved must still record the // other, or the next change to it reads as "unchanged" against a value from two epochs ago. @@ -3135,9 +3145,10 @@ fn sync_roster_with_scope(state: &mut PmsState, scope: &BrowseScope) { let was_fk = state.seen_facts; state.seen = k; state.seen_facts = fk; - if was_k == k && was_fk == fk && !scope_moved { + if was_k == k && was_fk == fk && !scope_moved && state.seen_clients == *scope.clients { return; } + if state.seen_clients != *scope.clients { state.seen_clients.clone_from(&scope.clients); } let want = roster_with_scope(scope); let mut srcs = std::mem::take(&mut state.srcs); let mut out: Vec = Vec::with_capacity(want.len()); @@ -3831,10 +3842,10 @@ fn step_landings_with_scope(state: &mut PmsState, adapter: &PmsAdapter, dt: Opti let scope_moved = browse_scope_moved(state, scope); if dirty || scope_moved { settle_deck(&mut srcs, refreshed); } let build = (dirty || scope_moved).then(|| { - let t0 = std::time::Instant::now(); + let t0 = crate::instruments::start(); let (mut build, _) = merge_held(&mut srcs, scope, state.hold); if paged && !refreshed && !scope_moved { preserve_heroes(state, &mut build); } - let took = t0.elapsed(); + let took = crate::instruments::elapsed(t0); (build, took) }); state.srcs = srcs; @@ -3961,7 +3972,7 @@ pub fn seed_two_library_home_for_test( let build = merge_with_scope(&sources, &scope); state.srcs = sources; remember_roster(state, &scope); - state.seen_facts = facts_key(); + state.seen_facts = facts_key(&scope); adopt_browse_scope(state, &scope); commit(state, build); } @@ -3969,7 +3980,7 @@ pub fn seed_two_library_home_for_test( #[cfg(any(test, feature = "test-support"))] fn seed_with_scope_for_test(state: &mut PmsState, adapter: &Arc, sid: ServerId, items: usize, hub_state: HubState, scope: &BrowseScope) { reset_with_scope(state, adapter, scope); - let handle = plx_plex::plex::server_facts(sid) + let handle = scope.clients.facts(sid).and_then(|facts| facts.described) .map(|facts| facts.handle.clone()) .unwrap_or_default(); let mut s = Src::new(sid, handle, &scope.clients); @@ -3992,7 +4003,7 @@ fn seed_with_scope_for_test(state: &mut PmsState, adapter: &Arc, sid // preserves the source whose sid and retained directory were supplied together. BOTH halves // of the fingerprint matter, or the facts epoch alone reads as a change and rebuilds anyway. remember_roster(state, scope); - state.seen_facts = facts_key(); + state.seen_facts = facts_key(&scope); commit(state, build); } @@ -4282,8 +4293,9 @@ pub fn seed_continue_window_for_test(state: &mut PmsState, adapter: &Arc Shelf) -> (Owner, ServerId) { let (build, _) = merge_held(&mut srcs, &scope, o.state.hold); o.state.srcs = srcs; remember_roster(&mut o.state, &scope); - o.state.seen_facts = facts_key(); + o.state.seen_facts = facts_key(&scope); commit(&mut o.state, build); (o, id) } @@ -370,7 +370,7 @@ fn merge_held_equals_a_merge_of_the_settled_ring_across_sources_the_deck_pins_an src(b.raw(), "", HubState::Ready, Some(built(b.raw(), &deck[..3], shelves(b)))), ]; settle_deck(&mut srcs, true); - let scope = BrowseScope { sections_gen: 1, pins: vec![(a, 5, false)], clients: Default::default() }; + let scope = BrowseScope { sections_gen: 1, pins: &[(a, 5, false)], clients: Default::default() }; let keys = |build: &HubBuild| build.0.iter().map(|m| (m.sid, m.rk.clone(), m.art.clone())).collect::>(); let rows = |build: &HubBuild| build.1.iter().map(|h| (h.title.clone(), h.hub_id.clone(), h.key.clone(), h.source.clone(), h.total, h.start, h.len, h.offset, h.more, h.epoch)).collect::>(); diff --git a/rust-modules/data/src/pms_multi_source_merge_tests.rs b/rust-modules/data/src/pms_multi_source_merge_tests.rs index 7b1d3ca2ba..1e196f2268 100644 --- a/rust-modules/data/src/pms_multi_source_merge_tests.rs +++ b/rust-modules/data/src/pms_multi_source_merge_tests.rs @@ -906,7 +906,7 @@ fn an_unpinned_library_publishes_nothing() { ]; let scope = BrowseScope { sections_gen: 0, - pins: vec![(sid(0), 1, true), (sid(1), 1, false)], + pins: &[(sid(0), 1, true), (sid(1), 1, false)], clients: Default::default(), }; let (items, hubs, _) = merge_with_scope(&srcs, &scope); @@ -1191,7 +1191,7 @@ fn an_unpinned_roster_first_copy_does_not_hide_the_pinned_one() { ready(h[0].0, "", vec![card(h[0].0, "own", "Estudios sociales", Some(4), 2, true, 100)]), ready(h[1].0, "friend", vec![card(h[1].0, "theirs", "Social Studies", Some(4), 1, true, 900)]), ]); - let scope = BrowseScope { sections_gen: 1, pins: vec![(h[0].0, 2, false), (h[1].0, 1, true)], clients: Default::default() }; + let scope = BrowseScope { sections_gen: 1, pins: &[(h[0].0, 2, false), (h[1].0, 1, true)], clients: Default::default() }; let (cat, hubs, _) = merge_with_scope(&o.state.srcs, &scope); let deck: Vec<_> = cat[hubs[0].start..hubs[0].start + hubs[0].len].iter().map(|m| m.rk.clone()).collect(); assert_eq!(deck, ["theirs"], "the show does not vanish"); diff --git a/rust-modules/data/src/pms_recent_paging_tests.rs b/rust-modules/data/src/pms_recent_paging_tests.rs index 440bef6b42..0770f3ac6b 100644 --- a/rust-modules/data/src/pms_recent_paging_tests.rs +++ b/rust-modules/data/src/pms_recent_paging_tests.rs @@ -312,7 +312,7 @@ fn paging_a_sparse_pinned_row_retains_its_selected_visible_card() { Arc::make_mut(item).sec=if i%8==0 { 7 } else { 8 }; } seed(&mut owner.state,vec![src(registered.raw(),"",HubState::Ready,Some(build))]); - let scope=BrowseScope { sections_gen:1,pins:vec![(registered,7,true),(registered,8,false)],clients:std::borrow::Cow::Owned(registry_keys_for_test()) }; + let scope=BrowseScope { sections_gen:1,pins:&[(registered,7,true),(registered,8,false)],clients:std::borrow::Cow::Owned(registry_keys_for_test()) }; let mut held=None; let seen=owner.state.catalog_gen; let _=run_with_scope(&mut owner.state,&owner.adapter, diff --git a/rust-modules/data/src/pms_test_support.rs b/rust-modules/data/src/pms_test_support.rs index e91572bbcb..c14a09c451 100644 --- a/rust-modules/data/src/pms_test_support.rs +++ b/rust-modules/data/src/pms_test_support.rs @@ -96,8 +96,9 @@ pub(super) fn seed(state: &mut PmsState, mut srcs: Vec) { let build = merge(&srcs); state.srcs = srcs; // leave `sync_roster` idle — both halves, see `seed_for_test` - remember_roster(state, &BrowseScope::standalone()); - state.seen_facts = facts_key(); + let scope = BrowseScope::standalone(); + remember_roster(state, &scope); + state.seen_facts = facts_key(&scope); commit(state, build); } diff --git a/rust-modules/data/src/search.rs b/rust-modules/data/src/search.rs index e8e4e6fa2a..5fb39c2f38 100644 --- a/rust-modules/data/src/search.rs +++ b/rust-modules/data/src/search.rs @@ -785,17 +785,51 @@ impl Source { /// A profile switch can additionally deactivate only the middle slot, so even that post-sign-out /// window is not necessarily contiguous. One index per live server is the honest shape, whatever /// the slot numbers have reached. -fn slots() -> Vec { - plx_plex::plex::server_ids().map(|id| id.raw() as usize).collect() -} +fn slots(state: &SearchState) -> Arc> { state.live.clone() } /// How many sources this store fans out over — the width of [`slots`]. -fn nsrc() -> usize { - slots().len() +fn nsrc(state: &SearchState) -> usize { + state.clients.slots().count() } /// One Search owner's main-thread-only logical state (`docs/stores-as-machines.md`). Production /// gains one through `stores::search::SearchStore`; the worker-touched half is [`SearchAdapter`]. +/// All synchronous Search facts, captured by the host before commands as well as pumps. +#[derive(Clone, Copy)] +pub struct SearchInput<'a> { + pub keys: &'a ClientKeys, + pub recents: recents::Input<'a>, +} + +#[cfg(any(test, feature = "test-support"))] +pub struct FixtureInput { + pub keys: ClientKeys, + pub session: Arc, + pub settled: bool, + pub profile_generation: u32, + pub session_generation: u64, + pub tenure: u64, + pub profile_key: String, +} +#[cfg(any(test, feature = "test-support"))] +impl FixtureInput { + pub fn input(&self) -> SearchInput<'_> { + SearchInput { keys: &self.keys, recents: recents::Input { + session: &self.session, settled: self.settled, profile_generation: self.profile_generation, + session_generation: self.session_generation, tenure: self.tenure, profile_key: &self.profile_key } } + } +} +#[cfg(any(test, feature = "test-support"))] +pub fn fixture_input() -> FixtureInput { + let settled = plx_plex::plex::session::peek_settled(); + FixtureInput { keys: crate::pms::registry_keys_for_test(), settled: settled.is_some(), + session: settled.unwrap_or_else(plx_plex::plex::session::peek), + profile_generation: plx_plex::plex::session::current_gen(), + session_generation: plx_plex::plex::session::visible_generation(), + tenure: plx_plex::plex::session::tenure(), + profile_key: plx_plex::plex::session::current_profile_key() } +} + pub struct SearchState { /// The publish order of view-state edits, shared by `stores::Stores`. pub(crate) ledger: crate::viewledger::ViewLedger, @@ -817,6 +851,11 @@ pub struct SearchState { /// changes and same-slot re-points alike; both supersede cached answers and workers aimed at /// the previous origin/profile. visible: u32, + clients: ClientKeys, + live: Arc>, + profile_generation: u32, + profile_key: Option, + profile_tenure: u64, /// **The favourite table this result set was projected under**, taken once per query when /// the request is made (`plex/CLAUDE.md` rule 5) and read by [`rebuild`]'s merge. It ranks; it never @@ -874,6 +913,11 @@ impl Default for SearchState { state: State::Idle, gen: 0, visible: 0, + clients: ClientKeys::default(), + live: Arc::new(Vec::new()), + profile_generation: 0, + profile_key: None, + profile_tenure: 0, favs: Vec::new(), fav_gen: 0, settle_us: 0, @@ -894,6 +938,16 @@ impl SearchState { self.query.as_deref().unwrap_or("") } + pub(crate) fn run_local(&mut self, adapter: &Arc, cmd: crate::stores::search::SearchCmd) -> bool { + use crate::stores::search::SearchCmd; + match cmd { + SearchCmd::ApplyView { at, edit } => apply_view(self, &at, edit), + SearchCmd::Reset => { reset(self, adapter); true }, + _ => { plx_base::eventlog::log("search: command without captured input refused"); + debug_assert!(false, "Search command requires captured input"); false } + } + } + pub fn state(&self) -> State { self.state } @@ -913,48 +967,49 @@ impl SearchState { /// handed the household). #[cfg(any(test, feature = "test-support"))] pub fn snapshot(&self) -> view::SearchSnapshot { - self.snapshot_with_scope(self.scope_cache.snapshot(&[])) + let captured = fixture_input(); + let input = captured.input(); + self.snapshot_with_scope(self.scope_cache.snapshot_with_input(&input, &[]), &input) } /// `household`: the signed-in profile's household member ids, read by the application's /// `Bridge` (`Session::household_ids`) and handed in, so the source scope this publishes /// reads no session global. - pub fn snapshot_with_directory( - &self, - directory: crate::stores::browse::DirectoryView<'_>, - household: &[i64], - ) -> view::SearchSnapshot { - self.snapshot_with_scope(self.scope_cache.snapshot_with_directory(directory, household)) + pub fn snapshot_with_directory_and_input(&self, directory: crate::stores::browse::DirectoryView<'_>, + input: &SearchInput<'_>, household: &[i64]) -> view::SearchSnapshot { + self.snapshot_with_scope(self.scope_cache.snapshot_with_directory_and_input(directory, input, household), input) + } + #[cfg(any(test, feature = "test-support"))] + pub fn snapshot_with_directory(&self, directory: crate::stores::browse::DirectoryView<'_>, household: &[i64]) -> view::SearchSnapshot { + self.snapshot_with_directory_and_input(directory, &fixture_input().input(), household) } - fn snapshot_with_scope(&self, scope: scope::SourceScopeSnapshot) -> view::SearchSnapshot { + fn snapshot_with_scope(&self, scope: scope::SourceScopeSnapshot, input: &SearchInput<'_>) -> view::SearchSnapshot { view::SearchSnapshot::from_parts( self.query.clone(), self.shelves.clone(), self.state, self.gen, - recents::snapshot(), + recents::snapshot_with_input(&input.recents), scope, ) } /// Synchronous command path. `stores::search::SearchStore::run_with_directory` is the /// production caller and is what rotates `adapter` on `SearchCmd::Reset`. - pub fn run( - &mut self, - adapter: &Arc, - cmd: crate::stores::search::SearchCmd, - ) -> bool { - run_with_optional_directory(self, adapter, cmd, None) + #[cfg(any(test, feature = "test-support"))] + pub fn run(&mut self, adapter: &Arc, cmd: crate::stores::search::SearchCmd) -> bool { + run_with_optional_directory(self, adapter, cmd, None, &fixture_input().input()) } - pub fn run_with_directory( - &mut self, - adapter: &Arc, - cmd: crate::stores::search::SearchCmd, - directory: crate::stores::browse::DirectoryView<'_>, - ) -> bool { - run_with_optional_directory(self, adapter, cmd, Some(directory)) + pub fn run_with_directory_and_input(&mut self, adapter: &Arc, cmd: crate::stores::search::SearchCmd, + directory: crate::stores::browse::DirectoryView<'_>, input: &SearchInput<'_>) -> bool { + run_with_optional_directory(self, adapter, cmd, Some(directory), input) + } + #[cfg(any(test, feature = "test-support"))] + pub fn run_with_directory(&mut self, adapter: &Arc, cmd: crate::stores::search::SearchCmd, + directory: crate::stores::browse::DirectoryView<'_>) -> bool { + self.run_with_directory_and_input(adapter, cmd, directory, &fixture_input().input()) } /// Test-only compatibility pump for fixtures without a retained directory. The requests it @@ -962,29 +1017,30 @@ impl SearchState { #[cfg(any(test, feature = "test-support"))] pub fn pump(&mut self, adapter: &Arc, dt: f32) -> bool { pump_with_optional_directory(self, adapter, dt, None, - plx_machine::landgate::fixture_gate(), &crate::pms::registry_keys_for_test()) + plx_machine::landgate::fixture_gate(), &fixture_input().input()) } /// Advance the debounce, land whatever arrived under this frame's retained directory policy and /// emit the requests that are due. `keys` is the registry's answer as of this call. Returns /// whether anything changed, so the caller can re-clamp focus. It does NOT start the requests it /// emitted: the owner takes them from [`SearchState::jobs`] and owes them to a runner. - pub fn pump_with_directory_and_gate( - &mut self, - adapter: &Arc, - dt: f32, - directory: crate::stores::browse::DirectoryView<'_>, - gate: &plx_machine::landgate::Gate, - keys: &ClientKeys, - ) -> bool { - pump_with_optional_directory(self, adapter, dt, Some(directory), gate, keys) + pub fn pump_with_directory_and_input_and_gate(&mut self, adapter: &Arc, dt: f32, + directory: crate::stores::browse::DirectoryView<'_>, gate: &plx_machine::landgate::Gate, input: &SearchInput<'_>) -> bool { + pump_with_optional_directory(self, adapter, dt, Some(directory), gate, input) + } + #[cfg(any(test, feature = "test-support"))] + pub fn pump_with_directory_and_gate(&mut self, adapter: &Arc, dt: f32, + directory: crate::stores::browse::DirectoryView<'_>, gate: &plx_machine::landgate::Gate, keys: &ClientKeys) -> bool { + let captured = fixture_input(); + let input = SearchInput { keys, ..captured.input() }; + self.pump_with_directory_and_input_and_gate(adapter, dt, directory, gate, &input) } #[cfg(any(test, feature = "test-support"))] pub fn pump_with_directory(&mut self, adapter: &Arc, dt: f32, directory: crate::stores::browse::DirectoryView<'_>) -> bool { - self.pump_with_directory_and_gate(adapter, dt, directory, - plx_machine::landgate::fixture_gate(), &crate::pms::registry_keys_for_test()) + self.pump_with_directory_and_input_and_gate(adapter, dt, directory, + plx_machine::landgate::fixture_gate(), &fixture_input().input()) } /// Publish a bounded catalog through the real retained-view boundary, without network work. @@ -1007,9 +1063,11 @@ impl SearchState { plx_base::testlock::assert_held("the search store (publish_shelves_for_test)"); // A published catalog represents completed source answers, not merely painted rows over // still-pending requests. Keep it valid when a real owned-screen Tick pumps the store. - self.visible = plx_plex::plex::server_roster_gen(); + self.clients = crate::pms::registry_keys_for_test(); + self.visible = self.clients.roster_gen(); + self.live = Arc::new(self.clients.slots().map(|sid| sid.raw() as usize).collect()); snapshot(self); - for i in slots() { + for i in slots(self).iter().copied() { let items = std::array::from_fn(|k| { shelves .iter() @@ -1227,7 +1285,7 @@ fn favs_match_directory( #[cfg(any(test, feature = "test-support"))] fn pump(state: &mut SearchState, adapter: &Arc, dt: f32) -> bool { pump_with_optional_directory(state, adapter, dt, None, - plx_machine::landgate::fixture_gate(), &crate::pms::registry_keys_for_test()) + plx_machine::landgate::fixture_gate(), &fixture_input().input()) } fn pump_with_optional_directory( @@ -1236,19 +1294,11 @@ fn pump_with_optional_directory( dt: f32, directory: Option>, gate: &plx_machine::landgate::Gate, - keys: &ClientKeys, + input: &SearchInput<'_>, ) -> bool { - let live = slots(); - let visible = plx_plex::plex::server_roster_gen(); - let roster_changed = state.visible != visible; - state.visible = visible; - if roster_changed { - // This is an identity boundary, not merely a changed source count. Clear every answer and - // generation so a slot reactivated for another profile cannot surface rows fetched with - // the credential it held before it was hidden. - supersede(state, adapter); - state.shelves = None; - } + let roster_changed = observe_inputs(state, adapter, input); + let keys = input.keys; + let live = slots(state); // **The second Browse identity, and it moves without the first.** Discovery appending a library // and a favourites edit both bump `SECTIONS_GEN`; an independent owner can instead carry a // different exact table at the SAME local generation. This screen runs discovery immediately @@ -1291,7 +1341,7 @@ fn pump_with_optional_directory( plx_base::eventlog::log(&format!( "search: q[{}ch] settled, asking {} source(s)", q.chars().count(), - nsrc() + nsrc(state) )); } } @@ -1447,7 +1497,7 @@ fn live_sources<'a>(state: &'a SearchState, live: &[usize]) -> Vec<&'a Source> { /// Recompute the merged shelves from every source's last answer. The [`State`] is NOT set here — /// `pump` recomputes that every frame, landing or no landing (see the note there). fn rebuild(state: &mut SearchState) { - let live = slots(); + let live = slots(state); let sources = live_sources(state, &live); let los: [usize; NKIND] = std::array::from_fn(|k| state.wins[k].lo); let epochs: [u32; NKIND] = std::array::from_fn(|k| state.wins[k].committed); @@ -1629,7 +1679,7 @@ fn owed_read(state: &SearchState, i: usize) -> Option<(usize, std::ops::Range bool { let Some(range) = waited_on else { // a source the window was committed without, reading the window on screen if !source(state, i).skipped[k] { return false } - let (depths, _) = window_of(&live_sources(state, &slots()), k, state.wins[k].lo); + let (depths, _) = window_of(&live_sources(state, &slots(state)), k, state.wins[k].lo); if source(state, i).tails[k].needs(&depths) { if !progressed { source_mut(state, i).retry_cd = RETRY_FRAMES; } return false; @@ -1842,9 +1892,9 @@ fn prune_pending(state: &mut SearchState, live: &[usize]) -> bool { /// Move kind `k`'s window to start at `lo`: every lane lets go of the depths outside it, and /// [`rebuild`] (the caller's) draws the new cards. fn commit_window(state: &mut SearchState, k: usize, lo: usize) { - let live = slots(); + let live = slots(state); let (depths, _) = window_of(&live_sources(state, &live), k, lo); - for i in live { + for i in live.iter().copied() { let s = source_mut(state, i); s.tails[k].trim(depths.clone()); // whoever still lacks a depth of the new window was left out of it: owed, and asked outside @@ -1878,7 +1928,7 @@ fn page(state: &mut SearchState, kind: Kind, before: bool, seen: (usize, usize)) if !before { return false } state.wins[k].pending = None; } - let live = slots(); + let live = slots(state); let sources = live_sources(state, &live); let lo = state.wins[k].lo; let (depths, answered) = window_of(&sources, k, lo); @@ -2040,9 +2090,30 @@ fn tag_hit(t: &plx_plex::plex::Tag, sid: ServerId, favs: &[(ServerId, i64, bool) /// Drop everything — the account changed, so both the query and the results belong to someone /// else. Called beside the Browse `BrowseCmd::Reset` command. +fn observe_inputs(state: &mut SearchState, adapter: &Arc, input: &SearchInput<'_>) -> bool { + let profile_changed = state.profile_key.as_ref().is_some_and(|key| + state.profile_generation != input.recents.profile_generation || key != input.recents.profile_key + || state.profile_tenure != input.recents.tenure); + if state.profile_key.as_deref() != Some(input.recents.profile_key) { + state.profile_key = Some(input.recents.profile_key.to_owned()); + } + state.profile_generation = input.recents.profile_generation; + state.profile_tenure = input.recents.tenure; + let roster_changed = state.visible != input.keys.roster_gen() + || !state.clients.slots().eq(input.keys.slots()) || !state.clients.iter().eq(input.keys.iter()); + if !state.clients.slots().eq(input.keys.slots()) { + state.live = Arc::new(input.keys.slots().map(|sid| sid.raw() as usize).collect()); + } + state.visible = input.keys.roster_gen(); + if state.clients != *input.keys { state.clients.clone_from(input.keys); } + if profile_changed { reset(state, adapter); } + else if roster_changed { supersede(state, adapter); state.shelves = None; } + roster_changed || profile_changed +} + fn reset(state: &mut SearchState, adapter: &Arc) { supersede(state, adapter); - state.visible = plx_plex::plex::server_roster_gen(); + state.visible = state.clients.roster_gen(); state.query = None; state.shelves = None; state.state = State::Idle; @@ -2070,8 +2141,10 @@ fn run_with_optional_directory( adapter: &Arc, cmd: crate::stores::search::SearchCmd, directory: Option>, + input: &SearchInput<'_>, ) -> bool { use crate::stores::search::SearchCmd; + observe_inputs(state, adapter, input); match cmd { SearchCmd::SetQuery(q) => { match directory { @@ -2081,7 +2154,7 @@ fn run_with_optional_directory( true } SearchCmd::SetQueryScoped { profile_generation, query } => { - if profile_generation != plx_plex::plex::session::current_gen() { return false; } + if profile_generation != input.recents.profile_generation { return false; } match directory { Some(directory) => set_query_from_directory(state, adapter, &query, directory), None => set_query(state, adapter, &query), @@ -2089,12 +2162,12 @@ fn run_with_optional_directory( true } SearchCmd::RememberRecent { profile_generation, term } => { - let edit = crate::search::recents::remember(profile_generation, &term); + let edit = crate::search::recents::remember_with_input(&input.recents, profile_generation, &term); owe_recents_save(state, adapter, edit.save); edit.changed } SearchCmd::ClearRecents { profile_generation } => { - let edit = crate::search::recents::clear(profile_generation); + let edit = crate::search::recents::clear_with_input(&input.recents, profile_generation); owe_recents_save(state, adapter, edit.save); edit.changed } @@ -2187,3 +2260,7 @@ mod dump_tests; #[cfg(test)] #[path = "search_job_tests.rs"] mod job_tests; + +#[cfg(test)] +#[path = "search/captured_inputs_tests.rs"] +mod captured_inputs_tests; diff --git a/rust-modules/data/src/search/captured_inputs_tests.rs b/rust-modules/data/src/search/captured_inputs_tests.rs new file mode 100644 index 0000000000..9d4ebbcb1c --- /dev/null +++ b/rust-modules/data/src/search/captured_inputs_tests.rs @@ -0,0 +1,75 @@ +use super::*; +use crate::captured_store_fixture::{key, roster}; +use crate::stores::search::SearchCmd; +fn input<'a>(keys: &'a ClientKeys, session: &'a plx_plex::plex::session::Session, profile: &'a str) -> SearchInput<'a> { + SearchInput { keys, recents: recents::Input { session, settled: true, profile_generation: 7, + session_generation: 11, tenure: 99, profile_key: profile } } +} +#[test] +fn captured_roster_includes_unkeyed_slots_and_ignores_conflicting_ambient() { + let _serial = plx_base::testlock::serial(); + plx_plex::plex::reset_servers_for_test(); + let ambient = plx_plex::plex::register_for_test("ambient-search", "127.0.0.1", 9, "ambient", "ambient"); + let keys = roster(&[(61, Some(key(1)), "captured"), (101, None, "unkeyed")], 3, 4); + let session = Default::default(); + let input = input(&keys, &session, "alpha"); + let directory = crate::stores::browse::DirectorySnapshot::default(); + let adapter = Arc::new(SearchAdapter::default()); + let mut state = SearchState::default(); + state.run_with_directory_and_input(&adapter, SearchCmd::SetQuery("captured query".into()), directory.view(), &input); + state.pump_with_directory_and_input_and_gate(&adapter, 0.3, directory.view(), &plx_machine::landgate::Gate::default(), &input); + let jobs = std::mem::take(&mut state.jobs); + assert_eq!(jobs.len(), 1, "unkeyed registered slots do not create requests"); + let crate::stores::StoreJob::Search(job, port) = jobs.into_iter().next().unwrap() else { panic!("search job") }; + assert_eq!(job.req.sid, ServerId::from_raw(61)); + let scope = state.scope_cache.snapshot_with_directory_and_input(directory.view(), &input, &[]); + assert_eq!(scope.sources().iter().map(|s| s.sid.raw()).collect::>(), [61, 101]); + assert_eq!(scope.sources()[1].handle, "unkeyed", "partial Browse directory is not an authorization roster"); + port.refused(job.addr); + state.pump_with_directory_and_input_and_gate(&adapter, 0.016, directory.view(), &plx_machine::landgate::Gate::default(), &input); + assert!(state.jobs.is_empty(), "a refusal is observed rather than resent every pump"); + assert_eq!(plx_plex::plex::server_ids().collect::>(), [ambient], "scripted inputs never install themselves into ambient state"); + plx_plex::plex::reset_servers_for_test(); +} +#[test] +fn same_generation_full_keys_fence_late_answers_and_reset_uses_captured_roster() { + let _serial = plx_base::testlock::serial(); + let a = roster(&[(61, Some(key(1)), "")], 3, 4); + let b = roster(&[(61, Some(key(2)), "")], 3, 4); + let session = Default::default(); + let directory = crate::stores::browse::DirectorySnapshot::default(); + let adapter = Arc::new(SearchAdapter::default()); + let mut state = SearchState::default(); + state.run_with_directory_and_input(&adapter, SearchCmd::SetQuery("old query".into()), directory.view(), &input(&a, &session, "alpha")); + state.pump_with_directory_and_input_and_gate(&adapter, 0.3, directory.view(), &plx_machine::landgate::Gate::default(), &input(&a, &session, "alpha")); + let old = state.gen; + state.jobs.clear(); + state.pump_with_directory_and_input_and_gate(&adapter, 0.0, directory.view(), &plx_machine::landgate::Gate::default(), &input(&b, &session, "alpha")); + assert_ne!(state.gen, old, "same generation is not the full credential key"); + land(&adapter, 61, old, Some(Default::default())); + state.pump_with_directory_and_input_and_gate(&adapter, 0.0, directory.view(), &plx_machine::landgate::Gate::default(), &input(&b, &session, "alpha")); + assert!(state.shelves().is_empty(), "the retired request cannot publish"); + state.run_with_directory_and_input(&adapter, SearchCmd::Reset, directory.view(), &input(&b, &session, "alpha")); + assert!(state.query().is_empty()); + assert_eq!(state.visible, b.roster_gen()); + state.run_with_directory_and_input(&adapter, SearchCmd::SetQueryScoped { profile_generation: 6, query: "stale".into() }, directory.view(), &input(&b, &session, "beta")); + assert!(state.query().is_empty(), "a stale draft cannot cross the captured profile epoch"); +} +#[test] +fn facts_only_and_roster_only_observations_each_publish_once_at_equal_directory_generations() { + let _serial = plx_base::testlock::serial(); + let a = roster(&[(61, None, "old credit")], 3, 4); + let b = roster(&[(61, None, "new credit")], 3, 4); + let c = roster(&[(101, None, "new credit")], 3, 4); + let session = Default::default(); + let directory = crate::stores::browse::DirectorySnapshot::default(); + let cache = scope::ScopeCache::default(); + let first = cache.snapshot_with_directory_and_input(directory.view(), &input(&a, &session, "alpha"), &[]); + let changed = cache.snapshot_with_directory_and_input(directory.view(), &input(&b, &session, "alpha"), &[]); + assert!(!first.same_publication(&changed)); + assert_eq!(first.sources()[0].handle, "old credit", "retained facts never change under their reader"); + assert_eq!(changed.sources()[0].handle, "new credit"); + assert!(changed.same_publication(&cache.snapshot_with_directory_and_input(directory.view(), &input(&b, &session, "alpha"), &[]))); + let replaced = cache.snapshot_with_directory_and_input(directory.view(), &input(&c, &session, "alpha"), &[]); + assert_eq!(replaced.sources()[0].sid.raw(), 101, "equal-sized same-generation roster replacement is observed"); +} diff --git a/rust-modules/data/src/search/recents.rs b/rust-modules/data/src/search/recents.rs index cf19a4ce22..74eda00529 100644 --- a/rust-modules/data/src/search/recents.rs +++ b/rust-modules/data/src/search/recents.rs @@ -28,8 +28,21 @@ impl RecentsSnapshot { } } +/// A complete host observation; unsettled is an explicit transient session, not a missing input. +#[derive(Clone, Copy)] +pub struct Input<'a> { + pub session: &'a plx_plex::plex::session::Session, + pub settled: bool, + pub profile_generation: u32, + pub session_generation: u64, + pub tenure: u64, + pub profile_key: &'a str, +} + struct Store { session_generation: u64, + session_id: usize, + tenure: u64, generation: u32, who: String, account: Account, @@ -37,41 +50,58 @@ struct Store { } static STORE: Mutex> = Mutex::new(None); -fn with_store(f: impl FnOnce(&mut Store) -> R) -> R { +fn with_store(input: &Input<'_>, f: impl FnOnce(&mut Store) -> R) -> R { let mut guard = STORE.lock().unwrap_or_else(|e| e.into_inner()); - let generation = plx_plex::plex::session::current_gen(); - let session_generation = plx_plex::plex::session::visible_generation(); - let settled = plx_plex::plex::session::peek_settled(); - if settled.is_none() && guard.as_ref().is_some_and(|s| s.generation == generation) { + let generation = input.profile_generation; + let session_generation = input.session_generation; + let who = input.profile_key; + let session_id = std::ptr::from_ref(input.session) as usize; + if !input.settled && guard.as_ref().is_some_and(|s| s.generation == generation && s.tenure == input.tenure + && s.who == who && (input.session.client_id.is_empty() || s.account.matches(input.session))) { return f(guard.as_mut().unwrap()); } - if guard.as_ref().map(|s| (s.generation, s.session_generation)) != Some((generation, session_generation)) { - let who = plx_plex::plex::session::current_profile_key(); - // Copy before taking the session snapshot: a worker may drain this entry concurrently. - // Keep the pending-store lock separate from the session snapshot lock. + if !guard.as_ref().is_some_and(|s| s.generation == generation && s.tenure == input.tenure + && s.session_generation == session_generation && s.who == who + && s.account.matches(input.session) && s.session_id == session_id) { let pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()) - .iter().find(|p| p.who == who).cloned(); - let session = settled.unwrap_or_default(); - let account = Account::of(&session); - let terms = pending.filter(|p| p.account == account).map(|p| p.terms) - .unwrap_or_else(|| sanitize(session.recents_for(&who).to_vec())); - *guard = Some(Store { session_generation, generation, who, account, terms: Arc::new(terms) }); + .iter().find(|p| p.who == who && p.account.matches(input.session)).cloned(); + let terms = pending.map(|p| p.terms) + .unwrap_or_else(|| sanitize(input.session.recents_for(who).to_vec())); + *guard = Some(Store { session_generation, generation, session_id, tenure: input.tenure, who: who.to_owned(), + account: Account::of(input.session), terms: Arc::new(terms) }); } f(guard.as_mut().expect("profile cache is populated")) } /// Capture before screen processing. Borrowed terms thereafter perform no file or global read. -pub fn snapshot() -> RecentsSnapshot { - with_store(|s| RecentsSnapshot { generation: s.generation, terms: s.terms.clone() }) +pub fn snapshot_with_input(input: &Input<'_>) -> RecentsSnapshot { + with_store(input, |s| RecentsSnapshot { generation: s.generation, terms: s.terms.clone() }) } /// Update data and capture the persistence payload under the same profile-cache lock. /// Unchanged edits keep the same Arc and neither owe a write nor invalidate the frame. `submit` /// is called once when a write is owed: the edit changed the history, or its queue was full and a /// drain must be retried. -fn edit(profile_generation: u32, change: impl FnOnce(&[String]) -> Option>, submit: impl FnOnce()) -> bool { +#[cfg(any(test, feature = "test-support"))] +pub fn snapshot() -> RecentsSnapshot { snapshot_with_input(&super::fixture_input().input().recents) } +#[cfg(any(test, feature = "test-support"))] +pub fn remember(generation: u32, term: &str) -> Edit { + remember_with_input(&super::fixture_input().input().recents, generation, term) +} +#[cfg(any(test, feature = "test-support"))] +pub fn clear(generation: u32) -> Edit { clear_with_input(&super::fixture_input().input().recents, generation) } +#[cfg(test)] +fn remember_with(generation: u32, term: &str, submit: impl FnOnce()) -> bool { + remember_with_input_and_submit(&super::fixture_input().input().recents, generation, term, submit) +} +#[cfg(test)] +fn clear_with(generation: u32, submit: impl FnOnce()) -> bool { + clear_with_input_and_submit(&super::fixture_input().input().recents, generation, submit) +} + +fn edit(input: &Input<'_>, profile_generation: u32, change: impl FnOnce(&[String]) -> Option>, submit: impl FnOnce()) -> bool { let mut retry_drain = false; - let changed = with_store(|s| { + let changed = with_store(input, |s| { if s.generation != profile_generation { return false; } let Some(terms) = change(&s.terms) else { return false }; let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()); @@ -102,16 +132,16 @@ pub struct Edit { pub save: bool, } -pub fn remember(profile_generation: u32, term: &str) -> Edit { +pub fn remember_with_input(input: &Input<'_>, profile_generation: u32, term: &str) -> Edit { let mut save = false; - let changed = remember_with(profile_generation, term, || save = true); + let changed = remember_with_input_and_submit(input, profile_generation, term, || save = true); Edit { changed, save } } -fn remember_with(profile_generation: u32, term: &str, submit: impl FnOnce()) -> bool { +fn remember_with_input_and_submit(input: &Input<'_>, profile_generation: u32, term: &str, submit: impl FnOnce()) -> bool { let term = term.trim(); if !usable(term) { return false; } - edit(profile_generation, |old| { + edit(input, profile_generation, |old| { if old.first().is_some_and(|first| first == term) { return None; } let mut next = old.to_vec(); promote(&mut next, term); @@ -119,14 +149,14 @@ fn remember_with(profile_generation: u32, term: &str, submit: impl FnOnce()) -> }, submit) } -pub fn clear(profile_generation: u32) -> Edit { +pub fn clear_with_input(input: &Input<'_>, profile_generation: u32) -> Edit { let mut save = false; - let changed = clear_with(profile_generation, || save = true); + let changed = clear_with_input_and_submit(input, profile_generation, || save = true); Edit { changed, save } } -fn clear_with(profile_generation: u32, submit: impl FnOnce()) -> bool { - edit(profile_generation, |old| if old.is_empty() { None } else { Some(Vec::new()) }, submit) +fn clear_with_input_and_submit(input: &Input<'_>, profile_generation: u32, submit: impl FnOnce()) -> bool { + edit(input, profile_generation, |old| if old.is_empty() { None } else { Some(Vec::new()) }, submit) } /// What the store will hold, whatever the file said. `de_soft_vec` guarantees each entry is a @@ -199,6 +229,10 @@ impl Account { fn of(s: &plx_plex::plex::session::Session) -> Self { Self { client_id: s.client_id.clone(), token: s.account_token.clone() } } + + fn matches(&self, session: &plx_plex::plex::session::Session) -> bool { + self.client_id == session.client_id && self.token == session.account_token + } } #[derive(Clone)] struct Pending { account: Account, who: String, terms: Vec } @@ -301,6 +335,94 @@ fn flush() { mod tests { use super::*; + #[test] + fn captured_recents_are_profile_and_account_scoped_even_when_all_generations_repeat() { + let _serial = plx_base::testlock::serial(); + let _clear = ClearCaches; + let mut session = plx_plex::plex::session::Session { client_id: "captured-client".into(), + account_token: "captured-account".into(), ..Default::default() }; + session.set_recents_for("alpha", vec!["alpha history".into()]); + session.set_recents_for("beta", vec!["beta history".into()]); + let alpha = Input { session: &session, settled: true, profile_generation: 7, + session_generation: 11, tenure: 99, profile_key: "alpha" }; + let first = snapshot_with_input(&alpha); + assert_eq!(first.terms(), &["alpha history"]); + assert!(remember_with_input(&alpha, 7, "pending alpha").changed); + let beta = Input { profile_key: "beta", ..alpha }; + assert_eq!(snapshot_with_input(&beta).terms(), &["beta history"], "same-generation profile replacement never exposes another profile's terms"); + assert_eq!(first.terms(), &["alpha history"], "retained snapshots keep their original profile"); + assert!(!remember_with_input(&beta, 6, "stale draft").changed); + let mut replacement = plx_plex::plex::session::Session { client_id: "captured-client".into(), + account_token: "replacement-account".into(), ..Default::default() }; + replacement.set_recents_for("alpha", vec!["replacement history".into()]); + let replaced = Input { session: &replacement, ..alpha }; + assert_eq!(snapshot_with_input(&replaced).terms(), &["replacement history"], "queued old-account writes do not overlay the replacement account at equal generations"); + let transient_session = Default::default(); + let transient = Input { session: &transient_session, settled: false, ..replaced }; + assert_eq!(snapshot_with_input(&transient).terms(), &["replacement history"], "an explicit unsettled same-profile observation retains the readable publication"); + let reset = Input { tenure: 100, ..transient }; + assert!(snapshot_with_input(&reset).terms().is_empty(), "an unreadable replacement tenure must not retain the previous account's history"); + } + + + mod allocation_probe { + use super::*; + use plx_plex::plex::session::Session; + use std::alloc::{GlobalAlloc, Layout, System}; + use std::cell::Cell; + + struct CountAlloc; + thread_local! { static ALLOCATIONS: Cell> = const { Cell::new(None) }; } + fn allocated() { + ALLOCATIONS.with(|n| { if let Some(count) = n.get() { n.set(Some(count + 1)); } }); + } + unsafe impl GlobalAlloc for CountAlloc { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + allocated(); + unsafe { System.alloc(layout) } + } + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + allocated(); + unsafe { System.alloc_zeroed(layout) } + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { + allocated(); + unsafe { System.realloc(ptr, layout, size) } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } + } + #[global_allocator] + static ALLOCATOR: CountAlloc = CountAlloc; + + #[test] + fn stable_captured_recents_100_snapshots_allocate_nothing() { + let _serial = plx_base::testlock::serial(); + let _clear = ClearCaches; + let mut session = Session { client_id: "populated-client".into(), account_token: "populated-token".into(), ..Default::default() }; + session.set_recents_for("alpha", vec!["retained history".into()]); + let input = Input { session: &session, settled: true, profile_generation: 7, + session_generation: 11, tenure: 99, profile_key: "alpha" }; + let retained = snapshot_with_input(&input); + for settled in [true, false] { + let input = Input { settled, ..input }; + ALLOCATIONS.with(|n| n.set(Some(0))); + for _ in 0..100 { std::hint::black_box(snapshot_with_input(&input)); } + let allocations = ALLOCATIONS.with(|n| n.replace(None).unwrap()); + println!("100 stable snapshots, settled={settled}: {allocations} allocations"); + assert_eq!(allocations, 0, "stable snapshots must borrow credential/cache keys"); + } + assert_eq!(retained.terms(), &["retained history"]); + session.account_token = "replacement-token".into(); + session.set_recents_for("alpha", vec!["replacement history".into()]); + let replacement = snapshot_with_input(&Input { session: &session, settled: true, profile_generation: 7, + session_generation: 11, tenure: 99, profile_key: "alpha" }); + assert_eq!(replacement.terms(), &["replacement history"]); + assert_eq!(retained.terms(), &["retained history"]); + } + } + struct ClearCaches; impl Drop for ClearCaches { fn drop(&mut self) { diff --git a/rust-modules/data/src/search/scope.rs b/rust-modules/data/src/search/scope.rs index c862dd817c..19e8a49379 100644 --- a/rust-modules/data/src/search/scope.rs +++ b/rust-modules/data/src/search/scope.rs @@ -69,22 +69,34 @@ impl SourceScopeSnapshot { #[derive(PartialEq, Eq)] struct Key { - /// The generation catches ordinary roster changes; the exact ids catch an equal-sized - /// replacement even if a test or a future registry path reuses the generation. - roster_gen: u32, - roster: Vec, - /// `facts_gen` covers authoritative descriptions. The pointer fingerprint also covers the - /// server's self-description path, which merges a name without advancing that revision. - facts_gen: u32, - facts: Vec, - /// `sections_gen` covers library title/table landings; `source_list_gen` covers reachability - /// and other source facts maintained by Browse. + clients: plx_plex::plex::ClientKeys, sections_gen: u32, source_list_gen: u32, profile_gen: u32, + profile_key: String, + tenure: u64, session_gen: u64, } +impl Key { + fn matches(&self, input: &super::SearchInput<'_>, directory: Option>) -> bool { + self.clients == *input.keys + && self.profile_gen == input.recents.profile_generation + && self.profile_key == input.recents.profile_key + && self.tenure == input.recents.tenure + && self.session_gen == input.recents.session_generation + && self.sections_gen == directory.map_or(0, |d| d.sections_gen()) + && self.source_list_gen == directory.map_or(0, |d| d.source_list_gen()) + } + fn capture(input: &super::SearchInput<'_>, directory: Option>) -> Self { + Self { clients: input.keys.clone(), profile_gen: input.recents.profile_generation, + profile_key: input.recents.profile_key.to_owned(), tenure: input.recents.tenure, + session_gen: input.recents.session_generation, + sections_gen: directory.map_or(0, |d| d.sections_gen()), + source_list_gen: directory.map_or(0, |d| d.source_list_gen()) } + } +} + struct Cache { key: Key, /// The signed-in profile's household member ids the caller passed in: an INPUT of the build @@ -146,40 +158,20 @@ pub struct ScopeCache { cache: RefCell>, } -/// Read every registry input used by a standalone Search fixture. Production adds the retained -/// Browse directory generations through [`read_key_with_directory`]. -fn read_key() -> Key { - read_registry_key() -} - -fn read_key_with_directory(directory: crate::stores::browse::DirectoryView<'_>) -> Key { - let mut key = read_registry_key(); - key.sections_gen = directory.sections_gen(); - key.source_list_gen = directory.source_list_gen(); - key -} - -fn read_registry_key() -> Key { - // Every live server, however many: the fingerprint must move when ANY of them changes, so it - // cannot be a fixed-size prefix of the roster. - let roster: Vec = plx_plex::plex::server_ids().collect(); - let facts = roster - .iter() - .map(|&sid| plx_plex::plex::server_facts(sid).map_or(0, |f| std::ptr::from_ref(f) as usize)) - .collect(); - Key { - roster_gen: plx_plex::plex::server_roster_gen(), - roster, - facts_gen: plx_plex::plex::server_facts_gen(), - facts, - sections_gen: 0, - source_list_gen: 0, - profile_gen: plx_plex::plex::session::current_gen(), - session_gen: plx_plex::plex::session::visible_generation(), - } +#[cfg(test)] +fn capture_key_for_test(directory: crate::stores::browse::DirectoryView<'_>) -> Key { + Key::capture(&super::fixture_input().input(), Some(directory)) } impl ScopeCache { + #[cfg(any(test, feature = "test-support"))] + pub fn snapshot(&self, household: &[i64]) -> SourceScopeSnapshot { + self.snapshot_with_input(&super::fixture_input().input(), household) + } + #[cfg(any(test, feature = "test-support"))] + pub fn snapshot_with_directory(&self, directory: crate::stores::browse::DirectoryView<'_>, household: &[i64]) -> SourceScopeSnapshot { + self.snapshot_with_directory_and_input(directory, &super::fixture_input().input(), household) + } /// Capture the current source facts, rebuilding only when a cheap semantic input moves. /// /// `household` is the signed-in profile's household member ids @@ -187,18 +179,17 @@ impl ScopeCache { /// ViewState steps are handed their registry keys: this module reads the server registry and /// the session's two generation counters (`current_gen`, `visible_generation`, as memo keys), /// never the session's contents (`peek`). - pub fn snapshot(&self, household: &[i64]) -> SourceScopeSnapshot { - let key = read_key(); + pub fn snapshot_with_input(&self, input: &super::SearchInput<'_>, household: &[i64]) -> SourceScopeSnapshot { let mut cache = self.cache.borrow_mut(); let matches = cache.as_ref().is_some_and(|cached| { - cached.key == key && cached.household == household && cached.directory.is_none() + cached.key.matches(input, None) && cached.household == household && cached.directory.is_none() }); if !matches { *cache = Some(Cache { - key, + key: Key::capture(input, None), household: household.to_vec(), directory: None, - publication: build(household), + publication: build(input.keys, household), }); } cache @@ -208,24 +199,24 @@ impl ScopeCache { .clone() } - pub fn snapshot_with_directory( + pub fn snapshot_with_directory_and_input( &self, directory: crate::stores::browse::DirectoryView<'_>, + input: &super::SearchInput<'_>, household: &[i64], ) -> SourceScopeSnapshot { - let key = read_key_with_directory(directory); let mut cache = self.cache.borrow_mut(); let matches = cache.as_ref().is_some_and(|cached| { - cached.key == key + cached.key.matches(input, Some(directory)) && cached.household == household && cached.directory.as_ref().is_some_and(|input| input.matches(directory)) }); if !matches { *cache = Some(Cache { - key, + key: Key::capture(input, Some(directory)), household: household.to_vec(), directory: Some(DirectoryInput::capture(directory)), - publication: build_with_directory(directory, household), + publication: build_with_directory(directory, input.keys, household), }); } cache.as_ref().expect("source scope cache was just built").publication.clone() @@ -250,11 +241,11 @@ fn grant_of( } } -fn build(household: &[i64]) -> SourceScopeSnapshot { - let first = plx_plex::plex::server_ids().next(); - let sources = plx_plex::plex::server_ids() +fn build(keys: &plx_plex::plex::ClientKeys, household: &[i64]) -> SourceScopeSnapshot { + let first = keys.slots().next(); + let sources = keys.slots() .map(|sid| { - let facts = plx_plex::plex::server_facts(sid); + let facts = keys.facts(sid).and_then(|facts| facts.described); // Registration order is the only honest ownership answer before the roster has // described a slot; the session server is registered first. let grant = grant_of(facts, Some(sid) == first); @@ -279,11 +270,12 @@ fn build(household: &[i64]) -> SourceScopeSnapshot { fn build_with_directory( directory: crate::stores::browse::DirectoryView<'_>, + keys: &plx_plex::plex::ClientKeys, household: &[i64], ) -> SourceScopeSnapshot { - let first = plx_plex::plex::server_ids().next(); - let sources = plx_plex::plex::server_ids().map(|sid| { - let facts = plx_plex::plex::server_facts(sid); + let first = keys.slots().next(); + let sources = keys.slots().map(|sid| { + let facts = keys.facts(sid).and_then(|facts| facts.described); let grant = grant_of(facts, Some(sid) == first); ScopeSource { sid, @@ -470,7 +462,7 @@ mod tests { ); let alpha = directory("Alpha"); let beta = directory("Beta"); - assert!(read_key_with_directory(alpha.view()) == read_key_with_directory(beta.view()), + assert!(capture_key_for_test(alpha.view()) == capture_key_for_test(beta.view()), "the regression requires equal owner-local generations"); let cache = ScopeCache::default(); @@ -516,7 +508,7 @@ mod tests { ]); let dir_a = directory("Owner A's Library"); let dir_b = directory("Owner B's Library"); - assert!(read_key_with_directory(dir_a.view()) == read_key_with_directory(dir_b.view()), + assert!(capture_key_for_test(dir_a.view()) == capture_key_for_test(dir_b.view()), "the regression requires equal owner-local generations"); let owner_a = ScopeCache::default(); @@ -650,20 +642,20 @@ mod tests { stores.capture_seeded_browse_for_test(&mut directory, plx_plex::plex::current_server()); let cache = ScopeCache::default(); let old = cache.snapshot_with_directory(directory.view(), &household()); - let before = read_key_with_directory(directory.view()); + let before = capture_key_for_test(directory.view()); assert!(old.sources().iter().all(|source| source.live)); plx_plex::plex::describe_server(share, "renamed-share", "new-friend", plx_plex::plex::GrantEvidence::outside()); let described = cache.snapshot_with_directory(directory.view(), &household()); - let after = read_key_with_directory(directory.view()); + let after = capture_key_for_test(directory.view()); assert!(!old.same_publication(&described), "a described source is a new sentence"); assert_eq!(described.sources()[1].handle, "new-friend"); assert_eq!( - (after.roster_gen, &after.roster, after.sections_gen, after.source_list_gen), - (before.roster_gen, &before.roster, before.sections_gen, before.source_list_gen), + (after.clients.roster_gen(), after.clients.slots().collect::>(), after.sections_gen, after.source_list_gen), + (before.clients.roster_gen(), before.clients.slots().collect::>(), before.sections_gen, before.source_list_gen), "a pure description moves no roster, section or reachability counter" ); - assert_ne!(after.facts, before.facts, "…it moves the facts fingerprint, and that is enough"); + assert_ne!(after.clients, before.clients, "…it moves the facts fingerprint, and that is enough"); stores.browse.borrow_mut().seed_sources_for_test(2, false); stores.capture_seeded_browse_for_test(&mut directory, plx_plex::plex::current_server()); @@ -672,7 +664,7 @@ mod tests { assert!(quiet.sources().iter().all(|source| !source.live)); assert!(described.sources().iter().all(|source| source.live), "…and the retained publication keeps saying what it said"); - assert_ne!(read_key_with_directory(directory.view()).source_list_gen, after.source_list_gen); + assert_ne!(capture_key_for_test(directory.view()).source_list_gen, after.source_list_gen); } #[test] diff --git a/rust-modules/data/src/search/view.rs b/rust-modules/data/src/search/view.rs index f26c3d628a..075373baa1 100644 --- a/rust-modules/data/src/search/view.rs +++ b/rust-modules/data/src/search/view.rs @@ -199,6 +199,8 @@ mod tests { answer[0].push(Item::Media(crate::pms::PmsMovie { sid, rk: "new-answer".into(), title: "Replacement result".into(), ..Default::default() })); + let input = crate::search::fixture_input(); + crate::search::observe_inputs(&mut fx.state, &fx.adapter, &input.input()); crate::search::record_for_test(&mut fx.state, sid.raw() as usize, Some(answer)); crate::search::rebuild_for_test(&mut fx.state); let next = fx.snapshot(); diff --git a/rust-modules/data/src/search_account_scope_tests.rs b/rust-modules/data/src/search_account_scope_tests.rs index 0fcd50ebb2..459ff904ae 100644 --- a/rust-modules/data/src/search_account_scope_tests.rs +++ b/rust-modules/data/src/search_account_scope_tests.rs @@ -14,16 +14,16 @@ fn signing_into_a_second_account_searches_its_slots_and_not_the_retired_ones() { let _g = fresh(); let mut owner = Owner::default(); register(&mut owner, 2); - assert_eq!(slots(), vec![0, 1]); + assert_eq!(fixture_slots(), vec![0, 1]); plx_plex::plex::revoke_all(); assert!( - slots().is_empty(), + fixture_slots().is_empty(), "there is nothing to ask while signed out" ); - assert_eq!(nsrc(), 0); + assert_eq!(fixture_nsrc(), 0); assert!( - live_sources(&owner.state, &slots()).is_empty(), + live_sources(&owner.state, &fixture_slots()).is_empty(), "and the retired records reach neither the merge nor the verdict" ); @@ -40,12 +40,12 @@ fn signing_into_a_second_account_searches_its_slots_and_not_the_retired_ones() { "the next account gets a fresh slot, above the retired ones" ); assert_eq!( - slots(), + fixture_slots(), vec![2], "and the live id follows it rather than starting at 0" ); - assert_eq!(nsrc(), 1); - assert_eq!(live_sources(&owner.state, &slots()).len(), 1); + assert_eq!(fixture_nsrc(), 1); + assert_eq!(live_sources(&owner.state, &fixture_slots()).len(), 1); } #[test] @@ -72,7 +72,7 @@ fn a_profile_hole_searches_exact_live_ids_and_supersedes_the_previous_profiles_a ); assert_eq!(restored.raw(), 2); assert_eq!( - slots(), + fixture_slots(), vec![0, 2], "the inactive middle share is not replaced by a range" ); @@ -86,7 +86,7 @@ fn a_profile_hole_searches_exact_live_ids_and_supersedes_the_previous_profiles_a owner.state.shelves().is_empty(), "old-profile tiles disappear before a new source lands" ); - let live = live_sources(&owner.state, &slots()); + let live = live_sources(&owner.state, &fixture_slots()); assert_eq!(live.len(), 2); assert!( live.iter().all(|s| s.status == Status::Pending), @@ -155,7 +155,7 @@ fn a_server_past_the_old_sixteen_slot_table_is_asked_and_merged() { let _g = fresh(); let mut owner = Owner::default(); register(&mut owner, 41); - assert_eq!(slots().last(), Some(&40), "slot 40 is in the fan-out"); + assert_eq!(fixture_slots().last(), Some(&40), "slot 40 is in the fan-out"); hold_off(&mut owner); owner.state.query = Some(Arc::from("wallace")); @@ -183,7 +183,7 @@ fn forty_one_servers_are_asked_by_search_and_by_a_person_page() { let mut owner = Owner::default(); register(&mut owner, 41); let far = plx_plex::plex::ServerId::from_raw(40); - assert!(slots().contains(&40), "search fans out to server 40"); + assert!(fixture_slots().contains(&40), "search fans out to server 40"); hold_off(&mut owner); owner.state.query = Some(Arc::from("wallace")); let mut what: Projection = Default::default(); @@ -197,7 +197,11 @@ fn forty_one_servers_are_asked_by_search_and_by_a_person_page() { let mut person = crate::person::PersonState::default(); let adapter = crate::person::PersonAdapter::default(); - person.open_for_test(&adapter, plx_plex::plex::ServerId::from_raw(0), "161", "5d77682a", "Idina Menzel"); + let keys = crate::pms::registry_keys_for_test(); + let input = crate::person::PersonInput { keys: &keys, session: None, visible_generation: 0, + profile_scope: 0, owner_epoch: 0, profile_generation: 0, tenure: 0, profile_key: "", + controlled: false, profile_refused: false, credits_refused: false, dev_bio: None, dev_credits: None }; + person.open_for_test(&adapter, plx_plex::plex::ServerId::from_raw(0), "161", "5d77682a", "Idina Menzel", &input); assert!(person.asks_server_for_test(far), "the person page asks server 40 as well"); } @@ -251,7 +255,7 @@ fn a_search_over_forty_servers_asks_them_four_at_a_time() { let mut asked = std::collections::BTreeSet::new(); for _ in 0..2000 { owner.pump(0.016); - let out: Vec = slots().into_iter().filter(|&i| owner.adapter.mailbox(i).busy()).collect(); + let out: Vec = fixture_slots().into_iter().filter(|&i| owner.adapter.mailbox(i).busy()).collect(); assert!(out.len() <= crate::stores::fanout::WIDTH, "{} requests out at once", out.len()); asked.extend(out); if asked.len() == 40 { break; } diff --git a/rust-modules/data/src/search_dump_tests.rs b/rust-modules/data/src/search_dump_tests.rs index 385f5f067c..a711690f1d 100644 --- a/rust-modules/data/src/search_dump_tests.rs +++ b/rust-modules/data/src/search_dump_tests.rs @@ -31,7 +31,7 @@ fn dump_mode_a_request_out_lands_on_the_pump_that_runs_whatever_the_worker() { std::thread::sleep(WORKER_DELAY); land(&worker, 0, gen, Some(answered(0, vec![media("A Close Shave")]).items)); }); - assert!(pump_with_optional_directory(&mut owner.state, &owner.adapter, 0.0, None, &gate, &crate::pms::registry_keys_for_test()), + assert!(pump_with_optional_directory(&mut owner.state, &owner.adapter, 0.0, None, &gate, &fixture_input().input()), "the answer the pump owed must be taken by the pump that asked"); assert_eq!(titles(&owner.state.shelves()[0]), ["A Close Shave"]); assert_eq!(owner.state.state(), State::Ready); @@ -63,7 +63,7 @@ fn dump_mode_a_superseded_requests_stale_answer_does_not_release_the_new_claim() std::thread::sleep(WORKER_DELAY); land(&worker, 0, current, Some(answered(0, vec![media("A Close Shave")]).items)); }); - assert!(pump_with_optional_directory(&mut owner.state, &owner.adapter, 0.0, None, &gate, &crate::pms::registry_keys_for_test()), + assert!(pump_with_optional_directory(&mut owner.state, &owner.adapter, 0.0, None, &gate, &fixture_input().input()), "B was out when the pump ran, so B's answer must land on this pump"); assert_eq!(titles(&owner.state.shelves()[0]), ["A Close Shave"]); join.join().unwrap(); diff --git a/rust-modules/data/src/search_job_tests.rs b/rust-modules/data/src/search_job_tests.rs index 1998784bd6..8a19fe2d62 100644 --- a/rust-modules/data/src/search_job_tests.rs +++ b/rust-modules/data/src/search_job_tests.rs @@ -56,7 +56,7 @@ fn a_settled_query_emits_one_request_per_slot_naming_the_client_it_decided_on() let keys = crate::pms::registry_keys_for_test(); let jobs = taken(&mut owner); assert_eq!(jobs.len(), 2, "one request per live slot"); - for ((job, port), i) in jobs.iter().zip(slots()) { + for ((job, port), i) in jobs.iter().zip(fixture_slots()) { let sid = ServerId::from_raw(i as u16); assert_eq!(job.req.server(), (sid, keys.key(sid).expect("registered"))); assert_eq!(job.addr, search_addr(owner.state.gen), "addressed by the query's generation"); @@ -74,14 +74,21 @@ fn a_settled_query_emits_one_request_per_slot_naming_the_client_it_decided_on() #[test] fn a_slot_without_a_client_emits_nothing_and_lands_as_a_failure() { let (_fresh, mut owner) = settled(1); - let none = ClientKeys::default(); + let fixture = fixture_input(); + let captured = &fixture.keys; + let none = ClientKeys::captured(captured.current(), captured.roster_gen(), captured.facts_gen(), + captured.slots().map(|sid| (sid, None, captured.facts(sid).expect("registered facts").clone()))); + let input = SearchInput { keys: &none, ..fixture.input() }; + assert_eq!(none.slots().count(), 1, "the registered slot remains visible"); + assert!(none.iter().next().is_none(), "the captured slot has no client key"); pump_with_optional_directory(&mut owner.state, &owner.adapter, 0.3, None, - plx_machine::landgate::fixture_gate(), &none); + plx_machine::landgate::fixture_gate(), &input); assert!(owner.state.jobs.is_empty(), "no client, no request"); assert!(owner.adapter.mailbox(0).has_mail(), "the failure is posted through the mailbox"); - owner.pump(0.016); + pump_with_optional_directory(&mut owner.state, &owner.adapter, 0.016, None, + plx_machine::landgate::fixture_gate(), &input); assert_eq!(source(&owner.state, 0).status, Status::Failed); assert_eq!(owner.state.state(), State::Failed); assert!(!claim_held(&owner, 0), "the take of the failure released the claim"); diff --git a/rust-modules/data/src/search_paging_tests.rs b/rust-modules/data/src/search_paging_tests.rs index 739add0b7b..49bcec0f1c 100644 --- a/rust-modules/data/src/search_paging_tests.rs +++ b/rust-modules/data/src/search_paging_tests.rs @@ -30,7 +30,7 @@ impl Rig { fn drain(&mut self, pumps: usize) { for _ in 0..pumps { self.owner.pump(0.3); - let busy = slots().iter().filter(|&&i| self.owner.adapter.mailbox(i).busy()).count(); + let busy = fixture_slots().iter().filter(|&&i| self.owner.adapter.mailbox(i).busy()).count(); self.peak = self.peak.max(busy); } } @@ -38,7 +38,7 @@ impl Rig { fn page(&mut self, kind: Kind, before: bool) { let seen = self.seen(kind); self.owner.state.run(&self.owner.adapter, SearchCmd::Page { kind, before, seen }); - let n = 6 * nsrc() + 12; + let n = 6 * fixture_nsrc() + 12; self.drain(n); } @@ -244,7 +244,7 @@ fn a_slide_waiting_on_a_source_that_left_the_roster_does_not_wait_for_ever() { let mut rig = Rig::new(2, Fake::new().movies(100)); let lo = rig.owner.state.wins[0].lo; rig.owner.state.wins[0].pending = Some(Pending { lo: lo + 4, hi: lo + 16, todo: vec![57], ..Default::default() }); - assert!(prune_pending(&mut rig.owner.state, &slots()), "the slide committed without it"); + assert!(prune_pending(&mut rig.owner.state, &fixture_slots()), "the slide committed without it"); assert_eq!(rig.owner.state.wins[0].lo, lo + 4); assert!(rig.owner.state.wins[0].pending.is_none()); } @@ -319,7 +319,7 @@ fn an_ask_computed_from_a_window_the_row_has_since_slid_is_refused() { let filled = rig.seen(Kind::Movie); assert_eq!((preview, filled), ((0, 12), (0, 24)), "the fill landed"); rig.owner.state.run(&rig.owner.adapter, SearchCmd::Page { kind: Kind::Movie, before: false, seen: preview }); - rig.drain(6 * nsrc() + 12); + rig.drain(6 * fixture_nsrc() + 12); assert_eq!(rig.seen(Kind::Movie), filled, "the filled window did not slide"); let first = filled.0; rig.page(Kind::Movie, false); @@ -327,7 +327,7 @@ fn an_ask_computed_from_a_window_the_row_has_since_slid_is_refused() { assert!(slid > first, "the slide landed"); let keys = rig.keys(Kind::Movie); rig.owner.state.run(&rig.owner.adapter, SearchCmd::Page { kind: Kind::Movie, before: false, seen: filled }); - rig.drain(6 * nsrc() + 12); + rig.drain(6 * fixture_nsrc() + 12); assert_eq!((rig.shelf(Kind::Movie).window.start, rig.keys(Kind::Movie)), (slid, keys), "the window did not move"); assert!(rig.owner.state.wins[0].pending.is_none()); // the way back, from the window that stands @@ -348,7 +348,7 @@ fn a_repeated_slide_ask_reads_and_slides_once_and_a_refused_one_is_taken_when_re for _ in 0..repeats { rig.owner.state.run(&rig.owner.adapter, SearchCmd::Page { kind: Kind::Movie, before: false, seen }); } - rig.drain(6 * nsrc() + 12); + rig.drain(6 * fixture_nsrc() + 12); let log = rig.fake.lock().unwrap().log.len(); (log, rig.seen(Kind::Movie), rig.keys(Kind::Movie)) }; @@ -362,10 +362,10 @@ fn a_repeated_slide_ask_reads_and_slides_once_and_a_refused_one_is_taken_when_re assert_ne!(moved, stale); rig.fake.lock().unwrap().log.clear(); rig.owner.state.run(&rig.owner.adapter, SearchCmd::Page { kind: Kind::Movie, before: false, seen: stale }); - rig.drain(6 * nsrc() + 12); + rig.drain(6 * fixture_nsrc() + 12); assert_eq!((rig.seen(Kind::Movie), rig.fake.lock().unwrap().log.len()), (moved, 0), "refused: no slide, no read"); rig.owner.state.run(&rig.owner.adapter, SearchCmd::Page { kind: Kind::Movie, before: false, seen: moved }); - rig.drain(6 * nsrc() + 12); + rig.drain(6 * fixture_nsrc() + 12); assert_ne!(rig.seen(Kind::Movie), moved, "sent again from the window that stands, it is taken"); } @@ -400,7 +400,7 @@ fn a_row_whose_every_landing_meets_a_stale_ask_still_reaches_its_last_card() { let stale = rig.seen(Kind::Movie); rig.page(Kind::Movie, false); rig.owner.state.run(&rig.owner.adapter, SearchCmd::Page { kind: Kind::Movie, before: false, seen: stale }); - rig.drain(6 * nsrc() + 12); + rig.drain(6 * fixture_nsrc() + 12); seen.extend(rig.keys(Kind::Movie)); } assert!(!rig.shelf(Kind::Movie).window.after, "the last card was reached"); diff --git a/rust-modules/data/src/search_query_debounce_tests.rs b/rust-modules/data/src/search_query_debounce_tests.rs index 9c6e5fbe69..4c7b62c449 100644 --- a/rust-modules/data/src/search_query_debounce_tests.rs +++ b/rust-modules/data/src/search_query_debounce_tests.rs @@ -289,7 +289,7 @@ fn an_empty_roster_settles_instead_of_spinning_forever() { State::Searching, "the query starts out pending, as typed" ); - assert_eq!(nsrc(), 0, "no server can ever answer it"); + assert_eq!(fixture_nsrc(), 0, "no server can ever answer it"); assert!( owner.pump(SETTLE_S * 2.0), "the verdict changed, so the screen must repaint" diff --git a/rust-modules/data/src/search_test_support.rs b/rust-modules/data/src/search_test_support.rs index 578e0b68ae..23817cc210 100644 --- a/rust-modules/data/src/search_test_support.rs +++ b/rust-modules/data/src/search_test_support.rs @@ -5,6 +5,11 @@ use super::*; /// **No library is enumerated**, which by [`section_is_fav`]'s unknown rule makes every hit a /// favourite — so every test below that does not care about ranking grades the round-robin /// merge exactly as it did before favourites existed. The ranking tests build their own table. +pub(super) fn fixture_slots() -> Vec { + crate::pms::registry_keys_for_test().slots().map(|sid| sid.raw() as usize).collect() +} +pub(super) fn fixture_nsrc() -> usize { fixture_slots().len() } + pub(super) const NO_FAVS: &[(ServerId, i64, bool)] = &[]; /// [`merge`] with no favourite table, for the tests whose subject is the merge itself. @@ -35,6 +40,7 @@ impl Default for Owner { impl Owner { pub(super) fn set_query(&mut self, q: &str) { + observe_inputs(&mut self.state, &self.adapter, &fixture_input().input()); set_query(&mut self.state, &self.adapter, q); } pub(super) fn set_query_from_directory( @@ -42,6 +48,7 @@ impl Owner { q: &str, directory: crate::stores::browse::DirectoryView<'_>, ) { + observe_inputs(&mut self.state, &self.adapter, &fixture_input().input()); set_query_from_directory(&mut self.state, &self.adapter, q, directory); } pub(super) fn run_with_directory( @@ -130,7 +137,7 @@ pub(super) fn fresh() -> Fresh { /// they inject themselves, and a request on the outbox would be one more thing for them to account /// for. Call it before every `pump()`. pub(super) fn hold_off(owner: &mut Owner) { - for i in slots() { + for i in fixture_slots() { source_mut(&mut owner.state, i).retry_cd = RETRY_FRAMES; } owner.state.armed = false; @@ -152,8 +159,10 @@ pub(super) fn register(owner: &mut Owner, n: usize) { // Test setup finishes before any seeded mailbox/status. Production learns this boundary // from its first pump; fixtures that inject a landing directly must mark the just-built // roster as already observed so that first pump grades the landing rather than setup. - owner.state.visible = plx_plex::plex::server_roster_gen(); - assert_eq!(nsrc(), n); + owner.state.clients = crate::pms::registry_keys_for_test(); + owner.state.visible = owner.state.clients.roster_gen(); + owner.state.live = Arc::new(owner.state.clients.slots().map(|sid| sid.raw() as usize).collect()); + assert_eq!(fixture_nsrc(), n); } pub(super) fn hub(id: &str, kind: &str) -> Hub { diff --git a/rust-modules/data/src/stores/browse.rs b/rust-modules/data/src/stores/browse.rs index dd6904ade0..554e6ed7e5 100644 --- a/rust-modules/data/src/stores/browse.rs +++ b/rust-modules/data/src/stores/browse.rs @@ -154,12 +154,13 @@ impl BrowseStore { /// controlled Home arm admits the discovery through the run's ledger). #[must_use] pub fn take_jobs(&mut self) -> Vec { + self.jobs.extend(self.state.take_preference_jobs()); std::mem::take(&mut self.jobs) } /// Does the outbox hold a job nobody has taken yet? pub fn has_jobs(&self) -> bool { - !self.jobs.is_empty() + !self.jobs.is_empty() || self.state.has_preference_jobs() } /// Run one command for a caller that holds no session: the Stores fan-outs, which send only @@ -174,7 +175,7 @@ impl BrowseStore { return false; } let session = plx_plex::plex::session::Session::default(); - self.run_with_input(cmd, &BrowseRosterInput { + self.run_with_input(cmd, &BrowseRosterInput { tenure: 0, keys, session: &session, visible_generation: 0, settled: false, profile_key: "", }) } @@ -221,7 +222,7 @@ impl BrowseStore { pub fn run_for_test(&mut self, cmd: BrowseCmd) -> bool { self.observe_pin_write(); let session = plx_plex::plex::session::peek(); - self.run_with_input(cmd, &BrowseRosterInput { + self.run_with_input(cmd, &BrowseRosterInput { tenure: plx_plex::plex::session::tenure(), keys: &ClientKeys::default(), session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -266,7 +267,7 @@ impl BrowseStore { keys.refill_roster(plx_plex::plex::current_server(), plx_plex::plex::server_roster_gen(), plx_plex::plex::server_facts_gen(), plx_plex::plex::server_ids(), plx_plex::plex::client_for, plx_plex::plex::server_facts, plx_plex::plex::server_probe_result); - self.pump_with_gate(plx_machine::landgate::fixture_gate(), &BrowseRosterInput { + self.pump_with_gate(plx_machine::landgate::fixture_gate(), &BrowseRosterInput { tenure: plx_plex::plex::session::tenure(), keys: &keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -303,7 +304,7 @@ impl BrowseStore { keys.refill_roster(plx_plex::plex::current_server(), plx_plex::plex::server_roster_gen(), plx_plex::plex::server_facts_gen(), plx_plex::plex::server_ids(), plx_plex::plex::client_for, plx_plex::plex::server_facts, plx_plex::plex::server_probe_result); - self.discover_pump_with_gate(plx_machine::landgate::fixture_gate(), &BrowseRosterInput { + self.discover_pump_with_gate(plx_machine::landgate::fixture_gate(), &BrowseRosterInput { tenure: plx_plex::plex::session::tenure(), keys: &keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -921,7 +922,7 @@ mod contract_tests { ); let session = plx_plex::plex::session::peek(); let profile_key = plx_plex::plex::session::current_profile_key(); - let input = BrowseRosterInput { + let input = BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), profile_key: &profile_key, @@ -1173,7 +1174,7 @@ mod contract_tests { plx_plex::plex::client_for, plx_plex::plex::server_facts, plx_plex::plex::server_probe_result, ); - let input = BrowseRosterInput { + let input = BrowseRosterInput { tenure: 0, keys: &keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), diff --git a/rust-modules/data/src/stores/held_keys_tests.rs b/rust-modules/data/src/stores/held_keys_tests.rs index 8b89f953bd..61ed484fd4 100644 --- a/rust-modules/data/src/stores/held_keys_tests.rs +++ b/rust-modules/data/src/stores/held_keys_tests.rs @@ -39,7 +39,11 @@ fn person_holds_its_shelves_for_that_person_only() { let arg = ContentArg::Person { sid: ServerId::UNSET, key: "42".into(), guid: String::new(), name: "N".into(), thumb: String::new() }; assert!(store.held_keys(&arg).is_empty(), "no person mounted"); - store.run(PersonCmd::Open { sid: ServerId::UNSET, key: "42".into(), guid: String::new(), name: "N".into(), thumb: String::new() }); + let keys = plx_plex::plex::ClientKeys::default(); + let input = crate::person::PersonInput { keys: &keys, session: None, visible_generation: 0, + profile_scope: 0, owner_epoch: 0, profile_generation: 0, tenure: 0, profile_key: "", + controlled: false, profile_refused: false, credits_refused: false, dev_bio: None, dev_credits: None }; + store.run_with_input(PersonCmd::Open { sid: ServerId::UNSET, key: "42".into(), guid: String::new(), name: "N".into(), thumb: String::new() }, &input); store.install_for_test(vec![movie("a"), movie("b")], vec![movie("c")]); assert_eq!(rks(&store.held_keys(&arg)), ["a", "b", "c"]); let other = ContentArg::Person { diff --git a/rust-modules/data/src/stores/metadata.rs b/rust-modules/data/src/stores/metadata.rs index 39bda3db24..833007ee19 100644 --- a/rust-modules/data/src/stores/metadata.rs +++ b/rust-modules/data/src/stores/metadata.rs @@ -345,7 +345,13 @@ impl MetadataStore { /// `Clear` — see the struct doc. `Reset` (the server/profile switch) DOES rotate, before the /// state clears, so a worker spawned before the reset can only land into the retired `Arc` — /// mirrors `PersonStore::run`/`SearchStore::run_with_directory`'s `Reset` arm. - pub fn run(&mut self, cmd: MetadataCmd) -> bool { + pub fn run(&mut self, cmd: MetadataCmd) -> bool { self.run_with_optional_keys(cmd, None) } + + pub fn run_with_keys(&mut self, cmd: MetadataCmd, keys: &plx_plex::plex::ClientKeys) -> bool { + self.run_with_optional_keys(cmd, Some(keys)) + } + + fn run_with_optional_keys(&mut self, cmd: MetadataCmd, keys: Option<&plx_plex::plex::ClientKeys>) -> bool { if matches!(&cmd, MetadataCmd::Reset) { self.adapter = Arc::new(Default::default()); } @@ -353,7 +359,7 @@ impl MetadataStore { // is drawn) raises no notice: a notice relayouts a mounted Detail page. Every other // command bumps whatever it returned. let view_edit = matches!(&cmd, MetadataCmd::ApplyView { .. }); - let changed = crate::metadata::run(&mut self.state, &self.adapter, cmd); + let changed = crate::metadata::run_with_keys(&mut self.state, &self.adapter, cmd, keys); if changed || !view_edit { self.bump(); } diff --git a/rust-modules/data/src/stores/mod.rs b/rust-modules/data/src/stores/mod.rs index bda309688d..5566d17af6 100644 --- a/rust-modules/data/src/stores/mod.rs +++ b/rust-modules/data/src/stores/mod.rs @@ -81,6 +81,7 @@ pub mod tape; pub mod viewreconcile; pub mod viewstate; pub mod watchlist; +pub mod watchlist_job; /// Production store aggregate. All seven stores are physical owners here — Browse, Person and /// ViewState landed first; Search, Hubs and Metadata completed the port. @@ -171,6 +172,7 @@ impl Stores { cmd: browse::BrowseCmd, input: &browse::BrowseRosterInput<'_>, ) -> bool { + let _step = plx_base::step::StepScope::enter(); self.browse.borrow_mut().run_with_input(cmd, input) } @@ -179,7 +181,7 @@ impl Stores { /// the pin write was observed. #[cfg(any(test, feature = "test-support"))] pub fn browse_run_for_test(&self, cmd: browse::BrowseCmd) -> bool { - self.browse_run(cmd, &browse::BrowseRosterInput { + self.browse_run(cmd, &browse::BrowseRosterInput { tenure: 0, keys: &Default::default(), session: &Default::default(), visible_generation: 0, settled: false, profile_key: "", }) @@ -196,6 +198,7 @@ impl Stores { &self, input: &browse::BrowseRosterInput<'_>, ) -> StoreOutcome { + let _step = plx_base::step::StepScope::enter(); self.browse.borrow_mut().discover_pump_with_gate(&self.landgate, input) } @@ -206,13 +209,15 @@ impl Stores { self.browse.borrow_mut().discover_pump() } - pub fn person_run(&mut self, cmd: person::PersonCmd) -> bool { - self.person.run(cmd) +pub fn person_run(&mut self, cmd: person::PersonCmd, input: &crate::person::PersonInput<'_>) -> bool { + let _step = plx_base::step::StepScope::enter(); + self.person.run_with_input(cmd, input) } /// Run one Collection command; `keys` is the registry's answer as of this call. A command /// emits no job. pub fn collection_run(&mut self, cmd: collection::CollectionCmd, keys: &plx_plex::plex::ClientKeys) -> bool { + let _step = plx_base::step::StepScope::enter(); self.collection.run(cmd, keys) } @@ -221,6 +226,7 @@ impl Stores { /// the job to a runner has stranded the page's fetch. The one production caller is /// `Bridge::collection_pump`, which drains in the same call. pub fn collection_pump(&mut self, keys: &plx_plex::plex::ClientKeys) -> bool { + let _step = plx_base::step::StepScope::enter(); self.collection.pump(&self.landgate, keys) } @@ -229,6 +235,7 @@ impl Stores { } pub fn subtitle_search_run(&mut self, cmd: subsearch::SubSearchCmd) -> bool { + let _step = plx_base::step::StepScope::enter(); self.subtitle_search.run(cmd) } @@ -237,6 +244,7 @@ impl Stores { /// handing the job to a runner has stranded the search. The one production caller is /// `Bridge::subsearch_pump`, which drains in the same call. pub fn subtitle_search_pump(&mut self, keys: &plx_plex::plex::ClientKeys) -> bool { + let _step = plx_base::step::StepScope::enter(); self.subtitle_search.pump(&self.landgate, keys) } @@ -248,8 +256,9 @@ impl Stores { /// requests it emitted: a caller that returns without [`Stores::take_jobs_of`] and handing the /// jobs to a runner has stranded the page's fetches. The one production caller is /// `Bridge::person_pump`, which drains in the same call. - pub fn person_pump(&mut self, keys: &plx_plex::plex::ClientKeys) -> bool { - self.person.pump(&self.landgate, keys) +pub fn person_pump(&mut self, input: &crate::person::PersonInput<'_>) -> bool { + let _step = plx_base::step::StepScope::enter(); + self.person.pump(&self.landgate, input) } pub fn person_view(&self) -> crate::person::PersonView<'_> { @@ -261,8 +270,9 @@ impl Stores { /// handing each job to a runner has stranded the request. The one production caller is /// `Bridge::metadata_run`, which drains in the same call; the application's test rigs fail a /// frame that ends with a job still here (`Bridge::assert_no_store_jobs_left_for_test`). - pub fn metadata_run(&mut self, cmd: metadata::MetadataCmd) -> bool { - self.metadata.run(cmd) + pub fn metadata_run(&mut self, cmd: metadata::MetadataCmd, keys: &plx_plex::plex::ClientKeys) -> bool { + let _step = plx_base::step::StepScope::enter(); + self.metadata.run_with_keys(cmd, keys) } /// Take every job any store has emitted since the last take, store by store in a fixed order. @@ -283,6 +293,7 @@ impl Stores { pub fn take_jobs_of(&mut self, id: StoreId) -> Vec { match id { StoreId::Notify => self.notify.take_jobs(), + StoreId::Watchlist => self.watchlist.take_jobs(), StoreId::Metadata => self.metadata.take_jobs(), StoreId::Collection => self.collection.take_jobs(), StoreId::Person => self.person.take_jobs(), @@ -307,6 +318,7 @@ impl Stores { fn has_jobs_of(&self, id: StoreId) -> bool { match id { StoreId::Notify => self.notify.has_jobs(), + StoreId::Watchlist => self.watchlist.has_jobs(), StoreId::Metadata => self.metadata.has_jobs(), StoreId::Collection => self.collection.has_jobs(), StoreId::Person => self.person.has_jobs(), @@ -323,6 +335,7 @@ impl Stores { } pub fn metadata_pump(&mut self, keys: &plx_plex::plex::ClientKeys, controlled: bool, stand_in: Option>) -> bool { + let _step = plx_base::step::StepScope::enter(); self.metadata.pump(keys, controlled, stand_in, &self.landgate) } @@ -334,8 +347,10 @@ impl Stores { &mut self, cmd: search::SearchCmd, directory: browse::DirectoryView<'_>, + input: &crate::search::SearchInput<'_>, ) -> bool { - self.search.run_with_directory(cmd, directory) + let _step = plx_base::step::StepScope::enter(); + self.search.run_with_directory_and_input(cmd, directory, input) } /// Pump the Search store; `keys` is the registry's answer as of this call. It does NOT start the @@ -346,21 +361,41 @@ impl Stores { &mut self, dt: f32, directory: browse::DirectoryView<'_>, - keys: &plx_plex::plex::ClientKeys, + input: &crate::search::SearchInput<'_>, ) -> bool { - self.search.pump_with_directory_and_gate(dt, directory, &self.landgate, keys) + let _step = plx_base::step::StepScope::enter(); + self.search.pump_with_directory_and_input_and_gate(dt, directory, &self.landgate, input) } pub fn search_snapshot( &self, directory: browse::DirectoryView<'_>, household: &[i64], + input: &crate::search::SearchInput<'_>, ) -> search::SearchSnapshot { - self.search.snapshot_with_directory(directory, household) + self.search.snapshot_with_directory_and_input(directory, household, input) } /// Controlled discovery against this aggregate's Browse owner: the read it asks for is left on /// Browse's outbox, for the controlled Home arm to admit through the run's ledger. + #[cfg(any(test, feature = "test-support"))] + pub fn search_run_for_test(&mut self, cmd: search::SearchCmd, directory: browse::DirectoryView<'_>) -> bool { + self.search_run(cmd, directory, &crate::search::fixture_input().input()) + } + #[cfg(any(test, feature = "test-support"))] + pub fn search_pump_for_test(&mut self, dt: f32, directory: browse::DirectoryView<'_>, keys: &plx_plex::plex::ClientKeys) -> bool { + let captured = crate::search::fixture_input(); + let input = crate::search::SearchInput { keys, ..captured.input() }; + self.search_pump(dt, directory, &input) + } + #[cfg(any(test, feature = "test-support"))] + pub fn search_snapshot_for_test(&self, directory: browse::DirectoryView<'_>, household: &[i64]) -> search::SearchSnapshot { + self.search_snapshot(directory, household, &crate::search::fixture_input().input()) + } + #[cfg(any(test, feature = "test-support"))] + pub fn metadata_run_for_test(&mut self, cmd: metadata::MetadataCmd) -> bool { + self.metadata_run(cmd, &crate::pms::registry_keys_for_test()) + } pub fn browse_controlled_discover(&self, input: &browse::BrowseRosterInput<'_>) { self.browse.borrow_mut().controlled_discover(input); } @@ -385,6 +420,7 @@ impl Stores { clients: &plx_plex::plex::ClientKeys, profile: u32, ) -> StoreOutcome { + let _step = plx_base::step::StepScope::enter(); if matches!(cmd, viewstate::ViewStateCmd::Reset) { self.reconcile.reset(); self.notify.reset(); @@ -405,7 +441,7 @@ impl Stores { &mut |hubcmd| hubs.run_with_directory(hubcmd, directory, clients), &mut |cmd| person.run(cmd), &mut |cmd| view_edit_collection(collection, cmd), - &mut |cmd| search.run_with_directory(cmd, directory), + &mut |cmd| search.run_local(cmd), &mut |cmd| metadata.run(cmd), ) } @@ -419,6 +455,7 @@ impl Stores { clients: &plx_plex::plex::ClientKeys, profile: u32, ) -> EndpointRefreshSet { + let _step = plx_base::step::StepScope::enter(); let browse = std::rc::Rc::clone(&self.browse); let hubs = &mut self.hubs; let person = &mut self.person; @@ -434,7 +471,7 @@ impl Stores { &mut |hubcmd| hubs.run_with_directory(hubcmd, directory, clients), &mut |cmd| person.run(cmd), &mut |cmd| view_edit_collection(collection, cmd), - &mut |cmd| search.run_with_directory(cmd, directory), + &mut |cmd| search.run_local(cmd), &mut |cmd| metadata.run(cmd), ) } @@ -443,26 +480,31 @@ impl Stores { /// (`StoreId` order): a server-side change re-reads its sections' shelves with /// `HubsInvalidateServer` and reads the affected source back with `RefetchSourceQuiet`. The /// Bridge drains exactly these after the map (`Bridge::start_store_jobs_in`). - pub const NOTIFY_FILLS: &'static [StoreId] = &[StoreId::Browse, StoreId::Hubs]; + pub const NOTIFY_FILLS: &'static [StoreId] = &[StoreId::Browse, StoreId::Hubs, StoreId::Watchlist]; /// The notification feed's per-frame pass. It stands down while the landing gate is armed (a /// recording, a replay or a dump owns the run), and never reads the registry's tokens. pub fn notify_begin(&mut self, input: ¬ify::NotifyInput<'_>) -> notify::NotifyPass { + let _step = plx_base::step::StepScope::enter(); assert_eq!(input.armed, self.landgate.is_armed()); self.notify.begin(input) } pub fn notify_prepare_next(&mut self, pass: &mut notify::NotifyPass, input: ¬ify::NotifyInput<'_>) -> Option { + let _step = plx_base::step::StepScope::enter(); assert_eq!(input.armed, self.landgate.is_armed()); self.notify.prepare_next(pass, input) } pub fn notify_settle_admission(&mut self, pass: &mut notify::NotifyPass, turn: &mut notify::NotifyTurn) { + let _step = plx_base::step::StepScope::enter(); self.notify.settle_admission(pass, turn) } pub fn notify_finish_turn(&mut self, pass: &mut notify::NotifyPass, turn: notify::NotifyTurn, input: ¬ify::NotifyInput<'_>) { + let _step = plx_base::step::StepScope::enter(); assert_eq!(input.armed, self.landgate.is_armed()); self.notify.finish_turn(pass, turn, input) } - pub fn notify_end(&mut self, pass: notify::NotifyPass) -> notify::NotifyOut { self.notify.end(pass) } + pub fn notify_end(&mut self, pass: notify::NotifyPass) -> notify::NotifyOut { + let _step = plx_base::step::StepScope::enter(); self.notify.end(pass) } /// Hold (`true`) or release the view-state reconcile network work; see [`Stores::network_held`]. /// Patches are not held: what the stores already show keeps changing while the player is up. @@ -546,7 +588,7 @@ impl Stores { &mut |hubcmd| hubs.run_with_directory(hubcmd, directory, clients), &mut |cmd| person.run(cmd), &mut |cmd| view_edit_collection(collection, cmd), - &mut |cmd| search.run_with_directory(cmd, directory), + &mut |cmd| search.run_local(cmd), &mut |cmd| metadata.run(cmd), ) } @@ -567,6 +609,7 @@ impl Stores { /// the end-of-stream fan-outs it queues are made under ([`Stores::viewstate_run`]). pub fn reconcile_pump(&mut self, directory: browse::DirectoryView<'_>, clients: &plx_plex::plex::ClientKeys, profile: u32) -> StoreOutcome { + let _step = plx_base::step::StepScope::enter(); let owed = self.viewstate.borrow_mut().take_reread(); self.reconcile.enqueue(owed); let idle = !self.viewstate.borrow().is_busy() && !self.network_held; @@ -584,7 +627,7 @@ impl Stores { &mut |hubcmd| hubs.run_with_directory(hubcmd, directory, clients), &mut |cmd| person.run(cmd), &mut |cmd| view_edit_collection(collection, cmd), - &mut |cmd| search.run_with_directory(cmd, directory), + &mut |cmd| search.run_local(cmd), &mut |cmd| metadata.run(cmd), ))); // A first watch whose read-back found the stream's end: the other servers' copies are @@ -742,6 +785,14 @@ impl StoreWork { /// lane a store is pumped on, a job carries the request itself and the port its answer goes to. #[derive(Debug, PartialEq)] pub enum StoreJob { + /// A profile-addressed preference edit, merged on the serial storage runner. Not taped. + BrowsePreferences(plx_machine::job::Job, + crate::browse::preferences_job::BrowsePreferencesPort), + WatchlistList(plx_machine::job::Job, watchlist_job::WatchlistStreamPort), + WatchlistRematch(plx_machine::job::Job, watchlist_job::WatchlistStreamPort), + WatchlistDelta(plx_machine::job::Job, watchlist_job::WatchlistStreamPort), + WatchlistResolve(plx_machine::job::Job, watchlist_job::ResolvePort), + WatchlistWrite(plx_machine::job::Job, watchlist_job::WritePort), NotifyStream(plx_machine::job::Job, notify_job::NotifyStreamPort), /// One detail fetch (`MetadataCmd::RequestDetail`), addressed by its request generation. Detail(plx_machine::job::Job, crate::metadata::DetailPort), @@ -863,12 +914,14 @@ impl StoreJob { // `frame_ingest`, the Browse pump's own discovery step) starts it through // `StoreRunner::start` as `Direct`, byte for byte as its unrecorded spawn was. Self::BrowseDiscovery(..) => Admission::Home, - Self::NotifyStream(..) + Self::WatchlistList(..) | Self::WatchlistRematch(..) | Self::WatchlistDelta(..) + | Self::WatchlistResolve(..) | Self::WatchlistWrite(..) | Self::NotifyStream(..) | Self::Catalog(..) | Self::SubtitleSearch(..) | Self::ViewReconcile(..) | Self::Search(..) | Self::SaveRecents(..) + | Self::BrowsePreferences(..) | Self::ViewWrite(..) | Self::MetaSeason(..) | Self::MetaEpisodes(..) => Admission::Direct, @@ -886,11 +939,13 @@ impl StoreJob { Self::Collection(..) => StoreId::Collection, Self::Person(..) => StoreId::Person, Self::NotifyStream(..) => StoreId::Notify, + Self::WatchlistList(..) | Self::WatchlistRematch(..) | Self::WatchlistDelta(..) + | Self::WatchlistResolve(..) | Self::WatchlistWrite(..) => StoreId::Watchlist, Self::Catalog(..) => StoreId::Catalog, Self::SubtitleSearch(..) => StoreId::SubtitleSearch, Self::ViewReconcile(..) => StoreId::ViewReconcile, Self::Hubs(..) => StoreId::Hubs, - Self::BrowseHubs(..) | Self::BrowseDirectory(..) | Self::BrowsePage(..) | Self::BrowseDiscovery(..) => StoreId::Browse, + Self::BrowsePreferences(..) | Self::BrowseHubs(..) | Self::BrowseDirectory(..) | Self::BrowsePage(..) | Self::BrowseDiscovery(..) => StoreId::Browse, Self::Search(..) | Self::SaveRecents(..) => StoreId::Search, Self::ViewWrite(..) => StoreId::ViewState, } @@ -1446,7 +1501,7 @@ mod tests { #[test] fn the_fan_out_fill_lists_name_the_stores_the_calls_can_fill() { assert_eq!(Stores::VIEWSTATE_FILLS, [StoreId::Browse, StoreId::Hubs, StoreId::ViewState]); - assert_eq!(Stores::NOTIFY_FILLS, [StoreId::Browse, StoreId::Hubs]); + assert_eq!(Stores::NOTIFY_FILLS, [StoreId::Browse, StoreId::Hubs, StoreId::Watchlist]); assert_eq!(Stores::RECONCILE_FILLS, [StoreId::ViewState, StoreId::ViewReconcile]); for list in [Stores::VIEWSTATE_FILLS, Stores::NOTIFY_FILLS, Stores::RECONCILE_FILLS] { for (i, id) in list.iter().enumerate() { diff --git a/rust-modules/data/src/stores/notify_map.rs b/rust-modules/data/src/stores/notify_map.rs index 92a519a32a..f1b2dd1b4d 100644 --- a/rust-modules/data/src/stores/notify_map.rs +++ b/rust-modules/data/src/stores/notify_map.rs @@ -362,6 +362,7 @@ impl Stores { directory: browse::DirectoryView<'_>, clients: &plx_plex::plex::ClientKeys, ) -> Spent { + let _step = plx_base::step::StepScope::enter(); self.notify_map.frame += 1; for (sid, _epoch) in &out.resynced { self.notify_map.forget_server(*sid); diff --git a/rust-modules/data/src/stores/notify_map_tests.rs b/rust-modules/data/src/stores/notify_map_tests.rs index d16ca30142..f7b21fbe9e 100644 --- a/rust-modules/data/src/stores/notify_map_tests.rs +++ b/rust-modules/data/src/stores/notify_map_tests.rs @@ -50,7 +50,9 @@ fn map(stores: &mut Stores, out: &NotifyOut, pages: &[ContentArg]) -> super::not fn map_shown(stores: &mut Stores, out: &NotifyOut, pages: &[ContentArg], shown: Shown) -> super::notify_map::Spent { let dir = DirectorySnapshot::default(); - stores.notify_map(out, pages, shown, dir.view(), &crate::pms::registry_keys_for_test()) + let spent = stores.notify_map(out, pages, shown, dir.view(), &crate::pms::registry_keys_for_test()); + stores.watchlist.dispatch_jobs_for_test(); + spent } fn pending(stores: &Stores) -> Vec { diff --git a/rust-modules/data/src/stores/person.rs b/rust-modules/data/src/stores/person.rs index 8bce6dd05a..7315e843b4 100644 --- a/rust-modules/data/src/stores/person.rs +++ b/rust-modules/data/src/stores/person.rs @@ -4,9 +4,9 @@ //! The store starts no worker. Its pump emits each request as a [`StoreJob`](super::StoreJob) that //! its owner takes and owes to a runner (`Stores::person_pump`'s caller, `Bridge::person_pump`), //! and the part of the registry it decides from, which client each server holds, arrives as -//! [`ClientKeys`], filled by the host right before the call. +//! [`plx_plex::plex::ClientKeys`] within PersonInput, filled by the host right before the call. -use plx_plex::plex::{ClientKeys, ServerId}; +use plx_plex::plex::ServerId; use plx_machine::machine::{Cx, Effects, Handled, Host, Machine}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::Arc; @@ -104,6 +104,13 @@ impl PersonStore { } changed } + /// Open uses the exact captured roster/session; independent commands remain usable without it. + pub fn run_with_input(&mut self, cmd: PersonCmd, input: &crate::person::PersonInput<'_>) -> bool { + if !matches!(&cmd, PersonCmd::Open { .. }) { return self.run(cmd); } + let changed = self.state.run_with_input(&self.adapter, cmd, input); + if changed { self.bump(); } + changed + } /// Route-unconditional landing pass for this owner's adapter, and the requests the open page /// wants now. `keys` is the registry's answer as of this call. It does NOT start the requests @@ -111,11 +118,16 @@ impl PersonStore { /// in the same turn (the one production caller is `Bridge::person_pump`; the application's test /// rigs fail a frame that ends with a job still here, /// `Bridge::assert_no_store_jobs_left_for_test`). - pub fn pump(&mut self, gate: &plx_machine::landgate::Gate, keys: &ClientKeys) -> bool { - let changed = self.state.pump_with_gate(&self.adapter, gate, keys); - if changed { - self.bump(); - } +pub fn pump(&mut self, gate: &plx_machine::landgate::Gate, input: &crate::person::PersonInput<'_>) -> bool { + let changed = self.state.pump_with_gate(&self.adapter, gate, input); + if changed { self.bump(); } + changed + } + + /// Same-drain terminal pass after the runner attempted these requests. No admission is emitted. + pub fn land_launch_refusals(&mut self) -> bool { + let changed = self.state.land_launch_refusals(&self.adapter); + if changed { self.bump(); } changed } @@ -195,17 +207,12 @@ impl PersonStore { impl Machine for PersonStore { type Ev = StoreEv; - fn step(&mut self, ev: &Self::Ev, _cx: &Cx<'_, H>, _fx: &mut Effects<'_, H>) -> Handled { +fn step(&mut self, ev: &Self::Ev, _cx: &Cx<'_, H>, _fx: &mut Effects<'_, H>) -> Handled { match ev { - StoreEv::Cmd(command) => { - self.run(command.clone()); - } + StoreEv::Cmd(command) => { self.run(command.clone()); } StoreEv::Pump { .. } => { - // Unreached: nothing sends `StoreEv::Pump`. A future sender must pass the host's - // keys and drain the jobs the pump emits: these empty keys read as "no server - // holds a client" (the per-server reads are held off), and the plex.tv reads it - // does emit would be stranded on the outbox. - self.pump(&plx_machine::landgate::Gate::default(), &ClientKeys::default()); + plx_base::eventlog::log("person: pump requires captured inputs — refused"); + debug_assert!(false, "Person pump requires captured inputs"); } } Handled::Yes diff --git a/rust-modules/data/src/stores/search.rs b/rust-modules/data/src/stores/search.rs index 02af462fd7..9bca332c43 100644 --- a/rust-modules/data/src/stores/search.rs +++ b/rust-modules/data/src/stores/search.rs @@ -87,12 +87,13 @@ impl SearchStore { /// `household`: the signed-in profile's household member ids, read by the application's /// `Bridge` and handed in (`SearchState::snapshot_with_directory`). - pub fn snapshot_with_directory( + pub fn snapshot_with_directory_and_input( &self, directory: crate::stores::browse::DirectoryView<'_>, household: &[i64], + input: &crate::search::SearchInput<'_>, ) -> SearchSnapshot { - self.state.snapshot_with_directory(directory, household) + self.state.snapshot_with_directory_and_input(directory, input, household) } /// The ITEMS the result shelves hold, in shelf order. A tag or collection hit has no rating @@ -140,16 +141,17 @@ impl SearchStore { /// Synchronous command path with the Browse owner publication captured by the application. /// Query admission snapshots its favourite-library ranking from this directory. - pub fn run_with_directory( + pub fn run_with_directory_and_input( &mut self, cmd: SearchCmd, directory: crate::stores::browse::DirectoryView<'_>, + input: &crate::search::SearchInput<'_>, ) -> bool { if matches!(&cmd, SearchCmd::Reset) { self.adapter = Arc::new(Default::default()); } let view_edit = matches!(&cmd, SearchCmd::ApplyView { .. }); - let answer = self.state.run_with_directory(&self.adapter, cmd, directory); + let answer = self.state.run_with_directory_and_input(&self.adapter, cmd, directory, input); if answer || !view_edit { self.bump(); } @@ -161,20 +163,44 @@ impl SearchStore { /// [`SearchStore::take_jobs`] and hands them to a runner in the same turn (the one production /// caller is `Bridge::search_pump`; the application's test rigs fail a frame that ends with a /// job still here, `Bridge::assert_no_store_jobs_left_for_test`). - pub fn pump_with_directory_and_gate( + pub fn pump_with_directory_and_input_and_gate( &mut self, dt: f32, directory: crate::stores::browse::DirectoryView<'_>, gate: &plx_machine::landgate::Gate, - keys: &plx_plex::plex::ClientKeys, + input: &crate::search::SearchInput<'_>, ) -> bool { - let changed = self.state.pump_with_directory_and_gate(&self.adapter, dt, directory, gate, keys); + let changed = self.state.pump_with_directory_and_input_and_gate(&self.adapter, dt, directory, gate, input); if changed { self.bump(); } changed } + pub(crate) fn run_local(&mut self, cmd: SearchCmd) -> bool { + if matches!(&cmd, SearchCmd::Reset) { self.adapter = Arc::new(Default::default()); } + let view_edit = matches!(&cmd, SearchCmd::ApplyView { .. }); + let changed = self.state.run_local(&self.adapter, cmd); + if changed || !view_edit { self.bump(); } + changed + } + + #[cfg(any(test, feature = "test-support"))] + pub fn snapshot_with_directory(&self, directory: crate::stores::browse::DirectoryView<'_>, household: &[i64]) -> SearchSnapshot { + self.snapshot_with_directory_and_input(directory, household, &crate::search::fixture_input().input()) + } + #[cfg(any(test, feature = "test-support"))] + pub fn run_with_directory(&mut self, cmd: SearchCmd, directory: crate::stores::browse::DirectoryView<'_>) -> bool { + self.run_with_directory_and_input(cmd, directory, &crate::search::fixture_input().input()) + } + #[cfg(any(test, feature = "test-support"))] + pub fn pump_with_directory_and_gate(&mut self, dt: f32, directory: crate::stores::browse::DirectoryView<'_>, + gate: &plx_machine::landgate::Gate, keys: &plx_plex::plex::ClientKeys) -> bool { + let captured = crate::search::fixture_input(); + let input = crate::search::SearchInput { keys, ..captured.input() }; + self.pump_with_directory_and_input_and_gate(dt, directory, gate, &input) + } + /// Take the jobs the last step has emitted since the last take, in order. The caller OWES each /// one to a runner: a job dropped here is a fetch whose claim is never released. #[must_use] diff --git a/rust-modules/data/src/stores/viewreconcile_parents_tests.rs b/rust-modules/data/src/stores/viewreconcile_parents_tests.rs index 080143f38e..11a3215e30 100644 --- a/rust-modules/data/src/stores/viewreconcile_parents_tests.rs +++ b/rust-modules/data/src/stores/viewreconcile_parents_tests.rs @@ -135,7 +135,7 @@ fn settled(stores: &Stores) -> bool { fn search_row(stores: &Stores, sid: ServerId, rk: &str) -> bool { let directory = DirectorySnapshot::default(); - let snap = stores.search_snapshot(directory.view(), &[]); + let snap = stores.search_snapshot_for_test(directory.view(), &[]); snap.view().shelves().iter().flat_map(|s| &s.items).find_map(|it| match it { Item::Media(m) if m.sid == sid && m.rk == rk => Some(m.watched), _ => None, diff --git a/rust-modules/data/src/stores/viewreconcile_tests.rs b/rust-modules/data/src/stores/viewreconcile_tests.rs index e5c2735af5..71e64a01e8 100644 --- a/rust-modules/data/src/stores/viewreconcile_tests.rs +++ b/rust-modules/data/src/stores/viewreconcile_tests.rs @@ -421,7 +421,7 @@ fn after_an_end_of_stream_the_other_servers_search_tile_reads_watched() { }]); let search_tile = |stores: &Stores| { let directory = DirectorySnapshot::default(); - let snap = stores.search_snapshot(directory.view(), &[]); + let snap = stores.search_snapshot_for_test(directory.view(), &[]); snap.view().shelves().iter().flat_map(|s| &s.items).find_map(|it| match it { Item::Media(m) if m.sid == sid_b => Some((m.watched, m.unwatched, m.resume_ms)), _ => None, diff --git a/rust-modules/data/src/stores/watchlist.rs b/rust-modules/data/src/stores/watchlist.rs index 12c23bbd33..ebbbd4dadd 100644 --- a/rust-modules/data/src/stores/watchlist.rs +++ b/rust-modules/data/src/stores/watchlist.rs @@ -1,12 +1,9 @@ //! The physically owned Watchlist model and its worker adapter (plan §1.2, §1.4, §1.5, §1.11). //! -//! Main-thread state plus an `Arc` mailbox, like the other owned stores. Three kinds of worker, -//! each `spawn_small`: the LIST worker (pages, released set, matching after each page), the -//! REMATCH worker (a full re-match after the roster moved) and the WRITE worker (one write at a -//! time, in press order). Every landing is tagged `{profile generation, store epoch, request id}` -//! and a landing for another profile or a rotated epoch is dropped. A profile switch rotates the -//! epoch: the rows, the match table and the intent ledger are cleared and the old workers land -//! into a retired mailbox. +//! The store emits addressed List, Rematch and Delta streams plus Resolve and serial Write +//! jobs. The app runner executes them through boot-selected ports; the step only consumes +//! captured facts and addressed landings. Streams post in order, then owe one acknowledged +//! terminal. A profile switch rotates the epoch, cancels queued jobs and retires old mailboxes. //! //! Membership is the default-order list from the service, with the intent ledger on top: a press //! flips the row at once, a write that fails reverts it (no toast), and an intent beats any list @@ -23,8 +20,8 @@ use crate::watchlist::ledger::{Intent, IntentLedger, PendingWrite, WriteOutcome} use crate::watchlist::model::{tile_state, Asked, Kind, MatchTable, ServerMatch, TileState, WatchRow}; use crate::watchlist::order::{sorted_filtered, FilterSpec, SortSpec}; use crate::watchlist::{ - run_delta, run_list, run_rematch, run_write, Failure, Landed, LiveIo, Tag, What, WatchlistAuth, WatchlistInput, - WatchlistIo, + Failure, Landed, Tag, What, WatchlistAuth, WatchlistInput, + }; use plx_machine::machine::{Cx, Effects, Handled, Host, Machine}; use plx_plex::plex::session::CurrentProfile; @@ -35,6 +32,8 @@ use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; use super::StoreEv; +#[cfg(any(test, feature = "test-support"))] +use crate::watchlist::WatchlistIo; /// Frames a refused spawn waits before the next try. A refused spawn never blocks a frame. const RETRY_FRAMES: u32 = 120; @@ -78,21 +77,57 @@ pub struct TileFacts { pub dur_ms: i64, } + +/// A single host-captured roster and date, shared by every decision in one pass. +use crate::watchlist::model::Reach; +use super::watchlist_job::{Snapshot, WatchlistStreamPort, ListReq, RematchReq, DeltaReq, AuthValue}; +use super::watchlist_job::stream::{StreamMailbox, StreamLanding, StreamEvent, StreamEnd}; +use plx_machine::machine::{Addr, MachineId, RequestId}; +#[derive(Clone, Copy, PartialEq)] +enum ListRead { HoldingRows, AwaitingPage, Publishing } +#[derive(Clone, Copy, PartialEq)] +enum StreamKind { List(ListRead), Rematch, Delta } +impl StreamKind { + fn is_list(self) -> bool { matches!(self, Self::List(_)) } +} +pub struct WatchlistFacts<'a> { + pub keys: &'a plx_plex::plex::ClientKeys, + pub today: Option<&'a str>, +} + +impl crate::watchlist::model::Reach for WatchlistFacts<'_> { + fn reachable(&self, server: ServerId) -> bool { + matches!(self.keys.facts(server).and_then(|f| f.source), + Some((Some(plx_plex::plex::probe::Outcome::Reachable), _))) + } + + fn roster(&self) -> Vec { + self.keys.slots().collect() + } + + fn copy_rank(&self, server: ServerId) -> u8 { + if server != ServerId::UNSET && self.keys.current() == server { + 0 + } else if self.keys.facts(server).and_then(|f| f.described).is_some_and(|f| f.owned) { + 1 + } else { + 2 + } + } +} + /// A worker's mailbox. Landings queue in post order; the pump drains them all. #[derive(Default)] pub struct WatchlistAdapter { mail: Mutex>, - list_busy: AtomicBool, - write_busy: AtomicBool, + /// Card rows asked to be resolved by `(server, rk)` (`WatchlistStore::want_hex`), spawned by the /// next pump. Behind a lock because a menu asks from `&self`. wanted: Mutex>, - /// Resolved ids, landed by the resolve workers. The outer `None` is "the server did not - /// answer": that attempt is forgotten, not memoized, so the next menu asks again. - resolved: Mutex>)>>, } impl WatchlistAdapter { + #[cfg(any(test, feature = "test-support"))] fn post(&self, landed: Landed) { self.mail.lock().unwrap_or_else(|e| e.into_inner()).push_back(landed); plx_machine::idle::invalidate(); @@ -103,25 +138,19 @@ impl WatchlistAdapter { } } -/// Clears a busy flag when the worker ends, however it ends (a panic included). -struct Release(Arc, fn(&WatchlistAdapter) -> &AtomicBool); - -impl Drop for Release { - fn drop(&mut self) { - (self.1)(&self.0).store(false, Ordering::SeqCst); - } -} - +#[cfg(any(test, feature = "test-support"))] type Spawn = fn(&str, Box) -> bool; -fn spawn_worker(what: &str, f: Box) -> bool { - plx_base::task::spawn_small(what, f) -} + /// Main-thread state. struct WatchlistState { epoch: u32, req: u32, + list_claim: Option, + write_claim: Option, + write_port: Option, + auth: Option, status: Status, rows: Vec, @@ -135,7 +164,7 @@ struct WatchlistState { table: MatchTable, states: Vec, facts: HashMap<(ServerId, i64), TileFacts>, - facts_seen: u32, + ledger: IntentLedger, /// The ledger stamp of the read whose rows are `rows`. rows_stamp: u64, @@ -148,7 +177,7 @@ struct WatchlistState { /// answered "no portable id" (or no answer), not asked again this epoch. resolved: HashMap<(ServerId, String), Option<[u8; 12]>>, /// Asked and not yet answered. - resolving: HashSet<(ServerId, String)>, + resolving: HashMap<(ServerId, String), (Tag, super::watchlist_job::ResolvePort)>, index: Vec, window: Range, list_wanted: bool, @@ -176,6 +205,10 @@ impl WatchlistState { Self { epoch, req: 0, + list_claim: None, + write_claim: None, + write_port: None, + auth: None, status: Status::Idle, rows: Vec::new(), @@ -186,7 +219,7 @@ impl WatchlistState { table: MatchTable::default(), states: Vec::new(), facts: HashMap::new(), - facts_seen: 0, + ledger: IntentLedger::new(), rows_stamp: 0, read_stamp: 0, @@ -194,7 +227,7 @@ impl WatchlistState { filter, members: HashSet::new(), resolved: HashMap::new(), - resolving: HashSet::new(), + resolving: HashMap::new(), index: Vec::new(), window: 0..0, list_wanted: false, @@ -212,16 +245,42 @@ impl WatchlistState { pub struct WatchlistStore { state: WatchlistState, + resolve_profile: Option, + resolve_mailbox: Arc, + write_mailbox: Arc, + stream_mailbox: Arc>, + stream: Option<(StreamKind, WatchlistStreamPort)>, + stream_keys: plx_plex::plex::ClientKeys, + retired_streams: Vec<(WatchlistStreamPort, Arc>)>, + pending_delta: Option<(ServerId, Arc>)>, + rematch_wanted: bool, + snapshot: Snapshot, + jobs: Vec, adapter: Arc, - io: Arc, + #[cfg(any(test, feature = "test-support"))] + io: Option>, + #[cfg(any(test, feature = "test-support"))] spawn: Spawn, notice_gen: AtomicU32, notice_dirty: AtomicBool, } impl Default for WatchlistStore { - fn default() -> Self { - Self::with_io(Arc::new(LiveIo)) +fn default() -> Self { + Self { + state: WatchlistState::new(0, default_sort(), FilterSpec::default()), + resolve_profile: None, + resolve_mailbox: Arc::new(Default::default()), + write_mailbox: Arc::new(Default::default()), + stream_mailbox: Arc::new(Default::default()), stream: None, pending_delta: None, rematch_wanted: false, + stream_keys: Default::default(), retired_streams: Vec::new(), + snapshot: Snapshot::default(), jobs: Vec::new(), adapter: Arc::new(Default::default()), + #[cfg(any(test, feature = "test-support"))] + io: None, + #[cfg(any(test, feature = "test-support"))] + spawn: |_, _| false, + notice_gen: AtomicU32::new(0), notice_dirty: AtomicBool::new(false), + } } } @@ -235,16 +294,10 @@ fn on_your_servers(state: TileState) -> bool { } impl WatchlistStore { - /// A store over a given I/O seam (tests script it; production is [`LiveIo`]). + /// Fixture transport; the pure store still emits the production job values. +#[cfg(any(test, feature = "test-support"))] pub fn with_io(io: Arc) -> Self { - Self { - state: WatchlistState::new(0, default_sort(), FilterSpec::default()), - adapter: Arc::new(WatchlistAdapter::default()), - io, - spawn: spawn_worker, - notice_gen: AtomicU32::new(0), - notice_dirty: AtomicBool::new(false), - } + Self { snapshot: Snapshot::scripted(&*io), io: Some(io), ..Self::default() } } fn bump(&self) { @@ -305,7 +358,7 @@ impl WatchlistStore { .get(&row.guid)? .iter() .filter_map(|(sid, asked)| match asked { - Asked::Held(m, facts) if self.io.reachable(*sid) => Some((self.io.copy_rank(*sid), (m, facts))), + Asked::Held(m, facts) if self.snapshot.reachable(*sid) => Some((self.snapshot.copy_rank(*sid), (m, facts))), _ => None, }) .min_by_key(|(rank, _)| *rank) @@ -445,10 +498,27 @@ impl WatchlistStore { /// A new epoch with nothing in it. The old workers land into a retired mailbox; their writes /// that were still queued are dropped with the old ledger (never sent to another profile). fn reset(&mut self) { + for (_, port) in self.state.resolving.values() { port.cancel_queued(); } + if let Some(port) = &self.state.write_port { port.cancel_queued(); } + if let Some((_, port)) = &self.stream { + port.cancel(); + self.retired_streams.push((port.clone(), Arc::clone(&self.stream_mailbox))); + } + for terminal in self.stream_mailbox.take() { terminal.ack_terminal(); } + self.stream = None; + self.pending_delta = None; + self.rematch_wanted = false; + self.stream_mailbox = Arc::new(Default::default()); + self.jobs.clear(); + self.write_mailbox = Arc::new(Default::default()); + self.resolve_mailbox = Arc::new(Default::default()); + self.resolve_profile = None; let epoch = self.state.epoch.wrapping_add(1); + let req = self.state.req; let (sort, filter) = (self.state.sort, self.state.filter); self.adapter = Arc::new(WatchlistAdapter::default()); self.state = WatchlistState::new(epoch, sort, filter); + self.state.req = req; } /// Recompute what is derived from rows, ledger and view: membership, then the sorted, @@ -474,11 +544,11 @@ impl WatchlistStore { /// Derive every row's tile state again (commit, `facts_gen`, a reachability flip). fn rederive(&mut self) { let s = &mut self.state; - let io = &*self.io; + let io = &self.snapshot; // Released read failed and the row's date cannot say (none, or no clock): its release is // unknown, so a row every server answered absent stays Unknown (plan §1.3), not washed. let release_blind = s.released.is_none(); - let today = io.today(); + let today = io.today.as_deref(); s.states = s .rows .iter() @@ -489,13 +559,13 @@ impl WatchlistStore { state => state, }) .collect(); - s.facts_seen = io.facts_gen(); + self.refresh(); } /// Settle a row's `released` against the released set; when that read failed, against today. fn settle_released(&self, rows: &mut [WatchRow]) { - let today = self.io.today(); + let today = self.snapshot.today.clone(); for r in rows { r.released = match (&self.state.released, &today, &r.release) { (Some(set), ..) => set.contains(&r.guid), @@ -530,6 +600,18 @@ impl WatchlistStore { if landed.tag.profile_gen != auth.generation || landed.tag.epoch != self.state.epoch { return false; } + let claim = match &landed.what { + What::Written { .. } => self.state.write_claim, + _ => self.state.list_claim, + }; + if claim != Some(landed.tag.req) { + return false; + } + match &landed.what { + What::ListDone => {}, + What::Written { .. } => self.state.write_claim = None, + _ => {} + } match landed.what { What::Page { start, total, mut rows, answers, roster_gen, etag } => { self.state.total = total; @@ -545,9 +627,9 @@ impl WatchlistStore { self.settle_released(&mut rows); self.merge(answers, roster_gen); if start == 0 { - self.state.truncated = false; if self.state.rows.is_empty() { // First load: the page shows as soon as it lands. + self.state.truncated = false; self.state.rows = rows; self.state.rows_stamp = self.state.read_stamp; self.state.status = Status::Ready; @@ -578,10 +660,10 @@ impl WatchlistStore { let had_rows = self.state.incoming.take().is_some(); if start == 0 && self.state.rows.is_empty() { self.state.status = Status::Failed(why); - } else { - // A reread's later page failing keeps the old complete rows: only a list - // that is itself being built from pages is cut short. - self.state.truncated = start > 0 && !had_rows; + } else if start > 0 && !had_rows { + // Only a first load changes the rows on a later-page failure. A failed + // reread retains the completeness of the rows already on screen. + self.state.truncated = true; } true } @@ -604,6 +686,7 @@ impl WatchlistStore { self.state.read_etag = None; if let Some(mut rows) = self.state.incoming.take() { self.settle_released(&mut rows); + self.state.truncated = false; self.state.rows = rows; self.state.rows_stamp = self.state.read_stamp; self.state.status = Status::Ready; @@ -645,90 +728,221 @@ impl WatchlistStore { /// `facts_gen`, then start whatever work is owed. MAIN THREAD, once a frame. /// `profile` is the one the Bridge read for this frame (`Bridge::seated_profile`): a pass never /// captures an identity (a reset leaves none, and the next `Open` captures), so it needs no more. - pub fn pump_with_gate(&mut self, gate: &plx_machine::landgate::Gate, profile: &CurrentProfile) -> bool { + pub fn pump_with_gate(&mut self, gate: &plx_machine::landgate::Gate, profile: &CurrentProfile, keys: &plx_plex::plex::ClientKeys) -> bool { + self.pump_with_gate_and_keys(gate, profile, keys) + } + +pub fn pump_with_gate_and_keys(&mut self, gate: &plx_machine::landgate::Gate, profile: &CurrentProfile, keys: &plx_plex::plex::ClientKeys) -> bool { + self.pump_with_snapshot(gate, profile, Snapshot::new(keys, self.snapshot.today.clone())) + } + + pub fn observe_snapshot(&mut self, input: Snapshot) { + let changed = self.snapshot != input; + self.snapshot = input; + if changed && self.state.auth.is_some() { self.rederive(); self.bump(); } + } + pub fn pump_with_snapshot(&mut self, gate: &plx_machine::landgate::Gate, profile: &CurrentProfile, input: Snapshot) -> bool { let mut changed = false; - if self.state.auth.as_ref().is_some_and(|a| !a.is_current(profile)) { - self.reset(); - changed = true; - } + if self.resolve_profile.is_some_and(|g| g != profile.generation) + || self.state.auth.as_ref().is_some_and(|a| !a.is_current(profile)) { + self.reset(); changed = true; + } + self.resolve_profile = Some(profile.generation); + self.retired_streams.retain(|(port, mail)| { + // A terminal phase guarantees its post is in the queue; sample it before draining. + let running = port.is_running(); + for terminal in mail.take() { terminal.ack_terminal(); } + running + }); + let facts_changed = self.snapshot != input; + self.snapshot = input; self.state.list_retry = self.state.list_retry.saturating_sub(1); self.state.write_retry = self.state.write_retry.saturating_sub(1); - let adapter = Arc::clone(&self.adapter); - // In the frame dump's landing gate this waits until no list or write worker is out, so a - // landing is a function of the frame that spawned the work. The flags are read BEFORE the - // drain: a worker posts, then clears its flag, so a flag read clear means its mail is in. - let was_idle = std::cell::Cell::new(true); - let landings = super::take_landings_owed(gate, super::StoreId::Watchlist, |_| !was_idle.get(), || { - was_idle.set(!adapter.list_busy.load(Ordering::SeqCst) && !adapter.write_busy.load(Ordering::SeqCst)); - adapter.take_all() - }); - for landed in landings { - plx_machine::idle::invalidate(); - changed |= self.apply(landed); - } - if self.state.auth.is_some() && self.io.facts_gen() != self.state.facts_seen { - self.rederive(); - changed = true; - } - changed |= self.pump_resolves(gate); + changed |= self.pump_streams(gate); + for landed in self.adapter.take_all() { changed |= self.apply(landed); } + if self.state.auth.is_some() && facts_changed { self.rederive(); changed = true; } + changed |= self.pump_writes(gate, profile.generation); + let snapshot = self.snapshot.clone(); + changed |= self.pump_resolves(gate, profile.generation, &snapshot.keys); self.maybe_spawn(); - if changed { - self.bump(); - } + if changed { self.bump(); } changed } - fn maybe_spawn(&mut self) { - let Some(auth) = self.state.auth.clone() else { return }; - // The write worker: one write at a time, in press order. - if !self.adapter.write_busy.load(Ordering::SeqCst) && self.state.write_retry == 0 { - if let Some(write) = self.state.ledger.next_write() { - self.spawn_write(&auth, write); + fn pump_streams(&mut self, gate: &plx_machine::landgate::Gate) -> bool { + let port = self.stream.as_ref().map(|(_, p)| p.clone()); + let mailbox = Arc::clone(&self.stream_mailbox); + let batch = super::take_landings_owed(gate, super::StoreId::Watchlist, + |_: &[StreamLanding]| port.as_ref().is_some_and(|p| p.is_running()), || mailbox.take()); + let mut changed = false; + for landed in batch { + landed.ack_terminal(); + let expected = Addr { to: MachineId::Store(super::StoreId::Watchlist.ord()), req: RequestId(landed.tag.req) }; + if landed.addr != expected || self.state.list_claim != Some(landed.tag.req) + || landed.tag.epoch != self.state.epoch + || !self.state.auth.as_ref().is_some_and(|a| a.generation == landed.tag.profile_gen) { continue; } + match landed.event { + StreamEvent::Post(mut what) => { + if matches!(&what, What::Page { .. }) { + if let Some((StreamKind::List(progress), _)) = &mut self.stream { + if *progress == ListRead::AwaitingPage { *progress = ListRead::Publishing; } + } + } + let keys = &self.stream_keys; + let now = &self.snapshot.keys; + let retain = |answers: &mut Vec| answers.retain(|(_, sid, _)| keys.key(*sid) == now.key(*sid)); + match &mut what { + What::Page { answers, .. } | What::Delta { answers } => retain(answers), + What::Rematch { answers, .. } => { + if keys != now { continue; } + retain(answers); + } + _ => {} + } + changed |= self.apply(Landed { tag: landed.tag, what }); + } + StreamEvent::End(end) => { + let kind = self.stream.as_ref().map(|(k, _)| *k); + match end { + StreamEnd::NotStarted => { + self.state.list_retry = RETRY_FRAMES; + if kind.is_some_and(StreamKind::is_list) { self.state.list_wanted = true; } + } + StreamEnd::Done if kind.is_some_and(StreamKind::is_list) => changed |= self.apply(Landed { tag: landed.tag, what: What::ListDone }), + StreamEnd::Panicked | StreamEnd::Cancelled => { + self.state.list_retry = RETRY_FRAMES; + if let Some(StreamKind::List(progress)) = kind { + let start = u32::from(progress == ListRead::Publishing); + changed |= self.apply(Landed { tag: landed.tag, what: What::PageFailed { start, why: Failure::Other } }); + changed |= self.apply(Landed { tag: landed.tag, what: What::ListDone }); + } + } + _ => {} + } + let stale_keys = self.stream_keys != self.snapshot.keys; + if kind == Some(StreamKind::Delta) && end == StreamEnd::Done && !stale_keys { self.pending_delta = None; } + if stale_keys || end != StreamEnd::Done { + self.state.list_retry = RETRY_FRAMES; + if kind == Some(StreamKind::Rematch) || (stale_keys && kind.is_some_and(StreamKind::is_list)) { self.rematch_wanted = true; } + } + self.state.list_claim = None; + self.stream = None; + } } } - if self.adapter.list_busy.load(Ordering::SeqCst) || self.state.list_retry > 0 { - return; - } - if self.state.list_wanted { - self.spawn_list(&auth); - } else if !self.state.rows.is_empty() - && self.io.roster_gen() != self.state.table.roster_gen - { - self.spawn_rematch(&auth); + changed + } + + /// Settle launch refusals in the emitting drain without advancing retry clocks or emitting work. + pub fn land_stream_results(&mut self, gate: &plx_machine::landgate::Gate, profile: &CurrentProfile) -> bool { + if self.state.auth.as_ref().is_some_and(|a| !a.is_current(profile)) { self.reset(); self.bump(); return true; } + // Admission refusals settle before ordinary landing gates, in the emitting drain. + for landed in self.stream_mailbox.take_not_started() { + landed.ack_terminal(); + let expected = Addr { to: MachineId::Store(super::StoreId::Watchlist.ord()), req: RequestId(landed.tag.req) }; + if landed.addr != expected || self.state.list_claim != Some(landed.tag.req) + || landed.tag.epoch != self.state.epoch + || !self.state.auth.as_ref().is_some_and(|a| a.generation == landed.tag.profile_gen) { continue; } + match self.stream.as_ref().map(|(kind, _)| *kind) { + Some(StreamKind::List(_)) => self.state.list_wanted = true, + Some(StreamKind::Rematch) => self.rematch_wanted = true, + _ => {} + } + self.state.list_retry = RETRY_FRAMES; + self.state.list_claim = None; + self.stream = None; } + if !self.stream_mailbox.has_mail() { return false; } + let changed = self.pump_streams(gate); + if changed { self.bump(); } + changed + } + +fn maybe_spawn(&mut self) { + if self.state.auth.is_none() { return; } + let write = if self.state.write_claim.is_none() && self.state.write_retry == 0 { + self.state.ledger.next_write() + } else { None }; + let stream_owed = self.state.list_claim.is_none() && self.state.list_retry == 0 + && (self.state.list_wanted || self.pending_delta.is_some() + || (!self.state.rows.is_empty() && (self.rematch_wanted || self.snapshot.roster_gen != self.state.table.roster_gen))); + if write.is_none() && !stream_owed { return; } + let auth = self.state.auth.clone().expect("a pending Watchlist job has captured auth"); + if let Some(write) = write { self.spawn_write(&auth, write); } + if !stream_owed { return; } + if self.state.list_wanted { self.spawn_list(&auth); } + else if let Some((sid, asks)) = self.pending_delta.clone() { self.emit_delta(&auth, sid, asks); } + else if !self.state.rows.is_empty() && (self.rematch_wanted || self.snapshot.roster_gen != self.state.table.roster_gen) { self.spawn_rematch(&auth); } } fn spawn_write(&mut self, auth: &WatchlistAuth, write: PendingWrite) { - self.state.req += 1; - // Whatever this write does, the service's list is no longer the one the validator names - // (even a failed request may have reached it): the next read must be whole. + use plx_machine::machine::{Addr, MachineId, RequestId}; + use super::watchlist_job::{WritePort, WriteReq}; + self.state.req = self.state.req.checked_add(1).expect("watchlist request ids exhausted"); + self.state.write_claim = Some(self.state.req); self.state.writes_seen = self.state.writes_seen.wrapping_add(1); self.state.list_etag = None; let tag = self.current_tag(auth); - let (adapter, io, auth) = (Arc::clone(&self.adapter), Arc::clone(&self.io), auth.clone()); - adapter.write_busy.store(true, Ordering::SeqCst); - let guard = Release(Arc::clone(&adapter), |a| &a.write_busy); - let spawned = (self.spawn)("wlist-write", Box::new(move || { - let _guard = guard; - let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - run_write(&*io, &auth, tag, write, &mut |l| adapter.post(l)); - })); - if outcome.is_err() { - adapter.post(Landed { tag, what: What::Written { write, outcome: WriteOutcome::Failed } }); + let addr = Addr { to: MachineId::Store(super::StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let req = WriteReq { tag, auth: auth.clone(), write }; + let port = WritePort::new(addr, &req, Arc::clone(&self.write_mailbox)); + self.state.write_port = Some(port.clone()); + self.jobs.push(super::StoreJob::WatchlistWrite(plx_machine::job::Job { addr, req }, port)); + } + + fn pump_writes(&mut self, gate: &plx_machine::landgate::Gate, profile_gen: u32) -> bool { + use plx_machine::machine::{Addr, MachineId, RequestId}; + use super::watchlist_job::WriteEnd; + let claim = self.state.write_claim; + let expected = claim.map(|req| Addr { to: MachineId::Store(super::StoreId::Watchlist.ord()), req: RequestId(req) }); + let epoch = self.state.epoch; + let answers = super::take_landings_owed(gate, super::StoreId::Watchlist, |got: &[super::watchlist_job::WriteLanding]| { + expected.is_some() && !got.iter().any(|landing| Some(landing.addr) == expected + && landing.tag.req == landing.addr.req.0 && landing.tag.epoch == epoch + && landing.tag.profile_gen == profile_gen) + }, || self.write_mailbox.take()); + let mut changed = false; + for landing in answers { + if Some(landing.addr) != expected || self.state.write_claim != Some(landing.tag.req) + || landing.addr.req.0 != landing.tag.req || landing.tag.epoch != self.state.epoch + || landing.tag.profile_gen != profile_gen { continue; } + self.state.write_port = None; + match landing.end { + WriteEnd::NotStarted { write } => { + self.state.write_claim = None; + self.state.ledger.requeue(write); + self.state.write_retry = RETRY_FRAMES; + } + WriteEnd::Written { write, outcome } => { + changed |= self.apply(Landed { tag: landing.tag, what: What::Written { write, outcome } }); + } } - })); - if !spawned { - // Nothing will run: hand the write back and try again in a while. - self.adapter.write_busy.store(false, Ordering::SeqCst); + } + changed + } + + /// Consume an immediate runner refusal without advancing the frame retry timer. + pub fn land_write_results(&mut self, gate: &plx_machine::landgate::Gate, profile: &CurrentProfile) -> bool { + for landed in self.write_mailbox.take_not_started() { + let expected = Addr { to: MachineId::Store(super::StoreId::Watchlist.ord()), req: RequestId(landed.tag.req) }; + if landed.addr != expected || self.state.write_claim != Some(landed.tag.req) + || landed.tag.epoch != self.state.epoch || landed.tag.profile_gen != profile.generation { continue; } + let super::watchlist_job::WriteEnd::NotStarted { write } = landed.end else { unreachable!() }; + self.state.write_claim = None; + self.state.write_port = None; self.state.ledger.requeue(write); self.state.write_retry = RETRY_FRAMES; } + if !self.write_mailbox.has_mail() { return false; } + let changed = self.pump_writes(gate, profile.generation); + if changed { self.bump(); } + changed } /// The guids the table already holds an answer for from every reachable server, so a reread /// matches only the new ones (the worker ignores this when the roster has moved since). fn matched_guids(&self) -> HashSet { - let asked: Vec = self.io.roster().into_iter().filter(|s| self.io.reachable(*s)).collect(); + let asked: Vec = self.snapshot.roster().into_iter().filter(|s| self.snapshot.reachable(*s)).collect(); self.state .table .by_guid @@ -738,59 +952,47 @@ impl WatchlistStore { .collect() } - fn spawn_list(&mut self, auth: &WatchlistAuth) { - self.state.req += 1; +fn spawn_list(&mut self, auth: &WatchlistAuth) { + self.state.req = self.state.req.checked_add(1).expect("watchlist request ids exhausted"); + self.state.list_claim = Some(self.state.req); let tag = self.current_tag(auth); self.state.read_stamp = self.state.ledger.stamp(); - let known = self.matched_guids(); - let known_gen = self.state.table.roster_gen; - // The validator only stands for a complete list with no write in the air. let quiet = !self.state.ledger.busy(); let etag = self.state.list_etag.clone().filter(|_| quiet && !self.state.rows.is_empty() && !self.state.truncated); self.state.read_etag = None; self.state.read_writes = quiet.then_some(self.state.writes_seen); - let (adapter, io, auth) = (Arc::clone(&self.adapter), Arc::clone(&self.io), auth.clone()); - adapter.list_busy.store(true, Ordering::SeqCst); - let guard = Release(Arc::clone(&adapter), |a| &a.list_busy); - let spawned = (self.spawn)("wlist", Box::new(move || { - let _guard = guard; - let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - run_list(&*io, &auth, tag, (&known, known_gen), etag.as_deref(), &mut |l| adapter.post(l)); - })); - if outcome.is_err() { - adapter.post(Landed { tag, what: What::PageFailed { start: 0, why: Failure::Other } }); - adapter.post(Landed { tag, what: What::ListDone }); - } - })); - if spawned { - self.state.list_wanted = false; - } else { - self.adapter.list_busy.store(false, Ordering::SeqCst); - self.state.list_retry = RETRY_FRAMES; - } + let req = ListReq { tag, input: self.snapshot.clone(), auth: AuthValue(auth.clone()), + known: self.matched_guids(), known_gen: self.state.table.roster_gen, etag }; + let progress = if self.state.rows.is_empty() { ListRead::AwaitingPage } else { ListRead::HoldingRows }; + let (addr, port) = self.stream_port(tag, StreamKind::List(progress)); + self.state.list_wanted = false; + self.jobs.push(super::StoreJob::WatchlistList(plx_machine::job::Job { addr, req }, port)); } - fn spawn_rematch(&mut self, auth: &WatchlistAuth) { - self.state.req += 1; +fn spawn_rematch(&mut self, auth: &WatchlistAuth) { + self.state.req = self.state.req.checked_add(1).expect("watchlist request ids exhausted"); + self.state.list_claim = Some(self.state.req); let tag = self.current_tag(auth); - let keys: Vec<(String, Kind)> = self.state.rows.iter().map(|r| (r.guid.clone(), r.kind)).collect(); - let (adapter, io) = (Arc::clone(&self.adapter), Arc::clone(&self.io)); - adapter.list_busy.store(true, Ordering::SeqCst); - let guard = Release(Arc::clone(&adapter), |a| &a.list_busy); - let spawned = (self.spawn)("wlist", Box::new(move || { - let _guard = guard; - let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - run_rematch(&*io, &keys, tag, &mut |l| adapter.post(l)); - })); - if outcome.is_err() { - // Keep the table as it is: no landing, the roster check asks again. - plx_base::eventlog::log("watchlist: rematch worker panicked"); - } - })); - if !spawned { - self.adapter.list_busy.store(false, Ordering::SeqCst); - self.state.list_retry = RETRY_FRAMES; - } + self.rematch_wanted = false; + let req = RematchReq { tag, input: self.snapshot.clone(), rows: self.state.rows.iter().map(|r| (r.guid.clone(), r.kind)).collect() }; + let (addr, port) = self.stream_port(tag, StreamKind::Rematch); + self.jobs.push(super::StoreJob::WatchlistRematch(plx_machine::job::Job { addr, req }, port)); + } + + fn stream_port(&mut self, tag: Tag, kind: StreamKind) -> (Addr, WatchlistStreamPort) { + let addr = Addr { to: MachineId::Store(super::StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let port = WatchlistStreamPort::new(addr, tag, Arc::clone(&self.stream_mailbox)); + self.stream_keys = self.snapshot.keys.clone(); + self.stream = Some((kind, port.clone())); + (addr, port) + } + fn emit_delta(&mut self, auth: &WatchlistAuth, sid: ServerId, rows: Arc>) { + self.state.req = self.state.req.checked_add(1).expect("watchlist request ids exhausted"); + self.state.list_claim = Some(self.state.req); + let tag = self.current_tag(auth); + let req = DeltaReq { tag, input: self.snapshot.clone(), sid, rows }; + let (addr, port) = self.stream_port(tag, StreamKind::Delta); + self.jobs.push(super::StoreJob::WatchlistDelta(plx_machine::job::Job { addr, req }, port)); } /// Has the list been read and shown? A library change is followed only once there are rows to @@ -802,9 +1004,7 @@ impl WatchlistStore { /// Is a list read out on a worker right now? Its matching may have asked a server before a /// library change that has just arrived, so a change must be kept for it; a read not yet /// started will ask after the change and needs no note of it. - pub fn read_in_flight(&self) -> bool { - self.adapter.list_busy.load(Ordering::SeqCst) - } +pub fn read_in_flight(&self) -> bool { self.state.list_claim.is_some() } /// The rows `sid` holds, by that server's ratingKey: what a library item deleted there is /// looked up in (built once for a whole frame's worth of deletes). @@ -841,39 +1041,15 @@ impl WatchlistStore { /// tiles re-derive at that commit. `false` = not started (no list yet, a read or re-match /// already out, or the worker was refused): the caller keeps the ask and tries a later frame. /// Nothing to ask, or a server that is not reachable, is `true`: there is nothing to start. - pub fn rematch_on(&mut self, sid: ServerId, asks: Vec<(String, Kind)>) -> bool { - if !self.is_ready() { - return false; - } - if asks.is_empty() || !self.io.reachable(sid) { - return true; - } +pub fn rematch_on(&mut self, sid: ServerId, asks: Vec<(String, Kind)>) -> bool { + if !self.is_ready() { return false; } + if asks.is_empty() || !self.snapshot.reachable(sid) { return true; } + if self.state.list_wanted || self.state.list_claim.is_some() || self.state.list_retry > 0 || self.pending_delta.is_some() { return false; } let Some(auth) = self.state.auth.clone() else { return false }; - if self.state.list_wanted - || self.adapter.list_busy.load(Ordering::SeqCst) - || self.state.list_retry > 0 - { - return false; - } - self.state.req += 1; - let tag = self.current_tag(&auth); - let (adapter, io) = (Arc::clone(&self.adapter), Arc::clone(&self.io)); - adapter.list_busy.store(true, Ordering::SeqCst); - let guard = Release(Arc::clone(&adapter), |a| &a.list_busy); - let spawned = (self.spawn)("wlist", Box::new(move || { - let _guard = guard; - let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - run_delta(&*io, sid, &asks, tag, &mut |l| adapter.post(l)); - })); - if outcome.is_err() { - plx_base::eventlog::log("watchlist: library re-match worker panicked"); - } - })); - if !spawned { - self.adapter.list_busy.store(false, Ordering::SeqCst); - self.state.list_retry = RETRY_FRAMES; - } - spawned + let asks = Arc::new(asks); + self.pending_delta = Some((sid, Arc::clone(&asks))); + self.emit_delta(&auth, sid, asks); + true } /// A card row carried no catalog id: ask for it to be read off the item's own server record @@ -881,7 +1057,7 @@ impl WatchlistStore { /// The answer is [`WatchlistView::resolved_hex`]; a menu opened after it lands offers the row. pub fn want_hex(&self, sid: ServerId, rk: &str) { let key = (sid, rk.to_owned()); - if self.state.resolved.contains_key(&key) || self.state.resolving.contains(&key) { + if self.state.resolved.contains_key(&key) || self.state.resolving.contains_key(&key) { return; } let mut wanted = self.adapter.wanted.lock().unwrap_or_else(|e| e.into_inner()); @@ -892,46 +1068,73 @@ impl WatchlistStore { /// Spawn a worker per asked-for record and land the answers. Needs no account: the read is /// the user's own server's. - fn pump_resolves(&mut self, gate: &plx_machine::landgate::Gate) -> bool { + + pub fn land_resolve_refusals(&mut self, profile: &CurrentProfile) { + for landed in self.resolve_mailbox.take_not_started() { + let expected = Addr { to: MachineId::Store(super::StoreId::Watchlist.ord()), req: RequestId(landed.tag.req) }; + let key = (landed.sid, landed.rk); + if landed.addr == expected && landed.tag.epoch == self.state.epoch && landed.tag.profile_gen == profile.generation + && self.state.resolving.get(&key).is_some_and(|(tag, _)| *tag == landed.tag) { + self.state.resolving.remove(&key); + } + } + } + fn pump_resolves(&mut self, gate: &plx_machine::landgate::Gate, profile_gen: u32, + keys: &plx_plex::plex::ClientKeys) -> bool { + use plx_machine::machine::{Addr, MachineId, RequestId}; + use super::watchlist_job::{ResolveEnd, ResolvePort, ResolveReq}; + let claims = &self.state.resolving; + let answers = super::take_landings_owed(gate, super::StoreId::Watchlist, |got: &[super::watchlist_job::ResolveLanding]| { + got.iter().filter(|landing| claims.get(&(landing.sid, landing.rk.clone())) + .is_some_and(|(tag, _)| *tag == landing.tag && landing.addr.req.0 == tag.req)).count() < claims.len() + }, || self.resolve_mailbox.take()); let mut changed = false; - // Every claim in `resolving` owes one answer (a refused spawn removes its claim at once), - // which the frame dump's landing gate waits for. - let (adapter, claimed) = (&self.adapter, self.state.resolving.len()); - let answers = super::take_landings_owed(gate, super::StoreId::Watchlist, |got| got.len() < claimed, || { - adapter.resolved.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect() - }); - for (sid, rk, hex) in answers { - self.state.resolving.remove(&(sid, rk.clone())); - if let Some(hex) = hex { - self.state.resolved.insert((sid, rk), hex); + for landing in answers { + let key = (landing.sid, landing.rk); + if !self.state.resolving.get(&key).is_some_and(|(tag, _)| *tag == landing.tag + && landing.addr.req.0 == tag.req && tag.epoch == self.state.epoch + && tag.profile_gen == profile_gen) { continue; } + self.state.resolving.remove(&key); + if let ResolveEnd::Answer(Some(hex)) = landing.end { + if landing.key != keys.key(key.0) { continue; } + self.state.resolved.insert(key, hex); changed = true; } } let wanted: Vec<_> = self.adapter.wanted.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect(); for (sid, rk) in wanted { - if self.state.resolved.contains_key(&(sid, rk.clone())) || !self.state.resolving.insert((sid, rk.clone())) { - continue; - } - let (adapter, io) = (Arc::clone(&self.adapter), Arc::clone(&self.io)); - let key = rk.clone(); - let spawned = (self.spawn)("wlist-resolve", Box::new(move || { - let hex = io.guid_of(sid, &key).map(|g| plx_plex::plex::resolve_catalog_hex(None, || Some(g))); - adapter.resolved.lock().unwrap_or_else(|e| e.into_inner()).push((sid, key, hex)); - plx_machine::idle::invalidate(); - })); - if !spawned { - // Nothing will run: forget it so the next menu asks again. - self.state.resolving.remove(&(sid, rk)); - } + let key = (sid, rk.clone()); + if self.state.resolved.contains_key(&key) || self.state.resolving.contains_key(&key) { continue; } + self.state.req = self.state.req.checked_add(1).expect("watchlist request ids exhausted"); + let tag = Tag { profile_gen, epoch: self.state.epoch, req: self.state.req }; + let addr = Addr { to: MachineId::Store(super::StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let req = ResolveReq { tag, keys: keys.clone(), sid, rk }; + let port = ResolvePort::new(addr, &req, Arc::clone(&self.resolve_mailbox)); + self.state.resolving.insert(key, (tag, port.clone())); + self.jobs.push(super::StoreJob::WatchlistResolve(plx_machine::job::Job { addr, req }, port)); } changed } + #[must_use] + pub fn take_jobs(&mut self) -> Vec { std::mem::take(&mut self.jobs) } + + pub fn has_jobs(&self) -> bool { !self.jobs.is_empty() } + /// [`Self::pump_with_gate`] for a test about something else: the fixture gate, and the seat /// [`WatchlistInput::for_test`] hands out at generation 1 (the one a store's tests open under). - #[cfg(any(test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] pub fn pump(&mut self) -> bool { - self.pump_with_gate(plx_machine::landgate::fixture_gate(), &WatchlistInput::profile_for_test(1)) + let gate = plx_machine::landgate::fixture_gate(); + let profile = WatchlistInput::profile_for_test(1); + let input = self.io.as_ref().map_or_else(|| self.snapshot.clone(), |io| Snapshot::scripted(&**io)); + let changed = self.pump_with_snapshot(gate, &profile, input); + let (streams, deferred): (Vec<_>, Vec<_>) = std::mem::take(&mut self.jobs).into_iter().partition(|j| + matches!(j, super::StoreJob::WatchlistList(..) | super::StoreJob::WatchlistRematch(..) | super::StoreJob::WatchlistDelta(..))); + self.jobs = streams; + self.dispatch_jobs_for_test(); + self.jobs.extend(deferred); + self.land_stream_results(gate, &profile) || changed } /// [`Self::run_with_input`] for a test about something else: the same generation-1 seat. @@ -947,6 +1150,48 @@ impl WatchlistStore { self } + #[cfg(any(test, feature = "test-support"))] + pub fn pump_scripted_with_gate(&mut self, gate: &plx_machine::landgate::Gate, profile: &CurrentProfile) -> bool { + let input = self.io.as_ref().map_or_else(|| self.snapshot.clone(), |io| Snapshot::scripted(&**io)); + let changed = self.pump_with_snapshot(gate, profile, input); + self.drive_jobs_for_test(gate, profile) || changed + } +#[cfg(any(test, feature = "test-support"))] + fn drive_jobs_for_test(&mut self, gate: &plx_machine::landgate::Gate, profile: &CurrentProfile) -> bool { + self.dispatch_jobs_for_test(); + let stream = self.land_stream_results(gate, profile); + self.land_write_results(gate, profile) || stream + } + #[cfg(any(test, feature = "test-support"))] + pub(crate) fn dispatch_jobs_for_test(&mut self) { + use plx_machine::job::Port; + use super::watchlist_job::{finish_list_job, finish_rematch_job, finish_delta_job, finish_write_job}; + let Some(io) = self.io.clone() else { return }; + for job in std::mem::take(&mut self.jobs) { + match job { + super::StoreJob::WatchlistList(job, port) => { + let (addr, refusal, io) = (job.addr, port.clone(), io.clone()); + if !(self.spawn)("wlist", Box::new(move || finish_list_job(&port, addr, job.req, &*io))) { refusal.refused(addr); } + } + super::StoreJob::WatchlistRematch(job, port) => { + let (addr, refusal, io) = (job.addr, port.clone(), io.clone()); + if !(self.spawn)("wlist", Box::new(move || finish_rematch_job(&port, addr, job.req, &*io))) { refusal.refused(addr); } + } + super::StoreJob::WatchlistDelta(job, port) => { + let (addr, refusal, io) = (job.addr, port.clone(), io.clone()); + if !(self.spawn)("wlist", Box::new(move || finish_delta_job(&port, addr, job.req, &*io))) { refusal.refused(addr); } + } + super::StoreJob::WatchlistWrite(job, port) => { + let (addr, refusal, io) = (job.addr, port.clone(), io.clone()); + if !(self.spawn)("wlist-write", Box::new(move || { + if port.start() { finish_write_job(&port, addr, job.req, &*io); } + })) { refusal.refused(addr); } + } + other => self.jobs.push(other), + } + } + } + #[cfg(any(test, feature = "test-support"))] pub fn adapter_for_test(&self) -> Arc { Arc::clone(&self.adapter) @@ -1040,9 +1285,9 @@ impl WatchlistView<'_> { /// The server whose photo proxy fetches Discover art for titles no server holds (plan §0, §3): /// the reachable one `copy_rank` prefers, ties in roster order. `None` when no server is /// reachable; those titles then draw the skeleton (Q9). - pub fn art_server(&self) -> Option { - let io = &*self.store.io; - io.roster().into_iter().filter(|s| io.reachable(*s)).min_by_key(|s| io.copy_rank(*s)) +pub fn art_server(&self) -> Option { + let input = &self.store.snapshot; + input.roster().into_iter().filter(|s| input.reachable(*s)).min_by_key(|s| input.copy_rank(*s)) } /// The service's list length, once it said, for the skeleton cells past the loaded tail. @@ -1136,6 +1381,7 @@ pub(super) mod tests { held: Mutex>, writes: Mutex>, fail_writes: AtomicBool, + panic_writes: AtomicBool, roster_gen: AtomicU32, facts_gen: AtomicU32, finds: AtomicUsize, @@ -1156,8 +1402,7 @@ pub(super) mod tests { /// Entries per page the decoder "dropped": counted in `raw`, absent from `items`; also /// withholds `totalSize` while non-zero. dropped: AtomicU32, - /// Scripted `guid_of` answers, front first; empty = no answer. - guid_answers: Mutex>>, + /// Does the service send an `ETag`? When it does, the validator names the list's content, /// so any change to `items` is a new one. etag_on: AtomicBool, @@ -1184,6 +1429,7 @@ pub(super) mod tests { held: Mutex::new(HashMap::new()), writes: Mutex::new(Vec::new()), fail_writes: AtomicBool::new(false), + panic_writes: AtomicBool::new(false), roster_gen: AtomicU32::new(1), facts_gen: AtomicU32::new(1), finds: AtomicUsize::new(0), @@ -1195,7 +1441,7 @@ pub(super) mod tests { listings: Mutex::new(HashMap::new()), starts: Mutex::new(Vec::new()), dropped: AtomicU32::new(0), - guid_answers: Mutex::new(Vec::new()), + etag_on: AtomicBool::new(true), asked: Mutex::new(Vec::new()), }) @@ -1244,6 +1490,7 @@ pub(super) mod tests { self.released.lock().unwrap().clone().ok_or(WatchlistError::Transport) } fn write(&self, _: &WatchlistAuth, hex: &str, intent: Intent) -> Result<(), WatchlistError> { + assert!(!self.panic_writes.load(Ordering::SeqCst), "scripted write panic"); self.writes.lock().unwrap().push((hex.to_owned(), intent)); if self.fail_writes.load(Ordering::SeqCst) { Err(WatchlistError::Transport) } else { Ok(()) } } @@ -1269,10 +1516,7 @@ pub(super) mod tests { fn today(&self) -> Option { Some("2026-10-15".into()) } - fn guid_of(&self, _: ServerId, _: &str) -> Option { - let mut q = self.guid_answers.lock().unwrap(); - if q.is_empty() { None } else { q.remove(0) } - } + } fn inline(_: &str, f: Box) -> bool { @@ -1294,8 +1538,15 @@ pub(super) mod tests { } /// One frame pass handed the profile the app read. - fn pump_handed(s: &mut WatchlistStore, profile: &plx_plex::plex::session::CurrentProfile) -> bool { - s.pump_with_gate(plx_machine::landgate::fixture_gate(), profile) + + + fn pump_scripted(s: &mut WatchlistStore) -> bool { + let profile = crate::watchlist::WatchlistInput::profile_for_test(1); + pump_handed(s, &profile) + } + +fn pump_handed(s: &mut WatchlistStore, profile: &CurrentProfile) -> bool { + s.pump_scripted_with_gate(plx_machine::landgate::fixture_gate(), profile) } /// Open, then pump until nothing is left to land. @@ -1318,12 +1569,12 @@ pub(super) mod tests { } /// A store whose first list read is out on a worker and has not landed (the claim is held). - pub(in crate::stores) fn reading_for_test(sid: ServerId, titles: u8) -> WatchlistStore { +pub(in crate::stores) fn reading_for_test(sid: ServerId, titles: u8) -> WatchlistStore { let mock = Mock::new((1..=titles).map(|n| item(n, "T")).collect()); *mock.roster.lock().unwrap() = vec![sid]; *mock.up.lock().unwrap() = vec![sid]; - let s = store(&mock); - s.adapter.list_busy.store(true, Ordering::SeqCst); + let mut s = store(&mock); + s.state.list_claim = Some(1); s } @@ -1412,17 +1663,123 @@ pub(super) mod tests { let mut s = store(&mock); load(&mut s); assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"]); - // Ready and nothing owed: no real list can land after this and supersede the ghost, so - // an applied stale landing would show. + // Keep a genuine list claim pending; its own request id does not authorize a different profile. + s.run(WatchlistCmd::Reread); + s.maybe_spawn(); let auth = s.state.auth.clone().unwrap(); - let stale = Tag { profile_gen: auth.generation + 1, epoch: s.state.epoch, req: 99 }; - s.adapter_for_test().post_for_test(Landed { tag: stale, what: ghost_page() }); - s.pump(); + let stale = Tag { profile_gen: auth.generation + 1, epoch: s.state.epoch, req: s.state.list_claim.unwrap() }; + assert!(!s.apply(Landed { tag: stale, what: ghost_page() }), "profile is checked against the live claim"); + pump_scripted(&mut s); assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"], "a stale generation never lands"); - let fresh = Tag { profile_gen: auth.generation, epoch: s.state.epoch, req: 99 }; - s.adapter_for_test().post_for_test(Landed { tag: fresh, what: ghost_page() }); - s.pump(); - assert!(titles(&s).contains(&"Ghost".to_string()), "the same landing with the live tag does"); + // A matching profile alone is insufficient: the request must also own a live claim. + } + + #[test] + fn an_unclaimed_request_in_the_current_epoch_cannot_land() { + let mock = three(); + let mut s = store(&mock); + load(&mut s); + let auth = s.state.auth.clone().unwrap(); + let unclaimed = Tag { profile_gen: auth.generation, epoch: s.state.epoch, req: 99 }; + s.adapter_for_test().post_for_test(Landed { tag: unclaimed, what: ghost_page() }); + pump_scripted(&mut s); + assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"], "an unclaimed request must not mutate rows"); + } + + + #[test] + fn captured_key_only_roster_never_invents_reachability_or_preference() { + let sid = ServerId::from_raw(7); + let key = plx_plex::plex::ClientKey { instance: 1, token: 2, grant: 3 }; + let keys = plx_plex::plex::ClientKeys::from_keys([(sid, key)]); + let facts = WatchlistFacts { keys: &keys, today: None }; + assert_eq!(facts.roster(), [sid]); + assert!(!facts.reachable(sid)); + assert_eq!(facts.copy_rank(sid), 2); + assert_eq!(facts.copy_rank(ServerId::UNSET), 2); + } + + + #[test] + fn captured_roster_keeps_order_reachability_and_copy_preference() { + use plx_plex::plex::{self, ClientKeys, ServerFacts}; + use plx_plex::plex::probe::Outcome; + struct ResetRegistry; + impl Drop for ResetRegistry { + fn drop(&mut self) { plex::reset_servers_for_test(); } + } + let _lock = plx_base::testlock::serial(); + plex::reset_servers_for_test(); + let _reset = ResetRegistry; + let current = plex::register_for_test("watchlist-current", "127.0.0.1", 9, "test-token", "test-client"); + let owned = plex::register_for_test("watchlist-owned", "127.0.0.1", 9, "test-token", "test-client"); + let shared = ServerId::from_raw(22); + let a = plex::client_for(current).expect("registered current client"); + let b = plex::client_for(owned).expect("registered owned client"); + let description: &'static ServerFacts = Box::leak(Box::new(ServerFacts { + name: String::new(), handle: String::new(), owned: true, home: false, owner_id: 0, + })); + let mut keys = ClientKeys::default(); + keys.refill_roster(current, 4, 5, [shared, owned, current], + |sid| if sid == current { Some(a) } else if sid == owned { Some(b) } else { None }, + |sid| (sid == owned).then_some(description), + |sid| (sid == current).then_some(Outcome::Reachable)); + let facts = WatchlistFacts { keys: &keys, today: Some("2026-10-15") }; + assert_eq!(facts.roster(), [shared, owned, current]); + assert!(facts.reachable(current)); + assert!(!facts.reachable(owned)); + assert!(!facts.reachable(shared)); + assert_eq!((facts.copy_rank(current), facts.copy_rank(owned), facts.copy_rank(shared)), (0, 1, 2)); + assert_eq!((keys.roster_gen(), keys.facts_gen()), (4, 5)); + } + + + #[test] + fn a_retired_request_cannot_land_into_a_new_list_claim() { + let mock = three(); + let mut s = store(&mock); + load(&mut s); + s.run(WatchlistCmd::Reread); + s.maybe_spawn(); + let old = Tag { profile_gen: s.state.auth.as_ref().unwrap().generation, epoch: s.state.epoch, req: s.state.list_claim.unwrap() }; + pump_scripted(&mut s); + s.run(WatchlistCmd::Reread); + s.maybe_spawn(); + assert_ne!(s.state.list_claim, Some(old.req)); + assert!(!s.apply(Landed { tag: old, what: ghost_page() }), "the retired claim cannot mutate its successor"); + pump_scripted(&mut s); + assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"]); + } + + + #[test] + fn paced_gate_cannot_release_a_claim_before_it_drains() { + thread_local! { static HELD: std::cell::RefCell>> = Default::default(); } + fn hold(_: &str, f: Box) -> bool { + HELD.with(|h| h.borrow_mut().push(f)); + true + } + let mock = three(); + let mut s = store(&mock); + load(&mut s); + s.spawn = hold; + s.run(WatchlistCmd::Reread); + s.maybe_spawn(); + let claim = s.state.list_claim; + let gate = plx_machine::landgate::Gate::default(); + gate.arm_dump_paced(1); + gate.dump_frame(0); + let profile = crate::watchlist::WatchlistInput::profile_for_test(1); + s.pump_scripted_with_gate(&gate, &profile); + assert_eq!(s.state.list_claim, claim, "a held gate has not consumed the answer"); + let jobs: Vec<_> = HELD.with(|h| h.borrow_mut().drain(..).collect()); + assert_eq!(jobs.len(), 1); + for job in jobs { job(); } + s.spawn = inline; + gate.dump_frame(1); + s.pump_scripted_with_gate(&gate, &profile); + assert!(s.state.list_claim.is_none()); + assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"]); } #[test] @@ -1474,7 +1831,7 @@ pub(super) mod tests { let mut s = store(&mock); open_handed(&mut s, &crate::watchlist::WatchlistInput::signed_out_for_test(1)); assert_eq!(s.view().status(), Status::NoAccount); - s.pump(); + pump_scripted(&mut s); assert_eq!(mock.pages.load(Ordering::SeqCst), 0, "no identity, no read"); } @@ -1495,7 +1852,7 @@ pub(super) mod tests { let pages = mock.pages.load(Ordering::SeqCst); open_handed(&mut s, &crate::watchlist::WatchlistInput::new(Arc::new(signed_out), None, "test-client")); assert_eq!(s.view().status(), Status::NoAccount); - s.pump(); + pump_scripted(&mut s); assert_eq!(mock.pages.load(Ordering::SeqCst), pages, "no account, no read"); } @@ -1509,15 +1866,13 @@ pub(super) mod tests { pump_handed(&mut s, &crate::watchlist::WatchlistInput::profile_for_test(2)); load_as(&mut s, 2); assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"]); - let epoch = s.state.epoch; - let old = Tag { profile_gen: 1, epoch, req: 99 }; - s.adapter_for_test().post_for_test(Landed { tag: old, what: ghost_page() }); - pump_handed(&mut s, &crate::watchlist::WatchlistInput::profile_for_test(2)); - assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"], "the old generation never lands"); - let live = Tag { profile_gen: 2, epoch, req: 99 }; - s.adapter_for_test().post_for_test(Landed { tag: live, what: ghost_page() }); + mock.items.lock().unwrap().push(item(9, "Ghost")); + s.run(WatchlistCmd::Reread); + s.maybe_spawn(); + let old = Tag { profile_gen: 1, epoch: s.state.epoch, req: s.state.list_claim.unwrap() }; + assert!(!s.apply(Landed { tag: old, what: ghost_page() }), "the old generation cannot use the new claim"); pump_handed(&mut s, &crate::watchlist::WatchlistInput::profile_for_test(2)); - assert!(titles(&s).contains(&"Ghost".to_string()), "the new generation's does"); + assert!(titles(&s).contains(&"Ghost".to_string()), "the new generation’s actual claimed read lands"); } /// The same seat is not a switch: a pass handed the profile the store opened under changes nothing, @@ -1557,7 +1912,7 @@ pub(super) mod tests { old_mailbox.post_for_test(Landed { tag: old_tag, what: ghost_page() }); // And one that somehow reaches the new mailbox still carries the old epoch. s.adapter_for_test().post_for_test(Landed { tag: old_tag, what: ghost_page() }); - s.pump(); + pump_scripted(&mut s); assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"], "only the new epoch's own list"); } @@ -1571,9 +1926,8 @@ pub(super) mod tests { s.maybe_spawn(); s.run(WatchlistCmd::Press { hex: hex_of(2), intent: Intent::Remove }); s.run(WatchlistCmd::Press { hex: hex_of(7), intent: Intent::Add }); - let gate = plx_machine::landgate::fixture_gate(); for _ in 0..3 { - s.pump_with_gate(gate, &crate::watchlist::WatchlistInput::profile_for_test(1)); + pump_handed(&mut s, &crate::watchlist::WatchlistInput::profile_for_test(1)); } assert_eq!(titles(&s), ["Alpha", "Charlie"], "the read, issued before the press, does not bring Bravo back"); assert!(s.view().is_member(&hex_of(7)), "nor does it forget an add the list has not heard of"); @@ -1588,7 +1942,7 @@ pub(super) mod tests { s.run(WatchlistCmd::Press { hex: hex_of(2), intent: Intent::Remove }); assert_eq!(titles(&s), ["Alpha", "Charlie"], "flipped at once"); for _ in 0..3 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"], "reverted"); assert!(s.view().is_member(&hex_of(2))); @@ -1602,7 +1956,7 @@ pub(super) mod tests { load(&mut s); s.run(WatchlistCmd::Press { hex: hex_of(2), intent: Intent::Remove }); for _ in 0..3 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(*mock.writes.lock().unwrap(), [(id(2), Intent::Remove)]); assert_eq!(titles(&s), ["Alpha", "Charlie"]); @@ -1619,7 +1973,7 @@ pub(super) mod tests { s.run(WatchlistCmd::Press { hex: hex_of(2), intent: Intent::Add }); s.run(WatchlistCmd::Press { hex: hex_of(2), intent: Intent::Remove }); for _ in 0..4 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(*mock.writes.lock().unwrap(), [(id(2), Intent::Remove)], "one write, the newest"); } @@ -1632,50 +1986,101 @@ pub(super) mod tests { s.run(WatchlistCmd::Press { hex: hex_of(3), intent: Intent::Remove }); s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); for _ in 0..6 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(*mock.writes.lock().unwrap(), [(id(3), Intent::Remove), (id(1), Intent::Remove)]); } #[test] fn a_silent_server_is_not_memoized_as_no_portable_id() { + use plx_machine::job::Port; + use super::super::watchlist_job::ResolveEnd; let mock = three(); let sid = ServerId::from_raw(0); let mut s = store(&mock); - // First read: no answer at all. + let answer = |s: &mut WatchlistStore, end| { + pump_scripted(s); + let mut jobs = s.take_jobs(); + assert_eq!(jobs.len(), 1); + let super::super::StoreJob::WatchlistResolve(job, port) = jobs.pop().unwrap() else { panic!("resolve job") }; + assert!(port.start()); + port.done(job.addr, end); + pump_scripted(s); + }; s.want_hex(sid, "7"); - s.pump(); - s.pump(); - assert_eq!(s.view().resolved_hex(sid, "7"), None, "no answer is not an answer"); - // The next menu asks again and now gets a portable guid. - mock.guid_answers.lock().unwrap().push(Some("plex://movie/abababababababababababab".into())); + answer(&mut s, ResolveEnd::Answer(None)); + assert_eq!(s.view().resolved_hex(sid, "7"), None); s.want_hex(sid, "7"); - s.pump(); - s.pump(); + answer(&mut s, ResolveEnd::Answer(Some(Some([0xab; 12])))); assert_eq!(s.view().resolved_hex(sid, "7"), Some(Some([0xab; 12]))); - // A server that answers with a non-portable guid IS memoized. - mock.guid_answers.lock().unwrap().push(Some("local://1".into())); s.want_hex(sid, "8"); - s.pump(); - s.pump(); + answer(&mut s, ResolveEnd::Answer(Some(None))); assert_eq!(s.view().resolved_hex(sid, "8"), Some(None)); } + #[test] + fn resolve_accountless_reset_and_stale_request_cannot_settle_the_new_claim() { + use plx_machine::job::Port; + use super::super::{StoreJob, watchlist_job::ResolveEnd}; + let mut s = store(&three()); + let sid = ServerId::from_raw(0); + s.want_hex(sid, "7"); + pump_scripted(&mut s); + let StoreJob::WatchlistResolve(old, old_port) = s.take_jobs().pop().unwrap() else { panic!("resolve job") }; + assert_eq!(old.req.tag.profile_gen, 1); + s.run(WatchlistCmd::Reset); + assert!(!old_port.start(), "a queued retired claim cannot start"); + s.want_hex(sid, "7"); + pump_scripted(&mut s); + let StoreJob::WatchlistResolve(new, new_port) = s.take_jobs().pop().unwrap() else { panic!("resolve job") }; + assert_ne!(old.addr.req, new.addr.req); + old_port.done(old.addr, ResolveEnd::Answer(Some(Some([1; 12])))); + pump_scripted(&mut s); + assert_eq!(s.view().resolved_hex(sid, "7"), None); + assert!(new_port.start()); + new_port.done(new.addr, ResolveEnd::Answer(Some(Some([2; 12])))); + pump_scripted(&mut s); + assert_eq!(s.view().resolved_hex(sid, "7"), Some(Some([2; 12]))); + } + + #[test] + fn resolve_refusal_panic_and_profile_change_release_their_own_claim() { + use plx_machine::job::Port; + use super::super::{StoreJob, watchlist_job::ResolveEnd}; + let mut s = store(&three()); + let sid = ServerId::from_raw(0); + for end in [ResolveEnd::NotStarted, ResolveEnd::Panicked] { + s.want_hex(sid, "7"); + pump_scripted(&mut s); + let StoreJob::WatchlistResolve(job, port) = s.take_jobs().pop().unwrap() else { panic!("resolve job") }; + port.done(job.addr, end); + pump_scripted(&mut s); + assert_eq!(s.view().resolved_hex(sid, "7"), None); + } + s.want_hex(sid, "7"); + pump_scripted(&mut s); + let StoreJob::WatchlistResolve(_, port) = s.take_jobs().pop().unwrap() else { panic!("resolve job") }; + let profile = WatchlistInput::profile_for_test(2); + s.pump_with_gate(plx_machine::landgate::fixture_gate(), &profile, &plx_plex::plex::ClientKeys::default()); + assert!(!port.start(), "profile change cancels a parked accountless job"); + assert_eq!(s.view().resolved_hex(sid, "7"), None); + } + #[test] fn a_refused_spawn_retries_after_n_frames_and_never_blocks() { let mock = three(); let mut s = store(&mock).with_spawn_for_test(refuse); s.run_for_test(WatchlistCmd::Open); - s.pump(); + pump_scripted(&mut s); assert_eq!(mock.pages.load(Ordering::SeqCst), 0); - assert!(!s.adapter.list_busy.load(Ordering::SeqCst), "the claim is released"); + assert!(s.state.list_claim.is_none(), "the claim is released"); s = s.with_spawn_for_test(inline); for _ in 0..(RETRY_FRAMES - 2) { - s.pump(); + pump_scripted(&mut s); } assert_eq!(mock.pages.load(Ordering::SeqCst), 0, "not before N frames"); for _ in 0..4 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(s.view().status(), Status::Ready, "then it goes"); } @@ -1694,12 +2099,109 @@ pub(super) mod tests { assert_eq!(s.view().status(), Status::Failed(Failure::Other), "unavailable, not an empty list"); assert_eq!(s.view().len(), 0); for _ in 0..(10 * 60) { - s.pump(); + pump_scripted(&mut s); } assert_eq!(mock.pages.load(Ordering::SeqCst), 1, "a refused read is not asked again"); assert_eq!(s.view().status(), Status::Failed(Failure::Other)); } + #[test] + fn write_retired_started_request_cannot_clear_new_profile_claim() { + use plx_machine::job::Port; + use super::super::watchlist_job::WriteEnd; + let mock = three(); + let mut s = store(&mock); + load(&mut s); + s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); + s.maybe_spawn(); + let super::super::StoreJob::WatchlistWrite(old, old_port) = s.take_jobs().pop().unwrap() else { panic!("write job") }; + assert!(old_port.start()); + s.run(WatchlistCmd::Reset); + load_as(&mut s, 2); + s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); + s.maybe_spawn(); + let claim = s.state.write_claim; + assert_ne!(claim, Some(old.req.tag.req)); + old_port.done(old.addr, WriteEnd::Written { write: old.req.write, outcome: WriteOutcome::Landed }); + assert!(!s.pump_writes(plx_machine::landgate::fixture_gate(), 2)); + assert_eq!(s.state.write_claim, claim); + assert!(mock.writes.lock().unwrap().is_empty()); + } + + + #[test] + fn write_full_tag_and_address_fence_rejects_stale_landings() { + use plx_machine::{job::Port, machine::{Addr, MachineId, RequestId}}; + use super::super::watchlist_job::{WriteEnd, WritePort, WriteReq}; + let mock = three(); + let mut s = store(&mock); + load(&mut s); + s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); + s.maybe_spawn(); + let super::super::StoreJob::WatchlistWrite(job, current) = s.take_jobs().pop().unwrap() else { panic!("write") }; + let claim = s.state.write_claim; + let tag = job.req.tag; + let mut stale_epoch = tag; stale_epoch.epoch = stale_epoch.epoch.wrapping_add(1); + let mut stale_profile = tag; stale_profile.profile_gen = stale_profile.profile_gen.wrapping_add(1); + let mut stale_req = tag; stale_req.req = stale_req.req.wrapping_add(1); + for stale in [stale_epoch, stale_profile, stale_req] { + let addr = Addr { to: MachineId::Store(super::super::StoreId::Watchlist.ord()), req: RequestId(stale.req) }; + let req = WriteReq { tag: stale, auth: job.req.auth.clone(), write: job.req.write }; + let port = WritePort::new(addr, &req, Arc::clone(&s.write_mailbox)); + port.done(addr, WriteEnd::Written { write: req.write, outcome: WriteOutcome::Failed }); + assert!(!s.pump_writes(plx_machine::landgate::fixture_gate(), tag.profile_gen)); + assert_eq!(s.state.write_claim, claim); + assert!(!s.view().is_member(&hex_of(1)), "stale failure cannot roll back the intent"); + } + let wrong = Addr { to: job.addr.to, req: RequestId(job.addr.req.0 + 1) }; + current.done(wrong, WriteEnd::Written { write: job.req.write, outcome: WriteOutcome::Failed }); + assert!(current.start(), "wrong address must not retire the current port"); + current.done(job.addr, WriteEnd::Written { write: job.req.write, outcome: WriteOutcome::Landed }); + assert!(s.pump_writes(plx_machine::landgate::fixture_gate(), tag.profile_gen)); + assert_eq!(s.state.write_claim, None); + assert!(!s.view().is_member(&hex_of(1))); + } + + #[test] + fn write_not_started_requeues_exactly_at_head_until_120th_pump() { + let mock = three(); + let mut s = store(&mock); + load(&mut s); + s.spawn = refuse; + s.run(WatchlistCmd::Press { hex: hex_of(3), intent: Intent::Remove }); + s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); + pump_scripted(&mut s); + assert_eq!(s.state.write_retry, RETRY_FRAMES); + let first = s.state.ledger.next_write().expect("refused write remains queued"); + assert_eq!(first.hex, hex_of(3)); + assert_eq!(first.intent, Intent::Remove); + assert_eq!(first.seq, 1); + s.state.ledger.requeue(first); + s.spawn = inline; + for _ in 0..(RETRY_FRAMES - 1) { pump_scripted(&mut s); } + assert!(mock.writes.lock().unwrap().is_empty(), "no write before the boundary"); + pump_scripted(&mut s); + assert_eq!(*mock.writes.lock().unwrap(), [(id(3), Intent::Remove)]); + for _ in 0..3 { pump_scripted(&mut s); } + assert_eq!(*mock.writes.lock().unwrap(), [(id(3), Intent::Remove), (id(1), Intent::Remove)]); + } + + #[test] + fn write_started_panic_is_failed_and_not_retried() { + let mock = three(); + let mut s = store(&mock); + load(&mut s); + mock.panic_writes.store(true, Ordering::SeqCst); + s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); + pump_scripted(&mut s); + assert_eq!(s.state.write_retry, 0); + assert!(!s.state.ledger.busy()); + assert!(s.view().is_member(&hex_of(1))); + mock.panic_writes.store(false, Ordering::SeqCst); + for _ in 0..(RETRY_FRAMES + 1) { pump_scripted(&mut s); } + assert!(mock.writes.lock().unwrap().is_empty(), "started panic was not retried"); + } + #[test] fn a_refused_write_spawn_keeps_the_write_for_later() { let mock = three(); @@ -1707,11 +2209,11 @@ pub(super) mod tests { load(&mut s); s = s.with_spawn_for_test(refuse); s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); - s.pump(); + pump_scripted(&mut s); assert!(s.state.ledger.busy(), "still owed"); s = s.with_spawn_for_test(inline); for _ in 0..(RETRY_FRAMES + 4) { - s.pump(); + pump_scripted(&mut s); } assert_eq!(*mock.writes.lock().unwrap(), [(id(1), Intent::Remove)]); } @@ -1731,7 +2233,7 @@ pub(super) mod tests { mock.roster_gen.fetch_add(1, Ordering::SeqCst); mock.facts_gen.fetch_add(1, Ordering::SeqCst); for _ in 0..4 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(s.state.table.roster_gen, mock.roster_gen.load(Ordering::SeqCst)); assert_eq!(s.view().state(0), Some(TileState::Available)); @@ -1750,7 +2252,7 @@ pub(super) mod tests { assert_eq!((s.view().state(0), s.view().state(1)), (Some(TileState::Available), Some(TileState::Available))); mock.up.lock().unwrap().clear(); mock.facts_gen.fetch_add(1, Ordering::SeqCst); - s.pump(); + pump_scripted(&mut s); assert_eq!( (s.view().state(0), s.view().state(1)), (Some(TileState::ServerOffline), Some(TileState::ServerOffline)), @@ -1759,7 +2261,7 @@ pub(super) mod tests { assert!(s.held_keys().is_empty() || s.state.window.is_empty()); mock.up.lock().unwrap().push(a); mock.facts_gen.fetch_add(1, Ordering::SeqCst); - s.pump(); + pump_scripted(&mut s); assert_eq!(s.view().state(0), Some(TileState::Available)); } @@ -1778,7 +2280,7 @@ pub(super) mod tests { assert_eq!(s.held_keys(), vec![(a, "5".to_string()), (a, "9".to_string())], "clamped to the list"); mock.up.lock().unwrap().clear(); mock.facts_gen.fetch_add(1, Ordering::SeqCst); - s.pump(); + pump_scripted(&mut s); assert!(s.held_keys().is_empty(), "an unreachable server is not read back"); } @@ -1857,7 +2359,7 @@ pub(super) mod tests { assert_eq!(titles(&s), ["Charlie", "Bravo", "Alpha"]); s.run(WatchlistCmd::Filter(FilterSpec { kind: None, show: Show::OnYourServers })); assert_eq!(titles(&s), ["Charlie"]); - s.pump(); + pump_scripted(&mut s); assert_eq!(mock.pages.load(Ordering::SeqCst), pages); } @@ -1871,7 +2373,7 @@ pub(super) mod tests { s.maybe_spawn(); assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"], "nothing blanked while it is out"); for _ in 0..3 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(titles(&s), ["Bravo", "Charlie"]); } @@ -1885,13 +2387,13 @@ pub(super) mod tests { assert!(first > 0); s.run(WatchlistCmd::Reread); for _ in 0..4 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(mock.finds.load(Ordering::SeqCst), first, "an unchanged list asks no server again"); mock.items.lock().unwrap().push(item(4, "Delta")); s.run(WatchlistCmd::Reread); for _ in 0..4 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(mock.finds.load(Ordering::SeqCst), first + 1, "one new movie guid: one chunk, one server"); assert_eq!(titles(&s).len(), 4); @@ -1899,7 +2401,7 @@ pub(super) mod tests { mock.roster_gen.fetch_add(1, Ordering::SeqCst); s.run(WatchlistCmd::Reread); for _ in 0..4 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(mock.finds.load(Ordering::SeqCst), first + 2); assert_eq!(s.state.table.roster_gen, mock.roster_gen.load(Ordering::SeqCst)); @@ -1924,7 +2426,7 @@ pub(super) mod tests { let mut s = store(&mock); s.run_for_test(WatchlistCmd::Open); for _ in 0..40 { - s.pump(); + pump_scripted(&mut s); } let starts = mock.starts.lock().unwrap().clone(); assert_eq!(starts.len(), 21); @@ -1946,11 +2448,11 @@ pub(super) mod tests { let mock = three(); let mut s = store(&mock); load(&mut s); - // A later read that finds no answer keeps the list. - let landed = |what| Landed { tag: Tag { profile_gen: 1, epoch: s.state.epoch, req: 0 }, what }; - let a = s.adapter_for_test(); - a.post_for_test(landed(What::PageFailed { start: 0, why: Failure::Offline })); - s.pump(); + // A real claimed reread fails before page zero and retains the complete list. + let _ = mock.etag_on.swap(false, Ordering::SeqCst); + mock.fail_pages_from.store(u32::MIN, Ordering::SeqCst); + s.run(WatchlistCmd::Reread); + for _ in 0..2 { pump_scripted(&mut s); } assert_eq!(s.view().status(), Status::Ready); assert_eq!(s.view().len(), 3); } @@ -1988,12 +2490,15 @@ pub(super) mod tests { assert_eq!(s.view().copy(1).map(|m| m.rating_key), Some(10)); // The owned server is second in the roster and wins over the first share. mock.ranks.lock().unwrap().insert(b, 1); + pump_scripted(&mut s); assert_eq!(s.view().copy(1).map(|m| m.rating_key), Some(20), "owned beats a share"); // The current server is last in the roster and wins over both. mock.ranks.lock().unwrap().insert(c, 0); + pump_scripted(&mut s); assert_eq!(s.view().copy(1).map(|m| m.rating_key), Some(30), "current beats owned"); // An unreachable preferred copy is never chosen. mock.up.lock().unwrap().retain(|x| *x != c); + pump_scripted(&mut s); assert_eq!(s.view().copy(1).map(|m| m.rating_key), Some(20)); } @@ -2014,8 +2519,10 @@ pub(super) mod tests { let genre = |s: &WatchlistStore| s.view().listing(1).and_then(|l| l.genre.clone()); assert_eq!((s.view().copy(1).map(|m| m.rating_key), genre(&s)), (Some(10), Some("Drama".into()))); mock.ranks.lock().unwrap().insert(b, 1); + pump_scripted(&mut s); assert_eq!((s.view().copy(1).map(|m| m.rating_key), genre(&s)), (Some(20), Some("Comedy".into())), "the owned copy's facts"); mock.up.lock().unwrap().clear(); + pump_scripted(&mut s); assert_eq!((s.view().copy(1), genre(&s)), (None, None), "no reachable copy, no facts"); assert_eq!(s.view().listing(0), None, "a title no server holds has none"); } @@ -2039,7 +2546,7 @@ pub(super) mod tests { mock.fail_pages_from.store(100, Ordering::SeqCst); s.run(WatchlistCmd::Reread); for _ in 0..3 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(s.view().len(), 150, "the old rows stay"); assert!(!s.view().truncated(), "a complete old list is not reported as cut short"); @@ -2055,6 +2562,29 @@ pub(super) mod tests { assert!(s.view().truncated()); } + #[test] + fn failed_rereads_preserve_the_truncated_status_of_held_rows() { + for failed_from in [0, 100] { + let mock = Mock::new((1..=150).map(|n| item(n, &format!("T{n:03}"))).collect()); + mock.fail_pages_from.store(100, Ordering::SeqCst); + let mut s = store(&mock); + load(&mut s); + assert_eq!(s.view().len(), 100); + assert!(s.view().truncated()); + + mock.fail_pages_from.store(failed_from, Ordering::SeqCst); + reread(&mut s); + assert_eq!(s.view().len(), 100, "old partial rows must stay on failure at {failed_from}"); + assert!(s.view().truncated(), "held rows remain partial after failure at {failed_from}"); + assert_eq!(s.state.list_etag, None); + + mock.fail_pages_from.store(u32::MAX, Ordering::SeqCst); + reread(&mut s); + assert_eq!(s.view().len(), 150); + assert!(!s.view().truncated()); + } + } + #[test] fn the_drawn_state_holds_until_the_pump_that_rederives_it() { let mock = three(); @@ -2067,7 +2597,7 @@ pub(super) mod tests { mock.up.lock().unwrap().clear(); mock.facts_gen.fetch_add(1, Ordering::SeqCst); assert_eq!(s.view().state(1), Some(TileState::Available), "the committed state, not the live one"); - s.pump(); + pump_scripted(&mut s); assert_eq!(s.view().state(1), Some(TileState::ServerOffline), "the pump re-derives it"); } @@ -2086,7 +2616,7 @@ pub(super) mod tests { fn reread(s: &mut WatchlistStore) { s.run(WatchlistCmd::Reread); for _ in 0..6 { - s.pump(); + pump_scripted(s); } } @@ -2161,7 +2691,7 @@ pub(super) mod tests { load(&mut s); s.run(WatchlistCmd::Press { hex: hex_of(2), intent: Intent::Remove }); for _ in 0..3 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(s.state.list_etag, None); assert!(s.take_reread_owed()); @@ -2178,7 +2708,7 @@ pub(super) mod tests { load(&mut s); s.run(WatchlistCmd::Press { hex: hex_of(2), intent: Intent::Remove }); for _ in 0..3 { - s.pump(); + pump_scripted(&mut s); } assert_eq!(s.state.list_etag, None, "a request that may have reached the service changed what it holds"); } @@ -2198,9 +2728,9 @@ pub(super) mod tests { mock.items.lock().unwrap().remove(2); s.spawn = hold; s.run(WatchlistCmd::Reread); - s.pump(); + pump_scripted(&mut s); s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); - s.pump(); + pump_scripted(&mut s); s.spawn = inline; let jobs: Vec<_> = HELD.with(|h| h.borrow_mut().drain(..).collect()); assert_eq!(jobs.len(), 2, "the list worker and the write worker"); @@ -2208,8 +2738,9 @@ pub(super) mod tests { job(); } for _ in 0..4 { - s.pump(); + pump_scripted(&mut s); } + assert_eq!(titles(&s), ["Bravo"], "the older list claim lands despite the newer write request"); assert_eq!(s.state.list_etag, None, "page 0 was read around the write; its validator may describe the old list"); } @@ -2274,8 +2805,9 @@ pub(super) mod tests { mock.found.lock().unwrap().clear(); mock.held.lock().unwrap().insert((sid0(), guid(1)), "11".into()); assert!(s.rematch_on(sid0(), s.unmatched_on(sid0(), Kind::Movie))); + s.drive_jobs_for_test(plx_machine::landgate::fixture_gate(), &WatchlistInput::profile_for_test(1)); assert_eq!(mock.found.lock().unwrap().len(), 1, "one chunk for three titles"); - s.pump(); + pump_scripted(&mut s); assert_eq!(movie_state_of(&s, 1), Some(TileState::Available), "the tile flips at the landing"); assert_eq!(movie_state_of(&s, 2), Some(TileState::NotOnAnyServer)); assert_eq!(s.state.table.roster_gen, mock.roster_gen.load(Ordering::SeqCst), "the roster mark is not touched"); @@ -2307,7 +2839,9 @@ pub(super) mod tests { let mut ready = store(&mock); load(&mut ready); let mut ready = ready.with_spawn_for_test(refuse); - assert!(!ready.rematch_on(sid0(), vec![(guid(1), Kind::Movie)]), "a refused worker is not started"); + assert!(ready.rematch_on(sid0(), vec![(guid(1), Kind::Movie)]), "an addressed job is emitted before admission"); + ready.drive_jobs_for_test(plx_machine::landgate::fixture_gate(), &WatchlistInput::profile_for_test(1)); + assert!(ready.pending_delta.is_some(), "refused delta stays owned for retry"); assert!(!ready.rematch_on(sid0(), vec![(guid(1), Kind::Movie)]), "and waits out its retry"); assert!(s.rematch_on(sid0(), Vec::new()), "nothing to ask is nothing to start"); assert!(s.rematch_on(ServerId::from_raw(9), vec![(guid(1), Kind::Movie)]), "an unreachable server is not asked"); @@ -2320,7 +2854,327 @@ pub(super) mod tests { load(&mut s); mock.found.lock().unwrap().clear(); assert!(s.rematch_on(sid0(), s.unmatched_on(sid0(), Kind::Movie))); + s.drive_jobs_for_test(plx_machine::landgate::fixture_gate(), &WatchlistInput::profile_for_test(1)); let sizes: Vec = mock.found.lock().unwrap().iter().map(Vec::len).collect(); assert_eq!(sizes, [40, 40, 10]); } + + #[test] + fn stream_jobs_list_rematch_delta_are_values_until_the_runner_enters() { + use super::super::{StoreJob, watchlist_job::*}; + let mock = three(); + let mut s = store(&mock); + s.run_for_test(WatchlistCmd::Open); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + assert_eq!(mock.pages.load(Ordering::SeqCst), 0, "the step does not do IO"); + let StoreJob::WatchlistList(job, port) = s.take_jobs().pop().unwrap() else { panic!("list job") }; + assert_eq!(job.addr.req.0, job.req.tag.req); + assert_eq!(job.req.tag.profile_gen, 1); + finish_list_job(&port, job.addr, job.req, &*mock); + assert!(port.is_owed()); + s.land_stream_results(gate, &profile); + assert!(!port.is_owed()); + assert_eq!(s.view().len(), 3); + let finds = mock.finds.load(Ordering::SeqCst); + mock.roster_gen.fetch_add(1, Ordering::SeqCst); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistRematch(job, port) = s.take_jobs().pop().unwrap() else { panic!("rematch job") }; + assert_eq!(mock.finds.load(Ordering::SeqCst), finds); + finish_rematch_job(&port, job.addr, job.req, &*mock); + s.land_stream_results(gate, &profile); + assert!(!port.is_owed()); + let finds = mock.finds.load(Ordering::SeqCst); + assert!(s.rematch_on(sid0(), s.rows_of(Kind::Movie))); + let StoreJob::WatchlistDelta(job, port) = s.take_jobs().pop().unwrap() else { panic!("delta job") }; + assert_eq!(mock.finds.load(Ordering::SeqCst), finds); + finish_delta_job(&port, job.addr, job.req, &*mock); + s.land_stream_results(gate, &profile); + assert!(!port.is_owed()); + assert!(!s.read_in_flight()); + } + #[test] + fn stream_jobs_refused_delta_retains_asks_and_retries_at_120_pumps() { + use super::super::StoreJob; + let mock = three(); + let mut s = store(&mock); + load(&mut s); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + assert!(s.rematch_on(sid0(), vec![(guid(1), Kind::Movie)])); + let StoreJob::WatchlistDelta(job, port) = s.take_jobs().pop().unwrap() else { panic!("delta") }; + port.refused(job.addr); + s.land_stream_results(gate, &profile); + assert!(!port.is_owed()); + assert!(s.pending_delta.is_some()); + for _ in 0..119 { s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); assert!(!s.has_jobs()); } + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + assert!(matches!(s.take_jobs().pop(), Some(StoreJob::WatchlistDelta(..)))); + } + + #[test] + fn stream_jobs_delta_rows_keep_original_allocation_through_refused_retries() { + use super::super::StoreJob; + let mock = three(); + let mut s = store(&mock); + load(&mut s); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + let rows = vec![(guid(2), Kind::Movie), (guid(1), Kind::Movie)]; + let original_rows = rows.as_ptr(); + let original_guids: Vec<_> = rows.iter().map(|(guid, _)| guid.as_ptr()).collect(); + let expected = rows.clone(); + assert!(s.rematch_on(sid0(), rows)); + let StoreJob::WatchlistDelta(mut job, mut port) = s.take_jobs().pop().unwrap() else { panic!("delta") }; + assert_eq!(job.req.rows.as_ptr(), original_rows); + assert_eq!(job.req.rows.as_ref(), &expected); + let (sid, retained) = s.pending_delta.as_ref().unwrap(); + assert_eq!(*sid, sid0()); + assert!(Arc::ptr_eq(retained, &job.req.rows)); + let retained = Arc::clone(retained); + let mut equal = job.req.clone(); + equal.rows = Arc::new(expected.clone()); + assert_eq!(job.req, equal, "request equality compares row content, not allocation identity"); + assert!(!Arc::ptr_eq(&job.req.rows, &equal.rows)); + for _ in 0..2 { + let tag = job.req.tag; + let input = job.req.input.clone(); + port.refused(job.addr); + drop(job); + s.land_stream_results(gate, &profile); + assert!(!port.is_owed()); + assert!(Arc::ptr_eq(&s.pending_delta.as_ref().unwrap().1, &retained)); + for _ in 0..119 { + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + assert!(!s.has_jobs()); + } + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistDelta(retry, retry_port) = s.take_jobs().pop().unwrap() else { panic!("delta retry") }; + assert_eq!(retry.req.sid, sid0()); + assert_eq!(retry.req.tag.profile_gen, tag.profile_gen); + assert_eq!(retry.req.tag.epoch, tag.epoch); + assert!(retry.req.tag.req > tag.req); + assert_eq!(retry.req.input, input); + assert!(Arc::ptr_eq(&retry.req.rows, &retained)); + assert_eq!(retry.req.rows.as_ptr(), original_rows); + assert_eq!(retry.req.rows.as_ref(), &expected); + assert_eq!(retry.req.rows.iter().map(|(guid, _)| guid.as_ptr()).collect::>(), original_guids); + job = retry; + port = retry_port; + } + } + #[test] + fn stream_jobs_captured_roster_is_used_even_when_transport_facts_move() { + use super::super::{StoreJob, watchlist_job::finish_list_job}; + let mock = three(); + let mut s = store(&mock); + s.run_for_test(WatchlistCmd::Open); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistList(job, port) = s.take_jobs().pop().unwrap() else { panic!("list") }; + mock.roster.lock().unwrap().clear(); + mock.up.lock().unwrap().clear(); + mock.roster_gen.store(99, Ordering::SeqCst); + finish_list_job(&port, job.addr, job.req, &*mock); + s.land_stream_results(gate, &profile); + assert_eq!(mock.finds.load(Ordering::SeqCst), 1, "captured reachable server is still asked"); + assert_eq!(s.state.table.roster_gen, 1, "transport's current generation is not a step input"); + } + #[test] + fn stream_jobs_reset_cancels_queued_work_and_acks_retired_terminal() { + use super::super::{StoreJob, watchlist_job::finish_list_job}; + let mock = three(); + let mut s = store(&mock); + s.run_for_test(WatchlistCmd::Open); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistList(job, port) = s.take_jobs().pop().unwrap() else { panic!("list") }; + s.run(WatchlistCmd::Reset); + finish_list_job(&port, job.addr, job.req, &*mock); + assert_eq!(mock.pages.load(Ordering::SeqCst), 0); + assert!(!port.is_owed()); + assert!(s.view().is_empty()); + } + #[test] + fn stream_jobs_started_reset_late_terminal_is_acked_without_publication() { + use super::super::StoreJob; + let mock = three(); + let mut s = store(&mock); + s.run_for_test(WatchlistCmd::Open); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistList(_, port) = s.take_jobs().pop().unwrap() else { panic!("list") }; + let producer = port.start().unwrap(); + s.run(WatchlistCmd::Reset); + producer.finish(StreamEnd::Cancelled); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + assert!(!port.is_owed()); + assert!(s.view().is_empty()); + assert!(s.retired_streams.is_empty()); + } + #[test] + fn stream_jobs_panicked_reread_preserves_held_completeness_before_and_after_page_zero() { + use super::super::StoreJob; + for truncated in [false, true] { + for page_seen in [false, true] { + let mock = Mock::new((1..=150).map(|n| item(n, &format!("T{n:03}"))).collect()); + if truncated { mock.fail_pages_from.store(100, Ordering::SeqCst); } + let mut s = store(&mock); + load(&mut s); + let held = titles(&s); + assert_eq!(s.view().truncated(), truncated); + s.run(WatchlistCmd::Reread); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistList(job, port) = s.take_jobs().pop().unwrap() else { panic!("list") }; + let producer = port.start().unwrap(); + if page_seen { + producer.post(job.addr, What::Page { start: 0, total: Some(200), rows: Vec::new(), + answers: Vec::new(), roster_gen: 1, etag: Some("partial".into()) }); + } + producer.finish(StreamEnd::Panicked); + assert!(s.land_stream_results(gate, &profile)); + assert_eq!(titles(&s), held); + assert_eq!(s.view().truncated(), truncated, "held completeness survives panic, page_seen={page_seen}"); + assert!(!s.read_in_flight()); + assert!(!port.is_owed()); + assert!(!s.land_stream_results(gate, &profile)); + } + } + } + + #[test] + fn stream_jobs_first_load_panic_after_page_zero_keeps_partial_rows_truncated() { + use super::super::StoreJob; + let mock = three(); + let mut s = store(&mock); + s.run_for_test(WatchlistCmd::Open); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistList(job, port) = s.take_jobs().pop().unwrap() else { panic!("list") }; + let producer = port.start().unwrap(); + producer.post(job.addr, What::Page { start: 0, total: Some(3), + rows: vec![crate::watchlist::row_of(&item(1, "Alpha"), 0).unwrap()], answers: Vec::new(), + roster_gen: 1, etag: Some("partial".into()) }); + producer.finish(StreamEnd::Panicked); + assert!(s.land_stream_results(gate, &profile)); + assert_eq!(titles(&s), ["Alpha"]); + assert!(s.view().truncated()); + assert_eq!(s.view().status(), Status::Ready); + assert!(!s.read_in_flight()); + assert!(!port.is_owed()); + assert!(!s.land_stream_results(gate, &profile)); + } + + #[test] + fn stream_jobs_panicked_reread_keeps_held_rows_and_has_one_terminal() { + use super::super::StoreJob; + let mock = three(); + let mut s = store(&mock); + load(&mut s); + s.run(WatchlistCmd::Reread); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistList(job, port) = s.take_jobs().pop().unwrap() else { panic!("list") }; + let producer = port.start().unwrap(); + producer.post(job.addr, What::Page { start: 0, total: Some(5), rows: Vec::new(), answers: Vec::new(), roster_gen: 1, etag: Some("partial".into()) }); + producer.finish(StreamEnd::Panicked); + s.land_stream_results(gate, &profile); + assert_eq!(titles(&s), ["Alpha", "Bravo", "Charlie"]); + assert!(!s.read_in_flight()); + assert!(!port.is_owed()); + assert!(s.state.list_etag.is_none() || s.state.list_etag == mock.tag()); + assert!(!s.land_stream_results(gate, &profile)); + } + + #[test] + fn resolve_stale_full_client_key_is_not_cached() { + use plx_machine::job::Port; + use plx_plex::plex::{ClientKey, ClientKeys}; + use super::super::{StoreJob, watchlist_job::ResolveEnd}; + let old = ClientKey { instance: 1, token: 2, grant: 3 }; + for moved in [ClientKey { instance: 9, ..old }, ClientKey { token: 9, ..old }, ClientKey { grant: 9, ..old }] { + let mut s = WatchlistStore::default(); + let sid = sid0(); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + let keys = ClientKeys::from_keys([(sid, old)]); + s.want_hex(sid, "7"); + s.pump_with_snapshot(gate, &profile, Snapshot::new(&keys, None)); + let StoreJob::WatchlistResolve(job, port) = s.take_jobs().pop().unwrap() else { panic!("resolve") }; + assert!(port.start()); + port.done(job.addr, ResolveEnd::Answer(Some(Some(hex_of(7))))); + let keys = ClientKeys::from_keys([(sid, moved)]); + s.pump_with_snapshot(gate, &profile, Snapshot::new(&keys, None)); + assert_eq!(s.view().resolved_hex(sid, "7"), None, "every full-key component fences a stale answer"); + assert!(s.state.resolving.is_empty()); + s.want_hex(sid, "7"); + s.pump_with_snapshot(gate, &profile, Snapshot::new(&keys, None)); + let StoreJob::WatchlistResolve(job, _) = s.take_jobs().pop().unwrap() else { panic!("replacement") }; + assert_eq!(job.req.keys.key(sid), Some(moved)); + } + } + #[test] + fn stream_jobs_retired_terminal_race_is_always_acknowledged() { + use super::super::StoreJob; + for _ in 0..200 { + let mock = three(); + let mut s = store(&mock); + s.run_for_test(WatchlistCmd::Open); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::fixture_gate(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + let StoreJob::WatchlistList(_, port) = s.take_jobs().pop().unwrap() else { panic!("list") }; + let producer = port.start().unwrap(); + s.run(WatchlistCmd::Reset); + let worker = std::thread::spawn(move || producer.finish(StreamEnd::Cancelled)); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + worker.join().unwrap(); + s.pump_with_snapshot(gate, &profile, Snapshot::scripted(&*mock)); + assert!(!port.is_owed()); + } + } + + #[test] + fn stream_jobs_all_admission_refusals_settle_before_paced_landing_gates() { + use plx_machine::job::Port; + use super::super::StoreJob; + let mock = three(); + let mut s = store(&mock); + load(&mut s); + let profile = WatchlistInput::profile_for_test(1); + let gate = plx_machine::landgate::Gate::default(); + gate.arm_dump_paced(120); + gate.dump_frame(0); + s.run(WatchlistCmd::Reread); + s.run(WatchlistCmd::Press { hex: hex_of(1), intent: Intent::Remove }); + s.want_hex(sid0(), "7"); + s.pump_with_snapshot(&gate, &profile, Snapshot::scripted(&*mock)); + let mut streams = Vec::new(); + for job in s.take_jobs() { + match job { + StoreJob::WatchlistList(job, port) => { port.refused(job.addr); streams.push(port); } + StoreJob::WatchlistWrite(job, port) => port.refused(job.addr), + StoreJob::WatchlistResolve(job, port) => port.refused(job.addr), + _ => panic!("unexpected job"), + } + } + s.land_stream_results(&gate, &profile); + s.land_write_results(&gate, &profile); + s.land_resolve_refusals(&profile); + assert!(s.state.list_claim.is_none()); + assert!(s.state.write_claim.is_none()); + assert!(s.state.resolving.is_empty()); + assert!(streams.iter().all(|p| !p.is_owed())); + assert_eq!(s.state.list_retry, RETRY_FRAMES); + assert_eq!(s.state.write_retry, RETRY_FRAMES); + assert!(!s.has_jobs(), "a refusal drain never emits a replacement"); + } } diff --git a/rust-modules/data/src/stores/watchlist_job.rs b/rust-modules/data/src/stores/watchlist_job.rs new file mode 100644 index 0000000000..7929acb40a --- /dev/null +++ b/rust-modules/data/src/stores/watchlist_job.rs @@ -0,0 +1,337 @@ +//! Addressed one-shot Watchlist resolve jobs. +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicU8, Ordering}; +use plx_machine::job::Port; +use plx_machine::machine::Addr; +use plx_plex::plex::{Client, ClientKeys, KeyedClients, ServerId}; +use crate::watchlist::Tag; + +#[path = "watchlist_stream_port.rs"] +pub mod stream; +#[path = "watchlist_ports.rs"] +pub mod ports; +#[path = "watchlist_stream_job.rs"] +mod streaming; +pub use streaming::*; + +#[derive(Clone, PartialEq)] +pub struct ResolveReq { + pub tag: Tag, + pub keys: ClientKeys, + pub sid: ServerId, + pub rk: String, +} +impl std::fmt::Debug for ResolveReq { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ResolveReq").field("tag", &self.tag).finish_non_exhaustive() + } +} + +pub enum ResolveEnd { Answer(Option>), NotStarted, Panicked } +pub struct ResolveLanding { pub addr: Addr, pub tag: Tag, pub sid: ServerId, pub rk: String, pub key: Option, pub end: ResolveEnd } +#[derive(Default)] +pub struct ResolveMailbox(Mutex>); + +impl ResolveMailbox { + pub fn take_not_started(&self) -> Vec { + let mut mail = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let (refused, rest) = std::mem::take(&mut *mail).into_iter().partition(|l| matches!(l.end, ResolveEnd::NotStarted)); + *mail = rest; + refused + } +} +impl ResolveMailbox { + pub fn take(&self) -> Vec { + self.0.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect() + } +} +struct Claim { state: AtomicU8 } +#[derive(Clone)] +pub struct ResolvePort { + addr: Addr, tag: Tag, sid: ServerId, rk: String, key: Option, + mailbox: Arc, claim: Arc, +} +impl std::fmt::Debug for ResolvePort { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ResolvePort").field("addr", &self.addr).finish() } +} +impl PartialEq for ResolvePort { + fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.claim, &other.claim) } +} +impl ResolvePort { + pub fn new(addr: Addr, req: &ResolveReq, mailbox: Arc) -> Self { + Self { addr, tag: req.tag, sid: req.sid, rk: req.rk.clone(), key: req.keys.key(req.sid), mailbox, + claim: Arc::new(Claim { state: AtomicU8::new(0) }) } + } + /// Only the runner may start, and only while the owner has not cancelled the queued job. + pub fn start(&self) -> bool { + self.claim.state.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst).is_ok() + } + pub fn cancel_queued(&self) { + self.refused(self.addr); + } +} +impl Port for ResolvePort { + fn done(&self, addr: Addr, end: ResolveEnd) { + if addr != self.addr { return; } + // Refusal can win only before entry; an entered worker owns its answer. + let retired = match &end { + ResolveEnd::NotStarted => self.claim.state.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), + _ => match self.claim.state.compare_exchange(1, 2, Ordering::SeqCst, Ordering::SeqCst) { + Ok(state) => Ok(state), + Err(0) => self.claim.state.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), + Err(state) => Err(state), + }, + }; + if retired.is_err() { return; } + self.mailbox.0.lock().unwrap_or_else(|e| e.into_inner()).push(ResolveLanding { + addr, tag: self.tag, sid: self.sid, rk: self.rk.clone(), key: self.key, end, + }); + plx_machine::idle::invalidate(); + } + fn refused(&self, addr: Addr) { self.done(addr, ResolveEnd::NotStarted); } +} + +/// The host supplies the registry lookup. KeyedClients rechecks the captured full key. +pub fn finish_resolve_job(port: &ResolvePort, addr: Addr, req: ResolveReq, + lookup: fn(ServerId) -> Option<&'static Client>) { + let end = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let clients = KeyedClients::new(&req.keys, lookup); + let guid = clients.client(req.sid).and_then(|client| client.metadata(&req.rk)).map(|m| m.guid); + ResolveEnd::Answer(guid.map(|g| plx_plex::plex::resolve_catalog_hex(None, || Some(g)))) + })).unwrap_or(ResolveEnd::Panicked); + port.done(addr, end); +} + +/// An owned write claim. Credentials are captured when the store makes the decision. +pub struct WriteReq { + pub tag: Tag, + pub auth: crate::watchlist::WatchlistAuth, + pub write: crate::watchlist::ledger::PendingWrite, +} +impl std::fmt::Debug for WriteReq { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WriteReq").field("tag", &self.tag).finish_non_exhaustive() + } +} +impl PartialEq for WriteReq { + fn eq(&self, other: &Self) -> bool { + self.tag == other.tag && self.write == other.write + && self.auth.generation == other.auth.generation + && self.auth.client_id == other.auth.client_id && self.auth.credential == other.auth.credential + && self.auth.user.id == other.auth.user.id && self.auth.user.uuid == other.auth.user.uuid + } +} + +pub enum WriteEnd { + Written { write: crate::watchlist::ledger::PendingWrite, outcome: crate::watchlist::ledger::WriteOutcome }, + NotStarted { write: crate::watchlist::ledger::PendingWrite }, +} +pub struct WriteLanding { pub addr: Addr, pub tag: Tag, pub end: WriteEnd } +#[derive(Default)] +pub struct WriteMailbox(Mutex>); + +impl WriteMailbox { + pub fn take_not_started(&self) -> Vec { + let mut mail = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let (refused, rest) = std::mem::take(&mut *mail).into_iter().partition(|l| matches!(l.end, WriteEnd::NotStarted { .. })); + *mail = rest; + refused + } +} +impl WriteMailbox { + pub fn has_mail(&self) -> bool { + !self.0.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + pub fn take(&self) -> Vec { + self.0.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect() + } +} + +/// State 0 is queued, 1 started, 2 terminal. Start and every terminal compete on +/// this one atomic, so a refusal cannot release a write that has reached a worker. +#[derive(Clone)] +pub struct WritePort { + addr: Addr, tag: Tag, write: crate::watchlist::ledger::PendingWrite, + mailbox: Arc, state: Arc, +} +impl std::fmt::Debug for WritePort { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WritePort").field("addr", &self.addr).finish() + } +} +impl PartialEq for WritePort { + fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.state, &other.state) } +} +impl WritePort { + pub fn new(addr: Addr, req: &WriteReq, mailbox: Arc) -> Self { + Self { addr, tag: req.tag, write: req.write, mailbox, state: Arc::new(AtomicU8::new(0)) } + } + pub fn start(&self) -> bool { + self.state.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst).is_ok() + } + pub fn cancel_queued(&self) { self.refused(self.addr); } +} +impl Port for WritePort { + fn done(&self, addr: Addr, end: WriteEnd) { + if addr != self.addr { return; } + let previous = match &end { + WriteEnd::NotStarted { write } if *write == self.write => + self.state.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), + WriteEnd::Written { write, .. } if *write == self.write => { + match self.state.compare_exchange(1, 2, Ordering::SeqCst, Ordering::SeqCst) { + Ok(state) => Ok(state), + Err(0) => self.state.compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst), + Err(state) => Err(state), + } + } + _ => return, + }; + if previous.is_err() { return; } + self.mailbox.0.lock().unwrap_or_else(|e| e.into_inner()).push(WriteLanding { addr, tag: self.tag, end }); + plx_machine::idle::invalidate(); + } + fn refused(&self, addr: Addr) { self.done(addr, WriteEnd::NotStarted { write: self.write }); } +} + +/// Runs only after `start` wins. A panic may have reached the wire and is a failed write. +pub fn finish_write_job(port: &WritePort, addr: Addr, req: WriteReq, io: &dyn crate::watchlist::WatchlistIo) { + use crate::watchlist::ledger::WriteOutcome; + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if io.write(&req.auth, &crate::watchlist::encode_hex(&req.write.hex), req.write.intent).is_ok() { + WriteOutcome::Landed + } else { + WriteOutcome::Failed + } + })).unwrap_or(WriteOutcome::Failed); + port.done(addr, WriteEnd::Written { write: req.write, outcome }); +} + +#[cfg(test)] +mod tests { + use super::*; + use plx_machine::machine::{MachineId, RequestId}; + use crate::stores::StoreId; + + fn fixture() -> (ResolveReq, ResolvePort, Addr, Arc) { + let tag = Tag { profile_gen: 9, epoch: 4, req: 7 }; + let addr = Addr { to: MachineId::Store(StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let req = ResolveReq { tag, keys: ClientKeys::default(), sid: ServerId::from_raw(0), rk: "7".into() }; + let mailbox = Arc::new(ResolveMailbox::default()); + let port = ResolvePort::new(addr, &req, Arc::clone(&mailbox)); + (req, port, addr, mailbox) + } + + fn write_fixture() -> (WriteReq, WritePort, Addr, Arc) { + use crate::watchlist::ledger::{Intent, PendingWrite}; + let tag = Tag { profile_gen: 1, epoch: 2, req: 3 }; + let addr = Addr { to: MachineId::Store(StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let req = WriteReq { tag, auth: crate::watchlist::WatchlistInput::for_test(1).auth().unwrap().clone(), + write: PendingWrite { hex: [7; 12], intent: Intent::Add, seq: 42 } }; + let mailbox = Arc::new(WriteMailbox::default()); + let port = WritePort::new(addr, &req, Arc::clone(&mailbox)); + (req, port, addr, mailbox) + } + + #[test] + fn write_wrong_address_does_not_retire_and_started_beats_cancel() { + let (req, port, addr, mailbox) = write_fixture(); + let wrong = Addr { to: addr.to, req: RequestId(addr.req.0 + 1) }; + port.refused(wrong); + assert!(port.start()); + port.cancel_queued(); + assert!(mailbox.take().is_empty()); + port.done(addr, WriteEnd::Written { write: req.write, outcome: crate::watchlist::ledger::WriteOutcome::Failed }); + port.refused(addr); + let answers = mailbox.take(); + assert_eq!(answers.len(), 1); + assert!(matches!(answers[0].end, WriteEnd::Written { outcome: crate::watchlist::ledger::WriteOutcome::Failed, .. })); + } + + #[test] + fn write_cancel_or_terminal_before_start_prevents_worker() { + let (req, port, _addr, mailbox) = write_fixture(); + port.cancel_queued(); + assert!(!port.start()); + assert!(matches!(mailbox.take().pop().unwrap().end, WriteEnd::NotStarted { write } if write == req.write)); + let (req, port, addr, mailbox) = write_fixture(); + port.done(addr, WriteEnd::Written { write: req.write, outcome: crate::watchlist::ledger::WriteOutcome::Failed }); + assert!(!port.start()); + assert_eq!(mailbox.take().len(), 1); + } + + #[test] + fn resolve_port_answers_once_and_rejects_wrong_address() { + let (_, port, addr, mailbox) = fixture(); + let wrong = Addr { to: addr.to, req: RequestId(addr.req.0 + 1) }; + port.done(wrong, ResolveEnd::Answer(Some(None))); + assert!(mailbox.take().is_empty()); + assert!(port.start()); + port.done(addr, ResolveEnd::Answer(Some(None))); + port.refused(addr); + let mut answers = mailbox.take(); + assert_eq!(answers.len(), 1); + assert!(matches!(answers.pop().unwrap().end, ResolveEnd::Answer(Some(None)))); + } + + #[test] + fn resolve_refusal_after_worker_entry_cannot_preempt_answer() { + let (_, port, addr, mailbox) = fixture(); + assert!(port.start()); + port.refused(addr); + port.cancel_queued(); + assert!(mailbox.take().is_empty()); + port.done(addr, ResolveEnd::Answer(Some(None))); + let answers = mailbox.take(); + assert_eq!(answers.len(), 1); + assert!(matches!(answers[0].end, ResolveEnd::Answer(Some(None)))); + } + + #[test] + fn resolve_refused_before_start_cannot_start() { + let (_, port, addr, mailbox) = fixture(); + port.refused(addr); + assert!(!port.start(), "a refused queued job must never start"); + assert_eq!(mailbox.take().len(), 1); + } + + #[test] + fn resolve_answer_before_start_cannot_start() { + let (_, port, addr, mailbox) = fixture(); + port.done(addr, ResolveEnd::Answer(Some(None))); + assert!(!port.start(), "a terminal queued job must never start"); + assert_eq!(mailbox.take().len(), 1); + } + + #[test] + fn resolve_cancel_before_start_cannot_start_and_answers_once() { + let (_, port, addr, mailbox) = fixture(); + port.cancel_queued(); + assert!(!port.start()); + port.refused(addr); + let answers = mailbox.take(); + assert_eq!(answers.len(), 1); + assert!(matches!(answers[0].end, ResolveEnd::NotStarted)); + } + + #[test] + fn resolve_worker_panic_answers_once() { + let (mut req, port, addr, mailbox) = fixture(); + req.keys = ClientKeys::from_keys([(req.sid, plx_plex::plex::ClientKey { instance: 1, token: 2, grant: 3 })]); + assert!(port.start()); + finish_resolve_job(&port, addr, req, |_| panic!("scripted lookup panic")); + port.refused(addr); + let answers = mailbox.take(); + assert_eq!(answers.len(), 1); + assert!(matches!(answers[0].end, ResolveEnd::Panicked)); + } + + #[test] + fn resolve_missing_key_is_unanswered() { + let (req, port, addr, mailbox) = fixture(); + assert!(port.start()); + finish_resolve_job(&port, addr, req, |_| panic!("lookup without a captured key")); + let answers = mailbox.take(); + assert_eq!(answers.len(), 1); + assert!(matches!(answers[0].end, ResolveEnd::Answer(None))); + } +} diff --git a/rust-modules/data/src/stores/watchlist_ports.rs b/rust-modules/data/src/stores/watchlist_ports.rs new file mode 100644 index 0000000000..61986b2a1f --- /dev/null +++ b/rust-modules/data/src/stores/watchlist_ports.rs @@ -0,0 +1,129 @@ +//! Worker-only transport. Registry and session readers are boot-selected by the runner. +use crate::watchlist::{WatchlistAuth, WatchlistIo}; +use crate::watchlist::ledger::Intent; +use crate::watchlist::model::Reach; +use plx_plex::plex::{Client, KeyedClients, ServerId, GuidKind, GuidMatch, GuidLookupError}; +use plx_plex::plex::account::AccountClient; +use plx_plex::plex::watchlist::{WatchPage, WatchItem, WatchlistError}; +use super::Snapshot; + +pub struct LiveWatchlistIo { + pub input: Snapshot, + pub lookup: fn(ServerId) -> Option<&'static Client>, + pub lease: fn(&WatchlistAuth) -> bool, +} +impl Reach for LiveWatchlistIo { + fn reachable(&self, sid: ServerId) -> bool { self.input.reachable(sid) } + fn roster(&self) -> Vec { self.input.roster() } + fn copy_rank(&self, sid: ServerId) -> u8 { self.input.copy_rank(sid) } +} +impl WatchlistIo for LiveWatchlistIo { + fn page(&self, auth: &WatchlistAuth, start: u32, size: u32, etag: Option<&str>) -> Result { + let client = AccountClient::new(&auth.client_id, Some(&auth.credential)); + let mut transport = client.watchlist_transport(); + if !(self.lease)(auth) { return Err(WatchlistError::Unauthorized); } + client.watchlist_page(start, size, etag, &mut transport) + } + fn released(&self, auth: &WatchlistAuth) -> Result, WatchlistError> { + let client = AccountClient::new(&auth.client_id, Some(&auth.credential)); + let mut transport = client.watchlist_transport(); + if !(self.lease)(auth) { return Err(WatchlistError::Unauthorized); } + client.watchlist_released(&mut transport) + } + fn write(&self, auth: &WatchlistAuth, hex: &str, intent: Intent) -> Result<(), WatchlistError> { + let client = AccountClient::new(&auth.client_id, Some(&auth.credential)); + let mut transport = client.watchlist_transport(); + if !(self.lease)(auth) { return Err(WatchlistError::Unauthorized); } + match intent { + Intent::Add => client.watchlist_add(hex, &mut transport), + Intent::Remove => client.watchlist_remove(hex, &mut transport), + } + } + fn find(&self, sid: ServerId, kind: GuidKind, guids: &[String]) -> Result, GuidLookupError> { + KeyedClients::new(&self.input.keys, self.lookup).client(sid) + .ok_or(GuidLookupError::Unanswered)?.find_by_guids(kind, guids) + } + fn roster_gen(&self) -> u32 { self.input.roster_gen } + fn facts_gen(&self) -> u32 { self.input.facts_gen } + fn today(&self) -> Option { self.input.today.clone() } +} + +/// The algorithm sees captured facts even when its transport is scripted. +pub struct CapturedIo<'a> { pub input: &'a Snapshot, pub transport: &'a dyn WatchlistIo, pub cancelled: &'a (dyn Fn() -> bool + Sync) } +impl Reach for CapturedIo<'_> { + fn reachable(&self, sid: ServerId) -> bool { self.input.reachable(sid) } + fn roster(&self) -> Vec { self.input.roster() } + fn copy_rank(&self, sid: ServerId) -> u8 { self.input.copy_rank(sid) } +} +impl WatchlistIo for CapturedIo<'_> { + fn page(&self, a: &WatchlistAuth, s: u32, n: u32, e: Option<&str>) -> Result { if (self.cancelled)() { Err(WatchlistError::Transport) } else { self.transport.page(a, s, n, e) } } + fn released(&self, a: &WatchlistAuth) -> Result, WatchlistError> { if (self.cancelled)() { Err(WatchlistError::Transport) } else { self.transport.released(a) } } + fn write(&self, a: &WatchlistAuth, h: &str, i: Intent) -> Result<(), WatchlistError> { self.transport.write(a, h, i) } + fn find(&self, s: ServerId, k: GuidKind, g: &[String]) -> Result, GuidLookupError> { if (self.cancelled)() { Err(GuidLookupError::Unanswered) } else { self.transport.find(s, k, g) } } + fn roster_gen(&self) -> u32 { self.input.roster_gen } + fn facts_gen(&self) -> u32 { self.input.facts_gen } + fn today(&self) -> Option { self.input.today.clone() } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::stores::watchlist_job::SnapshotData; + #[test] + fn stream_jobs_account_page_released_and_write_recheck_lease() { + let io = LiveWatchlistIo { input: Snapshot::default(), lookup: |_| panic!("no server lookup"), lease: |_| false }; + let auth = crate::watchlist::WatchlistInput::for_test(1).auth().unwrap().clone(); + assert!(matches!(io.page(&auth, 0, 1, None), Err(WatchlistError::Unauthorized))); + assert!(matches!(io.released(&auth), Err(WatchlistError::Unauthorized))); + assert!(matches!(io.write(&auth, "000000000000000000000000", Intent::Add), Err(WatchlistError::Unauthorized))); + } +#[test] + fn stream_jobs_live_find_rechecks_full_captured_client_key() { + use plx_plex::plex::{ClientKey, ClientKeys}; + let _serial = plx_base::testlock::serial(); + plx_plex::plex::reset_servers_for_test(); + let sid = plx_plex::plex::register_for_test("watchlist-key-test", "127.0.0.1", 9, "old", "cid"); + let client = plx_plex::plex::client_for(sid).unwrap(); + let keys = ClientKeys::of([(sid, client)]); + let before = keys.key(sid).unwrap(); + client.set_token("new"); + let after = ClientKey::of(client); + assert_eq!(before.instance, after.instance); + assert_ne!(before.token, after.token); + let io = LiveWatchlistIo { input: Snapshot::from(SnapshotData { keys, ..SnapshotData::default() }), lookup: plx_plex::plex::client_for, lease: |_| true }; + assert!(matches!(io.find(sid, GuidKind::Movie, &["plex://movie/test".into()]), Err(GuidLookupError::Unanswered))); + plx_plex::plex::reset_servers_for_test(); + } + + #[test] + fn stream_jobs_each_worker_panic_posts_exactly_one_terminal() { + use crate::stores::watchlist_job::*; + use crate::watchlist::{Tag, What}; + use crate::watchlist::model::Kind; + use plx_machine::machine::{Addr, MachineId, RequestId}; + use plx_plex::plex::{ClientKey, ClientKeys}; + use std::sync::Arc; + for kind in 0..3 { + let sid = ServerId::from_raw(0); + let tag = Tag { profile_gen: 1, epoch: 2, req: 3 }; + let addr = Addr { to: MachineId::Store(crate::stores::StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let input = Snapshot::from(SnapshotData { keys: ClientKeys::from_keys([(sid, ClientKey { instance: 1, token: 2, grant: 3 })]), + reach: vec![(sid, true, 0)], ..SnapshotData::default() }); + let io = LiveWatchlistIo { input: input.clone(), lookup: |_| panic!("scripted lookup panic"), lease: |_| panic!("scripted account lease panic") }; + let mail = Arc::new(stream::StreamMailbox::::default()); + let port = WatchlistStreamPort::new(addr, tag, mail.clone()); + let rows = vec![("plex://movie/010101010101010101010101".into(), Kind::Movie)]; + match kind { + 0 => finish_list_job(&port, addr, ListReq { tag, input, auth: AuthValue(crate::watchlist::WatchlistInput::for_test(1).auth().unwrap().clone()), known: Default::default(), known_gen: 0, etag: None }, &io), + 1 => finish_rematch_job(&port, addr, RematchReq { tag, input, rows }, &io), + _ => finish_delta_job(&port, addr, DeltaReq { tag, input, sid, rows: Arc::new(rows) }, &io), + } + port.refused(addr); + let batch = mail.take(); + assert_eq!(batch.len(), 1); + assert!(matches!(batch[0].event, stream::StreamEvent::End(stream::StreamEnd::Panicked))); + assert!(batch[0].ack_terminal()); + assert!(!port.is_owed()); + } + } +} diff --git a/rust-modules/data/src/stores/watchlist_stream_job.rs b/rust-modules/data/src/stores/watchlist_stream_job.rs new file mode 100644 index 0000000000..e0939705db --- /dev/null +++ b/rust-modules/data/src/stores/watchlist_stream_job.rs @@ -0,0 +1,176 @@ +//! Captured Watchlist stream requests and worker completions. +use super::{stream, ports}; +use crate::watchlist::{Tag, What, Landed, WatchlistIo, WatchlistAuth, run_list, run_rematch, run_delta}; +use crate::watchlist::model::{Kind, Reach}; +use plx_machine::machine::Addr; +use plx_plex::plex::{ClientKeys, ServerId}; +use std::collections::HashSet; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Snapshot(std::sync::Arc); + +#[derive(Debug, Default, PartialEq)] +pub struct SnapshotData { + pub keys: ClientKeys, + pub today: Option, + pub roster_gen: u32, + pub facts_gen: u32, + pub reach: Vec<(ServerId, bool, u8)>, +} +impl std::ops::Deref for Snapshot { + type Target = SnapshotData; + fn deref(&self) -> &Self::Target { &self.0 } +} +impl From for Snapshot { + fn from(data: SnapshotData) -> Self { Self(std::sync::Arc::new(data)) } +} +impl Snapshot { + pub fn new(keys: &ClientKeys, today: Option) -> Self { + let facts = crate::stores::watchlist::WatchlistFacts { keys, today: today.as_deref() }; + let reach = keys.slots().map(|s| (s, facts.reachable(s), facts.copy_rank(s))).collect(); + SnapshotData { keys: keys.clone(), today, roster_gen: keys.roster_gen(), facts_gen: keys.facts_gen(), reach }.into() + } + #[cfg(any(test, feature = "test-support"))] + pub fn scripted(io: &dyn WatchlistIo) -> Self { + SnapshotData { keys: ClientKeys::default(), today: io.today(), roster_gen: io.roster_gen(), facts_gen: io.facts_gen(), + reach: io.roster().into_iter().map(|s| (s, io.reachable(s), io.copy_rank(s))).collect() }.into() + } +} + +/// Host-owned retained capture. Equality includes credentials, facts and eligibility, not just generations. +#[derive(Default)] +pub struct SnapshotCache { + day: Option, + snapshot: Option, +} +impl SnapshotCache { + pub fn capture(&mut self, keys: &ClientKeys, day: Option) -> Snapshot { + if let Some(snapshot) = &self.snapshot { + if self.day == day && &snapshot.keys == keys { return snapshot.clone(); } + } + let snapshot = Snapshot::new(keys, day.map(crate::watchlist::ymd_of_unix_days)); + self.day = day; + self.snapshot = Some(snapshot.clone()); + snapshot + } +} +impl Reach for Snapshot { + fn reachable(&self, sid: ServerId) -> bool { self.reach.iter().any(|(s, up, _)| *s == sid && *up) } + fn roster(&self) -> Vec { self.reach.iter().map(|(s, _, _)| *s).collect() } + fn copy_rank(&self, sid: ServerId) -> u8 { self.reach.iter().find(|(s, _, _)| *s == sid).map_or(2, |(_, _, r)| *r) } +} +#[derive(Debug, PartialEq)] +pub struct ListReq { pub tag: Tag, pub input: Snapshot, pub auth: AuthValue, + pub known: HashSet, pub known_gen: u32, pub etag: Option } +#[derive(Clone)] +pub struct AuthValue(pub WatchlistAuth); +impl std::fmt::Debug for AuthValue { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } +} +impl PartialEq for AuthValue { + fn eq(&self, b: &Self) -> bool { let a = &self.0; let b = &b.0; + a.client_id == b.client_id && a.credential == b.credential && a.generation == b.generation + && a.user.id == b.user.id && a.user.uuid == b.user.uuid } +} +#[derive(Clone, Debug, PartialEq)] +pub struct RematchReq { pub tag: Tag, pub input: Snapshot, pub rows: Vec<(String, Kind)> } +#[derive(Clone, Debug, PartialEq)] +pub struct DeltaReq { pub tag: Tag, pub input: Snapshot, pub sid: ServerId, pub rows: std::sync::Arc> } +pub type WatchlistStreamPort = stream::StreamPort; +fn finish_stream(port: &WatchlistStreamPort, addr: Addr, input: &Snapshot, + transport: &dyn WatchlistIo, body: impl FnOnce(&dyn WatchlistIo, &mut dyn FnMut(Landed))) { + let Some(producer) = port.start() else { return }; + let cancelled = || port.is_cancelled(); + let io = ports::CapturedIo { input, transport, cancelled: &cancelled }; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + body(&io, &mut |l| { if !producer.is_cancelled() { producer.post(addr, l.what); } }); + })); + let end = if result.is_err() { stream::StreamEnd::Panicked } + else if producer.is_cancelled() { stream::StreamEnd::Cancelled } else { stream::StreamEnd::Done }; + producer.finish(end); +} +pub fn finish_list_job(port: &WatchlistStreamPort, addr: Addr, req: ListReq, io: &dyn WatchlistIo) { + finish_stream(port, addr, &req.input, io, |io, post| run_list(io, &req.auth.0, req.tag, (&req.known, req.known_gen), req.etag.as_deref(), post)); +} +pub fn finish_rematch_job(port: &WatchlistStreamPort, addr: Addr, req: RematchReq, io: &dyn WatchlistIo) { + finish_stream(port, addr, &req.input, io, |io, post| run_rematch(io, &req.rows, req.tag, post)); +} +pub fn finish_delta_job(port: &WatchlistStreamPort, addr: Addr, req: DeltaReq, io: &dyn WatchlistIo) { + finish_stream(port, addr, &req.input, io, |io, post| run_delta(io, req.sid, &req.rows, req.tag, post)); +} + +#[cfg(test)] +mod snapshot_cache_tests { + use super::*; + use plx_plex::plex::{Client, ClientKey, probe::Outcome}; + use std::sync::Arc; + + fn client() -> &'static Client { + let sid = plx_plex::plex::register_for_test( + "watchlist-capture", "127.0.0.1", 9, "old-token", "watchlist-test"); + plx_plex::plex::client_for(sid).unwrap() + } + fn keys(client: &'static Client, reachable: bool, allowed: bool) -> ClientKeys { + let mut keys = ClientKeys::default(); + keys.refill_roster_with_stream_policy(client.id(), 5, 7, [client.id()], + |_| Some(client), |_| None, |_| reachable.then_some(Outcome::Reachable), |_| allowed); + keys + } + + #[test] + fn watchlist_snapshot_cache_retains_populated_capture_and_buffers_on_stable_passes() { + let _serial = plx_base::testlock::serial(); + plx_plex::plex::reset_servers_for_test(); + let client = client(); + let keys = keys(client, true, true); + let mut cache = SnapshotCache::default(); + let held = cache.capture(&keys, Some(20_000)); + let reach = held.reach.as_ptr(); + let machine = held.keys.facts(client.id()).unwrap().machine_id.as_ptr(); + let date = held.today.as_ref().unwrap().as_ptr(); + for _ in 0..64 { + let current = cache.capture(&keys, Some(20_000)); + assert!(Arc::ptr_eq(&held.0, ¤t.0)); + assert_eq!(current.reach.as_ptr(), reach); + assert_eq!(current.keys.facts(client.id()).unwrap().machine_id.as_ptr(), machine); + assert_eq!(current.today.as_ref().unwrap().as_ptr(), date); + assert_eq!(current.keys.iter().count(), 1); + } + plx_plex::plex::reset_servers_for_test(); + } + + #[test] + fn watchlist_snapshot_cache_tracks_full_keys_facts_eligibility_and_day_without_mutating_old_jobs() { + let _serial = plx_base::testlock::serial(); + plx_plex::plex::reset_servers_for_test(); + let client = client(); + let initial = keys(client, true, true); + let old_key = ClientKey::of(client); + let mut cache = SnapshotCache::default(); + let old = cache.capture(&initial, Some(20_000)); + client.set_token("new-token"); + let retokened = keys(client, true, true); + assert_eq!((initial.roster_gen(), initial.facts_gen()), (retokened.roster_gen(), retokened.facts_gen())); + let changed_key = cache.capture(&retokened, Some(20_000)); + assert!(!Arc::ptr_eq(&old.0, &changed_key.0)); + assert_ne!(changed_key.keys.key(client.id()), Some(old_key)); + let ineligible = keys(client, true, false); + let changed_eligibility = cache.capture(&ineligible, Some(20_000)); + assert!(!Arc::ptr_eq(&changed_key.0, &changed_eligibility.0)); + assert!(!changed_eligibility.keys.stream_allowed(client.id())); + let unreachable = keys(client, false, false); + let changed_facts = cache.capture(&unreachable, Some(20_000)); + assert!(!Arc::ptr_eq(&changed_eligibility.0, &changed_facts.0)); + assert!(!changed_facts.reachable(client.id())); + let changed_day = cache.capture(&unreachable, Some(20_001)); + assert!(!Arc::ptr_eq(&changed_facts.0, &changed_day.0)); + assert_ne!(old.today, changed_day.today); + let no_day = cache.capture(&unreachable, None); + assert!(no_day.today.is_none()); + assert_eq!(old.keys.key(client.id()), Some(old_key)); + assert!(old.keys.stream_allowed(client.id())); + assert!(old.reachable(client.id())); + assert_eq!(old.today.as_deref(), Some(crate::watchlist::ymd_of_unix_days(20_000).as_str())); + plx_plex::plex::reset_servers_for_test(); + } +} diff --git a/rust-modules/data/src/stores/watchlist_stream_port.rs b/rust-modules/data/src/stores/watchlist_stream_port.rs new file mode 100644 index 0000000000..1d725b14cd --- /dev/null +++ b/rust-modules/data/src/stores/watchlist_stream_port.rs @@ -0,0 +1,147 @@ +//! Ordered, addressed delivery for a Watchlist stream job. +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, Ordering}; +use plx_machine::machine::Addr; +use crate::watchlist::Tag; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StreamEnd { Done, NotStarted, Panicked, Cancelled } +pub enum StreamEvent { Post(T), End(StreamEnd) } + +pub struct StreamLanding { + pub addr: Addr, + pub tag: Tag, + pub event: StreamEvent, + owed: Arc, +} +impl StreamLanding { + pub fn ack_terminal(&self) -> bool { + matches!(self.event, StreamEvent::End(_)) && self.owed.swap(false, Ordering::SeqCst) + } +} + +pub struct StreamMailbox(Mutex>>); + +impl StreamMailbox { + pub fn take_not_started(&self) -> Vec> { + let mut mail = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let (refused, rest) = std::mem::take(&mut *mail).into_iter().partition(|l| matches!(l.event, StreamEvent::End(StreamEnd::NotStarted))); + *mail = rest; + refused + } +} +impl Default for StreamMailbox { + fn default() -> Self { Self(Mutex::new(Vec::new())) } +} +impl StreamMailbox { + pub fn take(&self) -> Vec> { + std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner())) + } + pub fn has_mail(&self) -> bool { + !self.0.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Phase { Queued, Started, Terminal } +struct Claim { phase: Phase, cancelled: bool } +pub struct StreamPort { + addr: Addr, + tag: Tag, + mailbox: Arc>, + claim: Arc>, + owed: Arc, +} +impl Clone for StreamPort { + fn clone(&self) -> Self { + Self { addr: self.addr, tag: self.tag, mailbox: Arc::clone(&self.mailbox), + claim: Arc::clone(&self.claim), owed: Arc::clone(&self.owed) } + } +} +impl StreamPort { + pub fn new(addr: Addr, tag: Tag, mailbox: Arc>) -> Self { + Self { addr, tag, mailbox, claim: Arc::new(Mutex::new(Claim { phase: Phase::Queued, cancelled: false })), + owed: Arc::new(AtomicBool::new(true)) } + } + fn publish(&self, event: StreamEvent) { + self.mailbox.0.lock().unwrap_or_else(|e| e.into_inner()).push(StreamLanding { + addr: self.addr, tag: self.tag, event, owed: Arc::clone(&self.owed), + }); + plx_machine::idle::invalidate(); + } + pub fn start(&self) -> Option> { + let mut claim = self.claim.lock().unwrap_or_else(|e| e.into_inner()); + if claim.phase != Phase::Queued { return None; } + claim.phase = Phase::Started; + Some(StreamProducer { port: self.clone(), finished: false }) + } + pub fn post(&self, addr: Addr, value: T) -> bool { + if addr != self.addr { return false; } + let claim = self.claim.lock().unwrap_or_else(|e| e.into_inner()); + if claim.phase != Phase::Started { return false; } + self.publish(StreamEvent::Post(value)); + true + } + pub fn done(&self, addr: Addr, end: StreamEnd) { + if end == StreamEnd::NotStarted { self.refused(addr); return; } + if addr != self.addr { return; } + let mut claim = self.claim.lock().unwrap_or_else(|e| e.into_inner()); + if claim.phase == Phase::Terminal { return; } + claim.phase = Phase::Terminal; + self.publish(StreamEvent::End(end)); + } + pub fn refused(&self, addr: Addr) { + if addr != self.addr { return; } + let mut claim = self.claim.lock().unwrap_or_else(|e| e.into_inner()); + if claim.phase != Phase::Queued { return; } + claim.phase = Phase::Terminal; + self.publish(StreamEvent::End(StreamEnd::NotStarted)); + } + pub fn cancel(&self) { + let mut claim = self.claim.lock().unwrap_or_else(|e| e.into_inner()); + claim.cancelled = true; + if claim.phase == Phase::Queued { + claim.phase = Phase::Terminal; + self.publish(StreamEvent::End(StreamEnd::Cancelled)); + } + } + pub fn is_cancelled(&self) -> bool { + self.claim.lock().unwrap_or_else(|e| e.into_inner()).cancelled + } + pub fn is_owed(&self) -> bool { self.owed.load(Ordering::SeqCst) } +} +impl plx_machine::job::Port for StreamPort { + fn done(&self, addr: Addr, end: StreamEnd) { StreamPort::done(self, addr, end); } + fn refused(&self, addr: Addr) { StreamPort::refused(self, addr); } +} + +impl std::fmt::Debug for StreamPort { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("StreamPort").field("addr", &self.addr).field("tag", &self.tag).finish() } +} +impl PartialEq for StreamPort { + fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.claim, &other.claim) } +} +impl StreamPort { + pub fn is_running(&self) -> bool { self.claim.lock().unwrap_or_else(|e| e.into_inner()).phase != Phase::Terminal } +} +pub struct StreamProducer { port: StreamPort, finished: bool } +impl StreamProducer { + pub fn post(&self, addr: Addr, value: T) -> bool { self.port.post(addr, value) } + pub fn is_cancelled(&self) -> bool { self.port.is_cancelled() } + pub fn finish(mut self, end: StreamEnd) { + self.port.done(self.port.addr, end); + self.finished = true; + } +} +impl Drop for StreamProducer { + fn drop(&mut self) { + if !self.finished { + let end = if std::thread::panicking() { StreamEnd::Panicked } else { StreamEnd::Cancelled }; + self.port.done(self.port.addr, end); + } + } +} + +#[cfg(test)] +#[path = "watchlist_stream_port_tests.rs"] +mod tests; diff --git a/rust-modules/data/src/stores/watchlist_stream_port_tests.rs b/rust-modules/data/src/stores/watchlist_stream_port_tests.rs new file mode 100644 index 0000000000..6bea5381de --- /dev/null +++ b/rust-modules/data/src/stores/watchlist_stream_port_tests.rs @@ -0,0 +1,200 @@ +use super::*; +use plx_machine::machine::{MachineId, RequestId}; +use crate::stores::StoreId; + +fn fixture() -> (StreamPort, Addr, Tag, Arc>) { + let tag = Tag { profile_gen: 9, epoch: 4, req: 7 }; + let addr = Addr { to: MachineId::Store(StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let mailbox = Arc::new(StreamMailbox::default()); + (StreamPort::new(addr, tag, Arc::clone(&mailbox)), addr, tag, mailbox) +} + +#[test] +fn stream_port_order_and_acknowledgement() { + let (port, addr, tag, mailbox) = fixture(); + let producer = port.start().unwrap(); + assert!(producer.post(addr, 1)); + assert!(producer.post(addr, 2)); + producer.finish(StreamEnd::Done); + assert!(port.is_owed()); + let batch = mailbox.take(); + assert_eq!(batch.len(), 3); + assert!(batch.iter().all(|e| e.addr == addr && e.tag == tag)); + assert!(matches!(batch[0].event, StreamEvent::Post(1))); + assert!(matches!(batch[1].event, StreamEvent::Post(2))); + assert!(matches!(batch[2].event, StreamEvent::End(StreamEnd::Done))); + assert!(!batch[0].ack_terminal()); + assert!(port.is_owed()); + assert!(batch[2].ack_terminal()); + assert!(!batch[2].ack_terminal()); + assert!(!port.is_owed()); +} + +#[test] +fn stream_port_terminal_before_start_and_refusal() { + let (port, addr, _, mailbox) = fixture::(); + port.done(addr, StreamEnd::Done); + assert!(port.start().is_none()); + port.refused(addr); + let batch = mailbox.take(); + assert_eq!(batch.len(), 1); + assert!(matches!(batch[0].event, StreamEvent::End(StreamEnd::Done))); + assert!(port.is_owed()); + assert!(batch[0].ack_terminal()); + let (port, addr, _, mailbox) = fixture::(); + port.refused(addr); + assert!(port.start().is_none()); + assert!(matches!(mailbox.take()[0].event, StreamEvent::End(StreamEnd::NotStarted))); +} + +#[test] +fn stream_port_wrong_address_does_not_retire() { + let (port, addr, _, mailbox) = fixture(); + let wrong = Addr { to: addr.to, req: RequestId(addr.req.0 + 1) }; + port.done(wrong, StreamEnd::Done); + port.refused(wrong); + assert!(!port.post(wrong, 1)); + let producer = port.start().unwrap(); + assert!(!producer.post(wrong, 2)); + assert!(producer.post(addr, 3)); + producer.finish(StreamEnd::Done); + let batch = mailbox.take(); + assert_eq!(batch.len(), 2); + assert!(matches!(batch[0].event, StreamEvent::Post(3))); + assert!(matches!(batch[1].event, StreamEvent::End(StreamEnd::Done))); +} + +#[test] +fn stream_port_duplicate_and_late_publications_are_ignored() { + let (port, addr, _, mailbox) = fixture(); + assert!(!port.post(addr, 0)); + let producer = port.start().unwrap(); + assert!(producer.post(addr, 1)); + port.done(addr, StreamEnd::Done); + assert!(!producer.post(addr, 2)); + port.done(addr, StreamEnd::Panicked); + port.refused(addr); + drop(producer); + let batch = mailbox.take(); + assert_eq!(batch.len(), 2); + assert!(matches!(batch[0].event, StreamEvent::Post(1))); + assert!(matches!(batch[1].event, StreamEvent::End(StreamEnd::Done))); +} + +#[test] +fn stream_port_pending_cancel_prevents_retained_start() { + let (port, addr, _, mailbox) = fixture::(); + let retained = port.clone(); + port.cancel(); + port.cancel(); + port.refused(addr); + assert!(retained.start().is_none()); + assert!(retained.is_cancelled()); + let batch = mailbox.take(); + assert_eq!(batch.len(), 1); + assert!(matches!(batch[0].event, StreamEvent::End(StreamEnd::Cancelled))); + assert!(retained.is_owed()); + assert!(batch[0].ack_terminal()); +} + +#[test] +fn stream_port_started_cancel_is_a_latch_not_early_terminal() { + let (port, addr, _, mailbox) = fixture(); + let producer = port.start().unwrap(); + port.cancel(); + port.refused(addr); + port.done(addr, StreamEnd::NotStarted); + assert!(producer.is_cancelled()); + assert!(mailbox.take().is_empty()); + assert!(port.is_owed()); + assert!(producer.post(addr, 7)); + producer.finish(StreamEnd::Cancelled); + let batch = mailbox.take(); + assert_eq!(batch.len(), 2); + assert!(matches!(batch[0].event, StreamEvent::Post(7))); + assert!(matches!(batch[1].event, StreamEvent::End(StreamEnd::Cancelled))); +} + +#[test] +fn stream_port_panic_and_producer_drop_complete_once() { + let (port, addr, _, mailbox) = fixture::(); + let producer = port.start().unwrap(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _producer = producer; + panic!("scripted worker panic"); + })); + assert!(result.is_err()); + port.done(addr, StreamEnd::Done); + let batch = mailbox.take(); + assert_eq!(batch.len(), 1); + assert!(matches!(batch[0].event, StreamEvent::End(StreamEnd::Panicked))); + let (port, _, _, mailbox) = fixture::(); + drop(port.start().unwrap()); + assert!(matches!(mailbox.take()[0].event, StreamEvent::End(StreamEnd::Cancelled))); +} + +#[test] +fn stream_port_drain_moves_nonclone_payload_and_keeps_later_batch() { + struct Payload(Vec); + let (port, addr, _, mailbox) = fixture(); + let producer = port.start().unwrap(); + let bytes = vec![4, 5, 6]; + let original = bytes.as_ptr(); + assert!(producer.post(addr, Payload(bytes))); + let first = mailbox.take(); + assert!(!mailbox.has_mail()); + assert!(producer.post(addr, Payload(vec![7]))); + producer.finish(StreamEnd::Done); + let second = mailbox.take(); + match &first[0].event { + StreamEvent::Post(payload) => assert_eq!(payload.0.as_ptr(), original), + _ => panic!("expected payload"), + } + assert_eq!(second.len(), 2); + assert!(matches!(second[1].event, StreamEvent::End(StreamEnd::Done))); +} + +#[test] +fn stream_port_terminal_never_overtakes_concurrent_posts() { + for _ in 0..100 { + let (port, addr, _, mailbox) = fixture(); + let producer = port.start().unwrap(); + let barrier = Arc::new(std::sync::Barrier::new(2)); + let worker_barrier = Arc::clone(&barrier); + let worker = std::thread::spawn(move || { + worker_barrier.wait(); + for i in 0..10 { producer.post(addr, i); } + producer.finish(StreamEnd::Done); + }); + barrier.wait(); + port.done(addr, StreamEnd::Done); + worker.join().unwrap(); + let batch = mailbox.take(); + assert!(matches!(batch.last().unwrap().event, StreamEvent::End(StreamEnd::Done))); + assert_eq!(batch.iter().filter(|landing| matches!(landing.event, StreamEvent::End(_))).count(), 1); + } +} + +#[test] +fn stream_port_start_and_cancel_compete_across_threads() { + for _ in 0..100 { + let (port, _, _, mailbox) = fixture::(); + let barrier = Arc::new(std::sync::Barrier::new(2)); + let other = port.clone(); + let sync = Arc::clone(&barrier); + let worker = std::thread::spawn(move || { + sync.wait(); + if let Some(producer) = other.start() { + if producer.is_cancelled() { producer.finish(StreamEnd::Cancelled); } + else { producer.finish(StreamEnd::Done); } + } + }); + barrier.wait(); + port.cancel(); + worker.join().unwrap(); + let batch = mailbox.take(); + assert_eq!(batch.len(), 1); + assert!(matches!(batch[0].event, StreamEvent::End(StreamEnd::Done | StreamEnd::Cancelled))); + assert!(batch[0].ack_terminal()); + } +} diff --git a/rust-modules/data/src/viewstate.rs b/rust-modules/data/src/viewstate.rs index cb21305c3c..ab77d1d157 100644 --- a/rust-modules/data/src/viewstate.rs +++ b/rust-modules/data/src/viewstate.rs @@ -580,7 +580,7 @@ pub fn finish_view_write_job( // watched/unwatched pair could then settle differently per server, which is the one thing // this whole feature exists to stop. let also = if req.w.propagates() { - fan_out(origin, clients, req.sid, &req.rk, &req.guid, req.w) + fan_out(origin, clients, &req.keys, req.sid, &req.rk, &req.guid, req.w) } else { Vec::new() }; @@ -788,7 +788,7 @@ impl ViewStateState { keys: &ClientKeys, profile: u32) -> bool { // One server has no other copy to reach: the request would only cost a second hub refetch. let Some(key) = keys.key(sid) else { return false }; - if plx_plex::plex::server_ids().nth(1).is_none() + if keys.slots().nth(1).is_none() || self.queue.iter().chain(self.sent.iter()).any(|r| plx_plex::plex::same_item((r.sid, &r.rk), (sid, rk))) { return false; @@ -1189,12 +1189,13 @@ type Answer = (ServerId, Option>); fn fan_out( c: &plx_plex::plex::Client, clients: KeyedClients<'_>, + keys: &ClientKeys, sid: ServerId, rk: &str, guid: &str, w: Write, ) -> Vec<(ServerId, String)> { - let sources: Vec = plx_plex::plex::server_ids().collect(); + let sources: Vec = keys.slots().collect(); if sources.len() < 2 { // A one-server install pays NOTHING for this feature: no guid lookup, no query, no line in // the log. Checked before the lookup below for exactly that reason. @@ -1440,7 +1441,7 @@ mod tests { /// `(rk, watched, unwatched, resume_ms)` of every Search row, in shelf order. fn search_marks(stores: &crate::stores::Stores) -> Vec<(String, bool, bool, i64)> { let directory = crate::stores::browse::DirectorySnapshot::default(); - let snap = stores.search_snapshot(directory.view(), &[]); + let snap = stores.search_snapshot_for_test(directory.view(), &[]); snap.view().shelves().iter().flat_map(|s| &s.items).filter_map(|it| match it { crate::search::Item::Media(m) => Some((m.rk.clone(), m.watched, m.unwatched, m.resume_ms)), _ => None, @@ -1493,7 +1494,7 @@ mod tests { let (mut stores, sid) = search_with_show_and_episodes(); let directory = crate::stores::browse::DirectorySnapshot::default(); let run = |stores: &mut crate::stores::Stores, rk: &str, edit| { - stores.search_run(crate::stores::search::SearchCmd::ApplyView { at: ViewAt::leaf(sid, rk), edit }, directory.view()) + stores.search_run_for_test(crate::stores::search::SearchCmd::ApplyView { at: ViewAt::leaf(sid, rk), edit }, directory.view()) }; let facts = ViewEdit::Facts { watched: true, unwatched: false, resume_ms: 0, sort: None }; assert!(run(&mut stores, "other", facts), "the server says watched: the row changes"); @@ -1518,7 +1519,7 @@ mod tests { let (mut stores, sid) = search_with_show_and_episodes(); let directory = crate::stores::browse::DirectorySnapshot::default(); for rk in ["e11", "e12", "e21"] { - stores.search_run(crate::stores::search::SearchCmd::ApplyView { + stores.search_run_for_test(crate::stores::search::SearchCmd::ApplyView { at: ViewAt::leaf(sid, rk), edit: ViewEdit::Watched(true) }, directory.view()); } assert!(stores.viewstate_run(crate::stores::viewstate::ViewStateCmd::Request { @@ -2577,3 +2578,7 @@ mod sort_caption_reconcile_tests { assert_eq!(WatchSortFacts::of(&row), Some(sort), "a legacy cached row can receive the new facts"); } } + +#[cfg(test)] +#[path = "viewstate_captured_inputs_tests.rs"] +mod captured_inputs_tests; diff --git a/rust-modules/data/src/viewstate_captured_inputs_tests.rs b/rust-modules/data/src/viewstate_captured_inputs_tests.rs new file mode 100644 index 0000000000..c28c33f545 --- /dev/null +++ b/rust-modules/data/src/viewstate_captured_inputs_tests.rs @@ -0,0 +1,37 @@ +use super::*; +use crate::captured_store_fixture::{key, roster}; +#[test] +fn origin_fanout_counts_registered_captured_slots_not_eligible_or_ambient_slots() { + let _serial = plx_base::testlock::serial(); + let sid = ServerId::from_raw(61); + let one = roster(&[(61, Some(key(1)), "")], 3, 4); + let two = roster(&[(61, Some(key(1)), ""), (101, None, "unkeyed")], 3, 4); + let adapter = Arc::new(ViewStateAdapter::default()); + let mut state = ViewStateState::default(); + assert!(!state.fan_out_origin_watched(&adapter, sid, "4", &one, 7)); + assert!(state.fan_out_origin_watched(&adapter, sid, "4", &two, 7), "a registered unkeyed destination still makes this a multi-source observation"); + let StoreJob::ViewWrite(job, _) = state.jobs.pop().unwrap() else { panic!("view write") }; + assert!(job.req.origin_done); + assert_eq!(job.req.sid, sid); + assert_eq!(job.req.keys.slots().map(|s| s.raw()).collect::>(), [61, 101]); + assert_eq!(job.req.keys.iter().count(), 1); + let missing = roster(&[(61, None, ""), (101, Some(key(2)), "friend")], 3, 4); + let mut refused = ViewStateState::default(); + assert!(!refused.fan_out_origin_watched(&adapter, sid, "4", &missing, 7)); + assert!(refused.jobs.is_empty(), "missing origin input is not filled from the registry"); +} +#[test] +fn worker_one_captured_slot_never_queries_even_when_ambient_has_two() { + fn forbidden(_: ServerId) -> Option<&'static Client> { panic!("the captured one-server job must not look up any destination") } + let _serial = plx_base::testlock::serial(); + plx_plex::plex::reset_servers_for_test(); + let origin = plx_plex::plex::register_for_test("ambient-origin", "127.0.0.1", 9, "token", "cid"); + plx_plex::plex::register_for_test("ambient-other", "127.0.0.1", 9, "token", "cid"); + let client = plx_plex::plex::client_for(origin).unwrap(); + let keys = roster(&[(61, Some(key(1)), "")], 3, 4); + let result = fan_out(client, KeyedClients::new(&keys, forbidden), &keys, + ServerId::from_raw(61), "4", "", Write::Watched); + assert!(result.is_empty()); + assert_eq!(plx_plex::plex::server_ids().count(), 2, "scripted observations never rewrite ambient state"); + plx_plex::plex::reset_servers_for_test(); +} diff --git a/rust-modules/data/src/watchlist.rs b/rust-modules/data/src/watchlist.rs index 6c605711a3..c603b81e2f 100644 --- a/rust-modules/data/src/watchlist.rs +++ b/rust-modules/data/src/watchlist.rs @@ -16,7 +16,7 @@ pub mod order; use ledger::{Intent, PendingWrite, WriteOutcome}; use model::{Asked, Kind, Reach, ServerMatch, WatchRow}; -use plx_plex::plex::account::AccountClient; + use plx_plex::plex::session::{CurrentProfile, UserRef}; use plx_plex::plex::watchlist::{WatchItem, WatchKind, WatchPage, WatchlistError, MAX_PAGE}; use plx_plex::plex::{GuidKind, GuidLookupError, GuidMatch, ServerId, GUIDS_PER_REQUEST}; @@ -48,9 +48,11 @@ impl WatchlistAuth { && now.user.as_ref().is_some_and(|u| u.id == self.user.id && u.uuid == self.user.uuid) } - fn client(&self) -> AccountClient { - AccountClient::new(&self.client_id, Some(&self.credential)) + pub fn matches_lease(&self, profile: &CurrentProfile, credential: Option<&str>) -> bool { + self.is_current(profile) && credential == Some(self.credential.as_str()) } + + } /// **What the app reads from the session for the two plex.tv stores (docs/sans-io.md S5):** the @@ -106,8 +108,8 @@ impl WatchlistInput { } } -/// Everything a worker (and the store's frame pass) asks of the outside world. Production is -/// [`LiveIo`]; tests script it. `Reach` carries the roster and the reachability facts. +/// Worker transport plus captured facts. The job wrapper supplies `Reach`, generations and +/// today from its request; the narrow live port or a script supplies transport responses. pub trait WatchlistIo: Reach + Send + Sync { /// One page of the list. `if_none_match` is the `ETag` of the last COMPLETE read, handed over /// for page 0 only; an answer of `Err(WatchlistError::NotModified)` is the service saying the @@ -123,82 +125,13 @@ pub trait WatchlistIo: Reach + Send + Sync { fn facts_gen(&self) -> u32; /// Today as `YYYY-MM-DD` (UTC), the fallback "coming soon" test when the released list failed. fn today(&self) -> Option; - /// WORKER THREAD. The `guid` of the item `rk` on `server`'s own record - /// (`client.metadata(rk).guid`): what a card row that carried no catalog id is resolved by - /// (`plex::resolve_catalog_hex`). `None` when the server did not answer (the caller then forgets the - /// attempt and asks again at the next menu; a guid that is not portable answers `Some`). The default answers - /// nothing, so a script that never resolves needs no line for it. - fn guid_of(&self, _server: ServerId, _rk: &str) -> Option { - None - } -} - -/// The production seam: libcurl through `plex::watchlist`, matching through the registered -/// servers' clients, reachability from the probe results. -pub struct LiveIo; -impl Reach for LiveIo { - fn reachable(&self, server: ServerId) -> bool { - matches!(plx_plex::plex::server_probe_result(server), Some(plx_plex::plex::probe::Outcome::Reachable)) - } - fn roster(&self) -> Vec { - plx_plex::plex::server_ids().collect() - } - fn copy_rank(&self, server: ServerId) -> u8 { - if plx_plex::plex::current_server() == server { - 0 - } else if plx_plex::plex::server_facts(server).is_some_and(|f| f.owned) { - 1 - } else { - 2 - } - } } -impl WatchlistIo for LiveIo { - fn page(&self, auth: &WatchlistAuth, start: u32, size: u32, if_none_match: Option<&str>) - -> Result - { - let client = auth.client(); - let mut transport = client.watchlist_transport(); - let answer = client.watchlist_page(start, size, if_none_match, &mut transport); - answer - } - fn released(&self, auth: &WatchlistAuth) -> Result, WatchlistError> { - let client = auth.client(); - let mut transport = client.watchlist_transport(); - let answer = client.watchlist_released(&mut transport); - answer - } - fn write(&self, auth: &WatchlistAuth, hex: &str, intent: Intent) -> Result<(), WatchlistError> { - let client = auth.client(); - let mut transport = client.watchlist_transport(); - let answer = match intent { - Intent::Add => client.watchlist_add(hex, &mut transport), - Intent::Remove => client.watchlist_remove(hex, &mut transport), - }; - answer - } - fn find(&self, server: ServerId, kind: GuidKind, guids: &[String]) -> Result, GuidLookupError> { - plx_plex::plex::client_for(server).ok_or(GuidLookupError::Unanswered)?.find_by_guids(kind, guids) - } - fn roster_gen(&self) -> u32 { - plx_plex::plex::server_roster_gen() - } - fn facts_gen(&self) -> u32 { - plx_plex::plex::server_facts_gen() - } - fn guid_of(&self, server: ServerId, rk: &str) -> Option { - plx_plex::plex::client_for(server)?.metadata(rk).map(|m| m.guid) - } - fn today(&self) -> Option { - let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(); - Some(ymd_of_unix_days((secs / 86_400) as i64)) - } -} + /// Civil date of a day count since 1970-01-01 (Howard Hinnant's algorithm). -fn ymd_of_unix_days(days: i64) -> String { +pub fn ymd_of_unix_days(days: i64) -> String { let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z.rem_euclid(146_097); @@ -395,7 +328,8 @@ pub fn match_on(io: &dyn WatchlistIo, sid: ServerId, rows: &[(String, Kind)]) -> /// WORKER THREAD: read the list. Page 0, then the released set, then the remaining pages until /// the server's own end (`start` reaches `totalSize`, a short page, or an empty one); each page is -/// matched against the servers before it is posted so a tile arrives with its state. Stops at the first page that fails. Always ends with [`What::ListDone`]. +/// matched against the servers before it is posted so a tile arrives with its state. Stops at +/// the first page that fails; the owned stream worker owes the terminal completion. /// `known` is the guids already matched against every reachable server under roster generation /// `known.1`; they are skipped while the roster has not moved (a new roster is a full re-match). /// `etag` is the validator of the last complete read (`If-None-Match` on page 0 only): when the @@ -457,7 +391,7 @@ pub fn run_list( } page_no += 1; } - post(Landed { tag, what: What::ListDone }); + } /// WORKER THREAD: the full re-match of `rows` after the roster moved. @@ -501,6 +435,21 @@ mod tests { assert_eq!(ymd_of_unix_days(20_001), "2024-10-05"); } + #[test] + fn auth_lease_requires_the_same_profile_and_current_credential() { + let input = WatchlistInput::for_test(9); + let auth = input.auth().unwrap(); + assert!(auth.matches_lease(input.profile(), Some("test-credential"))); + assert!(!auth.matches_lease(input.profile(), Some("rotated-credential"))); + assert!(!auth.matches_lease(input.profile(), None)); + let other = WatchlistInput::profile_for_test(10); + assert!(!auth.matches_lease(&other, Some("test-credential"))); + let mut user = input.profile().user.clone().unwrap(); + user.uuid = "different".into(); + let other = CurrentProfile { user: Some(user), generation: 9, stamp: String::new() }; + assert!(!auth.matches_lease(&other, Some("test-credential"))); + } + #[test] fn the_auth_debug_form_hides_the_credential() { let a = WatchlistAuth { diff --git a/rust-modules/machine/src/job.rs b/rust-modules/machine/src/job.rs index fb82a6972d..ac7527875d 100644 --- a/rust-modules/machine/src/job.rs +++ b/rust-modules/machine/src/job.rs @@ -59,6 +59,8 @@ pub trait Port: Send + Sync + 'static { /// Assert that a step emitted exactly these jobs, in this order. `$got` is the `Vec` the step's /// owner hands back (`take_jobs()`), the list holds the expected values. +/// With `stamped [(emitter, effect_pattern), ...]`, assert the complete stamped buffer instead, +/// allowing pattern guards without requiring `Eq` or `Debug` on application effects. /// /// ```ignore /// assert_fx!(store.take_jobs(), [StoreJob::Detail(Job { addr, req }, store.detail_port())]); @@ -66,6 +68,21 @@ pub trait Port: Send + Sync + 'static { /// ``` #[macro_export] macro_rules! assert_fx { + ($actual:expr, stamped [$(($from:expr, $pattern:pat $(if $guard:expr)?)),* $(,)?]) => {{ + let actual = &$actual; + let mut effects = actual.iter(); + let total = actual.len(); + $( + let index = total - effects.len(); + let observed = effects.next().unwrap_or_else(|| panic!("missing effect at index {}", index)); + assert_eq!(observed.from, $from, "wrong emitter at effect index {}", index); + assert!(matches!(&observed.fx, $pattern $(if $guard)?), + "wrong effect at index {}: expected {}", index, stringify!($pattern)); + + )* + let consumed = total - effects.len(); + assert!(effects.next().is_none(), "extra effect at index {}", consumed); + }}; ($got:expr, [$($want:expr),* $(,)?]) => {{ let got: Vec<_> = $got; let want: Vec<_> = vec![$($want),*]; @@ -87,6 +104,7 @@ mod tests { fn assert_fx_passes_on_exactly_the_jobs_in_order() { assert_fx!(vec![job(1, "a"), job(2, "b")], [job(1, "a"), job(2, "b")]); assert_fx!(Vec::>::new(), []); + assert_fx!(vec![(1, "a")], [(1, "a")]); } #[test] diff --git a/rust-modules/machine/src/machine.rs b/rust-modules/machine/src/machine.rs index e09ef999c1..10f5f912f6 100644 --- a/rust-modules/machine/src/machine.rs +++ b/rust-modules/machine/src/machine.rs @@ -392,6 +392,8 @@ pub struct Stamped { pub fx: Fx, } +// Job-value and stamped-effect assertions share crate::assert_fx! from job.rs. + /// A single machine emitting more than this in one `step` is a debug assertion (§3.3 step 6). pub const MAX_EMIT_PER_STEP: u32 = 32; @@ -1059,6 +1061,35 @@ mod canon_tests { type Memory = (); } + #[test] + fn assert_fx_checks_stamp_order_absence_and_extras_without_effect_traits() { + let mut buf: Vec> = Vec::new(); + let mut present = Present::new(); + { + let _step = plx_base::step::StepScope::enter(); + let mut fx = Effects::new(&mut buf, MachineId::Nav, &mut present); + fx.push(Fx::Timer { id: TimerId(7), after_ms: 40 }); + fx.push(Fx::App(())); + } + crate::assert_fx!(&buf, stamped [(MachineId::Nav, Fx::Timer { id, after_ms: 40 } if *id == TimerId(7)), + (MachineId::Nav, Fx::App(()))]); + let empty: Vec> = Vec::new(); + crate::assert_fx!(&empty, stamped []); + use std::panic::{catch_unwind, AssertUnwindSafe}; + assert!(catch_unwind(AssertUnwindSafe(|| crate::assert_fx!(&empty, stamped + [(MachineId::Nav, Fx::App(()))]))).is_err()); + assert!(catch_unwind(AssertUnwindSafe(|| crate::assert_fx!(&buf, stamped []))).is_err()); + assert!(catch_unwind(AssertUnwindSafe(|| crate::assert_fx!(&buf, stamped + [(MachineId::Nav, Fx::App(())), (MachineId::Nav, Fx::Timer { .. })]))).is_err()); + assert!(catch_unwind(AssertUnwindSafe(|| crate::assert_fx!(&buf, stamped + [(MachineId::Nav, Fx::Timer { .. })]))).is_err()); + buf[0].from = MachineId::Instance(InstanceId(17)); + assert!(catch_unwind(AssertUnwindSafe(|| crate::assert_fx!(&buf, stamped + [(MachineId::Nav, Fx::Timer { .. }), (MachineId::Nav, Fx::App(()))]))).is_err()); + crate::assert_fx!(&buf, stamped [(MachineId::Instance(InstanceId(17)), Fx::Timer { .. }), + (MachineId::Nav, Fx::App(()))]); + } + #[test] fn the_effect_sink_counts_emissions_per_step() { // A sink over a plain buffer: no real host needed to prove the count and the stamp. diff --git a/rust-modules/media/src/player/attempt_metrics.rs b/rust-modules/media/src/player/attempt_metrics.rs index 6fba97bf80..acead0a799 100644 --- a/rust-modules/media/src/player/attempt_metrics.rs +++ b/rust-modules/media/src/player/attempt_metrics.rs @@ -1,3 +1,4 @@ +#![deny(clippy::wildcard_enum_match_arm)] //! Pure, local playback-attempt measurements. A logical request may try several physical //! backends; their identities come from the route owner. This reducer neither mints an attempt //! nor reads a clock, player registry, recorder, consent setting, URL, or user content. A caller @@ -44,16 +45,7 @@ pub struct SeenEvidence { pub clock_advanced: bool, pub picture_presented: bool, } -impl SeenEvidence { - fn observe(&mut self, evidence: Evidence) { - match evidence { - Evidence::CommandAcknowledged => self.command_acknowledged = true, - Evidence::PlaybackObserved => self.playback_observed = true, - Evidence::ClockAdvanced => self.clock_advanced = true, - Evidence::PicturePresented => self.picture_presented = true, - } - } -} + /// What the viewer or backend is doing during the next interval. Unknown and intentional /// pause/seek/hold time is never charged to involuntary rebuffer or handoff stall. @@ -190,7 +182,18 @@ impl AttemptSummary { /// route-owned physical identity such as `crate::route::RouteStartAttempt`; the reducer creates /// neither. IDs must increase in the owner's canonical order. Persisted high-water marks reject /// replay even after bounded history evicts an old summary. Completed summaries leave as effects. -pub struct AttemptMetrics { +/// IDs are data, not mutable capabilities. This closed bound keeps borrowed summaries inert. +pub trait Identity: Copy + Ord + identity::Sealed {} +mod identity { + pub trait Sealed {} + impl Sealed for u64 {} + impl Sealed for super::super::backend::LogicalRequestId {} + impl Sealed for plx_playback_contract::AttemptId {} +} +impl Identity for u64 {} +impl Identity for super::backend::LogicalRequestId {} +impl Identity for plx_playback_contract::AttemptId {} +pub struct AttemptMetrics { request: Option>, last_request_id: Option, last_attempt_id: Option, @@ -204,11 +207,11 @@ pub struct AttemptMetrics { pending_refusal: Option<(A, Backend)>, } -impl Default for AttemptMetrics { +impl Default for AttemptMetrics { fn default() -> Self { Self::new() } } -impl AttemptMetrics { +impl AttemptMetrics { pub const fn new() -> Self { Self { request: None, last_request_id: None, last_attempt_id: None, @@ -230,118 +233,147 @@ impl AttemptMetrics { } } - fn advance(&mut self, to: Tick) -> bool { - let Tick::Known(to) = to else { - // An unavailable clock breaks the interval. The next known tick starts a new - // anchor; no duration is invented for the unknown span. - self.time_anchor = None; - if let Some(request) = self.request.as_mut().filter(|r| r.outcome.is_none()) { - request.unknown_time_events = request.unknown_time_events.saturating_add(1); - } - self.request_start_clock_known = false; - self.attempt_start_clock_known = false; - return true; - }; - if self.last_known_tick.is_some_and(|last| to < last) { return false; } - let elapsed = self.time_anchor.map_or(0, |from| to - from); - if let Some(request) = self.request.as_mut().filter(|r| r.outcome.is_none()) { - let eligible = self.condition.eligible(); - let rebuffer = eligible && self.condition == Condition::Rebuffering && request.first_picture_at.is_some(); - let handoff = eligible && self.handoff.is_some(); - if rebuffer { request.rebuffer_ms = request.rebuffer_ms.saturating_add(elapsed); } - if handoff { request.handoff_gap_ms = request.handoff_gap_ms.saturating_add(elapsed); } - if rebuffer || handoff { - request.involuntary_stall_ms = request.involuntary_stall_ms.saturating_add(elapsed); - } - } - self.last_known_tick = Some(to); - self.time_anchor = Some(to); - true - } - - fn save_attempt(request: &mut RequestSummary, mut attempt: AttemptSummary) { - if attempt.outcome.is_none() { - attempt.outcome = Some(if attempt.first_picture_at.is_some() { - AttemptOutcome::Superseded - } else { AttemptOutcome::Unconfirmed }); - } - if request.recent_attempts.len() == MAX_ATTEMPT_HISTORY { request.recent_attempts.remove(0); } - request.recent_attempts.push(attempt); + pub fn step(&mut self, event: Event, effects: &mut Vec>) { + self.transition(event, effects); } - fn finish(&mut self, outcome: RequestOutcome, effects: &mut Vec>) { - let Some(request) = self.request.as_mut().filter(|r| r.outcome.is_none()) else { return }; - // An End without independent picture evidence is an unconfirmed playback, never a - // successful completion. Explicit failure and cancellation retain their own classes. - let outcome = if outcome == RequestOutcome::Ended && request.first_picture_at.is_none() { - RequestOutcome::Unconfirmed - } else { outcome }; - if let Some(attempt) = request.current_attempt.as_mut() { - if attempt.outcome.is_none() { - attempt.outcome = Some(match outcome { - RequestOutcome::Ended if attempt.first_picture_at.is_some() => AttemptOutcome::Ended, - RequestOutcome::Ended => AttemptOutcome::Unconfirmed, - RequestOutcome::Failed(failure) => AttemptOutcome::Failed(failure), - RequestOutcome::Cancelled => AttemptOutcome::Cancelled, - RequestOutcome::Unconfirmed => AttemptOutcome::Unconfirmed, - RequestOutcome::Replaced => AttemptOutcome::Superseded, - }); - } - } - request.outcome = Some(outcome); - if let RequestOutcome::Failed(failure) = outcome { - effects.push(Fx::HandledError { - request: request.id, - attempt: request.current_attempt.map(|a| a.id), - backend: request.current_attempt.map_or(Backend::Unknown, |a| a.backend), - failure, - }); - } - effects.push(Fx::Finished(request.clone())); - self.handoff = None; - self.pending_refusal = None; - } - pub fn step(&mut self, event: Event, effects: &mut Vec>) { + fn transition(&mut self, event: Event, effects: &mut Vec>) { // Address validation precedes time accounting. A late answer must not extend the // newer request's stall merely because it carries a later timestamp. let admitted = match &event { Event::RequestStarted { request, .. } => self.last_request_id.is_none_or(|last| *request > last), - Event::RequestFinished { request, .. } => self.request.as_ref().is_some_and(|r| r.id == *request && r.outcome.is_none()), + Event::RequestFinished { request, .. } => { + self.request.as_ref().is_some_and(|r| r.id == *request && r.outcome.is_none()) + } Event::AttemptStarted { request, attempt, .. } => self.request.as_ref().is_some_and(|r| { - r.id == *request && r.outcome.is_none() + r.id == *request + && r.outcome.is_none() && self.last_attempt_id.is_none_or(|last| *attempt > last) && !r.current_attempt.is_some_and(|a| a.id == *attempt) && !r.recent_attempts.iter().any(|a| a.id == *attempt) }), - Event::Evidence { request, attempt, .. } | Event::Condition { request, attempt, .. } + Event::Evidence { request, attempt, .. } + | Event::Condition { request, attempt, .. } | Event::AttemptFinished { request, attempt, .. } => self.request.as_ref().is_some_and(|r| { - r.id == *request && r.outcome.is_none() + r.id == *request + && r.outcome.is_none() && r.current_attempt.is_some_and(|a| a.id == *attempt && a.outcome.is_none()) }), Event::HandoffBegun { request, from, .. } => self.request.as_ref().is_some_and(|r| { - r.id == *request && r.outcome.is_none() + r.id == *request + && r.outcome.is_none() && r.current_attempt.is_some_and(|a| a.id == *from) && self.handoff.is_none() }), Event::Handoff { request, from, to, .. } => self.request.as_ref().is_some_and(|r| { - r.id == *request && r.outcome.is_none() && to > from + r.id == *request + && r.outcome.is_none() + && to > from && r.current_attempt.is_some_and(|a| a.id == *from) - && self.handoff.is_none() && self.last_handoff_to != Some(*to) + && self.handoff.is_none() + && self.last_handoff_to != Some(*to) }), }; - if !admitted { return; } + if !admitted { + return; + } let at = event.at(); - if !self.advance(at) { return; } + if let Tick::Known(to) = at { + if self.last_known_tick.is_some_and(|last| to < last) { + return; + } + let elapsed = self.time_anchor.map_or(0, |from| to - from); + if let Some(request) = self.request.as_mut().filter(|r| r.outcome.is_none()) { + let eligible = self.condition.eligible(); + let rebuffer = eligible && self.condition == Condition::Rebuffering && request.first_picture_at.is_some(); + let handoff = eligible && self.handoff.is_some(); + if rebuffer { + request.rebuffer_ms = request.rebuffer_ms.saturating_add(elapsed); + } + if handoff { + request.handoff_gap_ms = request.handoff_gap_ms.saturating_add(elapsed); + } + if rebuffer || handoff { + request.involuntary_stall_ms = request.involuntary_stall_ms.saturating_add(elapsed); + } + } + self.last_known_tick = Some(to); + self.time_anchor = Some(to); + } else { + // An unavailable clock breaks the interval. The next known tick starts a new + // anchor; no duration is invented for the unknown span. + self.time_anchor = None; + if let Some(request) = self.request.as_mut().filter(|r| r.outcome.is_none()) { + request.unknown_time_events = request.unknown_time_events.saturating_add(1); + } + self.request_start_clock_known = false; + self.attempt_start_clock_known = false; + } + let finish = match &event { + Event::RequestStarted { .. } => Some(RequestOutcome::Replaced), + Event::RequestFinished { outcome, .. } => Some(*outcome), + Event::AttemptStarted { .. } + | Event::Evidence { .. } + | Event::Condition { .. } + | Event::HandoffBegun { .. } + | Event::Handoff { .. } + | Event::AttemptFinished { .. } => None, + }; + if let Some(outcome) = finish { + if let Some(request) = self.request.as_mut().filter(|r| r.outcome.is_none()) { + // An End without independent picture evidence is an unconfirmed playback, never a + // successful completion. Explicit failure and cancellation retain their own classes. + let outcome = if outcome == RequestOutcome::Ended && request.first_picture_at.is_none() { + RequestOutcome::Unconfirmed + } else { + outcome + }; + if let Some(attempt) = request.current_attempt.as_mut() { + if attempt.outcome.is_none() { + attempt.outcome = Some(match outcome { + RequestOutcome::Ended if attempt.first_picture_at.is_some() => AttemptOutcome::Ended, + RequestOutcome::Ended => AttemptOutcome::Unconfirmed, + RequestOutcome::Failed(failure) => AttemptOutcome::Failed(failure), + RequestOutcome::Cancelled => AttemptOutcome::Cancelled, + RequestOutcome::Unconfirmed => AttemptOutcome::Unconfirmed, + RequestOutcome::Replaced => AttemptOutcome::Superseded, + }); + } + } + request.outcome = Some(outcome); + if let RequestOutcome::Failed(failure) = outcome { + effects.push(Fx::HandledError { + request: request.id, + attempt: request.current_attempt.map(|a| a.id), + backend: request.current_attempt.map_or(Backend::Unknown, |a| a.backend), + failure, + }); + } + effects.push(Fx::Finished(request.clone())); + self.handoff = None; + self.pending_refusal = None; + } + } match event { Event::RequestStarted { request, origin, at } => { - if self.request.as_ref().is_some_and(|old| old.id == request) { return; } - self.finish(RequestOutcome::Replaced, effects); + if self.request.as_ref().is_some_and(|old| old.id == request) { + return; + } self.request = Some(RequestSummary { - id: request, origin, started_at: at, first_picture_at: None, startup_ms: None, + id: request, + origin, + started_at: at, + first_picture_at: None, + startup_ms: None, outcome: None, - attempt_count: 0, recent_attempts: Vec::new(), current_attempt: None, - rebuffer_count: 0, rebuffer_ms: 0, handoff_count: 0, handoff_gap_ms: 0, + attempt_count: 0, + recent_attempts: Vec::new(), + current_attempt: None, + rebuffer_count: 0, + rebuffer_ms: 0, + handoff_count: 0, + handoff_gap_ms: 0, involuntary_stall_ms: 0, unknown_time_events: u32::from(at == Tick::Unknown), }); @@ -349,26 +381,44 @@ impl AttemptMetrics { self.last_attempt_id = None; self.condition = Condition::Unknown; self.time_anchor = at.as_millis(); - if let Some(ms) = at.as_millis() { self.last_known_tick = Some(ms); } + if let Some(ms) = at.as_millis() { + self.last_known_tick = Some(ms); + } self.request_start_clock_known = at.as_millis().is_some(); self.attempt_start_clock_known = false; self.handoff = None; self.last_handoff_to = None; self.pending_refusal = None; } - Event::RequestFinished { request, outcome, .. } => { - if self.request.as_ref().is_some_and(|r| r.id == request) { self.finish(outcome, effects); } - } + Event::RequestFinished { .. } => {} Event::AttemptStarted { request, attempt, backend, origin, at } => { let Some(r) = self.request.as_mut().filter(|r| r.id == request && r.outcome.is_none()) else { return }; - if r.current_attempt.is_some_and(|a| a.id == attempt) - || r.recent_attempts.iter().any(|a| a.id == attempt) { return; } - if let Some(old) = r.current_attempt.take() { Self::save_attempt(r, old); } + if r.current_attempt.is_some_and(|a| a.id == attempt) || r.recent_attempts.iter().any(|a| a.id == attempt) { + return; + } + if let Some(mut attempt) = r.current_attempt.take() { + if attempt.outcome.is_none() { + attempt.outcome = Some(if attempt.first_picture_at.is_some() { + AttemptOutcome::Superseded + } else { + AttemptOutcome::Unconfirmed + }); + } + if r.recent_attempts.len() == MAX_ATTEMPT_HISTORY { + r.recent_attempts.remove(0); + } + r.recent_attempts.push(attempt); + } r.attempt_count = r.attempt_count.saturating_add(1); r.current_attempt = Some(AttemptSummary { - id: attempt, backend, origin, started_at: at, first_picture_at: None, + id: attempt, + backend, + origin, + started_at: at, + first_picture_at: None, startup_ms: None, - evidence: SeenEvidence::default(), outcome: None, + evidence: SeenEvidence::default(), + outcome: None, }); self.last_attempt_id = Some(attempt); self.attempt_start_clock_known = at.as_millis().is_some(); @@ -376,19 +426,25 @@ impl AttemptMetrics { Event::Evidence { request, attempt, evidence, at } => { let Some(r) = self.request.as_mut().filter(|r| r.id == request && r.outcome.is_none()) else { return }; let Some(current) = r.current_attempt.as_mut().filter(|a| a.id == attempt && a.outcome.is_none()) else { return }; - current.evidence.observe(evidence); - if evidence != Evidence::PicturePresented || current.first_picture_at.is_some() { return; } + match evidence { + Evidence::CommandAcknowledged => current.evidence.command_acknowledged = true, + Evidence::PlaybackObserved => current.evidence.playback_observed = true, + Evidence::ClockAdvanced => current.evidence.clock_advanced = true, + Evidence::PicturePresented => current.evidence.picture_presented = true, + } + if evidence != Evidence::PicturePresented || current.first_picture_at.is_some() { + return; + } current.first_picture_at = Some(at); if self.attempt_start_clock_known { - current.startup_ms = current.started_at.as_millis() - .zip(at.as_millis()).map(|(start, end)| end.saturating_sub(start)); + current.startup_ms = + current.started_at.as_millis().zip(at.as_millis()).map(|(start, end)| end.saturating_sub(start)); } let first_for_request = r.first_picture_at.is_none(); if first_for_request { r.first_picture_at = Some(at); if self.request_start_clock_known { - r.startup_ms = r.started_at.as_millis() - .zip(at.as_millis()).map(|(start, end)| end.saturating_sub(start)); + r.startup_ms = r.started_at.as_millis().zip(at.as_millis()).map(|(start, end)| end.saturating_sub(start)); } } // Startup buffering becomes rebuffering only after the first picture; an @@ -401,15 +457,23 @@ impl AttemptMetrics { } // A failed first target may be followed by another physical try. The gap // ends at the first successor picture, not only the original target's. - if self.handoff.is_some_and(|h| h.from != attempt) { self.handoff = None; } + if self.handoff.is_some_and(|h| h.from != attempt) { + self.handoff = None; + } if let Some((refused_attempt, backend)) = self.pending_refusal.take().filter(|(old, _)| *old != attempt) { - effects.push(Fx::RecoveredRefusal { request, refused_attempt, recovered_attempt: attempt, refused_backend: backend }); + effects.push(Fx::RecoveredRefusal { + request, + refused_attempt, + recovered_attempt: attempt, + refused_backend: backend, + }); } } Event::Condition { request, attempt, condition, at } => { let Some(r) = self.request.as_mut().filter(|r| r.id == request && r.outcome.is_none()) else { return }; let Some(current) = r.current_attempt.filter(|a| a.id == attempt && a.outcome.is_none()) else { return }; - if condition == Condition::Rebuffering && self.condition != Condition::Rebuffering && r.first_picture_at.is_some() { + if condition == Condition::Rebuffering && self.condition != Condition::Rebuffering && r.first_picture_at.is_some() + { r.rebuffer_count = r.rebuffer_count.saturating_add(1); effects.push(Fx::Incident(current.record(request, current.proven_stage(), Incident::Rebuffer, at))); } @@ -418,7 +482,9 @@ impl AttemptMetrics { Event::HandoffBegun { request, from, at } => { let Some(r) = self.request.as_mut().filter(|r| r.id == request && r.outcome.is_none()) else { return }; let Some(source) = r.current_attempt.filter(|a| a.id == from) else { return }; - if self.handoff.is_some() { return; } + if self.handoff.is_some() { + return; + } r.handoff_count = r.handoff_count.saturating_add(1); self.handoff = Some(Handoff { from }); effects.push(Fx::Incident(source.record(request, Self::handoff_stage(&source), Incident::Handoff, at))); @@ -426,7 +492,9 @@ impl AttemptMetrics { Event::Handoff { request, from, to, at } => { let Some(r) = self.request.as_mut().filter(|r| r.id == request && r.outcome.is_none()) else { return }; let Some(source) = r.current_attempt.filter(|a| a.id == from) else { return }; - if to <= from || self.handoff.is_some() || self.last_handoff_to == Some(to) { return; } + if to <= from || self.handoff.is_some() || self.last_handoff_to == Some(to) { + return; + } r.handoff_count = r.handoff_count.saturating_add(1); self.handoff = Some(Handoff { from }); self.last_handoff_to = Some(to); @@ -437,7 +505,9 @@ impl AttemptMetrics { let Some(current) = r.current_attempt.as_mut().filter(|a| a.id == attempt && a.outcome.is_none()) else { return }; current.outcome = Some(if outcome == AttemptOutcome::Ended && current.first_picture_at.is_none() { AttemptOutcome::Unconfirmed - } else { outcome }); + } else { + outcome + }); if let AttemptOutcome::Failed(Failure { stage, cause }) = outcome { if stage != Stage::Release { effects.push(Fx::Incident(current.record(request, stage, Incident::Failed(cause), at))); @@ -456,6 +526,55 @@ mod tests { use super::*; type Model = AttemptMetrics; fn t(ms: u64) -> Tick { Tick::from_millis(ms) } + #[test] + fn rejected_events_preserve_every_field_and_the_next_interval() { + let mut m = Model::new(); + start(&mut m, 1, 10); + send(&mut m, picture(1, 10, 10)); + send(&mut m, condition(1, 10, 20, Condition::Rebuffering)); + send(&mut m, Event::HandoffBegun { request: 1, from: 10, at: t(30) }); + let before = (m.request.clone(), m.last_request_id, m.last_attempt_id, m.condition, + m.last_known_tick, m.time_anchor, m.request_start_clock_known, m.attempt_start_clock_known, + m.handoff.map(|h| h.from), m.last_handoff_to, m.pending_refusal); + for ev in [ + Event::Evidence { request: 9, attempt: 10, evidence: Evidence::PicturePresented, at: Tick::Unknown }, + Event::AttemptStarted { request: 1, attempt: 9, backend: Backend::Feed, origin: Origin::Recovery, at: t(100) }, + condition(1, 10, 5, Condition::Paused), + ] { + assert!(send(&mut m, ev).is_empty()); + assert_eq!((m.request.clone(), m.last_request_id, m.last_attempt_id, m.condition, + m.last_known_tick, m.time_anchor, m.request_start_clock_known, m.attempt_start_clock_known, + m.handoff.map(|h| h.from), m.last_handoff_to, m.pending_refusal), before); + } + assert!(send(&mut m, condition(1, 10, 50, Condition::Playing)).is_empty()); + let s = m.snapshot().unwrap(); + assert_eq!((s.rebuffer_count, s.rebuffer_ms, s.handoff_count, s.handoff_gap_ms, s.involuntary_stall_ms), (1, 30, 1, 20, 30)); + } + + #[test] + fn terminal_effects_follow_accounting_and_precede_replacement() { + let mut m = Model::new(); + start(&mut m, 1, 10); + send(&mut m, picture(1, 10, 10)); + send(&mut m, condition(1, 10, 20, Condition::Rebuffering)); + let fx = send(&mut m, Event::RequestStarted { request: 2, origin: Origin::UserRetry, at: t(50) }); + let [Fx::Finished(old)] = fx.as_slice() else { panic!("replacement must finish the old request once") }; + assert_eq!(old.outcome, Some(RequestOutcome::Replaced)); + assert_eq!((old.rebuffer_ms, old.involuntary_stall_ms), (30, 30)); + assert_eq!(old.current_attempt.unwrap().outcome, Some(AttemptOutcome::Superseded)); + assert_eq!(m.snapshot().unwrap().id, 2); + assert_eq!(m.snapshot().unwrap().attempt_count, 0); + assert_eq!((m.last_attempt_id, m.condition, m.time_anchor), (None, Condition::Unknown, Some(50))); + send(&mut m, Event::AttemptStarted { request: 2, attempt: 20, backend: Backend::Feed, origin: Origin::UserRetry, at: t(60) }); + let failure = Failure { stage: Stage::Open, cause: Cause::Refused }; + let fx = send(&mut m, Event::RequestFinished { request: 2, outcome: RequestOutcome::Failed(failure), at: t(70) }); + assert_eq!(fx, vec![ + Fx::HandledError { request: 2, attempt: Some(20), backend: Backend::Feed, failure }, + Fx::Finished(m.snapshot().unwrap().clone()), + ]); + assert!(m.handoff.is_none() && m.pending_refusal.is_none()); + } + fn start(model: &mut Model, request: u64, attempt: u64) { let mut effects = Vec::new(); model.step(Event::RequestStarted { request, origin: Origin::Fresh, at: t(0) }, &mut effects); diff --git a/rust-modules/media/src/player/foreground.rs b/rust-modules/media/src/player/foreground.rs index d928e08e15..42cfddc223 100644 --- a/rust-modules/media/src/player/foreground.rs +++ b/rust-modules/media/src/player/foreground.rs @@ -25,7 +25,7 @@ pub enum ForegroundActivation { } pub trait ForegroundActuator { - type Attempt: Copy + PartialEq; + type Attempt: super::lifecycle::ForegroundIdentity; /// Prepare the resume at `resume_ns`: settled on the spot, or a flight the machine waits on /// ([`Self::land_prepare`]). @@ -250,7 +250,7 @@ pub fn poll_foreground_flight( /// landing is discarded and only the replacement it registered is stopped — the same /// `suspend_bufferfeed` teardown an Engine's suspend takes) and park the session back where it was /// suspended, so the next foreground restores it from the start. False when no flight was pending. -pub fn park_pending_foreground_flight( +pub fn park_pending_foreground_flight( lifecycle: &mut ForegroundLifecycle, ps: &mut crate::route::PlaybackSession, pa: &mut crate::player::adapter::PlayerAdapter, diff --git a/rust-modules/media/src/player/lifecycle.rs b/rust-modules/media/src/player/lifecycle.rs index c2f7ed433e..ba38de967a 100644 --- a/rust-modules/media/src/player/lifecycle.rs +++ b/rust-modules/media/src/player/lifecycle.rs @@ -1,7 +1,7 @@ //! The player's app-switch lifecycle machine. //! //! `ForegroundLifecycle` is a tested `State + Event -> Effects` machine. Its state is private and -//! its one writer is `step(&ForegroundEvent, &mut Vec) -> Handled`; callers read +//! its one writer is `transition`, called by `step`; callers read //! it through `awaiting_load`, `claimable_clock`, `pending_flight` and `pending_load_attempt` (and //! `state()` under `test` / `test-support`). It reads no global: the pause it parks with arrives as //! a value on the event (`Park { viewer_paused, .. }`). The drivers which run it @@ -22,8 +22,14 @@ //! `RESUME_REWIND_NS` constant came with it from `app/mod.rs`). The drivers and the transport //! helpers left for `foreground.rs` and `transport.rs` in the Sans-IO lifecycle PR B. +#![deny(clippy::wildcard_enum_match_arm)] + use plx_machine::machine::Handled; +#[cfg(test)] +#[path = "lifecycle_obligation_tests.rs"] +mod obligation_tests; + /// How far an OS-suspended, still-playing session rewinds when it is resumed (a paused one resumes /// at exactly the saved offset). const RESUME_REWIND_NS: i64 = 5_000_000_000; @@ -229,15 +235,66 @@ pub enum Flight { Recovery, } -/// The machine's state is private and its one writer is [`step`](Self::step): there is no mutator +/// Attempt addresses are data, never borrowed state, pointers or callbacks. Only the explicit +/// inert identities below may cross the machine's read-only getters. Ordering is an identity +/// property; the reducer still compares exact attempts and does not order them. +pub trait ForegroundIdentity: Copy + Ord + identity::Sealed {} +mod identity { + pub trait Sealed {} + impl Sealed for u64 {} + impl Sealed for crate::route::RouteStartAttempt {} +} +impl ForegroundIdentity for u64 {} +impl ForegroundIdentity for crate::route::RouteStartAttempt {} + +/// The machine's state is private and its one writer is `transition`, called by [`step`](Self::step): there is no mutator /// beside it for a caller to reach, so a new way in is a new [`ForegroundEvent`]. #[derive(Debug)] -pub struct ForegroundLifecycle { +pub struct ForegroundLifecycle { state: ForegroundState, next_id: u64, } -impl ForegroundLifecycle { +impl ForegroundState { + /// The obligation of entering a newly claimed state, not an IO call. + fn entry_effect(self) -> Option> { + match self { + Self::Claimed { id, claim: ForegroundClaim::Prepare { resume_ns, .. } } => + Some(ForegroundEffect::Prepare { id, resume_ns }), + Self::Claimed { id, claim: ForegroundClaim::Load { resume_ns, clock } } => + Some(ForegroundEffect::Load { id, resume_ns, clock }), + Self::Claimed { id, claim: ForegroundClaim::PlayClock } => + Some(ForegroundEffect::PlayClock { id }), + Self::Idle | Self::Suspended { .. } | Self::Prepared { .. } | Self::LoadPending { .. } + | Self::PreparePending { .. } | Self::RecoveryPending { .. } | Self::ClockPending { .. } => None, + } + } + + /// Release what this state's load armed. The event supplies the exact settled attempt. + fn exit_load_effect(self, attempt: Option, started: bool) -> Option> { + match self { + Self::Claimed { claim: ForegroundClaim::Load { clock, .. }, .. } + | Self::RecoveryPending { clock, .. } | Self::LoadPending { clock, .. } => + Some(ForegroundEffect::AfterLoad { attempt, clock, started }), + Self::Idle | Self::Suspended { .. } | Self::Claimed { .. } | Self::Prepared { .. } + | Self::PreparePending { .. } | Self::ClockPending { .. } => None, + } + } + + /// An explicit exit retires the armed pending load; a replacement playback does not. + fn exit_retire_effect(self) -> Option> { + match self { + Self::LoadPending { id, clock, .. } => Some(ForegroundEffect::Retire { id, clock }), + Self::Idle | Self::Suspended { .. } | Self::Claimed { .. } | Self::Prepared { .. } + | Self::PreparePending { .. } | Self::RecoveryPending { .. } | Self::ClockPending { .. } => None, + } + } +} + +// A settlement emits at most AfterLoad followed by PlayClock; all other edges emit at most one. +type ForegroundDecision = (ForegroundState, Handled, [Option>; 2]); + +impl ForegroundLifecycle { pub const IDLE: Self = Self { state: ForegroundState::Idle, next_id: 0, @@ -274,6 +331,14 @@ impl ForegroundLifecycle { &mut self, ev: &ForegroundEvent, fx: &mut Vec>, + ) -> Handled { + self.transition(ev, fx) + } + + fn transition( + &mut self, + ev: &ForegroundEvent, + fx: &mut Vec>, ) -> Handled { match *ev { ForegroundEvent::Park { @@ -292,10 +357,30 @@ impl ForegroundLifecycle { }; Handled::Yes } - ForegroundEvent::ParkFlight => self.park_flight(fx), - ForegroundEvent::Input(input) => self.input(input, fx), - ForegroundEvent::PrepareAnswered { id, answer } => self.prepare_answered(id, answer, fx), - ForegroundEvent::LoadAnswered { id, start } => self.load_answered(id, start, fx), + ForegroundEvent::ParkFlight => { + let (next, handled, effects) = Self::park_flight(self.state); + self.state = next; + fx.extend(effects.into_iter().flatten()); + handled + } + ForegroundEvent::Input(input) => { + let (next, handled, effects) = Self::input(self.state, input); + self.state = next; + fx.extend(effects.into_iter().flatten()); + handled + } + ForegroundEvent::PrepareAnswered { id, answer } => { + let (next, handled, effects) = Self::prepare_answered(self.state, id, answer); + self.state = next; + fx.extend(effects.into_iter().flatten()); + handled + } + ForegroundEvent::LoadAnswered { id, start } => { + let (next, handled, effects) = Self::load_answered(self.state, id, start); + self.state = next; + fx.extend(effects.into_iter().flatten()); + handled + } ForegroundEvent::FlightStale => { if self.pending_flight().is_none() { return Handled::No; @@ -303,7 +388,12 @@ impl ForegroundLifecycle { self.state = ForegroundState::Idle; Handled::Yes } - ForegroundEvent::LoadStatus { attempt, status } => self.load_status(attempt, status, fx), + ForegroundEvent::LoadStatus { attempt, status } => { + let (next, handled, effects) = Self::load_status(self.state, attempt, status); + self.state = next; + fx.extend(effects.into_iter().flatten()); + handled + } ForegroundEvent::ClockAnswered { id, accepted } => { if !matches!( self.state, @@ -339,7 +429,10 @@ impl ForegroundLifecycle { ForegroundState::LoadPending { clock, .. } | ForegroundState::PreparePending { saved_clock: clock, .. } | ForegroundState::RecoveryPending { clock, .. } => clock, - _ => ForegroundClock::from_paused(transport_paused), + ForegroundState::Idle + | ForegroundState::Suspended { .. } + | ForegroundState::Claimed { .. } + | ForegroundState::Prepared { .. } => ForegroundClock::from_paused(transport_paused), } } @@ -369,7 +462,12 @@ impl ForegroundLifecycle { ForegroundState::Suspended { clock, .. } | ForegroundState::Prepared { clock, .. } => { Some(clock) } - _ => None, + ForegroundState::Idle + | ForegroundState::Claimed { .. } + | ForegroundState::LoadPending { .. } + | ForegroundState::PreparePending { .. } + | ForegroundState::RecoveryPending { .. } + | ForegroundState::ClockPending { .. } => None, } } @@ -391,382 +489,411 @@ impl ForegroundLifecycle { match self.state { ForegroundState::PreparePending { id, .. } => Some((Flight::Prepare, id)), ForegroundState::RecoveryPending { id, .. } => Some((Flight::Recovery, id)), - _ => None, + ForegroundState::Idle + | ForegroundState::Suspended { .. } + | ForegroundState::Claimed { .. } + | ForegroundState::Prepared { .. } + | ForegroundState::LoadPending { .. } + | ForegroundState::ClockPending { .. } => None, } } pub fn pending_load_attempt(&self) -> Option { match self.state { ForegroundState::LoadPending { attempt, .. } => Some(attempt), - _ => None, + ForegroundState::Idle + | ForegroundState::Suspended { .. } + | ForegroundState::Claimed { .. } + | ForegroundState::Prepared { .. } + | ForegroundState::PreparePending { .. } + | ForegroundState::RecoveryPending { .. } + | ForegroundState::ClockPending { .. } => None, } } /// `Input`: a DID foreground, a PLAY press or a supersession. - fn input(&mut self, input: ForegroundInput, fx: &mut Vec>) -> Handled { + fn input( + state: ForegroundState, + input: ForegroundInput, + ) -> ForegroundDecision { if let ForegroundInput::Superseded(successor) = input { - return self.supersede(successor, fx); + return Self::supersede(state, successor); } - // `ClockPending` belongs to an already-loaded player. If a later real exit has removed - // that route, its retry must not intercept Play for the next item. - if matches!(input, ForegroundInput::PlayKeyOffPlayer) - && matches!( - self.state, - ForegroundState::ClockPending { .. } - | ForegroundState::Claimed { - claim: ForegroundClaim::PlayClock, - .. - } - ) - { - self.state = ForegroundState::Idle; - return Handled::No; - } - let play = matches!( - input, - ForegroundInput::PlayKey | ForegroundInput::PlayKeyOffPlayer - ); - let state = self.state; - match state { - ForegroundState::Idle => Handled::No, - // Nothing is claimed: the parked states stay as they are, exactly as the pending ones - // do for every input. - ForegroundState::Suspended { .. } | ForegroundState::Prepared { .. } - if matches!(input, ForegroundInput::DidForegroundSuperseded) => + let mut next = state; + let mut effects = [None, None]; + let handled = { + // `ClockPending` belongs to an already-loaded player. If a later real exit has removed + // that route, its retry must not intercept Play for the next item. + if matches!(input, ForegroundInput::PlayKeyOffPlayer) + && matches!( + next, + ForegroundState::ClockPending { .. } + | ForegroundState::Claimed { + claim: ForegroundClaim::PlayClock, + .. + } + ) { - Handled::Yes - } - ForegroundState::Suspended { - id, - saved_ns, - clock: saved_clock, - } => { - let clock = if play { - ForegroundClock::Playing - } else { - saved_clock - }; - let resume_ns = if matches!(saved_clock, ForegroundClock::Paused) { - saved_ns - } else { - saved_ns.saturating_sub(RESUME_REWIND_NS).max(0) - }; - self.state = ForegroundState::Claimed { - id, - claim: ForegroundClaim::Prepare { - saved_ns, - saved_clock, - resume_ns, - clock, - }, - }; - fx.push(ForegroundEffect::Prepare { id, resume_ns }); - Handled::Yes + next = ForegroundState::Idle; + return (next, Handled::No, effects); } - ForegroundState::Prepared { - id, - resume_ns, - clock, - } => { - let clock = if play { ForegroundClock::Playing } else { clock }; - self.state = ForegroundState::Claimed { + let play = matches!( + input, + ForegroundInput::PlayKey | ForegroundInput::PlayKeyOffPlayer + ); + + match state { + ForegroundState::Idle => Handled::No, + // Nothing is claimed: the parked states stay as they are, exactly as the pending ones + // do for every input. + ForegroundState::Suspended { .. } | ForegroundState::Prepared { .. } + if matches!(input, ForegroundInput::DidForegroundSuperseded) => + { + Handled::Yes + } + ForegroundState::Suspended { id, - claim: ForegroundClaim::Load { resume_ns, clock }, - }; - fx.push(ForegroundEffect::Load { + saved_ns, + clock: saved_clock, + } => { + let clock = if play { + ForegroundClock::Playing + } else { + saved_clock + }; + let resume_ns = if matches!(saved_clock, ForegroundClock::Paused) { + saved_ns + } else { + saved_ns.saturating_sub(RESUME_REWIND_NS).max(0) + }; + next = ForegroundState::Claimed { + id, + claim: ForegroundClaim::Prepare { + saved_ns, + saved_clock, + resume_ns, + clock, + }, + }; + effects[0] = next.entry_effect(); + Handled::Yes + } + ForegroundState::Prepared { id, resume_ns, clock, - }); - Handled::Yes - } - ForegroundState::ClockPending { id } if play => { - self.state = ForegroundState::Claimed { - id, - claim: ForegroundClaim::PlayClock, - }; - fx.push(ForegroundEffect::PlayClock { id }); - Handled::Yes + } => { + let clock = if play { ForegroundClock::Playing } else { clock }; + next = ForegroundState::Claimed { + id, + claim: ForegroundClaim::Load { resume_ns, clock }, + }; + effects[0] = next.entry_effect(); + Handled::Yes + } + ForegroundState::ClockPending { id } if play => { + next = ForegroundState::Claimed { + id, + claim: ForegroundClaim::PlayClock, + }; + effects[0] = next.entry_effect(); + Handled::Yes + } + // A lifecycle edge or key which arrives while another claimant owns the effect is + // consumed, not allowed to fall through to the ordinary start path. + ForegroundState::Claimed { .. } + | ForegroundState::ClockPending { .. } + | ForegroundState::LoadPending { .. } + | ForegroundState::PreparePending { .. } + | ForegroundState::RecoveryPending { .. } => Handled::Yes, } - // A lifecycle edge or key which arrives while another claimant owns the effect is - // consumed, not allowed to fall through to the ordinary start path. - ForegroundState::Claimed { .. } - | ForegroundState::ClockPending { .. } - | ForegroundState::LoadPending { .. } - | ForegroundState::PreparePending { .. } - | ForegroundState::RecoveryPending { .. } => Handled::Yes, - } + }; + (next, handled, effects) } fn supersede( - &mut self, + state: ForegroundState, successor: Successor, - fx: &mut Vec>, - ) -> Handled { - let exit = matches!(successor, Successor::Exit); - match self.state { - ForegroundState::Idle => Handled::No, - ForegroundState::LoadPending { clock, id, .. } if exit => { - self.state = ForegroundState::Idle; - fx.push(ForegroundEffect::Retire { id, clock }); - Handled::Yes - } - ForegroundState::LoadPending { .. } => Handled::Yes, - ForegroundState::Claimed { - claim: ForegroundClaim::PlayClock, - .. - } - | ForegroundState::ClockPending { .. } => { - if exit { - self.state = ForegroundState::Idle; + ) -> ForegroundDecision { + let mut next = state; + let mut effects = [None, None]; + let handled = { + let exit = matches!(successor, Successor::Exit); + match next { + ForegroundState::Idle => Handled::No, + ForegroundState::LoadPending { .. } if exit => { + next = ForegroundState::Idle; + effects[0] = state.exit_retire_effect(); + Handled::Yes + } + ForegroundState::LoadPending { .. } => Handled::Yes, + ForegroundState::Claimed { + claim: ForegroundClaim::PlayClock, + .. + } + | ForegroundState::ClockPending { .. } => { + if exit { + next = ForegroundState::Idle; + } + Handled::Yes + } + ForegroundState::Suspended { .. } + | ForegroundState::Claimed { .. } + | ForegroundState::Prepared { .. } + | ForegroundState::PreparePending { .. } + | ForegroundState::RecoveryPending { .. } => { + next = ForegroundState::Idle; + Handled::Yes } - Handled::Yes - } - ForegroundState::Suspended { .. } - | ForegroundState::Claimed { .. } - | ForegroundState::Prepared { .. } - | ForegroundState::PreparePending { .. } - | ForegroundState::RecoveryPending { .. } => { - self.state = ForegroundState::Idle; - Handled::Yes } - } + }; + (next, handled, effects) } /// `ParkFlight`: the landing is discarded, and the parked session goes back to waiting for the /// next foreground exactly where it was (a pending rollback has no snapshot but its resume /// position, which the next restore rebuilds from). - fn park_flight(&mut self, fx: &mut Vec>) -> Handled { - self.state = match self.state { - ForegroundState::PreparePending { - id, - saved_ns, - saved_clock, - .. - } => ForegroundState::Suspended { - id, - saved_ns, - clock: saved_clock, - }, - ForegroundState::RecoveryPending { - id, - resume_ns, - clock, - } => ForegroundState::Suspended { - id, - saved_ns: resume_ns, - clock, - }, - _ => return Handled::No, + fn park_flight(state: ForegroundState) -> ForegroundDecision { + let mut next = state; + let mut effects = [None, None]; + let handled = { + next = match next { + ForegroundState::PreparePending { + id, + saved_ns, + saved_clock, + .. + } => ForegroundState::Suspended { + id, + saved_ns, + clock: saved_clock, + }, + ForegroundState::RecoveryPending { + id, + resume_ns, + clock, + } => ForegroundState::Suspended { + id, + saved_ns: resume_ns, + clock, + }, + ForegroundState::Idle + | ForegroundState::Suspended { .. } + | ForegroundState::Claimed { .. } + | ForegroundState::Prepared { .. } + | ForegroundState::LoadPending { .. } + | ForegroundState::ClockPending { .. } => return (next, Handled::No, effects), + }; + effects[0] = Some(ForegroundEffect::DropFlight); + Handled::Yes }; - fx.push(ForegroundEffect::DropFlight); - Handled::Yes + (next, handled, effects) } /// `PrepareAnswered`: settles the claimed `Prepare`, whether it answered on the spot or its /// flight has landed. fn prepare_answered( - &mut self, + state: ForegroundState, id: u64, answer: PrepareAnswer, - fx: &mut Vec>, - ) -> Handled { - let (owner, saved_ns, saved_clock, resume_ns, clock) = match self.state { - ForegroundState::Claimed { - id: owner, - claim: - ForegroundClaim::Prepare { - saved_ns, - saved_clock, - resume_ns, - clock, - }, - } - | ForegroundState::PreparePending { - id: owner, - saved_ns, - saved_clock, - resume_ns, - clock, - } => (owner, saved_ns, saved_clock, resume_ns, clock), - _ => return Handled::No, - }; - if owner != id { - return Handled::No; - } - match answer { - // The claimed `Prepare` is a flight: park until its landing. - PrepareAnswer::Pending => { - self.state = ForegroundState::PreparePending { - id, + ) -> ForegroundDecision { + let mut next = state; + let mut effects = [None, None]; + let handled = { + let (owner, saved_ns, saved_clock, resume_ns, clock) = match next { + ForegroundState::Claimed { + id: owner, + claim: + ForegroundClaim::Prepare { + saved_ns, + saved_clock, + resume_ns, + clock, + }, + } + | ForegroundState::PreparePending { + id: owner, saved_ns, saved_clock, resume_ns, clock, - }; - } - PrepareAnswer::Refused => { - self.state = ForegroundState::Suspended { - id, - saved_ns, - clock: saved_clock, - }; + } => (owner, saved_ns, saved_clock, resume_ns, clock), + ForegroundState::Idle + | ForegroundState::Suspended { .. } + | ForegroundState::Claimed { .. } + | ForegroundState::Prepared { .. } + | ForegroundState::LoadPending { .. } + | ForegroundState::RecoveryPending { .. } + | ForegroundState::ClockPending { .. } => return (next, Handled::No, effects), + }; + if owner != id { + return (next, Handled::No, effects); } - PrepareAnswer::Prepared => { - self.state = ForegroundState::Claimed { - id, - claim: ForegroundClaim::Load { resume_ns, clock }, - }; - fx.push(ForegroundEffect::Load { - id, - resume_ns, - clock, - }); + match answer { + // The claimed `Prepare` is a flight: park until its landing. + PrepareAnswer::Pending => { + next = ForegroundState::PreparePending { + id, + saved_ns, + saved_clock, + resume_ns, + clock, + }; + } + PrepareAnswer::Refused => { + next = ForegroundState::Suspended { + id, + saved_ns, + clock: saved_clock, + }; + } + PrepareAnswer::Prepared => { + next = ForegroundState::Claimed { + id, + claim: ForegroundClaim::Load { resume_ns, clock }, + }; + effects[0] = next.entry_effect(); + } } - } - Handled::Yes + Handled::Yes + }; + (next, handled, effects) } /// `LoadAnswered`: settles the claimed `Load`, whether starting it answered on the spot or its /// Original rollback's flight has landed. A refusal or a terminal answer releases what /// `before_load` armed (`AfterLoad`) with no exact attempt to retire. fn load_answered( - &mut self, + state: ForegroundState, id: u64, start: ForegroundLoadStart, - fx: &mut Vec>, - ) -> Handled { - let (owner, resume_ns, clock) = match self.state { - ForegroundState::Claimed { - id: owner, - claim: ForegroundClaim::Load { resume_ns, clock }, - } - | ForegroundState::RecoveryPending { - id: owner, - resume_ns, - clock, - } => (owner, resume_ns, clock), - _ => return Handled::No, - }; - if owner != id { - return Handled::No; - } - match start { - ForegroundLoadStart::Launched(attempt) => { - self.state = ForegroundState::LoadPending { - id, - attempt, - resume_ns, - clock, - }; - fx.push(ForegroundEffect::Launched { id }); - } - // The claimed `Load`'s Original rollback is a flight: park until its landing. - ForegroundLoadStart::Pending | ForegroundLoadStart::Deferred => { - self.state = ForegroundState::RecoveryPending { - id, - resume_ns, - clock, - }; - } - ForegroundLoadStart::Failed => { - self.state = ForegroundState::Prepared { - id, + ) -> ForegroundDecision { + let mut next = state; + let mut effects = [None, None]; + let handled = { + let (owner, resume_ns, clock) = match next { + ForegroundState::Claimed { + id: owner, + claim: ForegroundClaim::Load { resume_ns, clock }, + } + | ForegroundState::RecoveryPending { + id: owner, resume_ns, clock, - }; - fx.push(ForegroundEffect::AfterLoad { - attempt: None, - clock, - started: false, - }); + } => (owner, resume_ns, clock), + ForegroundState::Idle + | ForegroundState::Suspended { .. } + | ForegroundState::Claimed { .. } + | ForegroundState::Prepared { .. } + | ForegroundState::LoadPending { .. } + | ForegroundState::PreparePending { .. } + | ForegroundState::ClockPending { .. } => return (next, Handled::No, effects), + }; + if owner != id { + return (next, Handled::No, effects); } - // No exact candidate can be followed. `AlreadyRunning` is a stable Engine outside this - // suspended lifecycle; `Terminal` means Original rollback could not construct a truthful - // route. Neither is a retryable Prepared edge. - ForegroundLoadStart::AlreadyRunning | ForegroundLoadStart::Terminal => { - self.state = ForegroundState::Idle; - fx.push(ForegroundEffect::AfterLoad { - attempt: None, - clock, - started: false, - }); + match start { + ForegroundLoadStart::Launched(attempt) => { + next = ForegroundState::LoadPending { + id, + attempt, + resume_ns, + clock, + }; + effects[0] = Some(ForegroundEffect::Launched { id }); + } + // The claimed `Load`'s Original rollback is a flight: park until its landing. + ForegroundLoadStart::Pending | ForegroundLoadStart::Deferred => { + next = ForegroundState::RecoveryPending { + id, + resume_ns, + clock, + }; + } + ForegroundLoadStart::Failed => { + next = ForegroundState::Prepared { + id, + resume_ns, + clock, + }; + effects[0] = state.exit_load_effect(None, false); + } + // No exact candidate can be followed. `AlreadyRunning` is a stable Engine outside this + // suspended lifecycle; `Terminal` means Original rollback could not construct a truthful + // route. Neither is a retryable Prepared edge. + ForegroundLoadStart::AlreadyRunning | ForegroundLoadStart::Terminal => { + next = ForegroundState::Idle; + effects[0] = state.exit_load_effect(None, false); + } } - } - Handled::Yes + Handled::Yes + }; + (next, handled, effects) } /// `LoadStatus`: the exact native Load attempt reported. A finished one emits `AfterLoad`, and /// a Started one with the clock Playing then `PlayClock`, in that order. fn load_status( - &mut self, + state: ForegroundState, attempt: Attempt, status: ForegroundLoadStatus, - fx: &mut Vec>, - ) -> Handled { - let ForegroundState::LoadPending { - id, - attempt: owner, - resume_ns, - clock, - } = self.state - else { - return Handled::No; - }; - if owner != attempt { - return Handled::No; - } - match status { - ForegroundLoadStatus::Pending => {} - ForegroundLoadStatus::Superseded(replacement) => { - self.state = ForegroundState::LoadPending { - id, - attempt: replacement, - resume_ns, - clock, - }; - } - ForegroundLoadStatus::Failed => { - self.state = ForegroundState::Prepared { - id, - resume_ns, - clock, - }; - fx.push(ForegroundEffect::AfterLoad { - attempt: Some(attempt), - clock, - started: false, - }); - } - ForegroundLoadStatus::Stale => { - // Neither the observed Load nor a tokened replacement owns the route any more. - // Release foreground ownership instead of retrying an unknown candidate or - // destroying whichever Engine the main reducer may now own. - self.state = ForegroundState::Idle; - fx.push(ForegroundEffect::AfterLoad { - attempt: None, - clock, - started: false, - }); + ) -> ForegroundDecision { + let mut next = state; + let mut effects = [None, None]; + let handled = { + let ForegroundState::LoadPending { + id, + attempt: owner, + resume_ns, + clock, + } = next + else { + return (next, Handled::No, effects); + }; + if owner != attempt { + return (next, Handled::No, effects); } - ForegroundLoadStatus::Started => { - fx.push(ForegroundEffect::AfterLoad { - attempt: Some(attempt), - clock, - started: true, - }); - if matches!(clock, ForegroundClock::Paused) { - self.state = ForegroundState::Idle; - } else { - self.state = ForegroundState::Claimed { + match status { + ForegroundLoadStatus::Pending => {} + ForegroundLoadStatus::Superseded(replacement) => { + next = ForegroundState::LoadPending { id, - claim: ForegroundClaim::PlayClock, + attempt: replacement, + resume_ns, + clock, }; - fx.push(ForegroundEffect::PlayClock { id }); + } + ForegroundLoadStatus::Failed => { + next = ForegroundState::Prepared { + id, + resume_ns, + clock, + }; + effects[0] = state.exit_load_effect(Some(attempt), false); + } + ForegroundLoadStatus::Stale => { + // Neither the observed Load nor a tokened replacement owns the route any more. + // Release foreground ownership instead of retrying an unknown candidate or + // destroying whichever Engine the main reducer may now own. + next = ForegroundState::Idle; + effects[0] = state.exit_load_effect(None, false); + } + ForegroundLoadStatus::Started => { + effects[0] = state.exit_load_effect(Some(attempt), true); + if matches!(clock, ForegroundClock::Paused) { + next = ForegroundState::Idle; + } else { + next = ForegroundState::Claimed { + id, + claim: ForegroundClaim::PlayClock, + }; + effects[1] = next.entry_effect(); + } } } - } - Handled::Yes + Handled::Yes + }; + (next, handled, effects) } } @@ -855,6 +982,27 @@ mod foreground_resume_tests { Effect(ForegroundEffect), } + #[test] + fn park_alone_advances_the_owner_id_and_wraps_past_zero() { + let mut lifecycle = ForegroundLifecycle:: { state: ForegroundState::Idle, next_id: u64::MAX }; + let mut fx = Vec::new(); + assert_eq!(lifecycle.step(&ForegroundEvent::Park { saved_ns: 9_000_000_000, viewer_paused: false }, &mut fx), Handled::Yes); + assert_eq!(lifecycle.next_id, 1); + assert!(fx.is_empty()); + assert_eq!(lifecycle.step(&ForegroundEvent::Input(ForegroundInput::DidForeground), &mut fx), Handled::Yes); + assert_eq!(fx, [ForegroundEffect::Prepare { id: 1, resume_ns: 4_000_000_000 }]); + fx.clear(); + let before = lifecycle.state(); + assert_eq!(lifecycle.step(&ForegroundEvent::PrepareAnswered { id: 2, answer: PrepareAnswer::Pending }, &mut fx), Handled::No); + assert_eq!(lifecycle.state(), before); + assert_eq!(lifecycle.next_id, 1); + assert!(fx.is_empty()); + lifecycle.step(&ForegroundEvent::Park { saved_ns: 11_000_000_000, viewer_paused: false }, &mut fx); + assert_eq!(lifecycle.state(), ForegroundState::Suspended { id: 2, saved_ns: 11_000_000_000, clock: ForegroundClock::Playing }); + assert_eq!(lifecycle.next_id, 2); + assert!(fx.is_empty()); + } + fn claim(lifecycle: &mut ForegroundLifecycle, input: ForegroundInput) -> ForegroundClaimResult { let mut fx = Vec::new(); let handled = lifecycle.step(&ForegroundEvent::Input(input), &mut fx); @@ -1871,7 +2019,7 @@ mod foreground_resume_tests { assert_eq!(activation, expected_activation, "{name} x {successor:?}: activation"); let retired = match result { Effect(ForegroundEffect::Retire { clock, .. }) => vec![(None, clock, false)], - _ => Vec::new(), + Effect(_) | Ordinary | Suppressed => Vec::new(), }; assert_eq!(actuator.after_loads, retired, "{name} x {successor:?}: after_load"); assert_eq!( @@ -2491,7 +2639,13 @@ mod foreground_resume_tests { vec![], Handled::Yes, ), - _ => match row.cells.iter().find(|cell| cell.0 == *ev) { + ForegroundEvent::ParkFlight + | ForegroundEvent::Input(_) + | ForegroundEvent::PrepareAnswered { .. } + | ForegroundEvent::LoadAnswered { .. } + | ForegroundEvent::FlightStale + | ForegroundEvent::LoadStatus { .. } + | ForegroundEvent::ClockAnswered { .. } => match row.cells.iter().find(|cell| cell.0 == *ev) { Some((_, next, fx, handled)) => (*next, fx.clone(), *handled), None => (row.state, vec![], Handled::No), }, diff --git a/rust-modules/media/src/player/lifecycle_obligation_tests.rs b/rust-modules/media/src/player/lifecycle_obligation_tests.rs new file mode 100644 index 0000000000..9f72ad2de3 --- /dev/null +++ b/rust-modules/media/src/player/lifecycle_obligation_tests.rs @@ -0,0 +1,30 @@ +use super::*; +#[test] +fn foreground_state_entry_and_exit_obligations_are_exact_values() { + type S = ForegroundState; + use ForegroundClock::Playing; + let cases = [ + (S::Idle, None, false, false), + (S::Suspended { id: 7, saved_ns: 90, clock: Playing }, None, false, false), + (S::Claimed { id: 7, claim: ForegroundClaim::Prepare { saved_ns: 90, saved_clock: Playing, resume_ns: 80, clock: Playing } }, + Some(ForegroundEffect::Prepare { id: 7, resume_ns: 80 }), false, false), + (S::Claimed { id: 7, claim: ForegroundClaim::Load { resume_ns: 80, clock: Playing } }, + Some(ForegroundEffect::Load { id: 7, resume_ns: 80, clock: Playing }), true, false), + (S::Claimed { id: 7, claim: ForegroundClaim::PlayClock }, + Some(ForegroundEffect::PlayClock { id: 7 }), false, false), + (S::Prepared { id: 7, resume_ns: 80, clock: Playing }, None, false, false), + (S::LoadPending { id: 7, attempt: 42, resume_ns: 80, clock: Playing }, None, true, true), + (S::PreparePending { id: 7, saved_ns: 90, saved_clock: Playing, resume_ns: 80, clock: Playing }, None, false, false), + (S::RecoveryPending { id: 7, resume_ns: 80, clock: Playing }, None, true, false), + (S::ClockPending { id: 7 }, None, false, false), + ]; + for (state, entry, load, retire) in cases { + assert_eq!(state.entry_effect(), entry, "{state:?}"); + assert_eq!(state.exit_retire_effect(), retire.then_some(ForegroundEffect::Retire { id: 7, clock: Playing }), "{state:?}"); + for attempt in [None, Some(42)] { + for started in [false, true] { + assert_eq!(state.exit_load_effect(attempt, started), load.then_some(ForegroundEffect::AfterLoad { attempt, clock: Playing, started }), "{state:?}"); + } + } + } +} diff --git a/rust-modules/media/src/player/readout.rs b/rust-modules/media/src/player/readout.rs index 67db398d14..986838117b 100644 --- a/rust-modules/media/src/player/readout.rs +++ b/rust-modules/media/src/player/readout.rs @@ -25,6 +25,8 @@ //! carries a speed change (read it, then step `RateReloadTaken`). `start_queued` is the release //! machine's answer, stepped by `PlayerAdapter::release_step` after every step of the machine. +#![deny(clippy::wildcard_enum_match_arm)] + use plx_playback_contract::adaptive::{AbrReadout, CarriedSeed, FailureEdit, SeedReadout}; use plx_playback_contract::feed::{FeedRaw, PresentationTick, Stage}; use plx_playback_contract::subtitle::Spec; @@ -387,9 +389,20 @@ impl PlayerReadout { edge_pending(self.raw.native_audio_refusals, self.taken_native_audio_refusals) } - /// The one writer. Applies `event`; there are no effects yet. The session addresses the + /// Apply `event` through the sole reducer; this pure view has no effects. The session addresses the /// events that carry an attempt's facts before it steps them. pub fn step(&mut self, event: ReadoutEvent) { + self.transition(event); + } +} + +/// Whether the feed's count of an edge is ahead of what the player has taken. A count the feed +/// zeroed (its session reset) is no edge, whatever was taken before. +fn edge_pending(counted: u32, taken: u32) -> bool { counted != 0 && counted != taken } + +impl PlayerReadout { + /// The only writer of every readout field, including coalescing and consumed-edge counters. + fn transition(&mut self, event: ReadoutEvent) { match event { ReadoutEvent::StateDerived(state) => self.state = state, ReadoutEvent::StreamEnded => self.ended = true, @@ -408,7 +421,10 @@ impl PlayerReadout { self.pending_seek_ns = None; self.seek_requests = 0; } - ReadoutEvent::SeekRequeued { target_ns } => self.wait_for_pump(target_ns), + ReadoutEvent::SeekRequeued { target_ns } => { + self.pending_seek_ns = (target_ns >= 0).then_some(target_ns); + self.seek_requests = 1; + }, ReadoutEvent::ReloadSeek { target_ns } => self.reload_seek_ns = Some(target_ns), ReadoutEvent::SessionReset => { self.state = PlaybackState::Idle; @@ -461,7 +477,8 @@ impl PlayerReadout { // the feed's epoch makes the next request new again. let asked = raw.seek_requeue; if asked.epoch != 0 && asked.epoch != self.raw.seek_requeue.epoch { - self.wait_for_pump(asked.target_ns); + self.pending_seek_ns = (asked.target_ns >= 0).then_some(asked.target_ns); + self.seek_requests = 1; } if raw.frames > 0 { // The callback gate counts only the replacement Load here. A seeded @@ -526,18 +543,6 @@ impl PlayerReadout { } } -/// Whether the feed's count of an edge is ahead of what the player has taken. A count the feed -/// zeroed (its session reset) is no edge, whatever was taken before. -fn edge_pending(counted: u32, taken: u32) -> bool { counted != 0 && counted != taken } - -impl PlayerReadout { - /// `target_ns` waits for the pump as one request. - fn wait_for_pump(&mut self, target_ns: i64) { - self.pending_seek_ns = (target_ns >= 0).then_some(target_ns); - self.seek_requests = 1; - } -} - impl Default for PlayerReadout { fn default() -> Self { Self::IDLE } } @@ -550,6 +555,22 @@ mod tests { use plx_playback_contract::feed::{FeedFacts, FeedLoad, SeekRequeue}; use plx_playback_contract::feed_fake::FakeFeed; + #[test] + fn explicit_and_sampled_requeues_fold_only_the_requests_they_replace() { + let mut r = stepped(&[tap(1), tap(2), ReadoutEvent::SeekRequeued { target_ns: 3_000_000_000 }]); + assert_eq!((r.seek_epoch(), r.pending_seek(), r.seek_coalesced()), (2, Some(3_000_000_000), 0)); + assert_eq!(r.seek_display_ns(), Some(2_000_000_000)); + let raw = FeedRaw { seek_requeue: SeekRequeue { epoch: 7, target_ns: 4_000_000_000 }, ..FeedRaw::IDLE }; + r.step(ReadoutEvent::FactsIngested(raw)); + assert_eq!((r.seek_epoch(), r.pending_seek(), r.seek_coalesced()), (2, Some(4_000_000_000), 0)); + r.step(tap(5)); + r.step(ReadoutEvent::FactsIngested(raw)); + assert_eq!((r.seek_epoch(), r.pending_seek(), r.seek_coalesced()), (3, Some(5_000_000_000), 1)); + r.step(ReadoutEvent::SessionReset); + assert_eq!((r.seek_epoch(), r.pending_seek(), r.seek_coalesced()), (3, None, 0)); + assert!(!r.seeking()); + } + fn stepped(events: &[ReadoutEvent]) -> PlayerReadout { let mut readout = PlayerReadout::IDLE; for event in events { readout.step(event.clone()); } diff --git a/rust-modules/media/src/player/recovery.rs b/rust-modules/media/src/player/recovery.rs index b746e1f12c..0da946d70e 100644 --- a/rust-modules/media/src/player/recovery.rs +++ b/rust-modules/media/src/player/recovery.rs @@ -1,9 +1,11 @@ +#![deny(clippy::wildcard_enum_match_arm)] //! The failed-open recovery ladder: what a play request does when the pipeline (or the source) //! fails it BEFORE the first picture. //! //! `OpenRecovery` is a tested `State + RecoveryEvent -> Effects` machine in the shape of //! [`super::lifecycle::ForegroundLifecycle`]: its state is private and its one writer is -//! [`step`](OpenRecovery::step). It reads no global and performs no IO. The facts a decision needs +//! `transition`, reached through [`step`](OpenRecovery::step). It reads no global and performs no IO. +//! The facts a decision needs //! (an HLS->Original trial holding a live encoder, a cold Auto Original, Forced Direct Play, no //! decoded frame yet, the audio and the video the pipeline was fed, the natively fed audio a refusal names) arrive //! as a value on the event ([`OpenFacts`]), and so do the verdicts PMS gave a landed flight @@ -383,6 +385,16 @@ enum State { Failed, } +/// A rung's minimal decision data; the event reducer alone applies its entry obligations. +enum RecoveryDecision { + Rollback { audio: Option }, + Facet(Facet), + AutoHls { audio: Option, video: Option }, + Decode(Facet), + Encode { audio: Option, video: Option }, + Error { codec: Option }, +} + /// The ladder for one play request. See the module doc. #[derive(Clone, Debug)] pub struct OpenRecovery { @@ -428,12 +440,7 @@ struct Excluded { } impl Excluded { - fn take(&mut self, facet: Facet) { - match facet { - Facet::Audio { .. } => self.audio = Some(facet), - Facet::Video { .. } => self.video = Some(facet), - } - } + fn iter(&self) -> impl Iterator { self.audio.iter().chain(self.video.iter()) @@ -466,16 +473,158 @@ impl OpenRecovery { } } + /// Apply the event and all state-entry, state-exit and bookkeeping obligations in place. + fn transition(&mut self, ev: &RecoveryEvent, fx: &mut Vec) -> Handled { + // Only a refused flight needs to transfer its state-owned facts out of the old variant. + let failed_flight; + let (refusal, facts, decision, remember) = match ev { + RecoveryEvent::Refused { refusal, facts } => { + if !matches!(self.state, State::Opening | State::Proving { .. } | State::Playing) { + return Handled::No; + } + if let Some(facet) = &facts.native_audio { + fx.push(RecoveryEffect::ConfirmRefusal { facet: facet.clone(), evidence: Evidence::Named }); + } + (*refusal, facts, self.decide(*refusal, facts), true) + } + RecoveryEvent::FlightRefused => { + if !matches!(self.state, State::Flight { .. }) { + return Handled::No; + } + failed_flight = std::mem::replace(&mut self.state, State::Opening); + let State::Flight { rung, cause, facts } = &failed_flight else { unreachable!() }; + let decision = match rung { + Rung::Facet => self.decide(*cause, facts), + Rung::Both | Rung::Encode => self.app_decode_or_error(*cause, facts), + Rung::Rollback => RecoveryDecision::Error { codec: None }, + }; + (*cause, facts, decision, *rung == Rung::Facet) + } + RecoveryEvent::FlightLanded { lanes } => { + let State::Flight { rung, .. } = &self.state else { + return Handled::No; + }; + let proven = (*rung == Rung::Facet && !self.pictured && !self.unprovable) + .then(|| self.excluded.iter().find(|f| proves(f, lanes.as_ref()))) + .flatten(); + self.state = match proven { + Some(facet) => State::Proving { facet: facet.clone(), loaded: false }, + None => State::Opening, + }; + return Handled::Yes; + } + RecoveryEvent::FirstPicture => { + match &self.state { + State::Opening => {} + State::Proving { facet, .. } => { + fx.push(RecoveryEffect::ConfirmRefusal { facet: facet.clone(), evidence: Evidence::Proof }); + } + State::Flight { .. } | State::Playing | State::Failed => return Handled::No, + } + self.pictured = true; + self.state = State::Playing; + let rung = self.rescue.take(); + if !self.reported { + if let (Some(rung), Some((refusal, facet))) = (rung, &self.refused) { + self.reported = true; + fx.push(RecoveryEffect::ReportRecovered(Recovered { rung, refusal: *refusal, facet: facet.clone() })); + } + } + return Handled::Yes; + } + RecoveryEvent::LoadStarted => { + match &mut self.state { + // The landing's own reload keeps its proof, without copying the payload. + State::Proving { loaded: loaded @ false, .. } => *loaded = true, + State::Proving { .. } => self.state = State::Opening, + State::Flight { .. } | State::Failed => { + self.rescue = None; + self.state = State::Opening; + } + State::Opening | State::Playing => return Handled::No, + } + return Handled::Yes; + } + }; + if remember && self.refused.is_none() && refusal.reports() { + // A timeout names no stream; later rescue failures never replace this first refusal. + let facet = refusal.names_pipeline().then(|| { + let video = facts.video.as_ref().filter(|_| matches!(refusal, LoadRefusal::Refused { .. })); + facts.native_audio.clone().or_else(|| suspect(facts.audio.as_ref(), video)) + }); + self.refused = Some((refusal, facet.flatten())); + } + let hls = matches!(&decision, RecoveryDecision::AutoHls { .. }); + match decision { + RecoveryDecision::Rollback { audio } => { + if let Some(audio) = audio { + self.excluded.audio = Some(audio); + self.attempt = Arc::new(attempt_for(&self.start, &self.excluded, self.in_app.as_deref())); + } + fx.push(RecoveryEffect::Rollback); + self.state = State::Flight { rung: Rung::Rollback, cause: refusal, facts: facts.clone() }; + self.rescue = Some(Rung::Rollback); + } + RecoveryDecision::Facet(facet) => { + self.unprovable |= facts.audio.as_ref().is_some_and(|a| a.app_decoded_lossy); + match &facet { + Facet::Audio { .. } => self.excluded.audio = Some(facet.clone()), + Facet::Video { .. } => self.excluded.video = Some(facet.clone()), + } + self.attempt = Arc::new(attempt_for(&self.start, &self.excluded, self.in_app.as_deref())); + self.flights += 1; + fx.push(RecoveryEffect::ConvertFacet { facet, flight: self.flights }); + self.state = State::Flight { rung: Rung::Facet, cause: refusal, facts: facts.clone() }; + self.rescue = Some(Rung::Facet); + } + RecoveryDecision::AutoHls { audio, video } | RecoveryDecision::Encode { audio, video } => { + for facet in audio.into_iter().chain(video) { + match facet { + Facet::Audio { .. } => self.excluded.audio = Some(facet), + Facet::Video { .. } => self.excluded.video = Some(facet), + } + } + self.attempt = Arc::new(attempt_for(&self.start, &self.excluded, self.in_app.as_deref())); + self.flights += 1; + let rung = if hls { + fx.push(RecoveryEffect::StartAutoHls); + Rung::Both + } else { + fx.push(RecoveryEffect::ConvertBoth { flight: self.flights }); + Rung::Encode + }; + self.state = State::Flight { rung, cause: refusal, facts: facts.clone() }; + self.rescue = Some(rung); + } + RecoveryDecision::Decode(audio) => { + if let Facet::Audio { codec, .. } = &audio { + self.in_app = Some(codec.clone()); + } + self.excluded.video = None; + self.attempt = Arc::new(attempt_for(&self.start, &self.excluded, self.in_app.as_deref())); + self.state = State::Opening; + self.rescue = None; + fx.push(RecoveryEffect::DecodeInApp { audio, refusal }); + } + RecoveryDecision::Error { codec } => { + if let Some(codec) = codec { + fx.push(RecoveryEffect::NameRefusedAudio { codec }); + } + fx.push(RecoveryEffect::ShowError { refusal }); + self.state = State::Failed; + self.rescue = None; + } + } + Handled::Yes + } + /// The capability value this request plans and profiles from: `start` less the facets the rungs /// took out. A cheap `Arc` clone, so a worker or a flight can own it. pub fn attempt(&self) -> Arc { self.attempt.clone() } - /// Re-derive the attempt from `start` and `excluded`; a rung's entry is the only caller. - fn narrow(&mut self) { - self.attempt = Arc::new(attempt_for(&self.start, &self.excluded, self.in_app.as_deref())); - } + /// The codec the app-decode rung would put in force for this failure, when the rung is available: /// a pipeline refusal of a direct play that has shown no picture, whose audio the pipeline itself @@ -496,45 +645,26 @@ impl OpenRecovery { .then(|| Facet::Audio { codec: id.into_owned(), channels: audio.channels }) } - /// Fire the app-decode rung when it is available, else the failure read-out. Forced's ladder and a + /// Choose the app-decode rung when available, else the failure read-out. Forced's ladder and a /// refused both-facets flight end here. - fn app_decode_or_error(&mut self, refusal: LoadRefusal, facts: &OpenFacts, fx: &mut Vec) { - if self.try_app_decode(refusal, facts, fx) { - return; - } - fx.push(RecoveryEffect::ShowError { refusal }); - self.state = State::Failed; - self.rescue = None; - } - - /// Fire the app-decode rung when it is available and say so. The one place the rung's entry is - /// written: `in_app` set, the video facet cleared (the reload feeds the same source video, and a - /// lowered raster ceiling would shrink the Load's video envelope for nothing), the attempt - /// re-narrowed, no rescue to report (no flight flew), then the effect. - fn try_app_decode(&mut self, refusal: LoadRefusal, facts: &OpenFacts, fx: &mut Vec) -> bool { - let Some(audio) = self.app_decode_for(refusal, facts) else { - return false; - }; - if let Facet::Audio { codec, .. } = &audio { - self.in_app = Some(codec.clone()); + fn app_decode_or_error(&self, refusal: LoadRefusal, facts: &OpenFacts) -> RecoveryDecision { + match self.app_decode_for(refusal, facts) { + Some(audio) => RecoveryDecision::Decode(audio), + None => RecoveryDecision::Error { codec: None }, } - self.excluded.video = None; - self.narrow(); - self.state = State::Opening; - self.rescue = None; - fx.push(RecoveryEffect::DecodeInApp { audio, refusal }); - true } + + /// The manual both-facets rung, when it is earned: one encode with no video copy, the audio the /// attempt lacks converted with it. It fires from the facts alone, at most once: every both flight /// leaves an encoded video (`facts.video == None`) and its audio suspects taken, and the video /// facet's identical encode set `excluded.video`. It still fires for a refusal with no raster to /// lower (a 1080p frame rate): the video is fed at a known raster and nothing was excluded. Not for /// a cold Auto Original (its HLS rung is the video re-encode) or an Engine that showed a picture. - fn try_convert_both(&mut self, refusal: LoadRefusal, facts: &OpenFacts, fx: &mut Vec) -> bool { + fn try_convert_both(&self, refusal: LoadRefusal, facts: &OpenFacts) -> Option { if facts.auto_original || !facts.no_frames || !refusal.names_pipeline() || self.flights >= MAX_RECOVERY_FLIGHTS { - return false; + return None; } let audio = suspect_audio(facts.audio.as_ref()).filter(|f| self.attempt.without(f) != *self.attempt); let video = matches!(refusal, LoadRefusal::Refused { .. }) @@ -543,17 +673,9 @@ impl OpenRecovery { .filter(|f| self.attempt.without(f) != *self.attempt); let new_video = suspect_video(facts.video.as_ref()).is_some() && self.excluded.video.is_none(); if !new_video && audio.is_none() { - return false; - } - for facet in audio.into_iter().chain(video) { - self.excluded.take(facet); + return None; } - self.narrow(); - self.flights += 1; - fx.push(RecoveryEffect::ConvertBoth { flight: self.flights }); - self.state = State::Flight { rung: Rung::Encode, cause: refusal, facts: facts.clone() }; - self.rescue = Some(Rung::Encode); - true + Some(RecoveryDecision::Encode { audio, video }) } /// The codec Force Direct Play's read-out may name for `refusal`, or `None` when the refusal is not @@ -590,120 +712,54 @@ impl OpenRecovery { /// app mixes a surround source down only as the last rung), the read-out. The facet /// rung is for an Engine that has shown no picture (`facts.no_frames`: the picture is per /// Engine, so a reload after the request's first picture owes its own open the same rung). - fn decide(&mut self, refusal: LoadRefusal, facts: &OpenFacts, fx: &mut Vec) { - let flight = |rung| State::Flight { rung, cause: refusal, facts: facts.clone() }; - self.note_refusal(refusal, facts); + fn decide(&self, refusal: LoadRefusal, facts: &OpenFacts) -> RecoveryDecision { if facts.pending_original { - // A refusal of native audio (the learner's write was queued earlier in this step) - // narrows the rollback's profile too: the restored HLS route must not offer it natively - // again. - if let Some(facet) = facts.native_audio.as_ref().filter(|f| self.start.without(f) != *self.start) { - self.excluded.audio = Some(facet.clone()); - self.narrow(); - } - fx.push(RecoveryEffect::Rollback); - self.state = flight(Rung::Rollback); - self.rescue = Some(Rung::Rollback); - return; + let audio = facts.native_audio.as_ref() + .filter(|f| self.start.without(f) != *self.start).cloned(); + return RecoveryDecision::Rollback { audio }; } if facts.forced { - // A forced play is never converted, but the app can decode a stereo track the set refused (a - // surround track is not mixed down for it: `app_decode_for` declines, and the read-out follows). - if self.try_app_decode(refusal, facts, fx) { - return; + if let Some(audio) = self.app_decode_for(refusal, facts) { + return RecoveryDecision::Decode(audio); } - if let Some(codec) = self.refusal_attributable_to_audio(refusal, facts) { - fx.push(RecoveryEffect::NameRefusedAudio { codec }); - } - fx.push(RecoveryEffect::ShowError { refusal }); - self.state = State::Failed; - self.rescue = None; - return; + return RecoveryDecision::Error { codec: self.refusal_attributable_to_audio(refusal, facts) }; } if refusal.names_pipeline() && facts.no_frames && self.flights == 0 { - // The video facet rung runs only where no HLS contingency is retained: a cold Auto - // Original's HLS rung is already the video re-encode (ABR-managed), and only a refusal - // that gave a number can name a decode (`Stalled` is native audio's). + // A cold Auto Original already retains its video re-encode as the HLS rung. let video = facts.video.as_ref().filter(|_| !facts.auto_original && matches!(refusal, LoadRefusal::Refused { .. })); if let Some(facet) = suspect(facts.audio.as_ref(), video).filter(|f| self.start.without(f) != *self.start) { - // A flight after an app decode never proves a facet (`unprovable`). - self.unprovable |= facts.audio.as_ref().is_some_and(|a| a.app_decoded_lossy); - self.excluded.take(facet.clone()); - self.narrow(); - self.flights += 1; - fx.push(RecoveryEffect::ConvertFacet { facet, flight: self.flights }); - self.state = flight(Rung::Facet); - self.rescue = Some(Rung::Facet); - return; + return RecoveryDecision::Facet(facet); } } if facts.auto_original && facts.no_frames && self.flights < MAX_RECOVERY_FLIGHTS { - // The HLS attempt lacks every stream the refusal named that narrows `start`: the refused - // video raster (a numbered refusal) and native audio (any pipeline refusal). A timeout or - // a source failure names none, so main's attempt flies. - let audio = refusal.names_pipeline().then(|| suspect_audio(facts.audio.as_ref())).flatten(); - let video = matches!(refusal, LoadRefusal::Refused { .. }).then(|| suspect_video(facts.video.as_ref())).flatten(); - for facet in audio.into_iter().chain(video).filter(|f| self.start.without(f) != *self.start) { - self.excluded.take(facet); - } - self.narrow(); - self.flights += 1; - fx.push(RecoveryEffect::StartAutoHls); - self.state = flight(Rung::Both); - self.rescue = Some(Rung::Both); - return; + let audio = refusal.names_pipeline().then(|| suspect_audio(facts.audio.as_ref())).flatten() + .filter(|f| self.start.without(f) != *self.start); + let video = matches!(refusal, LoadRefusal::Refused { .. }).then(|| suspect_video(facts.video.as_ref())).flatten() + .filter(|f| self.start.without(f) != *self.start); + return RecoveryDecision::AutoHls { audio, video }; } - // The app decodes to stereo. For a source of at most two channels that loses nothing and keeps - // the direct play and asks the server nothing, so it comes before the manual encode (a refused - // conversion of the audio is decoded in the app, not converted twice). A surround source would - // lose its channels, so there (owner decision 2026-10-28) the encode, which keeps them, comes - // first and the app decode is the very last rung. + // Keep stereo direct play before encoding; preserve surround until the last rung. let mixes_down = facts.audio.as_ref().is_some_and(|a| plx_platform::devcaps::app_decode_mixes_down(i64::from(a.channels))); - if !mixes_down && self.try_app_decode(refusal, facts, fx) { - return; - } - if self.try_convert_both(refusal, facts, fx) { - return; - } - if mixes_down && self.try_app_decode(refusal, facts, fx) { - return; - } - fx.push(RecoveryEffect::ShowError { refusal }); - self.state = State::Failed; - self.rescue = None; - } - - /// Keep the request's first refusal the report can name ([`LoadRefusal::reports`]) and the - /// stream it put under suspicion: for a refusal that names the pipeline, the natively fed audio - /// it named, else [`suspect`] (the video only for a numbered refusal, which is what can name a - /// decode); none for a Load timeout. Later refusals, which are the failures of rescue - /// attempts, never replace it. - fn note_refusal(&mut self, refusal: LoadRefusal, facts: &OpenFacts) { - if self.refused.is_some() || !refusal.reports() { - return; + if !mixes_down { + if let Some(audio) = self.app_decode_for(refusal, facts) { + return RecoveryDecision::Decode(audio); + } } - // Only a refusal that names the pipeline puts a stream under suspicion: a Load timeout says - // nothing about the audio fed, and the ladder itself ignores it for one. - let facet = refusal.names_pipeline().then(|| { - let video = facts.video.as_ref().filter(|_| matches!(refusal, LoadRefusal::Refused { .. })); - facts.native_audio.clone().or_else(|| suspect(facts.audio.as_ref(), video)) - }); - self.refused = Some((refusal, facet.flatten())); - } - - /// The first picture of an open that rests on a rung's route: a rescued refusal, reported once - /// per request. - fn report_rescue(&mut self, fx: &mut Vec) { - let rung = self.rescue.take(); - if self.reported { - return; + if let Some(decision) = self.try_convert_both(refusal, facts) { + return decision; } - if let (Some(rung), Some((refusal, facet))) = (rung, &self.refused) { - self.reported = true; - fx.push(RecoveryEffect::ReportRecovered(Recovered { rung, refusal: *refusal, facet: facet.clone() })); + if mixes_down { + if let Some(audio) = self.app_decode_for(refusal, facts) { + return RecoveryDecision::Decode(audio); + } } + RecoveryDecision::Error { codec: None } } + + + + /// The one writer. The table (a pair not listed answers [`Handled::No`] and changes nothing): /// /// | state | event | effects, next state | @@ -756,93 +812,7 @@ impl OpenRecovery { /// `Proving` (kept, with the pending proof). The driver treats an unhandled `Refused` as the /// Engine failing for good, never as silence. pub fn step(&mut self, ev: &RecoveryEvent, fx: &mut Vec) -> Handled { - match ev { - RecoveryEvent::Refused { refusal, facts } => { - if !matches!(self.state, State::Opening | State::Proving { .. } | State::Playing) { - return Handled::No; - } - if let Some(facet) = &facts.native_audio { - fx.push(RecoveryEffect::ConfirmRefusal { facet: facet.clone(), evidence: Evidence::Named }); - } - self.decide(*refusal, facts, fx); - Handled::Yes - } - RecoveryEvent::FlightLanded { lanes } => { - let State::Flight { rung, .. } = &self.state else { - return Handled::No; - }; - let proven = (*rung == Rung::Facet && !self.pictured && !self.unprovable) - .then(|| self.excluded.iter().find(|f| proves(f, lanes.as_ref()))) - .flatten(); - self.state = match proven { - Some(facet) => State::Proving { facet: facet.clone(), loaded: false }, - None => State::Opening, - }; - Handled::Yes - } - RecoveryEvent::FlightRefused => { - let State::Flight { rung, cause, facts } = &self.state else { - return Handled::No; - }; - let (rung, cause, facts) = (*rung, *cause, facts.clone()); - match rung { - Rung::Facet => self.decide(cause, &facts, fx), - // The HLS contingency or the manual encode came back refused: the app decode is what is - // left (for a surround source, where it was held back for last, the very last rung; - // an encode is not a direct play, so its own refusal otherwise reads out). - Rung::Both | Rung::Encode => self.app_decode_or_error(cause, &facts, fx), - // A refused rollback stays terminal. - Rung::Rollback => { - fx.push(RecoveryEffect::ShowError { refusal: cause }); - self.state = State::Failed; - self.rescue = None; - } - } - Handled::Yes - } - RecoveryEvent::FirstPicture => match &self.state { - State::Opening => { - self.pictured = true; - self.state = State::Playing; - self.report_rescue(fx); - Handled::Yes - } - State::Proving { facet, .. } => { - fx.push(RecoveryEffect::ConfirmRefusal { facet: facet.clone(), evidence: Evidence::Proof }); - self.pictured = true; - self.state = State::Playing; - self.report_rescue(fx); - Handled::Yes - } - _ => Handled::No, - }, - RecoveryEvent::LoadStarted => match &mut self.state { - // The landing's own reload: `FlightLanded` moved the machine before the driver - // reloaded, so the first Load here is the one the landing asked for. - State::Proving { loaded: loaded @ false, .. } => { - *loaded = true; - Handled::Yes - } - // A second Load before the picture (a track switch, a restore after Home, a seek - // reload) is a route whose lanes were never read: the proof is dropped, and the new - // open is ruled on by the same ladder as below. - State::Proving { .. } | State::Flight { .. } | State::Failed => { - // The flight (if any) is gone with the Engine that waited on it, and the - // read-out belongs to the Engine that failed: the new Load is a new open, ruled - // on by the same ladder with what this request has already spent (`flights`, - // `excluded`). A flight that never landed or a read-out leaves the new open on - // no rung's route, so a picture from it is no rescue; a `Proving` state's route - // HAS landed (a track pick or a restore reloads that same installed route), so - // it keeps its rung, and only its proof is dropped. - if !matches!(self.state, State::Proving { .. }) { - self.rescue = None; - } - self.state = State::Opening; - Handled::Yes - } - State::Opening | State::Playing => Handled::No, - }, - } + self.transition(ev, fx) } /// Read-only view of the machine for tests; every write goes through [`step`](Self::step). @@ -873,6 +843,29 @@ pub enum Phase { mod tests { use super::*; + #[test] + fn ignored_events_keep_all_bookkeeping_and_proof_precedes_the_rescue_report() { + let mut m = OpenRecovery::new(opus_start()); + assert_eq!(run(&mut m, refused(NATIVE, names_opus(facts(false, false, true)))), + (Handled::Yes, vec![named(opus6()), RecoveryEffect::ConvertFacet { facet: opus6(), flight: 1 }])); + let before = format!("{m:?}"); + for ev in [refused(SHUT, on_dts(facts(true, true, true))), RecoveryEvent::FirstPicture] { + assert_eq!(run(&mut m, ev), (Handled::No, vec![])); + assert_eq!(format!("{m:?}"), before); + } + assert_eq!(run(&mut m, landed_with(CLEAN)), (Handled::Yes, vec![])); + assert_eq!(run(&mut m, RecoveryEvent::LoadStarted), (Handled::Yes, vec![])); + assert_eq!(run(&mut m, RecoveryEvent::FirstPicture), (Handled::Yes, vec![ + proof(opus6()), + RecoveryEffect::ReportRecovered(Recovered { rung: Rung::Facet, refusal: NATIVE, facet: Some(opus6()) }), + ])); + let before = format!("{m:?}"); + assert_eq!(run(&mut m, RecoveryEvent::FirstPicture), (Handled::No, vec![])); + assert_eq!(format!("{m:?}"), before); + assert_eq!(m.flights, 1); + assert!(m.reported && m.pictured && m.rescue.is_none()); + } + fn dts6() -> Facet { Facet::Audio { codec: "dts".into(), channels: 6 } } diff --git a/rust-modules/net/src/net.rs b/rust-modules/net/src/net.rs index 10199a8d60..b1d578750d 100644 --- a/rust-modules/net/src/net.rs +++ b/rust-modules/net/src/net.rs @@ -1542,9 +1542,11 @@ mod loopback_pms { } let reply = answer(&request); log.lock().unwrap_or_else(|e| e.into_inner()).push(request); - if tls.write_all(&reply).is_err() || tls.flush().is_err() || !keep_alive { - return; - } + if tls.write_all(&reply).is_err() { return; } + // OpenSSL must see an orderly TLS close to keep the TLS 1.3 session + // resumable after this response, not just a bare TCP EOF. + if !keep_alive { tls.conn.send_close_notify(); } + if tls.flush().is_err() || !keep_alive { return; } } }); } @@ -5099,6 +5101,20 @@ mod tls_mode_tests { #[cfg(test)] mod blocking_guard_tests { + #[test] + fn a_logic_step_cannot_dial_even_under_allow_blocking() { + let allowed = plx_base::task::allow_blocking(const { &plx_base::task::BlockingLabel::new("fixture") }); + let step = plx_base::step::StepScope::enter(); + let refused = std::panic::catch_unwind(|| { + super::request_evidence("https://plex.tv.invalid/ping", &[], "GET", None, super::API, false, None, None) + }); + assert!(refused.is_err()); + drop(step); + // A malformed URL returns before curl or DNS, proving the guard unwound and did not leak. + assert!(super::request_result("bad\0url", &[], "GET", None, super::API, false, None, None).is_err()); + drop(allowed); + } + use super::*; /// plex.tv calls (`AccountClient`) never pass `http::request_with`, so its `assert_may_block` diff --git a/rust-modules/net/src/net/h2_reset_fixture.py b/rust-modules/net/src/net/h2_reset_fixture.py index 1840adeb64..f550074269 100644 --- a/rust-modules/net/src/net/h2_reset_fixture.py +++ b/rust-modules/net/src/net/h2_reset_fixture.py @@ -12,7 +12,6 @@ import subprocess import sys import tempfile -import time def frame(kind, flags, stream, payload=b""): @@ -73,7 +72,22 @@ def main(): # Literal without indexing, indexed :status name, three ASCII digits. peer.sendall(frame(1, 4, stream, b"\x08\x03" + str(status).encode("ascii"))) peer.sendall(frame(0, 0, stream, b"short")) # no END_STREAM - time.sleep(0.05) + # A timer cannot prove the client consumed HEADERS under load. + # Its PING ACK fences processing of the preceding status and DATA. + ping = b"headers!" + peer.sendall(frame(6, 0, 0, ping)) + while True: + ack = receive(peer, 9) + ack_length = int.from_bytes(ack[:3], "big") + assert ack_length <= 16384 + ack_payload = receive(peer, ack_length) + ack_kind, ack_flags = ack[3], ack[4] + ack_stream = int.from_bytes(ack[5:], "big") & 0x7fffffff + if ack_kind == 4 and not ack_flags & 1: + peer.sendall(frame(4, 1, 0)) + if ack_kind == 6 and ack_flags & 1 and ack_stream == 0: + assert ack_payload == ping + break peer.sendall(frame(3, 0, stream, (2).to_bytes(4, "big"))) # INTERNAL_ERROR print("h2-reset-sent", flush=True) break diff --git a/rust-modules/play-uri/src/picture_gate.rs b/rust-modules/play-uri/src/picture_gate.rs index 54464d295a..7e64635fd4 100644 --- a/rust-modules/play-uri/src/picture_gate.rs +++ b/rust-modules/play-uri/src/picture_gate.rs @@ -29,6 +29,8 @@ //! **Shape.** Pure, like `acb_bind`: no clock, no global, no IO. An event goes in, [`Fx`] come out; //! the backend feeds the events and turns the effect into the observation and its log line. +#![deny(clippy::wildcard_enum_match_arm)] + /// What the backend observed. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Event { @@ -92,8 +94,11 @@ impl PictureGate { } pub fn step(&mut self, event: Event, fx: &mut Vec) { + self.transition(event, fx); + } + fn transition(&mut self, event: Event, fx: &mut Vec) { match event { - Event::Reset => *self = Self::new(), + Event::Reset => { self.stage = Stage::Neither; self.last_ms = None; }, Event::Seeked => self.last_ms = None, Event::PlaneFailed => { if self.stage != Stage::Presented { @@ -104,14 +109,14 @@ impl PictureGate { self.stage = match self.stage { Stage::Neither => Stage::ServiceOnly, Stage::PlaneOnly => Stage::Armed, - other => other, + other @ (Stage::ServiceOnly | Stage::Armed | Stage::Presented | Stage::Refused) => other, }; } Event::PlaneShown => { self.stage = match self.stage { Stage::Neither => Stage::PlaneOnly, Stage::ServiceOnly => Stage::Armed, - other => other, + other @ (Stage::PlaneOnly | Stage::Armed | Stage::Presented | Stage::Refused) => other, }; } Event::Clock(ms) => { diff --git a/rust-modules/play-uri/src/uriprobe.rs b/rust-modules/play-uri/src/uriprobe.rs index 1750e2a0e6..0b102e0817 100644 --- a/rust-modules/play-uri/src/uriprobe.rs +++ b/rust-modules/play-uri/src/uriprobe.rs @@ -1,3 +1,4 @@ +#![deny(clippy::wildcard_enum_match_arm)] //! The URI-mode probe machine (issue #1064, the first test): what to say to `com.webos.media`, in //! what order, and what each answer means, as a tested `State + Event -> Effects` machine in the //! shape of `plx_media::player::lifecycle::ForegroundLifecycle` (not linked: that crate is above this one). @@ -351,7 +352,7 @@ enum Phase { impl Phase { /// The name a failure in this phase is reported under. - fn name(self) -> &'static str { + fn name(&self) -> &'static str { match self { Phase::Idle | Phase::Registering { .. } | Phase::AwaitingClose => "register", Phase::Acb => "acb", @@ -412,20 +413,9 @@ struct PauseSamples { } impl PauseSamples { - fn begin(&mut self, now_ms: u64) { - *self = Self { started_ms: Some(now_ms), ..Self::default() }; - } - fn observe(&mut self, now_ms: u64, position: i64) { - if self.ended_ms.is_some() || !self.started_ms.is_some_and(|at| now_ms > at) { return; } - self.first.get_or_insert((now_ms, position)); - self.last = Some((now_ms, position)); - self.range = Some(match self.range { - Some((low, high)) => (low.min(position), high.max(position)), - None => (position, position), - }); - self.reports = self.reports.saturating_add(1); - } + + fn end_fresh(&self) -> bool { self.last.zip(self.ended_ms).is_some_and(|((at, _), end)| at == end) @@ -459,12 +449,7 @@ struct ReportClock { } impl ReportClock { - fn observe(&mut self, now_ms: u64) { - if let Some(last) = self.last_ms { - *self.gaps.entry(now_ms.saturating_sub(last)).or_insert(0) += 1; - } - self.last_ms = Some(now_ms); - } + /// The median gap; for an even count the smaller of the two middle gaps, so the answer is a /// gap that happened. `None` before the second report. @@ -557,11 +542,11 @@ impl Default for Facts { } } -/// The probe. State is private; the one writer is [`step`](UriProbe::step). +/// The probe. State is private; events enter through [`step`](UriProbe::step). pub struct UriProbe { config: Config, phase: Phase, - /// The identity this session registers as; the ladder moves it (see `next_shape_or_stop`). + /// The identity this session registers as; refusal events advance it along the ladder. shape: Shape, /// The identities refused so far: the input of `register_ladder::decide`. refused: Vec, @@ -582,7 +567,7 @@ pub struct UriProbe { impl std::fmt::Debug for UriProbe { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "UriProbe {{ phase: {:?}, shape: {:?} }}", self.phase, self.shape) + write!(f, "UriProbe {{ phase: {:?}, shape: {:?} }}", &self.phase, self.shape) } } @@ -612,530 +597,575 @@ impl UriProbe { } } - /// The session is over (everything it will say has been said). - pub fn is_done(&self) -> bool { - self.phase == Phase::Done - } - - /// From `playing` until the end: the service has said the video plays. A claim about the - /// service, not an observation of the plane. - pub fn plane_open(&self) -> bool { - matches!(self.phase, Phase::Playing { .. } | Phase::Driving { .. }) - } - - /// Apply one event at `now_ms`, pushing what the driver must execute onto `fx`, in order. Once - /// the session is `Done` nothing moves and nothing is pushed. - pub fn step(&mut self, ev: UriEvent, now_ms: u64, fx: &mut Vec) { - if self.phase == Phase::Done { - return; - } - match ev { - UriEvent::Start => self.start(now_ms, fx), - UriEvent::Back => self.stop(now_ms, End::Back, fx), - UriEvent::Closed if self.phase == Phase::AwaitingClose => { + /// The only writer of probe state. Continuations borrow only this input, never the model. + fn transition(&mut self, ev: UriEvent, now_ms: u64, fx: &mut Vec) { + if self.phase == Phase::Done { return; } + enum Work<'a> { + Start, + Tick, + Reply { method: Method, ok: bool, message: &'a Message }, + Service { method: Method, ok: bool, message: &'a Message }, + ServiceAfterVideo { method: Method, ok: bool, message: &'a Message }, + Events { message: &'a Message, index: usize }, + Seen { seen: &'a Seen, message: &'a Message }, + CurrentTime { seen: &'a Seen, message: &'a Message }, + Loaded { message: &'a Message }, + Acb { event: AcbEvent, now_ms: u64 }, + Drive { step: usize }, + NextShape { end: End }, + Stop { end: End }, + Finished, + } + let mut work = match &ev { + UriEvent::Start => Work::Start, + UriEvent::Back => Work::Stop { end: End::Back }, + UriEvent::Closed if matches!(self.phase, Phase::AwaitingClose) => { self.phase = Phase::Registering { deadline: now_ms.saturating_add(REGISTER_TIMEOUT_MS) }; fx.push(UriEffect::Open(self.shape)); + Work::Finished } - UriEvent::Closed => {}, - UriEvent::AcbReleaseTail {..} => {}, - UriEvent::AcbAnswered {request, invoked, completed_ms} => self.acb_event(AcbEvent::Answered {request, invoked, completed_ms}, completed_ms, fx), - UriEvent::Dispatched { method, kind, request } => { self.requests.insert((method, kind), request); }, - UriEvent::Tick => self.tick(now_ms, fx), - UriEvent::Reply { method, ok, message } => self.reply(method, ok, &message, now_ms, fx), - } - } - - fn line(&self, now_ms: u64, body: &str) -> UriEffect { - UriEffect::Log(format!("uriprobe: t={} {body}", now_ms.saturating_sub(self.started_ms))) - } - - fn start(&mut self, now_ms: u64, fx: &mut Vec) { - if self.phase != Phase::Idle { - return; - } - self.started_ms = now_ms; - let c = &self.config; - let window = if c.window_id.is_some() { "exported" } else { "none" }; - let kind = match c.kind { - Kind::Direct => "direct", - Kind::Hls => "hls", - }; - let armed = format!( - "armed variant={} scheme={} kind={kind} window={window} app={} fw={} build={}{}", - c.variant.label(), - c.scheme.label(), - c.app_id, - firmware_word(&c.firmware.release), - firmware_word(&c.firmware.build), - c.bps.label(), - ); - fx.push(self.line(now_ms, &armed)); - if self.config.variant.acb() { self.acb_event(AcbEvent::Start, now_ms, fx); } - else { - self.phase = Phase::Registering { deadline: now_ms + REGISTER_TIMEOUT_MS }; - fx.push(UriEffect::Open(self.shape)); - } - } - - /// An accepted call starts provisional. An explicit paused observation can confirm pause; - /// track confirmation requires identified correlation. Generic seekDone and trackSelected - /// notifications remain observations, not proof of a particular command. - fn outcome(ok: bool, denied: bool) -> CallResult { - if ok && !denied { CallResult::Unconfirmed } else { CallResult::Refused } - } - - /// The tail of a call's log line: `ok`, or `err()`. - fn said(ok: bool, denied: bool, text: &str) -> String { - if ok && !denied { "ok".to_owned() } else { format!("err({text})") } - } - - fn tick(&mut self, now_ms: u64, fx: &mut Vec) { - match self.phase { - Phase::Acb => self.acb_event(AcbEvent::Tick, now_ms, fx), - Phase::Registering { deadline } if now_ms >= deadline => self.stop(now_ms, End::Timeout("register"), fx), - Phase::Loading { deadline } if now_ms >= deadline => self.stop(now_ms, End::Timeout("load"), fx), - Phase::SettingWindow { deadline } if now_ms >= deadline => { - self.facts.window_call = WindowCall::Silent; - fx.push(self.line(now_ms, "call setWindowId no reply, playing anyway")); - self.play(now_ms, fx); + UriEvent::Closed | UriEvent::AcbReleaseTail { .. } => Work::Finished, + UriEvent::AcbAnswered { request, invoked, completed_ms } => Work::Acb { + event: AcbEvent::Answered { request: *request, invoked: *invoked, completed_ms: *completed_ms }, + now_ms: *completed_ms, + }, + UriEvent::Dispatched { method, kind, request } => { + self.requests.insert((*method, *kind), *request); + Work::Finished } - Phase::Starting { deadline } if now_ms >= deadline => self.stop(now_ms, End::Timeout("play"), fx), - Phase::Playing { frozen_at } if self.facts.time_moved.is_some() && now_ms >= frozen_at => { - self.stop(now_ms, End::Timeout("currentTime"), fx) - } - Phase::Driving { step, deadline } if now_ms >= deadline => self.drive_step(step, now_ms, fx), - _ => {} - } - } - - /// One step of the transport script. Each step sends its call, logs what it asked for (with the - /// position it can see), and schedules the next; the last one ends the session, so a tester - /// without a picture still learns whether the pipeline accepted the calls. - fn drive_step(&mut self, step: usize, now_ms: u64, fx: &mut Vec) { - let Some(media_id) = self.media_id.clone() else { - self.stop(now_ms, End::Script, fx); - return; + UriEvent::Tick => Work::Tick, + UriEvent::Reply { method, ok, message } => Work::Reply { method: *method, ok: *ok, message }, }; - let position = |p: Option| p.map_or_else(|| "-".to_owned(), |v| v.to_string()); - match step { - 0 => { - self.facts.pause_samples.begin(now_ms); - self.facts.pause_pos = self.last_time; - fx.push(self.line(now_ms, &format!("drive pause pos={}", position(self.facts.pause_pos)))); - fx.push(UriEffect::Call(UriCall::Pause { media_id })); - } - 1 => { - self.facts.pause_samples.ended_ms = Some(now_ms); - self.facts.resume_pos = self.last_time; - self.facts.resume_sent = true; - self.facts.resume = CallResult::Unconfirmed; - fx.push(self.line(now_ms, &format!("drive resume pos={}", position(self.facts.resume_pos)))); - fx.push(UriEffect::Call(UriCall::Play { media_id })); - } - 2 => { - let target = self.last_time.unwrap_or(0).max(0).saturating_add(DRIVE_SEEK_MS); - self.facts.seek_target = Some(target); - fx.push(self.line(now_ms, &format!("drive seek target={target}"))); - fx.push(UriEffect::Call(UriCall::Seek { media_id, position: target })); - } - 3 => { - self.facts.text_select_sent = true; - self.facts.track_pending = Some("text"); - fx.push(self.line(now_ms, "drive selectTrack type=text index=0")); - fx.push(UriEffect::Call(UriCall::SelectTrack { media_id, kind: "text", index: 0 })); - } - 4 => { - self.facts.track_pending = Some("audio"); - fx.push(self.line(now_ms, "drive selectTrack type=audio index=1")); - fx.push(UriEffect::Call(UriCall::SelectTrack { media_id, kind: "audio", index: 1 })); - } - 5 => { - fx.push(self.line(now_ms, "drive subtitles enable")); - fx.push(UriEffect::Call(UriCall::SetSubtitleEnable { media_id, enable: true })); - } - _ => { - self.stop(now_ms, End::Script, fx); - return; - } - } - self.phase = Phase::Driving { step: step + 1, deadline: now_ms + DRIVE_STEP_MS }; - } - - fn reply(&mut self, method: Method, ok: bool, message: &Message, now_ms: u64, fx: &mut Vec) { - if method == Method::Dropped { - let count = message.dropped.unwrap_or(0); - fx.push(self.line(now_ms, &format!("transport dropped {count} replies"))); - self.stop(now_ms, End::Refused("overflow"), fx); - return; - } - match self.phase { - Phase::Registering { .. } if method == Method::Register => { - let shape = register_ladder::label(self.shape); - if ok { - fx.push(self.line(now_ms, &format!("register shape={shape} ok"))); - self.phase = Phase::Loading { deadline: now_ms + LOAD_TIMEOUT_MS }; - let window_id = if self.config.variant.acb() { Some(super::acb_bind::DUMMY_WINDOW_ID.to_owned()) } - else if self.config.variant.binds_at_load() { self.config.window_id.clone() } else { None }; - fx.push(UriEffect::Call(UriCall::Load { window_id, bps: self.config.bps })); - } else { - fx.push(self.line(now_ms, &format!("register shape={shape} refused({})", message.why()))); - self.next_shape_or_stop(now_ms, End::Refused("register"), fx); - } - } - Phase::Loading { .. } | Phase::SettingWindow { .. } | Phase::Starting { .. } | Phase::Playing { .. } | Phase::Driving { .. } | Phase::Acb => { - self.service_message(method, ok, message, now_ms, fx) - } - _ => {} - } - } - - /// A refused registration or a denied load: the named client gives way to the anonymous one, - /// once; a refusal of the anonymous one ends the session. - fn next_shape_or_stop(&mut self, now_ms: u64, end: End, fx: &mut Vec) { - self.refused.push(Outcome::Refused); - match register_ladder::decide(&self.refused) { - Step::Register(shape) => { - self.shape = shape; - self.media_id = None; - self.subscribed = false; - fx.push(UriEffect::Close); - self.phase = Phase::AwaitingClose; - } - Step::Settled(_) | Step::Failed(_) => self.stop(now_ms, end, fx), - } - } - - fn service_message(&mut self, method: Method, ok: bool, message: &Message, now_ms: u64, fx: &mut Vec) { - if self.requests.get(&(method, message.reply_track)).is_some_and(|request| message.reply_request != Some(*request)) { return; } - if message.identity_conflict || (self.media_id.is_some() && message.media_id.is_some() && self.media_id != message.media_id) { return; } - if let Some(video) = message.video_info { - self.acb_event(AcbEvent::Video(video), now_ms, fx); - } - let denied = !ok || message.return_value == Some(false); - let text = message.why(); - if let Some(kind) = message.confirmed_track { - match kind { "text" => self.facts.text = CallResult::Ok, "audio" => self.facts.audio = CallResult::Ok, _ => {} } - } - match method { - Method::Load if denied && self.media_id.is_none() && matches!(self.phase, Phase::Loading { .. }) => { - fx.push(self.line(now_ms, &format!("call load err({text})"))); - self.next_shape_or_stop(now_ms, End::Refused("load"), fx); - return; - } - Method::Subscribe | Method::Load if denied => { - fx.push(self.line(now_ms, &format!("call {} err({text})", if method == Method::Load { "load" } else { "subscribe" }))); - } - Method::Play if denied => { - fx.push(self.line(now_ms, &format!("call play err({text})"))); - if matches!(self.phase, Phase::Driving { .. }) { - // A refused resume is a finding, not the end of the session: the script still - // has the seek and the track calls to ask about. - self.facts.resume = CallResult::Refused; - return; + // Video handling finishes before the service reply resumes; each seen item finishes before + // the next one. These continuations never nest, so no heap queue or model copy is needed. + let mut continuation = None; + 'reduce: loop { + match work { + Work::Finished => { + if let Some(next) = continuation.take() { work = next; continue 'reduce; } + break; } - self.stop(now_ms, End::Refused("play"), fx); - return; - } - Method::NotifyForeground => { - fx.push(self.line(now_ms, &format!("call notifyForeground {}", Self::said(ok, denied, &text)))); - if denied { self.stop(now_ms, End::Refused("notifyForeground"), fx); } - return; - } - Method::Pause => { - self.facts.pause = Self::outcome(ok, denied); - fx.push(self.line(now_ms, &format!("call pause {}", Self::said(ok, denied, &text)))); - return; - } - Method::Seek => { - self.facts.seek = Self::outcome(ok, denied); - fx.push(self.line(now_ms, &format!("call seek {}", Self::said(ok, denied, &text)))); - return; - } - Method::SelectTrack => { - let kind = message.reply_track.or_else(|| self.facts.track_pending.take()).unwrap_or("track"); - let outcome = Self::outcome(ok, denied); - match kind { - "text" => if self.facts.text != CallResult::Ok || outcome == CallResult::Refused { self.facts.text = outcome }, - "audio" => if self.facts.audio != CallResult::Ok || outcome == CallResult::Refused { self.facts.audio = outcome }, - _ => {}, + Work::Service { method, ok, message } => { + if self.requests.get(&(method, message.reply_track)).is_some_and(|request| message.reply_request != Some(*request)) { work = Work::Finished; continue 'reduce; } + if message.identity_conflict || (self.media_id.is_some() && message.media_id.is_some() && self.media_id != message.media_id) { work = Work::Finished; continue 'reduce; } + if let Some(video) = message.video_info { + debug_assert!(continuation.is_none()); + continuation = Some(Work::ServiceAfterVideo { method, ok, message }); + work = Work::Acb { event: AcbEvent::Video(video), now_ms }; continue 'reduce; + } + work = Work::ServiceAfterVideo { method, ok, message }; continue 'reduce; } - fx.push(self.line(now_ms, &format!("call selectTrack {kind} {}", Self::said(ok, denied, &text)))); - return; - } - Method::SetSubtitleEnable => { - // No event confirms this call: its own reply is the whole answer. - self.facts.subs = if denied { CallResult::Refused } else if message.return_value == Some(true) { CallResult::Ok } else { CallResult::Unconfirmed }; - fx.push(self.line(now_ms, &format!("call setSubtitleEnable {}", Self::said(ok, denied, &text)))); - return; - } - Method::SetWindowId => { - if !denied && message.return_value != Some(true) { return; } - if denied { - self.facts.window_call = WindowCall::Refused; - fx.push(self.line(now_ms, &format!("call setWindowId err({text})"))); - } else { - self.facts.window_call = WindowCall::Answered; - fx.push(self.line(now_ms, "call setWindowId ok")); + Work::Events { message, index } => { + if self.phase == Phase::Done { work = Work::Finished; continue 'reduce; } + let Some(seen) = message.seen.get(index) else { + if message.seen.is_empty() { + if let Some(name) = &message.unknown { fx.push(self.line(now_ms, &unparsed_text(name))); } + } + work = Work::Finished; continue 'reduce; + }; + let normalized = message.normalized.contains(&seen.ev); + if normalized || seen.ev == Ev::CurrentTime { + debug_assert!(continuation.is_none()); + continuation = Some(Work::Events { message, index: index + 1 }); + work = if normalized { + Work::Seen { seen, message } + } else { Work::CurrentTime { seen, message } }; continue 'reduce; + } + fx.push(self.line(now_ms, &event_text(message, seen, false))); + work = Work::Events { message, index: index + 1 }; continue 'reduce; } - if matches!(self.phase, Phase::SettingWindow { .. }) { - self.play(now_ms, fx); + Work::Start => { + if self.phase != Phase::Idle { + work = Work::Finished; continue 'reduce; + } + self.started_ms = now_ms; + let c = &self.config; + let window = if c.window_id.is_some() { "exported" } else { "none" }; + let kind = match c.kind { + Kind::Direct => "direct", + Kind::Hls => "hls", + }; + let armed = format!( + "armed variant={} scheme={} kind={kind} window={window} app={} fw={} build={}{}", + c.variant.label(), + c.scheme.label(), + c.app_id, + firmware_word(&c.firmware.release), + firmware_word(&c.firmware.build), + c.bps.label(), + ); + fx.push(self.line(now_ms, &armed)); + if self.config.variant.acb() { work = Work::Acb { event: AcbEvent::Start, now_ms }; continue 'reduce; } + else { + self.phase = Phase::Registering { deadline: now_ms + REGISTER_TIMEOUT_MS }; + fx.push(UriEffect::Open(self.shape)); + } } - return; - } - Method::Load | Method::Subscribe | Method::Play if !denied && message.return_value == Some(true) && !message.has_events() => { - if method == Method::Play && matches!(self.phase, Phase::Driving { .. }) { - self.facts.resume = CallResult::Unconfirmed; + Work::Tick => { + match self.phase { + Phase::Acb => { work = Work::Acb { event: AcbEvent::Tick, now_ms }; continue 'reduce; }, + Phase::Registering { deadline } if now_ms >= deadline => { work = Work::Stop { end: End::Timeout("register") }; continue 'reduce; }, + Phase::Loading { deadline } if now_ms >= deadline => { work = Work::Stop { end: End::Timeout("load") }; continue 'reduce; }, + Phase::SettingWindow { deadline } if now_ms >= deadline => { + self.facts.window_call = WindowCall::Silent; + fx.push(self.line(now_ms, "call setWindowId no reply, playing anyway")); + if let Some(media_id) = self.media_id.clone() { + self.phase = Phase::Starting { deadline: now_ms + PLAY_TIMEOUT_MS }; + fx.push(UriEffect::Call(UriCall::Play { media_id })); + } + } + Phase::Starting { deadline } if now_ms >= deadline => { work = Work::Stop { end: End::Timeout("play") }; continue 'reduce; }, + Phase::Playing { frozen_at } if self.facts.time_moved.is_some() && now_ms >= frozen_at => { + { work = Work::Stop { end: End::Timeout("currentTime") }; continue 'reduce; } + } + Phase::Driving { step, deadline } if now_ms >= deadline => { work = Work::Drive { step }; continue 'reduce; }, + Phase::Idle | Phase::Registering { .. } | Phase::AwaitingClose | Phase::Loading { .. } | Phase::SettingWindow { .. } | Phase::Starting { .. } | Phase::Playing { .. } | Phase::Driving { .. } | Phase::Done => {} + } } - fx.push(self.line(now_ms, &format!("call {} ok", match method { - Method::Load => "load", - Method::Subscribe => "subscribe", - _ => "play", - }))); - } - _ => {} - } - if self.media_id.is_none() && !denied { - self.media_id = message.media_id.clone(); - } - if let (Some(media_id), false) = (self.media_id.clone(), self.subscribed) { - self.subscribed = true; - if self.config.variant.acb() && !self.foreground_sent { - self.foreground_sent = true; - fx.push(UriEffect::Call(UriCall::NotifyForeground {media_id: media_id.clone()})); - } - fx.push(UriEffect::Call(UriCall::Subscribe { media_id })); - } - self.events(message, now_ms, fx); - } - - fn events(&mut self, message: &Message, now_ms: u64, fx: &mut Vec) { - for seen in &message.seen { - if self.phase == Phase::Done { - return; - } - if message.normalized.contains(&seen.ev) { self.event(seen, message, now_ms, fx); } - else if seen.ev == Ev::CurrentTime { self.current_time(seen, message, now_ms, fx); } - else { fx.push(self.line(now_ms, &event_text(message, seen, false))); } - } - if message.seen.is_empty() { - if let Some(name) = &message.unknown { - fx.push(self.line(now_ms, &unparsed_text(name))); - } - } - } - - fn event(&mut self, seen: &Seen, message: &Message, now_ms: u64, fx: &mut Vec) { - if seen.ev != Ev::CurrentTime { - fx.push(self.line(now_ms, &event_text(message, seen, false))); - } - match seen.ev { - Ev::Error => self.stop(now_ms, End::Error(message.error_code), fx), - Ev::LoadCompleted => { - if matches!(self.phase, Phase::Loading { .. }) { - self.loaded(message, now_ms, fx); + Work::Drive { step } => { + let Some(media_id) = self.media_id.clone() else { + work = Work::Stop { end: End::Script }; continue 'reduce; + }; + let position = |p: Option| p.map_or_else(|| "-".to_owned(), |v| v.to_string()); + match step { + 0 => { + self.facts.pause_samples = PauseSamples { started_ms: Some(now_ms), ended_ms: None, first: None, last: None, range: None, reports: 0 }; + self.facts.pause_pos = self.last_time; + fx.push(self.line(now_ms, &format!("drive pause pos={}", position(self.facts.pause_pos)))); + fx.push(UriEffect::Call(UriCall::Pause { media_id })); + } + 1 => { + self.facts.pause_samples.ended_ms = Some(now_ms); + self.facts.resume_pos = self.last_time; + self.facts.resume_sent = true; + self.facts.resume = CallResult::Unconfirmed; + fx.push(self.line(now_ms, &format!("drive resume pos={}", position(self.facts.resume_pos)))); + fx.push(UriEffect::Call(UriCall::Play { media_id })); + } + 2 => { + let target = self.last_time.unwrap_or(0).max(0).saturating_add(DRIVE_SEEK_MS); + self.facts.seek_target = Some(target); + fx.push(self.line(now_ms, &format!("drive seek target={target}"))); + fx.push(UriEffect::Call(UriCall::Seek { media_id, position: target })); + } + 3 => { + self.facts.text_select_sent = true; + self.facts.track_pending = Some("text"); + fx.push(self.line(now_ms, "drive selectTrack type=text index=0")); + fx.push(UriEffect::Call(UriCall::SelectTrack { media_id, kind: "text", index: 0 })); + } + 4 => { + self.facts.track_pending = Some("audio"); + fx.push(self.line(now_ms, "drive selectTrack type=audio index=1")); + fx.push(UriEffect::Call(UriCall::SelectTrack { media_id, kind: "audio", index: 1 })); + } + 5 => { + fx.push(self.line(now_ms, "drive subtitles enable")); + fx.push(UriEffect::Call(UriCall::SetSubtitleEnable { media_id, enable: true })); + } + _ => { + work = Work::Stop { end: End::Script }; continue 'reduce; + } + } + self.phase = Phase::Driving { step: step + 1, deadline: now_ms + DRIVE_STEP_MS }; } - } - Ev::Playing => { - if self.facts.playing_ms.is_none() { - self.facts.playing_ms = Some(now_ms.saturating_sub(self.started_ms)); + Work::Reply { method, ok, message } => { + if method == Method::Dropped { + let count = message.dropped.unwrap_or(0); + fx.push(self.line(now_ms, &format!("transport dropped {count} replies"))); + work = Work::Stop { end: End::Refused("overflow") }; continue 'reduce; + } + match self.phase { + Phase::Registering { .. } if method == Method::Register => { + let shape = register_ladder::label(self.shape); + if ok { + fx.push(self.line(now_ms, &format!("register shape={shape} ok"))); + self.phase = Phase::Loading { deadline: now_ms + LOAD_TIMEOUT_MS }; + let window_id = if self.config.variant.acb() { Some(super::acb_bind::DUMMY_WINDOW_ID.to_owned()) } + else if self.config.variant.binds_at_load() { self.config.window_id.clone() } else { None }; + fx.push(UriEffect::Call(UriCall::Load { window_id, bps: self.config.bps })); + } else { + fx.push(self.line(now_ms, &format!("register shape={shape} refused({})", message.why()))); + work = Work::NextShape { end: End::Refused("register") }; continue 'reduce; + } + } + Phase::Loading { .. } | Phase::SettingWindow { .. } | Phase::Starting { .. } | Phase::Playing { .. } | Phase::Driving { .. } | Phase::Acb => { + { work = Work::Service { method, ok, message }; continue 'reduce; } + } + Phase::Idle | Phase::Registering { .. } | Phase::AwaitingClose | Phase::Done => {} + } } - if matches!(self.phase, Phase::Starting { .. }) { - self.phase = if self.config.transport { - Phase::Driving { step: 0, deadline: now_ms + DRIVE_FIRST_MS } - } else { - Phase::Playing { frozen_at: now_ms + FROZEN_TIME_MS } - }; + Work::NextShape { end } => { + self.refused.push(Outcome::Refused); + match register_ladder::decide(&self.refused) { + Step::Register(shape) => { + self.shape = shape; + self.media_id = None; + self.subscribed = false; + fx.push(UriEffect::Close); + self.phase = Phase::AwaitingClose; + } + Step::Settled(_) | Step::Failed(_) => { work = Work::Stop { end: end }; continue 'reduce; }, + } } - } - Ev::Paused => { - let samples = &self.facts.pause_samples; - self.facts.paused_ev |= samples.started_ms.is_some() && samples.ended_ms.is_none(); - if self.facts.pause == CallResult::Unconfirmed { - self.facts.pause = CallResult::Ok; + Work::ServiceAfterVideo { method, ok, message } => { + + let denied = !ok || message.return_value == Some(false); + let text = message.why(); + if let Some(kind) = message.confirmed_track { + match kind { "text" => self.facts.text = CallResult::Ok, "audio" => self.facts.audio = CallResult::Ok, _ => {} } + } + match method { + Method::Load if denied && self.media_id.is_none() && matches!(self.phase, Phase::Loading { .. }) => { + fx.push(self.line(now_ms, &format!("call load err({text})"))); + work = Work::NextShape { end: End::Refused("load") }; continue 'reduce; + } + Method::Subscribe | Method::Load if denied => { + fx.push(self.line(now_ms, &format!("call {} err({text})", if method == Method::Load { "load" } else { "subscribe" }))); + } + Method::Play if denied => { + fx.push(self.line(now_ms, &format!("call play err({text})"))); + if matches!(self.phase, Phase::Driving { .. }) { + // A refused resume is a finding, not the end of the session: the script still + // has the seek and the track calls to ask about. + self.facts.resume = CallResult::Refused; + work = Work::Finished; continue 'reduce; + } + work = Work::Stop { end: End::Refused("play") }; continue 'reduce; + } + Method::NotifyForeground => { + fx.push(self.line(now_ms, &format!("call notifyForeground {}", Self::said(ok, denied, &text)))); + if denied { work = Work::Stop { end: End::Refused("notifyForeground") }; continue 'reduce; } + work = Work::Finished; continue 'reduce; + } + Method::Pause => { + self.facts.pause = Self::outcome(ok, denied); + fx.push(self.line(now_ms, &format!("call pause {}", Self::said(ok, denied, &text)))); + work = Work::Finished; continue 'reduce; + } + Method::Seek => { + self.facts.seek = Self::outcome(ok, denied); + fx.push(self.line(now_ms, &format!("call seek {}", Self::said(ok, denied, &text)))); + work = Work::Finished; continue 'reduce; + } + Method::SelectTrack => { + let kind = if let Some(kind) = message.reply_track { kind } else { self.facts.track_pending.take().unwrap_or("track") }; + let outcome = Self::outcome(ok, denied); + match kind { + "text" => if self.facts.text != CallResult::Ok || outcome == CallResult::Refused { self.facts.text = outcome }, + "audio" => if self.facts.audio != CallResult::Ok || outcome == CallResult::Refused { self.facts.audio = outcome }, + _ => {}, + } + fx.push(self.line(now_ms, &format!("call selectTrack {kind} {}", Self::said(ok, denied, &text)))); + work = Work::Finished; continue 'reduce; + } + Method::SetSubtitleEnable => { + // No event confirms this call: its own reply is the whole answer. + self.facts.subs = if denied { CallResult::Refused } else if message.return_value == Some(true) { CallResult::Ok } else { CallResult::Unconfirmed }; + fx.push(self.line(now_ms, &format!("call setSubtitleEnable {}", Self::said(ok, denied, &text)))); + work = Work::Finished; continue 'reduce; + } + Method::SetWindowId => { + if !denied && message.return_value != Some(true) { work = Work::Finished; continue 'reduce; } + if denied { + self.facts.window_call = WindowCall::Refused; + fx.push(self.line(now_ms, &format!("call setWindowId err({text})"))); + } else { + self.facts.window_call = WindowCall::Answered; + fx.push(self.line(now_ms, "call setWindowId ok")); + } + if matches!(self.phase, Phase::SettingWindow { .. }) { + if let Some(media_id) = self.media_id.clone() { + self.phase = Phase::Starting { deadline: now_ms + PLAY_TIMEOUT_MS }; + fx.push(UriEffect::Call(UriCall::Play { media_id })); + } + } + work = Work::Finished; continue 'reduce; + } + Method::Load | Method::Subscribe | Method::Play if !denied && message.return_value == Some(true) && !message.has_events() => { + if method == Method::Play && matches!(self.phase, Phase::Driving { .. }) { + self.facts.resume = CallResult::Unconfirmed; + } + fx.push(self.line(now_ms, &format!("call {} ok", match method { + Method::Load => "load", + Method::Subscribe => "subscribe", + Method::Register | Method::Play | Method::NotifyForeground | Method::Pause + | Method::Seek | Method::SelectTrack | Method::SetSubtitleEnable + | Method::SetWindowId | Method::Unload | Method::Dropped | Method::Other => "play", + }))); + } + Method::Register | Method::Load | Method::Subscribe | Method::Play + | Method::Unload | Method::Dropped | Method::Other => {} + } + if self.media_id.is_none() && !denied { + self.media_id = message.media_id.clone(); + } + if let (Some(media_id), false) = (self.media_id.clone(), self.subscribed) { + self.subscribed = true; + if self.config.variant.acb() && !self.foreground_sent { + self.foreground_sent = true; + fx.push(UriEffect::Call(UriCall::NotifyForeground {media_id: media_id.clone()})); + } + fx.push(UriEffect::Call(UriCall::Subscribe { media_id })); + } + work = Work::Events { message, index: 0 }; continue 'reduce; } - } - Ev::SeekDone => { - // The subscription's request ID is not the seek command's identity, so only the - // order says whose it is: one from before the script's Seek call is not its. - self.facts.seek_done_ev |= self.facts.seek_target.is_some(); - } - Ev::TrackSelected => { - if self.facts.text_select_sent && message.selected_track.is_some_and(|(kind, _)| kind == "text") { - self.facts.text_ev = true; + Work::Seen { seen, message } => { + if seen.ev != Ev::CurrentTime { + fx.push(self.line(now_ms, &event_text(message, seen, false))); + } + match seen.ev { + Ev::Error => { work = Work::Stop { end: End::Error(message.error_code) }; continue 'reduce; }, + Ev::LoadCompleted => { + if matches!(self.phase, Phase::Loading { .. }) { + work = Work::Loaded { message }; continue 'reduce; + } + } + Ev::Playing => { + if self.facts.playing_ms.is_none() { + self.facts.playing_ms = Some(now_ms.saturating_sub(self.started_ms)); + } + if matches!(self.phase, Phase::Starting { .. }) { + self.phase = if self.config.transport { + Phase::Driving { step: 0, deadline: now_ms + DRIVE_FIRST_MS } + } else { + Phase::Playing { frozen_at: now_ms + FROZEN_TIME_MS } + }; + } + } + Ev::Paused => { + let samples = &self.facts.pause_samples; + self.facts.paused_ev |= samples.started_ms.is_some() && samples.ended_ms.is_none(); + if self.facts.pause == CallResult::Unconfirmed { + self.facts.pause = CallResult::Ok; + } + } + Ev::SeekDone => { + // The subscription's request ID is not the seek command's identity, so only the + // order says whose it is: one from before the script's Seek call is not its. + self.facts.seek_done_ev |= self.facts.seek_target.is_some(); + } + Ev::TrackSelected => { + if self.facts.text_select_sent && message.selected_track.is_some_and(|(kind, _)| kind == "text") { + self.facts.text_ev = true; + } + // A generic subscription event cannot name a text or audio command. + match message.confirmed_track { + Some("text") if self.facts.text == CallResult::Unconfirmed => self.facts.text = CallResult::Ok, + Some("audio") if self.facts.audio == CallResult::Unconfirmed => self.facts.audio = CallResult::Ok, + _ => {}, + } + } + Ev::EndOfStream => { + self.facts.eos_ev = true; + if matches!(self.phase, Phase::Starting { .. } | Phase::Playing { .. } | Phase::Driving { .. } | Phase::Acb) { + work = Work::Stop { end: End::Eos }; continue 'reduce; + } + } + Ev::CurrentTime => { work = Work::CurrentTime { seen, message }; continue 'reduce; }, + Ev::VideoInfo => { + self.facts.video_seen.get_or_insert(now_ms.saturating_sub(self.started_ms)); + if let (Some((width, height)), true) = (message.dims, self.config.window_id.is_some()) { + if self.placed != Some((width, height)) { + self.placed = Some((width, height)); + fx.push(UriEffect::PlaceWindow { width, height }); + } + } + } + Ev::AudioInfo => { + let at = now_ms.saturating_sub(self.started_ms); + self.facts.audio_seen.get_or_insert(at); + if let Some(track) = message.audio_track { + self.facts.audio_track.get_or_insert((at, track)); + } + } + Ev::BufferRange | Ev::BufferingStart | Ev::BufferingEnd | Ev::SourceInfo | Ev::StreamingInfo | Ev::CustomizedStreamingInfo | Ev::UnloadCompleted => {} + } } - // A generic subscription event cannot name a text or audio command. - match message.confirmed_track { - Some("text") if self.facts.text == CallResult::Unconfirmed => self.facts.text = CallResult::Ok, - Some("audio") if self.facts.audio == CallResult::Unconfirmed => self.facts.audio = CallResult::Ok, - _ => {}, + Work::Loaded { message } => { + if self.media_id.is_none() { + self.media_id = message.media_id.clone(); + } + if self.media_id.is_none() { + fx.push(self.line(now_ms, "loadCompleted carried no mediaId")); + work = Work::Stop { end: End::Refused("mediaId") }; continue 'reduce; + } + self.facts.loaded_ms = Some(now_ms.saturating_sub(self.started_ms)); + if self.settled.is_none() { + self.settled = Some(Settle::Started); + fx.push(UriEffect::Settle(Settle::Started)); + } + if self.config.variant.acb() { + // Start service transport independently: some firmware emits videoInfo only after Play. + if let Some(media_id) = self.media_id.clone() { + self.phase = Phase::Starting { deadline: now_ms + PLAY_TIMEOUT_MS }; + fx.push(UriEffect::Call(UriCall::Play { media_id })); + } + let media_id = self.media_id.clone().expect("loaded identity"); + work = Work::Acb { event: AcbEvent::Loaded { media_id }, now_ms }; continue 'reduce; + } + match (self.config.variant, self.config.window_id.clone(), self.media_id.clone()) { + (Variant::Late, Some(window_id), Some(media_id)) => { + self.facts.window_call = WindowCall::Pending; + self.phase = Phase::SettingWindow { deadline: now_ms + LATE_ID_TIMEOUT_MS }; + fx.push(UriEffect::Call(UriCall::SetWindowId { media_id, window_id })); + } + _ => if let Some(media_id) = self.media_id.clone() { + self.phase = Phase::Starting { deadline: now_ms + PLAY_TIMEOUT_MS }; + fx.push(UriEffect::Call(UriCall::Play { media_id })); + }, + } } - } - Ev::EndOfStream => { - self.facts.eos_ev = true; - if matches!(self.phase, Phase::Starting { .. } | Phase::Playing { .. } | Phase::Driving { .. } | Phase::Acb) { - self.stop(now_ms, End::Eos, fx); + Work::Acb { event, now_ms } => { + let mut out = Vec::new(); + self.acb.step(event, now_ms, &mut out); + for effect in out { + match effect { + AcbFx::Run {request, step, op, ..} => { + self.phase = Phase::Acb; + fx.push(self.line(now_ms, &format!("acb request={} step={step:?}", request.number()))); + fx.push(UriEffect::Acb {request, op}); + } + AcbFx::WaitingVideo => { + self.phase = Phase::Acb; + fx.push(self.line(now_ms, "acb waiting for real videoInfo dimensions/rate")); + } + AcbFx::Answered {step, invoked} => { + fx.push(self.line(now_ms, &format!("acb answer step={step:?} invoked={invoked} (not plane proof)"))); + } + AcbFx::GatePassed => { + self.phase = Phase::Registering {deadline: now_ms.saturating_add(REGISTER_TIMEOUT_MS)}; + fx.push(UriEffect::Open(self.shape)); + } + AcbFx::Bound => { + self.phase = if self.facts.playing_ms.is_some() { Phase::Playing {frozen_at: now_ms.saturating_add(FROZEN_TIME_MS)} } + else { Phase::Starting {deadline: now_ms.saturating_add(PLAY_TIMEOUT_MS)} }; + } + AcbFx::Failed(failure) => { + let end = match failure { + AcbFailure::Refused => End::Refused("acb"), + AcbFailure::Timeout => End::Timeout("acb"), + AcbFailure::VideoTimeout => End::Timeout("acb-video"), + }; + if self.phase != Phase::Done { + self.facts.failed_in = Some(self.phase.name()); + self.facts.ended = Some(end); + if self.settled.is_none() { + self.settled = Some(Settle::StartFailed); + fx.push(UriEffect::Settle(Settle::StartFailed)); + } + if let Some(media_id) = self.media_id.take() { + fx.push(self.line(now_ms, "call unload requested")); + fx.push(UriEffect::Call(UriCall::Unload { media_id })); + } + fx.push(UriEffect::Close); + self.phase = Phase::Done; + fx.push(self.line(now_ms, &self.summary())); + fx.push(self.line(now_ms, "tester: report picture yes/no and sound yes/no"));} + } + } + } } - } - Ev::CurrentTime => self.current_time(seen, message, now_ms, fx), - Ev::VideoInfo => { - self.facts.video_seen.get_or_insert(now_ms.saturating_sub(self.started_ms)); - if let (Some((width, height)), true) = (message.dims, self.config.window_id.is_some()) { - if self.placed != Some((width, height)) { - self.placed = Some((width, height)); - fx.push(UriEffect::PlaceWindow { width, height }); + Work::CurrentTime { seen, message } => { + let Some(value) = message.current_time else { + // Reported, but in neither known shape: say so once, with no payload. It is no report + // of a position, so it moves nothing and arms no timeout. + if self.time_unparsed_ms.is_none() { + self.time_unparsed_ms = Some(now_ms); + fx.push(self.line(now_ms, &event_text(message, seen, false))); + } + work = Work::Finished; continue 'reduce; + }; + // Every valid report is fresh evidence, including an unchanged position. + if self.facts.pause_samples.ended_ms.is_none() && self.facts.pause_samples.started_ms.is_some_and(|at| now_ms > at) { + self.facts.pause_samples.first.get_or_insert((now_ms, value)); + self.facts.pause_samples.last = Some((now_ms, value)); + self.facts.pause_samples.range = Some(match self.facts.pause_samples.range { + Some((low, high)) => (low.min(value), high.max(value)), + None => (value, value), + }); + self.facts.pause_samples.reports = self.facts.pause_samples.reports.saturating_add(1); + } + if let Some(last) = self.facts.clock.last_ms { + *self.facts.clock.gaps.entry(now_ms.saturating_sub(last)).or_insert(0) += 1; + } + self.facts.clock.last_ms = Some(now_ms); + if self.facts.resume_sent && self.facts.seek_target.is_none() && self.facts.resume_first.is_none() { + self.facts.resume_first = Some(value); + } + let moved = self.last_time.is_some_and(|last| last != value); + self.last_time = Some(value); + if self.facts.seek_target.is_some() && self.facts.seek_seen.is_none() { + self.facts.seek_seen = Some(value); + } + if moved { + if matches!(self.phase, Phase::Playing { .. }) || (!self.config.transport && matches!(self.phase, Phase::Starting { .. })) { + // Drive waits for the explicit playing event before scheduling its one script. + self.phase = Phase::Playing { frozen_at: now_ms + FROZEN_TIME_MS }; + } + let first = self.facts.time_moved.is_none(); + self.facts.time_moved.get_or_insert(now_ms.saturating_sub(self.started_ms)); + let due = self.time_logged_ms.is_none_or(|at| now_ms.saturating_sub(at) >= CLOCK_LOG_EVERY_MS); + if first || due { + self.time_logged_ms = Some(now_ms); + fx.push(self.line(now_ms, &event_text(message, seen, false))); + } + } else if self.facts.time_moved.is_none() && self.time_logged_ms.is_none() { + self.time_logged_ms = Some(now_ms); + fx.push(self.line(now_ms, &event_text(message, seen, true))); } } - } - Ev::AudioInfo => { - let at = now_ms.saturating_sub(self.started_ms); - self.facts.audio_seen.get_or_insert(at); - if let Some(track) = message.audio_track { - self.facts.audio_track.get_or_insert((at, track)); + Work::Stop { end } => { + if self.phase == Phase::Done { + work = Work::Finished; continue 'reduce; + } + self.facts.failed_in = Some(self.phase.name()); + self.facts.ended = Some(end); + if self.settled.is_none() { + self.settled = Some(Settle::StartFailed); + fx.push(UriEffect::Settle(Settle::StartFailed)); + } + if let Some(media_id) = self.media_id.take() { + fx.push(self.line(now_ms, "call unload requested")); + fx.push(UriEffect::Call(UriCall::Unload { media_id })); + } + fx.push(UriEffect::Close); + self.phase = Phase::Done; + fx.push(self.line(now_ms, &self.summary())); + fx.push(self.line(now_ms, "tester: report picture yes/no and sound yes/no")); } } - _ => {} + work = Work::Finished; } } - /// `loadCompleted`: the attempt is settled as started, then `setWindowId` (late variant with a - /// window) or `play`. - fn loaded(&mut self, message: &Message, now_ms: u64, fx: &mut Vec) { - if self.media_id.is_none() { - self.media_id = message.media_id.clone(); - } - if self.media_id.is_none() { - fx.push(self.line(now_ms, "loadCompleted carried no mediaId")); - self.stop(now_ms, End::Refused("mediaId"), fx); - return; - } - self.facts.loaded_ms = Some(now_ms.saturating_sub(self.started_ms)); - self.settle(Settle::Started, fx); - if self.config.variant.acb() { - // Start service transport independently: some firmware emits videoInfo only after Play. - self.play(now_ms, fx); - let media_id = self.media_id.clone().expect("loaded identity"); - self.acb_event(AcbEvent::Loaded {media_id}, now_ms, fx); - return; - } - match (self.config.variant, self.config.window_id.clone(), self.media_id.clone()) { - (Variant::Late, Some(window_id), Some(media_id)) => { - self.facts.window_call = WindowCall::Pending; - self.phase = Phase::SettingWindow { deadline: now_ms + LATE_ID_TIMEOUT_MS }; - fx.push(UriEffect::Call(UriCall::SetWindowId { media_id, window_id })); - } - _ => self.play(now_ms, fx), - } + /// The session is over (everything it will say has been said). + pub fn is_done(&self) -> bool { + self.phase == Phase::Done } - /// Step the shared ACB sequence and turn what it reports into this machine's phases, log lines - /// and effects. `now_ms` is the event's own time (the call's completion for an answer). - fn acb_event(&mut self, event: AcbEvent, now_ms: u64, fx: &mut Vec) { - let mut out = Vec::new(); - self.acb.step(event, now_ms, &mut out); - for effect in out { - match effect { - AcbFx::Run {request, step, op, ..} => { - self.phase = Phase::Acb; - fx.push(self.line(now_ms, &format!("acb request={} step={step:?}", request.number()))); - fx.push(UriEffect::Acb {request, op}); - } - AcbFx::WaitingVideo => { - self.phase = Phase::Acb; - fx.push(self.line(now_ms, "acb waiting for real videoInfo dimensions/rate")); - } - AcbFx::Answered {step, invoked} => { - fx.push(self.line(now_ms, &format!("acb answer step={step:?} invoked={invoked} (not plane proof)"))); - } - AcbFx::GatePassed => { - self.phase = Phase::Registering {deadline: now_ms.saturating_add(REGISTER_TIMEOUT_MS)}; - fx.push(UriEffect::Open(self.shape)); - } - AcbFx::Bound => { - self.phase = if self.facts.playing_ms.is_some() { Phase::Playing {frozen_at: now_ms.saturating_add(FROZEN_TIME_MS)} } - else { Phase::Starting {deadline: now_ms.saturating_add(PLAY_TIMEOUT_MS)} }; - } - AcbFx::Failed(failure) => { - let end = match failure { - AcbFailure::Refused => End::Refused("acb"), - AcbFailure::Timeout => End::Timeout("acb"), - AcbFailure::VideoTimeout => End::Timeout("acb-video"), - }; - self.stop(now_ms, end, fx); - } - } - } + /// From `playing` until the end: the service has said the video plays, not plane proof. + pub fn plane_open(&self) -> bool { + matches!(self.phase, Phase::Playing { .. } | Phase::Driving { .. }) } - fn play(&mut self, now_ms: u64, fx: &mut Vec) { - if let Some(media_id) = self.media_id.clone() { - self.phase = Phase::Starting { deadline: now_ms + PLAY_TIMEOUT_MS }; - fx.push(UriEffect::Call(UriCall::Play { media_id })); - } + /// Apply one event, preserving effect order. Done is inert. + pub fn step(&mut self, ev: UriEvent, now_ms: u64, fx: &mut Vec) { + self.transition(ev, now_ms, fx); } - fn current_time(&mut self, seen: &Seen, message: &Message, now_ms: u64, fx: &mut Vec) { - let Some(value) = message.current_time else { - // Reported, but in neither known shape: say so once, with no payload. It is no report - // of a position, so it moves nothing and arms no timeout. - if self.time_unparsed_ms.is_none() { - self.time_unparsed_ms = Some(now_ms); - fx.push(self.line(now_ms, &event_text(message, seen, false))); - } - return; - }; - // Every valid report is fresh evidence, including an unchanged position. - self.facts.pause_samples.observe(now_ms, value); - self.facts.clock.observe(now_ms); - if self.facts.resume_sent && self.facts.seek_target.is_none() && self.facts.resume_first.is_none() { - self.facts.resume_first = Some(value); - } - let moved = self.last_time.is_some_and(|last| last != value); - self.last_time = Some(value); - if self.facts.seek_target.is_some() && self.facts.seek_seen.is_none() { - self.facts.seek_seen = Some(value); - } - if moved { - if matches!(self.phase, Phase::Playing { .. }) || (!self.config.transport && matches!(self.phase, Phase::Starting { .. })) { - // Drive waits for the explicit playing event before scheduling its one script. - self.phase = Phase::Playing { frozen_at: now_ms + FROZEN_TIME_MS }; - } - let first = self.facts.time_moved.is_none(); - self.facts.time_moved.get_or_insert(now_ms.saturating_sub(self.started_ms)); - let due = self.time_logged_ms.is_none_or(|at| now_ms.saturating_sub(at) >= CLOCK_LOG_EVERY_MS); - if first || due { - self.time_logged_ms = Some(now_ms); - fx.push(self.line(now_ms, &event_text(message, seen, false))); - } - } else if self.facts.time_moved.is_none() && self.time_logged_ms.is_none() { - self.time_logged_ms = Some(now_ms); - fx.push(self.line(now_ms, &event_text(message, seen, true))); - } + fn line(&self, now_ms: u64, body: &str) -> UriEffect { + UriEffect::Log(format!("uriprobe: t={} {body}", now_ms.saturating_sub(self.started_ms))) } - fn settle(&mut self, how: Settle, fx: &mut Vec) { - if self.settled.is_none() { - self.settled = Some(how); - fx.push(UriEffect::Settle(how)); - } + /// Accepted calls remain provisional until their attributed evidence arrives. + fn outcome(ok: bool, denied: bool) -> CallResult { + if ok && !denied { CallResult::Unconfirmed } else { CallResult::Refused } } - /// The one way out. Settles the attempt if it is still open, unloads once a `mediaId` is known, - /// always closes, writes the summary, and ends the session. - fn stop(&mut self, now_ms: u64, end: End, fx: &mut Vec) { - if self.phase == Phase::Done { - return; - } - self.facts.failed_in = Some(self.phase.name()); - self.facts.ended = Some(end); - self.settle(Settle::StartFailed, fx); - if let Some(media_id) = self.media_id.take() { - fx.push(self.line(now_ms, "call unload requested")); - fx.push(UriEffect::Call(UriCall::Unload { media_id })); - } - fx.push(UriEffect::Close); - self.phase = Phase::Done; - fx.push(self.line(now_ms, &self.summary())); - fx.push(self.line(now_ms, "tester: report picture yes/no and sound yes/no")); + /// The tail of a call log line. + fn said(ok: bool, denied: bool, text: &str) -> String { + if ok && !denied { "ok".to_owned() } else { format!("err({text})") } } /// The terminal line: what the service said, not what the screen showed. @@ -2257,7 +2287,7 @@ mod tests { } fn acb_request(fx: &[UriEffect]) -> AcbRequest { - fx.iter().find_map(|fx| match fx {UriEffect::Acb {request,..} => Some(*request), _ => None}).expect("ACB effect") + fx.iter().find_map(|fx| match fx {UriEffect::Acb {request,..} => Some(*request), UriEffect::Open(_) | UriEffect::Call(_) | UriEffect::Close | UriEffect::Settle(_) | UriEffect::PlaceWindow { .. } | UriEffect::Log(_) => None}).expect("ACB effect") } fn acb_loaded(variant: Variant, early_video: bool) -> (Rig, Vec) { let mut rig=Rig::new(variant,None); @@ -2267,7 +2297,7 @@ mod tests { let fx=rig.msg("register",""); assert!(fx.contains(&load(Some("window_id_dummy")))); let fx=rig.msg("load",r#"{"returnValue":true,"mediaId":"_m1"}"#); - let calls:Vec<_>=fx.iter().filter_map(|fx| match fx {UriEffect::Call(call)=>Some(call.method()),_=>None}).collect(); + let calls:Vec<_>=fx.iter().filter_map(|fx| match fx {UriEffect::Call(call)=>Some(call.method()),UriEffect::Open(_) | UriEffect::Acb { .. } | UriEffect::Close | UriEffect::Settle(_) | UriEffect::PlaceWindow { .. } | UriEffect::Log(_) => None}).collect(); assert_eq!(calls,["notifyForeground","subscribe"]); if early_video { rig.msg("subscribe",r#"{"mediaId":"_m1","videoInfo":{"width":1280,"height":720,"frameRate":24}}"#); } let fx=rig.msg("subscribe",r#"{"mediaId":"_m1","loadCompleted":true}"#); @@ -2281,7 +2311,7 @@ mod tests { let mut trace=Vec::new(); for step in 0..5 { let request=acb_request(&fx); - let op=fx.iter().find_map(|fx| match fx {UriEffect::Acb{op,..}=>Some(op.clone()),_=>None}).unwrap(); + let op=fx.iter().find_map(|fx| match fx {UriEffect::Acb{op,..}=>Some(op.clone()),UriEffect::Open(_) | UriEffect::Call(_) | UriEffect::Close | UriEffect::Settle(_) | UriEffect::PlaceWindow { .. } | UriEffect::Log(_) => None}).unwrap(); trace.push((rig.now,op)); fx=rig.feed(UriEvent::AcbAnswered{request,invoked:true,completed_ms:rig.now}); if step<4 { @@ -2805,4 +2835,53 @@ mod tests { assert!(!summary.contains('\n')); } + #[test] + fn grouped_events_finish_each_continuation_and_stop_before_the_remaining_items() { + let mut rig = Rig::new(Variant::AtLoad, Some(WINDOW)); + rig.loading(); + let events = [Ev::LoadCompleted, Ev::Playing, Ev::CurrentTime, Ev::Error, Ev::VideoInfo]; + let message = Message { + media_id: Some(media("_m1")), + seen: events.iter().map(|ev| Seen { ev: *ev, detail: String::new() }).collect(), + normalized: events.to_vec(), + current_time: Some(100), + error_code: Some(9), + dims: Some((1280, 720)), + ..Message::default() + }; + let fx = rig.feed(UriEvent::Reply { method: Method::Subscribe, ok: true, message }); + let position = |predicate: fn(&UriEffect) -> bool| fx.iter().position(predicate).expect("ordered effect"); + let settled = position(|effect| matches!(effect, UriEffect::Settle(Settle::Started))); + let play = position(|effect| matches!(effect, UriEffect::Call(UriCall::Play { .. }))); + let unload = position(|effect| matches!(effect, UriEffect::Call(UriCall::Unload { .. }))); + let close = position(|effect| matches!(effect, UriEffect::Close)); + let summary = position(|effect| matches!(effect, UriEffect::Log(line) if line.contains("summary "))); + assert!(settled < play && play < unload && unload < close && close < summary); + assert_eq!(settles(&fx, Settle::Started), 1); + assert_eq!(settles(&fx, Settle::StartFailed), 0); + assert!(rig.probe.is_done()); + assert!(!rig.probe.plane_open()); + assert_eq!(rig.probe.facts.playing_ms, Some(0)); + assert_eq!(rig.probe.last_time, Some(100)); + assert_eq!(rig.probe.facts.video_seen, None, "events after Error are inert"); + assert!(!fx.iter().any(|effect| matches!(effect, UriEffect::PlaceWindow { .. }))); + for event in [UriEvent::Start, UriEvent::Tick, UriEvent::Back, UriEvent::Closed] { + assert!(rig.feed(event).is_empty(), "Done emits no repeated close or summary"); + } + } + + #[test] + fn video_continuation_precedes_foreground_reply_and_preserves_its_early_return() { + let (mut rig, _) = acb_loaded(Variant::AcbControl, false); + let message = parse_event(r#"{"returnValue":true,"mediaId":"_m1","videoInfo":{"width":1280,"height":720,"frameRate":24},"errorCode":9}"#); + let fx = rig.feed(UriEvent::Reply { method: Method::NotifyForeground, ok: true, message }); + let acb = fx.iter().position(|effect| matches!(effect, UriEffect::Acb { .. })).expect("video starts binding"); + let answer = fx.iter().position(|effect| matches!(effect, UriEffect::Log(line) if line.contains("call notifyForeground ok"))).expect("foreground reply"); + assert!(acb < answer, "the video substep completes before reply handling resumes"); + assert!(!rig.probe.is_done(), "NotifyForeground does not consume service events"); + assert_eq!(rig.probe.facts.video_seen, None); + assert_eq!(closes(&fx), 0); + assert!(!logs(&fx).iter().any(|line| line.contains("ev="))); + } + } diff --git a/rust-modules/playback-contract/src/state.rs b/rust-modules/playback-contract/src/state.rs index f90b001b5f..e2bb63f41d 100644 --- a/rust-modules/playback-contract/src/state.rs +++ b/rust-modules/playback-contract/src/state.rs @@ -1,3 +1,4 @@ +#![deny(clippy::wildcard_enum_match_arm)] //! Pure admission and publication for one logical playback attempt across physical backends. //! Each concrete driver owns its native requests, release deadlines and quarantine evidence. use std::collections::BTreeMap; @@ -129,16 +130,11 @@ impl BackendState { } fn owns(&self, backend: BackendKind, attempt: AttemptId) -> bool { - self.snapshot.backend == Some(backend) && self.snapshot.attempt == Some(attempt) + let snapshot = &self.snapshot; + snapshot.backend == Some(backend) && snapshot.attempt == Some(attempt) } - fn dispatch(&mut self, backend: BackendKind, attempt: AttemptId, - operation: Operation, effects: &mut Vec) { - self.next_command = self.next_command.checked_add(1).expect("playback command IDs exhausted"); - let command = CommandId(self.next_command); - self.pending.insert(command, operation); - effects.push(Fx::Dispatch { backend, attempt, command, operation }); - } + fn reject_start(effects: &mut Vec, backend: BackendKind, attempt: AttemptId, source: SourceKey, failure: Failure) { @@ -149,6 +145,9 @@ impl BackendState { /// `capabilities` is supplied by the injected driver set for this event's backend. It may be /// absent; no source or operation is dispatched to an unavailable driver. pub fn step(&mut self, event: Event, capabilities: Option, effects: &mut Vec) { + self.transition(event, capabilities, effects); + } + fn transition(&mut self, event: Event, capabilities: Option, effects: &mut Vec) { match event { Event::Intent(Intent::Start { backend, attempt, source, requirements, initial }) => { let failure = if self.snapshot.phase != Phase::Vacant { @@ -169,7 +168,11 @@ impl BackendState { self.snapshot.attempt = Some(attempt); self.snapshot.viewer_paused = Some(initial.paused); self.settled_viewer_paused = Some(initial.paused); - self.dispatch(backend, attempt, Operation::Start { source, requirements }, effects); + let operation = Operation::Start { source, requirements }; + self.next_command = self.next_command.checked_add(1).expect("playback command IDs exhausted"); + let command = CommandId(self.next_command); + self.pending.insert(command, operation); + effects.push(Fx::Dispatch { backend, attempt, command, operation }); } } Event::Intent(Intent::Control { backend, attempt, operation }) => { @@ -183,12 +186,15 @@ impl BackendState { if let Some(failure) = failure { effects.push(Fx::Rejected { backend, attempt, failure }); } else { - self.dispatch(backend, attempt, operation, effects); + self.next_command = self.next_command.checked_add(1).expect("playback command IDs exhausted"); + let command = CommandId(self.next_command); + self.pending.insert(command, operation); + effects.push(Fx::Dispatch { backend, attempt, command, operation }); } } Event::Intent(Intent::Stop { backend, attempt, reason }) => { if !self.owns(backend, attempt) - || !matches!(self.snapshot.phase, Phase::Starting | Phase::Active) { return; } + || !matches!(&self.snapshot.phase, Phase::Starting | Phase::Active) { return; } self.pending.clear(); self.latest_queued_seek = None; self.latest_queued_transport = None; @@ -200,7 +206,11 @@ impl BackendState { effects.push(Fx::Rejected { backend, attempt, failure: Failure::Unavailable }); } else { self.snapshot.phase = Phase::Releasing; - self.dispatch(backend, attempt, Operation::Stop(reason), effects); + let operation = Operation::Stop(reason); + self.next_command = self.next_command.checked_add(1).expect("playback command IDs exhausted"); + let command = CommandId(self.next_command); + self.pending.insert(command, operation); + effects.push(Fx::Dispatch { backend, attempt, command, operation }); } } Event::CommandAnswer { backend, attempt, command, result } => { @@ -240,7 +250,7 @@ impl BackendState { } Event::Observation { backend, attempt, observation } if self.owns(backend, attempt) - && matches!(self.snapshot.phase, Phase::Starting | Phase::Active) => + && matches!(&self.snapshot.phase, Phase::Starting | Phase::Active) => { if observation == Observation::Presented && self.snapshot.presented { return; } match observation { @@ -275,7 +285,7 @@ impl BackendState { Event::Observation { .. } => {} Event::ViewerGoal { backend, attempt, paused } if self.owns(backend, attempt) - && matches!(self.snapshot.phase, Phase::Starting | Phase::Active) => { + && matches!(&self.snapshot.phase, Phase::Starting | Phase::Active) => { self.snapshot.viewer_paused = Some(paused); self.settled_viewer_paused = Some(paused); } @@ -751,4 +761,44 @@ mod tests { assert_eq!(state.snapshot.playback.unwrap().value, Playback::ReadyAwaitPlay); assert_eq!(state.snapshot.failure, Some(Failure::Refused)); } + + #[test] + fn pending_cancellation_quarantine_and_release_never_rewind_command_identity() { + let mut state = BackendState::new(); + let attempt = AttemptId::new(12, 1); + let first = start(&mut state, URI, attempt); + assert_eq!(state.pending.len(), 1); + assert!(step(&mut state, Event::CommandAnswer { backend: FEED, attempt, + command: first, result: DispatchResult::Queued }, None).is_empty()); + assert_eq!(state.pending.len(), 1, "wrong backend cannot consume an addressed command"); + let fx = step(&mut state, Event::Intent(Intent::Stop { backend: URI, attempt, + reason: StopReason::Replace }), Some(CAPS)); + let [Fx::Dispatch { command: stop, operation: Operation::Stop(StopReason::Replace), .. }] = fx.as_slice() + else { panic!("stop dispatch: {fx:?}") }; + let stop = *stop; + assert!(stop > first); + assert_eq!(state.pending.len(), 1); + assert!(!state.pending.contains_key(&first)); + assert!(step(&mut state, Event::CommandAnswer { backend: URI, attempt, + command: first, result: DispatchResult::Queued }, None).is_empty()); + step(&mut state, Event::Release { backend: URI, attempt, status: ReleaseStatus::Quarantined }, None); + assert!(state.pending.is_empty()); + assert!(step(&mut state, Event::CommandAnswer { backend: URI, attempt, + command: stop, result: DispatchResult::Queued }, None).is_empty()); + let next_attempt = AttemptId::new(12, 2); + assert!(step(&mut state, Event::Release { backend: URI, attempt: next_attempt, + status: ReleaseStatus::Released }, None).is_empty()); + assert_eq!(state.snapshot.phase, Phase::Quarantined); + step(&mut state, Event::Release { backend: URI, attempt, status: ReleaseStatus::Released }, None); + assert_eq!(*state.snapshot(), Snapshot::default()); + let next = start(&mut state, FEED, next_attempt); + assert!(next > stop, "release does not recycle a command ID"); + assert!(step(&mut state, Event::CommandAnswer { backend: URI, attempt, + command: first, result: DispatchResult::Queued }, None).is_empty()); + assert!(step(&mut state, Event::Release { backend: URI, attempt, + status: ReleaseStatus::Released }, None).is_empty()); + assert_eq!(state.snapshot.attempt, Some(next_attempt)); + assert_eq!(state.pending.len(), 1); + assert!(state.pending.contains_key(&next)); + } } diff --git a/rust-modules/plex/src/plex/client_keys.rs b/rust-modules/plex/src/plex/client_keys.rs index 50c2148fe9..c823958f18 100644 --- a/rust-modules/plex/src/plex/client_keys.rs +++ b/rust-modules/plex/src/plex/client_keys.rs @@ -84,6 +84,21 @@ impl Default for ClientKeys { } impl ClientKeys { + /// A complete value observation supplied by a scripted host. Registered slots without + /// eligible keys remain distinct from absent slots, just as in a live refill. + pub fn captured(current: ServerId, roster_gen: u32, facts_gen: u32, + rows: impl IntoIterator, ClientFacts)>) -> Self { + let mut keys = Self::default(); + keys.2 = current; + keys.3 = roster_gen; + keys.4 = facts_gen; + for (sid, key, facts) in rows { + if let Some(key) = key { keys.0.push((sid, key)); } + keys.1.push((sid, facts)); + } + keys + } + /// The keys of these clients. pub fn of<'a>(clients: impl IntoIterator) -> Self { Self::from_keys(clients.into_iter().map(|(sid, client)| (sid, ClientKey::of(client)))) @@ -118,6 +133,13 @@ impl ClientKeys { self.1.iter().find(|(slot, _)| *slot == sid).map(|(_, facts)| facts) } + /// Replace only scripted key values, retaining the separately captured complete roster. + #[cfg(any(test, feature = "test-support"))] + pub fn replace_keys_for_test(&mut self, keys: impl IntoIterator) { + self.0.clear(); + self.0.extend(keys); + } + /// Host-only registry capture through explicit readers. Reuses both buffers and machine strings. /// Eligibility is read on EVERY fill, irrespective of generations. The acquire-backed probe /// reader runs before tier and the second eligible lookup checks instance/token/grant again. @@ -201,6 +223,89 @@ impl ClientKeys { } } +/// Captured clock reasons and the coherent source identities they describe. The host fills this +/// from its already captured client roster; screen code never reads keypin or the registry. +#[derive(Clone, Debug, Default)] +pub struct ClockFacts { + revision: u64, + initialized: bool, + current: ServerId, + empty: Option, + rows: Vec, +} + +#[derive(Clone, Debug)] +struct ClockRow { + sid: ServerId, + machine: String, + blocked: Option, +} + +impl ClockFacts { + /// Explicit value input for a scripted host; never reads a process-global source. + pub fn scripted(revision: u64, current: ServerId, empty: Option, + rows: impl IntoIterator)>) -> Self { + Self { revision, initialized: true, current, empty, + rows: rows.into_iter().map(|(sid, machine, blocked)| ClockRow { sid, machine, blocked }).collect() } + } + + pub fn revision(&self) -> u64 { self.revision } + pub fn current_machine(&self) -> Option<&str> { self.machine(self.current) } + pub fn machine(&self, sid: ServerId) -> Option<&str> { + self.rows.iter().find(|row| row.sid == sid).map(|row| row.machine.as_str()) + } + pub fn blocked_for(&self, machine: Option<&str>) -> Option { + match machine { + None | Some("") => self.empty, + Some(machine) => self.rows.iter().find(|row| row.machine == machine).and_then(|row| row.blocked), + } + } + + /// Refresh only when the revision or the coherent source roster changed. The retained vector + /// and its strings are reused. `read` is supplied by the host, not by this value. + /// The cheap, allocation-free guard before touching a retained publication. + pub fn needs_refill(&self, revision: u64, keys: &ClientKeys) -> bool { + let sources = || keys.iter().filter_map(|(sid, _)| keys.facts(sid).map(|facts| (sid, facts))); + !self.initialized || self.revision != revision || self.current != keys.current() + || self.rows.len() != sources().count() + || !self.rows.iter().zip(sources()).all(|(row, (sid, facts))| + row.sid == sid && row.machine == facts.machine_id) + } + pub fn refill(&mut self, revision: u64, keys: &ClientKeys, + mut read: impl FnMut(&str) -> Option) -> bool { + if !self.needs_refill(revision, keys) { return false; } + let mut changed = self.current != keys.current(); + let empty = read(""); + changed |= self.empty != empty; + self.empty = empty; + let mut count = 0; + for (sid, _) in keys.iter() { + let Some(facts) = keys.facts(sid) else { continue }; + if count == self.rows.len() { + self.rows.push(ClockRow { sid, machine: String::new(), blocked: None }); + changed = true; + } + let row = &mut self.rows[count]; + changed |= row.sid != sid || row.machine != facts.machine_id; + row.sid = sid; + if row.machine != facts.machine_id { + row.machine.clear(); + row.machine.push_str(&facts.machine_id); + } + let blocked = read(&row.machine); + changed |= row.blocked != blocked; + row.blocked = blocked; + count += 1; + } + changed |= self.rows.len() != count; + self.rows.truncate(count); + self.current = keys.current(); + self.revision = revision; + self.initialized = true; + changed + } +} + /// A key-checked way to a server's client, for a WORKER that holds the snapshot its step decided /// under. A step decides from a [`ClientKeys`] taken just before it; the worker runs later, and a /// profile switch re-tokens the registry's `Client` objects IN PLACE (`servers::revoke_for_profile_switch`): @@ -226,6 +331,9 @@ impl<'a> KeyedClients<'a> { Self { keys, lookup } } + /// Described evidence from the captured roster, never the live registry. + pub fn facts(&self, sid: ServerId) -> Option<&ClientFacts> { self.keys.facts(sid) } + /// The client `sid` holds, only while its key matches the snapshot. `None` when the snapshot /// holds no key for `sid` (the step never saw that slot), when the registry holds no client /// for it, or when the client it holds is a different object or carries a moved credential. @@ -350,3 +458,49 @@ mod tests { #[cfg(test)] #[path = "client_keys_roster_tests.rs"] mod roster_tests; + +#[cfg(test)] +mod clock_facts_tests { + use super::*; + use plx_net::net::keypin::Blocked; + use std::sync::Arc; + + #[test] + fn retained_clock_facts_reuse_arc_buffers_and_machine_strings() { + let sid = ServerId::from_raw(907); + let client: &'static Client = Box::leak(Box::new(Client::new(sid, "clock-captured-machine", + super::super::Origin::http("127.0.0.1", 9), "token", "clock-test"))); + let mut keys = ClientKeys::default(); + keys.refill_roster(sid, 1, 1, [sid], |_| Some(client), |_| None, |_| None); + let mut facts = Arc::new(ClockFacts::default()); + assert!(Arc::make_mut(&mut facts).refill(1, &keys, |id| + (id == "clock-captured-machine").then_some(Blocked::NoKey))); + let published = Arc::clone(&facts); + let buffer = facts.rows.as_ptr(); + let machine = facts.rows[0].machine.as_ptr(); + let capacities = (facts.rows.capacity(), facts.rows[0].machine.capacity()); + for _ in 0..20 { + assert!(!facts.needs_refill(1, &keys)); + assert!(Arc::ptr_eq(&published, &facts)); + assert_eq!(facts.rows.as_ptr(), buffer); + assert_eq!(facts.rows[0].machine.as_ptr(), machine); + } + drop(published); + assert!(!Arc::make_mut(&mut facts).refill(2, &keys, |id| + (id == "clock-captured-machine").then_some(Blocked::NoKey))); + assert_eq!(facts.rows.as_ptr(), buffer); + assert_eq!(facts.rows[0].machine.as_ptr(), machine); + assert_eq!((facts.rows.capacity(), facts.rows[0].machine.capacity()), capacities); + assert_eq!(facts.current_machine(), Some("clock-captured-machine")); + assert_eq!(facts.blocked_for(Some("clock-captured-machine")), Some(Blocked::NoKey)); + assert_eq!(facts.blocked_for(None), None); + } + + #[test] + fn scripted_empty_id_fact_is_explicit() { + let facts = ClockFacts::scripted(3, ServerId::UNSET, Some(Blocked::KeyChanged), []); + assert_eq!(facts.blocked_for(None), Some(Blocked::KeyChanged)); + assert_eq!(facts.blocked_for(Some("")), Some(Blocked::KeyChanged)); + assert_eq!(facts.blocked_for(Some("other")), None); + } +} diff --git a/rust-modules/plex/src/plex/mod.rs b/rust-modules/plex/src/plex/mod.rs index f4a3939ac2..84cc1336af 100644 --- a/rust-modules/plex/src/plex/mod.rs +++ b/rust-modules/plex/src/plex/mod.rs @@ -114,7 +114,7 @@ pub use client::urlenc_str; pub use client::{decode_ip, decode_link, encode_ip, encode_link}; #[allow(unused_imports)] pub use client::{Client, IpVersion, StreamUrl}; -pub use client_keys::{ClientKey, ClientKeys, KeyedClients}; +pub use client_keys::{ClientFacts, ClientKey, ClientKeys, ClockFacts, KeyedClients}; // `Client::find_by_guids`' vocabulary (library.rs stays private). pub use library::{GuidKind, GuidLookupError, GuidMatch, Oldest, SectionTotal, GUIDS_PER_REQUEST}; // WHERE a server is, as one value. `Origin` is what `register_origin`/`install` take and what a diff --git a/rust-modules/plex/src/plex/session.rs b/rust-modules/plex/src/plex/session.rs index 07e497b302..4d2362869e 100644 --- a/rust-modules/plex/src/plex/session.rs +++ b/rust-modules/plex/src/plex/session.rs @@ -70,6 +70,7 @@ pub use plx_base::detail_parts::{DetailPart, DetailParts}; /// The signed-in profile, in-memory for the UI (the Home profile chip reads this). Set by the boot /// gate (from the stored session) and on every profile switch, so it survives an offline boot. static CURRENT: Mutex>> = Mutex::new(None); +static CURRENT_PUBLICATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Immutable worker publication. Identity and its explicit owner-assigned generation are one /// record, so a reader that needs both can retain one snapshot across subsequent publications. @@ -204,8 +205,9 @@ impl ProfilePublisher { return; } { - *CURRENT.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new( - CurrentProfile { user: user.clone(), generation, stamp })); + let mut current = CURRENT.lock().unwrap_or_else(|e| e.into_inner()); + *current = Some(std::sync::Arc::new(CurrentProfile { user: user.clone(), generation, stamp })); + CURRENT_PUBLICATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } warm(user, generation); } @@ -505,7 +507,7 @@ impl Drop for TempSession { #[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] -pub struct OpaqueExtensions(pub BTreeMap); +pub struct OpaqueExtensions(pub BTreeMap); impl OpaqueExtensions { fn is_empty(&self) -> bool { @@ -3523,6 +3525,36 @@ pub fn visible_generation() -> u64 { VISIBLE_GENERATION.load(std::sync::atomic::Ordering::Acquire) } +/// Host-only publication fence for retained screen inputs, including signed-out defaults. +/// The cache revision is read under CACHE: replace_cache assigns its content, advances the +/// counter, and projects keys before releasing that same lock. CURRENT is read separately +/// to avoid lock-order coupling; a before/after pair fences both publications without allocation. +pub fn screen_input_revision() -> (u64, u64) { + let cache_revision = { + let _cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + CACHE_GENERATION.load(std::sync::atomic::Ordering::Relaxed) + }; + let profile_revision = { + let _current = CURRENT.lock().unwrap_or_else(|e| e.into_inner()); + CURRENT_PUBLICATION.load(std::sync::atomic::Ordering::Relaxed) + }; + (cache_revision, profile_revision) +} + +#[cfg(any(test, feature = "test-support"))] +pub fn install_cleared_for_test(ui_resolution: UiResolution) { + plx_base::testlock::assert_held("cleared screen input fixture"); + let kept = Retained { language: plx_platform::i18n::Preference::System, ui_resolution }; + set_cache_locked(Cached::Settled(std::sync::Arc::new(ReadState::Cleared { kept }))); +} + +#[cfg(any(test, feature = "test-support"))] +pub fn install_locked_defaults_for_test(ui_resolution: UiResolution) { + plx_base::testlock::assert_held("locked screen input fixture"); + let kept = Retained { language: plx_platform::i18n::Preference::System, ui_resolution }; + set_cache_locked(Cached::Transient { state: std::sync::Arc::new(ReadState::Locked { kept }) }); +} + /// Per-consumer cursor for cached session-derived views. Poll on Tick, including while storage /// is unavailable: the owner's `RefreshCache` effect runs the bounded retry, so the frame never blocks. #[derive(Default)] @@ -6788,3 +6820,38 @@ mod server_key_pin_tests { assert_eq!(plx_net::net::keypin::pin_for_test(&key), None, "the late probe did not repopulate it"); } } + +#[cfg(test)] +mod screen_input_revision_tests { + use super::*; + #[test] + fn screen_input_revision_observes_cleared_defaults_without_a_visible_generation_change() { + let _serial = plx_base::testlock::serial(); + let _session = test_support::TempSession::new("screen-revision-defaults"); + install_cleared_for_test(UiResolution::Auto); + let before = screen_input_revision(); + let visible = visible_generation(); + install_cleared_for_test(UiResolution::Hd720); + assert_ne!(screen_input_revision().0, before.0); + assert_eq!(visible_generation(), visible); + assert_eq!(peek_settled().unwrap().ui_resolution(), UiResolution::Hd720); + } + #[test] + fn screen_input_revision_waits_for_the_cache_publication_lock() { + let _serial = plx_base::testlock::serial(); + let _session = test_support::TempSession::new("screen-revision-lock"); + let expected = screen_input_revision(); + let cache = CACHE.lock().unwrap(); + let (started, start) = std::sync::mpsc::channel(); + let (answer, result) = std::sync::mpsc::channel(); + let reader = std::thread::spawn(move || { + started.send(()).unwrap(); + answer.send(screen_input_revision()).unwrap(); + }); + start.recv().unwrap(); + assert!(matches!(result.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty))); + drop(cache); + assert_eq!(result.recv_timeout(std::time::Duration::from_secs(2)).unwrap(), expected); + reader.join().unwrap(); + } +} diff --git a/rust-modules/plex/src/plex/session_publication_tests.rs b/rust-modules/plex/src/plex/session_publication_tests.rs index 5d04dbdf92..23848b03c6 100644 --- a/rust-modules/plex/src/plex/session_publication_tests.rs +++ b/rust-modules/plex/src/plex/session_publication_tests.rs @@ -8,15 +8,21 @@ use super::test_support::*; #[test] fn profile_publication_has_one_writer_and_no_resource_scope_allocator() { let source = include_str!("session.rs"); - let publication = source.split("/// Session file locations").next().unwrap(); + let (publication, _) = source.split_once("/// Session file locations").expect("publication boundary"); assert!(!publication.contains("pub fn set_current(")); assert!(!publication.contains("wrapping_add(")); - assert!(!publication.contains("fetch_add(")); - assert_eq!(publication.matches("*CURRENT.lock()").count(), 1); - let writer = publication.split("impl ProfilePublisher {").nth(1).unwrap() - .split("/// Resource fixtures").next().unwrap(); - assert!(writer.contains("*CURRENT.lock()")); - assert!(writer.contains("CurrentProfile { user, generation, stamp }")); + // This revision wakes screen observers; it never supplies CurrentProfile::generation. + let observer = "CURRENT_PUBLICATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);"; + assert_eq!(publication.matches(observer).count(), 1); + assert!(!publication.replace(observer, "").contains("fetch_add(")); + assert_eq!(publication.matches("CURRENT.lock()").count(), 2); + assert_eq!(publication.matches("let mut current = CURRENT.lock()").count(), 1); + assert_eq!(publication.matches("*current = Some(").count(), 1); + let (_, writer) = publication.split_once("impl ProfilePublisher {").expect("profile writer"); + let (writer, _) = writer.split_once("/// Resource fixtures").expect("production writer boundary"); + assert!(writer.contains("let mut current = CURRENT.lock()")); + assert!(writer.contains("*current = Some(std::sync::Arc::new(CurrentProfile { user: user.clone(), generation, stamp }))")); + assert!(writer.contains("*scoped = std::sync::Arc::new(CurrentProfile { user, generation, stamp })")); } #[test] diff --git a/rust-modules/screens/src/account_menu.rs b/rust-modules/screens/src/account_menu.rs index ed14cd4c22..9a915a6566 100644 --- a/rust-modules/screens/src/account_menu.rs +++ b/rust-modules/screens/src/account_menu.rs @@ -250,7 +250,7 @@ pub struct AccountMenuScreen { form: FormTable, /// Rebuild on visible session landings as well as the initial mount. Focus keys name /// actions, not row positions, so a landing cannot turn an armed Settings press into Sign out. - session_watch: plx_plex::plex::session::VisibleSessionWatch, + session_watch: Option<(u64, bool, u32)>, /// The Session's published switch verdict the rows were built on /// ([`plx_session::auth::owner::SessionSnapshot::switch_refused`]) — a change rebuilds them. switch_refused: bool, @@ -276,15 +276,14 @@ impl AccountMenuScreen { } /// Capture a settled session without blocking storage. - fn build(&mut self, switch_refused: bool) { + fn build(&mut self, inputs: &crate::registry::ScreenInputs, switch_refused: bool) { if self.built { return; } - let Some(sess) = plx_plex::plex::session::peek_settled() else { return }; + let Some(sess) = inputs.settled_session() else { return }; self.built = true; let keep = self.form.selected_id().copied(); - let cur = plx_plex::plex::session::current(); - let acc = sess.account(cur.as_ref()); + let acc = sess.account(inputs.profile.user.as_ref()); self.switch_refused = switch_refused; let (header, form) = account_form(&AccountInputs::of(&acc, switch_refused)); self.header = header; @@ -343,22 +342,24 @@ impl Machine for AccountMenuScreen { type Ev = ScreenEvent; fn step(&mut self, ev: &Self::Ev, cx: &Cx<'_, H>, fx: &mut Effects<'_, H>) -> Handled { let switch_refused = H::auth(cx).0.switch_refused; + let inputs = H::screen_inputs(cx); match ev { ScreenEvent::Mount => { // the origin is the chip's LIVE drawn rect, handed in before every draw (`opener_rect`) self.popover.open_from(None); - self.build(switch_refused) + self.build(inputs, switch_refused) } // However the surface was dismissed (BACK, a pick, the host's own press), the panel // runs the morph back into the chip. ScreenEvent::Closing => self.popover.dismiss(), ScreenEvent::Tick(tick) => { self.popover.update(tick.dt()); - if self.session_watch.changed() || switch_refused != self.switch_refused { + if self.session_watch != Some(inputs.session_key()) || switch_refused != self.switch_refused { + self.session_watch = Some(inputs.session_key()); self.built = false; } if !self.built { - self.build(switch_refused); + self.build(inputs, switch_refused); if self.built { fx.invalidate(plx_machine::present::Provenance::Landing(plx_machine::machine::MachineId::Session)); } } self.form.table.sel = cx @@ -576,13 +577,17 @@ mod tests { type Fx = AppFx; type Msg = crate::registry::AppMsg; type Elem = u32; - type Views<'a> = plx_session::auth::SessionRead<'a>; + type Views<'a> = (plx_session::auth::SessionRead<'a>, &'a crate::registry::ScreenInputs); type Init = super::super::family::NoInit; type Memory = (); } - impl AuthLike for MenuHost { + impl crate::registry::ScreenInputsLike for MenuHost { + fn screen_inputs<'a>(cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { cx.views.1 } +} + +impl AuthLike for MenuHost { fn auth<'a>(cx: &Cx<'a, Self>) -> plx_session::auth::SessionRead<'a> { - cx.views + cx.views.0 } } @@ -607,7 +612,7 @@ mod tests { fn cx_of(read: &plx_session::auth::owner::SessionSnapshot) -> Cx<'_, MenuHost> { use plx_machine::machine::{InputOwner, Tick}; Cx:: { - views: read.read(), + views: (read.read(), crate::registry::publication_fixture()), tick: Tick::default(), measure: &plx_ui::fixture::FixtureMeasure, press: Default::default(), focus: Default::default(), owner: InputOwner::Entry(EntryId(0)), @@ -770,7 +775,7 @@ mod tests { ..Default::default() }]; plx_plex::plex::session::install_transient_for_test(true); let mut menu = AccountMenuScreen::new(EntryId(0)); - menu.build(false); + menu.build(&crate::registry::capture_fixture(), false); assert!(!menu_rows(&menu).contains(&Action::SignOut)); plx_plex::plex::session::save(&saved); tick(&mut menu, &published(false)); @@ -784,13 +789,13 @@ mod tests { let _serial = plx_base::testlock::serial(); let _session = plx_plex::plex::session::TempSession::new("account-action-identity"); let mut menu = AccountMenuScreen::new(EntryId(0)); - menu.build(false); + menu.build(&crate::registry::capture_fixture(), false); let settings_key = Action::Settings.focus_key(); assert_eq!(menu.form.index_of_key(RowKey(settings_key)), Some(1)); plx_plex::plex::session::save(&local(Session { client_id: "synthetic-client".into(), account_token: "synthetic-token".into(), ..Default::default() })); menu.built = false; - menu.build(false); + menu.build(&crate::registry::capture_fixture(), false); // Sign out arrives LAST behind a rule, so Settings holds its seat — and still its key assert_eq!(menu.form.index_of_key(RowKey(settings_key)), Some(1)); assert!(menu.form.index_of_key(RowKey(Action::SignOut.focus_key())) > Some(1)); @@ -1137,3 +1142,20 @@ mod tests { plx_ui::table::assert_no_fit_failures(&out); } } + +#[cfg(test)] +mod retained_input_tests { + use super::*; + #[test] + fn a_cold_account_menu_waits_for_the_retained_settled_session() { + let mut inputs = crate::registry::ScreenInputs::default(); + let mut menu = AccountMenuScreen::new(EntryId(0)); + menu.build(&inputs, false); + assert!(!menu.built); + inputs.settled = true; + menu.build(&inputs, false); + assert!(menu.built); + assert!(menu.form.index_of(&Action::SignIn).is_some()); + assert!(menu.form.index_of(&Action::SignOut).is_none()); + } +} diff --git a/rust-modules/screens/src/alt_sources_tests.rs b/rust-modules/screens/src/alt_sources_tests.rs index 855eef3c3c..6c3b645e2d 100644 --- a/rust-modules/screens/src/alt_sources_tests.rs +++ b/rust-modules/screens/src/alt_sources_tests.rs @@ -21,14 +21,40 @@ fn test_store() -> &'static mut plx_data::stores::metadata::MetadataStore { TEST_METADATA.with(|cell| unsafe { &mut *cell.get() }) } -/// D3 test helper: `metadata::alt_install`/`alt_restamp_owners` are private now, reached only -/// through `MetadataStore::run` — these wrap that so the call sites below read exactly as they -/// did before the visibility change. +/// TEST ONLY: capture the registry facts at each fixture command, as the host does before a step. fn alt_install(sid: ServerId, rk: &str, copies: Vec) -> bool { - test_store().run(MetadataCmd::AltInstall { sid, rk: rk.to_string(), copies }) + test_store().run_with_keys(MetadataCmd::AltInstall { sid, rk: rk.to_string(), copies }, + &plx_data::pms::registry_keys_for_test()) } fn alt_restamp_owners() -> bool { - test_store().run(MetadataCmd::AltRestampOwners) + test_store().run_with_keys(MetadataCmd::AltRestampOwners, &plx_data::pms::registry_keys_for_test()) +} + +#[test] +fn alt_fixture_uses_captured_server_facts() { + struct Cleanup; + impl Drop for Cleanup { + fn drop(&mut self) { + test_store().run(MetadataCmd::Clear); + plx_plex::plex::reset_servers_for_test(); + } + } + let _guard = plx_base::testlock::serial(); + let _cleanup = Cleanup; + plx_plex::plex::reset_servers_for_test(); + let server = plx_plex::plex::register_for_test("alt-capture", "127.0.0.1", 1, "t", "cid"); + plx_plex::plex::describe_server(server, "Server", "captured", plx_plex::plex::GrantEvidence::outside()); + let keys = plx_data::pms::registry_keys_for_test(); + plx_plex::plex::describe_server(server, "Server", "current", plx_plex::plex::GrantEvidence::outside()); + assert!(test_store().run_with_keys(MetadataCmd::AltInstall { + sid: server, rk: "4".into(), copies: vec![copy(server.raw(), "Movies", "stale", "4", "1080")], + }, &keys)); + assert_eq!(test_store().view().alt_copies(server, "4")[0].owner.as_deref(), Some("captured")); + assert!(alt_restamp_owners()); + assert_eq!(test_store().view().alt_copies(server, "4")[0].owner.as_deref(), Some("current")); + plx_plex::plex::describe_server(server, "Server", "latest", plx_plex::plex::GrantEvidence::outside()); + assert!(alt_install(server, "4", vec![copy(server.raw(), "Movies", "stale", "4", "1080")])); + assert_eq!(test_store().view().alt_copies(server, "4")[0].owner.as_deref(), Some("latest")); } fn sid(n: u16) -> ServerId { diff --git a/rust-modules/screens/src/clock_readout.rs b/rust-modules/screens/src/clock_readout.rs index a6e1b8993f..71052f2d10 100644 --- a/rust-modules/screens/src/clock_readout.rs +++ b/rust-modules/screens/src/clock_readout.rs @@ -23,26 +23,18 @@ pub fn reason_for(blocked: Option) -> Option<(&'static CStr, Icon)> { Some((reason, Icon::ClockBadgeAlert)) } -/// What a screen holds of `net::keypin::blocked_for` — the fact about the ONE server its read-out -/// speaks about — re-read only when `keypin::revision` moved or that server changed -/// (`OfferWatch`'s shape: the revision is global, the answer is per machine). +/// The captured reason held for the one server this read-out describes. The immutable +/// publication may be replaced independently of its revision, so compare the reason itself. #[derive(Clone, Debug, Default)] pub struct ClockWatch { - seen: Option<(u64, Option)>, held: Option, } impl ClockWatch { - /// Re-read the fact about `machine` (`None`: the read-out speaks about no known server, so no - /// server's fact applies); `true` when what the read-out shows changed. - pub fn refresh(&mut self, machine: Option<&str>) -> bool { - let rev = plx_net::net::keypin::revision(); - if matches!(&self.seen, Some((r, m)) if *r == rev && m.as_deref() == machine) { - return false; - } - self.seen = Some((rev, machine.map(str::to_owned))); - // The empty id names no server: only a dev-planted fact answers it. - let next = plx_net::net::keypin::blocked_for(machine.unwrap_or_default()); + /// Read the captured fact for `machine`; `None` selects the explicit empty-id fact. + /// Return `true` only when the held reason changed. + pub fn refresh(&mut self, facts: Option<&plx_plex::plex::ClockFacts>, machine: Option<&str>) -> bool { + let next = facts.and_then(|facts| facts.blocked_for(machine)); std::mem::replace(&mut self.held, next) != next } @@ -64,7 +56,7 @@ mod tests { use plx_base::fontcov::advances::ShippedMeasure; use plx_ui::fit::HEADROOM; use plx_platform::i18n::{language_on_this_thread_for_test, msg}; - use plx_net::net::keypin; + use plx_ui::widgets::StatusOverlay; #[test] @@ -93,30 +85,41 @@ mod tests { /// pair changes nothing and reports nothing. Another server's fact never shows. #[test] fn the_watch_re_reads_when_the_revision_or_the_machine_moves_and_not_otherwise() { - let _serial = plx_base::testlock::serial(); - let key = keypin::key_of("clock-watch.invalid", 32400); - let _scoped = keypin::Scoped::watch_machine("clock-watch-machine", &key); - let here = Some("clock-watch-machine"); + use plx_plex::plex::{ClockFacts, ServerId}; + let make = |reason| ClockFacts::scripted(7, ServerId::UNSET, None, + [(ServerId::UNSET, "machine".to_owned(), reason)]); + let no_key = make(Some(Blocked::NoKey)); + let changed = make(Some(Blocked::KeyChanged)); let mut watch = ClockWatch::default(); - watch.refresh(here); - assert_eq!(watch.blocked(), None, "no fact stands for this machine"); - let before = watch.blocked(); - keypin::strict_failure(&key, 60, Some(10)); - assert_eq!(watch.blocked(), before, "a held value does not change under the screen mid-frame"); - assert!(watch.refresh(here), "the revision moved"); - assert_eq!(watch.blocked(), Some(Blocked::NoKey)); - assert!(!watch.refresh(here), "nothing moved since"); - - assert!(watch.refresh(Some("clock-watch-other")), "another server: the fact is not its own"); - assert_eq!(watch.blocked(), None); - assert!(!watch.refresh(None), "no server at all: no fact, so nothing the read-out shows moved"); - assert!(watch.refresh(here), "back to the server the fact is about"); + assert!(watch.refresh(Some(&no_key), Some("machine"))); assert_eq!(watch.blocked(), Some(Blocked::NoKey)); + assert!(!watch.refresh(Some(&no_key), Some("machine"))); + assert!(watch.refresh(Some(&changed), Some("machine")), "equal revisions may carry different facts"); + assert_eq!(watch.blocked(), Some(Blocked::KeyChanged)); + assert!(watch.refresh(Some(&changed), Some("other"))); + assert!(!watch.refresh(Some(&changed), None)); + assert!(watch.refresh(Some(&no_key), Some("machine"))); + assert!(watch.refresh(None, Some("machine"))); } /// **Both reasons fit the two-line slot in every shipped language**: nothing else fit-tests /// Home's or a Library source's reason line. A reason that truncates loses its remedy. #[test] + fn clock_consumer_sites_do_not_read_ambient_sources() { + let cases = [ + (include_str!("clock_readout.rs"), "pub fn refresh(", "pub fn blocked("), + (include_str!("home/mod.rs"), "fn tick", "self.plaintext_alert.update(dt)"), + (include_str!("library/status.rs"), "pub(super) fn watch_readout", "pub(super) fn status_rect"), + ]; + for (source, start, end) in cases { + let body = source.split_once(start).expect("consumer start").1.split_once(end).expect("consumer end").0; + for forbidden in [concat!("keypin::", "revision"), concat!("keypin::", "blocked_for"), + concat!("plex::", "client_for"), concat!("plex::", "current_server")] { + assert!(!body.contains(forbidden), "ambient read: {forbidden}"); + } + } + } + #[test] fn both_reasons_fit_the_two_line_slot_in_every_shipped_language() { let mut out = Vec::new(); for language in plx_platform::i18n::SHIPPED { diff --git a/rust-modules/screens/src/consent_test_support.rs b/rust-modules/screens/src/consent_test_support.rs index 01e494e858..bebf3ec562 100644 --- a/rust-modules/screens/src/consent_test_support.rs +++ b/rust-modules/screens/src/consent_test_support.rs @@ -14,7 +14,7 @@ pub use plx_machine::present::Present; /// fixture is sufficient; the nested host still carries the same view type as production. pub fn test_cx(m: &FixtureMeasure) -> Cx<'_, InnerHost> { Cx { - views: plx_data::stores::browse::DirectoryView::empty_for_test().into(), + views: crate::registry::InnerViews::new(plx_data::stores::browse::DirectoryView::empty_for_test(), crate::registry::publication_fixture()), tick: Tick::default(), measure: m, press: PressRead::default(), diff --git a/rust-modules/screens/src/detail/tests.rs b/rust-modules/screens/src/detail/tests.rs index 745b3a6f26..d48ca55d19 100644 --- a/rust-modules/screens/src/detail/tests.rs +++ b/rust-modules/screens/src/detail/tests.rs @@ -227,11 +227,11 @@ fn clear() { // The *Also available* store outlives a page, so a test that seeded it hands the next one an // empty one — the addressed store cannot MIS-answer, but it can answer for an item a later // test happens to reuse the pair of. - test_store().run(plx_data::stores::metadata::MetadataCmd::AltInstall { + test_store().run_with_keys(plx_data::stores::metadata::MetadataCmd::AltInstall { sid: plx_plex::plex::ServerId::UNSET, rk: String::new(), copies: Vec::new(), - }); + }, &plx_data::pms::registry_keys_for_test()); } fn step( @@ -1570,7 +1570,7 @@ fn hero_action_row_hit_matches_the_drawn_controls_at_every_set_size() { // The *Also available* control's gate is the STORE, addressed by the page's own // pair — seeded here the way a landed cross-source resolve seeds it, never by // opening the panel. - test_store().run(plx_data::stores::metadata::MetadataCmd::AltInstall { + test_store().run_with_keys(plx_data::stores::metadata::MetadataCmd::AltInstall { sid, rk: "hero-hit".into(), copies: if alt { @@ -1581,7 +1581,7 @@ fn hero_action_row_hit_matches_the_drawn_controls_at_every_set_size() { } else { Vec::new() }, - }); + }, &plx_data::pms::registry_keys_for_test()); let mut screen = bare(&_guard, sid, "hero-hit"); let set = screen.hero_set(test_store().view()); assert_eq!( diff --git a/rust-modules/screens/src/family.rs b/rust-modules/screens/src/family.rs index 3b52d4594e..73eb23cb81 100644 --- a/rust-modules/screens/src/family.rs +++ b/rust-modules/screens/src/family.rs @@ -301,10 +301,11 @@ pub struct InnerHost; pub struct InnerViews<'a> { pub directory: plx_data::stores::browse::DirectoryView<'a>, pub marker_prefs: plx_appkit::skip_policy::MarkerPrefsView, + pub inputs: &'a crate::registry::ScreenInputs, } -impl<'a> From> for InnerViews<'a> { - fn from(directory: plx_data::stores::browse::DirectoryView<'a>) -> Self { - Self { directory, marker_prefs: Default::default() } +impl<'a> InnerViews<'a> { + pub fn new(directory: plx_data::stores::browse::DirectoryView<'a>, inputs: &'a crate::registry::ScreenInputs) -> Self { + Self { directory, inputs, marker_prefs: Default::default() } } } @@ -329,6 +330,10 @@ impl Host for InnerHost { type Memory = (); } +impl crate::registry::ScreenInputsLike for InnerHost { + fn screen_inputs<'a>(cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { cx.views.inputs } +} + impl DirectoryLike for InnerHost { fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a> { cx.views.directory @@ -343,7 +348,7 @@ impl DirectoryLike for InnerHost { /// borrow to hand it to a `DrawFrame`. pub fn inner_cx<'o, 'a: 'o, H: DirectoryLike>(cx: &Cx<'a, H>) -> Cx<'o, InnerHost> { Cx { - views: InnerViews { directory: H::directory(cx), marker_prefs: H::marker_prefs(cx) }, + views: InnerViews { directory: H::directory(cx), marker_prefs: H::marker_prefs(cx), inputs: H::screen_inputs(cx) }, tick: cx.tick, measure: cx.measure, press: cx.press, diff --git a/rust-modules/screens/src/filmography.rs b/rust-modules/screens/src/filmography.rs index 07d55e1d87..bf4860a11c 100644 --- a/rust-modules/screens/src/filmography.rs +++ b/rust-modules/screens/src/filmography.rs @@ -1165,7 +1165,7 @@ mod tests { #[test] fn a_fresh_filmography_reads_only_the_person_view_it_is_given() { let mut first = plx_data::stores::person::PersonStore::default(); - first.run(plx_data::stores::person::PersonCmd::Open { + crate::registry::run_person_fixture(&mut first, plx_data::stores::person::PersonCmd::Open { sid: ServerId::UNSET, key: "person".into(), guid: "guid".into(), name: "First owner".into(), thumb: String::new(), }); diff --git a/rust-modules/screens/src/home/cards_harness.rs b/rust-modules/screens/src/home/cards_harness.rs index cb3c165e4f..2b3362819c 100644 --- a/rust-modules/screens/src/home/cards_harness.rs +++ b/rust-modules/screens/src/home/cards_harness.rs @@ -18,7 +18,14 @@ impl Host for HomeHost { type Init = super::super::family::NoInit; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for HomeHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl HomeLike for HomeHost { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn hubs<'a>(cx: &Cx<'a, Self>) -> HubsView<'a> { cx.views } } diff --git a/rust-modules/screens/src/home/mod.rs b/rust-modules/screens/src/home/mod.rs index a783e01690..3e8c29f1ec 100644 --- a/rust-modules/screens/src/home/mod.rs +++ b/rust-modules/screens/src/home/mod.rs @@ -1831,9 +1831,10 @@ impl HomeScreen { self.snap_target = 0.0; self.snap.jump(0.0); } - let current = plx_plex::plex::client_for(plx_plex::plex::current_server()).map(|c| c.machine_id()); + let facts = H::clock_facts(cx); + let current = facts.and_then(|facts| facts.current_machine()); // `|` not `||`: both watches must re-read. - if self.plaintext.refresh(current, Near::First) | self.clock.refresh(current) { + if self.plaintext.refresh(&H::screen_inputs(cx).grants.offers, current, Near::First) | self.clock.refresh(facts, current) { fx.invalidate(Provenance::Landing(fx.from())); } if self.plaintext_alert.is_open() diff --git a/rust-modules/screens/src/home/tests.rs b/rust-modules/screens/src/home/tests.rs index 00884fafcf..84f62af1ce 100644 --- a/rust-modules/screens/src/home/tests.rs +++ b/rust-modules/screens/src/home/tests.rs @@ -43,21 +43,26 @@ impl Host for TestHost { type Fx = AppFx; type Msg = super::super::registry::AppMsg; type Elem = u32; - type Views<'a> = HubsView<'a>; + type Views<'a> = (HubsView<'a>, Option<&'a plx_plex::plex::ClockFacts>, &'a crate::registry::ScreenInputs); type Init = super::super::family::NoInit; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for TestHost { + fn screen_inputs<'a>(cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { cx.views.2 } +} + impl HomeLike for TestHost { + fn clock_facts<'a>(cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { cx.views.1 } fn hubs<'a>(cx: &Cx<'a, Self>) -> HubsView<'a> { - cx.views + cx.views.0 } } fn cx<'a>(view: HubsView<'a>, focus: Option>) -> Cx<'a, TestHost> { static MEASURE: FixtureMeasure = FixtureMeasure; Cx { - views: view, + views: (view, None, crate::registry::publication_fixture()), tick: Tick::default(), measure: &MEASURE, press: PressRead::default(), @@ -93,6 +98,15 @@ fn step( (handled, out, present.peek(0)) } +fn step_clock<'a>(s: &mut HomeScreen, view: HubsView<'a>, facts: &'a plx_plex::plex::ClockFacts) { + let mut context = cx(view, None); + context.views.1 = Some(facts); + let mut out = Vec::new(); + let mut present = plx_machine::present::Present::new(); + let mut fx = Effects::new(&mut out, plx_machine::machine::MachineId::Instance(InstanceId(9)), &mut present); + Machine::::step(s, &ScreenEvent::Tick(Tick::default()), &context, &mut fx); +} + /// Pop `key`'s card the way a deliberate move does: the move, then `frames` ticks with the card /// focused (the page must already be on the shelves, `snap` at 1). fn pop_card(s: &mut HomeScreen, view: HubsView<'_>, key: FocusKey, frames: u32) { @@ -347,13 +361,13 @@ fn a_failed_home_stands_on_the_page_readout_lines() { /// reason having moved the action row. #[test] fn a_failed_home_names_a_wrong_clock_when_key_mode_cannot_help() { - use plx_net::net::keypin::{self, Blocked}; + use plx_net::net::keypin::Blocked; + use plx_plex::plex::{ClockFacts, ServerId}; use plx_ui::icons::Icon; let _guard = plx_base::testlock::serial(); plx_plex::plex::grant::reset_for_test(); - let key = keypin::key_of("home-clock.invalid", 32400); - let _scoped = keypin::Scoped::watch_machine("home-clock-machine", &key); - let _current = current_server_for_test("home-clock-machine"); + let sid = ServerId::from_raw(77); + let facts = |reason| ClockFacts::scripted(7, sid, None, [(sid, "home-clock-machine".into(), reason)]); let mut state = plx_data::pms::PmsState::default(); let adapter = std::sync::Arc::new(plx_data::pms::PmsAdapter::default()); plx_data::pms::seed_for_test(&mut state, &adapter, 0, plx_data::pms::HubState::Failed); @@ -362,16 +376,16 @@ fn a_failed_home_names_a_wrong_clock_when_key_mode_cannot_help() { let mut s = screen(view); let measure = FixtureMeasure; - step(&mut s, view, None, &ScreenEvent::Tick(Tick::default())); + step_clock(&mut s, view, &facts(None)); let plain = status_overlay(view, &s.plaintext, &s.clock).unwrap(); assert_eq!((plain.reason, plain.glyph, plain.action), (None, Some(Icon::ServerBadgeMinus), Some(c"Try again"))); let plain_row = plain.action_frame_measured(&measure).unwrap(); let plain_caption = plain.caption.to_owned(); - keypin::strict_failure(&key, 60, Some(10)); + let before_tick = status_overlay(view, &s.plaintext, &s.clock).unwrap(); assert_eq!(before_tick.reason, None, "the held fact does not change between ticks"); - step(&mut s, view, None, &ScreenEvent::Tick(Tick::default())); + step_clock(&mut s, view, &facts(Some(Blocked::NoKey))); let overlay = status_overlay(view, &s.plaintext, &s.clock).unwrap(); assert_eq!(overlay.reason, Some(plx_platform::i18n::msg::browse_clock_no_key_c())); assert_eq!((overlay.glyph, overlay.action), (Some(Icon::ClockBadgeAlert), Some(c"Try again"))); @@ -381,8 +395,7 @@ fn a_failed_home_names_a_wrong_clock_when_key_mode_cannot_help() { let hit = s.hero_button_rect(view, 0, &measure).unwrap(); assert_eq!([hit.x, hit.y, hit.w, hit.h], [drawn.x, drawn.y, drawn.w, drawn.h], "the hit rect is the drawn pill"); - keypin::key_changed(&key); - step(&mut s, view, None, &ScreenEvent::Tick(Tick::default())); + step_clock(&mut s, view, &facts(Some(Blocked::KeyChanged))); let overlay = status_overlay(view, &s.plaintext, &s.clock).unwrap(); assert_eq!(s.clock.blocked(), Some(Blocked::KeyChanged)); assert_eq!(overlay.reason, Some(plx_platform::i18n::msg::browse_clock_key_changed_c())); @@ -402,7 +415,7 @@ fn a_failed_home_names_a_wrong_clock_when_key_mode_cannot_help() { choice: plx_plex::plex::session::PlaintextChoice::Undecided, }; plx_plex::plex::grant::offered(plx_plex::plex::grant::scope(), verdict.clone()); - step(&mut s, view, None, &ScreenEvent::Tick(Tick::default())); + step_clock(&mut s, view, &facts(Some(Blocked::KeyChanged))); let overlay = status_overlay(view, &s.plaintext, &s.clock).unwrap(); let offer = plx_session::auth::plaintext_copy(Some(&verdict), plx_session::auth::ReadoutSurface::SignedIn); assert_eq!(overlay.reason.and_then(|r| r.to_str().ok()), Some(offer.as_ref())); @@ -412,30 +425,22 @@ fn a_failed_home_names_a_wrong_clock_when_key_mode_cannot_help() { /// Make `machine` the current server (the one a failed Home speaks about) for a test, and put the /// registry back when it ends. -fn current_server_for_test(machine: &str) -> impl Drop { - struct Reset; - impl Drop for Reset { - fn drop(&mut self) { - plx_plex::plex::reset_servers_for_test(); - } - } - plx_plex::plex::reset_servers_for_test(); - let sid = plx_plex::plex::register_pinned_with_client_id(machine, &plx_plex::plex::Origin::http("192.168.1.53", 32400), - "", None, "client", Default::default()); - assert!(plx_plex::plex::set_current(sid) || plx_plex::plex::current_server() == sid, "the test server is current"); - Reset -} +// Source identities in these tests are supplied as clock facts. /// **A fact about ANOTHER server does not colour a failed Home** (scenario B): Home asks /// `net::keypin::blocked_for` about the current server only. #[test] fn a_failed_home_ignores_a_clock_fact_about_another_server() { - use plx_net::net::keypin; + use plx_net::net::keypin::Blocked; + use plx_plex::plex::{ClockFacts, ServerId}; let _guard = plx_base::testlock::serial(); plx_plex::plex::grant::reset_for_test(); - let elsewhere = keypin::key_of("home-elsewhere.invalid", 32400); - let _scoped = keypin::Scoped::watch_machine("home-elsewhere-machine", &elsewhere); - let _current = current_server_for_test("home-here-machine"); + let here = ServerId::from_raw(78); + let other = ServerId::from_raw(79); + let facts = ClockFacts::scripted(8, here, None, [ + (here, "home-here-machine".into(), None), + (other, "home-elsewhere-machine".into(), Some(Blocked::KeyChanged)), + ]); let mut state = plx_data::pms::PmsState::default(); let adapter = std::sync::Arc::new(plx_data::pms::PmsAdapter::default()); plx_data::pms::seed_for_test(&mut state, &adapter, 0, plx_data::pms::HubState::Failed); @@ -443,9 +448,7 @@ fn a_failed_home_ignores_a_clock_fact_about_another_server() { let view = snapshot.view(); let mut s = screen(view); - keypin::strict_failure(&elsewhere, 60, Some(10)); - keypin::key_changed(&elsewhere); - step(&mut s, view, None, &ScreenEvent::Tick(Tick::default())); + step_clock(&mut s, view, &facts); assert_eq!(s.clock.blocked(), None); let overlay = status_overlay(view, &s.plaintext, &s.clock).unwrap(); assert_eq!((overlay.reason, overlay.glyph), (None, Some(plx_ui::icons::Icon::ServerBadgeMinus))); diff --git a/rust-modules/screens/src/hud_settings_tests.rs b/rust-modules/screens/src/hud_settings_tests.rs index f17cb4d425..e780a830d3 100644 --- a/rust-modules/screens/src/hud_settings_tests.rs +++ b/rust-modules/screens/src/hud_settings_tests.rs @@ -11,7 +11,7 @@ use plx_ui::fixture::FixtureMeasure; fn context(focus: u32) -> Cx<'static, InnerHost> { static MEASURE: FixtureMeasure = FixtureMeasure; Cx { - views: plx_data::stores::browse::DirectoryView::empty_for_test().into(), + views: crate::registry::InnerViews::new(plx_data::stores::browse::DirectoryView::empty_for_test(), crate::registry::publication_fixture()), tick: Tick::default(), measure: &MEASURE, press: PressRead::default(), diff --git a/rust-modules/screens/src/inputs.rs b/rust-modules/screens/src/inputs.rs new file mode 100644 index 0000000000..8ceb2eed12 --- /dev/null +++ b/rust-modules/screens/src/inputs.rs @@ -0,0 +1,93 @@ +//! Retained screen inputs. The host captures these at its publication boundary; screens never +//! resolve them from process state. Empty inputs explicitly represent a cold or controlled host. +use std::sync::Arc; +use plx_plex::plex::{grant::PlaintextVerdict, session::{CurrentProfile, PlaintextChoice, Session}, ServerId}; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct GrantInputs { + pub offers: Vec, + pub choices: Vec<(String, PlaintextChoice)>, + pub connected: Vec, +} + +#[derive(Clone)] +pub struct ScreenInputs { + pub session: Arc, + pub settled: bool, + pub visible_generation: u64, + /// Advances only when the host publishes different screen-visible facts. + pub revision: u64, + pub profile: Arc, + pub current_server: ServerId, + /// Stable machine-to-slot identities captured from the host's S4 client keys. + pub servers: Arc>, + pub grants: Arc, + /// A host-local semantic revision, independent of server-roster changes. + pub grant_generation: u64, + pub resolution_offered: bool, +} +impl Default for ScreenInputs { + fn default() -> Self { + Self { session: Arc::new(Session::default()), settled: false, visible_generation: 0, revision: 0, + profile: Arc::new(CurrentProfile { user: None, generation: 0, stamp: String::new() }), + current_server: ServerId::UNSET, servers: Default::default(), grants: Arc::new(GrantInputs::default()), + grant_generation: 0, resolution_offered: false } + } +} +impl ScreenInputs { + pub fn settled_session(&self) -> Option<&Arc> { self.settled.then_some(&self.session) } + pub fn same_facts(&self, other: &Self) -> bool { + self.visible_generation == other.visible_generation + && self.settled == other.settled + && self.session.ui_resolution() == other.session.ui_resolution() + && self.current_server == other.current_server + && self.servers == other.servers + && self.resolution_offered == other.resolution_offered + && self.grant_generation == other.grant_generation + && self.profile.generation == other.profile.generation + && self.profile.stamp == other.profile.stamp + && match (&self.profile.user, &other.profile.user) { + (None, None) => true, + (Some(a), Some(b)) => a.id == b.id && a.uuid == b.uuid && a.title == b.title, + _ => false, + } + } + pub fn session_key(&self) -> (u64, bool, u32) { + (self.revision, self.settled, self.profile.generation) + } +} + +#[cfg(test)] +pub(crate) fn empty_fixture() -> &'static ScreenInputs { + static EMPTY: std::sync::OnceLock = std::sync::OnceLock::new(); + EMPTY.get_or_init(ScreenInputs::default) +} + +/// The explicit registry boundary of legacy fixture hosts, never a production screen fallback. +#[cfg(test)] +pub(crate) fn capture_fixture() -> ScreenInputs { + use plx_plex::plex::{grant, session}; + let mut keys = plx_plex::plex::ClientKeys::default(); + keys.refill_roster(plx_plex::plex::current_server(), plx_plex::plex::server_roster_gen(), + plx_plex::plex::server_facts_gen(), plx_plex::plex::server_ids(), + plx_plex::plex::client_for, plx_plex::plex::server_facts, plx_plex::plex::server_probe_result); + let servers = keys.iter().filter_map(|(sid, _)| keys.facts(sid) + .map(|facts| (facts.machine_id.clone(), sid))).collect(); + let settled = session::peek_settled(); + let stored = settled.clone().unwrap_or_else(session::peek); + ScreenInputs { grants: Arc::new(GrantInputs { offers: grant::offers(), + choices: grant::choices(&stored.prefs.plaintext_consent, &stored.account_token), + connected: grant::granted_machines() }), session: stored, settled: settled.is_some(), + visible_generation: session::visible_generation(), + revision: { let (cache, profile) = session::screen_input_revision(); cache.wrapping_add(profile) }, + profile: session::current_snapshot(), + current_server: plx_plex::plex::current_server(), servers: Arc::new(servers), grant_generation: grant::revision(), + resolution_offered: plx_platform::tv::device::ui_resolution_offered() } +} + +/// Immutable publications for legacy fixture contexts that outlive their helper call. +/// Each capture is deliberately independent, like the fixtures' leaked catalog rows. +#[cfg(test)] +pub(crate) fn publication_fixture() -> &'static ScreenInputs { + Box::leak(Box::new(capture_fixture())) +} diff --git a/rust-modules/screens/src/legal.rs b/rust-modules/screens/src/legal.rs index a944d0cbe7..65edd54ad4 100644 --- a/rust-modules/screens/src/legal.rs +++ b/rust-modules/screens/src/legal.rs @@ -812,7 +812,7 @@ mod tests { /// or stepping a `Machine` outside the real dispatcher. fn fixture_cx(m: &FixtureMeasure, focus: Option>) -> Cx<'_, InnerHost> { Cx { - views: plx_data::stores::browse::DirectoryView::empty_for_test().into(), + views: crate::registry::InnerViews::new(plx_data::stores::browse::DirectoryView::empty_for_test(), crate::registry::publication_fixture()), tick: Tick::default(), measure: m, press: PressRead::default(), diff --git a/rust-modules/screens/src/lib.rs b/rust-modules/screens/src/lib.rs index 70d6bdbae6..237fb9f990 100644 --- a/rust-modules/screens/src/lib.rs +++ b/rust-modules/screens/src/lib.rs @@ -35,6 +35,7 @@ pub mod legal; pub mod login; pub mod onboard; pub mod clock_readout; +pub mod inputs; pub mod plaintext_question; pub mod player; pub mod profiles; diff --git a/rust-modules/screens/src/library/cards_harness.rs b/rust-modules/screens/src/library/cards_harness.rs index 1f7ef4939e..10c715b04a 100644 --- a/rust-modules/screens/src/library/cards_harness.rs +++ b/rust-modules/screens/src/library/cards_harness.rs @@ -27,7 +27,14 @@ impl Host for LibHost { type Init = FixtureArg; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for LibHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl LibraryLike for LibHost { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a> { cx.views.directory } fn section_hubs<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::HubsView<'a> { cx.views.hubs } diff --git a/rust-modules/screens/src/library/deferred_tests.rs b/rust-modules/screens/src/library/deferred_tests.rs index 666497d926..755fa8541b 100644 --- a/rust-modules/screens/src/library/deferred_tests.rs +++ b/rust-modules/screens/src/library/deferred_tests.rs @@ -21,7 +21,14 @@ impl Host for TestHost { type Init = FixtureArg; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for TestHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl LibraryLike for TestHost { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } @@ -165,7 +172,7 @@ fn apply( Some(stores.person.run(command)) } Fx::App(AppFx::Store(_, StoreCmd::Search(command))) => { - Some(stores.search_run(command, directory)) + Some(stores.search_run_for_test(command, directory)) } Fx::App(AppFx::Store(_, StoreCmd::ViewState(command))) => { Some(stores.viewstate_run(command, directory, &plx_data::pms::registry_keys_for_test(), 0).changed) diff --git a/rust-modules/screens/src/library/foreign_replacement_tests.rs b/rust-modules/screens/src/library/foreign_replacement_tests.rs index 066ece834d..8883cd575b 100644 --- a/rust-modules/screens/src/library/foreign_replacement_tests.rs +++ b/rust-modules/screens/src/library/foreign_replacement_tests.rs @@ -21,7 +21,14 @@ impl Host for TestHost { type Init = FixtureArg; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for TestHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl LibraryLike for TestHost { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } diff --git a/rust-modules/screens/src/library/menu.rs b/rust-modules/screens/src/library/menu.rs index 9a23a5ef0d..5921bb47d8 100644 --- a/rust-modules/screens/src/library/menu.rs +++ b/rust-modules/screens/src/library/menu.rs @@ -1027,7 +1027,14 @@ mod tests { type Init = Arg; type Memory = crate::registry::PageMemory; } - impl LibraryLike for HostFixture { + impl crate::registry::ScreenInputsLike for HostFixture { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + +impl LibraryLike for HostFixture { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } diff --git a/rust-modules/screens/src/library/navigation_tests.rs b/rust-modules/screens/src/library/navigation_tests.rs index de1d79d20e..19c8ad8be8 100644 --- a/rust-modules/screens/src/library/navigation_tests.rs +++ b/rust-modules/screens/src/library/navigation_tests.rs @@ -21,7 +21,14 @@ impl Host for TestHost { type Init = FixtureArg; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for TestHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl LibraryLike for TestHost { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } diff --git a/rust-modules/screens/src/library/rail.rs b/rust-modules/screens/src/library/rail.rs index 6a5c910816..7799443791 100644 --- a/rust-modules/screens/src/library/rail.rs +++ b/rust-modules/screens/src/library/rail.rs @@ -463,7 +463,14 @@ mod tests { type Init = plx_ui::fixture::FixtureArg; type Memory = PageMemory; } - impl LibraryLike for RailHost { + impl crate::registry::ScreenInputsLike for RailHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + +impl LibraryLike for RailHost { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a> { cx.views.directory } fn section_hubs<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::HubsView<'a> { cx.views.hubs } diff --git a/rust-modules/screens/src/library/recommended_tests.rs b/rust-modules/screens/src/library/recommended_tests.rs index 2880731aed..39db83c94b 100644 --- a/rust-modules/screens/src/library/recommended_tests.rs +++ b/rust-modules/screens/src/library/recommended_tests.rs @@ -22,7 +22,14 @@ impl Host for HostFixture { type Init = FixtureArg; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for HostFixture { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl LibraryLike for HostFixture { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a> { cx.views.directory } fn section_hubs<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::HubsView<'a> { cx.views.hubs } diff --git a/rust-modules/screens/src/library/review_actions_tests.rs b/rust-modules/screens/src/library/review_actions_tests.rs index f8fff07d30..8d207df5e5 100644 --- a/rust-modules/screens/src/library/review_actions_tests.rs +++ b/rust-modules/screens/src/library/review_actions_tests.rs @@ -42,7 +42,14 @@ impl Host for HostFixture { type Init = Arg; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for HostFixture { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl LibraryLike for HostFixture { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } diff --git a/rust-modules/screens/src/library/shelf_action_tests.rs b/rust-modules/screens/src/library/shelf_action_tests.rs index 0b9b40d37a..0060fe4c80 100644 --- a/rust-modules/screens/src/library/shelf_action_tests.rs +++ b/rust-modules/screens/src/library/shelf_action_tests.rs @@ -22,7 +22,14 @@ impl Host for TestHost { type Init = FixtureArg; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for TestHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl LibraryLike for TestHost { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } diff --git a/rust-modules/screens/src/library/status.rs b/rust-modules/screens/src/library/status.rs index 7e202eb61d..c08aa1339f 100644 --- a/rust-modules/screens/src/library/status.rs +++ b/rust-modules/screens/src/library/status.rs @@ -49,12 +49,16 @@ impl LibraryScreen { /// shows changed, so the caller damages the frame (the reason line moves the action row). pub(super) fn watch_readout(&mut self, cx: &Cx<'_, H>) -> bool { use super::super::plaintext_question::{asks, Near}; - let machine = (self.readout == Readout::Failed) - .then(|| H::directory(cx).source().and_then(|(sid, _)| plx_plex::plex::client_for(*sid))) - .flatten() - .map(|client| client.machine_id()); - let offer_moved = self.plaintext.refresh(machine, Near::Only); - let clock_moved = self.clock.refresh(machine); + let facts = H::clock_facts(cx); + let inputs = H::screen_inputs(cx); + let source = (self.readout == Readout::Failed) + .then(|| H::directory(cx).source().map(|(sid, _)| *sid)).flatten(); + // Plaintext offers use the published server identity even without a clock publication. + let machine = source.and_then(|sid| inputs.servers.iter() + .find(|(_, slot)| *slot == sid).map(|(machine, _)| machine.as_str())); + let offer_moved = self.plaintext.refresh(&inputs.grants.offers, machine, Near::Only); + let clock_machine = source.and_then(|sid| facts.and_then(|facts| facts.machine(sid))); + let clock_moved = self.clock.refresh(facts, clock_machine); if self.plaintext_alert.is_open() && !(self.readout == Readout::Failed && self.plaintext_alert.subject() == self.plaintext.verdict().map(|v| v.machine_id.as_str()) diff --git a/rust-modules/screens/src/library/status_contract_tests.rs b/rust-modules/screens/src/library/status_contract_tests.rs index 9fc21a13ad..b082d05915 100644 --- a/rust-modules/screens/src/library/status_contract_tests.rs +++ b/rust-modules/screens/src/library/status_contract_tests.rs @@ -40,7 +40,14 @@ impl Host for StatusHost { type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for StatusHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + impl LibraryLike for StatusHost { + fn clock_facts<'a>(_cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { None } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a> { cx.views.directory } fn section_hubs<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::HubsView<'a> { cx.views.hubs } diff --git a/rust-modules/screens/src/library/tests.rs b/rust-modules/screens/src/library/tests.rs index 9da82dc123..2c6d6723a3 100644 --- a/rust-modules/screens/src/library/tests.rs +++ b/rust-modules/screens/src/library/tests.rs @@ -19,6 +19,8 @@ impl ScreenArg for Arg { pub(super) struct HostFixture; #[derive(Clone, Copy)] pub(super) struct Views<'a> { + inputs: &'a crate::registry::ScreenInputs, + clock: Option<&'a plx_plex::plex::ClockFacts>, listing: plx_data::stores::browse::ListingView<'a>, directory: plx_data::stores::browse::DirectoryView<'a>, hubs: plx_data::stores::browse::HubsView<'a>, @@ -32,7 +34,12 @@ impl Host for HostFixture { type Init = Arg; type Memory = PageMemory; } +impl crate::registry::ScreenInputsLike for HostFixture { + fn screen_inputs<'a>(cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { cx.views.inputs } +} + impl LibraryLike for HostFixture { + fn clock_facts<'a>(cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { cx.views.clock } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a> { cx.views.directory } fn section_hubs<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::HubsView<'a> { cx.views.hubs } @@ -442,19 +449,23 @@ fn retry_stop_matches_the_shared_measured_status_action_with_and_without_reason( /// and the *Try again* stop is the pill the same frame draws. #[test] fn a_failed_source_names_a_wrong_clock_when_key_mode_cannot_help() { - use plx_net::net::keypin::{self, Blocked}; + use plx_net::net::keypin::Blocked; + use plx_plex::plex::ClockFacts; use plx_ui::icons::Icon; use plx_ui::widgets::StatusOverlay; let _guard = plx_base::testlock::serial(); plx_plex::plex::grant::reset_for_test(); - let key = keypin::key_of("library-clock.invalid", 32400); - let _scoped = keypin::Scoped::watch_machine("library-clock-machine", &key); plx_plex::plex::reset_servers_for_test(); let failed_sid = plx_plex::plex::register_pinned_with_client_id("library-clock-machine", &plx_plex::plex::Origin::http("192.168.1.51", 32400), "", None, "client", Default::default()); // `tick_damaged`: a fact appearing or clearing under a static Failed read-out moves the // action row, so the tick must damage the frame. - let tick = tick_damaged; + let tick = |page: &mut LibraryScreen, fixture: &Fixture, reason| { + let sid = fixture.directory.view().source().unwrap().0; + let machine = if sid == failed_sid { "library-clock-machine" } else { "lan-machine" }; + let facts = ClockFacts::scripted(7, sid, None, [(sid, machine.into(), reason)]); + tick_with_clock(page, fixture, &facts) + }; let read = |page: &LibraryScreen, fixture: &Fixture| { let cx = fixture.cx(Some(page.key(RETRY))); let (caption, reason) = page.status_text(&cx); @@ -468,17 +479,17 @@ fn a_failed_source_names_a_wrong_clock_when_key_mode_cannot_help() { for owner in ["", "friend"] { let fixture = Fixture::failed_source(failed_sid, owner); let mut page = fixture.screen(); - tick(&mut page, &fixture); + tick(&mut page, &fixture, None); let (shown, glyph, plain_row, caption) = read(&page, &fixture); let shared = plx_platform::i18n::msg::browse_library_shared_unreachable("friend"); assert_eq!(shown.as_ref().and_then(|r| r.to_str().ok()), (!owner.is_empty()).then_some(shared.as_str()), "no fact: today's read-out"); assert_eq!(glyph, Some(Icon::ServerBadgeMinus)); - keypin::strict_failure(&key, 60, Some(10)); + let (stale, ..) = read(&page, &fixture); assert_eq!(stale, shown, "the held fact does not change between ticks"); - assert!(tick(&mut page, &fixture), "a fact appearing under a static read-out damages the frame"); + assert!(tick(&mut page, &fixture, Some(Blocked::NoKey)), "a fact appearing under a static read-out damages the frame"); let (shown, glyph, row, clock_caption) = read(&page, &fixture); assert_eq!(shown.as_deref(), Some(plx_platform::i18n::msg::browse_clock_no_key_c()), "owner {owner:?}"); assert_eq!(glyph, Some(Icon::ClockBadgeAlert)); @@ -489,14 +500,12 @@ fn a_failed_source_names_a_wrong_clock_when_key_mode_cannot_help() { } assert!(row.y >= StatusOverlay::FULL_ANCHOR_TOP); - keypin::key_changed(&key); - assert!(tick(&mut page, &fixture)); + assert!(tick(&mut page, &fixture, Some(Blocked::KeyChanged))); assert_eq!(page.clock.blocked(), Some(Blocked::KeyChanged)); let (shown, ..) = read(&page, &fixture); assert_eq!(shown.as_deref(), Some(plx_platform::i18n::msg::browse_clock_key_changed_c())); - keypin::strict_established(&key); - assert!(tick(&mut page, &fixture), "…and one clearing does too"); + assert!(tick(&mut page, &fixture, None), "…and one clearing does too"); let (shown, glyph, ..) = read(&page, &fixture); assert_eq!(shown.as_ref().and_then(|r| r.to_str().ok()), (!owner.is_empty()).then_some(shared.as_str()), "the fact cleared: the shared-by line is back"); @@ -505,17 +514,13 @@ fn a_failed_source_names_a_wrong_clock_when_key_mode_cannot_help() { // An offered plaintext server's reason outranks the clock's, glyph included. use plx_plex::plex::session::PlaintextChoice; - plx_plex::plex::reset_servers_for_test(); let sid = plx_plex::plex::register_pinned_with_client_id("lan-machine", &plx_plex::plex::Origin::http("192.168.1.50", 32400), "", None, "client", Default::default()); let fixture = Fixture::failed_source(sid, "friend"); let mut page = fixture.screen(); - let lan_key = keypin::key_of("192.168.1.50", 32400); - let _lan = keypin::Scoped::watch_machine("lan-machine", &lan_key); - keypin::strict_failure(&lan_key, 60, Some(10)); plx_plex::plex::grant::offered(plx_plex::plex::grant::scope(), plx_plex::plex::grant::PlaintextVerdict { machine_id: "lan-machine".into(), name: "nas".into(), shared_by: String::new(), eligibility: plx_plex::plex::probe::PlaintextEligibility::Eligible, choice: PlaintextChoice::Undecided }); - tick(&mut page, &fixture); + tick(&mut page, &fixture, Some(Blocked::NoKey)); assert!(page.clock.blocked().is_some(), "the clock fact stands"); let (shown, glyph, ..) = read(&page, &fixture); assert!(shown.as_ref().and_then(|r| r.to_str().ok()).is_some_and(|r| r.contains("Select Connect")), "{shown:?}"); @@ -528,35 +533,29 @@ fn a_failed_source_names_a_wrong_clock_when_key_mode_cannot_help() { /// server's expired certificate leaves it alone, and a fact for the source's own machine shows. #[test] fn a_failed_source_ignores_a_clock_fact_about_another_server() { - use plx_net::net::keypin; + use plx_net::net::keypin::Blocked; + use plx_plex::plex::{ClockFacts, ServerId}; use plx_ui::icons::Icon; let _guard = plx_base::testlock::serial(); plx_plex::plex::grant::reset_for_test(); - plx_plex::plex::reset_servers_for_test(); - let here = keypin::key_of("library-here.invalid", 32400); - let elsewhere = keypin::key_of("library-elsewhere.invalid", 32400); - let _here = keypin::Scoped::watch_machine("library-here-machine", &here); - let _elsewhere = keypin::Scoped::watch_machine("library-elsewhere-machine", &elsewhere); - let sid = plx_plex::plex::register_pinned_with_client_id("library-here-machine", - &plx_plex::plex::Origin::http("192.168.1.52", 32400), "", None, "client", Default::default()); + let sid = ServerId::from_raw(80); + let other = ServerId::from_raw(81); let fixture = Fixture::failed_source(sid, ""); let mut page = fixture.screen(); - let tick = |page: &mut LibraryScreen| tick_damaged(page, &fixture); let shown = |page: &LibraryScreen| { let cx = fixture.cx(Some(page.key(RETRY))); let (caption, reason) = page.status_text(&cx); let overlay = page.status_overlay(&cx, &caption, reason.as_deref()); (overlay.reason.map(|r| r.to_owned()), overlay.glyph) }; - tick(&mut page); - keypin::strict_failure(&elsewhere, 60, Some(10)); - keypin::key_changed(&elsewhere); - tick(&mut page); + let facts = |reason| ClockFacts::scripted(9, sid, None, [ + (sid, "library-here-machine".into(), reason), + (other, "library-elsewhere-machine".into(), Some(Blocked::KeyChanged)), + ]); + tick_with_clock(&mut page, &fixture, &facts(None)); assert_eq!(page.clock.blocked(), None, "another server's fact is not this source's"); - assert_eq!(shown(&page), (None, Some(Icon::ServerBadgeMinus)), "today's read-out"); - - keypin::strict_failure(&here, 60, Some(10)); - tick(&mut page); + assert_eq!(shown(&page), (None, Some(Icon::ServerBadgeMinus))); + tick_with_clock(&mut page, &fixture, &facts(Some(Blocked::NoKey))); assert_eq!(shown(&page), (Some(plx_platform::i18n::msg::browse_clock_no_key_c().to_owned()), Some(Icon::ClockBadgeAlert))); } @@ -921,6 +920,7 @@ fn a_failed_source_over_an_offered_server_asks_the_shared_question() { offer("lan-machine"); tick(&mut page); + let cx = fixture.cx(Some(page.key(RETRY))); let (caption, reason) = page.status_text(&cx); assert!(reason.as_ref().and_then(|r| r.to_str().ok()).is_some_and(|r| r.contains("Select Connect")), "{reason:?}"); assert_eq!(page.status_overlay(&cx, &caption, reason.as_deref()).action, Some(connect())); @@ -1118,7 +1118,7 @@ impl Fixture { } } pub(super) fn cx(&self, focus: Option>) -> Cx<'_, HostFixture> { - Cx { views: Views { listing: self.listing.view(), directory: self.directory.view(), hubs: self.hubs.view() }, + Cx { views: Views { inputs: crate::registry::publication_fixture(), listing: self.listing.view(), directory: self.directory.view(), hubs: self.hubs.view(), clock: None }, tick: Tick::default(), measure: &self.measure, focus: FocusRead { current: focus , ..Default::default() }, press: PressRead::default(), owner: OWNER } } @@ -1138,12 +1138,14 @@ impl Fixture { fixture } } -/// One Tick through the screen: whether it damaged the frame. -fn tick_damaged(page: &mut LibraryScreen, fixture: &Fixture) -> bool { + +fn tick_with_clock<'a>(page: &mut LibraryScreen, fixture: &'a Fixture, facts: &'a plx_plex::plex::ClockFacts) -> bool { let mut out = Vec::new(); let mut present = plx_machine::present::Present::new(); present.take(0); - page.step(&ScreenEvent::Tick(Tick::default()), &fixture.cx(None), + let mut cx = fixture.cx(None); + cx.views.clock = Some(facts); + page.step(&ScreenEvent::Tick(Tick::default()), &cx, &mut Effects::new(&mut out, MachineId::Instance(InstanceId(19)), &mut present)); present.changed() } diff --git a/rust-modules/screens/src/login.rs b/rust-modules/screens/src/login.rs index e596780558..8c9d11c9f3 100644 --- a/rust-modules/screens/src/login.rs +++ b/rust-modules/screens/src/login.rs @@ -2403,7 +2403,13 @@ mod tests { type Memory = (); } - impl AuthLike for SessionHost { + impl crate::registry::ScreenInputsLike for SessionHost { + fn screen_inputs<'a>(_cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + crate::registry::empty_fixture() + } +} + +impl AuthLike for SessionHost { fn auth<'a>(cx: &Cx<'a, Self>) -> auth::SessionRead<'a> { cx.views } diff --git a/rust-modules/screens/src/onboard.rs b/rust-modules/screens/src/onboard.rs index 9ceaf9bdbb..b79167b8d9 100644 --- a/rust-modules/screens/src/onboard.rs +++ b/rust-modules/screens/src/onboard.rs @@ -935,7 +935,7 @@ mod tests { directory: DirectoryView<'a>, ) -> Cx<'a, InnerHost> { Cx { - views: directory.into(), + views: crate::registry::InnerViews::new(directory, crate::registry::publication_fixture()), tick: plx_machine::machine::Tick::default(), measure: m, press: PressRead::default(), diff --git a/rust-modules/screens/src/person.rs b/rust-modules/screens/src/person.rs index 7be43b9dd6..9bf29bbf4a 100644 --- a/rust-modules/screens/src/person.rs +++ b/rust-modules/screens/src/person.rs @@ -1341,9 +1341,10 @@ impl Machine for PersonScreen { Handled::Yes } ScreenEvent::WillLeave(Leave::ForGood) | ScreenEvent::Unmount => { - // `&& !self.teardown_closed`: see the field. One teardown, one `Close`, even + // Cancel this body's Open even while the store is empty. The bridge keeps its + // sender address, so a retired page cannot close a replacement. One `Close`, even // though §3.4 delivers this arm twice and the queued command has not run yet. - if self.page.person(cx).is_some() && !self.teardown_closed { + if !self.teardown_closed { self.teardown_closed = true; fx.push(plx_machine::machine::Fx::App(AppFx::Store( plx_data::stores::StoreId::Person, @@ -1501,7 +1502,7 @@ mod tests { /// can force `credited` back to `false` on a live `Person` from outside `plx_data::person`). fn seed(movies: usize, shows: usize) -> (plx_data::stores::person::PersonStore, PersonScreen) { let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: ServerId::UNSET, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), @@ -1662,7 +1663,7 @@ mod tests { fn the_header_skeleton_spinner_reports_motion_while_facts_are_pending() { let _serial = plx_base::testlock::serial(); let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: ServerId::UNSET, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new(), @@ -1723,7 +1724,7 @@ mod tests { && name == "Person Name" && thumb == "thumb")); let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { sid: ServerId::from_raw(2), key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: ServerId::from_raw(2), key: "161".into(), guid: "person-guid".into(), name: "Person Name".into(), thumb: "thumb".into() }); out.clear(); { @@ -1752,7 +1753,7 @@ mod tests { "Person Name".into(), "thumb".into()); let measure = FixtureMeasure; let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { sid: ServerId::from_raw(2), key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: ServerId::from_raw(2), key: "161".into(), guid: "person-guid".into(), name: "Person Name".into(), thumb: "thumb".into() }); let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); @@ -1783,7 +1784,7 @@ mod tests { "Person Name".into(), "thumb".into()); let measure = FixtureMeasure; let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { sid: ServerId::from_raw(2), key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: ServerId::from_raw(2), key: "161".into(), guid: "person-guid".into(), name: "Person Name".into(), thumb: "thumb".into() }); let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); @@ -1800,6 +1801,31 @@ mod tests { assert_eq!(closes, 1, "a bare Unmount must close the Person store exactly once"); } + #[test] + fn empty_person_teardown_cancels_an_undelivered_open_exactly_once() { + for bare_unmount in [false, true] { + let mut screen = PersonScreen::new(EntryId(0), ServerId::UNSET, "pending".into(), + String::new(), "Pending".into(), String::new()); + let measure = FixtureMeasure; + let context = cx(&measure, plx_data::person::PersonView::default()); + let mut present = plx_machine::present::Present::new(); + let mut out = Vec::new(); + { + let mut fx = Effects::new(&mut out, plx_machine::machine::MachineId::Instance( + plx_machine::machine::InstanceId(0)), &mut present); + if !bare_unmount { + Machine::::step(&mut screen, &ScreenEvent::WillLeave(Leave::ForGood), &context, &mut fx); + } + Machine::::step(&mut screen, &ScreenEvent::Unmount, &context, &mut fx); + Machine::::step(&mut screen, &ScreenEvent::Unmount, &context, &mut fx); + } + let closes = out.iter().filter(|s| matches!(&s.fx, + plx_machine::machine::Fx::App(AppFx::Store(plx_data::stores::StoreId::Person, + plx_data::stores::StoreCmd::Person(PersonCmd::Close))))).count(); + assert_eq!(closes, 1, "an empty store may still owe this page an Open"); + } + } + /// **The mount-on-entry-pill rule's PENDING half** (module doc, point 2 of `ui/person.rs`'s /// own doc): with no filmography answered yet but a guid to ask plex.tv with, /// `entry_reachable_of` holds the entry group open even though `has_entry_of` is false — which @@ -2377,7 +2403,7 @@ mod tests { let share = plx_plex::plex::register_for_test("person-pending-share", "127.0.0.1", 2, "b", "cid"); let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { sid: origin, key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: origin, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new() }); let mut original = PersonScreen::new( @@ -2426,7 +2452,7 @@ mod tests { &cx_at(measure, store.view(), old_focus), &mut fx, ); - store.run(PersonCmd::Open { sid: origin, key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: origin, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new() }); store.install_source_for_test( @@ -2572,7 +2598,7 @@ mod tests { let share = plx_plex::plex::register_for_test("person-return-share", "127.0.0.1", 2, "b", "cid"); let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { sid: origin, key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: origin, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new() }); let mut first = PersonScreen::new( @@ -2609,7 +2635,7 @@ mod tests { "Other Person".to_string(), String::new(), ); - store.run(PersonCmd::Open { sid: origin, key: "other".into(), guid: "other-guid".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: origin, key: "other".into(), guid: "other-guid".into(), name: "Other Person".into(), thumb: String::new() }); assert!(first.page.person(&cx(&FixtureMeasure, store.view())).is_none(), "Person B displaced Person A"); @@ -2648,7 +2674,7 @@ mod tests { &cx_at(&measure, store.view(), old_focus), &mut fx, ); - store.run(PersonCmd::Open { sid: origin, key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: origin, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new() }); assert!(first.page.person(&cx(&FixtureMeasure, store.view())).is_some(), "return reclaims Person A's store"); @@ -2721,7 +2747,7 @@ mod tests { plx_plex::plex::reset_servers_for_test(); let sid = plx_plex::plex::register_for_test("person-cold-return", "127.0.0.1", 1, "a", "cid"); let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { sid, key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new() }); let mut original = PersonScreen::new( @@ -2776,7 +2802,7 @@ mod tests { &cx_at(&measure, store.view(), old_focus), &mut fx, ); - store.run(PersonCmd::Open { sid, key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new() }); assert!(remounted.page.person(&cx(&FixtureMeasure, store.view())).unwrap().shelf(0).is_empty()); @@ -2824,7 +2850,7 @@ mod tests { "Other Person".to_string(), String::new(), ); - store.run(PersonCmd::Open { sid: ServerId::UNSET, key: "other".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: ServerId::UNSET, key: "other".into(), guid: "other-guid".into(), name: "Other Person".into(), thumb: String::new() }); assert!(first.page.person(&cx(&FixtureMeasure, store.view())).is_none()); @@ -2842,7 +2868,7 @@ mod tests { &cx(&measure, store.view()), &mut fx, ); - store.run(PersonCmd::Open { sid: ServerId::UNSET, key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: ServerId::UNSET, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new() }); assert!(first.page.person(&cx(&FixtureMeasure, store.view())).is_some()); diff --git a/rust-modules/screens/src/person/cards_harness.rs b/rust-modules/screens/src/person/cards_harness.rs index 776638aaec..8456783204 100644 --- a/rust-modules/screens/src/person/cards_harness.rs +++ b/rust-modules/screens/src/person/cards_harness.rs @@ -45,7 +45,7 @@ pub(crate) fn mount(n: usize) -> Box { Box::new(Harness::new((0 impl Harness { fn new(movies: Vec) -> Self { let mut store = plx_data::stores::person::PersonStore::default(); - store.run(PersonCmd::Open { sid: ServerId::UNSET, key: "161".into(), + crate::registry::run_person_fixture(&mut store, PersonCmd::Open { sid: ServerId::UNSET, key: "161".into(), guid: "5d77682aeb5d26001f1de4b0".into(), name: "Idina Menzel".into(), thumb: String::new() }); let mut h = Self { store, screen: new_screen(), movies, focus: None, press: 1.0, ms: 0 }; h.install(); diff --git a/rust-modules/screens/src/plaintext_question.rs b/rust-modules/screens/src/plaintext_question.rs index 27d92853bc..4a23eccd52 100644 --- a/rust-modules/screens/src/plaintext_question.rs +++ b/rust-modules/screens/src/plaintext_question.rs @@ -400,7 +400,7 @@ pub enum AlertStep { /// server the read-out is about changed. #[derive(Clone, Debug, Default)] pub struct OfferWatch { - seen: Option<(u64, Option)>, + held: Option<(PlaintextVerdict, CString)>, } @@ -417,22 +417,12 @@ pub enum Near { impl OfferWatch { /// Re-read the offer for `machine` (`near` says whether another will do); `true` when what /// the read-out shows changed. - pub fn refresh(&mut self, machine: Option<&str>, near: Near) -> bool { - let key = (plx_plex::plex::grant::revision(), machine.map(str::to_owned)); - if self.seen.as_ref() == Some(&key) { - return false; - } - self.seen = Some(key); - let offers = plx_plex::plex::grant::offers(); - let at = offers.iter().position(|v| Some(v.machine_id.as_str()) == machine) - .or_else(|| (near == Near::First && !offers.is_empty()).then_some(0)); - let next = at.and_then(|i| offers.into_iter().nth(i)).map(|v| { - let line = reason(&v); - (v, line) - }); - let changed = next.as_ref().map(|(v, _)| v) != self.held.as_ref().map(|(v, _)| v); - self.held = next; - changed + pub fn refresh(&mut self, offers: &[PlaintextVerdict], machine: Option<&str>, near: Near) -> bool { + let next = offers.iter().find(|v| Some(v.machine_id.as_str()) == machine) + .or_else(|| (near == Near::First).then(|| offers.first()).flatten()); + if next == self.held.as_ref().map(|(v, _)| v) { return false; } + self.held = next.map(|v| (v.clone(), reason(v))); + true } /// The offer the read-out speaks about. @@ -500,3 +490,22 @@ mod tests { assert!(out.is_empty(), "answers wider than their pill:\n {}", out.join("\n ")); } } + +#[cfg(test)] +mod retained_input_tests { + use super::*; + #[test] + fn retained_offers_expire_without_a_roster_change() { + let offer = PlaintextVerdict { machine_id: "server".into(), name: "Server".into(), + shared_by: String::new(), eligibility: plx_plex::plex::probe::PlaintextEligibility::Eligible, + choice: PlaintextChoice::Undecided }; + let mut watch = OfferWatch::default(); + assert!(watch.refresh(std::slice::from_ref(&offer), Some("server"), Near::Only)); + assert!(!watch.refresh(std::slice::from_ref(&offer), Some("server"), Near::Only)); + assert!(asks(watch.verdict())); + assert!(watch.refresh(&[], Some("server"), Near::Only)); + assert!(watch.verdict().is_none()); + assert!(watch.reason().is_none()); + assert!(!watch.refresh(&[], Some("server"), Near::Only)); + } +} diff --git a/rust-modules/screens/src/preferences.rs b/rust-modules/screens/src/preferences.rs index 5f845190c7..8b8f498b71 100644 --- a/rust-modules/screens/src/preferences.rs +++ b/rust-modules/screens/src/preferences.rs @@ -139,10 +139,10 @@ impl Whose { /// the chip's own session accessors; `account_menu::chip_label` is that rule, but a screen never /// names a sibling. A seat implies a signed-in account, so the chip's signed-out arm (the Sign /// in label) cannot be this page's. Returns the publication generation it read, to notice a change. - fn now() -> (u32, Self) { - let profile = plx_plex::plex::session::current_snapshot(); + fn now(inputs: &crate::registry::ScreenInputs) -> (u32, Self) { + let profile = &inputs.profile; if profile.seat() == plx_plex::plex::session::Seat::Unseated { return (profile.generation, Self::Nobody); } - let account = plx_plex::plex::session::peek().account(profile.user.as_ref()); + let account = inputs.session.account(profile.user.as_ref()); let name = account.name.unwrap_or_else(|| plx_platform::i18n::msg::settings_account_title().to_string()); (profile.generation, Self::Profile(name)) } @@ -212,14 +212,16 @@ struct Txn { enum Landed { Nothing, Changed, Saved } impl Txn { - fn new(adopt_existing: bool) -> Self { + fn new(adopt_existing: bool, profile: &plx_plex::plex::session::CurrentProfile) -> Self { let mut txn = Self { request: None, snapshot: None, pending: None, retry: None, saving: false, seen: if adopt_existing { 0 } else { CONFIRMED.with(|c| c.borrow().0) } }; - txn.adopt_shared(); + txn.adopt_shared(profile); txn } fn prefs(&self) -> Option<&AudioPreferences> { self.snapshot.as_ref().map(|s| &s.preferences) } - fn stale(&self) -> bool { self.request.as_ref().is_some_and(|r| !r.is_current()) } + fn stale(&self, profile: &plx_plex::plex::session::CurrentProfile) -> bool { + self.request.as_ref().is_some_and(|r| !r.matches_profile(profile)) + } /// Publish the confirmed snapshot for the other page of the pair. fn publish(&mut self) { let (Some(request), Some(snapshot)) = (self.request.clone(), self.snapshot.clone()) else { return; }; @@ -231,7 +233,7 @@ impl Txn { }); } /// Take a newer published snapshot, unless a load/save of our own is in flight. True when taken. - fn adopt_shared(&mut self) -> bool { + fn adopt_shared(&mut self, profile: &plx_plex::plex::session::CurrentProfile) -> bool { if self.pending.is_some() { return false; } let taken = CONFIRMED.with(|c| { let c = c.borrow(); @@ -240,7 +242,7 @@ impl Txn { let Some((generation, shared)) = taken else { return false; }; self.seen = generation; match shared { - Some((request, snapshot)) if request.is_current() => { + Some((request, snapshot)) if request.matches_profile(profile) => { self.request = Some(request); self.snapshot = Some(snapshot); self.retry = None; true } _ => false, @@ -298,7 +300,7 @@ impl Txn { self.snapshot = None; self.pending = None; io.busy = false; self.load(io, fx); } - fn poll(&mut self, io: &mut Io, fx: &mut Effects<'_, InnerHost>) -> Landed { + fn poll(&mut self, io: &mut Io, fx: &mut Effects<'_, InnerHost>, profile: &plx_plex::plex::session::CurrentProfile) -> Landed { enum Receipt { Account(AccountPreferenceReply), Local(bool), Failed } let receipt = match &self.pending { Some(Pending::Account(rx)) => match rx.try_recv() { @@ -317,7 +319,7 @@ impl Txn { let mut landed = Landed::Changed; match receipt { Receipt::Account(reply) => { - if reply.request.as_ref().is_some_and(|request| !request.is_current()) { + if reply.request.as_ref().is_some_and(|request| !request.matches_profile(profile)) { self.snapshot = None; self.load(io, fx); } else if let Some(request) = reply.request { self.request = Some(request); @@ -398,6 +400,7 @@ impl LogicalState for State { } pub struct PreferencesPage { + inputs: crate::registry::ScreenInputs, marker_prefs: MarkerPrefsView, entry: EntryId, form: FormTable, @@ -425,16 +428,16 @@ pub struct PreferencesPage { whose: (u32, Whose), } impl PreferencesPage { - pub fn new(entry: EntryId, kind: Kind) -> Self { - let mut s = Self { marker_prefs: Default::default(), entry, form: FormTable::new(BAND), + pub fn new(entry: EntryId, kind: Kind, inputs: &crate::registry::ScreenInputs) -> Self { + let mut s = Self { inputs: inputs.clone(), marker_prefs: Default::default(), entry, form: FormTable::new(BAND), state: State { marker_prefs: Default::default(), kind, selected: 0, io: Io { busy: false, status: String::new() }, quality: plx_media::route::quality(), direct_play: plx_media::route::direct_play_mode(), values: Vec::new() }, - copy: String::new(), follow: plx_ui::follow_copy::FollowCopy::new(""), txn: Txn::new(false), + copy: String::new(), follow: plx_ui::follow_copy::FollowCopy::new(""), txn: Txn::new(false, &inputs.profile), look: (plx_media::route::subtitle_size(), plx_media::route::subtitle_position(), plx_media::player::subtitle_tone(), plx_media::route::hdr_overlay_brightness()), next_episode: plx_media::route::next_episode_mode(), deck_press: plx_media::route::deck_press(), skip_interval: plx_media::route::skip_interval(), instant_dpad_seeking: plx_media::route::instant_dpad_seeking(), uri_engine: plx_media::route::uri_engine(), - dolby_vision: plx_media::route::dolby_vision_mode(), whose: Whose::now() }; + dolby_vision: plx_media::route::dolby_vision_mode(), whose: Whose::now(inputs) }; s.rebuild(None); // A page opens on its first row's sentence at once, with nothing fading. s.follow = plx_ui::follow_copy::FollowCopy::new(&s.sentence()); @@ -472,7 +475,7 @@ impl PreferencesPage { self.instant_dpad_seeking = plx_media::route::instant_dpad_seeking(); self.uri_engine = plx_media::route::uri_engine(); self.dolby_vision = plx_media::route::dolby_vision_mode(); - self.whose = Whose::now(); + self.whose = Whose::now(&self.inputs); self.copy = copy_text(Subject::Page(self.state.kind), &self.state.io.status, self.state.direct_play, &self.whose.1).into_owned(); let inputs = FieldListInputs { kind: self.state.kind, quality: self.state.quality, direct_play: self.state.direct_play, @@ -584,7 +587,7 @@ fn resolve_value(field: PickerKind, quality: Quality, direct_play: DirectPlayMod PickerKind::InstantDpadSeeking => Value::InstantDpadSeeking(plx_media::route::instant_dpad_seeking()), PickerKind::UriEngine => Value::UriEngine(plx_media::route::uri_engine()), PickerKind::DolbyVision => Value::DolbyVision(plx_media::route::dolby_vision_mode()), - PickerKind::UiResolution => Value::UiResolution(plx_plex::plex::session::peek().ui_resolution()), + PickerKind::UiResolution => unreachable!("resolution requires the retained inputs"), // A deprecated code (`pb`) resolves to its replacement so the picker checks that entry. PickerKind::AudioLanguage => Value::Language(prefs.and_then(|p| p.stated_language.as_deref()).map(plx_plex::plex::languages::canonical).unwrap_or_default().to_string()), PickerKind::SubtitleLanguage => Value::Language(prefs.and_then(|p| p.subtitle_language.as_deref()).map(plx_plex::plex::languages::canonical).unwrap_or_default().to_string()), @@ -787,6 +790,14 @@ fn forced_readout(value: i64) -> &'static str { impl Machine for PreferencesPage { type Ev = ScreenEvent; fn step(&mut self, ev: &Self::Ev, cx: &Cx<'_, InnerHost>, fx: &mut Effects<'_, InnerHost>) -> Handled { + let inputs_changed = self.inputs.session_key() != cx.views.inputs.session_key() + || !std::sync::Arc::ptr_eq(&self.inputs.session, &cx.views.inputs.session) + || !std::sync::Arc::ptr_eq(&self.inputs.profile, &cx.views.inputs.profile); + self.inputs = cx.views.inputs.clone(); + if inputs_changed { + self.rebuild_keeping(); + fx.invalidate(plx_machine::present::Provenance::Landing(MachineId::Session)); + } let marker_prefs = cx.views.marker_prefs; if marker_prefs != self.marker_prefs { self.marker_prefs = marker_prefs; @@ -799,7 +810,7 @@ impl Machine for PreferencesPage { match ev { ScreenEvent::Enter(_) => { // A return from a picker: its save may have confirmed a new snapshot. - let adopted = self.txn.adopt_shared(); + let adopted = self.txn.adopt_shared(&self.inputs.profile); if self.start_initial_load(fx) || adopted { self.rebuild_keeping(); fx.invalidate(plx_machine::present::Provenance::Input); } @@ -807,11 +818,11 @@ impl Machine for PreferencesPage { } ScreenEvent::Tick(t) => { let started = self.start_initial_load(fx); - let stale = self.txn.stale(); + let stale = self.txn.stale(&self.inputs.profile); if stale { self.txn.recover_stale(&mut self.state.io, fx); } - let adopted = self.txn.adopt_shared(); + let adopted = self.txn.adopt_shared(&self.inputs.profile); let had_rows = self.form.table.n_rows() > 0; - let landed = self.txn.poll(&mut self.state.io, fx) != Landed::Nothing; + let landed = self.txn.poll(&mut self.state.io, fx, &self.inputs.profile) != Landed::Nothing; if landed || stale || started || adopted || self.state.quality != plx_media::route::quality() || self.state.direct_play != plx_media::route::direct_play_mode() || self.look != (plx_media::route::subtitle_size(), plx_media::route::subtitle_position(), plx_media::player::subtitle_tone(), plx_media::route::hdr_overlay_brightness()) @@ -821,7 +832,7 @@ impl Machine for PreferencesPage { || self.instant_dpad_seeking != plx_media::route::instant_dpad_seeking() || self.uri_engine != plx_media::route::uri_engine() || self.dolby_vision != plx_media::route::dolby_vision_mode() - || self.whose.0 != plx_plex::plex::session::current_gen() { + { self.rebuild_keeping(); // An empty loading table had no engine seat. Give its first landing (or // Retry row) one so OK works immediately, without moving an existing @@ -908,10 +919,11 @@ fn marker_label(mode: MarkerSkipMode) -> &'static str { } } fn resolve_with_marker(field: PickerKind, quality: Quality, direct_play: DirectPlayMode, - prefs: Option<&AudioPreferences>, marker: MarkerPrefsView) -> Value { + prefs: Option<&AudioPreferences>, marker: MarkerPrefsView, resolution: UiResolution) -> Value { match field { PickerKind::IntroSkip => Value::IntroSkip(marker.intro, marker.scope), PickerKind::CreditsSkip => Value::CreditsSkip(marker.credits, marker.scope), + PickerKind::UiResolution => Value::UiResolution(resolution), _ => resolve_value(field, quality, direct_play, prefs), } } diff --git a/rust-modules/screens/src/preferences/picker.rs b/rust-modules/screens/src/preferences/picker.rs index 961d228afa..1414696508 100644 --- a/rust-modules/screens/src/preferences/picker.rs +++ b/rust-modules/screens/src/preferences/picker.rs @@ -54,6 +54,7 @@ impl LogicalState for PickerState { pub const SHAPE: &str = "PickerV3{field:u8,selection:u32,busy:bool,status:str,quality:u8,direct_play:u8,checked:u32,confirm:bool,affirm:bool,alert_scroll:u32,shown_marker_scope:u64,marker:{scope:u64,needs_refresh:bool,intro_grant:bool,credits_grant:bool,intro:u8,credits:u8}}"; pub struct PickerPage { + inputs: crate::registry::ScreenInputs, marker_prefs: MarkerPrefsView, entry: EntryId, form: FormTable, @@ -77,18 +78,18 @@ fn option_form(options: Vec<(String, Value)>, current: &Value, busy: bool, retry } impl PickerPage { - pub fn new(entry: EntryId, field: PickerKind) -> Self { - let mut s = Self { marker_prefs: Default::default(), entry, form: FormTable::new(BAND), + pub fn new(entry: EntryId, field: PickerKind, inputs: &crate::registry::ScreenInputs) -> Self { + let mut s = Self { inputs: inputs.clone(), marker_prefs: Default::default(), entry, form: FormTable::new(BAND), state: PickerState { shown_marker_scope: 0, marker_prefs: Default::default(), field, selected: 0, io: Io { busy: false, status: String::new() }, quality: plx_media::route::quality(), direct_play: plx_media::route::direct_play_mode(), checked: u32::MAX, confirming: false, affirmative: false, alert_scroll: 0 }, - copy: String::new(), txn: Txn::new(true), + copy: String::new(), txn: Txn::new(true, &inputs.profile), alert: DecisionPrompt::new(ALERT_GROUP, ALERT, ALERT + 1, plx_platform::i18n::msg::settings_cancel_c(), plx_platform::i18n::msg::settings_playback_enable_force_c()) }; s.rebuild(true); s } fn current(&self) -> Value { - resolve_with_marker(self.state.field, self.state.quality, self.state.direct_play, self.txn.prefs(), self.marker_prefs) + resolve_with_marker(self.state.field, self.state.quality, self.state.direct_play, self.txn.prefs(), self.marker_prefs, self.inputs.session.ui_resolution()) } /// Whether the STORED setting already is `value`, for the profile seated now. Only Size and /// Position can differ from [`Self::current`]: they publish the live value before the write @@ -97,15 +98,14 @@ impl PickerPage { /// falls back to; reading the legacy key alone would call a profile's own pick "not saved" and /// write it again on every OK. fn durable(&self, value: &Value) -> bool { - use plx_plex::plex::session::{current_seat, peek, stored_effective, SubtitlePositionPref, SubtitleSizePref, SubtitleTonePref, HdrOverlayBrightnessPref}; - // One read of the session mirror and the seat, shared by every arm (and only taken for a value - // that has a stored form). - let stored = |pick: &dyn Fn(&plx_plex::plex::session::Session, &plx_plex::plex::session::Seat) -> bool| pick(&peek(), ¤t_seat()); + use plx_plex::plex::session::{stored_effective, SubtitlePositionPref, SubtitleSizePref, SubtitleTonePref, HdrOverlayBrightnessPref}; + let seat = self.inputs.profile.seat(); + let session = &self.inputs.session; match value { - Value::SubtitleSize(v) => stored(&|s, seat| stored_effective::(s, seat) == *v), - Value::SubtitlePosition(v) => stored(&|s, seat| stored_effective::(s, seat) == *v), - Value::SubtitleTone(v) => stored(&|s, seat| stored_effective::(s, seat) == *v), - Value::HdrOverlay(v) => stored(&|s, seat| stored_effective::(s, seat) == *v), + Value::SubtitleSize(v) => stored_effective::(session, &seat) == *v, + Value::SubtitlePosition(v) => stored_effective::(session, &seat) == *v, + Value::SubtitleTone(v) => stored_effective::(session, &seat) == *v, + Value::HdrOverlay(v) => stored_effective::(session, &seat) == *v, _ => true, } } @@ -219,6 +219,13 @@ impl PickerPage { impl Machine for PickerPage { type Ev = ScreenEvent; fn step(&mut self, ev: &Self::Ev, cx: &Cx<'_, InnerHost>, fx: &mut Effects<'_, InnerHost>) -> Handled { + let inputs_changed = self.inputs.session_key() != cx.views.inputs.session_key() + || !std::sync::Arc::ptr_eq(&self.inputs.session, &cx.views.inputs.session); + self.inputs = cx.views.inputs.clone(); + if inputs_changed { + self.rebuild(false); + fx.invalidate(plx_machine::present::Provenance::Landing(MachineId::Session)); + } if cx.views.marker_prefs != self.marker_prefs { self.marker_prefs = cx.views.marker_prefs; self.rebuild(false); @@ -252,7 +259,7 @@ impl Machine for PickerPage { ScreenEvent::Tick(t) => { self.alert.update(t.dt()); let started = self.start_initial_load(fx); - if self.txn.stale() { + if self.txn.stale(&self.inputs.profile) { // The profile changed under the list: nothing here can be saved any more. Leave; // the field list beneath sees the same staleness and reloads. self.txn.snapshot = None; self.txn.pending = None; self.state.io.busy = false; @@ -260,7 +267,7 @@ impl Machine for PickerPage { return Handled::Yes; } let had_rows = self.form.table.n_rows() > 0; - let landed = self.txn.poll(&mut self.state.io, fx); + let landed = self.txn.poll(&mut self.state.io, fx, &self.inputs.profile); match landed { Landed::Saved => { self.pop(fx); } Landed::Changed => { diff --git a/rust-modules/screens/src/preferences/picker_tests.rs b/rust-modules/screens/src/preferences/picker_tests.rs index 9e68d98fe4..4c69c4e030 100644 --- a/rust-modules/screens/src/preferences/picker_tests.rs +++ b/rust-modules/screens/src/preferences/picker_tests.rs @@ -17,7 +17,7 @@ fn key_of(page: &PickerPage, value: &Value) -> u32 { } fn audio_picker(account: &Account, field: PickerKind) -> PickerPage { let _parent = super::super::tests::loaded_audio_page(account); - PickerPage::new(EntryId(0), field) + PickerPage::new(EntryId(0), field, &crate::registry::capture_fixture()) } #[test] @@ -26,7 +26,7 @@ fn a_picker_opens_on_the_checked_option_with_position_keys() { let _session = plx_plex::plex::session::TempSession::new("picker-opens-checked"); let previous = plx_media::route::quality(); plx_media::route::restore_quality(Quality::P480); - let page = PickerPage::new(EntryId(0), PickerKind::Quality); + let page = PickerPage::new(EntryId(0), PickerKind::Quality, &crate::registry::capture_fixture()); let ladder = plx_media::route::available_quality_ladder(); let at = ladder.iter().position(|q| *q == Quality::P480).unwrap(); assert_eq!(page.state.selected, at as u32, "the cursor starts on the checked option"); @@ -41,7 +41,7 @@ fn choosing_the_checked_value_pops_without_a_write() { let _session = plx_plex::plex::session::TempSession::new("picker-checked-noop"); let previous = plx_media::route::quality(); plx_media::route::restore_quality(Quality::P480); - let mut page = PickerPage::new(EntryId(0), PickerKind::Quality); + let mut page = PickerPage::new(EntryId(0), PickerKind::Quality, &crate::registry::capture_fixture()); let key = page.state.selected; let emitted = drive(&mut page, ScreenEvent::Activate(key), key); assert!(popped(&emitted)); @@ -99,7 +99,7 @@ fn a_local_write_pops_on_its_receipt_and_a_refusal_keeps_the_page() { let previous = plx_media::route::quality(); plx_media::route::restore_quality(Quality::Original); for ok in [true, false] { - let mut page = PickerPage::new(EntryId(0), PickerKind::Quality); + let mut page = PickerPage::new(EntryId(0), PickerKind::Quality, &crate::registry::capture_fixture()); let other = plx_media::route::available_quality_ladder().iter().position(|q| *q != Quality::Original).unwrap() as u32; let emitted = drive(&mut page, ScreenEvent::Activate(other), other); let Some(Fx::App(AppFx::Preferences(PreferenceCmd::Choose(plx_media::route::Choice::Quality(_), reply)))) = emitted.into_iter().map(|e| e.fx) @@ -117,7 +117,7 @@ fn force_requires_acknowledgement_and_cancel_never_saves() { let _serial = plx_base::testlock::serial(); let _session = plx_plex::plex::session::TempSession::new("force-confirm-cancel"); plx_media::route::restore_direct_play_mode(DirectPlayMode::Auto); - let mut page = PickerPage::new(EntryId(0), PickerKind::DirectPlay); + let mut page = PickerPage::new(EntryId(0), PickerKind::DirectPlay, &crate::registry::capture_fixture()); let forced = key_of(&page, &Value::DirectPlay(DirectPlayMode::Forced)); let emitted = drive(&mut page, ScreenEvent::Activate(forced), forced); assert!(page.alert.is_open()); @@ -140,7 +140,7 @@ fn confirming_force_emits_a_preference_effect_without_executing_it() { let _session = plx_plex::plex::session::TempSession::new("force-confirm-yes"); let previous = plx_media::route::direct_play_mode(); plx_media::route::restore_direct_play_mode(DirectPlayMode::Auto); - let mut page = PickerPage::new(EntryId(0), PickerKind::DirectPlay); + let mut page = PickerPage::new(EntryId(0), PickerKind::DirectPlay, &crate::registry::capture_fixture()); let forced = key_of(&page, &Value::DirectPlay(DirectPlayMode::Forced)); drive(&mut page, ScreenEvent::Activate(forced), forced); let emitted = drive(&mut page, ScreenEvent::PressCommit(plx_machine::machine::PressId(1)), ALERT + 1); @@ -160,7 +160,7 @@ fn a_stale_request_leaves_the_picker_without_a_write_and_the_list_reloads() { let _session = plx_plex::plex::session::TempSession::new("picker-stale"); let account = Account::new("picker-stale", 23, AudioPreferences::default()); let mut parent = super::super::tests::loaded_audio_page(&account); - let mut page = PickerPage::new(EntryId(0), PickerKind::ForcedSubtitles); + let mut page = PickerPage::new(EntryId(0), PickerKind::ForcedSubtitles, &crate::registry::capture_fixture()); assert!(page.txn.snapshot.is_some(), "the picker starts from its parent's confirmed snapshot"); account.go_stale(); let emitted = drive(&mut page, tick(), 0); @@ -198,13 +198,13 @@ fn the_subtitle_pickers_write_locally_and_pop_on_the_receipt() { let tone = plx_media::player::subtitle_tone(); plx_media::player::restore_subtitle_tone(plx_plex::plex::session::SubtitleTone::White); for field in [PickerKind::SubtitleSize, PickerKind::SubtitlePosition, PickerKind::SubtitleColor] { - let mut page = PickerPage::new(EntryId(0), field); + let mut page = PickerPage::new(EntryId(0), field, &crate::registry::capture_fixture()); let checked = page.state.checked; let emitted = drive(&mut page, ScreenEvent::Activate(checked), checked); assert!(popped(&emitted), "{field:?}: the checked value pops"); assert_eq!(preference_commands(&emitted), 0, "{field:?}: and writes nothing"); - let mut page = PickerPage::new(EntryId(0), field); + let mut page = PickerPage::new(EntryId(0), field, &crate::registry::capture_fixture()); let other = if checked == 0 { 1 } else { 0 }; let emitted = drive(&mut page, ScreenEvent::Activate(other), other); assert!(!popped(&emitted), "{field:?}: a write waits for its receipt"); @@ -231,7 +231,7 @@ fn the_color_picker_checks_the_live_tone_and_chooses_yellow() { let _session = plx_plex::plex::session::TempSession::new("picker-color-yellow"); let tone = plx_media::player::subtitle_tone(); plx_media::player::restore_subtitle_tone(SubtitleTone::White); - let mut page = PickerPage::new(EntryId(0), PickerKind::SubtitleColor); + let mut page = PickerPage::new(EntryId(0), PickerKind::SubtitleColor, &crate::registry::capture_fixture()); assert_eq!(page.state.checked, SubtitleTone::White.index() as u32, "white is checked by default"); let yellow = SubtitleTone::Yellow.index() as u32; let emitted = drive(&mut page, ScreenEvent::Activate(yellow), yellow); @@ -254,7 +254,7 @@ fn the_size_picker_moves_its_checkmark_when_the_live_value_is_published() { let _session = plx_plex::plex::session::TempSession::new("picker-optimistic-check"); let (size, position) = (plx_media::route::subtitle_size(), plx_media::route::subtitle_position()); plx_media::route::restore_subtitle_size(plx_media::route::SubtitleSize::Medium); - let mut page = PickerPage::new(EntryId(0), PickerKind::SubtitleSize); + let mut page = PickerPage::new(EntryId(0), PickerKind::SubtitleSize, &crate::registry::capture_fixture()); let before = page.state.checked; plx_media::route::restore_subtitle_size(plx_media::route::SubtitleSize::Large); drive(&mut page, tick(), before); @@ -271,7 +271,7 @@ fn ok_on_the_checked_size_after_a_failed_write_retries_the_write() { let _session = plx_plex::plex::session::TempSession::new("picker-size-retry"); let (size, position) = (plx_media::route::subtitle_size(), plx_media::route::subtitle_position()); plx_media::route::restore_subtitle_size(plx_media::route::SubtitleSize::Medium); - let mut page = PickerPage::new(EntryId(0), PickerKind::SubtitleSize); + let mut page = PickerPage::new(EntryId(0), PickerKind::SubtitleSize, &crate::registry::capture_fixture()); let other = if page.state.checked == 0 { 1 } else { 0 }; let emitted = drive(&mut page, ScreenEvent::Activate(other), other); let reply = emitted.into_iter().find_map(|e| match e.fx { @@ -312,7 +312,7 @@ fn ok_on_checked_profile_size_pops() { "the legacy key says Medium"); plx_media::route::restore_subtitle_size(plx_media::route::SubtitleSize::Large); - let mut page = PickerPage::new(EntryId(0), PickerKind::SubtitleSize); + let mut page = PickerPage::new(EntryId(0), PickerKind::SubtitleSize, &crate::registry::capture_fixture()); let checked = page.state.checked; let emitted = drive(&mut page, ScreenEvent::Activate(checked), checked); assert!(popped(&emitted), "the profile's own Large is stored: OK on it pops"); @@ -330,7 +330,7 @@ fn the_local_subtitle_pickers_never_touch_the_plex_account() { let _serial = plx_base::testlock::serial(); let _session = plx_plex::plex::session::TempSession::new("pref-local-subtitle-pickers"); for field in [PickerKind::SubtitleSize, PickerKind::SubtitlePosition, PickerKind::SubtitleColor] { - let mut page = PickerPage::new(EntryId(0), field); + let mut page = PickerPage::new(EntryId(0), field, &crate::registry::capture_fixture()); let mut emitted = drive(&mut page, ScreenEvent::Enter(Enter::Fresh { focus: FocusTarget::ContainerGroup(GroupId(0)) }), 0); emitted.extend(drive(&mut page, tick(), 0)); assert_eq!(preference_commands(&emitted), 0, "{field:?}: no account load"); @@ -364,7 +364,7 @@ fn the_interface_resolution_picker_writes_install_wide_and_reverts_on_a_refused_ ("960x540".to_string(), Value::UiResolution(UiResolution::Sd540)), ]); - let mut page = PickerPage::new(EntryId(0), PickerKind::UiResolution); + let mut page = PickerPage::new(EntryId(0), PickerKind::UiResolution, &crate::registry::capture_fixture()); assert_eq!(page.state.checked, 0, "opens on the stored choice, Automatic"); let emitted = drive(&mut page, ScreenEvent::Enter(Enter::Fresh { focus: FocusTarget::ContainerGroup(GroupId(0)) }), 0); assert_eq!(preference_commands(&emitted), 0, "no Plex account load"); @@ -372,7 +372,7 @@ fn the_interface_resolution_picker_writes_install_wide_and_reverts_on_a_refused_ assert!(popped(&emitted) && preference_commands(&emitted) == 0, "OK on the checked row writes nothing"); for ok in [false, true] { - let mut page = PickerPage::new(EntryId(0), PickerKind::UiResolution); + let mut page = PickerPage::new(EntryId(0), PickerKind::UiResolution, &crate::registry::capture_fixture()); let other = key_of(&page, &Value::UiResolution(UiResolution::Hd720)); let emitted = drive(&mut page, ScreenEvent::Activate(other), other); assert!(!popped(&emitted), "a write waits for its receipt"); @@ -391,3 +391,25 @@ fn the_interface_resolution_picker_writes_install_wide_and_reverts_on_a_refused_ } } } + +#[test] +fn retained_resolution_and_durable_profile_values_ignore_ambient_replacement() { + use plx_plex::plex::session::{put_own, SubtitleSizePref}; + let _serial = plx_base::testlock::serial(); + let session = plx_plex::plex::session::TempSession::new("retained-picker-values"); + let stamp = session.seated("kid", "retained-account"); + assert!(plx_plex::plex::session::update(|cur| { + let mut next = cur.clone(); + put_own::(&mut next.prefs.profile_prefs, "kid", &stamp, SubtitleSize::Large); + Some(next) + })); + let inputs = crate::registry::capture_fixture(); + let page = PickerPage::new(EntryId(0), PickerKind::SubtitleSize, &inputs); + session.seated("other", "retained-account"); + assert!(page.durable(&Value::SubtitleSize(SubtitleSize::Large))); + assert!(!page.durable(&Value::SubtitleSize(SubtitleSize::Medium))); + let mut injected = inputs; + injected.session = std::sync::Arc::new(injected.session.with_ui_resolution(UiResolution::Hd720)); + let page = PickerPage::new(EntryId(0), PickerKind::UiResolution, &injected); + assert_eq!(page.current(), Value::UiResolution(UiResolution::Hd720)); +} diff --git a/rust-modules/screens/src/preferences_tests.rs b/rust-modules/screens/src/preferences_tests.rs index 250c41e075..fb94cf39ba 100644 --- a/rust-modules/screens/src/preferences_tests.rs +++ b/rust-modules/screens/src/preferences_tests.rs @@ -6,9 +6,9 @@ use plx_machine::machine::{FocusRead, InputOwner, PressRead, Stamped, Tick}; use plx_machine::present::Present; use plx_ui::fixture::FixtureMeasure; -pub fn context(focus: u32) -> Cx<'static, InnerHost> { +pub fn context<'a>(focus: u32) -> Cx<'a, InnerHost> { static MEASURE: FixtureMeasure = FixtureMeasure; - Cx { views: plx_data::stores::browse::DirectoryView::empty_for_test().into(), tick: Tick::default(), + Cx { views: crate::registry::InnerViews::new(plx_data::stores::browse::DirectoryView::empty_for_test(), crate::registry::publication_fixture()), tick: Tick::default(), measure: &MEASURE, press: PressRead::default(), focus: FocusRead { current: Some(FocusKey { entry: EntryId(0), elem: focus }), ..Default::default() }, owner: InputOwner::Entry(EntryId(0)) } @@ -64,7 +64,7 @@ impl Drop for Account { } /// An Audio & Subtitles field list that has loaded `account`'s snapshot (and published it). pub fn loaded_audio_page(account: &Account) -> PreferencesPage { - let mut page = PreferencesPage::new(EntryId(0), Kind::AudioSubtitles); + let mut page = PreferencesPage::new(EntryId(0), Kind::AudioSubtitles, &crate::registry::capture_fixture()); page.txn.request = Some(account.request.clone()); page.txn.snapshot = Some(account.snapshot.clone()); page.txn.publish(); @@ -75,7 +75,7 @@ pub fn loaded_audio_page(account: &Account) -> PreferencesPage { #[test] fn account_constructor_is_inert_and_first_enter_emits_one_load_effect() { let _serial = plx_base::testlock::serial(); - let mut page = PreferencesPage::new(EntryId(0), Kind::AudioSubtitles); + let mut page = PreferencesPage::new(EntryId(0), Kind::AudioSubtitles, &crate::registry::capture_fixture()); assert!(page.txn.pending.is_none()); assert!(page.txn.request.is_none()); assert!(page.state.io.status.is_empty()); @@ -106,7 +106,7 @@ fn every_field_row_pushes_its_picker_and_nothing_else() { let account = Account::new("pref-field-rows", 11, AudioPreferences::default()); // The Playback rows open only for a seated profile (an unseated page lists them read-only). seat_named(&session, "pref-field-rows", "Maya"); - let mut playback = PreferencesPage::new(EntryId(0), Kind::Playback); + let mut playback = PreferencesPage::new(EntryId(0), Kind::Playback, &crate::registry::capture_fixture()); let mut audio = loaded_audio_page(&account); for (page, fields) in [ (&mut playback, vec![PickerKind::Quality, PickerKind::DirectPlay, PickerKind::HdrOverlay, PickerKind::NextEpisode, PickerKind::DeckPress, PickerKind::SkipInterval, PickerKind::InstantDpadSeeking, PickerKind::DolbyVision, PickerKind::UriEngine]), @@ -131,7 +131,7 @@ fn the_field_list_shows_the_value_a_picker_committed_after_the_pop() { let mut parent = loaded_audio_page(&account); let mode_row = parent.form.index_of(&RowId::Field(PickerKind::SubtitleMode)).unwrap(); assert_eq!(parent.state.values[mode_row], plx_platform::i18n::msg::settings_audio_manual()); - let mut picker = PickerPage::new(EntryId(0), PickerKind::SubtitleMode); + let mut picker = PickerPage::new(EntryId(0), PickerKind::SubtitleMode, &crate::registry::capture_fixture()); let emitted = drive(&mut picker, ScreenEvent::Activate(2), 2); let Some(Fx::App(AppFx::Preferences(PreferenceCmd::Save { reply, .. }))) = emitted.into_iter().map(|e| e.fx).find(|f| matches!(f, Fx::App(AppFx::Preferences(_)))) else { panic!("choosing Always must save"); @@ -151,7 +151,7 @@ fn the_field_list_rereads_a_local_value_a_picker_committed() { let _session = plx_plex::plex::session::TempSession::new("pref-parent-local"); let previous = plx_media::route::quality(); plx_media::route::restore_quality(Quality::Original); - let mut parent = PreferencesPage::new(EntryId(0), Kind::Playback); + let mut parent = PreferencesPage::new(EntryId(0), Kind::Playback, &crate::registry::capture_fixture()); let before = parent.state.values[0].clone(); plx_media::route::restore_quality(Quality::P480); drive(&mut parent, tick(), 0); @@ -244,7 +244,7 @@ fn the_continue_watching_row_defaults_to_open_details_and_its_picker_saves_the_p assert_eq!(options, [("Open details".to_string(), Value::DeckPress(DeckPress::Details)), ("Play".to_string(), Value::DeckPress(DeckPress::Play))]); - let mut picker = PickerPage::new(EntryId(0), PickerKind::DeckPress); + let mut picker = PickerPage::new(EntryId(0), PickerKind::DeckPress, &crate::registry::capture_fixture()); let emitted = drive(&mut picker, ScreenEvent::Activate(1), 1); plx_media::route::restore_deck_press(prior); let saved = emitted.into_iter().find_map(|e| match e.fx { @@ -277,7 +277,7 @@ fn the_playback_engine_row_defaults_to_standard_and_its_picker_saves_the_opt_in( assert_eq!(PickerKind::UriEngine.title(), "Playback engine"); assert_eq!(PickerKind::UriEngine.parent(), SettingsPage::Playback); - let mut picker = PickerPage::new(EntryId(0), PickerKind::UriEngine); + let mut picker = PickerPage::new(EntryId(0), PickerKind::UriEngine, &crate::registry::capture_fixture()); let emitted = drive(&mut picker, ScreenEvent::Activate(1), 1); plx_media::route::restore_uri_engine(prior); let saved = emitted.into_iter().find_map(|e| match e.fx { @@ -319,7 +319,7 @@ fn right_at_edge() -> ScreenEvent { fn playback_rows_are_read_only_while_no_profile_is_seated() { let _serial = plx_base::testlock::serial(); let _session = plx_plex::plex::session::TempSession::new("pref-read-only-unseated"); - let mut page = PreferencesPage::new(EntryId(0), Kind::Playback); + let mut page = PreferencesPage::new(EntryId(0), Kind::Playback, &crate::registry::capture_fixture()); assert_eq!(page.copy, plx_platform::i18n::msg::settings_playback_unseated(), "the page says to choose a profile"); for field in [PickerKind::Quality, PickerKind::DirectPlay, PickerKind::HdrOverlay, PickerKind::NextEpisode, PickerKind::DeckPress, PickerKind::SkipInterval, PickerKind::InstantDpadSeeking, PickerKind::DolbyVision, PickerKind::UriEngine] { @@ -355,7 +355,7 @@ fn playback_rows_are_read_only_while_no_profile_is_seated() { fn the_player_hud_row_is_read_only_while_no_profile_is_seated() { let _serial = plx_base::testlock::serial(); let session = plx_plex::plex::session::TempSession::new("pref-hud-row-unseated"); - let mut page = PreferencesPage::new(EntryId(0), Kind::Playback); + let mut page = PreferencesPage::new(EntryId(0), Kind::Playback, &crate::registry::capture_fixture()); let key = RowId::PlayerHud.key().0; let row = page.form.index_of(&RowId::PlayerHud).expect("the Player HUD row is listed while unseated"); assert!(disabled_rows(&page)[row], "disabled"); @@ -378,7 +378,7 @@ fn the_player_hud_row_is_read_only_while_no_profile_is_seated() { fn the_playback_page_names_the_seated_profile_and_follows_the_seat() { let _serial = plx_base::testlock::serial(); let session = plx_plex::plex::session::TempSession::new("pref-names-the-profile"); - let mut page = PreferencesPage::new(EntryId(0), Kind::Playback); + let mut page = PreferencesPage::new(EntryId(0), Kind::Playback, &crate::registry::capture_fixture()); assert_eq!(page.copy, plx_platform::i18n::msg::settings_playback_unseated()); seat_named(&session, "maya", "Maya"); @@ -569,3 +569,23 @@ fn every_field_list_row_states_its_own_sentence() { assert_eq!(sentence(Kind::Playback, Some(&RowId::Field(PickerKind::DirectPlay)), false, true, &seated), PickerKind::DirectPlay.copy(), "Force changes only the Default quality row's meaning"); } + +#[test] +fn retained_profile_identity_does_not_follow_an_ambient_seat_change() { + let _serial = plx_base::testlock::serial(); + let session = plx_plex::plex::session::TempSession::new("retained-profile-name"); + seat_named(&session, "maya", "Maya"); + let inputs = crate::registry::capture_fixture(); + let mut page = PreferencesPage::new(EntryId(0), Kind::Playback, &inputs); + seat_named(&session, "noah", "Noah"); + let mut cx = context(0); + cx.views.inputs = &inputs; + let mut out = Vec::new(); + let mut present = Present::new(); + page.step(&tick(), &cx, &mut Effects::new(&mut out, MachineId::Instance(InstanceId(0)), &mut present)); + assert_eq!(page.copy, plx_platform::i18n::msg::settings_playback_copy_profile("Maya")); + let current = crate::registry::capture_fixture(); + cx.views.inputs = ¤t; + page.step(&tick(), &cx, &mut Effects::new(&mut out, MachineId::Instance(InstanceId(0)), &mut present)); + assert_eq!(page.copy, plx_platform::i18n::msg::settings_playback_copy_profile("Noah")); +} diff --git a/rust-modules/screens/src/preferences_text_fit_tests.rs b/rust-modules/screens/src/preferences_text_fit_tests.rs index a0ad1615e7..cf71eb1c63 100644 --- a/rust-modules/screens/src/preferences_text_fit_tests.rs +++ b/rust-modules/screens/src/preferences_text_fit_tests.rs @@ -157,7 +157,7 @@ fn every_picker_level_fits_its_column_in_every_language() { let fields: Vec = fields.iter().copied() .chain((kind == Kind::Playback).then_some(PickerKind::UiResolution)).collect(); for field in fields { - let current = resolve_with_marker(field, Quality::Original, DirectPlayMode::Auto, Some(&prefs), marker_grants()); + let current = resolve_with_marker(field, Quality::Original, DirectPlayMode::Auto, Some(&prefs), marker_grants(), UiResolution::default()); let section = options_with_marker(field, Quality::Original, DirectPlayMode::Auto, Some(&prefs), marker_grants()).into_iter() .fold(Section::new(""), |section, (label, value)| section.row(Row::new(&label).checked(value == current))); out.extend(table_of(section).app_fit_failures(frame_w(), &format!("{tag} {field:?} picker"))); diff --git a/rust-modules/screens/src/profiles.rs b/rust-modules/screens/src/profiles.rs index a8a00b0f1b..4808e0b597 100644 --- a/rust-modules/screens/src/profiles.rs +++ b/rust-modules/screens/src/profiles.rs @@ -796,9 +796,9 @@ impl ProfilesScreen { self.users.iter().position(|u| !self.seated.is_empty() && *u.uuid == *self.seated) } - fn avatar_art(u: &auth::UserTile) -> Art<'_> { + fn avatar_art(u: &auth::UserTile, sid: plx_plex::plex::ServerId) -> Art<'_> { Art::Thumb { - sid: plx_plex::plex::current_server().raw(), + sid: sid.raw(), key: &u.thumb, res: (300, 300), } @@ -1771,7 +1771,7 @@ impl Screen for ProfilesScreen { focused_i = Some(i); continue; // draw the focused tile last (ring over neighbours) } - let rect = self.row.draw(p, i, base, Self::avatar_art(u), false, f.measure); + let rect = self.row.draw(p, i, base, Self::avatar_art(u, H::screen_inputs(f.cx).current_server), false, f.measure); Self::draw_name(p, u, cx_, false, f.measure); f.stop( p, @@ -1799,7 +1799,7 @@ impl Screen for ProfilesScreen { ); Self::draw_name(p, u, cx_, true, f.measure); // the click dip folds into the focused avatar's pop (1.0 when idle) - let rect = self.row.draw(p, i, base, Self::avatar_art(u), true, f.measure); + let rect = self.row.draw(p, i, base, Self::avatar_art(u, H::screen_inputs(f.cx).current_server), true, f.measure); f.stop( p, Stop { @@ -1937,3 +1937,21 @@ mod pin_tests; #[cfg(test)] #[path = "profiles_pad_geometry_tests.rs"] mod pad_geometry_tests; + +#[cfg(test)] +mod retained_input_tests { + use super::*; + #[test] + fn avatars_use_the_supplied_server_even_without_a_client() { + let user = auth::UserTile { thumb: "avatar".into(), ..Default::default() }; + let server = plx_plex::plex::ServerId::from_raw(71); + match ProfilesScreen::avatar_art(&user, server) { + Art::Thumb { sid, key, res } => { + assert_eq!(sid, server.raw()); + assert_eq!(key, "avatar"); + assert_eq!(res, (300, 300)); + } + _ => panic!("a profile avatar uses its retained server"), + } + } +} diff --git a/rust-modules/screens/src/profiles_test_support.rs b/rust-modules/screens/src/profiles_test_support.rs index 0195c96db8..63816e3019 100644 --- a/rust-modules/screens/src/profiles_test_support.rs +++ b/rust-modules/screens/src/profiles_test_support.rs @@ -16,14 +16,18 @@ impl plx_machine::machine::Host for SessionHost { type Fx = AppFx; type Msg = AppMsg; type Elem = u32; - type Views<'a> = auth::SessionRead<'a>; + type Views<'a> = (auth::SessionRead<'a>, &'a crate::registry::ScreenInputs); type Init = super::super::family::NoInit; type Memory = (); } +impl crate::registry::ScreenInputsLike for SessionHost { + fn screen_inputs<'a>(cx: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { cx.views.1 } +} + impl AuthLike for SessionHost { fn auth<'a>(cx: &Cx<'a, Self>) -> auth::SessionRead<'a> { - cx.views + cx.views.0 } } @@ -73,7 +77,7 @@ pub fn cx_with<'a>( snapshot: &'a auth::owner::SessionSnapshot, ) -> Cx<'a, SessionHost> { Cx { - views: snapshot.read(), + views: (snapshot.read(), crate::registry::publication_fixture()), tick: Tick::default(), measure: &MEASURE, press: PressRead::default(), diff --git a/rust-modules/screens/src/registry.rs b/rust-modules/screens/src/registry.rs index c9dbbadc9b..323e128022 100644 --- a/rust-modules/screens/src/registry.rs +++ b/rust-modules/screens/src/registry.rs @@ -25,6 +25,10 @@ //! on the dispatcher yet. The bridge drains them after every dispatcher frame. pub use crate::family::SettingsPage; +pub use crate::family::InnerViews; +pub use crate::inputs::{GrantInputs, ScreenInputs}; +#[cfg(test)] +pub(crate) use crate::inputs::{capture_fixture, empty_fixture, publication_fixture}; /// The stored Under posters setting as the ui caption policy: the shared door a screen outside /// Settings (the Library's Collections page) reads it through, so none names `crate::settings`. pub use crate::settings::caption_policy_of; @@ -120,6 +124,7 @@ pub struct AccountPreferenceReply { } pub enum PreferenceCmd { + AutoSignIn { on: bool, reply: std::sync::mpsc::Sender }, /// Demand viewer features; the app coalesces this profile-scoped read. EnsureMarkerAccess, ChooseMarker { kind: plx_data::metadata::MarkerKind, mode: plx_plex::plex::session::MarkerSkipMode, @@ -1341,7 +1346,8 @@ pub trait MetadataLike: AppLike + Sized { /// A host that publishes Home's retained catalog view. The view is borrowed from the rig-owned /// snapshot and is therefore valid for the complete step/draw query without per-frame cloning. -pub trait HomeLike: AppLike + Sized { +pub trait HomeLike: AppLike + ScreenInputsLike + Sized { + fn clock_facts<'a>(cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts>; fn hubs<'a>(cx: &Cx<'a, Self>) -> plx_data::pms::HubsView<'a>; } @@ -1360,7 +1366,8 @@ pub trait SearchLike: AppLike + Sized { } /// A host that publishes all three retained Library views captured at the frame split. -pub trait LibraryLike: AppLike + Sized { +pub trait LibraryLike: AppLike + ScreenInputsLike + Sized { + fn clock_facts<'a>(cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts>; fn marker_prefs(_cx: &Cx<'_, Self>) -> plx_appkit::skip_policy::MarkerPrefsView { Default::default() } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a>; fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a>; @@ -1403,7 +1410,7 @@ pub struct Forbidden; /// A host carrying the retained Browse directory needed by Chrome and the Settings family. /// Full Library hosts implement this automatically; the nested Settings host carries only this /// one publication so its Onboard child never falls back to the compatibility selector. -pub trait DirectoryLike: AppLike + Sized { +pub trait DirectoryLike: AppLike + ScreenInputsLike + Sized { fn marker_prefs(_cx: &Cx<'_, Self>) -> plx_appkit::skip_policy::MarkerPrefsView { Default::default() } fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a>; } @@ -1416,7 +1423,12 @@ impl DirectoryLike for H { } /// Session's immutable frame publication; playback retains its separate `session` view. -pub trait AuthLike: AppLike + Sized { +/// A host must explicitly supply the retained inputs; no ambient or neutral fallback. +pub trait ScreenInputsLike: AppLike + Sized { + fn screen_inputs<'a>(cx: &Cx<'a, Self>) -> &'a crate::inputs::ScreenInputs; +} + +pub trait AuthLike: AppLike + ScreenInputsLike + Sized { fn auth<'a>(cx: &Cx<'a, Self>) -> plx_session::auth::SessionRead<'a>; } @@ -1429,6 +1441,21 @@ pub enum DetailRefreshPhase { Requested, } +/// Explicit offline screen-host capture; the production machine has no registry fallback. +#[cfg(test)] +pub(crate) fn run_person_fixture(store: &mut plx_data::stores::person::PersonStore, + cmd: plx_data::stores::person::PersonCmd) -> bool { + let mut keys = plx_plex::plex::ClientKeys::default(); + keys.refill_roster(plx_plex::plex::current_server(), plx_plex::plex::server_roster_gen(), + plx_plex::plex::server_facts_gen(), plx_plex::plex::server_ids(), + plx_plex::plex::client_for, plx_plex::plex::server_facts, plx_plex::plex::server_probe_result); + let bio = plx_base::devtrig::read("personbio"); + let input = plx_data::person::PersonInput { keys: &keys, session: None, visible_generation: 0, + profile_scope: 0, owner_epoch: 0, profile_generation: 0, tenure: 0, profile_key: "", + controlled: false, profile_refused: false, credits_refused: false, dev_bio: bio.as_deref(), dev_credits: None }; + store.run_with_input(cmd, &input) +} + /// The application's messages (spec §3.1). pub enum AppMsg { AutoSkipResolved { id: plx_appkit::skip_policy::OfferId, outcome: plx_appkit::skip_policy::OfferOutcome }, @@ -1441,6 +1468,8 @@ pub enum AppMsg { SelectionReply { correlation: u32, accepted: bool, flow_epoch: u64 }, BackReply { correlation: u32, resumed: bool }, Store(StoreCmd), + /// Person commands retain their originating body through deferred delivery and teardown. + PersonCommand { from: MachineId, command: plx_data::stores::person::PersonCmd }, StoreWork(StoreWork), HubsResult(plx_data::stores::hubs::HubsResult), Home(HomeCmd), diff --git a/rust-modules/screens/src/settings.rs b/rust-modules/screens/src/settings.rs index 10b01733f9..13ed2614f8 100644 --- a/rust-modules/screens/src/settings.rs +++ b/rust-modules/screens/src/settings.rs @@ -486,13 +486,13 @@ fn mount_page( fx: &mut Effects<'_, InnerHost>, ) -> Box> { match arg { - SettingsPage::Root => Box::new(RootPage::new(entry, cx.views.directory)), + SettingsPage::Root => Box::new(RootPage::new(entry, cx.views.directory, &cx.views.inputs)), SettingsPage::Language => Box::new(LanguagePage::new(entry)), SettingsPage::UnderPosters => Box::new(under_posters::UnderPostersPage::new(entry)), SettingsPage::UnderPostersDetails(kind) => Box::new(under_posters::DetailsPage::new(entry, kind)), SettingsPage::Contribute => Box::new(super::legal::DocumentPage::contribute(entry)), - SettingsPage::Playback => Box::new(super::preferences::PreferencesPage::new(entry, super::preferences::Kind::Playback)), - SettingsPage::AudioSubtitles => Box::new(super::preferences::PreferencesPage::new(entry, super::preferences::Kind::AudioSubtitles)), + SettingsPage::Playback => Box::new(super::preferences::PreferencesPage::new(entry, super::preferences::Kind::Playback, &cx.views.inputs)), + SettingsPage::AudioSubtitles => Box::new(super::preferences::PreferencesPage::new(entry, super::preferences::Kind::AudioSubtitles, &cx.views.inputs)), SettingsPage::Legal => Box::new(super::legal::LegalIndex::new(entry)), SettingsPage::About => Box::new(super::legal::DocumentPage::about(entry)), SettingsPage::Document(i) => Box::new(super::legal::DocumentPage::legal(entry, i)), @@ -503,7 +503,7 @@ fn mount_page( } SettingsPage::Favourites => Box::new(super::onboard::OnboardScreen::settings(entry, cx.views.directory)), SettingsPage::LibraryFavourites => Box::new(super::onboard::OnboardScreen::library(entry, cx.views.directory)), - SettingsPage::Picker(kind) => Box::new(super::preferences::PickerPage::new(entry, kind)), + SettingsPage::Picker(kind) => Box::new(super::preferences::PickerPage::new(entry, kind, &cx.views.inputs)), SettingsPage::PlayerHud => Box::new(super::hud_settings::HudPage::new(entry)), SettingsPage::Diagnostics => Box::new(diagnostics::DiagnosticsPage::new(entry)), page @ (SettingsPage::HudGallery | SettingsPage::HudDetail(..) | SettingsPage::HudAbout(..) | SettingsPage::HudPreview(..)) => @@ -1118,13 +1118,18 @@ pub struct RootPage { entry: EntryId, form: FormTable, state: RootState, - session_watch: plx_plex::plex::session::VisibleSessionWatch, + session_watch: Option<(u64, bool, u32)>, + inputs: crate::registry::ScreenInputs, session_snapshot: std::sync::Arc, - pending_auto: Option<(bool, plx_base::storage_worker::TypedTicket)>, + pending_auto: Option<(bool, std::sync::mpsc::Receiver)>, /// The hero trailer switch picked here and not yet answered: the value the row shows meanwhile, /// and the receipt of its `route::choose` (Confirm) write. A `false` (or dropped) receipt means /// the pick was not saved, and the row goes back to the stored value. pending_trailer: Option<(bool, std::sync::mpsc::Receiver)>, + auto_receipt: Option, + trailer_receipt: Option, + trailer_seat: plx_plex::plex::session::Seat, + trailer_scope: u32, /// The servers the signed-in account answered plx_platform::i18n::msg::settings_plaintext_question() for, then the /// ones discovery offers it for and nobody has answered, by row — the `(machine_id, allowed)` /// each switch shows. @@ -1400,18 +1405,21 @@ fn root_form(inputs: &RootInputs) -> Form { } impl RootPage { - fn new(entry: EntryId, directory: plx_data::stores::browse::DirectoryView<'_>) -> Self { + fn new(entry: EntryId, directory: plx_data::stores::browse::DirectoryView<'_>, inputs: &crate::registry::ScreenInputs) -> Self { let mut s = Self { entry, form: FormTable::new(super::registry::BAND), session_watch: Default::default(), + inputs: inputs.clone(), session_snapshot: Default::default(), pending_auto: None, pending_trailer: None, + auto_receipt: None, trailer_receipt: None, + trailer_seat: inputs.profile.seat(), trailer_scope: inputs.profile.generation, under_ask: Default::default(), plaintext_rows: Vec::new(), pending_plaintext: None, alert: PlaintextAlert::new(ALERT_GROUP, super::registry::ALERT, super::registry::ALERT + 1), - grant_seen: plx_plex::plex::grant::revision(), + grant_seen: inputs.grant_generation, // placeholder: the page opens on the sentence of the row it seats, set below follow: plx_ui::follow_copy::FollowCopy::new(""), state: RootState { @@ -1435,19 +1443,19 @@ impl RootPage { /// Re-derive the rows from the session, keeping focus on the row it is on BY IDENTITY (a /// vanished row falls to its next, else previous, neighbour — `FormTable::set`). fn rebuild(&mut self, directory: plx_data::stores::browse::DirectoryView<'_>) { - if let Some(snapshot) = plx_plex::plex::session::peek_settled() { - self.session_snapshot = snapshot; + if let Some(snapshot) = self.inputs.settled_session() { + self.session_snapshot = snapshot.clone(); } let sess = &self.session_snapshot; - let signed_in = sess.account(plx_plex::plex::session::current().as_ref()).signed_in; + let signed_in = sess.account(self.inputs.profile.user.as_ref()).signed_in; let auto_sign_in = self.pending_auto.as_ref().map_or_else(|| sess.auto_sign_in(), |(value, _)| *value); // The SEATED profile's own switch, else the TV's older key, else on (`stored_effective`). - let trailer_autoplay = self.pending_trailer.as_ref().map_or_else(|| { + let trailer_autoplay = self.pending_trailer.as_ref().filter(|_| self.trailer_scope == self.inputs.profile.generation).map_or_else(|| { plx_plex::plex::session::stored_effective::( - sess, &plx_plex::plex::session::current_seat()) + sess, &self.inputs.profile.seat()) }, |(value, _)| *value); let resolution = sess.ui_resolution(); - let resolution_offered = plx_platform::tv::device::ui_resolution_offered(); + let resolution_offered = self.inputs.resolution_offered; let multi_user = sess.home_users.len() > 1; self.state.auto_sign_in = auto_sign_in; self.state.trailer_autoplay = trailer_autoplay; @@ -1485,15 +1493,15 @@ impl RootPage { fn plaintext_inputs(&mut self) -> Vec { use plx_plex::plex::session::PlaintextChoice; let sess = &self.session_snapshot; - let answered = plx_plex::plex::grant::choices(&sess.prefs.plaintext_consent, &sess.account_token); + let answered = &self.inputs.grants.choices; let mut rows: Vec<(String, bool)> = answered .iter() .filter(|(_, choice)| *choice != PlaintextChoice::Undecided) .map(|(machine, choice)| (machine.clone(), choice.allows())) .collect(); - for offer in plx_plex::plex::grant::offers() { + for offer in &self.inputs.grants.offers { if plaintext_question::asks(Some(&offer)) && !rows.iter().any(|(m, _)| *m == offer.machine_id) { - rows.push((offer.machine_id, false)); + rows.push((offer.machine_id.clone(), false)); } } // The optimistic value holds until the answers read agree with it. @@ -1506,7 +1514,7 @@ impl RootPage { } self.plaintext_rows = rows.clone(); self.state.plaintext = rows.iter().map(|(_, on)| *on).collect(); - let offers = plx_plex::plex::grant::offers(); + let offers = &self.inputs.grants.offers; rows.into_iter() .map(|(machine, on)| { // An offered server was never reached, so the session file does not know it yet: @@ -1520,7 +1528,7 @@ impl RootPage { .map(|s| s.name.clone())); let named = real_name.is_some(); let name = real_name.unwrap_or_else(|| plx_platform::i18n::msg::settings_plaintext_server().to_string()); - let connected = on && plx_plex::plex::grant::granted_origin(&machine).is_some(); + let connected = on && self.inputs.grants.connected.iter().any(|m| m == &machine); PlaintextRowInput { machine: ServerMachineId(machine), name, named, on, connected } }) .collect() @@ -1552,10 +1560,10 @@ impl RootPage { Action::Door => {} Action::AutoSignIn => { let on = !self.state.auto_sign_in; - if let Ok(ticket) = plx_plex::plex::session::queue_update_ticket(move |current| - (current.auto_sign_in() != on).then(|| current.with_auto_sign_in(on))) { - self.pending_auto = Some((on, ticket)); - } + let (reply, receipt) = std::sync::mpsc::channel(); + fx.push(Fx::App(AppFx::Preferences(super::registry::PreferenceCmd::AutoSignIn { on, reply }))); + self.auto_receipt = None; + self.pending_auto = Some((on, receipt)); self.rebuild(directory); } Action::TrailerAutoplay => { @@ -1565,6 +1573,9 @@ impl RootPage { let (reply, receipt) = std::sync::mpsc::channel(); fx.push(Fx::App(AppFx::Preferences(super::registry::PreferenceCmd::Choose( plx_media::route::Choice::TrailerAutoplay(on), reply)))); + self.trailer_receipt = None; + self.trailer_seat = self.inputs.profile.seat(); + self.trailer_scope = self.inputs.profile.generation; self.pending_trailer = Some((on, receipt)); self.rebuild(directory); } @@ -1576,17 +1587,16 @@ impl RootPage { if !on { // ON asks first — the same question the sign-in and the failure read-outs // put, seated on *Not now*; only its *Connect* allows (`alert_answer`). - let sid = plx_plex::plex::id_of_machine(&machine); + let sid = self.inputs.servers.iter().find(|(id, _)| id == &machine).map(|(_, sid)| *sid); self.alert.open(&machine, sid, MachineId::Instance(InstanceId(0)), fx); return; } - // OFF is immediate: `grant::record` withdraws the grant NOW, before the - // preferences write lands, and records the revocation for this account. - plx_base::eventlog::log("settings: unencrypted connections turned off for one server"); - let account = plx_plex::plex::grant::account_key(&self.session_snapshot.account_token); - if plx_plex::plex::grant::record(&account, &machine, PlaintextChoice::Revoked).is_ok() { - self.pending_plaintext = Some((machine, false)); - } + // The same-drain Session runner withdraws the grant before its storage write. + fx.push(Fx::App(AppFx::Session(plx_session::auth::SessionCmd::AnswerPlaintext { + machine_id: machine.clone(), choice: PlaintextChoice::Revoked, + sid: self.inputs.servers.iter().find(|(id, _)| id == &machine).map(|(_, sid)| *sid), + }))); + self.pending_plaintext = Some((machine, false)); self.rebuild(directory); } } @@ -1620,6 +1630,7 @@ impl Machine for RootPage { cx: &Cx<'_, InnerHost>, fx: &mut Effects<'_, InnerHost>, ) -> Handled { + self.inputs = cx.views.inputs.clone(); match self.alert.step(ev, cx) { AlertStep::Pass => {} AlertStep::Done(handled) => return handled, @@ -1657,42 +1668,61 @@ impl Machine for RootPage { if owed && cx.focus.current.is_some_and(|key| key.entry == self.entry) { self.under_ask.step(cx, fx); } - let mut landed = self.session_watch.changed(); - if self.pending_auto.as_ref().is_some_and(|(_, ticket)| !matches!(ticket.try_recv(), - Err(std::sync::mpsc::TryRecvError::Empty))) { - // Read AFTER the receipt: the worker may have installed Locked/Blocked - // while this Tick was polling. Retain a consumed receipt's local value - // until authority settles; subsequent polls see Disconnected. - if let Some(snapshot) = plx_plex::plex::session::peek_settled() { - self.session_snapshot = snapshot; + let key = self.inputs.session_key(); + let mut landed = self.session_watch != Some(key); + self.session_watch = Some(key); + if let Some((value, ticket)) = &self.pending_auto { + if self.auto_receipt.is_none() { + self.auto_receipt = match ticket.try_recv() { + Ok(saved) => Some(saved), + Err(std::sync::mpsc::TryRecvError::Empty) => None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(false), + }; + } + // A receipt may arrive after this pump captured its views. A successful + // write keeps its optimistic value until the retained authority confirms it. + if self.inputs.settled && self.auto_receipt.is_some_and(|saved| + !saved || self.inputs.session.auto_sign_in() == *value) { self.pending_auto = None; + self.auto_receipt = None; landed = true; } } - if self.pending_trailer.as_ref().is_some_and(|(_, receipt)| !matches!(receipt.try_recv(), - Err(std::sync::mpsc::TryRecvError::Empty))) { - // Answered (saved, refused or dropped): the row reads the stored value again, - // which holds the pick only if the write was durable. Same wait for a settled - // session as above. - if let Some(snapshot) = plx_plex::plex::session::peek_settled() { - self.session_snapshot = snapshot; + if self.pending_trailer.is_some() && self.trailer_scope != self.inputs.profile.generation { + self.pending_trailer = None; + self.trailer_receipt = None; + landed = true; + } + if let Some((value, ticket)) = &self.pending_trailer { + if self.trailer_receipt.is_none() { + self.trailer_receipt = match ticket.try_recv() { + Ok(saved) => Some(saved), + Err(std::sync::mpsc::TryRecvError::Empty) => None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(false), + }; + } + let stored = plx_plex::plex::session::stored_effective::< + plx_plex::plex::session::TrailerAutoplayPref>(&self.inputs.session, &self.trailer_seat); + if self.inputs.settled && self.trailer_receipt.is_some_and(|saved| !saved || stored == *value) { self.pending_trailer = None; + self.trailer_receipt = None; landed = true; } } // An offer or an answer landed (`grant::revision`): the switches re-read. - let revision = plx_plex::plex::grant::revision(); + let revision = self.inputs.grant_generation; if revision != self.grant_seen { self.grant_seen = revision; landed = true; } + if landed { self.rebuild(cx.views.directory); } if self.alert.is_open() && !self.alert.subject().is_some_and(|m| self.plaintext_rows.iter().any(|(row, on)| row == m && !on)) { // the server the question is about left the list, or is on already self.alert.withdraw(); } self.alert.update(t.dt()); - if landed { self.rebuild(cx.views.directory); fx.invalidate(plx_machine::present::Provenance::Landing(MachineId::Session)); } + if landed { fx.invalidate(plx_machine::present::Provenance::Landing(MachineId::Session)); } self.form.table .update(t.dt(), RouteLayout::settings_page().sectioned_table().h); diff --git a/rust-modules/screens/src/settings_composed_tests.rs b/rust-modules/screens/src/settings_composed_tests.rs index e7ea5d0a68..875026e5e7 100644 --- a/rust-modules/screens/src/settings_composed_tests.rs +++ b/rust-modules/screens/src/settings_composed_tests.rs @@ -118,7 +118,7 @@ impl Rig for SurfaceRig { self.stores.capture_seeded_browse_for_test(&mut self.directory, plx_plex::plex::current_server()); Split { mounter: &mut self.mounter, - views: self.directory.view().into(), + views: crate::registry::InnerViews::new(self.directory.view(), crate::registry::publication_fixture()), measure: &self.measure, } } @@ -146,7 +146,14 @@ impl Rig for SurfaceRig { _parts: &CxParts, _out: &mut Effects<'_, InnerHost>, ) { - if let AppFx::Preferences(command) = effect { self.preference_commands.push(command); } + match effect { + AppFx::Preferences(command) => self.preference_commands.push(command), + AppFx::Session(plx_session::auth::SessionCmd::AnswerPlaintext { machine_id, choice, .. }) => { + let account = plx_plex::plex::grant::account_key(&plx_plex::plex::session::peek().account_token); + plx_plex::plex::grant::record(&account, &machine_id, choice).expect("fixture grant answer"); + } + _ => {} + } } fn log(&mut self, _line: &str) {} fn prepare(&mut self, _b: &mut Budget, _present: &mut Present) {} diff --git a/rust-modules/screens/src/settings_draw_and_lifecycle_tests.rs b/rust-modules/screens/src/settings_draw_and_lifecycle_tests.rs index c26602957e..78b331d532 100644 --- a/rust-modules/screens/src/settings_draw_and_lifecycle_tests.rs +++ b/rust-modules/screens/src/settings_draw_and_lifecycle_tests.rs @@ -138,7 +138,7 @@ fn opening_settings_never_writes_the_session_file() { fn the_signed_in_root_carries_no_sub_line_and_its_sentences_fit_elsewhere() { let _g = plx_base::testlock::serial(); let _sess = multi_user_session("root-detail-widths"); - let page = RootPage::new(EntryId(0), plx_data::stores::browse::DirectoryView::empty_for_test()); + let page = RootPage::new(EntryId(0), plx_data::stores::browse::DirectoryView::empty_for_test(), &crate::registry::capture_fixture()); // Settings v2: a root row is a label and a value, a switch or a chevron; its sentence is said // in the left column while it has focus (`sentence_for`, fit in `settings_v2_tests`), and a // server's switch (which states a status) is the only row that may keep a sub-line. diff --git a/rust-modules/screens/src/settings_nav_structure_tests.rs b/rust-modules/screens/src/settings_nav_structure_tests.rs index f9d03f4cc3..7cb6cca9bd 100644 --- a/rust-modules/screens/src/settings_nav_structure_tests.rs +++ b/rust-modules/screens/src/settings_nav_structure_tests.rs @@ -93,7 +93,7 @@ fn assert_every_nav_item_pushes_exactly_its_dest(label: &str, items: &[(u32, Set } fn root_items() -> Vec<(u32, SettingsPage)> { - let page = RootPage::new(EntryId(0), plx_data::stores::browse::DirectoryView::empty_for_test()); + let page = RootPage::new(EntryId(0), plx_data::stores::browse::DirectoryView::empty_for_test(), &crate::registry::capture_fixture()); nav_items(&page.form) } @@ -165,13 +165,14 @@ fn every_audio_and_subtitles_field_pushes_its_picker() { let previous = plx_plex::plex::session::current_snapshot(); struct Restore(std::sync::Arc); impl Drop for Restore { - fn drop(&mut self) { plx_plex::plex::session::publish_profile_for_test(self.0.user.clone(), self.0.generation); } + fn drop(&mut self) { plx_plex::plex::session::publish_seat_for_test(self.0.user.clone(), self.0.generation, self.0.stamp.clone()); } } let _restore = Restore(previous); - let user = plx_plex::plex::session::UserRef { id: 7, uuid: "nav-structure-audio".into(), ..Default::default() }; + let user = plx_plex::plex::session::UserRef { id: 7, uuid: "nav-structure-audio".into(), plex_tv_token: Some("synthetic-token".into()), ..Default::default() }; // seated: the Look rows (this app's own per-profile picks) are read-only for nobody plx_plex::plex::session::publish_seat_for_test(Some(user.clone()), 81, "nav-structure-stamp".into()); - let (request, snapshot) = PreferenceRequest::fixture_for_test(user, 81, AudioPreferences::default()); + let (_, snapshot) = PreferenceRequest::fixture_for_test(user, 81, AudioPreferences::default()); + let request = PreferenceRequest::capture().expect("the host captures the stamped fixture seat"); let items = super::super::preferences::nav_items_for_test(super::super::preferences::Kind::AudioSubtitles, Some(&AudioPreferences::default())); assert_eq!(items.len(), 7, "the four account fields and the three Look rows (subtitle size, position and color): {items:?}"); assert_every_nav_item_pushes_exactly_its_dest("audio & subtitles", &items, &|| { @@ -400,16 +401,17 @@ fn every_pushed_picker_opens_on_its_checked_line_and_pops_to_its_row() { let previous = ses::current_snapshot(); struct Restore(std::sync::Arc); impl Drop for Restore { - fn drop(&mut self) { ses::publish_profile_for_test(self.0.user.clone(), self.0.generation); } + fn drop(&mut self) { ses::publish_seat_for_test(self.0.user.clone(), self.0.generation, self.0.stamp.clone()); } } let _restore = Restore(previous); - let user = ses::UserRef { id: 7, uuid: "nav-structure-checked-lines".into(), ..Default::default() }; + let user = ses::UserRef { id: 7, uuid: "nav-structure-checked-lines".into(), plex_tv_token: Some("synthetic-token".into()), ..Default::default() }; ses::publish_seat_for_test(Some(user.clone()), 81, "nav-structure-stamp".into()); let language_line = |code: &str| 1 + plx_plex::plex::languages::picker().position(|l| l.code == code) .unwrap_or_else(|| panic!("{code} is in the language picker")) as u32; let prefs = AudioPreferences { stated_language: Some("fr".into()), subtitle_language: Some("de".into()), subtitle_mode: 2, subtitle_forced: 3, ..Default::default() }; - let (request, snapshot) = PreferenceRequest::fixture_for_test(user, 81, prefs.clone()); + let (_, snapshot) = PreferenceRequest::fixture_for_test(user, 81, prefs.clone()); + let request = PreferenceRequest::capture().expect("the host captures the stamped fixture seat"); let items = super::super::preferences::nav_items_for_test(super::super::preferences::Kind::AudioSubtitles, Some(&prefs)); assert_eq!(items.len(), 7, "every Audio & Subtitles picker is in the table: {items:?}"); for &(row, dest) in &items { diff --git a/rust-modules/screens/src/settings_root_navigation_tests.rs b/rust-modules/screens/src/settings_root_navigation_tests.rs index cee0fe1b96..b8edf75238 100644 --- a/rust-modules/screens/src/settings_root_navigation_tests.rs +++ b/rust-modules/screens/src/settings_root_navigation_tests.rs @@ -86,7 +86,8 @@ fn a_multi_user_root_toggles_automatically_sign_in_in_place() { }, Some(row), ); - step(&mut s, ScreenEvent::Activate(row.elem), Some(row)); + let out = step(&mut s, ScreenEvent::Activate(row.elem), Some(row)); + execute_storage_effects(&out); plx_base::storage_worker::drain_for_test(); assert_eq!( name(&s), @@ -98,7 +99,8 @@ fn a_multi_user_root_toggles_automatically_sign_in_in_place() { plx_plex::plex::session::peek().auto_sign_in(), "the queued switch is durable after the worker completes" ); - step(&mut s, ScreenEvent::Activate(row.elem), Some(row)); + let out = step(&mut s, ScreenEvent::Activate(row.elem), Some(row)); + execute_storage_effects(&out); plx_base::storage_worker::drain_for_test(); assert!(!plx_plex::plex::session::peek().auto_sign_in()); assert_eq!(s.inner.depth(), 1); @@ -541,7 +543,7 @@ fn session_refresh_rebuilds_root_without_navigation() { let _sess = multi_user_session("root-session-refresh"); let saved = plx_plex::plex::session::peek(); plx_plex::plex::session::install_transient_for_test(true); - let mut root = RootPage::new(EntryId(0), cx(None).views.directory); + let mut root = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); assert!(!root.form.index_of(&RootId::AutoSignIn).is_some()); plx_plex::plex::session::save(&saved.with_auto_sign_in(true)); let mut out = Vec::new(); @@ -558,8 +560,9 @@ fn session_refresh_keeps_optimistic_setting_through_transient_completion() { let _g = plx_base::testlock::serial(); let _sess = multi_user_session("root-pending-refresh"); let saved = plx_plex::plex::session::peek(); - let mut root = RootPage::new(EntryId(0), cx(None).views.directory); - let ticket = plx_base::storage_worker::submit_retained(|| false); + let mut root = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); + let (reply, ticket) = std::sync::mpsc::channel(); + reply.send(false).unwrap(); plx_base::storage_worker::drain_for_test(); root.pending_auto = Some((true, ticket)); root.rebuild(cx(None).views.directory); @@ -601,7 +604,7 @@ fn the_unencrypted_connection_switch_shows_the_grant_and_revokes_it_at_once() { plx_plex::plex::grant::mint(plx_plex::plex::grant::scope(), "lan-machine", &lan, &plx_plex::plex::grant::eligible_evidence_for_test()).unwrap(); - let mut root = RootPage::new(EntryId(0), cx(None).views.directory); + let mut root = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); let row = root.form.index_of(&RootId::Plaintext(ServerMachineId("lan-machine".into()))) .expect("an allowed server has its switch"); let drawn = root.form.table.sections.iter().flat_map(|s| &s.rows).nth(row).unwrap(); @@ -613,7 +616,12 @@ fn the_unencrypted_connection_switch_shows_the_grant_and_revokes_it_at_once() { let mut out = Vec::new(); let mut present = Present::new(); let mut fx = Effects::new(&mut out, MachineId::Session, &mut present); - root.activate(root.form.key_at(row).unwrap().0, cx(None).views.directory, &mut fx); + let captured = cx(None); + { + let _step = plx_base::step::StepScope::enter(); + root.activate(root.form.key_at(row).unwrap().0, captured.views.directory, &mut fx); + } + execute_storage_effects(&out); assert_eq!(plx_plex::plex::grant::granted_origin("lan-machine"), None, "revoked before the write lands"); assert!(!plx_plex::plex::grant::allowed_under(plx_plex::plex::CredentialPolicy::HttpsOnly, &lan)); assert_eq!(root.state.plaintext, vec![false], "the switch shows the answer optimistically"); @@ -631,7 +639,7 @@ fn the_unencrypted_connection_switch_shows_the_grant_and_revokes_it_at_once() { fn no_unencrypted_connection_section_without_an_answer() { let _g = plx_base::testlock::serial(); let _sess = multi_user_session("root-plaintext-none"); - let root = RootPage::new(EntryId(0), cx(None).views.directory); + let root = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); assert!(root.form.index_of_key(RowKey(PLAINTEXT_KEY_BASE)).is_none()); assert!(root.state.plaintext.is_empty()); } @@ -652,7 +660,7 @@ fn turning_an_unencrypted_connection_on_asks_the_shared_question_first() { machine_id: "lan-machine".into(), name: "Basement".into(), shared_by: String::new(), eligibility: plx_plex::plex::probe::PlaintextEligibility::Eligible, choice: PlaintextChoice::Undecided, }); - let mut root = RootPage::new(EntryId(0), cx(None).views.directory); + let mut root = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); let row = root.form.index_of(&RootId::Plaintext(ServerMachineId("lan-machine".into()))) .expect("an offered, never-asked server has its switch"); let drawn = root.form.table.sections.iter().flat_map(|s| &s.rows).nth(row).unwrap(); @@ -757,7 +765,7 @@ fn the_interface_resolution_row_is_offered_on_webos_1_to_3_only() { // a host test has no television: the real page is the webOS 4+ shape and has no such row let _g = plx_base::testlock::serial(); let _sess = multi_user_session("root-resolution-gate"); - let page = RootPage::new(EntryId(0), cx(None).views.directory); + let page = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); assert_eq!(page.form.index_of(&RootId::Resolution), None); } @@ -862,7 +870,7 @@ fn back_from_each_root_door_reseats_focus_on_the_same_root_id() { fn a_rebuild_keeps_the_row_by_id_and_a_vanished_row_falls_to_its_neighbour() { let _g = plx_base::testlock::serial(); let _sess = multi_user_session("root-rebuild-identity"); - let mut page = RootPage::new(EntryId(0), cx(None).views.directory); + let mut page = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); select_root(&mut page, RootId::Language); page.rebuild(cx(None).views.directory); assert_eq!(page.form.selected_id(), Some(&RootId::Language), "a rebuild keeps the row it is on"); @@ -890,7 +898,7 @@ fn a_rebuild_keeps_the_row_by_id_and_a_vanished_row_falls_to_its_neighbour() { fn the_root_diagnostics_row_reads_the_status_the_runner_answers() { use plx_platform::playback_trace::Status; let _serial = plx_base::testlock::serial(); - let mut root = RootPage::new(EntryId(0), cx(None).views.directory); + let mut root = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); let mut fx = Effects::new(&mut out, MachineId::Instance(InstanceId(0)), &mut present); @@ -940,3 +948,58 @@ fn hud_return_to_player_hud(remove: bool) { fn use_hud_returns_to_player_hud_with_an_unrelated_surface_id() {hud_return_to_player_hud(false);} #[test] fn remove_hud_returns_to_player_hud_with_an_unrelated_surface_id() {hud_return_to_player_hud(true);} + +#[test] +fn retained_offer_expiry_rebuilds_the_switches_without_a_roster_change() { + use plx_plex::plex::{grant::PlaintextVerdict, probe::PlaintextEligibility, session::PlaintextChoice}; + let _serial = plx_base::testlock::serial(); + let mut inputs = crate::registry::ScreenInputs::default(); + std::sync::Arc::make_mut(&mut inputs.session).account_token = "retained-account".into(); + inputs.settled = true; + std::sync::Arc::make_mut(&mut inputs.grants).offers.push(PlaintextVerdict { + machine_id: "server".into(), name: "Server".into(), shared_by: String::new(), + eligibility: PlaintextEligibility::Eligible, choice: PlaintextChoice::Undecided }); + let mut cx = cx(None); + cx.views.inputs = &inputs; + let mut page = RootPage::new(EntryId(0), cx.views.directory, &cx.views.inputs); + assert_eq!(page.plaintext_rows, vec![("server".into(), false)]); + let mut expired = inputs.clone(); + expired.grants = Default::default(); + expired.grant_generation += 1; + cx.views.inputs = &expired; + let mut out = Vec::new(); + let mut present = Present::new(); + page.step(&ScreenEvent::Tick(Default::default()), &cx, + &mut Effects::new(&mut out, MachineId::Instance(InstanceId(0)), &mut present)); + assert!(page.plaintext_rows.is_empty()); +} + +#[test] +fn a_success_receipt_waits_for_the_next_captured_authority() { + let _serial = plx_base::testlock::serial(); + let mut inputs = crate::registry::ScreenInputs::default(); + inputs.session = std::sync::Arc::new(inputs.session.with_auto_sign_in(false)); + inputs.settled = true; + let mut cx = cx(None); + cx.views.inputs = &inputs; + let mut page = RootPage::new(EntryId(0), cx.views.directory, cx.views.inputs); + let (reply, ticket) = std::sync::mpsc::channel(); + reply.send(true).unwrap(); + plx_base::storage_worker::drain_for_test(); + page.pending_auto = Some((true, ticket)); + page.rebuild(cx.views.directory); + let mut out = Vec::new(); + let mut present = Present::new(); + page.step(&ScreenEvent::Tick(Default::default()), &cx, + &mut Effects::new(&mut out, MachineId::Instance(InstanceId(0)), &mut present)); + assert!(page.state.auto_sign_in, "an old captured snapshot cannot undo a successful write"); + assert!(page.pending_auto.is_some()); + let mut confirmed = inputs.clone(); + confirmed.session = std::sync::Arc::new(confirmed.session.with_auto_sign_in(true)); + confirmed.visible_generation += 1; + cx.views.inputs = &confirmed; + page.step(&ScreenEvent::Tick(Default::default()), &cx, + &mut Effects::new(&mut out, MachineId::Instance(InstanceId(0)), &mut present)); + assert!(page.pending_auto.is_none()); + assert!(page.state.auto_sign_in); +} diff --git a/rust-modules/screens/src/settings_test_support.rs b/rust-modules/screens/src/settings_test_support.rs index 70cf6c47c1..c56ce6bd54 100644 --- a/rust-modules/screens/src/settings_test_support.rs +++ b/rust-modules/screens/src/settings_test_support.rs @@ -35,7 +35,7 @@ pub fn cx_with<'a>( directory: plx_data::stores::browse::DirectoryView<'a>, ) -> Cx<'a, InnerHost> { Cx { - views: directory.into(), + views: crate::registry::InnerViews::new(directory, crate::registry::publication_fixture()), tick: Tick::default(), measure: &MEASURE, press: PressRead::default(), @@ -44,7 +44,7 @@ pub fn cx_with<'a>( } } -pub fn cx(focus: Option>) -> Cx<'static, InnerHost> { +pub fn cx<'a>(focus: Option>) -> Cx<'a, InnerHost> { cx_with(focus, plx_data::stores::browse::DirectoryView::empty_for_test()) } @@ -59,10 +59,30 @@ pub fn step( let mut present = Present::new(); let mut fx = Effects::new(&mut out, MachineId::Instance(InstanceId(0)), &mut present); let c = cx(focus); + let _step = plx_base::step::StepScope::enter(); let _ = >::step(s, &ev, &c, &mut fx); out } +/// Execute the storage effects of this fixture host, after leaving the screen step. +pub fn execute_storage_effects(out: &[Stamped]) { + for effect in out { + match &effect.fx { + Fx::App(AppFx::Preferences(crate::registry::PreferenceCmd::AutoSignIn { on, reply })) => { + let (on, reply) = (*on, reply.clone()); + plx_plex::plex::session::queue_update_settled(move |current| + (current.auto_sign_in() != on).then(|| current.with_auto_sign_in(on)), + move |saved| { let _ = reply.send(saved); }); + } + Fx::App(AppFx::Session(plx_session::auth::SessionCmd::AnswerPlaintext { machine_id, choice, .. })) => { + let account = plx_plex::plex::grant::account_key(&plx_plex::plex::session::peek().account_token); + plx_plex::plex::grant::record(&account, machine_id, *choice).expect("fixture grant answer"); + } + _ => {} + } + } +} + pub fn name(s: &RouteSurface) -> &'static str { >::name(s) } @@ -131,6 +151,7 @@ pub fn seated_scratch_session(tag: &str) -> plx_plex::plex::session::TempSession } pub fn multi_user_session(tag: &str) -> plx_plex::plex::session::TempSession { + plx_plex::plex::grant::reset_for_test(); let t = plx_plex::plex::session::TempSession::new(tag); plx_plex::plex::session::save(&plx_plex::plex::session::Session { client_id: "cid-test".into(), diff --git a/rust-modules/screens/src/settings_text_fit_tests.rs b/rust-modules/screens/src/settings_text_fit_tests.rs index 392a1dab8f..c552ad964d 100644 --- a/rust-modules/screens/src/settings_text_fit_tests.rs +++ b/rust-modules/screens/src/settings_text_fit_tests.rs @@ -55,7 +55,7 @@ fn every_settings_row_fits_its_column_in_every_language() { for language in SHIPPED { let _guard = language_on_this_thread_for_test(language); let tag = language.tag(); - overflowing(&format!("{tag} root (signed out)"), &RootPage::new(EntryId(0), test_support::cx(None).views.directory).form.table, &mut out); + overflowing(&format!("{tag} root (signed out)"), &RootPage::new(EntryId(0), test_support::cx(None).views.directory, &crate::registry::capture_fixture()).form.table, &mut out); overflowing(&format!("{tag} language"), &LanguagePage::new(EntryId(0)).form.table, &mut out); // The Diagnostics page's Export row reads `trace_label(status)`: every status, through the // page's own constructor (the table it draws), not a table of the test's own. diff --git a/rust-modules/screens/src/settings_under_posters_tests.rs b/rust-modules/screens/src/settings_under_posters_tests.rs index 3ee7bd9597..583ac83658 100644 --- a/rust-modules/screens/src/settings_under_posters_tests.rs +++ b/rust-modules/screens/src/settings_under_posters_tests.rs @@ -768,7 +768,7 @@ fn the_root_page_reads_the_stored_setting_into_its_row() { let _en = language_on_this_thread_for_test(plx_platform::i18n::Preference::En); let stored = UnderPosters { title: true, details: parts(&[P::Genre]), show_details: DetailParts::NONE, sort_value: false }; let _live = Live::set(stored); - let page = RootPage::new(EntryId(0), test_support::cx(None).views.directory); + let page = RootPage::new(EntryId(0), test_support::cx(None).views.directory, &crate::registry::capture_fixture()); assert_eq!(page.state.under_posters, stored); } @@ -1009,7 +1009,7 @@ fn the_settings_root_asks_for_the_missing_poster_only_on_its_under_posters_row_a // The Libraries section (and the Under posters row in it) is there only for a signed-in account. let _session = multi_user_session("under-posters-root-ask"); let snapshot = movies_only_directory(); - let mut root = RootPage::new(EntryId(0), snapshot.view()); + let mut root = RootPage::new(EntryId(0), snapshot.view(), &crate::registry::capture_fixture()); let on = |elem: u32| Some(FocusKey { entry: EntryId(0), elem }); let tick = |root: &mut RootPage, focus| { let c = cx_with(focus, snapshot.view()); diff --git a/rust-modules/screens/src/settings_v2_tests.rs b/rust-modules/screens/src/settings_v2_tests.rs index f49dd58281..2a88d8bb4d 100644 --- a/rust-modules/screens/src/settings_v2_tests.rs +++ b/rust-modules/screens/src/settings_v2_tests.rs @@ -107,7 +107,7 @@ fn the_sentence_follows_the_focused_row_and_falls_back_to_the_pages() { #[test] fn the_root_opens_on_its_first_rows_sentence_with_nothing_fading() { let _serial = plx_base::testlock::serial(); - let root = RootPage::new(EntryId(0), cx(None).views.directory); + let root = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); let first = root.form.selected_id().cloned(); assert!(first.is_some(), "the root seats a row on mount"); assert_eq!(root.follow.text(), sentence_for(first.as_ref()).as_ref()); @@ -117,7 +117,7 @@ fn the_root_opens_on_its_first_rows_sentence_with_nothing_fading() { #[test] fn moving_focus_moves_the_followed_sentence() { let _serial = plx_base::testlock::serial(); - let mut root = RootPage::new(EntryId(0), cx(None).views.directory); + let mut root = RootPage::new(EntryId(0), cx(None).views.directory, &crate::registry::capture_fixture()); select_root(&mut root, RootId::Language); assert_eq!(root.follow.text(), msg::settings_language_detail()); assert!(root.follow.arrival() < 1.0, "a new sentence fades in"); @@ -246,7 +246,7 @@ fn the_root_asks_for_posters_while_favorite_libraries_has_focus_and_the_fan_is_e let sid = plx_plex::plex::ServerId::from_raw(0); let section = |key, kind| SectionView { sid: Some(sid), key, kind, row: SrcRow { pinned: true, ..Default::default() } }; let empty = DirectorySnapshot::fixture(7, 0, vec![section(1, SecKind::Movie), section(2, SecKind::Show)]); - let mut root = RootPage::new(EntryId(0), empty.view()); + let mut root = RootPage::new(EntryId(0), empty.view(), &crate::registry::capture_fixture()); assert_eq!(root.form.selected_id(), Some(&RootId::Favourites), "premise: the root opens on Favorite libraries"); let focus = Some(FocusKey { entry: EntryId(0), elem: root.state.sel.0 }); let tick = |root: &mut RootPage, snapshot: &DirectorySnapshot| { diff --git a/rust-modules/session/src/auth.rs b/rust-modules/session/src/auth.rs index c55fd27513..b01684c64a 100644 --- a/rust-modules/session/src/auth.rs +++ b/rust-modules/session/src/auth.rs @@ -21,8 +21,11 @@ use plx_plex::plex::probe::{ use plx_plex::plex::session::{self, PlaintextChoice, ProfileCreds, ServerRef, Session, SourceRef, UserRef}; use plx_plex::plex::{CredentialPolicy, Origin, ServerId}; use std::sync::atomic::{AtomicU8, Ordering}; -use std::sync::{mpsc, Arc}; +use std::sync::Arc; use std::time::{Duration, Instant}; +mod ports; +use ports::{home_roster_worker_with_io, mint_pin, finish_sign_in, race_batch, discover_and_store_with_resources, server_roster_worker_with_output, probe_endpoint_work, LivePin}; +pub use ports::profile_switch_worker_with_io; pub mod owner; pub mod observation; @@ -461,19 +464,7 @@ fn home_roster_worker_with_output(epoch: u64, expected: SessionIdentity, cid: St |ac, remaining| ac.home_users_with(account_timeouts(remaining))); } -fn home_roster_worker_with_io(epoch: u64, expected: SessionIdentity, cid: String, - token: String, output: &dyn owner::ObservationSink, - mut home_users: impl FnMut(&AccountClient, Duration) -> Result, CallEvidence>) { - if !output.live() { return; } - let ac = AccountClient::new(&cid, Some(&token)); - let mut clock = LiveRetryClock { output, started: Instant::now() }; - let Some(users) = home_roster_with_io_and_clock(&ac, &mut clock, &mut home_users) else { return }; - output.terminal(AuthProgress::HomeRoster(HomeRosterProgress { - epoch, - expected, - users, - })); -} + fn home_roster_with_io_and_clock(ac: &AccountClient, clock: &mut impl RetryClock, mut home_users: impl FnMut(&AccountClient, Duration) -> Result, CallEvidence>) @@ -1171,89 +1162,7 @@ fn another_code_allowed(generation: u32) -> bool { /// /// `None` means "stop": either the flow was superseded (silent — the successor owns the screen) or /// creation failed and has already said so on the error read-out. -fn mint_pin(ac: &AccountClient, epoch: u64, generation: u32, - output: &dyn owner::ObservationSink) -> Option { - if !output.live() { return None; } - if generation > 1 { - // Liveness only, no write — see the section doc above [`login_thread`]. This is the same - // "stop wasting plex.tv calls on a dead flow" courtesy the old synchronous check made: - // without it, the account call below would still burn a network round trip minting a code - // nobody is left to scan. - if !output.live() { - return None; - } - if !output.progress(LoginProgress::CodeReplacing { epoch }.into()) { return None; } - } - let mut clock = LiveRetryClock { output, started: Instant::now() }; - let created = retry_account_call(INTERACTIVE_ACCOUNT, &mut clock, |_, _, _| {}, - |remaining| scripted::signin_trouble_create() - .unwrap_or_else(|| ac.create_pin_with(account_timeouts(remaining)))); - let created = match created.result { - AccountCallEnd::Answer(pin) => Ok(pin), - AccountCallEnd::Failed(evidence) => Err(evidence), - AccountCallEnd::Cancelled => return None, - }; - let pin = match created { - Ok(p) if p.id != 0 && !p.code.is_empty() => p, - failed => { - // A 2xx that decoded into a pin with no id or code is still an answer: classed by - // its status, which is the 2xx it was. - let last = match failed { Err(evidence) => evidence, Ok(_) => Ok(200) }; - // Says what the internet is FOR here — signing in — because the one time this screen - // appears with the link deliberately down is the first boot of a set that has never - // signed in. Drawn as the reason under "Couldn't sign in" (`screens/login.rs`). - output_failed(output, - epoch, - plx_platform::i18n::msg::browse_auth_plex_unreachable(), - IncidentContext::new(IncidentKind::PinCreate, Some(last)) - .with_link_state(0, None, generation), - None, - ); - return None; - } - }; - // **The lease starts HERE, not where the polling does.** plex.tv began counting the moment it - // answered, and the QR fetch below is another request on `net::API`'s 25 s deadline — so a - // clock started after it would let the poll run that much past the code's real death, which is - // the same over-run in miniature that this whole change is about. - let minted = Instant::now(); - // Neither the id nor the code may be logged. `GET /api/v2/pins/{id}` is what RETURNS the - // account token once the user authorizes (plex/account.rs `poll_pin`), so the id is a handle - // that redeems a credential, and the code is what authorizes it — and this file is the one we - // ask users to send us when something goes wrong. Log that we got here, not what we got. - log(&format!( - "auth: pin created (code {generation} of {MAX_PIN_GENERATIONS}, {}s to authorize)", - pin_window(pin.expires_in).as_secs() - )); - // fetch the server-rendered QR PNG (the exact QR the official apps display); public, no token. - let qr_url = if pin.qr.is_empty() { - format!("{}/api/v2/pins/qr/{}", plx_plex::plex::account::plex_tv(), pin.code) - } else { - pin.qr.clone() - }; - if !output.live() { return None; } - let qr_png = plx_net::net::https_get_public(&qr_url) - .filter(|r| r.ok()) - .map(|r| r.body) - .unwrap_or_default(); - log(&format!("auth: qr png {} bytes", qr_png.len())); - // Same liveness-only check as above, and the same reason: no point publishing a code the flow - // this worker belongs to no longer exists to show. The owner's checked QR allocator runs - // only on accepted CodeReady, not here on the producer. - if !output.live() { - return None; - } - if !output.progress(LoginProgress::CodeReady { - epoch, - code: pin.code.clone(), - qr_png, - }.into()) { return None; } - Some(MintedCode { - id: pin.id, - expires_in: pin.expires_in, - minted, - }) -} + /// What [`login_thread`] needs to know about the code it just put on screen: the handle to poll, /// how long plex.tv will honour it, and **when that clock started**. @@ -1266,41 +1175,7 @@ struct MintedCode { /// Finish a successful discovery. Shared by the QR flow and the discovery-only Retry path. /// /// `server`/`sources` are discovery's own result, passed directly rather than reread from Session. -fn finish_sign_in(ac: &AccountClient, epoch: u64, server: ServerRef, sources: Vec, - output: &dyn owner::ObservationSink) { - if !output.live() { return; } - // Discovery already queued its activation observations before this SignedIn observation. - // Only owner-accepted resource effects install clients; the historical "installed" log - // label below describes the observed result, not proof of main-thread commit completion. - // `log_form`, not `base()`: byte-identical to the `{addr}:{port}` this line always printed - // for a plaintext origin (so an archived log stays comparable), and the whole URL as soon as - // the scheme is worth saying. See `Origin::log_form`. - log(&format!( - "auth: PMS client installed {}", - server.origin().log_form() - )); - // 4) Plex Home roster → who's-watching, or straight in if there's a single user. The roster is - // kept on the session so it persists with the creds — the boot picker and every later - // "Change profile" render from it instantly, online or not. - // - // A failed fetch still signs in (as a single user) and persists an empty roster, which the - // session reads as "unknown" (`Session::account`) — but it now says WHY in the log, in the - // same grading the Change-profile refresh uses, rather than a bare `n=0`. - let mut clock = LiveRetryClock { output, started: Instant::now() }; - let Some(users) = sign_in_home_users_with_clock(ac, epoch, output, &mut clock, - |ac, remaining| ac.home_users_with(account_timeouts(remaining))) else { return }; - log(&format!("auth: home users n={}", users.len())); - // One observation carrying everything the owner needs to commit the session at once — - // see [`LoginProgress::SignedIn`] for why this used to be three separate `with_ctl` writes and - // is now one. - output.terminal(LoginProgress::SignedIn { - epoch, - server, - sources, - users, - }.into()); -} fn sign_in_home_users_with_clock(ac: &AccountClient, epoch: u64, output: &dyn owner::ObservationSink, clock: &mut impl RetryClock, @@ -1463,12 +1338,12 @@ fn retry_account_call(policy: AccountRetryPolicy, clock: &mut impl RetryClock let mut attempts = 0u32; loop { attempts = attempts.saturating_add(1); - let remaining = policy.budget.saturating_sub(clock.elapsed()); + let remaining = policy.budget.saturating_sub(RetryClock::elapsed(clock)); match call(remaining) { Ok(value) => return Retried { result: AccountCallEnd::Answer(value), attempts, - elapsed: clock.elapsed() }, + elapsed: RetryClock::elapsed(clock) }, Err(evidence) => { - let elapsed = clock.elapsed(); + let elapsed = RetryClock::elapsed(clock); on_miss(attempts, elapsed, evidence); let status = match evidence { Ok(status) => Some(status), Err(f) => f.status }; let can_retry = plx_plex::plex::account::transient(&evidence) @@ -1483,7 +1358,7 @@ fn retry_account_call(policy: AccountRetryPolicy, clock: &mut impl RetryClock .min(policy.budget.saturating_sub(elapsed)); if !clock.wait(pause) { return Retried { result: AccountCallEnd::Cancelled, attempts, - elapsed: clock.elapsed() }; + elapsed: RetryClock::elapsed(clock) }; } } } @@ -1506,35 +1381,13 @@ fn account_timeouts(remaining: Duration) -> plx_net::net::Timeouts { ..plx_net::net::API } } -fn cancellable_wait_while(duration: Duration, live: impl Fn() -> bool) -> bool { - const SLICE: Duration = Duration::from_secs(1); - let deadline = Instant::now() + duration; - loop { - if !live() { return false; } - let now = Instant::now(); - if now >= deadline { return true; } - std::thread::sleep((deadline - now).min(SLICE)); - } -} -struct LiveRetryClock<'a> { - output: &'a dyn owner::ObservationSink, - started: Instant, -} -impl RetryClock for LiveRetryClock<'_> { - fn elapsed(&self) -> Duration { self.started.elapsed() } - fn wait(&mut self, duration: Duration) -> bool { - cancellable_wait_while(duration, || self.output.live()) - } -} -struct LiveFnClock<'a> { live: &'a dyn Fn() -> bool, started: Instant } -impl RetryClock for LiveFnClock<'_> { - fn elapsed(&self) -> Duration { self.started.elapsed() } - fn wait(&mut self, duration: Duration) -> bool { - cancellable_wait_while(duration, self.live) - } -} + + + + + /// Everything [`poll_for_token`] needs from the world: one network answer, one interruptible /// wait, and a clock. @@ -1572,38 +1425,9 @@ struct Stall { } /// The real one: a live pin, the wall clock, and the flow's epoch. -struct LivePin<'a> { - ac: &'a AccountClient, - id: i64, - output: &'a dyn owner::ObservationSink, - started: Instant, - epoch: u64, - /// Which code of the flow this is, 1-based — the report's code generation. - generation: u32, -} -impl PinWatch for LivePin<'_> { - fn poll(&mut self) -> PinPoll { - scripted::signin_trouble_poll().unwrap_or_else(|| self.ac.poll_pin(self.id)) - } - fn wait(&mut self, d: Duration) -> bool { - // SLICED, so a cancel is noticed within a slice however far the backoff has grown. The - // worker's answer would be discarded anyway, but a thread that lingers for the whole of a - // 16 s backoff after the user has left the screen is a thread the next flow shares the - // device with. - cancellable_wait_while(d, || self.output.live()) - } - fn elapsed(&self) -> Duration { - self.started.elapsed() - } - fn link_trouble(&mut self, stall: Option) { - let trouble = stall.map(|s| { - IncidentContext::new(IncidentKind::LinkStalled, Some(s.last)) - .with_link_state(s.unanswered, Some(s.failing_for), self.generation) - }); - self.output.progress(LoginProgress::LinkTrouble { epoch: self.epoch, trouble }.into()); - } -} + + /// Poll `/pins/{id}` until the user authorizes, the code dies, or the flow is superseded. /// @@ -1630,7 +1454,7 @@ fn poll_for_token(w: &mut impl PinWatch, window: Duration) -> PollEnd { // expiry at 905s and throw away a token that was sitting there. So the pause is clamped to // what is left of the code, and the poll after it always happens. Only plex.tv gets to say // a pin is finished before we have asked it once more. - let pause = poll_delay(misses).min(window.saturating_sub(w.elapsed())); + let pause = poll_delay(misses).min(window.saturating_sub(PinWatch::elapsed(w))); if !w.wait(pause) { return PollEnd::Superseded; } @@ -1649,16 +1473,16 @@ fn poll_for_token(w: &mut impl PinWatch, window: Duration) -> PollEnd { } PinPoll::Gone => { log("auth: plex.tv no longer knows this sign-in code — expired or already used"); - return PollEnd::Expired(PollTail::at(w.elapsed(), misses, failing_since, last_seen)); + return PollEnd::Expired(PollTail::at(PinWatch::elapsed(w), misses, failing_since, last_seen)); } PinPoll::Unreachable(last) => { last_seen = Some(last); if misses == 0 { - failing_since = w.elapsed(); + failing_since = PinWatch::elapsed(w); } misses = misses.saturating_add(1); if misses == LINK_TROUBLE_AFTER { - let failing_for = w.elapsed().saturating_sub(failing_since); + let failing_for = PinWatch::elapsed(w).saturating_sub(failing_since); w.link_trouble(Some(Stall { unanswered: misses, failing_for, last })); } // Once when it starts, and rarely after, because this line is written every two @@ -1678,9 +1502,9 @@ fn poll_for_token(w: &mut impl PinWatch, window: Duration) -> PollEnd { // the replacement code by another 25 s. Every pause is clamped to what is left, so exactly // one poll can ever begin before the deadline and finish after it, and that one is always // allowed to answer. - if w.elapsed() >= window { + if PinWatch::elapsed(w) >= window { log("auth: the sign-in code reached the end of its life unused"); - return PollEnd::Expired(PollTail::at(w.elapsed(), misses, failing_since, last_seen)); + return PollEnd::Expired(PollTail::at(PinWatch::elapsed(w), misses, failing_since, last_seen)); } } } @@ -2156,12 +1980,7 @@ impl AdmissionBudget { fn exhausted(&self) -> bool { self.remaining.is_zero() } - fn attempt( - &mut self, - request: impl FnOnce(Instant) -> plx_plex::plex::EndpointAdmission, - ) -> plx_plex::plex::EndpointAdmission { - self.attempt_on(Instant::now, request) - } + /// [`Self::attempt`] reading time from `now`. The profile worker passes /// [`ProfileWorkIo::admission_clock`], so a host test can spend request time without sleeping. @@ -2404,217 +2223,7 @@ fn race_decided( /// exhaustion. Only a successful spawn creates a pending entry. Each entry owns an absolute /// deadline; expiring one local worker never settles a still-live remote worker. Direct and relay /// are separate phases, so each phase receives the full per-candidate budget appropriate to it. -fn race_batch( - plan: &ProbePlan, - indices: &[usize], - dial: ProbeDial, - spawn: &dyn Fn(usize, ProbeJob) -> bool, - policy: ProbeDeadlines, - activate: &mut dyn FnMut(&ProbePlan, &Candidate, &Origin), -) -> BatchResult { - let (tx, rx) = mpsc::channel::(); - let mut pending = vec![None; plan.candidates.len()]; - let mut live = 0usize; - for &index in indices { - let c = &plan.candidates[index]; - let Some(origin) = dial_target(c) else { - continue; - }; - let started = Instant::now(); - let budget = probe_deadline(c, policy); - let deadline = started + budget; - let state = Arc::new(AtomicU8::new(PROBE_PENDING)); - let tx = tx.clone(); - let dial = Arc::clone(&dial); - let worker_state = Arc::clone(&state); - let machine_id = plan.machine_id.clone(); - // Built here, at the dial that decides a winner — not only at `apply_candidate_activation`, - // which pins the same way after one already has. `None` for a plaintext candidate (a pin - // belongs to a TLS name only) or an unmatched/undecodable label; the request then resolves - // through DNS exactly as before. - let pin = plx_plex::plex::ResolvePin::for_origin(&origin, &c.address); - let location = c.location; - let job = Box::new(move || { - let reply = dial(&origin, pin.as_ref(), budget); - let untrusted = reply.untrusted(); - let (outcome, route) = reply.grade_learning(&machine_id, location); - let on_time = Instant::now() <= deadline; - // Claim completion before publishing the message. If the coordinator expires first, - // this result is inert. If this claim wins and the worker is descheduled before send, - // the coordinator sees COMPLETED and waits for the already-decided result rather than - // erasing it on its own later wall-clock sample. - if worker_state - .compare_exchange( - PROBE_PENDING, - PROBE_COMPLETED, - Ordering::AcqRel, - Ordering::Acquire, - ) - .is_ok() - { - let _ = tx.send(ProbeMessage { - index, - on_time, - outcome, - route, - untrusted, - }); - } - }); - if spawn(index, job) { - pending[index] = Some(PendingProbe { deadline, state }); - live += 1; - } - } - // Only worker-held senders remain. If one panics (or an injected spawner accepts then drops its - // job), disconnect settles the remaining pending set instead of parking the coordinator. - drop(tx); - - let mut result = BatchResult { - observed: vec![None; plan.candidates.len()], - ..BatchResult::default() - }; - let mut first_win: Option = None; - while live > 0 { - // Drain results that completed on time BEFORE expiring by the coordinator's current clock. - // Spawn setup and queue backlog are allowed to delay observation; `finished` is the fact - // that decides whether the candidate met its own absolute deadline. - loop { - match rx.try_recv() { - Ok(message) => settle_probe_message( - plan, - message, - &mut pending, - &mut live, - &mut result, - activate, - ), - Err(mpsc::TryRecvError::Empty) => break, - Err(mpsc::TryRecvError::Disconnected) => { - if live > 0 { - live = 0; - pending.fill(None); - } - break; - } - } - } - if live == 0 { - break; - } - let now = Instant::now(); - for &index in indices { - let expired = pending[index].as_ref().is_some_and(|p| { - p.deadline <= now - && p.state - .compare_exchange( - PROBE_PENDING, - PROBE_EXPIRED, - Ordering::AcqRel, - Ordering::Acquire, - ) - .is_ok() - }); - if expired { - pending[index] = None; - live -= 1; - result.observed[index] = Some(RouteOutcome::Timeout); - let c = &plan.candidates[index]; - log(&format!( - "auth: '{}' probe timed out at {}:{}", - plan.name, c.address, c.port - )); - } - } - if live == 0 { - break; - } - if first_win.is_none() && result.first.is_some() { - first_win = Some(Instant::now()); - } - // A candidate whose worker already claimed completion owes a message that is about to - // land, so it is never skipped; only one still dialling can be left behind. - let undecided: Vec = indices - .iter() - .copied() - .filter(|&i| { - pending[i] - .as_ref() - .is_some_and(|p| p.state.load(Ordering::Acquire) == PROBE_PENDING) - }) - .collect(); - if undecided.len() == live - && race_decided( - plan, - &undecided, - result.best.as_ref(), - first_win.map(|at| at.elapsed()), - policy.grace, - ) - { - let mut left_behind = 0usize; - for &index in &undecided { - if let Some(p) = pending[index].take() { - if p - .state - .compare_exchange( - PROBE_PENDING, - PROBE_EXPIRED, - Ordering::AcqRel, - Ordering::Acquire, - ) - .is_ok() - { - left_behind += 1; - } - } - } - if left_behind > 0 { - log(&format!( - "auth: '{}' settled on its first verified route; {left_behind} slower or lower-ranked address(es) not waited for", - plan.name - )); - } - break; - } - let next = indices - .iter() - .filter_map(|&i| pending[i].as_ref()) - .filter(|p| p.state.load(Ordering::Acquire) == PROBE_PENDING) - .map(|p| p.deadline) - // Wake for the end of the grace too, but only while it is still ahead: a past one - // would turn the wait below into a zero-timeout spin. - .chain(first_win.map(|at| at + policy.grace).filter(|end| *end > Instant::now())) - .min(); - let received = match next { - Some(next) => rx.recv_timeout(next.saturating_duration_since(Instant::now())), - // Every live worker has already claimed completion and owes exactly one message. - // Blocking here avoids a zero-timeout spin in the tiny claim-before-send window. - None => rx.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected), - }; - match received { - Ok(message) => settle_probe_message( - plan, - message, - &mut pending, - &mut live, - &mut result, - activate, - ), - Err(mpsc::RecvTimeoutError::Timeout) => {} - Err(mpsc::RecvTimeoutError::Disconnected) => { - // Every sender is gone, so no pending candidate can ever report. This includes a - // worker panic and an injected accepted-but-dropped job. - live = 0; - for slot in pending.iter_mut() { - *slot = None; - } - } - } - } - result -} /// Parallel within one server, with relay held out until every direct candidate has settled. /// The coordinator alone activates: first usable immediately, then at most one re-point to the @@ -3483,13 +3092,7 @@ fn discover_and_store(ac: &AccountClient, client_id: &str, epoch: u64, trigger: /// Injectable account edge for discovery. Production supplies [`AccountClient::resources`]; the /// seam keeps retry policy host-testable without putting a socket behind an auth worker test. -fn discover_and_store_with_resources(ac: &AccountClient, client_id: &str, epoch: u64, - trigger: DiscoveryTrigger, ask: &PlaintextAsk, output: &dyn owner::ObservationSink, - resources_call: impl FnMut(&AccountClient, Duration) -> Result, CallEvidence>) -> Discovery { - let mut clock = LiveRetryClock { output, started: Instant::now() }; - discover_and_store_with_resources_and_clock(ac, client_id, epoch, trigger, ask, output, - &mut clock, resources_call) -} + fn discover_and_store_with_resources_and_clock(ac: &AccountClient, client_id: &str, epoch: u64, trigger: DiscoveryTrigger, ask: &PlaintextAsk, output: &dyn owner::ObservationSink, @@ -3782,86 +3385,7 @@ fn reconcile_refresh_session( changed } -fn server_roster_worker_with_output(sess: Session, epoch: u64, expected: SessionIdentity, - household: Vec, ask: &PlaintextAsk, output: &dyn owner::ObservationSink) { - if !output.live() { return; } - let ac = AccountClient::new(&sess.client_id, Some(&sess.account_token)); - let mut clock = LiveRetryClock { output, started: Instant::now() }; - let run = retry_account_call(BACKGROUND_ACCOUNT, &mut clock, |_, _, _| {}, - |remaining| ac.resources_with(account_timeouts(remaining))); - let resources = match run.result { - AccountCallEnd::Answer(resources) => resources, - AccountCallEnd::Cancelled => return, - AccountCallEnd::Failed(evidence) => { - log(&format!("auth: server roster refresh could not list resources ({})", - plx_plex::plex::account::describe_evidence(&evidence))); - output.terminal(AuthProgress::ServerRoster(ServerRosterProgress { - epoch, - expected, - outcome: ServerRosterOutcome::Unreachable, - })); - return; - } - }; - let mut activate = |plan: &ProbePlan, c: &Candidate, origin: &Origin| { - let credit = credit_for_machine(&resources, &plan.machine_id, &household); - let evidence = evidence_for_machine(&resources, &plan.machine_id); - output.progress(AuthProgress::Registry(RegistryProgress::Activate { - epoch, - expected: Some(expected.clone()), - candidate: candidate_activation(plan, c, origin, &credit, evidence), - })); - }; - let mut settled = Vec::new(); - // Unlike `activate` above, this does NOT also `output.progress(RegistryProgress::Settled)` - // per server as the race runs. It used to, and the owner committed BOTH: the live progress - // arm (`Observation::Registry` in `owner.rs`) planned one `RegistryPlan::Probe` per server as - // it settled, and the terminal `ServerRosterOutcome` below planned the identical set again - // through `settled`/`roster_plan` — every probe this worker ever runs was published twice. - // This worker is a BACKGROUND refresh (`refresh_roster`) with no live race screen watching - // it — unlike `discover_and_store`'s sign-in flow, which really does drive a Sources/QR - // screen off `RegistryProgress::Activate` while candidates settle, and keeps publishing both - // — so there is nothing here for the extra progress arrival to reach before the terminal - // commit does the same work. `settled` alone, folded into the terminal outcome, is authoritative. - let resolution = resolve_roster_live_while( - &resources, - &household, - &sess.client_id, - ask, - &mut activate, - &mut |plan, verdict| { - settled.push(settled_probe_of(plan, verdict)); - }, - &|| output.live(), - ); - let found = match resolution.outcome { - Resolved::Reached(found) => found, - _ => { - // R2/A5: a background refresh that found nothing to REGISTER may still have PROBED - // something worth recording — carry it rather than throwing `settled` away, so the - // owner can commit it as a registry-only `RegistryPlan::Probe` (`owner.rs`). - output.terminal(AuthProgress::ServerRoster(ServerRosterProgress { - epoch, - expected, - outcome: ServerRosterOutcome::NoReachable { settled }, - })); - return; - } - }; - let admitted_machine_id = resolution.admitted_machine_id - .expect("a reached roster has one authenticated primary"); - output.terminal(AuthProgress::ServerRoster(ServerRosterProgress { - epoch, - expected, - outcome: ServerRosterOutcome::Reconcile { - resources, - found, - admitted_machine_id, - household, - settled, - }, - })); -} + /// Replace only the route facts of one already-granted source. /// @@ -3906,49 +3430,7 @@ fn apply_refreshed_endpoint( Some((next, changed)) } -fn probe_endpoint_work( - id: ServerId, - machine_id: &str, - sess: &Session, - mut resources: impl FnMut(&AccountClient, Duration) -> Result, CallEvidence>, - probe: impl FnOnce(&Resource, &[i64]) -> (Option, SettledProbe), - live: &dyn Fn() -> bool, -) -> (Option, Option) { - // Nothing was actually probed on any of the early exits below — plex.tv never answered, or - // this machine is no longer among its resources — so there is no verdict to report at all: - // fabricating `Unreachable` here would widen a real, more specific probe result - // (`InsecureOnly`/`Unauthorized`) into "Not reachable" once it reached the registry. - if !live() { return (None, None); } - let ac = AccountClient::new(&sess.client_id, Some(&sess.account_token)); - let mut clock = LiveFnClock { live, started: Instant::now() }; - let run = retry_account_call(BACKGROUND_ACCOUNT, &mut clock, |_, _, _| {}, - |remaining| resources(&ac, remaining)); - let resources = match run.result { - AccountCallEnd::Answer(resources) => resources, - AccountCallEnd::Cancelled => return (None, None), - AccountCallEnd::Failed(evidence) => { - log(&format!( - "auth: endpoint refresh for source {} could not list resources ({})", - id.raw(), - plx_plex::plex::account::describe_evidence(&evidence) - )); - return (None, None); - } - }; - let Some(resource) = resources - .iter() - .find(|resource| resource.is_server() && resource.client_identifier == machine_id) - else { - log(&format!( - "auth: endpoint refresh for source {} found no matching resource", - id.raw() - )); - return (None, None); - }; - if !live() { return (None, None); } - let (fresh, probe) = probe(resource, &sess.household_ids()); - (fresh, Some(probe)) -} + /// Point the persisted PRIMARY at wherever the refreshed roster says that machine now answers. /// Returns whether anything moved, so the caller knows the save is owed. @@ -4310,7 +3792,7 @@ pub trait ProfileWorkIo { } fn admission_budget(&self) -> Duration { ADMISSION_BUDGET } /// The clock the admission budget is charged against. Only a host test replaces it. - fn admission_clock(&self) -> fn() -> Instant { Instant::now } + fn admission_clock(&self) -> fn() -> Instant { ports::admission_clock() } fn gap(&mut self); } @@ -4404,321 +3886,7 @@ pub fn profile_switch_worker_with_output( output, &mut LiveProfileWorkIo { switch: Some(switch), ask: ask.clone() }); } -pub fn profile_switch_worker_with_io( - epoch: u64, - expected: SessionIdentity, - stored: Session, - tile: UserTile, - pin: Option, - recently_unreachable: bool, - output: &dyn owner::ObservationSink, - io: &mut impl ProfileWorkIo, -) { - if !output.live() { return; } - let cid = stored.client_id.clone(); - let account_token = stored.account_token.clone(); - let ac = AccountClient::new(&cid, Some(&account_token)); - let cache_first = stored.cached_profile(&tile.uuid).is_some() && recently_unreachable; - let outcome = if cache_first { - log("auth: switch — plex.tv was unreachable moments ago, trying the cached credentials first"); - SwitchOutcome::Unreachable - } else { - io.switch(&ac, &tile.uuid, pin.as_deref()) - }; - let user = match outcome { - SwitchOutcome::Switched(user) => user, - SwitchOutcome::Refused(status) => { - log(&format!( - "auth: switch '{}' -> refused (HTTP {status})", - tile.title - )); - let (error, pin_denied) = switch_failure(pin.is_some()); - output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { - epoch, - expected, - outcome: ProfileSwitchOutcomeProgress::Failed { error, pin_denied }, - })); - return; - } - SwitchOutcome::Unreachable => { - let outcome = offline_switch_outcome(&stored, &tile, pin.as_deref()); - output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { - epoch, - expected, - outcome, - })); - return; - } - }; - if !output.live() { return; } - let profile_account = AccountClient::new(&cid, Some(&user.auth_token)); - let mut clock = LiveRetryClock { output, started: Instant::now() }; - let run = retry_account_call(PROFILE_SWITCH_ACCOUNT, &mut clock, |_, _, _| {}, - |_| io.resources(&profile_account)); - let resources = match run.result { - AccountCallEnd::Answer(resources) => resources, - AccountCallEnd::Cancelled => return, - AccountCallEnd::Failed(evidence) => { - log(&format!("auth: profile resources request failed ({})", - plx_plex::plex::account::describe_evidence(&evidence))); - // A refusal is an answer, not a dead link: "check the connection" would send the - // person to a router that is fine. The PIN was already accepted by this point, so - // this is never the PIN flash either. - let error = if plx_plex::plex::account::refused_identity(&evidence).is_some() { - plx_platform::i18n::msg::browse_auth_profile_signin_refused(&tile.title) - } else { - plx_platform::i18n::msg::browse_auth_switch_failed().into() - }; - output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { - epoch, - expected, - outcome: ProfileSwitchOutcomeProgress::Failed { - error, - pin_denied: false, - }, - })); - return; - } - }; - let grants = ordered_profile_grants(&resources); - if grants.is_empty() { - output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { - epoch, - expected, - outcome: ProfileSwitchOutcomeProgress::Failed { - error: plx_platform::i18n::msg::browse_auth_no_access(&tile.title), - pin_denied: false, - }, - })); - return; - } - - let household = stored.household_ids(); - let mut admission_budget = AdmissionBudget::new(io.admission_budget()); - let admission_clock = io.admission_clock(); - let mut order = grants.clone(); - if let Some(pos) = order - .iter() - .position(|&i| resources[i].client_identifier == stored.server.machine_id) - { - order.swap(0, pos); - } - let mut reached = Vec::new(); - let mut probes: Vec = Vec::new(); - let mut probed = vec![false; resources.len()]; - let mut admission_failures = Vec::new(); - let mut selected_mid = None; - for &i in &order { - probed[i] = true; - let mut rejected_origins = Vec::new(); - loop { - if !output.live() { return; } - let (mut winner, mut settled) = - io.probe_after(&resources[i], &household, &rejected_origins); - if !output.live() { return; } - if winner.is_none() { - if let Some(cached) = stored.sources.iter() - .find(|source| source.machine_id == resources[i].client_identifier) { - if let Some((cached_winner, cached_settled)) = - io.probe_cached(&resources[i], cached, &household, &rejected_origins) { - winner = cached_winner; - settled = cached_settled.after_fresh(&settled); - } - } - } - if !output.live() { return; } - if let Some(previous) = probes.iter_mut() - .find(|probe| probe.machine_id == resources[i].client_identifier) { - if previous.outcome != Outcome::Reachable || settled.outcome == Outcome::Reachable { - *previous = settled; - } - } else { - probes.push(settled); - } - let Some(winner) = winner else { break }; - let origin = winner.origin_url.clone(); - if rejected_origins.contains(&origin) { break; } - let admission = admission_budget.attempt_on(admission_clock, |deadline| - io.admit_until(&winner, &cid, deadline)); - if admission == plx_plex::plex::EndpointAdmission::Usable { - selected_mid = Some(winner.machine_id.clone()); - reached.push(winner); - break; - } - log(&format!("auth: switch '{}' — {:?} did not admit this profile ({admission:?})", - tile.title, resources[i].name)); - admission_failures.push((resources[i].name.clone(), admission)); - if admission_budget.exhausted() { break; } - rejected_origins.push(origin); - } - if selected_mid.is_some() { - break; - } - } - let cached_sources = profile_sources(&stored.sources, &reached, &resources, &household); - let initial = cached_sources.clone(); - let Some(primary) = - selected_mid.and_then(|mid| initial.iter().find(|s| s.machine_id == mid).cloned()) - else { - // S7: a grant that verified but only over plaintext is not the same failure as "you were - // never given this server" — it names a fixable cause (HTTPS to the server), and the - // ordinary copy sends the user to ask their friend for access they already have. - let insecure_only = probes.iter().any(|p| p.outcome == Outcome::InsecureOnly) - || admission_failures.iter().any(|(_, evidence)| - *evidence == plx_plex::plex::EndpointAdmission::InsecureOnly); - let refusal = admission_failures.iter().find_map(|(name, evidence)| match evidence { - plx_plex::plex::EndpointAdmission::Refused(status) => Some((name, *status)), - _ => None, - }); - let malformed = admission_failures.iter().any(|(_, evidence)| - *evidence == plx_plex::plex::EndpointAdmission::Malformed); - // Why each server that no route verified could not be used. A probe that verified (and was - // then refused at admission, or only over plaintext) is not in here: the arms above own it. - let mut causes = FailureCauses::default(); - for probe in &probes { - if let Some(cause) = probe.cause() { causes.push(&probe.machine_id, cause); } - } - let probe_cause = causes.worst(); - log(&format!( - "auth: switch '{}' -> {}", - tile.title, - if insecure_only { "verified only over plaintext" } - else if refusal.is_some() { "server refused the profile credential" } - else if malformed { "server returned a malformed authenticated response" } - else if !admission_failures.is_empty() { "no server admitted the profile" } - else { match probe_cause { - Some(Cause::TlsUntrusted { .. }) => "a server's certificate is not trusted by this TV", - Some(Cause::Unauthorized) => "no server access", - Some(Cause::Unreachable) | None => "no server answered", - } }, - )); - if !(insecure_only || refusal.is_some() || malformed || !admission_failures.is_empty()) { - log(&causes.log_line()); - } - output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { - epoch, - expected, - outcome: ProfileSwitchOutcomeProgress::Failed { - error: if insecure_only { - discovery_insecure_only_message().to_owned() - } else if let Some((name, _)) = refusal { - plx_platform::i18n::msg::browse_auth_server_profile_refused(&tile.title, &name) - } else if malformed { - plx_platform::i18n::msg::browse_auth_switch_invalid().into() - } else if !admission_failures.is_empty() { - plx_platform::i18n::msg::browse_auth_switch_failed().into() - } else { - // Closed precedence, strongest first: a certificate this TV does not trust (the - // person can fix it by updating), a 401 (the profile has no grant — the ONLY - // case `no_source_access` is true of), then silence. A probe that left no cause at - // all cannot occur once a server was probed; it reads as silence, never as a refusal. - match probe_cause { - Some(Cause::TlsUntrusted { .. }) => plx_platform::i18n::msg::browse_auth_tls_untrusted().into(), - Some(Cause::Unauthorized) => plx_platform::i18n::msg::browse_auth_no_source_access(&tile.title), - Some(Cause::Unreachable) | None => plx_platform::i18n::msg::browse_auth_servers_unreachable().into(), - } - }, - pin_denied: false, - }, - })); - return; - }; - - log(&format!( - "auth: switch '{}' -> ok (per-user server token)", - tile.title - )); - let server = server_ref(&primary); - let plex_tv_token = (!user.auth_token.is_empty()).then(|| user.auth_token.clone()); - let user = UserRef { - id: user.id, - uuid: seated_uuid(&user, &tile), - title: user.title, - thumb: tile.thumb, - token: primary.token.clone(), - plex_tv_token, - extensions: Default::default(), - }; - if !output.live() { return; } - // Carry forward whatever this uuid's PRIOR seating cached in `extensions` — the serde-flatten - // catch-all for fields this build does not model (forward compatibility with a newer build - // that wrote this session). `remember_profile` below replaces that uuid's whole cache entry, - // so building a fresh one with `Default::default()` here silently erased it (Copilot review on - // PR #105, finding 3). - let carried_extensions = stored - .profiles - .iter() - .find(|p| p.uuid == user.uuid) - .map(|p| p.extensions.clone()) - .unwrap_or_default(); - let cache = ProfileCreds { - uuid: user.uuid.clone(), - user: user.clone(), - server: server.clone(), - sources: cached_sources, - pin: pin - .as_deref() - .filter(|value| !value.is_empty()) - .map(session::PinVerifier::new), - extensions: carried_extensions, - }; - let next_identity = SessionIdentity { - client_id: expected.client_id.clone(), - account_token: expected.account_token.clone(), - profile_uuid: user.uuid.clone(), - }; - if !output.progress(AuthProgress::ProfileSwitch(ProfileSwitchProgress { - epoch, - expected, - outcome: ProfileSwitchOutcomeProgress::Ready { - delta: ProfileDelta { - server, - sources: initial, - user, - cache: Some(cache), - }, - probes: probes.clone(), - }, - })) { return; } - for &i in &grants { - if probed[i] { - continue; - } - if !output.live() { return; } - io.gap(); - if !output.live() { return; } - let (mut winner, mut settled) = io.probe_after(&resources[i], &household, &[]); - if !output.live() { return; } - if winner.is_none() { - if let Some(cached) = stored.sources.iter() - .find(|source| source.machine_id == resources[i].client_identifier) { - if let Some((cached_winner, cached_settled)) = - io.probe_cached(&resources[i], cached, &household, &[]) { - winner = cached_winner; - settled = cached_settled.after_fresh(&settled); - } - } - } - if !output.live() { return; } - if let Some(previous) = probes.iter_mut() - .find(|probe| probe.machine_id == resources[i].client_identifier) { - if previous.outcome != Outcome::Reachable || settled.outcome == Outcome::Reachable { - *previous = settled; - } - } else { - probes.push(settled); - } - if let Some(winner) = winner { reached.push(winner); } - } - output.terminal(AuthProgress::ProfileRoster(ProfileRosterProgress { - epoch, - expected: next_identity, - resources, - reached, - probes, - })); -} // ---- helpers ---- diff --git a/rust-modules/session/src/auth/owner.rs b/rust-modules/session/src/auth/owner.rs index ae119c35b8..4f9b354804 100644 --- a/rust-modules/session/src/auth/owner.rs +++ b/rust-modules/session/src/auth/owner.rs @@ -1,5 +1,6 @@ //! Concrete auth decisions and immutable publications. Resource operations belong to the //! application adapter; constructing or observing this value performs no external work. +#![deny(clippy::wildcard_enum_match_arm)] use super::{Phase, Picker, UserTile}; use plx_plex::plex::session::async_persistence::{PersistencePurpose, RejectionKind}; @@ -9,8 +10,11 @@ use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; use plx_machine::machine::{Addr, Canon, LogicalState, MachineId}; +mod attempt; mod incident; -use plx_telemetry::telemetry::incident::{IncidentContext, InternalClass}; +use plx_telemetry::telemetry::incident::{IncidentContext, InternalClass, IncidentKind}; +use plx_telemetry::telemetry::consent::Permission; +use incident::{is_settled, SEEN_CAP}; pub use incident::{IncidentDelivery, IncidentFlow, IncidentKey, IncidentLane, IncidentOffer, IncidentReport, IncidentState}; @@ -338,10 +342,42 @@ pub struct CommitPlan { pub authority: plx_plex::plex::session::SaveAuthority, } +#[derive(Clone, Copy, Default)] +enum CommitDestination { + #[default] + Unchanged, + Roster, + ReadyCommitted, + SignInProfiles, + SignInReady, + ProfileReady, + StoredReady, +} + +impl CommitDestination { + // The legacy patch is decoded once, at the compatibility boundary, never by a live transition. + fn from_init(delta: &CommitDelta) -> Self { + match delta.phase { + Some(Phase::Profiles) => Self::SignInProfiles, + Some(Phase::Ready) if delta.profile_seated => Self::ProfileReady, + Some(Phase::Ready) if delta.complete_signin => Self::SignInReady, + Some(Phase::Ready) => Self::StoredReady, + Some(Phase::Idle | Phase::Creating | Phase::Waiting | Phase::Discovering + | Phase::Switching | Phase::Error | Phase::Deleted) | None => { + if delta.ready == Some(false) { Self::ReadyCommitted } + else if delta.users.is_some() { Self::Roster } + else { Self::Unchanged } + } + } + } +} + /// Only the changes whose side effects are awaiting acknowledgement. This is not a second /// controller snapshot: unchanged fields remain solely in SessionInit. #[derive(Clone, Default, Serialize, Deserialize)] pub struct CommitDelta { + #[serde(skip)] + destination: CommitDestination, pub dev: Option, pub credentials: Option, pub phase: Option, @@ -456,7 +492,7 @@ impl CommitAdmission { pub fn admitted_revision(self) -> Option { match self { Self::Admitted { revision, .. } => Some(revision), - _ => None, + Self::StaleAuthority | Self::RegistryOnly | Self::Rejected { .. } => None, } } /// The purpose storage was actually asked to write for. This is the authoritative purpose for @@ -465,7 +501,7 @@ impl CommitAdmission { pub fn admitted_purpose(self) -> Option { match self { Self::Admitted { purpose, .. } => Some(purpose), - _ => None, + Self::StaleAuthority | Self::RegistryOnly | Self::Rejected { .. } => None, } } } @@ -594,6 +630,16 @@ pub trait SessionHost: plx_machine::machine::Host { } pub enum SessionEvent { + /// Consume the aggregate dirty marker through the same owner-event boundary. + ConsumeLogicalDirty, + /// Legacy incident producers enter with closed evidence, never a mutable owner escape. + RaiseIncident { flow: IncidentFlow, context: IncidentContext }, + ForgetIncidents, + #[cfg(any(test, feature = "test-support"))] ReserveWork { op: SessionOp, lifecycle: Option }, + #[cfg(test)] RebuildPublication, + #[cfg(test)] RestartLogin { fresh_login: bool }, + #[cfg(test)] ObserveQr(SessionEnvelope), + #[cfg(test)] FailLogin { message: String, incident: Option }, Command(Command), Result(SessionEnvelope), Commit(CommitReply), @@ -800,7 +846,7 @@ pub struct SessionInit { /// measured by the screen. Personal data, so UI state ONLY: never serialized (a recording's /// initial state must not carry it), never hashed into [`Canon`] (it would reach a replay /// digest), never logged, never part of an incident. Set by a failed sign-in that carries one, - /// cleared by every other ending and by a new attempt; read through [`Self::readout_account`]. + /// cleared by every other ending and by a new attempt; read through the private account readout. #[serde(skip)] pub signin_account: Option, /// The identity plex.tv REFUSED a roster to while nothing was cached to switch from — the @@ -816,46 +862,6 @@ pub struct SessionInit { } impl SessionInit { - /// The picker is showing #132's read-out: nobody to offer, and a reason why. - fn roster_readout_up(&self) -> bool { - is_roster_readout(self.phase, &self.users, &self.error) - } - - /// Is the picker on screen one that has nobody to offer and is no longer waiting to? Then no - /// profile boundary can be crossed from it — nobody can be handed the remote — and BACK - /// resumes whatever session is behind it rather than stranding the person on Sign out - /// (#132). A picker with tiles, or with a roster request still in flight, is not this. - fn roster_dead_end(&self) -> bool { - self.phase == Phase::Profiles && self.users.is_empty() - && !self.pending.values().any(|pending| pending.key.op == SessionOp::HomeRoster) - } - - /// Whether BACK from a [dead end](Self::roster_dead_end) resumes a session inside the app: - /// the dev session it never left, or a stored one it can reach. Otherwise BACK is the root - /// press and the television takes the screen. - fn dead_end_resumes(&self) -> bool { - matches!(self.authority, BootstrapAuthority::DevPms { .. }) - || self.committed_credentials.merge_into(&self.persisted).can_go_local() - } - - /// [`SessionSnapshot::switch_refused`]: the identity a roster was refused to (with nothing - /// cached) is still the one in use. - /// The account name the failure read-out may print: only on the no-server read-out itself, so - /// a name left by an earlier failure can never sit under another reason. - fn readout_account(&self) -> Option<&str> { - self.signin_account.as_deref().filter(|_| self.phase == Phase::Error - && self.error == plx_platform::i18n::msg::browse_auth_no_servers()) - } - fn switch_refused(&self) -> bool { - self.switch_refused_for.as_ref().is_some_and(|id| id.matches(&self.persisted)) - } - - /// Put up #132's refused read-out and remember the verdict for this identity. - fn refuse_switch(&mut self) { - self.error = roster_refused().into(); - self.switch_refused_for = Some(Identity::of(&self.persisted)); - } - pub fn captured(persisted: PersistedSession) -> Self { let committed_credentials = CredentialPatch::of(&persisted); let disk_identity = Identity::of(&persisted); @@ -991,7 +997,94 @@ pub fn write_persisted(w: &mut Canon, s: &PersistedSession) { }); } -impl LogicalState for SessionInit { +/// Borrowed V5 logical fields. Omitted wire-only and private values are intentionally absent. +struct LegacyV5Projection<'a> { + disk_identity: &'a Identity, + authority: &'a BootstrapAuthority, + phase: Phase, + picker: Picker, + persisted: &'a PersistedSession, + committed_credentials: &'a CredentialPatch, + pin_code: &'a String, + qr_png: &'a Vec, + users: &'a Vec, + error: &'a String, + pin_denied: bool, + authorized_in_flow: bool, + signin_active: bool, + apply_pending: bool, + code_replaced: bool, + qr_gen: u64, + next_qr: u64, + epoch: u64, + next_req: u32, + delete_leftovers: usize, + profile_scope: ProfileScope, + active_profile: &'a Option, + pending: &'a BTreeMap, + persistence_purpose: Option, + commit_phase: &'a CommitPhase, + persistence_warning: &'a Option, + held_handoff: &'a Option, + persistence_warning_answered: bool, + pending_commit: &'a Option, + pending_erase: Option<(u64, bool)>, + pump_pending: bool, + inbox: &'a VecDeque, + incident: &'a Option, + incidents_seen: &'a Vec, + next_incident: u32, + link_trouble: bool, + switch_refused_for: &'a Option, + plaintext: &'a Option, + discovery_retry: Option, +} + +impl<'a> LegacyV5Projection<'a> { + fn from_init(init: &'a SessionInit) -> Self { + Self { + disk_identity: &init.disk_identity, + authority: &init.authority, + phase: init.phase, + picker: init.picker, + persisted: &init.persisted, + committed_credentials: &init.committed_credentials, + pin_code: &init.pin_code, + qr_png: &init.qr_png, + users: &init.users, + error: &init.error, + pin_denied: init.pin_denied, + authorized_in_flow: init.authorized_in_flow, + signin_active: init.signin_active, + apply_pending: init.apply_pending, + code_replaced: init.code_replaced, + qr_gen: init.qr_gen, + next_qr: init.next_qr, + epoch: init.epoch, + next_req: init.next_req, + delete_leftovers: init.delete_leftovers, + profile_scope: init.profile_scope, + active_profile: &init.active_profile, + pending: &init.pending, + persistence_purpose: init.persistence_purpose, + commit_phase: &init.commit_phase, + persistence_warning: &init.persistence_warning, + held_handoff: &init.held_handoff, + persistence_warning_answered: init.persistence_warning_answered, + pending_commit: &init.pending_commit, + pending_erase: init.pending_erase, + pump_pending: init.pump_pending, + inbox: &init.inbox, + incident: &init.incident, + incidents_seen: &init.incidents_seen, + next_incident: init.next_incident, + link_trouble: init.link_trouble, + switch_refused_for: &init.switch_refused_for, + plaintext: &init.plaintext, + discovery_retry: init.discovery_retry, + } + } + fn write(&self, w: &mut Canon) { w.str(&self.disk_identity.client_id).str(&self.disk_identity.account_token) .str(&self.disk_identity.profile_uuid); @@ -1008,9 +1101,9 @@ impl LogicalState for SessionInit { write_persisted(w, &self.persisted); write_persisted(w, &self.committed_credentials.merge_into(&PersistedSession::default())); w.str(&self.pin_code).seq(self.qr_png.len()); - for byte in &self.qr_png { w.u8(*byte); } + for byte in self.qr_png { w.u8(*byte); } w.seq(self.users.len()); - for user in &self.users { + for user in self.users { w.u64(user.id as u64).str(&user.uuid).str(&user.title).str(&user.thumb) .bool(user.protected).bool(user.admin); } @@ -1020,7 +1113,7 @@ impl LogicalState for SessionInit { .u64(self.delete_leftovers as u64).u32(self.profile_scope.0); w.option(self.active_profile.as_ref(), write_user); w.seq(self.pending.len()); - for (&req, pending) in &self.pending { + for (&req, pending) in self.pending { w.u32(req).u64(pending.key.epoch); write_op(w, pending.key.op); w.str(&pending.expected.client_id).str(&pending.expected.account_token) @@ -1092,10 +1185,10 @@ impl LogicalState for SessionInit { }); w.option(self.pending_erase, |w, (epoch, sign_in)| { w.u64(epoch).bool(sign_in); }); w.bool(self.pump_pending).seq(self.inbox.len()); - for envelope in &self.inbox { envelope.write(w); } + for envelope in self.inbox { envelope.write(w); } w.option(self.incident.as_ref(), incident::write_offer); w.seq(self.incidents_seen.len()); - for key in &self.incidents_seen { incident::write_key(w, key); } + for key in self.incidents_seen { incident::write_key(w, key); } w.u32(self.next_incident).bool(self.link_trouble); w.option(self.switch_refused_for.as_ref(), |w, id| { w.str(&id.client_id).str(&id.account_token).str(&id.profile_uuid); @@ -1111,6 +1204,10 @@ impl LogicalState for SessionInit { }).u32(retry.misses).u32(retry.elapsed_ms); } } +} + +impl LogicalState for SessionInit { + fn write(&self, w: &mut Canon) { LegacyV5Projection::from_init(self).write(w); } fn probe(&self, out: &mut String) { use std::fmt::Write; let _ = write!(out, "session phase={:?} requests={} scope={}", @@ -1119,8 +1216,8 @@ impl LogicalState for SessionInit { } impl LogicalState for SessionMachine { - fn write(&self, w: &mut Canon) { self.state.write(w); } - fn probe(&self, out: &mut String) { self.state.probe(out); } + fn write(&self, w: &mut Canon) { LegacyV5Projection::from_partition(self.view()).write(w); } + fn probe(&self, out: &mut String) { use std::fmt::Write; let p = LegacyV5Projection::from_partition(self.view()); let _ = write!(out, "session phase={:?} requests={} scope={}", p.phase, p.pending.len(), p.profile_scope.0); } } /// Derived UI facts only. Credentials and writable controller state are not part of the view. @@ -1204,32 +1301,36 @@ impl SessionSnapshot { pub fn roster_readout(&self) -> Option<&str> { is_roster_readout(self.phase, &self.users, &self.error).then_some(&*self.error) } - fn from_state(state: &SessionInit) -> Self { + fn from_state(state: attempt::PartitionView<'_>) -> Self { Self::from_state_counted(state, None, &mut |_| {}) } - fn matches_state(&self, state: &SessionInit) -> bool { + fn matches_state(&self, state: attempt::PartitionView<'_>) -> bool { + let partition = state; + let state = LegacyV5Projection::from_partition(partition); self.flow_epoch == state.epoch && self.phase == state.phase && self.qr_generation == state.qr_gen && &*self.code == state.pin_code.as_str() && &*self.png == state.qr_png.as_slice() && &*self.users == state.users.as_slice() && &*self.error == state.error.as_str() && &*self.seated == state.persisted.user.uuid.as_str() && self.code_replaced == state.code_replaced && self.pin_denied == state.pin_denied && self.scope == state.profile_scope && self.delete_leftovers == state.delete_leftovers - && self.persistence_warning == state.persistence_warning - && self.incident == state.incident && self.link_trouble == state.link_trouble + && self.persistence_warning == *state.persistence_warning + && self.incident == *state.incident && self.link_trouble == state.link_trouble && self.discovery_retry == state.discovery_retry - && self.plaintext == state.plaintext - && self.account.as_deref() == state.readout_account() - && self.switch_refused == state.switch_refused() - && self.readout_back_resumes == (state.roster_readout_up() && state.roster_dead_end() - && state.dead_end_resumes()) - && match (&self.profile, &state.active_profile) { + && self.plaintext == *state.plaintext + && self.account.as_deref() == partition.readout_account() + && self.switch_refused == partition.switch_refused() + && self.readout_back_resumes == (partition.roster_readout_up() && partition.roster_dead_end() + && partition.dead_end_resumes()) + && match (&self.profile, state.active_profile) { (None, None) => true, (Some(read), Some(profile)) => read.uuid == profile.uuid && read.title == profile.title && read.thumb == profile.thumb, _ => false, } } - fn from_state_counted(state: &SessionInit, previous: Option<&Self>, built: &mut impl FnMut(usize)) -> Self { + fn from_state_counted(state: attempt::PartitionView<'_>, previous: Option<&Self>, built: &mut impl FnMut(usize)) -> Self { + let partition = state; + let state = LegacyV5Projection::from_partition(partition); let code = previous.filter(|old| &*old.code == state.pin_code.as_str()) .map(|old| Arc::clone(&old.code)).unwrap_or_else(|| { built(0); Arc::from(state.pin_code.as_str()) @@ -1252,18 +1353,401 @@ impl SessionSnapshot { profile: state.active_profile.as_ref().map(|p| ProfileRead { uuid: p.uuid.clone(), title: p.title.clone(), thumb: p.thumb.clone(), }), scope: state.profile_scope, delete_leftovers: state.delete_leftovers, - persistence_warning: state.persistence_warning, incident: state.incident.clone(), + persistence_warning: *state.persistence_warning, incident: (*state.incident).clone(), link_trouble: state.link_trouble, discovery_retry: state.discovery_retry, - plaintext: state.plaintext.clone(), - account: state.readout_account().map(Arc::from), - switch_refused: state.switch_refused(), - readout_back_resumes: state.roster_readout_up() && state.roster_dead_end() - && state.dead_end_resumes() } + plaintext: (*state.plaintext).clone(), + account: partition.readout_account().map(Arc::from), + switch_refused: partition.switch_refused(), + readout_back_resumes: partition.roster_readout_up() && partition.roster_dead_end() + && partition.dead_end_resumes() } + } +} + +struct CancelBatch { + commit: Option<(u32, u64)>, + requests: Vec, + epoch: u64, +} + +struct ExitActions { + cancel: Option, + acknowledge: Vec, + coordinator: Option, +} + +enum ExitFx { + Idle(ExitActions), + Creating(ExitActions), + Waiting(ExitActions), + Discovering(ExitActions), + Profiles(ExitActions), + Switching(ExitActions), + Ready(ExitActions), + Error(ExitActions), + Deleted(ExitActions), + Erasing(ExitActions), +} + +impl ExitFx { + fn for_state(state: &attempt::Attempt, actions: ExitActions) -> Self { + match state { + attempt::Attempt::Idle(_) => Self::Idle(actions), + attempt::Attempt::Creating(_) => Self::Creating(actions), + attempt::Attempt::Waiting(_) => Self::Waiting(actions), + attempt::Attempt::Discovering(_) => Self::Discovering(actions), + attempt::Attempt::Profiles(_) => Self::Profiles(actions), + attempt::Attempt::Switching(_) => Self::Switching(actions), + attempt::Attempt::Ready(_) => Self::Ready(actions), + attempt::Attempt::Error(_) => Self::Error(actions), + attempt::Attempt::Deleted(_) => Self::Deleted(actions), + attempt::Attempt::Erasing(_) => Self::Erasing(actions), + } + } + fn attempt(state: attempt::PartitionView<'_>, event: &AttemptEvent) -> Self { + let coordinator = if !state.common.signin_notice.owed() { None } + else if matches!(event, AttemptEvent::LoginFailed { .. }) { Some(CoordinatorAction::SignInFailed { phase: state.attempt.phase() }) } + else if matches!(event, AttemptEvent::ResumeBack) { Some(CoordinatorAction::SignInCancelled) } + else if matches!(event, AttemptEvent::SigninProfiles { .. } | AttemptEvent::SigninReady) { Some(CoordinatorAction::SignInCompleted) } + else { None }; + Self::for_state(state.attempt, ExitActions { cancel: None, acknowledge: Vec::new(), coordinator }) + } + fn epoch(state: attempt::PartitionView<'_>) -> Option { + let common = state.common; + let epoch = common.epoch.checked_add(1)?; + let mut acknowledge: Vec<_> = common.inbox.iter().map(Receipt::of).collect(); + let commit = common.pending_commit.as_ref().map(|commit| { + if let Some(receipt) = commit.receipt { acknowledge.push(receipt); } + (commit.req, common.epoch) + }); + Some(Self::for_state(state.attempt, ExitActions { + cancel: Some(CancelBatch { commit, requests: common.pending.keys().copied().collect(), epoch }), + acknowledge, + coordinator: None, + })) + } + + fn epoch_number(&self) -> u64 { + let actions = match self { + Self::Idle(actions) => actions, + Self::Creating(actions) => actions, + Self::Waiting(actions) => actions, + Self::Discovering(actions) => actions, + Self::Profiles(actions) => actions, + Self::Switching(actions) => actions, + Self::Ready(actions) => actions, + Self::Error(actions) => actions, + Self::Deleted(actions) => actions, + Self::Erasing(actions) => actions, + }; + actions.cancel.as_ref().expect("epoch exit has a cancellation").epoch + } + fn emit(self, emit: &mut impl FnMut(SessionFx)) { + let actions = match self { + Self::Idle(actions) => actions, + Self::Creating(actions) => actions, + Self::Waiting(actions) => actions, + Self::Discovering(actions) => actions, + Self::Profiles(actions) => actions, + Self::Switching(actions) => actions, + Self::Ready(actions) => actions, + Self::Error(actions) => actions, + Self::Deleted(actions) => actions, + Self::Erasing(actions) => actions, + }; + let ExitActions { cancel, acknowledge, coordinator } = actions; + if let Some(batch) = cancel { + if let Some((req, epoch)) = batch.commit { + emit(SessionFx::Cancel { requests: vec![req], epoch }); + } + if !acknowledge.is_empty() { emit(SessionFx::Acknowledge(acknowledge)); } + emit(SessionFx::Cancel { requests: batch.requests, epoch: batch.epoch }); + } else if !acknowledge.is_empty() { + emit(SessionFx::Acknowledge(acknowledge)); + } + if let Some(action) = coordinator { emit(SessionFx::Coordinator(action)); } + } +} + +enum EntryWork { + Capture { req: u32, epoch: u64 }, + Work { req: u32, key: SessionWorkKey, admission: AdmissionId, input: SessionWork }, +} + +struct CommitEntry { req: u32, epoch: u64, arrival: u64, plan: CommitPlan } +impl CommitEntry { fn emit(self, emit: &mut impl FnMut(SessionFx)) { let Self { req, epoch, arrival, plan } = self; emit(SessionFx::Commit { req, epoch, arrival, plan }); } } +struct PickerSetup { initial: Option, server_roster: Option, home_roster: Option } +impl EntryWork { + fn emit(self, emit: &mut impl FnMut(SessionFx)) { + match self { + Self::Capture { req, epoch } => emit(SessionFx::Capture { req, epoch, request: SessionReadRequest::LoginClientId }), + Self::Work { req, key, admission, input } => emit(SessionFx::Work { req, key, admission, input }), + } + } +} +struct ReadyEntry { epoch: u64, scope: ProfileScope, server: plx_plex::plex::session::ServerRef, token: String, install: ReadyInstall } +struct EraseEntry { req: u32, epoch: u64, all_local: bool } + +// Entry obligations are values of the destination state, not calls into another machine. +enum EntryFx { + Idle, + Creating { work: Option, started: bool }, + Waiting, + Discovering { work: Option, started: bool }, + Profiles { setup: Option }, + Switching { capture: Option<(u32, u64)> }, + Ready { announcement: Option }, + Error, + Deleted { announce_erased: bool }, + Erasing { erase: Option }, +} + +impl EntryFx { + fn retained(state: &attempt::Attempt) -> Self { + match state { + attempt::Attempt::Idle(_) => Self::Idle, + attempt::Attempt::Creating(_) => Self::Creating { work: None, started: false }, + attempt::Attempt::Waiting(_) => Self::Waiting, + attempt::Attempt::Discovering(_) => Self::Discovering { work: None, started: false }, + attempt::Attempt::Profiles(_) => Self::Profiles { setup: None }, + attempt::Attempt::Switching(_) => Self::Switching { capture: None }, + attempt::Attempt::Ready(_) => Self::Ready { announcement: None }, + attempt::Attempt::Error(_) => Self::Error, + attempt::Attempt::Deleted(_) => Self::Deleted { announce_erased: false }, + attempt::Attempt::Erasing(_) => Self::Erasing { erase: None }, + } + } + fn attempt(state: attempt::PartitionView<'_>, event: &AttemptEvent) -> Self { + let common = state.common; + // Erasing retains imported read-out changes, but owes no second erase job. + if matches!(state.attempt, attempt::Attempt::Erasing(_)) + && !matches!(event, AttemptEvent::BeginErase { .. } | AttemptEvent::FinishErase) { + return Self::Erasing { erase: None }; + } + match event { + AttemptEvent::LoginFailed { .. } => Self::Error, + AttemptEvent::CodeReplacing => Self::Creating { work: None, started: false }, + AttemptEvent::CodeReady { .. } => Self::Waiting, + AttemptEvent::Authorized => Self::Discovering { work: None, started: false }, + AttemptEvent::RestartDiscovery { .. } => Self::Discovering { work: None, started: false }, + AttemptEvent::RestartLogin { .. } => Self::Creating { work: None, started: false }, + AttemptEvent::ResumeBack => Self::Ready { announcement: None }, + AttemptEvent::ResumeDevBack => { + let announcement = if let BootstrapAuthority::DevPms { primary, .. } = &common.authority { + Some(ReadyEntry { epoch: common.epoch, scope: common.profile_scope, server: primary.clone(), token: primary.token.clone(), install: ReadyInstall::AlreadyInstalled }) + } else { None }; + Self::Ready { announcement } + }, + AttemptEvent::BeginDevAccount { .. } => Self::Creating { work: None, started: false }, + AttemptEvent::ActivateDev => { + let announcement = if let BootstrapAuthority::DevPms { primary, .. } = &common.authority { + Some(ReadyEntry { epoch: common.epoch, scope: common.profile_scope, server: primary.clone(), token: primary.token.clone(), install: ReadyInstall::AlreadyInstalled }) + } else { None }; + Self::Ready { announcement } + }, + AttemptEvent::ReadyExhausted => Self::Profiles { setup: None }, + AttemptEvent::SwitchCommitRefused => Self::Profiles { setup: None }, + AttemptEvent::DevCommitRefused => Self::Error, + AttemptEvent::SwitchAdmissionRefused => Self::Profiles { setup: None }, + AttemptEvent::OpenDevPicker => Self::Profiles { setup: None }, + AttemptEvent::OpenPicker { .. } => Self::Profiles { setup: None }, + AttemptEvent::ReuseProfile => Self::Ready { announcement: None }, + AttemptEvent::SelectProfile { req } => Self::Switching { capture: Some((*req, common.epoch)) }, + AttemptEvent::SwitchDropped => Self::Profiles { setup: None }, + AttemptEvent::SwitchFailed { .. } => Self::Profiles { setup: None }, + AttemptEvent::SigninProfiles { .. } => Self::Profiles { setup: None }, + AttemptEvent::SigninReady => Self::Ready { announcement: None }, + AttemptEvent::ProfileReady { .. } => Self::Ready { announcement: None }, + AttemptEvent::StoredReady => Self::Ready { announcement: None }, + AttemptEvent::LinkTrouble { .. } => Self::retained(state.attempt), + AttemptEvent::RosterFailed { .. } => Self::retained(state.attempt), + AttemptEvent::BeginSignin { .. } => Self::Creating { work: None, started: true }, + AttemptEvent::DiscoveryTrouble { .. } => Self::retained(state.attempt), + AttemptEvent::DiscoverySettled { .. } => Self::retained(state.attempt), + AttemptEvent::DiscoveryFailed { .. } => Self::retained(state.attempt), + AttemptEvent::PlaintextDeclined { .. } => Self::retained(state.attempt), + AttemptEvent::RosterArrived { .. } => Self::retained(state.attempt), + AttemptEvent::ReadyCommitted => Self::retained(state.attempt), + AttemptEvent::EraseAuthority => Self::retained(state.attempt), + AttemptEvent::EpochAdvanced | AttemptEvent::WorkRetired { .. } + | AttemptEvent::BeginDevActivation { .. } | AttemptEvent::BeginStoredRestore { .. } + | AttemptEvent::InstallPicker { .. } | AttemptEvent::BeginReadyCommit { .. } => Self::retained(state.attempt), + AttemptEvent::BeginErase { epoch, sign_in } => Self::Erasing { erase: Some(EraseEntry { req: common.next_req, epoch: *epoch, all_local: !*sign_in }) }, + AttemptEvent::FinishErase => Self::Deleted { announce_erased: state.attempt.pending_erase().is_some_and(|(_, sign_in)| !sign_in) }, + } + } + + fn login(state: attempt::PartitionView<'_>, req: u32, discovery: bool, started: bool) -> Self { + let common = state.common; + let key = common.pending[&req].key; + let client_id = &common.persisted.client_id; + if !discovery && client_id.is_empty() { + return Self::Creating { work: Some(EntryWork::Capture { req, epoch: key.epoch }), started }; + } + let input = if discovery { + SessionWork::Rediscover { client_id: client_id.clone(), account_token: common.persisted.account_token.clone() } + } else { SessionWork::Login { client_id: client_id.clone() } }; + let work = Some(EntryWork::Work { req, key, admission: AdmissionId(req), input }); + if discovery { Self::Discovering { work, started } } else { Self::Creating { work, started } } + } + fn work(&self) -> &EntryWork { + match self { + Self::Creating { work, .. } | Self::Discovering { work, .. } => work.as_ref().expect("new sign-in entry owns work"), + Self::Idle | Self::Waiting | Self::Profiles { .. } | Self::Switching { .. } | Self::Ready { .. } + | Self::Error | Self::Deleted { .. } | Self::Erasing { .. } => panic!("not a sign-in entry"), + } + } + fn emit(self, emit: &mut impl FnMut(SessionFx)) { + match self { + Self::Creating { work, started } | Self::Discovering { work, started } => { + if started { emit(SessionFx::Coordinator(CoordinatorAction::SignInStarted)); } + if let Some(work) = work { + work.emit(emit); + } + } + Self::Profiles { setup } => { + if let Some(PickerSetup { initial, server_roster, home_roster }) = setup { + if let Some(commit) = initial { commit.emit(emit); } + if let Some(work) = server_roster { work.emit(emit); } + if let Some(work) = home_roster { work.emit(emit); } + } + } + Self::Switching { capture } => { + if let Some((req, epoch)) = capture { emit(SessionFx::Capture { req, epoch, request: SessionReadRequest::ProfilePolicy }); } + } + Self::Ready { announcement } => { + if let Some(ReadyEntry { epoch, scope, server, token, install }) = announcement { + emit(SessionFx::Ready { epoch, scope, server, token, install }); + } + } + Self::Deleted { announce_erased } => { + if announce_erased { emit(SessionFx::Coordinator(CoordinatorAction::LocalDataErased)); } + } + Self::Erasing { erase } => { + if let Some(EraseEntry { req, epoch, all_local }) = erase { emit(SessionFx::Erase { req, epoch, all_local }); } + } + Self::Idle | Self::Waiting | Self::Error => {} + } } } +enum AttemptEvent { + LoginFailed { message: String, revoke: bool }, + CodeReplacing, + CodeReady { generation: u64, code: String, png: Vec }, + Authorized, + RestartDiscovery { req: u32 }, + RestartLogin { req: u32 }, + ResumeBack, + ResumeDevBack, + BeginDevAccount { boundary_req: u32, login_req: u32 }, + ActivateDev, + ReadyExhausted, + SwitchCommitRefused, + DevCommitRefused, + SwitchAdmissionRefused, + OpenDevPicker, + OpenPicker { kind: Picker, fallback: Vec }, + ReuseProfile, + SelectProfile { req: u32 }, + SwitchDropped, + SwitchFailed { message: String, denied: bool }, + SigninProfiles { users: Vec }, + SigninReady, + ProfileReady { req: u32 }, + StoredReady, + LinkTrouble { present: bool }, + RosterFailed { message: String }, + BeginSignin { req: u32 }, + DiscoveryTrouble { progress: super::DiscoveryRetryProgress }, + DiscoverySettled { run: super::DiscoveryRetryRun }, + DiscoveryFailed { plaintext: Option, account: Option }, + PlaintextDeclined { choice: plx_plex::plex::session::PlaintextChoice }, + RosterArrived { users: Vec }, + ReadyCommitted, + EraseAuthority, + EpochAdvanced, + WorkRetired { req: u32 }, + BeginDevActivation { req: u32 }, + BeginStoredRestore { req: u32 }, + InstallPicker { req: u32 }, + BeginReadyCommit { req: u32 }, + BeginErase { epoch: u64, sign_in: bool }, + FinishErase, +} + +fn next_attempt(attempt: attempt::Attempt, event: AttemptEvent) -> attempt::Attempt { +match event { + AttemptEvent::LoginFailed { message, revoke } => attempt.login_failed(message, revoke), + AttemptEvent::CodeReplacing => attempt.code_replacing(), + AttemptEvent::CodeReady { generation, code, png } => attempt.code_ready(generation, code, png), + AttemptEvent::Authorized => attempt.authorized(), + AttemptEvent::RestartDiscovery { req } => attempt.restart_discovery(req), + AttemptEvent::RestartLogin { req } => attempt.restart_login(req), + AttemptEvent::ResumeBack => attempt.resume_back(), + AttemptEvent::ResumeDevBack => attempt.resume_dev_back(), + AttemptEvent::BeginDevAccount { boundary_req, login_req } => attempt.begin_dev_account(boundary_req, login_req), + AttemptEvent::ActivateDev => attempt.activate_dev(), + AttemptEvent::ReadyExhausted => attempt.ready_exhausted(), + AttemptEvent::SwitchCommitRefused => attempt.switch_commit_refused(), + AttemptEvent::DevCommitRefused => attempt.dev_commit_refused(), + AttemptEvent::SwitchAdmissionRefused => attempt.switch_admission_refused(), + AttemptEvent::OpenDevPicker => attempt.open_dev_picker(), + AttemptEvent::OpenPicker { kind, fallback } => attempt.open_picker(kind, fallback), + AttemptEvent::ReuseProfile => attempt.reuse_profile(), + AttemptEvent::SelectProfile { req } => attempt.select_profile(req), + AttemptEvent::SwitchDropped => attempt.switch_dropped(), + AttemptEvent::SwitchFailed { message, denied } => attempt.switch_failed(message, denied), + AttemptEvent::SigninProfiles { users } => attempt.signin_profiles(users), + AttemptEvent::SigninReady => attempt.signin_ready(), + AttemptEvent::ProfileReady { req } => attempt.profile_ready(req), + AttemptEvent::StoredReady => attempt.stored_ready(), + AttemptEvent::LinkTrouble { present } => attempt.link_trouble(present), + AttemptEvent::RosterFailed { message } => attempt.roster_failed(message), + AttemptEvent::BeginSignin { req } => attempt.begin_signin(req), + AttemptEvent::DiscoveryTrouble { progress } => attempt.discovery_trouble(progress), + AttemptEvent::DiscoverySettled { run } => attempt.discovery_settled(run), + AttemptEvent::DiscoveryFailed { plaintext, account } => attempt.discovery_failed(plaintext, account), + AttemptEvent::PlaintextDeclined { choice } => attempt.plaintext_declined(choice), + AttemptEvent::RosterArrived { users } => attempt.roster_arrived(users), + AttemptEvent::ReadyCommitted => attempt.ready_committed(), + AttemptEvent::EraseAuthority => attempt.erase_authority(), + AttemptEvent::EpochAdvanced => attempt.epoch_advanced(), + AttemptEvent::WorkRetired { req } => attempt.work_retired(req), + AttemptEvent::BeginDevActivation { req } => attempt.begin_dev_activation(req), + AttemptEvent::BeginStoredRestore { req } => attempt.begin_stored_restore(req), + AttemptEvent::InstallPicker { req } => attempt.install_picker(req), + AttemptEvent::BeginReadyCommit { req } => attempt.begin_ready_commit(req), + AttemptEvent::BeginErase { epoch, sign_in } => attempt.begin_erase(epoch, sign_in), + AttemptEvent::FinishErase => attempt.finish_erase(), + } +} + +fn signin_notice(event: &AttemptEvent) -> Option { +match event { + AttemptEvent::RestartLogin { .. } | AttemptEvent::RestartDiscovery { .. } | AttemptEvent::BeginSignin { .. } => Some(attempt::SignInNotice::Owed), + AttemptEvent::LoginFailed { .. } | AttemptEvent::ResumeBack | AttemptEvent::SigninProfiles { .. } + | AttemptEvent::SigninReady | AttemptEvent::EraseAuthority => Some(attempt::SignInNotice::Settled), + AttemptEvent::CodeReplacing | AttemptEvent::CodeReady { .. } | AttemptEvent::Authorized | AttemptEvent::ResumeDevBack + | AttemptEvent::BeginDevAccount { .. } | AttemptEvent::ActivateDev | AttemptEvent::ReadyExhausted | AttemptEvent::SwitchCommitRefused + | AttemptEvent::DevCommitRefused | AttemptEvent::SwitchAdmissionRefused | AttemptEvent::OpenDevPicker | AttemptEvent::OpenPicker { .. } + | AttemptEvent::ReuseProfile | AttemptEvent::SelectProfile { .. } | AttemptEvent::SwitchDropped | AttemptEvent::SwitchFailed { .. } + | AttemptEvent::ProfileReady { .. } | AttemptEvent::StoredReady | AttemptEvent::LinkTrouble { .. } + | AttemptEvent::RosterFailed { .. } | AttemptEvent::DiscoveryTrouble { .. } + | AttemptEvent::DiscoverySettled { .. } | AttemptEvent::DiscoveryFailed { .. } | AttemptEvent::PlaintextDeclined { .. } + | AttemptEvent::RosterArrived { .. } | AttemptEvent::ReadyCommitted | AttemptEvent::EpochAdvanced | AttemptEvent::WorkRetired { .. } + | AttemptEvent::BeginDevActivation { .. } | AttemptEvent::BeginStoredRestore { .. } + | AttemptEvent::InstallPicker { .. } | AttemptEvent::BeginReadyCommit { .. } + | AttemptEvent::BeginErase { .. } | AttemptEvent::FinishErase => None + } +} + +struct WorkReservation { req: u32, pending: Pending } +struct CommitPreparation { pending: PendingCommit, entry: CommitEntry } +enum LoginRestart { Fresh, Retry } + pub struct SessionMachine { - state: SessionInit, + state: attempt::Attempt, + common: attempt::Common, publication: Arc, subhash: u64, logical_dirty: bool, @@ -1278,57 +1762,83 @@ impl SessionMachine { pub fn from_init(state: SessionInit) -> Self { assert!(state.inbox.len() + usize::from(state.pending_commit.as_ref().is_some_and(|c| c.receipt.is_some())) <= SESSION_TRANSFER_RECORDS, "invalid Session transfer state"); + let attempt::Partition { common, attempt: state } = attempt::Partition::from_init(state); + let view = attempt::PartitionView { common: &common, attempt: &state }; let mut canon = Canon::new(); - state.write(&mut canon); + LegacyV5Projection::from_partition(view).write(&mut canon); let subhash = canon.finish(); - let publication = Arc::new(SessionSnapshot::from_state(&state)); - Self { state, publication, subhash, logical_dirty: true, + let publication = Arc::new(SessionSnapshot::from_state(view)); + Self { state, common, publication, subhash, logical_dirty: true, cache_refresh: CacheRefresh::Idle, next_cache_req: 0, #[cfg(test)] publication_payload_allocations: [0; 3] } } +fn plan_reservation(&self, op: SessionOp, lifecycle: Option) -> Option { + let req = self.common.next_req.checked_add(1)?; + Some(WorkReservation { req, pending: Pending { + key: SessionWorkKey { epoch: self.common.epoch, op }, + expected: Identity::of(&self.common.persisted), lifecycle, + last_arrival: None, phase: StreamPhase::Running, capture: None, admission: AdmissionState::NotRequested, + } }) +} + +fn plan_commit(&self, req: u32, arrival: u64, terminal: bool, plan: CommitPlan, delta: CommitDelta) -> Option { + if self.common.pending_commit.is_some() { return None; } + let pending = self.common.pending.get(&req)?; + if pending.key.epoch != self.common.epoch { return None; } + let epoch = pending.key.epoch; + let fresh = plan.writes_durable && plan.credentials.is_some() + && plan.authority == plx_plex::plex::session::SaveAuthority::FreshReauthentication; + Some(CommitPreparation { pending: PendingCommit { req, epoch, arrival, terminal, + writes_credentials: plan.writes_durable && plan.credentials.is_some(), + receipt: None, delta, admitted_revision: None, + purpose: plan.writes_durable.then_some(plan.purpose), fresh, + }, entry: CommitEntry { req, epoch, arrival, plan } }) +} + +fn publication_update(&self) -> Option<(Arc, [usize; 3])> { + if self.publication.matches_state(self.view()) { return None; } + let mut allocations = [0; 3]; + let next = SessionSnapshot::from_state_counted(self.view(), Some(&self.publication), &mut |field| allocations[field] += 1); + Some((Arc::new(next), allocations)) + } + #[cfg(test)] fn fail_login(&mut self, message: &str, incident: Option, emit: &mut impl FnMut(SessionFx)) { let mut effects = Vec::new(); self.transition(&SessionEvent::FailLogin { message: message.into(), incident }, 0, &mut effects); effects.into_iter().for_each(emit); } // Required controlled-init boundary; full AppInit capture remains a following stage. - pub fn snapshot_init(&self) -> SessionInit { self.state.clone() } + pub fn snapshot_init(&self) -> SessionInit { self.view().snapshot_init() } + fn view(&self) -> attempt::PartitionView<'_> { attempt::PartitionView { common: &self.common, attempt: &self.state } } pub fn read(&self) -> SessionRead<'_> { self.publication.read() } pub fn publication(&self) -> Arc { Arc::clone(&self.publication) } /// The request of the [`SessionFx::RefreshCache`] still awaiting its answer, if any. The app's /// frame step compares it with the adapter's own slot to reconcile a job the adapter began and /// then lost. pub fn cache_refresh_in_flight(&self) -> Option { - match self.cache_refresh { CacheRefresh::InFlight { req, .. } => Some(req), _ => None } + match self.cache_refresh { CacheRefresh::InFlight { req, .. } => Some(req), CacheRefresh::Idle | CacheRefresh::Backoff { .. } => None } } pub fn subhash(&self) -> u64 { self.subhash } // Cached hashes already change on logical transitions; aggregate dirty consumption is // separate from UI Arc damage and remains a following-stage App recording integration. - pub fn take_logical_dirty(&mut self) -> bool { std::mem::take(&mut self.logical_dirty) } + pub fn take_logical_dirty(&mut self) -> bool { self.transition(&SessionEvent::ConsumeLogicalDirty, 0, &mut Vec::new()) } + - fn refresh_subhash(&mut self) { - let mut canon = Canon::new(); - self.state.write(&mut canon); - let next = canon.finish(); - if next != self.subhash { - self.subhash = next; - self.logical_dirty = true; - } - } pub fn ready_is_current(&self, epoch: u64, scope: ProfileScope) -> bool { - self.state.epoch == epoch && self.state.profile_scope == scope - && self.state.phase == Phase::Ready && !self.state.apply_pending + self.common.epoch == epoch && self.common.profile_scope == scope + && self.state.phase() == Phase::Ready && !self.state.handoff_pending() } pub fn needs_ready_commit(&self) -> bool { - self.state.phase == Phase::Ready && self.state.apply_pending && self.state.pending_commit.is_none() - && self.state.persistence_warning.is_none() + self.state.phase() == Phase::Ready && self.state.handoff_pending() && self.common.pending_commit.is_none() + && self.common.persistence_warning.is_none() } pub fn publication_is_current(&self, publication: &ProfilePublication) -> bool { - publication.epoch == self.state.epoch && publication.scope == self.state.profile_scope + publication.epoch == self.common.epoch && publication.scope == self.common.profile_scope } pub fn read_is_current(&self, req: u32, epoch: u64, request: SessionReadRequest) -> bool { - if epoch != self.state.epoch { return false; } - let Some(pending) = self.state.pending.get(&req) else { return false }; - if pending.key.epoch != epoch || !pending.expected.matches(&self.state.persisted) { return false; } + if epoch != self.common.epoch { return false; } + let Some(pending) = self.common.pending.get(&req) else { return false }; + if pending.key.epoch != epoch || !pending.expected.matches(&self.common.persisted) + || !self.state.owns_work(req, pending) { return false; } match (&pending.capture, request) { (Some(CaptureIntent::Login), SessionReadRequest::LoginClientId) | (Some(CaptureIntent::Profile { .. }), SessionReadRequest::ProfilePolicy) => true, @@ -1339,22 +1849,15 @@ impl SessionMachine { /// Physical completion remains evidence even after its authority permit was superseded. /// Advance only the comparison fence; never publish obsolete credentials as trusted state. - fn observe_disk_write(&mut self, before: &Identity, after: &Identity, - outcome: plx_plex::plex::session::async_persistence::CompletionOutcome) -> bool { - use plx_plex::plex::session::async_persistence::{CompletionOutcome, Operation}; - if self.state.disk_identity != *before || before == after - || !matches!(outcome, CompletionOutcome::Durable(Operation::Write { .. })) { return false; } - self.state.disk_identity = after.clone(); - true - } + #[cfg(test)] fn observe_disk_write(&mut self, before: &Identity, after: &Identity, outcome: plx_plex::plex::session::async_persistence::CompletionOutcome) -> bool { self.transition(&SessionEvent::DiskWrite { before: before.clone(), after: after.clone(), outcome }, 0, &mut Vec::new()) } /// Read-only authorization at effect execution, after any carried cancellation command. /// The bridge checks before admission and again when the worker completes. Supersession /// cancels pending work; a write already completed still reports its physical disk evidence. pub fn commit_is_current(&self, req: u32, epoch: u64, arrival: u64) -> bool { - self.state.epoch == epoch - && self.state.pending.contains_key(&req) - && self.state.pending_commit.as_ref().is_some_and(|commit| + self.common.epoch == epoch + && self.common.pending.get(&req).is_some_and(|pending| self.state.owns_work(req, pending)) + && self.common.pending_commit.as_ref().is_some_and(|commit| commit.req == req && commit.epoch == epoch && commit.arrival == arrival) } @@ -1367,129 +1870,25 @@ impl SessionMachine { /// Bridge wiring hook for Stage B: the caller that owns the decision can name the purpose /// explicitly instead of inheriting a default. The adapter reaches the plan's own purpose /// through [`CommitPlan`], so this is not yet called inside this crate. - #[allow(dead_code)] pub fn commit_permit_for(&self, req: u32, epoch: u64, arrival: u64) -> Option> { self.commit_is_current(req, epoch, arrival).then_some(CommitPermit { req, epoch, arrival, owner: std::marker::PhantomData, }) } - fn begin_commit(&mut self, req: u32, arrival: u64, terminal: bool, - plan: CommitPlan, delta: CommitDelta, emit: &mut impl FnMut(SessionFx)) -> bool { - if self.state.pending_commit.is_some() { return false; } - let Some(pending) = self.state.pending.get_mut(&req) else { return false }; - if pending.key.epoch != self.state.epoch { return false; } - pending.last_arrival = Some(arrival); - let epoch = pending.key.epoch; - let fresh = plan.writes_durable && plan.credentials.is_some() - && plan.authority == plx_plex::plex::session::SaveAuthority::FreshReauthentication; - self.state.pending_commit = Some(PendingCommit { req, epoch, arrival, terminal, - writes_credentials: plan.writes_durable && plan.credentials.is_some(), - receipt: None, delta, - admitted_revision: None, - purpose: plan.writes_durable.then_some(plan.purpose), - fresh }); - self.state.persistence_purpose = Some(plan.purpose); - emit(SessionFx::Commit { req, epoch, arrival, plan }); - true - } - fn take_ready(&mut self, emit: &mut impl FnMut(SessionFx)) -> bool { - if self.state.phase != Phase::Ready || !self.state.apply_pending - || self.state.pending_commit.is_some() { return false; } - // A discovery failure left a warning unacknowledged: the final fresh write must not run - // over it (AUTH-03) — acknowledging is what re-admits `needs_ready_commit`. - if self.state.persistence_warning.is_some() { return false; } - let Some(req) = self.allocate(SessionOp::Ready, None) else { - self.state.phase = Phase::Profiles; - self.state.apply_pending = false; - self.state.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); - self.replace_publication(); - return true; - }; - let mut next = self.state.persisted.clone(); - super::remember_unprotected_active(&mut next); - let patch = CredentialPatch::of(&next); - // Consumed exactly once: a discovery/rediscovery retry only PEEKS this flag - // (`apply_resource_observation`), so it cannot spend the authority the final write needs. - let authority = if std::mem::take(&mut self.state.authorized_in_flow) { - plx_plex::plex::session::SaveAuthority::FreshReauthentication - } else { plx_plex::plex::session::SaveAuthority::Routine }; - let plan = CommitPlan { registry_client_id: self.state.persisted.client_id.clone(), - expected_disk: self.state.disk_identity.clone(), - credentials: Some(patch.clone()), lifecycle: None, - registry: vec![RegistryPlan::Install { sources: next.sources.clone(), primary: None, commit: RosterCommit::Merge }], - purpose: PersistencePurpose::Final, writes_durable: true, authority }; - self.begin_commit(req, 0, true, plan, CommitDelta { - credentials: Some(patch), activate_profile: true, ready: Some(false), - ..Default::default() - }, emit) - } - fn activate_dev(&mut self, emit: &mut impl FnMut(SessionFx)) -> bool { - if self.state.phase != Phase::Idle || self.state.pending_commit.is_some() - || self.state.pending_erase.is_some() { return false; } - let BootstrapAuthority::DevPms { primary, extras } = &self.state.authority else { return false }; - let registry = vec![RegistryPlan::DevInstall { primary: primary.clone(), extras: extras.clone(), - client_id: self.state.persisted.client_id.clone() }]; - let Some(req) = self.allocate(SessionOp::DevBoundary, None) else { return false }; - self.begin_commit(req, 0, true, CommitPlan { registry_client_id: self.state.persisted.client_id.clone(), - expected_disk: self.state.disk_identity.clone(), - credentials: None, lifecycle: None, registry, - purpose: PersistencePurpose::Background, writes_durable: false, - authority: plx_plex::plex::session::SaveAuthority::Routine }, CommitDelta { - dev: Some(DevCommitDelta::Activated), ..Default::default() - }, emit) - } - - fn begin_dev_account(&mut self, emit: &mut impl FnMut(SessionFx)) -> bool { - if self.state.pending_erase.is_some() || self.state.epoch.checked_add(1).is_none() - || self.state.next_req.checked_add(2).is_none() - || self.state.pending_commit.as_ref().is_some_and(|c| - matches!(c.delta.dev, Some(DevCommitDelta::StartAccount { .. }))) { return false; } - self.advance_epoch(emit).expect("dev login epoch preflight"); - self.publish_profile(None, emit); - self.state.phase = Phase::Creating; - self.state.apply_pending = false; - self.state.error.clear(); - let req = self.allocate(SessionOp::DevBoundary, None).expect("two-slot preflight"); - let login_req = self.allocate(SessionOp::Login, None).expect("two-slot preflight"); - self.begin_commit(req, 0, true, CommitPlan { registry_client_id: self.state.persisted.client_id.clone(), - expected_disk: self.state.disk_identity.clone(), - credentials: None, lifecycle: None, registry: vec![RegistryPlan::Revoke], - purpose: PersistencePurpose::Background, writes_durable: false, - authority: plx_plex::plex::session::SaveAuthority::Routine }, CommitDelta { - dev: Some(DevCommitDelta::StartAccount { login_req }), ..Default::default() - }, emit); - self.replace_publication(); - true - } - fn start_reserved_login(&mut self, req: u32, emit: &mut impl FnMut(SessionFx)) { - let client_id = self.state.persisted.client_id.clone(); - if client_id.is_empty() { - self.state.pending.get_mut(&req).expect("reserved login").capture = Some(CaptureIntent::Login); - emit(SessionFx::Capture { req, epoch: self.state.epoch, request: SessionReadRequest::LoginClientId }); - } else { self.emit_work(req, SessionWork::Login { client_id }, emit); } - } - fn resume_stored(&mut self, emit: &mut impl FnMut(SessionFx)) -> bool { - if !matches!(self.state.authority, BootstrapAuthority::Account { .. }) { return false; } - if self.state.phase != Phase::Idle || !self.state.persisted.can_go_local() - || self.state.pending_commit.is_some() { return false; } - let Some(req) = self.allocate(SessionOp::Ready, None) else { return false }; - let plan = CommitPlan { registry_client_id: self.state.persisted.client_id.clone(), - expected_disk: self.state.disk_identity.clone(), - credentials: None, lifecycle: None, - registry: vec![RegistryPlan::Install { sources: self.state.persisted.sources.clone(), - primary: None, commit: RosterCommit::Merge }], - purpose: PersistencePurpose::Background, writes_durable: false, - authority: plx_plex::plex::session::SaveAuthority::Routine }; - self.begin_commit(req, 0, true, plan, CommitDelta { - phase: Some(Phase::Ready), activate_profile: true, ready: Some(false), - ..Default::default() - }, emit) - } + + + + + + + + + #[cfg(test)] fn resume_stored(&mut self, emit: &mut impl FnMut(SessionFx)) -> bool { let mut effects = Vec::new(); let handled = self.transition(&SessionEvent::Command(Command::ResumeStored), 0, &mut effects); effects.into_iter().for_each(emit); handled } /// Settle a durability verdict ONLY if it still describes the write this owner is waiting on. /// @@ -1497,177 +1896,1495 @@ impl SessionMachine { /// is inert: it must not activate registry or profile, must not clear a newer error, and must /// not release admission credit that belongs to a different operation. The owner keeps only /// this logical identity; channels and receipts stay in the adapter. - fn apply_persistence_completion( - &mut self, - completion: plx_plex::plex::session::async_persistence::PersistenceCompletion, - emit: &mut impl FnMut(SessionFx), - ) -> bool { - use plx_plex::plex::session::async_persistence::CompletionOutcome; - let Some(admitted) = self.state.admitted_persistence else { return false }; - let correlation = plx_plex::plex::session::async_persistence::PersistenceCorrelation { - req: admitted.req, epoch: admitted.epoch, arrival: admitted.arrival, - }; - if !completion.acts_on(correlation, admitted.revision) { return false; } - // A verdict the worker resolved for a DIFFERENT purpose than the one admitted is not this - // operation's verdict either. - if admitted.purpose.is_some_and(|purpose| purpose != completion.purpose) { return false; } - let durable = matches!(completion.outcome, CompletionOutcome::Durable(_)); - self.state.admitted_persistence = None; - let prior = self.state.unconfirmed_fresh_prior.take(); - if let (Some(prior), CompletionOutcome::Failed(_)) = (prior, &completion.outcome) { - if admitted.fresh { self.state.disk_identity = prior; } - } - self.state.commit_phase.durable = durable; - self.state.commit_phase.proves_saved_login = - durable && completion.purpose.proves_saved_login(); - let correlation_key = PersistenceWarningKey { epoch: completion.epoch, req: completion.req }; - if durable { - // 0.6.6 parity: a later FRESH write landing durably supersedes any warning still - // showing about an earlier fresh attempt — the failure it was reporting on no longer - // describes the session's current state, so holding it would strand an acknowledgement - // over a problem that already resolved itself. - let superseded = admitted.fresh && self.state.persistence_warning.is_some(); - if superseded { - self.state.persistence_warning = None; - self.retire_save_incident(); - } - // Release only the handoff THIS completion is for — a routine completion arriving - // while an unrelated fresh handoff is held must not free it. - let released = self.state.held_handoff == Some(HeldHandoff { epoch: completion.epoch, req: completion.req }); - if released { self.release_held_handoff(emit); } - if superseded || released { self.replace_publication(); } - } else if admitted.fresh { - if self.state.persistence_warning_answered { - // This authorization already had its one unsaved-login question answered - // (AUTH-03's field bug: a device unwritable on BOTH Discovery and Final used to - // ask it twice). Storage failing again must not ask it a second time — release - // whatever handoff this completion was holding so entry proceeds regardless. - let released = self.state.held_handoff == Some(HeldHandoff { epoch: completion.epoch, req: completion.req }); - if released { self.release_held_handoff(emit); self.replace_publication(); } - } else { - // The final write's own non-durable completion replaces a Discovery warning still - // showing (`Discovery` and `Final` never coexist: an unacknowledged Discovery warning - // blocks `take_ready`), so the newer one wins by direct overwrite. - let warning = PersistenceWarning::from_outcome(correlation_key, admitted.site, &completion.outcome); - self.retire_save_incident(); - self.state.persistence_warning = Some(warning); - if warning.helper.is_some() { - // The reducer reads no clock. Both report paths use this fenced completion's - // local warning evidence, not later process-global diagnostics. - if let Some(context) = warning.incident_context() { - self.raise_incident(IncidentFlow::SignIn, context); - } - } - self.replace_publication(); - } - } - true + + + #[cfg(test)] fn apply_commit_reply(&mut self, reply: CommitReply, emit: &mut impl FnMut(SessionFx)) -> bool { let mut effects = Vec::new(); let handled = self.transition(&SessionEvent::Commit(reply), 0, &mut effects); effects.into_iter().for_each(emit); handled } + + + + /// The single site that publishes a profile and announces `SessionFx::Ready`. A fresh + /// handoff reaches it only once its write is released — durably confirmed, or its warning + /// acknowledged; a non-fresh (`Routine`) commit reaches it immediately, exactly as before. + + + + + /// The AUTH-03 acknowledgement door: clears the warning and, if a handoff is still held for + /// it, releases it — exactly ONE `SessionFx::Ready` for the flow, through + /// [`Self::release_held_handoff`], never a second one from here. + + + + + + pub fn work_is_current(&self, req: u32, key: SessionWorkKey, admission: AdmissionId) -> bool { + key.epoch == self.common.epoch && self.common.pending.get(&req).is_some_and(|pending| + pending.key == key && self.state.owns_work(req, pending) && pending.capture.is_none() + && pending.admission == AdmissionState::Awaiting(admission) + && pending.expected.matches(&self.common.persisted)) } - fn apply_commit_reply(&mut self, reply: CommitReply, emit: &mut impl FnMut(SessionFx)) -> bool { - if !self.commit_is_current(reply.req, reply.epoch, reply.arrival) { return false; } - // `take()` is what makes a duplicate reply inert. The admitted revision and purpose are - // copied into `admitted_persistence` first, because that is the identity a later - // completion must repeat exactly to be allowed to settle anything. - let admit_revision = reply.admission.admitted_revision(); - // The admission names what storage was actually asked for; the plan only records intent. - let admit_purpose = reply.admission.admitted_purpose() - .or_else(|| self.state.pending_commit.as_ref().and_then(|c| c.purpose)); - let commit = self.state.pending_commit.take().unwrap(); - self.state.admitted_persistence = admit_revision.map(|revision| AdmittedPersistence { - req: commit.req, epoch: commit.epoch, arrival: commit.arrival, revision, - purpose: admit_purpose, fresh: commit.fresh, - site: match admit_purpose { - Some(PersistencePurpose::Discovery) => PersistenceWarningSite::Discovery, - _ => PersistenceWarningSite::Final, - } }); - self.state.commit_phase = CommitPhase { - admitted: admit_revision.is_some(), - durable: false, - proves_saved_login: false, - }; - self.state.persistence_purpose = None; - if !reply.admission.accepted() { - if let Some(DevCommitDelta::StartAccount { login_req }) = commit.delta.dev { - self.retire(login_req, emit); - } - let op = self.state.pending.remove(&reply.req).unwrap().key.op; - match op { - SessionOp::Login | SessionOp::Rediscover => self.fail_login(plx_platform::i18n::msg::browse_auth_finish_failed(), - Some(IncidentContext::internal(InternalClass::CommitRefused)), emit), - SessionOp::ProfileSwitch | SessionOp::Ready => { - self.state.phase = Phase::Profiles; - self.state.apply_pending = false; - self.state.error = plx_platform::i18n::msg::browse_auth_switch_failed().into(); - } - SessionOp::HomeRoster | SessionOp::ServerRoster | SessionOp::Endpoint(_) | SessionOp::Picker => {} - SessionOp::DevBoundary => { - self.state.phase = Phase::Error; - self.state.apply_pending = false; - self.state.error = plx_platform::i18n::msg::browse_auth_authority_failed().into(); - } - } - emit(SessionFx::Retire { req: reply.req }); - if let Some(receipt) = commit.receipt { emit(SessionFx::Acknowledge(vec![receipt])); } - self.schedule_pump(emit); - self.replace_publication(); - return true; - } - let delta = commit.delta; - if let Some(dev) = &delta.dev { - match dev { - DevCommitDelta::Activated => { - if let BootstrapAuthority::DevPms { primary, .. } = &self.state.authority { - let primary = primary.clone(); - self.state.phase = Phase::Ready; - self.state.apply_pending = false; - self.publish_profile(None, emit); - emit(SessionFx::Ready { epoch: self.state.epoch, scope: self.state.profile_scope, - token: primary.token.clone(), server: primary, install: ReadyInstall::AlreadyInstalled }); - } - } - DevCommitDelta::StartAccount { login_req } => { - self.state.authority = BootstrapAuthority::Account { extras: Vec::new() }; - self.state.signin_active = true; - emit(SessionFx::Coordinator(CoordinatorAction::SignInStarted)); - self.start_reserved_login(*login_req, emit); - } - } - } - if let Some(patch) = delta.credentials { - self.state.persisted = patch.merge_into(&self.state.persisted); - if commit.writes_credentials { - let prior = std::mem::replace(&mut self.state.disk_identity, patch.identity()); - self.state.unconfirmed_fresh_prior = - (commit.fresh && admit_revision.is_some()).then_some(prior); - self.state.committed_credentials = patch; + + + + + fn owns_receipt(&self, receipt: Receipt) -> bool { + self.common.inbox.iter().any(|record| Receipt::of(record) == receipt) + || self.common.pending_commit.as_ref().and_then(|commit| commit.receipt) == Some(receipt) + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + fn roster_plan(next: &PersistedSession, probes: &[super::SettledProbe], commit: RosterCommit) + -> Vec { + let primary = next.sources.iter().position(|source| source.machine_id == next.server.machine_id); + let mut plans = vec![RegistryPlan::Install { sources: next.sources.clone(), primary, commit }]; + plans.extend(probes.iter().cloned().map(RegistryPlan::Probe)); + plans + } + + /// A roster request ended without tiles. With cached tiles on screen nothing changes — they + /// are still the household, and offline switching reads them. With NONE, the picker says so + /// on its own route: `Phase::Profiles` with the reason in `error` and no tiles is the + /// read-out `screens/profiles.rs` draws, and [`SessionInit::roster_dead_end`] is what lets BACK leave + /// it. It used to be `fail_login`, i.e. `Phase::Error` — which the app routes to the SIGN-IN + /// screen ("Couldn't sign in", whose Try again starts a new QR sign-in) for a person who is + /// signed in, and whose BACK the Change-profile picker's root rule then refused (#132). + + + /// [`Self::fail_empty_home_roster`] for plex.tv's VERDICT: over nothing cached it is the dead + /// end itself, so it is also remembered for this identity and the account menu stops offering + /// the way in (`SessionInit::refuse_switch`). Over cached tiles it changes nothing, like any + /// other empty answer. + + + + + /// Start/restart is one owner decision. Check both counters before cancelling anything: + /// exhaustion must not detach the still-live operation or reuse its resource address. + #[cfg(test)] fn restart_login(&mut self, fresh_login: bool, emit: &mut impl FnMut(SessionFx)) -> bool { let mut effects = Vec::new(); let handled = self.transition(&SessionEvent::RestartLogin { fresh_login }, 0, &mut effects); effects.into_iter().for_each(emit); handled } + + /// **The sign-in read-out's *Try again*.** Over an eligible server the person said *Not now* + /// to (or turned off), it is also how they are asked again — Settings, where a signed-in person + /// changes that answer, is out of reach before sign-in — so the answer is withdrawn (recorded + /// `Undecided`, through the same [`SessionFx::PlaintextAnswer`]) BEFORE the retry's work + /// captures the answers, and the retry that follows asks. + + + /// **The answer to "Connect without encryption?"** — recorded through + /// [`SessionFx::PlaintextAnswer`] first, so the work an *Allowed* starts captures it + /// (`plex::grant::PlaintextAsk`). + /// + /// On the sign-in read-out it must answer the server shown there: *Connect* retries the + /// discovery, *Not now* re-words the read-out (its primary becomes *Try again*, which + /// withdraws the answer and asks again — [`Self::retry`]) and starts nothing. Signed in (Home's or the Library's read-out, Settings), any server may be + /// answered; an *Allowed* re-finds `sid`'s endpoint, or the whole roster without one. Nothing + /// is recorded without an account to bind it to. + #[cfg(test)] fn answer_plaintext(&mut self, machine_id: &str, choice: plx_plex::plex::session::PlaintextChoice, sid: Option, emit: &mut impl FnMut(SessionFx)) -> bool { let mut effects = Vec::new(); let handled = self.transition(&SessionEvent::Command(Command::AnswerPlaintext { machine_id: machine_id.into(), choice, sid }), 0, &mut effects); effects.into_iter().for_each(emit); handled } + + /// End the flow on the error read-out. **Every ending names its incident**: `Some` is the + /// failure's own closed evidence and is raised here, so the read-out's Details and Send report + /// are about THIS failure; `None` is an ending the onboarding report does not cover, and it + /// retires whatever is held, which explains an earlier failure and not this one. + + + /// QR observations need no external commit. SignedIn and registry/profile facts go through + /// the separate resource commit protocol, rather than treating their side effects as reads. + #[cfg(test)] fn apply_qr_observation(&mut self, envelope: &SessionEnvelope, emit: &mut impl FnMut(SessionFx)) -> bool { let mut effects = Vec::new(); let handled = self.transition(&SessionEvent::ObserveQr(envelope.clone()), 0, &mut effects); effects.into_iter().for_each(emit); handled } + + /// The checked allocator is independent from the full-width auth epoch. Exhaustion cannot + /// reuse an address, including when a cancelled worker still owns a Landing reservation. + #[cfg(any(test, feature = "test-support"))] fn allocate(&mut self, op: SessionOp, lifecycle: Option) -> Option { self.transition(&SessionEvent::ReserveWork { op, lifecycle }, 0, &mut Vec::new()).then_some(self.common.next_req) } + + /// Admission to logical application, not a resource reservation. Landing owns the latter. + /// Merely inspecting an invalid envelope must not mutate pending state or its publication. + fn accepts_header(&self, envelope: &SessionEnvelope) -> bool { + if envelope.addr.to != MachineId::Session { return false; } + let Some(pending) = self.common.pending.get(&envelope.addr.req.0) else { return false; }; + pending.key == envelope.key && pending.key.epoch == self.common.epoch + && self.state.owns_work(envelope.addr.req.0, pending) + && pending.capture.is_none() + && matches!(pending.admission, AdmissionState::Awaiting(id) | AdmissionState::Accepted(id) if id == envelope.admission) + && pending.last_arrival.is_none_or(|last| envelope.arrival > last) + } + + fn accepts(&self, envelope: &SessionEnvelope) -> bool { + if !self.accepts_header(envelope) { return false; } + let pending = &self.common.pending[&envelope.addr.req.0]; + match &envelope.outcome { + SessionArrival::Data(data) => data.matches_request(pending, envelope.terminal) + && (!matches!(pending.key.op, SessionOp::Endpoint(_)) + || pending.lifecycle == envelope.lifecycle), + SessionArrival::Dropped | SessionArrival::Refused => envelope.terminal, + } + } + + /// The frame step reports what the cache lacks. At most one refresh is out at a time; a backoff + /// holds the next one back on the frame clock; and the first transient observation of a cache + /// entry arms the backoff instead of reading, so a boot with the storage helper down retries + /// about a second later, as the in-line retry timer did, not on frame one. + + + /// A refresh ended. Only the request in flight can end it: a duplicate or stale answer is dropped. + + + /// Apply one addressed event, preserving the owner's effect order. +fn transition(&mut self, ev: &SessionEvent, tick_ms: u32, fx: &mut Vec) -> bool { + let mut publish = false; +let mut pump = false; +let mut restart = None; +let mut restart_reply = None; +let mut handled = match ev { +SessionEvent::ConsumeLogicalDirty => { + std::mem::take(&mut self.logical_dirty) +}, +SessionEvent::RaiseIncident { flow, context } => { publish = true; 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (*flow, *context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}; true }, +SessionEvent::ForgetIncidents => { publish = true; { + + self.common.incident = None; + self.common.incidents_seen.clear(); + { let event = AttemptEvent::LinkTrouble { present: false }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |_| {}); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |_| {}); true }; + +}; true }, +#[cfg(any(test, feature = "test-support"))] SessionEvent::ReserveWork { op, lifecycle } => (('reservation: { let (op, lifecycle): (SessionOp, Option) = (*op, *lifecycle); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) })).is_some(), +#[cfg(test)] SessionEvent::RebuildPublication => { { publish = true; }; true }, +#[cfg(test)] SessionEvent::RestartLogin { fresh_login } => { restart = Some(if *fresh_login { LoginRestart::Fresh } else { LoginRestart::Retry }); true }, +#[cfg(test)] SessionEvent::ObserveQr(envelope) => 'apply_qr_observation: { +let (envelope,): (&SessionEnvelope,) = (envelope,); + + if !self.accepts(envelope) + || !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { + break 'apply_qr_observation false; + } + let req = envelope.addr.req.0; + if !self.common.pending[&req].expected.matches(&self.common.persisted) { break 'apply_qr_observation false; } + match &envelope.outcome { + SessionArrival::Refused | SessionArrival::Dropped => { + if !envelope.terminal { break 'apply_qr_observation false; } + let (message, class) = match (envelope.key.op, &envelope.outcome) { + (SessionOp::Rediscover, SessionArrival::Refused) => + (plx_platform::i18n::msg::browse_auth_rediscover_failed(), InternalClass::WorkerRefused), + (_, SessionArrival::Refused) => (plx_platform::i18n::msg::browse_auth_start_failed(), InternalClass::WorkerRefused), + _ => (plx_platform::i18n::msg::browse_auth_finish_failed(), InternalClass::WorkerDropped), + }; + { +let (message, incident,): (&str, Option,) = (message, Some(IncidentContext::internal(class)),); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}; + } + SessionArrival::Data(data) => { + let super::observation::Observation::Login(progress) = &**data else { break 'apply_qr_observation false }; + use super::LoginProgress; + let (epoch, terminal) = match progress { + LoginProgress::CodeReplacing { epoch } + | LoginProgress::CodeReady { epoch, .. } + | LoginProgress::Authorized { epoch, .. } + | LoginProgress::DiscoveryTrouble { epoch, .. } + | LoginProgress::DiscoveryRetrySettled { epoch, .. } + | LoginProgress::LinkTrouble { epoch, .. } => (*epoch, false), + LoginProgress::Failed { epoch, .. } => (*epoch, true), + LoginProgress::SignedIn { .. } => break 'apply_qr_observation false, + }; + if epoch != envelope.key.epoch || terminal != envelope.terminal { break 'apply_qr_observation false; } + match progress { + LoginProgress::CodeReplacing { .. } => { + if envelope.key.op != SessionOp::Login || !matches!(self.state.phase(), Phase::Creating | Phase::Waiting) { break 'apply_qr_observation false; } + { let event = AttemptEvent::CodeReplacing; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::CodeReady { code, qr_png, .. } => { + if envelope.key.op != SessionOp::Login { break 'apply_qr_observation false; } + let Some(next) = self.common.next_qr.checked_add(1) else { + { +let (message, incident,): (&str, Option,) = (plx_platform::i18n::msg::browse_auth_start_failed(), Some(IncidentContext::internal(InternalClass::Exhausted)),); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}; + self.common.pending.remove(&req); + fx.push(SessionFx::Cancel { requests: vec![req], epoch: self.common.epoch }); + fx.push(SessionFx::Retire { req }); + { publish = true; }; + break 'apply_qr_observation true; + }; + self.common.next_qr = next; + { let event = AttemptEvent::CodeReady { + generation: next, code: code.clone(), png: qr_png.clone(), + }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::Authorized { token, .. } => { + if envelope.key.op != SessionOp::Login { break 'apply_qr_observation false; } + // A sign-in that is not a sign-out (a stored session that could not be + // activated, *Use another account*, the dev login trigger) starts from the + // stored record. Whoever that record seated, its roster and its offline + // profile cache belong to the authorization this token replaces, so none of + // them may ride into the new account: `SignedIn` writes the roster and + // `Session::account` names a single-user account from it; a Home account + // seats through the picker. Reset BEFORE `expected` is recomputed below. + // The new token cannot say whose cache this is (every sign-in mints one), + // so the cache is emptied while the identity is unknown and `SignedIn` + // restores the STORED record's when its roster names the same owner. + self.common.persisted.user = UserRef::default(); + self.common.persisted.home_users.clear(); + self.common.persisted.profiles.clear(); + self.common.persisted.account_token = token.clone(); + { let event = AttemptEvent::Authorized; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.pending.get_mut(&req).unwrap().expected = Identity::of(&self.common.persisted); + } + LoginProgress::DiscoveryTrouble { progress, .. } => { + if !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { + break 'apply_qr_observation false; + } + { let event = AttemptEvent::DiscoveryTrouble { progress: *progress }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::DiscoveryRetrySettled { run, .. } => { + if !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { + break 'apply_qr_observation false; + } + { let event = AttemptEvent::DiscoverySettled { run: *run }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::LinkTrouble { trouble, .. } => { + if envelope.key.op != SessionOp::Login { break 'apply_qr_observation false; } + { let event = AttemptEvent::LinkTrouble { + present: trouble.is_some(), + }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + if let Some(context) = trouble { + 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, *context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}; + } + } + LoginProgress::Failed { message, incident, plaintext, account, .. } => { + { +let (message, incident,): (&str, Option,) = (message, Some(*incident),); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}; + { let event = AttemptEvent::DiscoveryFailed { plaintext: plaintext.clone(), account: account.clone() }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::SignedIn { .. } => unreachable!(), + } + } + } + if envelope.terminal { + self.common.pending.remove(&req); + } else { + self.common.pending.get_mut(&req).unwrap().last_arrival = Some(envelope.arrival); + } + { publish = true; }; + true + +}, +#[cfg(test)] SessionEvent::FailLogin { message, incident } => { { +let (message, incident,): (&str, Option,) = (message, *incident,); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}; true }, + + SessionEvent::Command(Command::ActivateDevBootstrap) => 'activate_dev: { + + if self.state.phase() != Phase::Idle || self.common.pending_commit.is_some() + || self.state.pending_erase().is_some() { break 'activate_dev false; } + let BootstrapAuthority::DevPms { primary, extras } = &self.common.authority else { break 'activate_dev false }; + let registry = vec![RegistryPlan::DevInstall { primary: primary.clone(), extras: extras.clone(), + client_id: self.common.persisted.client_id.clone() }]; + let Some(req) = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::DevBoundary, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }) else { break 'activate_dev false }; + { let event = AttemptEvent::BeginDevActivation { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + 'begin_commit: { +let (req, arrival, terminal, plan, delta,): (u32, u64, bool, CommitPlan, CommitDelta,) = (req, 0, true, CommitPlan { registry_client_id: self.common.persisted.client_id.clone(), + expected_disk: self.common.disk_identity.clone(), + credentials: None, lifecycle: None, registry, + purpose: PersistencePurpose::Background, writes_durable: false, + authority: plx_plex::plex::session::SaveAuthority::Routine }, CommitDelta { + dev: Some(DevCommitDelta::Activated), ..Default::default() + },); + + let Some(entry) = ('commit: { let (req, arrival, terminal, plan, delta): (u32, u64, bool, CommitPlan, CommitDelta) = (req, arrival, terminal, plan, delta); let Some(CommitPreparation { pending, entry }) = self.plan_commit(req, arrival, terminal, plan, delta) else { break 'commit None }; self.common.pending.get_mut(&req).unwrap().last_arrival = Some(arrival); self.common.pending_commit = Some(pending); self.common.persistence_purpose = Some(entry.plan.purpose); Some(entry) }) else { break 'begin_commit false }; + entry.emit(&mut |effect| fx.push(effect)); + true + +} + +}, + SessionEvent::Command(Command::ResumeStored) => 'resume_stored: { + + if !matches!(self.common.authority, BootstrapAuthority::Account { .. }) { break 'resume_stored false; } + if self.state.phase() != Phase::Idle || !self.common.persisted.can_go_local() + || self.common.pending_commit.is_some() { break 'resume_stored false; } + let Some(req) = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::Ready, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }) else { break 'resume_stored false }; + let plan = CommitPlan { registry_client_id: self.common.persisted.client_id.clone(), + expected_disk: self.common.disk_identity.clone(), + credentials: None, lifecycle: None, + registry: vec![RegistryPlan::Install { sources: self.common.persisted.sources.clone(), + primary: None, commit: RosterCommit::Merge }], + purpose: PersistencePurpose::Background, writes_durable: false, + authority: plx_plex::plex::session::SaveAuthority::Routine }; + { let event = AttemptEvent::BeginStoredRestore { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + 'begin_commit: { +let (req, arrival, terminal, plan, delta,): (u32, u64, bool, CommitPlan, CommitDelta,) = (req, 0, true, plan, CommitDelta { + destination: CommitDestination::StoredReady, + phase: Some(Phase::Ready), activate_profile: true, ready: Some(false), + ..Default::default() + },); + + let Some(entry) = ('commit: { let (req, arrival, terminal, plan, delta): (u32, u64, bool, CommitPlan, CommitDelta) = (req, arrival, terminal, plan, delta); let Some(CommitPreparation { pending, entry }) = self.plan_commit(req, arrival, terminal, plan, delta) else { break 'commit None }; self.common.pending.get_mut(&req).unwrap().last_arrival = Some(arrival); self.common.pending_commit = Some(pending); self.common.persistence_purpose = Some(entry.plan.purpose); Some(entry) }) else { break 'begin_commit false }; + entry.emit(&mut |effect| fx.push(effect)); + true + +} + +}, + SessionEvent::Command(Command::StartLogin) => { restart = Some(if true { LoginRestart::Fresh } else { LoginRestart::Retry }); true }, + SessionEvent::Command(Command::Retry) => { + + use plx_plex::plex::session::PlaintextChoice; + if self.state.phase() == Phase::Error { + let account = plx_plex::plex::grant::account_key(&self.common.persisted.account_token); + let answered = self.state.plaintext().filter(|v| v.offers() + && matches!(v.choice, PlaintextChoice::Declined | PlaintextChoice::Revoked)); + if let (Some(v), false) = (answered, account.is_empty()) { + fx.push(SessionFx::PlaintextAnswer { + machine_id: v.machine_id.clone(), choice: PlaintextChoice::Undecided, account, + }); + } + } + { restart = Some(if false { LoginRestart::Fresh } else { LoginRestart::Retry }); true } + +}, + SessionEvent::Command(Command::TakeReady) => 'take_ready: { + + if self.state + .phase() != Phase::Ready || !self.state + .handoff_pending() + || self.common.pending_commit.is_some() { break 'take_ready false; } + // A discovery failure left a warning unacknowledged: the final fresh write must not run + // over it (AUTH-03) — acknowledging is what re-admits `needs_ready_commit`. + if self.common.persistence_warning.is_some() { break 'take_ready false; } + let Some(req) = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::Ready, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }) else { + { let event = AttemptEvent::ReadyExhausted; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + { publish = true; }; + break 'take_ready true; + }; + let mut next = self.common.persisted.clone(); + super::remember_unprotected_active(&mut next); + let patch = CredentialPatch::of(&next); + // Consumed exactly once: a discovery/rediscovery retry only PEEKS this flag + // (`apply_resource_observation`), so it cannot spend the authority the final write needs. + let fresh = self.state.fresh_authority(); + { let event = AttemptEvent::BeginReadyCommit { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + let authority = if fresh { + plx_plex::plex::session::SaveAuthority::FreshReauthentication + } else { plx_plex::plex::session::SaveAuthority::Routine }; + let plan = CommitPlan { registry_client_id: self.common.persisted.client_id.clone(), + expected_disk: self.common.disk_identity.clone(), + credentials: Some(patch.clone()), lifecycle: None, + registry: vec![RegistryPlan::Install { sources: next.sources.clone(), primary: None, commit: RosterCommit::Merge }], + purpose: PersistencePurpose::Final, writes_durable: true, authority }; + 'begin_commit: { +let (req, arrival, terminal, plan, delta,): (u32, u64, bool, CommitPlan, CommitDelta,) = (req, 0, true, plan, CommitDelta { + destination: CommitDestination::ReadyCommitted, + credentials: Some(patch), activate_profile: true, ready: Some(false), + ..Default::default() + },); + + let Some(entry) = ('commit: { let (req, arrival, terminal, plan, delta): (u32, u64, bool, CommitPlan, CommitDelta) = (req, arrival, terminal, plan, delta); let Some(CommitPreparation { pending, entry }) = self.plan_commit(req, arrival, terminal, plan, delta) else { break 'commit None }; self.common.pending.get_mut(&req).unwrap().last_arrival = Some(arrival); self.common.pending_commit = Some(pending); self.common.persistence_purpose = Some(entry.plan.purpose); Some(entry) }) else { break 'begin_commit false }; + entry.emit(&mut |effect| fx.push(effect)); + true + +} + +}, + SessionEvent::Command(Command::AcknowledgePersistenceWarning { key }) => + 'acknowledge_persistence_warning: { +let (key,): (PersistenceWarningKey,) = (*key,); + + if self.common.persistence_warning.map(|warning| warning.key) != Some(key) { break 'acknowledge_persistence_warning false; } + self.common.persistence_warning = None; + { + + if self.common.incident.as_ref().is_some_and(|offer| + offer.key.kind == plx_telemetry::telemetry::incident::IncidentKind::SaveFailed) { + self.common.incident = None; + } + +}; + // This authorization's unsaved-login question is answered now: storage may never gate + // entry a second time for it (AUTH-03's field bug). A later failure — Discovery then + // Final, or a retry — releases the handoff itself instead of asking again. + self.common.persistence_warning_answered = true; + if self.common.held_handoff.is_some() { + { + + self.common.held_handoff = None; + { +let (profile,): (Option,) = (Some(self.common.persisted.user.clone()),); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; + if self.state.phase() == Phase::Ready { + EntryFx::Ready { announcement: Some(ReadyEntry { epoch: self.common.epoch, scope: self.common.profile_scope, + server: self.common.persisted.server.clone(), token: self.common.persisted.pms_token().into(), + install: ReadyInstall::PrimaryAndExtras(match &self.common.authority { + BootstrapAuthority::Account { extras } => extras.clone(), + BootstrapAuthority::DevPms { .. } => Vec::new(), + }) }) }.emit(&mut |effect| fx.push(effect)); + } + +}; + } + { publish = true; }; + true + +}, + SessionEvent::Command(command @ (Command::ResolveIncident { .. } + | Command::ReportIncident { .. } | Command::DeclineIncident { .. })) => { + let handled = { +let (command,): (&Command,) = (command,); + + match command { + Command::ResolveIncident { id, permission, revision } => { + 'resolve_incident: { +let (id, permission, revision,): (u32, Permission, u32,) = (*id, *permission, *revision,); + + let seen = &self.common.incidents_seen; + let Some(held) = self.common.incident.as_mut().filter(|held| held.id == id) else { break 'resolve_incident false }; + match held.state { + IncidentState::Pending => {} + IncidentState::Offered { revision: at } | IncidentState::OnRequest { revision: at } + if at != revision => {} + IncidentState::Offered { .. } | IncidentState::OnRequest { .. } | IncidentState::AutoSending + | IncidentState::Sending | IncidentState::Queued { .. } | IncidentState::Saved { .. } + | IncidentState::Delivered { .. } | IncidentState::Failed | IncidentState::NotNow | IncidentState::Dropped => break 'resolve_incident false, + } + let key = held.key; + // Offered behind Details only: a kind the alert never covers, a key this launch has + // already asked about (the raise that brought it back is Pending over a seen key), and + // an offer already resolved that way — a later decision may drop it, never escalate it. + let quiet = !key.kind.alert_eligible() + || matches!(held.state, IncidentState::OnRequest { .. }) + || (held.state == IncidentState::Pending && seen.contains(&key)); + match permission { + Permission::Declined => { + held.state = IncidentState::Dropped; + held.context = None; + } + Permission::Granted | Permission::NotDetermined if quiet => { + held.state = IncidentState::OnRequest { revision }; + } + Permission::Granted if key.kind.standing_eligible() => { + let Some(context) = held.context else { break 'resolve_incident false }; + held.state = IncidentState::AutoSending; + fx.push(SessionFx::Incident { id, lane: IncidentLane::Standing, report: IncidentReport::Retained(context) }); + } + Permission::Granted | Permission::NotDetermined => { + held.state = IncidentState::Offered { revision }; + } + } + 'remember_seen: { +let (key,): (IncidentKey,) = (key,); + + if self.common.incidents_seen.contains(&key) { + break 'remember_seen; + } + if self.common.incidents_seen.len() >= SEEN_CAP { + self.common.incidents_seen.remove(0); + } + self.common.incidents_seen.push(key); + +}; + true + +} + } + Command::ReportIncident { id } => 'report_incident: { +let (id,): (u32,) = (*id,); + + let Some(held) = self.common.incident.as_mut().filter(|held| held.id == id && held.sendable()) else { + break 'report_incident false; + }; + let report = match held.context { + Some(context) => IncidentReport::Retained(context), + None => { + self.common.persistence_warning + .filter(|_| held.key.kind == IncidentKind::SaveFailed) + .and_then(|warning| warning.incident_context()) + .map(IncidentReport::Retained) + .unwrap_or(IncidentReport::AtPress(held.key)) + }, + }; + let key = held.key; + held.state = IncidentState::Sending; + fx.push(SessionFx::Incident { id, lane: IncidentLane::OneOff, report }); + 'remember_seen: { +let (key,): (IncidentKey,) = (key,); + + if self.common.incidents_seen.contains(&key) { + break 'remember_seen; + } + if self.common.incidents_seen.len() >= SEEN_CAP { + self.common.incidents_seen.remove(0); + } + self.common.incidents_seen.push(key); + +}; + true + +}, + Command::DeclineIncident { id } => 'decline_incident: { +let (id,): (u32,) = (*id,); + + let Some(held) = self.common.incident.as_mut().filter(|held| held.id == id) else { break 'decline_incident false }; + if !matches!(held.state, IncidentState::Offered { .. }) { + break 'decline_incident false; + } + held.state = IncidentState::NotNow; + true + +}, + Command::ActivateDevBootstrap | Command::ResumeStored | Command::StartLogin | Command::Retry + | Command::RestartWait { .. } | Command::StartSwitch(_) | Command::SelectProfile { .. } + | Command::SelectProfileWithReply { .. } | Command::DismissPinError | Command::BackAtRoot { .. } + | Command::SignOut | Command::EraseLocal | Command::NoteDeleteLeftovers(_) | Command::RefreshRoster + | Command::RequestEndpoint { .. } | Command::TakeReady | Command::AcknowledgePersistenceWarning { .. } + | Command::AnswerPlaintext { .. } => false, + } + +}; + if handled { { publish = true; }; } + handled + } + SessionEvent::Command(Command::StartSwitch(picker)) => 'start_switch: { +let (picker,): (Picker,) = (*picker,); + + if matches!(self.common.authority, BootstrapAuthority::DevPms { .. }) { + // A dev-token session has no account behind it to list a roster with. The account + // menu still offers *Change profile* (it reads the on-disk sign-in), and the app has + // already routed to the picker by the time this runs — so refusing SILENTLY left that + // route with nothing behind it: a spinner that never ends and a BACK that could not + // leave (#132, TV session 8). Say so on the picker instead; `back` returns. + // `picker` is deliberately not recorded: nothing is detached here, so there is no + // picker-kind rule for `back` to apply, and BACK restores this session state exactly. + if self.state.phase() != Phase::Ready || self.state.pending_erase().is_some() { break 'start_switch false; } + let _ = picker; + { let event = AttemptEvent::OpenDevPicker; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.switch_refused_for = Some(Identity::of(&self.common.persisted)); + { publish = true; }; + break 'start_switch true; + } + if self.state.pending_erase().is_some() { break 'start_switch false; } + if ('advance_epoch: { + + let exit = match ExitFx::epoch(self.view()) { Some(value) => value, None => break 'advance_epoch None }; + let epoch = exit.epoch_number(); + self.common.inbox.clear(); + self.common.pending_commit = None; + self.common.pending.clear(); + self.common.epoch = epoch; + { let event = AttemptEvent::EpochAdvanced; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + // Keep pump_pending: a marker may still be carried outside the owner. + exit.emit(&mut |effect| fx.push(effect)); + Some(epoch) + +}).is_none() { break 'start_switch false; } + if self.common.persisted.account_token.is_empty() { + { +let (message, incident,): (&str, Option,) = (plx_platform::i18n::msg::browse_auth_signed_out(), None,); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}; + { publish = true; }; + break 'start_switch true; + } + if super::detaches_active_profile(picker) { { +let (profile,): (Option,) = (None,); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; } + { let event = AttemptEvent::OpenPicker { kind: picker, fallback: if self.state.picker_data().users.is_empty() { self.common.persisted.home_users.iter().map(UserTile::of_ref).collect() } else { Vec::new() } }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + let mut initial = None; + if let Some(req) = 'reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::Picker, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) } { + let initial_profile = picker == Picker::Boot && self.common.active_profile.is_none() + && self.common.persisted.can_go_local(); + let mut registry = Vec::new(); + if initial_profile { + registry.push(RegistryPlan::Primary { server: self.common.persisted.server.clone(), + token: self.common.persisted.pms_token().into() }); + } + registry.push(RegistryPlan::Install { + sources: self.common.persisted.sources.clone(), primary: None, commit: RosterCommit::Merge, + }); + let plan = CommitPlan { registry_client_id: self.common.persisted.client_id.clone(), + expected_disk: self.common.disk_identity.clone(), + credentials: None, lifecycle: None, registry, + purpose: PersistencePurpose::Background, writes_durable: false, + authority: plx_plex::plex::session::SaveAuthority::Routine }; + { let event = AttemptEvent::InstallPicker { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + initial = 'commit: { let (req, arrival, terminal, plan, delta): (u32, u64, bool, CommitPlan, CommitDelta) = (req, 0, true, plan, CommitDelta { + activate_profile: initial_profile, ..Default::default() + }); let Some(CommitPreparation { pending, entry }) = self.plan_commit(req, arrival, terminal, plan, delta) else { break 'commit None }; self.common.pending.get_mut(&req).unwrap().last_arrival = Some(arrival); self.common.pending_commit = Some(pending); self.common.persistence_purpose = Some(entry.plan.purpose); Some(entry) }; + } + let server_roster = match 'reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::ServerRoster, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) } { Some(req) => Some( + { +let (req, input,): (u32, SessionWork,) = (req, SessionWork::ServerRoster { session: self.common.persisted.clone(), expected: Identity::of(&self.common.persisted) },); + + let pending = self.common.pending.get_mut(&req).expect("owned work request"); + let admission = AdmissionId(req); + pending.admission = AdmissionState::Awaiting(admission); + EntryWork::Work { req, key: pending.key, admission, input } + +}), None => None }; + let home_roster = match 'reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::HomeRoster, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) } { Some(req) => Some( + { +let (req, input,): (u32, SessionWork,) = (req, SessionWork::HomeRoster { client_id: self.common.persisted.client_id.clone(), account_token: self.common.persisted.account_token.clone(), expected: Identity::of(&self.common.persisted) },); + + let pending = self.common.pending.get_mut(&req).expect("owned work request"); + let admission = AdmissionId(req); + pending.admission = AdmissionState::Awaiting(admission); + EntryWork::Work { req, key: pending.key, admission, input } + +}), None => None }; + EntryFx::Profiles { setup: Some(PickerSetup { initial, server_roster, home_roster }) }.emit(&mut |effect| fx.push(effect)); + { publish = true; }; + true + +}, + SessionEvent::Command(Command::SelectProfile { index, pin }) => 'select_profile: { +let (index, pin,): (usize, Option,) = (*index, pin.clone(),); + + if self.state.pending_erase().is_some() || !matches!(self.state, attempt::Attempt::Profiles(_) | attempt::Attempt::Switching(_)) { break 'select_profile false; } + let Some(tile) = self.state.picker_data().users.get(index).cloned() else { break 'select_profile false }; + if self.common.next_req.checked_add(1).is_none() { break 'select_profile false; } + if ('advance_epoch: { + + let exit = match ExitFx::epoch(self.view()) { Some(value) => value, None => break 'advance_epoch None }; + let epoch = exit.epoch_number(); + self.common.inbox.clear(); + self.common.pending_commit = None; + self.common.pending.clear(); + self.common.epoch = epoch; + { let event = AttemptEvent::EpochAdvanced; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + // Keep pump_pending: a marker may still be carried outside the owner. + exit.emit(&mut |effect| fx.push(effect)); + Some(epoch) + +}).is_none() { break 'select_profile false; } + let same_user = super::may_reuse_seated_profile(&self.common.persisted, &tile, pin.as_deref()); + if same_user { + { let event = AttemptEvent::ReuseProfile; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } else { + let req = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::ProfileSwitch, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }).expect("request preflight"); + self.common.pending.get_mut(&req).unwrap().capture = Some(CaptureIntent::Profile { tile, pin }); + { let event = AttemptEvent::SelectProfile { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + { publish = true; }; + true + +}, + SessionEvent::Command(Command::SelectProfileWithReply { index, pin, reply }) => { + let accepted = 'select_profile: { +let (index, pin,): (usize, Option,) = (*index, pin.clone(),); + + if self.state.pending_erase().is_some() || !matches!(self.state, attempt::Attempt::Profiles(_) | attempt::Attempt::Switching(_)) { break 'select_profile false; } + let Some(tile) = self.state.picker_data().users.get(index).cloned() else { break 'select_profile false }; + if self.common.next_req.checked_add(1).is_none() { break 'select_profile false; } + if ('advance_epoch: { + + let exit = match ExitFx::epoch(self.view()) { Some(value) => value, None => break 'advance_epoch None }; + let epoch = exit.epoch_number(); + self.common.inbox.clear(); + self.common.pending_commit = None; + self.common.pending.clear(); + self.common.epoch = epoch; + { let event = AttemptEvent::EpochAdvanced; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + // Keep pump_pending: a marker may still be carried outside the owner. + exit.emit(&mut |effect| fx.push(effect)); + Some(epoch) + +}).is_none() { break 'select_profile false; } + let same_user = super::may_reuse_seated_profile(&self.common.persisted, &tile, pin.as_deref()); + if same_user { + { let event = AttemptEvent::ReuseProfile; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } else { + let req = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::ProfileSwitch, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }).expect("request preflight"); + self.common.pending.get_mut(&req).unwrap().capture = Some(CaptureIntent::Profile { tile, pin }); + { let event = AttemptEvent::SelectProfile { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + { publish = true; }; + true + +}; + fx.push(SessionFx::SelectionReply { to: *reply, accepted, flow_epoch: self.common.epoch }); + true + } + SessionEvent::Command(Command::BackAtRoot { reply }) => 'back: { +let (reply,): (ReplyTo,) = (*reply,); + + // AUTH-03: while an unacknowledged persistence warning is showing, BACK must not clear it + // or resume — clearing it here would silently re-admit `needs_ready_commit`/`take_ready` + // on the next frame (a second, routine save over the still-unconfirmed fresh one) and, for + // a held Final handoff, would release it without the explicit acknowledgement the warning + // exists to require. Only the labelled Continue (`acknowledge_persistence_warning`) may + // clear it; BACK here is the platform root press only. + if self.common.persistence_warning.is_some() { + fx.push(SessionFx::BackReply { to: reply, resumed: false }); + break 'back true; + } + let dead_end = self.view().roster_dead_end(); + if dead_end { + if matches!(self.common.authority, BootstrapAuthority::DevPms { .. }) { + // Nothing was detached or re-pointed (see `start_switch`): re-announce the dev + // session exactly as its activation did. + { let event = AttemptEvent::ResumeDevBack; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + fx.push(SessionFx::BackReply { to: reply, resumed: true }); + { publish = true; }; + break 'back true; + } + } + let stored = self.common.committed_credentials.merge_into(&self.common.persisted); + // A dead-end picker offered nobody, so the picker-kind rule (`may_resume`: the + // Change-profile picker is a root, so BACK cannot skip a PIN) has no boundary to guard. + // Only "is there a session to go back to" remains — `dead_end_resumes`, the same answer + // the read-out publishes so its *Back* control is offered exactly when this resumes. + let resumable = if dead_end { self.view().dead_end_resumes() } else { super::resumable(&stored, self.state + .picker_data().picker) }; + if !resumable || self.common.epoch.checked_add(1).is_none() { + fx.push(SessionFx::BackReply { to: reply, resumed: false }); + break 'back true; + } + ('advance_epoch: { + + let exit = match ExitFx::epoch(self.view()) { Some(value) => value, None => break 'advance_epoch None }; + let epoch = exit.epoch_number(); + self.common.inbox.clear(); + self.common.pending_commit = None; + self.common.pending.clear(); + self.common.epoch = epoch; + { let event = AttemptEvent::EpochAdvanced; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + // Keep pump_pending: a marker may still be carried outside the owner. + exit.emit(&mut |effect| fx.push(effect)); + Some(epoch) + +}).expect("epoch preflight"); + self.common.persisted = stored; + { let event = AttemptEvent::ResumeBack; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + fx.push(SessionFx::BackReply { to: reply, resumed: true }); + { publish = true; }; + true + +}, + SessionEvent::Command(Command::SignOut) => 'erase: { +let (sign_in,): (bool,) = (true,); + + if self.state .pending_erase().is_some() || self.common.epoch.checked_add(1).is_none() { break 'erase false; } + ExitFx::for_state(&self.state, ExitActions { cancel: None, acknowledge: Vec::new(), coordinator: Some(CoordinatorAction::CloseTelemetry) }).emit(&mut |effect| fx.push(effect)); + ('advance_epoch: { + + let exit = match ExitFx::epoch(self.view()) { Some(value) => value, None => break 'advance_epoch None }; + let epoch = exit.epoch_number(); + self.common.inbox.clear(); + self.common.pending_commit = None; + self.common.pending.clear(); + self.common.epoch = epoch; + { let event = AttemptEvent::EpochAdvanced; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + // Keep pump_pending: a marker may still be carried outside the owner. + exit.emit(&mut |effect| fx.push(effect)); + Some(epoch) + +}).expect("epoch preflight"); + self.common.persisted = PersistedSession::default(); + self.common.committed_credentials = CredentialPatch::of(&self.common.persisted); + // The identity ends here, and its verdicts with it: the same account signed back in is + // the same `Identity`, and nothing has refused it anything in that sign-in. + self.common.switch_refused_for = None; + self.common.authority = BootstrapAuthority::Account { extras: Vec::new() }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + { let event = AttemptEvent::EraseAuthority; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + { + + self.common.incident = None; + self.common.incidents_seen.clear(); + { let event = AttemptEvent::LinkTrouble { present: false }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |_| {}); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |_| {}); true }; + +}; + { +let (profile,): (Option,) = (None,); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; + { let event = AttemptEvent::BeginErase { epoch: self.common.epoch, sign_in }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + { publish = true; }; + true + +}, + SessionEvent::Command(Command::EraseLocal) => 'erase: { +let (sign_in,): (bool,) = (false,); + + if self.state .pending_erase().is_some() || self.common.epoch.checked_add(1).is_none() { break 'erase false; } + ExitFx::for_state(&self.state, ExitActions { cancel: None, acknowledge: Vec::new(), coordinator: Some(CoordinatorAction::CloseTelemetry) }).emit(&mut |effect| fx.push(effect)); + ('advance_epoch: { + + let exit = match ExitFx::epoch(self.view()) { Some(value) => value, None => break 'advance_epoch None }; + let epoch = exit.epoch_number(); + self.common.inbox.clear(); + self.common.pending_commit = None; + self.common.pending.clear(); + self.common.epoch = epoch; + { let event = AttemptEvent::EpochAdvanced; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + // Keep pump_pending: a marker may still be carried outside the owner. + exit.emit(&mut |effect| fx.push(effect)); + Some(epoch) + +}).expect("epoch preflight"); + self.common.persisted = PersistedSession::default(); + self.common.committed_credentials = CredentialPatch::of(&self.common.persisted); + // The identity ends here, and its verdicts with it: the same account signed back in is + // the same `Identity`, and nothing has refused it anything in that sign-in. + self.common.switch_refused_for = None; + self.common.authority = BootstrapAuthority::Account { extras: Vec::new() }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + { let event = AttemptEvent::EraseAuthority; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + { + + self.common.incident = None; + self.common.incidents_seen.clear(); + { let event = AttemptEvent::LinkTrouble { present: false }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |_| {}); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |_| {}); true }; + +}; + { +let (profile,): (Option,) = (None,); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; + { let event = AttemptEvent::BeginErase { epoch: self.common.epoch, sign_in }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + { publish = true; }; + true + +}, + SessionEvent::Command(Command::RefreshRoster) => 'refresh_roster: { + + if self.common.persisted.account_token.is_empty() { break 'refresh_roster false; } + let Some(req) = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::ServerRoster, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }) else { break 'refresh_roster false }; + { +let (req, input,): (u32, SessionWork,) = (req, SessionWork::ServerRoster { session: self.common.persisted.clone(), + expected: Identity::of(&self.common.persisted) },); + + ({ +let (req, input,): (u32, SessionWork,) = (req, input,); + + let pending = self.common.pending.get_mut(&req).expect("owned work request"); + let admission = AdmissionId(req); + pending.admission = AdmissionState::Awaiting(admission); + EntryWork::Work { req, key: pending.key, admission, input } + +}).emit(&mut |effect| fx.push(effect)); + +}; + true + +}, + SessionEvent::Command(Command::RequestEndpoint { sid }) => 'request_endpoint: { +let (sid,): (plx_plex::plex::ServerId,) = (*sid,); + + // The registry's own validity rule: every id but the reserved UNSET names a slot. + if !sid.is_set() + || self.common.persisted.account_token.is_empty() + || self.common.pending.values().any(|pending| pending.key.op == SessionOp::Endpoint(sid.raw())) { + break 'request_endpoint false; + } + let sid = sid.raw(); + let Some(req) = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::Endpoint(sid), None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }) else { break 'request_endpoint false }; + self.common.pending.get_mut(&req).unwrap().capture = Some(CaptureIntent::Endpoint { sid }); + fx.push(SessionFx::Capture { req, epoch: self.common.epoch, request: SessionReadRequest::Endpoint { sid } }); + true + +}, + SessionEvent::Command(Command::AnswerPlaintext { machine_id, choice, sid }) => + 'answer_plaintext: { +let (machine_id, choice, sid,): (&str, plx_plex::plex::session::PlaintextChoice, Option,) = (machine_id, *choice, *sid,); + + use plx_plex::plex::session::PlaintextChoice; + let account = plx_plex::plex::grant::account_key(&self.common.persisted.account_token); + if account.is_empty() || machine_id.is_empty() || choice == PlaintextChoice::Undecided { + break 'answer_plaintext false; + } + let on_sign_in = self.state.phase() == Phase::Error; + if on_sign_in && !self.state.plaintext().is_some_and(|v| v.machine_id == machine_id) { + break 'answer_plaintext false; + } + fx.push(SessionFx::PlaintextAnswer { machine_id: machine_id.to_owned(), choice, account }); + if on_sign_in { + if choice.allows() { + break 'answer_plaintext ({ restart = Some(if false { LoginRestart::Fresh } else { LoginRestart::Retry }); true }); } + { let event = AttemptEvent::PlaintextDeclined { choice }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + { publish = true; }; + break 'answer_plaintext true; } - if let Some(phase) = delta.phase { self.state.phase = phase; } - if let Some(picker) = delta.picker { self.state.picker = picker; } - if let Some(users) = delta.users { self.state.users = users; } - if delta.roster_answered { self.state.switch_refused_for = None; } - if let Some(ready) = delta.ready { self.state.apply_pending = ready; } - if delta.clear_error { - self.state.error.clear(); - self.state.pin_denied = false; - } - if delta.profile_seated { - let pending = self.state.pending.get_mut(&reply.req).unwrap(); - pending.expected = Identity::of(&self.state.persisted); - pending.phase = StreamPhase::ProfileSeated; - self.cancel_obsolete_interests(reply.req, emit); + if choice.allows() { + let _ = match sid { + Some(sid) => 'request_endpoint: { +let (sid,): (plx_plex::plex::ServerId,) = (sid,); + + // The registry's own validity rule: every id but the reserved UNSET names a slot. + if !sid.is_set() + || self.common.persisted.account_token.is_empty() + || self.common.pending.values().any(|pending| pending.key.op == SessionOp::Endpoint(sid.raw())) { + break 'request_endpoint false; + } + let sid = sid.raw(); + let Some(req) = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::Endpoint(sid), None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }) else { break 'request_endpoint false }; + self.common.pending.get_mut(&req).unwrap().capture = Some(CaptureIntent::Endpoint { sid }); + fx.push(SessionFx::Capture { req, epoch: self.common.epoch, request: SessionReadRequest::Endpoint { sid } }); + true + +}, + None => 'refresh_roster: { + + if self.common.persisted.account_token.is_empty() { break 'refresh_roster false; } + let Some(req) = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::ServerRoster, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }) else { break 'refresh_roster false }; + { +let (req, input,): (u32, SessionWork,) = (req, SessionWork::ServerRoster { session: self.common.persisted.clone(), + expected: Identity::of(&self.common.persisted) },); + + ({ +let (req, input,): (u32, SessionWork,) = (req, input,); + + let pending = self.common.pending.get_mut(&req).expect("owned work request"); + let admission = AdmissionId(req); + pending.admission = AdmissionState::Awaiting(admission); + EntryWork::Work { req, key: pending.key, admission, input } + +}).emit(&mut |effect| fx.push(effect)); + +}; + true + +}, + }; + } + true + +}, + SessionEvent::Command(Command::RestartWait { phase, qr_generation, reply }) => { + let accepted = matches!(self.common.authority, BootstrapAuthority::Account { .. }) + && super::restart_permitted(Some((*phase, *qr_generation)), + (self.state.phase(), self.state.qr().generation)) && { restart = Some(if false { LoginRestart::Fresh } else { LoginRestart::Retry }); true }; + { restart_reply = Some((reply, accepted)); }; + true + } + SessionEvent::Command(Command::DismissPinError) => { + let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); + self.state = attempt.dismiss_pin(); + { publish = true; }; + true + } + SessionEvent::Command(Command::NoteDeleteLeftovers(count)) => { + self.common.delete_leftovers = *count; + { publish = true; }; + true + } + SessionEvent::Result(envelope) => 'ingest: { +let (envelope,): (&SessionEnvelope,) = (envelope,); + + let receipt = Receipt::of(envelope); + if self.owns_receipt(receipt) { break 'ingest true; } + if !self.accepts_header(envelope) { + fx.push(SessionFx::Acknowledge(vec![receipt])); + break 'ingest true; + } + // The adapter admits only receipt-bearing records from an accepted resource. This can + // also confirm acceptance if its small admission reply is still carried in the queue. + self.common.pending.get_mut(&envelope.addr.req.0).unwrap().admission = AdmissionState::Accepted(envelope.admission); + let active = usize::from(self.common.pending_commit.as_ref().is_some_and(|commit| commit.receipt.is_some())); + assert!(self.common.inbox.len() + active < SESSION_TRANSFER_RECORDS, "Session transfer credit invariant"); + // Do not advance last_arrival here: that is the processing watermark, not receipt + // admission. Advancing it would make the FIFO head reject its own first delivery. + self.common.inbox.push_back(envelope.clone()); + if self.common.pending_commit.is_none() && !self.common.pump_pending { { pump = true; }; } + true + +}, + SessionEvent::Commit(reply) => 'apply_commit_reply: { +let (reply,): (CommitReply,) = (*reply,); + + if !self.commit_is_current(reply.req, reply.epoch, reply.arrival) { break 'apply_commit_reply false; } + // `take()` is what makes a duplicate reply inert. The admitted revision and purpose are + // copied into `admitted_persistence` first, because that is the identity a later + // completion must repeat exactly to be allowed to settle anything. + let admit_revision = reply.admission.admitted_revision(); + // The admission names what storage was actually asked for; the plan only records intent. + let admit_purpose = reply.admission.admitted_purpose() + .or_else(|| self.common.pending_commit.as_ref().and_then(|c| c.purpose)); + let commit = self.common.pending_commit.take().unwrap(); + self.common.admitted_persistence = admit_revision.map(|revision| AdmittedPersistence { + req: commit.req, epoch: commit.epoch, arrival: commit.arrival, revision, + purpose: admit_purpose, fresh: commit.fresh, + site: match admit_purpose { + Some(PersistencePurpose::Discovery) => PersistenceWarningSite::Discovery, + _ => PersistenceWarningSite::Final, + } }); + self.common.commit_phase = CommitPhase { + admitted: admit_revision.is_some(), + durable: false, + proves_saved_login: false, + }; + self.common.persistence_purpose = None; + if !reply.admission.accepted() { + if let Some(DevCommitDelta::StartAccount { login_req }) = commit.delta.dev { + { +let (req,): (u32,) = (login_req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + } + let op = self.common.pending[&reply.req].key.op; + match op { + SessionOp::Login | SessionOp::Rediscover => { +let (message, incident,): (&str, Option,) = (plx_platform::i18n::msg::browse_auth_finish_failed(), Some(IncidentContext::internal(InternalClass::CommitRefused)),); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}, + SessionOp::ProfileSwitch | SessionOp::Ready => { + { let event = AttemptEvent::SwitchCommitRefused; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + SessionOp::HomeRoster | SessionOp::ServerRoster | SessionOp::Endpoint(_) | SessionOp::Picker => {} + SessionOp::DevBoundary => { + { let event = AttemptEvent::DevCommitRefused; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + } + { +let (req,): (u32,) = (reply.req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + if let Some(receipt) = commit.receipt { fx.push(SessionFx::Acknowledge(vec![receipt])); } + { + + if !self.common.inbox.is_empty() && self.common.pending_commit.is_none() && !self.common.pump_pending { + self.common.pump_pending = true; + fx.push(SessionFx::Pump); + } + +}; + { publish = true; }; + break 'apply_commit_reply true; + } + let delta = commit.delta; + if let Some(dev) = &delta.dev { + match dev { + DevCommitDelta::Activated => { + if matches!(self.common.authority, BootstrapAuthority::DevPms { .. }) { + { +let (profile,): (Option,) = (None,); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; + { let event = AttemptEvent::ActivateDev; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + } + DevCommitDelta::StartAccount { login_req } => { + self.common.authority = BootstrapAuthority::Account { extras: Vec::new() }; + { let event = AttemptEvent::BeginSignin { req: *login_req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + { +let (req,): (u32,) = (*login_req,); + + let entry = EntryFx::login(self.view(), req, false, false); + let pending = self.common.pending.get_mut(&req).expect("reserved login"); + match entry.work() { + EntryWork::Capture { .. } => pending.capture = Some(CaptureIntent::Login), + EntryWork::Work { admission, .. } => pending.admission = AdmissionState::Awaiting(*admission), + } + entry.emit(&mut |effect| fx.push(effect)); + +}; + } + } + } + if let Some(patch) = delta.credentials { + self.common.persisted = patch.merge_into(&self.common.persisted); + if commit.writes_credentials { + let prior = std::mem::replace(&mut self.common.disk_identity, patch.identity()); + self.common.unconfirmed_fresh_prior = + (commit.fresh && admit_revision.is_some()).then_some(prior); + self.common.committed_credentials = patch; + } + } + match delta.destination { + CommitDestination::Unchanged => {} + CommitDestination::Roster => { if let Some(users) = delta.users { { let event = AttemptEvent::RosterArrived { users }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } } + CommitDestination::ReadyCommitted => { { let event = AttemptEvent::ReadyCommitted; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } + CommitDestination::SignInProfiles => { { let event = AttemptEvent::SigninProfiles { users: delta.users.expect("sign-in roster") }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } + CommitDestination::SignInReady => { { let event = AttemptEvent::SigninReady; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } + CommitDestination::ProfileReady => { { let event = AttemptEvent::ProfileReady { req: reply.req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } + CommitDestination::StoredReady => { { let event = AttemptEvent::StoredReady; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } } - if delta.complete_signin && std::mem::take(&mut self.state.signin_active) { - emit(SessionFx::Coordinator(CoordinatorAction::SignInCompleted)); + if delta.roster_answered { self.common.switch_refused_for = None; } + if matches!(delta.destination, CommitDestination::ProfileReady) { + let pending = self.common.pending.get_mut(&reply.req).unwrap(); + pending.expected = Identity::of(&self.common.persisted); + pending.phase = StreamPhase::ProfileSeated; + 'cancel_obsolete_interests: { +let (retained,): (u32,) = (reply.req,); + + let requests: Vec<_> = self.common.pending.iter().filter_map(|(&req, pending)| + (req != retained && !pending.expected.matches(&self.common.persisted)).then_some(req)).collect(); + if requests.is_empty() { break 'cancel_obsolete_interests; } + for req in &requests { self.common.pending.remove(req); } + let mut receipts = Vec::new(); + self.common.inbox.retain(|record| { + if requests.contains(&record.addr.req.0) { + receipts.push(Receipt::of(record)); + false + } else { true } + }); + fx.push(SessionFx::Cancel { requests, epoch: self.common.epoch }); + if !receipts.is_empty() { fx.push(SessionFx::Acknowledge(receipts)); } + +}; } if delta.activate_profile { - if commit.fresh && admit_revision.is_some() && !self.state.persistence_warning_answered { + if commit.fresh && admit_revision.is_some() && !self.common.persistence_warning_answered { // The fresh write is admitted but not yet confirmed durable: hold the handoff // rather than announce Ready/publish the profile until a completion (or an // acknowledged warning) releases it — the AUTH-03 gate. - self.state.held_handoff = Some(HeldHandoff { epoch: commit.epoch, req: commit.req }); - } else if self.state.persistence_warning.is_none() { + self.common.held_handoff = Some(HeldHandoff { epoch: commit.epoch, req: commit.req }); + } else if self.common.persistence_warning.is_none() { // `persistence_warning_answered` true means this authorization already spent its // one Continue: nothing is left to wait for, so a fresh write lands here exactly // like a routine one — publish immediately rather than hold a handoff whose @@ -1677,165 +3394,564 @@ impl SessionMachine { // a handoff still held behind an unacknowledged warning — that release is // `acknowledge_persistence_warning`'s alone. An unrelated held handoff with NO live // warning (already superseded above, or never one to begin with) is unaffected. - self.release_held_handoff(emit); + { + + self.common.held_handoff = None; + { +let (profile,): (Option,) = (Some(self.common.persisted.user.clone()),); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; + if self.state.phase() == Phase::Ready { + EntryFx::Ready { announcement: Some(ReadyEntry { epoch: self.common.epoch, scope: self.common.profile_scope, + server: self.common.persisted.server.clone(), token: self.common.persisted.pms_token().into(), + install: ReadyInstall::PrimaryAndExtras(match &self.common.authority { + BootstrapAuthority::Account { extras } => extras.clone(), + BootstrapAuthority::DevPms { .. } => Vec::new(), + }) }) }.emit(&mut |effect| fx.push(effect)); + } + +}; } } - if commit.terminal { - self.state.pending.remove(&reply.req); - emit(SessionFx::Retire { req: reply.req }); + if commit.terminal { { +let (req,): (u32,) = (reply.req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; } + if let Some(receipt) = commit.receipt { fx.push(SessionFx::Acknowledge(vec![receipt])); } + { + + if !self.common.inbox.is_empty() && self.common.pending_commit.is_none() && !self.common.pump_pending { + self.common.pump_pending = true; + fx.push(SessionFx::Pump); } - if let Some(receipt) = commit.receipt { emit(SessionFx::Acknowledge(vec![receipt])); } - self.schedule_pump(emit); - self.replace_publication(); + +}; + { publish = true; }; true - } - fn retire(&mut self, req: u32, emit: &mut impl FnMut(SessionFx)) { - self.state.pending.remove(&req); - emit(SessionFx::Retire { req }); - } +}, + SessionEvent::DiskWrite { before, after, outcome } => 'observe_disk_write: { +let (before, after, outcome,): (&Identity, &Identity, plx_plex::plex::session::async_persistence::CompletionOutcome,) = (before, after, *outcome,); - /// The single site that publishes a profile and announces `SessionFx::Ready`. A fresh - /// handoff reaches it only once its write is released — durably confirmed, or its warning - /// acknowledged; a non-fresh (`Routine`) commit reaches it immediately, exactly as before. - fn release_held_handoff(&mut self, emit: &mut impl FnMut(SessionFx)) { - self.state.held_handoff = None; - self.publish_profile(Some(self.state.persisted.user.clone()), emit); - if self.state.phase == Phase::Ready { - emit(SessionFx::Ready { epoch: self.state.epoch, scope: self.state.profile_scope, - server: self.state.persisted.server.clone(), token: self.state.persisted.pms_token().into(), - install: ReadyInstall::PrimaryAndExtras(match &self.state.authority { + use plx_plex::plex::session::async_persistence::{CompletionOutcome, Operation}; + if self.common.disk_identity != *before || before == after + || !matches!(outcome, CompletionOutcome::Durable(Operation::Write { .. })) { break 'observe_disk_write false; } + self.common.disk_identity = after.clone(); + true + +}, + SessionEvent::Persistence(completion) => 'apply_persistence_completion: { +let (completion,): (plx_plex::plex::session::async_persistence::PersistenceCompletion,) = (*completion,); + + use plx_plex::plex::session::async_persistence::CompletionOutcome; + let Some(admitted) = self.common.admitted_persistence else { break 'apply_persistence_completion false }; + let correlation = plx_plex::plex::session::async_persistence::PersistenceCorrelation { + req: admitted.req, epoch: admitted.epoch, arrival: admitted.arrival, + }; + if !completion.acts_on(correlation, admitted.revision) { break 'apply_persistence_completion false; } + // A verdict the worker resolved for a DIFFERENT purpose than the one admitted is not this + // operation's verdict either. + if admitted.purpose.is_some_and(|purpose| purpose != completion.purpose) { break 'apply_persistence_completion false; } + let durable = matches!(completion.outcome, CompletionOutcome::Durable(_)); + self.common.admitted_persistence = None; + let prior = self.common.unconfirmed_fresh_prior.take(); + if let (Some(prior), CompletionOutcome::Failed(_)) = (prior, &completion.outcome) { + if admitted.fresh { self.common.disk_identity = prior; } + } + self.common.commit_phase.durable = durable; + self.common.commit_phase.proves_saved_login = + durable && completion.purpose.proves_saved_login(); + let correlation_key = PersistenceWarningKey { epoch: completion.epoch, req: completion.req }; + if durable { + // 0.6.6 parity: a later FRESH write landing durably supersedes any warning still + // showing about an earlier fresh attempt — the failure it was reporting on no longer + // describes the session's current state, so holding it would strand an acknowledgement + // over a problem that already resolved itself. + let superseded = admitted.fresh && self.common.persistence_warning.is_some(); + if superseded { + self.common.persistence_warning = None; + { + + if self.common.incident.as_ref().is_some_and(|offer| + offer.key.kind == plx_telemetry::telemetry::incident::IncidentKind::SaveFailed) { + self.common.incident = None; + } + +}; + } + // Release only the handoff THIS completion is for — a routine completion arriving + // while an unrelated fresh handoff is held must not free it. + let released = self.common.held_handoff == Some(HeldHandoff { epoch: completion.epoch, req: completion.req }); + if released { { + + self.common.held_handoff = None; + { +let (profile,): (Option,) = (Some(self.common.persisted.user.clone()),); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; + if self.state.phase() == Phase::Ready { + EntryFx::Ready { announcement: Some(ReadyEntry { epoch: self.common.epoch, scope: self.common.profile_scope, + server: self.common.persisted.server.clone(), token: self.common.persisted.pms_token().into(), + install: ReadyInstall::PrimaryAndExtras(match &self.common.authority { BootstrapAuthority::Account { extras } => extras.clone(), BootstrapAuthority::DevPms { .. } => Vec::new(), - }) }); + }) }) }.emit(&mut |effect| fx.push(effect)); } - } - fn retire_save_incident(&mut self) { - if self.state.incident.as_ref().is_some_and(|offer| +}; } + if superseded || released { { publish = true; }; } + } else if admitted.fresh { + if self.common.persistence_warning_answered { + // This authorization already had its one unsaved-login question answered + // (AUTH-03's field bug: a device unwritable on BOTH Discovery and Final used to + // ask it twice). Storage failing again must not ask it a second time — release + // whatever handoff this completion was holding so entry proceeds regardless. + let released = self.common.held_handoff == Some(HeldHandoff { epoch: completion.epoch, req: completion.req }); + if released { { + + self.common.held_handoff = None; + { +let (profile,): (Option,) = (Some(self.common.persisted.user.clone()),); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; + if self.state.phase() == Phase::Ready { + EntryFx::Ready { announcement: Some(ReadyEntry { epoch: self.common.epoch, scope: self.common.profile_scope, + server: self.common.persisted.server.clone(), token: self.common.persisted.pms_token().into(), + install: ReadyInstall::PrimaryAndExtras(match &self.common.authority { + BootstrapAuthority::Account { extras } => extras.clone(), + BootstrapAuthority::DevPms { .. } => Vec::new(), + }) }) }.emit(&mut |effect| fx.push(effect)); + } + +}; { publish = true; }; } + } else { + // The final write's own non-durable completion replaces a Discovery warning still + // showing (`Discovery` and `Final` never coexist: an unacknowledged Discovery warning + // blocks `take_ready`), so the newer one wins by direct overwrite. + let warning = PersistenceWarning::from_outcome(correlation_key, admitted.site, &completion.outcome); + { + + if self.common.incident.as_ref().is_some_and(|offer| offer.key.kind == plx_telemetry::telemetry::incident::IncidentKind::SaveFailed) { - self.state.incident = None; + self.common.incident = None; } - } - /// The AUTH-03 acknowledgement door: clears the warning and, if a handoff is still held for - /// it, releases it — exactly ONE `SessionFx::Ready` for the flow, through - /// [`Self::release_held_handoff`], never a second one from here. - fn acknowledge_persistence_warning(&mut self, key: PersistenceWarningKey, - emit: &mut impl FnMut(SessionFx)) -> bool { - if self.state.persistence_warning.map(|warning| warning.key) != Some(key) { return false; } - self.state.persistence_warning = None; - self.retire_save_incident(); - // This authorization's unsaved-login question is answered now: storage may never gate - // entry a second time for it (AUTH-03's field bug). A later failure — Discovery then - // Final, or a retry — releases the handoff itself instead of asking again. - self.state.persistence_warning_answered = true; - if self.state.held_handoff.is_some() { - self.release_held_handoff(emit); +}; + self.common.persistence_warning = Some(warning); + if warning.helper.is_some() { + // The reducer reads no clock. Both report paths use this fenced completion's + // local warning evidence, not later process-global diagnostics. + if let Some(context) = warning.incident_context() { + 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}; + } + } + { publish = true; }; + } } - self.replace_publication(); true - } - fn emit_work(&mut self, req: u32, input: SessionWork, emit: &mut impl FnMut(SessionFx)) { - let pending = self.state.pending.get_mut(&req).expect("owned work request"); +}, + SessionEvent::Read(reply) => 'apply_read: { +let (reply,): (&SessionReadReply,) = (reply,); + + if reply.addr.to != MachineId::Session || reply.epoch != self.common.epoch { break 'apply_read false; } + let req = reply.addr.req.0; + let Some(pending) = self.common.pending.get(&req) else { break 'apply_read false }; + if pending.key.epoch != reply.epoch || !pending.expected.matches(&self.common.persisted) || !self.state.owns_work(req, pending) { break 'apply_read false; } + let Some(intent) = pending.capture.clone() else { break 'apply_read false }; + let input = match (intent, &reply.value) { + (CaptureIntent::Login, SessionReadValue::LoginClientId(client_id)) if !client_id.is_empty() => { + if self.common.disk_identity.client_id.is_empty() { + self.common.disk_identity.client_id = client_id.clone(); + } + self.common.persisted.client_id = client_id.clone(); + self.common.committed_credentials.client_id = client_id.clone(); + self.common.pending.get_mut(&req).unwrap().expected = Identity::of(&self.common.persisted); + SessionWork::Login { client_id: client_id.clone() } + } + (CaptureIntent::Profile { tile, pin }, SessionReadValue::ProfilePolicy { recently_unreachable }) => + SessionWork::ProfileSwitch { session: self.common.persisted.clone(), + expected: Identity::of(&self.common.persisted), tile, pin, recently_unreachable: *recently_unreachable }, + (CaptureIntent::Endpoint { sid }, SessionReadValue::Endpoint(Some(captured))) + if captured.lifecycle.sid == sid && self.common.persisted.sources.iter().any(|source| + source.machine_id == captured.machine_id && source.dialable()) => { + self.common.pending.get_mut(&req).unwrap().lifecycle = Some(captured.lifecycle); + SessionWork::Endpoint { session: self.common.persisted.clone(), expected: Identity::of(&self.common.persisted), + lifecycle: captured.lifecycle, machine_id: captured.machine_id.clone() } + } + (CaptureIntent::Endpoint { .. }, SessionReadValue::Endpoint(_)) => { + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + break 'apply_read true; + } + (CaptureIntent::Login, SessionReadValue::LoginClientId(_)) => { + { +let (message, incident,): (&str, Option,) = (plx_platform::i18n::msg::browse_auth_start_failed(), Some(IncidentContext::internal(InternalClass::ClientIdUnavailable)),); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + { publish = true; }; + break 'apply_read true; + } + _ => break 'apply_read false, + }; + let pending = self.common.pending.get_mut(&req).unwrap(); + pending.capture = None; + { +let (req, input,): (u32, SessionWork,) = (req, input,); + + ({ +let (req, input,): (u32, SessionWork,) = (req, input,); + + let pending = self.common.pending.get_mut(&req).expect("owned work request"); let admission = AdmissionId(req); pending.admission = AdmissionState::Awaiting(admission); - emit(SessionFx::Work { req, key: pending.key, admission, input }); - } + EntryWork::Work { req, key: pending.key, admission, input } - pub fn work_is_current(&self, req: u32, key: SessionWorkKey, admission: AdmissionId) -> bool { - key.epoch == self.state.epoch && self.state.pending.get(&req).is_some_and(|pending| - pending.key == key && pending.capture.is_none() - && pending.admission == AdmissionState::Awaiting(admission) - && pending.expected.matches(&self.state.persisted)) - } +}).emit(&mut |effect| fx.push(effect)); + +}; + true + +}, + SessionEvent::Admission(reply) => 'apply_admission: { +let (reply,): (AdmissionReply,) = (*reply,); - fn apply_admission(&mut self, reply: AdmissionReply, emit: &mut impl FnMut(SessionFx)) -> bool { - if reply.addr.to != MachineId::Session || reply.key.epoch != self.state.epoch { return false; } + if reply.addr.to != MachineId::Session || reply.key.epoch != self.common.epoch { break 'apply_admission false; } let req = reply.addr.req.0; - let Some(pending) = self.state.pending.get_mut(&req) else { return false }; - if pending.key != reply.key || pending.admission != AdmissionState::Awaiting(reply.correlation) { return false; } + if !self.common.pending.get(&req).is_some_and(|pending| self.state.owns_work(req, pending)) { break 'apply_admission false; } + let Some(pending) = self.common.pending.get_mut(&req) else { break 'apply_admission false }; + if pending.key != reply.key || pending.admission != AdmissionState::Awaiting(reply.correlation) { break 'apply_admission false; } if reply.accepted { pending.admission = AdmissionState::Accepted(reply.correlation); } else { // This is an unsequenced, never-admitted refusal. Accepted requests (including ones // without a first observation) cannot enter this branch. match pending.key.op { - SessionOp::Login => self.fail_login(plx_platform::i18n::msg::browse_auth_start_failed(), - Some(IncidentContext::internal(InternalClass::AdmissionRefused)), emit), - SessionOp::Rediscover => self.fail_login(plx_platform::i18n::msg::browse_auth_rediscover_failed(), - Some(IncidentContext::internal(InternalClass::AdmissionRefused)), emit), + SessionOp::Login => { +let (message, incident,): (&str, Option,) = (plx_platform::i18n::msg::browse_auth_start_failed(), Some(IncidentContext::internal(InternalClass::AdmissionRefused)),); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}, + SessionOp::Rediscover => { +let (message, incident,): (&str, Option,) = (plx_platform::i18n::msg::browse_auth_rediscover_failed(), Some(IncidentContext::internal(InternalClass::AdmissionRefused)),); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); + +}, + None => self.common.incident = None, + } + +}, SessionOp::ProfileSwitch => { - self.state.phase = Phase::Profiles; - self.state.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); + { let event = AttemptEvent::SwitchAdmissionRefused; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } - SessionOp::HomeRoster => self.fail_empty_home_roster(roster_unreachable()), - _ => {} - } - self.retire(req, emit); - self.replace_publication(); + SessionOp::HomeRoster => { +let (reason,): (&str,) = (roster_unreachable(),); + + if self.state.picker_data().users.is_empty() && self.state.phase() == Phase::Profiles { + { let event = AttemptEvent::RosterFailed { message: reason.to_owned() }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } - self.schedule_pump(emit); - true - } - fn advance_epoch(&mut self, emit: &mut impl FnMut(SessionFx)) -> Option { - let epoch = self.state.epoch.checked_add(1)?; - let requests = self.state.pending.keys().copied().collect(); - self.discard_owned_envelopes(emit); - self.state.pending.clear(); - self.state.epoch = epoch; - self.state.discovery_retry = None; - emit(SessionFx::Cancel { requests, epoch }); - Some(epoch) - } +}, + SessionOp::ServerRoster | SessionOp::Endpoint(_) | SessionOp::Ready | SessionOp::Picker | SessionOp::DevBoundary => {} + } + { +let (req,): (u32,) = (req,); - fn owns_receipt(&self, receipt: Receipt) -> bool { - self.state.inbox.iter().any(|record| Receipt::of(record) == receipt) - || self.state.pending_commit.as_ref().and_then(|commit| commit.receipt) == Some(receipt) - } + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); - fn schedule_pump(&mut self, emit: &mut impl FnMut(SessionFx)) { - if !self.state.inbox.is_empty() && self.state.pending_commit.is_none() && !self.state.pump_pending { - self.state.pump_pending = true; - emit(SessionFx::Pump); +}; + { publish = true; }; } - } + { - fn discard_owned_envelopes(&mut self, emit: &mut impl FnMut(SessionFx)) { - let mut receipts: Vec<_> = self.state.inbox.drain(..).map(|record| Receipt::of(&record)).collect(); - if let Some(commit) = self.state.pending_commit.take() { - emit(SessionFx::Cancel { requests: vec![commit.req], epoch: self.state.epoch }); - if let Some(receipt) = commit.receipt { receipts.push(receipt); } + if !self.common.inbox.is_empty() && self.common.pending_commit.is_none() && !self.common.pump_pending { + self.common.pump_pending = true; + fx.push(SessionFx::Pump); } - // Keep pump_pending: the marker may still be an App effect or a carried typed event. - // Carried envelope receipts are not ours yet and therefore are NOT acknowledged here. - if !receipts.is_empty() { emit(SessionFx::Acknowledge(receipts)); } - } - fn ingest(&mut self, envelope: &SessionEnvelope, emit: &mut impl FnMut(SessionFx)) -> bool { - let receipt = Receipt::of(envelope); - if self.owns_receipt(receipt) { return true; } - if !self.accepts_header(envelope) { - emit(SessionFx::Acknowledge(vec![receipt])); - return true; +}; + true + +}, + SessionEvent::Erased { epoch, leftovers } => 'erased: { +let (epoch, leftovers,): (u64, usize,) = (*epoch, *leftovers,); + + let Some((expected, sign_in)) = self.state.pending_erase() else { break 'erased false }; + if expected != epoch || self.common.epoch != epoch { break 'erased false; } + { let event = AttemptEvent::FinishErase; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.disk_identity = Identity::of(&self.common.persisted); + self.common.delete_leftovers = leftovers; + if sign_in { { restart = Some(if true { LoginRestart::Fresh } else { LoginRestart::Retry }); true }; } + { publish = true; }; + true + +}, + SessionEvent::IncidentReported { id, delivery } => { + let handled = 'incident_reported: { +let (id, delivery,): (u32, &IncidentDelivery,) = (*id, delivery,); + + let Some(held) = self.common.incident.as_mut().filter(|held| held.id == id) else { break 'incident_reported false }; + let shown = match &held.state { + IncidentState::Queued { receipt } | IncidentState::Saved { receipt } => Some(receipt.as_str()), + IncidentState::Pending | IncidentState::Offered { .. } | IncidentState::OnRequest { .. } + | IncidentState::AutoSending | IncidentState::Sending | IncidentState::Delivered { .. } + | IncidentState::Failed | IncidentState::NotNow | IncidentState::Dropped => None, + }; + held.state = match (&held.state, delivery) { + (IncidentState::AutoSending, IncidentDelivery::Standing { receipt: Some(receipt) }) + | (IncidentState::Sending, IncidentDelivery::OneOff { receipt: Some(receipt) }) => { + IncidentState::Queued { receipt: receipt.clone() } + } + (IncidentState::AutoSending, IncidentDelivery::Standing { receipt: None }) + | (IncidentState::Sending, IncidentDelivery::OneOff { receipt: None }) => IncidentState::Failed, + // Tried and not through yet, still queued durably: said once, from Queued. + (IncidentState::Queued { .. }, IncidentDelivery::Held { receipt }) if shown == Some(receipt) => { + IncidentState::Saved { receipt: receipt.clone() } + } + (_, IncidentDelivery::Delivered { receipt }) if shown == Some(receipt) => { + IncidentState::Delivered { receipt: receipt.clone() } + } + // The report did not get through after all: Send report is accepted again. + (_, IncidentDelivery::Undelivered { receipt }) if shown == Some(receipt) => IncidentState::Failed, + _ => break 'incident_reported false, + }; + true + +}; + if handled { { publish = true; }; } + handled + } + SessionEvent::Pump => { + self.common.pump_pending = false; + { pump = true; }; + true + } + SessionEvent::CacheObserved(need) => { + 'observe_cache: { +let (need, now_ms,): (plx_plex::plex::session::RefreshNeed, u32,) = (*need, tick_ms,); + + use plx_plex::plex::session::LOCKED_RETRY_MS; + let tracked = match self.cache_refresh { + CacheRefresh::InFlight { .. } => break 'observe_cache, + CacheRefresh::Backoff { armed_ms, generation } => { + let covers = generation.is_none_or(|g| g == need.generation); + if covers && now_ms.wrapping_sub(armed_ms) < LOCKED_RETRY_MS { break 'observe_cache; } + covers + } + CacheRefresh::Idle => false, + }; + if need.transient && !tracked { + self.cache_refresh = CacheRefresh::Backoff { armed_ms: now_ms, generation: Some(need.generation) }; + break 'observe_cache; } - // The adapter admits only receipt-bearing records from an accepted resource. This can - // also confirm acceptance if its small admission reply is still carried in the queue. - self.state.pending.get_mut(&envelope.addr.req.0).unwrap().admission = AdmissionState::Accepted(envelope.admission); - let active = usize::from(self.state.pending_commit.as_ref().is_some_and(|commit| commit.receipt.is_some())); - assert!(self.state.inbox.len() + active < SESSION_TRANSFER_RECORDS, "Session transfer credit invariant"); - // Do not advance last_arrival here: that is the processing watermark, not receipt - // admission. Advancing it would make the FIFO head reject its own first delivery. - self.state.inbox.push_back(envelope.clone()); - if self.state.pending_commit.is_none() && !self.state.pump_pending { self.pump_one(emit); } + self.next_cache_req = self.next_cache_req.wrapping_add(1); + let req = self.next_cache_req; + self.cache_refresh = CacheRefresh::InFlight { req, generation: need.generation }; + fx.push(SessionFx::RefreshCache { req, generation: need.generation }); + +}; + true + } + SessionEvent::CacheRefreshed { req, outcome } => 'cache_refreshed: { +let (req, outcome, now_ms,): (u32, plx_plex::plex::session::CacheRefreshOutcome, u32,) = (*req, *outcome, tick_ms,); + + use plx_plex::plex::session::CacheRefreshOutcome; + if self.cache_refresh_in_flight() != Some(req) { break 'cache_refreshed false; } + let armed_ms = now_ms; + self.cache_refresh = match outcome { + CacheRefreshOutcome::Settled | CacheRefreshOutcome::Superseded => CacheRefresh::Idle, + CacheRefreshOutcome::Transient { generation } => CacheRefresh::Backoff { armed_ms, generation: Some(generation) }, + CacheRefreshOutcome::Refused => CacheRefresh::Backoff { armed_ms, generation: None }, + }; true - } - fn pump_one(&mut self, emit: &mut impl FnMut(SessionFx)) { - if self.state.pending_commit.is_some() { return; } - let Some(mut envelope) = self.state.inbox.pop_front() else { return }; +}, + }; +// Result ingress and Pump share one receipt-ordered observation drain. +if pump { 'pump_one: { + + if self.common.pending_commit.is_some() { break 'pump_one; } + let Some(mut envelope) = self.common.inbox.pop_front() else { break 'pump_one }; let receipt = Receipt::of(&envelope); // Completion authority is independent of payload authority. Recheck at the FIFO // head (a preceding commit may have changed this request), never at ingress. @@ -1844,356 +3960,296 @@ impl SessionMachine { if !self.accepts(&envelope) && envelope.terminal && matches!(envelope.outcome, SessionArrival::Data(_)) && self.accepts_header(&envelope) - && self.state.pending.get(&envelope.addr.req.0).is_some_and(|pending| + && self.common.pending.get(&envelope.addr.req.0).is_some_and(|pending| !matches!(pending.key.op, SessionOp::Endpoint(_)) || pending.lifecycle == envelope.lifecycle) { envelope.outcome = SessionArrival::Dropped; } if self.accepts(&envelope) { - if !self.apply_qr_observation(&envelope, emit) { - self.apply_resource_observation(&envelope, emit); - } - } - if let Some(commit) = &mut self.state.pending_commit { - assert!(commit.req == receipt.addr.req.0 && commit.epoch == receipt.key.epoch - && commit.arrival == receipt.arrival, "Session commit receipt mismatch"); - commit.receipt = Some(receipt); - } else { - emit(SessionFx::Acknowledge(vec![receipt])); - } - self.schedule_pump(emit); - } - - fn publish_profile(&mut self, profile: Option, emit: &mut impl FnMut(SessionFx)) { - // This is the sole scope allocator. Resource publication will store this explicit value - // rather than independently incrementing another generation. - self.state.profile_scope.0 = self.state.profile_scope.0.wrapping_add(1); - self.state.active_profile = profile; - emit(SessionFx::PublishProfile(ProfilePublication { - epoch: self.state.epoch, profile: self.state.active_profile.clone(), scope: self.state.profile_scope, - stamp: plx_plex::plex::grant::account_key(&self.state.persisted.account_token), - })); - } - - fn cancel_obsolete_interests(&mut self, retained: u32, emit: &mut impl FnMut(SessionFx)) { - let requests: Vec<_> = self.state.pending.iter().filter_map(|(&req, pending)| - (req != retained && !pending.expected.matches(&self.state.persisted)).then_some(req)).collect(); - if requests.is_empty() { return; } - for req in &requests { self.state.pending.remove(req); } - let mut receipts = Vec::new(); - self.state.inbox.retain(|record| { - if requests.contains(&record.addr.req.0) { - receipts.push(Receipt::of(record)); - false - } else { true } - }); - emit(SessionFx::Cancel { requests, epoch: self.state.epoch }); - if !receipts.is_empty() { emit(SessionFx::Acknowledge(receipts)); } - } - - fn refresh_roster(&mut self, emit: &mut impl FnMut(SessionFx)) -> bool { - if self.state.persisted.account_token.is_empty() { return false; } - let Some(req) = self.allocate(SessionOp::ServerRoster, None) else { return false }; - self.emit_work(req, SessionWork::ServerRoster { session: self.state.persisted.clone(), - expected: Identity::of(&self.state.persisted) }, emit); - true - } + if !('apply_qr_observation: { +let (envelope,): (&SessionEnvelope,) = (&envelope,); - fn start_switch(&mut self, picker: Picker, emit: &mut impl FnMut(SessionFx)) -> bool { - if matches!(self.state.authority, BootstrapAuthority::DevPms { .. }) { - // A dev-token session has no account behind it to list a roster with. The account - // menu still offers *Change profile* (it reads the on-disk sign-in), and the app has - // already routed to the picker by the time this runs — so refusing SILENTLY left that - // route with nothing behind it: a spinner that never ends and a BACK that could not - // leave (#132, TV session 8). Say so on the picker instead; `back` returns. - // `picker` is deliberately not recorded: nothing is detached here, so there is no - // picker-kind rule for `back` to apply, and BACK restores this session state exactly. - if self.state.phase != Phase::Ready || self.state.pending_erase.is_some() { return false; } - let _ = picker; - self.state.phase = Phase::Profiles; - self.state.users.clear(); - self.state.refuse_switch(); - self.replace_publication(); - return true; - } - if self.state.pending_erase.is_some() { return false; } - if self.advance_epoch(emit).is_none() { return false; } - if self.state.persisted.account_token.is_empty() { - self.fail_login(plx_platform::i18n::msg::browse_auth_signed_out(), None, emit); - self.replace_publication(); - return true; - } - if super::detaches_active_profile(picker) { self.publish_profile(None, emit); } - self.state.error.clear(); - if self.state.users.is_empty() { - self.state.users = self.state.persisted.home_users.iter().map(UserTile::of_ref).collect(); - } - self.state.phase = Phase::Profiles; - self.state.picker = picker; - if let Some(req) = self.allocate(SessionOp::Picker, None) { - let initial_profile = picker == Picker::Boot && self.state.active_profile.is_none() - && self.state.persisted.can_go_local(); - let mut registry = Vec::new(); - if initial_profile { - registry.push(RegistryPlan::Primary { server: self.state.persisted.server.clone(), - token: self.state.persisted.pms_token().into() }); - } - registry.push(RegistryPlan::Install { - sources: self.state.persisted.sources.clone(), primary: None, commit: RosterCommit::Merge, - }); - let plan = CommitPlan { registry_client_id: self.state.persisted.client_id.clone(), - expected_disk: self.state.disk_identity.clone(), - credentials: None, lifecycle: None, registry, - purpose: PersistencePurpose::Background, writes_durable: false, - authority: plx_plex::plex::session::SaveAuthority::Routine }; - self.begin_commit(req, 0, true, plan, CommitDelta { - activate_profile: initial_profile, ..Default::default() - }, emit); - } - self.refresh_roster(emit); - if let Some(req) = self.allocate(SessionOp::HomeRoster, None) { - self.emit_work(req, SessionWork::HomeRoster { client_id: self.state.persisted.client_id.clone(), - account_token: self.state.persisted.account_token.clone(), - expected: Identity::of(&self.state.persisted) }, emit); + if !self.accepts(envelope) + || !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { + break 'apply_qr_observation false; } - self.replace_publication(); - true - } + let req = envelope.addr.req.0; + if !self.common.pending[&req].expected.matches(&self.common.persisted) { break 'apply_qr_observation false; } + match &envelope.outcome { + SessionArrival::Refused | SessionArrival::Dropped => { + if !envelope.terminal { break 'apply_qr_observation false; } + let (message, class) = match (envelope.key.op, &envelope.outcome) { + (SessionOp::Rediscover, SessionArrival::Refused) => + (plx_platform::i18n::msg::browse_auth_rediscover_failed(), InternalClass::WorkerRefused), + (_, SessionArrival::Refused) => (plx_platform::i18n::msg::browse_auth_start_failed(), InternalClass::WorkerRefused), + _ => (plx_platform::i18n::msg::browse_auth_finish_failed(), InternalClass::WorkerDropped), + }; + { +let (message, incident,): (&str, Option,) = (message, Some(IncidentContext::internal(class)),); - fn select_profile(&mut self, index: usize, pin: Option, emit: &mut impl FnMut(SessionFx)) -> bool { - if self.state.pending_erase.is_some() { return false; } - let Some(tile) = self.state.users.get(index).cloned() else { return false }; - if self.state.next_req.checked_add(1).is_none() { return false; } - if self.advance_epoch(emit).is_none() { return false; } - let same_user = super::may_reuse_seated_profile(&self.state.persisted, &tile, pin.as_deref()); - if same_user { - self.state.error.clear(); - self.state.phase = Phase::Ready; - self.state.apply_pending = true; - } else { - self.state.phase = Phase::Switching; - self.state.pin_denied = false; - let req = self.allocate(SessionOp::ProfileSwitch, None).expect("request preflight"); - self.state.pending.get_mut(&req).unwrap().capture = Some(CaptureIntent::Profile { tile, pin }); - emit(SessionFx::Capture { req, epoch: self.state.epoch, request: SessionReadRequest::ProfilePolicy }); + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; } - self.replace_publication(); - true - } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); - fn request_endpoint(&mut self, sid: plx_plex::plex::ServerId, emit: &mut impl FnMut(SessionFx)) -> bool { - // The registry's own validity rule: every id but the reserved UNSET names a slot. - if !sid.is_set() - || self.state.persisted.account_token.is_empty() - || self.state.pending.values().any(|pending| pending.key.op == SessionOp::Endpoint(sid.raw())) { - return false; +}, + None => self.common.incident = None, } - let sid = sid.raw(); - let Some(req) = self.allocate(SessionOp::Endpoint(sid), None) else { return false }; - self.state.pending.get_mut(&req).unwrap().capture = Some(CaptureIntent::Endpoint { sid }); - emit(SessionFx::Capture { req, epoch: self.state.epoch, request: SessionReadRequest::Endpoint { sid } }); - true - } - fn back(&mut self, reply: ReplyTo, emit: &mut impl FnMut(SessionFx)) -> bool { - // AUTH-03: while an unacknowledged persistence warning is showing, BACK must not clear it - // or resume — clearing it here would silently re-admit `needs_ready_commit`/`take_ready` - // on the next frame (a second, routine save over the still-unconfirmed fresh one) and, for - // a held Final handoff, would release it without the explicit acknowledgement the warning - // exists to require. Only the labelled Continue (`acknowledge_persistence_warning`) may - // clear it; BACK here is the platform root press only. - if self.state.persistence_warning.is_some() { - emit(SessionFx::BackReply { to: reply, resumed: false }); - return true; - } - let dead_end = self.state.roster_dead_end(); - if dead_end { - if let BootstrapAuthority::DevPms { primary, .. } = &self.state.authority { - // Nothing was detached or re-pointed (see `start_switch`): re-announce the dev - // session exactly as its activation did. - let primary = primary.clone(); - self.state.phase = Phase::Ready; - self.state.error.clear(); - emit(SessionFx::Ready { epoch: self.state.epoch, scope: self.state.profile_scope, - token: primary.token.clone(), server: primary, install: ReadyInstall::AlreadyInstalled }); - emit(SessionFx::BackReply { to: reply, resumed: true }); - self.replace_publication(); - return true; +}; + } + SessionArrival::Data(data) => { + let super::observation::Observation::Login(progress) = &**data else { break 'apply_qr_observation false }; + use super::LoginProgress; + let (epoch, terminal) = match progress { + LoginProgress::CodeReplacing { epoch } + | LoginProgress::CodeReady { epoch, .. } + | LoginProgress::Authorized { epoch, .. } + | LoginProgress::DiscoveryTrouble { epoch, .. } + | LoginProgress::DiscoveryRetrySettled { epoch, .. } + | LoginProgress::LinkTrouble { epoch, .. } => (*epoch, false), + LoginProgress::Failed { epoch, .. } => (*epoch, true), + LoginProgress::SignedIn { .. } => break 'apply_qr_observation false, + }; + if epoch != envelope.key.epoch || terminal != envelope.terminal { break 'apply_qr_observation false; } + match progress { + LoginProgress::CodeReplacing { .. } => { + if envelope.key.op != SessionOp::Login || !matches!(self.state.phase(), Phase::Creating | Phase::Waiting) { break 'apply_qr_observation false; } + { let event = AttemptEvent::CodeReplacing; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::CodeReady { code, qr_png, .. } => { + if envelope.key.op != SessionOp::Login { break 'apply_qr_observation false; } + let Some(next) = self.common.next_qr.checked_add(1) else { + { +let (message, incident,): (&str, Option,) = (plx_platform::i18n::msg::browse_auth_start_failed(), Some(IncidentContext::internal(InternalClass::Exhausted)),); + + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); } + break 'raise_incident; } - let stored = self.state.committed_credentials.merge_into(&self.state.persisted); - // A dead-end picker offered nobody, so the picker-kind rule (`may_resume`: the - // Change-profile picker is a root, so BACK cannot skip a PIN) has no boundary to guard. - // Only "is there a session to go back to" remains — `dead_end_resumes`, the same answer - // the read-out publishes so its *Back* control is offered exactly when this resumes. - let resumable = if dead_end { self.state.dead_end_resumes() } else { super::resumable(&stored, self.state.picker) }; - if !resumable || self.state.epoch.checked_add(1).is_none() { - emit(SessionFx::BackReply { to: reply, resumed: false }); - return true; - } - self.advance_epoch(emit).expect("epoch preflight"); - if std::mem::take(&mut self.state.signin_active) { - emit(SessionFx::Coordinator(CoordinatorAction::SignInCancelled)); - } - self.state.persisted = stored; - self.state.phase = Phase::Ready; - self.state.apply_pending = true; - self.state.pin_code.clear(); - self.state.qr_png.clear(); - self.state.qr_gen = 0; - self.state.users.clear(); - self.state.error.clear(); - self.state.pin_denied = false; - self.state.authorized_in_flow = false; - self.state.persistence_warning = None; - self.state.held_handoff = None; - self.state.persistence_warning_answered = false; - self.state.code_replaced = false; - emit(SessionFx::BackReply { to: reply, resumed: true }); - self.replace_publication(); - true - } - - fn erase(&mut self, sign_in: bool, emit: &mut impl FnMut(SessionFx)) -> bool { - if self.state.pending_erase.is_some() || self.state.epoch.checked_add(1).is_none() { return false; } - emit(SessionFx::Coordinator(CoordinatorAction::CloseTelemetry)); - self.advance_epoch(emit).expect("epoch preflight"); - self.state.persisted = PersistedSession::default(); - self.state.committed_credentials = CredentialPatch::of(&self.state.persisted); - // The identity ends here, and its verdicts with it: the same account signed back in is - // the same `Identity`, and nothing has refused it anything in that sign-in. - self.state.switch_refused_for = None; - self.state.pending_erase = Some((self.state.epoch, sign_in)); - self.state.authority = BootstrapAuthority::Account { extras: Vec::new() }; - self.state.picker = Picker::Boot; - self.state.pin_code.clear(); - self.state.qr_png.clear(); - self.state.qr_gen = 0; - self.state.users.clear(); - self.state.error.clear(); - self.state.pin_denied = false; - self.state.authorized_in_flow = false; - self.state.persistence_warning = None; - self.state.held_handoff = None; - self.state.persistence_warning_answered = false; - self.state.signin_active = false; - self.state.apply_pending = false; - self.state.code_replaced = false; - self.forget_incidents(); - self.publish_profile(None, emit); - emit(SessionFx::Erase { req: self.state.next_req, epoch: self.state.epoch, all_local: !sign_in }); - self.replace_publication(); - true - } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); - fn erased(&mut self, epoch: u64, leftovers: usize, emit: &mut impl FnMut(SessionFx)) -> bool { - let Some((expected, sign_in)) = self.state.pending_erase else { return false }; - if expected != epoch || self.state.epoch != epoch { return false; } - self.state.pending_erase = None; - self.state.disk_identity = Identity::of(&self.state.persisted); - self.state.delete_leftovers = leftovers; - self.state.phase = Phase::Deleted; - if sign_in { self.restart_login(true, emit); } - else { emit(SessionFx::Coordinator(CoordinatorAction::LocalDataErased)); } - self.replace_publication(); - true - } +}, + None => self.common.incident = None, + } - fn apply_read(&mut self, reply: &SessionReadReply, emit: &mut impl FnMut(SessionFx)) -> bool { - if reply.addr.to != MachineId::Session || reply.epoch != self.state.epoch { return false; } - let req = reply.addr.req.0; - let Some(pending) = self.state.pending.get(&req) else { return false }; - if pending.key.epoch != reply.epoch || !pending.expected.matches(&self.state.persisted) { return false; } - let Some(intent) = pending.capture.clone() else { return false }; - let input = match (intent, &reply.value) { - (CaptureIntent::Login, SessionReadValue::LoginClientId(client_id)) if !client_id.is_empty() => { - if self.state.disk_identity.client_id.is_empty() { - self.state.disk_identity.client_id = client_id.clone(); - } - self.state.persisted.client_id = client_id.clone(); - self.state.committed_credentials.client_id = client_id.clone(); - self.state.pending.get_mut(&req).unwrap().expected = Identity::of(&self.state.persisted); - SessionWork::Login { client_id: client_id.clone() } - } - (CaptureIntent::Profile { tile, pin }, SessionReadValue::ProfilePolicy { recently_unreachable }) => - SessionWork::ProfileSwitch { session: self.state.persisted.clone(), - expected: Identity::of(&self.state.persisted), tile, pin, recently_unreachable: *recently_unreachable }, - (CaptureIntent::Endpoint { sid }, SessionReadValue::Endpoint(Some(captured))) - if captured.lifecycle.sid == sid && self.state.persisted.sources.iter().any(|source| - source.machine_id == captured.machine_id && source.dialable()) => { - self.state.pending.get_mut(&req).unwrap().lifecycle = Some(captured.lifecycle); - SessionWork::Endpoint { session: self.state.persisted.clone(), expected: Identity::of(&self.state.persisted), - lifecycle: captured.lifecycle, machine_id: captured.machine_id.clone() } - } - (CaptureIntent::Endpoint { .. }, SessionReadValue::Endpoint(_)) => { - self.retire(req, emit); - return true; - } - (CaptureIntent::Login, SessionReadValue::LoginClientId(_)) => { - self.fail_login(plx_platform::i18n::msg::browse_auth_start_failed(), - Some(IncidentContext::internal(InternalClass::ClientIdUnavailable)), emit); - self.retire(req, emit); - self.replace_publication(); - return true; +}; + self.common.pending.remove(&req); + fx.push(SessionFx::Cancel { requests: vec![req], epoch: self.common.epoch }); + fx.push(SessionFx::Retire { req }); + { publish = true; }; + break 'apply_qr_observation true; + }; + self.common.next_qr = next; + { let event = AttemptEvent::CodeReady { + generation: next, code: code.clone(), png: qr_png.clone(), + }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::Authorized { token, .. } => { + if envelope.key.op != SessionOp::Login { break 'apply_qr_observation false; } + // A sign-in that is not a sign-out (a stored session that could not be + // activated, *Use another account*, the dev login trigger) starts from the + // stored record. Whoever that record seated, its roster and its offline + // profile cache belong to the authorization this token replaces, so none of + // them may ride into the new account: `SignedIn` writes the roster and + // `Session::account` names a single-user account from it; a Home account + // seats through the picker. Reset BEFORE `expected` is recomputed below. + // The new token cannot say whose cache this is (every sign-in mints one), + // so the cache is emptied while the identity is unknown and `SignedIn` + // restores the STORED record's when its roster names the same owner. + self.common.persisted.user = UserRef::default(); + self.common.persisted.home_users.clear(); + self.common.persisted.profiles.clear(); + self.common.persisted.account_token = token.clone(); + { let event = AttemptEvent::Authorized; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.pending.get_mut(&req).unwrap().expected = Identity::of(&self.common.persisted); + } + LoginProgress::DiscoveryTrouble { progress, .. } => { + if !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { + break 'apply_qr_observation false; + } + { let event = AttemptEvent::DiscoveryTrouble { progress: *progress }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::DiscoveryRetrySettled { run, .. } => { + if !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { + break 'apply_qr_observation false; + } + { let event = AttemptEvent::DiscoverySettled { run: *run }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::LinkTrouble { trouble, .. } => { + if envelope.key.op != SessionOp::Login { break 'apply_qr_observation false; } + { let event = AttemptEvent::LinkTrouble { + present: trouble.is_some(), + }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + if let Some(context) = trouble { + 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, *context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); } - _ => return false, - }; - let pending = self.state.pending.get_mut(&req).unwrap(); - pending.capture = None; - self.emit_work(req, input, emit); - true - } + break 'raise_incident; + } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); - fn roster_plan(next: &PersistedSession, probes: &[super::SettledProbe], commit: RosterCommit) - -> Vec { - let primary = next.sources.iter().position(|source| source.machine_id == next.server.machine_id); - let mut plans = vec![RegistryPlan::Install { sources: next.sources.clone(), primary, commit }]; - plans.extend(probes.iter().cloned().map(RegistryPlan::Probe)); - plans - } +}; + } + } + LoginProgress::Failed { message, incident, plaintext, account, .. } => { + { +let (message, incident,): (&str, Option,) = (message, Some(*incident),); - /// A roster request ended without tiles. With cached tiles on screen nothing changes — they - /// are still the household, and offline switching reads them. With NONE, the picker says so - /// on its own route: `Phase::Profiles` with the reason in `error` and no tiles is the - /// read-out `screens/profiles.rs` draws, and [`SessionInit::roster_dead_end`] is what lets BACK leave - /// it. It used to be `fail_login`, i.e. `Phase::Error` — which the app routes to the SIGN-IN - /// screen ("Couldn't sign in", whose Try again starts a new QR sign-in) for a person who is - /// signed in, and whose BACK the Change-profile picker's root rule then refused (#132). - fn fail_empty_home_roster(&mut self, reason: &str) { - if self.state.users.is_empty() && self.state.phase == Phase::Profiles { - self.state.error = reason.to_owned(); + { let event = AttemptEvent::LoginFailed { message: message.to_owned(), revoke: incident.is_some_and(|context| context.kind.refuses_the_account_token()) }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + // A token plex.tv refused is not an authorization in flight any more: without this, the + // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same + // refused token again, and Try again could never recover. Dropping it makes the retry a + // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. + match incident { + Some(context) => 'raise_incident: { +let (flow, context,): (IncidentFlow, IncidentContext,) = (IncidentFlow::SignIn, context,); + + let key = IncidentKey { flow, kind: context.kind, link: context.link }; + if let Some(held) = self.common.incident.as_mut().filter(|held| held.key == key) { + // The same failure again. Unresolved (a second stalled report in one wait): keep the + // offer, take the fresher report evidence. Resolved: keep the answer and report + // evidence it already has. Details always reads the current failure facts. + held.readout_context = Some(context); + if !is_settled(held) { + held.context = Some(context); + } + break 'raise_incident; } - } + self.common.next_incident = self.common.next_incident.wrapping_add(1).max(1); + self.common.incident = Some(IncidentOffer { + id: self.common.next_incident, + key, + context: Some(context), + readout_context: Some(context), + state: IncidentState::Pending, + }); - /// [`Self::fail_empty_home_roster`] for plex.tv's VERDICT: over nothing cached it is the dead - /// end itself, so it is also remembered for this identity and the account menu stops offering - /// the way in (`SessionInit::refuse_switch`). Over cached tiles it changes nothing, like any - /// other empty answer. - fn refuse_empty_home_roster(&mut self) { - if self.state.users.is_empty() && self.state.phase == Phase::Profiles { - self.state.refuse_switch(); +}, + None => self.common.incident = None, } - } - fn apply_resource_observation(&mut self, envelope: &SessionEnvelope, - emit: &mut impl FnMut(SessionFx)) -> bool { +}; + { let event = AttemptEvent::DiscoveryFailed { plaintext: plaintext.clone(), account: account.clone() }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + LoginProgress::SignedIn { .. } => unreachable!(), + } + } + } + if envelope.terminal { + self.common.pending.remove(&req); + } else { + self.common.pending.get_mut(&req).unwrap().last_arrival = Some(envelope.arrival); + } + { publish = true; }; + true + +}) { + 'apply_resource_observation: { +let (envelope,): (&SessionEnvelope,) = (&envelope,); + use super::observation::Observation; - if !self.accepts(envelope) { return false; } + if !self.accepts(envelope) { break 'apply_resource_observation false; } let req = envelope.addr.req.0; - let pending = &self.state.pending[&req]; - if !pending.expected.matches(&self.state.persisted) { return false; } + let pending = &self.common.pending[&req]; + if !pending.expected.matches(&self.common.persisted) { break 'apply_resource_observation false; } let SessionArrival::Data(data) = &envelope.outcome else { if pending.key.op == SessionOp::ProfileSwitch && pending.phase == StreamPhase::Running { - self.state.phase = Phase::Profiles; - self.state.pin_denied = false; - self.state.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); + { let event = AttemptEvent::SwitchDropped; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; } else if pending.key.op == SessionOp::HomeRoster { - self.fail_empty_home_roster(roster_unreachable()); + { +let (reason,): (&str,) = (roster_unreachable(),); + + if self.state.picker_data().users.is_empty() && self.state.phase() == Phase::Profiles { + { let event = AttemptEvent::RosterFailed { message: reason.to_owned() }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + +}; } - self.retire(req, emit); - self.replace_publication(); - return true; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + { publish = true; }; + break 'apply_resource_observation true; }; let mut delta = CommitDelta::default(); // Purpose is decided by the op, not by whether the write happens to be a credential @@ -2203,32 +4259,33 @@ impl SessionMachine { let purpose = match pending.key.op { SessionOp::Login | SessionOp::Rediscover => PersistencePurpose::Discovery, SessionOp::ProfileSwitch => PersistencePurpose::Profile, - _ => PersistencePurpose::Background, + SessionOp::HomeRoster | SessionOp::ServerRoster | SessionOp::Endpoint(_) + | SessionOp::Ready | SessionOp::Picker | SessionOp::DevBoundary => PersistencePurpose::Background, }; // A PEEK, never a consume: a discovery/rediscovery write must not spend the fresh // authority the FINAL write (take_ready) needs (AUTH-04). Only take_ready consumes it. let authority = if matches!(pending.key.op, SessionOp::Login | SessionOp::Rediscover) - && self.state.authorized_in_flow { + && self.state.fresh_authority() { plx_plex::plex::session::SaveAuthority::FreshReauthentication } else { plx_plex::plex::session::SaveAuthority::Routine }; - let mut plan = CommitPlan { registry_client_id: self.state.persisted.client_id.clone(), - expected_disk: self.state.disk_identity.clone(), + let mut plan = CommitPlan { registry_client_id: self.common.persisted.client_id.clone(), + expected_disk: self.common.disk_identity.clone(), credentials: None, registry: Vec::new(), lifecycle: pending.lifecycle, purpose, writes_durable: false, authority }; match &**data { Observation::Login(super::LoginProgress::SignedIn { server, sources, users, .. }) => { - let mut next = self.state.persisted.clone(); + let mut next = self.common.persisted.clone(); next.server = server.clone(); next.sources = sources.clone(); next.home_users = users.iter().map(super::UserTile::to_ref).collect(); // `Authorized` emptied the offline profile cache because the new token names no // account. The roster does: the same owner as the stored record gets that // record's cache back (nothing of another account's, nor when either is unknown). - if pending.key.op == SessionOp::Login && self.state.authorized_in_flow + if pending.key.op == SessionOp::Login && self.state.fresh_authority() && next.profiles.is_empty() - && plx_plex::plex::session::same_owner(&self.state.committed_credentials.home_users, + && plx_plex::plex::session::same_owner(&self.common.committed_credentials.home_users, &next.home_users) { - next.profiles = self.state.committed_credentials.profiles.clone(); + next.profiles = self.common.committed_credentials.profiles.clone(); } // A fresh QR sign-in's account token is the owner's plex.tv credential. Keep it // on the owner profile too; rediscovery can belong to a managed active profile @@ -2241,19 +4298,21 @@ impl SessionMachine { plan.credentials = Some(patch); delta.roster_answered = !users.is_empty(); if users.len() > 1 { + delta.destination = CommitDestination::SignInProfiles; delta.phase = Some(Phase::Profiles); delta.picker = Some(Picker::SignedIn); delta.users = Some(users.clone()); } else { + delta.destination = CommitDestination::SignInReady; delta.phase = Some(Phase::Ready); delta.ready = Some(true); } delta.complete_signin = true; } - Observation::Login(_) => return false, + Observation::Login(_) => break 'apply_resource_observation false, Observation::Registry(progress) => { if pending.key.op == SessionOp::ServerRoster - && !self.state.persisted.active_profile_is_admin() { + && !self.common.persisted.active_profile_is_admin() { // This operation fetched `/resources` with the ACCOUNT token. Its Activate // and Install observations therefore carry the account holder's grants, not // the seated profile's. The identity/epoch checks above prove which request @@ -2278,7 +4337,7 @@ impl SessionMachine { // a server both call OWNED proves them one identity. Every other // operation's grants are the identity it is establishing. same_identity: pending.key.op != SessionOp::ServerRoster - || super::seated_is_account_holder(&self.state.persisted, + || super::seated_is_account_holder(&self.common.persisted, candidate.owned.then_some(candidate.machine_id.as_str())), }, super::RegistryProgress::Settled { probe, .. } => RegistryPlan::Probe(probe.clone()), @@ -2297,27 +4356,60 @@ impl SessionMachine { Some(users) if !users.is_empty() => users, graded => { if graded.is_none() { - self.fail_empty_home_roster(roster_unreachable()); + { +let (reason,): (&str,) = (roster_unreachable(),); + + if self.state.picker_data().users.is_empty() && self.state.phase() == Phase::Profiles { + { let event = AttemptEvent::RosterFailed { message: reason.to_owned() }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + +}; } else { - self.refuse_empty_home_roster(); + { + + if self.state.picker_data().users.is_empty() && self.state.phase() == Phase::Profiles { + { let event = AttemptEvent::RosterFailed { message: roster_refused().into() }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + self.common.switch_refused_for = Some(Identity::of(&self.common.persisted)); + } + +}; } - self.retire(req, emit); - self.replace_publication(); - return true; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + { publish = true; }; + break 'apply_resource_observation true; } }; - let mut next = self.state.persisted.clone(); + let mut next = self.common.persisted.clone(); next.home_users = users.iter().map(super::UserTile::to_ref).collect(); let patch = CredentialPatch::of(&next); delta.credentials = Some(patch.clone()); + delta.destination = CommitDestination::Roster; delta.users = Some(users.clone()); delta.roster_answered = true; plan.credentials = Some(patch); } Observation::ServerRoster(progress) => match &progress.outcome { super::ServerRosterOutcome::Unreachable => { - self.retire(req, emit); - return true; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + break 'apply_resource_observation true; } super::ServerRosterOutcome::NoReachable { settled } => { // R2/A5: nothing was found to REGISTER, but a probe may still have verified @@ -2325,22 +4417,40 @@ impl SessionMachine { // registry-only commit, the same shape `start_switch`'s initial-primary plan // already uses: no credential patch, no lifecycle, just the probe facts. if settled.is_empty() { - self.retire(req, emit); - return true; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + break 'apply_resource_observation true; } plan.registry = settled.iter().cloned().map(RegistryPlan::Probe).collect(); } super::ServerRosterOutcome::Reconcile { resources, found, admitted_machine_id, household, settled, } => { - if !self.state.persisted.active_profile_is_admin() { + if !self.common.persisted.active_profile_is_admin() { if settled.is_empty() { - self.retire(req, emit); - return true; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + break 'apply_resource_observation true; } plan.registry = settled.iter().cloned().map(RegistryPlan::Probe).collect(); } else { - let mut next = self.state.persisted.clone(); + let mut next = self.common.persisted.clone(); let refreshed = super::refreshed_sources(&next.sources, found, resources, household); let usable = !refreshed.is_empty(); let sources = if usable { refreshed } else { next.sources.clone() }; @@ -2351,8 +4461,17 @@ impl SessionMachine { let repaired = next.refresh_profile_record(); if !(roster_changed || moved || repaired) { if settled.is_empty() { - self.retire(req, emit); - return true; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + break 'apply_resource_observation true; } plan.registry = settled.iter().cloned().map(RegistryPlan::Probe).collect(); } else { @@ -2367,7 +4486,7 @@ impl SessionMachine { // a REFRESH, never a switch: a rotated grant for the same user must // not revoke every live client (owner trace 2026-09-30). let same_identity = super::seated_is_account_holder( - &self.state.persisted, + &self.common.persisted, resources.iter().filter(|r| r.is_server() && r.owned) .map(|r| r.client_identifier.as_str())); plan.registry = vec![RegistryPlan::Install { @@ -2381,17 +4500,25 @@ impl SessionMachine { }, Observation::ProfileSwitch(progress) => match &progress.outcome { super::ProfileSwitchOutcomeProgress::Failed { error, pin_denied } => { - self.state.error = error.clone(); - self.state.pin_denied = *pin_denied; - self.state.phase = Phase::Profiles; - self.retire(req, emit); - self.replace_publication(); - return true; + { let event = AttemptEvent::SwitchFailed { message: error.clone(), denied: *pin_denied }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + { publish = true; }; + break 'apply_resource_observation true; } super::ProfileSwitchOutcomeProgress::Ready { delta: profile, probes } => { - let mut next = self.state.persisted.clone(); + let mut next = self.common.persisted.clone(); super::merge_profile_delta(&mut next, profile.clone()); delta.credentials = Some(CredentialPatch::of(&next)); + delta.destination = CommitDestination::ProfileReady; delta.phase = Some(Phase::Ready); delta.ready = Some(true); delta.clear_error = true; @@ -2400,537 +4527,276 @@ impl SessionMachine { } }, Observation::ProfileRoster(progress) => { - let mut next = self.state.persisted.clone(); + let mut next = self.common.persisted.clone(); let sources = super::profile_sources(&next.sources, &progress.reached, &progress.resources, &next.household_ids()); let Some(primary) = sources.iter() .find(|s| s.machine_id == next.server.machine_id && s.dialable()) .or_else(|| sources.iter().find(|s| s.dialable())).cloned() else { - self.retire(req, emit); - return true; + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + break 'apply_resource_observation true; }; next.sources = sources; next.server = super::server_ref(&primary); next.user.token = primary.token; next.refresh_profile_record(); - let patch = CredentialPatch::of(&next); - delta.credentials = Some(patch.clone()); - if !self.state.apply_pending { plan.credentials = Some(patch); } - // This request's `Ready` already seated this profile and committed its roster as - // the `Switch` — the one revoke that change of identity owes. This late roster is - // for that SAME seat, and that is proven, not assumed: `matches_request` admits it - // only in `ProfileSeated` and only for `progress.expected == pending.expected`; - // the `Ready` commit stamped `pending.expected` from the seat it installed; and - // `observe` dropped it above unless that identity is still the persisted one. So - // it is a same-identity refresh — retoken in place, retire what is no longer - // granted — never a second switch that blanks Home's live clients seconds after - // they drew (owner trace 2026-09-30, who's-watching picker path). - debug_assert!(pending.phase == StreamPhase::ProfileSeated - && pending.expected.matches(&self.state.persisted)); - let commit = RosterCommit::Refresh { same_identity: true }; - plan.registry = Self::roster_plan(&next, &progress.probes, commit); - } - Observation::Endpoint(progress) => { - let Some(lifecycle) = pending.lifecycle else { return false; }; - match &progress.fresh { - None => match &progress.probe { - // Nothing to INSTALL, but the probe itself is evidence — an InsecureOnly - // verdict most of all — so publish it rather than retiring silently. - Some(probe) => plan.registry.push(RegistryPlan::Probe(probe.clone())), - // The worker exited early (plex.tv itself unreachable, or the machine no - // longer among its resources): nothing was dialled, so there is nothing - // to publish and no verdict to widen — retire exactly as an empty - // `ServerRosterOutcome::NoReachable` does. - None => { - self.retire(req, emit); - return true; - } - }, - Some(fresh) => { - let mut next = self.state.persisted.clone(); - let Some((source, changed)) = super::apply_refreshed_endpoint(&mut next, &progress.machine_id, fresh) else { - self.retire(req, emit); - return true; - }; - // Issue #95 step 6: this endpoint repair changes exactly the fields - // `refresh_profile_record` copies into the active profile's cached - // record (server/sources) — miss this and a plaintext-to-https repair - // (or any other endpoint move) never reaches `Session::profiles`, so an - // offline reseat of this same profile keeps dialling the stale origin - // forever. `ProfileRoster`'s commit above makes the identical call. - // The ServerRoster Reconcile arm above already plans credentials on - // `changed || repaired`; this commit used to gate on `changed` alone, - // silently dropping a repaired-but-otherwise-unchanged active - // `ProfileCreds` record on the floor. - let repaired = next.refresh_profile_record(); - let patch = CredentialPatch::of(&next); - delta.credentials = Some(patch.clone()); - if (changed || repaired) && !self.state.apply_pending { plan.credentials = Some(patch); } - plan.registry.push(RegistryPlan::Endpoint { expected: lifecycle, source }); - } - } - } - } - plan.writes_durable = plan.credentials.is_some(); - self.begin_commit(req, envelope.arrival, envelope.terminal, plan, delta, emit) - } - - /// Start/restart is one owner decision. Check both counters before cancelling anything: - /// exhaustion must not detach the still-live operation or reuse its resource address. - fn restart_login(&mut self, fresh_login: bool, emit: &mut impl FnMut(SessionFx)) -> bool { - if matches!(self.state.authority, BootstrapAuthority::DevPms { .. }) { - return (fresh_login || self.state.phase == Phase::Error) && self.begin_dev_account(emit); - } - if self.state.pending_erase.is_some() { return false; } - let Some(epoch) = self.state.epoch.checked_add(1) else { return false }; - if self.state.next_req.checked_add(1).is_none() { return false; } - let discovery = !fresh_login && super::retry_kind(self.state.phase, - self.state.authorized_in_flow) == super::RetryKind::Discovery; - let fresh_attempt = fresh_login || super::restart_is_a_new_attempt(self.state.signin_active); - let requests = self.state.pending.keys().copied().collect(); - self.discard_owned_envelopes(emit); - self.state.pending.clear(); - self.state.epoch = epoch; - self.state.discovery_retry = None; - emit(SessionFx::Cancel { requests, epoch }); - if discovery { - self.state.phase = Phase::Discovering; - self.state.error.clear(); - // 0.6.6 parity (`discovery-warning-not-cleared-on-retry-or-fresh-success`): a restart - // begins a fresh discovery attempt under a NEW epoch, so a warning (or a held handoff) - // left over from the attempt being retried can never be released or acknowledged by - // anything this new epoch does — it would sit stale forever. A rediscovery restart - // clears both, the same way the fresh-attempt branch below already does. - self.state.persistence_warning = None; - self.state.held_handoff = None; - self.state.persistence_warning_answered = false; - } else { - self.state.persisted = self.state.committed_credentials.merge_into(&self.state.persisted); - self.state.phase = Phase::Creating; - self.state.picker = Picker::Boot; - self.state.pin_code.clear(); - self.state.qr_png.clear(); - self.state.users.clear(); - self.state.error.clear(); - self.state.pin_denied = false; - self.state.authorized_in_flow = false; - self.state.persistence_warning = None; - self.state.held_handoff = None; - self.state.persistence_warning_answered = false; - self.state.apply_pending = false; - self.state.code_replaced = false; - self.state.qr_gen = 0; - } - self.state.signin_active = true; - self.state.link_trouble = false; - self.state.plaintext = None; - self.state.signin_account = None; - if fresh_attempt { emit(SessionFx::Coordinator(CoordinatorAction::SignInStarted)); } - let op = if discovery { SessionOp::Rediscover } else { SessionOp::Login }; - let req = self.allocate(op, None).expect("request exhaustion checked before transition"); - let client_id = self.state.persisted.client_id.clone(); - let input = if discovery { - SessionWork::Rediscover { client_id, account_token: self.state.persisted.account_token.clone() } - } else { SessionWork::Login { client_id } }; - if !discovery && self.state.persisted.client_id.is_empty() { - self.state.pending.get_mut(&req).unwrap().capture = Some(CaptureIntent::Login); - emit(SessionFx::Capture { req, epoch, request: SessionReadRequest::LoginClientId }); - } else { - self.emit_work(req, input, emit); - } - self.replace_publication(); - true - } - - /// **The sign-in read-out's *Try again*.** Over an eligible server the person said *Not now* - /// to (or turned off), it is also how they are asked again — Settings, where a signed-in person - /// changes that answer, is out of reach before sign-in — so the answer is withdrawn (recorded - /// `Undecided`, through the same [`SessionFx::PlaintextAnswer`]) BEFORE the retry's work - /// captures the answers, and the retry that follows asks. - fn retry(&mut self, emit: &mut impl FnMut(SessionFx)) -> bool { - use plx_plex::plex::session::PlaintextChoice; - if self.state.phase == Phase::Error { - let account = plx_plex::plex::grant::account_key(&self.state.persisted.account_token); - let answered = self.state.plaintext.as_ref().filter(|v| v.offers() - && matches!(v.choice, PlaintextChoice::Declined | PlaintextChoice::Revoked)); - if let (Some(v), false) = (answered, account.is_empty()) { - emit(SessionFx::PlaintextAnswer { - machine_id: v.machine_id.clone(), choice: PlaintextChoice::Undecided, account, - }); - } - } - self.restart_login(false, emit) - } - - /// **The answer to "Connect without encryption?"** — recorded through - /// [`SessionFx::PlaintextAnswer`] first, so the work an *Allowed* starts captures it - /// (`plex::grant::PlaintextAsk`). - /// - /// On the sign-in read-out it must answer the server shown there: *Connect* retries the - /// discovery, *Not now* re-words the read-out (its primary becomes *Try again*, which - /// withdraws the answer and asks again — [`Self::retry`]) and starts nothing. Signed in (Home's or the Library's read-out, Settings), any server may be - /// answered; an *Allowed* re-finds `sid`'s endpoint, or the whole roster without one. Nothing - /// is recorded without an account to bind it to. - fn answer_plaintext(&mut self, machine_id: &str, choice: plx_plex::plex::session::PlaintextChoice, - sid: Option, emit: &mut impl FnMut(SessionFx)) -> bool { - use plx_plex::plex::session::PlaintextChoice; - let account = plx_plex::plex::grant::account_key(&self.state.persisted.account_token); - if account.is_empty() || machine_id.is_empty() || choice == PlaintextChoice::Undecided { - return false; - } - let on_sign_in = self.state.phase == Phase::Error; - if on_sign_in && !self.state.plaintext.as_ref().is_some_and(|v| v.machine_id == machine_id) { - return false; - } - emit(SessionFx::PlaintextAnswer { machine_id: machine_id.to_owned(), choice, account }); - if on_sign_in { - if choice.allows() { - return self.restart_login(false, emit); - } - if let Some(verdict) = self.state.plaintext.as_mut() { - verdict.choice = choice; - self.state.error = super::insecure_only_copy(Some(verdict)).into_owned(); - } - self.replace_publication(); - return true; - } - if choice.allows() { - let _ = match sid { - Some(sid) => self.request_endpoint(sid, emit), - None => self.refresh_roster(emit), - }; - } - true - } - - /// End the flow on the error read-out. **Every ending names its incident**: `Some` is the - /// failure's own closed evidence and is raised here, so the read-out's Details and Send report - /// are about THIS failure; `None` is an ending the onboarding report does not cover, and it - /// retires whatever is held, which explains an earlier failure and not this one. - fn fail_login(&mut self, message: &str, incident: Option, emit: &mut impl FnMut(SessionFx)) { - if std::mem::take(&mut self.state.signin_active) { - emit(SessionFx::Coordinator(CoordinatorAction::SignInFailed { phase: self.state.phase })); - } - self.state.error = message.to_owned(); - self.state.phase = Phase::Error; - self.state.plaintext = None; - self.state.signin_account = None; - self.state.persistence_warning = None; - self.state.held_handoff = None; - self.state.persistence_warning_answered = false; - self.state.link_trouble = false; - self.state.discovery_retry = None; - // A token plex.tv refused is not an authorization in flight any more: without this, the - // retry decision (`retry_kind`) kept offering a discovery-only pass that presents the same - // refused token again, and Try again could never recover. Dropping it makes the retry a - // new QR sign-in; the incident below is raised exactly as before, so its dedup holds. - if incident.is_some_and(|context| context.kind.refuses_the_account_token()) { - self.state.authorized_in_flow = false; - } - match incident { - Some(context) => self.raise_incident(IncidentFlow::SignIn, context), - None => self.state.incident = None, - } - } - - /// QR observations need no external commit. SignedIn and registry/profile facts go through - /// the separate resource commit protocol, rather than treating their side effects as reads. - fn apply_qr_observation(&mut self, envelope: &SessionEnvelope, - emit: &mut impl FnMut(SessionFx)) -> bool { - if !self.accepts(envelope) - || !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { - return false; - } - let req = envelope.addr.req.0; - if !self.state.pending[&req].expected.matches(&self.state.persisted) { return false; } - match &envelope.outcome { - SessionArrival::Refused | SessionArrival::Dropped => { - if !envelope.terminal { return false; } - let (message, class) = match (envelope.key.op, &envelope.outcome) { - (SessionOp::Rediscover, SessionArrival::Refused) => - (plx_platform::i18n::msg::browse_auth_rediscover_failed(), InternalClass::WorkerRefused), - (_, SessionArrival::Refused) => (plx_platform::i18n::msg::browse_auth_start_failed(), InternalClass::WorkerRefused), - _ => (plx_platform::i18n::msg::browse_auth_finish_failed(), InternalClass::WorkerDropped), - }; - self.fail_login(message, Some(IncidentContext::internal(class)), emit); - } - SessionArrival::Data(data) => { - let super::observation::Observation::Login(progress) = &**data else { return false }; - use super::LoginProgress; - let (epoch, terminal) = match progress { - LoginProgress::CodeReplacing { epoch } - | LoginProgress::CodeReady { epoch, .. } - | LoginProgress::Authorized { epoch, .. } - | LoginProgress::DiscoveryTrouble { epoch, .. } - | LoginProgress::DiscoveryRetrySettled { epoch, .. } - | LoginProgress::LinkTrouble { epoch, .. } => (*epoch, false), - LoginProgress::Failed { epoch, .. } => (*epoch, true), - LoginProgress::SignedIn { .. } => return false, - }; - if epoch != envelope.key.epoch || terminal != envelope.terminal { return false; } - match progress { - LoginProgress::CodeReplacing { .. } => { - if envelope.key.op != SessionOp::Login { return false; } - self.state.phase = Phase::Creating; - self.state.pin_code.clear(); - self.state.qr_png.clear(); - self.state.code_replaced = true; - // The worker's miss count is per code: a fresh code starts clean. - self.state.link_trouble = false; - } - LoginProgress::CodeReady { code, qr_png, .. } => { - if envelope.key.op != SessionOp::Login { return false; } - let Some(next) = self.state.next_qr.checked_add(1) else { - self.fail_login(plx_platform::i18n::msg::browse_auth_start_failed(), - Some(IncidentContext::internal(InternalClass::Exhausted)), emit); - self.state.pending.remove(&req); - emit(SessionFx::Cancel { requests: vec![req], epoch: self.state.epoch }); - emit(SessionFx::Retire { req }); - self.replace_publication(); - return true; - }; - self.state.next_qr = next; - self.state.qr_gen = next; - self.state.pin_code = code.clone(); - self.state.qr_png = qr_png.clone(); - self.state.phase = Phase::Waiting; - } - LoginProgress::Authorized { token, .. } => { - if envelope.key.op != SessionOp::Login { return false; } - // A sign-in that is not a sign-out (a stored session that could not be - // activated, *Use another account*, the dev login trigger) starts from the - // stored record. Whoever that record seated, its roster and its offline - // profile cache belong to the authorization this token replaces, so none of - // them may ride into the new account: `SignedIn` writes the roster and - // `Session::account` names a single-user account from it; a Home account - // seats through the picker. Reset BEFORE `expected` is recomputed below. - // The new token cannot say whose cache this is (every sign-in mints one), - // so the cache is emptied while the identity is unknown and `SignedIn` - // restores the STORED record's when its roster names the same owner. - self.state.persisted.user = UserRef::default(); - self.state.persisted.home_users.clear(); - self.state.persisted.profiles.clear(); - self.state.persisted.account_token = token.clone(); - self.state.authorized_in_flow = true; - self.state.link_trouble = false; - self.state.discovery_retry = None; - self.state.error.clear(); - self.state.phase = Phase::Discovering; - self.state.pending.get_mut(&req).unwrap().expected = Identity::of(&self.state.persisted); - } - LoginProgress::DiscoveryTrouble { progress, .. } => { - if !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { - return false; - } - self.state.discovery_retry = Some(*progress); - } - LoginProgress::DiscoveryRetrySettled { run, .. } => { - if !matches!(envelope.key.op, SessionOp::Login | SessionOp::Rediscover) { - return false; - } - if self.state.discovery_retry.is_some_and(|retry| retry.run == *run) { - self.state.discovery_retry = None; - } - } - LoginProgress::LinkTrouble { trouble, .. } => { - if envelope.key.op != SessionOp::Login { return false; } - self.state.link_trouble = trouble.is_some(); - if let Some(context) = trouble { - self.raise_incident(IncidentFlow::SignIn, *context); + let patch = CredentialPatch::of(&next); + delta.credentials = Some(patch.clone()); + if !self.state.handoff_pending() { plan.credentials = Some(patch); } + // This request's `Ready` already seated this profile and committed its roster as + // the `Switch` — the one revoke that change of identity owes. This late roster is + // for that SAME seat, and that is proven, not assumed: `matches_request` admits it + // only in `ProfileSeated` and only for `progress.expected == pending.expected`; + // the `Ready` commit stamped `pending.expected` from the seat it installed; and + // `observe` dropped it above unless that identity is still the persisted one. So + // it is a same-identity refresh — retoken in place, retire what is no longer + // granted — never a second switch that blanks Home's live clients seconds after + // they drew (owner trace 2026-09-30, who's-watching picker path). + debug_assert!(pending.phase == StreamPhase::ProfileSeated + && pending.expected.matches(&self.common.persisted)); + let commit = RosterCommit::Refresh { same_identity: true }; + plan.registry = Self::roster_plan(&next, &progress.probes, commit); + } + Observation::Endpoint(progress) => { + let Some(lifecycle) = pending.lifecycle else { break 'apply_resource_observation false; }; + match &progress.fresh { + None => match &progress.probe { + // Nothing to INSTALL, but the probe itself is evidence — an InsecureOnly + // verdict most of all — so publish it rather than retiring silently. + Some(probe) => plan.registry.push(RegistryPlan::Probe(probe.clone())), + // The worker exited early (plex.tv itself unreachable, or the machine no + // longer among its resources): nothing was dialled, so there is nothing + // to publish and no verdict to widen — retire exactly as an empty + // `ServerRosterOutcome::NoReachable` does. + None => { + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + break 'apply_resource_observation true; } + }, + Some(fresh) => { + let mut next = self.common.persisted.clone(); + let Some((source, changed)) = super::apply_refreshed_endpoint(&mut next, &progress.machine_id, fresh) else { + { +let (req,): (u32,) = (req,); + + if self.common.pending.contains_key(&req) { + { let event = AttemptEvent::WorkRetired { req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + } + self.common.pending.remove(&req); + fx.push(SessionFx::Retire { req }); + +}; + break 'apply_resource_observation true; + }; + // Issue #95 step 6: this endpoint repair changes exactly the fields + // `refresh_profile_record` copies into the active profile's cached + // record (server/sources) — miss this and a plaintext-to-https repair + // (or any other endpoint move) never reaches `Session::profiles`, so an + // offline reseat of this same profile keeps dialling the stale origin + // forever. `ProfileRoster`'s commit above makes the identical call. + // The ServerRoster Reconcile arm above already plans credentials on + // `changed || repaired`; this commit used to gate on `changed` alone, + // silently dropping a repaired-but-otherwise-unchanged active + // `ProfileCreds` record on the floor. + let repaired = next.refresh_profile_record(); + let patch = CredentialPatch::of(&next); + delta.credentials = Some(patch.clone()); + if (changed || repaired) && !self.state.handoff_pending() { plan.credentials = Some(patch); } + plan.registry.push(RegistryPlan::Endpoint { expected: lifecycle, source }); } - LoginProgress::Failed { message, incident, plaintext, account, .. } => { - self.fail_login(message, Some(*incident), emit); - self.state.plaintext = plaintext.clone(); - self.state.signin_account = account.clone(); - } - LoginProgress::SignedIn { .. } => unreachable!(), } } } - if envelope.terminal { - self.state.pending.remove(&req); - } else { - self.state.pending.get_mut(&req).unwrap().last_arrival = Some(envelope.arrival); - } - self.replace_publication(); + plan.writes_durable = plan.credentials.is_some(); + 'begin_commit: { +let (req, arrival, terminal, plan, delta,): (u32, u64, bool, CommitPlan, CommitDelta,) = (req, envelope.arrival, envelope.terminal, plan, delta,); + + let Some(entry) = ('commit: { let (req, arrival, terminal, plan, delta): (u32, u64, bool, CommitPlan, CommitDelta) = (req, arrival, terminal, plan, delta); let Some(CommitPreparation { pending, entry }) = self.plan_commit(req, arrival, terminal, plan, delta) else { break 'commit None }; self.common.pending.get_mut(&req).unwrap().last_arrival = Some(arrival); self.common.pending_commit = Some(pending); self.common.persistence_purpose = Some(entry.plan.purpose); Some(entry) }) else { break 'begin_commit false }; + entry.emit(&mut |effect| fx.push(effect)); true - } - /// The checked allocator is independent from the full-width auth epoch. Exhaustion cannot - /// reuse an address, including when a cancelled worker still owns a Landing reservation. - fn allocate(&mut self, op: SessionOp, lifecycle: Option) -> Option { - let req = self.state.next_req.checked_add(1)?; - self.state.next_req = req; - self.state.pending.insert(req, Pending { - key: SessionWorkKey { epoch: self.state.epoch, op }, - expected: Identity::of(&self.state.persisted), lifecycle, - last_arrival: None, phase: StreamPhase::Running, capture: None, admission: AdmissionState::NotRequested, - }); - Some(req) - } +} - /// Admission to logical application, not a resource reservation. Landing owns the latter. - /// Merely inspecting an invalid envelope must not mutate pending state or its publication. - fn accepts_header(&self, envelope: &SessionEnvelope) -> bool { - if envelope.addr.to != MachineId::Session { return false; } - let Some(pending) = self.state.pending.get(&envelope.addr.req.0) else { return false; }; - pending.key == envelope.key && pending.key.epoch == self.state.epoch - && pending.capture.is_none() - && matches!(pending.admission, AdmissionState::Awaiting(id) | AdmissionState::Accepted(id) if id == envelope.admission) - && pending.last_arrival.is_none_or(|last| envelope.arrival > last) - } +}; + } + } + if let Some(commit) = &self.common.pending_commit { + assert!(commit.req == receipt.addr.req.0 && commit.epoch == receipt.key.epoch + && commit.arrival == receipt.arrival, "Session commit receipt mismatch"); + self.common.pending_commit.as_mut().unwrap().receipt = Some(receipt); + } else { + fx.push(SessionFx::Acknowledge(vec![receipt])); + } + { - fn accepts(&self, envelope: &SessionEnvelope) -> bool { - if !self.accepts_header(envelope) { return false; } - let pending = &self.state.pending[&envelope.addr.req.0]; - match &envelope.outcome { - SessionArrival::Data(data) => data.matches_request(pending, envelope.terminal) - && (!matches!(pending.key.op, SessionOp::Endpoint(_)) - || pending.lifecycle == envelope.lifecycle), - SessionArrival::Dropped | SessionArrival::Refused => envelope.terminal, + if !self.common.inbox.is_empty() && self.common.pending_commit.is_none() && !self.common.pump_pending { + self.common.pump_pending = true; + fx.push(SessionFx::Pump); } - } - /// The frame step reports what the cache lacks. At most one refresh is out at a time; a backoff - /// holds the next one back on the frame clock; and the first transient observation of a cache - /// entry arms the backoff instead of reading, so a boot with the storage helper down retries - /// about a second later, as the in-line retry timer did, not on frame one. - fn observe_cache(&mut self, need: plx_plex::plex::session::RefreshNeed, now_ms: u32, - emit: &mut impl FnMut(SessionFx)) { - use plx_plex::plex::session::LOCKED_RETRY_MS; - let tracked = match self.cache_refresh { - CacheRefresh::InFlight { .. } => return, - CacheRefresh::Backoff { armed_ms, generation } => { - let covers = generation.is_none_or(|g| g == need.generation); - if covers && now_ms.wrapping_sub(armed_ms) < LOCKED_RETRY_MS { return; } - covers - } - CacheRefresh::Idle => false, - }; - if need.transient && !tracked { - self.cache_refresh = CacheRefresh::Backoff { armed_ms: now_ms, generation: Some(need.generation) }; - return; +}; + +}; } +// All login entry paths converge here; the reply follows its ordered exit and entry effects. +let mut restarted = false; +if let Some(restart) = restart { restarted = 'restart_login: { +let (fresh_login,): (bool,) = (matches!(restart, LoginRestart::Fresh),); + + if matches!(self.common.authority, BootstrapAuthority::DevPms { .. }) { + break 'restart_login (fresh_login || self.state .phase() == Phase::Error) && 'begin_dev_account: { + + if self.state .pending_erase().is_some() || self.common.epoch.checked_add(1).is_none() + || self.common.next_req.checked_add(2).is_none() + || self.common.pending_commit.as_ref().is_some_and(|c| + matches!(c.delta.dev, Some(DevCommitDelta::StartAccount { .. }))) { break 'begin_dev_account false; } + ('advance_epoch: { + + let exit = match ExitFx::epoch(self.view()) { Some(value) => value, None => break 'advance_epoch None }; + let epoch = exit.epoch_number(); + self.common.inbox.clear(); + self.common.pending_commit = None; + self.common.pending.clear(); + self.common.epoch = epoch; + { let event = AttemptEvent::EpochAdvanced; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + // Keep pump_pending: a marker may still be carried outside the owner. + exit.emit(&mut |effect| fx.push(effect)); + Some(epoch) + +}).expect("dev login epoch preflight"); + { +let (profile,): (Option,) = (None,); + + // This is the sole scope allocator. Resource publication will store this explicit value + // rather than independently incrementing another generation. + self.common.profile_scope.0 = self.common.profile_scope.0.wrapping_add(1); + self.common.active_profile = profile; + fx.push(SessionFx::PublishProfile(ProfilePublication { + epoch: self.common.epoch, profile: self.common.active_profile.clone(), scope: self.common.profile_scope, + stamp: plx_plex::plex::grant::account_key(&self.common.persisted.account_token), + })); + +}; + let req = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::DevBoundary, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }).expect("two-slot preflight"); + let login_req = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (SessionOp::Login, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }).expect("two-slot preflight"); + { let event = AttemptEvent::BeginDevAccount { boundary_req: req, login_req }; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + 'begin_commit: { +let (req, arrival, terminal, plan, delta,): (u32, u64, bool, CommitPlan, CommitDelta,) = (req, 0, true, CommitPlan { registry_client_id: self.common.persisted.client_id.clone(), + expected_disk: self.common.disk_identity.clone(), + credentials: None, lifecycle: None, registry: vec![RegistryPlan::Revoke], + purpose: PersistencePurpose::Background, writes_durable: false, + authority: plx_plex::plex::session::SaveAuthority::Routine }, CommitDelta { + dev: Some(DevCommitDelta::StartAccount { login_req }), ..Default::default() + },); + + let Some(entry) = ('commit: { let (req, arrival, terminal, plan, delta): (u32, u64, bool, CommitPlan, CommitDelta) = (req, arrival, terminal, plan, delta); let Some(CommitPreparation { pending, entry }) = self.plan_commit(req, arrival, terminal, plan, delta) else { break 'commit None }; self.common.pending.get_mut(&req).unwrap().last_arrival = Some(arrival); self.common.pending_commit = Some(pending); self.common.persistence_purpose = Some(entry.plan.purpose); Some(entry) }) else { break 'begin_commit false }; + entry.emit(&mut |effect| fx.push(effect)); + true + +}; + { publish = true; }; + true + +}; } - self.next_cache_req = self.next_cache_req.wrapping_add(1); - let req = self.next_cache_req; - self.cache_refresh = CacheRefresh::InFlight { req, generation: need.generation }; - emit(SessionFx::RefreshCache { req, generation: need.generation }); - } + if self.state .pending_erase().is_some() { break 'restart_login false; } + if self.common.epoch.checked_add(1).is_none() { break 'restart_login false; } + if self.common.next_req.checked_add(1).is_none() { break 'restart_login false; } + let discovery = !fresh_login && super::retry_kind(self.state .phase(), + self.state.fresh_authority()) == super::RetryKind::Discovery; + let fresh_attempt = fresh_login || super::restart_is_a_new_attempt(self.common.signin_notice.owed()); + ('advance_epoch: { + + let exit = match ExitFx::epoch(self.view()) { Some(value) => value, None => break 'advance_epoch None }; + let epoch = exit.epoch_number(); + self.common.inbox.clear(); + self.common.pending_commit = None; + self.common.pending.clear(); + self.common.epoch = epoch; + { let event = AttemptEvent::EpochAdvanced; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + // Keep pump_pending: a marker may still be carried outside the owner. + exit.emit(&mut |effect| fx.push(effect)); + Some(epoch) - /// A refresh ended. Only the request in flight can end it: a duplicate or stale answer is dropped. - fn cache_refreshed(&mut self, req: u32, outcome: plx_plex::plex::session::CacheRefreshOutcome, now_ms: u32) -> bool { - use plx_plex::plex::session::CacheRefreshOutcome; - if self.cache_refresh_in_flight() != Some(req) { return false; } - let armed_ms = now_ms; - self.cache_refresh = match outcome { - CacheRefreshOutcome::Settled | CacheRefreshOutcome::Superseded => CacheRefresh::Idle, - CacheRefreshOutcome::Transient { generation } => CacheRefresh::Backoff { armed_ms, generation: Some(generation) }, - CacheRefreshOutcome::Refused => CacheRefresh::Backoff { armed_ms, generation: None }, - }; +}).expect("epoch exhaustion checked before transition"); + if discovery { + // 0.6.6 parity (`discovery-warning-not-cleared-on-retry-or-fresh-success`): a restart + // begins a fresh discovery attempt under a NEW epoch, so a warning (or a held handoff) + // left over from the attempt being retried can never be released or acknowledged by + // anything this new epoch does — it would sit stale forever. A rediscovery restart + // clears both, the same way the fresh-attempt branch below already does. + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + } else { + self.common.persisted = self.common.committed_credentials.merge_into(&self.common.persisted); + self.common.persistence_warning = None; + self.common.held_handoff = None; + self.common.persistence_warning_answered = false; + } + let op = if discovery { SessionOp::Rediscover } else { SessionOp::Login }; + let req = ('reservation: { let (op, lifecycle): (SessionOp, Option) = (op, None); let Some(WorkReservation { req, pending }) = self.plan_reservation(op, lifecycle) else { break 'reservation None }; self.common.next_req = req; self.common.pending.insert(req, pending); Some(req) }).expect("request exhaustion checked before transition"); + let event = if discovery { AttemptEvent::RestartDiscovery { req } } else { AttemptEvent::RestartLogin { req } }; + { let event = event; let exit = ExitFx::attempt(self.view(), &event); let entry = EntryFx::attempt(self.view(), &event); if let Some(notice) = signin_notice(&event) { self.common.signin_notice = notice; } exit.emit(&mut |effect| fx.push(effect)); let attempt = std::mem::replace(&mut self.state, attempt::Attempt::placeholder()); self.state = next_attempt(attempt, event); entry.emit(&mut |effect| fx.push(effect)); true }; + let entry = EntryFx::login(self.view(), req, discovery, fresh_attempt); + let pending = self.common.pending.get_mut(&req).expect("allocated login request"); + match entry.work() { + EntryWork::Capture { .. } => pending.capture = Some(CaptureIntent::Login), + EntryWork::Work { admission, .. } => pending.admission = AdmissionState::Awaiting(*admission), + } + entry.emit(&mut |effect| fx.push(effect)); + { publish = true; }; true - } - fn replace_publication(&mut self) { - // Compare borrowed fields first: constructing a throwaway snapshot here would copy - // QR/roster payloads even if equality then retained all of the old handles. - if self.publication.matches_state(&self.state) { return; } - let next = SessionSnapshot::from_state_counted(&self.state, Some(&self.publication), &mut |field| { - #[cfg(test)] - { self.publication_payload_allocations[field] += 1; } - #[cfg(not(test))] - { let _ = field; } - }); - self.publication = Arc::new(next); - } +}; if !matches!(ev, SessionEvent::Erased { .. } | SessionEvent::Command(Command::RestartWait { .. })) { handled = restarted; } } +if let Some((reply, permitted)) = restart_reply { fx.push(SessionFx::RestartReply { to: *reply, accepted: permitted && restarted }); } +// Publications are observable only after this atomic event has finished. +if publish { if let Some((next, allocations)) = self.publication_update() { self.publication = next; #[cfg(test)] for (total, count) in self.publication_payload_allocations.iter_mut().zip(allocations) { *total += count; } #[cfg(not(test))] let _ = allocations; } } +if !matches!(ev, SessionEvent::CacheObserved(_) | SessionEvent::CacheRefreshed { .. } | SessionEvent::ConsumeLogicalDirty) { { + + let mut canon = Canon::new(); + LegacyV5Projection::from_partition(self.view()).write(&mut canon); + let next = canon.finish(); + if next != self.subhash { + self.subhash = next; + self.logical_dirty = true; + } + +}; } +handled +} + #[cfg(test)] fn replace_publication(&mut self) { self.transition(&SessionEvent::RebuildPublication, 0, &mut Vec::new()); } } impl plx_machine::machine::Machine for SessionMachine { type Ev = SessionEvent; - fn step(&mut self, ev: &SessionEvent, cx: &plx_machine::machine::Cx<'_, H>, - fx: &mut plx_machine::machine::Effects<'_, H>) -> plx_machine::machine::Handled { - use plx_machine::machine::{Fx, Handled}; - let before = self.publication(); - let mut emit = |effect| fx.push(Fx::App(H::session_effect(effect))); - let handled = match ev { - SessionEvent::Command(Command::ActivateDevBootstrap) => self.activate_dev(&mut emit), - SessionEvent::Command(Command::ResumeStored) => self.resume_stored(&mut emit), - SessionEvent::Command(Command::StartLogin) => self.restart_login(true, &mut emit), - SessionEvent::Command(Command::Retry) => self.retry(&mut emit), - SessionEvent::Command(Command::TakeReady) => self.take_ready(&mut emit), - SessionEvent::Command(Command::AcknowledgePersistenceWarning { key }) => - self.acknowledge_persistence_warning(*key, &mut emit), - SessionEvent::Command(command @ (Command::ResolveIncident { .. } - | Command::ReportIncident { .. } | Command::DeclineIncident { .. })) => { - let handled = self.step_incident_command(command, &mut emit); - if handled { self.replace_publication(); } - handled - } - SessionEvent::Command(Command::StartSwitch(picker)) => self.start_switch(*picker, &mut emit), - SessionEvent::Command(Command::SelectProfile { index, pin }) => self.select_profile(*index, pin.clone(), &mut emit), - SessionEvent::Command(Command::SelectProfileWithReply { index, pin, reply }) => { - let accepted = self.select_profile(*index, pin.clone(), &mut emit); - emit(SessionFx::SelectionReply { to: *reply, accepted, flow_epoch: self.state.epoch }); - true - } - SessionEvent::Command(Command::BackAtRoot { reply }) => self.back(*reply, &mut emit), - SessionEvent::Command(Command::SignOut) => self.erase(true, &mut emit), - SessionEvent::Command(Command::EraseLocal) => self.erase(false, &mut emit), - SessionEvent::Command(Command::RefreshRoster) => self.refresh_roster(&mut emit), - SessionEvent::Command(Command::RequestEndpoint { sid }) => self.request_endpoint(*sid, &mut emit), - SessionEvent::Command(Command::AnswerPlaintext { machine_id, choice, sid }) => - self.answer_plaintext(machine_id, *choice, *sid, &mut emit), - SessionEvent::Command(Command::RestartWait { phase, qr_generation, reply }) => { - let accepted = matches!(self.state.authority, BootstrapAuthority::Account { .. }) - && super::restart_permitted(Some((*phase, *qr_generation)), - (self.state.phase, self.state.qr_gen)) && self.restart_login(false, &mut emit); - emit(SessionFx::RestartReply { to: *reply, accepted }); - true - } - SessionEvent::Command(Command::DismissPinError) => { - self.state.pin_denied = false; - self.replace_publication(); - true - } - SessionEvent::Command(Command::NoteDeleteLeftovers(count)) => { - self.state.delete_leftovers = *count; - self.replace_publication(); - true - } - SessionEvent::Result(envelope) => self.ingest(envelope, &mut emit), - SessionEvent::Commit(reply) => self.apply_commit_reply(*reply, &mut emit), - SessionEvent::DiskWrite { before, after, outcome } => self.observe_disk_write(before, after, *outcome), - SessionEvent::Persistence(completion) => self.apply_persistence_completion(*completion, &mut emit), - SessionEvent::Read(reply) => self.apply_read(reply, &mut emit), - SessionEvent::Admission(reply) => self.apply_admission(*reply, &mut emit), - SessionEvent::Erased { epoch, leftovers } => self.erased(*epoch, *leftovers, &mut emit), - SessionEvent::IncidentReported { id, delivery } => { - let handled = self.incident_reported(*id, delivery); - if handled { self.replace_publication(); } - handled - } - SessionEvent::Pump => { - self.state.pump_pending = false; - self.pump_one(&mut emit); - true - } - SessionEvent::CacheObserved(need) => { - self.observe_cache(*need, cx.tick.ms, &mut emit); - true - } - SessionEvent::CacheRefreshed { req, outcome } => self.cache_refreshed(*req, *outcome, cx.tick.ms), - }; - if !Arc::ptr_eq(&before, &self.publication) { - fx.invalidate(plx_machine::present::Provenance::Landing(MachineId::Session)); - } - // The cache bookkeeping is outside the recorded state, so its events (the first of them on - // EVERY frame a read is missing) cannot move the subhash: skip the whole-state rehash. - if !matches!(ev, SessionEvent::CacheObserved(_) | SessionEvent::CacheRefreshed { .. }) { - self.refresh_subhash(); - } - if handled { Handled::Yes } else { Handled::No } - } + fn step(&mut self, ev: &SessionEvent, cx: &plx_machine::machine::Cx<'_, H>, fx: &mut plx_machine::machine::Effects<'_, H>) -> plx_machine::machine::Handled { + use plx_machine::machine::{Fx, Handled}; + let before = self.publication(); + let mut effects = Vec::new(); + let handled = self.transition(ev, cx.tick.ms, &mut effects); + for effect in effects { fx.push(Fx::App(H::session_effect(effect))); } + if !Arc::ptr_eq(&before, &self.publication) { fx.invalidate(plx_machine::present::Provenance::Landing(MachineId::Session)); } + if handled { Handled::Yes } else { Handled::No } +} } #[cfg(any(test, feature = "test-support"))] @@ -2941,6 +4807,60 @@ mod tests { use super::*; use super::scenarios::{roster_refresh_fixture, step, step_at, OwnerHost}; + #[test] + fn logical_dirty_drain_is_an_owner_event_without_effects_or_publication_damage() { + let mut owner = SessionMachine::from_init(SessionInit::captured(PersistedSession::default())); + let publication = owner.publication(); + let subhash = owner.subhash(); + let mut effects = Vec::new(); + assert!(owner.transition(&SessionEvent::ConsumeLogicalDirty, 0, &mut effects)); + assert!(!owner.transition(&SessionEvent::ConsumeLogicalDirty, 0, &mut effects)); + assert!(effects.is_empty()); + assert_eq!(owner.subhash(), subhash); + assert!(Arc::ptr_eq(&publication, &owner.publication())); + } + + #[test] + fn legacy_incident_callback_forwards_the_typed_event_effect_drain() { + let mut legacy = SessionMachine::from_init(SessionInit::captured(PersistedSession::default())); + let context = IncidentContext::new(IncidentKind::PinCreate, None); + legacy.raise_incident(IncidentFlow::SignIn, context); + let id = legacy.common.incident.as_ref().unwrap().id; + let mut typed = SessionMachine::from_init(legacy.snapshot_init()); + let mut observed = Vec::new(); + assert!(legacy.resolve_incident(id, Permission::Granted, 1, &mut |effect| observed.push(effect))); + let mut expected = Vec::new(); + assert!(typed.transition(&SessionEvent::Command(Command::ResolveIncident { + id, permission: Permission::Granted, revision: 1, + }), 0, &mut expected)); + assert_eq!(observed.len(), 1); + assert_eq!(expected.len(), 1); + for effect in observed.iter().chain(expected.iter()) { + assert!(matches!(effect, SessionFx::Incident { id: seen, lane: IncidentLane::Standing, + report: IncidentReport::Retained(evidence) } if *seen == id && *evidence == context)); + } + assert_eq!(legacy.snapshot_init().incident, typed.snapshot_init().incident); + assert_eq!(legacy.subhash(), typed.subhash()); + } + + #[test] + fn standalone_incident_events_publish_the_owned_readout() { + let mut owner = SessionMachine::from_init(SessionInit::captured(PersistedSession::default())); + let context = IncidentContext::new(IncidentKind::PinCreate, None); + let before = owner.publication(); + let mut effects = Vec::new(); + assert!(owner.transition(&SessionEvent::RaiseIncident { flow: IncidentFlow::SignIn, context }, 0, &mut effects)); + assert!(owner.common.incident.is_some()); + assert_eq!(owner.read().0.incident, owner.snapshot_init().incident); + assert!(!Arc::ptr_eq(&before, &owner.publication())); + let before = owner.publication(); + assert!(owner.transition(&SessionEvent::ForgetIncidents, 0, &mut effects)); + assert!(owner.common.incident.is_none()); + assert!(owner.read().0.incident.is_none()); + assert!(!Arc::ptr_eq(&before, &owner.publication())); + assert!(effects.is_empty()); + } + /// The session-cache refresh bookkeeping (`CacheRefresh`): driven by tick values, no sleeping. mod cache_refresh { use super::*; @@ -2955,7 +4875,12 @@ mod tests { fn refreshes(effects: &[SessionFx]) -> Vec<(u32, u64)> { effects.iter().filter_map(|fx| match fx { SessionFx::RefreshCache { req, generation } => Some((*req, *generation)), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } => None, }).collect() } fn owner() -> SessionMachine { SessionMachine::from_init(captured_session()) } @@ -3163,6 +5088,87 @@ mod tests { SessionInit::captured(PersistedSession { client_id: "synthetic-client".into(), ..Default::default() }) } + #[test] + fn epoch_exit_plan_is_pure_and_preserves_cancel_receipt_fifo() { + let mut owner = SessionMachine::from_init(captured_session()); + let first = owner.allocate(SessionOp::ServerRoster, None).unwrap(); + let second = owner.allocate(SessionOp::HomeRoster, None).unwrap(); + let envelope = |req, arrival, op| SessionEnvelope { + addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, + key: SessionWorkKey { epoch: 1, op }, admission: AdmissionId(req), arrival, + terminal: true, lifecycle: None, outcome: SessionArrival::Refused, + }; + let queued = envelope(second, 2, SessionOp::HomeRoster); + let committed = envelope(first, 1, SessionOp::ServerRoster); + let receipts = vec![Receipt::of(&queued), Receipt::of(&committed)]; + owner.common.inbox.push_back(queued); + owner.common.pending_commit = Some(PendingCommit { + req: first, epoch: 1, arrival: 1, terminal: true, writes_credentials: false, + receipt: Some(Receipt::of(&committed)), delta: CommitDelta::default(), + admitted_revision: None, purpose: None, fresh: false, + }); + owner.common.pump_pending = true; + let before = serde_json::to_value(owner.snapshot_init()).unwrap(); + let exit = ExitFx::epoch(owner.view()).unwrap(); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), before); + let mut planned = Vec::new(); + exit.emit(&mut |fx| planned.push(fx)); + assert!(matches!(planned.as_slice(), [ + SessionFx::Cancel { requests: a, epoch: 1 }, + SessionFx::Acknowledge(r), + SessionFx::Cancel { requests: b, epoch: 2 }, + ] if a == &vec![first] && r == &receipts && b == &vec![first, second])); + let actual = step(&mut owner, SessionEvent::Command(Command::StartLogin)); + assert!(matches!(actual.as_slice(), [ + SessionFx::Cancel { requests: a, epoch: 1 }, + SessionFx::Acknowledge(r), + SessionFx::Cancel { requests: b, epoch: 2 }, + SessionFx::Coordinator(CoordinatorAction::SignInStarted), + SessionFx::Work { req: 3, .. }, + ] if a == &vec![first] && r == &receipts && b == &vec![first, second])); + assert!(owner.common.pump_pending); + } + + #[test] + fn epoch_exit_plan_refuses_exhaustion_without_effects_or_mutation() { + let mut init = captured_session(); + init.epoch = u64::MAX; + let mut owner = SessionMachine::from_init(init); + let before = serde_json::to_value(owner.snapshot_init()).unwrap(); + assert!(ExitFx::epoch(owner.view()).is_none()); + assert!(step(&mut owner, SessionEvent::Command(Command::StartLogin)).is_empty()); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), before); + } + + #[test] + fn login_entry_plans_capture_or_work_without_mutating_the_ledger() { + for (client, discovery) in [("", false), ("synthetic-client", false), ("", true), ("synthetic-client", true)] { + let mut init = captured_session(); + init.persisted.client_id = client.into(); + init.persisted.account_token = "synthetic-account".into(); + let mut owner = SessionMachine::from_init(init); + let op = if discovery { SessionOp::Rediscover } else { SessionOp::Login }; + let req = owner.allocate(op, None).unwrap(); + let before = serde_json::to_value(owner.snapshot_init()).unwrap(); + let entry = EntryFx::login(owner.view(), req, discovery, false); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), before); + let mut effects = Vec::new(); + entry.emit(&mut |fx| effects.push(fx)); + if discovery { + assert!(matches!(effects.as_slice(), [SessionFx::Work { req: 1, key, + admission: AdmissionId(1), input: SessionWork::Rediscover { client_id, account_token } }] + if key.epoch == 1 && client_id == client && account_token == "synthetic-account")); + } else if client.is_empty() { + assert!(matches!(effects.as_slice(), [SessionFx::Capture { req: 1, epoch: 1, + request: SessionReadRequest::LoginClientId }])); + } else { + assert!(matches!(effects.as_slice(), [SessionFx::Work { req: 1, key, + admission: AdmissionId(1), input: SessionWork::Login { client_id } }] + if key.epoch == 1 && client_id == client)); + } + } + } + /// A session that can actually go local, so `resume_stored` can reach its registry-only /// commit. Synthetic values only. fn local_session() -> SessionInit { @@ -3232,8 +5238,8 @@ mod tests { CompletionOutcome, Failure, Operation, PersistOutcome, PersistenceCompletion, }; let mut owner = SessionMachine::from_init(reopened_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { uuid: "u-1".into(), protected: false, @@ -3249,7 +5255,7 @@ mod tests { outcome: PersistOutcome::PersistedPlaintext, verified: true, protection: None }) }; step(&mut owner, SessionEvent::Persistence(discovery_durable)); step(&mut owner, SessionEvent::Command(Command::TakeReady)); - let final_req = owner.state.next_req; + let final_req = owner.common.next_req; let final_reply = CommitReply { req: final_req, epoch, arrival: 0, admission: CommitAdmission::Admitted { revision: 2, purpose: PersistencePurpose::Final } }; step(&mut owner, SessionEvent::Commit(final_reply)); @@ -3257,8 +5263,8 @@ mod tests { purpose: PersistencePurpose::Final, outcome: CompletionOutcome::Failed(Failure::Persistence(PersistOutcome::WriteFailed)) }; step(&mut owner, SessionEvent::Persistence(final_failed)); - assert!(owner.state.held_handoff.is_some(), "rig: the Ready handoff is held"); - assert!(owner.state.persistence_warning.is_some(), "rig: a Final warning is showing"); + assert!(owner.common.held_handoff.is_some(), "rig: the Ready handoff is held"); + assert!(owner.common.persistence_warning.is_some(), "rig: a Final warning is showing"); owner } @@ -3268,43 +5274,43 @@ mod tests { fn commit_consumption_is_typed_and_a_stale_reply_settles_nothing() { let mut owner = SessionMachine::from_init(local_session()); assert!(owner.resume_stored(&mut |_| {})); - let req = owner.state.next_req; - let epoch = owner.state.epoch; - assert!(owner.state.pending_commit.is_some()); + let req = owner.common.next_req; + let epoch = owner.common.epoch; + assert!(owner.common.pending_commit.is_some()); // A registry-only commit asked storage for nothing and must not claim a revision. let registry_only = CommitReply { req, epoch, arrival: 0, admission: CommitAdmission::RegistryOnly }; let effects = step(&mut owner, SessionEvent::Commit(registry_only)); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Retire { .. }))); - assert_eq!(owner.state.commit_phase, CommitPhase { admitted: false, durable: false, proves_saved_login: false }); - assert!(owner.state.pending_commit.is_none()); - assert_eq!(owner.state.persistence_purpose, None, + assert_eq!(owner.common.commit_phase, CommitPhase { admitted: false, durable: false, proves_saved_login: false }); + assert!(owner.common.pending_commit.is_none()); + assert_eq!(owner.common.persistence_purpose, None, "a registry-only commit must not claim a persistence purpose"); // A stale completion (wrong epoch) must not settle or retire anything. let mut owner = SessionMachine::from_init(local_session()); assert!(owner.resume_stored(&mut |_| {})); - let req = owner.state.next_req; + let req = owner.common.next_req; let before = owner.snapshot_init().hash(); - let stale = CommitReply { req, epoch: owner.state.epoch + 9, arrival: 0, + let stale = CommitReply { req, epoch: owner.common.epoch + 9, arrival: 0, admission: CommitAdmission::StaleAuthority }; assert!(step(&mut owner, SessionEvent::Commit(stale)).is_empty()); assert_eq!(owner.snapshot_init().hash(), before, "a stale completion must change nothing"); - assert!(owner.state.pending_commit.is_some()); - assert_eq!(owner.state.commit_phase, CommitPhase { admitted: false, durable: false, proves_saved_login: false }, + assert!(owner.common.pending_commit.is_some()); + assert_eq!(owner.common.commit_phase, CommitPhase { admitted: false, durable: false, proves_saved_login: false }, "a stale completion must not report a durable admission"); // The committed purpose survives into the owner's state so the caller can refuse to // treat a background refresh as proof of a saved login. let mut owner = SessionMachine::from_init(local_session()); assert!(owner.resume_stored(&mut |_| {})); - let req = owner.state.next_req; - let durable = CommitReply { req, epoch: owner.state.epoch, arrival: 0, + let req = owner.common.next_req; + let durable = CommitReply { req, epoch: owner.common.epoch, arrival: 0, admission: CommitAdmission::Admitted { revision: 3, purpose: PersistencePurpose::Final } }; assert!(owner.apply_commit_reply(durable, &mut |_| {})); - assert_eq!(owner.state.commit_phase, CommitPhase { admitted: true, durable: false, proves_saved_login: false }); - assert_eq!(owner.state.persistence_purpose, None, + assert_eq!(owner.common.commit_phase, CommitPhase { admitted: true, durable: false, proves_saved_login: false }); + assert_eq!(owner.common.persistence_purpose, None, "the purpose is cleared once the commit settles"); } @@ -3319,8 +5325,8 @@ mod tests { PersistencePurpose, }; let admit = |owner: &mut SessionMachine, purpose: PersistencePurpose| { - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let durable = CommitReply { req, epoch, arrival: 0, admission: CommitAdmission::Admitted { revision: 1, purpose } }; assert!(owner.apply_commit_reply(durable, &mut |_| {})); @@ -3342,29 +5348,29 @@ mod tests { let mut owner = SessionMachine::from_init(local_session()); assert!(owner.resume_stored(&mut |_| {})); let correlation = admit(&mut owner, PersistencePurpose::Final); - assert!(owner.state.admitted_persistence.is_some(), + assert!(owner.common.admitted_persistence.is_some(), "an admitted write must leave a fenced identity behind"); let stale_epoch = durable_completion(correlation, PersistencePurpose::Final, 1, correlation.epoch + 9); deliver(&mut owner, stale_epoch); - assert!(!owner.state.commit_phase.durable, + assert!(!owner.common.commit_phase.durable, "a completion from a retired epoch must be inert"); - assert!(!owner.state.commit_phase.proves_saved_login); - assert!(owner.state.admitted_persistence.is_some(), + assert!(!owner.common.commit_phase.proves_saved_login); + assert!(owner.common.admitted_persistence.is_some(), "a fenced-out completion must not consume the admitted identity"); // (b) A completion naming another revision is a different operation's verdict. let wrong_revision = durable_completion(correlation, PersistencePurpose::Final, 99, correlation.epoch); deliver(&mut owner, wrong_revision); - assert!(!owner.state.commit_phase.durable, + assert!(!owner.common.commit_phase.durable, "a completion naming another revision is a different operation's verdict"); // (c) The matching completion for a Final purpose DOES settle as saved-login evidence. let matching = durable_completion(correlation, PersistencePurpose::Final, 1, correlation.epoch); deliver(&mut owner, matching); - assert!(owner.state.commit_phase.durable, "storage confirmed durability"); - assert!(owner.state.commit_phase.proves_saved_login, + assert!(owner.common.commit_phase.durable, "storage confirmed durability"); + assert!(owner.common.commit_phase.proves_saved_login, "a Final write is evidence a login was saved"); - assert!(owner.state.admitted_persistence.is_none(), "the identity is consumed once settled"); + assert!(owner.common.admitted_persistence.is_none(), "the identity is consumed once settled"); // (d) The SAME matching completion for a Background purpose is durable but NOT evidence. let mut owner = SessionMachine::from_init(local_session()); @@ -3372,8 +5378,8 @@ mod tests { let correlation = admit(&mut owner, PersistencePurpose::Background); let background = durable_completion(correlation, PersistencePurpose::Background, 1, correlation.epoch); deliver(&mut owner, background); - assert!(owner.state.commit_phase.durable, "a background refresh does become durable"); - assert!(!owner.state.commit_phase.proves_saved_login, + assert!(owner.common.commit_phase.durable, "a background refresh does become durable"); + assert!(!owner.common.commit_phase.proves_saved_login, "a background refresh must never be offered as proof of a saved login"); // (e) A purpose mismatch is fenced even when the correlation matches exactly. @@ -3382,7 +5388,7 @@ mod tests { let correlation = admit(&mut owner, PersistencePurpose::Background); let mismatched = durable_completion(correlation, PersistencePurpose::Final, 1, correlation.epoch); deliver(&mut owner, mismatched); - assert!(!owner.state.commit_phase.durable, + assert!(!owner.common.commit_phase.durable, "a verdict resolved for a different purpose is not this operation's verdict"); } @@ -3398,9 +5404,9 @@ mod tests { CompletionOutcome, Failure, Operation, PersistOutcome, PersistenceCompletion, }; let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; - assert!(owner.state.authorized_in_flow, "the rig starts with a completed PIN authorization"); + let req = owner.common.next_req; + let epoch = owner.common.epoch; + assert!(owner.state.projected_authorization(), "the rig starts with a completed PIN authorization"); // The SignedIn observation begins a DISCOVERY commit, on a PEEKED fresh authority (not // consumed yet — AUTH-04's own guarantee). @@ -3414,7 +5420,7 @@ mod tests { }; assert_eq!(plan.purpose, PersistencePurpose::Discovery); assert_eq!(plan.authority, plx_plex::plex::session::SaveAuthority::FreshReauthentication); - assert!(owner.state.authorized_in_flow, "a discovery commit only PEEKS the authority"); + assert!(owner.state.projected_authorization(), "a discovery commit only PEEKS the authority"); let discovery_reply = CommitReply { req, epoch, arrival: 1, admission: CommitAdmission::Admitted { revision: 1, purpose: PersistencePurpose::Discovery } }; @@ -3426,7 +5432,7 @@ mod tests { outcome: CompletionOutcome::Durable(Operation::Write { outcome: PersistOutcome::PersistedPlaintext, verified: true, protection: None }) }; step(&mut owner, SessionEvent::Persistence(discovery_durable)); - assert!(owner.state.persistence_warning.is_none(), "the discovery write DID land durably"); + assert!(owner.common.persistence_warning.is_none(), "the discovery write DID land durably"); // take_ready now issues the FINAL commit, consuming the authority exactly once. let effects = step(&mut owner, SessionEvent::Command(Command::TakeReady)); @@ -3436,15 +5442,15 @@ mod tests { }; assert_eq!(final_plan.purpose, PersistencePurpose::Final); assert_eq!(final_plan.authority, plx_plex::plex::session::SaveAuthority::FreshReauthentication); - assert!(!owner.state.authorized_in_flow, "the final commit consumes the authority"); + assert!(!owner.state.projected_authorization(), "the final commit consumes the authority"); - let final_req = owner.state.next_req; + let final_req = owner.common.next_req; let final_reply = CommitReply { req: final_req, epoch, arrival: 0, admission: CommitAdmission::Admitted { revision: 2, purpose: PersistencePurpose::Final } }; let effects = step(&mut owner, SessionEvent::Commit(final_reply)); assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Ready { .. })), "a FRESH admission is held, not announced, until its durability is known"); - assert!(owner.state.held_handoff.is_some(), "the Ready handoff is held for this commit"); + assert!(owner.common.held_handoff.is_some(), "the Ready handoff is held for this commit"); // The final write's OWN completion fails to confirm durable: this is the AUTH-03 gate. let final_failed = PersistenceCompletion { req: final_req, epoch, arrival: 0, revision: 2, @@ -3453,24 +5459,24 @@ mod tests { let effects = step(&mut owner, SessionEvent::Persistence(final_failed)); assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Ready { .. })), "MUTATION M1 TARGET: skipping the gate would announce Ready right here"); - assert_eq!(owner.state.persistence_warning.map(|w| w.site), Some(PersistenceWarningSite::Final)); + assert_eq!(owner.common.persistence_warning.map(|w| w.site), Some(PersistenceWarningSite::Final)); assert_eq!(owner.publication().persistence_warning.map(|w| w.site), Some(PersistenceWarningSite::Final), "the warning must reach the UI-facing publication, not only internal state"); - assert!(!owner.state.commit_phase.proves_saved_login, + assert!(!owner.common.commit_phase.proves_saved_login, "no saved/final claim before the user acknowledges"); - let warning_key = owner.state.persistence_warning.unwrap().key; + let warning_key = owner.common.persistence_warning.unwrap().key; let wrong = PersistenceWarningKey { epoch: warning_key.epoch, req: warning_key.req + 1 }; assert!(!step(&mut owner, SessionEvent::Command(Command::AcknowledgePersistenceWarning { key: wrong })) .iter().any(|fx| matches!(fx, SessionFx::Ready { .. }))); - assert!(owner.state.persistence_warning.is_some(), "a mismatched key must not clear the warning"); + assert!(owner.common.persistence_warning.is_some(), "a mismatched key must not clear the warning"); let effects = step(&mut owner, SessionEvent::Command(Command::AcknowledgePersistenceWarning { key: warning_key })); assert_eq!(effects.iter().filter(|fx| matches!(fx, SessionFx::Ready { .. })).count(), 1, "acknowledging releases exactly the ONE held handoff, exactly once"); - assert!(owner.state.persistence_warning.is_none()); - assert!(owner.state.held_handoff.is_none()); + assert!(owner.common.persistence_warning.is_none()); + assert!(owner.common.held_handoff.is_none()); } #[test] @@ -3505,18 +5511,24 @@ mod tests { ..IncidentContext::internal(InternalClass::CommitRefused) }.with_persistence(&outcome); assert_eq!(expected.persistence, Some(class)); let warning = PersistenceWarning::from_outcome( - PersistenceWarningKey { epoch: owner.state.epoch, req: 1 }, PersistenceWarningSite::Final, &outcome); + PersistenceWarningKey { epoch: owner.common.epoch, req: 1 }, PersistenceWarningSite::Final, &outcome); // Replay/serialization must preserve the same local evidence as the live warning. - owner.state.persistence_warning = Some(serde_json::from_value(serde_json::to_value(warning).unwrap()).unwrap()); + owner.common.persistence_warning = Some(serde_json::from_value(serde_json::to_value(warning).unwrap()).unwrap()); owner.raise_incident(IncidentFlow::SignIn, expected); - let id = owner.state.incident.as_ref().unwrap().id; + let id = owner.common.incident.as_ref().unwrap().id; step(&mut owner, SessionEvent::Command(Command::ResolveIncident { id, permission: plx_telemetry::telemetry::consent::Permission::Declined, revision: 1 })); - assert!(owner.state.incident.as_ref().unwrap().context.is_none()); + assert!(owner.common.incident.as_ref().unwrap().context.is_none()); let effects = step(&mut owner, SessionEvent::Command(Command::ReportIncident { id })); let rebuilt = effects.iter().find_map(|effect| match effect { SessionFx::Incident { lane: IncidentLane::OneOff, report: IncidentReport::Retained(context), .. } => Some(*context), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("classified warning must reconstruct its report"); assert_eq!(rebuilt, expected, "class {class:?}"); } @@ -3529,8 +5541,8 @@ mod tests { #[test] fn fresh_owner_sign_in_records_the_account_token_as_its_plex_tv_credential() { let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { title: "Only user".into(), ..Default::default() }], @@ -3538,7 +5550,12 @@ mod tests { let effects = step(&mut owner, SessionEvent::Result(signed_in)); let plan = effects.iter().find_map(|fx| match fx { SessionFx::Commit { plan, .. } => Some(plan), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("SignedIn must begin its discovery commit"); let credentials = plan.credentials.as_ref().expect("fresh sign-in commits credentials"); assert!(!credentials.account_token.is_empty()); @@ -3552,8 +5569,8 @@ mod tests { use plx_platform::storage::wire::failure::{Detail, Stage}; for reconcile in [false, true] { let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { title: "Synthetic user".into(), ..Default::default() }], @@ -3569,7 +5586,7 @@ mod tests { let helper = warning.helper.expect("uncertain helper reply lost DB8 evidence"); assert_eq!(helper.helper, Some(Detail::new(Stage::Db8, Some(-3963)))); assert_eq!(helper.line(), "storage: helper · db8 (-3963)"); - assert_eq!(owner.state.incident.as_ref().unwrap().context.as_ref().unwrap().helper, Some(helper)); + assert_eq!(owner.common.incident.as_ref().unwrap().context.as_ref().unwrap().helper, Some(helper)); let context = plx_telemetry::telemetry::incident::IncidentContext::new( plx_telemetry::telemetry::incident::IncidentKind::SaveFailed, None).with_persistence(&outcome); let body = plx_telemetry::telemetry::incident::event_body(&"a".repeat(32), "", None, context, @@ -3577,15 +5594,21 @@ mod tests { assert_eq!(body["contexts"]["incident"]["persistence"], "commit_uncertain"); assert_eq!(body["contexts"]["incident"]["helper"]["helper"]["stage"], "db8"); assert_eq!(body["contexts"]["incident"]["helper"]["helper"]["code"], -3963); - let offer = owner.state.incident.clone().unwrap(); + let offer = owner.common.incident.clone().unwrap(); let retained = offer.context.unwrap(); step(&mut owner, SessionEvent::Command(Command::ResolveIncident { id: offer.id, permission: plx_telemetry::telemetry::consent::Permission::Declined, revision: 1 })); - assert!(owner.state.incident.as_ref().unwrap().context.is_none()); + assert!(owner.common.incident.as_ref().unwrap().context.is_none()); let effects = step(&mut owner, SessionEvent::Command(Command::ReportIncident { id: offer.id })); let rebuilt = effects.iter().find_map(|effect| match effect { SessionFx::Incident { lane: IncidentLane::OneOff, report: IncidentReport::Retained(context), .. } => Some(*context), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("one-off save report must use the visible warning evidence"); assert_eq!(rebuilt.persistence, retained.persistence); assert_eq!(rebuilt.helper, retained.helper); @@ -3600,8 +5623,8 @@ mod tests { for permission in [plx_telemetry::telemetry::consent::Permission::NotDetermined, plx_telemetry::telemetry::consent::Permission::Declined] { let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { title: "Synthetic user".into(), ..Default::default() }], @@ -3616,23 +5639,23 @@ mod tests { purpose: PersistencePurpose::Discovery, outcome: CompletionOutcome::Failed(Failure::Helper(failure, errnos)) }; step(&mut owner, SessionEvent::Persistence(PersistenceCompletion { req: req + 99, ..completion })); - assert!(owner.state.persistence_warning.is_none()); + assert!(owner.common.persistence_warning.is_none()); step(&mut owner, SessionEvent::Persistence(completion)); let warning = owner.publication().persistence_warning.unwrap(); assert_eq!(warning.helper, Some(failure)); - let offer = owner.state.incident.clone().unwrap(); + let offer = owner.common.incident.clone().unwrap(); assert_eq!(offer.context.unwrap().helper, Some(failure)); let effects = step(&mut owner, SessionEvent::Command(Command::ResolveIncident { id: offer.id, permission, revision: 1 })); assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Incident { .. }))); - assert!(matches!(owner.state.incident.as_ref().unwrap().state, + assert!(matches!(owner.common.incident.as_ref().unwrap().state, IncidentState::Offered { .. } | IncidentState::Dropped)); let effects = step(&mut owner, SessionEvent::Command(Command::ReportIncident { id: offer.id })); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Incident { lane: IncidentLane::OneOff, report: IncidentReport::Retained(context), .. } if context.helper == Some(failure) && context.candidate_errnos == errnos))); step(&mut owner, SessionEvent::Command(Command::AcknowledgePersistenceWarning { key: warning.key })); - assert!(owner.state.incident.is_none()); + assert!(owner.common.incident.is_none()); } } @@ -3645,8 +5668,8 @@ mod tests { CompletionOutcome, Failure, PersistenceCompletion, }; let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { title: "Synthetic user".into(), ..Default::default() }], @@ -3664,7 +5687,7 @@ mod tests { })); let discovery_warning = owner.publication().persistence_warning.unwrap(); assert_eq!(discovery_warning.site, PersistenceWarningSite::Discovery); - assert!(owner.state.held_handoff.is_none()); + assert!(owner.common.held_handoff.is_none()); step(&mut owner, SessionEvent::Command(Command::AcknowledgePersistenceWarning { key: discovery_warning.key, })); @@ -3673,7 +5696,13 @@ mod tests { let final_req = effects.iter().find_map(|fx| match fx { SessionFx::Commit { req, plan, .. } if plan.purpose == PersistencePurpose::Final => Some(*req), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("accepted Continue must reach the final commit"); // The authorization already answered its one Continue, so the Final commit's own reply // must publish immediately rather than hold a handoff behind a completion that may never @@ -3684,7 +5713,7 @@ mod tests { revision: 2, purpose: PersistencePurpose::Final, }, })); - assert!(owner.state.held_handoff.is_none(), + assert!(owner.common.held_handoff.is_none(), "an already-answered authorization must not hold a handoff on the Final commit"); let effects = step(&mut owner, SessionEvent::Persistence(PersistenceCompletion { req: final_req, epoch, arrival: 0, revision: 2, @@ -3719,8 +5748,8 @@ mod tests { CompletionOutcome, Failure, PersistenceCompletion, }; let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { title: "Synthetic user".into(), ..Default::default() }], @@ -3740,13 +5769,19 @@ mod tests { step(&mut owner, SessionEvent::Command(Command::AcknowledgePersistenceWarning { key: discovery_warning.key, })); - assert!(owner.state.persistence_warning_answered, + assert!(owner.common.persistence_warning_answered, "acknowledging must record that this authorization already answered"); let effects = step(&mut owner, SessionEvent::Command(Command::TakeReady)); let final_req = effects.iter().find_map(|fx| match fx { SessionFx::Commit { req, plan, .. } if plan.purpose == PersistencePurpose::Final => Some(*req), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("accepted Continue must reach the final commit"); // No `SessionEvent::Persistence` follows this reply at all — the completion is LOST. let effects = step(&mut owner, SessionEvent::Commit(CommitReply { @@ -3758,7 +5793,7 @@ mod tests { assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Ready { .. })), "an already-answered authorization must enter on the Final commit reply itself, \ not wait on a completion that may never arrive"); - assert!(owner.state.held_handoff.is_none(), + assert!(owner.common.held_handoff.is_none(), "nothing may still be held once Ready has already been announced"); } @@ -3770,26 +5805,26 @@ mod tests { fn a_discovery_failure_cannot_spend_or_authorize_the_final_fresh_save() { use plx_plex::plex::session::async_persistence::{CompletionOutcome, Failure, Operation, PersistOutcome, PersistenceCompletion}; - let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let mut owner = SessionMachine::from_init(reopened_after_authorization()); + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { - epoch, server: Default::default(), sources: Vec::new(), - users: vec![UserTile { title: "Only user".into(), ..Default::default() }], + epoch, server: local_server(), sources: Vec::new(), + users: vec![UserTile { uuid: "u-1".into(), title: "Only user".into(), ..Default::default() }], }, true); step(&mut owner, SessionEvent::Result(signed_in)); let discovery_reply = CommitReply { req, epoch, arrival: 1, admission: CommitAdmission::Admitted { revision: 1, purpose: PersistencePurpose::Discovery } }; step(&mut owner, SessionEvent::Commit(discovery_reply)); - assert!(owner.state.authorized_in_flow, "the discovery admission only PEEKED the authority"); + assert!(owner.state.projected_authorization(), "the discovery admission only PEEKED the authority"); let discovery_failed = PersistenceCompletion { req, epoch, arrival: 1, revision: 1, purpose: PersistencePurpose::Discovery, outcome: CompletionOutcome::Failed(Failure::Persistence(PersistOutcome::WriteFailed)) }; step(&mut owner, SessionEvent::Persistence(discovery_failed)); - assert_eq!(owner.state.persistence_warning.map(|w| w.site), Some(PersistenceWarningSite::Discovery)); - assert!(owner.state.authorized_in_flow, + assert_eq!(owner.common.persistence_warning.map(|w| w.site), Some(PersistenceWarningSite::Discovery)); + assert!(owner.state.projected_authorization(), "MUTATION M3 TARGET: a discovery failure must not have spent the fresh authority"); // Blocked: an unacknowledged warning must refuse TakeReady outright. @@ -3798,9 +5833,9 @@ mod tests { assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Commit { .. })), "MUTATION M4 TARGET: take_ready must not begin a commit over an unacknowledged warning"); - let warning_key = owner.state.persistence_warning.unwrap().key; + let warning_key = owner.common.persistence_warning.unwrap().key; step(&mut owner, SessionEvent::Command(Command::AcknowledgePersistenceWarning { key: warning_key })); - assert!(owner.state.persistence_warning.is_none()); + assert!(owner.common.persistence_warning.is_none()); // Acknowledging a DISCOVERY warning (no held handoff behind it) re-admits TakeReady, and // the authority the discovery failure did NOT spend is still there for the real final write. @@ -3811,9 +5846,11 @@ mod tests { assert_eq!(plan.purpose, PersistencePurpose::Final); assert_eq!(plan.authority, plx_plex::plex::session::SaveAuthority::FreshReauthentication, "the authority a discovery failure never spent is still available to the final write"); - assert!(!owner.state.authorized_in_flow, "this final commit consumes it now"); + assert!(!owner.state.projected_authorization(), "this final commit consumes it now"); - let final_req = owner.state.next_req; + let final_req = owner.common.next_req; + assert!(owner.state.owns_work(final_req, &owner.common.pending[&final_req])); + assert!(owner.commit_is_current(final_req, epoch, 0)); let admitted = CommitReply { req: final_req, epoch, arrival: 0, admission: CommitAdmission::Admitted { revision: 2, purpose: PersistencePurpose::Final } }; // This authorization already answered its one Continue (the discovery warning above), so @@ -3832,13 +5869,16 @@ mod tests { // A LATER, ordinary Ready-op commit (a ready profile re-applying itself) must never carry // fresh authority again — the flag was spent once and stays spent. - owner.state.apply_pending = true; - owner.state.phase = Phase::Ready; + step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::ChangeProfile))); + step(&mut owner, SessionEvent::Command(Command::SelectProfile { index: 0, pin: None })); + assert!(owner.needs_ready_commit()); + assert!(!owner.state.fresh_authority()); let effects = step(&mut owner, SessionEvent::Command(Command::TakeReady)); let Some(SessionFx::Commit { plan: routine_plan, .. }) = effects.iter().find(|fx| matches!(fx, SessionFx::Commit { .. })) else { panic!("the second Ready-op commit must still be reachable"); }; + assert!(owner.commit_is_current(owner.common.next_req, owner.common.epoch, 0)); assert_eq!(routine_plan.authority, plx_plex::plex::session::SaveAuthority::Routine, "the authority was spent once; a later Ready-op commit is Routine"); } @@ -3851,7 +5891,7 @@ mod tests { /// to require. BACK while a warning is showing must be inert except for the platform root /// press: `resumed: false`, warning/handoff/authority untouched, no `Commit`/`Ready` emitted. /// MUTATION for `back-bypasses-persistence-warning-ack`: delete the - /// `if self.state.persistence_warning.is_some() { .. }` early-return this test guards at the + /// `if self.common.persistence_warning.is_some() { .. }` early-return this test guards at the /// top of `back()` — this test must then fail (the warning clears and, in the Final-site half, /// a `Ready` is emitted with no acknowledgement). #[test] @@ -3864,8 +5904,8 @@ mod tests { // --- Discovery-site warning: the authority is only PEEKED so far (AUTH-04's guarantee), // and BACK must not spend it or clear the warning either. let mut owner = SessionMachine::from_init(reopened_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { uuid: "u-1".into(), protected: false, title: "Only user".into(), ..Default::default() }], @@ -3878,17 +5918,17 @@ mod tests { purpose: PersistencePurpose::Discovery, outcome: CompletionOutcome::Failed(Failure::Persistence(PersistOutcome::WriteFailed)) }; step(&mut owner, SessionEvent::Persistence(discovery_failed)); - assert!(owner.state.persistence_warning.is_some(), "rig: a Discovery warning is showing"); - assert!(owner.state.authorized_in_flow, "rig: the authority is still unspent"); - assert!(owner.state.committed_credentials.merge_into(&owner.state.persisted).can_go_local(), + assert!(owner.common.persistence_warning.is_some(), "rig: a Discovery warning is showing"); + assert!(owner.state.projected_authorization(), "rig: the authority is still unspent"); + assert!(owner.common.committed_credentials.merge_into(&owner.common.persisted).can_go_local(), "rig: the discovery write's own admission already published the signed-in credentials \ (`apply_commit_reply`'s `writes_credentials` branch runs on ADMISSION, not completion), \ so BACK's `resumable()` check really is exercised here rather than short-circuited"); let effects = step(&mut owner, SessionEvent::Command(Command::BackAtRoot { reply })); - assert!(owner.state.persistence_warning.is_some(), + assert!(owner.common.persistence_warning.is_some(), "MUTATION TARGET: BACK must not clear an unacknowledged warning"); - assert!(owner.state.authorized_in_flow, + assert!(owner.state.projected_authorization(), "BACK must not spend the fresh authority the final write still needs"); assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Ready { .. } | SessionFx::Commit { .. })), "BACK over a live warning must not begin or announce any save"); @@ -3898,8 +5938,8 @@ mod tests { // --- Final-site warning with a held handoff: acknowledging is the ONLY door that may // release it (`acknowledge_persistence_warning` / `release_held_handoff`); BACK must not. let mut owner = SessionMachine::from_init(reopened_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { uuid: "u-1".into(), protected: false, title: "Only user".into(), ..Default::default() }], @@ -3914,21 +5954,21 @@ mod tests { outcome: PersistOutcome::PersistedPlaintext, verified: true, protection: None }) }; step(&mut owner, SessionEvent::Persistence(discovery_durable)); step(&mut owner, SessionEvent::Command(Command::TakeReady)); - let final_req = owner.state.next_req; + let final_req = owner.common.next_req; let final_reply = CommitReply { req: final_req, epoch, arrival: 0, admission: CommitAdmission::Admitted { revision: 2, purpose: PersistencePurpose::Final } }; step(&mut owner, SessionEvent::Commit(final_reply)); - assert!(owner.state.held_handoff.is_some(), "rig: the Ready handoff is held for this commit"); + assert!(owner.common.held_handoff.is_some(), "rig: the Ready handoff is held for this commit"); let final_failed = PersistenceCompletion { req: final_req, epoch, arrival: 0, revision: 2, purpose: PersistencePurpose::Final, outcome: CompletionOutcome::Failed(Failure::Persistence(PersistOutcome::WriteFailed)) }; step(&mut owner, SessionEvent::Persistence(final_failed)); - assert!(owner.state.persistence_warning.is_some(), "rig: a Final warning is showing"); + assert!(owner.common.persistence_warning.is_some(), "rig: a Final warning is showing"); let effects = step(&mut owner, SessionEvent::Command(Command::BackAtRoot { reply })); - assert!(owner.state.persistence_warning.is_some(), + assert!(owner.common.persistence_warning.is_some(), "MUTATION TARGET: BACK must not clear an unacknowledged Final-site warning"); - assert!(owner.state.held_handoff.is_some(), + assert!(owner.common.held_handoff.is_some(), "MUTATION TARGET: BACK must not release a held handoff without acknowledgement"); assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Ready { .. } | SessionFx::Commit { .. })), "BACK over a held Final handoff must not announce Ready or begin a second save"); @@ -3942,7 +5982,7 @@ mod tests { /// acknowledged by anything the new attempt does — it must be cleared at the restart, not left /// to strand `take_ready` (`needs_ready_commit` refuses while any warning is live) once the /// retry itself succeeds. - /// MUTATION TARGET: drop the `self.state.persistence_warning = None;` this test guards in + /// MUTATION TARGET: drop the `self.common.persistence_warning = None;` this test guards in /// `restart_login`'s `if discovery { .. }` arm. #[test] fn a_discovery_retry_clears_a_stale_warning_from_the_attempt_it_replaces() { @@ -3950,8 +5990,8 @@ mod tests { CompletionOutcome, Failure, PersistOutcome, PersistenceCompletion, }; let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { title: "Only user".into(), ..Default::default() }], @@ -3964,7 +6004,7 @@ mod tests { purpose: PersistencePurpose::Discovery, outcome: CompletionOutcome::Failed(Failure::Persistence(PersistOutcome::WriteFailed)) }; step(&mut owner, SessionEvent::Persistence(discovery_failed)); - assert!(owner.state.persistence_warning.is_some(), "rig: a Discovery warning is showing"); + assert!(owner.common.persistence_warning.is_some(), "rig: a Discovery warning is showing"); // `retry_kind` needs a phase that reads as Discovery-retriable; the rig is already // `Phase::Discovering` from `discovering_after_authorization`. // `retry_kind` reads `(phase, authorized_in_flow)`; a single-user `SignedIn` already @@ -3975,13 +6015,15 @@ mod tests { // as the retry decision would see mid-flight for a *multi-worker* discovery (a resource // fetch retried while the earlier attempt's OWN persistence write is still unacknowledged) // rather than depending on today's one call sequence to happen to produce that phase. - owner.state.phase = Phase::Discovering; - assert_eq!(super::super::retry_kind(owner.state.phase, owner.state.authorized_in_flow), + let mut init = owner.snapshot_init(); + init.phase = Phase::Discovering; + owner = SessionMachine::from_init(init); + assert_eq!(super::super::retry_kind(owner.state.phase(), owner.state.projected_authorization()), super::super::RetryKind::Discovery, "rig: Retry must resolve to the DISCOVERY arm here"); step(&mut owner, SessionEvent::Command(Command::Retry)); - assert!(owner.state.persistence_warning.is_none(), + assert!(owner.common.persistence_warning.is_none(), "MUTATION TARGET: a discovery restart must clear the stale warning it is replacing"); - assert!(owner.state.held_handoff.is_none()); + assert!(owner.common.held_handoff.is_none()); } /// A fresh write admitted over a READABLE record whose write then definitely failed leaves @@ -3991,15 +6033,15 @@ mod tests { fn a_durable_superseded_write_advances_only_the_disk_fence() { use plx_plex::plex::session::async_persistence::{CompletionOutcome, Operation, PersistOutcome}; let mut owner = SessionMachine::from_init(captured_session()); - let before = owner.state.disk_identity.clone(); + let before = owner.common.disk_identity.clone(); let mut after = before.clone(); after.account_token = "superseded-durable-token".into(); - let trusted = Identity::of(&owner.state.persisted); + let trusted = Identity::of(&owner.common.persisted); let outcome = CompletionOutcome::Durable(Operation::Write { outcome: PersistOutcome::PersistedPlaintext, verified: true, protection: None }); assert!(owner.observe_disk_write(&before, &after, outcome)); - assert!(owner.state.disk_identity == after); - assert!(Identity::of(&owner.state.persisted) == trusted, "disk evidence is not login authority"); + assert!(owner.common.disk_identity == after); + assert!(Identity::of(&owner.common.persisted) == trusted, "disk evidence is not login authority"); assert!(!owner.observe_disk_write(&before, &after, outcome), "duplicate receipt is inert"); } @@ -4009,11 +6051,11 @@ mod tests { CompletionOutcome, Failure, PersistOutcome, PersistenceCompletion, }; let mut owner = SessionMachine::from_init(discovering_after_authorization()); - owner.state.disk_identity = Identity { client_id: "synthetic-client".into(), + owner.common.disk_identity = Identity { client_id: "synthetic-client".into(), account_token: "synthetic-revoked-account".into(), profile_uuid: "old".into() }; - let before = owner.state.disk_identity.clone(); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let before = owner.common.disk_identity.clone(); + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { title: "Only user".into(), ..Default::default() }], @@ -4021,13 +6063,13 @@ mod tests { step(&mut owner, SessionEvent::Result(signed_in)); step(&mut owner, SessionEvent::Commit(CommitReply { req, epoch, arrival: 1, admission: CommitAdmission::Admitted { revision: 1, purpose: PersistencePurpose::Discovery } })); - assert!(owner.state.disk_identity != before, "rig: admission re-bases on the new identity"); + assert!(owner.common.disk_identity != before, "rig: admission re-bases on the new identity"); step(&mut owner, SessionEvent::Persistence(PersistenceCompletion { req, epoch, arrival: 1, revision: 1, purpose: PersistencePurpose::Discovery, outcome: CompletionOutcome::Failed(Failure::Persistence(PersistOutcome::WriteFailed)) })); - assert!(owner.state.disk_identity == before, + assert!(owner.common.disk_identity == before, "MUTATION TARGET: a definite failure must restore the identity still on disk"); - assert!(owner.state.persistence_warning.is_some()); + assert!(owner.common.persistence_warning.is_some()); } /// Second half of `discovery-warning-not-cleared-on-retry-or-fresh-success`: a LATER fresh @@ -4043,13 +6085,13 @@ mod tests { CompletionOutcome, Operation, PersistOutcome, PersistenceCompletion, }; let mut owner = SessionMachine::from_init(discovering_after_authorization()); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; // Manufacture a showing warning directly (no restart), keeping `admitted_persistence` // fenced so the very next completion below is accepted as this same operation's verdict. - owner.state.persistence_warning = Some(PersistenceWarning { + owner.common.persistence_warning = Some(PersistenceWarning { key: PersistenceWarningKey { epoch, req }, site: PersistenceWarningSite::Discovery, helper: None, candidate_errnos: [None; 8], persistence: None }); - owner.state.admitted_persistence = Some(AdmittedPersistence { + owner.common.admitted_persistence = Some(AdmittedPersistence { req, epoch, arrival: 0, revision: 1, purpose: Some(PersistencePurpose::Discovery), fresh: true, site: PersistenceWarningSite::Discovery }); let durable = PersistenceCompletion { req, epoch, arrival: 0, revision: 1, @@ -4057,7 +6099,7 @@ mod tests { outcome: CompletionOutcome::Durable(Operation::Write { outcome: PersistOutcome::PersistedPlaintext, verified: true, protection: None }) }; step(&mut owner, SessionEvent::Persistence(durable)); - assert!(owner.state.persistence_warning.is_none(), + assert!(owner.common.persistence_warning.is_none(), "MUTATION TARGET: a later durable fresh write must supersede the earlier warning"); } @@ -4065,17 +6107,22 @@ mod tests { /// by the same code path `resume_stored`) issues a ROUTINE `activate_profile` commit, whose /// `apply_commit_reply` arm must not release a handoff still held behind a DIFFERENT, /// unacknowledged warning — that release belongs to `acknowledge_persistence_warning` alone. - /// MUTATION TARGET: drop the `self.state.persistence_warning.is_none()` guard this test pins + /// MUTATION TARGET: drop the `self.common.persistence_warning.is_none()` guard this test pins /// in `apply_commit_reply`'s non-fresh `activate_profile` arm (reverting to an unconditional /// `self.release_held_handoff(emit)`). #[test] fn start_switch_does_not_release_a_handoff_held_behind_an_unacknowledged_warning() { let mut owner = owner_with_held_final_warning(); - let held_before = owner.state.held_handoff; + let held_before = owner.common.held_handoff; let effects = step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::Boot))); let Some((switch_req, switch_epoch)) = effects.iter().find_map(|fx| match fx { SessionFx::Commit { req, epoch, .. } => Some((*req, *epoch)), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }) else { panic!("rig: StartSwitch(Boot) must begin its own (registry-only) commit"); }; @@ -4085,26 +6132,33 @@ mod tests { assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Ready { .. })), "MUTATION TARGET: no Ready may be announced for the unrelated held handoff before \ its own warning is acknowledged"); - assert_eq!(owner.state.held_handoff, held_before, + assert_eq!(owner.common.held_handoff, held_before, "the handoff held behind the still-showing warning must be untouched"); - assert!(owner.state.persistence_warning.is_some(), "the warning itself is still unanswered"); + assert!(owner.common.persistence_warning.is_some(), "the warning itself is still unanswered"); } #[test] fn disk_comparison_identity_is_not_a_worker_or_back_input() { let src = include_str!("owner.rs"); let production = src.split("\n#[cfg(test)]\nmod tests").next().unwrap(); - // Explicit function-body list, not a transitive call-graph claim. apply_read may update - // an empty comparison client-id from a resource reply; it never reads its token for work. - for name in ["start_reserved_login", "restart_login", "start_switch", "select_profile", - "back", "request_endpoint", "refresh_roster", "emit_work", "work_is_current"] { - let marker = format!("fn {name}("); - let start = production.find(&marker).unwrap(); - let rest = &production[start..]; - let end = rest.find("\n }").unwrap(); - // start_switch also emits a no-save registry commit. Its exact comparison-field - // projection is allowed; no other use in these worker/BACK constructors is. - let body = rest[..end].replace("expected_disk: self.state.disk_identity.clone(),", ""); + // The former helper bodies now live in these canonical event arms and entry plans. + // This is still an explicit source-scope check, not a transitive call-graph claim. + for (name, marker, boundary) in [ + ("start_reserved_login/emit_work", "fn login(state:", "enum AttemptEvent {"), + ("restart_login", "restarted = 'restart_login: {", "}; if !matches!(ev, SessionEvent::Erased"), + ("start_switch", "SessionEvent::Command(Command::StartSwitch(picker))", "SessionEvent::Command(Command::SelectProfile { index, pin })"), + ("select_profile", "SessionEvent::Command(Command::SelectProfile { index, pin })", "SessionEvent::Command(Command::BackAtRoot"), + ("back", "SessionEvent::Command(Command::BackAtRoot", "SessionEvent::Command(Command::SignOut)"), + ("request_endpoint", "SessionEvent::Command(Command::RequestEndpoint { sid })", "SessionEvent::Command(Command::AnswerPlaintext"), + ("refresh_roster", "SessionEvent::Command(Command::RefreshRoster)", "SessionEvent::Command(Command::RequestEndpoint { sid })"), + ("work_is_current", "pub fn work_is_current(", "\n }"), + ] { + let start = production.find(marker).unwrap_or_else(|| panic!("missing owner scope {name}")); + let rest = &production[start + marker.len()..]; + let end = rest.find(boundary).unwrap_or_else(|| panic!("missing end of owner scope {name}")); + // A no-save registry commit may carry the exact comparison projection, + // never use it to construct worker credentials or BACK authority. + let body = rest[..end].replace("expected_disk: self.common.disk_identity.clone(),", ""); assert!(!body.contains("disk_identity"), "comparison identity reached {name}"); } } @@ -4200,7 +6254,7 @@ mod tests { let a = owner.allocate(SessionOp::ServerRoster, None).unwrap(); let b = owner.allocate(SessionOp::ServerRoster, None).unwrap(); for req in [a, b] { - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); } let make = |req, arrival| SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, @@ -4245,7 +6299,7 @@ mod tests { progress: super::super::LoginProgress, terminal: bool) -> SessionEnvelope { SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, - key: owner.state.pending[&req].key, + key: owner.common.pending[&req].key, admission: AdmissionId(req), arrival, terminal, lifecycle: None, outcome: SessionArrival::Data(Arc::new(super::super::observation::Observation::Login(progress))), @@ -4257,8 +6311,8 @@ mod tests { let mut owner = SessionMachine::from_init(captured_session()); let mut effects = Vec::new(); assert!(owner.restart_login(true, &mut |fx| effects.push(fx))); - let epoch = owner.state.epoch; - let req = owner.state.next_req; + let epoch = owner.common.epoch; + let req = owner.common.next_req; let code = qr_event(&owner, req, 1, super::super::LoginProgress::CodeReady { epoch, code: "synthetic-code-a".into(), qr_png: vec![1, 2, 3], }, false); @@ -4282,7 +6336,7 @@ mod tests { fn request_exhaustion_cannot_cancel_the_live_qr_operation() { let mut owner = SessionMachine::from_init(captured_session()); assert!(owner.restart_login(true, &mut |_| {})); - owner.state.next_req = u32::MAX; + owner.common.next_req = u32::MAX; let before = owner.publication(); let mut canon = Canon::new(); owner.write(&mut canon); @@ -4292,27 +6346,27 @@ mod tests { owner.write(&mut canon); assert_eq!(hash, canon.finish()); assert!(Arc::ptr_eq(&before, &owner.publication())); - assert_eq!(owner.state.pending.len(), 1); + assert_eq!(owner.common.pending.len(), 1); } #[test] fn qr_allocator_exhaustion_fails_and_retires_the_admitted_request() { let mut owner = SessionMachine::from_init(captured_session()); assert!(owner.restart_login(true, &mut |_| {})); - let req = owner.state.next_req; - let epoch = owner.state.epoch; - owner.state.next_qr = u64::MAX; + let req = owner.common.next_req; + let epoch = owner.common.epoch; + owner.common.next_qr = u64::MAX; let code = qr_event(&owner, req, 1, super::super::LoginProgress::CodeReady { epoch, code: "synthetic-code".into(), qr_png: vec![1, 2, 3], }, false); let mut effects = Vec::new(); let handled = owner.apply_qr_observation(&code, &mut |fx| effects.push(fx)); - assert_eq!(owner.state.phase, Phase::Error, "exhaustion must settle the spinner as failure"); + assert_eq!(owner.state.phase(), Phase::Error, "exhaustion must settle the spinner as failure"); assert!(handled); - assert_eq!(owner.state.next_qr, u64::MAX); - assert_eq!(owner.state.qr_gen, 0, "no generation is reused or published"); - assert!(owner.state.pending.is_empty()); - assert!(!owner.state.signin_active); + assert_eq!(owner.common.next_qr, u64::MAX); + assert_eq!(owner.state.qr().generation, 0, "no generation is reused or published"); + assert!(owner.common.pending.is_empty()); + assert!(!owner.common.signin_notice.owed()); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Cancel { requests, .. } if requests == &[req]))); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Retire { req: retired } if *retired == req))); @@ -4337,13 +6391,13 @@ mod tests { fn authorization_advances_same_request_identity_and_retry_preserves_account_link() { let mut owner = SessionMachine::from_init(captured_session()); assert!(owner.restart_login(true, &mut |_| {})); - let epoch = owner.state.epoch; - let req = owner.state.next_req; + let epoch = owner.common.epoch; + let req = owner.common.next_req; let authorized = qr_event(&owner, req, 1, super::super::LoginProgress::Authorized { epoch, token: "synthetic-token".into(), }, false); assert!(owner.apply_qr_observation(&authorized, &mut |_| {})); - assert!(owner.state.pending[&req].expected.matches(&owner.state.persisted)); + assert!(owner.common.pending[&req].expected.matches(&owner.common.persisted)); let failed = qr_event(&owner, req, 2, super::super::LoginProgress::Failed { epoch, message: "synthetic discovery failure".into(), incident: crate::auth::synthetic_incident(), plaintext: None, account: None }, true); @@ -4353,7 +6407,7 @@ mod tests { assert!(Arc::ptr_eq(&retained, &owner.publication())); let mut effects = Vec::new(); assert!(owner.restart_login(false, &mut |fx| effects.push(fx))); - assert_eq!(owner.state.phase, Phase::Discovering); + assert_eq!(owner.state.phase(), Phase::Discovering); assert!(matches!(effects.last(), Some(SessionFx::Work { input: SessionWork::Rediscover { account_token, .. }, .. }) if account_token == "synthetic-token")); @@ -4384,13 +6438,13 @@ mod tests { let mut owner = SessionMachine::from_init(init); assert!(owner.restart_login(true, &mut |_| {})); - let epoch = owner.state.epoch; - let req = owner.state.next_req; + let epoch = owner.common.epoch; + let req = owner.common.next_req; let authorized = qr_event(&owner, req, 1, super::super::LoginProgress::Authorized { epoch, token: "synthetic-account-b".into(), }, false); assert!(owner.apply_qr_observation(&authorized, &mut |_| {})); - assert!(owner.state.pending[&req].expected.matches(&owner.state.persisted)); + assert!(owner.common.pending[&req].expected.matches(&owner.common.persisted)); let signed_in = qr_event(&owner, req, 2, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users: vec![UserTile { id: 1, uuid: "demo-user".into(), title: "Demo".into(), admin: true, @@ -4398,7 +6452,13 @@ mod tests { }, true); let effects = step(&mut owner, SessionEvent::Result(signed_in)); let saved = effects.iter().find_map(|fx| match fx { - SessionFx::Commit { plan, .. } => plan.credentials.clone(), _ => None, + SessionFx::Commit { plan, .. } => plan.credentials.clone(), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the sign-in saves its credentials"); assert_ne!(saved.user.uuid, "previous-owner", "the discovery save must not keep the previous profile"); assert_ne!(saved.user.title, "Previous Name"); @@ -4411,7 +6471,7 @@ mod tests { outcome: CompletionOutcome::Durable(Operation::Write { outcome: PersistOutcome::PersistedPlaintext, verified: true, protection: None }) })); step(&mut owner, SessionEvent::Command(Command::TakeReady)); - let final_req = owner.state.next_req; + let final_req = owner.common.next_req; step(&mut owner, SessionEvent::Commit(CommitReply { req: final_req, epoch, arrival: 0, admission: CommitAdmission::Admitted { revision: 2, purpose: PersistencePurpose::Final } })); let effects = step(&mut owner, SessionEvent::Persistence(PersistenceCompletion { req: final_req, epoch, @@ -4419,12 +6479,18 @@ mod tests { outcome: CompletionOutcome::Durable(Operation::Write { outcome: PersistOutcome::PersistedPlaintext, verified: true, protection: None }) })); let published = effects.iter().find_map(|fx| match fx { - SessionFx::PublishProfile(p) => Some(p.profile.clone()), _ => None, + SessionFx::PublishProfile(p) => Some(p.profile.clone()), + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the sign-in publishes who is watching"); - let account = owner.state.persisted.account(published.as_ref()); + let account = owner.common.persisted.account(published.as_ref()); assert_eq!(account.name.as_deref(), Some("Demo"), "the chip names the account that signed in"); assert!(published.as_ref().is_none_or(|u| u.uuid != "previous-owner" && u.thumb.is_empty())); - assert!(owner.state.persisted.profiles.is_empty()); + assert!(owner.common.persisted.profiles.is_empty()); } /// **The same person signing in again keeps the offline profile cache.** A fresh QR sign-in @@ -4447,19 +6513,26 @@ mod tests { init.committed_credentials = CredentialPatch::of(&init.persisted); let mut owner = SessionMachine::from_init(init); assert!(owner.restart_login(true, &mut |_| {})); - let epoch = owner.state.epoch; - let req = owner.state.next_req; + let epoch = owner.common.epoch; + let req = owner.common.next_req; let authorized = qr_event(&owner, req, 1, super::super::LoginProgress::Authorized { epoch, token: "synthetic-token-after".into(), }, false); assert!(owner.apply_qr_observation(&authorized, &mut |_| {})); - assert!(owner.state.persisted.profiles.is_empty(), "identity is unknown at Authorized"); + assert!(owner.common.persisted.profiles.is_empty(), "identity is unknown at Authorized"); let signed_in = qr_event(&owner, req, 2, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users, }, true); let effects = step(&mut owner, SessionEvent::Result(signed_in)); effects.iter().find_map(|fx| match fx { - SessionFx::Commit { plan, .. } => plan.credentials.clone(), _ => None, + SessionFx::Commit { plan, .. } => plan.credentials.clone(), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("the sign-in saves its credentials") }; let tile = |id: i64| UserTile { id, uuid: format!("owner-{id}"), title: "Synthetic".into(), @@ -4484,8 +6557,8 @@ mod tests { for allow in [true, false] { let mut owner = SessionMachine::from_init(captured_session()); assert!(owner.restart_login(true, &mut |_| {})); - let epoch = owner.state.epoch; - let req = owner.state.next_req; + let epoch = owner.common.epoch; + let req = owner.common.next_req; let authorized = qr_event(&owner, req, 1, super::super::LoginProgress::Authorized { epoch, token: "synthetic-token".into(), }, false); @@ -4509,13 +6582,13 @@ mod tests { assert!(matches!(effects.first(), Some(SessionFx::PlaintextAnswer { machine_id, choice, account }) if machine_id == "lan-machine" && *choice == want && *account == key), "allow={allow}"); if allow { - assert_eq!(owner.state.phase, Phase::Discovering); + assert_eq!(owner.state.phase(), Phase::Discovering); assert!(owner.read().0.plaintext.is_none(), "the question is answered"); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Work { input: SessionWork::Rediscover { account_token, .. }, .. } if account_token == "synthetic-token"))); } else { - assert_eq!(owner.state.phase, Phase::Error); + assert_eq!(owner.state.phase(), Phase::Error); let shown = owner.read().0; assert_eq!(shown.plaintext.as_ref().map(|v| v.choice), Some(PlaintextChoice::Declined)); assert!(shown.error.contains("Select Try again to be asked again."), "{}", shown.error); @@ -4528,7 +6601,7 @@ mod tests { let work = retried.iter().position(|fx| matches!(fx, SessionFx::Work { .. })); assert!(withdrawn.is_some() && withdrawn < work, "the declined answer is withdrawn before the retry: {:?}", retried.iter().map(|fx| std::mem::discriminant(fx)).collect::>()); - assert_eq!(owner.state.phase, Phase::Discovering); + assert_eq!(owner.state.phase(), Phase::Discovering); } } } @@ -4577,8 +6650,8 @@ mod tests { assert_eq!(b.allocate(SessionOp::HomeRoster, None), Some(1)); assert_eq!(a.read().0.phase, Phase::Idle); assert_eq!(b.read().0.phase, Phase::Profiles); - assert_eq!(b.state.pending[&1].key.epoch, u32::MAX as u64 + 7); - a.state.next_req = u32::MAX; + assert_eq!(b.common.pending[&1].key.epoch, u32::MAX as u64 + 7); + a.common.next_req = u32::MAX; assert!(a.allocate(SessionOp::Login, None).is_none()); assert_eq!(b.allocate(SessionOp::ServerRoster, None), Some(2)); } @@ -4604,17 +6677,44 @@ mod tests { assert!(!probe.contains("synthetic")); } + fn admit_profile_selection(owner: &mut SessionMachine) -> u32 { + let effects = step(owner, SessionEvent::Command(Command::SelectProfile { index: 0, pin: None })); + let req = owner.common.next_req; + let epoch = owner.common.epoch; + assert!(matches!(effects.last(), Some(SessionFx::Capture { + req: captured, epoch: captured_epoch, request: SessionReadRequest::ProfilePolicy, + }) if *captured == req && *captured_epoch == epoch)); + assert!(owner.state.owns_work(req, &owner.common.pending[&req])); + assert!(owner.read_is_current(req, epoch, SessionReadRequest::ProfilePolicy)); + let effects = step(owner, SessionEvent::Read(SessionReadReply { + addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, + epoch, value: SessionReadValue::ProfilePolicy { recently_unreachable: false }, + })); + assert!(matches!(effects.as_slice(), [SessionFx::Work { + req: launched, input: SessionWork::ProfileSwitch { .. }, .. + }] if *launched == req)); + let key = owner.common.pending[&req].key; + assert!(owner.work_is_current(req, key, AdmissionId(req))); + step(owner, SessionEvent::Admission(AdmissionReply { + addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, + key, correlation: AdmissionId(req), accepted: true, + })); + assert!(owner.common.pending[&req].admission == AdmissionState::Accepted(AdmissionId(req))); + assert!(owner.state.owns_work(req, &owner.common.pending[&req])); + req + } + #[test] fn queued_running_terminal_is_revalidated_after_ready_ack_seats_new_profile() { let mut init = captured_session(); - init.phase = Phase::Switching; + init.phase = Phase::Profiles; + init.users = vec![UserTile { uuid: "new-profile".into(), ..Default::default() }]; init.persisted.account_token = "synthetic-account".into(); init.persisted.user.uuid = "old-profile".into(); let mut owner = SessionMachine::from_init(init); - let req = owner.allocate(SessionOp::ProfileSwitch, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + let req = admit_profile_selection(&mut owner); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let make = |arrival, terminal, outcome| SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, key: SessionWorkKey { epoch, op: SessionOp::ProfileSwitch }, @@ -4635,26 +6735,33 @@ mod tests { let effects = step(&mut owner, SessionEvent::Result(ready.clone())); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Commit { .. }))); assert!(step(&mut owner, SessionEvent::Result(terminal.clone())).is_empty()); - assert_eq!(owner.state.inbox.len(), 1); + assert_eq!(owner.common.inbox.len(), 1); let acked = step(&mut owner, SessionEvent::Commit(CommitReply { req, epoch, arrival: 1, admission: CommitAdmission::Admitted { revision: 1, purpose: PersistencePurpose::Final } })); - assert_eq!(owner.state.phase, Phase::Ready); - assert_eq!(owner.state.persisted.user.uuid, "new-profile"); - assert!(owner.state.pending[&req].phase == StreamPhase::ProfileSeated); + assert_eq!(owner.state.phase(), Phase::Ready); + assert_eq!(owner.common.persisted.user.uuid, "new-profile"); + assert!(owner.common.pending[&req].phase == StreamPhase::ProfileSeated); + assert!(owner.state.owns_work(req, &owner.common.pending[&req])); assert!(!owner.accepts(&terminal), "same body is invalid at the changed FIFO head"); let seated = owner.publication(); let effects = step(&mut owner, SessionEvent::Pump); - assert!(owner.state.pending.is_empty()); - assert!(owner.state.pending_commit.is_none()); - assert_eq!(owner.state.phase, Phase::Ready); - assert_eq!(owner.state.persisted.user.uuid, "new-profile"); - assert!(!owner.state.pin_denied); - assert!(owner.state.error.is_empty()); + assert!(owner.common.pending.is_empty()); + assert!(owner.common.pending_commit.is_none()); + assert_eq!(owner.state.phase(), Phase::Ready); + assert_eq!(owner.common.persisted.user.uuid, "new-profile"); + assert!(!owner.state.picker_data().pin_denied); + assert!(owner.state.picker_data().error.is_empty()); assert!(Arc::ptr_eq(&seated, &owner.publication())); assert!(effects.iter().all(|fx| matches!(fx, SessionFx::Retire { .. } | SessionFx::Acknowledge(_))), "rejected terminal must not emit another commit/profile publication/Ready"); let receipts: Vec<_> = acked.iter().chain(&effects).filter_map(|fx| match fx { - SessionFx::Acknowledge(receipts) => Some(receipts.as_slice()), _ => None, + SessionFx::Acknowledge(receipts) => Some(receipts.as_slice()), + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).flatten().copied().collect(); assert!(receipts == [Receipt::of(&ready), Receipt::of(&terminal)]); } @@ -4664,23 +6771,71 @@ mod tests { for (op, seated) in [(SessionOp::Login, false), (SessionOp::ProfileSwitch, false), (SessionOp::ProfileSwitch, true)] { let mut init = captured_session(); - init.phase = if op == SessionOp::Login { Phase::Waiting } - else if seated { Phase::Ready } else { Phase::Switching }; + init.persisted.account_token = "synthetic-account".into(); + init.persisted.user.uuid = "old-profile".into(); + if op == SessionOp::ProfileSwitch { + init.phase = Phase::Profiles; + init.users = vec![UserTile { uuid: "new-profile".into(), ..Default::default() }]; + } let mut owner = SessionMachine::from_init(init); - let req = owner.allocate(op, None).unwrap(); - let pending = owner.state.pending.get_mut(&req).unwrap(); - pending.admission = AdmissionState::Accepted(AdmissionId(req)); - if seated { pending.phase = StreamPhase::ProfileSeated; } + let req = if op == SessionOp::Login { + step(&mut owner, SessionEvent::Command(Command::StartLogin)); + let req = owner.common.next_req; + let key = owner.common.pending[&req].key; + assert!(owner.work_is_current(req, key, AdmissionId(req))); + step(&mut owner, SessionEvent::Admission(AdmissionReply { + addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, + key, correlation: AdmissionId(req), accepted: true, + })); + let code = qr_event(&owner, req, 1, super::super::LoginProgress::CodeReady { + epoch: owner.common.epoch, code: "ABCD".into(), qr_png: vec![1], + }, false); + assert!(owner.accepts(&code)); + step(&mut owner, SessionEvent::Result(code)); + assert_eq!(owner.state.phase(), Phase::Waiting); + req + } else { admit_profile_selection(&mut owner) }; + if seated { + let epoch = owner.common.epoch; + let ready = SessionEnvelope { + addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, + key: owner.common.pending[&req].key, admission: AdmissionId(req), + arrival: 1, terminal: false, lifecycle: None, + outcome: SessionArrival::Data(Arc::new(super::super::observation::Observation::ProfileSwitch( + super::super::ProfileSwitchProgress { + epoch, expected: super::super::SessionIdentity::of(&owner.common.persisted), + outcome: super::super::ProfileSwitchOutcomeProgress::Ready { + delta: super::super::ProfileDelta { + user: UserRef { uuid: "new-profile".into(), token: "new-token".into(), ..Default::default() }, + server: local_server(), sources: Vec::new(), cache: None, + }, probes: Vec::new(), + }, + }))), + }; + assert!(owner.accepts(&ready)); + let effects = step(&mut owner, SessionEvent::Result(ready)); + assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Commit { .. }))); + assert!(owner.commit_is_current(req, epoch, 1)); + step(&mut owner, SessionEvent::Commit(CommitReply { + req, epoch, arrival: 1, admission: CommitAdmission::RegistryOnly, + })); + assert_eq!(owner.state.phase(), Phase::Ready); + assert!(owner.common.pending[&req].phase == StreamPhase::ProfileSeated); + } + assert!(owner.state.owns_work(req, &owner.common.pending[&req])); + assert!(owner.common.pending[&req].admission == AdmissionState::Accepted(AdmissionId(req))); // Wrong inner epoch; the outer header still identifies this admitted terminal. - let record = qr_event(&owner, req, 1, super::super::LoginProgress::Failed { - epoch: owner.state.epoch + 1, message: "rejected payload text".into(), incident: crate::auth::synthetic_incident(), plaintext: None, account: None + let record = qr_event(&owner, req, 2, super::super::LoginProgress::Failed { + epoch: owner.common.epoch + 1, message: "rejected payload text".into(), incident: crate::auth::synthetic_incident(), plaintext: None, account: None }, true); + assert!(owner.accepts_header(&record)); + assert!(!owner.accepts(&record)); step(&mut owner, SessionEvent::Result(record)); - assert!(owner.state.pending.is_empty()); - assert!(owner.state.pending_commit.is_none()); - assert_eq!(owner.state.phase, if op == SessionOp::Login { Phase::Error } + assert!(owner.common.pending.is_empty()); + assert!(owner.common.pending_commit.is_none()); + assert_eq!(owner.state.phase(), if op == SessionOp::Login { Phase::Error } else if seated { Phase::Ready } else { Phase::Profiles }); - assert_ne!(owner.state.error, "rejected payload text"); + assert_ne!(owner.state.picker_data().error, "rejected payload text"); } } @@ -4689,17 +6844,17 @@ mod tests { for captured in [false, true] { let mut owner = SessionMachine::from_init(captured_session()); let req = owner.allocate(SessionOp::Login, None).unwrap(); - let pending = owner.state.pending.get_mut(&req).unwrap(); + let pending = owner.common.pending.get_mut(&req).unwrap(); pending.admission = AdmissionState::Accepted(AdmissionId(req)); if captured { pending.capture = Some(CaptureIntent::Login); } else { pending.last_arrival = Some(2); } let record = qr_event(&owner, req, 1, super::super::LoginProgress::Failed { - epoch: owner.state.epoch + 1, message: "rejected payload text".into(), incident: crate::auth::synthetic_incident(), plaintext: None, account: None + epoch: owner.common.epoch + 1, message: "rejected payload text".into(), incident: crate::auth::synthetic_incident(), plaintext: None, account: None }, true); let before = owner.snapshot_init().hash(); step(&mut owner, SessionEvent::Result(record)); assert_eq!(owner.snapshot_init().hash(), before); - assert!(owner.state.pending.contains_key(&req)); + assert!(owner.common.pending.contains_key(&req)); } } @@ -4707,10 +6862,19 @@ mod tests { fn envelope_validation_keeps_full_epoch_and_exact_destination() { use plx_machine::machine::RequestId; let mut init = captured_session(); - init.epoch = 0x1_0000_0001; + init.epoch = 0x1_0000_0000; let mut owner = SessionMachine::from_init(init); - let req = owner.allocate(SessionOp::Login, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + step(&mut owner, SessionEvent::Command(Command::StartLogin)); + let req = owner.common.next_req; + let key = owner.common.pending[&req].key; + assert_eq!(owner.common.epoch, 0x1_0000_0001); + assert!(owner.work_is_current(req, key, AdmissionId(req))); + step(&mut owner, SessionEvent::Admission(AdmissionReply { + addr: Addr { to: MachineId::Session, req: RequestId(req) }, + key, correlation: AdmissionId(req), accepted: true, + })); + assert!(owner.state.owns_work(req, &owner.common.pending[&req])); + assert!(owner.common.pending[&req].admission == AdmissionState::Accepted(AdmissionId(req))); let mut envelope = SessionEnvelope { addr: Addr { to: MachineId::Session, req: RequestId(req) }, key: SessionWorkKey { epoch: 1, op: SessionOp::Login }, @@ -4742,9 +6906,9 @@ mod tests { let mut owner = SessionMachine::from_init(captured_session()); let req = owner.allocate(SessionOp::Endpoint(sid.raw()), Some(lifecycle.logical(sid.raw()))).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let probe = super::super::settled_probe_for_test( "insecure-mach", plx_plex::plex::probe::Outcome::InsecureOnly, Some(plx_plex::plex::probe::Location::Local), Some("10.0.0.9".into())); let envelope = SessionEnvelope { @@ -4761,7 +6925,12 @@ mod tests { let effects = step(&mut owner, SessionEvent::Result(envelope)); let plan = effects.iter().find_map(|fx| match fx { SessionFx::Commit { plan, .. } => Some(plan), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("a None-fresh endpoint reply must still commit its probe"); assert_eq!(plan.registry.len(), 1, "nothing to INSTALL — the probe is the whole plan"); assert!( @@ -4818,9 +6987,9 @@ mod tests { let mut owner = SessionMachine::from_init(SessionInit::captured(persisted)); let req = owner.allocate(SessionOp::Endpoint(sid.raw()), Some(lifecycle.logical(sid.raw()))).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let probe = super::super::settled_probe_for_test( "ours", plx_plex::plex::probe::Outcome::Reachable, Some(plx_plex::plex::probe::Location::Local), Some("10.0.0.9".into())); let envelope = SessionEnvelope { @@ -4837,7 +7006,12 @@ mod tests { let effects = step(&mut owner, SessionEvent::Result(envelope)); let plan = effects.iter().find_map(|fx| match fx { SessionFx::Commit { plan, .. } => Some(plan), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("an endpoint reply that repairs the profile record must still commit"); assert!( plan.credentials.is_some(), @@ -4855,9 +7029,9 @@ mod tests { let _g = plx_base::testlock::serial(); let mut owner = SessionMachine::from_init(captured_session()); let req = owner.allocate(SessionOp::ServerRoster, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let settled = vec![ super::super::settled_probe_for_test("a", plx_plex::plex::probe::Outcome::InsecureOnly, Some(plx_plex::plex::probe::Location::Local), Some("10.0.0.1".into())), @@ -4874,7 +7048,12 @@ mod tests { let effects = step(&mut owner, SessionEvent::Result(envelope)); let plan = effects.iter().find_map(|fx| match fx { SessionFx::Commit { plan, .. } => Some(plan), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("NoReachable with a non-empty settled list must still commit"); assert_eq!(plan.registry.len(), settled.len(), "one RegistryPlan::Probe per settled probe, no roster Install"); assert!(plan.registry.iter().all(|p| matches!(p, RegistryPlan::Probe(_))), @@ -4893,10 +7072,10 @@ mod tests { fn land_account_roster_refresh(owner: &mut SessionMachine) -> (CommitPlan, CommitPlan) { let req = owner.allocate(SessionOp::ServerRoster, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let fresh = account_refresh_source(); let activate = SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, @@ -4916,7 +7095,13 @@ mod tests { }; let activate_effects = step(owner, SessionEvent::Result(activate)); let activate_plan = activate_effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan.clone()), _ => None, + SessionFx::Commit { plan, .. } => Some(plan.clone()), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the progress observation reaches the commit boundary"); step(owner, SessionEvent::Commit(CommitReply { req, epoch, arrival: 1, admission: CommitAdmission::RegistryOnly, @@ -4945,7 +7130,13 @@ mod tests { }; let reconcile_effects = step(owner, SessionEvent::Result(reconcile)); let reconcile_plan = reconcile_effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan.clone()), _ => None, + SessionFx::Commit { plan, .. } => Some(plan.clone()), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the terminal observation reaches the commit boundary"); step(owner, SessionEvent::Commit(CommitReply { req, epoch, arrival: 2, admission: CommitAdmission::RegistryOnly, @@ -4954,7 +7145,7 @@ mod tests { } fn assert_non_admin_roster_refresh_is_probe_only(mut owner: SessionMachine) { - let before = CredentialPatch::of(&owner.state.persisted); + let before = CredentialPatch::of(&owner.common.persisted); let (activate, reconcile) = land_account_roster_refresh(&mut owner); assert!(activate.credentials.is_none()); assert!(activate.registry.is_empty(), @@ -4965,13 +7156,13 @@ mod tests { assert!(matches!(&reconcile.registry[0], RegistryPlan::Probe(probe) if probe.machine_id == "account-machine" && probe.outcome == plx_plex::plex::probe::Outcome::Reachable)); - assert_eq!(owner.state.persisted.server.machine_id, before.server.machine_id); - assert_eq!(owner.state.persisted.server.token, before.server.token); - assert_eq!(owner.state.persisted.user.token, before.user.token); - assert_eq!(owner.state.persisted.sources[0].token, before.sources[0].token); - assert_eq!(owner.state.persisted.profiles[0].server.token, before.profiles[0].server.token); - assert_eq!(owner.state.persisted.profiles[0].user.token, before.profiles[0].user.token); - assert_eq!(owner.state.persisted.profiles[0].sources[0].token, + assert_eq!(owner.common.persisted.server.machine_id, before.server.machine_id); + assert_eq!(owner.common.persisted.server.token, before.server.token); + assert_eq!(owner.common.persisted.user.token, before.user.token); + assert_eq!(owner.common.persisted.sources[0].token, before.sources[0].token); + assert_eq!(owner.common.persisted.profiles[0].server.token, before.profiles[0].server.token); + assert_eq!(owner.common.persisted.profiles[0].user.token, before.profiles[0].user.token); + assert_eq!(owner.common.persisted.profiles[0].sources[0].token, before.profiles[0].sources[0].token); } @@ -5024,13 +7215,12 @@ mod tests { extensions: Default::default(), }); let mut init = SessionInit::captured(persisted); - init.phase = Phase::Switching; + init.phase = Phase::Profiles; init.users = vec![UserTile { uuid: "u-kid".into(), title: "Kid".into(), ..Default::default() }]; let mut owner = SessionMachine::from_init(init); - let req = owner.allocate(SessionOp::ProfileSwitch, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + let req = admit_profile_selection(&mut owner); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let mut tokenless_secondary = secondary.clone(); tokenless_secondary.token.clear(); let ready = SessionEnvelope { @@ -5059,11 +7249,16 @@ mod tests { SessionFx::Commit { req, epoch, arrival, .. } => Some(CommitReply { req: *req, epoch: *epoch, arrival: *arrival, admission: CommitAdmission::RegistryOnly, }), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the profile switch must commit"); step(&mut owner, SessionEvent::Commit(reply)); - let next_identity = super::super::SessionIdentity::of(&owner.state.persisted); + let next_identity = super::super::SessionIdentity::of(&owner.common.persisted); let resources = vec![ plx_plex::plex::account::Resource { name: primary.name.clone(), client_identifier: primary.machine_id.clone(), provides: "server".into(), @@ -5085,15 +7280,30 @@ mod tests { SessionFx::Commit { req, epoch, arrival, .. } => Some(CommitReply { req: *req, epoch: *epoch, arrival: *arrival, admission: CommitAdmission::RegistryOnly, }), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the unavailable-secondary roster must commit"); step(&mut owner, SessionEvent::Commit(reply)); - step(&mut owner, SessionEvent::Command(Command::SelectProfile { index: 0, pin: None })); + step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::ChangeProfile))); + let effects = step(&mut owner, SessionEvent::Command(Command::SelectProfile { index: 0, pin: None })); + assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Capture { .. } | SessionFx::Work { .. }))); + assert!(owner.needs_ready_commit()); let effects = step(&mut owner, SessionEvent::Command(Command::TakeReady)); let final_plan = effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan), _ => None, + SessionFx::Commit { plan, .. } => Some(plan), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the same-user shortcut must pass through take_ready"); + assert!(owner.commit_is_current(owner.common.next_req, owner.common.epoch, 0)); let patch = final_plan.credentials.as_ref().expect("take_ready saves the live session"); assert_eq!(patch.sources.iter().find(|source| source.machine_id == "b").unwrap().token, "kid-b-token", "B remains live even though its identity probe was unavailable"); @@ -5147,9 +7357,9 @@ mod tests { title: "Owner".into(), admin: true, ..Default::default() }]; let mut owner = roster_refresh_fixture("u-owner", users); let req = owner.allocate(SessionOp::ServerRoster, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let admitted = plx_plex::plex::session::SourceRef { machine_id: "preferred-machine".into(), name: "Preferred server".into(), owned: true, token: "preferred-token".into(), address: "10.0.0.9".into(), @@ -5184,13 +7394,21 @@ mod tests { }; let effects = step(&mut owner, SessionEvent::Result(envelope)); let plan = effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan), _ => None, + SessionFx::Commit { plan, .. } => Some(plan), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the admitted endpoint changes the roster"); let patch = plan.credentials.as_ref().unwrap(); assert_eq!(patch.server.machine_id, admitted.machine_id); let install = plan.registry.iter().find_map(|plan| match plan { RegistryPlan::Install { sources, primary, commit } => Some((sources, primary, commit)), - _ => None, + RegistryPlan::DevInstall { .. } | RegistryPlan::Primary { .. } + | RegistryPlan::Activate { .. } | RegistryPlan::Endpoint { .. } | RegistryPlan::Probe(_) + | RegistryPlan::Revoke => None, }).expect("refresh installs an admitted roster"); assert_eq!(install.1.and_then(|index| install.0.get(index)) .map(|source| source.machine_id.as_str()), Some("preferred-machine")); @@ -5211,13 +7429,13 @@ mod tests { address: "10.0.0.7".into(), port: 32400, origin_url: "https://10-0-0-7.example.plex.direct:32400".into(), tier: Some(plx_plex::plex::probe::Location::Remote), ..Default::default() }; - owner.state.persisted.sources.push(secondary.clone()); - owner.state.persisted.refresh_profile_record(); + owner.common.persisted.sources.push(secondary.clone()); + owner.common.persisted.refresh_profile_record(); let req = owner.allocate(SessionOp::ServerRoster, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let admitted = plx_plex::plex::session::SourceRef { machine_id: "profile-machine".into(), name: "Profile server".into(), owned: true, token: "fresh-primary-token".into(), address: "10.0.0.18".into(), port: 32400, @@ -5246,11 +7464,19 @@ mod tests { }; let effects = step(&mut owner, SessionEvent::Result(envelope)); let plan = effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan), _ => None, + SessionFx::Commit { plan, .. } => Some(plan), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the primary address change commits the refreshed roster"); let install = plan.registry.iter().find_map(|plan| match plan { RegistryPlan::Install { sources, primary, commit } => Some((sources, primary, commit)), - _ => None, + RegistryPlan::DevInstall { .. } | RegistryPlan::Primary { .. } + | RegistryPlan::Activate { .. } | RegistryPlan::Endpoint { .. } | RegistryPlan::Probe(_) + | RegistryPlan::Revoke => None, }).expect("the address change replaces the live registry"); assert!(install.0.iter().any(|source| source.machine_id == "secondary" && source.token == "fresh-secondary-token"), @@ -5278,7 +7504,13 @@ mod tests { let effects = step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::ChangeProfile))); let (req, key) = effects.iter().find_map(|fx| match fx { SessionFx::Work { req, key, input: SessionWork::HomeRoster { .. }, .. } => Some((*req, *key)), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("Change profile fetches the Home roster"); settle_picker_commit(&mut owner, &effects); let envelope = roster_envelope(&mut owner, req, key, users); @@ -5300,13 +7532,19 @@ mod tests { fn empty_roster_change_profile(users: Option>) -> (SessionMachine, Vec) { let mut owner = SessionMachine::from_init(local_session()); - assert!(owner.state.persisted.home_users.is_empty(), "rig: nothing cached to show"); + assert!(owner.common.persisted.home_users.is_empty(), "rig: nothing cached to show"); let effects = step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::ChangeProfile))); let (req, key) = effects.iter().find_map(|fx| match fx { SessionFx::Work { req, key, input: SessionWork::HomeRoster { .. }, .. } => Some((*req, *key)), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("Change profile fetches the Home roster"); - assert_eq!(owner.state.phase, Phase::Profiles); + assert_eq!(owner.state.phase(), Phase::Profiles); settle_picker_commit(&mut owner, &effects); let envelope = roster_envelope(&mut owner, req, key, users); let effects = step(&mut owner, SessionEvent::Result(envelope)); @@ -5318,17 +7556,22 @@ mod tests { fn settle_picker_commit(owner: &mut SessionMachine, effects: &[SessionFx]) { let (req, epoch) = effects.iter().find_map(|fx| match fx { SessionFx::Commit { req, epoch, .. } => Some((*req, *epoch)), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("rig: the picker commits its registry plan"); step(owner, SessionEvent::Commit(CommitReply { req, epoch, arrival: 0, admission: CommitAdmission::RegistryOnly })); - assert!(owner.state.pending_commit.is_none(), "rig: nothing is left in flight"); + assert!(owner.common.pending_commit.is_none(), "rig: nothing is left in flight"); } fn roster_envelope(owner: &mut SessionMachine, req: u32, key: SessionWorkKey, users: Option>) -> SessionEnvelope { - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let expected = super::super::SessionIdentity::of(&owner.common.persisted); SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, key, admission: AdmissionId(req), arrival: 1, terminal: true, lifecycle: None, @@ -5345,18 +7588,18 @@ mod tests { (Some(Vec::new()), roster_refused()), ] { let (mut owner, _) = empty_roster_change_profile(users); - assert_eq!(owner.state.phase, Phase::Profiles, + assert_eq!(owner.state.phase(), Phase::Profiles, "the failure is read out on the picker's own route, not as a sign-in Error"); - assert!(owner.state.users.is_empty()); - assert_eq!(owner.state.error, reason); - assert!(owner.state.persisted.home_users.is_empty(), "no roster is invented or committed"); + assert!(owner.state.picker_data().users.is_empty()); + assert_eq!(owner.state.picker_data().error, reason); + assert!(owner.common.persisted.home_users.is_empty(), "no roster is invented or committed"); let reply = ReplyTo { instance: 0, correlation: 7 }; let effects = step(&mut owner, SessionEvent::Command(Command::BackAtRoot { reply })); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::BackReply { resumed: true, .. })), "BACK from a picker that never offered a profile resumes the session behind it"); - assert_eq!(owner.state.phase, Phase::Ready); - assert!(owner.state.apply_pending, "the resume goes through the ordinary Ready handoff"); - assert!(owner.state.error.is_empty()); + assert_eq!(owner.state.phase(), Phase::Ready); + assert!(owner.state.handoff_pending(), "the resume goes through the ordinary Ready handoff"); + assert!(owner.state.picker_data().error.is_empty()); } } @@ -5372,16 +7615,22 @@ mod tests { let effects = step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::ChangeProfile))); let (req, key) = effects.iter().find_map(|fx| match fx { SessionFx::Work { req, key, input: SessionWork::HomeRoster { .. }, .. } => Some((*req, *key)), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).unwrap(); settle_picker_commit(&mut owner, &effects); let envelope = roster_envelope(&mut owner, req, key, Some(Vec::new())); let effects = step(&mut owner, SessionEvent::Result(envelope)); assert!(!effects.iter().any(|fx| matches!(fx, SessionFx::Commit { .. })), "an answer with nobody in it is not committed over the cached roster"); - assert_eq!(owner.state.users.len(), 1); - assert_eq!(owner.state.persisted.home_users.len(), 1); - assert!(owner.state.error.is_empty()); + assert_eq!(owner.state.picker_data().users.len(), 1); + assert_eq!(owner.common.persisted.home_users.len(), 1); + assert!(owner.state.picker_data().error.is_empty()); let reply = ReplyTo { instance: 0, correlation: 7 }; let effects = step(&mut owner, SessionEvent::Command(Command::BackAtRoot { reply })); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::BackReply { resumed: false, .. })), @@ -5401,18 +7650,23 @@ mod tests { let effects = step(&mut owner, SessionEvent::Command(Command::ActivateDevBootstrap)); let (req, epoch) = effects.iter().find_map(|fx| match fx { SessionFx::Commit { req, epoch, .. } => Some((*req, *epoch)), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("rig: the dev boundary commits"); step(&mut owner, SessionEvent::Commit(CommitReply { req, epoch, arrival: 0, admission: CommitAdmission::RegistryOnly })); - assert_eq!(owner.state.phase, Phase::Ready, "rig: the dev session is up"); + assert_eq!(owner.state.phase(), Phase::Ready, "rig: the dev session is up"); let before = owner.publication(); step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::ChangeProfile))); - assert_eq!(owner.state.phase, Phase::Profiles, + assert_eq!(owner.state.phase(), Phase::Profiles, "the picker the app just routed to must have a state behind it"); - assert_eq!(owner.state.error, roster_refused()); - assert!(owner.state.users.is_empty()); + assert_eq!(owner.state.picker_data().error, roster_refused()); + assert!(owner.state.picker_data().users.is_empty()); // TV, PR #212: this read-out exists BEFORE the Profiles screen mounts, so only the step // that entered it can announce it — and it must, once. let entered = owner.publication(); @@ -5426,8 +7680,8 @@ mod tests { assert!(effects.iter().any(|fx| matches!(fx, SessionFx::BackReply { resumed: true, .. }))); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Ready { install: ReadyInstall::AlreadyInstalled, .. })), "BACK hands the dev session back"); - assert_eq!(owner.state.phase, Phase::Ready); - assert!(owner.state.error.is_empty()); + assert_eq!(owner.state.phase(), Phase::Ready); + assert!(owner.state.picker_data().error.is_empty()); assert!(!before.switch_refused, "nothing has been refused before anybody asked"); assert!(owner.publication().switch_refused, "the refusal outlives the read-out, so the menu stops offering it"); @@ -5448,10 +7702,10 @@ mod tests { "a stored, dialable session is behind the picker: BACK resumes it"); let reply = ReplyTo { instance: 0, correlation: 7 }; step(&mut owner, SessionEvent::Command(Command::BackAtRoot { reply })); - assert_eq!(owner.state.phase, Phase::Ready, "rig: BACK resumed"); + assert_eq!(owner.state.phase(), Phase::Ready, "rig: BACK resumed"); assert_eq!(owner.publication().switch_refused, refused, "the same identity is still refused once the picker has gone"); - owner.state.persisted.user.uuid = "another-profile".into(); + owner.common.persisted.user.uuid = "another-profile".into(); owner.replace_publication(); assert!(!owner.publication().switch_refused, "a different identity has not been refused anything"); @@ -5467,11 +7721,11 @@ mod tests { let _g = plx_base::testlock::serial(); let (mut owner, _) = empty_roster_change_profile(Some(Vec::new())); assert!(owner.publication().switch_refused, "rig: the verdict is recorded"); - let account = owner.state.persisted.clone(); + let account = owner.common.persisted.clone(); step(&mut owner, SessionEvent::Command(Command::SignOut)); - assert!(owner.state.switch_refused_for.is_none(), "sign-out ends the identity and its verdict"); + assert!(owner.common.switch_refused_for.is_none(), "sign-out ends the identity and its verdict"); // The same account, signed back in: nothing refused it in this sign-in. - owner.state.persisted = account; + owner.common.persisted = account; owner.replace_publication(); assert!(!owner.publication().switch_refused); } @@ -5490,16 +7744,16 @@ mod tests { init.switch_refused_for = Some(Identity::of(&init.persisted)); let mut owner = SessionMachine::from_init(init); assert!(owner.publication().switch_refused, "rig: the verdict is recorded"); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let signed_in = qr_event(&owner, req, 1, super::super::LoginProgress::SignedIn { epoch, server: local_server(), sources: Vec::new(), users }, true); step(&mut owner, SessionEvent::Result(signed_in)); step(&mut owner, SessionEvent::Commit(CommitReply { req, epoch, arrival: 1, admission: CommitAdmission::Admitted { revision: 1, purpose: PersistencePurpose::Discovery } })); - assert!(owner.state.pending_commit.is_none(), "rig: the sign-in committed"); + assert!(owner.common.pending_commit.is_none(), "rig: the sign-in committed"); assert_eq!(owner.publication().switch_refused, !cleared); - assert_eq!(owner.state.switch_refused_for.is_none(), cleared); + assert_eq!(owner.common.switch_refused_for.is_none(), cleared); } } @@ -5515,12 +7769,18 @@ mod tests { let effects = step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::ChangeProfile))); let (req, key) = effects.iter().find_map(|fx| match fx { SessionFx::Work { req, key, input: SessionWork::HomeRoster { .. }, .. } => Some((*req, *key)), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).unwrap(); settle_picker_commit(&mut owner, &effects); let envelope = roster_envelope(&mut owner, req, key, Some(Vec::new())); step(&mut owner, SessionEvent::Result(envelope)); - assert_eq!(owner.state.persisted.home_users.len(), 1, "the cache survives the refusal"); + assert_eq!(owner.common.persisted.home_users.len(), 1, "the cache survives the refusal"); assert!(!owner.publication().switch_refused); } @@ -5535,7 +7795,13 @@ mod tests { let effects = step(&mut owner, SessionEvent::Command(Command::StartSwitch(Picker::ChangeProfile))); let (req, key) = effects.iter().find_map(|fx| match fx { SessionFx::Work { req, key, input: SessionWork::HomeRoster { .. }, .. } => Some((*req, *key)), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("rig: an account token is enough to ask for a roster"); if effects.iter().any(|fx| matches!(fx, SessionFx::Commit { .. })) { settle_picker_commit(&mut owner, &effects); diff --git a/rust-modules/session/src/auth/owner/attempt.rs b/rust-modules/session/src/auth/owner/attempt.rs new file mode 100644 index 0000000000..6f90fdaf77 --- /dev/null +++ b/rust-modules/session/src/auth/owner/attempt.rs @@ -0,0 +1,1831 @@ +//! Owned auth states. Only SessionMachine::transition installs a runtime Attempt. +//! Arbitrary legacy flags live solely in read-only history, never in active work authority. +use super::*; + +pub(super) struct Common { + pub(super) authority: BootstrapAuthority, + pub(super) disk_identity: Identity, + pub(super) persisted: PersistedSession, + pub(super) committed_credentials: CredentialPatch, + pub(super) signin_notice: SignInNotice, + pub(super) next_qr: u64, + pub(super) epoch: u64, + pub(super) next_req: u32, + pub(super) pending: BTreeMap, + pub(super) pending_commit: Option, + pub(super) persistence_purpose: Option, + pub(super) commit_phase: CommitPhase, + pub(super) admitted_persistence: Option, + pub(super) persistence_warning: Option, + pub(super) held_handoff: Option, + pub(super) persistence_warning_answered: bool, + pub(super) unconfirmed_fresh_prior: Option, + pub(super) inbox: VecDeque, + pub(super) pump_pending: bool, + pub(super) active_profile: Option, + pub(super) profile_scope: ProfileScope, + pub(super) delete_leftovers: usize, + pub(super) incident: Option, + pub(super) incidents_seen: Vec, + pub(super) next_incident: u32, + pub(super) switch_refused_for: Option, +} + + +pub(super) struct QrHistory { pub(super) code: String, pub(super) png: Vec, pub(super) generation: u64, pub(super) replaced: bool, pub(super) trouble: bool } +pub(super) struct PickerPresentation { pub(super) picker: Picker, pub(super) users: Vec, pub(super) error: String, pub(super) pin_denied: bool } +// Read-only retention: never confers work or selection authority. +struct HistoricalPresentation { qr: QrHistory, picker: PickerPresentation } +struct ImportedIntent(bool); +struct HandoffIntent(bool); + +pub(super) struct IdleData { boot: BootStage, signin: SignInHistory, history: HistoricalPresentation, residue: ImportedIntent } +pub(super) struct CreatingData { login: LoginStage, signin: SignInHistory, qr: QrHistory, picker_history: PickerPresentation, residue: ImportedIntent } +pub(super) struct WaitingData { login: LoginStage, signin: SignInHistory, qr: QrHistory, picker_history: PickerPresentation, residue: ImportedIntent } +pub(super) struct DiscoveringData { discovery: DiscoveryStage, signin: SignInHistory, history: HistoricalPresentation, residue: ImportedIntent } +pub(super) struct ProfilesData { setup: PickerStage, choice: Authorization, signin: SignInHistory, qr_history: QrHistory, picker: PickerPresentation, residue: ImportedIntent } +pub(super) struct SwitchingData { selection: SelectionStage, signin: SignInHistory, qr_history: QrHistory, picker: PickerPresentation, residue: ImportedIntent } +pub(super) struct ReadyData { handoff: Handoff, roster: Option, signin: SignInHistory, history: HistoricalPresentation, intent: HandoffIntent } +pub(super) struct ErrorData { retry: RetryAuthority, signin: SignInHistory, qr_history: QrHistory, picker: PickerPresentation, residue: ImportedIntent } +pub(super) struct DeletedData { signin: SignInHistory, history: HistoricalPresentation, residue: ImportedIntent } +pub(super) struct ErasingData { signin: SignInHistory, history: HistoricalPresentation, residue: ImportedIntent, prior_phase: Phase, pending_erase: (u64, bool) } + + +// A cross-phase coordinator debt, not authorization to run a sign-in or save credentials. +#[derive(Clone, Copy)] +pub(super) enum SignInNotice { Settled, Owed } +impl SignInNotice { pub(super) fn owed(self) -> bool { matches!(self, Self::Owed) } } +#[derive(Clone, Copy)] +enum HistoricalAuthorization { Stored, Fresh } +struct SignInHistory { + authorization: HistoricalAuthorization, + retry: Option, + plaintext: Option, + account: Option, +} +impl SignInHistory { + fn authorized(&self) -> bool { matches!(self.authorization, HistoricalAuthorization::Fresh) } +} + +#[derive(Clone, Copy)] +enum Authorization { Stored, Fresh } +impl Authorization { fn is_fresh(self) -> bool { matches!(self, Self::Fresh) } } +#[derive(Clone, Copy)] +enum LoginStage { Dormant, Preparing { boundary_req: u32, login_req: u32 }, Authorizing { req: u32 } } +impl LoginStage { + fn owns(self, req: u32) -> bool { matches!(self, Self::Authorizing { req: owned } if owned == req) } + fn promote(self, req: u32) -> Self { if matches!(self, Self::Preparing { login_req, .. } if login_req == req) { Self::Authorizing { req } } else { self } } +} +#[derive(Clone, Copy)] +enum DiscoveryStage { Dormant(Authorization), Running { req: u32, authorization: Authorization } } +impl DiscoveryStage { + fn authorization(self) -> Authorization { match self { Self::Dormant(a) | Self::Running { authorization: a, .. } => a } } + fn owns(self, req: u32) -> bool { matches!(self, Self::Running { req: owned, .. } if owned == req) } + fn cancelled(self) -> Self { Self::Dormant(self.authorization()) } + fn routine(self) -> Self { match self { Self::Dormant(_) => Self::Dormant(Authorization::Stored), Self::Running { req, .. } => Self::Running { req, authorization: Authorization::Stored } } } +} +#[derive(Clone, Copy)] +enum SelectionStage { Dormant(Authorization), Selecting { req: u32, authorization: Authorization } } +impl SelectionStage { + fn authorization(self) -> Authorization { match self { Self::Dormant(a) | Self::Selecting { authorization: a, .. } => a } } + fn owns(self, req: u32) -> bool { matches!(self, Self::Selecting { req: owned, .. } if owned == req) } + fn cancelled(self) -> Self { Self::Dormant(self.authorization()) } + fn routine(self) -> Self { match self { Self::Dormant(_) => Self::Dormant(Authorization::Stored), Self::Selecting { req, .. } => Self::Selecting { req, authorization: Authorization::Stored } } } +} +#[derive(Clone, Copy)] +enum BootStage { Dormant, ActivatingDev { req: u32 }, RestoringStored { req: u32 } } +impl BootStage { + fn owns(self, req: u32) -> bool { matches!(self, Self::ActivatingDev { req: owned } | Self::RestoringStored { req: owned } if owned == req) } +} +#[derive(Clone, Copy)] +enum PickerStage { Idle, Installing { req: u32 } } +impl PickerStage { fn owns(self, req: u32) -> bool { matches!(self, Self::Installing { req: owned } if owned == req) } } +#[derive(Clone, Copy)] +enum FinalCommitStage { Unrequested, Committing { req: u32 } } +#[derive(Clone, Copy)] +enum Handoff { Available, Pending { authorization: Authorization, commit: FinalCommitStage } } +impl Handoff { + fn authorization(self) -> Authorization { match self { Self::Available => Authorization::Stored, Self::Pending { authorization, .. } => authorization } } + fn routine(self) -> Self { match self { Self::Available => Self::Available, Self::Pending { commit, .. } => Self::Pending { authorization: Authorization::Stored, commit } } } + fn cancelled(self) -> Self { match self { Self::Available => Self::Available, Self::Pending { authorization, .. } => Self::Pending { authorization, commit: FinalCommitStage::Unrequested } } } + fn owns(self, req: u32) -> bool { matches!(self, Self::Pending { commit: FinalCommitStage::Committing { req: owned }, .. } if owned == req) } +} +#[derive(Clone, Copy)] +struct ProfileStream { req: u32 } +#[derive(Clone, Copy)] +enum RetryAuthority { Login, Discovery(Authorization) } +impl RetryAuthority { + fn of(a: Authorization) -> Self { if a.is_fresh() { Self::Discovery(a) } else { Self::Login } } + fn authorization(self) -> Authorization { match self { Self::Login => Authorization::Stored, Self::Discovery(a) => a } } +} + +pub(super) enum Attempt { + Idle(IdleData), + Creating(CreatingData), + Waiting(WaitingData), + Discovering(DiscoveringData), + Profiles(ProfilesData), + Switching(SwitchingData), + Ready(ReadyData), + Error(ErrorData), + Deleted(DeletedData), + Erasing(ErasingData), +} + +pub(super) struct Partition { pub(super) common: Common, pub(super) attempt: Attempt } + + + +struct PresentationRef<'a> { phase: Phase, qr: &'a QrHistory, picker: &'a PickerPresentation, apply_pending: bool, pending_erase: Option<(u64, bool)> } +impl Partition { + pub(super) fn from_init(init: SessionInit) -> Self { + let SessionInit { authority, disk_identity, phase, picker, persisted, committed_credentials, pin_code, qr_png, users, error, pin_denied, authorized_in_flow, signin_active, apply_pending, code_replaced, qr_gen, next_qr, epoch, next_req, pending, mut pending_commit, persistence_purpose, commit_phase, admitted_persistence, persistence_warning, held_handoff, persistence_warning_answered, unconfirmed_fresh_prior, pending_erase, inbox, pump_pending, active_profile, profile_scope, delete_leftovers, incident, incidents_seen, next_incident, link_trouble, discovery_retry, plaintext, signin_account, switch_refused_for } = init; + if let Some(commit) = pending_commit.as_mut() { commit.delta.destination = CommitDestination::from_init(&commit.delta); } + let authorization = if authorized_in_flow && !persisted.account_token.is_empty() { Authorization::Fresh } else { Authorization::Stored }; + let owned = |op: SessionOp| pending.iter().rev().find_map(|(&req, p)| (p.key.op == op && p.key.epoch == epoch && p.expected.matches(&persisted)).then_some(req)); + let login = owned(SessionOp::Login).map_or(LoginStage::Dormant, |req| LoginStage::Authorizing { req }); + let discovery = owned(SessionOp::Login).or_else(|| owned(SessionOp::Rediscover)).map_or(DiscoveryStage::Dormant(authorization), |req| DiscoveryStage::Running { req, authorization }); + let selection = owned(SessionOp::ProfileSwitch).map_or(SelectionStage::Dormant(authorization), |req| SelectionStage::Selecting { req, authorization }); + let roster = owned(SessionOp::ProfileSwitch).filter(|req| pending[req].phase == StreamPhase::ProfileSeated).map(|req| ProfileStream { req }); + let commit_req = |op: SessionOp| pending_commit.as_ref().and_then(|c| pending.get(&c.req).filter(|p| p.key.op == op && p.key.epoch == epoch && c.epoch == epoch && p.expected.matches(&persisted)).map(|_| c.req)); + let boot = if matches!(&authority, BootstrapAuthority::DevPms { .. }) && pending_commit.as_ref().is_some_and(|c| matches!(&c.delta.dev, Some(DevCommitDelta::Activated))) { + commit_req(SessionOp::DevBoundary).map_or(BootStage::Dormant, |req| BootStage::ActivatingDev { req }) + } else if matches!(&authority, BootstrapAuthority::Account { .. }) && persisted.can_go_local() && pending_commit.as_ref().is_some_and(|c| matches!(c.delta.destination, CommitDestination::StoredReady)) { + commit_req(SessionOp::Ready).map_or(BootStage::Dormant, |req| BootStage::RestoringStored { req }) + } else { BootStage::Dormant }; + let setup = if matches!(&authority, BootstrapAuthority::Account { .. }) && !persisted.account_token.is_empty() { + commit_req(SessionOp::Picker).map_or(PickerStage::Idle, |req| PickerStage::Installing { req }) + } else { PickerStage::Idle }; + let commit = if pending_commit.as_ref().is_some_and(|c| matches!(c.delta.destination, CommitDestination::ReadyCommitted)) { + commit_req(SessionOp::Ready).map_or(FinalCommitStage::Unrequested, |req| FinalCommitStage::Committing { req }) + } else { FinalCommitStage::Unrequested }; + let handoff = if apply_pending && persisted.can_go_local() { Handoff::Pending { authorization, commit } } else { Handoff::Available }; + let creating = pending_commit.as_ref().and_then(|c| if let Some(DevCommitDelta::StartAccount { login_req }) = c.delta.dev { Some(LoginStage::Preparing { boundary_req: c.req, login_req }) } else { None }).unwrap_or(login); + let signin_notice = if signin_active { SignInNotice::Owed } else { SignInNotice::Settled }; + let common = Common { authority, disk_identity, persisted, committed_credentials, signin_notice, next_qr, epoch, next_req, pending, pending_commit, persistence_purpose, commit_phase, admitted_persistence, persistence_warning, held_handoff, persistence_warning_answered, unconfirmed_fresh_prior, inbox, pump_pending, active_profile, profile_scope, delete_leftovers, incident, incidents_seen, next_incident, switch_refused_for }; + let signin = SignInHistory { authorization: if authorized_in_flow { HistoricalAuthorization::Fresh } else { HistoricalAuthorization::Stored }, retry: discovery_retry, plaintext, account: signin_account }; + let qr = QrHistory { code: pin_code, png: qr_png, generation: qr_gen, replaced: code_replaced, trouble: link_trouble }; + let picker = PickerPresentation { picker, users, error, pin_denied }; + let attempt = if let Some(pending_erase) = pending_erase { + Attempt::Erasing(ErasingData { signin, history: HistoricalPresentation { qr, picker }, residue: ImportedIntent(apply_pending), prior_phase: phase, pending_erase }) + } else { match phase { + Phase::Idle => Attempt::Idle(IdleData { boot, signin, history: HistoricalPresentation { qr, picker }, residue: ImportedIntent(apply_pending) }), + Phase::Creating => Attempt::Creating(CreatingData { login: creating, signin, qr, picker_history: picker, residue: ImportedIntent(apply_pending) }), + Phase::Waiting => Attempt::Waiting(WaitingData { login, signin, qr, picker_history: picker, residue: ImportedIntent(apply_pending) }), + Phase::Discovering => Attempt::Discovering(DiscoveringData { discovery, signin, history: HistoricalPresentation { qr, picker }, residue: ImportedIntent(apply_pending) }), + Phase::Profiles => Attempt::Profiles(ProfilesData { setup, choice: authorization, signin, qr_history: qr, picker, residue: ImportedIntent(apply_pending) }), + Phase::Switching => Attempt::Switching(SwitchingData { selection, signin, qr_history: qr, picker, residue: ImportedIntent(apply_pending) }), + Phase::Ready => Attempt::Ready(ReadyData { handoff, roster, signin, history: HistoricalPresentation { qr, picker }, intent: HandoffIntent(apply_pending) }), + Phase::Error => Attempt::Error(ErrorData { retry: RetryAuthority::of(authorization), signin, qr_history: qr, picker, residue: ImportedIntent(apply_pending) }), + Phase::Deleted => Attempt::Deleted(DeletedData { signin, history: HistoricalPresentation { qr, picker }, residue: ImportedIntent(apply_pending) }), + }}; + Self { common, attempt } + } + +} +#[derive(Clone, Copy)] +pub(super) struct PartitionView<'a> { pub(super) common: &'a Common, pub(super) attempt: &'a Attempt } +#[cfg(test)] +impl Partition { + pub(super) fn phase(&self) -> Phase { self.attempt.phase() } + pub(super) fn qr(&self) -> &QrHistory { self.attempt.qr() } + pub(super) fn picker_data(&self) -> &PickerPresentation { self.attempt.picker_data() } + pub(super) fn pending_erase(&self) -> Option<(u64, bool)> { self.attempt.pending_erase() } + pub(super) fn view(&self) -> PartitionView<'_> { PartitionView { common: &self.common, attempt: &self.attempt } } + pub(super) fn snapshot_init(&self) -> SessionInit { self.view().snapshot_init() } +} +impl PartitionView<'_> { + pub(super) fn roster_dead_end(&self) -> bool { self.attempt.phase() == Phase::Profiles && self.attempt.picker_data().users.is_empty() && !self.common.pending.values().any(|pending| pending.key.op == SessionOp::HomeRoster) } + pub(super) fn dead_end_resumes(&self) -> bool { matches!(self.common.authority, BootstrapAuthority::DevPms { .. }) || self.common.committed_credentials.merge_into(&self.common.persisted).can_go_local() } + pub(super) fn switch_refused(&self) -> bool { self.common.switch_refused_for.as_ref().is_some_and(|id| id.matches(&self.common.persisted)) } + pub(super) fn readout_account(&self) -> Option<&str> { self.attempt.readout_account() } + pub(super) fn roster_readout_up(&self) -> bool { self.attempt.roster_readout_up() } + /// Allocate an owned DTO only at the explicit snapshot boundary. + pub(super) fn snapshot_init(&self) -> SessionInit { + let p = self.attempt.presentation(); + SessionInit { + authority: self.common.authority.clone(), + disk_identity: self.common.disk_identity.clone(), + phase: p.phase, + picker: p.picker.picker, + persisted: self.common.persisted.clone(), + committed_credentials: self.common.committed_credentials.clone(), + pin_code: p.qr.code.clone(), + qr_png: p.qr.png.clone(), + users: p.picker.users.clone(), + error: p.picker.error.clone(), + pin_denied: p.picker.pin_denied, + authorized_in_flow: self.attempt.projected_authorization(), + signin_active: self.common.signin_notice.owed(), + apply_pending: p.apply_pending, + code_replaced: p.qr.replaced, + qr_gen: p.qr.generation, + next_qr: self.common.next_qr.clone(), + epoch: self.common.epoch.clone(), + next_req: self.common.next_req.clone(), + pending: self.common.pending.clone(), + pending_commit: self.common.pending_commit.clone(), + persistence_purpose: self.common.persistence_purpose.clone(), + commit_phase: self.common.commit_phase.clone(), + admitted_persistence: self.common.admitted_persistence.clone(), + persistence_warning: self.common.persistence_warning.clone(), + held_handoff: self.common.held_handoff.clone(), + persistence_warning_answered: self.common.persistence_warning_answered.clone(), + unconfirmed_fresh_prior: self.common.unconfirmed_fresh_prior.clone(), + pending_erase: p.pending_erase, + inbox: self.common.inbox.clone(), + pump_pending: self.common.pump_pending.clone(), + active_profile: self.common.active_profile.clone(), + profile_scope: self.common.profile_scope.clone(), + delete_leftovers: self.common.delete_leftovers.clone(), + incident: self.common.incident.clone(), + incidents_seen: self.common.incidents_seen.clone(), + next_incident: self.common.next_incident.clone(), + link_trouble: p.qr.trouble, + discovery_retry: self.attempt.discovery_retry(), + plaintext: self.attempt.plaintext().cloned(), + signin_account: self.attempt.signin_account().map(str::to_owned), + switch_refused_for: self.common.switch_refused_for.clone(), + } + } +} + +impl Attempt { + pub(super) fn placeholder() -> Self { + Self::Idle(IdleData { boot: BootStage::Dormant, history: HistoricalPresentation { + qr: QrHistory { code: String::new(), png: Vec::new(), generation: 0, replaced: false, trouble: false }, + picker: PickerPresentation { picker: Picker::Boot, users: Vec::new(), error: String::new(), pin_denied: false }, + }, residue: ImportedIntent(false), signin: SignInHistory { authorization: HistoricalAuthorization::Stored, retry: None, plaintext: None, account: None } }) + } + fn retained_signin(&self) -> &SignInHistory { + match self { + Self::Idle(d) => &d.signin, + Self::Creating(d) => &d.signin, + Self::Waiting(d) => &d.signin, + Self::Discovering(d) => &d.signin, + Self::Profiles(d) => &d.signin, + Self::Switching(d) => &d.signin, + Self::Ready(d) => &d.signin, + Self::Error(d) => &d.signin, + Self::Deleted(d) => &d.signin, + Self::Erasing(d) => &d.signin, + } + } + pub(super) fn phase(&self) -> Phase { self.presentation().phase } + pub(super) fn qr(&self) -> &QrHistory { self.presentation().qr } + pub(super) fn picker_data(&self) -> &PickerPresentation { self.presentation().picker } + pub(super) fn pending_erase(&self) -> Option<(u64, bool)> { self.presentation().pending_erase } + pub(super) fn projected_authorization(&self) -> bool { self.retained_signin().authorized() } + pub(super) fn discovery_retry(&self) -> Option { self.retained_signin().retry } + pub(super) fn plaintext(&self) -> Option<&super::super::PlaintextVerdict> { self.retained_signin().plaintext.as_ref() } + pub(super) fn signin_account(&self) -> Option<&str> { self.retained_signin().account.as_deref() } + pub(super) fn readout_account(&self) -> Option<&str> { self.signin_account().filter(|_| self.phase() == Phase::Error && self.picker_data().error == plx_platform::i18n::msg::browse_auth_no_servers()) } + pub(super) fn roster_readout_up(&self) -> bool { is_roster_readout(self.phase(), &self.picker_data().users, &self.picker_data().error) } + fn authorization(&self) -> Authorization { + match self { + Self::Discovering(d) => d.discovery.authorization(), + Self::Profiles(d) => d.choice, + Self::Switching(d) => d.selection.authorization(), + Self::Ready(d) => d.handoff.authorization(), + Self::Error(d) => d.retry.authorization(), + Self::Idle(_) | Self::Creating(_) | Self::Waiting(_) | Self::Deleted(_) | Self::Erasing(_) => Authorization::Stored, + } + } + fn login_stage(&self) -> LoginStage { + match self { + Self::Creating(d) => d.login, + Self::Waiting(d) => d.login, + Self::Idle(_) | Self::Discovering(_) | Self::Profiles(_) | Self::Switching(_) + | Self::Ready(_) | Self::Error(_) | Self::Deleted(_) | Self::Erasing(_) => LoginStage::Dormant, + } + } + pub(super) fn fresh_authority(&self) -> bool { self.authorization().is_fresh() } + pub(super) fn handoff_pending(&self) -> bool { matches!(self, Self::Ready(d) if matches!(d.handoff, Handoff::Pending { .. })) } + #[cfg(test)] + pub(super) fn active_signin(&self) -> bool { + match self { + Self::Creating(d) => matches!(d.login, LoginStage::Authorizing { .. }), + Self::Waiting(d) => matches!(d.login, LoginStage::Authorizing { .. }), + Self::Discovering(d) => matches!(d.discovery, DiscoveryStage::Running { .. }), + Self::Idle(_) | Self::Profiles(_) | Self::Switching(_) | Self::Ready(_) + | Self::Error(_) | Self::Deleted(_) | Self::Erasing(_) => false, + } + } + pub(super) fn owns_work(&self, req: u32, pending: &Pending) -> bool { + match pending.key.op { + SessionOp::Login => match self { + Self::Creating(d) => d.login.owns(req), Self::Waiting(d) => d.login.owns(req), Self::Discovering(d) => d.discovery.owns(req), + Self::Idle(_) | Self::Profiles(_) | Self::Switching(_) | Self::Ready(_) | Self::Error(_) | Self::Deleted(_) | Self::Erasing(_) => false, + }, + SessionOp::Rediscover => matches!(self, Self::Discovering(d) if d.discovery.owns(req)), + SessionOp::ProfileSwitch => match self { + Self::Switching(d) => d.selection.owns(req), + Self::Ready(d) => pending.phase == StreamPhase::ProfileSeated && d.roster.is_some_and(|stream| stream.req == req), + Self::Idle(_) | Self::Creating(_) | Self::Waiting(_) | Self::Discovering(_) | Self::Profiles(_) | Self::Error(_) | Self::Deleted(_) | Self::Erasing(_) => false, + }, + SessionOp::DevBoundary => match self { + Self::Idle(d) => matches!(d.boot, BootStage::ActivatingDev { req: owned } if owned == req), + Self::Creating(d) => matches!(d.login, LoginStage::Preparing { boundary_req, .. } if boundary_req == req), + Self::Waiting(_) | Self::Discovering(_) | Self::Profiles(_) | Self::Switching(_) | Self::Ready(_) | Self::Error(_) | Self::Deleted(_) | Self::Erasing(_) => false, + }, + SessionOp::Ready => match self { + Self::Idle(d) => matches!(d.boot, BootStage::RestoringStored { req: owned } if owned == req), + Self::Ready(d) => d.handoff.owns(req), + Self::Creating(_) | Self::Waiting(_) | Self::Discovering(_) | Self::Profiles(_) | Self::Switching(_) | Self::Error(_) | Self::Deleted(_) | Self::Erasing(_) => false, + }, + SessionOp::Picker => matches!(self, Self::Profiles(d) if d.setup.owns(req)), + SessionOp::HomeRoster | SessionOp::ServerRoster | SessionOp::Endpoint(_) => !matches!(self, Self::Erasing(_)), + } + } + pub(super) fn login_failed(self, message: String, revoke: bool) -> Self { + let authorization = self.authorization(); + fn destination(mut qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, mut signin: SignInHistory, authorization: Authorization, message: String, revoke: bool) -> Attempt { + qr.trouble = false; picker.error = message; + + signin.retry = None; signin.plaintext = None; signin.account = None; + if revoke { signin.authorization = HistoricalAuthorization::Stored; } + Attempt::Error(ErrorData { retry: if revoke { RetryAuthority::Login } else { RetryAuthority::of(authorization) }, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, message, revoke), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, message, revoke), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, message, revoke), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, message, revoke), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, message, revoke), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, message, revoke), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization, message, revoke), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, message, revoke), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, message, revoke), + Self::Erasing(mut d) => { + d.history.qr.trouble = false; d.history.picker.error = message; + d.signin.retry = None; d.signin.plaintext = None; d.signin.account = None; + if revoke { d.signin.authorization = HistoricalAuthorization::Stored; } + d.prior_phase = Phase::Error; + Self::Erasing(d) + } + } + } + pub(super) fn code_replacing(self) -> Self { + let login = self.login_stage(); + fn destination(mut qr: QrHistory, picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory, login: LoginStage) -> Attempt { + qr.code.clear(); qr.png.clear(); qr.replaced = true; qr.trouble = false; + Attempt::Creating(CreatingData { login, qr, picker_history: picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, login), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, login), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, login), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login), + Self::Erasing(mut d) => { + d.history.qr.code.clear(); d.history.qr.png.clear(); d.history.qr.replaced = true; d.history.qr.trouble = false; + d.prior_phase = Phase::Creating; + Self::Erasing(d) + } + } + } + pub(super) fn code_ready(self, generation: u64, code: String, png: Vec) -> Self { + let login = self.login_stage(); + fn destination(mut qr: QrHistory, picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory, login: LoginStage, generation: u64, code: String, png: Vec) -> Attempt { + qr.generation = generation; qr.code = code; qr.png = png; + Attempt::Waiting(WaitingData { login, qr, picker_history: picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login, generation, code, png), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, login, generation, code, png), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, login, generation, code, png), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login, generation, code, png), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login, generation, code, png), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login, generation, code, png), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, login, generation, code, png), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login, generation, code, png), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login, generation, code, png), + Self::Erasing(mut d) => { + d.history.qr.generation = generation; d.history.qr.code = code; d.history.qr.png = png; + d.prior_phase = Phase::Waiting; + Self::Erasing(d) + } + } + } + pub(super) fn authorized(self) -> Self { + let login = self.login_stage(); + fn destination(mut qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, mut signin: SignInHistory, login: LoginStage) -> Attempt { + qr.trouble = false; picker.error.clear(); + signin.authorization = HistoricalAuthorization::Fresh; signin.retry = None; + Attempt::Discovering(DiscoveringData { discovery: match login { LoginStage::Authorizing { req } => DiscoveryStage::Running { req, authorization: Authorization::Fresh }, LoginStage::Dormant | LoginStage::Preparing { .. } => DiscoveryStage::Dormant(Authorization::Stored) }, history: HistoricalPresentation { qr, picker }, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, login), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, login), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, login), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, login), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, login), + Self::Erasing(mut d) => { + d.history.qr.trouble = false; d.history.picker.error.clear(); + d.signin.authorization = HistoricalAuthorization::Fresh; d.signin.retry = None; + d.prior_phase = Phase::Discovering; + Self::Erasing(d) + } + } + } + pub(super) fn restart_discovery(self, req: u32) -> Self { + let authorization = self.authorization(); + fn destination(mut qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, mut signin: SignInHistory, authorization: Authorization, req: u32) -> Attempt { + qr.trouble = false; picker.error.clear(); + signin.plaintext = None; signin.account = None; + Attempt::Discovering(DiscoveringData { discovery: DiscoveryStage::Running { req, authorization }, history: HistoricalPresentation { qr, picker }, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, req), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, req), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization, req), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Erasing(mut d) => { + d.history.qr.trouble = false; d.history.picker.error.clear(); + d.signin.plaintext = None; d.signin.account = None; + d.prior_phase = Phase::Discovering; + Self::Erasing(d) + } + } + } + pub(super) fn restart_login(self, req: u32) -> Self { + fn destination(mut qr: QrHistory, mut picker: PickerPresentation, mut residue: ImportedIntent, mut signin: SignInHistory, req: u32) -> Attempt { + qr.code.clear(); qr.png.clear(); qr.generation = 0; qr.replaced = false; qr.trouble = false; + picker.picker = Picker::Boot; picker.users.clear(); picker.error.clear(); picker.pin_denied = false; residue.0 = false; + signin.authorization = HistoricalAuthorization::Stored; + signin.plaintext = None; signin.account = None; + Attempt::Creating(CreatingData { login: LoginStage::Authorizing { req }, qr, picker_history: picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, req), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, req), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, req), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, req), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, req), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, req), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, req), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, req), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, req), + Self::Erasing(mut d) => { + d.history.qr.code.clear(); d.history.qr.png.clear(); d.history.qr.generation = 0; d.history.qr.replaced = false; d.history.qr.trouble = false; + d.history.picker.picker = Picker::Boot; d.history.picker.users.clear(); d.history.picker.error.clear(); d.history.picker.pin_denied = false; d.residue.0 = false; + d.signin.authorization = HistoricalAuthorization::Stored; + d.signin.plaintext = None; d.signin.account = None; + d.prior_phase = Phase::Creating; + Self::Erasing(d) + } + } + } + pub(super) fn resume_back(self) -> Self { + fn destination(mut qr: QrHistory, mut picker: PickerPresentation, mut residue: ImportedIntent, mut signin: SignInHistory) -> Attempt { + qr.code.clear(); qr.png.clear(); qr.generation = 0; qr.replaced = false; + picker.users.clear(); picker.error.clear(); picker.pin_denied = false; residue.0 = true; + signin.authorization = HistoricalAuthorization::Stored; + Attempt::Ready(ReadyData { handoff: Handoff::Pending { authorization: Authorization::Stored, commit: FinalCommitStage::Unrequested }, roster: None, history: HistoricalPresentation { qr, picker }, intent: HandoffIntent(residue.0), signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Erasing(mut d) => { + d.history.qr.code.clear(); d.history.qr.png.clear(); d.history.qr.generation = 0; d.history.qr.replaced = false; + d.history.picker.users.clear(); d.history.picker.error.clear(); d.history.picker.pin_denied = false; d.residue.0 = true; + d.signin.authorization = HistoricalAuthorization::Stored; + d.prior_phase = Phase::Ready; + Self::Erasing(d) + } + } + } + pub(super) fn resume_dev_back(self) -> Self { + fn destination(qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory) -> Attempt { + picker.error.clear(); + Attempt::Ready(ReadyData { handoff: Handoff::Available, roster: None, history: HistoricalPresentation { qr, picker }, intent: HandoffIntent(residue.0), signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Erasing(mut d) => { + d.history.picker.error.clear(); + d.prior_phase = Phase::Ready; + Self::Erasing(d) + } + } + } + pub(super) fn begin_dev_account(self, boundary_req: u32, login_req: u32) -> Self { + fn destination(qr: QrHistory, mut picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory, boundary_req: u32, login_req: u32) -> Attempt { + picker.error.clear(); residue.0 = false; + Attempt::Creating(CreatingData { login: LoginStage::Preparing { boundary_req, login_req }, qr, picker_history: picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, boundary_req, login_req), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, boundary_req, login_req), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, boundary_req, login_req), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, boundary_req, login_req), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, boundary_req, login_req), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, boundary_req, login_req), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, boundary_req, login_req), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, boundary_req, login_req), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, boundary_req, login_req), + Self::Erasing(mut d) => { + d.history.picker.error.clear(); d.residue.0 = false; + d.prior_phase = Phase::Creating; + Self::Erasing(d) + } + } + } + pub(super) fn activate_dev(self) -> Self { + fn destination(qr: QrHistory, picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory) -> Attempt { + residue.0 = false; + Attempt::Ready(ReadyData { handoff: Handoff::Available, roster: None, history: HistoricalPresentation { qr, picker }, intent: HandoffIntent(residue.0), signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Erasing(mut d) => { + d.residue.0 = false; + d.prior_phase = Phase::Ready; + Self::Erasing(d) + } + } + } + pub(super) fn ready_exhausted(self) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory, authorization: Authorization) -> Attempt { + residue.0 = false; picker.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); + Attempt::Profiles(ProfilesData { setup: PickerStage::Idle, choice: authorization, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Erasing(mut d) => { + d.residue.0 = false; d.history.picker.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); + d.prior_phase = Phase::Profiles; + Self::Erasing(d) + } + } + } + pub(super) fn switch_commit_refused(self) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory, authorization: Authorization) -> Attempt { + residue.0 = false; picker.error = plx_platform::i18n::msg::browse_auth_switch_failed().into(); + Attempt::Profiles(ProfilesData { setup: PickerStage::Idle, choice: authorization, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Erasing(mut d) => { + d.residue.0 = false; d.history.picker.error = plx_platform::i18n::msg::browse_auth_switch_failed().into(); + d.prior_phase = Phase::Profiles; + Self::Erasing(d) + } + } + } + pub(super) fn dev_commit_refused(self) -> Self { + fn destination(qr: QrHistory, mut picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory) -> Attempt { + residue.0 = false; picker.error = plx_platform::i18n::msg::browse_auth_authority_failed().into(); + Attempt::Error(ErrorData { retry: RetryAuthority::Login, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Erasing(mut d) => { + d.residue.0 = false; d.history.picker.error = plx_platform::i18n::msg::browse_auth_authority_failed().into(); + d.prior_phase = Phase::Error; + Self::Erasing(d) + } + } + } + pub(super) fn switch_admission_refused(self) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory, authorization: Authorization) -> Attempt { + picker.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); + Attempt::Profiles(ProfilesData { setup: PickerStage::Idle, choice: authorization, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Erasing(mut d) => { + d.history.picker.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); + d.prior_phase = Phase::Profiles; + Self::Erasing(d) + } + } + } + pub(super) fn open_dev_picker(self) -> Self { + fn destination(qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory) -> Attempt { + picker.users.clear(); picker.error = roster_refused().into(); + Attempt::Profiles(ProfilesData { setup: PickerStage::Idle, choice: Authorization::Stored, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Erasing(mut d) => { + d.history.picker.users.clear(); d.history.picker.error = roster_refused().into(); + d.prior_phase = Phase::Profiles; + Self::Erasing(d) + } + } + } + pub(super) fn open_picker(self, kind: Picker, fallback: Vec) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory, authorization: Authorization, kind: Picker, fallback: Vec) -> Attempt { + picker.error.clear(); if picker.users.is_empty() { picker.users = fallback; } picker.picker = kind; + Attempt::Profiles(ProfilesData { setup: PickerStage::Idle, choice: authorization, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, kind, fallback), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, kind, fallback), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, kind, fallback), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, kind, fallback), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, kind, fallback), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, kind, fallback), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization, kind, fallback), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, kind, fallback), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, kind, fallback), + Self::Erasing(mut d) => { + d.history.picker.error.clear(); if d.history.picker.users.is_empty() { d.history.picker.users = fallback; } d.history.picker.picker = kind; + d.prior_phase = Phase::Profiles; + Self::Erasing(d) + } + } + } + pub(super) fn reuse_profile(self) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory, authorization: Authorization) -> Attempt { + picker.error.clear(); residue.0 = true; + Attempt::Ready(ReadyData { handoff: Handoff::Pending { authorization, commit: FinalCommitStage::Unrequested }, roster: None, history: HistoricalPresentation { qr, picker }, intent: HandoffIntent(residue.0), signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Erasing(mut d) => { + d.history.picker.error.clear(); d.residue.0 = true; + d.prior_phase = Phase::Ready; + Self::Erasing(d) + } + } + } + pub(super) fn select_profile(self, req: u32) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory, authorization: Authorization, req: u32) -> Attempt { + picker.pin_denied = false; + Attempt::Switching(SwitchingData { selection: SelectionStage::Selecting { req, authorization }, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, req), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, req), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization, req), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Erasing(mut d) => { + d.history.picker.pin_denied = false; + d.prior_phase = Phase::Switching; + Self::Erasing(d) + } + } + } + pub(super) fn switch_dropped(self) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory, authorization: Authorization) -> Attempt { + picker.pin_denied = false; picker.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); + Attempt::Profiles(ProfilesData { setup: PickerStage::Idle, choice: authorization, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Erasing(mut d) => { + d.history.picker.pin_denied = false; d.history.picker.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); + d.prior_phase = Phase::Profiles; + Self::Erasing(d) + } + } + } + pub(super) fn switch_failed(self, message: String, denied: bool) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory, authorization: Authorization, message: String, denied: bool) -> Attempt { + picker.error = message; picker.pin_denied = denied; + Attempt::Profiles(ProfilesData { setup: PickerStage::Idle, choice: authorization, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, message, denied), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, message, denied), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, message, denied), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, message, denied), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, message, denied), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, message, denied), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization, message, denied), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, message, denied), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, message, denied), + Self::Erasing(mut d) => { + d.history.picker.error = message; d.history.picker.pin_denied = denied; + d.prior_phase = Phase::Profiles; + Self::Erasing(d) + } + } + } + pub(super) fn signin_profiles(self, users: Vec) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, residue: ImportedIntent, signin: SignInHistory, authorization: Authorization, users: Vec) -> Attempt { + picker.picker = Picker::SignedIn; picker.users = users; + + Attempt::Profiles(ProfilesData { setup: PickerStage::Idle, choice: authorization, qr_history: qr, picker, residue, signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, users), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, users), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, users), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, users), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, users), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, users), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization, users), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, users), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, users), + Self::Erasing(mut d) => { + d.history.picker.picker = Picker::SignedIn; d.history.picker.users = users; + d.prior_phase = Phase::Profiles; + Self::Erasing(d) + } + } + } + pub(super) fn signin_ready(self) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory, authorization: Authorization) -> Attempt { + residue.0 = true; + + Attempt::Ready(ReadyData { handoff: Handoff::Pending { authorization, commit: FinalCommitStage::Unrequested }, roster: None, history: HistoricalPresentation { qr, picker }, intent: HandoffIntent(residue.0), signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization), + Self::Erasing(mut d) => { + d.residue.0 = true; + d.prior_phase = Phase::Ready; + Self::Erasing(d) + } + } + } + pub(super) fn profile_ready(self, req: u32) -> Self { + let authorization = self.authorization(); + fn destination(qr: QrHistory, mut picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory, authorization: Authorization, req: u32) -> Attempt { + residue.0 = true; picker.error.clear(); picker.pin_denied = false; + Attempt::Ready(ReadyData { handoff: Handoff::Pending { authorization, commit: FinalCommitStage::Unrequested }, roster: Some(ProfileStream { req }), history: HistoricalPresentation { qr, picker }, intent: HandoffIntent(residue.0), signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, req), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin, authorization, req), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin, authorization, req), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin, authorization, req), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin, authorization, req), + Self::Erasing(mut d) => { + d.residue.0 = true; d.history.picker.error.clear(); d.history.picker.pin_denied = false; + d.prior_phase = Phase::Ready; + Self::Erasing(d) + } + } + } + pub(super) fn stored_ready(self) -> Self { + fn destination(qr: QrHistory, picker: PickerPresentation, mut residue: ImportedIntent, signin: SignInHistory) -> Attempt { + residue.0 = false; + Attempt::Ready(ReadyData { handoff: Handoff::Available, roster: None, history: HistoricalPresentation { qr, picker }, intent: HandoffIntent(residue.0), signin }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Creating(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.residue, d.signin), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Switching(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Ready(d) => destination(d.history.qr, d.history.picker, ImportedIntent(d.intent.0), d.signin), + Self::Error(d) => destination(d.qr_history, d.picker, d.residue, d.signin), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.residue, d.signin), + Self::Erasing(mut d) => { + d.residue.0 = false; + d.prior_phase = Phase::Ready; + Self::Erasing(d) + } + } + } + pub(super) fn link_trouble(self, present: bool) -> Self { + match self { + Self::Idle(mut d) => { d.history.qr.trouble = present; Self::Idle(d) }, + Self::Creating(mut d) => { d.qr.trouble = present; Self::Creating(d) }, + Self::Waiting(mut d) => { d.qr.trouble = present; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.history.qr.trouble = present; Self::Discovering(d) }, + Self::Profiles(mut d) => { d.qr_history.trouble = present; Self::Profiles(d) }, + Self::Switching(mut d) => { d.qr_history.trouble = present; Self::Switching(d) }, + Self::Ready(mut d) => { d.history.qr.trouble = present; Self::Ready(d) }, + Self::Error(mut d) => { d.qr_history.trouble = present; Self::Error(d) }, + Self::Deleted(mut d) => { d.history.qr.trouble = present; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.history.qr.trouble = present; Self::Erasing(d) }, + } + } + pub(super) fn dismiss_pin(self) -> Self { + match self { + Self::Idle(mut d) => { d.history.picker.pin_denied = false; Self::Idle(d) }, + Self::Creating(mut d) => { d.picker_history.pin_denied = false; Self::Creating(d) }, + Self::Waiting(mut d) => { d.picker_history.pin_denied = false; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.history.picker.pin_denied = false; Self::Discovering(d) }, + Self::Profiles(mut d) => { d.picker.pin_denied = false; Self::Profiles(d) }, + Self::Switching(mut d) => { d.picker.pin_denied = false; Self::Switching(d) }, + Self::Ready(mut d) => { d.history.picker.pin_denied = false; Self::Ready(d) }, + Self::Error(mut d) => { d.picker.pin_denied = false; Self::Error(d) }, + Self::Deleted(mut d) => { d.history.picker.pin_denied = false; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.history.picker.pin_denied = false; Self::Erasing(d) }, + } + } + pub(super) fn roster_failed(self, message: String) -> Self { + match self { + Self::Idle(mut d) => { d.history.picker.error = message; Self::Idle(d) }, + Self::Creating(mut d) => { d.picker_history.error = message; Self::Creating(d) }, + Self::Waiting(mut d) => { d.picker_history.error = message; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.history.picker.error = message; Self::Discovering(d) }, + Self::Profiles(mut d) => { d.picker.error = message; Self::Profiles(d) }, + Self::Switching(mut d) => { d.picker.error = message; Self::Switching(d) }, + Self::Ready(mut d) => { d.history.picker.error = message; Self::Ready(d) }, + Self::Error(mut d) => { d.picker.error = message; Self::Error(d) }, + Self::Deleted(mut d) => { d.history.picker.error = message; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.history.picker.error = message; Self::Erasing(d) }, + } + } + pub(super) fn begin_signin(self, req: u32) -> Self { + match self { + Self::Idle(d) => { Self::Idle(d) }, + Self::Creating(mut d) => { d.login = d.login.promote(req); Self::Creating(d) }, + Self::Waiting(d) => { Self::Waiting(d) }, + Self::Discovering(d) => { Self::Discovering(d) }, + Self::Profiles(d) => { Self::Profiles(d) }, + Self::Switching(d) => { Self::Switching(d) }, + Self::Ready(d) => { Self::Ready(d) }, + Self::Error(d) => { Self::Error(d) }, + Self::Deleted(d) => { Self::Deleted(d) }, + Self::Erasing(d) => { Self::Erasing(d) }, + } + } + pub(super) fn consume_authorization(self) -> Self { + match self { + Self::Idle(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; Self::Idle(d) }, + Self::Creating(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; Self::Creating(d) }, + Self::Waiting(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.discovery = d.discovery.routine(); Self::Discovering(d) }, + Self::Profiles(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.choice = Authorization::Stored; Self::Profiles(d) }, + Self::Switching(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.selection = d.selection.routine(); Self::Switching(d) }, + Self::Ready(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.handoff = d.handoff.routine(); Self::Ready(d) }, + Self::Error(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.retry = RetryAuthority::Login; Self::Error(d) }, + Self::Deleted(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; Self::Erasing(d) }, + } + } + pub(super) fn discovery_trouble(self, progress: super::super::DiscoveryRetryProgress) -> Self { + match self { + Self::Idle(mut d) => { d.signin.retry = Some(progress); Self::Idle(d) }, + Self::Creating(mut d) => { d.signin.retry = Some(progress); Self::Creating(d) }, + Self::Waiting(mut d) => { d.signin.retry = Some(progress); Self::Waiting(d) }, + Self::Discovering(mut d) => { d.signin.retry = Some(progress); Self::Discovering(d) }, + Self::Profiles(mut d) => { d.signin.retry = Some(progress); Self::Profiles(d) }, + Self::Switching(mut d) => { d.signin.retry = Some(progress); Self::Switching(d) }, + Self::Ready(mut d) => { d.signin.retry = Some(progress); Self::Ready(d) }, + Self::Error(mut d) => { d.signin.retry = Some(progress); Self::Error(d) }, + Self::Deleted(mut d) => { d.signin.retry = Some(progress); Self::Deleted(d) }, + Self::Erasing(mut d) => { d.signin.retry = Some(progress); Self::Erasing(d) }, + } + } + pub(super) fn discovery_settled(self, run: super::super::DiscoveryRetryRun) -> Self { + match self { + Self::Idle(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Idle(d) }, + Self::Creating(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Creating(d) }, + Self::Waiting(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Waiting(d) }, + Self::Discovering(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Discovering(d) }, + Self::Profiles(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Profiles(d) }, + Self::Switching(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Switching(d) }, + Self::Ready(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Ready(d) }, + Self::Error(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Error(d) }, + Self::Deleted(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Deleted(d) }, + Self::Erasing(mut d) => { if d.signin.retry.is_some_and(|retry| retry.run == run) { d.signin.retry = None; } Self::Erasing(d) }, + } + } + pub(super) fn discovery_failed(self, plaintext: Option, account: Option) -> Self { + match self { + Self::Idle(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Idle(d) }, + Self::Creating(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Creating(d) }, + Self::Waiting(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Discovering(d) }, + Self::Profiles(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Profiles(d) }, + Self::Switching(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Switching(d) }, + Self::Ready(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Ready(d) }, + Self::Error(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Error(d) }, + Self::Deleted(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.signin.plaintext = plaintext; d.signin.account = account; Self::Erasing(d) }, + } + } + pub(super) fn plaintext_declined(self, choice: plx_plex::plex::session::PlaintextChoice) -> Self { + match self { + Self::Idle(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.history.picker.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Idle(d) }, + Self::Creating(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.picker_history.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Creating(d) }, + Self::Waiting(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.picker_history.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Waiting(d) }, + Self::Discovering(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.history.picker.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Discovering(d) }, + Self::Profiles(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.picker.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Profiles(d) }, + Self::Switching(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.picker.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Switching(d) }, + Self::Ready(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.history.picker.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Ready(d) }, + Self::Error(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.picker.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Error(d) }, + Self::Deleted(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.history.picker.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Deleted(d) }, + Self::Erasing(mut d) => { if let Some(verdict) = d.signin.plaintext.as_mut() { verdict.choice = choice; d.history.picker.error = super::super::insecure_only_copy(Some(verdict)).into_owned(); } Self::Erasing(d) }, + } + } + pub(super) fn roster_arrived(self, users: Vec) -> Self { + match self { + Self::Idle(mut d) => { d.history.picker.users = users; Self::Idle(d) }, + Self::Creating(mut d) => { d.picker_history.users = users; Self::Creating(d) }, + Self::Waiting(mut d) => { d.picker_history.users = users; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.history.picker.users = users; Self::Discovering(d) }, + Self::Profiles(mut d) => { d.picker.users = users; Self::Profiles(d) }, + Self::Switching(mut d) => { d.picker.users = users; Self::Switching(d) }, + Self::Ready(mut d) => { d.history.picker.users = users; Self::Ready(d) }, + Self::Error(mut d) => { d.picker.users = users; Self::Error(d) }, + Self::Deleted(mut d) => { d.history.picker.users = users; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.history.picker.users = users; Self::Erasing(d) }, + } + } + pub(super) fn ready_committed(self) -> Self { + match self { + Self::Idle(mut d) => { d.residue.0 = false; Self::Idle(d) }, + Self::Creating(mut d) => { d.residue.0 = false; Self::Creating(d) }, + Self::Waiting(mut d) => { d.residue.0 = false; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.residue.0 = false; Self::Discovering(d) }, + Self::Profiles(mut d) => { d.residue.0 = false; Self::Profiles(d) }, + Self::Switching(mut d) => { d.residue.0 = false; Self::Switching(d) }, + Self::Ready(mut d) => { d.intent.0 = false; d.handoff = Handoff::Available; Self::Ready(d) }, + Self::Error(mut d) => { d.residue.0 = false; Self::Error(d) }, + Self::Deleted(mut d) => { d.residue.0 = false; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.residue.0 = false; Self::Erasing(d) }, + } + } + pub(super) fn erase_authority(self) -> Self { + match self { + Self::Idle(mut d) => { d.boot = BootStage::Dormant; d.signin.authorization = HistoricalAuthorization::Stored; Self::Idle(d) }, + Self::Creating(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.login = LoginStage::Dormant; Self::Creating(d) }, + Self::Waiting(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.login = LoginStage::Dormant; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.discovery = DiscoveryStage::Dormant(Authorization::Stored); Self::Discovering(d) }, + Self::Profiles(mut d) => { d.setup = PickerStage::Idle; d.signin.authorization = HistoricalAuthorization::Stored; d.choice = Authorization::Stored; Self::Profiles(d) }, + Self::Switching(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.selection = SelectionStage::Dormant(Authorization::Stored); Self::Switching(d) }, + Self::Ready(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.handoff = Handoff::Available; d.roster = None; Self::Ready(d) }, + Self::Error(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; d.retry = RetryAuthority::Login; Self::Error(d) }, + Self::Deleted(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.signin.authorization = HistoricalAuthorization::Stored; Self::Erasing(d) }, + } + } + pub(super) fn begin_dev_activation(self, req: u32) -> Self { + match self { + Self::Idle(mut d) => { d.boot = BootStage::ActivatingDev { req }; Self::Idle(d) }, + Self::Creating(d) => { Self::Creating(d) }, + Self::Waiting(d) => { Self::Waiting(d) }, + Self::Discovering(d) => { Self::Discovering(d) }, + Self::Profiles(d) => { Self::Profiles(d) }, + Self::Switching(d) => { Self::Switching(d) }, + Self::Ready(d) => { Self::Ready(d) }, + Self::Error(d) => { Self::Error(d) }, + Self::Deleted(d) => { Self::Deleted(d) }, + Self::Erasing(d) => { Self::Erasing(d) }, + } + } + pub(super) fn begin_stored_restore(self, req: u32) -> Self { + match self { + Self::Idle(mut d) => { d.boot = BootStage::RestoringStored { req }; Self::Idle(d) }, + Self::Creating(d) => { Self::Creating(d) }, + Self::Waiting(d) => { Self::Waiting(d) }, + Self::Discovering(d) => { Self::Discovering(d) }, + Self::Profiles(d) => { Self::Profiles(d) }, + Self::Switching(d) => { Self::Switching(d) }, + Self::Ready(d) => { Self::Ready(d) }, + Self::Error(d) => { Self::Error(d) }, + Self::Deleted(d) => { Self::Deleted(d) }, + Self::Erasing(d) => { Self::Erasing(d) }, + } + } + pub(super) fn install_picker(self, req: u32) -> Self { + match self { + Self::Idle(d) => { Self::Idle(d) }, + Self::Creating(d) => { Self::Creating(d) }, + Self::Waiting(d) => { Self::Waiting(d) }, + Self::Discovering(d) => { Self::Discovering(d) }, + Self::Profiles(mut d) => { d.setup = PickerStage::Installing { req }; Self::Profiles(d) }, + Self::Switching(d) => { Self::Switching(d) }, + Self::Ready(d) => { Self::Ready(d) }, + Self::Error(d) => { Self::Error(d) }, + Self::Deleted(d) => { Self::Deleted(d) }, + Self::Erasing(d) => { Self::Erasing(d) }, + } + } + pub(super) fn begin_ready_commit(self, req: u32) -> Self { + match self.consume_authorization() { + Self::Ready(mut d) => { if let Handoff::Pending { authorization, .. } = d.handoff { d.handoff = Handoff::Pending { authorization, commit: FinalCommitStage::Committing { req } }; } Self::Ready(d) }, + Self::Idle(d) => Self::Idle(d), + Self::Creating(d) => Self::Creating(d), + Self::Waiting(d) => Self::Waiting(d), + Self::Discovering(d) => Self::Discovering(d), + Self::Profiles(d) => Self::Profiles(d), + Self::Switching(d) => Self::Switching(d), + Self::Error(d) => Self::Error(d), + Self::Deleted(d) => Self::Deleted(d), + Self::Erasing(d) => Self::Erasing(d), + } + } + pub(super) fn work_retired(self, req: u32) -> Self { + match self { + Self::Idle(mut d) => { if d.boot.owns(req) { d.boot = BootStage::Dormant; } Self::Idle(d) }, + Self::Creating(mut d) => { if d.login.owns(req) || matches!(d.login, LoginStage::Preparing { boundary_req, login_req } if boundary_req == req || login_req == req) { d.login = LoginStage::Dormant; } Self::Creating(d) }, + Self::Waiting(mut d) => { if d.login.owns(req) { d.login = LoginStage::Dormant; } Self::Waiting(d) }, + Self::Discovering(mut d) => { if d.discovery.owns(req) { d.discovery = d.discovery.cancelled(); } Self::Discovering(d) }, + Self::Profiles(mut d) => { if d.setup.owns(req) { d.setup = PickerStage::Idle; } Self::Profiles(d) }, + Self::Switching(mut d) => { if d.selection.owns(req) { d.selection = d.selection.cancelled(); } Self::Switching(d) }, + Self::Ready(mut d) => { if d.roster.is_some_and(|stream| stream.req == req) { d.roster = None; } if d.handoff.owns(req) { d.handoff = d.handoff.cancelled(); } Self::Ready(d) }, + Self::Error(d) => Self::Error(d), + Self::Deleted(d) => Self::Deleted(d), + Self::Erasing(d) => Self::Erasing(d), + } + } + + pub(super) fn epoch_advanced(self) -> Self { + match self { + Self::Idle(mut d) => { d.boot = BootStage::Dormant; d.signin.retry = None; Self::Idle(d) }, + Self::Creating(mut d) => { d.signin.retry = None; d.login = LoginStage::Dormant; Self::Creating(d) }, + Self::Waiting(mut d) => { d.signin.retry = None; d.login = LoginStage::Dormant; Self::Waiting(d) }, + Self::Discovering(mut d) => { d.signin.retry = None; d.discovery = d.discovery.cancelled(); Self::Discovering(d) }, + Self::Profiles(mut d) => { d.setup = PickerStage::Idle; d.signin.retry = None; Self::Profiles(d) }, + Self::Switching(mut d) => { d.signin.retry = None; d.selection = d.selection.cancelled(); Self::Switching(d) }, + Self::Ready(mut d) => { d.signin.retry = None; d.roster = None; d.handoff = d.handoff.cancelled(); Self::Ready(d) }, + Self::Error(mut d) => { d.signin.retry = None; Self::Error(d) }, + Self::Deleted(mut d) => { d.signin.retry = None; Self::Deleted(d) }, + Self::Erasing(mut d) => { d.signin.retry = None; Self::Erasing(d) }, + } + } + pub(super) fn begin_erase(self, epoch: u64, sign_in: bool) -> Self { + fn destination(mut qr: QrHistory, mut picker: PickerPresentation, signin: SignInHistory, phase: Phase, epoch: u64, sign_in: bool) -> Attempt { + qr.code.clear(); qr.png.clear(); qr.generation = 0; qr.replaced = false; + picker.picker = Picker::Boot; picker.users.clear(); picker.error.clear(); picker.pin_denied = false; + Attempt::Erasing(ErasingData { history: HistoricalPresentation { qr, picker }, residue: ImportedIntent(false), signin, prior_phase: phase, pending_erase: (epoch, sign_in) }) + } + match self { + Self::Idle(d) => destination(d.history.qr, d.history.picker, d.signin, Phase::Idle, epoch, sign_in), + Self::Creating(d) => destination(d.qr, d.picker_history, d.signin, Phase::Creating, epoch, sign_in), + Self::Waiting(d) => destination(d.qr, d.picker_history, d.signin, Phase::Waiting, epoch, sign_in), + Self::Discovering(d) => destination(d.history.qr, d.history.picker, d.signin, Phase::Discovering, epoch, sign_in), + Self::Profiles(d) => destination(d.qr_history, d.picker, d.signin, Phase::Profiles, epoch, sign_in), + Self::Switching(d) => destination(d.qr_history, d.picker, d.signin, Phase::Switching, epoch, sign_in), + Self::Ready(d) => destination(d.history.qr, d.history.picker, d.signin, Phase::Ready, epoch, sign_in), + Self::Error(d) => destination(d.qr_history, d.picker, d.signin, Phase::Error, epoch, sign_in), + Self::Deleted(d) => destination(d.history.qr, d.history.picker, d.signin, Phase::Deleted, epoch, sign_in), + Self::Erasing(d) => destination(d.history.qr, d.history.picker, d.signin, d.prior_phase, epoch, sign_in), + } + } + pub(super) fn finish_erase(self) -> Self { + match self { + Self::Idle(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.history.qr, picker: d.history.picker }, residue: d.residue, signin: d.signin }), + Self::Creating(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.qr, picker: d.picker_history }, residue: d.residue, signin: d.signin }), + Self::Waiting(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.qr, picker: d.picker_history }, residue: d.residue, signin: d.signin }), + Self::Discovering(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.history.qr, picker: d.history.picker }, residue: d.residue, signin: d.signin }), + Self::Profiles(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.qr_history, picker: d.picker }, residue: d.residue, signin: d.signin }), + Self::Switching(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.qr_history, picker: d.picker }, residue: d.residue, signin: d.signin }), + Self::Ready(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.history.qr, picker: d.history.picker }, residue: ImportedIntent(d.intent.0), signin: d.signin }), + Self::Error(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.qr_history, picker: d.picker }, residue: d.residue, signin: d.signin }), + Self::Deleted(d) => Self::Deleted(DeletedData { history: HistoricalPresentation { qr: d.history.qr, picker: d.history.picker }, residue: d.residue, signin: d.signin }), + Self::Erasing(d) => Self::Deleted(DeletedData { history: d.history, residue: d.residue, signin: d.signin }), + } + } +} +impl Attempt { + fn presentation(&self) -> PresentationRef<'_> { + match self { + Self::Idle(data) => PresentationRef { phase: Phase::Idle, qr: &data.history.qr, picker: &data.history.picker, apply_pending: data.residue.0, pending_erase: None }, + Self::Creating(data) => PresentationRef { phase: Phase::Creating, qr: &data.qr, picker: &data.picker_history, apply_pending: data.residue.0, pending_erase: None }, + Self::Waiting(data) => PresentationRef { phase: Phase::Waiting, qr: &data.qr, picker: &data.picker_history, apply_pending: data.residue.0, pending_erase: None }, + Self::Discovering(data) => PresentationRef { phase: Phase::Discovering, qr: &data.history.qr, picker: &data.history.picker, apply_pending: data.residue.0, pending_erase: None }, + Self::Profiles(data) => PresentationRef { phase: Phase::Profiles, qr: &data.qr_history, picker: &data.picker, apply_pending: data.residue.0, pending_erase: None }, + Self::Switching(data) => PresentationRef { phase: Phase::Switching, qr: &data.qr_history, picker: &data.picker, apply_pending: data.residue.0, pending_erase: None }, + Self::Ready(data) => PresentationRef { phase: Phase::Ready, qr: &data.history.qr, picker: &data.history.picker, apply_pending: data.intent.0, pending_erase: None }, + Self::Error(data) => PresentationRef { phase: Phase::Error, qr: &data.qr_history, picker: &data.picker, apply_pending: data.residue.0, pending_erase: None }, + Self::Deleted(data) => PresentationRef { phase: Phase::Deleted, qr: &data.history.qr, picker: &data.history.picker, apply_pending: data.residue.0, pending_erase: None }, + Self::Erasing(data) => PresentationRef { phase: data.prior_phase, qr: &data.history.qr, picker: &data.history.picker, apply_pending: data.residue.0, pending_erase: Some(data.pending_erase) }, + } + } +} + +impl<'a> LegacyV5Projection<'a> { + pub(super) fn from_partition(partition: PartitionView<'a>) -> Self { + let c = partition.common; + let attempt = partition.attempt; + let p = attempt.presentation(); + Self { + disk_identity: &c.disk_identity, + authority: &c.authority, + phase: p.phase, + picker: p.picker.picker, + persisted: &c.persisted, + committed_credentials: &c.committed_credentials, + pin_code: &p.qr.code, + qr_png: &p.qr.png, + users: &p.picker.users, + error: &p.picker.error, + pin_denied: p.picker.pin_denied, + authorized_in_flow: attempt.projected_authorization(), + signin_active: c.signin_notice.owed(), + apply_pending: p.apply_pending, + code_replaced: p.qr.replaced, + qr_gen: p.qr.generation, + next_qr: c.next_qr, + epoch: c.epoch, + next_req: c.next_req, + delete_leftovers: c.delete_leftovers, + profile_scope: c.profile_scope, + active_profile: &c.active_profile, + pending: &c.pending, + persistence_purpose: c.persistence_purpose, + commit_phase: &c.commit_phase, + persistence_warning: &c.persistence_warning, + held_handoff: &c.held_handoff, + persistence_warning_answered: c.persistence_warning_answered, + pending_commit: &c.pending_commit, + pending_erase: p.pending_erase, + pump_pending: c.pump_pending, + inbox: &c.inbox, + incident: &c.incident, + incidents_seen: &c.incidents_seen, + next_incident: c.next_incident, + link_trouble: p.qr.trouble, + switch_refused_for: &c.switch_refused_for, + plaintext: &attempt.retained_signin().plaintext, + discovery_retry: attempt.discovery_retry(), + } + } +} + + + +#[cfg(test)] +mod tests { + use super::*; + + + fn projected_fields(p: &LegacyV5Projection<'_>) -> Vec { + vec![ + serde_json::to_value(&p.disk_identity).unwrap(), + serde_json::to_value(&p.authority).unwrap(), + serde_json::to_value(&p.phase).unwrap(), + serde_json::to_value(&p.picker).unwrap(), + serde_json::to_value(&p.persisted).unwrap(), + serde_json::to_value(&p.committed_credentials).unwrap(), + serde_json::to_value(&p.pin_code).unwrap(), + serde_json::to_value(&p.qr_png).unwrap(), + serde_json::to_value(&p.users).unwrap(), + serde_json::to_value(&p.error).unwrap(), + serde_json::to_value(&p.pin_denied).unwrap(), + serde_json::to_value(&p.authorized_in_flow).unwrap(), + serde_json::to_value(&p.signin_active).unwrap(), + serde_json::to_value(&p.apply_pending).unwrap(), + serde_json::to_value(&p.code_replaced).unwrap(), + serde_json::to_value(&p.qr_gen).unwrap(), + serde_json::to_value(&p.next_qr).unwrap(), + serde_json::to_value(&p.epoch).unwrap(), + serde_json::to_value(&p.next_req).unwrap(), + serde_json::to_value(&p.delete_leftovers).unwrap(), + serde_json::to_value(&p.profile_scope).unwrap(), + serde_json::to_value(&p.active_profile).unwrap(), + serde_json::to_value(&p.pending).unwrap(), + serde_json::to_value(&p.persistence_purpose).unwrap(), + serde_json::to_value(&p.commit_phase).unwrap(), + serde_json::to_value(&p.persistence_warning).unwrap(), + serde_json::to_value(&p.held_handoff).unwrap(), + serde_json::to_value(&p.persistence_warning_answered).unwrap(), + serde_json::to_value(&p.pending_commit).unwrap(), + serde_json::to_value(&p.pending_erase).unwrap(), + serde_json::to_value(&p.pump_pending).unwrap(), + serde_json::to_value(&p.inbox).unwrap(), + serde_json::to_value(&p.incident).unwrap(), + serde_json::to_value(&p.incidents_seen).unwrap(), + serde_json::to_value(&p.next_incident).unwrap(), + serde_json::to_value(&p.link_trouble).unwrap(), + serde_json::to_value(&p.switch_refused_for).unwrap(), + serde_json::to_value(&p.plaintext).unwrap(), + serde_json::to_value(&p.discovery_retry).unwrap(), + ] + } + + // Imported-residue fixtures intentionally include states no addressed runtime event admits. + // Construct their owned successor while exercising the production exit and entry plans. + fn fixture_after_attempt(init: SessionInit, event: AttemptEvent) -> (SessionMachine, Vec) { + let mut owner = SessionMachine::from_init(init); + let exit = ExitFx::attempt(owner.view(), &event); + let entry = EntryFx::attempt(owner.view(), &event); + if let Some(notice) = signin_notice(&event) { owner.common.signin_notice = notice; } + let mut effects = Vec::new(); + exit.emit(&mut |fx| effects.push(fx)); + owner.state = next_attempt(owner.state, event); + entry.emit(&mut |fx| effects.push(fx)); + assert!(owner.transition(&SessionEvent::RebuildPublication, 0, &mut effects)); + (owner, effects) + } + + fn fixture(phase: Phase, erase: Option<(u64, bool)>) -> SessionInit { + let mut s = SessionInit::captured(PersistedSession { client_id: "representation-client".into(), ..Default::default() }); + s.phase = phase; + s.pending_erase = erase; + s.picker = Picker::ChangeProfile; + s.pin_code = "retained-code".into(); + s.qr_png = vec![8, 3, 7]; + s.qr_gen = 91; + s.next_qr = 127; + s.code_replaced = true; + s.link_trouble = true; + s.users = vec![UserTile { uuid: "retained-user".into(), ..Default::default() }]; + s.error = "retained-error".into(); + s.pin_denied = true; + s.apply_pending = true; + s.authorized_in_flow = true; + s.signin_active = true; + s.signin_account = Some("private-account".into()); + s + } + + #[test] + fn attempt_characterization_login_failure_preserves_imported_presentation() { + for phase in [Phase::Idle, Phase::Creating, Phase::Waiting, Phase::Discovering, + Phase::Profiles, Phase::Switching, Phase::Ready, Phase::Error, Phase::Deleted] { + for erase in [None, Some((77, true))] { + let mut init = fixture(phase, erase); + let mut owner = SessionMachine::from_init(init.clone()); + let mut effects = Vec::new(); + owner.fail_login("synthetic failure", None, &mut |effect| effects.push(effect)); + assert!(matches!(effects.as_slice(), [SessionFx::Coordinator( + CoordinatorAction::SignInFailed { phase: actual })] if *actual == phase)); + init.phase = Phase::Error; + init.error = "synthetic failure".into(); + init.link_trouble = false; + init.signin_active = false; + init.signin_account = None; + init.incident = None; + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), serde_json::to_value(&init).unwrap()); + assert_eq!(owner.snapshot_init().signin_account, None); + } + } + } + + #[test] + fn attempt_representation_all_phases_and_erase_preserve_every_field() { + for phase in [Phase::Idle, Phase::Creating, Phase::Waiting, Phase::Discovering, + Phase::Profiles, Phase::Switching, Phase::Ready, Phase::Error, Phase::Deleted] { + for erase in [None, Some((0, false)), Some((77, true))] { + let init = fixture(phase, erase); + let expected = serde_json::to_value(&init).unwrap(); + let expected_fields = projected_fields(&LegacyV5Projection::from_init(&init)); + let hash = init.hash(); + let code_ptr = init.pin_code.as_ptr(); + let png_ptr = init.qr_png.as_ptr(); + let users_ptr = init.users.as_ptr(); + let error_ptr = init.error.as_ptr(); + let partition = Partition::from_init(init); + let projection = LegacyV5Projection::from_partition(partition.view()); + assert_eq!(projected_fields(&projection), expected_fields); + assert_eq!(projection.phase, phase); + assert_eq!(projection.pending_erase, erase); + assert_eq!(projection.pin_code.as_ptr(), code_ptr); + assert_eq!(projection.qr_png.as_ptr(), png_ptr); + assert_eq!(projection.users.as_ptr(), users_ptr); + assert_eq!(projection.error.as_ptr(), error_ptr); + let mut canon = Canon::new(); + projection.write(&mut canon); + assert_eq!(canon.finish(), hash); + let snapshot = partition.snapshot_init(); + assert_eq!(serde_json::to_value(&snapshot).unwrap(), expected); + assert_eq!(snapshot.signin_account.as_deref(), Some("private-account")); + assert!(expected.get("signin_account").is_none()); + assert_eq!(snapshot.hash(), hash); + assert!(partition.common.pending.is_empty()); + if erase.is_some() { assert!(matches!(partition.attempt, Attempt::Erasing(_))); } + } + } + } + + #[test] + fn attempt_runtime_moves_retain_presentation_and_erase_projection() { + let init = fixture(Phase::Waiting, Some((77, true))); + let code_ptr = init.pin_code.as_ptr(); + let users_ptr = init.users.as_ptr(); + let mut runtime = Partition::from_init(init); + let attempt = std::mem::replace(&mut runtime.attempt, Attempt::placeholder()); + runtime.attempt = attempt.authorized(); + assert_eq!(runtime.phase(), Phase::Discovering); + assert_eq!(runtime.qr().code.as_ptr(), code_ptr); + assert_eq!(runtime.picker_data().users.as_ptr(), users_ptr); + assert_eq!(runtime.pending_erase(), Some((77, true))); + let attempt = std::mem::replace(&mut runtime.attempt, Attempt::placeholder()); + runtime.attempt = attempt.login_failed("updated".into(), false); + let attempt = std::mem::replace(&mut runtime.attempt, Attempt::placeholder()); + runtime.attempt = attempt.ready_committed(); + let projected = LegacyV5Projection::from_partition(runtime.view()); + assert_eq!(projected.phase, Phase::Error); + assert_eq!(projected.pending_erase, Some((77, true))); + assert_eq!(projected.pin_code.as_ptr(), code_ptr); + assert_eq!(projected.users.as_ptr(), users_ptr); + assert_eq!(projected.error.as_str(), "updated"); + assert!(!projected.apply_pending && !projected.link_trouble); + let mut canon = Canon::new(); + projected.write(&mut canon); + assert_eq!(canon.finish(), runtime.snapshot_init().hash()); + let mut init = runtime.snapshot_init(); + init.pending_erase = None; + // Move the code into the imported DTO so the pointer assertion still tests retention. + init.pin_code = match runtime.attempt { + Attempt::Erasing(data) => data.history.qr.code, + Attempt::Idle(_) | Attempt::Creating(_) | Attempt::Waiting(_) | Attempt::Discovering(_) + | Attempt::Profiles(_) | Attempt::Switching(_) | Attempt::Ready(_) | Attempt::Error(_) + | Attempt::Deleted(_) => panic!("fixture retains its erase"), + }; + runtime = Partition::from_init(init); + assert_eq!(runtime.phase(), Phase::Error); + assert!(runtime.pending_erase().is_none()); + assert_eq!(runtime.qr().code.as_ptr(), code_ptr); + } + + #[test] + fn attempt_representation_pin_dismissal_replaces_only_the_verdict_in_every_imported_phase() { + for phase in [Phase::Idle, Phase::Creating, Phase::Waiting, Phase::Discovering, + Phase::Profiles, Phase::Switching, Phase::Ready, Phase::Error, Phase::Deleted] { + for erase in [None, Some((77, true))] { + let init = fixture(phase, erase); + let code = init.pin_code.as_ptr(); + let users = init.users.as_ptr(); + let mut expected = init.clone(); + expected.pin_denied = false; + let mut owner = SessionMachine::from_init(init); + let effects = super::super::scenarios::step(&mut owner, + SessionEvent::Command(Command::DismissPinError)); + assert!(effects.is_empty()); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), + serde_json::to_value(&expected).unwrap()); + assert_eq!(owner.snapshot_init().signin_account, expected.signin_account); + assert_eq!(owner.state.qr().code.as_ptr(), code); + assert_eq!(owner.state.picker_data().users.as_ptr(), users); + let publication = owner.publication(); + assert!(super::super::scenarios::step(&mut owner, + SessionEvent::Command(Command::DismissPinError)).is_empty()); + assert!(Arc::ptr_eq(&publication, &owner.publication())); + } + } + } + + #[test] + fn attempt_runtime_qr_flow_moves_only_the_accepted_presentation_patch() { + for phase in [Phase::Idle, Phase::Creating, Phase::Waiting, Phase::Discovering, + Phase::Profiles, Phase::Switching, Phase::Ready, Phase::Error, Phase::Deleted] { + for erase in [None, Some((77, true))] { + for event in 0..4 { + let init = fixture(phase, erase); + let users = init.users.as_ptr(); + let mut expected = init.clone(); + let flow = match event { + 0 => { + expected.phase = Phase::Creating; + expected.pin_code.clear(); + expected.qr_png.clear(); + expected.code_replaced = true; + expected.link_trouble = false; + AttemptEvent::CodeReplacing + } + 1 => { + expected.phase = Phase::Waiting; + expected.qr_gen = 128; + expected.pin_code = "new-code".into(); + expected.qr_png = vec![4, 5]; + AttemptEvent::CodeReady { generation: 128, code: "new-code".into(), png: vec![4, 5] } + } + 2 => { + expected.phase = Phase::Discovering; + expected.link_trouble = false; + expected.error.clear(); + AttemptEvent::Authorized + } + _ => { + expected.link_trouble = false; + AttemptEvent::LinkTrouble { present: false } + } + }; + let (state, _effects) = fixture_after_attempt(init, flow); + assert_eq!(serde_json::to_value(state.snapshot_init()).unwrap(), + serde_json::to_value(&expected).unwrap()); + assert_eq!(state.snapshot_init().signin_account, expected.signin_account); + assert_eq!(state.state.picker_data().users.as_ptr(), users); + } + } + } + } + + #[test] + fn attempt_runtime_named_flow_patches_preserve_unwritten_imported_residue() { + for phase in [Phase::Idle, Phase::Creating, Phase::Waiting, Phase::Discovering, + Phase::Profiles, Phase::Switching, Phase::Ready, Phase::Error, Phase::Deleted] { + for event in 0..8 { + let init = fixture(phase, (event == 4).then_some((77, true))); + let users = init.users.as_ptr(); + let mut expected = init.clone(); + let flow = match event { + 0 => { + expected.phase = Phase::Discovering; + expected.link_trouble = false; + expected.error.clear(); expected.signin_account = None; + AttemptEvent::RestartDiscovery { req: 29 } + } + 1 => { + expected.phase = Phase::Creating; + expected.picker = Picker::Boot; + expected.pin_code.clear(); expected.qr_png.clear(); expected.qr_gen = 0; + expected.code_replaced = false; expected.link_trouble = false; + expected.users.clear(); expected.error.clear(); expected.pin_denied = false; + expected.apply_pending = false; expected.authorized_in_flow = false; expected.signin_account = None; + AttemptEvent::RestartLogin { req: 29 } + } + 2 => { + expected.phase = Phase::Ready; + expected.pin_code.clear(); expected.qr_png.clear(); expected.qr_gen = 0; + expected.code_replaced = false; + expected.users.clear(); expected.error.clear(); expected.pin_denied = false; + expected.apply_pending = true; expected.authorized_in_flow = false; expected.signin_active = false; + AttemptEvent::ResumeBack + } + 3 => { + expected.pending_erase = Some((78, false)); expected.picker = Picker::Boot; + expected.pin_code.clear(); expected.qr_png.clear(); expected.qr_gen = 0; + expected.code_replaced = false; + expected.users.clear(); expected.error.clear(); expected.pin_denied = false; + expected.apply_pending = false; + AttemptEvent::BeginErase { epoch: 78, sign_in: false } + } + 4 => { expected.pending_erase = None; expected.phase = Phase::Deleted; AttemptEvent::FinishErase } + 5 => { expected.phase = Phase::Creating; expected.error.clear(); expected.apply_pending = false; AttemptEvent::BeginDevAccount { boundary_req: 28, login_req: 29 } } + 6 => { expected.phase = Phase::Ready; expected.apply_pending = false; AttemptEvent::ActivateDev } + _ => { expected.phase = Phase::Ready; expected.error.clear(); AttemptEvent::ResumeDevBack } + }; + let (state, _effects) = fixture_after_attempt(init, flow); + let actual = state.snapshot_init(); + assert_eq!(serde_json::to_value(&actual).unwrap(), serde_json::to_value(&expected).unwrap()); + assert_eq!(actual.signin_account, expected.signin_account); + if matches!(event, 0 | 4 | 5 | 6 | 7) { + assert_eq!(state.state.picker_data().users.as_ptr(), users); + } + } + } + } + + #[test] + fn attempt_representation_sparse_imports_do_not_invent_code_or_handoff() { + for phase in [Phase::Waiting, Phase::Discovering, Phase::Switching, Phase::Ready] { + let mut init = SessionInit::captured(PersistedSession::default()); + init.phase = phase; + init.qr_gen = 42; + init.code_replaced = true; + init.link_trouble = true; + let expected = serde_json::to_value(&init).unwrap(); + let hash = init.hash(); + let partition = Partition::from_init(init); + let p = LegacyV5Projection::from_partition(partition.view()); + assert!(p.pin_code.is_empty() && p.qr_png.is_empty()); + assert_eq!(p.qr_gen, 42); + assert!(p.code_replaced && p.link_trouble); + assert!(!p.apply_pending); + assert!(partition.common.pending.is_empty()); + let snapshot = partition.snapshot_init(); + assert_eq!(serde_json::to_value(snapshot).unwrap(), expected); + let mut canon = Canon::new(); + p.write(&mut canon); + assert_eq!(canon.finish(), hash); + } + } + + #[test] + fn attempt_representation_private_readout_is_common_not_history_or_hash() { + let mut init = fixture(Phase::Discovering, None); + let before = init.hash(); + init.signin_account = Some("another-private-account".into()); + assert_eq!(init.hash(), before); + let partition = Partition::from_init(init); + assert_eq!(partition.attempt.signin_account(), Some("another-private-account")); + let p = partition.attempt.presentation(); + assert_eq!(p.qr.code, "retained-code"); + assert_eq!(p.picker.users[0].uuid, "retained-user"); + assert_eq!(partition.snapshot_init().signin_account.as_deref(), Some("another-private-account")); + } + #[test] + fn attempt_runtime_all_owned_destinations_preserve_arbitrary_imported_residue() { + for phase in [Phase::Idle, Phase::Creating, Phase::Waiting, Phase::Discovering, + Phase::Profiles, Phase::Switching, Phase::Ready, Phase::Error, Phase::Deleted] { + for erase in [None, Some((77, true))] { + for case in 0..16 { + let init = fixture(phase, erase); + let code = init.pin_code.as_ptr(); + let mut expected = init.clone(); + let users = vec![UserTile { uuid: "new-roster".into(), ..Default::default() }]; + let event = match case { + 0 => { expected.phase = Phase::Profiles; expected.apply_pending = false; + expected.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); AttemptEvent::ReadyExhausted } + 1 => { expected.phase = Phase::Profiles; expected.apply_pending = false; + expected.error = plx_platform::i18n::msg::browse_auth_switch_failed().into(); AttemptEvent::SwitchCommitRefused } + 2 => { expected.phase = Phase::Error; expected.apply_pending = false; + expected.error = plx_platform::i18n::msg::browse_auth_authority_failed().into(); AttemptEvent::DevCommitRefused } + 3 => { expected.phase = Phase::Profiles; + expected.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); AttemptEvent::SwitchAdmissionRefused } + 4 => { expected.phase = Phase::Profiles; expected.users.clear(); + expected.error = roster_refused().into(); AttemptEvent::OpenDevPicker } + 5 => { expected.phase = Phase::Profiles; expected.error.clear(); expected.picker = Picker::Boot; + AttemptEvent::OpenPicker { kind: Picker::Boot, fallback: users } } + 6 => { expected.phase = Phase::Ready; expected.error.clear(); expected.apply_pending = true; + AttemptEvent::ReuseProfile } + 7 => { expected.phase = Phase::Switching; expected.pin_denied = false; AttemptEvent::SelectProfile { req: 29 } } + 8 => { expected.phase = Phase::Profiles; expected.pin_denied = false; + expected.error = plx_platform::i18n::msg::browse_auth_switch_retry().into(); AttemptEvent::SwitchDropped } + 9 => { expected.phase = Phase::Profiles; expected.error = "profile failure".into(); expected.pin_denied = false; + AttemptEvent::SwitchFailed { message: "profile failure".into(), denied: false } } + 10 => { expected.phase = Phase::Profiles; expected.picker = Picker::SignedIn; expected.users = users.clone(); expected.signin_active = false; + AttemptEvent::SigninProfiles { users } } + 11 => { expected.phase = Phase::Ready; expected.apply_pending = true; expected.signin_active = false; AttemptEvent::SigninReady } + 12 => { expected.phase = Phase::Ready; expected.apply_pending = true; expected.error.clear(); expected.pin_denied = false; + AttemptEvent::ProfileReady { req: 29 } } + 13 => { expected.phase = Phase::Ready; expected.apply_pending = false; AttemptEvent::StoredReady } + 14 => { expected.users = users.clone(); AttemptEvent::RosterArrived { users } } + _ => { expected.apply_pending = false; AttemptEvent::ReadyCommitted } + }; + let (owner, transition_effects) = fixture_after_attempt(init, event); + let mut effects = Vec::new(); + let mut coordinator = Vec::new(); + for fx in transition_effects { + if let SessionFx::Coordinator(action) = fx { coordinator.push(action); } + else { effects.push(fx); } + } + if matches!(case, 10 | 11) { + assert!(matches!(coordinator.as_slice(), [CoordinatorAction::SignInCompleted])); + } else { assert!(coordinator.is_empty()); } + let actual = owner.snapshot_init(); + assert_eq!(serde_json::to_value(&actual).unwrap(), serde_json::to_value(&expected).unwrap(), "phase={phase:?} case={case}"); + assert_eq!(actual.signin_account, expected.signin_account); + assert_eq!(owner.state.qr().code.as_ptr(), code); + if erase.is_some() { + assert!(matches!(&owner.state, Attempt::Erasing(_))); + } + if case == 7 && erase.is_none() { + assert!(matches!(&owner.state, Attempt::Switching(data) if data.selection.owns(29))); + assert!(matches!(effects.as_slice(), [SessionFx::Capture { req: 29, epoch: 1, request: SessionReadRequest::ProfilePolicy }])); + } else { assert!(effects.is_empty()); } + } + } + } + } + + #[test] + fn attempt_runtime_historical_tiles_are_not_selection_authority() { + for phase in [Phase::Idle, Phase::Creating, Phase::Waiting, Phase::Discovering, + Phase::Ready, Phase::Error, Phase::Deleted] { + let init = fixture(phase, None); + let expected = serde_json::to_value(&init).unwrap(); + let mut owner = SessionMachine::from_init(init); + let publication = owner.publication(); + let effects = super::super::scenarios::step(&mut owner, + SessionEvent::Command(Command::SelectProfile { index: 0, pin: None })); + assert!(effects.is_empty()); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), expected); + assert!(Arc::ptr_eq(&publication, &owner.publication())); + } + } + + #[test] + fn attempt_runtime_ready_history_cannot_reactivate_a_legacy_login_claim() { + use super::super::super::{LoginProgress, observation::Observation}; + use plx_machine::machine::RequestId; + let mut init = fixture(Phase::Ready, None); + init.persisted.account_token = "synthetic-stored-account".into(); + init.apply_pending = false; + let key = SessionWorkKey { epoch: init.epoch, op: SessionOp::Login }; + init.pending.insert(31, Pending { key, expected: Identity::of(&init.persisted), lifecycle: None, + last_arrival: None, phase: StreamPhase::Running, capture: None, + admission: AdmissionState::Awaiting(AdmissionId(31)) }); + let expected = serde_json::to_value(&init).unwrap(); + let hash = init.hash(); + let epoch = init.epoch; + for (terminal, progress) in [ + (false, LoginProgress::CodeReady { epoch, code: "STALE".into(), qr_png: vec![99] }), + (false, LoginProgress::Authorized { epoch, token: "synthetic-stale-token".into() }), + (true, LoginProgress::Failed { epoch, message: "stale failure".into(), + incident: IncidentContext::internal(InternalClass::WorkerDropped), plaintext: None, account: None }), + ] { + let mut owner = SessionMachine::from_init(init.clone()); + assert!(owner.snapshot_init().signin_active && owner.snapshot_init().authorized_in_flow); + assert!(!owner.state.active_signin()); + assert!(!owner.state.fresh_authority()); + assert!(!owner.work_is_current(31, key, AdmissionId(31))); + let publication = owner.publication(); + let envelope = SessionEnvelope { addr: Addr { to: MachineId::Session, req: RequestId(31) }, key, + admission: AdmissionId(31), arrival: 1, terminal, lifecycle: None, + outcome: SessionArrival::Data(Arc::new(Observation::Login(progress))) }; + let receipt = Receipt::of(&envelope); + let effects = super::super::scenarios::step(&mut owner, SessionEvent::Result(envelope)); + assert!(matches!(effects.as_slice(), [SessionFx::Acknowledge(receipts)] if receipts == &vec![receipt])); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), expected); + assert_eq!(owner.snapshot_init().signin_account, init.signin_account); + assert_eq!(owner.subhash(), hash); + assert!(Arc::ptr_eq(&publication, &owner.publication())); + } + } + + #[test] + fn attempt_runtime_ready_history_cannot_authorize_capture_admission_or_commit() { + use plx_machine::machine::RequestId; + let mut init = fixture(Phase::Ready, None); + init.apply_pending = false; + let key = SessionWorkKey { epoch: init.epoch, op: SessionOp::Login }; + init.pending.insert(31, Pending { key, expected: Identity::of(&init.persisted), lifecycle: None, + last_arrival: None, phase: StreamPhase::Running, capture: Some(CaptureIntent::Login), + admission: AdmissionState::Awaiting(AdmissionId(31)) }); + init.pending_commit = Some(PendingCommit { req: 31, epoch: init.epoch, arrival: 5, terminal: true, + writes_credentials: false, receipt: None, + delta: CommitDelta { phase: Some(Phase::Profiles), users: Some(Vec::new()), ..Default::default() }, + admitted_revision: None, purpose: None, fresh: false }); + let expected = serde_json::to_value(&init).unwrap(); + let mut owner = SessionMachine::from_init(init); + assert!(!owner.read_is_current(31, key.epoch, SessionReadRequest::LoginClientId)); + assert!(!owner.commit_is_current(31, key.epoch, 5)); + assert!(owner.commit_permit(31, key.epoch, 5).is_none()); + let publication = owner.publication(); + let addr = Addr { to: MachineId::Session, req: RequestId(31) }; + for event in [ + SessionEvent::Read(SessionReadReply { addr, epoch: key.epoch, value: SessionReadValue::LoginClientId("stale-client".into()) }), + SessionEvent::Admission(AdmissionReply { addr, key, correlation: AdmissionId(31), accepted: true }), + SessionEvent::Commit(CommitReply { req: 31, epoch: key.epoch, arrival: 5, admission: CommitAdmission::RegistryOnly }), + ] { + assert!(super::super::scenarios::step(&mut owner, event).is_empty()); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), expected); + assert!(Arc::ptr_eq(&publication, &owner.publication())); + } + } + + #[test] + fn attempt_runtime_foreground_commit_claims_require_the_phase_owned_slot() { + for (phase, op) in [(Phase::Idle, SessionOp::DevBoundary), (Phase::Idle, SessionOp::Ready), + (Phase::Profiles, SessionOp::Picker), (Phase::Ready, SessionOp::Ready), + (Phase::Ready, SessionOp::DevBoundary), (Phase::Ready, SessionOp::Picker), + (Phase::Profiles, SessionOp::Ready), (Phase::Error, SessionOp::DevBoundary)] { + let mut init = fixture(phase, None); + init.apply_pending = false; + let key = SessionWorkKey { epoch: init.epoch, op }; + init.pending.insert(41, Pending { key, expected: Identity::of(&init.persisted), lifecycle: None, + last_arrival: None, phase: StreamPhase::Running, capture: None, admission: AdmissionState::NotRequested }); + let delta = match op { + SessionOp::DevBoundary => CommitDelta { dev: Some(DevCommitDelta::Activated), ..Default::default() }, + SessionOp::Ready => CommitDelta { phase: (phase == Phase::Idle).then_some(Phase::Ready), ready: Some(false), activate_profile: true, ..Default::default() }, + SessionOp::Picker => CommitDelta { users: Some(Vec::new()), ..Default::default() }, + SessionOp::Login | SessionOp::Rediscover | SessionOp::HomeRoster | SessionOp::ServerRoster + | SessionOp::ProfileSwitch | SessionOp::Endpoint(_) => unreachable!(), + }; + init.pending_commit = Some(PendingCommit { req: 41, epoch: init.epoch, arrival: 3, terminal: true, + writes_credentials: false, receipt: None, delta, admitted_revision: None, purpose: None, fresh: false }); + let expected = serde_json::to_value(&init).unwrap(); + let hash = init.hash(); + let mut owner = SessionMachine::from_init(init); + let publication = owner.publication(); + assert!(!owner.commit_is_current(41, key.epoch, 3), "{phase:?}"); + assert!(owner.commit_permit(41, key.epoch, 3).is_none()); + let effects = super::super::scenarios::step(&mut owner, SessionEvent::Commit(CommitReply { + req: 41, epoch: key.epoch, arrival: 3, admission: CommitAdmission::RegistryOnly })); + assert!(effects.is_empty()); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), expected); + assert_eq!(owner.subhash(), hash); + assert!(Arc::ptr_eq(&publication, &owner.publication())); + } + } + + #[test] + fn attempt_runtime_foreground_commit_owners_survive_compatibility_import() { + for case in 0..4 { + let mut persisted = PersistedSession { client_id: "synthetic-client".into(), account_token: "synthetic-account".into(), ..Default::default() }; + persisted.server.address = "127.0.0.1".into(); persisted.server.port = 32400; + persisted.server.token = "synthetic-pms".into(); persisted.user.token = "synthetic-pms".into(); + let mut init = SessionInit::captured(persisted); + let command = match case { + 0 => { init.authority = BootstrapAuthority::DevPms { primary: init.persisted.server.clone(), extras: Vec::new() }; Command::ActivateDevBootstrap } + 1 => Command::ResumeStored, + 2 => Command::StartSwitch(Picker::Boot), + _ => { init.phase = Phase::Ready; init.apply_pending = true; Command::TakeReady } + }; + let mut owner = SessionMachine::from_init(init); + let effects = super::super::scenarios::step(&mut owner, SessionEvent::Command(command)); + assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Commit { .. }))); + let captured = owner.snapshot_init(); + let commit = captured.pending_commit.as_ref().unwrap(); + let reply = CommitReply { req: commit.req, epoch: commit.epoch, arrival: commit.arrival, admission: CommitAdmission::RegistryOnly }; + let bytes = serde_json::to_vec(&captured).unwrap(); + let decoded: SessionInit = serde_json::from_slice(&bytes).unwrap(); + let mut restored = SessionMachine::from_init(decoded); + assert!(owner.commit_is_current(reply.req, reply.epoch, reply.arrival)); + assert!(restored.commit_is_current(reply.req, reply.epoch, reply.arrival)); + let original_fx = super::super::scenarios::step(&mut owner, SessionEvent::Commit(reply)); + let restored_fx = super::super::scenarios::step(&mut restored, SessionEvent::Commit(reply)); + assert_eq!(serde_json::to_value(&original_fx).unwrap(), serde_json::to_value(&restored_fx).unwrap()); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), serde_json::to_value(restored.snapshot_init()).unwrap()); + assert_eq!(owner.subhash(), restored.subhash()); + assert_eq!(serde_json::to_vec(&captured).unwrap(), bytes); + } + } + +} diff --git a/rust-modules/session/src/auth/owner/attempt_characterization_tests.rs b/rust-modules/session/src/auth/owner/attempt_characterization_tests.rs index 65aae32ef3..7cc404b3e9 100644 --- a/rust-modules/session/src/auth/owner/attempt_characterization_tests.rs +++ b/rust-modules/session/src/auth/owner/attempt_characterization_tests.rs @@ -23,7 +23,11 @@ fn safe_effect_diagnostics(effects: &[SessionFx]) -> Vec { SessionFx::BackReply { to, resumed } => format!("{kind:?} instance={} correlation={} resumed={resumed}", to.instance, to.correlation), - _ => format!("{kind:?}"), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Ready { .. } + | SessionFx::Capture { .. } | SessionFx::PublishProfile(_) | SessionFx::Coordinator(_) + | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => format!("{kind:?}"), } }).collect() } @@ -68,11 +72,11 @@ fn command(owner: &mut SessionMachine, command: Command) -> Vec { fn envelope(owner: &SessionMachine, req: u32, arrival: u64, terminal: bool, data: Observation) -> SessionEnvelope { SessionEnvelope { addr: Addr { to: MachineId::Session, req: RequestId(req) }, - key: owner.state.pending[&req].key, admission: AdmissionId(req), arrival, terminal, + key: owner.common.pending[&req].key, admission: AdmissionId(req), arrival, terminal, lifecycle: None, outcome: SessionArrival::Data(Arc::new(data)) } } fn login(owner: &mut SessionMachine, arrival: u64, progress: LoginProgress, terminal: bool) -> SessionEnvelope { - let e = envelope(owner, owner.state.next_req, arrival, terminal, Observation::Login(progress)); + let e = envelope(owner, owner.common.next_req, arrival, terminal, Observation::Login(progress)); let effects = step(owner, SessionEvent::Result(e.clone())); assert!(matches!(effects.as_slice(), [SessionFx::Acknowledge(r)] if r == &vec![Receipt::of(&e)])); e @@ -85,7 +89,7 @@ fn start(owner: &mut SessionMachine) -> u64 { admission: AdmissionId(1), input: SessionWork::Login { client_id } }] if requests.is_empty() && client_id == "synthetic-client")); assert_eq!(owner.read().0.phase, Phase::Creating); - owner.state.epoch + owner.common.epoch } fn waiting(owner: &mut SessionMachine) -> u64 { let epoch = start(owner); @@ -101,6 +105,49 @@ fn durable() -> CompletionOutcome { outcome: PersistOutcome::PersistedPlaintext, verified: true, protection: None }) } +#[test] +fn arbitrary_legacy_phases_and_erasing_roundtrip_without_normalizing_residue() { + for phase in [Phase::Idle, Phase::Creating, Phase::Waiting, Phase::Discovering, Phase::Profiles, + Phase::Switching, Phase::Ready, Phase::Error, Phase::Deleted] { + for erasing in [false, true] { + let mut init = captured(); + init.phase = phase; + init.pending_erase = erasing.then_some((73, true)); + init.picker = Picker::ChangeProfile; + init.pin_code = "synthetic-code".into(); + init.qr_png = vec![1, 2, 3]; + init.qr_gen = 9; + init.code_replaced = true; + init.link_trouble = true; + init.users = vec![UserTile { uuid: "synthetic-retained".into(), ..Default::default() }]; + init.error = "synthetic-error".into(); + init.pin_denied = true; + init.signin_active = true; + init.authorized_in_flow = true; + init.persistence_warning_answered = true; + init.apply_pending = true; + init.signin_account = Some("Synthetic Hidden Name".into()); + let mut owner = SessionMachine::from_init(init.clone()); + assert_eq!(owner.read().0.phase, phase); + let restored = owner.snapshot_init(); + assert_eq!(serde_json::to_value(&restored).unwrap(), serde_json::to_value(&init).unwrap()); + assert_eq!(restored.signin_account, init.signin_account); + let wire = serde_json::to_value(&restored).unwrap(); + assert!(wire.get("signin_account").is_none()); + let decoded: SessionInit = serde_json::from_value(wire).unwrap(); + assert!(decoded.signin_account.is_none()); + assert_eq!(decoded.hash(), init.hash()); + assert_eq!(owner.subhash(), init.hash()); + assert!(command(&mut owner, Command::DismissPinError).is_empty()); + init.pin_denied = false; + let after = owner.snapshot_init(); + assert_eq!(serde_json::to_value(&after).unwrap(), serde_json::to_value(&init).unwrap()); + assert_eq!(after.signin_account, init.signin_account); + assert_eq!(owner.subhash(), init.hash()); + } + } +} + #[test] fn qr_waiting_replacement_discovery_and_duplicate_receipts() { let mut owner = SessionMachine::from_init(captured()); @@ -119,8 +166,8 @@ fn qr_waiting_replacement_discovery_and_duplicate_receipts() { assert_eq!(owner.read().0.qr_generation, 2); login(&mut owner, 4, LoginProgress::Authorized { epoch, token: "synthetic-new-account".into() }, false); assert_eq!(owner.read().0.phase, Phase::Discovering); - assert!(owner.state.authorized_in_flow); - assert_eq!(owner.state.pending[&1].expected.account_token, "synthetic-new-account"); + assert!(owner.state.projected_authorization()); + assert_eq!(owner.common.pending[&1].expected.account_token, "synthetic-new-account"); assert_eq!(&*retained.code, "TEST"); assert_eq!(&*retained.png, &[1, 2, 3]); // Authorization does NOT clear the old QR payload in today's flat state. @@ -174,11 +221,11 @@ fn back_cancels_login_but_only_resumes_committed_credentials() { SessionFx::Coordinator(CoordinatorAction::SignInCancelled), SessionFx::BackReply { to: ReplyTo { instance: 4, correlation: 9 }, resumed: true }] if requests == &vec![1]), "BACK effects: {:?}", safe_effect_diagnostics(&fx)); - assert_eq!(owner.state.persisted.account_token, "synthetic-account"); - assert_eq!(owner.state.persisted.user.uuid, "synthetic-saved-profile"); - assert_eq!(owner.state.persisted.server.token, "synthetic-pms"); + assert_eq!(owner.common.persisted.account_token, "synthetic-account"); + assert_eq!(owner.common.persisted.user.uuid, "synthetic-saved-profile"); + assert_eq!(owner.common.persisted.server.token, "synthetic-pms"); assert_eq!(owner.read().0.phase, Phase::Ready); - assert!(owner.state.apply_pending); + assert!(owner.state.handoff_pending()); assert!(owner.read().0.code.is_empty()); assert!(owner.read().0.png.is_empty()); assert_eq!(owner.read().0.qr_generation, 0); @@ -213,13 +260,13 @@ fn erase_is_ordered_and_stale_completions_do_not_finish_it() { assert!(owner.read().0.code.is_empty()); assert!(owner.read().0.png.is_empty()); assert_eq!(owner.read().0.qr_generation, 0); - assert!(owner.state.users.is_empty()); - assert!(owner.state.error.is_empty()); - assert!(!owner.state.apply_pending); - assert!(owner.state.persisted.account_token.is_empty()); + assert!(owner.state.picker_data().users.is_empty()); + assert!(owner.state.picker_data().error.is_empty()); + assert!(!owner.state.handoff_pending()); + assert!(owner.common.persisted.account_token.is_empty()); assert!(command(&mut owner, Command::StartLogin).is_empty()); assert!(step(&mut owner, SessionEvent::Erased { epoch: 2, leftovers: 99 }).is_empty()); - assert!(owner.state.pending_erase.is_some()); + assert!(owner.state.pending_erase().is_some()); let fx = step(&mut owner, SessionEvent::Erased { epoch: 3, leftovers: 2 }); assert!(matches!(fx.as_slice(), [SessionFx::Coordinator(CoordinatorAction::LocalDataErased)])); assert_eq!(owner.read().0.phase, Phase::Deleted); @@ -251,7 +298,13 @@ fn picker() -> SessionMachine { SessionFx::Commit { .. }, SessionFx::Work { input: SessionWork::ServerRoster { .. }, .. }, SessionFx::Work { input: SessionWork::HomeRoster { .. }, .. }])); let reply = fx.iter().find_map(|f| match f { SessionFx::Commit { req, epoch, arrival, .. } => - Some(CommitReply { req: *req, epoch: *epoch, arrival: *arrival, admission: CommitAdmission::RegistryOnly }), _ => None }).unwrap(); + Some(CommitReply { req: *req, epoch: *epoch, arrival: *arrival, admission: CommitAdmission::RegistryOnly }), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } | SessionFx::Ready { .. } + | SessionFx::Capture { .. } | SessionFx::Work { .. } | SessionFx::Cancel { .. } + | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } | SessionFx::Coordinator(_) + | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None }).unwrap(); let settled = step(&mut owner, SessionEvent::Commit(reply)); assert!(matches!(settled.as_slice(), [SessionFx::Retire { .. }])); owner @@ -266,15 +319,15 @@ fn profiles_selection_capture_pin_failure_and_root_back() { SessionFx::Capture { request: SessionReadRequest::ProfilePolicy, .. }, SessionFx::SelectionReply { to: ReplyTo { instance: 5, correlation: 6 }, accepted: true, .. }])); assert_eq!(owner.read().0.phase, Phase::Switching); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; let fx = step(&mut owner, SessionEvent::Read(SessionReadReply { addr: Addr { to: MachineId::Session, req: RequestId(req) }, epoch, value: SessionReadValue::ProfilePolicy { recently_unreachable: false } })); assert!(matches!(fx.as_slice(), [SessionFx::Work { req: r, input: SessionWork::ProfileSwitch { pin: Some(p), .. }, .. }] if *r == req && p == "0000")); let e = envelope(&owner, req, 1, true, Observation::ProfileSwitch(super::super::ProfileSwitchProgress { - epoch, expected: super::super::SessionIdentity::of(&owner.state.persisted), + epoch, expected: super::super::SessionIdentity::of(&owner.common.persisted), outcome: super::super::ProfileSwitchOutcomeProgress::Failed { error: "synthetic-pin-denied".into(), pin_denied: true } })); let fx = step(&mut owner, SessionEvent::Result(e.clone())); assert!(matches!(fx.as_slice(), [SessionFx::Retire { req: r }, SessionFx::Acknowledge(rs)] @@ -315,38 +368,38 @@ fn stored_ready_admission_is_not_durability_and_background_is_not_saved_login() let fx = step(&mut owner, SessionEvent::Commit(reply)); assert!(matches!(fx.as_slice(), [SessionFx::PublishProfile(_), SessionFx::Ready { .. }, SessionFx::Retire { .. }])); assert_eq!(owner.read().0.phase, Phase::Ready); - assert!(!owner.state.commit_phase.admitted); - assert!(!owner.state.commit_phase.durable); + assert!(!owner.common.commit_phase.admitted); + assert!(!owner.common.commit_phase.durable); // Actual supported refresh command, with an ordinary synthetic HomeRoster result. let mut owner = picker(); - let req = owner.state.pending.iter().find(|(_, p)| p.key.op == SessionOp::HomeRoster).unwrap().0.to_owned(); - let epoch = owner.state.epoch; + let req = owner.common.pending.iter().find(|(_, p)| p.key.op == SessionOp::HomeRoster).unwrap().0.to_owned(); + let epoch = owner.common.epoch; let e = envelope(&owner, req, 1, true, Observation::HomeRoster(super::super::HomeRosterProgress { - epoch, expected: super::super::SessionIdentity::of(&owner.state.persisted), + epoch, expected: super::super::SessionIdentity::of(&owner.common.persisted), users: Some(vec![UserTile { uuid: "synthetic-other".into(), ..Default::default() }]) })); let fx = step(&mut owner, SessionEvent::Result(e.clone())); let reply = commit_reply(&fx, CommitAdmission::Admitted { revision: 7, purpose: PersistencePurpose::Background }); let fx = step(&mut owner, SessionEvent::Commit(reply)); assert!(matches!(fx.as_slice(), [SessionFx::Retire { .. }, SessionFx::Acknowledge(rs)] if rs == &vec![Receipt::of(&e)])); - assert!(owner.state.commit_phase.admitted && !owner.state.commit_phase.durable); + assert!(owner.common.commit_phase.admitted && !owner.common.commit_phase.durable); let completion = PersistenceCompletion { req, epoch, arrival: 1, revision: 7, purpose: PersistencePurpose::Background, outcome: durable() }; assert!(step(&mut owner, SessionEvent::Persistence(PersistenceCompletion { revision: 8, ..completion })).is_empty()); - assert!(!owner.state.commit_phase.durable); + assert!(!owner.common.commit_phase.durable); assert!(step(&mut owner, SessionEvent::Persistence(completion)).is_empty()); - assert!(owner.state.commit_phase.durable); - assert!(!owner.state.commit_phase.proves_saved_login); + assert!(owner.common.commit_phase.durable); + assert!(!owner.common.commit_phase.proves_saved_login); } #[test] fn superseded_durable_disk_evidence_never_seats_the_superseded_identity() { let mut owner = SessionMachine::from_init(captured()); - let before = owner.state.disk_identity.clone(); + let before = owner.common.disk_identity.clone(); let after = Identity { account_token: "synthetic-superseded".into(), ..before.clone() }; let retained = owner.publication(); assert!(step(&mut owner, SessionEvent::DiskWrite { before: before.clone(), after: after.clone(), outcome: durable() }).is_empty()); - assert!(owner.state.disk_identity == after); - assert_eq!(owner.state.persisted.account_token, ""); + assert!(owner.common.disk_identity == after); + assert_eq!(owner.common.persisted.account_token, ""); assert!(Arc::ptr_eq(&retained, &owner.publication())); assert!(step(&mut owner, SessionEvent::DiskWrite { before, after, outcome: durable() }).is_empty()); } @@ -416,8 +469,8 @@ fn v5_boot_roundtrip_and_frozen_canonical_field_order() { fn profile_seating_revokes_once_and_late_roster_is_same_identity_refresh() { let mut owner = picker(); command(&mut owner, Command::SelectProfile { index: 0, pin: None }); - let req = owner.state.next_req; - let epoch = owner.state.epoch; + let req = owner.common.next_req; + let epoch = owner.common.epoch; step(&mut owner, SessionEvent::Read(SessionReadReply { addr: Addr { to: MachineId::Session, req: RequestId(req) }, epoch, value: SessionReadValue::ProfilePolicy { recently_unreachable: false } })); @@ -425,7 +478,7 @@ fn profile_seating_revokes_once_and_late_roster_is_same_identity_refresh() { machine_id: "synthetic-server".into(), address: "127.0.0.1".into(), port: 32400, token: "synthetic-profile-token".into(), owned: true, ..Default::default() }; let e = envelope(&owner, req, 1, false, Observation::ProfileSwitch(super::super::ProfileSwitchProgress { - epoch, expected: super::super::SessionIdentity::of(&owner.state.persisted), + epoch, expected: super::super::SessionIdentity::of(&owner.common.persisted), outcome: super::super::ProfileSwitchOutcomeProgress::Ready { delta: super::super::ProfileDelta { server: super::super::server_ref(&primary), sources: vec![primary.clone()], user: UserRef { uuid: "synthetic-other".into(), @@ -437,8 +490,8 @@ fn profile_seating_revokes_once_and_late_roster_is_same_identity_refresh() { let fx = step(&mut owner, SessionEvent::Commit(reply)); assert!(matches!(fx.as_slice(), [SessionFx::Acknowledge(rs)] if rs == &vec![Receipt::of(&e)])); assert_eq!(owner.read().0.phase, Phase::Ready); - assert!(owner.state.pending[&req].phase == StreamPhase::ProfileSeated); - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + assert!(owner.common.pending[&req].phase == StreamPhase::ProfileSeated); + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let plan = scenarios::late_profile_roster(&mut owner, req, epoch, &primary, expected); assert!(matches!(plan.registry.as_slice(), [RegistryPlan::Install { commit: RosterCommit::Refresh { same_identity: true }, .. }])); @@ -465,20 +518,20 @@ fn failure_readout_survives_resuming_back_erase_and_deleted() { let fx = step(&mut owner, SessionEvent::Result(failed.clone())); assert!(matches!(fx.as_slice(), [SessionFx::Coordinator(CoordinatorAction::SignInFailed { phase: Phase::Discovering }), SessionFx::Acknowledge(rs)] if rs == &vec![Receipt::of(&failed)]), "{:?}", safe_effect_diagnostics(&fx)); - let readout = serde_json::to_vec(&owner.state.plaintext).unwrap(); + let readout = serde_json::to_vec(&owner.state.plaintext()).unwrap(); let fx = command(&mut owner, Command::BackAtRoot { reply: ReplyTo { instance: 1, correlation: 2 } }); // Terminal Failed already retired login; signin_active was consumed by SignInFailed. assert!(matches!(fx.as_slice(), [SessionFx::Cancel { requests, epoch: 3 }, SessionFx::BackReply { resumed: true, .. }] if requests.is_empty()), "{:?}", safe_effect_diagnostics(&fx)); assert_eq!(owner.read().0.phase, Phase::Ready); - assert_eq!(owner.state.persisted.account_token, "synthetic-account"); + assert_eq!(owner.common.persisted.account_token, "synthetic-account"); for phase in [Phase::Ready, Phase::Ready, Phase::Deleted] { assert_eq!(owner.read().0.phase, phase); - assert_eq!(serde_json::to_vec(&owner.state.plaintext).unwrap(), readout); - assert_eq!(owner.state.signin_account.as_deref(), Some("Synthetic Person")); + assert_eq!(serde_json::to_vec(&owner.state.plaintext()).unwrap(), readout); + assert_eq!(owner.state.signin_account().as_deref(), Some("Synthetic Person")); // readout_account:845-847 hides the retained private name outside the no-server Error. assert!(owner.read().0.account.is_none()); - if owner.state.pending_erase.is_some() { + if owner.state.pending_erase().is_some() { let fx = step(&mut owner, SessionEvent::Erased { epoch: 4, leftovers: 1 }); assert!(matches!(fx.as_slice(), [SessionFx::Coordinator(CoordinatorAction::LocalDataErased)]), "{:?}", safe_effect_diagnostics(&fx)); } else if phase == Phase::Ready { @@ -487,7 +540,7 @@ fn failure_readout_survives_resuming_back_erase_and_deleted() { SessionFx::Cancel { requests, epoch: 4 }, SessionFx::PublishProfile(_), SessionFx::Erase { epoch: 4, all_local: true, .. }] if requests.is_empty()), "{:?}", safe_effect_diagnostics(&fx)); assert!(owner.read().0.code.is_empty()); - assert!(!owner.state.apply_pending); + assert!(!owner.state.handoff_pending()); } } } @@ -503,16 +556,16 @@ fn discovery_retry_is_live_restorable_but_epoch_advance_clears_it() { let init = owner.snapshot_init(); let mut restored = SessionMachine::from_init(init.clone()); assert_eq!(restored.subhash(), init.hash()); - assert_eq!(restored.state.discovery_retry.unwrap().elapsed_ms, 1234); + assert_eq!(restored.state.discovery_retry().unwrap().elapsed_ms, 1234); let fx = command(&mut restored, Command::EraseLocal); assert!(matches!(fx.as_slice(), [SessionFx::Coordinator(CoordinatorAction::CloseTelemetry), SessionFx::Cancel { epoch: 3, .. }, SessionFx::PublishProfile(_), SessionFx::Erase { epoch: 3, .. }]), "{:?}", safe_effect_diagnostics(&fx)); // Important source correction: advance_epoch:1789 explicitly clears this anchor. - assert!(restored.state.discovery_retry.is_none()); + assert!(restored.state.discovery_retry().is_none()); assert_eq!(restored.read().0.phase, Phase::Discovering); step(&mut restored, SessionEvent::Erased { epoch: 3, leftovers: 0 }); assert_eq!(restored.read().0.phase, Phase::Deleted); - assert!(restored.state.discovery_retry.is_none()); + assert!(restored.state.discovery_retry().is_none()); assert!(serde_json::to_vec(&init).unwrap().as_slice() == include_bytes!("fixtures/legacy-v5/live.json"), "legacy V5 bytes differ for live"); assert_eq!(init.hash(), 18001482832323156010); @@ -535,31 +588,31 @@ fn fresh_final_warning_holds_publication_until_addressed_continue() { let reply = commit_reply(&fx, CommitAdmission::Admitted { revision: 1, purpose: PersistencePurpose::Discovery }); let fx = step(&mut owner, SessionEvent::Commit(reply)); assert!(!fx.iter().any(|f| matches!(f, SessionFx::PublishProfile(_) | SessionFx::Ready { .. })), "{:?}", safe_effect_diagnostics(&fx)); - assert!(owner.state.authorized_in_flow); + assert!(owner.state.projected_authorization()); assert!(step(&mut owner, SessionEvent::Persistence(PersistenceCompletion { req: reply.req, epoch, arrival: 3, revision: 1, purpose: PersistencePurpose::Discovery, outcome: durable() })).is_empty()); let fx = command(&mut owner, Command::TakeReady); assert!(matches!(fx.as_slice(), [SessionFx::Commit { plan, .. }] if plan.authority == plx_plex::plex::session::SaveAuthority::FreshReauthentication), "{:?}", safe_effect_diagnostics(&fx)); - assert!(!owner.state.authorized_in_flow); + assert!(!owner.state.projected_authorization()); let reply = commit_reply(&fx, CommitAdmission::Admitted { revision: 2, purpose: PersistencePurpose::Final }); let fx = step(&mut owner, SessionEvent::Commit(reply)); assert!(matches!(fx.as_slice(), [SessionFx::Retire { req }] if *req == reply.req), "{:?}", safe_effect_diagnostics(&fx)); - assert!(owner.state.held_handoff.is_some()); + assert!(owner.common.held_handoff.is_some()); let completion = PersistenceCompletion { req: reply.req, epoch, arrival: 0, revision: 2, purpose: PersistencePurpose::Final, outcome: CompletionOutcome::Failed(Failure::Persistence(PersistOutcome::WriteFailed)) }; assert!(step(&mut owner, SessionEvent::Persistence(PersistenceCompletion { revision: 3, ..completion })).is_empty()); - assert!(owner.state.persistence_warning.is_none()); + assert!(owner.common.persistence_warning.is_none()); assert!(step(&mut owner, SessionEvent::Persistence(completion)).is_empty()); - let key = owner.state.persistence_warning.unwrap().key; + let key = owner.common.persistence_warning.unwrap().key; let fx = command(&mut owner, Command::BackAtRoot { reply: ReplyTo { instance: 2, correlation: 3 } }); assert!(matches!(fx.as_slice(), [SessionFx::BackReply { resumed: false, .. }]), "{:?}", safe_effect_diagnostics(&fx)); assert!(command(&mut owner, Command::TakeReady).is_empty()); let fx = command(&mut owner, Command::AcknowledgePersistenceWarning { key }); assert!(matches!(fx.as_slice(), [SessionFx::PublishProfile(_), SessionFx::Ready { .. }]), "{:?}", safe_effect_diagnostics(&fx)); - assert!(owner.state.held_handoff.is_none()); - assert!(!owner.state.commit_phase.proves_saved_login); + assert!(owner.common.held_handoff.is_none()); + assert!(!owner.common.commit_phase.proves_saved_login); assert!(command(&mut owner, Command::AcknowledgePersistenceWarning { key }).is_empty()); } @@ -577,16 +630,16 @@ fn busy_commit_retains_fifo_and_supersession_returns_each_credit_once() { for record in [&second, &third, &second] { assert!(step(&mut owner, SessionEvent::Result(record.clone())).is_empty()); } - assert!(owner.state.inbox.iter().map(Receipt::of).collect::>() == + assert!(owner.common.inbox.iter().map(Receipt::of).collect::>() == vec![Receipt::of(&second), Receipt::of(&third)]); - assert!(!owner.state.pump_pending); - assert_eq!(owner.state.pending[&1].last_arrival, Some(3)); + assert!(!owner.common.pump_pending); + assert_eq!(owner.common.pending[&1].last_arrival, Some(3)); let fx = command(&mut owner, Command::StartLogin); // discard_owned_envelopes drains FIFO first, then returns the commit's owned receipt. assert!(matches!(fx.as_slice(), [SessionFx::Cancel { epoch: 2, .. }, SessionFx::Acknowledge(rs), SessionFx::Cancel { epoch: 3, .. }, SessionFx::Coordinator(CoordinatorAction::SignInStarted), SessionFx::Work { .. }] if rs == &vec![Receipt::of(&second), Receipt::of(&third), Receipt::of(&e)]), "{:?}", safe_effect_diagnostics(&fx)); - assert!(owner.state.inbox.is_empty()); + assert!(owner.common.inbox.is_empty()); assert!(owner.commit_permit(old.req, old.epoch, old.arrival).is_none()); assert!(step(&mut owner, SessionEvent::Commit(old)).is_empty()); } @@ -616,3 +669,52 @@ fn nested_v5_prior_writer_golden_probe() { assert_eq!(SessionMachine::from_init(private).snapshot_init().signin_account.as_deref(), Some("Synthetic Hidden Name")); } + +#[test] +fn restored_accepted_discovery_keeps_stream_authority_and_matching_retry_fence() { + let mut original = SessionMachine::from_init(captured()); + let epoch = waiting(&mut original); + let req = original.common.next_req; + let key = original.common.pending[&req].key; + let admission = AdmissionReply { addr: Addr { to: MachineId::Session, req: RequestId(req) }, + key, correlation: AdmissionId(req), accepted: true }; + assert!(step(&mut original, SessionEvent::Admission(admission)).is_empty()); + assert!(original.common.pending[&req].admission == AdmissionState::Accepted(AdmissionId(req))); + login(&mut original, 2, LoginProgress::Authorized { epoch, token: "synthetic-account".into() }, false); + login(&mut original, 3, LoginProgress::DiscoveryTrouble { epoch, + progress: super::super::DiscoveryRetryProgress { + run: super::super::DiscoveryRetryRun::Resources, misses: 2, elapsed_ms: 1234 } }, false); + let mut restored = SessionMachine::from_init(original.snapshot_init()); + assert_eq!(original.subhash(), restored.subhash()); + assert_eq!(restored.common.pending[&req].last_arrival, Some(3)); + assert!(restored.common.pending[&req].admission == AdmissionState::Accepted(AdmissionId(req))); + for (arrival, run) in [(4, super::super::DiscoveryRetryRun::HomeUsers), + (5, super::super::DiscoveryRetryRun::Resources)] { + let record = envelope(&original, req, arrival, false, + Observation::Login(LoginProgress::DiscoveryRetrySettled { epoch, run })); + let original_fx = step(&mut original, SessionEvent::Result(record.clone())); + let restored_fx = step(&mut restored, SessionEvent::Result(record)); + assert_eq!(serde_json::to_value(original_fx).unwrap(), serde_json::to_value(restored_fx).unwrap()); + assert_eq!(serde_json::to_value(original.snapshot_init()).unwrap(), + serde_json::to_value(restored.snapshot_init()).unwrap()); + assert_eq!(original.subhash(), restored.subhash()); + assert_eq!(restored.read().0.discovery_retry.is_some(), arrival == 4); + } +} + +#[test] +fn restored_empty_waiting_and_ready_do_not_invent_work_or_handoff() { + for phase in [Phase::Waiting, Phase::Ready] { + let mut init = captured(); + init.phase = phase; + init.signin_account = Some("Synthetic Hidden Name".into()); + let mut owner = SessionMachine::from_init(init.clone()); + let previous = owner.publication(); + assert!(command(&mut owner, Command::TakeReady).is_empty()); + assert!(Arc::ptr_eq(&previous, &owner.publication())); + let after = owner.snapshot_init(); + assert_eq!(serde_json::to_value(&after).unwrap(), serde_json::to_value(&init).unwrap()); + assert_eq!(after.signin_account, init.signin_account); + assert_eq!(owner.subhash(), init.hash()); + } +} diff --git a/rust-modules/session/src/auth/owner/incident.rs b/rust-modules/session/src/auth/owner/incident.rs index fadebd8cfa..1855670808 100644 --- a/rust-modules/session/src/auth/owner/incident.rs +++ b/rust-modules/session/src/auth/owner/incident.rs @@ -56,7 +56,7 @@ //! screen only renders the state; it never samples telemetry. //! * Sign-out and *Delete all local data* erase the offer and the seen keys with everything else. -use super::{Command, SessionFx, SessionMachine}; +use super::{Command, SessionFx, SessionMachine, SessionEvent}; use plx_telemetry::telemetry::consent::Permission; use plx_telemetry::telemetry::incident::{IncidentContext, IncidentKind, LinkClass}; use plx_machine::machine::Canon; @@ -179,10 +179,10 @@ pub enum IncidentDelivery { /// How many distinct keys a launch remembers. The closed kind × link space is small; the bound /// only stops a pathological loop from growing state without limit. -const SEEN_CAP: usize = 32; +pub(super) const SEEN_CAP: usize = 32; /// Has the question about this offer been settled — answered, sent, or decided by the consent? -fn is_settled(offer: &IncidentOffer) -> bool { +pub(super) fn is_settled(offer: &IncidentOffer) -> bool { !matches!( offer.state, IncidentState::Pending | IncidentState::Offered { .. } | IncidentState::OnRequest { .. } @@ -284,164 +284,42 @@ impl SessionMachine { /// A producer's failure, with its closed evidence. See the module doc for the rules: the /// failure already held keeps its offer and its answer; anything else supersedes what is /// held — a key this launch has already resolved included, which is then resolved quietly. - pub fn raise_incident(&mut self, flow: IncidentFlow, context: IncidentContext) { - let key = IncidentKey { flow, kind: context.kind, link: context.link }; - if let Some(held) = self.state.incident.as_mut().filter(|held| held.key == key) { - // The same failure again. Unresolved (a second stalled report in one wait): keep the - // offer, take the fresher report evidence. Resolved: keep the answer and report - // evidence it already has. Details always reads the current failure facts. - held.readout_context = Some(context); - if !is_settled(held) { - held.context = Some(context); - } - return; - } - self.state.next_incident = self.state.next_incident.wrapping_add(1).max(1); - self.state.incident = Some(IncidentOffer { - id: self.state.next_incident, - key, - context: Some(context), - readout_context: Some(context), - state: IncidentState::Pending, - }); - } + pub fn raise_incident(&mut self, flow: IncidentFlow, context: IncidentContext) { self.transition(&SessionEvent::RaiseIncident { flow, context }, 0, &mut Vec::new()); } /// The offer's permission, derived by the presenting screen at `revision`. - pub fn resolve_incident( - &mut self, - id: u32, - permission: Permission, - revision: u32, - emit: &mut impl FnMut(SessionFx), - ) -> bool { - let seen = &self.state.incidents_seen; - let Some(held) = self.state.incident.as_mut().filter(|held| held.id == id) else { return false }; - match held.state { - IncidentState::Pending => {} - IncidentState::Offered { revision: at } | IncidentState::OnRequest { revision: at } - if at != revision => {} - _ => return false, - } - let key = held.key; - // Offered behind Details only: a kind the alert never covers, a key this launch has - // already asked about (the raise that brought it back is Pending over a seen key), and - // an offer already resolved that way — a later decision may drop it, never escalate it. - let quiet = !key.kind.alert_eligible() - || matches!(held.state, IncidentState::OnRequest { .. }) - || (held.state == IncidentState::Pending && seen.contains(&key)); - match permission { - Permission::Declined => { - held.state = IncidentState::Dropped; - held.context = None; - } - Permission::Granted | Permission::NotDetermined if quiet => { - held.state = IncidentState::OnRequest { revision }; - } - Permission::Granted if key.kind.standing_eligible() => { - let Some(context) = held.context else { return false }; - held.state = IncidentState::AutoSending; - emit(SessionFx::Incident { id, lane: IncidentLane::Standing, report: IncidentReport::Retained(context) }); - } - Permission::Granted | Permission::NotDetermined => { - held.state = IncidentState::Offered { revision }; - } - } - self.remember_seen(key); - true - } + pub fn resolve_incident(&mut self, id: u32, permission: Permission, revision: u32, emit: &mut impl FnMut(SessionFx)) -> bool { let mut effects = Vec::new(); let handled = self.transition(&SessionEvent::Command(Command::ResolveIncident { id, permission, revision }), 0, &mut effects); effects.into_iter().for_each(emit); handled } /// The person's Send report — from the alert, or from Details afterwards. - pub fn report_incident(&mut self, id: u32, emit: &mut impl FnMut(SessionFx)) -> bool { - let Some(held) = self.state.incident.as_mut().filter(|held| held.id == id && held.sendable()) else { - return false; - }; - let report = match held.context { - Some(context) => IncidentReport::Retained(context), - None => { - self.state.persistence_warning - .filter(|_| held.key.kind == IncidentKind::SaveFailed) - .and_then(|warning| warning.incident_context()) - .map(IncidentReport::Retained) - .unwrap_or(IncidentReport::AtPress(held.key)) - }, - }; - let key = held.key; - held.state = IncidentState::Sending; - emit(SessionFx::Incident { id, lane: IncidentLane::OneOff, report }); - self.remember_seen(key); - true - } + pub fn report_incident(&mut self, id: u32, emit: &mut impl FnMut(SessionFx)) -> bool { let mut effects = Vec::new(); let handled = self.transition(&SessionEvent::Command(Command::ReportIncident { id }), 0, &mut effects); effects.into_iter().for_each(emit); handled } /// The person's Not now. Only an offer on screen can be answered. - pub fn decline_incident(&mut self, id: u32) -> bool { - let Some(held) = self.state.incident.as_mut().filter(|held| held.id == id) else { return false }; - if !matches!(held.state, IncidentState::Offered { .. }) { - return false; - } - held.state = IncidentState::NotNow; - true - } + pub fn decline_incident(&mut self, id: u32) -> bool { self.transition(&SessionEvent::Command(Command::DeclineIncident { id }), 0, &mut Vec::new()) } /// The adapter's answer. Fenced by id: a reply for a superseded offer changes nothing. What /// became of a queued report is fenced by its receipt as well — a different receipt is a report /// this offer no longer shows. - pub fn incident_reported(&mut self, id: u32, delivery: &IncidentDelivery) -> bool { - let Some(held) = self.state.incident.as_mut().filter(|held| held.id == id) else { return false }; - let shown = match &held.state { - IncidentState::Queued { receipt } | IncidentState::Saved { receipt } => Some(receipt.as_str()), - _ => None, - }; - held.state = match (&held.state, delivery) { - (IncidentState::AutoSending, IncidentDelivery::Standing { receipt: Some(receipt) }) - | (IncidentState::Sending, IncidentDelivery::OneOff { receipt: Some(receipt) }) => { - IncidentState::Queued { receipt: receipt.clone() } - } - (IncidentState::AutoSending, IncidentDelivery::Standing { receipt: None }) - | (IncidentState::Sending, IncidentDelivery::OneOff { receipt: None }) => IncidentState::Failed, - // Tried and not through yet, still queued durably: said once, from Queued. - (IncidentState::Queued { .. }, IncidentDelivery::Held { receipt }) if shown == Some(receipt) => { - IncidentState::Saved { receipt: receipt.clone() } - } - (_, IncidentDelivery::Delivered { receipt }) if shown == Some(receipt) => { - IncidentState::Delivered { receipt: receipt.clone() } - } - // The report did not get through after all: Send report is accepted again. - (_, IncidentDelivery::Undelivered { receipt }) if shown == Some(receipt) => IncidentState::Failed, - _ => return false, - }; - true - } + pub fn incident_reported(&mut self, id: u32, delivery: &IncidentDelivery) -> bool { self.transition(&SessionEvent::IncidentReported { id, delivery: delivery.clone() }, 0, &mut Vec::new()) } /// Sign-out and Delete all local data: every incident, and what this launch has seen. - pub fn forget_incidents(&mut self) { - self.state.incident = None; - self.state.incidents_seen.clear(); - self.state.link_trouble = false; - } + pub fn forget_incidents(&mut self) { self.transition(&SessionEvent::ForgetIncidents, 0, &mut Vec::new()); } + - fn remember_seen(&mut self, key: IncidentKey) { - if self.state.incidents_seen.contains(&key) { - return; - } - if self.state.incidents_seen.len() >= SEEN_CAP { - self.state.incidents_seen.remove(0); - } - self.state.incidents_seen.push(key); - } pub fn step_incident_command( &mut self, command: &Command, emit: &mut impl FnMut(SessionFx), ) -> bool { - match command { - Command::ResolveIncident { id, permission, revision } => { - self.resolve_incident(*id, *permission, *revision, emit) - } - Command::ReportIncident { id } => self.report_incident(*id, emit), - Command::DeclineIncident { id } => self.decline_incident(*id), - _ => false, + if !matches!( + command, + Command::ResolveIncident { .. } | Command::ReportIncident { .. } | Command::DeclineIncident { .. } + ) { + return false; } + let mut effects = Vec::new(); + let handled = self.transition(&SessionEvent::Command(command.clone()), 0, &mut effects); + effects.into_iter().for_each(emit); + handled } } diff --git a/rust-modules/session/src/auth/owner/incident_tests.rs b/rust-modules/session/src/auth/owner/incident_tests.rs index 846e23b830..7f34830b97 100644 --- a/rust-modules/session/src/auth/owner/incident_tests.rs +++ b/rust-modules/session/src/auth/owner/incident_tests.rs @@ -41,7 +41,8 @@ fn step(owner: &mut SessionMachine, event: SessionEvent) -> Vec { .into_iter() .map(|effect| match effect.fx { Fx::App(effect) => effect, - _ => panic!("Session emitted a non-domain effect"), + Fx::Nav(_) | Fx::Mount(_) | Fx::Unmount(_) | Fx::Deliver(..) | Fx::Timer { .. } + | Fx::CancelTimer(_) | Fx::Press(_) | Fx::Remember { .. } | Fx::Log(_) => panic!("Session emitted a non-domain effect"), }) .collect() } @@ -53,7 +54,7 @@ fn command(owner: &mut SessionMachine, command: Command) -> Vec { /// A sign-in request's observation, as the adapter would deliver it. fn observe(owner: &mut SessionMachine, progress: LoginProgress, terminal: bool) -> Vec { let req = signin_request(owner); - let pending = &owner.state.pending[&req]; + let pending = &owner.common.pending[&req]; let arrival = pending.last_arrival.map_or(1, |a| a + 1); let envelope = SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, @@ -110,7 +111,7 @@ fn signing_in() -> SessionMachine { /// The flow's worker failed with `context`. fn fail(owner: &mut SessionMachine, context: IncidentContext) -> Vec { - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe( owner, LoginProgress::Failed { epoch, message: "synthetic failure".into(), incident: context, plaintext: None, account: None }, @@ -132,7 +133,12 @@ fn incident_effects(effects: &[SessionFx]) -> Vec<(IncidentLane, IncidentReport) .iter() .filter_map(|fx| match fx { SessionFx::Incident { lane, report, .. } => Some((*lane, *report)), - _ => None, + SessionFx::Commit { .. } | SessionFx::Pump | SessionFx::Acknowledge(_) + | SessionFx::Retire { .. } | SessionFx::Ready { .. } | SessionFx::Capture { .. } + | SessionFx::Work { .. } | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) + | SessionFx::Erase { .. } | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }) .collect() } @@ -245,7 +251,7 @@ fn granted_sends_the_standing_report_and_offers_nothing() { #[test] fn a_stalled_wait_is_never_sent_standing() { let mut owner = signing_in(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::LinkTrouble { epoch, trouble: Some(stalled()) }, false); assert!(owner.read().0.link_trouble, "the wait says the link is down"); let held = offer(&owner).expect("a stalled wait raises an incident"); @@ -263,7 +269,7 @@ fn a_stalled_wait_is_never_sent_standing() { #[test] fn discovery_trouble_is_non_terminal_and_never_an_incident() { let mut owner = signing_in(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::Authorized { epoch, token: "token".into() }, false); assert_eq!(owner.read().0.phase, Phase::Discovering); let progress = retry(crate::auth::DiscoveryRetryRun::Resources, 2, 2_000); @@ -277,38 +283,38 @@ fn discovery_trouble_is_non_terminal_and_never_an_incident() { #[test] fn discovery_trouble_is_accepted_for_rediscover_and_stale_epochs_are_fenced() { let mut owner = signing_in(); - let first_epoch = owner.state.epoch; + let first_epoch = owner.common.epoch; observe(&mut owner, LoginProgress::Authorized { epoch: first_epoch, token: "token".into(), }, false); fail(&mut owner, IncidentContext::new( IncidentKind::Discovery(plx_telemetry::telemetry::incident::DiscoveryClass::Silent), None)); command(&mut owner, Command::Retry); - let epoch = owner.state.epoch; - assert_eq!(owner.state.phase, Phase::Discovering); + let epoch = owner.common.epoch; + assert_eq!(owner.state.phase(), Phase::Discovering); let progress = retry(crate::auth::DiscoveryRetryRun::Resources, 1, 50); observe(&mut owner, LoginProgress::DiscoveryTrouble { epoch, progress }, false); - assert_eq!(owner.state.discovery_retry, Some(progress), + assert_eq!(owner.state.discovery_retry(), Some(progress), "Rediscover accepts the same non-terminal progress as Login"); let stale = retry(crate::auth::DiscoveryRetryRun::HomeUsers, 2, 9_000); observe(&mut owner, LoginProgress::DiscoveryTrouble { epoch: first_epoch, progress: stale, }, false); - assert_eq!(owner.state.discovery_retry, Some(progress), + assert_eq!(owner.state.discovery_retry(), Some(progress), "a stale worker cannot publish trouble into the new retry epoch"); observe(&mut owner, LoginProgress::DiscoveryRetrySettled { epoch: first_epoch, run: crate::auth::DiscoveryRetryRun::Resources, }, false); - assert_eq!(owner.state.discovery_retry, Some(progress), + assert_eq!(owner.state.discovery_retry(), Some(progress), "a stale-epoch reset cannot clear the current run"); observe(&mut owner, LoginProgress::DiscoveryRetrySettled { epoch, run: crate::auth::DiscoveryRetryRun::Resources, }, false); - assert_eq!(owner.state.discovery_retry, None, + assert_eq!(owner.state.discovery_retry(), None, "the matching current run clears before slow probing continues"); } @@ -318,7 +324,7 @@ fn discovery_trouble_is_accepted_for_rediscover_and_stale_epochs_are_fenced() { fn a_stalled_wait_is_offered_through_details_only_never_by_the_alert() { for permission in [Permission::NotDetermined, Permission::Granted] { let mut owner = signing_in(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::LinkTrouble { epoch, trouble: Some(stalled()) }, false); let effects = resolve(&mut owner, permission, 1); assert!(incident_effects(&effects).is_empty(), "{permission:?}: a stall is never sent without a press"); @@ -341,7 +347,7 @@ fn a_stalled_wait_is_offered_through_details_only_never_by_the_alert() { #[test] fn a_later_no_forgets_a_stall_offered_behind_details() { let mut owner = signing_in(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::LinkTrouble { epoch, trouble: Some(stalled()) }, false); resolve(&mut owner, Permission::NotDetermined, 1); assert!(resolve(&mut owner, Permission::NotDetermined, 1).is_empty(), "same revision: nothing to redo"); @@ -390,7 +396,7 @@ fn a_newer_incident_supersedes_the_held_one_and_fences_its_reply() { let old = offer(&owner).unwrap(); command(&mut owner, Command::ReportIncident { id: old.id }); command(&mut owner, Command::Retry); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::LinkTrouble { epoch, trouble: Some(stalled()) }, false); let new = offer(&owner).unwrap(); assert_ne!(new.id, old.id); @@ -409,13 +415,13 @@ fn sign_out_forgets_the_incident_and_what_this_launch_has_seen() { resolve(&mut owner, Permission::NotDetermined, 1); command(&mut owner, Command::SignOut); assert_eq!(offer(&owner), None); - assert!(owner.state.incidents_seen.is_empty()); + assert!(owner.common.incidents_seen.is_empty()); } #[test] fn a_failure_keeps_an_offer_the_wait_raised() { let mut owner = signing_in(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::LinkTrouble { epoch, trouble: Some(stalled()) }, false); resolve(&mut owner, Permission::NotDetermined, 1); assert!(matches!(offer(&owner).unwrap().state, IncidentState::OnRequest { .. })); @@ -433,7 +439,7 @@ fn a_failure_keeps_an_offer_the_wait_raised() { /// The sign-in request in flight — a QR sign-in, or the discovery-only retry of an authorized one. fn signin_request(owner: &SessionMachine) -> u32 { *owner - .state + .common .pending .iter() .find(|(_, p)| matches!(p.key.op, SessionOp::Login | SessionOp::Rediscover)) @@ -444,7 +450,7 @@ fn signin_request(owner: &SessionMachine) -> u32 { /// A terminal non-data arrival for the sign-in request: the worker was refused or went away. fn arrive(owner: &mut SessionMachine, outcome: SessionArrival) -> Vec { let req = signin_request(owner); - let pending = &owner.state.pending[&req]; + let pending = &owner.common.pending[&req]; let envelope = SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, key: pending.key, @@ -493,7 +499,7 @@ fn a_refused_worker_and_a_refused_admission_offer_their_own_failure() { let (mut owner, _) = after_a_declined_pin_create(); let req = signin_request(&owner); - let key = owner.state.pending[&req].key; + let key = owner.common.pending[&req].key; step(&mut owner, SessionEvent::Admission(AdmissionReply { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, key, @@ -507,7 +513,7 @@ fn a_refused_worker_and_a_refused_admission_offer_their_own_failure() { #[test] fn a_sign_in_whose_commit_is_refused_offers_its_own_failure() { let (mut owner, _) = after_a_declined_pin_create(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::Authorized { epoch, token: "synthetic-token".into() }, false); let effects = observe(&mut owner, LoginProgress::SignedIn { epoch, @@ -517,7 +523,12 @@ fn a_sign_in_whose_commit_is_refused_offers_its_own_failure() { }, true); let (req, arrival) = effects.iter().find_map(|fx| match fx { SessionFx::Commit { req, arrival, .. } => Some((*req, *arrival)), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } | SessionFx::Ready { .. } + | SessionFx::Capture { .. } | SessionFx::Work { .. } | SessionFx::Cancel { .. } + | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } | SessionFx::Coordinator(_) + | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } | SessionFx::SelectionReply { .. } + | SessionFx::BackReply { .. } | SessionFx::PlaintextAnswer { .. } + | SessionFx::RefreshCache { .. } => None, }).expect("the sign-in is committed"); step(&mut owner, SessionEvent::Commit(CommitReply { req, @@ -565,7 +576,7 @@ fn a_seen_failure_after_another_is_offered_again_behind_details_only() { fn an_uncovered_ending_retires_the_held_offer() { let (mut owner, _) = after_a_declined_pin_create(); owner.fail_login("synthetic uncovered ending", None, &mut |_| {}); - assert_eq!(owner.state.incident, None); + assert_eq!(owner.common.incident, None); } /// **Try again after an authorized discovery failed asks nothing new.** The retry is a @@ -574,7 +585,7 @@ fn an_uncovered_ending_retires_the_held_offer() { #[test] fn a_discovery_retry_that_fails_the_same_way_is_not_asked_about_again() { let mut owner = signing_in(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::Authorized { epoch, token: "synthetic-token".into() }, false); let silent = IncidentContext { occurred_at_ms: 3, @@ -586,7 +597,7 @@ fn a_discovery_retry_that_fails_the_same_way_is_not_asked_about_again() { command(&mut owner, Command::DeclineIncident { id: first.id }); command(&mut owner, Command::Retry); let req = signin_request(&owner); - assert!(owner.state.pending[&req].key.op == SessionOp::Rediscover, "the retry re-runs discovery only"); + assert!(owner.common.pending[&req].key.op == SessionOp::Rediscover, "the retry re-runs discovery only"); fail(&mut owner, silent); let after = offer(&owner).unwrap(); assert_eq!((after.id, after.state), (first.id, IncidentState::NotNow), "the Not now stands"); @@ -604,7 +615,7 @@ fn a_settled_discovery_offer_keeps_one_answer_but_details_reads_the_latest_run() IncidentState::Delivered { receipt: "receipt-1".into() }, ] { let mut owner = signing_in(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::Authorized { epoch, token: "synthetic-token".into(), }, false); @@ -635,7 +646,9 @@ fn a_settled_discovery_offer_keeps_one_answer_but_details_reads_the_latest_run() }); } } - _ => unreachable!(), + IncidentState::Pending | IncidentState::Offered { .. } | IncidentState::OnRequest { .. } + | IncidentState::AutoSending | IncidentState::Sending | IncidentState::Saved { .. } + | IncidentState::Failed | IncidentState::Dropped => unreachable!(), } assert_eq!(&offer(&owner).unwrap().state, &final_state); command(&mut owner, Command::Retry); @@ -652,7 +665,7 @@ fn a_settled_discovery_offer_keeps_one_answer_but_details_reads_the_latest_run() let after = offer(&owner).unwrap(); assert_eq!((after.id, &after.state), (first.id, &final_state), "the same dedup key keeps one report offer and its settled state"); - assert_eq!(owner.state.next_incident, 1, "no second report offer was allocated"); + assert_eq!(owner.common.next_incident, 1, "no second report offer was allocated"); assert_eq!(after.context.and_then(|context| context.discovery_attempts), Some(2), "the deduplicated report keeps its original evidence"); assert_eq!(after.readout_context().and_then(|context| context.discovery_attempts), Some(3), @@ -668,7 +681,7 @@ fn a_settled_discovery_offer_keeps_one_answer_but_details_reads_the_latest_run() #[test] fn try_again_after_the_token_was_refused_starts_a_new_sign_in() { let mut owner = signing_in(); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::Authorized { epoch, token: "synthetic-token".into() }, false); let refused = IncidentContext { occurred_at_ms: 4, @@ -680,12 +693,12 @@ fn try_again_after_the_token_was_refused_starts_a_new_sign_in() { command(&mut owner, Command::DeclineIncident { id: first.id }); let effects = command(&mut owner, Command::Retry); let req = signin_request(&owner); - assert!(owner.state.pending[&req].key.op == SessionOp::Login, "the retry reused the refused token"); + assert!(owner.common.pending[&req].key.op == SessionOp::Login, "the retry reused the refused token"); assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Work { input: SessionWork::Login { .. }, .. })), "the retry asks for a new code"); assert_eq!(owner.read().0.phase, Phase::Creating); - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(&mut owner, LoginProgress::Authorized { epoch, token: "synthetic-token-2".into() }, false); fail(&mut owner, refused); let after = offer(&owner).unwrap(); @@ -822,7 +835,7 @@ fn no_servers_incident() -> IncidentContext { } fn fail_naming(owner: &mut SessionMachine, message: &str, account: Option<&str>) -> Vec { - let epoch = owner.state.epoch; + let epoch = owner.common.epoch; observe(owner, LoginProgress::Failed { epoch, message: message.into(), incident: no_servers_incident(), plaintext: None, account: account.map(str::to_owned), @@ -862,7 +875,7 @@ fn the_account_name_is_absent_from_every_report_effect_and_digest() { let context = offer.readout_context().copied().expect("the read-out's context"); let mut seen = vec![ format!("{:?}", incident_effects(&effects)), - serde_json::to_string(&owner.state).unwrap(), + serde_json::to_string(&owner.snapshot_init()).unwrap(), serde_json::to_string(&context).unwrap(), format!("{context:?}"), ]; @@ -891,3 +904,86 @@ fn the_account_name_is_absent_from_every_report_effect_and_digest() { plaintext: None, account: Some(NAME.into()) })).unwrap(); assert!(!encoded.contains(NAME), "{encoded}"); } + +fn incident_compat_seeded_owner() -> SessionMachine { + let mut init = SessionInit::captured(PersistedSession { + client_id: "synthetic-incident-client".into(), + account_token: "synthetic-incident-account-token".into(), + user: UserRef { uuid: "synthetic-incident-user".into(), + token: "synthetic-incident-profile-token".into(), ..Default::default() }, + ..Default::default() + }); + init.phase = Phase::Ready; + init.active_profile = Some(init.persisted.user.clone()); + init.profile_scope = ProfileScope(7); + init.delete_leftovers = 3; + let mut owner = SessionMachine::from_init(init); + owner.raise_incident(IncidentFlow::SignIn, pin_create()); + let id = offer(&owner).unwrap().id; + assert!(owner.resolve_incident(id, Permission::NotDetermined, 1, &mut |_| {})); + owner +} + +#[test] +fn incident_compat_rejects_nonincident_commands_without_touching_default_or_seeded_state() { + for mut owner in [ + SessionMachine::from_init(SessionInit::captured(PersistedSession::default())), + incident_compat_seeded_owner(), + ] { + for rejected in [Command::SignOut, Command::EraseLocal, Command::StartLogin, + Command::Retry, Command::NoteDeleteLeftovers(99), Command::RefreshRoster] { + let snapshot = serde_json::to_string(&owner.snapshot_init()).unwrap(); + let account = owner.snapshot_init().signin_account; + let publication = owner.publication(); + let fingerprint = (owner.subhash(), owner.logical_dirty, owner.cache_refresh, + owner.next_cache_req, owner.publication_payload_allocations); + let mut effects = Vec::new(); + assert!(!owner.step_incident_command(&rejected, &mut |fx| effects.push(fx))); + assert!(effects.is_empty()); + assert_eq!(serde_json::to_string(&owner.snapshot_init()).unwrap(), snapshot); + assert_eq!(owner.snapshot_init().signin_account, account); + assert!(Arc::ptr_eq(&publication, &owner.publication())); + assert_eq!((owner.subhash(), owner.logical_dirty, owner.cache_refresh, + owner.next_cache_req, owner.publication_payload_allocations), fingerprint); + } + } +} + +#[test] +fn incident_compat_preserves_all_three_accepted_commands_and_their_effects() { + let mut legacy = signing_in(); + fail(&mut legacy, pin_create()); + let id = offer(&legacy).unwrap().id; + let mut typed = SessionMachine::from_init(legacy.snapshot_init()); + for accepted in [ + Command::ResolveIncident { id, permission: Permission::NotDetermined, revision: 1 }, + Command::DeclineIncident { id }, + Command::ReportIncident { id }, + ] { + let mut observed = Vec::new(); + assert!(legacy.step_incident_command(&accepted, &mut |fx| observed.push(fx))); + let mut expected = Vec::new(); + assert!(typed.transition(&SessionEvent::Command(accepted), 0, &mut expected)); + assert_eq!(observed.len(), expected.len()); + assert_eq!(incident_effects(&observed), incident_effects(&expected)); + assert_eq!(serde_json::to_string(&legacy.snapshot_init()).unwrap(), + serde_json::to_string(&typed.snapshot_init()).unwrap()); + assert_eq!(legacy.subhash(), typed.subhash()); + } + assert_eq!(offer(&legacy).unwrap().state, IncidentState::Sending); +} + +#[test] +fn authorized_sign_out_still_erases_credentials_and_incidents_through_the_owner_step() { + let mut owner = incident_compat_seeded_owner(); + assert!(!owner.common.persisted.account_token.is_empty()); + assert!(!owner.common.incidents_seen.is_empty()); + let effects = command(&mut owner, Command::SignOut); + assert!(effects.iter().any(|fx| matches!(fx, SessionFx::Erase { .. }))); + assert!(owner.common.persisted.account_token.is_empty()); + assert!(owner.common.persisted.user.token.is_empty()); + assert!(owner.common.active_profile.is_none()); + assert!(owner.common.incident.is_none()); + assert!(owner.common.incidents_seen.is_empty()); + assert!(owner.state.pending_erase().is_some()); +} diff --git a/rust-modules/session/src/auth/owner/scenarios.rs b/rust-modules/session/src/auth/owner/scenarios.rs index 25d4d8b669..225d95341b 100644 --- a/rust-modules/session/src/auth/owner/scenarios.rs +++ b/rust-modules/session/src/auth/owner/scenarios.rs @@ -38,7 +38,9 @@ pub fn step_at(owner: &mut SessionMachine, event: SessionEvent, ms: u32) -> Vec< owner.step(&event, &cx, &mut Effects::new(&mut effects, MachineId::Session, &mut present)); effects.into_iter().map(|effect| match effect.fx { Fx::App(effect) => effect, - _ => panic!("Session emitted a non-domain effect"), + Fx::Nav(_) | Fx::Mount(_) | Fx::Unmount(_) | Fx::Deliver(..) | Fx::Timer { .. } + | Fx::CancelTimer(_) | Fx::Press(_) | Fx::Remember { .. } | Fx::Log(_) => + panic!("Session emitted a non-domain effect"), }).collect() } @@ -89,13 +91,23 @@ pub fn picker_switch_seated() -> (SessionMachine, u32, u64, plx_plex::plex::sess sources: vec![primary.clone()], ..Default::default() }; let mut init = SessionInit::captured(persisted); - init.phase = Phase::Switching; + init.phase = Phase::Profiles; init.users = vec![UserTile { uuid: "u-kid".into(), title: "Kid".into(), ..Default::default() }]; let mut owner = SessionMachine::from_init(init); - let req = owner.allocate(SessionOp::ProfileSwitch, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + step(&mut owner, SessionEvent::Command(Command::SelectProfile { index: 0, pin: None })); + let req = owner.common.next_req; + let epoch = owner.common.epoch; + let addr = Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }; + assert!(owner.read_is_current(req, epoch, SessionReadRequest::ProfilePolicy)); + step(&mut owner, SessionEvent::Read(SessionReadReply { + addr, epoch, value: SessionReadValue::ProfilePolicy { recently_unreachable: false }, + })); + let key = SessionWorkKey { epoch, op: SessionOp::ProfileSwitch }; + assert!(owner.work_is_current(req, key, AdmissionId(req))); + step(&mut owner, SessionEvent::Admission(AdmissionReply { + addr, key, correlation: AdmissionId(req), accepted: true, + })); + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let ready = SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, key: SessionWorkKey { epoch, op: SessionOp::ProfileSwitch }, admission: AdmissionId(req), @@ -116,7 +128,12 @@ pub fn picker_switch_seated() -> (SessionMachine, u32, u64, plx_plex::plex::sess SessionFx::Commit { req, epoch, arrival, plan } => Some((CommitReply { req: *req, epoch: *epoch, arrival: *arrival, admission: CommitAdmission::RegistryOnly, }, plan.clone())), - _ => None, + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the profile switch must commit"); assert!(matches!(&plan.registry[0], RegistryPlan::Install { commit: RosterCommit::Switch, .. }), "seating a different profile is a switch"); @@ -124,7 +141,7 @@ pub fn picker_switch_seated() -> (SessionMachine, u32, u64, plx_plex::plex::sess assert!(super::super::execute_session_registry(p, "synthetic-client")); } step(&mut owner, SessionEvent::Commit(reply)); - assert_eq!(owner.state.persisted.user.uuid, "u-kid"); + assert_eq!(owner.common.persisted.user.uuid, "u-kid"); (owner, req, epoch, primary) } @@ -143,7 +160,13 @@ pub fn late_profile_roster(owner: &mut SessionMachine, req: u32, epoch: u64, }; let effects = step(owner, SessionEvent::Result(roster)); effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan.clone()), _ => None, + SessionFx::Commit { plan, .. } => Some(plan.clone()), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the late profile roster must commit") } @@ -155,7 +178,7 @@ pub fn late_profile_roster(owner: &mut SessionMachine, req: u32, epoch: u64, pub fn late_roster_of_the_seated_profile() -> (plx_plex::plex::ServerId, CommitPlan) { let (mut owner, req, epoch, primary) = picker_switch_seated(); let sid = plx_plex::plex::id_of_machine("a").expect("the switch installed the seated server"); - let seated = super::super::SessionIdentity::of(&owner.state.persisted); + let seated = super::super::SessionIdentity::of(&owner.common.persisted); let plan = late_profile_roster(&mut owner, req, epoch, &primary, seated); (sid, plan) } @@ -171,7 +194,7 @@ pub fn admin_boot_refresh_of_the_seated_profile(grant: &str) -> (plx_plex::plex: title: "Owner".into(), admin: true, ..Default::default() }]; let mut owner = roster_refresh_fixture("u-owner", users); // The stored-session boot: the persisted roster, registered before any discovery. - let stored = owner.state.persisted.sources.clone(); + let stored = owner.common.persisted.sources.clone(); assert!(super::super::execute_session_registry(&RegistryPlan::Install { sources: stored.clone(), primary: None, commit: RosterCommit::Merge, }, "synthetic-client")); @@ -181,9 +204,9 @@ pub fn admin_boot_refresh_of_the_seated_profile(grant: &str) -> (plx_plex::plex: let mut reached = stored[0].clone(); reached.token = grant.into(); let req = owner.allocate(SessionOp::ServerRoster, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let resources = vec![plx_plex::plex::account::Resource { name: reached.name.clone(), client_identifier: reached.machine_id.clone(), provides: "server".into(), owned: true, access_token: reached.token.clone(), ..Default::default() }]; @@ -202,7 +225,13 @@ pub fn admin_boot_refresh_of_the_seated_profile(grant: &str) -> (plx_plex::plex: }; let effects = step(&mut owner, SessionEvent::Result(envelope)); let plan = effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan.clone()), _ => None, + SessionFx::Commit { plan, .. } => Some(plan.clone()), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("a rotated grant is persisted"); (sid, plan) } @@ -223,8 +252,8 @@ pub fn member_account_on_admin_seat() -> (SessionMachine, plx_plex::plex::Server ..Default::default() }, ]; let owner = roster_refresh_fixture("u-admin", users); - assert!(owner.state.persisted.active_profile_is_admin()); - let stored = owner.state.persisted.sources.clone(); + assert!(owner.common.persisted.active_profile_is_admin()); + let stored = owner.common.persisted.sources.clone(); assert!(stored[0].owned, "the admin's roster calls the admin's server owned"); assert!(super::super::execute_session_registry(&RegistryPlan::Install { sources: stored.clone(), primary: None, commit: RosterCommit::Merge, @@ -245,9 +274,9 @@ pub fn member_account_on_admin_seat() -> (SessionMachine, plx_plex::plex::Server pub fn refresh_under_another_accounts_token() -> (plx_plex::plex::ServerId, CommitPlan) { let (mut owner, sid, members_view) = member_account_on_admin_seat(); let req = owner.allocate(SessionOp::ServerRoster, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let resources = vec![plx_plex::plex::account::Resource { name: members_view.name.clone(), client_identifier: members_view.machine_id.clone(), provides: "server".into(), owned: false, access_token: members_view.token.clone(), ..Default::default() }]; @@ -266,7 +295,13 @@ pub fn refresh_under_another_accounts_token() -> (plx_plex::plex::ServerId, Comm }; let effects = step(&mut owner, SessionEvent::Result(envelope)); let plan = effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan.clone()), _ => None, + SessionFx::Commit { plan, .. } => Some(plan.clone()), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the changed roster commits"); (sid, plan) } @@ -280,9 +315,9 @@ pub fn refresh_under_another_accounts_token() -> (plx_plex::plex::ServerId, Comm pub fn activation_under_another_accounts_token() -> (plx_plex::plex::ServerId, CommitPlan) { let (mut owner, sid, members_view) = member_account_on_admin_seat(); let req = owner.allocate(SessionOp::ServerRoster, None).unwrap(); - owner.state.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); - let epoch = owner.state.epoch; - let expected = super::super::SessionIdentity::of(&owner.state.persisted); + owner.common.pending.get_mut(&req).unwrap().admission = AdmissionState::Accepted(AdmissionId(req)); + let epoch = owner.common.epoch; + let expected = super::super::SessionIdentity::of(&owner.common.persisted); let activate = SessionEnvelope { addr: Addr { to: MachineId::Session, req: plx_machine::machine::RequestId(req) }, key: SessionWorkKey { epoch, op: SessionOp::ServerRoster }, @@ -301,7 +336,13 @@ pub fn activation_under_another_accounts_token() -> (plx_plex::plex::ServerId, C }; let effects = step(&mut owner, SessionEvent::Result(activate)); let plan = effects.iter().find_map(|effect| match effect { - SessionFx::Commit { plan, .. } => Some(plan.clone()), _ => None, + SessionFx::Commit { plan, .. } => Some(plan.clone()), + SessionFx::Pump | SessionFx::Acknowledge(_) | SessionFx::Retire { .. } + | SessionFx::Ready { .. } | SessionFx::Capture { .. } | SessionFx::Work { .. } + | SessionFx::Cancel { .. } | SessionFx::PublishProfile(_) | SessionFx::Erase { .. } + | SessionFx::Coordinator(_) | SessionFx::RestartReply { .. } | SessionFx::Incident { .. } + | SessionFx::SelectionReply { .. } | SessionFx::BackReply { .. } + | SessionFx::PlaintextAnswer { .. } | SessionFx::RefreshCache { .. } => None, }).expect("the activation reaches the commit boundary"); (sid, plan) } diff --git a/rust-modules/session/src/auth/ports.rs b/rust-modules/session/src/auth/ports.rs new file mode 100644 index 0000000000..8a46178e9d --- /dev/null +++ b/rust-modules/session/src/auth/ports.rs @@ -0,0 +1,904 @@ +//! Live session job bodies and their clock adapters. No SessionMachine logic lives here. +use super::*; +use std::sync::mpsc; + +fn clock_now() -> Instant { + plx_base::step::assert_io_allowed("session clock"); + Instant::now() +} +fn clock_elapsed(started: Instant) -> Duration { + plx_base::step::assert_io_allowed("session elapsed clock"); + started.elapsed() +} +#[cfg(test)] +mod scope_tests { + use super::*; + #[test] + fn captured_clock_and_live_retry_clock_still_refuse_step_reads() { + let now = admission_clock(); + let live = || true; + let clock = LiveFnClock { live: &live, started: now() }; + let _allowed = plx_base::task::allow_blocking(const { &plx_base::task::BlockingLabel::new("fixture") }); + let step = plx_base::step::StepScope::enter(); + assert!(std::panic::catch_unwind(now).is_err()); + assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| RetryClock::elapsed(&clock))).is_err()); + drop(step); + now(); + RetryClock::elapsed(&clock); + } +} + + +pub(super) fn home_roster_worker_with_io(epoch: u64, expected: SessionIdentity, cid: String, + token: String, output: &dyn owner::ObservationSink, + mut home_users: impl FnMut(&AccountClient, Duration) -> Result, CallEvidence>) { + plx_base::step::assert_io_allowed("session::home_roster_worker_with_io"); + if !output.live() { return; } + let ac = AccountClient::new(&cid, Some(&token)); + let mut clock = LiveRetryClock { output, started: clock_now() }; + let Some(users) = home_roster_with_io_and_clock(&ac, &mut clock, &mut home_users) else { return }; + output.terminal(AuthProgress::HomeRoster(HomeRosterProgress { + epoch, + expected, + users, + })); +} + +pub(super) fn mint_pin(ac: &AccountClient, epoch: u64, generation: u32, + output: &dyn owner::ObservationSink) -> Option { + plx_base::step::assert_io_allowed("session::mint_pin"); + if !output.live() { return None; } + if generation > 1 { + // Liveness only, no write — see the section doc above [`login_thread`]. This is the same + // "stop wasting plex.tv calls on a dead flow" courtesy the old synchronous check made: + // without it, the account call below would still burn a network round trip minting a code + // nobody is left to scan. + if !output.live() { + return None; + } + if !output.progress(LoginProgress::CodeReplacing { epoch }.into()) { return None; } + } + let mut clock = LiveRetryClock { output, started: clock_now() }; + let created = retry_account_call(INTERACTIVE_ACCOUNT, &mut clock, |_, _, _| {}, + |remaining| scripted::signin_trouble_create() + .unwrap_or_else(|| ac.create_pin_with(account_timeouts(remaining)))); + let created = match created.result { + AccountCallEnd::Answer(pin) => Ok(pin), + AccountCallEnd::Failed(evidence) => Err(evidence), + AccountCallEnd::Cancelled => return None, + }; + let pin = match created { + Ok(p) if p.id != 0 && !p.code.is_empty() => p, + failed => { + // A 2xx that decoded into a pin with no id or code is still an answer: classed by + // its status, which is the 2xx it was. + let last = match failed { Err(evidence) => evidence, Ok(_) => Ok(200) }; + // Says what the internet is FOR here — signing in — because the one time this screen + // appears with the link deliberately down is the first boot of a set that has never + // signed in. Drawn as the reason under "Couldn't sign in" (`screens/login.rs`). + output_failed(output, + epoch, + plx_platform::i18n::msg::browse_auth_plex_unreachable(), + IncidentContext::new(IncidentKind::PinCreate, Some(last)) + .with_link_state(0, None, generation), + None, + ); + return None; + } + }; + // **The lease starts HERE, not where the polling does.** plex.tv began counting the moment it + // answered, and the QR fetch below is another request on `net::API`'s 25 s deadline — so a + // clock started after it would let the poll run that much past the code's real death, which is + // the same over-run in miniature that this whole change is about. + let minted = clock_now(); + // Neither the id nor the code may be logged. `GET /api/v2/pins/{id}` is what RETURNS the + // account token once the user authorizes (plex/account.rs `poll_pin`), so the id is a handle + // that redeems a credential, and the code is what authorizes it — and this file is the one we + // ask users to send us when something goes wrong. Log that we got here, not what we got. + log(&format!( + "auth: pin created (code {generation} of {MAX_PIN_GENERATIONS}, {}s to authorize)", + pin_window(pin.expires_in).as_secs() + )); + // fetch the server-rendered QR PNG (the exact QR the official apps display); public, no token. + let qr_url = if pin.qr.is_empty() { + format!("{}/api/v2/pins/qr/{}", plx_plex::plex::account::plex_tv(), pin.code) + } else { + pin.qr.clone() + }; + if !output.live() { return None; } + let qr_png = plx_net::net::https_get_public(&qr_url) + .filter(|r| r.ok()) + .map(|r| r.body) + .unwrap_or_default(); + log(&format!("auth: qr png {} bytes", qr_png.len())); + // Same liveness-only check as above, and the same reason: no point publishing a code the flow + // this worker belongs to no longer exists to show. The owner's checked QR allocator runs + // only on accepted CodeReady, not here on the producer. + if !output.live() { + return None; + } + if !output.progress(LoginProgress::CodeReady { + epoch, + code: pin.code.clone(), + qr_png, + }.into()) { return None; } + Some(MintedCode { + id: pin.id, + expires_in: pin.expires_in, + minted, + }) +} + +pub(super) fn finish_sign_in(ac: &AccountClient, epoch: u64, server: ServerRef, sources: Vec, + output: &dyn owner::ObservationSink) { + plx_base::step::assert_io_allowed("session::finish_sign_in"); + if !output.live() { return; } + // Discovery already queued its activation observations before this SignedIn observation. + // Only owner-accepted resource effects install clients; the historical "installed" log + // label below describes the observed result, not proof of main-thread commit completion. + // `log_form`, not `base()`: byte-identical to the `{addr}:{port}` this line always printed + // for a plaintext origin (so an archived log stays comparable), and the whole URL as soon as + // the scheme is worth saying. See `Origin::log_form`. + log(&format!( + "auth: PMS client installed {}", + server.origin().log_form() + )); + + // 4) Plex Home roster → who's-watching, or straight in if there's a single user. The roster is + // kept on the session so it persists with the creds — the boot picker and every later + // "Change profile" render from it instantly, online or not. + // + // A failed fetch still signs in (as a single user) and persists an empty roster, which the + // session reads as "unknown" (`Session::account`) — but it now says WHY in the log, in the + // same grading the Change-profile refresh uses, rather than a bare `n=0`. + let mut clock = LiveRetryClock { output, started: clock_now() }; + let Some(users) = sign_in_home_users_with_clock(ac, epoch, output, &mut clock, + |ac, remaining| ac.home_users_with(account_timeouts(remaining))) else { return }; + log(&format!("auth: home users n={}", users.len())); + // One observation carrying everything the owner needs to commit the session at once — + // see [`LoginProgress::SignedIn`] for why this used to be three separate `with_ctl` writes and + // is now one. + output.terminal(LoginProgress::SignedIn { + epoch, + server, + sources, + users, + }.into()); +} + +pub(super) fn cancellable_wait_while(duration: Duration, live: impl Fn() -> bool) -> bool { + plx_base::step::assert_io_allowed("session::cancellable_wait_while"); + const SLICE: Duration = Duration::from_secs(1); + let deadline = clock_now() + duration; + loop { + if !live() { return false; } + let now = clock_now(); + if now >= deadline { return true; } + std::thread::sleep((deadline - now).min(SLICE)); + } +} + +pub(super) fn race_batch( + plan: &ProbePlan, + indices: &[usize], + dial: ProbeDial, + spawn: &dyn Fn(usize, ProbeJob) -> bool, + policy: ProbeDeadlines, + activate: &mut dyn FnMut(&ProbePlan, &Candidate, &Origin), +) -> BatchResult { + plx_base::step::assert_io_allowed("session::race_batch"); + let (tx, rx) = mpsc::channel::(); + let mut pending = vec![None; plan.candidates.len()]; + let mut live = 0usize; + + for &index in indices { + let c = &plan.candidates[index]; + let Some(origin) = dial_target(c) else { + continue; + }; + let started = clock_now(); + let budget = probe_deadline(c, policy); + let deadline = started + budget; + let state = Arc::new(AtomicU8::new(PROBE_PENDING)); + let tx = tx.clone(); + let dial = Arc::clone(&dial); + let worker_state = Arc::clone(&state); + let machine_id = plan.machine_id.clone(); + // Built here, at the dial that decides a winner — not only at `apply_candidate_activation`, + // which pins the same way after one already has. `None` for a plaintext candidate (a pin + // belongs to a TLS name only) or an unmatched/undecodable label; the request then resolves + // through DNS exactly as before. + let pin = plx_plex::plex::ResolvePin::for_origin(&origin, &c.address); + let location = c.location; + let job = Box::new(move || { + let reply = dial(&origin, pin.as_ref(), budget); + let untrusted = reply.untrusted(); + let (outcome, route) = reply.grade_learning(&machine_id, location); + let on_time = clock_now() <= deadline; + // Claim completion before publishing the message. If the coordinator expires first, + // this result is inert. If this claim wins and the worker is descheduled before send, + // the coordinator sees COMPLETED and waits for the already-decided result rather than + // erasing it on its own later wall-clock sample. + if worker_state + .compare_exchange( + PROBE_PENDING, + PROBE_COMPLETED, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok() + { + let _ = tx.send(ProbeMessage { + index, + on_time, + outcome, + route, + untrusted, + }); + } + }); + if spawn(index, job) { + pending[index] = Some(PendingProbe { deadline, state }); + live += 1; + } + } + // Only worker-held senders remain. If one panics (or an injected spawner accepts then drops its + // job), disconnect settles the remaining pending set instead of parking the coordinator. + drop(tx); + + let mut result = BatchResult { + observed: vec![None; plan.candidates.len()], + ..BatchResult::default() + }; + let mut first_win: Option = None; + while live > 0 { + // Drain results that completed on time BEFORE expiring by the coordinator's current clock. + // Spawn setup and queue backlog are allowed to delay observation; `finished` is the fact + // that decides whether the candidate met its own absolute deadline. + loop { + match rx.try_recv() { + Ok(message) => settle_probe_message( + plan, + message, + &mut pending, + &mut live, + &mut result, + activate, + ), + Err(mpsc::TryRecvError::Empty) => break, + Err(mpsc::TryRecvError::Disconnected) => { + if live > 0 { + live = 0; + pending.fill(None); + } + break; + } + } + } + if live == 0 { + break; + } + let now = clock_now(); + for &index in indices { + let expired = pending[index].as_ref().is_some_and(|p| { + p.deadline <= now + && p.state + .compare_exchange( + PROBE_PENDING, + PROBE_EXPIRED, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok() + }); + if expired { + pending[index] = None; + live -= 1; + result.observed[index] = Some(RouteOutcome::Timeout); + let c = &plan.candidates[index]; + log(&format!( + "auth: '{}' probe timed out at {}:{}", + plan.name, c.address, c.port + )); + } + } + if live == 0 { + break; + } + if first_win.is_none() && result.first.is_some() { + first_win = Some(clock_now()); + } + // A candidate whose worker already claimed completion owes a message that is about to + // land, so it is never skipped; only one still dialling can be left behind. + let undecided: Vec = indices + .iter() + .copied() + .filter(|&i| { + pending[i] + .as_ref() + .is_some_and(|p| p.state.load(Ordering::Acquire) == PROBE_PENDING) + }) + .collect(); + if undecided.len() == live + && race_decided( + plan, + &undecided, + result.best.as_ref(), + first_win.map(clock_elapsed), + policy.grace, + ) + { + let mut left_behind = 0usize; + for &index in &undecided { + if let Some(p) = pending[index].take() { + if p + .state + .compare_exchange( + PROBE_PENDING, + PROBE_EXPIRED, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok() + { + left_behind += 1; + } + } + } + if left_behind > 0 { + log(&format!( + "auth: '{}' settled on its first verified route; {left_behind} slower or lower-ranked address(es) not waited for", + plan.name + )); + } + break; + } + let next = indices + .iter() + .filter_map(|&i| pending[i].as_ref()) + .filter(|p| p.state.load(Ordering::Acquire) == PROBE_PENDING) + .map(|p| p.deadline) + // Wake for the end of the grace too, but only while it is still ahead: a past one + // would turn the wait below into a zero-timeout spin. + .chain(first_win.map(|at| at + policy.grace).filter(|end| *end > clock_now())) + .min(); + let received = match next { + Some(next) => rx.recv_timeout(next.saturating_duration_since(clock_now())), + // Every live worker has already claimed completion and owes exactly one message. + // Blocking here avoids a zero-timeout spin in the tiny claim-before-send window. + None => rx.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected), + }; + match received { + Ok(message) => settle_probe_message( + plan, + message, + &mut pending, + &mut live, + &mut result, + activate, + ), + Err(mpsc::RecvTimeoutError::Timeout) => {} + Err(mpsc::RecvTimeoutError::Disconnected) => { + // Every sender is gone, so no pending candidate can ever report. This includes a + // worker panic and an injected accepted-but-dropped job. + live = 0; + for slot in pending.iter_mut() { + *slot = None; + } + } + } + } + result +} + +pub(super) fn discover_and_store_with_resources(ac: &AccountClient, client_id: &str, epoch: u64, + trigger: DiscoveryTrigger, ask: &PlaintextAsk, output: &dyn owner::ObservationSink, + resources_call: impl FnMut(&AccountClient, Duration) -> Result, CallEvidence>) -> Discovery { + plx_base::step::assert_io_allowed("session::discover_and_store_with_resources"); + let mut clock = LiveRetryClock { output, started: clock_now() }; + discover_and_store_with_resources_and_clock(ac, client_id, epoch, trigger, ask, output, + &mut clock, resources_call) +} + +pub(super) fn server_roster_worker_with_output(sess: Session, epoch: u64, expected: SessionIdentity, + household: Vec, ask: &PlaintextAsk, output: &dyn owner::ObservationSink) { + plx_base::step::assert_io_allowed("session::server_roster_worker_with_output"); + if !output.live() { return; } + let ac = AccountClient::new(&sess.client_id, Some(&sess.account_token)); + let mut clock = LiveRetryClock { output, started: clock_now() }; + let run = retry_account_call(BACKGROUND_ACCOUNT, &mut clock, |_, _, _| {}, + |remaining| ac.resources_with(account_timeouts(remaining))); + let resources = match run.result { + AccountCallEnd::Answer(resources) => resources, + AccountCallEnd::Cancelled => return, + AccountCallEnd::Failed(evidence) => { + log(&format!("auth: server roster refresh could not list resources ({})", + plx_plex::plex::account::describe_evidence(&evidence))); + output.terminal(AuthProgress::ServerRoster(ServerRosterProgress { + epoch, + expected, + outcome: ServerRosterOutcome::Unreachable, + })); + return; + } + }; + let mut activate = |plan: &ProbePlan, c: &Candidate, origin: &Origin| { + let credit = credit_for_machine(&resources, &plan.machine_id, &household); + let evidence = evidence_for_machine(&resources, &plan.machine_id); + output.progress(AuthProgress::Registry(RegistryProgress::Activate { + epoch, + expected: Some(expected.clone()), + candidate: candidate_activation(plan, c, origin, &credit, evidence), + })); + }; + let mut settled = Vec::new(); + // Unlike `activate` above, this does NOT also `output.progress(RegistryProgress::Settled)` + // per server as the race runs. It used to, and the owner committed BOTH: the live progress + // arm (`Observation::Registry` in `owner.rs`) planned one `RegistryPlan::Probe` per server as + // it settled, and the terminal `ServerRosterOutcome` below planned the identical set again + // through `settled`/`roster_plan` — every probe this worker ever runs was published twice. + // This worker is a BACKGROUND refresh (`refresh_roster`) with no live race screen watching + // it — unlike `discover_and_store`'s sign-in flow, which really does drive a Sources/QR + // screen off `RegistryProgress::Activate` while candidates settle, and keeps publishing both + // — so there is nothing here for the extra progress arrival to reach before the terminal + // commit does the same work. `settled` alone, folded into the terminal outcome, is authoritative. + let resolution = resolve_roster_live_while( + &resources, + &household, + &sess.client_id, + ask, + &mut activate, + &mut |plan, verdict| { + settled.push(settled_probe_of(plan, verdict)); + }, + &|| output.live(), + ); + let found = match resolution.outcome { + Resolved::Reached(found) => found, + _ => { + // R2/A5: a background refresh that found nothing to REGISTER may still have PROBED + // something worth recording — carry it rather than throwing `settled` away, so the + // owner can commit it as a registry-only `RegistryPlan::Probe` (`owner.rs`). + output.terminal(AuthProgress::ServerRoster(ServerRosterProgress { + epoch, + expected, + outcome: ServerRosterOutcome::NoReachable { settled }, + })); + return; + } + }; + let admitted_machine_id = resolution.admitted_machine_id + .expect("a reached roster has one authenticated primary"); + output.terminal(AuthProgress::ServerRoster(ServerRosterProgress { + epoch, + expected, + outcome: ServerRosterOutcome::Reconcile { + resources, + found, + admitted_machine_id, + household, + settled, + }, + })); +} + +pub(super) fn probe_endpoint_work( + id: ServerId, + machine_id: &str, + sess: &Session, + mut resources: impl FnMut(&AccountClient, Duration) -> Result, CallEvidence>, + probe: impl FnOnce(&Resource, &[i64]) -> (Option, SettledProbe), + live: &dyn Fn() -> bool, +) -> (Option, Option) { + plx_base::step::assert_io_allowed("session::probe_endpoint_work"); + // Nothing was actually probed on any of the early exits below — plex.tv never answered, or + // this machine is no longer among its resources — so there is no verdict to report at all: + // fabricating `Unreachable` here would widen a real, more specific probe result + // (`InsecureOnly`/`Unauthorized`) into "Not reachable" once it reached the registry. + if !live() { return (None, None); } + let ac = AccountClient::new(&sess.client_id, Some(&sess.account_token)); + let mut clock = LiveFnClock { live, started: clock_now() }; + let run = retry_account_call(BACKGROUND_ACCOUNT, &mut clock, |_, _, _| {}, + |remaining| resources(&ac, remaining)); + let resources = match run.result { + AccountCallEnd::Answer(resources) => resources, + AccountCallEnd::Cancelled => return (None, None), + AccountCallEnd::Failed(evidence) => { + log(&format!( + "auth: endpoint refresh for source {} could not list resources ({})", + id.raw(), + plx_plex::plex::account::describe_evidence(&evidence) + )); + return (None, None); + } + }; + let Some(resource) = resources + .iter() + .find(|resource| resource.is_server() && resource.client_identifier == machine_id) + else { + log(&format!( + "auth: endpoint refresh for source {} found no matching resource", + id.raw() + )); + return (None, None); + }; + if !live() { return (None, None); } + let (fresh, probe) = probe(resource, &sess.household_ids()); + (fresh, Some(probe)) +} + +pub fn profile_switch_worker_with_io( + epoch: u64, + expected: SessionIdentity, + stored: Session, + tile: UserTile, + pin: Option, + recently_unreachable: bool, + output: &dyn owner::ObservationSink, + io: &mut impl ProfileWorkIo, +) { + plx_base::step::assert_io_allowed("session::profile_switch_worker_with_io"); + if !output.live() { return; } + let cid = stored.client_id.clone(); + let account_token = stored.account_token.clone(); + let ac = AccountClient::new(&cid, Some(&account_token)); + let cache_first = stored.cached_profile(&tile.uuid).is_some() && recently_unreachable; + let outcome = if cache_first { + log("auth: switch — plex.tv was unreachable moments ago, trying the cached credentials first"); + SwitchOutcome::Unreachable + } else { + io.switch(&ac, &tile.uuid, pin.as_deref()) + }; + let user = match outcome { + SwitchOutcome::Switched(user) => user, + SwitchOutcome::Refused(status) => { + log(&format!("auth: profile switch -> refused (HTTP {status})")); + let (error, pin_denied) = switch_failure(pin.is_some()); + output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { + epoch, + expected, + outcome: ProfileSwitchOutcomeProgress::Failed { error, pin_denied }, + })); + return; + } + SwitchOutcome::Unreachable => { + let outcome = offline_switch_outcome(&stored, &tile, pin.as_deref()); + output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { + epoch, + expected, + outcome, + })); + return; + } + }; + if !output.live() { return; } + let profile_account = AccountClient::new(&cid, Some(&user.auth_token)); + let mut clock = LiveRetryClock { output, started: clock_now() }; + let run = retry_account_call(PROFILE_SWITCH_ACCOUNT, &mut clock, |_, _, _| {}, + |_| io.resources(&profile_account)); + let resources = match run.result { + AccountCallEnd::Answer(resources) => resources, + AccountCallEnd::Cancelled => return, + AccountCallEnd::Failed(evidence) => { + log(&format!("auth: profile resources request failed ({})", + plx_plex::plex::account::describe_evidence(&evidence))); + // A refusal is an answer, not a dead link: "check the connection" would send the + // person to a router that is fine. The PIN was already accepted by this point, so + // this is never the PIN flash either. + let error = if plx_plex::plex::account::refused_identity(&evidence).is_some() { + plx_platform::i18n::msg::browse_auth_profile_signin_refused(&tile.title) + } else { + plx_platform::i18n::msg::browse_auth_switch_failed().into() + }; + output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { + epoch, + expected, + outcome: ProfileSwitchOutcomeProgress::Failed { + error, + pin_denied: false, + }, + })); + return; + } + }; + let grants = ordered_profile_grants(&resources); + if grants.is_empty() { + output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { + epoch, + expected, + outcome: ProfileSwitchOutcomeProgress::Failed { + error: plx_platform::i18n::msg::browse_auth_no_access(&tile.title), + pin_denied: false, + }, + })); + return; + } + + let household = stored.household_ids(); + let mut admission_budget = AdmissionBudget::new(io.admission_budget()); + let admission_clock = io.admission_clock(); + let mut order = grants.clone(); + if let Some(pos) = order + .iter() + .position(|&i| resources[i].client_identifier == stored.server.machine_id) + { + order.swap(0, pos); + } + let mut reached = Vec::new(); + let mut probes: Vec = Vec::new(); + let mut probed = vec![false; resources.len()]; + let mut admission_failures = Vec::new(); + let mut selected_mid = None; + for &i in &order { + probed[i] = true; + let mut rejected_origins = Vec::new(); + loop { + if !output.live() { return; } + let (mut winner, mut settled) = + io.probe_after(&resources[i], &household, &rejected_origins); + if !output.live() { return; } + if winner.is_none() { + if let Some(cached) = stored.sources.iter() + .find(|source| source.machine_id == resources[i].client_identifier) { + if let Some((cached_winner, cached_settled)) = + io.probe_cached(&resources[i], cached, &household, &rejected_origins) { + winner = cached_winner; + settled = cached_settled.after_fresh(&settled); + } + } + } + if !output.live() { return; } + if let Some(previous) = probes.iter_mut() + .find(|probe| probe.machine_id == resources[i].client_identifier) { + if previous.outcome != Outcome::Reachable || settled.outcome == Outcome::Reachable { + *previous = settled; + } + } else { + probes.push(settled); + } + let Some(winner) = winner else { break }; + let origin = winner.origin_url.clone(); + if rejected_origins.contains(&origin) { break; } + let admission = admission_budget.attempt_on(admission_clock, |deadline| + io.admit_until(&winner, &cid, deadline)); + if admission == plx_plex::plex::EndpointAdmission::Usable { + selected_mid = Some(winner.machine_id.clone()); + reached.push(winner); + break; + } + log(&format!("auth: profile switch — resource[{i}] did not admit this profile ({admission:?})")); + admission_failures.push((resources[i].name.clone(), admission)); + if admission_budget.exhausted() { break; } + rejected_origins.push(origin); + } + if selected_mid.is_some() { + break; + } + } + let cached_sources = profile_sources(&stored.sources, &reached, &resources, &household); + let initial = cached_sources.clone(); + let Some(primary) = + selected_mid.and_then(|mid| initial.iter().find(|s| s.machine_id == mid).cloned()) + else { + // S7: a grant that verified but only over plaintext is not the same failure as "you were + // never given this server" — it names a fixable cause (HTTPS to the server), and the + // ordinary copy sends the user to ask their friend for access they already have. + let insecure_only = probes.iter().any(|p| p.outcome == Outcome::InsecureOnly) + || admission_failures.iter().any(|(_, evidence)| + *evidence == plx_plex::plex::EndpointAdmission::InsecureOnly); + let refusal = admission_failures.iter().find_map(|(name, evidence)| match evidence { + plx_plex::plex::EndpointAdmission::Refused(status) => Some((name, *status)), + _ => None, + }); + let malformed = admission_failures.iter().any(|(_, evidence)| + *evidence == plx_plex::plex::EndpointAdmission::Malformed); + // Why each server that no route verified could not be used. A probe that verified (and was + // then refused at admission, or only over plaintext) is not in here: the arms above own it. + let mut causes = FailureCauses::default(); + for probe in &probes { + if let Some(cause) = probe.cause() { causes.push(&probe.machine_id, cause); } + } + let probe_cause = causes.worst(); + log(&format!( + "auth: profile switch -> {}", + if insecure_only { "verified only over plaintext" } + else if refusal.is_some() { "server refused the profile credential" } + else if malformed { "server returned a malformed authenticated response" } + else if !admission_failures.is_empty() { "no server admitted the profile" } + else { match probe_cause { + Some(Cause::TlsUntrusted { .. }) => "a server's certificate is not trusted by this TV", + Some(Cause::Unauthorized) => "no server access", + Some(Cause::Unreachable) | None => "no server answered", + } }, + )); + if !(insecure_only || refusal.is_some() || malformed || !admission_failures.is_empty()) { + log(&causes.log_line()); + } + output.terminal(AuthProgress::ProfileSwitch(ProfileSwitchProgress { + epoch, + expected, + outcome: ProfileSwitchOutcomeProgress::Failed { + error: if insecure_only { + discovery_insecure_only_message().to_owned() + } else if let Some((name, _)) = refusal { + plx_platform::i18n::msg::browse_auth_server_profile_refused(&tile.title, &name) + } else if malformed { + plx_platform::i18n::msg::browse_auth_switch_invalid().into() + } else if !admission_failures.is_empty() { + plx_platform::i18n::msg::browse_auth_switch_failed().into() + } else { + // Closed precedence, strongest first: a certificate this TV does not trust (the + // person can fix it by updating), a 401 (the profile has no grant — the ONLY + // case `no_source_access` is true of), then silence. A probe that left no cause at + // all cannot occur once a server was probed; it reads as silence, never as a refusal. + match probe_cause { + Some(Cause::TlsUntrusted { .. }) => plx_platform::i18n::msg::browse_auth_tls_untrusted().into(), + Some(Cause::Unauthorized) => plx_platform::i18n::msg::browse_auth_no_source_access(&tile.title), + Some(Cause::Unreachable) | None => plx_platform::i18n::msg::browse_auth_servers_unreachable().into(), + } + }, + pin_denied: false, + }, + })); + return; + }; + + log("auth: profile switch -> ok (per-user server token)"); + let server = server_ref(&primary); + let plex_tv_token = (!user.auth_token.is_empty()).then(|| user.auth_token.clone()); + let user = UserRef { + id: user.id, + uuid: seated_uuid(&user, &tile), + title: user.title, + thumb: tile.thumb, + token: primary.token.clone(), + plex_tv_token, + extensions: Default::default(), + }; + if !output.live() { return; } + // Carry forward whatever this uuid's PRIOR seating cached in `extensions` — the serde-flatten + // catch-all for fields this build does not model (forward compatibility with a newer build + // that wrote this session). `remember_profile` below replaces that uuid's whole cache entry, + // so building a fresh one with `Default::default()` here silently erased it (Copilot review on + // PR #105, finding 3). + let carried_extensions = stored + .profiles + .iter() + .find(|p| p.uuid == user.uuid) + .map(|p| p.extensions.clone()) + .unwrap_or_default(); + let cache = ProfileCreds { + uuid: user.uuid.clone(), + user: user.clone(), + server: server.clone(), + sources: cached_sources, + pin: pin + .as_deref() + .filter(|value| !value.is_empty()) + .map(session::PinVerifier::new), + extensions: carried_extensions, + }; + let next_identity = SessionIdentity { + client_id: expected.client_id.clone(), + account_token: expected.account_token.clone(), + profile_uuid: user.uuid.clone(), + }; + if !output.progress(AuthProgress::ProfileSwitch(ProfileSwitchProgress { + epoch, + expected, + outcome: ProfileSwitchOutcomeProgress::Ready { + delta: ProfileDelta { + server, + sources: initial, + user, + cache: Some(cache), + }, + probes: probes.clone(), + }, + })) { return; } + + for &i in &grants { + if probed[i] { + continue; + } + if !output.live() { return; } + io.gap(); + if !output.live() { return; } + let (mut winner, mut settled) = io.probe_after(&resources[i], &household, &[]); + if !output.live() { return; } + if winner.is_none() { + if let Some(cached) = stored.sources.iter() + .find(|source| source.machine_id == resources[i].client_identifier) { + if let Some((cached_winner, cached_settled)) = + io.probe_cached(&resources[i], cached, &household, &[]) { + winner = cached_winner; + settled = cached_settled.after_fresh(&settled); + } + } + } + if !output.live() { return; } + if let Some(previous) = probes.iter_mut() + .find(|probe| probe.machine_id == resources[i].client_identifier) { + if previous.outcome != Outcome::Reachable || settled.outcome == Outcome::Reachable { + *previous = settled; + } + } else { + probes.push(settled); + } + if let Some(winner) = winner { reached.push(winner); } + } + output.terminal(AuthProgress::ProfileRoster(ProfileRosterProgress { + epoch, + expected: next_identity, + resources, + reached, + probes, + })); +} + +pub(super) struct LiveRetryClock<'a> { + pub(super) output: &'a dyn owner::ObservationSink, + pub(super) started: Instant, +} + +impl RetryClock for LiveRetryClock<'_> { + fn elapsed(&self) -> Duration { clock_elapsed(self.started) } + fn wait(&mut self, duration: Duration) -> bool { + cancellable_wait_while(duration, || self.output.live()) + } +} + +pub(super) struct LiveFnClock<'a> { pub(super) live: &'a dyn Fn() -> bool, pub(super) started: Instant } + +impl RetryClock for LiveFnClock<'_> { + fn elapsed(&self) -> Duration { clock_elapsed(self.started) } + fn wait(&mut self, duration: Duration) -> bool { + cancellable_wait_while(duration, self.live) + } +} + +pub(super) struct LivePin<'a> { + pub(super) ac: &'a AccountClient, + pub(super) id: i64, + pub(super) output: &'a dyn owner::ObservationSink, + pub(super) started: Instant, + pub(super) epoch: u64, + /// Which code of the flow this is, 1-based — the report's code generation. + pub(super) generation: u32, +} + +impl PinWatch for LivePin<'_> { + fn poll(&mut self) -> PinPoll { + scripted::signin_trouble_poll().unwrap_or_else(|| self.ac.poll_pin(self.id)) + } + fn wait(&mut self, d: Duration) -> bool { + // SLICED, so a cancel is noticed within a slice however far the backoff has grown. The + // worker's answer would be discarded anyway, but a thread that lingers for the whole of a + // 16 s backoff after the user has left the screen is a thread the next flow shares the + // device with. + cancellable_wait_while(d, || self.output.live()) + } + fn elapsed(&self) -> Duration { + clock_elapsed(self.started) + } + fn link_trouble(&mut self, stall: Option) { + let trouble = stall.map(|s| { + IncidentContext::new(IncidentKind::LinkStalled, Some(s.last)) + .with_link_state(s.unanswered, Some(s.failing_for), self.generation) + }); + self.output.progress(LoginProgress::LinkTrouble { epoch: self.epoch, trouble }.into()); + } +} + +impl AdmissionBudget { + pub(super) fn attempt( + &mut self, + request: impl FnOnce(Instant) -> plx_plex::plex::EndpointAdmission, + ) -> plx_plex::plex::EndpointAdmission { + plx_base::step::assert_io_allowed("session::attempt"); + self.attempt_on(clock_now, request) + } +} + +pub(super) fn admission_clock() -> fn() -> Instant { + plx_base::step::assert_io_allowed("session::admission_clock"); clock_now } diff --git a/rust-modules/session/src/auth_test_support.rs b/rust-modules/session/src/auth_test_support.rs index c07a6b1d3a..26695e8826 100644 --- a/rust-modules/session/src/auth_test_support.rs +++ b/rust-modules/session/src/auth_test_support.rs @@ -309,7 +309,8 @@ pub fn signed_in_as(uuid: &str) -> Session { } } -/// Extract one `fn NAME(` … `}` body, verbatim, from this file's OWN source. A tiny lexer — +/// Extract one `fn NAME(` … `}` body, verbatim, from the supplied auth source or its live +/// worker module. A tiny lexer — /// tracking only whether it is inside a `"…"` string literal or a `//` line comment — rather /// than a bare brace count, because several of these functions log a `format!("…{x}…")` whose /// placeholder braces are balanced on their own and would otherwise silently agree with a real @@ -317,9 +318,10 @@ pub fn signed_in_as(uuid: &str) -> Session { /// it. pub fn extract_fn_body<'a>(src: &'a str, name: &str) -> &'a str { let needle = format!("fn {name}("); + let src = if src.contains(&needle) { src } else { include_str!("auth/ports.rs") }; let start = src .find(&needle) - .unwrap_or_else(|| panic!("no `{needle}` in auth.rs — did it get renamed?")); + .unwrap_or_else(|| panic!("no `{needle}` in auth source modules — did it get renamed?")); let open = src[start..] .find('{') .map(|i| start + i) diff --git a/rust-modules/src/app/adapters/session.rs b/rust-modules/src/app/adapters/session.rs index 561e5582ae..9f69cf1923 100644 --- a/rust-modules/src/app/adapters/session.rs +++ b/rust-modules/src/app/adapters/session.rs @@ -1718,7 +1718,8 @@ mod tests { plx_plex::plex::session::revoke_cached_session(); let mut init = SessionInit::captured((*disk).clone()); init.epoch = 1; - init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::Ready }, + // Generic adapter/OCC/durability fixtures use background correlation, not a Ready handoff. + init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::ServerRoster }, expected: Identity::of(&disk), lifecycle: None, last_arrival: Some(0), phase: StreamPhase::Running, capture: None, admission: plx_session::auth::owner::AdmissionState::NotRequested }); @@ -1757,7 +1758,7 @@ mod tests { let disk = plx_plex::plex::session::peek(); let mut init = SessionInit::captured((*disk).clone()); init.epoch = 1; - init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::Ready }, + init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::ServerRoster }, expected: Identity::of(&disk), lifecycle: None, last_arrival: Some(0), phase: StreamPhase::Running, capture: None, admission: plx_session::auth::owner::AdmissionState::NotRequested }); @@ -1826,7 +1827,7 @@ mod tests { let disk = plx_plex::plex::session::peek(); let mut init = SessionInit::captured((*disk).clone()); init.epoch = 1; - init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::Ready }, + init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::ServerRoster }, expected: Identity::of(&disk), lifecycle: None, last_arrival: Some(0), phase: StreamPhase::Running, capture: None, admission: plx_session::auth::owner::AdmissionState::NotRequested }); @@ -2044,7 +2045,7 @@ mod tests { let disk = plx_plex::plex::session::peek(); let mut init = SessionInit::captured((*disk).clone()); init.epoch = 1; - init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::Ready }, + init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::ServerRoster }, expected: Identity::of(&disk), lifecycle: None, last_arrival: Some(0), phase: StreamPhase::Running, capture: None, admission: plx_session::auth::owner::AdmissionState::NotRequested }); @@ -2111,8 +2112,8 @@ mod tests { /// `client_id` makes `update_with_outcome` refuse before `edit` ever runs. #[test] fn a_fresh_sign_in_over_an_unopenable_envelope_is_persisted_for_the_next_launch() { - use plx_session::auth::owner::{CommitAdmission, CommitDelta, CredentialPatch, Identity, Pending, - PendingCommit, SessionInit, SessionMachine, StreamPhase}; + use plx_session::auth::owner::{CommitAdmission, Command, CredentialPatch, Identity, SessionEvent, SessionFx, + SessionInit, SessionMachine}; use plx_plex::plex::session::async_persistence::PersistencePurpose; let _serial = plx_base::testlock::serial(); @@ -2184,15 +2185,21 @@ mod tests { let disk = plx_plex::plex::session::peek(); let mut init = SessionInit::captured((*disk).clone()); - init.epoch = 1; - init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::Login }, - expected: Identity::of(&disk), lifecycle: None, last_arrival: Some(0), - phase: StreamPhase::Running, capture: None, - admission: plx_session::auth::owner::AdmissionState::NotRequested }); - init.pending_commit = Some(PendingCommit { req: 1, epoch: 1, arrival: 0, terminal: true, - writes_credentials: true, receipt: None, delta: CommitDelta::default(), - admitted_revision: None, purpose: Some(PersistencePurpose::Final), fresh: true }); - let owner = SessionMachine::from_init(init); + // Capture the completed fresh sign-in, retaining the Locked disk identity as its OCC fence. + init.phase = plx_session::auth::Phase::Ready; + init.apply_pending = true; + init.authorized_in_flow = true; + init.persisted.client_id = "cid-fresh".into(); + init.persisted.account_token = "acct".into(); + init.persisted.server.address = "127.0.0.1".into(); + init.persisted.server.port = 32400; + init.persisted.server.token = "synthetic-pms".into(); + init.persisted.user.token = "synthetic-pms".into(); + let mut owner = SessionMachine::from_init(init); + let effects = plx_session::auth::owner::scenarios::step(&mut owner, SessionEvent::Command(Command::TakeReady)); + assert!(matches!(effects.as_slice(), [SessionFx::Commit { req: 1, epoch: 1, arrival: 0, plan }] + if plan.purpose == PersistencePurpose::Final + && plan.authority == plx_plex::plex::session::SaveAuthority::FreshReauthentication)); let mut next = (*disk).clone(); next.client_id = "cid-fresh".into(); @@ -2256,7 +2263,7 @@ mod tests { let expected = Identity::of(&disk); let mut init = SessionInit::captured((*disk).clone()); init.epoch = 1; - init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::Ready }, + init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::ServerRoster }, expected: expected.clone(), lifecycle: None, last_arrival: Some(0), phase: StreamPhase::Running, capture: None, admission: plx_session::auth::owner::AdmissionState::NotRequested }); @@ -2285,13 +2292,36 @@ mod tests { } } + #[test] + fn fixture_adapter_has_no_permit_for_a_forged_idle_ready_commit() { + use plx_session::auth::owner::{AdmissionState, CommitDelta, Identity, Pending, PendingCommit, + SessionInit, SessionMachine, StreamPhase}; + let disk = plx_plex::plex::session::Session { client_id: "synthetic-client".into(), ..Default::default() }; + let mut init = SessionInit::captured(disk.clone()); + init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::Ready }, + expected: Identity::of(&disk), lifecycle: None, last_arrival: Some(0), phase: StreamPhase::Running, + capture: None, admission: AdmissionState::NotRequested }); + let mut delta = CommitDelta::default(); + delta.ready = Some(false); + init.pending_commit = Some(PendingCommit { req: 1, epoch: 1, arrival: 0, terminal: true, + writes_credentials: true, receipt: None, delta, admitted_revision: None, purpose: None, fresh: false }); + let expected = serde_json::to_value(&init).unwrap(); + let owner = SessionMachine::from_init(init); + let mut adapter = SessionAdapter::fixture_with(disk); + assert!(owner.commit_permit(1, 1, 0).is_none()); + assert_eq!(serde_json::to_value(owner.snapshot_init()).unwrap(), expected); + assert!(adapter.fixture_resources().disk.account_token.is_empty()); + assert!(adapter.fixture_resources().profile.is_none()); + assert!(adapter.fixture_resources().registry_writes.is_empty()); + } + #[test] fn fixture_commit_uses_latest_preferences_and_never_writes_another_adapter() { use plx_session::auth::owner::{CommitDelta, CredentialPatch, Identity, Pending, PendingCommit, SessionInit, SessionMachine, StreamPhase}; let disk = plx_plex::plex::session::Session { client_id: "synthetic-client".into(), ..Default::default() }; let mut init = SessionInit::captured(disk.clone()); - init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::Ready }, + init.pending.insert(1, Pending { key: SessionWorkKey { epoch: 1, op: SessionOp::ServerRoster }, expected: Identity::of(&disk), lifecycle: None, last_arrival: Some(0), phase: StreamPhase::Running, capture: None, admission: plx_session::auth::owner::AdmissionState::NotRequested }); init.pending_commit = Some(PendingCommit { req: 1, epoch: 1, arrival: 0, terminal: true, diff --git a/rust-modules/src/app/adapters/stores.rs b/rust-modules/src/app/adapters/stores.rs index c560a0fb20..13b5b10ac7 100644 --- a/rust-modules/src/app/adapters/stores.rs +++ b/rust-modules/src/app/adapters/stores.rs @@ -76,6 +76,7 @@ use plx_data::pms::{launch_hubs_job, HubRequest, HubsPort}; use plx_data::stores::{Admission, StoreJob}; use plx_data::stores::notify_job::{finish_notify_stream_job, NotifyStreamReq, NotifyStreamPort, NotifyTerminal}; use plx_data::search::recents::{finish_save_recents_job, SaveRecentsPort, SaveRecentsReq}; +use plx_data::browse::preferences_job::{finish_browse_preferences_job, BrowsePreferencesReq, BrowsePreferencesPort}; use plx_data::search::{finish_search_job, SearchPort, SearchReq}; use plx_data::subsearch::{finish_subsearch_job, SubSearchPort, SubSearchReq}; use plx_data::viewstate::{finish_view_write_job, ViewWritePort, ViewWriteReq}; @@ -87,6 +88,69 @@ use crate::app::bootstrap::HomeIo; /// The viewer's time zone for a bands read, as the platform layer reads it from the OS: this runner is /// where the zone may be read (the data job takes it as two plain functions, `Zone`, and no machine /// reads it), and a calendar family's edges are converted with it. +pub(crate) fn launch_watchlist_write( + job: Job, + port: plx_data::stores::watchlist_job::WritePort, + io: std::sync::Arc, +) { + let addr = job.addr; + let refusal = port.clone(); + if !plx_base::task::spawn_small("wlist-write", move || { + if port.start() { + plx_data::stores::watchlist_job::finish_write_job(&port, addr, job.req, &*io); + } + }) { refusal.refused(addr); } +} + +fn launch_watchlist_resolve_with( + job: Job, + port: plx_data::stores::watchlist_job::ResolvePort, + spawn: impl FnOnce(Box) -> bool, +) { + let addr = job.addr; + let refusal = port.clone(); + if !spawn(Box::new(move || { + if port.start() { + plx_data::stores::watchlist_job::finish_resolve_job(&port, addr, job.req, plx_plex::plex::client_for); + } + })) { refusal.refused(addr); } +} + + +fn watchlist_day() -> Option { + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(); + Some((secs / 86_400) as i64) +} +fn watchlist_auth_current(auth: &plx_data::watchlist::WatchlistAuth) -> bool { + let profile = plx_plex::plex::session::current_snapshot(); + let credential = profile.user.as_ref().and_then(plx_plex::plex::session::plex_tv_credential); + auth.matches_lease(&profile, credential.as_deref()) +} +fn watchlist_io(input: plx_data::stores::watchlist_job::Snapshot) -> std::sync::Arc { + std::sync::Arc::new(plx_data::stores::watchlist_job::ports::LiveWatchlistIo { + input, lookup: plx_plex::plex::client_for, lease: watchlist_auth_current, + }) +} +fn launch_watchlist_stream_with(job: StoreJob, scripted: Option>, + spawn: impl FnOnce(Box) -> bool) { + use plx_data::stores::watchlist_job::{finish_list_job, finish_rematch_job, finish_delta_job}; + let (addr, refusal, worker): (_, _, Box) = match job { + StoreJob::WatchlistList(job, port) => { + let io = scripted.unwrap_or_else(|| watchlist_io(job.req.input.clone())); + (job.addr, port.clone(), Box::new(move || finish_list_job(&port, job.addr, job.req, &*io))) + } + StoreJob::WatchlistRematch(job, port) => { + let io = scripted.unwrap_or_else(|| watchlist_io(job.req.input.clone())); + (job.addr, port.clone(), Box::new(move || finish_rematch_job(&port, job.addr, job.req, &*io))) + } + StoreJob::WatchlistDelta(job, port) => { + let io = scripted.unwrap_or_else(|| watchlist_io(job.req.input.clone())); + (job.addr, port.clone(), Box::new(move || finish_delta_job(&port, job.addr, job.req, &*io))) + } + _ => panic!("not a Watchlist stream job"), + }; + if !spawn(worker) { refusal.refused(addr); } +} fn os_zone() -> Zone { Zone { local_midnight: plx_platform::i18n::local_midnight, local_date: plx_platform::i18n::local_calendar_date } } @@ -198,7 +262,8 @@ pub(crate) enum StoreRunner { /// (`run_held` resolves its client when it runs the job). A kind in `live` starts as `Live` /// starts it. #[cfg(test)] - Held { parked: Vec, live: &'static [LiveKind], notify: NotifyTransport }, + Held { parked: Vec, live: &'static [LiveKind], notify: NotifyTransport, + watchlist_write: Option>, watchlist_streams_held: bool }, } /// Boot-selected transport, not a second Notify state machine. Scripts must be finite; @@ -287,7 +352,7 @@ impl StoreRunner { /// worker (the Related rigs land the window with `land_related_for_test`), so those are parked. #[cfg(test)] pub(crate) fn held() -> Self { - Self::Held { parked: Vec::new(), live: &[LiveKind::Hubs, LiveKind::MetaSeason, LiveKind::BrowsePage, LiveKind::BrowseDiscovery, LiveKind::MetaAltSources, LiveKind::NotifyStream], notify: NotifyTransport::Refuse } + Self::Held { parked: Vec::new(), live: &[LiveKind::Hubs, LiveKind::MetaSeason, LiveKind::BrowsePage, LiveKind::BrowseDiscovery, LiveKind::MetaAltSources, LiveKind::NotifyStream], notify: NotifyTransport::Refuse, watchlist_write: None, watchlist_streams_held: false } } /// TEST ONLY: park the Library listing's page reads of a held runner too (the Home Hubs read @@ -305,7 +370,7 @@ impl StoreRunner { /// chooses to settle them. #[cfg(test)] pub(crate) fn held_all() -> Self { - Self::Held { parked: Vec::new(), live: &[], notify: NotifyTransport::Refuse } + Self::Held { parked: Vec::new(), live: &[], notify: NotifyTransport::Refuse, watchlist_write: None, watchlist_streams_held: false } } /// Start `job`, admitting it through the tape when its kind is taped (Detail, Collection, @@ -313,6 +378,11 @@ impl StoreRunner { /// port: the fetch's own, or a refusal when nothing was started. pub(crate) fn start(&mut self, job: StoreJob) { match job { + StoreJob::WatchlistList(job, port) => self.start_watchlist_stream(StoreJob::WatchlistList(job, port)), + StoreJob::WatchlistRematch(job, port) => self.start_watchlist_stream(StoreJob::WatchlistRematch(job, port)), + StoreJob::WatchlistDelta(job, port) => self.start_watchlist_stream(StoreJob::WatchlistDelta(job, port)), + StoreJob::WatchlistResolve(job, port) => self.start_watchlist_resolve(job, port), + StoreJob::WatchlistWrite(job, port) => self.start_watchlist_write(job, port), StoreJob::Detail(job, port) => self.start_detail(job, port), StoreJob::Collection(job, port) => self.start_collection(job, port), StoreJob::Person(job, port) => self.start_person(job, port), @@ -325,6 +395,7 @@ impl StoreRunner { StoreJob::BrowsePage(job, port) => self.start_browse_page(job, port), StoreJob::BrowseDiscovery(job, port) => self.start_browse_discovery(job, port), StoreJob::Search(job, port) => self.start_search(job, port), + StoreJob::BrowsePreferences(job, port) => self.start_browse_preferences(job, port), StoreJob::SaveRecents(job, port) => self.start_save_recents(job, port), StoreJob::ViewWrite(job, port) => self.start_view_write(job, port), StoreJob::MetaSeason(job, port) => self.start_meta_season(job, port), @@ -369,7 +440,9 @@ impl StoreRunner { } } // Not a Home kind: `Admission::Home` routed here only the kinds the arm above names. - other @ (StoreJob::Detail(..) + other @ (StoreJob::WatchlistList(..) | StoreJob::WatchlistRematch(..) | StoreJob::WatchlistDelta(..) + | StoreJob::WatchlistWrite(..) | StoreJob::WatchlistResolve(..) + | StoreJob::Detail(..) | StoreJob::Collection(..) | StoreJob::Person(..) | StoreJob::Catalog(..) @@ -379,6 +452,7 @@ impl StoreRunner { | StoreJob::BrowseDirectory(..) | StoreJob::BrowsePage(..) | StoreJob::Search(..) + | StoreJob::BrowsePreferences(..) | StoreJob::SaveRecents(..) | StoreJob::ViewWrite(..) | StoreJob::MetaSeason(..) @@ -467,7 +541,10 @@ impl StoreRunner { old_port.done(old.addr, ((old.req.sid, old.req.rk), None)); } kept @ ( - StoreJob::Collection(..) + StoreJob::WatchlistList(..) | StoreJob::WatchlistRematch(..) | StoreJob::WatchlistDelta(..) + | StoreJob::WatchlistWrite(..) + | StoreJob::WatchlistResolve(..) + | StoreJob::Collection(..) | StoreJob::Person(..) | StoreJob::Hubs(..) | StoreJob::Catalog(..) @@ -478,7 +555,8 @@ impl StoreRunner { | StoreJob::BrowsePage(..) | StoreJob::BrowseDiscovery(..) | StoreJob::Search(..) - | StoreJob::SaveRecents(..) + | StoreJob::BrowsePreferences(..) + | StoreJob::SaveRecents(..) | StoreJob::ViewWrite(..) | StoreJob::MetaSeason(..) | StoreJob::MetaEpisodes(..) @@ -549,8 +627,8 @@ impl StoreRunner { let request = job.req.admission(); let admission = port.clone(); if !plx_data::stores::tape::admit(request, || self.launch_person(job, port)) { - // Nothing was started, so nothing will ever answer on its own: the refusal hands the - // slot's claim back, and the next pump asks again. + // An unstarted request still owes one addressed terminal. The Bridge consumes it + // in this drain; the owner releases its claim and applies its retry policy. admission.refused(addr); } } @@ -588,6 +666,55 @@ impl StoreRunner { } } + + + pub(crate) fn watchlist_snapshot(&self, keys: &ClientKeys, cache: &mut plx_data::stores::watchlist_job::SnapshotCache) -> plx_data::stores::watchlist_job::Snapshot { + match self { + Self::Live => cache.capture(keys, watchlist_day()), + #[cfg(test)] + Self::Held { watchlist_write: Some(io), .. } => plx_data::stores::watchlist_job::Snapshot::scripted(&**io), + #[cfg(test)] + Self::Held { .. } => cache.capture(keys, watchlist_day()), + } + } + #[cfg(test)] + pub(crate) fn hold_watchlist_streams(&mut self, hold: bool) { + if let Self::Held { watchlist_streams_held, .. } = self { *watchlist_streams_held = hold; } + if !hold { self.run_held_where(|j| matches!(j, StoreJob::WatchlistList(..) | StoreJob::WatchlistRematch(..) | StoreJob::WatchlistDelta(..))); } + } +fn start_watchlist_stream(&mut self, job: StoreJob) { + match self { + Self::Live => launch_watchlist_stream_with(job, None, |worker| plx_base::task::spawn_small("wlist", worker)), + #[cfg(test)] + Self::Held { watchlist_write: Some(io), watchlist_streams_held: false, .. } => { + launch_watchlist_stream_with(job, Some(io.clone()), |worker| { worker(); true }); + } + #[cfg(test)] + Self::Held { parked, .. } => parked.push(job), + } + } + fn start_watchlist_resolve(&mut self, job: Job, + port: plx_data::stores::watchlist_job::ResolvePort) { + match self { + Self::Live => { + launch_watchlist_resolve_with(job, port, |worker| plx_base::task::spawn_small("wlist-resolve", worker)); + } + #[cfg(test)] + Self::Held { parked, .. } => parked.push(StoreJob::WatchlistResolve(job, port)), + } + } + + fn start_watchlist_write(&mut self, job: Job, + port: plx_data::stores::watchlist_job::WritePort) { + match self { + Self::Live => { + launch_watchlist_write(job, port, watchlist_io(Default::default())); + } + #[cfg(test)] + Self::Held { parked, .. } => parked.push(StoreJob::WatchlistWrite(job, port)), + } + } + fn launch_catalog(&mut self, job: Job, port: CatalogPort) -> bool { match self { Self::Live => { @@ -682,6 +809,30 @@ impl StoreRunner { } } + fn start_browse_preferences(&mut self, job: Job, port: BrowsePreferencesPort) { + let addr = job.addr; + let refusal = port.clone(); + if !job.req.matches_account(&plx_plex::plex::session::peek()) + || !job.req.matches_tenure(plx_plex::plex::session::tenure()) { + refusal.refused(addr); + return; + } + let launched = match self { + Self::Live => { + let _ = plx_base::storage_worker::submit_retained(move || { + finish_browse_preferences_job(&port, addr, job.req); + }); + true + } + #[cfg(test)] + Self::Held { parked, .. } => { + parked.push(StoreJob::BrowsePreferences(job, port)); + true + } + }; + if !launched { refusal.refused(addr); } + } + fn launch_save_recents(&mut self, job: Job, port: SaveRecentsPort) -> bool { match self { Self::Live => { @@ -1051,6 +1202,11 @@ impl StoreRunner { if let Self::Held { notify, .. } = self { *notify = transport; } } + #[cfg(test)] + pub(crate) fn set_watchlist_write_io(&mut self, io: std::sync::Arc) { + if let Self::Held { watchlist_write, .. } = self { *watchlist_write = Some(io); } + } + fn start_notify_stream(&mut self, job: Job, port: NotifyStreamPort) { let transport = self.notify_transport(); self.start_notify_stream_with(job, port, |req| transport.resolve(req), @@ -1117,15 +1273,47 @@ impl StoreRunner { self.run_held_where(|job| job.store() == id) } + + #[cfg(test)] + pub(crate) fn run_held_watchlist_writes(&mut self) -> usize { + self.run_held_where(|job| matches!(job, StoreJob::WatchlistWrite(..))) + } + + + #[cfg(test)] + pub(crate) fn take_held_watchlist_resolves(&mut self) -> Vec { + let Self::Held { parked, .. } = self else { return Vec::new() }; + let (take, keep) = std::mem::take(parked).into_iter() + .partition(|job| matches!(job, StoreJob::WatchlistResolve(..))); + *parked = keep; + take + } + #[cfg(test)] fn run_held_where(&mut self, wanted: impl Fn(&StoreJob) -> bool) -> usize { let transport = self.notify_transport(); + let watchlist_write = match &*self { Self::Held { watchlist_write, .. } => watchlist_write.clone(), Self::Live => None }; let Self::Held { parked, .. } = self else { return 0 }; let (run, keep): (Vec<_>, Vec<_>) = std::mem::take(parked).into_iter().partition(|job| wanted(job)); *parked = keep; let n = run.len(); for job in run { match job { + stream @ (StoreJob::WatchlistList(..) | StoreJob::WatchlistRematch(..) | StoreJob::WatchlistDelta(..)) => { + if let Some(io) = &watchlist_write { + launch_watchlist_stream_with(stream, Some(io.clone()), |worker| { worker(); true }); + } else { launch_watchlist_stream_with(stream, None, |_| false); } + } + StoreJob::WatchlistResolve(job, port) => { + if port.start() { + plx_data::stores::watchlist_job::finish_resolve_job(&port, job.addr, job.req, plx_plex::plex::client_for); + } + } + StoreJob::WatchlistWrite(job, port) => { + if let Some(io) = &watchlist_write { + if port.start() { plx_data::stores::watchlist_job::finish_write_job(&port, job.addr, job.req, &**io); } + } else { port.refused(job.addr); } + }, StoreJob::Detail(job, port) => { // The client is resolved when the job runs (a live one is resolved by // `start_detail`, at the admission); a server with none answers the failure. @@ -1225,6 +1413,7 @@ impl StoreRunner { None => port.refused(job.addr), } } + StoreJob::BrowsePreferences(job, port) => finish_browse_preferences_job(&port, job.addr, job.req), StoreJob::SaveRecents(job, port) => finish_save_recents_job(&port, job.addr, job.req), StoreJob::ViewWrite(job, port) => { // The registry may have moved on since the job was parked: a write whose @@ -1588,9 +1777,17 @@ mod tests { assert_eq!(sid.raw(), 0, "slot arithmetic below assumes the first server"); if controlled { tape::init(None, false); } let mut store = PersonStore::default(); - assert!(store.run(PersonCmd::Open { - sid, key: "19".into(), guid: PERSON_GUID.into(), name: "Actor".into(), thumb: String::new() })); - store.pump(plx_machine::landgate::fixture_gate(), ®istry_keys()); + let keys = registry_keys(); + let session = plx_plex::plex::session::peek_settled(); + let input = plx_data::person::PersonInput { keys: &keys, session: session.as_ref(), + profile_scope: 0, owner_epoch: 0, profile_generation: 0, tenure: 0, profile_key: "", + visible_generation: plx_plex::plex::session::visible_generation(), controlled, + profile_refused: plx_plex::plex::discover::person_profile_refused(PERSON_GUID), + credits_refused: plx_plex::plex::discover::person_credits_refused(PERSON_GUID), + dev_bio: None, dev_credits: None }; + assert!(store.run_with_input(PersonCmd::Open { + sid, key: "19".into(), guid: PERSON_GUID.into(), name: "Actor".into(), thumb: String::new() }, &input)); + store.pump(plx_machine::landgate::fixture_gate(), &input); let (mut local, mut global) = (Vec::new(), Vec::new()); for job in store.take_jobs() { let StoreJob::Person(ref j, _) = job else { panic!("not a person job") }; @@ -1629,7 +1826,15 @@ mod tests { "the request the runner admitted is the recorded shape, admitted"); assert!(store.adapter_for_test().has_mail_for_test(MEDIA), "the worker answered"); tape::reset_for_test(); - store.pump(plx_machine::landgate::fixture_gate(), ®istry_keys()); + let (person_keys, person_session) = (registry_keys(), plx_plex::plex::session::peek_settled()); + let person_input = plx_data::person::PersonInput { + profile_scope: 0, owner_epoch: 0, profile_generation: 0, tenure: 0, profile_key: "", + keys: &person_keys, session: person_session.as_ref(), controlled: false, + visible_generation: plx_plex::plex::session::visible_generation(), + profile_refused: plx_plex::plex::discover::person_profile_refused(PERSON_GUID), + credits_refused: plx_plex::plex::discover::person_credits_refused(PERSON_GUID), dev_bio: None, dev_credits: None, + }; + store.pump(plx_machine::landgate::fixture_gate(), &person_input); assert!(!store.adapter_for_test().busy_for_test(MEDIA), "taking the one answer released the claim"); } @@ -1659,12 +1864,16 @@ mod tests { fn a_person_job_the_tape_does_not_admit_is_refused_once_and_its_claim_comes_back() { let _serial = plx_base::testlock::serial(); let _rig = CollectionRig; - let (sid, store, job, _) = person_requests(false); + let (sid, mut store, job, _) = person_requests(false); let admission = media_admission(sid, false); tape::init(None, true); tape::begin([admission.clone()].into(), Default::default()); StoreRunner::live().start(job); + { + let _step = plx_base::step::StepScope::enter(); + store.land_launch_refusals(); + } plx_base::task::drain_workers_for_test(); assert_eq!(tape::finish(), (vec![admission], None), @@ -1699,11 +1908,15 @@ mod tests { fn a_person_job_whose_client_the_registry_has_moved_on_from_is_not_started() { let _serial = plx_base::testlock::serial(); let _rig = CollectionRig; - let (sid, store, job, _) = person_requests(false); + let (sid, mut store, job, _) = person_requests(false); plx_plex::plex::client_for(sid).expect("registered").set_token("rotated"); tape::init(None, false); StoreRunner::live().start(job); + { + let _step = plx_base::step::StepScope::enter(); + store.land_launch_refusals(); + } plx_base::task::drain_workers_for_test(); assert_eq!(tape::finish(), (vec![media_admission(sid, false)], None), @@ -1741,7 +1954,7 @@ mod tests { fn a_parked_person_job_whose_client_is_gone_when_it_runs_is_refused() { let _serial = plx_base::testlock::serial(); let _rig = CollectionRig; - let (_, store, job, mut global) = person_requests(true); + let (_, mut store, job, mut global) = person_requests(true); let mut runner = StoreRunner::held(); runner.start(job); @@ -1750,6 +1963,10 @@ mod tests { assert!(adapter.busy_for_test(MEDIA) && adapter.busy_for_test(PROFILE), "parked, still out"); plx_plex::plex::reset_servers_for_test(); assert_eq!(runner.run_held(), 2); + { + let _step = plx_base::step::StepScope::enter(); + store.land_launch_refusals(); + } assert!(!adapter.busy_for_test(MEDIA), "the refusal handed the claim back"); assert!(!adapter.has_mail_for_test(MEDIA)); @@ -1902,17 +2119,29 @@ mod tests { plx_plex::plex::reset_servers_for_test(); let sid = plx_plex::plex::register_for_test("runner", "127.0.0.1", 9, "t", "cid"); let mut store = SearchStore::default(); - search_store_pump(&mut store, 0.0); // the first pump observes the roster - assert!(store.run(SearchCmd::SetQuery("wallace".into()))); - search_store_pump(&mut store, 0.3); + let host_capture = plx_data::search::fixture_input(); + let search_input = host_capture.input(); + let directory = DirectorySnapshot::default(); + search_store_pump_with_input(&mut store, 0.0, &search_input); // the first pump observes the roster + assert!(store.run_with_directory_and_input( + SearchCmd::SetQuery("wallace".into()), directory.view(), &search_input)); + search_store_pump_with_input(&mut store, 0.3, &search_input); let mut jobs = store.take_jobs(); assert_eq!(jobs.len(), 1, "one registered server, one request"); (sid, store, jobs.remove(0)) } fn search_store_pump(store: &mut SearchStore, dt: f32) { + let captured = plx_data::search::fixture_input(); + search_store_pump_with_input(store, dt, &captured.input()); + } + + fn search_store_pump_with_input( + store: &mut SearchStore, dt: f32, input: &plx_data::search::SearchInput<'_>, + ) { let directory = DirectorySnapshot::default(); - store.pump_with_directory_and_gate(dt, directory.view(), plx_machine::landgate::fixture_gate(), ®istry_keys()); + store.pump_with_directory_and_input_and_gate( + dt, directory.view(), plx_machine::landgate::fixture_gate(), input); } fn search_store_claim_held(store: &SearchStore, sid: ServerId) -> bool { @@ -1970,6 +2199,10 @@ mod tests { let _serial = plx_base::testlock::serial(); let _rig = CollectionRig; let (sid, mut store, job) = search_store_request(); + // Keep the host publication that admitted this request: observing the retoken instead + // supersedes the query and intentionally retires its refusal/backoff with that scope. + let captured = plx_data::search::fixture_input(); + let input = captured.input(); plx_plex::plex::client_for(sid).expect("registered").set_token("rotated"); StoreRunner::live().start(job); @@ -1977,10 +2210,10 @@ mod tests { assert!(!search_store_claim_held(&store, sid), "the refusal handed the claim back"); assert!(!search_store_has_mail(&store, sid), "nothing was read, so nothing answered"); - search_store_pump(&mut store, 0.016); + search_store_pump_with_input(&mut store, 0.016, &input); assert!(!store.has_jobs(), "backed off: no request at once"); for _ in 0..30 { - search_store_pump(&mut store, 0.016); + search_store_pump_with_input(&mut store, 0.016, &input); assert!(!store.has_jobs(), "and none while the wait runs"); } } @@ -2613,6 +2846,134 @@ mod tests { assert_eq!(io.reads.load(Ordering::SeqCst), 1); } + +// Watchlist write runner coverage lives with the bridge press fixture. + #[test] + fn watchlist_resolve_cancel_before_worker_entry_prevents_execution() { + use plx_data::stores::watchlist_job::{ResolveEnd, ResolveMailbox, ResolvePort, ResolveReq}; + use plx_machine::machine::{Addr, MachineId, RequestId}; + let tag = plx_data::watchlist::Tag { profile_gen: 1, epoch: 2, req: 3 }; + let addr = Addr { to: MachineId::Store(plx_data::stores::StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let req = ResolveReq { tag, keys: ClientKeys::default(), sid: ServerId::from_raw(0), rk: "7".into() }; + let mailbox = Arc::new(ResolveMailbox::default()); + let port = ResolvePort::new(addr, &req, Arc::clone(&mailbox)); + let mut worker = None; + launch_watchlist_resolve_with(Job { addr, req }, port.clone(), |f| { worker = Some(f); true }); + port.cancel_queued(); + worker.unwrap()(); + let answers = mailbox.take(); + assert_eq!(answers.len(), 1); + assert!(matches!(answers[0].end, ResolveEnd::NotStarted)); + } + + fn watchlist_stream_fixture(kind: u8) -> (StoreJob, plx_data::stores::watchlist_job::WatchlistStreamPort, + Arc>) { + use plx_data::stores::watchlist_job::*; + use plx_machine::machine::{Addr, MachineId, RequestId}; + let tag = plx_data::watchlist::Tag { profile_gen: 1, epoch: 2, req: 3 }; + let addr = Addr { to: MachineId::Store(plx_data::stores::StoreId::Watchlist.ord()), req: RequestId(tag.req) }; + let mailbox = Arc::new(stream::StreamMailbox::default()); + let port = WatchlistStreamPort::new(addr, tag, Arc::clone(&mailbox)); + let job = match kind { + 0 => StoreJob::WatchlistList(Job { addr, req: ListReq { tag, input: Snapshot::default(), auth: AuthValue(plx_data::watchlist::WatchlistInput::for_test(1).auth().unwrap().clone()), known: Default::default(), known_gen: 0, etag: None } }, port.clone()), + 1 => StoreJob::WatchlistRematch(Job { addr, req: RematchReq { tag, input: Snapshot::default(), rows: Vec::new() } }, port.clone()), + _ => StoreJob::WatchlistDelta(Job { addr, req: DeltaReq { tag, input: Snapshot::default(), sid: ServerId::UNSET, rows: Vec::new().into() } }, port.clone()), + }; + (job, port, mailbox) + } + #[test] + fn watchlist_stream_all_three_kinds_refuse_once_without_worker_entry() { + use plx_data::stores::watchlist_job::stream::{StreamEvent, StreamEnd}; + for kind in 0..3 { + let (job, port, mail) = watchlist_stream_fixture(kind); + launch_watchlist_stream_with(job, None, |_| false); + assert!(port.start().is_none()); + let batch = mail.take(); + assert_eq!(batch.len(), 1); + assert!(matches!(batch[0].event, StreamEvent::End(StreamEnd::NotStarted))); + assert!(batch[0].ack_terminal()); + assert!(!port.is_owed()); + } + } + #[test] + fn watchlist_stream_all_three_kinds_cancel_at_actual_worker_entry() { + use plx_data::stores::watchlist_job::stream::{StreamEvent, StreamEnd}; + for kind in 0..3 { + let (job, port, mail) = watchlist_stream_fixture(kind); + let mut worker = None; + launch_watchlist_stream_with(job, None, |f| { worker = Some(f); true }); + assert!(mail.take().is_empty(), "admission is not entry"); + port.cancel(); + worker.unwrap()(); + let batch = mail.take(); + assert_eq!(batch.len(), 1); + assert!(matches!(batch[0].event, StreamEvent::End(StreamEnd::Cancelled))); + assert!(batch[0].ack_terminal()); + } + } + #[test] + fn watchlist_stream_held_jobs_survive_detail_retirement_and_refuse_on_release() { + use plx_data::stores::watchlist_job::stream::{StreamEvent, StreamEnd}; + let mut runner = StoreRunner::held(); + let mut claims = Vec::new(); + for kind in 0..3 { + let (job, port, mail) = watchlist_stream_fixture(kind); + runner.start(job); + claims.push((port, mail)); + } + if let StoreRunner::Held { parked, .. } = &mut runner { StoreRunner::retire_parked_details(parked); } + assert_eq!(runner.run_held(), 3); + for (port, mail) in claims { + let batch = mail.take(); + assert_eq!(batch.len(), 1); + assert!(matches!(batch[0].event, StreamEvent::End(StreamEnd::NotStarted))); + assert!(batch[0].ack_terminal()); + assert!(!port.is_owed()); + } + } + + #[test] + fn watchlist_resolve_live_answers_and_releases_an_unanswered_claim() { + let _serial = plx_base::testlock::serial(); + let mut store = plx_data::stores::watchlist::WatchlistStore::default(); + let sid = ServerId::from_raw(0); + store.want_hex(sid, "7"); + store.pump(); + let job = store.take_jobs().pop().unwrap(); + StoreRunner::live().start(job); + plx_base::task::drain_workers_for_test(); + store.pump(); + assert_eq!(store.view().resolved_hex(sid, "7"), None); + store.want_hex(sid, "7"); + store.pump(); + assert_eq!(store.take_jobs().len(), 1, "unanswered is retryable"); + } + + #[test] + fn watchlist_resolve_held_cancel_cannot_run_or_settle_a_replacement() { + let _serial = plx_base::testlock::serial(); + let mut store = plx_data::stores::watchlist::WatchlistStore::default(); + let sid = ServerId::from_raw(0); + let mut runner = StoreRunner::held_all(); + store.want_hex(sid, "7"); + store.pump(); + runner.start(store.take_jobs().pop().unwrap()); + store.run(plx_data::stores::watchlist::WatchlistCmd::Reset); + store.want_hex(sid, "7"); + store.pump(); + let replacement = store.take_jobs().pop().unwrap(); + assert_eq!(runner.run_held(), 1); + store.pump(); + assert_eq!(store.view().resolved_hex(sid, "7"), None); + assert!(!store.has_jobs(), "the replacement is still claimed"); + runner.start(replacement); + assert_eq!(runner.run_held(), 1); + store.pump(); + store.want_hex(sid, "7"); + store.pump(); + assert_eq!(store.take_jobs().len(), 1, "the replacement answered once"); + } + /// A newer DETAIL request retires only the detail fetches parked before it: a catalog read is /// not a request it supersedes. `run_held_of` takes one store's jobs and leaves the rest. #[test] @@ -2831,7 +3192,7 @@ mod tests { refill_client_keys(&mut keys); let session = plx_plex::plex::session::peek(); let profile_key = plx_plex::plex::session::current_profile_key(); - browse.run_with_input(cmd, &plx_data::browse::BrowseRosterInput { + browse.run_with_input(cmd, &plx_data::browse::BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -2907,7 +3268,7 @@ mod tests { browse.observe_pin_write(); let mut keys = plx_plex::plex::ClientKeys::default(); refill_client_keys(&mut keys); - let _outcome = browse.pump_with_gate(plx_machine::landgate::fixture_gate(), &plx_data::browse::BrowseRosterInput { + let _outcome = browse.pump_with_gate(plx_machine::landgate::fixture_gate(), &plx_data::browse::BrowseRosterInput { tenure: 0, keys: &keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -2974,7 +3335,7 @@ mod tests { browse.observe_pin_write(); let mut keys = plx_plex::plex::ClientKeys::default(); refill_client_keys(&mut keys); - let _outcome = browse.pump_with_gate(plx_machine::landgate::fixture_gate(), &plx_data::browse::BrowseRosterInput { + let _outcome = browse.pump_with_gate(plx_machine::landgate::fixture_gate(), &plx_data::browse::BrowseRosterInput { tenure: 0, keys: &keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -3081,7 +3442,7 @@ mod tests { browse.observe_pin_write(); let mut keys = plx_plex::plex::ClientKeys::default(); refill_client_keys(&mut keys); - let _ = browse.pump_with_gate(plx_machine::landgate::fixture_gate(), &plx_data::browse::BrowseRosterInput { + let _ = browse.pump_with_gate(plx_machine::landgate::fixture_gate(), &plx_data::browse::BrowseRosterInput { tenure: 0, keys: &keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -3428,7 +3789,7 @@ mod tests { browse.observe_pin_write(); let mut keys = plx_plex::plex::ClientKeys::default(); refill_client_keys(&mut keys); - let _ = browse.discover_pump_with_gate(plx_machine::landgate::fixture_gate(), &plx_data::browse::BrowseRosterInput { + let _ = browse.discover_pump_with_gate(plx_machine::landgate::fixture_gate(), &plx_data::browse::BrowseRosterInput { tenure: 0, keys: &keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), diff --git a/rust-modules/src/app/bootstrap/effects.rs b/rust-modules/src/app/bootstrap/effects.rs index 50443a07c9..38728337d0 100644 --- a/rust-modules/src/app/bootstrap/effects.rs +++ b/rust-modules/src/app/bootstrap/effects.rs @@ -281,6 +281,7 @@ pub(crate) fn message(message: &AppMsg) -> Result { }, AppMsg::PlaybackTrace(plx_platform::playback_trace::Status::Off) => json!({"playback_trace":"off"}), AppMsg::Store(command) => store(command)?, + AppMsg::PersonCommand { command, .. } => store(&plx_data::stores::StoreCmd::Person(command.clone()))?, AppMsg::StoreWork(work) => work_value(work)?, AppMsg::HubsResult(result) => plx_data::pms::record::encode(result), AppMsg::Home(command) => json!({"home_command":home_command(command)}), @@ -288,6 +289,18 @@ pub(crate) fn message(message: &AppMsg) -> Result { }) } +/// The retained Person sender duplicates the effect envelope, not the legacy delivery payload. +/// Validate that equality before using the historical wire spelling; never erase forged provenance. +pub(crate) fn encode_from(from: plx_machine::machine::MachineId, + effect: &Fx) -> Result { + if let Fx::Deliver(to, Delivery::Machine(AppMsg::PersonCommand { from: sender, .. })) = effect { + if *sender != from || *to != plx_machine::machine::MachineId::Store(plx_data::stores::StoreId::Person.ord()) { + return Err("mismatched controlled Person sender or destination"); + } + } + encode(effect) +} + pub(crate) fn encode(effect: &Fx) -> Result { Ok(match effect { Fx::App(effect) => app(effect)?, @@ -378,6 +391,37 @@ mod tests { use plx_screens::registry::AppArg; use plx_machine::machine::{Fx, NavOp}; + #[test] + fn controlled_person_delivery_retains_the_recorded_open_close_and_reset_payloads() { + use plx_data::stores::{StoreCmd, person::PersonCmd}; + use plx_machine::machine::{Delivery, MachineId}; + use plx_screens::registry::AppMsg; + use serde_json::json; + let from = MachineId::Instance(plx_machine::machine::InstanceId(3)); + let to = MachineId::Store(plx_data::stores::StoreId::Person.ord()); + for (command, body) in [ + (PersonCmd::Open { sid: plx_plex::plex::ServerId::from_raw(0), key: "19".into(), + guid: "sf06c144a".into(), name: "s025b413f".into(), + thumb: "/library/metadata/people/19/thumb/1".into() }, + json!({"person":{"open":[0,"19","sf06c144a","s025b413f","/library/metadata/people/19/thumb/1"]}})), + (PersonCmd::Close, json!({"person":"close"})), + (PersonCmd::Reset, json!({"person":"reset"})), + ] { + let legacy = Fx::Deliver(to, Delivery::Machine(AppMsg::Store(StoreCmd::Person(command.clone())))); + let addressed = Fx::Deliver(to, Delivery::Machine(AppMsg::PersonCommand { from, command: command.clone() })); + let misrouted = Fx::Deliver(MachineId::Session, Delivery::Machine(AppMsg::PersonCommand { from, command })); + assert_eq!(super::encode_from(from, &misrouted), + Err("mismatched controlled Person sender or destination")); + let expected = json!({"to":"store:4","delivery":body}); + assert_eq!(serde_json::to_vec(&encode(&legacy).unwrap()).unwrap(), + serde_json::to_vec(&super::encode_from(from, &addressed).unwrap()).unwrap()); + assert_eq!(encode(&legacy), Ok(expected.clone())); + assert_eq!(super::encode_from(from, &addressed), Ok(expected)); + assert_eq!(super::encode_from(MachineId::Nav, &addressed), + Err("mismatched controlled Person sender or destination")); + } + } + #[test] fn controlled_diagnostics_only_records_the_deterministic_off_query() { use plx_platform::playback_trace::{Command, Status}; diff --git a/rust-modules/src/app/bootstrap/tests.rs b/rust-modules/src/app/bootstrap/tests.rs index 1bfb6c7647..53baa2fce1 100644 --- a/rust-modules/src/app/bootstrap/tests.rs +++ b/rust-modules/src/app/bootstrap/tests.rs @@ -102,7 +102,7 @@ fn controlled_discovery(io: &mut HomeIo, runner: &mut StoreRunner, stores: &mut let visible_generation = plx_plex::plex::session::visible_generation(); let settled = plx_plex::plex::session::peek_settled().is_some(); let profile_key = plx_plex::plex::session::current_profile_key(); - stores.browse_controlled_discover(&plx_data::browse::BrowseRosterInput { + stores.browse_controlled_discover(&plx_data::browse::BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation, settled, profile_key: &profile_key, }); for job in stores.take_jobs_of(plx_data::stores::StoreId::Browse) { @@ -575,7 +575,7 @@ fn controlled_discovery_replays_refusal_retry_and_success_with_exact_identity() let visible_generation = plx_plex::plex::session::visible_generation(); let settled = plx_plex::plex::session::peek_settled().is_some(); let profile_key = plx_plex::plex::session::current_profile_key(); - let input = plx_data::browse::BrowseRosterInput { + let input = plx_data::browse::BrowseRosterInput { tenure: 0, keys: &keys, session: &session, visible_generation, settled, profile_key: &profile_key, }; stores.browse.borrow_mut().prepare_discovery_replay_for_test( diff --git a/rust-modules/src/app/bridge.rs b/rust-modules/src/app/bridge.rs index 0a62c4c6dd..d822345417 100644 --- a/rust-modules/src/app/bridge.rs +++ b/rust-modules/src/app/bridge.rs @@ -87,27 +87,30 @@ struct LibraryPageVisit { pub(crate) struct AppHost; -/// Host facts captured after observing the pending pin receipt. Never retained across calls. +/// Retained host facts; each refresh is fenced against both session/profile publishers. struct BrowseContext { session: std::sync::Arc, visible_generation: u64, + tenure: u64, settled: bool, profile_key: String, } impl BrowseContext { fn capture(stores: &plx_data::stores::Stores) -> Self { + let tenure = plx_plex::plex::session::tenure(); stores.browse.borrow().observe_pin_write(); Self { session: plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), + tenure, settled: plx_plex::plex::session::peek_settled().is_some(), profile_key: plx_plex::plex::session::current_profile_key(), } } fn input<'a>(&'a self, keys: &'a plx_plex::plex::ClientKeys) -> plx_data::browse::BrowseRosterInput<'a> { - plx_data::browse::BrowseRosterInput { + plx_data::browse::BrowseRosterInput { tenure: self.tenure, keys, session: &self.session, visible_generation: self.visible_generation, settled: self.settled, profile_key: &self.profile_key, } @@ -131,6 +134,26 @@ fn is_first_run_consent(a: &AppArg) -> bool { /// Core-side shape of the Chrome refresh boundary. The retained directory is explicit so Chrome /// always reads this Bridge's captured Browse publication. +/// A store notice is needed only when its selected read-out's held reason changes. +fn clock_notice_changed(before: Option, + facts: &plx_plex::plex::ClockFacts, machine: Option<&str>) -> bool { + before != facts.blocked_for(machine) +} + +#[test] +fn clock_fact_change_notice_tracks_only_the_selected_reason() { + use plx_net::net::keypin::Blocked; + use plx_plex::plex::{ClockFacts, ServerId}; + let facts = |reason| ClockFacts::scripted(4, ServerId::UNSET, None, + [(ServerId::UNSET, "server".to_owned(), reason)]); + let a = facts(Some(Blocked::NoKey)); + let b = facts(Some(Blocked::KeyChanged)); + assert!(!clock_notice_changed(Some(Blocked::NoKey), &a, Some("server"))); + assert!(clock_notice_changed(Some(Blocked::NoKey), &b, Some("server"))); + assert!(clock_notice_changed(Some(Blocked::NoKey), &a, Some("other"))); + assert!(!clock_notice_changed(None, &b, Some("other"))); + assert!(!clock_notice_changed(None, &b, None)); +} fn refresh_chrome( chrome: &mut super::chrome::ChromeSnapshot, measure: &dyn Measure, @@ -145,6 +168,8 @@ fn refresh_chrome( #[derive(Clone, Copy)] pub(crate) struct AppViews<'a> { + pub(crate) inputs: &'a plx_screens::inputs::ScreenInputs, + pub(crate) clock: &'a plx_plex::plex::ClockFacts, pub(crate) marker_prefs: plx_appkit::skip_policy::MarkerPrefsView, pub(crate) auth: plx_session::auth::SessionRead<'a>, pub(crate) hubs: plx_data::pms::HubsView<'a>, @@ -190,7 +215,7 @@ impl Bridge { /// [`Self::views`] reading `session` as the playback publication — what a test rig with no /// player of its own passes. pub(crate) fn views_with<'a>(&'a self, session: &'a plx_media::route::PlaybackSession) -> AppViews<'a> { - AppViews { marker_prefs: self.marker_prefs, auth: self.session.read(), hubs: self.hubs.view(), listing: self.listing.view(), + AppViews { inputs: &self.screen_inputs, clock: &self.clock_facts, marker_prefs: self.marker_prefs, auth: self.session.read(), hubs: self.hubs.view(), listing: self.listing.view(), directory: self.directory.view(), section_hubs: self.section_hubs.view(), search: self.search.view(), metadata: self.stores.metadata_view(), person: self.stores.person_view(), collection: self.stores.collection_view(), subtitle_search: self.stores.subtitle_search_view(), session, @@ -244,7 +269,12 @@ impl Host for AppHost { } } +impl plx_screens::registry::ScreenInputsLike for AppHost { + fn screen_inputs<'a>(cx: &Cx<'a, Self>) -> &'a plx_screens::inputs::ScreenInputs { cx.views.inputs } +} + impl HomeLike for AppHost { + fn clock_facts<'a>(cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { Some(cx.views.clock) } fn hubs<'a>(cx: &Cx<'a, Self>) -> plx_data::pms::HubsView<'a> { cx.views.hubs } } @@ -303,6 +333,7 @@ impl plx_screens::registry::SearchLike for AppHost { } impl plx_screens::registry::LibraryLike for AppHost { + fn clock_facts<'a>(cx: &Cx<'a, Self>) -> Option<&'a plx_plex::plex::ClockFacts> { Some(cx.views.clock) } fn marker_prefs(cx: &Cx<'_, Self>) -> plx_appkit::skip_policy::MarkerPrefsView { cx.views.marker_prefs } fn listing<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::ListingView<'a> { cx.views.listing } fn directory<'a>(cx: &Cx<'a, Self>) -> plx_data::stores::browse::DirectoryView<'a> { cx.views.directory } @@ -430,6 +461,112 @@ impl SeatWatch { } /// What the bridge lends the dispatcher, and what it collects for the loop. +/// An accepted Open stays owned here until one coherent input publication can deliver it. +struct PendingPersonOpen { + command: plx_data::stores::person::PersonCmd, + sender: Option, + scope: u32, + owner_epoch: u64, + profile: std::sync::Arc, + controlled: bool, + tenure: u64, + session: Option>, +} +/// Retained Person-only host facts. No registry or dev provider is callable by the data step. +#[derive(Default)] +struct PersonCapture { + guid: String, + controlled: bool, + profile_refused: bool, + credits_refused: bool, + dev_bio: Option, + dev_credits: Option, +} + +impl PersonCapture { +fn refresh(&mut self, guid: &str, controlled: bool, opening: bool, read: &mut impl FnMut(&str) -> Option) { + // Provider refusal is a boot-fixed fact. Keep it with the person/control identity rather + // than formatting two provider URLs on every stable pump. + if opening || self.controlled != controlled || self.guid != guid { + self.guid.clear(); + self.guid.push_str(guid); + self.profile_refused = !controlled && !guid.is_empty() && plx_plex::plex::discover::person_profile_refused(guid); + self.credits_refused = !controlled && !guid.is_empty() && plx_plex::plex::discover::person_credits_refused(guid); + } + self.controlled = controlled; + if controlled { + self.dev_bio = None; + let rows = plx_data::stores::tape::credits(); + if self.dev_credits.as_deref().and_then(|s| s.parse::().ok()) != rows { + self.dev_credits = rows.map(|n| n.to_string()); + } + } else { + if opening { self.dev_bio = read("personbio"); } + self.dev_credits = read("personcredits"); + } + } + + fn input<'a>(&'a self, keys: &'a plx_plex::plex::ClientKeys, + capture: &'a StoreSessionCapture, profile_scope: u32, owner_epoch: u64) -> plx_data::person::PersonInput<'a> { + plx_data::person::PersonInput { + keys, session: capture.session.as_ref(), visible_generation: capture.visible_generation, + profile_scope, owner_epoch, profile_generation: capture.profile_generation, + tenure: capture.tenure, profile_key: &capture.profile_key, + controlled: self.controlled, profile_refused: self.profile_refused, + credits_refused: self.credits_refused, dev_bio: self.dev_bio.as_deref(), + dev_credits: self.dev_credits.as_deref(), + } + } +} + +#[derive(Default)] +struct StoreSessionCapture { + revision: Option<(u64, u64)>, + session: Option>, + observed: std::sync::Arc, + visible_generation: u64, + profile_generation: u32, + tenure: u64, + profile_key: String, + household: Vec, + controlled: bool, + tape_active: bool, +} + +impl StoreSessionCapture { + /// Commit a cache/profile publication only if neither publisher moved during capture. + /// A rejected attempt keeps the previous coherent publication and the caller retries later. + fn refill_store_session(&mut self, mut revision: impl FnMut() -> (u64, u64)) -> bool { + use plx_plex::plex::session; + let before = revision(); + if !self.controlled && self.revision == Some(before) { return true; } + let settled = session::peek_settled(); + let observed = settled.clone().unwrap_or_else(session::peek); + let visible_generation = session::visible_generation(); + let tenure = session::tenure(); + let profile = session::current_snapshot(); + if revision() != before { return false; } + if !std::sync::Arc::ptr_eq(&self.observed, &observed) { + self.household = observed.household_ids(); + } + let key = profile.user.as_ref().map_or("", |user| user.uuid.as_str()); + if self.profile_key != key { self.profile_key.clear(); self.profile_key.push_str(key); } + self.session = settled; + self.observed = observed; + self.visible_generation = visible_generation; + self.tenure = tenure; + self.profile_generation = profile.generation; + self.revision = Some(before); + true + } + fn search_input<'a>(&'a self, keys: &'a plx_plex::plex::ClientKeys) -> plx_data::search::SearchInput<'a> { + plx_data::search::SearchInput { keys, recents: plx_data::search::recents::Input { + session: &self.observed, settled: self.session.is_some(), + profile_generation: self.profile_generation, session_generation: self.visible_generation, tenure: self.tenure, + profile_key: &self.profile_key } } + } +} + pub(crate) struct Bridge { marker_access: super::preferences::MarkerAccessRunner, marker_prefs: plx_appkit::skip_policy::MarkerPrefsView, @@ -473,6 +610,21 @@ pub(crate) struct Bridge { /// that decides from it (`adapters::stores::refill_client_keys`), in the same call. ONE value /// kept for the life of the Bridge, so a pump that runs every frame allocates nothing for it. client_keys: plx_plex::plex::ClientKeys, + store_session: StoreSessionCapture, + person_capture: PersonCapture, + pending_person_open: Option, + person_owner: Option, + /// Host-chosen capture boundary; rejection must leave Open owed to this owner. + person_session_capture: fn(&mut Bridge) -> bool, + watchlist_capture: plx_data::stores::watchlist_job::SnapshotCache, + clock_facts: std::sync::Arc, + clock_scratch: plx_plex::plex::ClockFacts, + screen_inputs: plx_screens::inputs::ScreenInputs, + screen_grant_key: Option<(u64, u64)>, + screen_cache_revision: Option<(u64, u64)>, + /// Root's grant choices retain settled authority while readable public defaults may move. + screen_grant_session: std::sync::Arc, + live_screen_inputs: bool, stores: plx_data::stores::Stores, mounter: AppMounter, /// This frame's publication of the playback session — see `AppViews::session`. Refreshed by @@ -616,7 +768,7 @@ impl Bridge { hubs, listing:plx_data::stores::browse::ListingSnapshot::empty(), directory:Default::default(), section_hubs:plx_data::stores::browse::HubsSnapshot::empty(), search:Default::default(), - }, stores); + }, stores, false); bridge.initial_subhash = initial.hash(); bridge.measure = if replay { plx_ui::rec::Measurements::Pending(Default::default()) @@ -651,7 +803,7 @@ impl Bridge { bridge.metadata_alt_host = |request, _| request.answer(None); // Keep the test SessionMachine unseated; Search's initial household input, like // subsequent captures, is the actual session's independently observed roster. - bridge.search = bridge.stores.search_snapshot(bridge.directory.view(), &Self::household_ids()); + bridge.search = bridge.capture_search_publication(); bridge } @@ -662,18 +814,21 @@ impl Bridge { store_runner: super::adapters::stores::StoreRunner) -> Self { let stores = plx_data::stores::Stores::default(); let mut directory = plx_data::stores::browse::DirectorySnapshot::default(); - let browse = stores.capture_browse(&mut directory, &plx_data::browse::BrowseRosterInput { + let browse = stores.capture_browse(&mut directory, &plx_data::browse::BrowseRosterInput { tenure: plx_plex::plex::session::tenure(), keys: &Default::default(), session: &init.persisted, visible_generation: 0, settled: false, profile_key: "", }); - let search = stores.search_snapshot(browse.directory.view(), &init.persisted.household_ids()); - Self::with_publications_and_stores(measure, now_us, init, session_adapter, consent, + + let mut bridge = Self::with_publications_and_stores(measure, now_us, init, session_adapter, consent, consent_adapter, store_runner, StorePublications { hubs: stores.hubs.snapshot(), listing: browse.listing, directory: browse.directory, section_hubs: browse.section_hubs, - search, - }, stores) + search: Default::default(), + }, stores, true); + super::adapters::stores::refill_client_keys(&mut bridge.client_keys); + bridge.search = bridge.capture_search_publication(); + bridge } #[cfg(test)] @@ -724,7 +879,7 @@ impl Bridge { consent_adapter: super::adapters::consent::ConsentAdapter, reads: StorePublications) -> Self { let mut bridge = Self::with_publications_and_stores(measure, now_us, init, session_adapter, consent, - consent_adapter, super::adapters::stores::StoreRunner::held(), reads, Default::default()); + consent_adapter, super::adapters::stores::StoreRunner::held(), reads, Default::default(), true); bridge.metadata_alt_host = |request, _| request.answer(None); bridge } @@ -734,8 +889,8 @@ impl Bridge { consent: plx_telemetry::telemetry::consent::Consent, consent_adapter: super::adapters::consent::ConsentAdapter, store_runner: super::adapters::stores::StoreRunner, - reads: StorePublications, stores: plx_data::stores::Stores) -> Self { - Self { + reads: StorePublications, stores: plx_data::stores::Stores, live_screen_inputs: bool) -> Self { + let mut bridge = Self { session_cache_generation: plx_plex::plex::session::visible_generation(), cache_refresh_begun: None, marker_access: Default::default(), marker_prefs: Default::default(), marker_now: 0, @@ -757,6 +912,15 @@ impl Bridge { metadata_alt_host: crate::dev::scenarios::metadata_alt_stand_in, late_store_jobs: 0, client_keys: Default::default(), + store_session: Default::default(), + person_capture: Default::default(), + pending_person_open: None, + person_owner: None, + person_session_capture: Self::capture_store_session_live, + watchlist_capture: Default::default(), + clock_facts: Default::default(), + clock_scratch: Default::default(), + screen_inputs: Default::default(), screen_grant_key: None, screen_cache_revision: None, screen_grant_session: Default::default(), live_screen_inputs, stores, mounter: AppMounter::default(), playback: plx_media::route::PlaybackSession::IDLE, @@ -797,7 +961,9 @@ impl Bridge { effect_return: ReturnState::default(), held: Vec::new(), now_us, - } + }; + bridge.capture_screen_inputs(); + bridge } /// Observe storage landings on the frame thread, alongside store/adapter publications, and @@ -1379,13 +1545,90 @@ impl Bridge { d.nav.tabs.strip_selected = self.chrome.key_at(selected); } + /// Capture registry facts once per publication boundary. Stable frames only clone Arcs or + /// compare generation hints; consent hashing and vectors run only after a semantic source move. + fn capture_screen_inputs(&mut self) -> bool { + self.capture_screen_inputs_with(plx_plex::plex::session::screen_input_revision) + } + + fn capture_screen_inputs_with(&mut self, mut revision: impl FnMut() -> (u64, u64)) -> bool { + if !self.live_screen_inputs { return false; } + use plx_plex::plex::{grant, session}; + let before = revision(); + let mut next = self.screen_inputs.clone(); + let mut grant_session = self.screen_grant_session.clone(); + if self.screen_cache_revision.map(|r| r.0) != Some(before.0) { + let settled = session::peek_settled(); + next.settled = settled.is_some(); + next.session = match settled { + Some(session) => { grant_session = session.clone(); session } + None => session::peek(), + }; + next.visible_generation = session::visible_generation(); + } + if self.screen_cache_revision.map(|r| r.1) != Some(before.1) { + next.profile = session::current_snapshot(); + } + let key = (grant::revision(), before.0); + next.current_server = self.client_keys.current(); + let same_servers = self.client_keys.iter().filter_map(|(sid, _)| self.client_keys.facts(sid) + .map(|facts| (facts.machine_id.as_str(), sid))) + .eq(next.servers.iter().map(|(machine, sid)| (machine.as_str(), *sid))); + if !same_servers { + next.servers = std::sync::Arc::new(self.client_keys.iter().filter_map(|(sid, _)| self.client_keys.facts(sid) + .map(|facts| (facts.machine_id.clone(), sid))).collect()); + } + next.resolution_offered = plx_platform::tv::device::ui_resolution_offered(); + if self.screen_grant_key != Some(key) { + let session = &grant_session; + let mut grants = plx_screens::inputs::GrantInputs { offers: grant::offers(), + choices: grant::choices(&session.prefs.plaintext_consent, &session.account_token), + connected: grant::granted_machines() }; + grants.connected.sort_unstable(); + if *next.grants != grants { + next.grants = std::sync::Arc::new(grants); + next.grant_generation = next.grant_generation.wrapping_add(1); + } + } + // These tokens fence completed publications, not requests. Keep the previous coherent + // view if a worker or profile publisher moved while facts were copied; retry next pump. + if revision() != before || grant::revision() != key.0 { return false; } + let changed = !self.screen_inputs.same_facts(&next); + if changed { + next.revision = self.screen_inputs.revision.wrapping_add(1); + self.screen_inputs = next; + } + self.screen_grant_session = grant_session; + self.screen_cache_revision = Some(before); + self.screen_grant_key = Some(key); + changed + } + /// Return publication changes so the frame can coalesce them with store notices. fn capture_views(&mut self, _d: &mut Dispatcher) -> (bool, bool, bool) { + // Controlled Home has no captured keypin facts. Select that policy before any + // registry or keypin read; unrelated Browse capture below keeps its own boundary. + let controlled_clock = self.home_io.is_some(); + let home_clock_before = self.clock_facts.blocked_for(self.clock_facts.current_machine()); + let library_clock_before = self.clock_facts.blocked_for(self.directory.view().source() + .and_then(|(sid, _)| self.clock_facts.machine(*sid))); let directory_before = self.directory.clone(); let hubs_before = (self.section_hubs.view().id(), self.section_hubs.view().revision()); // One owner borrow, in the load-bearing order: directory capture resolves profile pins // and may repoint the current section, so listing and shelves are captured only after it. super::adapters::stores::refill_client_keys(&mut self.client_keys); + if !controlled_clock { + let revision = plx_net::net::keypin::revision(); + if self.clock_facts.needs_refill(revision, &self.client_keys) { + self.clock_scratch.refill(revision, &self.client_keys, plx_net::net::keypin::blocked_for); + // Never publish a table assembled across a keypin change. The next frame retries. + if plx_net::net::keypin::revision() == revision { + std::mem::swap(std::sync::Arc::make_mut(&mut self.clock_facts), &mut self.clock_scratch); + } + } + } + + let inputs_changed = self.capture_screen_inputs(); let context = self.browse_session(); let owned = self.stores.capture_browse(&mut self.directory, &context.input(&self.client_keys)); if self.home_io.is_none() { self.section_hubs = owned.section_hubs; } @@ -1393,10 +1636,12 @@ impl Bridge { let listing_changed = !self.listing.view().same_items(listing.view()) || self.listing.view().fetch() != listing.view().fetch(); self.listing = listing; - let browse_changed = listing_changed || !self.directory.same_publication(&directory_before) + let library_clock_changed = clock_notice_changed(library_clock_before, &self.clock_facts, + self.directory.view().source().and_then(|(sid, _)| self.clock_facts.machine(*sid))); + let browse_changed = library_clock_changed || listing_changed || !self.directory.same_publication(&directory_before) || hubs_before != (self.section_hubs.view().id(), self.section_hubs.view().revision()); let search = if self.home_io.is_some() { self.search.clone() } else { - self.stores.search_snapshot(self.directory.view(), &Self::household_ids()) + self.capture_search_publication() }; let search_changed = !self.search.same_publication(&search); if search_changed { @@ -1405,8 +1650,9 @@ impl Bridge { let before = (self.hubs.view().generation, self.hubs.view().state); self.hubs = self.stores.hubs.snapshot(); let after = (self.hubs.view().generation, self.hubs.view().state); - let hubs_changed = before != after; - (browse_changed, hubs_changed, search_changed) + let home_clock_changed = clock_notice_changed(home_clock_before, &self.clock_facts, self.clock_facts.current_machine()); + let hubs_changed = before != after || home_clock_changed; + (browse_changed || inputs_changed, hubs_changed || inputs_changed, search_changed) } pub(crate) fn update_home_chrome(&mut self, d: &mut Dispatcher, @@ -1638,17 +1884,135 @@ impl Bridge { } pub(crate) fn person_run(&mut self, cmd: plx_data::stores::person::PersonCmd) -> bool { - self.stores.person_run(cmd) + self.person_run_from(None, cmd) + } + fn retain_person_open(&mut self, sender: Option, command: plx_data::stores::person::PersonCmd) { + use plx_plex::plex::session; + let controlled = !self.live_screen_inputs || plx_data::stores::tape::active(); + let owner = self.session.read().0; + self.pending_person_open = Some(PendingPersonOpen { + command, sender, scope: owner.scope.0, owner_epoch: owner.flow_epoch, controlled, + profile: if controlled { self.screen_inputs.profile.clone() } else { session::current_snapshot() }, + tenure: if controlled { 0 } else { session::tenure() }, + session: controlled.then(|| self.screen_inputs.session.clone()), + }); + } + + fn deliver_person_open(&mut self) -> bool { + self.deliver_person_open_with_seed_read(&mut plx_base::devtrig::read) + } + + fn deliver_person_open_with_seed_read(&mut self, read: &mut impl FnMut(&str) -> Option) -> bool { + let Some(pending) = self.pending_person_open.take() else { return false }; + let owner = self.session.read().0; + let capture = &self.store_session; + let profile_key = pending.profile.user.as_ref().map_or("", |user| user.uuid.as_str()); + if pending.scope != owner.scope.0 || pending.owner_epoch != owner.flow_epoch + || pending.controlled != capture.controlled + || pending.profile.generation != capture.profile_generation || profile_key != capture.profile_key + || (!pending.controlled && pending.tenure != capture.tenure) + || pending.session.as_ref().is_some_and(|session| + session.client_id != capture.observed.client_id || session.account_token != capture.observed.account_token) { + return false; + } + let plx_data::stores::person::PersonCmd::Open { guid, .. } = &pending.command else { return false }; + self.person_capture.refresh(guid, capture.controlled, true, read); + let input = self.person_capture.input(&self.client_keys, capture, owner.scope.0, owner.flow_epoch); + self.person_owner = pending.sender; + self.stores.person_run(pending.command, &input) + } + + fn person_run_from(&mut self, sender: Option, cmd: plx_data::stores::person::PersonCmd) -> bool { + use plx_data::stores::person::PersonCmd; + match cmd { + command @ PersonCmd::Open { .. } => { + // Acknowledgment transfers delivery responsibility to this retained, latest-wins slot. + self.retain_person_open(sender, command); + if !self.capture_store_session() { return false; } + super::adapters::stores::refill_client_keys(&mut self.client_keys); + self.deliver_person_open() + } + command => { + if matches!(&command, PersonCmd::Close | PersonCmd::Reset) { + let reset = matches!(&command, PersonCmd::Reset); + if reset || sender.is_none() || self.pending_person_open.as_ref().is_some_and(|pending| pending.sender == sender) { + self.pending_person_open = None; + } + // A retired body may tear down after its replacement has claimed this slot. + if !reset && sender.is_some() && self.person_owner.is_some() && sender != self.person_owner { + return false; + } + self.person_owner = None; + } + let _step = plx_base::step::StepScope::enter(); + self.stores.person.run(command) + } + } } /// One frame's Person pump: refill the keys, step, and start the requests the step emitted, all /// in this call, so the tape's admissions are written where the page asked for them, before /// the next store's (`collection_pump`, then the detail reconciliation) record theirs. pub(crate) fn person_pump(&mut self) -> bool { + self.person_pump_with_seed_read(&mut plx_base::devtrig::read) + } + + fn person_pump_with_seed_read(&mut self, read: &mut impl FnMut(&str) -> Option) -> bool { + if !self.capture_store_session() { return false; } super::adapters::stores::refill_client_keys(&mut self.client_keys); - let changed = self.stores.person_pump(&self.client_keys); + let before = self.stores.person.gen(); + let opened = self.deliver_person_open_with_seed_read(read); + if let Some(person) = self.stores.person_view().current() { + self.person_capture.refresh(&person.guid, self.store_session.controlled, false, read); + } else { + self.person_capture.controlled = self.store_session.controlled; + } + let capture = &self.store_session; + let owner = self.session.read().0; + let person_input = self.person_capture.input(&self.client_keys, capture, owner.scope.0, owner.flow_epoch); + let changed = self.stores.person_pump(&person_input); self.start_store_jobs_of(StoreId::Person); - changed + opened || changed || self.stores.person.gen() != before + } + fn capture_search_publication(&mut self) -> plx_data::search::view::SearchSnapshot { + self.capture_store_session(); + self.stores.search_snapshot(self.directory.view(), &self.store_session.household, + &self.store_session.search_input(&self.client_keys)) + } + fn capture_store_session_live(&mut self) -> bool { + use plx_plex::plex::session; + let tape_active = plx_data::stores::tape::active(); + let controlled = !self.live_screen_inputs || tape_active; + let capture = &mut self.store_session; + let previous_session = capture.observed.clone(); + if controlled { + let profile = &self.screen_inputs.profile; + let key = profile.user.as_ref().map_or("", |user| user.uuid.as_str()); + if !capture.controlled || capture.profile_generation != profile.generation || capture.profile_key != key + || (self.screen_inputs.settled && (capture.observed.client_id != self.screen_inputs.session.client_id + || capture.observed.account_token != self.screen_inputs.session.account_token)) { + capture.tenure = capture.tenure.wrapping_add(1); + } + capture.session = self.screen_inputs.settled_session().cloned(); + capture.observed = self.screen_inputs.session.clone(); + capture.visible_generation = self.screen_inputs.visible_generation; + capture.profile_generation = self.screen_inputs.profile.generation; + let key = self.screen_inputs.profile.user.as_ref().map_or("", |user| user.uuid.as_str()); + if capture.profile_key != key { capture.profile_key.clear(); capture.profile_key.push_str(key); } + capture.revision = None; + } else { + if !capture.refill_store_session(session::screen_input_revision) { return false; } + } + if controlled && !std::sync::Arc::ptr_eq(&previous_session, &capture.observed) { + capture.household = capture.observed.household_ids(); + } + capture.controlled = controlled; + capture.tape_active = tape_active; + true + } + + fn capture_store_session(&mut self) -> bool { + (self.person_session_capture)(self) } pub(crate) fn person_view(&self) -> plx_data::person::PersonView<'_> { @@ -1678,7 +2042,7 @@ impl Bridge { /// captures no identity. pub(crate) fn catalog_pump(&mut self) -> bool { let profile = Self::seated_profile(); - let mut changed = self.stores.catalog.pump(&profile); + let mut changed = { let _step = plx_base::step::StepScope::enter(); self.stores.catalog.pump(&profile) }; if let Some(hex) = self.stores.catalog.take_reopen() { self.catalog_open(hex); changed = true; @@ -1690,7 +2054,8 @@ impl Bridge { /// The catalog page mounted (or read again) for `hex`: the store's `open` handed /// `watchlist_input()`, then its read started in this call. pub(crate) fn catalog_open(&mut self, hex: [u8; 12]) { - self.stores.catalog.open(hex, &Self::watchlist_input()); + let input = Self::watchlist_input(); + { let _step = plx_base::step::StepScope::enter(); self.stores.catalog.open(hex, &input); } self.start_store_jobs_of(StoreId::Catalog); } @@ -1744,7 +2109,9 @@ impl Bridge { /// neither is not lost: the next pump's backstop starts the job a frame late, counts it in /// `late_store_jobs` and logs it, and the test rigs fail on that count. pub(crate) fn metadata_run(&mut self, cmd: plx_data::stores::metadata::MetadataCmd) -> bool { - let changed = self.stores.metadata_run(cmd); + self.capture_store_session(); + super::adapters::stores::refill_client_keys(&mut self.client_keys); + let changed = self.stores.metadata_run(cmd, &self.client_keys); self.start_store_jobs_of(StoreId::Metadata); changed } @@ -1777,10 +2144,21 @@ impl Bridge { ids.iter().map(|&id| self.start_store_jobs_of(id)).sum() } - fn start_jobs(&mut self, jobs: Vec) -> usize { +fn start_jobs(&mut self, jobs: Vec) -> usize { let started = jobs.len(); - for job in jobs { - self.store_runner.start(job); + let watchlist = jobs.iter().any(|j| j.store() == StoreId::Watchlist); + let person = jobs.iter().any(|j| j.store() == StoreId::Person); + for job in jobs { self.store_runner.start(job); } + if person { + let _step = plx_base::step::StepScope::enter(); + self.stores.person.land_launch_refusals(); + } + if watchlist { + let profile = Self::seated_profile(); + let stream = self.stores.watchlist.land_stream_results(&self.stores.landgate, &profile); + let write = self.stores.watchlist.land_write_results(&self.stores.landgate, &profile); + self.stores.watchlist.land_resolve_refusals(&profile); + if stream || write { plx_machine::idle::invalidate(); } } started } @@ -1862,9 +2240,10 @@ impl Bridge { /// backstop as [`Bridge::metadata_pump_detail`]. #[cfg(test)] pub(crate) fn metadata_pump(&mut self) -> bool { + self.capture_store_session(); self.start_late_store_jobs(); super::adapters::stores::refill_client_keys(&mut self.client_keys); - let changed = self.stores.metadata_pump(&self.client_keys, plx_data::stores::tape::active(), None); + let changed = self.stores.metadata_pump(&self.client_keys, self.store_session.tape_active, None); self.start_store_jobs_of(StoreId::Metadata); changed } @@ -1873,8 +2252,9 @@ impl Bridge { /// runner refused since the last Hubs step is settled by whatever steps Hubs next): the caller /// carries them. pub(crate) fn viewstate_run(&mut self, cmd: plx_data::stores::viewstate::ViewStateCmd) -> plx_data::stores::StoreOutcome { + self.capture_store_session(); super::adapters::stores::refill_client_keys(&mut self.client_keys); - let outcome = self.stores.viewstate_run(cmd, self.directory.view(), &self.client_keys, Self::profile_scope()); + let outcome = self.stores.viewstate_run(cmd, self.directory.view(), &self.client_keys, self.store_session.profile_generation); self.start_store_jobs_in(plx_data::stores::Stores::VIEWSTATE_FILLS); outcome } @@ -1910,14 +2290,21 @@ impl Bridge { /// The Watchlist store's landing pass, once a frame and route-unconditional: a write burst /// lands, a profile switch resets it, and the page reads its notice through `take_notices`. pub(crate) fn watchlist_pump(&mut self) { - if self.stores.watchlist.pump_with_gate(&self.stores.landgate, &Self::seated_profile()) { + super::adapters::stores::refill_client_keys(&mut self.client_keys); + let profile = Self::seated_profile(); + let input = self.store_runner.watchlist_snapshot(&self.client_keys, &mut self.watchlist_capture); + let changed = { let _step = plx_base::step::StepScope::enter(); + self.stores.watchlist.pump_with_snapshot(&self.stores.landgate, &profile, input) }; + if changed { plx_machine::idle::invalidate(); } + self.start_store_jobs_of(StoreId::Watchlist); } pub(crate) fn viewstate_pump(&mut self) -> plx_data::stores::EndpointRefreshSet { + self.capture_store_session(); super::adapters::stores::refill_client_keys(&mut self.client_keys); - let endpoints = self.stores.viewstate_pump(self.directory.view(), &self.client_keys, Self::profile_scope()); + let endpoints = self.stores.viewstate_pump(self.directory.view(), &self.client_keys, self.store_session.profile_generation); self.start_store_jobs_in(plx_data::stores::Stores::VIEWSTATE_FILLS); endpoints } @@ -1929,8 +2316,9 @@ impl Bridge { /// so both outboxes are drained here (`Stores::RECONCILE_FILLS`); the shared `Stores` call's /// other fan-outs emit no jobs of their own. pub(crate) fn reconcile_pump(&mut self) -> plx_data::stores::EndpointRefreshSet { + self.capture_store_session(); super::adapters::stores::refill_client_keys(&mut self.client_keys); - let mut outcome = self.stores.reconcile_pump(self.directory.view(), &self.client_keys, Self::profile_scope()); + let mut outcome = self.stores.reconcile_pump(self.directory.view(), &self.client_keys, self.store_session.profile_generation); self.start_store_jobs_in(plx_data::stores::Stores::RECONCILE_FILLS); if outcome.changed { plx_machine::idle::invalidate(); @@ -1984,6 +2372,7 @@ impl Bridge { self.stores.notify_finish_turn(&mut pass, turn, &input); } let out = self.stores.notify_end(pass); + self.stores.watchlist.observe_snapshot(self.store_runner.watchlist_snapshot(&self.client_keys, &mut self.watchlist_capture)); let mut spent = self.stores.notify_map(&out, pages, shown, self.directory.view(), &self.client_keys); self.start_store_jobs_in(plx_data::stores::Stores::NOTIFY_FILLS); self.start_store_jobs_of(StoreId::Notify); @@ -2059,12 +2448,6 @@ impl Bridge { self.stores.take_landed_views() } - /// The signed-in profile's household member ids, which Search's source scope grades each - /// server's household mark against. The Bridge reads the session here and hands the answer to - /// the store; the data layer reads no session global for it. - fn household_ids() -> Vec { - plx_plex::plex::session::peek().household_ids() - } /// The profile the Watchlist and catalog frame passes are handed: the seated one, as the Session /// owner published it. An `Arc` clone, so the two per-frame passes cost nothing to read it; a pass @@ -2106,7 +2489,10 @@ impl Bridge { /// (`RememberRecent` / `ClearRecents`) emits its `StoreJob::SaveRecents` here, and this drain is /// what starts it. pub(crate) fn search_run(&mut self, cmd: plx_data::stores::search::SearchCmd) -> bool { - let changed = self.stores.search_run(cmd, self.directory.view()); + self.capture_store_session(); + super::adapters::stores::refill_client_keys(&mut self.client_keys); + let input = self.store_session.search_input(&self.client_keys); + let changed = self.stores.search_run(cmd, self.directory.view(), &input); self.start_store_jobs_of(StoreId::Search); changed } @@ -2116,7 +2502,9 @@ impl Bridge { /// per source that is due; the runner launches each through the client the keys named. pub(crate) fn search_pump(&mut self, dt: f32) -> bool { super::adapters::stores::refill_client_keys(&mut self.client_keys); - let changed = self.stores.search_pump(dt, self.directory.view(), &self.client_keys); + self.capture_store_session(); + let input = self.store_session.search_input(&self.client_keys); + let changed = self.stores.search_pump(dt, self.directory.view(), &input); self.start_store_jobs_of(StoreId::Search); changed } @@ -2152,7 +2540,7 @@ impl Bridge { pub(crate) fn hubs_run(&mut self, cmd: plx_data::stores::hubs::HubsCmd) -> plx_data::stores::StoreOutcome { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let out = self.stores.hubs.run_with_directory(cmd, directory, &self.client_keys); + let out = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.run_with_directory(cmd, directory, &self.client_keys) }; self.start_store_jobs_of(StoreId::Hubs); out } @@ -2188,13 +2576,14 @@ impl Bridge { /// The `MetadataStore`'s own async detail landing — `app/run.rs`'s route-unconditional pump. pub(crate) fn metadata_pump_detail(&mut self) -> bool { + self.capture_store_session(); // The backstop: every sender drains its own jobs, so nothing is found here. A job that is // found would leave a request nothing runs, and the pump below would wait on it; it is // started now, so the request settles, and counted and logged so the bypass is not silent. self.start_late_store_jobs(); super::adapters::stores::refill_client_keys(&mut self.client_keys); let changed = self.stores.metadata.pump_detail_with_gate(&self.client_keys, - plx_data::stores::tape::active(), &self.stores.landgate); + self.store_session.tape_active, &self.stores.landgate); self.start_store_jobs_of(StoreId::Metadata); changed } @@ -2219,13 +2608,14 @@ impl Bridge { // returns its exclusive pass, and the Bridge executes the host between begin and finish. fn metadata_pump_alt_sources_with(&mut self, host: impl FnOnce(plx_data::metadata::AltStandInReq, Option<&str>) -> plx_data::metadata::AltStandInAnswer) -> bool { + self.capture_store_session(); // Capture keys/roster BEFORE host registration. The pass exclusively borrows Metadata // and shares the keys until finish, preventing intervening step/reset/refill/publication. super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); let library = directory.current().and_then(|section| directory.sections().get(section)) .map(|section| section.row.title.as_str()); - let mut pass = self.stores.metadata.begin_alt_sources(&self.client_keys, plx_data::stores::tape::active()); + let mut pass = self.stores.metadata.begin_alt_sources(&self.client_keys, self.store_session.tape_active); let answer = pass.take_request().map(|request| host(request, library)); pass.finish(answer, &self.stores.landgate) } @@ -2443,6 +2833,11 @@ impl Bridge { } fn deliver_inner(&mut self, to: MachineId, msg: &AppMsg, parts: &CxParts, fx: &mut Effects<'_, AppHost>) -> Handled { + if let AppMsg::PersonCommand { from, command } = msg { + if to != MachineId::Store(StoreId::Person.ord()) { return Handled::No; } + self.person_run_from(Some(*from), command.clone()); + return Handled::Yes; + } if let AppMsg::Consent(command) = msg { if to != MachineId::Consent { return Handled::No; } match command { @@ -2471,7 +2866,7 @@ impl Bridge { // The owner reads its retained publication, not a borrow through its own mutable // field. Every other view still comes from this same Bridge frame boundary. let publication = self.session.publication(); - let cx = parts.cx::(AppViews { marker_prefs: self.marker_prefs, auth: publication.read(), + let cx = parts.cx::(AppViews { inputs: &self.screen_inputs, clock: &self.clock_facts, marker_prefs: self.marker_prefs, auth: publication.read(), hubs: self.hubs.view(), listing: self.listing.view(), directory: self.directory.view(), section_hubs: self.section_hubs.view(), search: self.search.view(), metadata: self.stores.metadata_view(), person: self.stores.person_view(), collection: self.stores.collection_view(), subtitle_search: self.stores.subtitle_search_view(), session: &self.playback, transport_paused: self.transport_paused, @@ -2507,7 +2902,7 @@ impl Bridge { AppMsg::Store(StoreCmd::Hubs(cmd)) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = self.stores.hubs.run_with_directory(cmd.clone(), directory, &self.client_keys).endpoints; + let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.run_with_directory(cmd.clone(), directory, &self.client_keys) }.endpoints; Self::admit_home_jobs(&mut self.stores, &mut self.store_runner, io, StoreId::Hubs); return Self::carry(&mut self.endpoint_carry, due); } @@ -2529,7 +2924,7 @@ impl Bridge { AppMsg::StoreWork(plx_data::stores::StoreWork::Hubs) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = self.stores.hubs.tick_with_directory(parts.tick.dt(), directory, &self.client_keys).endpoints; + let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.tick_with_directory(parts.tick.dt(), directory, &self.client_keys) }.endpoints; Self::admit_home_jobs(&mut self.stores, &mut self.store_runner, io, StoreId::Hubs); return Self::carry(&mut self.endpoint_carry, due); } @@ -2579,7 +2974,7 @@ impl Bridge { AppMsg::Store(StoreCmd::Hubs(c)) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = self.stores.hubs.run_with_directory(c.clone(), directory, &self.client_keys).endpoints; + let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.run_with_directory(c.clone(), directory, &self.client_keys) }.endpoints; self.start_store_jobs_of(StoreId::Hubs); Self::carry(&mut self.endpoint_carry, due) } @@ -2587,14 +2982,14 @@ impl Bridge { AppMsg::HubsResult(result) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = self.stores.hubs.land_with_directory(result, directory, &self.client_keys).endpoints; + let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.land_with_directory(result, directory, &self.client_keys) }.endpoints; self.start_store_jobs_of(StoreId::Hubs); Self::carry(&mut self.endpoint_carry, due) } AppMsg::StoreWork(plx_data::stores::StoreWork::Hubs) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = self.stores.hubs.tick_with_directory(parts.tick.dt(), directory, &self.client_keys).endpoints; + let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.tick_with_directory(parts.tick.dt(), directory, &self.client_keys) }.endpoints; self.start_store_jobs_of(StoreId::Hubs); Self::carry(&mut self.endpoint_carry, due) } @@ -2672,7 +3067,7 @@ impl Rig for Bridge { fn split(&mut self) -> Split<'_, AppHost> { Split { mounter: &mut self.mounter, - views: AppViews { marker_prefs: self.marker_prefs, auth: self.session.read(), + views: AppViews { inputs: &self.screen_inputs, clock: &self.clock_facts, marker_prefs: self.marker_prefs, auth: self.session.read(), hubs: self.hubs.view(), listing: self.listing.view(), directory: self.directory.view(), @@ -2683,6 +3078,14 @@ impl Rig for Bridge { measure: &self.measure, } } + fn deliver_from(&mut self, from: MachineId, to: MachineId, msg: &AppMsg, + parts: &CxParts, fx: &mut Effects<'_, AppHost>) -> Handled { + if matches!(msg, AppMsg::PersonCommand { from: embedded, .. } if *embedded != from) { + return Handled::No; + } + self.deliver(to, msg, parts, fx) + } + fn deliver(&mut self, to: MachineId, msg: &AppMsg, parts: &CxParts, fx: &mut Effects<'_, AppHost>) -> Handled { let handled = self.deliver_inner(to, msg, parts, fx); // A store step queues the endpoint refreshes it owes; they leave here, as many as the step @@ -2820,6 +3223,8 @@ impl Bridge { out.push(Fx::Deliver(from, Delivery::Screen(ScreenEvent::App(AppMsg::PlaybackTrace(status))))); } AppFx::Huds(command) => out.push(Fx::Deliver(MachineId::Huds, Delivery::Machine(AppMsg::Huds(command)))), + AppFx::Store(StoreId::Person, StoreCmd::Person(command)) => out.push(Fx::Deliver( + MachineId::Store(StoreId::Person.ord()), Delivery::Machine(AppMsg::PersonCommand { from, command }))), AppFx::Store(id, cmd) => out.push(Fx::Deliver(MachineId::Store(id.ord()), Delivery::Machine(AppMsg::Store(cmd)))), AppFx::StoreWork(work) => out.push(Fx::Deliver( MachineId::Store(work.store().ord()), Delivery::Machine(AppMsg::StoreWork(work)))), @@ -5213,3 +5618,212 @@ fn transport_keys_keep_their_identity_through_dispatcher_input() { let input = key_input(consts::SDLK_LEFT, consts::WCODE_REWIND, 1, Tick::default(), Source::Sdl); assert!(matches!(input.kind, InputKind::Key { key: Key::Left, .. }), "plain D-pad precedence is unchanged"); } + +#[cfg(test)] + +#[test] +fn watchlist_resolve_bridge_drains_in_the_emitting_call() { + let _serial = plx_base::testlock::serial(); + let mut bridge = Bridge::for_test(|| 0); + let sid = plx_plex::plex::ServerId::UNSET; + bridge.stores.watchlist.want_hex(sid, "7"); + bridge.watchlist_pump(); + assert!(!bridge.stores.watchlist.has_jobs(), "the emitting call drained the outbox"); + assert_eq!(bridge.run_held_store_jobs_of_for_test(StoreId::Watchlist), 1); + bridge.watchlist_pump(); + assert_eq!(bridge.stores.watchlist.view().resolved_hex(sid, "7"), None); + bridge.stores.watchlist.want_hex(sid, "7"); + bridge.watchlist_pump(); + assert!(!bridge.stores.watchlist.has_jobs()); + assert_eq!(bridge.run_held_store_jobs_of_for_test(StoreId::Watchlist), 1); +} + +#[cfg(test)] +mod screen_input_publication_tests { + use super::*; + #[test] + fn screen_inputs_notice_offer_expiry_with_a_stable_roster_and_retain_stable_arcs() { + use plx_plex::plex::{grant, session, probe::PlaintextEligibility}; + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("screen-input-notice"); + grant::reset_for_test(); + let mut bridge = Bridge::for_test(|| 0); + assert!(!bridge.capture_screen_inputs()); + let stored = bridge.screen_inputs.session.clone(); + let grants = bridge.screen_inputs.grants.clone(); + let profile = bridge.screen_inputs.profile.clone(); + assert!(!bridge.capture_screen_inputs()); + assert!(std::sync::Arc::ptr_eq(&stored, &bridge.screen_inputs.session)); + assert!(std::sync::Arc::ptr_eq(&grants, &bridge.screen_inputs.grants)); + assert!(std::sync::Arc::ptr_eq(&profile, &bridge.screen_inputs.profile)); + grant::offered(grant::scope(), grant::PlaintextVerdict { machine_id: "server".into(), + name: "Server".into(), shared_by: String::new(), eligibility: PlaintextEligibility::Eligible, + choice: session::PlaintextChoice::Undecided }); + assert!(bridge.capture_screen_inputs()); + assert_eq!(bridge.views().inputs.grants.offers.len(), 1); + assert!(!bridge.capture_screen_inputs()); + let generation = bridge.screen_inputs.grant_generation; + grant::network_changed(); + assert!(bridge.capture_screen_inputs()); + assert!(bridge.views().inputs.grants.offers.is_empty()); + assert_ne!(bridge.screen_inputs.grant_generation, generation); + assert!(!bridge.capture_screen_inputs()); + grant::reset_for_test(); + } + #[test] + fn screen_inputs_controlled_policy_never_captures_ambient_facts() { + let _serial = plx_base::testlock::serial(); + let mut bridge = Bridge::for_test(|| 0); + bridge.live_screen_inputs = false; + bridge.screen_inputs = Default::default(); + assert!(!bridge.capture_screen_inputs()); + assert!(!bridge.views().inputs.settled); + assert!(bridge.views().inputs.profile.user.is_none()); + assert!(bridge.views().inputs.grants.offers.is_empty()); + } +} + +#[cfg(test)] +mod screen_input_cache_revision_tests { + use super::*; + use plx_plex::plex::session::{self, UiResolution}; + #[test] + fn readable_locked_defaults_move_without_replacing_settled_grant_choices() { + use plx_plex::plex::grant; + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("screen-readable-locked-defaults"); + grant::reset_for_test(); + session::install_cleared_for_test(UiResolution::Auto); + let mut bridge = Bridge::for_test(|| 0); + let mut known = session::Session::default(); + known.account_token = "known-account".into(); + known.prefs.plaintext_consent.push(session::PlaintextConsent { + account: grant::account_key(&known.account_token), machine_id: "server".into(), + choice: session::PlaintextChoice::Allowed, extensions: Default::default() }); + let known = std::sync::Arc::new(known); + bridge.screen_grant_session = known.clone(); + session::install_locked_defaults_for_test(UiResolution::Hd720); + assert!(bridge.capture_screen_inputs()); + assert!(!bridge.views().inputs.settled); + assert_eq!(bridge.views().inputs.session.ui_resolution(), UiResolution::Hd720); + assert!(bridge.views().inputs.session.account_token.is_empty()); + assert_eq!(bridge.views().inputs.grants.choices, vec![("server".into(), session::PlaintextChoice::Allowed)]); + assert!(std::sync::Arc::ptr_eq(&known, &bridge.screen_grant_session)); + let readable = bridge.screen_inputs.session.clone(); + assert!(!bridge.capture_screen_inputs()); + assert!(std::sync::Arc::ptr_eq(&readable, &bridge.screen_inputs.session)); + grant::reset_for_test(); + } + #[test] + fn a_locked_defaults_race_does_not_publish_partial_readable_or_settled_facts() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("screen-readable-locked-race"); + session::install_cleared_for_test(UiResolution::Auto); + let mut bridge = Bridge::for_test(|| 0); + let readable = bridge.screen_inputs.session.clone(); + let settled = bridge.screen_grant_session.clone(); + session::install_locked_defaults_for_test(UiResolution::Hd900); + let mut calls = 0; + assert!(!bridge.capture_screen_inputs_with(|| { + calls += 1; + if calls == 2 { session::install_locked_defaults_for_test(UiResolution::Hd720); } + session::screen_input_revision() + })); + assert!(std::sync::Arc::ptr_eq(&readable, &bridge.screen_inputs.session)); + assert!(std::sync::Arc::ptr_eq(&settled, &bridge.screen_grant_session)); + assert!(bridge.capture_screen_inputs()); + assert!(!bridge.screen_inputs.settled); + assert_eq!(bridge.screen_inputs.session.ui_resolution(), UiResolution::Hd720); + assert!(std::sync::Arc::ptr_eq(&settled, &bridge.screen_grant_session)); + } + #[test] + fn a_cache_change_during_capture_keeps_the_previous_coherent_publication() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("screen-capture-race"); + session::install_cleared_for_test(UiResolution::Auto); + let mut bridge = Bridge::for_test(|| 0); + let held = bridge.screen_inputs.session.clone(); + let revision = bridge.screen_inputs.revision; + session::install_cleared_for_test(UiResolution::Hd900); + let mut calls = 0; + assert!(!bridge.capture_screen_inputs_with(|| { + calls += 1; + if calls == 2 { session::install_cleared_for_test(UiResolution::Hd720); } + session::screen_input_revision() + })); + assert_eq!(calls, 2); + assert!(std::sync::Arc::ptr_eq(&held, &bridge.screen_inputs.session)); + assert_eq!(bridge.screen_inputs.revision, revision); + assert!(bridge.capture_screen_inputs()); + assert_eq!(bridge.screen_inputs.session.ui_resolution(), UiResolution::Hd720); + } + #[test] + fn equal_cache_and_profile_publications_do_not_emit_a_semantic_notice() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("screen-equal-publication"); + session::install_cleared_for_test(UiResolution::Auto); + session::publish_profile_for_test(None, 0); + let mut bridge = Bridge::for_test(|| 0); + let held = bridge.screen_inputs.session.clone(); + let profile = bridge.screen_inputs.profile.clone(); + let before = bridge.screen_cache_revision; + session::install_cleared_for_test(UiResolution::Auto); + session::publish_profile_for_test(None, 0); + assert!(!bridge.capture_screen_inputs()); + assert_ne!(bridge.screen_cache_revision, before); + assert!(std::sync::Arc::ptr_eq(&held, &bridge.screen_inputs.session)); + assert!(std::sync::Arc::ptr_eq(&profile, &bridge.screen_inputs.profile)); + assert!(!bridge.capture_screen_inputs()); + } + #[test] + fn same_generation_profile_replacement_is_a_new_screen_input() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("screen-profile-generation-zero"); + session::publish_profile_for_test(Some(session::UserRef { uuid: "maya".into(), + title: "Maya".into(), ..Default::default() }), 0); + let mut bridge = Bridge::for_test(|| 0); + session::publish_profile_for_test(Some(session::UserRef { uuid: "noah".into(), + title: "Noah".into(), ..Default::default() }), 0); + assert!(bridge.capture_screen_inputs()); + assert_eq!(bridge.views().inputs.profile.user.as_ref().unwrap().title, "Noah"); + assert!(!bridge.capture_screen_inputs()); + } + #[test] + fn stable_cleared_and_locked_screen_inputs_retain_the_same_session_arc() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("screen-stable-cleared"); + session::install_cleared_for_test(UiResolution::Auto); + let mut bridge = Bridge::for_test(|| 0); + let held = bridge.screen_inputs.session.clone(); + for _ in 0..3 { + assert!(!bridge.capture_screen_inputs()); + assert!(std::sync::Arc::ptr_eq(&held, &bridge.screen_inputs.session)); + } + session::install_transient_for_test(true); + assert!(bridge.capture_screen_inputs()); + assert!(!bridge.screen_inputs.settled); + let held = bridge.screen_inputs.session.clone(); + for _ in 0..3 { + assert!(!bridge.capture_screen_inputs()); + assert!(std::sync::Arc::ptr_eq(&held, &bridge.screen_inputs.session)); + } + } + #[test] + fn cleared_defaults_publish_even_when_visible_session_generation_does_not_move() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("screen-cleared-defaults"); + session::install_cleared_for_test(UiResolution::Auto); + let mut bridge = Bridge::for_test(|| 0); + let visible = session::visible_generation(); + session::install_cleared_for_test(UiResolution::Hd720); + assert_eq!(session::visible_generation(), visible); + assert!(bridge.capture_screen_inputs(), "the changed defaults owe a notice"); + assert_eq!(bridge.views().inputs.session.ui_resolution(), UiResolution::Hd720); + assert!(!bridge.capture_screen_inputs()); + } + +} + +#[cfg(test)] +#[path = "person_boundary_tests.rs"] +mod person_boundary_tests; diff --git a/rust-modules/src/app/bridge_test_support.rs b/rust-modules/src/app/bridge_test_support.rs index 481dbebffc..b9495f3768 100644 --- a/rust-modules/src/app/bridge_test_support.rs +++ b/rust-modules/src/app/bridge_test_support.rs @@ -649,6 +649,7 @@ impl World { pub(super) fn step(&mut self, inputs: Vec>) { self.frame += 1; if let Some(feed) = self.feed { feed(&mut self.d, &mut self.bridge); } + if self.script.is_some() { self.bridge.store_runner.run_held_watchlist_writes(); } plx_machine::idle::frame_begin(0.016); super::frame(&mut self.d, &mut self.bridge, tick(self.frame), inputs); let now = self.frame * 16; diff --git a/rust-modules/src/app/clock.rs b/rust-modules/src/app/clock.rs index 56b99f4e3c..b65982c690 100644 --- a/rust-modules/src/app/clock.rs +++ b/rust-modules/src/app/clock.rs @@ -49,6 +49,7 @@ pub(crate) const REPLAY_DATE: [i32; 3] = [2026, 1, 1]; /// Milliseconds since SDL init — or, under a replay, the recorded tick of the frame in flight. pub(crate) fn now() -> u32 { + plx_base::step::assert_io_allowed("app::clock::now"); if let Some(ms) = REPLAY.with(|c| c.get()) { return ms; } @@ -68,6 +69,7 @@ pub(crate) fn set_replay(ms: u32) { /// inventing today's date for a historical frame would make the HUD nondeterministic. The platform /// clock is sampled at most every five seconds and advanced with monotonic frame ticks between samples. pub(crate) fn unix_ms() -> Option { + plx_base::step::assert_io_allowed("app::clock::unix_ms"); if REPLAY.with(|c| c.get().is_some()) { UNIX.with(|c| c.set(None)); return None; @@ -119,6 +121,7 @@ fn advance_unix_ms(sampled_at: u32, sampled: Option, tick: u32) -> Option Option<[i32; 3]> { + plx_base::step::assert_io_allowed("app::clock::today"); // A recorded Library grid sorted by a date must word the same on every run and on every day. if REPLAY.with(|c| c.get()).is_some() { return Some(REPLAY_DATE); @@ -134,6 +137,20 @@ pub(crate) fn today() -> Option<[i32; 3]> { #[cfg(test)] mod tests { + #[test] + fn a_machine_cannot_sample_even_the_replay_clock_or_cached_calendar() { + super::set_replay(4242); + let _allowed = plx_base::task::allow_blocking(const { &plx_base::task::BlockingLabel::new("fixture") }); + let step = plx_base::step::StepScope::enter(); + for read in [|| { super::now(); }, || { super::unix_ms(); }, || { super::today(); }] { + assert!(std::panic::catch_unwind(read).is_err()); + } + drop(step); + assert_eq!(super::now(), 4242); + assert_eq!(super::today(), Some(super::REPLAY_DATE)); + super::REPLAY.with(|c| c.set(None)); + } + #[test] fn a_replay_tick_overrides_the_clock_for_the_thread() { super::set_replay(4242); diff --git a/rust-modules/src/app/detail_panel_tests.rs b/rust-modules/src/app/detail_panel_tests.rs index b4e5f8b170..0cef959f3f 100644 --- a/rust-modules/src/app/detail_panel_tests.rs +++ b/rust-modules/src/app/detail_panel_tests.rs @@ -40,7 +40,7 @@ fn a_detail_panel_parks_across_a_push_and_returns_with_the_same_instance() { // stacks the person page over it — which is the shape the loop really produces. let mut d = Dispatcher::::new(); let mut rig = Bridge::for_test(|| 0); - rig.stores.metadata.run(plx_data::stores::metadata::MetadataCmd::AltInstall { + rig.metadata_run(plx_data::stores::metadata::MetadataCmd::AltInstall { sid: here, rk: "m1".into(), copies: vec![ diff --git a/rust-modules/src/app/hubs_dump_tests.rs b/rust-modules/src/app/hubs_dump_tests.rs index d1e310c4a0..077146a718 100644 --- a/rust-modules/src/app/hubs_dump_tests.rs +++ b/rust-modules/src/app/hubs_dump_tests.rs @@ -172,7 +172,7 @@ fn the_controlled_home_discovery_take_waits_for_a_request_it_owes_under_dump_mod // answer. rig.stores.browse.borrow().observe_pin_write(); crate::app::adapters::stores::refill_client_keys(&mut rig.client_keys); - let input = plx_data::browse::BrowseRosterInput { + let input = plx_data::browse::BrowseRosterInput { tenure: 0, keys: &rig.client_keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), diff --git a/rust-modules/src/app/library_switch_route_tests.rs b/rust-modules/src/app/library_switch_route_tests.rs index 7ce73cbc58..42695a0bbf 100644 --- a/rust-modules/src/app/library_switch_route_tests.rs +++ b/rust-modules/src/app/library_switch_route_tests.rs @@ -12,7 +12,7 @@ fn store_current(r: &World) -> Option { r.bridge.stores.browse.borrow().observe_pin_write(); let mut keys = plx_plex::plex::ClientKeys::default(); crate::app::adapters::stores::refill_client_keys(&mut keys); - let input = plx_data::browse::BrowseRosterInput { + let input = plx_data::browse::BrowseRosterInput { tenure: 0, keys: &keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), diff --git a/rust-modules/src/app/notify_bridge_tests.rs b/rust-modules/src/app/notify_bridge_tests.rs index c4a8b41ef1..92903791e7 100644 --- a/rust-modules/src/app/notify_bridge_tests.rs +++ b/rust-modules/src/app/notify_bridge_tests.rs @@ -56,7 +56,7 @@ fn ordered(port: &NotifyStreamPort, addr: Addr, _: &'static Client, req: NotifyS fn boot(bridge: &mut Bridge, held: bool) { SCRIPT.with(|s| s.borrow_mut().eligible = true); bridge.store_runner = if held { StoreRunner::held_all() } else { - StoreRunner::Held { parked: Vec::new(), live: &[LiveKind::NotifyStream], notify: NotifyTransport::Refuse } + StoreRunner::Held { parked: Vec::new(), live: &[LiveKind::NotifyStream], notify: NotifyTransport::Refuse, watchlist_write: None, watchlist_streams_held: false } }; bridge.store_runner.set_notify_transport(NotifyTransport::Script { eligible, run: ordered }); } @@ -133,7 +133,7 @@ fn cursor_posts_and_terminal_map_in_connection_order_without_second_drain_or_lat assert_eq!(bridge.stores.reconcile.pending_for_test(), [(a, "a-first".into()), (b, "b-first".into()), (a, "a-late".into())]); SCRIPT.with(|s| assert_eq!(s.borrow().launches, [a, b])); - assert_eq!(plx_data::stores::Stores::NOTIFY_FILLS, [StoreId::Browse, StoreId::Hubs]); + assert_eq!(plx_data::stores::Stores::NOTIFY_FILLS, [StoreId::Browse, StoreId::Hubs, StoreId::Watchlist]); assert!(StoreId::Hubs.ord().0 < StoreId::Notify.ord().0); clean(&bridge); bridge.notify_suspend(); } diff --git a/rust-modules/src/app/person_boundary_tests.rs b/rust-modules/src/app/person_boundary_tests.rs new file mode 100644 index 0000000000..d75c914727 --- /dev/null +++ b/rust-modules/src/app/person_boundary_tests.rs @@ -0,0 +1,438 @@ +use super::*; +use plx_plex::plex::{session, ClientKeys, ServerId}; + +#[test] +fn store_session_capture_rejects_adversarial_publication_without_partial_commit() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-coherent-capture"); + session::save(&session::Session { client_id: "person-a".into(), account_token: "token-a".into(), ..Default::default() }); + let mut capture = StoreSessionCapture::default(); + assert!(capture.refill_store_session(session::screen_input_revision)); + let retained = capture.observed.clone(); + let retained_generation = capture.visible_generation; + let retained_revision = capture.revision; + let mut calls = 0; + // Force a capture, and publish between the reads and the closing fence. + capture.controlled = true; + assert!(!capture.refill_store_session(|| { + calls += 1; + if calls == 2 { session::save(&session::Session { client_id: "person-b".into(), account_token: "token-b".into(), ..Default::default() }); } + session::screen_input_revision() + })); + assert!(std::sync::Arc::ptr_eq(&capture.observed, &retained)); + assert_eq!(capture.visible_generation, retained_generation); + assert_eq!(capture.revision, retained_revision); + assert!(capture.refill_store_session(session::screen_input_revision)); + assert!(std::sync::Arc::ptr_eq(capture.session.as_ref().unwrap(), &session::peek_settled().unwrap())); + assert_eq!(capture.visible_generation, session::visible_generation()); + assert_eq!(capture.profile_generation, session::current_snapshot().generation); + assert_eq!(capture.tenure, session::tenure()); + assert_eq!(capture.revision, Some(session::screen_input_revision())); + capture.controlled = false; + let retained = capture.observed.clone(); + let key = capture.profile_key.as_ptr(); + for _ in 0..8 { assert!(capture.refill_store_session(session::screen_input_revision)); } + assert!(std::sync::Arc::ptr_eq(&capture.observed, &retained)); + assert_eq!(capture.profile_key.as_ptr(), key); +} + +#[test] +fn actual_runner_launch_refusal_is_consumed_in_the_same_bridge_drain() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-same-drain-refusal"); + plx_plex::plex::reset_servers_for_test(); + let sid = plx_plex::plex::register_for_test("person-refusal", "127.0.0.1", 1, "token", "cid"); + let mut bridge = Bridge::for_test(|| 0); + bridge.person_run(plx_data::stores::person::PersonCmd::Open { + sid, key: "7".into(), guid: "".into(), name: "Actor".into(), thumb: "".into(), + }); + assert!(bridge.capture_store_session()); + super::super::adapters::stores::refill_client_keys(&mut bridge.client_keys); + let owner = bridge.session.read().0; + let input = bridge.person_capture.input(&bridge.client_keys, &bridge.store_session, owner.scope.0, owner.flow_epoch); + bridge.stores.person_pump(&input); + let jobs = bridge.stores.take_jobs_of(StoreId::Person); + assert_eq!(jobs.len(), 1); + let adapter = bridge.stores.person.adapter_for_test(); + let slot = sid.raw() as usize * 3 + 1; + assert!(adapter.busy_for_test(slot)); + let notice = bridge.stores.person.gen(); + // The real runner resolves the captured key here and refuses this retired client. + plx_plex::plex::reset_servers_for_test(); + assert_eq!(bridge.start_jobs(jobs), 1); + assert!(!adapter.busy_for_test(slot)); + assert!(!adapter.has_mail_for_test(slot), "refusal did not masquerade as a network answer"); + assert!(bridge.stores.person.gen() > notice, "the owner observed the addressed terminal in this call"); + assert!(!bridge.stores.person.has_jobs(), "the refusal pass never re-emits work"); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn person_capture_carries_session_machine_scope_epoch_and_retained_profile_tenure() { + let capture = StoreSessionCapture { profile_generation: 19, tenure: 23, profile_key: "tenant".into(), ..Default::default() }; + let person = PersonCapture::default(); + let keys = ClientKeys::default(); + let input = person.input(&keys, &capture, 29, 31); + assert_eq!((input.profile_scope, input.owner_epoch, input.profile_generation, input.tenure), (29, 31, 19, 23)); + assert_eq!(input.profile_key, "tenant"); + assert_eq!(input.keys as *const ClientKeys, &keys as *const ClientKeys); + assert_eq!(ServerId::UNSET, keys.current()); +} + +#[test] +fn mounted_person_recovers_from_rejected_capture_without_enter_or_uncover() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-mounted-capture-retry"); + let mut bridge = Bridge::for_test(|| 0); + bridge.person_session_capture = |_| false; + let mut dispatcher = Dispatcher::::new(); + show_page(&mut dispatcher, super::test_support::person_arg("pending-actor")); + frame(&mut dispatcher, &mut bridge, super::test_support::tick(0), vec![]); + let entry = dispatcher.nav.top_page().unwrap().id; + assert!(bridge.person_view().current().is_none(), "incoherent input cannot Open"); + assert!(!bridge.stores.person.has_jobs(), "no claim before coherent input"); + bridge.person_session_capture = Bridge::capture_store_session_live; + assert!(bridge.person_pump(), "the owner must deliver its deferred Open on recovery"); + assert!(bridge.pending_person_open.is_none(), "successful delivery consumes the obligation"); + let notice = bridge.stores.person.gen(); + assert_eq!(bridge.person_view().current().unwrap().key, "pending-actor"); + for n in 1..4 { + frame(&mut dispatcher, &mut bridge, super::test_support::tick(n), vec![]); + bridge.person_pump(); + assert_eq!(dispatcher.nav.top_page().unwrap().id, entry, "the page stayed mounted"); + assert_eq!(bridge.stores.person.gen(), notice, "recovery delivers Open exactly once"); + } + bridge.assert_no_store_jobs_left_for_test(); +} + +fn deferred_open(key: &str) -> plx_data::stores::person::PersonCmd { + plx_data::stores::person::PersonCmd::Open { + sid: ServerId::UNSET, key: key.into(), guid: String::new(), + name: key.into(), thumb: String::new(), + } +} + +#[test] +fn close_or_reset_before_capture_recovery_cancels_the_owed_open() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-deferred-close"); + for cancel in [plx_data::stores::person::PersonCmd::Close, plx_data::stores::person::PersonCmd::Reset] { + let mut bridge = Bridge::for_test(|| 0); + bridge.person_session_capture = |_| false; + assert!(!bridge.person_run(deferred_open("cancelled"))); + assert!(bridge.pending_person_open.is_some(), "the bridge accepted responsibility for delivery"); + bridge.person_run(cancel); + assert!(bridge.pending_person_open.is_none()); + let notice = bridge.stores.person.gen(); + bridge.person_session_capture = Bridge::capture_store_session_live; + bridge.person_pump(); + assert!(bridge.person_view().current().is_none()); + assert_eq!(bridge.stores.person.gen(), notice, "a cancelled Open cannot reappear"); + bridge.assert_no_store_jobs_left_for_test(); + } +} + +#[test] +fn replacement_deferred_open_is_latest_wins_and_delivered_once() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-deferred-replacement"); + let mut bridge = Bridge::for_test(|| 0); + bridge.person_session_capture = |_| false; + bridge.person_run(deferred_open("old")); + bridge.person_run(deferred_open("latest")); + assert!(bridge.pending_person_open.is_some()); + assert!(bridge.person_view().current().is_none()); + assert_eq!(bridge.stores.person.gen(), 0, "no speculative Open or claim"); + bridge.person_session_capture = Bridge::capture_store_session_live; + assert!(bridge.person_pump()); + assert_eq!(bridge.person_view().current().unwrap().key, "latest"); + assert!(bridge.pending_person_open.is_none(), "successful delivery consumes the obligation"); + let notice = bridge.stores.person.gen(); + for _ in 0..3 { bridge.person_pump(); } + assert_eq!(bridge.stores.person.gen(), notice); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn profile_edge_before_capture_recovery_cannot_reopen_the_old_person() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-deferred-profile-edge"); + let mut bridge = Bridge::for_test(|| 0); + bridge.live_screen_inputs = false; + bridge.person_session_capture = |_| false; + bridge.person_run(deferred_open("old-profile")); + assert!(bridge.pending_person_open.is_some()); + bridge.screen_inputs.profile = std::sync::Arc::new(session::CurrentProfile { + generation: bridge.screen_inputs.profile.generation.wrapping_add(1), user: None, stamp: String::new(), + }); + bridge.person_session_capture = Bridge::capture_store_session_live; + bridge.person_pump(); + assert!(bridge.person_view().current().is_none()); + assert_eq!(bridge.stores.person.gen(), 0); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn leaving_an_empty_mounted_person_cancels_its_deferred_open() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-deferred-navigation"); + let mut bridge = Bridge::for_test(|| 0); + bridge.person_session_capture = |_| false; + let mut dispatcher = Dispatcher::::new(); + show_page(&mut dispatcher, super::test_support::person_arg("left-actor")); + frame(&mut dispatcher, &mut bridge, super::test_support::tick(0), vec![]); + let entry = dispatcher.nav.top_page().unwrap().id; + assert!(bridge.pending_person_open.is_some()); + nav_root(&mut dispatcher, super::test_support::detail_arg("replacement-page")); + for n in 1..40 { frame(&mut dispatcher, &mut bridge, super::test_support::tick(n), vec![]); } + assert_ne!(dispatcher.nav.top_page().unwrap().id, entry); + assert!(bridge.pending_person_open.is_none(), "teardown cancels even before recovery"); + assert!(bridge.person_view().current().is_none()); + bridge.person_session_capture = Bridge::capture_store_session_live; + bridge.person_pump(); + assert!(bridge.person_view().current().is_none(), "navigation cannot resurrect the retired page"); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn session_owner_edge_before_capture_recovery_cannot_reopen_the_old_person() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-deferred-owner-edge"); + let mut bridge = Bridge::for_test(|| 0); + bridge.person_session_capture = |_| false; + bridge.person_run(deferred_open("retired-owner")); + assert!(bridge.pending_person_open.is_some()); + let before = { let owner = bridge.session.read().0; (owner.scope.0, owner.flow_epoch) }; + let mut dispatcher = Dispatcher::::new(); + execute_session_command(&mut dispatcher, plx_session::auth::SessionCmd::SignOut); + frame(&mut dispatcher, &mut bridge, super::test_support::tick(0), vec![]); + let after = { let owner = bridge.session.read().0; (owner.scope.0, owner.flow_epoch) }; + assert_ne!(before, after, "exercise the real session owner cancellation edge"); + bridge.person_session_capture = Bridge::capture_store_session_live; + bridge.person_pump(); + assert!(bridge.person_view().current().is_none()); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn controlled_account_edge_before_recovery_cannot_reopen_the_old_person() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-deferred-controlled-account"); + let mut bridge = Bridge::for_test(|| 0); + bridge.live_screen_inputs = false; + bridge.screen_inputs.session = std::sync::Arc::new(session::Session { + client_id: "account-a".into(), account_token: "token-a".into(), ..Default::default() + }); + bridge.person_session_capture = |_| false; + bridge.person_run(deferred_open("old-account")); + assert!(bridge.pending_person_open.is_some()); + bridge.screen_inputs.session = std::sync::Arc::new(session::Session { + client_id: "account-b".into(), account_token: "token-b".into(), ..Default::default() + }); + bridge.person_session_capture = Bridge::capture_store_session_live; + bridge.person_pump(); + assert!(bridge.pending_person_open.is_none()); + assert!(bridge.person_view().current().is_none()); + assert_eq!(bridge.stores.person.gen(), 0); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn live_tenure_revocation_before_recovery_cannot_reopen_the_old_person() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-deferred-live-tenure"); + let mut bridge = Bridge::for_test(|| 0); + bridge.live_screen_inputs = true; + bridge.person_session_capture = |_| false; + bridge.person_run(deferred_open("revoked-account")); + assert!(bridge.pending_person_open.is_some()); + let tenure = session::tenure(); + session::revoke_cached_session(); + assert_ne!(session::tenure(), tenure); + bridge.person_session_capture = Bridge::capture_store_session_live; + bridge.person_pump(); + assert!(bridge.pending_person_open.is_none()); + assert!(bridge.person_view().current().is_none()); + assert_eq!(bridge.stores.person.gen(), 0); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn retired_sender_cannot_cancel_or_close_its_replacement() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-deferred-sender-replacement"); + let mut bridge = Bridge::for_test(|| 0); + let old = Some(MachineId::Instance(InstanceId(901))); + let latest = Some(MachineId::Instance(InstanceId(902))); + bridge.person_session_capture = |_| false; + bridge.person_run_from(old, deferred_open("old")); + bridge.person_run_from(latest, deferred_open("latest")); + bridge.person_run_from(old, plx_data::stores::person::PersonCmd::Close); + assert!(bridge.pending_person_open.is_some()); + bridge.person_session_capture = Bridge::capture_store_session_live; + assert!(bridge.person_pump()); + assert_eq!(bridge.person_view().current().unwrap().key, "latest"); + let notice = bridge.stores.person.gen(); + assert!(!bridge.person_run_from(old, plx_data::stores::person::PersonCmd::Close)); + assert_eq!(bridge.stores.person.gen(), notice, "retired Close cannot mutate its replacement"); + for _ in 0..3 { bridge.person_pump(); } + assert_eq!(bridge.stores.person.gen(), notice, "only one successful Open"); + bridge.person_run_from(latest, plx_data::stores::person::PersonCmd::Close); + assert!(bridge.person_view().current().is_none()); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn mounted_person_replacement_survives_old_empty_page_teardown() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-mounted-deferred-replacement"); + let mut bridge = Bridge::for_test(|| 0); + bridge.person_session_capture = |_| false; + let mut dispatcher = Dispatcher::::new(); + show_page(&mut dispatcher, super::test_support::person_arg("old-mounted")); + frame(&mut dispatcher, &mut bridge, super::test_support::tick(0), vec![]); + let old = dispatcher.nav.top_page().unwrap().id; + nav_root(&mut dispatcher, super::test_support::person_arg("latest-mounted")); + for n in 1..40 { frame(&mut dispatcher, &mut bridge, super::test_support::tick(n), vec![]); } + assert_ne!(dispatcher.nav.top_page().unwrap().id, old); + assert!(bridge.pending_person_open.is_some()); + bridge.person_session_capture = Bridge::capture_store_session_live; + assert!(bridge.person_pump()); + assert_eq!(bridge.person_view().current().unwrap().key, "latest-mounted"); + let notice = bridge.stores.person.gen(); + for n in 40..44 { frame(&mut dispatcher, &mut bridge, super::test_support::tick(n), vec![]); bridge.person_pump(); } + assert_eq!(bridge.stores.person.gen(), notice); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn idle_person_100_host_passes_do_not_read_developer_seeds() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-idle-seed-reads"); + let mut bridge = Bridge::for_test(|| 0); + let mut reads = 0; + for _ in 0..100 { + bridge.person_pump_with_seed_read(&mut |_| { reads += 1; None }); + } + println!("100 idle Person host passes: {reads} seed reads"); + assert_eq!(reads, 0, "closed Person must not touch trigger paths or files"); + assert!(bridge.person_view().current().is_none()); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn person_seed_reads_wait_for_admission_and_track_open_capture_changes() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-open-seed-reads"); + let mut bridge = Bridge::for_test(|| 0); + bridge.person_session_capture = |_| false; + bridge.person_run(deferred_open("seeded")); + let mut reads = Vec::new(); + assert!(!bridge.person_pump_with_seed_read(&mut |name| { reads.push(name.to_owned()); Some("2".into()) })); + assert!(reads.is_empty(), "rejected capture cannot read speculative Open seeds"); + bridge.person_session_capture = Bridge::capture_store_session_live; + assert!(bridge.person_pump_with_seed_read(&mut |name| { reads.push(name.to_owned()); Some("2".into()) })); + assert_eq!(reads.iter().filter(|s| s.as_str() == "personbio").count(), 1); + assert!(reads.iter().any(|s| s == "personcredits")); + assert_eq!(bridge.person_capture.dev_bio.as_deref(), Some("2")); + assert_eq!(bridge.person_capture.dev_credits.as_deref(), Some("2")); + let initial_total = plx_data::person::filmography_total(bridge.person_view().current().unwrap()); + assert!(initial_total > 0, "the admitted Open seeds the actual Person filmography"); + reads.clear(); + bridge.person_pump_with_seed_read(&mut |name| { reads.push(name.to_owned()); Some("3".into()) }); + assert_eq!(reads, ["personcredits"], "an open page refreshes credits, not its Open-only biography"); + assert_eq!(bridge.person_capture.dev_credits.as_deref(), Some("3")); + assert_eq!(plx_data::person::filmography_total(bridge.person_view().current().unwrap()), initial_total + 1); + assert_eq!(bridge.person_capture.dev_bio.as_deref(), Some("2")); + bridge.person_run(plx_data::stores::person::PersonCmd::Close); + reads.clear(); + bridge.person_pump_with_seed_read(&mut |name| { reads.push(name.to_owned()); None }); + assert!(reads.is_empty(), "closing retires seed IO immediately"); + bridge.assert_no_store_jobs_left_for_test(); +} + +#[test] +fn controlled_person_capture_never_calls_the_live_seed_reader() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("person-controlled-seed-reads"); + let mut bridge = Bridge::for_test(|| 0); + for live in [false, true] { + bridge.live_screen_inputs = live; + bridge.person_pump_with_seed_read(&mut |_| panic!("closed Person must not read live trigger files")); + assert_eq!(bridge.person_capture.controlled, !live, "closed pumps still capture control identity"); + } + let mut capture = PersonCapture::default(); + capture.refresh("", true, true, &mut |_| panic!("controlled input must not read live trigger files")); + assert!(capture.controlled); + assert!(capture.dev_bio.is_none()); +} + +impl Bridge { + pub(crate) fn assert_person_provenance_at_dispatch(tap: &mut dyn plx_ui::dispatch::Tap) { + use plx_data::stores::person::PersonCmd; + use std::sync::atomic::{AtomicUsize, Ordering}; + static CAPTURES: AtomicUsize = AtomicUsize::new(0); + let sender = MachineId::Instance(InstanceId(3)); + let other = MachineId::Instance(InstanceId(4)); + let mut bridge = Bridge::for_test(|| 0); + bridge.live_screen_inputs = false; + assert!(bridge.person_run_from(Some(sender), deferred_open("admitted"))); + bridge.stores.person.seed_ownership_fixture_for_test(); + let publication = bridge.stores.person.ownership_fixture_for_test(); + let generation = bridge.stores.person.gen(); + let owner = bridge.person_owner; + let captured = bridge.store_session.observed.clone(); + let capture_guid = bridge.person_capture.guid.clone(); + bridge.person_session_capture = |_| { CAPTURES.fetch_add(1, Ordering::SeqCst); false }; + CAPTURES.store(0, Ordering::SeqCst); + let mut dispatcher = Dispatcher::::new(); + let parts = CxParts { tick: Tick::default(), press: Default::default(), + focus: Default::default(), owner: InputOwner::Entry(EntryId(0)) }; + let mut report = FrameReport::default(); + // The tap sees the forged envelope, but cannot prevent its execution. + for (from, embedded) in [(MachineId::Nav, sender), (sender, MachineId::Nav), (other, sender)] { + for command in [PersonCmd::Reset, deferred_open("forged")] { + dispatcher.emit(from, Fx::Deliver(MachineId::Store(StoreId::Person.ord()), + Delivery::Machine(AppMsg::PersonCommand { from: embedded, command }))); + assert_eq!(dispatcher.drain(&mut bridge, &parts, 1, &mut report, tap), 1); + assert_eq!(bridge.stores.person.ownership_fixture_for_test(), publication, + "mismatched Person provenance must not mutate its publication or flights"); + assert_eq!(bridge.stores.person.gen(), generation); + assert_eq!(bridge.person_owner, owner); + assert!(bridge.pending_person_open.is_none(), "forged Open must not become deferred work"); + assert!(std::sync::Arc::ptr_eq(&bridge.store_session.observed, &captured)); + assert_eq!(bridge.person_capture.guid, capture_guid); + assert_eq!(CAPTURES.load(Ordering::SeqCst), 0, "rejection must precede captured-input IO"); + assert!(!bridge.stores.person.has_jobs()); + assert!(bridge.take_held_store_jobs_for_test().is_empty(), "no runner IO admitted"); + bridge.assert_no_store_jobs_left_for_test(); + } + } + let mut out = Vec::new(); + let mut present = Present::new(); + let mut fx = Effects::new(&mut out, MachineId::Store(StoreId::Person.ord()), &mut present); + assert_eq!(Rig::deliver_from(&mut bridge, MachineId::Nav, MachineId::Store(StoreId::Person.ord()), + &AppMsg::PersonCommand { from: sender, command: PersonCmd::Reset }, &parts, &mut fx), Handled::No); + assert!(out.is_empty(), "refusal emits no work"); + // Matching provenance still executes in this drain, including after tap refusal. + bridge.person_session_capture = Bridge::capture_store_session_live; + dispatcher.emit(other, Fx::Deliver(MachineId::Store(StoreId::Person.ord()), + Delivery::Machine(AppMsg::PersonCommand { from: other, command: deferred_open("matching") }))); + assert_eq!(dispatcher.drain(&mut bridge, &parts, 1, &mut report, tap), 1); + assert_eq!(bridge.person_view().current().unwrap().key, "matching"); + assert!(bridge.pending_person_open.is_none()); + let matching = bridge.stores.person.ownership_fixture_for_test(); + dispatcher.emit(sender, Fx::Deliver(MachineId::Store(StoreId::Person.ord()), + Delivery::Machine(AppMsg::PersonCommand { from: sender, command: PersonCmd::Close }))); + dispatcher.drain(&mut bridge, &parts, 1, &mut report, tap); + assert_eq!(bridge.stores.person.ownership_fixture_for_test(), matching, + "matching provenance must not bypass retired-instance authorization"); + dispatcher.emit(other, Fx::Deliver(MachineId::Store(StoreId::Person.ord()), + Delivery::Machine(AppMsg::PersonCommand { from: other, command: PersonCmd::Reset }))); + assert_eq!(dispatcher.drain(&mut bridge, &parts, 1, &mut report, tap), 1); + assert!(bridge.person_view().current().is_none()); + assert!(bridge.stores.person.gen() > generation); + assert_eq!(CAPTURES.load(Ordering::SeqCst), 0); + bridge.assert_no_store_jobs_left_for_test(); + } +} diff --git a/rust-modules/src/app/preferences.rs b/rust-modules/src/app/preferences.rs index ae4355cd93..5b2976c68d 100644 --- a/rust-modules/src/app/preferences.rs +++ b/rust-modules/src/app/preferences.rs @@ -65,6 +65,18 @@ pub(super) fn execute(command: PreferenceCmd) { } // Every live setting saves through the one write door, in `choose_setting`. PreferenceCmd::Choose(choice, reply) => choose_setting(choice, reply), + PreferenceCmd::AutoSignIn { on, reply } => { + let expected = plx_plex::plex::session::peek(); + let tenure = plx_plex::plex::session::tenure(); + let _ = plx_base::storage_worker::submit_retained(move || { + let saved = plx_plex::plex::session::update_guarded_with_outcome(|current| { + if current.client_id != expected.client_id || current.account_token != expected.account_token { return None; } + (current.auto_sign_in() != on).then(|| current.with_auto_sign_in(on)) + }, || plx_plex::plex::session::tenure() == tenure).is_some_and(|write| write.outcome.persisted()); + let _ = reply.send(saved); + plx_machine::idle::invalidate(); + }); + } PreferenceCmd::UiResolution { mode, reply } => { let _ = plx_base::storage_worker::submit_retained(move || { let _ = reply.send(plx_plex::plex::session::set_ui_resolution(mode)); @@ -89,3 +101,139 @@ pub(super) fn execute_marker(command: PreferenceCmd, view: plx_appkit::skip_poli plx_data::metadata::MarkerKind::Credits => Choice::CreditsSkip(mode) }, reply); } } +#[cfg(test)] +mod tests { + use super::*; + use plx_plex::plex::session::{self, Session}; + use std::sync::mpsc::{self, Sender, TryRecvError}; + + struct FullStorageQueue(Option>); + impl FullStorageQueue { + fn new() -> Self { + plx_base::storage_worker::drain_for_test(); + let (release, held) = mpsc::channel(); + let (started, entered) = mpsc::channel(); + let guard = Self(Some(release)); + let _ = plx_base::storage_worker::submit(move || { + started.send(()).unwrap(); + let _ = held.recv(); + }).unwrap(); + entered.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + for _ in 0..plx_base::storage_worker::CAPACITY { + let _ = plx_base::storage_worker::submit(|| ()).unwrap(); + } + assert!(matches!(plx_base::storage_worker::submit(|| ()), + Err(plx_base::storage_worker::SubmitError::Full))); + guard + } + } + impl Drop for FullStorageQueue { + fn drop(&mut self) { + if let Some(release) = self.0.take() { let _ = release.send(()); } + plx_base::storage_worker::drain_for_test(); + } + } + + fn account() -> Session { + Session { client_id: "preference-client".into(), account_token: "synthetic-account".into(), + ..Default::default() }.with_auto_sign_in(false) + } + + #[test] + fn auto_sign_in_retains_a_full_worker_queue_edit() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("app-auto-sign-in-full"); + session::save(&account()); + let queue = FullStorageQueue::new(); + let (reply, answer) = mpsc::channel(); + execute(PreferenceCmd::AutoSignIn { on: true, reply }); + assert_eq!(answer.try_recv(), Err(TryRecvError::Empty), "backpressure is not a terminal refusal"); + assert!(!session::peek().auto_sign_in()); + drop(queue); + assert_eq!(answer.try_recv(), Ok(true)); + assert_eq!(answer.try_recv(), Err(TryRecvError::Disconnected), "exactly one terminal reply"); + session::invalidate_for_test(); + assert!(session::load().auto_sign_in(), "the actual preference command persisted its edit"); + } + + #[test] + fn auto_sign_in_retained_edit_cannot_write_after_an_account_change() { + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("app-auto-sign-in-stale"); + session::save(&account()); + let queue = FullStorageQueue::new(); + let (reply, answer) = mpsc::channel(); + execute(PreferenceCmd::AutoSignIn { on: true, reply }); + let mut replacement = account(); + replacement.account_token = "replacement-account".into(); + session::save(&replacement); + let before = std::fs::read(_session.path()).unwrap(); + drop(queue); + assert_eq!(answer.try_recv(), Ok(false)); + assert_eq!(answer.try_recv(), Err(TryRecvError::Disconnected)); + assert_eq!(std::fs::read(_session.path()).unwrap(), before, "stale work writes nothing"); + assert!(!session::peek().auto_sign_in()); + } + + #[test] + fn browse_preferences_retains_a_full_worker_queue_edit() { + use plx_data::stores::browse::{BrowseCmd, BrowseStore, SecKind}; + use plx_data::stores::StoreJob; + use plx_machine::job::Port; + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("app-browse-preferences-full"); + session::save(&account()); + let mut store = BrowseStore::default(); + store.seed_pins_for_test(&[false]); + assert!(store.run_for_test(BrowseCmd::ApplyPins(vec![(0, true)]))); + let mut jobs = store.take_jobs(); + assert_eq!(jobs.len(), 1); + let StoreJob::BrowsePreferences(job, port) = jobs.remove(0) else { panic!("preference job") }; + let addr = job.addr; + let observer = port.clone(); + let queue = FullStorageQueue::new(); + crate::app::adapters::stores::StoreRunner::live().start(StoreJob::BrowsePreferences(job, port)); + assert!(session::peek().pins_for("").is_none()); + drop(queue); + session::invalidate_for_test(); + let mut persisted = session::load(); + let pins = persisted.pins_for("").expect("the live runner persisted the retained edit"); + assert!(pins.asked); + assert_eq!(pins.on.len(), 1); + assert_eq!(pins.on[0].machine_id, "mach-test"); + assert_eq!(pins.on[0].key, 1); + // A terminal receipt cannot be overwritten by a later addressed refusal. + observer.refused(addr); + observer.done(addr, plx_data::browse::preferences_job::WriteOutcome::Finished(false)); + store.observe_pin_write(); + let mut newer = pins.clone(); + newer.off = std::mem::take(&mut newer.on); + persisted.set_pins_for("", newer); + session::save(&persisted); + store.append_section_for_test(0, 2, "Other", SecKind::Movie); + assert!(!store.pinned_for_test(0), "one successful terminal releases the optimistic pin overlay"); + assert!(store.take_jobs().is_empty(), "no duplicate preference job"); + } + + #[test] + fn browse_preferences_retained_edit_cannot_write_after_an_account_change() { + use plx_data::stores::browse::{BrowseCmd, BrowseStore}; + let _serial = plx_base::testlock::serial(); + let _session = session::TempSession::new("app-browse-preferences-stale"); + session::save(&account()); + let mut store = BrowseStore::default(); + store.seed_pins_for_test(&[false]); + assert!(store.run_for_test(BrowseCmd::ApplyPins(vec![(0, true)]))); + let mut jobs = store.take_jobs(); + assert_eq!(jobs.len(), 1); + let queue = FullStorageQueue::new(); + crate::app::adapters::stores::StoreRunner::live().start(jobs.remove(0)); + let mut replacement = account(); + replacement.account_token = "replacement-account".into(); + session::save(&replacement); + let before = std::fs::read(_session.path()).unwrap(); + drop(queue); + assert_eq!(std::fs::read(_session.path()).unwrap(), before, "stale work writes nothing"); + assert!(session::peek().pins_for("").is_none()); + } +} diff --git a/rust-modules/src/app/recorder.rs b/rust-modules/src/app/recorder.rs index d51ca7be23..1086bede11 100644 --- a/rust-modules/src/app/recorder.rs +++ b/rust-modules/src/app/recorder.rs @@ -693,7 +693,7 @@ impl plx_ui::dispatch::Tap for Recplay { Fx::CancelTimer(_) => "CancelTimer", Fx::Press(_) => "Press", Fx::Remember { .. } => "Remember", Fx::Log(_) => "Log", Fx::App(_) => "App", }; - let payload = match super::bootstrap::effects::encode(&stamped.fx) { + let payload = match super::bootstrap::effects::encode_from(stamped.from, &stamped.fx) { Ok(payload) => payload, Err(reason) => { self.refuse(reason); return; } }; @@ -1452,6 +1452,68 @@ mod tests { effect_at:0,input_at:0,input_diffs:0,effect_diffs:0,started:false,failure:None }) } + #[test] + fn dispatcher_person_provenance_rejects_before_state_or_io_in_live_record_and_replay() { + use super::super::bridge::Bridge; + let _serial = plx_base::testlock::serial(); + let _session = plx_plex::plex::session::TempSession::new("person-dispatch-provenance"); + Bridge::assert_person_provenance_at_dispatch(&mut plx_ui::dispatch::NoTap); + let initial = super::super::bootstrap::Initial::synthetic_home(1, 32517, None).unwrap(); + let mut recording = Recplay::recording_with_sink(&initial, + Box::new(plx_ui::rec::MemSink::default())).unwrap(); + Bridge::assert_person_provenance_at_dispatch(&mut recording); + assert_eq!(recording.failure(), Some("mismatched controlled Person sender or destination")); + let manifest = Header::new(state_fp(), &initial).to_json().to_string(); + for mode in [ReplayMode::Targets, ReplayMode::Resolve] { + let recording = Recording::parse(&manifest, &[], state_fp()).unwrap(); + let mut replay = replay_for_test(recording, mode); + Bridge::assert_person_provenance_at_dispatch(&mut replay); + assert_eq!(replay.failure(), Some("mismatched controlled Person sender or destination")); + } + } + + #[test] + fn person_sender_provenance_is_checked_when_recording_and_in_both_replay_modes() { + use plx_machine::machine::{Delivery, Fx, InstanceId, MachineId, Stamped}; + use plx_screens::registry::AppMsg; + use plx_ui::dispatch::Tap; + use super::super::bridge::AppHost; + let _serial = plx_base::testlock::serial(); + let initial = super::super::bootstrap::Initial::synthetic_home(1, 32517, None).unwrap(); + let sender = MachineId::Instance(InstanceId(3)); + let delivery = |from| Stamped { from, fx: Fx::Deliver( + MachineId::Store(plx_data::stores::StoreId::Person.ord()), + Delivery::Machine(AppMsg::PersonCommand { from: sender, + command: plx_data::stores::person::PersonCmd::Close })) }; + let sink = plx_ui::rec::MemSink::default(); + let segments = sink.segments.clone(); + let manifest = Header::new(state_fp(), &initial).to_json().to_string(); + let mut rec = Recplay::recording_with_sink(&initial, Box::new(sink)).unwrap(); + rec.tick(0, 0.0); + Tap::::effect(&mut rec, 0, &delivery(sender)); + rec.end_frame(&|| 7); + assert!(!rec.finish(plx_machine::landgate::fixture_gate())); + let recording = Recording::parse(&manifest, + &segments.borrow().iter().map(Vec::as_slice).collect::>(), state_fp()).unwrap(); + let mut refused = Recplay::recording_with_sink(&initial, + Box::new(plx_ui::rec::MemSink::default())).unwrap(); + Tap::::effect(&mut refused, 0, &delivery(MachineId::Nav)); + let Recplay::Recording(r) = &refused else { unreachable!() }; + assert_eq!(r.failure, Some("mismatched controlled Person sender or destination")); + for mode in [ReplayMode::Targets, ReplayMode::Resolve] { + for valid in [true, false] { + let mut replay = replay_for_test(copy_recording(&recording), mode); + replay.tick(0, 0.0); + Tap::::effect(&mut replay, 0, + &delivery(if valid { sender } else { MachineId::Nav })); + let Recplay::Replaying(r) = replay else { unreachable!() }; + assert_eq!(r.failure, (!valid).then_some("mismatched controlled Person sender or destination")); + assert_eq!(r.effect_at, usize::from(valid)); + assert_eq!(r.effect_diffs, 0); + } + } + } + #[test] fn controlled_replay_retains_capture_readiness_when_the_gpu_finishes_earlier() { use plx_ui::dispatch::Tap; diff --git a/rust-modules/src/app/search_owned_tests.rs b/rust-modules/src/app/search_owned_tests.rs index 4950cbc3e6..55d294e66a 100644 --- a/rust-modules/src/app/search_owned_tests.rs +++ b/rust-modules/src/app/search_owned_tests.rs @@ -218,7 +218,7 @@ fn owned_search_external_departure_never_submits_the_draft() { session.watching("synthetic-external-leave"); let mut rig = Bridge::for_test(|| 0); rig.search_run(plx_data::stores::search::SearchCmd::SetQuery("unfinished draft".into())); - rig.search = rig.stores.search_snapshot(rig.directory.view(), &Bridge::household_ids()); + rig.search = { let household = rig.views().inputs.session.household_ids(); rig.stores.search_snapshot_for_test(rig.directory.view(), &household) }; let parts = CxParts { tick: tick(0), press: Default::default(), focus: Default::default(), owner: InputOwner::Entry(EntryId(1)) }; let split = rig.split(); @@ -695,7 +695,7 @@ fn owned_search_return_memory_reconstructs_positions_with_a_query_guard() { if changed { rig.search_run(plx_data::stores::search::SearchCmd::SetQuery("replacement".into())); rig.stores.search.publish_shelves_for_test(catalog()); - rig.search = rig.stores.search_snapshot(rig.directory.view(), &Bridge::household_ids()); + rig.search = { let household = rig.views().inputs.session.household_ids(); rig.stores.search_snapshot_for_test(rig.directory.view(), &household) }; } let cx = parts.cx::(rig.views_with(plx_media::route::idle_session_for_test()), &rig.measure); let mut restored = plx_screens::search::SearchScreen::new(key.entry, InstanceId(900)); diff --git a/rust-modules/src/app/search_publication_tests.rs b/rust-modules/src/app/search_publication_tests.rs index 38b4dd34e7..eaa28254b0 100644 --- a/rust-modules/src/app/search_publication_tests.rs +++ b/rust-modules/src/app/search_publication_tests.rs @@ -24,7 +24,7 @@ fn search_publication_is_frozen_for_the_frame_then_notified_once_at_the_next_spl d.emit(MachineId::Nav, Fx::App(AppFx::Store(StoreId::Search, StoreCmd::Search(SearchCmd::SetQuery("after".into()))))); frame(&mut d, &mut rig, AppArg::Search, tick(1), vec![]); - assert_eq!(rig.stores.search_snapshot(rig.directory.view(), &Bridge::household_ids()).view().query(), "after", + assert_eq!({ let household = rig.views().inputs.session.household_ids(); rig.stores.search_snapshot_for_test(rig.directory.view(), &household) }.view().query(), "after", "real store delivery ran"); assert_eq!(rig.search.view().query(), "before", "the frame split precedes the store drain"); assert!(rig.search.same_publication(&retained)); diff --git a/rust-modules/src/app/session_dispatch_tests.rs b/rust-modules/src/app/session_dispatch_tests.rs index 9c21995621..33782fc740 100644 --- a/rust-modules/src/app/session_dispatch_tests.rs +++ b/rust-modules/src/app/session_dispatch_tests.rs @@ -95,7 +95,7 @@ fn production_bridges_do_not_share_browse_state_or_landings() { // the page read it left, started by the runner (which resolves the key and starts the worker). crate::app::adapters::stores::refill_client_keys(&mut first.client_keys); first.stores.browse.borrow().observe_pin_write(); - let input = plx_data::browse::BrowseRosterInput { + let input = plx_data::browse::BrowseRosterInput { tenure: 0, keys: &first.client_keys, session: &plx_plex::plex::session::peek(), visible_generation: plx_plex::plex::session::visible_generation(), settled: plx_plex::plex::session::peek_settled().is_some(), @@ -279,12 +279,14 @@ fn session_cancel_preserves_carried_receipts_until_unique_discard() { let mut init = plx_session::auth::SessionInit::captured(plx_plex::plex::session::Session { client_id: "synthetic-client".into(), ..Default::default() }); + init.phase = plx_session::auth::Phase::Discovering; let key = SessionWorkKey { epoch: 1, op: SessionOp::Login }; init.next_req = 1; init.pending.insert(1, Pending { key, expected: Identity::of(&init.persisted), lifecycle: None, last_arrival: None, phase: StreamPhase::Running, capture: None, admission: AdmissionState::Awaiting(AdmissionId(1)) }); let mut rig = Bridge::for_session_test(init); + assert!(rig.session.work_is_current(1, key, AdmissionId(1)), "rig: the discovering attempt owns this carried work"); rig.session_adapter.launch(RequestId(1), key, true, |job| { job(); true }, |output| { assert!(output.progress(AuthProgress::Registry(RegistryProgress::Install { epoch: 1, expected: None, sources: Vec::new(), primary: None, diff --git a/rust-modules/src/app/watchlist_press_tests.rs b/rust-modules/src/app/watchlist_press_tests.rs index 0b5210e066..f5cae1dea3 100644 --- a/rust-modules/src/app/watchlist_press_tests.rs +++ b/rust-modules/src/app/watchlist_press_tests.rs @@ -125,10 +125,7 @@ impl WatchlistIo for Script { fn facts_gen(&self) -> u32 { self.facts.load(Ordering::SeqCst) } - fn guid_of(&self, server: ServerId, rk: &str) -> Option { - self.record_reads.fetch_add(1, Ordering::SeqCst); - self.records.lock().unwrap().get(&(server, rk.to_owned())).cloned() - } + fn today(&self) -> Option { Some("2026-10-15".into()) } @@ -165,21 +162,17 @@ fn inline(_: &str, f: Box) -> bool { /// A spawn that refuses every job: the store's worker never starts, so its first read stays ON ITS /// WAY (the store retries on its frame counter and is refused again; it never blocks). -fn refuse(_: &str, _: Box) -> bool { - false -} + /// Hold the Watchlist's reads: until [`release_reads`] the list is `Loading`, the answer a real /// plex.tv has not given yet (a scripted one answers inside the call). pub(super) fn hold_reads(rig: &mut Bridge) { - let store = std::mem::take(rig.watchlist_for_test()); - *rig.watchlist_for_test() = store.with_spawn_for_test(refuse); + rig.store_runner.hold_watchlist_streams(true); } /// Let the held read run: the store reads the list again and the next frames land the rows. pub(super) fn release_reads(rig: &mut Bridge) { - let store = std::mem::take(rig.watchlist_for_test()); - *rig.watchlist_for_test() = store.with_spawn_for_test(inline); + rig.store_runner.hold_watchlist_streams(false); rig.watchlist_for_test().run_with_input(plx_data::stores::watchlist::WatchlistCmd::Open, &Bridge::watchlist_input()); } @@ -188,6 +181,7 @@ pub(super) fn rig_over(script: &Arc