fix(media): settle cancelled watches and connection handoffs

This commit is contained in:
AAA committed 2026-11-29 21:20:49 -05:00
1 parent 6fff8ee516
commit ee3ea0c6ff
7 files changed
+136 -32

No files matched your search

+18 -3
View File
@@ -1,6 +1,6 @@
# Codex → Claude
Reviewed queue: `535e8ac0`. Current changes through `82bdf76f` are pushed;
Reviewed queue: `93797639`. Current changes through `6fff8ee5` are pushed;
private beta.76 stays frozen at `6ef82fc5`. Maintenance #560 is still held.
## Outcomes
@@ -13,8 +13,9 @@ private beta.76 stays frozen at `6ef82fc5`. Maintenance #560 is still held.
Recovered pairs remain excluded from extra-child trials while the same routable
sessions remain; ordinary routing still considers them. The reported eighty
mixed scripts are your evidence, separate from our source-only comparison.
- **`992b0d1d`: keep study-only.** The completed kernel/media control below
- **`992b0d1d`: withdrawal agreed.** The completed kernel/media control below
does not establish a connectivity or playback benefit over ordinary ICE.
Keep the cited branch as research evidence, not an active delivery candidate.
- **Shared diagnostic ring: fixed in `0e61a591`.** Live video samples have their
own bounded typed FIFO. The existing event ring keeps the rare transitions.
The capture-enabled check and diagnostic/admission tests passed.
@@ -31,7 +32,21 @@ The Native queue audit corrected terminal input replies and unclaimed DCEP
streams. Reply consumption makes the source publish its current revoked state;
a failed channel handoff closes that stream so the creator can reopen it.
Actual input-routing and str0m regressions preserve sibling room data and video.
The remaining Connected/PreparedPath notification review is in progress.
Connection transitions now retire only their transport if the driver cannot
receive the required state. PreparedPath updates its reported value only after
successful enqueue; a later SDK observation can repeat a missed update. The
SDK's disconnect contract prevents pending outputs from reviving that transport.
Five focused Native regressions pass, including ordinary recovery, original-pair
prepared handoff, lost input release and diagnostic stage separation.
The ScreenWatch review found an ordinary cancellation gap: after subscribe(true)
was sent, dismissing a waiting successor hit operation_pending and could still
start viewing. One existing watch controller now spans lookup and subscription.
Unwatch records the departure before cancellation, waits for old work to settle,
then sends one withdrawal. Late confirmation/state cannot restore it. The
first-publication App preview exception uses the previous raw snapshot. Both
TypeScript projects and all 770 Session tests pass. A thin map wrapper was
declined; no new ScreenWatches class was needed for this correction.
The 2.x counterpart has no equivalent reply queue. It did ignore a failed Pion
SendText below its backlog limit. `998e9f50` closes only that input leg. A real
+1 -1
View File
@@ -306,7 +306,7 @@ Two partially observed sequential peers remained unreachable. If the retained
endpoint's mapping varies toward the peer, the bounded search can exhaust its
targets. Ordinary ICE keeps its independently gathered candidates.
The multi-exit draft (992b0d1d) remains a study. A kernel NAT control used
The multi-exit draft (992b0d1d) was not adopted. A kernel NAT control used
destination-selected, port-preserving exits and endpoint-dependent filtering.
The stable endpoint completed authenticated preparation. An unknown exit
returned Unavailable after about five seconds. In the matched media runs,
+4 -1
View File
@@ -104,6 +104,7 @@ pub(crate) enum TransportFailure {
SendSourceUnavailable,
RtcOutputFailed,
DeadlineWaitFailed,
ConnectionEventUnavailable,
}
#[derive(Clone, Copy, Default, Serialize)]
pub(crate) struct PreparationChecks {
@@ -876,6 +877,7 @@ mod tests {
TransportFailure::SendSourceUnavailable,
TransportFailure::RtcOutputFailed,
TransportFailure::DeadlineWaitFailed,
TransportFailure::ConnectionEventUnavailable,
] {
recorder.rtc_pair(first, RtcPairEvent::TransportFailed { reason });
}
@@ -920,7 +922,7 @@ mod tests {
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
assert_eq!(events.len(), 14);
assert_eq!(events.len(), 15);
assert!(events
.iter()
.all(|event| event["level"] == "INFO" && event["target"] == "piik.rtc"));
@@ -964,6 +966,7 @@ mod tests {
"send_source_unavailable",
"rtc_output_failed",
"deadline_wait_failed",
"connection_event_unavailable",
]) {
assert_eq!(
*record,
@@ -2019,6 +2019,41 @@ async fn initial_candidate_overflow_retires_only_its_pair() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn saturated_connection_transition_retires_only_its_pair() -> Result<()> {
use crate::peer::tests::support::{vp8, Fixture};
use crate::peer::NativeEvent;
use piik_channel_core::wire::{Command as WireCommand, LinkState};
let mut f = Fixture::new(vp8()).await?;
let result = async {
f.until(|f| f.driver.pairs.values().all(|pair| pair.connected() && pair.data.control_open())).await?;
let pair = f.parents[0].pair;
let sibling = f.sink;
f.driver.pairs[&pair].pc.call(|engine| {
engine.event(RtcEvent::IceConnectionStateChange(str0m::IceConnectionState::Disconnected));
Ok(())
}).await?;
f.until(|f| f.reported.iter().any(|command| matches!(command,
WireCommand::LinkState { pair_id, state: LinkState::Disconnected } if *pair_id == pair))).await?;
while f.driver.events.try_send(Event::Negotiate(pair)).is_ok() {}
ensure!(f.events.len() == 1024);
f.driver.pairs[&pair].pc.call(|engine| {
engine.event(RtcEvent::Connected);
Ok(())
}).await?;
while f.events.try_recv().is_ok() {}
f.driver.deadlines().await;
ensure!(!f.driver.pairs.contains_key(&pair));
ensure!(f.driver.pairs[&sibling].connected() && f.driver.pairs[&sibling].data.control_open());
ensure!(std::iter::from_fn(|| f.commands.try_recv().ok()).any(|event|
matches!(event, NativeEvent::Command(WireCommand::LinkState { pair_id, state: LinkState::Failed }) if pair_id == pair)));
Ok(())
}.await;
f.close().await;
result
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn live_ice_adopts_prepared_path_on_original_pair() -> Result<()> {
use crate::peer::{preparation::loopback_winners, tests::{driver, support::exchange}, ChannelEvent, Deadline};
@@ -2124,6 +2159,23 @@ async fn live_ice_adopts_prepared_path_on_original_pair() -> Result<()> {
anyhow::bail!("missing selected prepared path")
}).await??;
selected(&b,lb,la).await?;
// Suppress one deselection notification, then repeat the same SDK observation.
let alternate = a.call(move |engine| {
let mut stats = engine.peer_stats.clone().context("selected pair stats")?;
stats.selected_candidate_pair = None;
let EventTarget::Peer(events) = &engine.events else { unreachable!() };
while events.try_send(Event::Negotiate(id)).is_ok() {}
engine.event(RtcEvent::PeerStats(stats.clone()));
ensure!(!engine.overflow.load(Ordering::Acquire));
Ok(stats)
}).await?;
while local_events.try_recv().is_ok() {}
a.call(move |engine| {
engine.event(RtcEvent::PeerStats(alternate));
Ok(())
}).await?;
ensure!(std::iter::from_fn(|| local_events.try_recv().ok()).any(|event|
matches!(event, Event::PreparedPath(pair, instance, false) if pair == id && instance == a.instance)));
}
ensure!(identities == (identity(&a).await?, identity(&b).await?));
for (handle, expected) in [(&a,identities.1.5.clone()),(&b,identities.0.5.clone())] {
+21 -14
View File
@@ -208,7 +208,8 @@ impl EventTarget {
match self {
EventTarget::Peer(events) => {
if let Err(error) = events.try_send(event) {
if !matches!(error.into_inner(), Event::Track(..)) {
if !matches!(error.into_inner(), Event::Track(..) | Event::PreparedPath(..)
| Event::State(_, PeerState::Connected | PeerState::Disconnected)) {
overflow.store(true, Ordering::Release);
}
return false;
@@ -454,6 +455,7 @@ pub(crate) struct Engine {
source_error: Option<SocketAddr>,
stats_origin: Instant,
prepared_path: Option<(SocketAddr, SocketAddr)>,
prepared_selected_reported: bool,
peer_stats: Option<PeerStats>,
ingress_stats: HashMap<(Mid, Option<Rid>), MediaIngressStats>,
egress_stats: HashMap<(Mid, Option<Rid>), MediaEgressStats>,
@@ -1061,6 +1063,7 @@ impl Runtime {
source_error: None,
stats_origin,
prepared_path: None,
prepared_selected_reported: false,
peer_stats: None,
ingress_stats: HashMap::new(),
egress_stats: HashMap::new(),
@@ -2071,6 +2074,15 @@ impl Engine {
}
}
fn report_connection(&mut self, state: PeerState) {
if self.state.swap(state as u8, Ordering::AcqRel) == state as u8 {
return;
}
if !self.emit(Event::State(self.handle.pair, state)) {
self.fail(TransportFailure::ConnectionEventUnavailable);
}
}
fn fail(&mut self, reason: TransportFailure) {
self.nat64.take();
if matches!(self.state.load(Ordering::Acquire), state if state == PeerState::Failed as u8 || state == PeerState::Closed as u8)
@@ -2274,22 +2286,16 @@ impl Engine {
if !self.rtc.has_send_consent() {
self.fail(TransportFailure::SendConsentUnavailable);
} else if PeerState::established(self.state.load(Ordering::Acquire)) {
self.state
.store(PeerState::Disconnected as u8, Ordering::Release);
self.emit(Event::State(self.handle.pair, PeerState::Disconnected));
self.report_connection(PeerState::Disconnected);
}
} else if state.is_connected() && self.rtc.is_connected() {
self.state
.store(PeerState::Connected as u8, Ordering::Release);
self.emit(Event::State(self.handle.pair, PeerState::Connected));
self.report_connection(PeerState::Connected);
}
}
RtcEvent::Connected => {
self.trace_pair(RtcPairEvent::TransportConnected);
self.nat64.take();
self.state
.store(PeerState::Connected as u8, Ordering::Release);
self.emit(Event::State(self.handle.pair, PeerState::Connected));
self.report_connection(PeerState::Connected);
}
RtcEvent::Closed => {
self.trace_pair(RtcPairEvent::TransportClosed);
@@ -2395,10 +2401,11 @@ impl Engine {
}
}
if let Some((local, remote)) = self.prepared_path {
let matches = |stats: &PeerStats| path(stats) == Some((Protocol::Udp, local, remote));
let current = matches(&stats);
if self.peer_stats.as_ref().is_some_and(matches) != current {
self.emit(Event::PreparedPath(self.handle.pair, self.handle.instance, current));
let current = selected == Some((Protocol::Udp, local, remote));
if self.prepared_selected_reported != current
&& self.emit(Event::PreparedPath(self.handle.pair, self.handle.instance, current))
{
self.prepared_selected_reported = current;
}
}
self.peer_stats = Some(stats.clone());
+12 -13
View File
@@ -79,7 +79,7 @@ interface ScreenWatch {
playbackError?: ScreenPlaybackError;
helperSessionId?: string;
retry?: { controller: AbortController; available: () => boolean };
query?: AbortController;
controller: AbortController;
operation?: Promise<void>;
}
@@ -786,7 +786,8 @@ export class ChannelSession {
}
for (const [id, watch] of this.watching) {
const publication = state.publications.find(value => value.id === id);
if (!publication && (watch.query || !this.pendingActions.has(`watch:${id}`))) this.retireWatch(id);
// An App preview can subscribe before its first publication snapshot.
if (!publication && (previous?.publications.some(value => value.id === id) || !this.pendingActions.has(`watch:${id}`))) this.retireWatch(id);
if (watch.playbackError !== undefined) {
const before = previous?.publications.find(value => value.id === id);
const room = state.channel.rooms.find(value => value.id === publication?.roomId);
@@ -2341,9 +2342,10 @@ export class ChannelSession {
};
revokeRoomAccess = (roomId: string, userId: string): Promise<void> => this.action(`revoke:${roomId}:${userId}`, () => this.request({ type: "revoke_room_access", roomId, userId }), false);
watch = (publicationId: string, roomId?: string, signal?: AbortSignal, reportError: ReportError = true): Promise<void> => {
const watch: ScreenWatch = {};
const watch: ScreenWatch = { controller: new AbortController() };
const operation = this.action(`watch:${publicationId}`, async () => {
if (signal?.aborted) throw new DOMException("Capture cancelled", "AbortError");
const lifetime = AbortSignal.any([watch.controller.signal, this.captureLifetime.signal, ...(signal ? [signal] : [])]);
lifetime.throwIfAborted();
this.watching.get(publicationId)?.retry?.controller.abort();
this.watching.set(publicationId, watch);
this.unleave(publicationId);
@@ -2354,17 +2356,14 @@ export class ChannelSession {
// Source location is independent of Native admission. Only assistance
// waits for hosting readiness after the ordinary subscription.
if (app?.connected && !remote && !this.view.localScreens.has(publicationId)) {
watch.query = new AbortController();
const lifetime = AbortSignal.any([watch.query.signal, this.captureLifetime.signal, ...(signal ? [signal] : [])]);
const endpoint = await app.localEndpoint(lifetime).catch(error => {
if (this.app === app && app.connected) throw error;
});
watch.query = undefined;
lifetime.throwIfAborted();
if (endpoint) this.rememberLocalEndpoint(app, endpoint);
if (this.watching.get(publicationId) !== watch) throw new DOMException("Capture cancelled", "AbortError");
}
await this.request({ type: "subscribe", publicationId, enabled: true }, undefined, roomId);
await this.request({ type: "subscribe", publicationId, enabled: true }, undefined, roomId, { signal: lifetime });
if (signal?.aborted || this.watching.get(publicationId) !== watch) throw new DOMException("Capture cancelled", "AbortError");
} catch (error) {
if (this.watching.get(publicationId) !== watch) throw new DOMException("Capture cancelled", "AbortError");
@@ -2382,19 +2381,19 @@ export class ChannelSession {
this.input.close(publicationId);
const watch = this.watching.get(publicationId);
watch?.retry?.controller.abort();
watch?.query?.abort();
watch?.controller.abort();
this.watching.delete(publicationId);
}
unwatch = async (publicationId: string): Promise<void> => {
const watch = this.watching.get(publicationId);
if (watch?.query) {
const roomId = this.view.state?.publications.find(value => value.id === publicationId)?.roomId;
if (roomId) this.leave(publicationId, roomId);
if (watch?.operation) {
this.retireWatch(publicationId);
await watch.operation?.catch(() => {});
await watch.operation.catch(() => {});
}
return this.action(`watch:${publicationId}`, async () => {
this.retireWatch(publicationId);
const roomId = this.view.state?.publications.find(value => value.id === publicationId)?.roomId;
if (roomId) this.leave(publicationId, roomId);
this.refreshActivity();
if (this.view.connection === "connected") await this.request({ type: "subscribe", publicationId, enabled: false });
}, false);
+28
View File
@@ -13751,6 +13751,34 @@ test("viewers join the exact confirmed screen and watch successor through normal
reply("join_watch");
} finally { session.close(); }
});
test("dismissing a screen successor withdraws its pending Browser subscription before a late confirmation", async () => {
const { session, socket } = await setup(1000, false);
const base = session.getSnapshot().state!;
const screen = { id: "old", userId: "other", sessionId: "source", roomId: "first", kind: "screen", paused: false,
audience: [], source: { kind: "screen", name: "Display" }, title: null };
const next = { ...screen, id: "next", predecessor: { kind: "screen", id: screen.id } };
const reply = (command: Record<string, unknown>) => socket.receive({ type: "reply", roomId: "first", requestId: command.requestId, result: { type: "done" } });
try {
socket.receive({ type: "state", state: { ...base, publications: [screen] } });
const watching = session.watch(screen.id);
reply(socket.sent.at(-1)!); await watching;
socket.receive({ type: "state", state: { ...base, publications: [screen], subscriptions: [screen.id] } });
socket.receive({ type: "state", state: { ...base, publications: [next] } });
const commands = () => socket.sent.filter(c => c.type === "subscribe" && c.publicationId === next.id);
const [enable] = commands();
expect(enable).toMatchObject({ enabled: true });
const dismissed = session.unwatch(next.id).catch(error => error);
await vi.waitFor(() => expect(commands().map(c => c.enabled)).toEqual([true, false]));
reply(commands()[1]); expect(await dismissed).toBeUndefined();
reply(enable);
socket.receive({ type: "state", state: { ...base, publications: [next], subscriptions: [next.id] } });
expect(session.getSnapshot().state?.subscriptions).not.toContain(next.id);
expect(session.getSnapshot().error).toBeNull();
expect(commands().map(c => c.enabled)).toEqual([true, false]);
} finally { session.close(); }
});
function confirmWatchJoinOrLeave(socket: ChannelSocket) {
const command = socket.sent.findLast(c => c.type === "join_watch")!;
socket.receive({ type: "reply", roomId: command.roomId, requestId: command.requestId,