Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
fix(media): make peer quality reselection make-before-break (#173)
AAA532852d5872b
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.mdindex 21dbf440..e9c9a249 100644--- a/docs/adr/0005-automatic-hybrid-media-routing.md+++ b/docs/adr/0005-automatic-hybrid-media-routing.md@@ -347,14 +347,16 @@ windows. One confirmed child remains edge-local. Two distinct confirmedchildren under the same Viewer parent session and share generation within fiveseconds temporarily make that parent relay-ineligible (effective capacity zero)for 30 seconds; its advertised capacity is unchanged. The triggering edge still-follows its own intent: relative FPS is peer-only, while severe evidence retains-the ordinary peer, SFU, selected-edge TURN, then bounded-failure ladder.+follows its own intent through one peer-to-peer make-before-break attempt.+Severe and relative-FPS quality evidence do not enter SFU or TURN; a real+`route-failed` remains the separate owner of the ordinary failure ladder.The authenticated standby is not a transport: it has no grant and never joins aroom. During route prepare the current implementation warms only an unpublishing/unsubscribedtransport. Its media transition remains break-before-make: the host releases the-replaced peer or SFU media edge before activating the new one, and a viewer-retires its SFU subscriber before returning to peer media.+replaced peer or SFU media edge before activating the new one. The accepted+one-root healthy SFU probe and the peer-quality slice below are explicit bounded+exceptions: they retain old media until current-generation receive/decode proof.## Standby Prewarm Result@@ -410,24 +412,31 @@ alone is diagnostic-only. C may be stored before B arrives, but only oneunchanged severe or relative pair advances its own streak. Healthy or ambiguouscorrelated windows clear it. A Viewer or parent session,connection ID, route revision or parent identity change also resets it, as does-an evidence gap over five seconds. Severe evidence retains the existing bounded-peer/SFU/TURN ladder. Relative-FPS evidence tries only another peer; if none is-eligible, the old active edge stays and no route, SFU, TURN, or room cooldown is-created. A successful peer reassignment or started severe SFU prepare creates+an evidence gap over five seconds. Severe and relative-FPS evidence each open at+most one peer-to-peer make-before-break attempt. Its v1 parent is an ordinary+Viewer whose active upstream is peer; Host and SFU-root provisional children+remain later work, and their exclusion does not stop enumeration. The old active edge and its+connection ID remain authoritative while the candidate uses a separate exact+identity. The Viewer sends prepare-ready only after positive current-candidate+RTP and decoded-frame progress plus a live video track; only then does the server+commit the planned topology and promote the candidate connection ID. A failure+after prepare-ready retains that exact identity until matching active authority+is failed or rollback clears it. An unrelated authoritative route failure first+aborts the soft probe and then immediately resumes its ordinary ladder. Failure,+timeout, stale identity, or no eligible peer keeps the old active edge and does+not start SFU, TURN, an error, or another migration. A started attempt createsone 30-second room migration budget. Viewer/session churncannot bypass that budget; removal, disconnect, authorization or generationchange clears per-edge evidence and intent state, while room stop/delete clearsthe room budget. A quality-created intent retains its Viewer/parent sessions,-connection, revision and parent guard through every drain, peer change, SFU-prepare and commit boundary. Pending SFU work also retains the exact originating-intent identity: missing, replaced or changed guards abort before grants or-commit, while a genuine `route-failed` may explicitly take over that same-intent as the ordinary failure owner. A successful relative-FPS move holds its+connection, revision and parent guard through prepare and commit. A successful+relative-FPS move holds itsold parent for 30 seconds, or until that parent session changes, to avoid a softbounce. A real `route-failed` is stronger evidence: it releases that soft hold,hard-excludes the current failed parent and may immediately reuse the oldplayable parent. Other successful quality moves release their temporary-exclusion. The W3C stats+exclusion. This slice migrates only the triggering child; make-before-break for+other children of a quarantined relay remains separate. The W3C statsdefinitions establish the counter meanings and their WebRTC 1.0 example uses30% loss as a likely culprit; they do notprescribe Screener's route policy. Therefore 50%, two-thirds FPS, 100 packets,diff --git a/docs/project-memory.md b/docs/project-memory.mdindex 65a609a0..c2aae4e0 100644--- a/docs/project-memory.md+++ b/docs/project-memory.md@@ -28,7 +28,7 @@ Last updated: 2026-08-22- Mobile endpoints are Web Viewer-only. Current Android/iOS browsers do not expose Web Host capture; AirPlay/system mirroring is Viewer-local output.- ADR-0005: direct/peer UDP -> bounded SFU roots -> selected-edge TURN. The deployed controller caps pending/answered `peer-selected` at one per room; Host ingress is independent. A pre-`ecc794d` exact-source/production-media canary proves active Host ingress only. Ordinary peers stay STUN-only.- `PEER_ASSISTED_MEDIA=true` covers all rooms. One-root healthy-SFU MBB is deployed with retained parent, media proof, Host2/browser1 overlap, cooldown and fresh two-window proof; it excludes `peer-selected`. Active-SFU loss uses normal recovery; the manual control keeps its route: peer restarts its edge, SFU reauthenticates signaling and rebuilds that subscriber. Capacity `0 -> 1`, multi-root/browser gates remain open.-- C+B stays edge-local: severe keeps its fallback ladder; relative relay FPS uses fresh parent evidence and peers only. Two confirmed children under one Viewer relay/session/share within 5s pause its eligibility for 30s and peer-only evacuate its children; no score.+- C+B stays edge-local: severe and relative relay-FPS evidence give only the triggering child one ordinary peer-upstream Viewer MBB attempt while its old edge remains active; v1 excludes Host/SFU roots. Current-generation RTP, decoded frames, and live video atomically promote the candidate; a ready-then-failed identity survives until active/rollback, and an unrelated authoritative failure preempts the soft probe. Failure, timeout, or no candidate keeps the old edge without SFU/TURN. Sibling MBB remains separate. No score.- Flagship media is UDP; HTTPS/WSS stays TLS/TCP; the old release remains rollback-only.- Treat settings as ceilings and degradation as unclassified. Use correlated Host A+B/Viewer C and one-variable evidence; never force AV1, infer by UA, or create a composite score.- Screen audio: production Web capture requests speech processing off and ideal stereo. Share advanced settings offer 64/128/256 kbps sender ceilings, default 128, and lock the choice for the active share across P2P, browser relay, and SFU. Peer answers permit stereo up to 256 kbps; SFU keeps `forceStereo`, DTX off, and RED retained. Local Viewer details expose non-uploaded A/V playout, jitter-buffer, and concealment evidence. Target-browser/route proof remains open; voice and Native stay separate.diff --git a/docs/research/advanced-peer-distribution.md b/docs/research/advanced-peer-distribution.mdindex 43eeacb5..6a4f7806 100644--- a/docs/research/advanced-peer-distribution.md+++ b/docs/research/advanced-peer-distribution.md@@ -214,22 +214,26 @@ limitation or at least 100 sent packets with remote loss divided by sent packetsat least 30%. Three consecutive windows of the same severe or relative kind arerequired. A healthy or incomplete correlated window, any Viewer/parent session,connection, route revision or parent change, or a gap over five seconds clears-the streak. Severe evidence retains the existing fallback ladder. Relative FPS-tries another peer only; no candidate keeps the old edge without SFU, TURN, an-error, or room cooldown. A successful peer move or started severe SFU prepare-spends a 30-second room migration+the streak. Severe and relative-FPS quality evidence each tries one ordinary+peer-upstream Viewer through make-before-break; v1 skips Host and SFU roots but+continues to later eligible Viewers. No candidate, probe failure, or timeout keeps+the old edge without SFU, TURN, or an error. A started attempt spends a+30-second room migrationbudget, so a new public Viewer identity cannot bypass it. Per-edge state clearson authentication/generation change, disconnect/removal and route replacement;room stop/delete also clears the cooldown.-An SFU preparation created by severe quality retains the exact originating intent and-its full Viewer/parent session, connection and revision guard until grants and-commit finish. Missing, replaced or changed intent state aborts and releases-only its quality-owned parent exclusion. A real `route-failed` can take over-that same intent without losing its exclusion. A successful relative move holds-the old parent for 30 seconds or until its session changes. A real active-route-failure overrides that soft hold, hard-excludes the current failed parent, and-allows the old playable peer to take over immediately.+The candidate is bound to the exact Viewer/parent sessions, active and pending+route revisions, share lifecycle and a separate connection ID. Signaling keeps+the old connection ID authoritative until the Viewer proves positive RTP,+positive decoded-frame progress and a live video track on the candidate; commit+then changes topology, route and active connection identity together. Failure+after ready retains the exact provisional identity until matching active or+rollback, while another edge's authoritative failure aborts the soft probe+before using the ordinary ladder. A+successful relative move holds the old parent for 30 seconds or until its+session changes. A real active-route failure remains a separate hard recovery+trigger and can reuse an otherwise playable old parent.W3C defines outbound `packetsSent` as the local cumulative RTP packet count.`remote-inbound-rtp.packetsLost` is remote receiver data delivered by RTCP and@@ -260,7 +264,9 @@ try deterministic peer reassignment and keep their old edge when none exists;the parent keeps its upstream and the pause itself never starts SFU or TURN.Host parents are excluded, while expiry, a new parent session or a new sharerestores eligibility. Alternate-parent selection remains breadth-first;-preferring recent healthy candidates remains a later make-before-break slice.+preferring recent healthy candidates remains later. The triggering child now+uses bounded make-before-break; converting the quarantined parent's remaining+children from their existing immediate reassignment is a separate slice.With host and current browser-relay degree two, deterministic breadth-firstassignment keeps eight viewers to depth three. A tree for `N` viewers@@ -327,10 +333,10 @@ avoid reversal during cooldown, and restore the prior deterministic route onrollback. Reject this candidate if it needs all-pairs probing, a continuousoptimizer, temporary fanout above budget, self-reported geography or devicequality, or cannot beat the unchanged route. The earlier admission-rescue case-remains valid, while this quality slice moves only the affected Viewer-rooted-subtree and excludes only its current failed parent through the existing-peer-first, then SFU path. The configured selected-edge TURN attempt follows SFU-failure; healthy paths never enter relay optimization.+remains valid. The implemented quality slice moves only the affected+Viewer-rooted subtree, keeps its old edge until the candidate decodes, and does+not enter SFU or selected-edge TURN. Those transports remain available only to+the separate real-failure route owner.## Staged Connection Recovery Evidencediff --git a/docs/status.md b/docs/status.mdindex 09cd612c..e1ddd05a 100644--- a/docs/status.md+++ b/docs/status.md@@ -18,7 +18,7 @@ This file is the current execution index. Load [verification status](./verificat- The source candidate adds click-only, versioned JSON export beside expanded connection details. A fixed allowlist excludes candidate addresses/ports, participant and room identity, raw signaling, URLs, and credentials; no report is uploaded or persisted. Production rollout is pending.- Private fragment grants enter directly; code-only Viewers need site access and private rooms additionally need their password. Credentials remain unstored. Web names and presence are session-only; duplicate names alone show an ID suffix.- Rooms default to eight Viewers and accept an explicit admission limit from one through sixteen. Roots and ordinary Web relays are bounded to two downstream edges, Viewer upstream receive is free, and source permits an explicit endpoint cap from one through three. SFU root capacity remains separate.-- Relay quality handling compares fresh child FPS with parent input. Two current corroborating children can pause one Viewer relay for 30 seconds and request peer-only reassignment; no candidate keeps the old edge.+- Relay quality handling compares fresh child FPS with parent input. Two current corroborating children can pause one Viewer relay for 30 seconds and request peer-only reassignment. The source candidate keeps the triggering child's old edge while one ordinary peer-upstream Viewer proves current-generation RTP, decoded frames, and live video; v1 excludes Host/SFU roots, preserves ready-failure identity through commit/rollback, and lets unrelated hard failures preempt the soft probe. Failure, timeout, or no candidate keeps the old edge without SFU/TURN. Sibling MBB remains open.- A generation-bound 15-second initial-connect deadline enters ICE restart. One-root healthy-SFU make-before-break is deployed but media-unverified; capacity `0 -> 1`, multi-root, browser, and mobile gates remain open.## Active Milestonediff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"index 65d63a6d..2ed96ca3 100644--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"@@ -184,7 +184,7 @@ Viewer 本地连接详情只从当前 route 的唯一 inbound screen video/audio质量自适应采用 ADR-0007 的 built-in-first 路径隔离双表示,而不是全房间按最差链路降档。Direct/peer 保留每条 PeerConnection 的 stock WebRTC GCC。每条 SFU path 从 `HIGH` ceiling 开始;优先发布共享 `HIGH+LOW` 并让 LiveKit BWE 独立降层和恢复。若该 gate 通过,Screener 不实现媒体层 selector。应用证据只决定下述 parent/leaf 拓扑资格与诊断。`LOW` 可以常驻;关闭空闲层只是资源优化。active representation/layer 数量硬限制为二,不能按 viewer 增长。标准浏览器不保证跨 PeerConnection 共用一个物理编码器,inactive 层也不保证释放 GPU;实际层数、实例数、CPU/GPU、游戏 FPS/p1 low、区间 encode cost、上传与释放行为必须实测。若没有合格 hardware/power-efficient 路径或额外表示破坏游戏/上传预算,则 fail closed,保留健康路径并明确显示弱路径降级或失败。-单个三窗确认的 C+B 事件仍是 edge-local:`severe` 进入原 fallback ladder,`relative-fps` 只尝试 peer。若同一 Viewer parent peer/session/share 在五秒内由两个不同 child 分别确认任一类型,服务端把该 parent 的独立 `relayEligible` 暂停 30 秒,使拓扑有效容量为零但保留客户端广告值;后续 capacity 广播不能绕过。Host 不参与,parent 自身 upstream/观看和无可替代 peer 的旧 child edge 均保留;有 peer 的当前 children 各自重选,退位不创建 SFU/TURN intent。到期惰性恢复,parent 新 session 或新分享立即恢复,stop/delete/disconnect 清理状态。该离散资格不命令 LiveKit/WebRTC 媒体层,也不把 RTT、CPU、码率、设备信息压成综合分数;窗口仍需真实质量矩阵校准。+单个三窗确认的 C+B 事件仍是 edge-local,`severe` 与 `relative-fps` 都先且只尝试一个 ordinary peer-upstream Viewer;v1 排除 Host 与 SFU root,但继续枚举后续合格 Viewer,二者的 provisional-child 支持留待后续。服务端在现有 route prepare 上保留旧 active edge 与 connection generation;新 parent 只建立一个 provisional edge,Viewer 以当前 prepare revision 的正 RTP、正 decoded frames 和 live video track 证明后,服务端才一次性提交拓扑、route 与候选 connection ID。prepare-ready 后的候选失败必须保留精确 revision/parent/connection identity 到 matching active 或 rollback;matching active 先到时立即报告 active failure,不能 promotion 已失败 peer。其他 edge 的已鉴权 hard `route-failed` 先 abort soft probe 并让 target/candidate 回到 current authority,再立即进入原故障梯级。候选失败、超时或无候选均回滚/保留旧边,不创建 SFU/TURN intent。同房同时最多一个 peer migration。若同一 Viewer parent peer/session/share 在五秒内由两个不同 child 分别确认任一类型,服务端把该 parent 的独立 `relayEligible` 暂停 30 秒,使拓扑有效容量为零但保留客户端广告值;后续 capacity 广播不能绕过。Host 不参与,parent 自身 upstream/观看不变;本 slice 只保证触发 child 的 MBB,其他 current children 暂沿既有有界重选,完整 sibling MBB 后续实现。到期惰性恢复,parent 新 session 或新分享立即恢复,stop/delete/disconnect 清理状态。该离散资格不命令 LiveKit/WebRTC 媒体层,也不把 RTT、CPU、码率、设备信息压成综合分数;窗口仍需真实质量矩阵校准。状态决策必须关联同一时间区间和媒体代次的三段证据:diff --git "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md" "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"index b44ae325..5b5a2fff 100644--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"@@ -41,7 +41,7 @@- [ ] 私密房间双入口:private room 接受现有 `/r/{code}#v={grant}` 合法邀请直接进入,或“站点访问 + 房间号 + 该房间观看密码”。没有 grant 的 `/join` 或 `/r/{code}` 先显示明确标为“站点访问”的整站验证,通过后才显示明确标为“加入房间”的当前房间密码输入;有效 site-access cookie 直接跳过第一步,但两类密码不得复用、代填或互相替代。Host 可设置、轮换或移除房间观看密码。密码接受 1 至 64 个可见 ASCII 字符;异步 scrypt 全局最多执行 2 个、等待 16 个派生。站点口令和房间密码都不得进入 URL/query/storage/log/SQLite;不存在、错误密码、队满和正确密码后的满房都返回通用结果。-- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。合格父节点构成网状候选关系,但实际媒体保持无环且每个 Viewer 只有一个 active upstream;加入、容量变化、掉线和当前边失败触发有界重选,切换重叠必须受现有边预算与当前代媒体证据约束,不做常驻多源分片。一个 child 的已确认 C+B 质量事件仍只处理该 edge;只有同一 Viewer parent peer/session/share 在五秒内收到两个不同 child 各自三窗确认的 `severe` 或 `relative-fps`,服务端才把该 parent 的独立 relay 资格暂停 30 秒,使有效容量为零但不覆盖客户端广告。Host 不退位,parent 的上游观看不变;当前 children 只尝试其他 peer,无候选时保留旧边,退位本身不得准备 SFU/TURN。新 parent session、新分享或 30 秒到期立即/惰性恢复资格。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。+- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。合格父节点构成网状候选关系,但实际媒体保持无环且每个 Viewer 只有一个 active upstream;加入、容量变化、掉线和当前边失败触发有界重选,切换重叠必须受现有边预算与当前代媒体证据约束,不做常驻多源分片。一个 child 的已确认 C+B 质量事件仍只处理该 edge:v1 只选择 active upstream 仍为 peer 的普通 Viewer,跳过 Host/SFU root 后继续枚举;保留旧边并建立至多一个候选边,只有候选在当前 prepare revision 收到 RTP、解码出帧且持有 live video track 后才原子换父。prepare-ready 后候选失败时,精确 revision/parent/connection identity 必须保留到 matching active 或 rollback;matching active 先到则报告 active failure,不能 promotion 已失败 peer。其他 edge 的真实 `route-failed` 必须先抢占 soft probe、恢复 target/candidate current authority,再进入原故障梯级。候选失败、超时或无候选都保留旧边,质量事件本身不得进入 SFU/TURN。只有同一 Viewer parent peer/session/share 在五秒内收到两个不同 child 各自三窗确认的 `severe` 或 `relative-fps`,服务端才把该 parent 的独立 relay 资格暂停 30 秒,使有效容量为零但不覆盖客户端广告。Host 不退位,parent 的上游观看不变;其他当前 children 暂沿既有有界重选,完整 sibling MBB 是后续 slice。新 parent session、新分享或 30 秒到期立即/惰性恢复资格。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。- [ ] 质量控制扩展:推荐档位仍是默认入口;“高级视频设置”只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling、清晰/平衡/流畅三种偏好,以及 `自动 | H.264 | VP8` 编码选择;初始值采用 `balanced` 与 `automatic`,其余偏好和编码保留为显式选择。视频档位在直播中显式应用;codec 直播中锁定并于下一次分享生效,避免滑杆产生连续控制流量。本期不重命名该区域,也不增加音频 UI:屏幕音频固定使用一个媒体默认,所有实际浏览器 sender 请求并读回 128 kbps ceiling,DTX 关闭,Web peer 与 SFU 都显式允许 Opus stereo 并协商 128 kbps maximum average bitrate;实际码率仍由浏览器拥塞控制和 stats 决定。Peer 只在唯一明确的 active Opus audio 上做结构化、幂等的 Viewer answer `stereo=1;maxaveragebitrate=128000` 变换;非目标形态或 parser/writer 异常必须原样保留浏览器 answer,不得阻断可继续的 mono/video edge。不得用宽泛字符串/正则改 SDP,也不得改写浏览器协商的 FEC。SFU 使用 pinned SDK 的 128 kbps high-quality stereo preset、`forceStereo = true`、`dtx = false`,并保留 pinned room default `red = true`。不得暴露声道、采样率、codec、任意码率、stereo、DTX、RED 或 FEC 控件。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。未来 microphone voice 若进入范围,必须是独立 track/处理链,不能把 AEC/降噪/DTX 套到电影或游戏音频。- [ ] SFU 质量设置生命周期:直播中修改档位时,浏览器 sender 的 applied readback、LiveKit `LocalVideoTrack` 保存的 degradation preference、track restart options 与 `LocalTrackPublication` 的 republish options 必须作为同一次串行操作更新;任一步失败恢复旧 sender 与旧 SDK 保存态,旧 publication generation 不得回写当前状态。LiveKit full reconnect/republish 不得恢复初次发布的旧偏好。该修复不改变 codec、码率上限、层数或路由,也不能单独解释即时低帧。- [ ] 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。diff --git a/src/client/media/viewer-sfu-route.ts b/src/client/media/viewer-sfu-route.tsindex 8b70ee4f..9d95899d 100644--- a/src/client/media/viewer-sfu-route.ts+++ b/src/client/media/viewer-sfu-route.ts@@ -67,6 +67,7 @@ export class ViewerSfuRoute {private active: ViewerSubscriberSlot | null = null;private recovery: { revision: number; refreshed: boolean } | null = null;private peerProbeRevision: number | null = null;+ private failedPeerProbe: { revision: number; parentPeerId: string; connectionId: string } | null = null;private healthySfuWindows: number | null = null;private transitionTail: Promise<void> = Promise.resolve();private resyncGeneration = 0;@@ -91,12 +92,15 @@ export class ViewerSfuRoute {if (previousRevision !== update.revision) {this.recovery = null;this.peerProbeRevision = null;+ this.failedPeerProbe = null;this.healthySfuWindows = null;}if (update.phase === "prepare") {+ const mediaUpstream = this.route.getMediaAssignment()?.upstream;if (update.assignment.upstream.kind === "peer" &&- this.route.getMediaAssignment()?.upstream.kind === "sfu"+ (mediaUpstream?.kind !== "peer" ||+ mediaUpstream.peerId !== update.assignment.upstream.peerId)) {this.peerProbeRevision = update.revision;this.events.preparePeer?.(update.assignment, update.revision);@@ -136,6 +140,7 @@ export class ViewerSfuRoute {if (this.closed) {return "stale";}+ this.peerProbeRevision = this.failedPeerProbe = null;if (!this.active && !this.pending) {const result = this.accept(update, false);if (result !== "stale") {@@ -147,7 +152,6 @@ export class ViewerSfuRoute {this.resyncing = true;this.route.reset();this.recovery = null;- this.peerProbeRevision = null;this.healthySfuWindows = null;const pending = this.pending;const active = this.active;@@ -305,6 +309,16 @@ export class ViewerSfuRoute {);}+ reportPeerProbeFailure(parentPeerId: string, connectionId: string, ready: boolean): boolean {+ const revision = this.peerProbeRevision, phase = this.route.getPhase();+ const upstream = this.route.getPlannedAssignment()?.upstream;+ if (revision === null || phase === null ||+ upstream?.kind !== "peer" || upstream.peerId !== parentPeerId) return false;+ if (ready) this.failedPeerProbe = { revision, parentPeerId, connectionId };+ this.events.send({ type: "route-failed", revision, phase, connectionId });+ return true;+ }+armHealthySfuReselection(revision: number): void {if (this.route.getRevision() === revision &&@@ -324,6 +338,7 @@ export class ViewerSfuRoute {this.route.reset();this.recovery = null;this.peerProbeRevision = null;+ this.failedPeerProbe = null;this.healthySfuWindows = null;this.events.preparePeer?.(null);await this.queueTransition(async () => {@@ -384,6 +399,15 @@ export class ViewerSfuRoute {}const probeRevision = this.peerProbeRevision;+ const failedProbe = this.failedPeerProbe;+ if (failedProbe?.revision === token.revision &&+ assignment.upstream.kind === "peer" &&+ assignment.upstream.peerId === failedProbe.parentPeerId) {+ this.failedPeerProbe = null;+ this.events.send({ type: "route-failed", revision: token.revision,+ phase: "active", connectionId: failedProbe.connectionId });+ return;+ }const promoted =probeRevision === token.revision? await this.events.activatePeer(assignment, token.revision)diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex 4a66dd8b..5d015715 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -102,6 +102,7 @@ interface SfuUpstreamState {interface PeerProbe {revision: number;parentPeerId: string;+ peer: ViewerPeer | null;ready: boolean;stream: MediaStream | null;snapshot: PeerSnapshot | null;@@ -457,25 +458,21 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {}function discardPeerProbe(): void {- const hadPeerProbe = peerProbe !== null;+ const probe = peerProbe;peerProbe = null;prepareParent(null);- if (!hadPeerProbe) {- return;- }- peerRef.current?.dispose();- peerRef.current = null;+ probe?.peer?.dispose();}function peerProbeHasCurrentMedia(probe: PeerProbe,- ): probe is PeerProbe & { stream: MediaStream; snapshot: PeerSnapshot } {+ ): probe is PeerProbe & { peer: ViewerPeer; stream: MediaStream; snapshot: PeerSnapshot } {const { snapshot, stream } = probe;return (snapshot !== null &&stream !== null &&snapshot.peerId === probe.parentPeerId &&- peerRef.current?.hasConnectionId(snapshot.connectionId) === true &&+ probe.peer?.hasConnectionId(snapshot.connectionId) === true &&snapshot.connectionState === "connected" &&(snapshot.metrics.intervalPacketsReceived ?? 0) > 0 &&(snapshot.metrics.intervalFramesDecoded ?? 0) > 0 &&@@ -526,8 +523,11 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {discardPeerProbe();return false;}+ const previousPeer = peerRef.current;peerProbe = null;prepareParent(null);+ peerRef.current = probe.peer;+ previousPeer?.dispose();applyMediaAssignment({parentPeerId: probe.parentPeerId,@@ -562,6 +562,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {peerProbe = {revision,parentPeerId: assignment.upstream.peerId,+ peer: null,ready: false,stream: null,snapshot: null,@@ -725,6 +726,53 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {reconcileRelayChildren(previousChildPeerIds);}+ function ensurePeerProbe(): ViewerPeer | null {+ const probe = peerProbe;+ if (!probe || !currentIceConfig) return null;+ if (probe.peer) return probe.peer;+ const peer: ViewerPeer = new ViewerPeer(currentIceConfig, {+ sendSignal: (targetPeerId, payload) =>+ signal.send(viewerSignalMessage(peerAssisted, targetPeerId, payload)),+ sendRestartRequest: () => false,+ onStream: (stream) => {+ if (peerProbe === probe) {+ probe.stream = stream;+ provePeerProbe();+ } else if (active && peerRef.current === peer) {+ setRemoteStream(stream);+ ensureViewerRelay()?.setStream(stream);+ setStatusText("正在播放");+ }+ },+ onUpdate: (snapshot) => {+ if (peerProbe === probe) {+ probe.snapshot = snapshot;+ provePeerProbe();+ } else if (active && peerRef.current === peer) {+ qualityEvidenceReporter.offer(snapshot, currentRouteRevision);+ setPeerSnapshot(snapshot);+ setStatusText(+ snapshot.connectionState === "connected"+ ? "已连接"+ : "正在恢复连接",+ );+ }+ },+ onRecoveryExhausted: (parentPeerId, connectionId): boolean => {+ if (peerProbe === probe && peer.hasConnectionId(connectionId)) {+ viewerSfuRoute?.reportPeerProbeFailure(parentPeerId, connectionId, probe.ready);+ discardPeerProbe();+ return true;+ }+ return peerRef.current === peer && viewerSfuRoute+ ? viewerSfuRoute.reportPeerFailure(parentPeerId, connectionId)+ : true;+ },+ });+ probe.peer = peer;+ return peer;+ }+function ensurePeer(): ViewerPeer | null {if (peerRef.current) {return peerRef.current;@@ -742,7 +790,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {viewerSignalMessage(peerAssisted, targetPeerId, payload),),sendRestartRequest: (targetPeerId, connectionId, rebuild) =>- !peerProbe && signal.send(+ signal.send(viewerRestartMessage(peerAssisted,targetPeerId,@@ -752,11 +800,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {),onStream: (nextStream) => {if (active) {- if (peerProbe) {- peerProbe.stream = nextStream;- provePeerProbe();- return;- }setRemoteStream(nextStream);setStatusText("正在播放");// Audio and video can arrive as separate track events on the@@ -766,11 +809,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {},onUpdate: (snapshot) => {if (active) {- if (peerProbe) {- peerProbe.snapshot = snapshot;- provePeerProbe();- return;- }qualityEvidenceReporter.offer(snapshot, currentRouteRevision);if (!currentHostOnline &&@@ -792,25 +830,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {}},onRecoveryExhausted: (parentPeerId, connectionId) => {- if (- peerProbe?.parentPeerId === parentPeerId &&- peerProbe.snapshot?.connectionId === connectionId- ) {- signal.send({- type: "route-failed",- revision: peerProbe.revision,- phase: "prepare",- connectionId,- });- signal.send({- type: "route-failed",- revision: peerProbe.revision,- phase: "active",- connectionId,- });- discardPeerProbe();- return true;- }if (selectedEdgeTurn?.grant.parentPeerId === parentPeerId &&selectedEdgeTurn.grant.newConnectionId === connectionId@@ -1091,7 +1110,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {}if (message.type === "signal") {if (peerAssisted && peerProbe?.parentPeerId === message.fromPeerId) {- await ensurePeer()?.acceptSignal(message.fromPeerId, message.payload);+ await ensurePeerProbe()?.acceptSignal(message.fromPeerId, message.payload);return;}if (diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.tsindex 3439b791..407c9803 100644--- a/src/server/hybrid-media-router.ts+++ b/src/server/hybrid-media-router.ts@@ -48,6 +48,7 @@ interface PendingRoutePreparation {grantsIssued: boolean;hostSfuIngressTurnAttempted: boolean;healthyReselection: HealthySfuReselectionProbe | null;+ peerQualityReselection: PeerQualityReselectionProbe | null;timer: NodeJS.Timeout;}@@ -108,6 +109,12 @@ interface HealthySfuReselectionProbe {parentPeerId: string;}+interface PeerQualityReselectionProbe {+ excludedParentPeerIds: ReadonlySet<string>;+ newParentPeerId: string;+ newConnectionId: string | null;+}+interface DeferredHealthySfuReselection {activeRevision: number;shareGeneration: string;@@ -189,6 +196,7 @@ export interface HybridMediaRouterOptions {selectedEdgeTurn?: SelectedEdgeTurnConfig;sendToSession: (sessionId: string, message: ServerMessage) => void;getConnectionId: (roomId: string, viewerPeerId: string) => string | undefined;+ setConnectionId: (roomId: string, viewerPeerId: string, connectionId: string) => void;deleteConnectionId: (roomId: string, viewerPeerId: string) => void;getShareGeneration: (roomId: string) => string | undefined;onActiveRouteChanged?: (roomId: string) => void;@@ -437,7 +445,7 @@ export class HybridMediaRouter {connectionId: string;signalKind: "candidate" | "description";descriptionType?: "offer" | "answer";- }): boolean | undefined {+ }): boolean | "probe" | undefined {const sourceKey = viewerConnectionKey(input.roomId, input.sourcePeerId);const targetKey = viewerConnectionKey(input.roomId, input.targetPeerId);const lease =@@ -450,6 +458,32 @@ export class HybridMediaRouter {: undefined;if (!lease) {const pending = this.pendingRoutePreparations.get(input.roomId);+ const qualityProbe = pending?.peerQualityReselection;+ const viewerPeerId = pending?.intentPeerId;+ const parentToViewer =+ qualityProbe?.newParentPeerId === input.sourcePeerId &&+ viewerPeerId === input.targetPeerId;+ const viewerToParent =+ viewerPeerId === input.sourcePeerId &&+ qualityProbe?.newParentPeerId === input.targetPeerId;+ if (pending && qualityProbe && (parentToViewer || viewerToParent)) {+ if (!this.peerQualityReselectionIsCurrent(input.roomId, pending)) {+ return false;+ }+ if (+ parentToViewer &&+ input.signalKind === "description" &&+ input.descriptionType === "offer"+ ) {+ qualityProbe.newConnectionId ??= input.connectionId;+ }+ return (+ qualityProbe.newConnectionId === input.connectionId &&+ (input.signalKind === "candidate" ||+ (parentToViewer && input.descriptionType === "offer") ||+ (viewerToParent && input.descriptionType === "answer"))+ ) ? "probe" : false;+ }const probe = pending?.healthyReselection;const parentToRoot = probe?.parentPeerId === input.sourcePeerId &&probe.rootPeerId === input.targetPeerId;@@ -1015,6 +1049,7 @@ export class HybridMediaRouter {rootPeerId: participant.peerId,parentPeerId,},+ peerQualityReselection: null,timer,});for (const [sessionId, assignment] of [@@ -1086,6 +1121,24 @@ export class HybridMediaRouter {return;}}+ const qualityProbe = pending.peerQualityReselection;+ if (qualityProbe) {+ const current = this.peerQualityReselectionIsCurrent(+ participant.roomId,+ pending,+ );+ if (+ participant.role !== "viewer" ||+ participant.peerId !== pending.intentPeerId ||+ qualityProbe.newConnectionId === null ||+ !current+ ) {+ if (!current) {+ this.abortPendingRoute(participant.roomId);+ }+ return;+ }+ }const expectedSessionId = pending.expectedSessionIds.get(participant.peerId);if (!expectedSessionId) {this.sendError(@@ -1159,6 +1212,8 @@ export class HybridMediaRouter {): void {const healthyPending = this.pendingRoutePreparations.get(participant.roomId);const healthy = healthyPending?.healthyReselection;+ const qualityProbe = healthyPending?.peerQualityReselection;+ const qualityGuard = healthyPending?.qualityIntent?.guard;const ownsHealthyActiveSfu = healthyPending? this.ownsActiveSfuForHealthyReselection(participant, healthyPending): false;@@ -1176,6 +1231,27 @@ export class HybridMediaRouter {}message = { ...message, revision: rollbackRevision };}+ const qualityActiveIngress = this.activeSelectedSfuIngresses.get(+ participant.roomId,+ );+ const qualityActiveRoute = this.mediaRouteControllers+ .get(participant.roomId)+ ?.getActiveRoute();+ if (+ qualityProbe &&+ participant.role === "host" &&+ qualityActiveIngress?.hostPeerId === participant.peerId &&+ qualityActiveIngress.hostSessionId === participant.sessionId &&+ qualityActiveIngress.connectionId === message.connectionId &&+ qualityActiveIngress.shareGeneration === this.options.getShareGeneration(participant.roomId) &&+ qualityActiveRoute?.sfu.publicationGeneration === qualityActiveIngress.publicationGeneration &&+ ((message.phase === "active" && message.revision === qualityActiveRoute.revision) ||+ (message.phase === "prepare" && message.revision === healthyPending?.revision))+ ) {+ this.abortPeerQualityReselectionForHardFailure(participant.roomId);+ this.activeSelectedSfuIngresses.delete(participant.roomId);+ return;+ }if (message.phase === "prepare" &&healthyPending?.revision === message.revision &&@@ -1214,6 +1290,22 @@ export class HybridMediaRouter {}return;}+ if (+ message.phase === "prepare" &&+ healthyPending?.revision === message.revision &&+ qualityProbe+ ) {+ if (+ participant.role === "viewer" &&+ participant.peerId === healthyPending.intentPeerId &&+ participant.sessionId === qualityGuard?.viewerSessionId &&+ qualityProbe.newConnectionId !== null &&+ message.connectionId === qualityProbe.newConnectionId+ ) {+ this.abortPendingRoute(participant.roomId);+ }+ return;+ }if (message.phase === "prepare") {this.handlePrepareRouteFailed(participant, message);return;@@ -1247,13 +1339,17 @@ export class HybridMediaRouter {);return;}+ this.abortPeerQualityReselectionForHardFailure(+ participant.roomId,+ participant.role === "viewer" ? participant.peerId : undefined,+ );if (hostOwnsGeneration &&this.startSelectedSfuIngressTurn(participant.roomId,participant.peerId,participant.sessionId,- active,+ controller.getActiveRoute(),)) {return;@@ -1298,6 +1394,10 @@ export class HybridMediaRouter {) {return;}+ this.abortPeerQualityReselectionForHardFailure(+ participant.roomId,+ participant.peerId,+ );const now = this.options.now?.() ?? Date.now();this.pruneHeldQualityParentExclusion(participant.roomId,@@ -1495,10 +1595,14 @@ export class HybridMediaRouter {private roomPeerMigrationAttempt(roomId: string,viewerPeerId?: string,- ): "healthy" | "selected" | null {- if (this.pendingRoutePreparations.get(roomId)?.healthyReselection) {+ ): "healthy" | "quality" | "selected" | null {+ const pending = this.pendingRoutePreparations.get(roomId);+ if (pending?.healthyReselection) {return "healthy";}+ if (pending?.peerQualityReselection) {+ return "quality";+ }return [...this.selectedPeerEdgeLeases.values()].some((lease) =>lease.roomId === roomId &&@@ -1508,6 +1612,13 @@ export class HybridMediaRouter {: null;}+ private abortPeerQualityReselectionForHardFailure(roomId: string, failedViewerPeerId?: string): void {+ const pending = this.pendingRoutePreparations.get(roomId);+ if (pending?.peerQualityReselection && pending.intentPeerId !== failedViewerPeerId) {+ this.abortPendingRoute(roomId, undefined, false);+ }+ }+private startSelectedEdgeTurn(roomId: string,viewerPeerId: string,@@ -1519,8 +1630,8 @@ export class HybridMediaRouter {const intent = this.viewerRouteIntentsByRoom.get(roomId)?.get(viewerPeerId);const key = viewerConnectionKey(roomId, viewerPeerId);const roomAttempt = this.roomPeerMigrationAttempt(roomId);- if (roomAttempt === "healthy") {- // The healthy probe already owns recovery, so suppress active-route failback.+ if (roomAttempt === "healthy" || roomAttempt === "quality") {+ // The room probe already owns recovery, so suppress concurrent failback.return true;}if (this.selectedPeerEdgeLeases.has(key)) {@@ -1902,6 +2013,10 @@ export class HybridMediaRouter {) {return false;}+ this.abortPeerQualityReselectionForHardFailure(+ participant.roomId,+ lease.viewerPeerId,+ );this.settleSelectedPeerEdgeLease(key);this.sendError(participant.sessionId,@@ -2150,6 +2265,20 @@ export class HybridMediaRouter {this.discardQualityIntent(roomId, viewerPeerId, intent);continue;}+ if (intent.qualityGuard) {+ if (+ this.startPeerQualityReselection(+ roomId,+ viewerPeerId,+ intent,+ failedParents,+ )+ ) {+ return;+ }+ this.discardQualityIntent(roomId, viewerPeerId, intent, true);+ continue;+ }const changes = this.peerRelayTopology.reassignViewer(roomId,viewerPeerId,@@ -2158,29 +2287,6 @@ export class HybridMediaRouter {MAX_PEER_RELAY_DEPTH,);if (changes) {- if (intent.qualityGuard) {- this.startRoomQualityMigrationCooldown(roomId);- if (intent.qualityGuard.kind === "relative-fps") {- this.heldQualityParentExclusionsByViewer.set(- viewerConnectionKey(roomId, viewerPeerId),- {- parentPeerId: intent.qualityGuard.parentPeerId,- parentSessionId: intent.qualityGuard.parentSessionId,- expiresAtMs:- (this.options.now?.() ?? Date.now()) +- VIEWER_QUALITY_REASSIGN_COOLDOWN_MS,- },- );- intent.qualityGuard.exclusionOwnedByQuality = false;- } else {- this.releaseQualityOwnedParentExclusion(- roomId,- viewerPeerId,- intent,- intent.qualityGuard,- );- }- }intents.delete(viewerPeerId);this.clearChangedConnectionIds(roomId, changes);this.reconcileMediaRoute(roomId);@@ -2249,6 +2355,132 @@ export class HybridMediaRouter {}}+ private startPeerQualityReselection(+ roomId: string,+ viewerPeerId: string,+ intent: ViewerRouteIntent,+ excludedParentPeerIds: ReadonlySet<string>,+ ): boolean {+ const guard = intent.qualityGuard;+ const controller = this.mediaRouteControllers.get(roomId);+ const active = controller?.getActiveRoute();+ const viewer = this.options.roomStore.getConnectedViewer(roomId, viewerPeerId);+ if (+ !guard ||+ !controller ||+ controller.getPendingRoute() ||+ this.roomPeerMigrationAttempt(roomId) !== null ||+ !active ||+ !viewer ||+ !this.qualityIntentIsCurrent(roomId, viewerPeerId, intent)+ ) {+ return false;+ }++ const candidateExclusions = new Set(excludedParentPeerIds);+ candidateExclusions.add(this.peerRelayTopology.getHostPeerId(roomId) ?? guard.parentPeerId);+ for (const [peerId, assignment] of active.assignments) {+ if (assignment.upstream.kind !== "peer" || active.sfu.rootPeerIds.includes(peerId)) candidateExclusions.add(peerId);+ }+ const newParentPeerId = this.peerRelayTopology.findViewerReassignmentParent(+ roomId,+ viewerPeerId,+ this.connectedPeerIds(roomId),+ candidateExclusions,+ MAX_PEER_RELAY_DEPTH,+ );+ const newParent = newParentPeerId+ ? this.connectedPeer(roomId, newParentPeerId)+ : undefined;+ if (!newParentPeerId || !newParent) {+ return false;+ }++ const assignments = cloneAssignments(active.assignments);+ const participantOrder = [...assignments.keys()];+ const viewerAssignment = assignments.get(viewerPeerId);+ const oldParentAssignment = assignments.get(guard.parentPeerId);+ const newParentAssignment = assignments.get(newParentPeerId);+ if (+ viewerAssignment?.upstream.kind !== "peer" ||+ viewerAssignment.upstream.peerId !== guard.parentPeerId ||+ !oldParentAssignment ||+ !newParentAssignment+ ) {+ return false;+ }+ assignments.set(guard.parentPeerId, {+ ...oldParentAssignment,+ childPeerIds: oldParentAssignment.childPeerIds.filter(+ (peerId) => peerId !== viewerPeerId,+ ),+ });+ assignments.set(newParentPeerId, {+ ...newParentAssignment,+ childPeerIds: [...newParentAssignment.childPeerIds, viewerPeerId].sort((left, right) =>+ participantOrder.indexOf(left) - participantOrder.indexOf(right)),+ });+ assignments.set(viewerPeerId, {+ ...viewerAssignment,+ upstream: { kind: "peer", peerId: newParentPeerId },+ });++ let revision: number | undefined;+ try {+ revision = controller.prepare({+ assignments,+ expectedParticipantIds: new Set([viewerPeerId]),+ sfuPublicationGeneration: active.sfu.publicationGeneration,+ sfuRootPeerIds: active.sfu.rootPeerIds,+ });+ } catch {+ return false;+ }+ if (revision === undefined) {+ return false;+ }+ const timer = setTimeout(+ () => this.abortPendingRoute(roomId),+ this.options.sfuFallback?.prepareTimeoutMs ?? DEFAULT_SFU_PREPARE_TIMEOUT_MS,+ );+ timer.unref();+ this.pendingRoutePreparations.set(roomId, {+ revision,+ intentPeerId: viewerPeerId,+ routeIntent: intent,+ qualityIntent: {+ guard: { ...guard },+ takenOverByRouteFailure: false,+ },+ expectedSessionIds: new Map([+ [viewerPeerId, viewer.sessionId],+ [newParentPeerId, newParent.sessionId],+ ]),+ grantsIssued: true,+ hostSfuIngressTurnAttempted: false,+ healthyReselection: null,+ peerQualityReselection: {+ excludedParentPeerIds: candidateExclusions,+ newParentPeerId,+ newConnectionId: null,+ },+ timer,+ });+ this.startRoomQualityMigrationCooldown(roomId);+ for (const [sessionId, assignment] of [+ [viewer.sessionId, assignments.get(viewerPeerId)!],+ [newParent.sessionId, assignments.get(newParentPeerId)!],+ ] as const) {+ this.options.sendToSession(sessionId, {+ type: "route-update",+ revision,+ phase: "prepare",+ assignment,+ });+ }+ return true;+ }+private qualityIntentIsCurrent(roomId: string,viewerPeerId: string,@@ -2274,12 +2506,26 @@ export class HybridMediaRouter {roomId: string,viewerPeerId: string,intent: ViewerRouteIntent,+ holdParentExclusion = false,): void {const guard = intent.qualityGuard;const intents = this.viewerRouteIntentsByRoom.get(roomId);if (!guard || intents?.get(viewerPeerId) !== intent) {return;}+ if (holdParentExclusion) {+ this.heldQualityParentExclusionsByViewer.set(+ viewerConnectionKey(roomId, viewerPeerId),+ {+ parentPeerId: guard.parentPeerId,+ parentSessionId: guard.parentSessionId,+ expiresAtMs:+ (this.options.now?.() ?? Date.now()) ++ VIEWER_QUALITY_REASSIGN_COOLDOWN_MS,+ },+ );+ guard.exclusionOwnedByQuality = false;+ }intents.delete(viewerPeerId);if (intents.size === 0) {this.viewerRouteIntentsByRoom.delete(roomId);@@ -2528,6 +2774,7 @@ export class HybridMediaRouter {grantsIssued: false,hostSfuIngressTurnAttempted: false,healthyReselection: null,+ peerQualityReselection: null,timer,});void this.issueSfuPrepareGrants(@@ -2636,6 +2883,26 @@ export class HybridMediaRouter {return;}const before = controller.getActiveRoute();+ const qualityProbe = pending.peerQualityReselection;+ const qualityGuard = pending.qualityIntent?.guard;+ if (qualityProbe) {+ if (+ !qualityGuard ||+ qualityProbe.newConnectionId === null ||+ !this.peerQualityReselectionIsCurrent(roomId, pending) ||+ !this.peerRelayTopology.reassignViewer(+ roomId,+ pending.intentPeerId,+ this.connectedPeerIds(roomId),+ qualityProbe.excludedParentPeerIds,+ MAX_PEER_RELAY_DEPTH,+ qualityProbe.newParentPeerId,+ )+ ) {+ this.abortPendingRoute(roomId);+ return;+ }+ }if (!controller.commit(revision)) {return;}@@ -2649,6 +2916,18 @@ export class HybridMediaRouter {);this.viewerRouteIntentsByRoom.get(roomId)?.delete(healthy.rootPeerId);this.consumedSfuRefreshesByRoom.delete(roomId);+ } else if (qualityProbe?.newConnectionId) {+ this.options.setConnectionId(+ roomId,+ pending.intentPeerId,+ qualityProbe.newConnectionId,+ );+ this.discardQualityIntent(+ roomId,+ pending.intentPeerId,+ pending.routeIntent,+ qualityGuard?.kind === "relative-fps",+ );} else {this.clearChangedRouteConnectionIds(roomId, before, active);}@@ -2674,6 +2953,25 @@ export class HybridMediaRouter {);}+ private peerQualityReselectionIsCurrent(+ roomId: string,+ pending: PendingRoutePreparation,+ ): boolean {+ const probe = pending.peerQualityReselection;+ const controller = this.mediaRouteControllers.get(roomId);+ const planned = controller?.getPendingRoute()?.route;+ const plannedUpstream = planned?.assignments.get(pending.intentPeerId)?.upstream;+ return Boolean(+ probe &&+ this.pendingRoutePreparations.get(roomId) === pending &&+ planned?.revision === pending.revision &&+ plannedUpstream?.kind === "peer" &&+ plannedUpstream.peerId === probe.newParentPeerId &&+ this.pendingSessionsAreCurrent(roomId, pending) &&+ this.pendingQualityIntentIsCurrent(roomId, pending),+ );+ }+private ownsActiveSfuForHealthyReselection(participant: AuthenticatedRouteParticipant,pending: PendingRoutePreparation,@@ -2732,6 +3030,14 @@ export class HybridMediaRouter {excludedPeerId,);}+ if (pending.peerQualityReselection) {+ this.discardQualityIntent(+ roomId,+ pending.intentPeerId,+ pending.routeIntent,+ true,+ );+ }if (drainFailureIntents) {this.drainViewerRouteIntents(roomId);}@@ -3522,12 +3828,6 @@ export class HybridMediaRouter {now + VIEWER_QUALITY_REASSIGN_COOLDOWN_MS;this.peerRelayTopology.setViewerRelayEligible(roomId, parentPeerId, false);}- if (- badWindowKind === "relative-fps" &&- !this.pendingRoutePreparations.has(roomId)- ) {- this.evacuateRelayParentChildren(roomId, parentPeerId);- }return this.resolveActivePeerEdge(roomId, childPeerId)?.parentPeerId ===parentPeerId? badWindowKind@@ -3541,6 +3841,13 @@ export class HybridMediaRouter {const childPeerIds =this.peerRelayTopology.getAssignment(roomId, parentPeerId)?.childPeerIds ?? [];for (const childPeerId of childPeerIds) {+ if (+ this.heldQualityParentExclusionsByViewer.get(+ viewerConnectionKey(roomId, childPeerId),+ )?.parentPeerId === parentPeerId+ ) {+ continue;+ }const failedParents = this.failedParentPeerIdsByViewer.get(viewerConnectionKey(roomId, childPeerId),);diff --git a/src/server/peer-relay-topology.ts b/src/server/peer-relay-topology.tsindex c7850ad0..aefe25f4 100644--- a/src/server/peer-relay-topology.ts+++ b/src/server/peer-relay-topology.ts@@ -244,7 +244,44 @@ export class PeerRelayTopology {connectedPeerIds: ReadonlySet<string>,excludedParentPeerIds: ReadonlySet<string>,maxDepth = MAX_PEER_RELAY_DEPTH,+ requiredParentPeerId?: string,): MediaAssignmentChange[] | undefined {+ const parentPeerId = this.findViewerReassignmentParent(+ roomId,+ peerId,+ connectedPeerIds,+ excludedParentPeerIds,+ maxDepth,+ );+ if (!parentPeerId || (requiredParentPeerId && parentPeerId !== requiredParentPeerId)) {+ return undefined;+ }++ const room = this.rooms.get(roomId);+ const viewer = room?.viewers.get(peerId);+ if (!room || !viewer) {+ return undefined;+ }++ const before = snapshot(room);+ this.detach(room, peerId, viewer.parentPeerId);+ viewer.parentPeerId = parentPeerId;+ const children = childPeerIds(room, parentPeerId);+ children.push(peerId);+ children.sort(+ (left, right) =>+ room.viewers.get(left)!.order - room.viewers.get(right)!.order,+ );+ return changedAssignments(before, snapshot(room));+ }++ findViewerReassignmentParent(+ roomId: string,+ peerId: string,+ connectedPeerIds: ReadonlySet<string>,+ excludedParentPeerIds: ReadonlySet<string>,+ maxDepth = MAX_PEER_RELAY_DEPTH,+ ): string | undefined {const room = this.rooms.get(roomId);const viewer = room?.viewers.get(peerId);if (@@ -269,20 +306,7 @@ export class PeerRelayTopology {subtreePeerIds,maxDepth - subtreeHeight - 1,);- if (!parentPeerId || parentPeerId === viewer.parentPeerId) {- return undefined;- }-- const before = snapshot(room);- this.detach(room, peerId, viewer.parentPeerId);- viewer.parentPeerId = parentPeerId;- const children = childPeerIds(room, parentPeerId);- children.push(peerId);- children.sort(- (left, right) =>- room.viewers.get(left)!.order - room.viewers.get(right)!.order,- );- return changedAssignments(before, snapshot(room));+ return parentPeerId === viewer.parentPeerId ? undefined : parentPeerId;}isParentOf(roomId: string, parentPeerId: string, childPeerId: string): boolean {diff --git a/src/server/signaling.ts b/src/server/signaling.tsindex 3ad09570..962ade02 100644--- a/src/server/signaling.ts+++ b/src/server/signaling.ts@@ -165,6 +165,8 @@ export class SignalingServer {this.connectionIdsByViewer.get(viewerConnectionKey(roomId, viewerPeerId),),+ setConnectionId: (roomId, viewerPeerId, connectionId) =>+ this.setViewerConnectionId(roomId, viewerPeerId, connectionId),deleteConnectionId: (roomId, viewerPeerId) =>this.deleteViewerConnectionId(roomId, viewerPeerId),getShareGeneration: (roomId) => this.shareGenerationsByRoom.get(roomId),@@ -1319,7 +1321,10 @@ export class SignalingServer {return;}- if (description?.type === "offer") {+ if (+ description?.type === "offer" &&+ selectedEdgeAuthorized !== "probe"+ ) {this.setViewerConnectionId(source.roomId,targetPeerId,diff --git a/tests/peer-relay-topology.test.ts b/tests/peer-relay-topology.test.tsindex 0d8c255a..fd0a65da 100644--- a/tests/peer-relay-topology.test.ts+++ b/tests/peer-relay-topology.test.ts@@ -695,6 +695,50 @@ describe("PeerRelayTopology", () => {expect(expectValidTree(topology, "room", "host", peers.slice(1))).toBe(3);});+ it("plans a bounded reparent without mutating until the exact parent commits", () => {+ const topology = new PeerRelayTopology();+ const peers = ["host", "a", "b", "c", "d", "e"];+ topology.setHost("room", "host", connected(...peers));+ for (const peerId of peers.slice(1)) {+ addRelayViewer(topology, "room", peerId, connected(...peers));+ }+ const before = topology.getAssignments("room");+ const excluded = new Set(["c"]);++ expect(+ topology.findViewerReassignmentParent(+ "room",+ "e",+ connected(...peers),+ excluded,+ 4,+ ),+ ).toBe("d");+ expect(topology.getAssignments("room")).toEqual(before);+ expect(+ topology.reassignViewer(+ "room",+ "e",+ connected(...peers),+ excluded,+ 4,+ "b",+ ),+ ).toBeUndefined();+ expect(topology.getAssignments("room")).toEqual(before);+ expect(+ topology.reassignViewer(+ "room",+ "e",+ connected(...peers),+ excluded,+ 4,+ "d",+ ),+ ).toBeDefined();+ expect(topology.getAssignment("room", "e")?.parentPeerId).toBe("d");+ });+it("does not mutate when every bounded reparent candidate is excluded", () => {const topology = new PeerRelayTopology();topology.setHost("room", "host", connected("host", "a", "b", "c"));diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.tsindex 01c65fd5..5b099c8a 100644--- a/tests/route-transition.test.ts+++ b/tests/route-transition.test.ts@@ -1206,6 +1206,136 @@ describe("ViewerSfuRoute", () => {expect(activatePeer).not.toHaveBeenCalledWith(peer);});+ it("prepares a second peer without replacing the active peer before commit", async () => {+ const prepared: Array<{ parent: string | null; revision?: number }> = [];+ const activatePeer = vi.fn();+ const route = new ViewerSfuRoute({+ activatePeer,+ preparePeer: (assignment, revision) => prepared.push({+ parent: assignment?.upstream.kind === "peer"+ ? assignment.upstream.peerId+ : null,+ ...(revision === undefined ? {} : { revision }),+ }),+ reconcileSfuChildren: () => undefined,+ onSfuStream: () => undefined,+ send: () => true,+ });+ const oldPeer = peerAssignment("old-parent");+ const newPeer = peerAssignment("new-parent");++ route.accept({ revision: 1, phase: "active", assignment: oldPeer });+ await vi.waitFor(() => expect(activatePeer).toHaveBeenCalledWith(oldPeer));+ activatePeer.mockClear();+ route.accept({ revision: 2, phase: "prepare", assignment: newPeer });+ expect(prepared.at(-1)).toEqual({ parent: "new-parent", revision: 2 });+ expect(activatePeer).not.toHaveBeenCalled();++ route.accept({ revision: 3, phase: "active", assignment: oldPeer });+ await vi.waitFor(() => expect(activatePeer).toHaveBeenCalledWith(oldPeer));+ expect(activatePeer).not.toHaveBeenCalledWith(newPeer, 2);+ });++ it("reports an active failure instead of promoting a failed ready peer probe", async () => {+ const sent: ClientMessage[] = [];+ const activatePeer = vi.fn(() => true);+ const route = new ViewerSfuRoute({+ activatePeer,+ reconcileSfuChildren: () => undefined,+ onSfuStream: () => undefined,+ send: (message) => { sent.push(message); return true; },+ });+ const oldPeer = peerAssignment("old-parent");+ const newPeer = peerAssignment("new-parent");++ route.accept({ revision: 1, phase: "active", assignment: oldPeer });+ await vi.waitFor(() => expect(activatePeer).toHaveBeenCalledWith(oldPeer));+ activatePeer.mockClear();+ route.accept({ revision: 2, phase: "prepare", assignment: newPeer });+ expect(route.reportPeerProbeFailure("new-parent", "failed-probe", true)).toBe(true);+ expect(sent).toContainEqual({ type: "route-failed", revision: 2,+ phase: "prepare", connectionId: "failed-probe" });++ route.accept({ revision: 2, phase: "active", assignment: newPeer });+ await vi.waitFor(() => expect(sent).toContainEqual({ type: "route-failed",+ revision: 2, phase: "active", connectionId: "failed-probe" }));+ expect(activatePeer).not.toHaveBeenCalled();+ });++ it("blocks promotion when a ready probe fails after active is accepted", async () => {+ const sent: ClientMessage[] = [];+ const activatePeer = vi.fn(() => true);+ const route = new ViewerSfuRoute({+ activatePeer,+ reconcileSfuChildren: () => undefined,+ onSfuStream: () => undefined,+ send: (message) => { sent.push(message); return true; },+ });+ const oldPeer = peerAssignment("old-parent");+ const newPeer = peerAssignment("new-parent");++ route.accept({ revision: 1, phase: "active", assignment: oldPeer });+ await vi.waitFor(() => expect(activatePeer).toHaveBeenCalledWith(oldPeer));+ activatePeer.mockClear();+ route.accept({ revision: 2, phase: "prepare", assignment: newPeer });+ route.accept({ revision: 2, phase: "active", assignment: newPeer });+ expect(route.reportPeerProbeFailure("new-parent", "accepted-failed-probe", true)).toBe(true);+ await vi.waitFor(() => expect(sent).toContainEqual({ type: "route-failed",+ revision: 2, phase: "active", connectionId: "accepted-failed-probe" }));+ expect(activatePeer).not.toHaveBeenCalled();+ });++ it("clears a failed peer probe tombstone on rollback", async () => {+ const sent: ClientMessage[] = [];+ const prepared: Array<{ parent: string | null; revision?: number }> = [];+ const route = new ViewerSfuRoute({+ activatePeer: () => true,+ preparePeer: (assignment, revision) => prepared.push({+ parent: assignment?.upstream.kind === "peer"+ ? assignment.upstream.peerId+ : null,+ ...(revision === undefined ? {} : { revision }),+ }),+ reconcileSfuChildren: () => undefined,+ onSfuStream: () => undefined,+ send: (message) => { sent.push(message); return true; },+ });+ const oldPeer = peerAssignment("old-parent");++ route.accept({ revision: 1, phase: "active", assignment: oldPeer });+ route.accept({ revision: 2, phase: "prepare", assignment: peerAssignment("new-parent") });+ route.reportPeerProbeFailure("new-parent", "rolled-back-probe", true);+ route.accept({ revision: 3, phase: "active", assignment: oldPeer });+ await vi.waitFor(() => expect(prepared.at(-1)).toEqual({ parent: "old-parent" }));+ expect(sent).not.toContainEqual(expect.objectContaining({+ phase: "active", connectionId: "rolled-back-probe",+ }));+ });++ it("clears a failed peer probe tombstone on authoritative resync", async () => {+ const sent: ClientMessage[] = [];+ const activatePeer = vi.fn(() => true);+ const route = new ViewerSfuRoute({+ activatePeer,+ reconcileSfuChildren: () => undefined,+ onSfuStream: () => undefined,+ send: (message) => { sent.push(message); return true; },+ });+ const oldPeer = peerAssignment("old-parent");+ const newPeer = peerAssignment("new-parent");++ route.accept({ revision: 1, phase: "active", assignment: oldPeer });+ await vi.waitFor(() => expect(activatePeer).toHaveBeenCalledWith(oldPeer));+ route.accept({ revision: 2, phase: "prepare", assignment: newPeer });+ route.reportPeerProbeFailure("new-parent", "resynced-probe", true);+ activatePeer.mockClear();+ await route.resyncAuthoritative({ revision: 2, phase: "active", assignment: newPeer });+ await vi.waitFor(() => expect(activatePeer).toHaveBeenCalledWith(newPeer));+ expect(sent).not.toContainEqual(expect.objectContaining({+ phase: "active", connectionId: "resynced-probe",+ }));+ });+it("requests provisional peer teardown on a newer SFU rollback", async () => {const prepared: Array<{ parent: string | null; revision?: number }> = [];const { route, subscriber } = await activateViewerSfuRoute({diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.tsindex 454acd22..7433a5ba 100644--- a/tests/server-signal.test.ts+++ b/tests/server-signal.test.ts@@ -313,6 +313,8 @@ async function startRelayRelativeFpsFixture(alternateRelayCapacity?: 0 | 1 | 2;issueSfuToken?: (peerId: string) => Promise<string>;onSfuTokenIssue?: () => void;+ prepareTimeoutMs?: number;+ hostFirstCandidate?: boolean;secondChild?: boolean;selectedEdgeTurn?: boolean;sfu?: boolean;@@ -321,6 +323,7 @@ async function startRelayRelativeFpsFixture(const harness = options.sfu? await startSfuHarness({now,+ prepareTimeoutMs: options.prepareTimeoutMs,selectedEdgeTurn: options.selectedEdgeTurn,tokenIssuer: {issueToken: async ({ peerId }) => {@@ -341,9 +344,21 @@ async function startRelayRelativeFpsFixture(harness.room,"viewer",`${prefix}-parent`,- options.secondChild ? 2 : 1,+ options.secondChild || options.hostFirstCandidate ? 2 : 1,),);+ const releasedHostSlot = options.hostFirstCandidate+ ? await openClient(harness.webSocketUrl)+ : undefined;+ if (releasedHostSlot) {+ await authenticate(+ releasedHostSlot,+ harness.room,+ "viewer",+ `${prefix}-released-host-slot`,+ 0,+ );+ }const alternate = await openClient(harness.webSocketUrl);const alternateAuth = peerAssisted(await authenticate(@@ -376,10 +391,8 @@ async function startRelayRelativeFpsFixture(kind: "peer",peerId: hostAuth.peerId,});- expect(alternateAuth.routeAssignment.upstream).toEqual({- kind: "peer",- peerId: hostAuth.peerId,- });+ expect(alternateAuth.routeAssignment.upstream).toEqual({ kind: "peer",+ peerId: options.hostFirstCandidate ? parentAuth.peerId : hostAuth.peerId });expect(childAuth.routeAssignment.upstream).toEqual({kind: "peer",peerId: parentAuth.peerId,@@ -389,10 +402,20 @@ async function startRelayRelativeFpsFixture(? { kind: "peer", peerId: parentAuth.peerId }: undefined,);- const routeRevision = secondChildAuth?.routeRevision ?? childAuth.routeRevision;+ let routeRevision = secondChildAuth?.routeRevision ?? childAuth.routeRevision;if (secondChildAuth) {await nextActiveRouteRevision(child, routeRevision);}+ if (releasedHostSlot) {+ releasedHostSlot.socket.close();+ const [releasedRoute] = await Promise.all([+ nextActiveRouteAfter(child, routeRevision),+ nextActiveRouteAfter(host, routeRevision),+ nextActiveRouteAfter(parent, routeRevision),+ nextActiveRouteAfter(alternate, routeRevision),+ ]);+ routeRevision = releasedRoute.revision;+ }const parentConnectionId = `${prefix}_parent_connection`;await sendTestOffer(host, parent, parentAuth.peerId, parentConnectionId);@@ -845,6 +868,44 @@ async function nextPreparedRoute(client: TestClient) {}}+async function completePreparedPeerMigration(+ viewer: TestClient,+ newParent: TestClient,+ viewerPeerId: string,+ newParentPeerId: string,+ previousRevision: number,+ connectionId: string,+) {+ const [viewerPrepare, parentPrepare] = await Promise.all([+ nextPreparedRoute(viewer),+ nextPreparedRoute(newParent),+ ]);+ expect(viewerPrepare).toMatchObject({+ phase: "prepare",+ assignment: { upstream: { kind: "peer", peerId: newParentPeerId } },+ });+ expect(parentPrepare.revision).toBe(viewerPrepare.revision);+ await sendTestOffer(newParent, viewer, viewerPeerId, connectionId);+ viewer.socket.send(JSON.stringify({+ type: "signal",+ targetPeerId: newParentPeerId,+ payload: {+ kind: "description",+ connectionId,+ description: { type: "answer", sdp: "v=0\r\n" },+ },+ }));+ expect(await newParent.inbox.next("signal")).toMatchObject({+ fromPeerId: viewerPeerId,+ });+ viewer.socket.send(JSON.stringify({+ type: "route-ready",+ revision: viewerPrepare.revision,+ phase: "prepare",+ }));+ return nextActiveRouteAfter(viewer, previousRevision);+}+async function nextActiveRouteRevision(client: TestClient, revision: number) {while (true) {const message = await client.inbox.next("route-update");@@ -3280,7 +3341,14 @@ describe("WebSocket signaling", () => {}now += 2_000;}- const moved = await nextActiveRouteAfter(viewer, active.revision);+ const moved = await completePreparedPeerMigration(+ viewer,+ unrelatedParent,+ viewerAuth.peerId,+ unrelatedParentAuth.peerId,+ active.revision,+ "quality_guard_probe",+ );expect(acceptedParentEvidence).toHaveBeenCalledTimes(3);expect(moved.assignment.upstream).toEqual({kind: "peer",@@ -3316,34 +3384,25 @@ describe("WebSocket signaling", () => {await correlateRelayChildFps(fixture, sequence, 10);now += 2_000;}- const moved = await nextActiveRouteAfter(+ const moved = await completePreparedPeerMigration(fixture.child,+ fixture.alternate,+ fixture.childAuth.peerId,+ fixture.alternateAuth.peerId,fixture.routeRevision,+ "relative_peer_move_probe",);expect(moved.assignment.upstream).toEqual({kind: "peer",peerId: fixture.alternateAuth.peerId,});- const failedAlternateConnection = "relative_peer_move_failed_alternate";- fixture.alternate.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: fixture.childAuth.peerId,- payload: {- kind: "description",- connectionId: failedAlternateConnection,- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- await fixture.child.inbox.next("signal");fixture.child.socket.send(JSON.stringify({type: "route-failed",revision: moved.revision,phase: "active",- connectionId: failedAlternateConnection,+ connectionId: "relative_peer_move_probe",}),);const recovered = await nextActiveRouteAfter(fixture.child, moved.revision);@@ -3353,6 +3412,146 @@ describe("WebSocket signaling", () => {});});+ it("skips an eligible Host and probes the later peer Viewer", async () => {+ let now = 120_000;+ const fixture = await startRelayRelativeFpsFixture(+ "quality_skip_host",+ () => now,+ { alternateRelayCapacity: 1, hostFirstCandidate: true },+ );+ const advanceWindow = () => { now += 2_000; };+ await confirmRelayChildSevere(+ fixture,+ fixture.child,+ fixture.childConnectionId,+ advanceWindow,+ );+ const hostRoute = fixture.host.inbox.next("route-update");+ const moved = await completePreparedPeerMigration(+ fixture.child,+ fixture.alternate,+ fixture.childAuth.peerId,+ fixture.alternateAuth.peerId,+ fixture.routeRevision,+ "quality_skip_host_probe",+ );+ expect(await hostRoute).toMatchObject({+ phase: "active",+ revision: moved.revision,+ });+ expect(moved.assignment.upstream).toEqual({+ kind: "peer",+ peerId: fixture.alternateAuth.peerId,+ });+ });++ it("keeps the old edge when only the Host is a capable alternate", async () => {+ let now = 125_000;+ const fixture = await startRelayRelativeFpsFixture(+ "quality_only_host",+ () => now,+ { alternateRelayCapacity: 0, hostFirstCandidate: true },+ );+ const advanceWindow = () => { now += 2_000; };+ await confirmRelayChildSevere(+ fixture,+ fixture.child,+ fixture.childConnectionId,+ advanceWindow,+ );+ await Promise.all([+ expect(fixture.child.inbox.next("route-update", 40)).rejects.toThrow("Timed out"),+ expect(fixture.host.inbox.next("route-update", 40)).rejects.toThrow("Timed out"),+ expect(fixture.alternate.inbox.next("route-update", 40)).rejects.toThrow("Timed out"),+ ]);+ });++ it("keeps the old edge when only the Host and an SFU root are capable", async () => {+ let now = 128_000;+ const harness = await startSfuHarness({+ now: () => now,+ tokenIssuer: { async issueToken({ peerId }) { return `token-${peerId}`; } },+ });+ const active = await activateSingleViewerSfu(+ harness.webSocketUrl,+ harness.room,+ "quality_only_host_sfu_root",+ );+ active.viewer.socket.send(JSON.stringify({+ type: "relay-capacity",+ downstreamEdges: 2,+ }));+ await new Promise<void>((resolve) => setTimeout(resolve, 0));++ const hostFiller = await openClient(harness.webSocketUrl);+ const hostFillerAuth = peerAssisted(await authenticate(+ hostFiller, harness.room, "viewer", "quality-host-filler", 0,+ ));+ expect(hostFillerAuth.routeAssignment.upstream).toEqual({+ kind: "peer",+ peerId: active.hostAuth.peerId,+ });+ const parent = await openClient(harness.webSocketUrl);+ const parentAuth = peerAssisted(await authenticate(+ parent, harness.room, "viewer", "quality-sfu-root-parent", 1,+ ));+ expect(parentAuth.routeAssignment.upstream).toEqual({+ kind: "peer",+ peerId: active.viewerAuth.peerId,+ });+ const rootFiller = await openClient(harness.webSocketUrl);+ const rootFillerAuth = peerAssisted(await authenticate(+ rootFiller, harness.room, "viewer", "quality-root-filler", 0,+ ));+ expect(rootFillerAuth.routeAssignment.upstream).toEqual({+ kind: "peer",+ peerId: active.viewerAuth.peerId,+ });+ const child = await openClient(harness.webSocketUrl);+ const childAuth = peerAssisted(await authenticate(+ child, harness.room, "viewer", "quality-sfu-root-child", 0,+ ));+ expect(childAuth.routeAssignment.upstream).toEqual({+ kind: "peer",+ peerId: parentAuth.peerId,+ });++ const parentConnectionId = "quality_sfu_root_parent_connection";+ await sendTestOffer(+ active.viewer,+ parent,+ parentAuth.peerId,+ parentConnectionId,+ );+ const childConnectionId = "quality_sfu_root_child_connection";+ await sendTestOffer(parent, child, childAuth.peerId, childConnectionId);+ hostFiller.socket.close();+ const hostFreed = await nextActiveRouteAfter(child, childAuth.routeRevision);+ rootFiller.socket.close();+ const rootFreed = await nextActiveRouteAfter(child, hostFreed.revision);+ await Promise.all([+ nextActiveRouteRevision(active.host, rootFreed.revision),+ nextActiveRouteRevision(active.viewer, rootFreed.revision),+ nextActiveRouteRevision(parent, rootFreed.revision),+ ]);++ for (let sequence = 0; sequence < 3; sequence += 1) {+ child.socket.send(JSON.stringify(viewerQualityEvidenceWithMetrics(+ childConnectionId,+ rootFreed.revision,+ sequence,+ { framesDecodedDelta: 0 },+ )));+ await correlateParentEdgeQualityEvidence(parent);+ now += 2_000;+ }+ await Promise.all([+ expect(child.inbox.next("route-update", 40)).rejects.toThrow("Timed out"),+ expect(active.host.inbox.next("route-update", 40)).rejects.toThrow("Timed out"),+ expect(active.viewer.inbox.next("route-update", 40)).rejects.toThrow("Timed out"),+ ]);+ });+it("keeps the old relay edge when relative FPS has no alternate peer", async () => {let now = 130_000;let issuedSfuTokens = 0;@@ -3414,15 +3613,16 @@ describe("WebSocket signaling", () => {await new Promise<void>((resolve) => setTimeout(resolve, 0));now += 2_000;}- const prepare = await nextPreparedRoute(fixture.child);- expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });- expect(await fixture.child.inbox.next("sfu-config")).toMatchObject({- revision: prepare.revision,- });- expect(issuedSfuTokens).toBeGreaterThan(0);+ await expect(+ fixture.child.inbox.next("route-update", 40),+ ).rejects.toThrow("Timed out");+ await expect(+ fixture.child.inbox.next("sfu-config", 40),+ ).rejects.toThrow("Timed out");+ expect(issuedSfuTokens).toBe(0);});- it("keeps severe SFU fallback when the second child quarantines a relay", async () => {+ it("keeps a severe child on its old edge when no peer alternate exists", async () => {let now = 142_000;const fixture = await startRelayRelativeFpsFixture("relay_parent_second_severe",@@ -3440,11 +3640,12 @@ describe("WebSocket signaling", () => {advanceWindow,);- const prepare = await nextPreparedRoute(fixture.secondChild!);- expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });- expect(await fixture.secondChild!.inbox.next("sfu-config")).toMatchObject({- revision: prepare.revision,- });+ await expect(+ fixture.secondChild!.inbox.next("route-update", 40),+ ).rejects.toThrow("Timed out");+ await expect(+ fixture.secondChild!.inbox.next("sfu-config", 40),+ ).rejects.toThrow("Timed out");});it("gives a severe trigger the sole alternate before evacuating siblings", async () => {@@ -3478,9 +3679,13 @@ describe("WebSocket signaling", () => {advanceWindow,);- const triggerMoved = await nextActiveRouteAfter(+ const triggerMoved = await completePreparedPeerMigration(fixture.secondChild!,+ fixture.alternate,+ fixture.secondChildAuth!.peerId,+ fixture.alternateAuth.peerId,fixture.routeRevision,+ "relay_parent_severe_peer_probe",);expect(triggerMoved.assignment.upstream).toEqual({kind: "peer",@@ -3497,26 +3702,15 @@ describe("WebSocket signaling", () => {expect(issuedSfuTokens).toBe(0);});- it("keeps quarantine stable while severe fallback waits on selected TURN", async () => {+ it("does not escalate soft quality recovery to SFU or selected TURN", async () => {let now = 144_500;- let releaseTokens!: () => void;- let markTokenStarted!: () => void;- const tokenBarrier = new Promise<void>((resolve) => {- releaseTokens = resolve;- });- const tokenStarted = new Promise<void>((resolve) => {- markTokenStarted = resolve;- });+ let issuedSfuTokens = 0;const fixture = await startRelayRelativeFpsFixture("relay_parent_severe_selected_turn",() => now,{alternateRelayCapacity: 0,- issueSfuToken: async () => {- markTokenStarted();- await tokenBarrier;- throw new Error("offline");- },+ onSfuTokenIssue: () => { issuedSfuTokens += 1; },secondChild: true,selectedEdgeTurn: true,sfu: true,@@ -3532,52 +3726,13 @@ describe("WebSocket signaling", () => {fixture.secondChildConnectionId,advanceWindow,);- await tokenStarted;-- const takeoverConnectionId = "relay_parent_selected_turn_takeover";- await sendTestOffer(- fixture.parent,- fixture.secondChild!,- fixture.secondChildAuth!.peerId,- takeoverConnectionId,- );- fixture.secondChild!.socket.send(JSON.stringify({- type: "route-failed",- revision: fixture.routeRevision,- phase: "active",- connectionId: takeoverConnectionId,- }));- await new Promise<void>((resolve) => setTimeout(resolve, 0));- releaseTokens();-- const [viewerGrant, parentGrant] = await Promise.all([- fixture.secondChild!.inbox.next("selected-edge-turn"),- fixture.parent.inbox.next("selected-edge-turn"),- ]);- expect(parentGrant).toEqual(viewerGrant);- expect(viewerGrant).toMatchObject({- parentPeerId: fixture.parentAuth.peerId,- viewerPeerId: fixture.secondChildAuth!.peerId,- oldConnectionId: takeoverConnectionId,- });- await Promise.all([- nextActiveRouteRevision(fixture.child, viewerGrant.revision),- nextActiveRouteRevision(fixture.secondChild!, viewerGrant.revision),- ]);-- fixture.alternate.socket.send(JSON.stringify({- type: "relay-capacity",- downstreamEdges: 1,- }));- await new Promise<void>((resolve) => setTimeout(resolve, 0));- await Promise.all([- expect(fixture.child.inbox.next("route-update", 40)).rejects.toThrow(- "Timed out",- ),- expect(fixture.secondChild!.inbox.next("route-update", 40)).rejects.toThrow(- "Timed out",- ),- ]);+ await expect(+ fixture.secondChild!.inbox.next("sfu-config", 40),+ ).rejects.toThrow("Timed out");+ await expect(+ fixture.secondChild!.inbox.next("selected-edge-turn", 40),+ ).rejects.toThrow("Timed out");+ expect(issuedSfuTokens).toBe(0);});it("quarantines a relay only after two children and restores it lazily", async () => {@@ -3666,9 +3821,13 @@ describe("WebSocket signaling", () => {now += 2_000;};await confirmRelayParentChildRelativeFps(fixture, 0, advanceWindow);- const firstMoved = await nextActiveRouteAfter(+ const firstMoved = await completePreparedPeerMigration(fixture.child,+ fixture.alternate,+ fixture.childAuth.peerId,+ fixture.alternateAuth.peerId,fixture.routeRevision,+ "relay_parent_peer_only_probe",);expect(firstMoved.assignment.upstream).toEqual({kind: "peer",@@ -3704,26 +3863,13 @@ describe("WebSocket signaling", () => {).rejects.toThrow("Timed out");});- it("defers quarantine evacuation until a pending severe SFU prepare commits", async () => {+ it("allows only one peer quality migration per room", async () => {let now = 200_000;- let releaseTokens!: () => void;- let markTokenStarted!: () => void;- const tokenBarrier = new Promise<void>((resolve) => {- releaseTokens = resolve;- });- const tokenStarted = new Promise<void>((resolve) => {- markTokenStarted = resolve;- });const fixture = await startRelayRelativeFpsFixture("relay_parent_pending_severe",() => now,{- alternateRelayCapacity: 0,- issueSfuToken: async (peerId) => {- markTokenStarted();- await tokenBarrier;- return `token-${peerId}`;- },+ alternateRelayCapacity: 1,secondChild: true,sfu: true,},@@ -3737,53 +3883,34 @@ describe("WebSocket signaling", () => {fixture.childConnectionId,advanceWindow,);- await tokenStarted;-- fixture.alternate.socket.send(JSON.stringify({- type: "relay-capacity",- downstreamEdges: 2,- }));- await new Promise<void>((resolve) => setTimeout(resolve, 0));await confirmRelayChildSevere(fixture,fixture.secondChild!,fixture.secondChildConnectionId,advanceWindow,);- releaseTokens();-- const [hostPrepare, parentPrepare, childPrepare] = await Promise.all([- nextPreparedRoute(fixture.host),- nextPreparedRoute(fixture.parent),- nextPreparedRoute(fixture.child),- ]);- await Promise.all([- fixture.host.inbox.next("sfu-config"),- fixture.parent.inbox.next("sfu-config"),- fixture.child.inbox.next("sfu-config"),- ]);- expect(parentPrepare.revision).toBe(childPrepare.revision);- expect(hostPrepare.revision).toBe(childPrepare.revision);- for (const client of [fixture.host, fixture.parent, fixture.child]) {- client.socket.send(JSON.stringify({- type: "route-ready",- revision: childPrepare.revision,- phase: "prepare",- }));- }-- const childActive = await nextActiveRouteRevision(+ await expect(+ fixture.secondChild!.inbox.next("route-update", 40),+ ).rejects.toThrow("Timed out");+ const childActive = await completePreparedPeerMigration(fixture.child,- childPrepare.revision,+ fixture.alternate,+ fixture.childAuth.peerId,+ fixture.alternateAuth.peerId,+ fixture.routeRevision,+ "relay_parent_pending_probe",);- expect(childActive.assignment.upstream).toEqual({ kind: "sfu" });- const siblingMoved = await nextActiveRouteAfter(+ expect(childActive.assignment.upstream).toEqual({+ kind: "peer",+ peerId: fixture.alternateAuth.peerId,+ });+ const siblingStayed = await nextActiveRouteRevision(fixture.secondChild!,- childPrepare.revision,+ childActive.revision,);- expect(siblingMoved.assignment.upstream).toEqual({+ expect(siblingStayed.assignment.upstream).toEqual({kind: "peer",- peerId: fixture.alternateAuth.peerId,+ peerId: fixture.parentAuth.peerId,});});@@ -3807,9 +3934,13 @@ describe("WebSocket signaling", () => {await new Promise<void>((resolve) => setTimeout(resolve, 0));await confirmRelayParentChildRelativeFps(fixture, 1, advanceWindow);- const secondMoved = await nextActiveRouteAfter(+ const secondMoved = await completePreparedPeerMigration(secondChild,+ fixture.alternate,+ fixture.secondChildAuth!.peerId,+ fixture.alternateAuth.peerId,fixture.routeRevision,+ "relay_parent_stale_gap_probe",);expect(secondMoved.assignment.upstream).toEqual({kind: "peer",@@ -3880,9 +4011,13 @@ describe("WebSocket signaling", () => {await new Promise<void>((resolve) => setTimeout(resolve, 0));await confirmRelayParentChildRelativeFps(fixture, 1, advanceWindow);- const secondMoved = await nextActiveRouteAfter(+ const secondMoved = await completePreparedPeerMigration(secondChild,+ fixture.alternate,+ fixture.secondChildAuth!.peerId,+ fixture.alternateAuth.peerId,fixture.routeRevision,+ `${prefix}_probe`,);expect(secondMoved.assignment.upstream).toEqual({kind: "peer",@@ -4067,7 +4202,7 @@ describe("WebSocket signaling", () => {},);- it("keeps severe zero-decode quality fallback eligible for SFU", async () => {+ it("keeps severe zero-decode quality on the old edge without an alternate", async () => {let now = 190_000;const harness = await startSfuHarness({now: () => now,@@ -4107,11 +4242,12 @@ describe("WebSocket signaling", () => {await correlateParentEdgeQualityEvidence(host);now += 2_000;}- const prepare = await nextPreparedRoute(viewer);- expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });- expect(await viewer.inbox.next("sfu-config")).toMatchObject({- revision: prepare.revision,- });+ await expect(viewer.inbox.next("route-update", 40)).rejects.toThrow(+ "Timed out",+ );+ await expect(viewer.inbox.next("sfu-config", 40)).rejects.toThrow(+ "Timed out",+ );expect(hostAuth.routeAssignment.upstream).toEqual({ kind: "none" });});@@ -4341,9 +4477,13 @@ describe("WebSocket signaling", () => {packetsSentDelta: 1_500,reason: "cpu",});- const movedRoot = await nextActiveRouteAfter(+ const movedRoot = await completePreparedPeerMigration(subtreeRoot,+ alternateParent,+ subtreeRootAuth.peerId,+ alternateParentAuth.peerId,subtreeLeafAuth.routeRevision,+ "quality_route_probe",);expect(movedRoot.assignment.upstream).toEqual({kind: "peer",@@ -4506,10 +4646,7 @@ describe("WebSocket signaling", () => {await expect(viewer.inbox.next("error", 40)).rejects.toThrow("Timed out");now += 2_000;await sendBadWindow(4);- expect(await viewer.inbox.next("error")).toMatchObject({- code: "PEER_NOT_FOUND",- message: "No media fallback route is available",- });+ await expect(viewer.inbox.next("error", 40)).rejects.toThrow("Timed out");expect(viewerAuth.routeAssignment.upstream).toEqual({kind: "peer",peerId: hostAuth.peerId,@@ -4579,216 +4716,157 @@ describe("WebSocket signaling", () => {now += 2_000;sendBadC(4);await correlateParentEdgeQualityEvidence(host);- expect(await viewer.inbox.next("error")).toMatchObject({- code: "PEER_NOT_FOUND",- message: "No media fallback route is available",- });+ await expect(viewer.inbox.next("error", 40)).rejects.toThrow("Timed out");expect(viewerAuth.routeAssignment.upstream).toEqual({kind: "peer",peerId: hostAuth.peerId,});});- it("keeps a pending quality SFU prepare after the same intent becomes a real failure", async () => {+ it("keeps the old edge when a peer quality probe fails", async () => {let now = 250_000;- let releaseTokens!: () => void;- let markTokenStarted!: () => void;- const tokenBarrier = new Promise<void>((resolve) => {- releaseTokens = resolve;- });- const tokenStarted = new Promise<void>((resolve) => {- markTokenStarted = resolve;- });- const harness = await startSfuHarness({- now: () => now,- tokenIssuer: {- async issueToken(request) {- markTokenStarted();- await tokenBarrier;- return `token-${request.peerId}`;- },- },- });- const host = await openClient(harness.webSocketUrl);- peerAssisted(- await authenticate(host, harness.room, "host", "quality-takeover-host"),+ const fixture = await startRelayRelativeFpsFixture(+ "quality_probe_failure",+ () => now,+ { alternateRelayCapacity: 1 },);- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = peerAssisted(- await authenticate(- viewer,- harness.room,- "viewer",- "quality-takeover-viewer",- ),+ const advanceWindow = () => { now += 2_000; };+ await confirmRelayChildSevere(+ fixture,+ fixture.child,+ fixture.childConnectionId,+ advanceWindow,);- await nextActiveRouteRevision(host, viewerAuth.routeRevision);- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "description",- connectionId: "quality_takeover_connection",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),+ const [viewerPrepare, parentPrepare] = await Promise.all([+ nextPreparedRoute(fixture.child),+ nextPreparedRoute(fixture.alternate),+ ]);+ expect(parentPrepare.revision).toBe(viewerPrepare.revision);+ await sendTestOffer(+ fixture.parent,+ fixture.child,+ fixture.childAuth.peerId,+ fixture.childConnectionId,);- await viewer.inbox.next("signal");- for (let sequence = 0; sequence < 3; sequence += 1) {- viewer.socket.send(- JSON.stringify(- viewerQualityEvidenceWithMetrics(- "quality_takeover_connection",- viewerAuth.routeRevision,- sequence,- { framesDecodedDelta: 0 },- ),- ),- );- await correlateParentEdgeQualityEvidence(host);- now += 2_000;- }- await tokenStarted;-- viewer.socket.send(- JSON.stringify({- type: "route-failed",- revision: viewerAuth.routeRevision,- phase: "active",- connectionId: "quality_takeover_connection",- }),+ const probeConnectionId = "quality_probe_failure_candidate";+ await sendTestOffer(+ fixture.alternate,+ fixture.child,+ fixture.childAuth.peerId,+ probeConnectionId,);- viewer.socket.send(- JSON.stringify({- type: "set-quality-settings",- qualitySettings: defaultQualitySettings,- }),+ fixture.child.socket.send(JSON.stringify({+ type: "route-failed",+ revision: viewerPrepare.revision,+ phase: "prepare",+ connectionId: probeConnectionId,+ }));+ const rollback = await nextActiveRouteAfter(+ fixture.child,+ viewerPrepare.revision,);- expect(await viewer.inbox.next("error")).toMatchObject({- code: "FORBIDDEN",- });- releaseTokens();-- const prepare = await nextPreparedRoute(viewer);- expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });- expect(await viewer.inbox.next("sfu-config")).toMatchObject({- revision: prepare.revision,+ expect(rollback.assignment.upstream).toEqual({+ kind: "peer",+ peerId: fixture.parentAuth.peerId,});+ await sendTestOffer(+ fixture.parent,+ fixture.child,+ fixture.childAuth.peerId,+ "quality_probe_failure_old_edge",+ );});- it("aborts a quality SFU prepare after next-generation C removes its intent", async () => {+ it("keeps the old edge when a peer quality probe times out", async () => {let now = 300_000;- let releaseTokens!: () => void;- let holdTokens = true;- const tokenBarrier = new Promise<void>((resolve) => {- releaseTokens = resolve;- });- const harness = await startSfuHarness({- now: () => now,- tokenIssuer: {- async issueToken(request) {- if (holdTokens) {- await tokenBarrier;- }- return `token-${request.peerId}`;- },+ let issuedSfuTokens = 0;+ const fixture = await startRelayRelativeFpsFixture(+ "quality_probe_timeout",+ () => now,+ {+ alternateRelayCapacity: 1,+ onSfuTokenIssue: () => { issuedSfuTokens += 1; },+ prepareTimeoutMs: 20,+ sfu: true,},- });- const host = await openClient(harness.webSocketUrl);- const hostAuth = peerAssisted(- await authenticate(host, harness.room, "host", "quality-guard-host"),- );- const viewer = await openClient(harness.webSocketUrl);- const viewerAuth = peerAssisted(- await authenticate(- viewer,- harness.room,- "viewer",- "quality-guard-viewer",- ),);- await nextActiveRouteRevision(host, viewerAuth.routeRevision);-- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "description",- connectionId: "quality_guard_original",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),- );- await viewer.inbox.next("signal");- for (let sequence = 0; sequence < 3; sequence += 1) {- viewer.socket.send(- JSON.stringify(- viewerQualityEvidenceWithMetrics(- "quality_guard_original",- viewerAuth.routeRevision,- sequence,- { framesDecodedDelta: 0 },- ),- ),- );- await correlateParentEdgeQualityEvidence(host);- now += 2_000;- }-- host.socket.send(- JSON.stringify({- type: "signal",- targetPeerId: viewerAuth.peerId,- payload: {- kind: "description",- connectionId: "quality_guard_replaced",- description: { type: "offer", sdp: "v=0\r\n" },- },- }),+ const advanceWindow = () => { now += 2_000; };+ await confirmRelayChildSevere(+ fixture,+ fixture.child,+ fixture.childConnectionId,+ advanceWindow,);- await viewer.inbox.next("signal");- viewer.socket.send(- JSON.stringify(- viewerQualityEvidence(- "quality_guard_replaced",- viewerAuth.routeRevision,- 0,- ),- ),+ const [viewerPrepare, parentPrepare] = await Promise.all([+ nextPreparedRoute(fixture.child),+ nextPreparedRoute(fixture.alternate),+ ]);+ expect(parentPrepare.revision).toBe(viewerPrepare.revision);+ await sendTestOffer(+ fixture.parent,+ fixture.child,+ fixture.childAuth.peerId,+ fixture.childConnectionId,);- expect(await host.inbox.next("viewer-quality-evidence")).toMatchObject({- guard: { connectionId: "quality_guard_replaced" },- sequence: 0,- });- holdTokens = false;- releaseTokens();-const rollback = await nextActiveRouteAfter(- viewer,- viewerAuth.routeRevision,+ fixture.child,+ viewerPrepare.revision,);- expect(rollback.assignment).toMatchObject({- upstream: { kind: "peer", peerId: hostAuth.peerId },- sfuPublicationGeneration: null,+ expect(rollback.assignment.upstream).toEqual({+ kind: "peer",+ peerId: fixture.parentAuth.peerId,});- await expect(viewer.inbox.next("sfu-config", 40)).rejects.toThrow(+ await expect(fixture.child.inbox.next("sfu-config", 40)).rejects.toThrow("Timed out",);+ expect(issuedSfuTokens).toBe(0);+ });- viewer.socket.send(- JSON.stringify({- type: "route-failed",- revision: rollback.revision,- phase: "active",- connectionId: "quality_guard_replaced",- }),+ it("lets another viewer hard failure preempt a soft peer probe", async () => {+ let now = 320_000;+ const fixture = await startRelayRelativeFpsFixture(+ "quality_probe_hard_preemption",+ () => now,+ { alternateRelayCapacity: 1, secondChild: true },+ );+ const advanceWindow = () => { now += 2_000; };+ await confirmRelayChildSevere(+ fixture,+ fixture.child,+ fixture.childConnectionId,+ advanceWindow,);- const prepare = await nextPreparedRoute(viewer);- expect(prepare.assignment.upstream).toEqual({ kind: "sfu" });- expect(await viewer.inbox.next("sfu-config")).toMatchObject({- revision: prepare.revision,+ const [viewerPrepare, parentPrepare] = await Promise.all([+ nextPreparedRoute(fixture.child),+ nextPreparedRoute(fixture.alternate),+ ]);+ expect(parentPrepare.revision).toBe(viewerPrepare.revision);++ fixture.secondChild!.socket.send(JSON.stringify({+ type: "route-failed",+ revision: fixture.routeRevision,+ phase: "active",+ connectionId: fixture.secondChildConnectionId,+ }));+ const [softRollback, candidateRollback, hardRollback] = await Promise.all([+ nextActiveRouteAfter(fixture.child, viewerPrepare.revision),+ nextActiveRouteAfter(fixture.alternate, viewerPrepare.revision),+ nextActiveRouteAfter(fixture.secondChild!, viewerPrepare.revision),+ ]);+ expect(softRollback.assignment.upstream).toEqual({+ kind: "peer",+ peerId: fixture.parentAuth.peerId,+ });+ expect(candidateRollback.revision).toBe(softRollback.revision);+ expect(hardRollback.revision).toBe(softRollback.revision);++ const hardMoved = await nextActiveRouteAfter(+ fixture.secondChild!,+ hardRollback.revision,+ );+ expect(hardMoved.assignment.upstream).toEqual({+ kind: "peer",+ peerId: fixture.alternateAuth.peerId,});});