Skip to content

fix(process): serialize lifecycle transitions and harden termination - #6123

Draft
mikefaille wants to merge 27 commits into
SunshineStream:masterfrom
mikefaille:feat/audio-lifecycle-hardening
Draft

mikefaille wants to merge 27 commits into
SunshineStream:masterfrom
mikefaille:feat/audio-lifecycle-hardening

Conversation

@mikefaille

@mikefaille mikefaille commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

Context

Follow-up to #5935 per scope agreement: lifecycle hardening moved out of #5935, which keeps the target branch's lifecycle behavior.

Problem

Rapid relaunches and overlapping close-then-launch sequences race today: cleanup for the old app can terminate the successor, overwrite its preparation, or revert the host display after the new stream started. Status polls can also block behind a transition in flight.

Solution

Serialize lifecycle transitions so each launch and cleanup fully orders against the next, and keep running() polls responsive while a transition is in flight.

  • Harden proc_t launch/cleanup: snapshot app state and claim termination atomically with a lifecycle generation, serialize app_process_id/app_process_identity reads with the lifecycle mutex, locked getters and POSIX reaper, and gate complete execute/running/terminate transitions with proc_transition_mutex (review 5931543184 P2 verbatim).
  • Carry the shared capture-target record in platf::audio_control_t (identity struct, record, snapshot helpers, mutex, conditional clear, hook) with a mechanical audio.cpp call-site update, plus lifecycle and BaseRecord regression coverage including a latch-controlled overlap test and the P2 test-guard correction for the identity-producer test.
  • Make running() polls non-blocking (f345d547, c1b1c98e): classification runs under the lifecycle mutex only, mid-launch reports busy (fail closed), and cleanup takes the transition gate with try_to_lock, leaving the cleanup to the transition owner on contention. The POSIX reaper runs only when the gate is idle and after the root checks, and finish_termination() still runs under the transition hold, so the undo/display-revert-before-successor-prep ordering is preserved.
  • Place the identity types (process_identity_t et al.) in platform/common.h, not process.h: audio backends and session guards need them but must not include the process manager (rtsp/boost.process) or audio capture; common.h is the only header all three layers already include, so it is the dependency-leaf home for the cross-layer handoff.

Screenshot

N/A (no UI changes).

Issues Fixed or Closed

Roadmap Issues

None.

Stack

Testing

B-only gates, observed on Linux (Release, tray OFF, ccache), tip c1b1c98e:

  • cmake -B cmake-build-b -DPython3_EXECUTABLE=$PWD/.venv/bin/python (Release, tray OFF cache): configure done.
  • cmake --build cmake-build-b --target test_sunshine -j16: built.
  • ./cmake-build-b/tests/test_sunshine (full): 1146 ran, 1137 passed, 9 skipped (CUDA/tray/HID/nvenc environmental), 0 failed, exit 0. Includes 6 new ProcessTest.* (gated-prep poll, gated-undo poll, cleanup ordering, poller hammer, terminate-during-launch drain, OS-death cleanup), a hardened PID oracle (kill liveness + /proc cmdline identity + sample count), and an extended provider test (placebo {0,0} branch; Windows exact-match marker assertions added, need a Windows runner to execute).
  • Mutation check: the 3 gated promptness tests fail on pre-fix production code (each hits the 2s poll deadline) and pass with the fix.
  • uv run --locked --no-sync lb-update-clang-format: applied one reflow to a new test helper; final clang-format --dry-run --Werror clean on all touched files.
  • git diff --check: clean, exit 0.
  • docs target: exit 0, 1115 HTML pages (after provisioning third-party/dockle: npm run build + uv pip install ./third-party/dockle).
  • test_audio scope check: B's test_audio.cpp changes contain zero loopback|wasapi|activat|audio_tests|should_capture|provider symbols (count 0), so no C-only wiring leaked into B.
  • Dedup follow-up (tip e1a687db): 2f69cd0a replaces the six hand-rolled gated-launch setups with gated_launch_t (one config list per test, zero templates) and derives the hook audio fake from the recording fake. Rebuilt + full suite: 1149 ran, 1140 passed, 9 skipped (same environmental set), 0 failed, exit 0. Format + git diff --check clean.
  • Not run here: Windows execution, full integration/platform validation.

