Repository navigation
fix(process): serialize lifecycle transitions and harden termination - #6123
Draft
mikefaille wants to merge 27 commits into
Draft
mikefaille wants to merge 27 commits into
mikefaille wants to merge 27 commits into
Conversation
… 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.
Contributor
Author
|
This was referenced Nov 17, 2026
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).
8 of 18 tasks
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.
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



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.proc_tlaunch/cleanup: snapshot app state and claim termination atomically with a lifecycle generation, serializeapp_process_id/app_process_identityreads with the lifecycle mutex, locked getters and POSIX reaper, and gate completeexecute/running/terminatetransitions withproc_transition_mutex(review 5931543184 P2 verbatim).platf::audio_control_t(identity struct, record, snapshot helpers, mutex, conditional clear, hook) with a mechanicalaudio.cppcall-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.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 withtry_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, andfinish_termination()still runs under the transition hold, so the undo/display-revert-before-successor-prep ordering is preserved.process_identity_tet al.) inplatform/common.h, notprocess.h: audio backends and session guards need them but must not include the process manager (rtsp/boost.process) or audio capture;common.his 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
57213112(PR feat(audio): add keep_default_sink routing core without swapping host default #5935 tip,mikefaille/feat/audio-keep-default-sink). This PR must land after feat(audio): add keep_default_sink routing core without swapping host default #5935.mikefaille/feat/audio-lifecycle-hardening(e1a687db), for [process] Lifecycle hardening: serialize launch/cleanup transitions (follow-up to #5935) #6120.feat/windows-process-tree-capturebased on merged B-tipe1a687db, for [windows/audio] Process-tree capture + identity handoff (follow-up to #5935) #6121.feat/audio-capture-target-uifrom57213112, for [web-ui] Audio Capture UI redesign (follow-up to #5935) #6122.masterincludes feat(audio): add keep_default_sink routing core without swapping host default #5935 (stacked base). B-only diff:git diff 57213112..c1b1c98e(7 files, +1865/-128);e1a687dbadds the dedup commit2f69cd0aplus a merge of upstream master (007a08df: portalgrab, deps, FreeBSD CI).git merge origin/masterplus a plain push. B/C/D leave draft only after their base has merged and they have merged it back.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 newProcessTest.*(gated-prep poll, gated-undo poll, cleanup ordering, poller hammer, terminate-during-launch drain, OS-death cleanup), a hardened PID oracle (killliveness +/proccmdline identity + sample count), and an extended provider test (placebo{0,0}branch; Windows exact-match marker assertions added, need a Windows runner to execute).uv run --locked --no-sync lb-update-clang-format: applied one reflow to a new test helper; finalclang-format --dry-run --Werrorclean on all touched files.git diff --check: clean, exit 0.third-party/dockle:npm run build+uv pip install ./third-party/dockle).test_audioscope check: B'stest_audio.cppchanges contain zeroloopback|wasapi|activat|audio_tests|should_capture|providersymbols (count 0), so no C-only wiring leaked into B.e1a687db):2f69cd0areplaces the six hand-rolled gated-launch setups withgated_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 --checkclean.Type of Change
Checklist
AI Usage
See our AI usage policy.