Type of Change

  • feat: New feature (non-breaking change which adds functionality)
  • fix: Bug fix (non-breaking change which fixes an issue)
  • docs: Documentation only changes
  • style: Changes that do not affect the meaning of the code (white-space, formatting, missing semicolons, etc.)
  • refactor: Code change that neither fixes a bug nor adds a feature
  • perf: Code change that improves performance
  • test: Adding missing tests or correcting existing tests
  • build: Changes that affect the build system or external dependencies
  • ci: Changes to CI configuration files and scripts
  • chore: Other changes that don't modify src or test files
  • revert: Reverts a previous commit
  • BREAKING CHANGE: Introduces a breaking change (can be combined with any type above)

Checklist

  • Code follows the style guidelines of this project
  • Code has been self-reviewed
  • Code has been commented, particularly in hard-to-understand areas
  • Code docstring/documentation-blocks for new or existing methods/components have been added or updated
  • Tests have been added or updated for new or modified functionality, including regression tests for bug fixes

AI Usage

See our AI usage policy.

  • AI tools were used while preparing this PR

This pull request was generated by Muse Code powered by Meta Muse Spark

… host default

Adds the keep_default_sink config key controlling whether audio capture swaps the host default sink.

- Config: new keep_default_sink key (default disabled) with validation.
- Policy: when enabled, capture keeps the host default sink untouched; teardown restores only state this session changed.
- UI: AudioVideo tab toggle plus locale strings.
- Docs: configuration.md documents the new key.
- Tests: config, audio, and linux audio unit coverage.
Rename shadowed module field (S1669), extract adopt_sink/ensure_sink
helpers from the duplicated sink setup blocks (S3776), shrink the
oversized enumeration lambda (S1188), and guard destructor teardown
against throwing unloads (S1048). Behavior unchanged.
Give the destructor's catch-all a log statement so the intentionally
suppressed unload path is not an empty handler (S2486). Teardown
stays non-throwing.
Route the capture-only path at the configured sink, or the saved host sink
when nothing is configured, instead of the virtual sink. Without a swap,
applications stay on the host default, so capturing the virtual sink's
monitor yields silence when host playback is muted.

Extract the startup selection plus swap-vs-capture policy into the pure
resolve_capture_routing() helper so the empty/configured sink by HOST_AUDIO
matrix is covered by unit tests, and pin the historical virtual-sink
selection on the swap path.
Include the new shared checkbox in the Windows control-list assertion and
add round-trip coverage rendering it on Windows, Linux, and macOS.
Share the keep-default routing contract across backends. Windows records
the capture target for direct WASAPI capture and guards the default
reassertion callback, the startup default-device reset, and the Steam
driver install behind hands-off-mode predicates, composing with the
existing external_audio behavior. macOS reports support natively since
tap/input capture never touches the default output. Document the
per-platform behavior.
Satisfies Sonar cpp:S3562 on the new code. Behavior unchanged: layouts
other than stereo/5.1/7.1 keep the previously selected sink.
Extract the duplicated mountAudioVideo helper into audioVideoMount.js so
the keep_default_sink suite and the external_audio suite use one copy.
Clears the Sonar new-code duplication gate.
…ap-owned activation blob

Unify keep-default capture under one shared key with a thread-safe
session guard, a microphone params bundle, and WASAPI process loopback
using a heap-owned activation blob plus PID revalidation.
Behavior-preserving modernization of the audio capture path: string_view for read-only string parameters, using-enum with exhaustive switches, constexpr/noexcept/nodiscard on pure predicates and intent helpers, const-correct virtual-sink helpers, explicit wstring materialization at the UTF-8 boundary, a params-bundle using-declaration for the Linux backend, and documented no-op capture-target defaults. No behavior change.
Production: extract the find_device_id endpoint probe, rename shadowed error locals, std::format for sink names, dropped redundant lambda return types, CTAD atomics, using-enum in the concurrency seam, and the macOS params-bundle using-declaration. Tests: noexcept guard destructor with deleted copies, three params-bundle using-declarations, string_view call_index, std::array mapping. Behavior-preserving throughout.
…et clear

Hoist the identical keep-default capture_sink bodies into a protected base helper so both backends record through one path, and reset Windows creation-time identity via an on_capture_target_cleared() hook fired under the same lock hold as the shared record reset.
…ne()

The d3dc65f surgery dropped the process-loopback if-block but kept its
closing brace after 'auto mic', which would close microphone() early and
break the Windows build (unseen on Linux where this TU is excluded).
Harden proc_t launch/cleanup: snapshot app state and claim termination
atomically with a lifecycle generation, serialize app_process_id/identity
reads with the lifecycle mutex, lock getters and reaper, and gate complete
execute/running/terminate transitions with proc_transition_mutex so an
overlapping web close/stream cleanup cannot run the old snapshot's undo or
display revert after the successor's preparation.

Carry the shared capture-target record (identity struct, record, snapshot
helpers, mutex, conditional clear, hook) in platf::audio_control_t with a
mechanical audio.cpp call-site update, plus lifecycle and BaseRecord
regression coverage including a latch-controlled overlap test and the P2
test-guard correction for the identity-producer test.
@mikefaille

Copy link
Copy Markdown
Contributor Author

This pull request was generated by Muse Code powered by Meta Muse Spark

Pollers (stream loop, nvhttp launch/resume/cancel/serverinfo) no longer
block on the transition gate: running() classifies state under the
lifecycle mutex only, reports mid-launch as busy (fail closed), and
takes the transition gate with try_to_lock only when an exited app
needs cleanup. On contention the last-known app id is reported and the
transition owner performs the cleanup.

The POSIX blanket reaper runs only when the gate is idle and after the
root checks, so it can neither steal prep/undo wait statuses nor lose
the root exit code (Boost keeps still_active after an external reap,
which would break auto_detach detection).

finish_termination() still runs under the transition hold, preserving
the undo/display-revert-before-successor-prep ordering.

Also corrects the lifecycle/audio lock-order docs (the two mutexes are
never nested in either direction), documents the identity-type home in
platf/common.h, and rewords the POSIX zero-marker comment as a
fail-closed contract instead of a backend prediction.
Adds gated overlap tests proving running() answers promptly during
execute()/terminate()/owned-cleanup (each fails on the blocking
implementation), a poller hammer across natural exit and racing
terminate, a terminate-during-launch drain test, and an OS-death
cleanup test with successor relaunch.

Hardens the PID oracle (kill liveness + /proc cmdline identity +
sample count) and the provider test (Windows exact-match marker vs an
independent OS query, placebo {0,0} branch).
The six gated lifecycle tests each hand-rolled the same $\sim0-line setup
(scratch dir, marker scripts, app contexts, process manager, guards), which
SonarCloud flags as 148 duplicated lines on PR SunshineStream#6123.

Replace the six setups with gated_launch_t: one config list per test selects
markers, gating, and commands, while the fixture owns the directory, scripts,
apps, target, background-launch thread, deadline poll, and gate release. The
Overlapping test additionally drops its bespoke tmp dir, script writer, and
read/wait loops in favor of the existing gate helpers. Test bodies keep only
their orchestration and assertions; all markers and gate behavior are unchanged.

The hook audio control fake now derives from the recording fake instead of
duplicating its 50 lines, keeping its two intentional differences documented.
@sonarqubecloud

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[process] Lifecycle hardening: serialize launch/cleanup transitions (follow-up to #5935)

1 participant