Kaynağa Gözat

fix(video): 持久化SIP终止证据并按代次归还媒体资源

Kazerin 3 hafta önce
ebeveyn
işleme
a58b01eedd
28 değiştirilmiş dosya ile 3533 ekleme ve 569 silme
  1. 3 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/IInviteStreamService.java
  2. 11 3
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/DeviceServiceImpl.java
  3. 24 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/InviteStreamServiceImpl.java
  4. 166 110
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/PlayServiceImpl.java
  5. 25 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/PendingSipInvite.java
  6. 132 9
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SSRCFactory.java
  7. 269 34
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipInviteSessionManager.java
  8. 46 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRedisCompareAndSet.java
  9. 49 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRequestBinding.java
  10. 26 6
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/SIPProcessorObserver.java
  11. 78 14
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/cmd/impl/SIPCommander.java
  12. 13 8
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/event/request/impl/ByeRequestProcessor.java
  13. 100 62
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/event/response/impl/InviteResponseProcessor.java
  14. 213 95
      video-service/src/main/java/com/ruoyi/wvp/service/impl/RtpServerServiceImpl.java
  15. 2 1
      video-service/src/main/java/com/zksy/video/lifecycle/Gb28181LifecycleMedia.java
  16. 5 2
      video-service/src/main/java/com/zksy/video/lifecycle/ManualLifecycleMedia.java
  17. 7 1
      video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleService.java
  18. 247 0
      video-service/src/main/java/com/zksy/video/lifecycle/VideoStopReceipts.java
  19. 92 85
      video-service/src/test/java/com/zksy/video/lifecycle/AdoptedGbDeepSeamTest.java
  20. 261 0
      video-service/src/test/java/com/zksy/video/lifecycle/FakeStringRedis.java
  21. 5 3
      video-service/src/test/java/com/zksy/video/lifecycle/Gb28181LifecycleMediaTest.java
  22. 442 0
      video-service/src/test/java/com/zksy/video/lifecycle/LateSipRecoveryTest.java
  23. 410 0
      video-service/src/test/java/com/zksy/video/lifecycle/LegacyRtpLifecycleCompatibilityTest.java
  24. 258 132
      video-service/src/test/java/com/zksy/video/lifecycle/ManagedGbDeepSeamTest.java
  25. 8 4
      video-service/src/test/java/com/zksy/video/lifecycle/ManualLifecycleMediaTest.java
  26. 179 0
      video-service/src/test/java/com/zksy/video/lifecycle/SsrcAllocationTokenTest.java
  27. 18 0
      video-service/src/test/java/com/zksy/video/lifecycle/VideoLifecycleRaceTest.java
  28. 444 0
      video-service/src/test/java/com/zksy/video/lifecycle/VideoStopReceiptRestartTest.java

+ 3 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/IInviteStreamService.java

@@ -34,6 +34,9 @@ public interface IInviteStreamService {
      * 移除点播的状态信息
      * 移除点播的状态信息
      */
      */
     void removeInviteInfo(InviteInfo inviteInfo);
     void removeInviteInfo(InviteInfo inviteInfo);
+
+    /** Compare the original allocation, then atomically delete only the observed raw hash value. */
+    boolean removeInviteInfoIfSame(InviteInfo expected);
     /**
     /**
      * 移除点播的状态信息
      * 移除点播的状态信息
      */
      */

+ 11 - 3
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/DeviceServiceImpl.java

@@ -3,6 +3,7 @@ package com.ruoyi.wvp.gb28181.service.impl;
 import com.alibaba.fastjson2.JSON;
 import com.alibaba.fastjson2.JSON;
 import com.baomidou.dynamic.datasource.annotation.DS;
 import com.baomidou.dynamic.datasource.annotation.DS;
 import com.ruoyi.wvp.common.CommonCallback;
 import com.ruoyi.wvp.common.CommonCallback;
+import com.ruoyi.wvp.common.InviteInfo;
 import com.ruoyi.wvp.common.VideoManagerConstants;
 import com.ruoyi.wvp.common.VideoManagerConstants;
 import com.ruoyi.wvp.common.enums.ChannelDataType;
 import com.ruoyi.wvp.common.enums.ChannelDataType;
 import com.ruoyi.wvp.conf.DynamicTask;
 import com.ruoyi.wvp.conf.DynamicTask;
@@ -19,6 +20,7 @@ import com.ruoyi.wvp.gb28181.transmit.event.request.impl.message.response.cmd.Ca
 import com.ruoyi.wvp.mapper.DeviceChannelMapper;
 import com.ruoyi.wvp.mapper.DeviceChannelMapper;
 import com.ruoyi.wvp.mapper.DeviceMapper;
 import com.ruoyi.wvp.mapper.DeviceMapper;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
 import com.ruoyi.wvp.storager.IRedisCatchStorage;
 import com.ruoyi.wvp.storager.IRedisCatchStorage;
 import com.ruoyi.wvp.utils.DateUtil;
 import com.ruoyi.wvp.utils.DateUtil;
 import com.zksy.common.enums.ErrorCode;
 import com.zksy.common.enums.ErrorCode;
@@ -79,6 +81,9 @@ public class DeviceServiceImpl implements IDeviceService {
     @Autowired
     @Autowired
     private IMediaServerService mediaServerService;
     private IMediaServerService mediaServerService;
 
 
+    @Autowired
+    private RtpServerServiceImpl rtpServerService;
+
     private Device getDeviceByDeviceIdFromDb(String deviceId) {
     private Device getDeviceByDeviceIdFromDb(String deviceId) {
         return deviceMapper.getDeviceByDeviceId(deviceId);
         return deviceMapper.getDeviceByDeviceId(deviceId);
     }
     }
@@ -197,9 +202,12 @@ public class DeviceServiceImpl implements IDeviceService {
         List<SsrcTransaction> ssrcTransactions = sessionManager.getSsrcTransactionByDeviceId(deviceId);
         List<SsrcTransaction> ssrcTransactions = sessionManager.getSsrcTransactionByDeviceId(deviceId);
         if (ssrcTransactions != null && ssrcTransactions.size() > 0) {
         if (ssrcTransactions != null && ssrcTransactions.size() > 0) {
             for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
             for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
-                mediaServerService.releaseSsrc(ssrcTransaction.getMediaServerId(), ssrcTransaction.getSsrc());
-                mediaServerService.closeRTPServer(ssrcTransaction.getMediaServerId(), ssrcTransaction.getStream());
-                sessionManager.removeByCallId(ssrcTransaction.getCallId());
+                InviteInfo invite = inviteStreamService.getInviteInfo(ssrcTransaction.getType(),
+                        ssrcTransaction.getChannelId(), ssrcTransaction.getStream());
+                if (!rtpServerService.closeRTPServerForSession(ssrcTransaction, invite)) continue;
+                if (invite != null && !inviteStreamService.removeInviteInfoIfSame(invite)) continue;
+                // Local loss detection is not SIP completion; retain durable receipts and original dialog there.
+                sessionManager.removeIfSame(ssrcTransaction);
             }
             }
         }
         }
         // 移除订阅
         // 移除订阅

+ 24 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/InviteStreamServiceImpl.java

@@ -8,6 +8,7 @@ import com.ruoyi.wvp.gb28181.bean.Device;
 import com.ruoyi.wvp.mapper.DeviceChannelMapper;
 import com.ruoyi.wvp.mapper.DeviceChannelMapper;
 import com.ruoyi.wvp.mapper.DeviceMapper;
 import com.ruoyi.wvp.mapper.DeviceMapper;
 import com.ruoyi.wvp.gb28181.service.IInviteStreamService;
 import com.ruoyi.wvp.gb28181.service.IInviteStreamService;
+import com.ruoyi.wvp.gb28181.session.SipRedisCompareAndSet;
 import com.ruoyi.wvp.media.event.media.MediaDepartureEvent;
 import com.ruoyi.wvp.media.event.media.MediaDepartureEvent;
 import com.ruoyi.wvp.service.bean.ErrorCallback;
 import com.ruoyi.wvp.service.bean.ErrorCallback;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
@@ -230,6 +231,29 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
         removeInviteInfo(inviteInfo.getType(), inviteInfo.getChannelId(), inviteInfo.getStream());
         removeInviteInfo(inviteInfo.getType(), inviteInfo.getChannelId(), inviteInfo.getStream());
     }
     }
 
 
+    @Override
+    public boolean removeInviteInfoIfSame(InviteInfo expected) {
+        if (expected == null || expected.getType() == null || expected.getChannelId() == null
+                || expected.getStream() == null || expected.getSsrcInfo() == null) return false;
+        String key = VideoManagerConstants.INVITE_PREFIX;
+        String field = expected.getType() + ":" + expected.getChannelId() + ":" + expected.getStream();
+        // Status/StreamInfo may advance while the same allocation stops; never follow a new allocation.
+        for (int attempt = 0; attempt < 3; attempt++) {
+            Object raw = redisTemplate.opsForHash().get(key, field);
+            if (raw == null) return true;
+            if (!(raw instanceof InviteInfo)) return false;
+            InviteInfo current = (InviteInfo) raw;
+            if (expected.getType() != current.getType()
+                    || !java.util.Objects.equals(expected.getChannelId(), current.getChannelId())
+                    || !java.util.Objects.equals(expected.getDeviceId(), current.getDeviceId())
+                    || !java.util.Objects.equals(expected.getMediaServerId(), current.getMediaServerId())
+                    || !java.util.Objects.equals(expected.getStream(), current.getStream())
+                    || !expected.getSsrcInfo().equals(current.getSsrcInfo())) return false;
+            if (SipRedisCompareAndSet.apply(redisTemplate, new SipRedisCompareAndSet.Change(key, field, raw, null))) return true;
+        }
+        return false;
+    }
+
     @Override
     @Override
     public void once(InviteSessionType type, Integer channelId, String stream, ErrorCallback<StreamInfo> callback) {
     public void once(InviteSessionType type, Integer channelId, String stream, ErrorCallback<StreamInfo> callback) {
         String key = buildKey(type, channelId, stream);
         String key = buildKey(type, channelId, stream);

+ 166 - 110
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/PlayServiceImpl.java

@@ -171,7 +171,10 @@ public class PlayServiceImpl implements IPlayService {
     }
     }
 
 
 
 
-    /** Retains termination evidence independently of the legacy channel cache/ready TTL. */
+    @Autowired
+    private com.zksy.video.lifecycle.VideoStopReceipts stopReceipts;
+
+    /** Local callback ownership only; durable stop evidence lives in VideoStopReceipts. */
     private final java.util.Map<String, ManagedPlay> managedPlays = new java.util.concurrent.ConcurrentHashMap<>();
     private final java.util.Map<String, ManagedPlay> managedPlays = new java.util.concurrent.ConcurrentHashMap<>();
 
 
     private static final class ManagedPlay {
     private static final class ManagedPlay {
@@ -180,10 +183,6 @@ public class PlayServiceImpl implements IPlayService {
         private final DeviceChannel channel;
         private final DeviceChannel channel;
         private final String stream;
         private final String stream;
         private SSRCInfo ssrc;
         private SSRCInfo ssrc;
-        private boolean inviteSent;
-        private boolean byeConfirmed;
-        private String confirmedCallId;
-        private boolean stopped;
         private boolean answered;
         private boolean answered;
         private ManagedPlay(MediaServer node, Device device, DeviceChannel channel, String stream) {
         private ManagedPlay(MediaServer node, Device device, DeviceChannel channel, String stream) {
             this.node = node; this.device = device; this.channel = channel; this.stream = stream;
             this.node = node; this.device = device; this.channel = channel; this.stream = stream;
@@ -194,17 +193,11 @@ public class PlayServiceImpl implements IPlayService {
         return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
         return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
     }
     }
 
 
-    private boolean managedMatches(ManagedPlay play, MediaServer node, Device device, DeviceChannel channel) {
-        return java.util.Objects.equals(play.node.getId(), node.getId())
-                && java.util.Objects.equals(play.device.getDeviceId(), device.getDeviceId())
-                && java.util.Objects.equals(play.channel.getId(), channel.getId());
-    }
-
     @Override
     @Override
     public synchronized SSRCInfo playManaged(MediaServer node, String deviceId, String channelId, String stream,
     public synchronized SSRCInfo playManaged(MediaServer node, String deviceId, String channelId, String stream,
                                               ErrorCallback<StreamInfo> callback) {
                                               ErrorCallback<StreamInfo> callback) {
         if (node == null || node.getId() == null || !node.isRtpEnable() || stream == null
         if (node == null || node.getId() == null || !node.isRtpEnable() || stream == null
-                || !stream.matches("managed_[0-9a-fA-F]{32}") || managedCancelled(stream)) {
+                || !stream.matches("managed_[0-9a-fA-F]{32}") || managedCancelled(stream) || stopReceipts == null) {
             if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled or unsupported node/stream", null);
             if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled or unsupported node/stream", null);
             return null;
             return null;
         }
         }
@@ -225,10 +218,14 @@ public class PlayServiceImpl implements IPlayService {
         InviteInfo existing = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
         InviteInfo existing = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
         if (existing != null) {
         if (existing != null) {
             if (!node.getId().equals(existing.getMediaServerId()) || !deviceId.equals(existing.getDeviceId())) return null;
             if (!node.getId().equals(existing.getMediaServerId()) || !deviceId.equals(existing.getDeviceId())) return null;
+            com.zksy.video.lifecycle.VideoStopReceipts.Snapshot receipt = stopReceipts.read(node.getId(), stream);
+            if (receipt == null || !receiptIdentity(receipt.plays.get(stream), device, channel)
+                    || receipt.plays.get(stream).cancelled || receipt.allocation == null
+                    || !receipt.allocation.matches(existing.getSsrcInfo())) return null;
             ManagedPlay retained = managedPlays.get(stream);
             ManagedPlay retained = managedPlays.get(stream);
             if (retained == null) {
             if (retained == null) {
                 retained = new ManagedPlay(node, device, channel, stream); retained.ssrc = existing.getSsrcInfo();
                 retained = new ManagedPlay(node, device, channel, stream); retained.ssrc = existing.getSsrcInfo();
-                retained.inviteSent = true; managedPlays.put(stream, retained);
+                managedPlays.put(stream, retained);
             }
             }
             if (managedCancelled(stream)) return null;
             if (managedCancelled(stream)) return null;
             if (existing.getStreamInfo() != null) {
             if (existing.getStreamInfo() != null) {
@@ -239,7 +236,11 @@ public class PlayServiceImpl implements IPlayService {
             return existing.getSsrcInfo();
             return existing.getSsrcInfo();
         }
         }
         // Same UUID is single-use even after a failure or a cache eviction.
         // Same UUID is single-use even after a failure or a cache eviction.
-        if (managedPlays.containsKey(stream)) return null;
+        if (managedPlays.containsKey(stream) || stopReceipts == null) return null;
+        if (stopReceipts.update(node.getId(), stream, snapshot -> {
+            if (!snapshot.plays.isEmpty() || snapshot.allocation != null) return null;
+            snapshot.plays.put(stream, playReceipt(device, channel)); return snapshot;
+        }) == null) return null;
         ManagedPlay play = new ManagedPlay(node, device, channel, stream);
         ManagedPlay play = new ManagedPlay(node, device, channel, stream);
         managedPlays.put(stream, play);
         managedPlays.put(stream, play);
         RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(node); param.setStreamId(stream);
         RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(node); param.setStreamId(stream);
@@ -259,8 +260,16 @@ public class PlayServiceImpl implements IPlayService {
                 failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed generation cancelled");
                 failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed generation cancelled");
                 return null;
                 return null;
             }
             }
-            // Set BEFORE dispatch: timeout/throw does not prove that no INVITE left the process.
-            play.inviteSent = true;
+            // Persist BEFORE dispatch. Throw/timeout does not prove no INVITE left the process.
+            if (stopReceipts.update(node.getId(), stream, snapshot -> {
+                com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = snapshot.plays.get(stream);
+                if (receipt == null || receipt.cancelled || snapshot.allocation == null
+                        || !snapshot.allocation.matches(play.ssrc)) return null;
+                receipt.inviteSent = true; return snapshot;
+            }) == null) {
+                failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed invite intent not retained");
+                return null;
+            }
             cmder.playStreamCmd(node, play.ssrc, device, channel,
             cmder.playStreamCmd(node, play.ssrc, device, channel,
                     event -> managedInviteOk(play, callback, event),
                     event -> managedInviteOk(play, callback, event),
                     event -> failManaged(play, callback, event.statusCode, event.msg), userSetting.getPlayTimeout().longValue());
                     event -> failManaged(play, callback, event.statusCode, event.msg), userSetting.getPlayTimeout().longValue());
@@ -301,6 +310,17 @@ public class PlayServiceImpl implements IPlayService {
     }
     }
 
 
     private synchronized void managedInviteOk(ManagedPlay play, ErrorCallback<StreamInfo> callback, SipSubscribe.EventResult event) {
     private synchronized void managedInviteOk(ManagedPlay play, ErrorCallback<StreamInfo> callback, SipSubscribe.EventResult event) {
+        // Save the exact response dialog before cancellation can initiate BYE/delete its live registry entry.
+        SsrcTransaction expected = sessionManager.getSsrcTransactionByStream("rtp", play.stream);
+        try {
+            if (expected == null || !play.stream.equals(expected.getStream()) || !stopReceipts.retainDialog(expected)) {
+                failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Original managed dialog could not be retained");
+                return;
+            }
+        } catch (RuntimeException ex) {
+            failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Original managed dialog receipt unavailable");
+            return;
+        }
         // SIPCommander has retained the exact late dialog for ACK/BYE, but never republishes it.
         // SIPCommander has retained the exact late dialog for ACK/BYE, but never republishes it.
         if (managedCancelled(play.stream)) {
         if (managedCancelled(play.stream)) {
             stopManaged(play.node, play.device, play.channel, play.stream);
             stopManaged(play.node, play.device, play.channel, play.stream);
@@ -353,82 +373,84 @@ public class PlayServiceImpl implements IPlayService {
         }
         }
     }
     }
 
 
+    private com.zksy.video.lifecycle.VideoStopReceipts.Play playReceipt(Device device, DeviceChannel channel) {
+        com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = new com.zksy.video.lifecycle.VideoStopReceipts.Play();
+        receipt.deviceId = device.getDeviceId(); receipt.channelId = channel.getId(); receipt.channelCode = channel.getDeviceId();
+        return receipt;
+    }
+
+    private boolean receiptIdentity(com.zksy.video.lifecycle.VideoStopReceipts.Play receipt, Device device, DeviceChannel channel) {
+        return receipt != null && device != null && channel != null
+                && java.util.Objects.equals(receipt.deviceId, device.getDeviceId())
+                && java.util.Objects.equals(receipt.channelId, channel.getId())
+                && java.util.Objects.equals(receipt.channelCode, channel.getDeviceId());
+    }
+
     @Override
     @Override
     public synchronized boolean stopManaged(MediaServer node, Device device, DeviceChannel channel, String stream) {
     public synchronized boolean stopManaged(MediaServer node, Device device, DeviceChannel channel, String stream) {
         if (node == null || node.getId() == null || device == null || channel == null || stream == null
         if (node == null || node.getId() == null || device == null || channel == null || stream == null
-                || !stream.matches("managed_[0-9a-fA-F]{32}")) return false;
-        ManagedPlay play = managedPlays.get(stream);
-        InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
-        SsrcTransaction transaction = sessionManager.getSsrcTransactionByStream("rtp", stream);
-        if ((play != null && !managedMatches(play, node, device, channel))
-                || (invite != null && (!node.getId().equals(invite.getMediaServerId()) || !device.getDeviceId().equals(invite.getDeviceId())))
-                || (transaction != null && (!node.getId().equals(transaction.getMediaServerId())
-                || !device.getDeviceId().equals(transaction.getDeviceId()) || !java.util.Objects.equals(channel.getId(), transaction.getChannelId())))) return false;
-        if (videoLifecycleStore == null) return false;
-        videoLifecycleStore.markStreamCancelled(stream);
+                || !stream.matches("managed_[0-9a-fA-F]{32}") || stopReceipts == null || videoLifecycleStore == null) return false;
         try {
         try {
-            inviteStreamService.call(InviteSessionType.PLAY, channel.getId(), stream,
-                    InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", null);
-        } catch (RuntimeException ex) {
-            log.warn("[Managed callback close] {}: {}", stream, ex.getMessage());
-        }
-        if (play == null) {
-            // Missing transaction is NOT evidence that an INVITE was never sent.
-            if (invite == null && transaction == null) return false;
-            play = new ManagedPlay(node, device, channel, stream); play.inviteSent = true;
-            play.ssrc = invite == null ? new SSRCInfo(0, transaction.getSsrc(), "rtp", stream, null) : invite.getSsrcInfo();
-            managedPlays.put(stream, play);
-        }
-        if (play.stopped && transaction == null) return true;
-        final ManagedPlay owned = play;
-        if (transaction != null && owned.byeConfirmed && !java.util.Objects.equals(owned.confirmedCallId, transaction.getCallId())) {
-            owned.byeConfirmed = false;
-            owned.stopped = false;
-        }
-        boolean rtpClosed = false;
-        try {
-            if (transaction != null && !owned.byeConfirmed) {
-                String callId = transaction.getCallId();
-                cmder.streamByeCmd(device, channel.getDeviceId(), "rtp", stream, callId, event -> {
-                    synchronized (PlayServiceImpl.this) {
-                        if (event.statusCode >= 200 && event.statusCode < 300
-                                && (event.callId == null || java.util.Objects.equals(callId, event.callId))) {
-                            owned.byeConfirmed = true;
-                            owned.confirmedCallId = callId;
-                            sessionManager.removeManagedIfSame(transaction);
-                        }
-                    }
-                });
-            }
-        } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
-            log.warn("[Managed BYE] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
-        } finally {
+            com.zksy.video.lifecycle.VideoStopReceipts.Snapshot retained = stopReceipts.read(node.getId(), stream);
+            if (retained == null || !receiptIdentity(retained.plays.get(stream), device, channel)) return false;
+            InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+            if (invite != null && (!node.getId().equals(invite.getMediaServerId())
+                    || !device.getDeviceId().equals(invite.getDeviceId()) || retained.allocation == null
+                    || !retained.allocation.matches(invite.getSsrcInfo()))) return false;
+            if (current != null && (!node.getId().equals(current.getMediaServerId())
+                    || !"rtp".equals(current.getApp()) || !stream.equals(current.getStream())
+                    || !device.getDeviceId().equals(current.getDeviceId()) || !java.util.Objects.equals(channel.getId(), current.getChannelId())
+                    || retained.allocation == null || !java.util.Objects.equals(retained.allocation.ssrc, current.getSsrc()))) return false;
+            retained = stopReceipts.update(node.getId(), stream, snapshot -> {
+                com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = snapshot.plays.get(stream);
+                if (!receiptIdentity(receipt, device, channel)
+                        || (receipt.dialog != null && current != null && !SipInviteSessionManager.sameDialog(receipt.dialog, current))) return null;
+                receipt.cancelled = true;
+                if (receipt.dialog == null && current != null) receipt.dialog = current;
+                if (receipt.dialog != null) receipt.inviteSent = true;
+                return snapshot;
+            });
+            if (retained == null) return false;
+            videoLifecycleStore.markStreamCancelled(stream);
+            try { inviteStreamService.call(InviteSessionType.PLAY, channel.getId(), stream,
+                    InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", null); }
+            catch (RuntimeException ex) { log.warn("[Managed callback close] {}: {}", stream, ex.getMessage()); }
+            com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = retained.plays.get(stream);
+            SsrcTransaction expected = receipt.dialog;
+            boolean rtpClosed;
             try {
             try {
-                SSRCInfo info = owned.ssrc == null ? new SSRCInfo(0, null, "rtp", stream, null) : owned.ssrc;
-                rtpClosed = receiveRtpServerService.closeManagedRTPServer(node, info);
-            } catch (RuntimeException ex) {
-                log.warn("[Managed close] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
-            }
-        }
-        if (rtpClosed && (!owned.inviteSent || owned.byeConfirmed)) {
-            if (transaction != null && java.util.Objects.equals(owned.confirmedCallId, transaction.getCallId())) {
-                sessionManager.removeManagedIfSame(transaction);
+                if (expected != null && !sessionManager.isSipTerminated(expected) && current != null) {
+                    // Only durable outgoing confirmation or a matched real peer BYE is protocol evidence.
+                    cmder.streamByeCmd(device, channel.getDeviceId(), expected.getSipTransactionInfo(), event -> { });
+                }
+            } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
+                log.warn("[Managed BYE] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
+            } finally {
+                // Cancellation must fence the pool acquisition as well as RTP creation. Its
+                // single-use token is the managed stream even if the pool reply was lost.
+                rtpClosed = false;
+                if (retained.allocation == null && !receipt.inviteSent)
+                    rtpClosed = receiveRtpServerService.closeManagedRTPServer(node, new SSRCInfo(0, null, "rtp", stream, stream));
+                if (retained.allocation != null) rtpClosed = receiveRtpServerService.closeManagedRTPServer(node, retained.allocation.info(stream));
             }
             }
+            if (!rtpClosed || (receipt.inviteSent && (expected == null || !sessionManager.isSipTerminated(expected)))) return false;
+            SsrcTransaction now = sessionManager.getSsrcTransactionByStream("rtp", stream);
+            if (now != null && !SipInviteSessionManager.sameDialog(expected, now)) return false;
             inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
             inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
-            owned.stopped = true;
             return true;
             return true;
+        } catch (RuntimeException ex) {
+            log.warn("[Managed receipt] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
+            return false;
         }
         }
-        return false;
     }
     }
 
 
-    /** Adoption is a capability for one observed dialog, NOT a reusable legacy stream name. */
-    private final java.util.Map<String, AdoptedPlay> adoptedPlays = new java.util.concurrent.ConcurrentHashMap<>();
+    /** Adoption is a persisted capability for one observed dialog, never a reusable stream name. */
 
 
     private static final class AdoptedPlay {
     private static final class AdoptedPlay {
         private final SsrcTransaction dialog;
         private final SsrcTransaction dialog;
         private final SSRCInfo info;
         private final SSRCInfo info;
         private final String channelCode;
         private final String channelCode;
-        private boolean byeConfirmed;
         private boolean cancelled;
         private boolean cancelled;
         private AdoptedPlay(SsrcTransaction current, SSRCInfo ssrc, String channelCode) {
         private AdoptedPlay(SsrcTransaction current, SSRCInfo ssrc, String channelCode) {
             this.channelCode = channelCode;
             this.channelCode = channelCode;
@@ -443,6 +465,15 @@ public class PlayServiceImpl implements IPlayService {
         }
         }
     }
     }
 
 
+    private AdoptedPlay restoredAdoption(MediaServer node, String stream, String handle) {
+        if (node == null || node.getId() == null || stream == null || handle == null || stopReceipts == null) return null;
+        com.zksy.video.lifecycle.VideoStopReceipts.Snapshot snapshot = stopReceipts.read(node.getId(), stream);
+        com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = snapshot == null ? null : snapshot.plays.get(handle);
+        if (receipt == null || receipt.dialog == null || receipt.allocation == null) return null;
+        AdoptedPlay restored = new AdoptedPlay(receipt.dialog, receipt.allocation.info(stream), receipt.channelCode);
+        restored.cancelled = receipt.cancelled; return restored;
+    }
+
     private static boolean nonblank(String value) { return value != null && !value.isBlank(); }
     private static boolean nonblank(String value) { return value != null && !value.isBlank(); }
 
 
     private boolean adoptedIdentity(AdoptedPlay owned, MediaServer node, Device device, DeviceChannel channel, String stream) {
     private boolean adoptedIdentity(AdoptedPlay owned, MediaServer node, Device device, DeviceChannel channel, String stream) {
@@ -466,11 +497,11 @@ public class PlayServiceImpl implements IPlayService {
     @Override
     @Override
     public synchronized String adoptStream(MediaServer node, Device device, DeviceChannel channel, String stream, String handle) {
     public synchronized String adoptStream(MediaServer node, Device device, DeviceChannel channel, String stream, String handle) {
         if (node == null || !nonblank(node.getId()) || !node.isRtpEnable() || device == null || channel == null
         if (node == null || !nonblank(node.getId()) || !node.isRtpEnable() || device == null || channel == null
-                || !nonblank(stream) || stream.startsWith("managed_")) return null;
+                || !nonblank(stream) || stream.startsWith("managed_") || stopReceipts == null) return null;
         InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
         InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
         SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
         SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
         if (handle != null) {
         if (handle != null) {
-            AdoptedPlay owned = adoptedPlays.get(handle);
+            AdoptedPlay owned = restoredAdoption(node, stream, handle);
             return adoptedIdentity(owned, node, device, channel, stream) && !owned.cancelled
             return adoptedIdentity(owned, node, device, channel, stream) && !owned.cancelled
                     && adoptedInvite(owned, invite) && SipInviteSessionManager.sameDialog(owned.dialog, current)
                     && adoptedInvite(owned, invite) && SipInviteSessionManager.sameDialog(owned.dialog, current)
                     ? handle : null;
                     ? handle : null;
@@ -486,44 +517,62 @@ public class PlayServiceImpl implements IPlayService {
         AdoptedPlay owned = new AdoptedPlay(current, invite.getSsrcInfo(), channel.getDeviceId());
         AdoptedPlay owned = new AdoptedPlay(current, invite.getSsrcInfo(), channel.getDeviceId());
         if (!adoptedIdentity(owned, node, device, channel, stream) || !adoptedInvite(owned, invite)
         if (!adoptedIdentity(owned, node, device, channel, stream) || !adoptedInvite(owned, invite)
                 || !sessionManager.retainAdopted(owned.dialog, owned.info)) return null;
                 || !sessionManager.retainAdopted(owned.dialog, owned.info)) return null;
-        String token = java.util.UUID.randomUUID().toString(); adoptedPlays.put(token, owned); return token;
+        String token = java.util.UUID.randomUUID().toString();
+        return stopReceipts.update(node.getId(), stream, snapshot -> {
+            com.zksy.video.lifecycle.VideoStopReceipts.Allocation allocation = snapshot.allocation;
+            if (allocation == null) {
+                // Migration/adoption is backed by the already validated Invite and SIP dialog, not absence.
+                allocation = new com.zksy.video.lifecycle.VideoStopReceipts.Allocation();
+                allocation.token = owned.info.getTimeOutTaskKey(); allocation.ssrc = owned.info.getSsrc();
+                allocation.port = owned.info.getPort(); allocation.state = com.zksy.video.lifecycle.VideoStopReceipts.RtpState.OPEN;
+                snapshot.allocation = allocation;
+            }
+            if (!allocation.matches(owned.info) || allocation.state != com.zksy.video.lifecycle.VideoStopReceipts.RtpState.OPEN
+                    || (allocation.callId != null && !allocation.callId.equals(owned.dialog.getCallId()))) return null;
+            if (snapshot.plays.values().stream().anyMatch(play -> java.util.Objects.equals(play.allocationToken, owned.info.getTimeOutTaskKey())
+                    && (play.cancelled || (play.dialog != null && !SipInviteSessionManager.sameDialog(play.dialog, owned.dialog))))) return null;
+            allocation.callId = owned.dialog.getCallId();
+            com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = playReceipt(device, channel);
+            receipt.allocationToken = allocation.token; receipt.allocation = allocation;
+            receipt.dialog = owned.dialog; receipt.inviteSent = true;
+            snapshot.plays.put(token, receipt); return snapshot;
+        }) == null ? null : token;
     }
     }
 
 
     @Override
     @Override
     public synchronized boolean stopAdopted(MediaServer node, Device device, DeviceChannel channel, String stream, String handle) {
     public synchronized boolean stopAdopted(MediaServer node, Device device, DeviceChannel channel, String stream, String handle) {
-        AdoptedPlay owned = handle == null ? null : adoptedPlays.get(handle);
-        if (!adoptedIdentity(owned, node, device, channel, stream)) return false;
-        InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
-        SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
-        if ((invite != null && !adoptedInvite(owned, invite))
-                || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))
-                || (current == null && !owned.byeConfirmed)) return false;
-        owned.cancelled = true;
         try {
         try {
-            if (!owned.byeConfirmed) {
-                // Explicit dialog overload: never invokes the legacy remove-before-send path.
-                cmder.streamByeCmd(device, owned.channelCode, owned.dialog.getSipTransactionInfo(), event -> {
-                    synchronized (PlayServiceImpl.this) {
-                        if (event.statusCode >= 200 && event.statusCode < 300
-                                && owned.dialog.getCallId().equals(event.callId)) {
-                            owned.byeConfirmed = true;
-                            sessionManager.removeAdoptedIfSame(owned.dialog);
-                        }
-                    }
-                });
+            AdoptedPlay owned = restoredAdoption(node, stream, handle);
+            if (!adoptedIdentity(owned, node, device, channel, stream)) return false;
+            InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+            if ((invite != null && !adoptedInvite(owned, invite))
+                    || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))) return false;
+            if (stopReceipts.update(node.getId(), stream, snapshot -> {
+                com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = snapshot.plays.get(handle);
+                if (receipt == null || snapshot.allocation == null || !snapshot.allocation.matches(owned.info)) return null;
+                receipt.cancelled = true; return snapshot;
+            }) == null) return false;
+            try {
+                if (current != null && !sessionManager.isSipTerminated(owned.dialog)) {
+                    // Explicit original dialog only; a peer termination is not an outgoing BYE confirmation.
+                    cmder.streamByeCmd(device, owned.channelCode, owned.dialog.getSipTransactionInfo(), event -> { });
+                }
+            } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
+                log.warn("[Adopted BYE] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
             }
             }
-        } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
-            log.warn("[Adopted BYE] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
-        }
-        // A retained receipt can survive departure/Invite eviction; a different allocation cannot.
-        boolean closed = receiveRtpServerService.closeAdoptedRTPServer(node, owned.info, owned.dialog.getCallId());
-        current = sessionManager.getSsrcTransactionByStream("rtp", stream);
-        invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
-        if (!closed || !owned.byeConfirmed || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))
-                || (invite != null && !adoptedInvite(owned, invite))) return false;
-        sessionManager.removeAdoptedIfSame(owned.dialog);
-        if (invite != null) inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
-        return true;
+            boolean closed = receiveRtpServerService.closeAdoptedRTPServer(node, owned.info, owned.dialog.getCallId());
+            current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+            invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            if (!closed || !sessionManager.isSipTerminated(owned.dialog)
+                    || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))
+                    || (invite != null && !adoptedInvite(owned, invite))) return false;
+            if (invite != null) inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            return true;
+        } catch (RuntimeException ex) {
+            log.warn("[Adopted receipt] {}/{} remains pending: {}", node == null ? null : node.getId(), stream, ex.getMessage());
+            return false;
+        }
     }
     }
 
 
     @Override
     @Override
@@ -1013,6 +1062,13 @@ public class PlayServiceImpl implements IPlayService {
                                 "下级自定义了ssrc,重新设置收流信息失败", null);
                                 "下级自定义了ssrc,重新设置收流信息失败", null);
 
 
                     }else {
                     }else {
+                        // The legacy path changes only the device-facing SSRC; the pool number that
+                        // must come back is the one originally allocated for this token.
+                        if (stopReceipts != null) {
+                            try { stopReceipts.recordNegotiatedSsrc(mediaServerItem.getId(), ssrcInfo.getStream(),
+                                    ssrcInfo, ssrcInResponse, true); }
+                            catch (RuntimeException ex) { log.warn("[Invite 200OK] 协商 SSRC 保存失败: {}", ex.getMessage()); }
+                        }
                         ssrcInfo.setSsrc(ssrcInResponse);
                         ssrcInfo.setSsrc(ssrcInResponse);
                         inviteInfo.setSsrcInfo(ssrcInfo);
                         inviteInfo.setSsrcInfo(ssrcInfo);
                         inviteInfo.setStream(ssrcInfo.getStream());
                         inviteInfo.setStream(ssrcInfo.getStream());

+ 25 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/PendingSipInvite.java

@@ -0,0 +1,25 @@
+package com.ruoyi.wvp.gb28181.session;
+
+import lombok.Data;
+import com.ruoyi.wvp.service.bean.SSRCInfo;
+
+/** Minimal pre-send snapshot. IDs identify the original source, never inferred from a response or SDP. */
+@Data
+public class PendingSipInvite {
+    private SipRequestBinding binding;
+    private String nodeId;
+    private String deviceId;
+    private Integer channelId;
+    private String channelSipId;
+    private String app;
+    private String stream;
+    private String ssrc;
+    private int port;
+    private String timeoutToken;
+    private String localIp;
+    private long deadlineMillis;
+
+    @com.alibaba.fastjson2.annotation.JSONField(serialize = false, deserialize = false)
+    public boolean isExpired() { return deadlineMillis <= System.currentTimeMillis(); }
+    public SSRCInfo allocation() { return new SSRCInfo(port, ssrc, app, stream, timeoutToken); }
+}

+ 132 - 9
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SSRCFactory.java

@@ -4,9 +4,11 @@ import com.ruoyi.wvp.conf.SipConfig;
 import com.ruoyi.wvp.conf.UserSetting;
 import com.ruoyi.wvp.conf.UserSetting;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.data.redis.core.script.DefaultRedisScript;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
 import java.util.ArrayList;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.List;
 import java.util.Set;
 import java.util.Set;
 
 
@@ -26,6 +28,50 @@ public class SSRCFactory {
      */
      */
     private static final String SSRC_INFO_KEY = "CITY_VIDEO_VMP_SSRC_INFO_";
     private static final String SSRC_INFO_KEY = "CITY_VIDEO_VMP_SSRC_INFO_";
 
 
+    private static final DefaultRedisScript<String> ALLOCATE_OWNED = new DefaultRedisScript<>(
+            "local known = redis.call('HGET', KEYS[2], ARGV[2])\n"
+            + "if known and redis.call('HGET', KEYS[2], known) ~= ARGV[1] then return nil end\n"
+            + "if known then return known end\n"
+            + "if redis.call('HEXISTS', KEYS[2], ARGV[3]) == 1 then return nil end\n"
+            + "local sn = redis.call('SPOP', KEYS[1])\n"
+            + "if not sn then return nil end\n"
+            + "redis.call('HSET', KEYS[2], sn, ARGV[1])\n"
+            + "redis.call('HSET', KEYS[2], ARGV[2], sn)\n"
+            + "return sn", String.class);
+
+    private static final DefaultRedisScript<Long> RELEASE_OWNED = new DefaultRedisScript<>(
+            "if redis.call('HGET', KEYS[2], ARGV[1]) ~= ARGV[2] then return 0 end\n"
+            + "redis.call('HSET', KEYS[2], ARGV[3], ARGV[1])\n"
+            + "redis.call('HDEL', KEYS[2], ARGV[1], ARGV[4])\n"
+            + "return redis.call('SADD', KEYS[1], ARGV[1])", Long.class);
+
+    private static final DefaultRedisScript<Long> CANCEL_OWNED = new DefaultRedisScript<>(
+            "if redis.call('HEXISTS', KEYS[2], ARGV[3]) == 1 then return 1 end\n"
+            + "local sn = redis.call('HGET', KEYS[2], ARGV[2])\n"
+            + "if not sn then return redis.call('HSET', KEYS[2], ARGV[3], ARGV[4]) end\n"
+            + "if redis.call('HGET', KEYS[2], sn) ~= ARGV[1] then return 0 end\n"
+            + "redis.call('HSET', KEYS[2], ARGV[3], sn)\n"
+            + "redis.call('HDEL', KEYS[2], sn, ARGV[2])\n"
+            + "redis.call('SADD', KEYS[1], sn)\nreturn 1", Long.class);
+
+    private static final DefaultRedisScript<String> ALLOCATE_UNOWNED = new DefaultRedisScript<>(
+            "local sn = redis.call('SPOP', KEYS[1])\n"
+            + "if not sn then return nil end\n"
+            + "redis.call('HSET', KEYS[2], sn, ARGV[1])\n"
+            + "return sn", String.class);
+
+    private static final DefaultRedisScript<Long> RELEASE_UNOWNED = new DefaultRedisScript<>(
+            "local owner = redis.call('HGET', KEYS[2], ARGV[1])\n"
+            + "if owner == ARGV[2] then redis.call('HDEL', KEYS[2], ARGV[1]) end\n"
+            + "if redis.call('HEXISTS', KEYS[2], ARGV[1]) == 1 then return 0 end\n"
+            + "return redis.call('SADD', KEYS[1], ARGV[1])", Long.class);
+
+    private static final DefaultRedisScript<Long> RELEASE_OBSERVED_LEGACY = new DefaultRedisScript<>(
+            "if redis.call('HEXISTS', KEYS[2], ARGV[2]) == 1 then return 0 end\n"
+            + "if redis.call('HEXISTS', KEYS[2], ARGV[1]) == 1 then return 0 end\n"
+            + "redis.call('HSET', KEYS[2], ARGV[2], ARGV[1])\n"
+            + "return redis.call('SADD', KEYS[1], ARGV[1])", Long.class);
+
     @Autowired
     @Autowired
     private StringRedisTemplate redisTemplate;
     private StringRedisTemplate redisTemplate;
 
 
@@ -65,6 +111,14 @@ public class SSRCFactory {
         return "0" + getSN(mediaServerId);
         return "0" + getSN(mediaServerId);
     }
     }
 
 
+    /**
+     * Allocate with a unique, non-empty token for this allocation attempt (never reuse the token).
+     * Persist nodeId, SSRC and token together so another Factory can release after a proven stop.
+     */
+    public String getPlaySsrc(String nodeId, String allocationToken) {
+        return "0" + getOwnedSN(nodeId, allocationToken);
+    }
+
     /**
     /**
      * 获取录像回放的SSRC值,第一位固定为1
      * 获取录像回放的SSRC值,第一位固定为1
      */
      */
@@ -72,6 +126,11 @@ public class SSRCFactory {
         return "1" + getSN(mediaServerId);
         return "1" + getSN(mediaServerId);
     }
     }
 
 
+    /** Playback uses the same node pool and allocation ownership as live play; only the prefix differs. */
+    public String getPlayBackSsrc(String nodeId, String allocationToken) {
+        return "1" + getOwnedSN(nodeId, allocationToken);
+    }
+
     /**
     /**
      * 释放ssrc,主要用完的ssrc一定要释放,否则会耗尽
      * 释放ssrc,主要用完的ssrc一定要释放,否则会耗尽
      *
      *
@@ -82,22 +141,85 @@ public class SSRCFactory {
             return;
             return;
         }
         }
         String sn = ssrc.substring(1);
         String sn = ssrc.substring(1);
-        String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
-        redisTemplate.opsForSet().add(redisKey, sn);
+        // An unowned legacy callback has no authority over a currently tracked allocation.
+        redisTemplate.execute(RELEASE_UNOWNED, allocationKeys(mediaServerId), sn, "__legacy__");
+    }
+
+    /**
+     * Return only this allocation's SN. The owner comparison, deletion and pool insertion execute
+     * in one Redis script; no process-local release flag is required. False means no SN was added
+     * (wrong/stale token or already released), not evidence that media has stopped.
+     */
+    public boolean releaseSsrc(String nodeId, String ssrc, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        if (ssrc == null || ssrc.length() < 2) {
+            return false;
+        }
+        return Long.valueOf(1).equals(redisTemplate.execute(RELEASE_OWNED, allocationKeys(nodeId),
+                ssrc.substring(1), allocationToken, "released:" + allocationToken, "allocated:" + allocationToken));
+    }
+
+    /** Cancels the pool acquisition itself, including a lost SPOP reply. A later allocation
+     * with this token cannot occur even if cancellation reached Redis before the allocation. */
+    public boolean cancelAllocation(String nodeId, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        return Long.valueOf(1).equals(redisTemplate.execute(CANCEL_OWNED, allocationKeys(nodeId), allocationToken,
+                "allocated:" + allocationToken, "released:" + allocationToken, "cancelled-before-allocation"));
+    }
+
+    /** Positive durable return receipt; checking it never inserts a number back into the pool. */
+    public boolean wasReleased(String nodeId, String ssrc, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        return ssrc != null && ssrc.length() > 1 && ssrc.substring(1).equals(
+                redisTemplate.opsForHash().get(allocationKeys(nodeId).get(1), "released:" + allocationToken));
+    }
+
+    /** Only for a pre-upgrade, untracked allocation whose exact close was observed. A newer
+     * tracked OR legacy owner blocks the return. The once-only receipt is atomic with SADD. */
+    public boolean releaseObservedLegacySsrc(String nodeId, String ssrc, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        if (ssrc == null || ssrc.length() < 2) return false;
+        return Long.valueOf(1).equals(redisTemplate.execute(RELEASE_OBSERVED_LEGACY, allocationKeys(nodeId),
+                ssrc.substring(1), "released:" + allocationToken));
+    }
+
+    private String getOwnedSN(String nodeId, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        String sn = redisTemplate.execute(ALLOCATE_OWNED, allocationKeys(nodeId), allocationToken,
+                "allocated:" + allocationToken, "released:" + allocationToken);
+        if (sn == null) {
+            throw new RuntimeException("ssrc已经用完");
+        }
+        return sn;
+    }
+
+    /**
+     * Preserve the existing serverId/node pool and store SN -> token in its companion owner hash.
+     * No TTL: allocations must survive process restart. The hash tag uses the unchanged pool key
+     * (normal identifiers contain no braces); live Redis / Redis Cluster behavior is not verified
+     * by the offline command-boundary tests.
+     */
+    private List<String> allocationKeys(String nodeId) {
+        String poolKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + nodeId;
+        return Arrays.asList(poolKey, "{" + poolKey + "}_OWNERS");
+    }
+
+    private static void requireAllocationToken(String allocationToken) {
+        if (allocationToken == null || allocationToken.trim().isEmpty() || "__legacy__".equals(allocationToken)) {
+            throw new IllegalArgumentException("allocationToken不能为空");
+        }
     }
     }
 
 
     /**
     /**
      * 获取后四位数SN,随机数
      * 获取后四位数SN,随机数
      */
      */
     private String getSN(String mediaServerId) {
     private String getSN(String mediaServerId) {
-        String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
-        Long size = redisTemplate.opsForSet().size(redisKey);
-        if (size == null || size == 0) {
+        // Clear any prior owner while popping, including after an explicit legacy pool reset.
+        String sn = redisTemplate.execute(ALLOCATE_UNOWNED, allocationKeys(mediaServerId), "__legacy__");
+        if (sn == null) {
             throw new RuntimeException("ssrc已经用完");
             throw new RuntimeException("ssrc已经用完");
-        } else {
-            // 在集合中移除并返回一个随机成员。
-            return redisTemplate.opsForSet().pop(redisKey);
         }
         }
+        return sn;
     }
     }
 
 
     /**
     /**
@@ -116,7 +238,8 @@ public class SSRCFactory {
      */
      */
     public boolean hasMediaServerSSRC(String mediaServerId) {
     public boolean hasMediaServerSSRC(String mediaServerId) {
         String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
         String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
-        return Boolean.TRUE.equals(redisTemplate.hasKey(redisKey));
+        return Boolean.TRUE.equals(redisTemplate.hasKey(redisKey))
+                || Boolean.TRUE.equals(redisTemplate.hasKey(allocationKeys(mediaServerId).get(1)));
     }
     }
 
 
 }
 }

+ 269 - 34
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipInviteSessionManager.java

@@ -67,28 +67,77 @@ public class SipInviteSessionManager {
 		}
 		}
 	}
 	}
 
 
-    private final java.util.Map<String, SsrcTransaction> adoptedDialogs = new java.util.concurrent.ConcurrentHashMap<>();
-    private final java.util.Map<String, com.ruoyi.wvp.service.bean.SSRCInfo> adoptedAllocations = new java.util.concurrent.ConcurrentHashMap<>();
-
-    /** Bind an observed legacy dialog before any cancellation can remove its retry handle. */
-    public synchronized boolean retainAdopted(SsrcTransaction owned, com.ruoyi.wvp.service.bean.SSRCInfo info) {
-        if (owned == null || info == null || !sameDialog(owned, getSsrcTransactionByStream(owned.getApp(), owned.getStream()))
-                || !sameDialog(owned, getSsrcTransactionByCallId(owned.getCallId()))) return false;
-        adoptedDialogs.put(owned.getCallId(), owned);
-        adoptedAllocations.put(owned.getCallId(), new com.ruoyi.wvp.service.bean.SSRCInfo(info.getPort(), info.getSsrc(), info.getApp(), info.getStream(), info.getTimeOutTaskKey()));
-        return true;
+    /** Persist a minimal independent snapshot; no Device/MediaServer credentials are retained. */
+    public boolean retainAdopted(SsrcTransaction owned, com.ruoyi.wvp.service.bean.SSRCInfo info) {
+        if (owned == null || info == null) return false;
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if (!sameDialog(owned, stream) || !sameDialog(owned, call)
+                || !java.util.Objects.equals(owned.getApp(), info.getApp())
+                || !java.util.Objects.equals(owned.getStream(), info.getStream())
+                || !java.util.Objects.equals(owned.getSsrc(), info.getSsrc())) return false;
+        String key = recoveryKey("adoption");
+        String field = dialogIdentity(owned);
+        Object previous = redisTemplate.opsForHash().get(key, field);
+        com.alibaba.fastjson2.JSONObject snapshot = new com.alibaba.fastjson2.JSONObject();
+        snapshot.put("dialog", owned); snapshot.put("port", info.getPort());
+        snapshot.put("timeoutToken", info.getTimeOutTaskKey());
+        String update = snapshot.toJSONString();
+        if (previous != null && !previous.equals(update)) return false;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, stream),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, call),
+                new SipRedisCompareAndSet.Change(key, field, previous, update));
     }
     }
 
 
     public boolean isAdopted(SsrcTransaction owned) {
     public boolean isAdopted(SsrcTransaction owned) {
-        return owned != null && owned.getCallId() != null && sameDialog(owned, adoptedDialogs.get(owned.getCallId()));
+        com.alibaba.fastjson2.JSONObject snapshot = adoption(owned);
+        return snapshot != null && sameDialog(owned, snapshot.getObject("dialog", SsrcTransaction.class));
+    }
+
+    public com.ruoyi.wvp.service.bean.SSRCInfo getAdoptedAllocation(SsrcTransaction owned) {
+        com.alibaba.fastjson2.JSONObject snapshot = adoption(owned);
+        if (snapshot == null || !sameDialog(owned, snapshot.getObject("dialog", SsrcTransaction.class))) return null;
+        return new com.ruoyi.wvp.service.bean.SSRCInfo(snapshot.getIntValue("port"), owned.getSsrc(), owned.getApp(),
+                owned.getStream(), snapshot.getString("timeoutToken"));
     }
     }
 
 
     public boolean isAdoptedRtp(String nodeId, String callId, com.ruoyi.wvp.service.bean.SSRCInfo info) {
     public boolean isAdoptedRtp(String nodeId, String callId, com.ruoyi.wvp.service.bean.SSRCInfo info) {
-        SsrcTransaction owned = callId == null ? null : adoptedDialogs.get(callId);
-        return owned != null && java.util.Objects.equals(nodeId, owned.getMediaServerId())
-                && info != null && info.equals(adoptedAllocations.get(callId));
+        if (info == null || callId == null) return false;
+        for (Object value : redisTemplate.opsForHash().values(recoveryKey("adoption"))) {
+            com.alibaba.fastjson2.JSONObject snapshot = com.alibaba.fastjson2.JSON.parseObject((String) value);
+            SsrcTransaction owned = snapshot.getObject("dialog", SsrcTransaction.class);
+            if (java.util.Objects.equals(nodeId, owned.getMediaServerId()) && java.util.Objects.equals(callId, owned.getCallId())
+                    && info.equals(allocation(snapshot, owned))) return true;
+        }
+        return false;
+    }
+
+    public boolean isAdoptedAllocation(String nodeId, com.ruoyi.wvp.service.bean.SSRCInfo info) {
+        if (info == null) return false;
+        for (Object value : redisTemplate.opsForHash().values(recoveryKey("adoption"))) {
+            com.alibaba.fastjson2.JSONObject snapshot = com.alibaba.fastjson2.JSON.parseObject((String) value);
+            SsrcTransaction owned = snapshot.getObject("dialog", SsrcTransaction.class);
+            if (java.util.Objects.equals(nodeId, owned.getMediaServerId()) && info.equals(allocation(snapshot, owned))) return true;
+        }
+        return false;
+    }
+
+    private com.alibaba.fastjson2.JSONObject adoption(SsrcTransaction owned) {
+        if (owned == null || owned.getSipTransactionInfo() == null) return null;
+        Object value = redisTemplate.opsForHash().get(recoveryKey("adoption"), dialogIdentity(owned));
+        return value == null ? null : com.alibaba.fastjson2.JSON.parseObject((String) value);
+    }
+
+    private com.ruoyi.wvp.service.bean.SSRCInfo allocation(com.alibaba.fastjson2.JSONObject snapshot, SsrcTransaction owned) {
+        return new com.ruoyi.wvp.service.bean.SSRCInfo(snapshot.getIntValue("port"), owned.getSsrc(), owned.getApp(),
+                owned.getStream(), snapshot.getString("timeoutToken"));
     }
     }
 
 
+    private String recoveryKey(String kind) { return "SIP_RECOVERY_V1:" + userSetting.getServerId() + ":" + kind; }
+    private String streamKey() { return VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId(); }
+    private String callKey() { return VideoManagerConstants.SIP_INVITE_SESSION_CALL_ID + userSetting.getServerId(); }
+
     public static boolean sameDialog(SsrcTransaction expected, SsrcTransaction current) {
     public static boolean sameDialog(SsrcTransaction expected, SsrcTransaction current) {
         return expected != null && current != null
         return expected != null && current != null
                 && java.util.Objects.equals(expected.getCallId(), current.getCallId())
                 && java.util.Objects.equals(expected.getCallId(), current.getCallId())
@@ -102,26 +151,212 @@ public class SipInviteSessionManager {
                 && expected.getSipTransactionInfo() != null && current.getSipTransactionInfo() != null
                 && expected.getSipTransactionInfo() != null && current.getSipTransactionInfo() != null
                 && java.util.Objects.equals(expected.getSipTransactionInfo().getCallId(), current.getSipTransactionInfo().getCallId())
                 && java.util.Objects.equals(expected.getSipTransactionInfo().getCallId(), current.getSipTransactionInfo().getCallId())
                 && java.util.Objects.equals(expected.getSipTransactionInfo().getFromTag(), current.getSipTransactionInfo().getFromTag())
                 && java.util.Objects.equals(expected.getSipTransactionInfo().getFromTag(), current.getSipTransactionInfo().getFromTag())
-                && java.util.Objects.equals(expected.getSipTransactionInfo().getToTag(), current.getSipTransactionInfo().getToTag());
-    }
-
-    public synchronized boolean removeAdoptedIfSame(SsrcTransaction owned) {
-        if (!isAdopted(owned) || !sameDialog(owned, getSsrcTransactionByStream(owned.getApp(), owned.getStream()))
-                || !sameDialog(owned, getSsrcTransactionByCallId(owned.getCallId()))) return false;
-        redisTemplate.opsForHash().delete(VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId(), owned.getApp() + owned.getStream());
-        redisTemplate.opsForHash().delete(VideoManagerConstants.SIP_INVITE_SESSION_CALL_ID + userSetting.getServerId(), owned.getCallId());
-        return true;
-    }
-
-    /** A late BYE acknowledgement may remove only the dialog it actually terminated. */
-    public synchronized boolean removeManagedIfSame(SsrcTransaction owned) {
-        if (owned == null || owned.getStream() == null || !owned.getStream().startsWith("managed_")) return false;
-        SsrcTransaction current = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
-        if (current == null || !java.util.Objects.equals(current.getCallId(), owned.getCallId())
-                || !java.util.Objects.equals(current.getMediaServerId(), owned.getMediaServerId())) return false;
-        redisTemplate.opsForHash().delete(VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId(), owned.getApp() + owned.getStream());
-        redisTemplate.opsForHash().delete(VideoManagerConstants.SIP_INVITE_SESSION_CALL_ID + userSetting.getServerId(), owned.getCallId());
-        return true;
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getToTag(), current.getSipTransactionInfo().getToTag())
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getViaBranch(), current.getSipTransactionInfo().getViaBranch())
+                && expected.getSipTransactionInfo().isAsSender() == current.getSipTransactionInfo().isAsSender();
+    }
+
+    /** Persist before dispatch; failed persistence means no managed INVITE may be sent. */
+    public boolean rememberInvite(javax.sip.message.Request request, String nodeId, String deviceId, Integer channelId,
+                                  String channelSipId, com.ruoyi.wvp.service.bean.SSRCInfo allocation,
+                                  String localIp, long deadlineMillis) {
+        SipRequestBinding binding = SipRequestBinding.from(request, javax.sip.message.Request.INVITE);
+        if (binding == null || allocation == null || allocation.getStream() == null
+                || !allocation.getStream().startsWith("managed_") || !SipRequestBinding.present(nodeId)
+                || !SipRequestBinding.present(deviceId) || channelId == null || !SipRequestBinding.present(channelSipId)
+                || !SipRequestBinding.present(localIp) || !SipRequestBinding.present(allocation.getTimeOutTaskKey())
+                || !SipRequestBinding.present(allocation.getSsrc()) || !SipRequestBinding.present(allocation.getApp())) return false;
+        PendingSipInvite pending = new PendingSipInvite(); pending.setBinding(binding); pending.setNodeId(nodeId);
+        pending.setDeviceId(deviceId); pending.setChannelId(channelId); pending.setChannelSipId(channelSipId);
+        pending.setApp(allocation.getApp()); pending.setStream(allocation.getStream()); pending.setSsrc(allocation.getSsrc());
+        pending.setPort(allocation.getPort()); pending.setTimeoutToken(allocation.getTimeOutTaskKey());
+        pending.setLocalIp(localIp); pending.setDeadlineMillis(deadlineMillis);
+        String json = com.alibaba.fastjson2.JSON.toJSONString(pending);
+        Object before = redisTemplate.opsForHash().get(recoveryKey("invite-request"), binding.key());
+        String streamField = allocation.getApp() + ":" + allocation.getStream();
+        Object streamBefore = redisTemplate.opsForHash().get(recoveryKey("invite-stream"), streamField);
+        if ((before != null && !before.equals(json)) || (streamBefore != null && !streamBefore.equals(json))) return false;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(recoveryKey("invite-request"), binding.key(), before, json),
+                new SipRedisCompareAndSet.Change(recoveryKey("invite-stream"), streamField, streamBefore, json));
+    }
+
+    public PendingSipInvite getPendingInviteByStream(String app, String stream) {
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("invite-stream"), app + ":" + stream);
+        return raw == null ? null : com.alibaba.fastjson2.JSON.parseObject((String) raw, PendingSipInvite.class);
+    }
+
+    public boolean hasPendingInviteRequest(gov.nist.javax.sip.message.SIPResponse response) {
+        String field = SipRequestBinding.key(response);
+        return field != null && redisTemplate.opsForHash().get(recoveryKey("invite-request"), field) != null;
+    }
+
+    public PendingSipInvite matchPendingInvite(gov.nist.javax.sip.message.SIPResponse response) {
+        String field = SipRequestBinding.key(response);
+        if (field == null) return null;
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("invite-request"), field);
+        if (raw == null) return null;
+        PendingSipInvite pending = com.alibaba.fastjson2.JSON.parseObject((String) raw, PendingSipInvite.class);
+        return pending.getBinding().matches(response) ? pending : null;
+    }
+
+    /** Restore the actual To-tag and transaction from headers; malformed/absent SDP cannot erase a SIP dialog. */
+    public SsrcTransaction restoreManagedInvite(gov.nist.javax.sip.message.SIPResponse response) {
+        PendingSipInvite pending = matchPendingInvite(response);
+        if (pending == null) return null;
+        SsrcTransaction owned = SsrcTransaction.buildForDevice(pending.getDeviceId(), pending.getChannelId(),
+                pending.getBinding().getCallId(), pending.getApp(), pending.getStream(), pending.getSsrc(), pending.getNodeId(),
+                response, com.ruoyi.wvp.common.InviteSessionType.PLAY);
+        String identity = dialogIdentity(owned);
+        if (isSipTerminated(owned)) return null; // INVITE retransmissions cannot revive either kind of real termination.
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if ((stream != null && !sameDialog(owned, stream)) || (call != null && !sameDialog(owned, call))) return null;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, owned),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, owned),
+                new SipRedisCompareAndSet.Change(recoveryKey("bye-confirmed"), identity, null, null),
+                new SipRedisCompareAndSet.Change(recoveryKey("peer-bye"), identity, null, null)) ? owned : null;
+    }
+
+    /** Persist the actual outgoing request before the transport is allowed to send it. */
+    public boolean rememberBye(javax.sip.message.Request request, SsrcTransaction owned) {
+        SipRequestBinding binding = SipRequestBinding.from(request, javax.sip.message.Request.BYE);
+        if (binding == null || owned == null || owned.getSipTransactionInfo() == null
+                || !java.util.Objects.equals(binding.getCallId(), owned.getCallId())
+                || !java.util.Objects.equals(binding.getFromTag(), owned.getSipTransactionInfo().getFromTag())
+                || !java.util.Objects.equals(binding.getToTag(), owned.getSipTransactionInfo().getToTag())
+                || !SipRequestBinding.present(binding.getToTag())) return false;
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if (!sameDialog(owned, stream) || !sameDialog(owned, call)) return false;
+        com.alibaba.fastjson2.JSONObject snapshot = new com.alibaba.fastjson2.JSONObject();
+        snapshot.put("binding", binding); snapshot.put("dialog", owned);
+        String key = recoveryKey("bye-request");
+        Object before = redisTemplate.opsForHash().get(key, binding.key());
+        String update = snapshot.toJSONString();
+        if (before != null && !before.equals(update)) return false;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, stream),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, call),
+                new SipRedisCompareAndSet.Change(key, binding.key(), before, update));
+    }
+
+    public boolean hasByeRequest(gov.nist.javax.sip.message.SIPResponse response) {
+        String field = SipRequestBinding.key(response);
+        return field != null && redisTemplate.opsForHash().get(recoveryKey("bye-request"), field) != null;
+    }
+
+    /** Returns the original dialog only after a matching real BYE 2xx is durably recorded. */
+    public SsrcTransaction confirmBye(gov.nist.javax.sip.message.SIPResponse response) {
+        String field = SipRequestBinding.key(response);
+        if (field == null || !javax.sip.message.Request.BYE.equals(response.getCSeqHeader().getMethod())) return null;
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("bye-request"), field);
+        if (raw == null) return null;
+        com.alibaba.fastjson2.JSONObject request = com.alibaba.fastjson2.JSON.parseObject((String) raw);
+        if (!request.getObject("binding", SipRequestBinding.class).matches(response)) return null;
+        SsrcTransaction owned = request.getObject("dialog", SsrcTransaction.class);
+        String identity = dialogIdentity(owned), key = recoveryKey("bye-confirmed");
+        Object before = redisTemplate.opsForHash().get(key, identity);
+        String update = com.alibaba.fastjson2.JSON.toJSONString(owned);
+        if (before != null) return sameDialog(owned, com.alibaba.fastjson2.JSON.parseObject((String) before, SsrcTransaction.class)) ? owned : null;
+        if (SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(recoveryKey("bye-request"), field, raw, raw),
+                new SipRedisCompareAndSet.Change(key, identity, null, update))) return owned;
+        return isByeConfirmed(owned) ? owned : null;
+    }
+
+    /** A receipt proves this exact dialog, not a successful send or another allocation with the same Call-ID. */
+    public boolean isByeConfirmed(SsrcTransaction expected) {
+        if (expected == null || expected.getSipTransactionInfo() == null) return false;
+        Object value = redisTemplate.opsForHash().get(recoveryKey("bye-confirmed"), dialogIdentity(expected));
+        return value != null && sameDialog(expected, com.alibaba.fastjson2.JSON.parseObject((String) value, SsrcTransaction.class));
+    }
+
+    /** Called only after replying 200 to an actual peer BYE; not an outgoing-BYE confirmation. */
+    public boolean rememberPeerBye(javax.sip.message.Request request, SsrcTransaction owned) {
+        SipRequestBinding binding = SipRequestBinding.from(request, javax.sip.message.Request.BYE);
+        if (!matchesPeerBye(binding, owned)) return false;
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if (!sameDialog(owned, stream) || !sameDialog(owned, call)) return false;
+        String key = recoveryKey("peer-bye"), field = dialogIdentity(owned);
+        Object before = redisTemplate.opsForHash().get(key, field);
+        com.alibaba.fastjson2.JSONObject snapshot = new com.alibaba.fastjson2.JSONObject();
+        snapshot.put("binding", binding); snapshot.put("dialog", owned);
+        if (before != null && !matchedPeerBye(owned, before)) return false;
+        // Keep the first actual request as evidence; retransmits must still own both original indexes.
+        Object update = before == null ? snapshot.toJSONString() : before;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, stream),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, call),
+                new SipRedisCompareAndSet.Change(key, field, before, update));
+    }
+
+    private static boolean matchesPeerBye(SipRequestBinding binding, SsrcTransaction owned) {
+        return binding != null && owned != null && owned.getSipTransactionInfo() != null
+                && javax.sip.message.Request.BYE.equals(binding.getMethod())
+                && org.springframework.util.StringUtils.hasText(binding.getCallId())
+                && org.springframework.util.StringUtils.hasText(binding.getFromTag())
+                && org.springframework.util.StringUtils.hasText(binding.getToTag())
+                && org.springframework.util.StringUtils.hasText(binding.getViaBranch())
+                && java.util.Objects.equals(binding.getCallId(), owned.getCallId())
+                && java.util.Objects.equals(binding.getCallId(), owned.getSipTransactionInfo().getCallId())
+                && java.util.Objects.equals(binding.getFromTag(), owned.getSipTransactionInfo().getToTag())
+                && java.util.Objects.equals(binding.getToTag(), owned.getSipTransactionInfo().getFromTag());
+    }
+
+    private static boolean matchedPeerBye(SsrcTransaction expected, Object raw) {
+        com.alibaba.fastjson2.JSONObject snapshot = com.alibaba.fastjson2.JSON.parseObject((String) raw);
+        return sameDialog(expected, snapshot.getObject("dialog", SsrcTransaction.class))
+                && matchesPeerBye(snapshot.getObject("binding", SipRequestBinding.class), expected);
+    }
+
+    /** Read-only protocol evidence for this exact original dialog, independent of live index deletion. */
+    public boolean isSipTerminated(SsrcTransaction expected) {
+        if (expected == null || expected.getSipTransactionInfo() == null) return false;
+        if (isByeConfirmed(expected)) return true;
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("peer-bye"), dialogIdentity(expected));
+        return raw != null && matchedPeerBye(expected, raw);
+    }
+
+    private static String dialogIdentity(SsrcTransaction tx) {
+        com.ruoyi.wvp.gb28181.bean.SipTransactionInfo sip = tx.getSipTransactionInfo();
+        String identity = com.alibaba.fastjson2.JSON.toJSONString(java.util.Arrays.asList(tx.getMediaServerId(),
+                tx.getDeviceId(), tx.getChannelId(), tx.getApp(), tx.getStream(), tx.getCallId(), tx.getSsrc(), tx.getType(),
+                sip.getCallId(), sip.getFromTag(), sip.getToTag(), sip.getViaBranch(), sip.isAsSender()));
+        try {
+            byte[] digest = java.security.MessageDigest.getInstance("SHA-256")
+                    .digest(identity.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+            return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
+        } catch (java.security.NoSuchAlgorithmException impossible) {
+            throw new IllegalStateException("SHA-256 is required by the Java runtime", impossible);
+        }
+    }
+
+    public boolean removeAdoptedIfSame(SsrcTransaction owned) {
+        return isAdopted(owned) && removeConfirmedIfSame(owned);
+    }
+
+    /** Real termination is required here; offline cleanup uses removeIfSame without claiming SIP completion. */
+    public boolean removeManagedIfSame(SsrcTransaction owned) {
+        return owned != null && owned.getStream() != null && owned.getStream().startsWith("managed_")
+                && removeConfirmedIfSame(owned);
+    }
+
+    private boolean removeConfirmedIfSame(SsrcTransaction owned) {
+        return isSipTerminated(owned) && removeIfSame(owned);
+    }
+
+    /** Compare the caller's original snapshot and atomically delete both indexes, never a replacement. */
+    public boolean removeIfSame(SsrcTransaction owned) {
+        if (owned == null || owned.getApp() == null || owned.getStream() == null || owned.getCallId() == null) return false;
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if (!sameDialog(owned, stream) || !sameDialog(owned, call)) return false;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, null),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, null));
     }
     }
 
 
 	public void removeByCallId(String callId) {
 	public void removeByCallId(String callId) {

+ 46 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRedisCompareAndSet.java

@@ -0,0 +1,46 @@
+package com.ruoyi.wvp.gb28181.session;
+
+import org.springframework.data.redis.connection.ReturnType;
+import org.springframework.data.redis.core.RedisCallback;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.RedisSerializer;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Compare every observed hash value before changing any index; atomic across service instances. */
+public final class SipRedisCompareAndSet {
+    private static final byte[] SCRIPT = ("-- sip-recovery-cas-v1\n"
+            + "for i=1,#KEYS do local a=(i-1)*5; local v=redis.call('HGET',KEYS[i],ARGV[a+1]); "
+            + "if ARGV[a+2]=='0' then if v then return 0 end "
+            + "elseif not v or v~=ARGV[a+3] then return 0 end end; "
+            + "for i=1,#KEYS do local a=(i-1)*5; if ARGV[a+4]=='1' then "
+            + "redis.call('HSET',KEYS[i],ARGV[a+1],ARGV[a+5]) else redis.call('HDEL',KEYS[i],ARGV[a+1]) end end; return 1")
+            .getBytes(StandardCharsets.UTF_8);
+    public static final class Change {
+        final String key, field;
+        final Object before, after;
+        public Change(String key, String field, Object before, Object after) {
+            this.key = key; this.field = field; this.before = before; this.after = after;
+        }
+    }
+    @SuppressWarnings("unchecked")
+    public static boolean apply(RedisTemplate<Object,Object> redis, Change... changes) {
+        RedisSerializer<Object> keys = (RedisSerializer<Object>) redis.getKeySerializer();
+        RedisSerializer<Object> fields = (RedisSerializer<Object>) redis.getHashKeySerializer();
+        RedisSerializer<Object> values = (RedisSerializer<Object>) redis.getHashValueSerializer();
+        List<byte[]> args = new ArrayList<>();
+        for (Change c : changes) args.add(keys.serialize(c.key));
+        for (Change c : changes) {
+            args.add(fields.serialize(c.field));
+            args.add(flag(c.before != null)); args.add(c.before == null ? new byte[0] : values.serialize(c.before));
+            args.add(flag(c.after != null)); args.add(c.after == null ? new byte[0] : values.serialize(c.after));
+        }
+        Long result = redis.execute((RedisCallback<Long>) connection -> connection.eval(
+                SCRIPT, ReturnType.INTEGER, changes.length, args.toArray(new byte[0][])));
+        return Long.valueOf(1).equals(result);
+    }
+    private static byte[] flag(boolean value) { return new byte[]{ (byte) (value ? '1' : '0') }; }
+    private SipRedisCompareAndSet() { }
+}

+ 49 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRequestBinding.java

@@ -0,0 +1,49 @@
+package com.ruoyi.wvp.gb28181.session;
+
+import gov.nist.javax.sip.message.SIPResponse;
+import lombok.Data;
+import javax.sip.header.*;
+import javax.sip.message.Request;
+import java.util.Objects;
+
+/** Only correlation headers, never a SIP message, SDP, authorization or credentials. */
+@Data
+public class SipRequestBinding {
+    private String callId;
+    private long cseq;
+    private String method;
+    private String fromTag;
+    private String toTag;
+    private String viaBranch;
+
+    static SipRequestBinding from(Request request, String method) {
+        if (request == null || !method.equals(request.getMethod())) return null;
+        CallIdHeader call = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
+        CSeqHeader seq = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
+        FromHeader from = (FromHeader) request.getHeader(FromHeader.NAME);
+        ToHeader to = (ToHeader) request.getHeader(ToHeader.NAME);
+        ViaHeader via = (ViaHeader) request.getHeader(ViaHeader.NAME);
+        if (call == null || seq == null || from == null || via == null || to == null
+                || !method.equals(seq.getMethod()) || !present(call.getCallId())
+                || !present(from.getTag()) || !present(via.getBranch())) return null;
+        SipRequestBinding result = new SipRequestBinding(); result.callId = call.getCallId();
+        result.cseq = seq.getSeqNumber(); result.method = method; result.fromTag = from.getTag();
+        result.toTag = to.getTag(); result.viaBranch = via.getBranch(); return result;
+    }
+
+    boolean matches(SIPResponse response) {
+        return response != null && response.getStatusCode() >= 200 && response.getStatusCode() < 300
+                && response.getCallIdHeader() != null && response.getCSeqHeader() != null
+                && response.getTopmostViaHeader() != null && Objects.equals(callId, response.getCallIdHeader().getCallId())
+                && cseq == response.getCSeqHeader().getSeqNumber() && Objects.equals(method, response.getCSeqHeader().getMethod())
+                && Objects.equals(fromTag, response.getFromTag()) && Objects.equals(viaBranch, response.getTopmostViaHeader().getBranch())
+                && present(response.getToTag()) && (Request.INVITE.equals(method) || Objects.equals(toTag, response.getToTag()));
+    }
+    String key() { return callId.length() + ":" + callId + ":" + cseq; }
+    static String key(SIPResponse response) {
+        if (response == null || response.getCallIdHeader() == null || response.getCSeqHeader() == null) return null;
+        String call = response.getCallIdHeader().getCallId();
+        return call == null ? null : call.length() + ":" + call + ":" + response.getCSeqHeader().getSeqNumber();
+    }
+    static boolean present(String value) { return value != null && !value.isEmpty(); }
+}

+ 26 - 6
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/SIPProcessorObserver.java

@@ -36,6 +36,9 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
     @Autowired
     @Autowired
     private EventPublisher eventPublisher;
     private EventPublisher eventPublisher;
 
 
+    @Autowired
+    private com.ruoyi.wvp.gb28181.session.SipInviteSessionManager sessionManager;
+
     /**
     /**
      * 添加 request订阅
      * 添加 request订阅
      * @param method 方法名
      * @param method 方法名
@@ -81,9 +84,28 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
     public void processResponse(ResponseEvent responseEvent) {
     public void processResponse(ResponseEvent responseEvent) {
         SIPResponse response = (SIPResponse)responseEvent.getResponse();
         SIPResponse response = (SIPResponse)responseEvent.getResponse();
         int status = response.getStatusCode();
         int status = response.getStatusCode();
+        if (response.getCSeqHeader() == null) return;
+        if (status >= 200 && status < 300 && javax.sip.message.Request.BYE.equals(response.getCSeqHeader().getMethod())
+                && sessionManager != null) {
+            com.ruoyi.wvp.gb28181.bean.SsrcTransaction confirmed = sessionManager.confirmBye(response);
+            if (confirmed != null) {
+                // Also runs after SipSubscribe expiry or process reconstruction; receipt precedes deletion.
+                if (sessionManager.isAdopted(confirmed)) sessionManager.removeAdoptedIfSame(confirmed);
+                else sessionManager.removeManagedIfSame(confirmed);
+                if (responseEvent.getDialog() != null) responseEvent.getDialog().delete();
+            } else if (sessionManager.hasByeRequest(response)) {
+                return;
+            }
+        }
 
 
         // Success
         // Success
         if (((status >= Response.OK) && (status < Response.MULTIPLE_CHOICES)) || status == Response.UNAUTHORIZED) {
         if (((status >= Response.OK) && (status < Response.MULTIPLE_CHOICES)) || status == Response.UNAUTHORIZED) {
+            ISIPResponseProcessor processor = responseProcessorMap.get(response.getCSeqHeader().getMethod());
+            boolean invite = javax.sip.message.Request.INVITE.equals(response.getCSeqHeader().getMethod());
+            // ACK and retain before a downstream SDP callback can reject the response body.
+            if (invite && processor != null) processor.process(responseEvent);
+            if (invite && status >= 200 && status < 300 && sessionManager != null
+                    && sessionManager.hasPendingInviteRequest(response) && sessionManager.matchPendingInvite(response) == null) return;
             if (status != Response.UNAUTHORIZED && responseEvent.getResponse() != null && !sipSubscribe.isEmpty() ) {
             if (status != Response.UNAUTHORIZED && responseEvent.getResponse() != null && !sipSubscribe.isEmpty() ) {
                 CallIdHeader callIdHeader = response.getCallIdHeader();
                 CallIdHeader callIdHeader = response.getCallIdHeader();
                 CSeqHeader cSeqHeader = response.getCSeqHeader();
                 CSeqHeader cSeqHeader = response.getCSeqHeader();
@@ -94,14 +116,11 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
                             SipSubscribe.EventResult<ResponseEvent> eventResult = new SipSubscribe.EventResult<>(responseEvent);
                             SipSubscribe.EventResult<ResponseEvent> eventResult = new SipSubscribe.EventResult<>(responseEvent);
                             sipEvent.getOkEvent().response(eventResult);
                             sipEvent.getOkEvent().response(eventResult);
                         }
                         }
-                        sipSubscribe.removeSubscribe(callIdHeader.getCallId());
+                        sipSubscribe.removeSubscribe(callIdHeader.getCallId() + cSeqHeader.getSeqNumber());
                     }
                     }
                 }
                 }
             }
             }
-            ISIPResponseProcessor sipRequestProcessor = responseProcessorMap.get(response.getCSeqHeader().getMethod());
-            if (sipRequestProcessor != null) {
-                sipRequestProcessor.process(responseEvent);
-            }
+            if (!invite && processor != null) processor.process(responseEvent);
         } else if ((status >= Response.TRYING) && (status < Response.OK)) {
         } else if ((status >= Response.TRYING) && (status < Response.OK)) {
             // 增加其它无需回复的响应,如101、180等
             // 增加其它无需回复的响应,如101、180等
             // 更新sip订阅的时间
             // 更新sip订阅的时间
@@ -122,7 +141,8 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
                     }
                     }
                 }
                 }
             }
             }
-            if (responseEvent.getDialog() != null) {
+            if (responseEvent.getDialog() != null
+                    && (sessionManager == null || !sessionManager.hasByeRequest(response))) {
                 responseEvent.getDialog().delete();
                 responseEvent.getDialog().delete();
             }
             }
         }
         }

+ 78 - 14
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/cmd/impl/SIPCommander.java

@@ -337,25 +337,42 @@ public class SIPCommander implements ISIPCommander {
 
 
         Request request = headerProvider.createInviteRequest(device, channel.getDeviceId(), content.toString(), SipUtils.getNewViaTag(), SipUtils.getNewFromTag(), null, ssrcInfo.getSsrc(),sipSender.getNewCallIdHeader(sipLayer.getLocalIp(device.getLocalIp()),device.getTransport()));
         Request request = headerProvider.createInviteRequest(device, channel.getDeviceId(), content.toString(), SipUtils.getNewViaTag(), SipUtils.getNewFromTag(), null, ssrcInfo.getSsrc(),sipSender.getNewCallIdHeader(sipLayer.getLocalIp(device.getLocalIp()),device.getTransport()));
         if (managedCancelled(stream)) throw new SipException("Managed generation cancelled before INVITE dispatch");
         if (managedCancelled(stream)) throw new SipException("Managed generation cancelled before INVITE dispatch");
-        sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), request, (e -> {
+        String inviteLocalIp = sipLayer.getLocalIp(device.getLocalIp());
+        if (stream.startsWith("managed_") && !sessionManager.rememberInvite(request, mediaServerItem.getId(),
+                device.getDeviceId(), channel.getId(), channel.getDeviceId(), ssrcInfo, inviteLocalIp,
+                System.currentTimeMillis() + (timeout == null ? sipConfig.getTimeout() : timeout))) {
+            throw new SipException("Managed INVITE correlation could not be persisted");
+        }
+        if (managedCancelled(stream)) throw new SipException("Managed generation cancelled after INVITE persistence");
+        sipSender.transmitRequest(inviteLocalIp, request, (e -> {
             if (!stream.startsWith("managed_")) {
             if (!stream.startsWith("managed_")) {
                 sessionManager.removeByStream(ssrcInfo.getApp(), ssrcInfo.getStream());
                 sessionManager.removeByStream(ssrcInfo.getApp(), ssrcInfo.getStream());
                 mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
                 mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
             }
             }
             // A managed timeout/error cannot destroy a dialog retained for BYE retry.
             // A managed timeout/error cannot destroy a dialog retained for BYE retry.
-            errorEvent.response(e);
+            if (errorEvent != null) errorEvent.response(e);
         }), e -> {
         }), e -> {
+            if (!(e.event instanceof ResponseEvent)) return;
             ResponseEvent responseEvent = (ResponseEvent) e.event;
             ResponseEvent responseEvent = (ResponseEvent) e.event;
+            if (!(responseEvent.getResponse() instanceof SIPResponse)) return;
             SIPResponse response = (SIPResponse) responseEvent.getResponse();
             SIPResponse response = (SIPResponse) responseEvent.getResponse();
+            if (stream.startsWith("managed_")) {
+                com.ruoyi.wvp.gb28181.session.PendingSipInvite pending = sessionManager.matchPendingInvite(response);
+                if (pending == null || !stream.equals(pending.getStream())
+                        || !mediaServerItem.getId().equals(pending.getNodeId())
+                        || !device.getDeviceId().equals(pending.getDeviceId())
+                        || !java.util.Objects.equals(channel.getId(), pending.getChannelId())) return;
+                SsrcTransaction actual = sessionManager.restoreManagedInvite(response);
+                if (actual == null || pending.isExpired() || managedCancelled(stream)) return;
+                if (okEvent != null) okEvent.response(e);
+                return;
+            }
             String callId = response.getCallIdHeader().getCallId();
             String callId = response.getCallIdHeader().getCallId();
             SsrcTransaction ssrcTransaction = SsrcTransaction.buildForDevice(device.getDeviceId(), channel.getId(),
             SsrcTransaction ssrcTransaction = SsrcTransaction.buildForDevice(device.getDeviceId(), channel.getId(),
                     callId,ssrcInfo.getApp(), ssrcInfo.getStream(), ssrcInfo.getSsrc(), mediaServerItem.getId(), response,
                     callId,ssrcInfo.getApp(), ssrcInfo.getStream(), ssrcInfo.getSsrc(), mediaServerItem.getId(), response,
                     InviteSessionType.PLAY);
                     InviteSessionType.PLAY);
-            if (managedCancelled(stream)) {
-                log.info("[Managed INVITE] late 200 retained for ACK/BYE only: {}", stream);
-            }
             sessionManager.put(ssrcTransaction);
             sessionManager.put(ssrcTransaction);
-            okEvent.response(e);
+            if (okEvent != null) okEvent.response(e);
         }, timeout);
         }, timeout);
     }
     }
 
 
@@ -571,25 +588,72 @@ public class SIPCommander implements ISIPCommander {
 
 
         log.info("[发送BYE] 设备: device: {}, channel: {}, callId: {}", device.getDeviceId(), channelId, ssrcTransaction.getCallId());
         log.info("[发送BYE] 设备: device: {}, channel: {}, callId: {}", device.getDeviceId(), channelId, ssrcTransaction.getCallId());
         final SsrcTransaction owned = ssrcTransaction;
         final SsrcTransaction owned = ssrcTransaction;
+        if ((app != null && !java.util.Objects.equals(app, owned.getApp()))
+                || (stream != null && !java.util.Objects.equals(stream, owned.getStream())))
+            throw new SipException("BYE source does not match the retained dialog");
+        sendObservedBye(device, channelId, owned, okEvent);
+    }
+
+    private void sendObservedBye(Device device, String channelId, SsrcTransaction owned,
+                                 SipSubscribe.Event okEvent) throws InvalidArgumentException, SipException, ParseException {
         boolean managed = owned.getStream() != null && owned.getStream().startsWith("managed_");
         boolean managed = owned.getStream() != null && owned.getStream().startsWith("managed_");
         boolean adopted = sessionManager.isAdopted(owned);
         boolean adopted = sessionManager.isAdopted(owned);
         if (!managed && !adopted) sessionManager.removeByCallId(owned.getCallId());
         if (!managed && !adopted) sessionManager.removeByCallId(owned.getCallId());
-        Request byteRequest = headerProvider.createByteRequest(device, channelId, owned.getSipTransactionInfo());
-        SipSubscribe.Event response = !managed && !adopted ? okEvent : event -> {
-            if (event.statusCode >= 200 && event.statusCode < 300
-                    && (adopted ? owned.getCallId().equals(event.callId)
-                    : event.callId == null || owned.getCallId().equals(event.callId))) {
-                if (adopted) sessionManager.removeAdoptedIfSame(owned);
-                else sessionManager.removeManagedIfSame(owned);
+        Device byeDevice = device;
+        String byeLocalIp = sipLayer.getLocalIp(device.getLocalIp());
+        if (managed || adopted) {
+            if (!java.util.Objects.equals(device.getDeviceId(), owned.getDeviceId())) {
+                throw new SipException("BYE source does not match the retained dialog");
             }
             }
+            if (managed) {
+                com.ruoyi.wvp.gb28181.session.PendingSipInvite pending = sessionManager.getPendingInviteByStream(owned.getApp(), owned.getStream());
+                if (pending != null && java.util.Objects.equals(pending.getBinding().getCallId(), owned.getCallId())
+                        && java.util.Objects.equals(pending.getNodeId(), owned.getMediaServerId())
+                        && java.util.Objects.equals(pending.getDeviceId(), owned.getDeviceId())
+                        && java.util.Objects.equals(pending.getChannelId(), owned.getChannelId())) {
+                    if (!java.util.Objects.equals(channelId, pending.getChannelSipId())) throw new SipException("BYE channel source changed");
+                    byeLocalIp = pending.getLocalIp();
+                    byeDevice = new Device();
+                    org.springframework.beans.BeanUtils.copyProperties(device, byeDevice);
+                    byeDevice.setLocalIp(byeLocalIp);
+                }
+            }
+        }
+        Request byteRequest = headerProvider.createByteRequest(byeDevice, channelId, owned.getSipTransactionInfo());
+        if ((managed || adopted) && !sessionManager.rememberBye(byteRequest, owned)) {
+            throw new SipException("BYE correlation could not be persisted for the owned dialog");
+        }
+        SipSubscribe.Event response = !managed && !adopted ? okEvent : event -> {
+            if (!(event.event instanceof ResponseEvent)) return;
+            ResponseEvent actual = (ResponseEvent) event.event;
+            if (!(actual.getResponse() instanceof SIPResponse)) return;
+            SsrcTransaction confirmed = sessionManager.confirmBye((SIPResponse) actual.getResponse());
+            if (!SipInviteSessionManager.sameDialog(owned, confirmed)) return;
+            // A matching durable receipt must precede both dialog deletion and the caller callback.
+            if (adopted) sessionManager.removeAdoptedIfSame(owned);
+            else sessionManager.removeManagedIfSame(owned);
             if (okEvent != null) okEvent.response(event);
             if (okEvent != null) okEvent.response(event);
         };
         };
         // Managed transport errors leave the actual dialog available for retry.
         // Managed transport errors leave the actual dialog available for retry.
-        sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), byteRequest, null, response);
+        sipSender.transmitRequest(byeLocalIp, byteRequest, null, response);
     }
     }
 
 
     @Override
     @Override
     public void streamByeCmd(Device device, String channelId, SipTransactionInfo sipTransactionInfo, SipSubscribe.Event okEvent) throws InvalidArgumentException, SipException, ParseException, SsrcTransactionNotFoundException {
     public void streamByeCmd(Device device, String channelId, SipTransactionInfo sipTransactionInfo, SipSubscribe.Event okEvent) throws InvalidArgumentException, SipException, ParseException, SsrcTransactionNotFoundException {
+        if (device == null || sipTransactionInfo == null || sipTransactionInfo.getCallId() == null)
+            throw new SipException("Original BYE dialog is required");
+        SsrcTransaction owned = sessionManager.getSsrcTransactionByCallId(sipTransactionInfo.getCallId());
+        if (owned != null) {
+            SsrcTransaction expected = new SsrcTransaction();
+            org.springframework.beans.BeanUtils.copyProperties(owned, expected);
+            expected.setSipTransactionInfo(sipTransactionInfo);
+            if (!SipInviteSessionManager.sameDialog(owned, expected))
+                throw new SipException("Original BYE tags no longer match the live dialog");
+            if ((owned.getStream() != null && owned.getStream().startsWith("managed_")) || sessionManager.isAdopted(owned)) {
+                sendObservedBye(device, channelId, expected, okEvent);
+                return;
+            }
+        }
         Request byteRequest = headerProvider.createByteRequest(device, channelId, sipTransactionInfo);
         Request byteRequest = headerProvider.createByteRequest(device, channelId, sipTransactionInfo);
         sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), byteRequest, null, okEvent);
         sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), byteRequest, null, okEvent);
     }
     }

+ 13 - 8
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/event/request/impl/ByeRequestProcessor.java

@@ -11,6 +11,7 @@ import com.ruoyi.wvp.gb28181.transmit.cmd.ISIPCommander;
 import com.ruoyi.wvp.gb28181.transmit.event.request.ISIPRequestProcessor;
 import com.ruoyi.wvp.gb28181.transmit.event.request.ISIPRequestProcessor;
 import com.ruoyi.wvp.gb28181.transmit.event.request.SIPRequestProcessorParent;
 import com.ruoyi.wvp.gb28181.transmit.event.request.SIPRequestProcessorParent;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
 import com.ruoyi.wvp.storager.IRedisCatchStorage;
 import com.ruoyi.wvp.storager.IRedisCatchStorage;
 import gov.nist.javax.sip.message.SIPRequest;
 import gov.nist.javax.sip.message.SIPRequest;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
@@ -52,6 +53,9 @@ public class ByeRequestProcessor extends SIPRequestProcessorParent implements In
 	@Autowired
 	@Autowired
 	private IMediaServerService mediaServerService;
 	private IMediaServerService mediaServerService;
 
 
+    @Autowired
+    private RtpServerServiceImpl rtpServerService;
+
 	@Autowired
 	@Autowired
 	private SIPProcessorObserver sipProcessorObserver;
 	private SIPProcessorObserver sipProcessorObserver;
 
 
@@ -77,21 +81,22 @@ public class ByeRequestProcessor extends SIPRequestProcessorParent implements In
 	@Override
 	@Override
 	public void process(RequestEvent evt) {
 	public void process(RequestEvent evt) {
         SIPRequest request = (SIPRequest) evt.getRequest();
         SIPRequest request = (SIPRequest) evt.getRequest();
+        CallIdHeader callId = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
+        SsrcTransaction transaction = callId == null ? null : sessionManager.getSsrcTransactionByCallId(callId.getCallId());
         try {
         try {
             responseAck(request, Response.OK);
             responseAck(request, Response.OK);
         } catch (SipException | InvalidArgumentException | ParseException e) {
         } catch (SipException | InvalidArgumentException | ParseException e) {
             log.error("[BYE] Reply failed", e);
             log.error("[BYE] Reply failed", e);
+            return;
         }
         }
-        CallIdHeader callId = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
-        SsrcTransaction transaction = sessionManager.getSsrcTransactionByCallId(callId.getCallId());
-        if (transaction == null) return;
-        // Match the exact stream and session type; playback must not remove a live session.
+        // The request must match the pre-reply snapshot and both indexes at the durable write.
+        if (!sessionManager.rememberPeerBye(request, transaction)) return;
+        // Freeze original evidence before any Invite/dialog removal; unknown close stays retryable.
         InviteInfo info = inviteStreamService.getInviteInfo(transaction.getType(), transaction.getChannelId(), transaction.getStream());
         InviteInfo info = inviteStreamService.getInviteInfo(transaction.getType(), transaction.getChannelId(), transaction.getStream());
-        if (info != null) inviteStreamService.removeInviteInfo(info);
+        if (!rtpServerService.closeRTPServerForSession(transaction, info)) return;
+        if (info != null && !inviteStreamService.removeInviteInfoIfSame(info)) return;
+        if (!sessionManager.removeIfSame(transaction)) return;
         if (transaction.getType() == InviteSessionType.PLAY) deviceChannelService.stopPlay(transaction.getChannelId());
         if (transaction.getType() == InviteSessionType.PLAY) deviceChannelService.stopPlay(transaction.getChannelId());
-        mediaServerService.closeRTPServer(transaction.getMediaServerId(), transaction.getStream());
-        mediaServerService.releaseSsrc(transaction.getMediaServerId(), transaction.getSsrc());
-        sessionManager.removeByCallId(transaction.getCallId());
 
 
     }
     }
 }
 }

+ 100 - 62
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/event/response/impl/InviteResponseProcessor.java

@@ -1,89 +1,127 @@
 package com.ruoyi.wvp.gb28181.transmit.event.response.impl;
 package com.ruoyi.wvp.gb28181.transmit.event.response.impl;
 
 
-import com.ruoyi.wvp.gb28181.bean.Gb28181Sdp;
+import com.ruoyi.wvp.gb28181.bean.*;
+import com.ruoyi.wvp.gb28181.service.IDeviceChannelService;
+import com.ruoyi.wvp.gb28181.service.IPlayService;
+import com.ruoyi.wvp.gb28181.session.PendingSipInvite;
+import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
 import com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver;
 import com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver;
 import com.ruoyi.wvp.gb28181.transmit.SIPSender;
 import com.ruoyi.wvp.gb28181.transmit.SIPSender;
 import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
 import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
 import com.ruoyi.wvp.gb28181.transmit.event.response.SIPResponseProcessorAbstract;
 import com.ruoyi.wvp.gb28181.transmit.event.response.SIPResponseProcessorAbstract;
 import com.ruoyi.wvp.gb28181.utils.SipUtils;
 import com.ruoyi.wvp.gb28181.utils.SipUtils;
+import com.ruoyi.wvp.media.bean.MediaServer;
+import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.storager.IRedisCatchStorage;
+import com.zksy.video.lifecycle.VideoLifecycleStore;
 import gov.nist.javax.sip.ResponseEventExt;
 import gov.nist.javax.sip.ResponseEventExt;
 import gov.nist.javax.sip.message.SIPResponse;
 import gov.nist.javax.sip.message.SIPResponse;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Lazy;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
-import javax.sdp.SdpParseException;
-import javax.sdp.SessionDescription;
-import javax.sip.InvalidArgumentException;
 import javax.sip.ResponseEvent;
 import javax.sip.ResponseEvent;
-import javax.sip.SipException;
 import javax.sip.SipFactory;
 import javax.sip.SipFactory;
 import javax.sip.address.SipURI;
 import javax.sip.address.SipURI;
 import javax.sip.message.Request;
 import javax.sip.message.Request;
 import javax.sip.message.Response;
 import javax.sip.message.Response;
-import java.text.ParseException;
+import java.nio.charset.StandardCharsets;
+import java.util.Objects;
 
 
-
-/**
- * @description: 处理INVITE响应
- * @author: panlinlin
- * @date: 2021年11月5日 16:40
- */
+/** ACK all INVITE 200s as before; recover managed dialogs only through the durable outgoing binding. */
 @Slf4j
 @Slf4j
 @Component
 @Component
 public class InviteResponseProcessor extends SIPResponseProcessorAbstract {
 public class InviteResponseProcessor extends SIPResponseProcessorAbstract {
+    @Autowired private SIPProcessorObserver sipProcessorObserver;
+    @Autowired private SIPSender sipSender;
+    @Autowired private SIPRequestHeaderProvider headerProvider;
+    @Autowired private SipInviteSessionManager sessionManager;
+    @Autowired private VideoLifecycleStore videoLifecycleStore;
+    @Autowired private IMediaServerService mediaServerService;
+    @Autowired private IRedisCatchStorage redisCatchStorage;
+    @Autowired private IDeviceChannelService deviceChannelService;
+    @Lazy @Autowired private IPlayService playService;
 
 
-	private final String method = "INVITE";
-
-	@Autowired
-	private SIPProcessorObserver sipProcessorObserver;
-
-	@Autowired
-	private SIPSender sipSender;
-
-	@Autowired
-	private SIPRequestHeaderProvider headerProvider;
-
-	@Override
-	public void afterPropertiesSet() throws Exception {
-		// 添加消息处理的订阅
-		sipProcessorObserver.addResponseProcessor(method, this);
-	}
-
-
-
-	/**
-	 * 处理invite响应
-	 *
-	 * @param evt 响应消息
-	 * @throws ParseException
-	 */
-	@Override
-	public void process(ResponseEvent evt ){
-		log.debug("接收到消息:" + evt.getResponse());
-		try {
-			SIPResponse response = (SIPResponse)evt.getResponse();
-			int statusCode = response.getStatusCode();
-			// trying不会回复
-			if (statusCode == Response.TRYING) {
-			}
-			// 成功响应
-			// 下发ack
-			if (statusCode == Response.OK) {
-				ResponseEventExt event = (ResponseEventExt)evt;
+    @Override public void afterPropertiesSet() { sipProcessorObserver.addResponseProcessor(Request.INVITE, this); }
 
 
-				String contentString = new String(response.getRawContent());
-				Gb28181Sdp gb28181Sdp = SipUtils.parseSDP(contentString);
-				SessionDescription sdp = gb28181Sdp.getBaseSdb();
-				SipURI requestUri = SipFactory.getInstance().createAddressFactory().createSipURI(sdp.getOrigin().getUsername(), event.getRemoteIpAddress() + ":" + event.getRemotePort());
-				Request reqAck = headerProvider.createAckRequest(response.getLocalAddress().getHostAddress(), requestUri, response);
+    @Override public void process(ResponseEvent event) {
+        if (!(event.getResponse() instanceof SIPResponse)) return;
+        SIPResponse response = (SIPResponse) event.getResponse();
+        if (response.getStatusCode() != Response.OK || response.getCSeqHeader() == null
+                || !Request.INVITE.equals(response.getCSeqHeader().getMethod())) return;
+        PendingSipInvite pending = null;
+        SsrcTransaction restored = null;
+        // Retention and ACK are separate: persistence outages or malformed SDP must not suppress legacy ACK.
+        try {
+            if (sessionManager != null) {
+                pending = sessionManager.matchPendingInvite(response);
+                if (pending != null) restored = sessionManager.restoreManagedInvite(response);
+            }
+        } catch (RuntimeException ex) {
+            log.warn("[INVITE recovery] persistence unavailable; ACK still required");
+        }
+        try {
+            ResponseEventExt remote = (ResponseEventExt) event;
+            String localIp = pending == null ? response.getLocalAddress().getHostAddress() : pending.getLocalIp();
+            String user = pending == null ? ackUser(response) : pending.getChannelSipId();
+            SipURI target = SipFactory.getInstance().createAddressFactory().createSipURI(user, remote.getRemoteIpAddress());
+            target.setPort(remote.getRemotePort());
+            Request ack = headerProvider.createAckRequest(localIp, target, response);
+            sipSender.transmitRequest(localIp, ack);
+        } catch (Exception ex) {
+            // Never log complete SIP/SDP bodies or credential-bearing source objects.
+            log.warn("[INVITE ACK] send failed; retained dialog remains retryable");
+            return;
+        }
+        if (pending != null && restored != null) cleanupLate(pending, restored);
+    }
 
 
-				log.info("[回复ack] {}-> {}:{} ", sdp.getOrigin().getUsername(), event.getRemoteIpAddress(), event.getRemotePort());
-				sipSender.transmitRequest( response.getLocalAddress().getHostAddress(), reqAck);
-			}
-		} catch (InvalidArgumentException | ParseException | SipException | SdpParseException e) {
-			log.info("[点播回复ACK],异常:", e );
-		}
-	}
+    private String ackUser(SIPResponse response) {
+        // Preserve the SDP-origin username used by legacy devices when parsable.
+        try {
+            if (response.getRawContent() != null) {
+                String user = SipUtils.parseSDP(new String(response.getRawContent(), StandardCharsets.UTF_8))
+                        .getBaseSdb().getOrigin().getUsername();
+                if (user != null && !user.isEmpty()) return user;
+            }
+        } catch (Exception ignored) { /* Established dialog headers remain usable without SDP. */ }
+        if (response.getToHeader() != null && response.getToHeader().getAddress().getURI() instanceof SipURI)
+            return ((SipURI) response.getToHeader().getAddress().getURI()).getUser();
+        return null;
+    }
 
 
+    private void cleanupLate(PendingSipInvite pending, SsrcTransaction restored) {
+        try {
+            if (videoLifecycleStore == null) return;
+            boolean cancelled = videoLifecycleStore.isStreamCancelled(pending.getStream());
+            if (!cancelled) {
+                String compact = pending.getStream().substring("managed_".length());
+                if (!compact.matches("[0-9a-fA-F]{32}")) return;
+                String generation = compact.substring(0, 8) + "-" + compact.substring(8, 12) + "-"
+                        + compact.substring(12, 16) + "-" + compact.substring(16, 20) + "-" + compact.substring(20);
+                com.zksy.video.lifecycle.VideoLifecycleRecord current = videoLifecycleStore.find(generation.toLowerCase(java.util.Locale.ROOT));
+                if (current == null) return; // Lost ownership evidence is not an instruction to stop a live camera.
+                cancelled = current.isCancelled() || "CLEANUP_PENDING".equals(current.getStatus())
+                        || "STOPPED".equals(current.getStatus()) || "FAILED".equals(current.getStatus());
+                // INVITE retransmissions can arrive long after healthy playback began. The
+                // original start deadline does not expire ACTIVE generations or their viewers.
+                if (!cancelled && !("STARTING".equals(current.getStatus()) && current.getDeadline() != null
+                        && current.getDeadline() <= System.currentTimeMillis())) return;
+            }
+            videoLifecycleStore.markStreamCancelled(pending.getStream());
+            // No default node, SDP-derived source or unscoped channel lookup is permitted here.
+            MediaServer node = mediaServerService.getOne(pending.getNodeId());
+            Device device = redisCatchStorage.getDevice(pending.getDeviceId());
+            DeviceChannel channel = deviceChannelService.getOneForSource(pending.getDeviceId(), pending.getChannelSipId());
+            if (node == null || device == null || channel == null || !Objects.equals(pending.getNodeId(), node.getId())
+                    || !Objects.equals(pending.getDeviceId(), device.getDeviceId())
+                    || !Objects.equals(pending.getChannelId(), channel.getId())
+                    || !Objects.equals(pending.getChannelSipId(), channel.getDeviceId())
+                    || !SipInviteSessionManager.sameDialog(restored, sessionManager.getSsrcTransactionByStream(pending.getApp(), pending.getStream()))) return;
+            playService.stopManaged(node, device, channel, pending.getStream());
+        } catch (RuntimeException ex) {
+            log.warn("[INVITE recovery] original-source cleanup remains pending");
+        }
+    }
 }
 }

+ 213 - 95
video-service/src/main/java/com/ruoyi/wvp/service/impl/RtpServerServiceImpl.java

@@ -1,8 +1,10 @@
 package com.ruoyi.wvp.service.impl;
 package com.ruoyi.wvp.service.impl;
 
 
+import com.ruoyi.wvp.common.InviteInfo;
 import com.ruoyi.wvp.conf.DynamicTask;
 import com.ruoyi.wvp.conf.DynamicTask;
 import com.ruoyi.wvp.conf.UserSetting;
 import com.ruoyi.wvp.conf.UserSetting;
 import com.ruoyi.wvp.gb28181.bean.OpenRTPServerResult;
 import com.ruoyi.wvp.gb28181.bean.OpenRTPServerResult;
+import com.ruoyi.wvp.gb28181.bean.SsrcTransaction;
 import com.ruoyi.wvp.gb28181.session.SSRCFactory;
 import com.ruoyi.wvp.gb28181.session.SSRCFactory;
 import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
 import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
 import com.ruoyi.wvp.media.bean.MediaServer;
 import com.ruoyi.wvp.media.bean.MediaServer;
@@ -17,13 +19,19 @@ import com.ruoyi.wvp.service.bean.ErrorCallback;
 import com.ruoyi.wvp.service.bean.InviteErrorCode;
 import com.ruoyi.wvp.service.bean.InviteErrorCode;
 import com.ruoyi.wvp.service.bean.RTPServerParam;
 import com.ruoyi.wvp.service.bean.RTPServerParam;
 import com.ruoyi.wvp.service.bean.SSRCInfo;
 import com.ruoyi.wvp.service.bean.SSRCInfo;
+import com.zksy.video.lifecycle.VideoStopReceipts;
+import com.zksy.video.lifecycle.VideoStopReceipts.Allocation;
+import com.zksy.video.lifecycle.VideoStopReceipts.RtpState;
+import com.zksy.video.lifecycle.VideoStopReceipts.Snapshot;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.event.EventListener;
 import org.springframework.context.event.EventListener;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
+import java.util.Objects;
 import java.util.UUID;
 import java.util.UUID;
+import java.util.function.Predicate;
 
 
 @Slf4j
 @Slf4j
 @Service
 @Service
@@ -68,6 +76,10 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
     @Autowired
     @Autowired
     private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
     private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
 
 
+    @Autowired
+    private VideoStopReceipts stopReceipts;
+
+    // Only callback/timer ownership is local. No field here is stop evidence.
     private final java.util.concurrent.ConcurrentMap<String, ManagedRtp> managedRtp = new java.util.concurrent.ConcurrentHashMap<>();
     private final java.util.concurrent.ConcurrentMap<String, ManagedRtp> managedRtp = new java.util.concurrent.ConcurrentHashMap<>();
 
 
     private static final class ManagedRtp {
     private static final class ManagedRtp {
@@ -75,8 +87,6 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         private HookSubscribe.Subscription owner;
         private HookSubscribe.Subscription owner;
         private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
         private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
         private final java.util.concurrent.atomic.AtomicBoolean released = new java.util.concurrent.atomic.AtomicBoolean();
         private final java.util.concurrent.atomic.AtomicBoolean released = new java.util.concurrent.atomic.AtomicBoolean();
-        private volatile boolean closed;
-        private volatile boolean opening = true;
         private ManagedRtp(SSRCInfo info) { this.info = info; }
         private ManagedRtp(SSRCInfo info) { this.info = info; }
     }
     }
 
 
@@ -84,6 +94,90 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         return Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId()).toString();
         return Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId()).toString();
     }
     }
 
 
+    private boolean reserveAllocation(MediaServer node, SSRCInfo info, boolean externalSsrc) {
+        if (stopReceipts == null) return false;
+        return stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
+            if (!snapshot.canReplaceAllocation()) return null;
+            if (info.getStream().startsWith("managed_") && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null;
+            Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey();
+            allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.INTENT;
+            allocation.poolTracked = !externalSsrc; allocation.externalSsrc = externalSsrc;
+            snapshot.allocation = allocation;
+            VideoStopReceipts.Play play = snapshot.plays.get(info.getStream());
+            if (play != null) play.allocationToken = allocation.token;
+            return snapshot;
+        }) != null;
+    }
+
+    private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next) {
+        return allocationState(node, info, expected, next, snapshot -> true);
+    }
+
+    private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next,
+                                    Predicate<Snapshot> actorGuard) {
+        if (stopReceipts == null) return false;
+        for (int attempt = 0; attempt < 4; attempt++) {
+            Snapshot updated = stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
+                Allocation allocation = snapshot.allocation;
+                if (allocation == null || !allocation.matches(info) || allocation.state != expected || !actorGuard.test(snapshot)) return null;
+                if (next == RtpState.CREATING && info.getStream().startsWith("managed_")
+                        && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null;
+                allocation.state = next; allocation.port = info.getPort(); return snapshot;
+            });
+            if (updated != null) return true;
+            Snapshot latest = stopReceipts.read(node.getId(), info.getStream());
+            if (latest == null || latest.allocation == null || !latest.allocation.matches(info)
+                    || latest.allocation.state != expected) return false;
+        }
+        return false;
+    }
+
+    private boolean closeAllocation(MediaServer node, SSRCInfo info) {
+        return closeAllocation(node, info, snapshot -> true);
+    }
+
+    private boolean closeAllocation(MediaServer node, SSRCInfo info, Predicate<Snapshot> actorGuard) {
+        if (stopReceipts == null || info == null || info.getStream() == null || info.getTimeOutTaskKey() == null
+                || info.getSsrc() == null || !"rtp".equals(info.getApp())) return false;
+        Snapshot retained = stopReceipts.read(node.getId(), info.getStream());
+        if ((retained == null || retained.allocation == null) && !info.getStream().startsWith("managed_")) {
+            // Pre-upgrade legacy callers retain the original typed allocation. Never replace a newer token,
+            // reconstruct a managed/adopted receipt, or treat absence as a positive stop acknowledgement.
+            retained = stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
+                if (snapshot.allocation != null || !snapshot.plays.isEmpty() || !actorGuard.test(snapshot)
+                        || (sessionManager != null && sessionManager.isAdoptedAllocation(node.getId(), info))) return null;
+                Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey();
+                allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.OPEN;
+                snapshot.allocation = allocation; return snapshot;
+            });
+        }
+        if (retained == null || retained.allocation == null || !retained.allocation.matches(info) || !actorGuard.test(retained)) return false;
+        if (retained.allocation.terminal()) return true;
+        if (retained.allocation.state == RtpState.INTENT) {
+            // CAS competes with the creator's INTENT -> CREATING, so this is positive never-created evidence.
+            return allocationState(node, info, RtpState.INTENT, RtpState.NEVER_CREATED, actorGuard);
+        }
+        // A process lost during create/close cannot infer completion or send another name-based command.
+        if (!allocationState(node, info, RtpState.OPEN, RtpState.CLOSING, actorGuard)) return false;
+        try {
+            mediaServerService.closeRTPServer(node, info.getStream(), closed -> {
+                // Boolean true is the ZLM adapter's code=0/hit=1 receipt, not a request-send result.
+                // Retry only shared state CAS inside allocationState, never the external name-close.
+                if (!Boolean.TRUE.equals(closed)) return;
+                if (!allocationState(node, info, RtpState.CLOSING, RtpState.CLOSED)) return;
+                // A late positive receipt must finish pool cleanup even when the caller already
+                // returned and no second stop is ever issued.
+                try { releaseClosedSsrc(node, info); }
+                catch (RuntimeException ex) { log.warn("[RTP close return] {}/{}: {}", node.getId(), info.getStream(), ex.getMessage()); }
+            });
+        } catch (RuntimeException ex) {
+            log.warn("[RTP close] {}/{} remains pending: {}", node.getId(), info.getStream(), ex.getMessage());
+        }
+        Snapshot after = stopReceipts.read(node.getId(), info.getStream());
+        return after != null && after.allocation != null && after.allocation.matches(info)
+                && after.allocation.state == RtpState.CLOSED;
+    }
+
     private boolean cancelled(String stream) {
     private boolean cancelled(String stream) {
         // Managed resource creation fails closed without the cancellation persistence seam.
         // Managed resource creation fails closed without the cancellation persistence seam.
         return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
         return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
@@ -97,30 +191,35 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
             if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP requires a unique stream, multi-port node and live generation", null);
             if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP requires a unique stream, multi-port node and live generation", null);
             return null;
             return null;
         }
         }
-        ManagedRtp entry = new ManagedRtp(new SSRCInfo(0, null, "rtp", stream, java.util.UUID.randomUUID().toString()));
+        // The stream is a single-use generation identity; use it for the pool request too,
+        // so cancellation can fence/recover an acquisition whose reply was lost before RTP registration.
+        ManagedRtp entry = new ManagedRtp(new SSRCInfo(0, null, "rtp", stream, stream));
         if (managedRtp.putIfAbsent(managedKey(node, stream), entry) != null) {
         if (managedRtp.putIfAbsent(managedKey(node, stream), entry) != null) {
             callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP generation already allocated", null);
             callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP generation already allocated", null);
             return null;
             return null;
         }
         }
         try {
         try {
-            if (cancelled(stream)) {
-                entry.opening = false; entry.closed = true;
+            entry.info.setSsrc(ssrcFactory.getPlaySsrc(node.getId(), entry.info.getTimeOutTaskKey()));
+            if (!reserveAllocation(node, entry.info, false)) {
+                Snapshot current = stopReceipts.read(node.getId(), stream);
+                if (current == null || current.allocation == null || !current.allocation.matches(entry.info))
+                    releaseManagedSsrc(node, entry);
+                callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation is already retained", null);
                 return null;
                 return null;
             }
             }
-            entry.info.setSsrc(ssrcFactory.getPlaySsrc(node.getId()));
             if (cancelled(stream)) {
             if (cancelled(stream)) {
-                entry.opening = false;
-                entry.closed = true;
-                releaseManagedSsrc(node, entry);
+                closeManagedRTPServer(node, entry.info);
                 return null;
                 return null;
             }
             }
+            if (!allocationState(node, entry.info, RtpState.INTENT, RtpState.CREATING)) {
+                closeManagedRTPServer(node, entry.info); return null;
+            }
             int port = mediaServerService.createRTPServer(node, stream,
             int port = mediaServerService.createRTPServer(node, stream,
                     param.isSsrcCheck() ? Long.parseLong(entry.info.getSsrc()) : 0,
                     param.isSsrcCheck() ? Long.parseLong(entry.info.getSsrc()) : 0,
                     0, false, param.isDisableAudio(), false, param.getTcpMode());
                     0, false, param.isDisableAudio(), false, param.getTcpMode());
             entry.info.setPort(port);
             entry.info.setPort(port);
-            entry.opening = false;
-            // A close response obtained while create was in-flight cannot prove the newly returned allocation closed.
-            entry.closed = false;
+            // Only the creator knows create returned. Restart during create remains CREATING.
+            if (!allocationState(node, entry.info, RtpState.CREATING, RtpState.OPEN)) return null;
             if (port <= 0 || cancelled(stream) || entry.terminal.get()) {
             if (port <= 0 || cancelled(stream) || entry.terminal.get()) {
                 closeManagedRTPServer(node, entry.info);
                 closeManagedRTPServer(node, entry.info);
                 callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation failed or was cancelled", null);
                 callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation failed or was cancelled", null);
@@ -164,7 +263,7 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
             if (entry.terminal.get()) dynamicTask.stop(entry.info.getTimeOutTaskKey());
             if (entry.terminal.get()) dynamicTask.stop(entry.info.getTimeOutTaskKey());
             return entry.info;
             return entry.info;
         } catch (RuntimeException ex) {
         } catch (RuntimeException ex) {
-            entry.opening = false;
+            // An ambiguous create/receipt write is not proof that the port never existed.
             closeManagedRTPServer(node, entry.info);
             closeManagedRTPServer(node, entry.info);
             callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation uncertain: " + ex.getMessage(), null);
             callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation uncertain: " + ex.getMessage(), null);
             return null;
             return null;
@@ -172,39 +271,50 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
     }
     }
 
 
     private void releaseManagedSsrc(MediaServer node, ManagedRtp entry) {
     private void releaseManagedSsrc(MediaServer node, ManagedRtp entry) {
-        if (entry.info.getSsrc() != null && entry.released.compareAndSet(false, true)) {
-            ssrcFactory.releaseSsrc(node.getId(), entry.info.getSsrc());
+        if (entry.info.getSsrc() != null) {
+            ssrcFactory.releaseSsrc(node.getId(), entry.info.getSsrc(), entry.info.getTimeOutTaskKey());
         }
         }
     }
     }
 
 
+    /** A completed port close is not full cleanup until its pool allocation was returned.
+     * The Factory receipt is atomic with SADD and remains valid after the SN is reused. */
+    private boolean releaseClosedSsrc(MediaServer node, SSRCInfo info) {
+        Snapshot snapshot = stopReceipts.read(node.getId(), info.getStream());
+        if (snapshot == null || snapshot.allocation == null || !snapshot.allocation.matches(info)
+                || !snapshot.allocation.terminal()) return false;
+        Allocation allocation = snapshot.allocation;
+        if (allocation.externalSsrc || allocation.poolSsrc() == null || allocation.poolReturned) return true;
+        String poolSsrc = allocation.poolSsrc(), token = allocation.token;
+        if (ssrcFactory.wasReleased(node.getId(), poolSsrc, token)) return true;
+        // Return the originally allocated number, never a device-negotiated SSRC.
+        boolean released = allocation.poolTracked
+                ? ssrcFactory.releaseSsrc(node.getId(), poolSsrc, token)
+                : ssrcFactory.releaseObservedLegacySsrc(node.getId(), poolSsrc, token);
+        return released || ssrcFactory.wasReleased(node.getId(), poolSsrc, token);
+    }
+
     @Override
     @Override
     public boolean closeManagedRTPServer(MediaServer node, SSRCInfo info) {
     public boolean closeManagedRTPServer(MediaServer node, SSRCInfo info) {
         if (node == null || node.getId() == null || info == null || info.getStream() == null
         if (node == null || node.getId() == null || info == null || info.getStream() == null
                 || !info.getStream().matches("managed_[0-9a-fA-F]{32}")) return false;
                 || !info.getStream().matches("managed_[0-9a-fA-F]{32}")) return false;
-        ManagedRtp entry = managedRtp.computeIfAbsent(managedKey(node, info.getStream()), key -> {
-            ManagedRtp adopted = new ManagedRtp(info); adopted.opening = false; return adopted;
-        });
-        entry.terminal.set(true);
-        // Remove local ownership even when the remote close throws or never answers.
-        try {
-            if (entry.info.getTimeOutTaskKey() != null) dynamicTask.stop(entry.info.getTimeOutTaskKey());
-        } catch (RuntimeException ex) {
-            log.warn("[Managed timer close] {}: {}", info.getStream(), ex.getMessage());
-        } finally {
-            subscribe.removeOwnedSubscribe(entry.owner);
+        if (stopReceipts != null) {
+            Snapshot pending = stopReceipts.read(node.getId(), info.getStream());
+            VideoStopReceipts.Play intent = pending == null ? null : pending.plays.get(info.getStream());
+            if (pending != null && pending.allocation == null && intent != null && intent.cancelled
+                    && !intent.inviteSent && info.getStream().equals(info.getTimeOutTaskKey()))
+                return ssrcFactory.cancelAllocation(node.getId(), info.getStream());
         }
         }
-        if (entry.closed) return true;
-        try {
-            mediaServerService.closeRTPServer(node, info.getStream(), closed -> {
-                if (Boolean.TRUE.equals(closed) && !entry.opening) {
-                    entry.closed = true;
-                    releaseManagedSsrc(node, entry);
-                }
-            });
-        } catch (RuntimeException ex) {
-            log.warn("[Managed RTP close] {}/{} remains uncertain: {}", node.getId(), info.getStream(), ex.getMessage());
+        ManagedRtp entry = managedRtp.get(managedKey(node, info.getStream()));
+        if (entry != null) {
+            entry.terminal.set(true);
+            try {
+                if (entry.info.getTimeOutTaskKey() != null) dynamicTask.stop(entry.info.getTimeOutTaskKey());
+            } catch (RuntimeException ex) {
+                log.warn("[Managed timer close] {}: {}", info.getStream(), ex.getMessage());
+            } finally { subscribe.removeOwnedSubscribe(entry.owner); }
         }
         }
-        return entry.closed;
+        boolean closed = closeAllocation(node, info);
+        return closed && releaseClosedSsrc(node, info);
     }
     }
 
 
     /** Unlike managed UUIDs, legacy names can be allocated again. Keep the allocation token, not a name receipt. */
     /** Unlike managed UUIDs, legacy names can be allocated again. Keep the allocation token, not a name receipt. */
@@ -215,10 +325,6 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         private HookSubscribe.Subscription owner;
         private HookSubscribe.Subscription owner;
         private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
         private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
         private final java.util.concurrent.atomic.AtomicBoolean released = new java.util.concurrent.atomic.AtomicBoolean();
         private final java.util.concurrent.atomic.AtomicBoolean released = new java.util.concurrent.atomic.AtomicBoolean();
-        private String callId;
-        private boolean closing;
-        private volatile boolean closed;
-        private volatile boolean opening = true;
         private LegacyRtp(SSRCInfo info) { this.info = info; }
         private LegacyRtp(SSRCInfo info) { this.info = info; }
     }
     }
 
 
@@ -227,42 +333,28 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         if (node == null || node.getId() == null || !node.isRtpEnable() || info == null
         if (node == null || node.getId() == null || !node.isRtpEnable() || info == null
                 || info.getStream() == null || info.getStream().startsWith("managed_") || !"rtp".equals(info.getApp())
                 || info.getStream() == null || info.getStream().startsWith("managed_") || !"rtp".equals(info.getApp())
                 || info.getSsrc() == null || info.getTimeOutTaskKey() == null || callId == null
                 || info.getSsrc() == null || info.getTimeOutTaskKey() == null || callId == null
-                || sessionManager == null || !sessionManager.isAdoptedRtp(node.getId(), callId, info)) return false;
+                || sessionManager == null || stopReceipts == null || !sessionManager.isAdoptedRtp(node.getId(), callId, info)) return false;
         String key = managedKey(node, info.getStream());
         String key = managedKey(node, info.getStream());
         LegacyRtp entry = legacyRtp.get(key);
         LegacyRtp entry = legacyRtp.get(key);
-        if (entry != null && (!entry.info.equals(info) || entry.opening
-                || (entry.callId != null && !entry.callId.equals(callId)))) return false;
+        if (entry != null && !entry.info.equals(info)) entry = null; // stale local timer owner is not allocation evidence
         com.ruoyi.wvp.gb28181.bean.SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", info.getStream());
         com.ruoyi.wvp.gb28181.bean.SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", info.getStream());
         if (current != null && (!callId.equals(current.getCallId()) || !info.getSsrc().equals(current.getSsrc())
         if (current != null && (!callId.equals(current.getCallId()) || !info.getSsrc().equals(current.getSsrc())
                 || !node.getId().equals(current.getMediaServerId()) || !sessionManager.isAdopted(current))) return false;
                 || !node.getId().equals(current.getMediaServerId()) || !sessionManager.isAdopted(current))) return false;
-        if (entry == null) {
-            // Only Play's already observed Invite/dialog supplies this handle, never media-list guesses.
-            entry = new LegacyRtp(info); entry.opening = false; legacyRtp.put(key, entry);
-        }
-        entry.callId = callId;
-        final LegacyRtp owned = entry;
-        owned.terminal.set(true);
+        Snapshot retained = stopReceipts.read(node.getId(), info.getStream());
+        if (retained == null || retained.allocation == null || !retained.allocation.matches(info)
+                || !callId.equals(retained.allocation.callId)) return false;
+        com.ruoyi.wvp.gb28181.bean.SsrcTransaction expected = retained.plays.values().stream()
+                .filter(play -> java.util.Objects.equals(play.allocationToken, info.getTimeOutTaskKey())
+                        && play.dialog != null && callId.equals(play.dialog.getCallId()))
+                .map(play -> play.dialog).findFirst().orElse(null);
+        if (expected == null || !sessionManager.isAdopted(expected)
+                || (current != null && !SipInviteSessionManager.sameDialog(expected, current))) return false;
+        if (entry != null) entry.terminal.set(true);
         try { dynamicTask.stop(info.getTimeOutTaskKey()); }
         try { dynamicTask.stop(info.getTimeOutTaskKey()); }
         catch (RuntimeException ex) { log.warn("[Adopted timer close] {}: {}", info.getStream(), ex.getMessage()); }
         catch (RuntimeException ex) { log.warn("[Adopted timer close] {}: {}", info.getStream(), ex.getMessage()); }
-        finally { subscribe.removeOwnedSubscribe(owned.owner); }
-        if (owned.closed) return true;
-        if (owned.closing) return false; // Never leave a second name-based close in flight across reallocation.
-        owned.closing = true;
-        try {
-            mediaServerService.closeRTPServer(node, info.getStream(), closed -> {
-                synchronized (RtpServerServiceImpl.this) {
-                    if (Boolean.TRUE.equals(closed) && legacyRtp.get(key) == owned && !owned.opening) {
-                        if (owned.released.compareAndSet(false, true)) ssrcFactory.releaseSsrc(node.getId(), info.getSsrc());
-                        owned.closed = true;
-                    }
-                    owned.closing = false;
-                }
-            });
-        } catch (RuntimeException ex) {
-            // Dispatch may already have escaped; without a response keep the allocation fenced.
-            log.warn("[Adopted RTP close] {}/{} remains uncertain: {}", node.getId(), info.getStream(), ex.getMessage());
-        }
-        return owned.closed;
+        finally { if (entry != null) subscribe.removeOwnedSubscribe(entry.owner); }
+        boolean closed = closeAllocation(node, info, snapshot -> originalActor(snapshot, info, expected));
+        return closed && releaseClosedSsrc(node, info);
     }
     }
 
 
     @Override
     @Override
@@ -284,14 +376,15 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         }
         }
 
 
         // 获取mediaServer可用的ssrc
         // 获取mediaServer可用的ssrc
+        final String timeOutTaskKey = UUID.randomUUID().toString();
         final String ssrc;
         final String ssrc;
         if (rtpServerParam.getPresetSsrc() != null) {
         if (rtpServerParam.getPresetSsrc() != null) {
             ssrc = rtpServerParam.getPresetSsrc();
             ssrc = rtpServerParam.getPresetSsrc();
         }else {
         }else {
             if (rtpServerParam.isPlayback()) {
             if (rtpServerParam.isPlayback()) {
-                ssrc = ssrcFactory.getPlayBackSsrc(rtpServerParam.getMediaServerItem().getId());
+                ssrc = ssrcFactory.getPlayBackSsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey);
             }else {
             }else {
-                ssrc = ssrcFactory.getPlaySsrc(rtpServerParam.getMediaServerItem().getId());
+                ssrc = ssrcFactory.getPlaySsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey);
             }
             }
         }
         }
         final String streamId;
         final String streamId;
@@ -305,17 +398,18 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
             log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验");
             log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验");
         }
         }
         // Register BEFORE create: even an in-flight replacement invalidates the previous close receipt.
         // Register BEFORE create: even an in-flight replacement invalidates the previous close receipt.
-        String timeOutTaskKey = UUID.randomUUID().toString();
         SSRCInfo ssrcInfo = new SSRCInfo(0, ssrc, "rtp", streamId, timeOutTaskKey);
         SSRCInfo ssrcInfo = new SSRCInfo(0, ssrc, "rtp", streamId, timeOutTaskKey);
         LegacyRtp entry = new LegacyRtp(ssrcInfo);
         LegacyRtp entry = new LegacyRtp(ssrcInfo);
         String allocationKey = managedKey(rtpServerParam.getMediaServerItem(), streamId);
         String allocationKey = managedKey(rtpServerParam.getMediaServerItem(), streamId);
-        LegacyRtp previous = legacyRtp.get(allocationKey);
-        if (previous != null && previous.callId != null && !previous.closed) {
-            if (rtpServerParam.getPresetSsrc() == null) ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc);
+        if (!reserveAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo, rtpServerParam.getPresetSsrc() != null)) {
+            if (rtpServerParam.getPresetSsrc() == null) ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey);
             callback.run(InviteErrorCode.FAIL.getCode(), "Adopted RTP close is still pending", null);
             callback.run(InviteErrorCode.FAIL.getCode(), "Adopted RTP close is still pending", null);
             return null;
             return null;
         }
         }
         legacyRtp.put(allocationKey, entry);
         legacyRtp.put(allocationKey, entry);
+        if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.INTENT, RtpState.CREATING)) {
+            closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo); return null;
+        }
         int rtpServerPort;
         int rtpServerPort;
         if (rtpServerParam.getMediaServerItem().isRtpEnable()) {
         if (rtpServerParam.getMediaServerItem().isRtpEnable()) {
             rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId,
             rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId,
@@ -325,12 +419,12 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
             rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort();
             rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort();
         }
         }
         ssrcInfo.setPort(rtpServerPort);
         ssrcInfo.setPort(rtpServerPort);
-        entry.opening = false;
+        if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.CREATING, RtpState.OPEN)) return null;
         if (rtpServerPort == 0) {
         if (rtpServerPort == 0) {
             callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null);
             callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null);
             // 释放ssrc
             // 释放ssrc
             if (rtpServerParam.getPresetSsrc() == null) {
             if (rtpServerParam.getPresetSsrc() == null) {
-                ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc);
+                ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey);
             }
             }
             return null;
             return null;
         }
         }
@@ -341,13 +435,8 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId());
         Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId());
         dynamicTask.startDelay(timeOutTaskKey, () -> {
         dynamicTask.startDelay(timeOutTaskKey, () -> {
             if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
             if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
-            // 收流超时
-            // 释放ssrc
-            if (rtpServerParam.getPresetSsrc() == null) {
-                ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc);
-            }
-            // 关闭收流端口
-            mediaServerService.closeRTPServer(rtpServerParam.getMediaServerItem(), streamId);
+            // Close through the shared allocation fence; never release an unknown allocation's SSRC early.
+            closeRTPServer(rtpServerParam.getMediaServerItem(), ssrcInfo);
             subscribe.removeOwnedSubscribe(entry.owner);
             subscribe.removeOwnedSubscribe(entry.owner);
             callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult);
             callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult);
         }, userSetting.getPlayTimeout());
         }, userSetting.getPlayTimeout());
@@ -368,22 +457,51 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         return ssrcInfo;
         return ssrcInfo;
     }
     }
 
 
+    /** Peer BYE/offline must use the original Invite and dialog, never the name's current allocation. */
+    public boolean closeRTPServerForSession(SsrcTransaction original, InviteInfo invite) {
+        if (original == null || sessionManager == null || stopReceipts == null
+                || !SipInviteSessionManager.sameDialog(original,
+                sessionManager.getSsrcTransactionByStream(original.getApp(), original.getStream()))) return false;
+        SSRCInfo info = invite == null ? sessionManager.getAdoptedAllocation(original) : invite.getSsrcInfo();
+        if (info == null || !Objects.equals(original.getApp(), info.getApp())
+                || !Objects.equals(original.getStream(), info.getStream()) || !Objects.equals(original.getSsrc(), info.getSsrc())
+                || (invite != null && (!Objects.equals(original.getMediaServerId(), invite.getMediaServerId())
+                || !Objects.equals(original.getDeviceId(), invite.getDeviceId()) || !Objects.equals(original.getChannelId(), invite.getChannelId())
+                || original.getType() != invite.getType() || !Objects.equals(original.getStream(), invite.getStream())))) return false;
+        MediaServer node = mediaServerService.getOne(original.getMediaServerId());
+        if (node == null || !Objects.equals(original.getMediaServerId(), node.getId())) return false;
+        if (info.getStream().startsWith("managed_")) {
+            if (!stopReceipts.retainDialog(original)) return false;
+            return closeManagedRTPServer(node, info);
+        }
+        if (sessionManager.isAdopted(original)) return closeAdoptedRTPServer(node, info, original.getCallId());
+        return closeLegacyRtp(node, info, snapshot -> originalActor(snapshot, info, original));
+    }
+
+    private boolean originalActor(Snapshot snapshot, SSRCInfo info, SsrcTransaction original) {
+        return (snapshot.allocation == null || snapshot.allocation.callId == null
+                || Objects.equals(snapshot.allocation.callId, original.getCallId()))
+                && snapshot.plays.values().stream().noneMatch(play -> Objects.equals(play.allocationToken, info.getTimeOutTaskKey())
+                && play.dialog != null && !SipInviteSessionManager.sameDialog(original, play.dialog));
+    }
+
     @Override
     @Override
     public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
     public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
         if (ssrcInfo != null && ssrcInfo.getStream() != null && ssrcInfo.getStream().startsWith("managed_")) {
         if (ssrcInfo != null && ssrcInfo.getStream() != null && ssrcInfo.getStream().startsWith("managed_")) {
             closeManagedRTPServer(mediaServer, ssrcInfo);
             closeManagedRTPServer(mediaServer, ssrcInfo);
             return;
             return;
         }
         }
-        if (mediaServer == null) {
-            return;
-        }
-        if (ssrcInfo.getTimeOutTaskKey() != null) {
-            dynamicTask.stop(ssrcInfo.getTimeOutTaskKey());
-        }
-        if (ssrcInfo.getSsrc() != null) {
-            // 释放ssrc
-            ssrcFactory.releaseSsrc(mediaServer.getId(), ssrcInfo.getSsrc());
+        closeLegacyRtp(mediaServer, ssrcInfo, snapshot -> true);
+    }
+
+    private boolean closeLegacyRtp(MediaServer mediaServer, SSRCInfo ssrcInfo, Predicate<Snapshot> actorGuard) {
+        if (mediaServer == null || mediaServer.getId() == null || ssrcInfo == null || ssrcInfo.getStream() == null) return false;
+        if (ssrcInfo.getTimeOutTaskKey() != null) dynamicTask.stop(ssrcInfo.getTimeOutTaskKey());
+        LegacyRtp entry = legacyRtp.get(managedKey(mediaServer, ssrcInfo.getStream()));
+        if (entry != null && entry.info.equals(ssrcInfo)) {
+            entry.terminal.set(true); subscribe.removeOwnedSubscribe(entry.owner);
         }
         }
-        mediaServerService.closeRTPServer(mediaServer, ssrcInfo.getStream());
+        boolean closed = closeAllocation(mediaServer, ssrcInfo, actorGuard);
+        return closed && releaseClosedSsrc(mediaServer, ssrcInfo);
     }
     }
 }
 }

+ 2 - 1
video-service/src/main/java/com/zksy/video/lifecycle/Gb28181LifecycleMedia.java

@@ -102,7 +102,7 @@ public class Gb28181LifecycleMedia implements VideoLifecycleMedia {
             boolean stopped = intendedStream(record).equals(record.getStream())
             boolean stopped = intendedStream(record).equals(record.getStream())
                     ? play.stopManaged(server, device(record), channel(record), record.getStream())
                     ? play.stopManaged(server, device(record), channel(record), record.getStream())
                     : play.stopAdopted(server, device(record), channel(record), record.getStream(), record.getAdoptedHandle());
                     : play.stopAdopted(server, device(record), channel(record), record.getStream(), record.getAdoptedHandle());
-            if (!stopped || record.isStartInFlight()) return outcome(record, "CLEANUP_PENDING", null);
+            if (!stopped) return outcome(record, "CLEANUP_PENDING", null);
             JSONObject still = VideoLifecycleMedia.findMedia(zlm, server, APP, record.getStream());
             JSONObject still = VideoLifecycleMedia.findMedia(zlm, server, APP, record.getStream());
             return outcome(record, still == null ? "STOPPED" : "CLEANUP_PENDING", null);
             return outcome(record, still == null ? "STOPPED" : "CLEANUP_PENDING", null);
         } catch (RuntimeException unknown) {
         } catch (RuntimeException unknown) {
@@ -145,6 +145,7 @@ public class Gb28181LifecycleMedia implements VideoLifecycleMedia {
 
 
     private static Map<String, Object> outcome(VideoLifecycleRecord record, String status, Map<String, Object> media) {
     private static Map<String, Object> outcome(VideoLifecycleRecord record, String status, Map<String, Object> media) {
         Map<String, Object> result = new LinkedHashMap<>(); result.put("status", status);
         Map<String, Object> result = new LinkedHashMap<>(); result.put("status", status);
+        if ("STOPPED".equals(status)) result.put("allocationClosed", true);
         record.setMedia(media);
         record.setMedia(media);
         if (media != null) result.put("media", media);
         if (media != null) result.put("media", media);
         if (record.getStream() != null) result.put("stream", record.getStream());
         if (record.getStream() != null) result.put("stream", record.getStream());

+ 5 - 2
video-service/src/main/java/com/zksy/video/lifecycle/ManualLifecycleMedia.java

@@ -80,12 +80,14 @@ public class ManualLifecycleMedia implements VideoLifecycleMedia {
         String key = record.getProxyKey();
         String key = record.getProxyKey();
         if (key != null && !key.isBlank()) {
         if (key != null && !key.isBlank()) {
             boolean stopped = manual.stop(record.getMediaServerId(), key);
             boolean stopped = manual.stop(record.getMediaServerId(), key);
-            return outcome(record, stopped && !record.isStartInFlight() ? "STOPPED" : "CLEANUP_PENDING", null);
+            // A persisted actual key is only available after add completed (or on read-only
+            // adoption). Exact confirmed deletion then fences that allocation despite a lost RPC.
+            return outcome(record, stopped ? "STOPPED" : "CLEANUP_PENDING", null);
         }
         }
         // 原生地址确实没有外部资源;代理缺 actual key 永远不能假报已回收。
         // 原生地址确实没有外部资源;代理缺 actual key 永远不能假报已回收。
         boolean nativeOnly = false;
         boolean nativeOnly = false;
         try { nativeOnly = !proxy(record) && record.getStream() == null; } catch (RuntimeException unknown) { /* 未知来源 */ }
         try { nativeOnly = !proxy(record) && record.getStream() == null; } catch (RuntimeException unknown) { /* 未知来源 */ }
-        return outcome(record, nativeOnly && !record.isStartInFlight() ? "STOPPED" : "CLEANUP_PENDING", null);
+        return outcome(record, nativeOnly ? "STOPPED" : "CLEANUP_PENDING", null);
     }
     }
 
 
     static String managedStream(VideoLifecycleRecord record) {
     static String managedStream(VideoLifecycleRecord record) {
@@ -95,6 +97,7 @@ public class ManualLifecycleMedia implements VideoLifecycleMedia {
     private static Map<String, Object> outcome(VideoLifecycleRecord record, String status, Map<String, Object> media) {
     private static Map<String, Object> outcome(VideoLifecycleRecord record, String status, Map<String, Object> media) {
         Map<String, Object> result = new java.util.LinkedHashMap<>();
         Map<String, Object> result = new java.util.LinkedHashMap<>();
         result.put("status", status);
         result.put("status", status);
+        if ("STOPPED".equals(status)) result.put("allocationClosed", true);
         record.setMedia(media);
         record.setMedia(media);
         if (media != null) result.put("media", media);
         if (media != null) result.put("media", media);
         if (record.getStream() != null) result.put("stream", record.getStream());
         if (record.getStream() != null) result.put("stream", record.getStream());

+ 7 - 1
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleService.java

@@ -123,8 +123,14 @@ public class VideoLifecycleService {
                 }
                 }
                 if (outcome.get("proxyKey") instanceof String) row.setProxyKey((String) outcome.get("proxyKey"));
                 if (outcome.get("proxyKey") instanceof String) row.setProxyKey((String) outcome.get("proxyKey"));
             }
             }
+            // A transport flag can outlive its process. Only positive quiescence evidence from
+            // the exact media adapter may settle it; an ordinary STOPPED/empty list cannot.
+            boolean quiescent = cleanup && TERMINAL.contains(state) && outcome != null
+                    && Boolean.TRUE.equals(outcome.get("allocationClosed"));
+            if (quiescent) row.setStartInFlight(false);
             if (row.isCancelled()) {
             if (row.isCancelled()) {
-                row.setStatus(cleanup && !attempt.isStartInFlight() && !row.isStartInFlight() && TERMINAL.contains(state) ? state : "CLEANUP_PENDING");
+                row.setStatus(cleanup && (quiescent || (!attempt.isStartInFlight() && !row.isStartInFlight()))
+                        && TERMINAL.contains(state) ? state : "CLEANUP_PENDING");
                 row.setMedia(null);
                 row.setMedia(null);
             } else if ("CLEANUP_PENDING".equals(state)) {
             } else if ("CLEANUP_PENDING".equals(state)) {
                 row.setStatus(state); row.setCancelled(true); row.setMedia(null);
                 row.setStatus(state); row.setCancelled(true); row.setMedia(null);

+ 247 - 0
video-service/src/main/java/com/zksy/video/lifecycle/VideoStopReceipts.java

@@ -0,0 +1,247 @@
+package com.zksy.video.lifecycle;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.wvp.gb28181.bean.SsrcTransaction;
+import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
+import com.ruoyi.wvp.service.bean.SSRCInfo;
+import org.springframework.data.redis.core.RedisOperations;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.SessionCallback;
+import org.springframework.stereotype.Component;
+
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.function.UnaryOperator;
+
+/**
+ * Durable stop evidence and allocation fencing, shared by all API instances (not serverId scoped).
+ * A missing snapshot is UNKNOWN, not stopped. No TTL: unknown dispatches must not unlock a name.
+ * update runs against a detached typed snapshot under Redis WATCH/MULTI/EXEC; null rejects a change.
+ * An aborted CAS returns null, never success. Exceptions (including ambiguous EXEC) propagate.
+ * Callers must never dispatch external I/O inside an update, nor use a local cache as evidence.
+ */
+@Component
+public class VideoStopReceipts {
+    private final RedisTemplate<Object, Object> redis;
+    private final ObjectMapper json = new ObjectMapper();
+
+    public VideoStopReceipts(RedisTemplate<Object, Object> redis) { this.redis = Objects.requireNonNull(redis); }
+
+    public enum RtpState { INTENT, CREATING, OPEN, CLOSING, CLOSED, NEVER_CREATED }
+
+    public static class Allocation {
+        public String token;
+        public String ssrc;
+        /** Device-chosen SSRC after a real renegotiation; the pool number above stays the return identity. */
+        public String negotiatedSsrc;
+        /** The pre-existing legacy path already returned the pool number while negotiating. */
+        public boolean poolReturned;
+        public boolean poolTracked;
+        public boolean externalSsrc;
+        public int port;
+        public RtpState state;
+        public String callId;
+        public SSRCInfo info(String stream) { return new SSRCInfo(port, ssrc, "rtp", stream, token); }
+        public boolean matches(SSRCInfo info) {
+            return info != null && Objects.equals(token, info.getTimeOutTaskKey())
+                    && "rtp".equals(info.getApp())
+                    && (Objects.equals(ssrc, info.getSsrc())
+                    || (negotiatedSsrc != null && Objects.equals(negotiatedSsrc, info.getSsrc())));
+        }
+        /** Pool return always uses the originally allocated number, never the negotiated one. */
+        public String poolSsrc() { return ssrc; }
+        public boolean terminal() { return state == RtpState.CLOSED || state == RtpState.NEVER_CREATED; }
+    }
+
+    public static class Play {
+        public String deviceId;
+        public Integer channelId;
+        public String channelCode;
+        public String allocationToken;
+        /** Frozen allocation identity retained even when the legacy name is allocated again. */
+        public Allocation allocation;
+        public boolean inviteSent;
+        public boolean cancelled;
+        /** Original dialog is never discarded, even after the live session registry removes it. */
+        public SsrcTransaction dialog;
+    }
+
+    public static class Snapshot {
+        public String nodeId;
+        public String stream;
+        public Allocation allocation;
+        /** managed uses stream as key; adoption uses its full UUID capability. */
+        public Map<String, Play> plays = new LinkedHashMap<>();
+
+        /** Ordinary legacy OPEN is provenance, not a lease. Adoption and uncertain I/O fence reuse. */
+        public boolean canReplaceAllocation() {
+            if (allocation == null) return true;
+            if (stream.startsWith("managed_")) return false;
+            return allocation.terminal() || (allocation.state == RtpState.OPEN && allocation.callId == null
+                    && plays.values().stream().noneMatch(play -> Objects.equals(play.allocationToken, allocation.token)));
+        }
+    }
+
+    public Snapshot read(String nodeId, String stream) {
+        Snapshot snapshot = decode(redis.opsForValue().get(key(nodeId, stream)));
+        return snapshot != null && Objects.equals(nodeId, snapshot.nodeId) ? snapshot : null;
+    }
+
+    /** Record a real device renegotiation without changing the original pool number.
+     * Only the holder of the original allocation token may add it. */
+    public boolean recordNegotiatedSsrc(String nodeId, String stream, String allocationToken, String poolSsrc, String negotiatedSsrc) {
+        if (nodeId == null || stream == null || allocationToken == null || negotiatedSsrc == null) return false;
+        return update(nodeId, stream, snapshot -> {
+            Allocation allocation = snapshot.allocation;
+            if (allocation == null || !Objects.equals(allocation.token, allocationToken)) return null;
+            if (poolSsrc != null && !Objects.equals(allocation.ssrc, poolSsrc)) return null;
+            if (allocation.negotiatedSsrc != null && !Objects.equals(allocation.negotiatedSsrc, negotiatedSsrc)) return null;
+            allocation.negotiatedSsrc = negotiatedSsrc;
+            return snapshot;
+        }) != null;
+    }
+
+    /** Legacy negotiation happens before any stop receipt exists; create the original allocation
+     * from the typed handle and remember that its pool number was already returned by that path. */
+    public boolean recordNegotiatedSsrc(String nodeId, String stream, SSRCInfo original, String negotiatedSsrc,
+                                        boolean poolAlreadyReturned) {
+        if (nodeId == null || stream == null || original == null || original.getTimeOutTaskKey() == null
+                || original.getSsrc() == null || negotiatedSsrc == null || !"rtp".equals(original.getApp())) return false;
+        return update(nodeId, stream, snapshot -> {
+            Allocation allocation = snapshot.allocation;
+            if (allocation == null) {
+                allocation = new Allocation(); allocation.token = original.getTimeOutTaskKey();
+                allocation.ssrc = original.getSsrc(); allocation.port = original.getPort(); allocation.state = RtpState.OPEN;
+                snapshot.allocation = allocation;
+            }
+            if (!Objects.equals(allocation.token, original.getTimeOutTaskKey())
+                    || !Objects.equals(allocation.ssrc, original.getSsrc())) return null;
+            if (allocation.negotiatedSsrc != null && !Objects.equals(allocation.negotiatedSsrc, negotiatedSsrc)) return null;
+            allocation.negotiatedSsrc = negotiatedSsrc;
+            allocation.poolReturned = allocation.poolReturned || poolAlreadyReturned;
+            return snapshot;
+        }) != null;
+    }
+
+    /** Retain the original managed dialog before an automatic/late BYE can erase the live index. */
+    public boolean retainDialog(SsrcTransaction expected) {
+        if (expected == null || expected.getMediaServerId() == null || expected.getStream() == null
+                || !expected.getStream().matches("managed_[0-9a-fA-F]{32}") || !"rtp".equals(expected.getApp())
+                || expected.getCallId() == null || expected.getSipTransactionInfo() == null
+                || !Objects.equals(expected.getCallId(), expected.getSipTransactionInfo().getCallId())
+                || expected.getSipTransactionInfo().getFromTag() == null || expected.getSipTransactionInfo().getToTag() == null) return false;
+        return update(expected.getMediaServerId(), expected.getStream(), snapshot -> {
+            Play play = snapshot.plays.get(expected.getStream());
+            if (play == null || snapshot.allocation == null || !Objects.equals(snapshot.allocation.ssrc, expected.getSsrc())
+                    || !Objects.equals(play.deviceId, expected.getDeviceId()) || !Objects.equals(play.channelId, expected.getChannelId())
+                    || (play.dialog != null && !SipInviteSessionManager.sameDialog(play.dialog, expected))) return null;
+            play.dialog = expected; play.inviteSent = true; return snapshot;
+        }) != null;
+    }
+
+    public Snapshot update(String nodeId, String stream, UnaryOperator<Snapshot> change) {
+        final String key = key(nodeId, stream);
+        // A conflict does not entitle the caller to repeat a name-close; only a committed transition does.
+        return redis.execute(new SessionCallback<Snapshot>() {
+            @Override @SuppressWarnings({"unchecked", "rawtypes"})
+            public <K, V> Snapshot execute(RedisOperations<K, V> operations) {
+                RedisOperations ops = operations;
+                ops.watch(key);
+                boolean transaction = false;
+                try {
+                    Snapshot before = decode(ops.opsForValue().get(key));
+                    if (before != null && !Objects.equals(nodeId, before.nodeId)) return null;
+                    Snapshot proposed = before == null ? new Snapshot() : decode(encode(before));
+                    proposed.nodeId = nodeId; proposed.stream = stream;
+                    Snapshot next = change.apply(proposed);
+                    if (next == null) return null;
+                    validate(before, next, nodeId, stream);
+                    String encoded = encode(next);
+                    ops.multi(); transaction = true;
+                    ops.opsForValue().set(key, encoded);
+                    List<Object> committed = ops.exec(); transaction = false;
+                    if (committed == null || committed.isEmpty()) return null;
+                    for (Object result : committed) {
+                        if (result == null || Boolean.FALSE.equals(result)) throw new IllegalStateException("Receipt write not acknowledged");
+                        if (result instanceof RuntimeException) throw (RuntimeException) result;
+                        if (result instanceof Throwable) throw new IllegalStateException("Receipt write failed", (Throwable) result);
+                    }
+                    return decode(encoded);
+                } finally {
+                    if (transaction) ops.discard();
+                    else ops.unwatch();
+                }
+            }
+        });
+    }
+
+    private void validate(Snapshot old, Snapshot next, String nodeId, String stream) {
+        if (!Objects.equals(nodeId, next.nodeId) || !Objects.equals(stream, next.stream) || next.plays == null)
+            throw new IllegalArgumentException("Receipt identity cannot change");
+        Allocation a = old == null ? null : old.allocation, b = next.allocation;
+        if (b != null && (b.token == null || b.ssrc == null || b.state == null))
+            throw new IllegalArgumentException("Allocation requires SSRC and timeout token");
+        if (a != null) {
+            if (b == null) throw new IllegalArgumentException("Allocation evidence cannot disappear");
+            if (!Objects.equals(a.token, b.token)) {
+                if (!old.canReplaceAllocation() || b.state != RtpState.INTENT)
+                    throw new IllegalArgumentException("Previous allocation is not closed");
+            } else if (!Objects.equals(a.ssrc, b.ssrc) || a.poolTracked != b.poolTracked || a.externalSsrc != b.externalSsrc
+                    || (a.negotiatedSsrc != null && !Objects.equals(a.negotiatedSsrc, b.negotiatedSsrc))
+                    || (a.poolReturned && !b.poolReturned)
+                    || !transition(a.state, b.state)
+                    || (a.port != b.port && !(a.state == RtpState.CREATING && b.state == RtpState.OPEN))
+                    || (a.callId != null && !Objects.equals(a.callId, b.callId))) {
+                throw new IllegalArgumentException("Allocation evidence cannot regress or change owner");
+            }
+        }
+        if (old == null) return;
+        for (Map.Entry<String, Play> entry : old.plays.entrySet()) {
+            Play p = entry.getValue(), q = next.plays.get(entry.getKey());
+            if (q == null || !Objects.equals(p.deviceId, q.deviceId) || !Objects.equals(p.channelId, q.channelId)
+                    || !Objects.equals(p.channelCode, q.channelCode) || (p.inviteSent && !q.inviteSent)
+                    || (p.cancelled && !q.cancelled)
+                    || (p.allocationToken != null && !Objects.equals(p.allocationToken, q.allocationToken))
+                    || (p.allocation != null && (q.allocation == null || !Objects.equals(p.allocation.token, q.allocation.token)
+                    || !Objects.equals(p.allocation.ssrc, q.allocation.ssrc) || p.allocation.port != q.allocation.port
+                    || !Objects.equals(p.allocation.negotiatedSsrc, q.allocation.negotiatedSsrc)
+                    || (p.allocation.poolReturned && !q.allocation.poolReturned)
+                    || p.allocation.poolTracked != q.allocation.poolTracked || p.allocation.externalSsrc != q.allocation.externalSsrc))
+                    || (p.dialog != null && !SipInviteSessionManager.sameDialog(p.dialog, q.dialog)))
+                throw new IllegalArgumentException("Original play evidence cannot regress or change dialog");
+        }
+    }
+
+    private boolean transition(RtpState old, RtpState next) {
+        if (old == next) return true;
+        switch (old) {
+            case INTENT: return next == RtpState.CREATING || next == RtpState.NEVER_CREATED;
+            case CREATING: return next == RtpState.OPEN;
+            case OPEN: return next == RtpState.CLOSING;
+            case CLOSING: return next == RtpState.CLOSED;
+            default: return false;
+        }
+    }
+
+    private String key(String nodeId, String stream) {
+        if (nodeId == null || stream == null) throw new IllegalArgumentException("Original node and stream required");
+        Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
+        // Managed UUIDs are single-use even if an API request later names a different node.
+        String owner = stream.matches("managed_[0-9a-fA-F]{32}") ? "managed" : encoder.encodeToString(nodeId.getBytes(StandardCharsets.UTF_8));
+        return "video:stop-receipts:v1:" + owner
+                + ":" + encoder.encodeToString(stream.getBytes(StandardCharsets.UTF_8));
+    }
+
+    private String encode(Snapshot value) {
+        try { return json.writeValueAsString(value); }
+        catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot encode stop receipt", ex); }
+    }
+
+    private Snapshot decode(Object value) {
+        if (value == null) return null;
+        if (!(value instanceof String)) throw new IllegalStateException("Unsupported stop receipt representation");
+        try { return json.readValue((String) value, Snapshot.class); }
+        catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot decode stop receipt", ex); }
+    }
+}

+ 92 - 85
video-service/src/test/java/com/zksy/video/lifecycle/AdoptedGbDeepSeamTest.java

@@ -4,174 +4,181 @@ import com.alibaba.fastjson2.JSONObject;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.ruoyi.wvp.common.*;
 import com.ruoyi.wvp.common.*;
 import com.ruoyi.wvp.common.InviteInfo;
 import com.ruoyi.wvp.common.InviteInfo;
-import com.ruoyi.wvp.gb28181.SipLayer;
 import com.ruoyi.wvp.gb28181.bean.*;
 import com.ruoyi.wvp.gb28181.bean.*;
-import com.ruoyi.wvp.gb28181.event.SipSubscribe;
-import com.ruoyi.wvp.gb28181.service.*;
-import com.ruoyi.wvp.gb28181.transmit.SIPSender;
-import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
-import com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander;
-import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
 import com.ruoyi.wvp.service.bean.*;
 import com.ruoyi.wvp.service.bean.*;
+import gov.nist.javax.sip.message.SIPResponse;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.Test;
-import javax.sip.SipException;
+
 import javax.sip.message.Request;
 import javax.sip.message.Request;
 import java.util.*;
 import java.util.*;
+import static com.zksy.video.lifecycle.ManagedGbDeepSeamTest.assertDialogSnapshot;
 import static org.junit.jupiter.api.Assertions.*;
 import static org.junit.jupiter.api.Assertions.*;
 import static org.mockito.Mockito.*;
 import static org.mockito.Mockito.*;
 
 
-/** Real adapter -> Play -> RTP/Hook/Invite/Session/Commander; only external I/O is replaced. */
+/** Real adapter -> Play -> RTP/Hook/Invite/Session/Commander; serialized external Redis and real SIP messages. */
 class AdoptedGbDeepSeamTest {
 class AdoptedGbDeepSeamTest {
     private static final String STREAM = "device_channel";
     private static final String STREAM = "device_channel";
 
 
     @Test void lastStopRequiresExactBye2xxAndPositiveRtpCloseThenConverges() throws Exception {
     @Test void lastStopRequiresExactBye2xxAndPositiveRtpCloseThenConverges() throws Exception {
         Fixture f = new Fixture(); f.legacy("call-first", true);
         Fixture f = new Fixture(); f.legacy("call-first", true);
+        SsrcTransaction owned = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
         VideoLifecycleRecord record = f.record();
         VideoLifecycleRecord record = f.record();
         f.adapter.prepare(record);
         f.adapter.prepare(record);
         assertEquals("ACTIVE", f.adapter.start(record).get("status"));
         assertEquals("ACTIVE", f.adapter.start(record).get("status"));
-        assertNotNull(record.getAdoptedHandle());
+        assertNotNull(record.getAdoptedHandle()); assertTrue(f.sessions.isAdopted(owned));
         record.setCancelled(true);
         record.setCancelled(true);
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
-        assertNotNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertDialogSnapshot(owned, f.sessions.getSsrcTransactionByStream("rtp", STREAM));
         assertFalse(f.open.contains(STREAM)); assertTrue(f.hooks.getAll().isEmpty());
         assertFalse(f.open.contains(STREAM)); assertTrue(f.hooks.getAll().isEmpty());
-        f.ack(0, "wrong-call", 200);
-        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
-        f.ack(0, "call-first", 200);
+        Request bye = f.lastBye("call-first"); f.assertBye(bye, owned);
+        List<SIPResponse> mismatches = new ArrayList<>();
+        SIPResponse wrongCall = Fixture.reply(bye, 200); wrongCall.getCallIdHeader().setCallId("wrong-call"); mismatches.add(wrongCall);
+        SIPResponse wrongMethod = Fixture.reply(bye, 200); wrongMethod.getCSeqHeader().setMethod(Request.OPTIONS); mismatches.add(wrongMethod);
+        // cancel() below can send legitimate BYE retries with the next CSeq. Choose a
+        // sequence never dispatched by this fixture, not a retry's valid correlation key.
+        SIPResponse wrongSequence = Fixture.reply(bye, 200); wrongSequence.getCSeqHeader().setSeqNumber(wrongSequence.getCSeqHeader().getSeqNumber() + 1000); mismatches.add(wrongSequence);
+        SIPResponse wrongFrom = Fixture.reply(bye, 200); wrongFrom.getFrom().setTag("wrong-from"); mismatches.add(wrongFrom);
+        SIPResponse wrongTo = Fixture.reply(bye, 200); wrongTo.getTo().setTag("wrong-to"); mismatches.add(wrongTo);
+        SIPResponse wrongBranch = Fixture.reply(bye, 200); wrongBranch.getTopmostViaHeader().setBranch("z9hG4bK-wrong"); mismatches.add(wrongBranch);
+        mismatches.add(Fixture.reply(bye, 500));
+        for (SIPResponse response : mismatches) {
+            f.byeResponse(bye, response);
+            assertFalse(f.sessions.isByeConfirmed(owned));
+            assertDialogSnapshot(owned, f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+            assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        }
+        f.byeResponse(bye, 200);
+        assertTrue(f.sessions.isByeConfirmed(owned));
         assertNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
         assertNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertNull(f.sessions.getSsrcTransactionByCallId("call-first"));
         assertEquals("STOPPED", f.adapter.cancel(record).get("status"));
         assertEquals("STOPPED", f.adapter.cancel(record).get("status"));
         assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, STREAM));
         assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, STREAM));
-        verify(f.media, never()).getDefaultMediaServer();
+        assertEquals(Collections.singletonList(STREAM), f.closeRequests);
+        verify(f.mediaMapper, never()).queryDefault();
     }
     }
 
 
     @Test void sameNameNewDialogAndAllocationCannotReuseOldCloseReceipt() throws Exception {
     @Test void sameNameNewDialogAndAllocationCannotReuseOldCloseReceipt() throws Exception {
-        Fixture f = new Fixture(); f.legacy("call-first", true);
+        Fixture f = new Fixture(); SSRCInfo first = f.legacy("call-first", true);
         VideoLifecycleRecord old = f.record(); assertEquals("ACTIVE", f.adapter.start(old).get("status"));
         VideoLifecycleRecord old = f.record(); assertEquals("ACTIVE", f.adapter.start(old).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
-        f.ack(0, "call-first", 200);
+        Request firstBye = f.lastBye("call-first"); f.byeResponse(firstBye, 200);
         assertEquals("STOPPED", f.adapter.cancel(old).get("status"));
         assertEquals("STOPPED", f.adapter.cancel(old).get("status"));
-        f.legacy("call-second", true);
+        SSRCInfo replacement = f.legacy("call-second", true);
+        assertNotEquals(first.getTimeOutTaskKey(), replacement.getTimeOutTaskKey());
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
-        assertTrue(f.open.contains(STREAM));
-        assertEquals("call-second", f.sessions.getSsrcTransactionByStream("rtp", STREAM).getCallId());
+        assertTrue(f.open.contains(STREAM)); assertEquals(1, f.closeRequests.size());
+        SsrcTransaction second = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
+        assertEquals("call-second", second.getCallId());
         VideoLifecycleRecord next = f.record(); next.setGeneration("22222222-2222-2222-2222-222222222222");
         VideoLifecycleRecord next = f.record(); next.setGeneration("22222222-2222-2222-2222-222222222222");
         assertEquals("ACTIVE", f.adapter.start(next).get("status"));
         assertEquals("ACTIVE", f.adapter.start(next).get("status"));
         assertNotEquals(old.getAdoptedHandle(), next.getAdoptedHandle());
         assertNotEquals(old.getAdoptedHandle(), next.getAdoptedHandle());
-        f.closeAcknowledged = false;
+        // Withhold the original external close reply, not a second name-based close after an unknown result.
+        f.closeAcknowledged = false; f.delayClose = true;
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(next).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(next).get("status"));
-        f.ack(0, "call-first", 200); // a late duplicate cannot terminate the new dialog
-        assertNotNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
-        f.ack(1, "call-second", 200);
+        Request secondBye = f.lastBye("call-second"); f.assertBye(secondBye, second);
+        f.byeResponse(firstBye, 200); // a late duplicate cannot terminate the new dialog
+        assertFalse(f.sessions.isByeConfirmed(second));
+        assertDialogSnapshot(second, f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        f.byeResponse(secondBye, 200); assertTrue(f.sessions.isByeConfirmed(second));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(next).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(next).get("status"));
-        assertTrue(f.open.contains(STREAM));
-        f.closeAcknowledged = true;
+        assertTrue(f.open.contains(STREAM)); assertEquals(1, f.pendingCloses.size());
+        assertEquals(2, f.closeRequests.size());
+        f.closeAcknowledged = true; f.pendingCloses.get(0).run();
         assertEquals("STOPPED", f.adapter.cancel(next).get("status"));
         assertEquals("STOPPED", f.adapter.cancel(next).get("status"));
+        assertFalse(f.open.contains(STREAM)); assertEquals(2, f.closeRequests.size());
     }
     }
 
 
     @Test void transportFailureRetainsAdoptedDialogAndOnlyClosesExactRtp() throws Exception {
     @Test void transportFailureRetainsAdoptedDialogAndOnlyClosesExactRtp() throws Exception {
         Fixture f = new Fixture(); f.legacy("call-first", false);
         Fixture f = new Fixture(); f.legacy("call-first", false);
+        SsrcTransaction owned = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
         VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
         VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
-        doThrow(new SipException("offline")).when(f.sender).transmitRequest(any(), any(), any(), any());
+        f.failBye = true;
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
-        assertNotNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertDialogSnapshot(owned, f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertFalse(f.sessions.isByeConfirmed(owned)); assertEquals(1, f.byeAttempts.get());
         assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, STREAM));
         assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, STREAM));
         assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(STREAM));
         assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(STREAM));
+        assertEquals(Collections.singletonList(STREAM), f.closeRequests);
     }
     }
 
 
     @Test void missingOrMismatchedDialogNeverGrantsAdoptionOrBlindStops() throws Exception {
     @Test void missingOrMismatchedDialogNeverGrantsAdoptionOrBlindStops() throws Exception {
         Fixture f = new Fixture(); SSRCInfo info = f.legacy("call-first", false);
         Fixture f = new Fixture(); SSRCInfo info = f.legacy("call-first", false);
+        SsrcTransaction tx = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
         f.sessions.removeByStream("rtp", STREAM);
         f.sessions.removeByStream("rtp", STREAM);
         VideoLifecycleRecord record = f.record();
         VideoLifecycleRecord record = f.record();
         assertEquals("CLEANUP_PENDING", f.adapter.start(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.start(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
-        assertTrue(f.open.contains(STREAM)); assertTrue(f.acks.isEmpty());
-        SsrcTransaction tx = f.dialog(STREAM); tx.setSsrc(info.getSsrc()); tx.setMediaServerId("node-b"); f.sessions.put(tx);
+        assertNull(record.getAdoptedHandle()); assertTrue(f.open.contains(STREAM)); assertTrue(f.byes.isEmpty());
+        tx.setSsrc(info.getSsrc()); tx.setMediaServerId("node-b"); f.sessions.put(tx);
         assertEquals("CLEANUP_PENDING", f.adapter.start(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.start(record).get("status"));
-        assertTrue(f.open.contains(STREAM));
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        assertNull(record.getAdoptedHandle()); assertTrue(f.open.contains(STREAM));
+        assertTrue(f.closeRequests.isEmpty()); assertTrue(f.byes.isEmpty());
     }
     }
 
 
     @Test void replacementBeforeLateByeAckSurvivesAndOldRecordNeverAdoptsAgain() throws Exception {
     @Test void replacementBeforeLateByeAckSurvivesAndOldRecordNeverAdoptsAgain() throws Exception {
         Fixture f = new Fixture(); SSRCInfo first = f.legacy("call-first", true);
         Fixture f = new Fixture(); SSRCInfo first = f.legacy("call-first", true);
+        SsrcTransaction original = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
         VideoLifecycleRecord old = f.record(); assertEquals("ACTIVE", f.adapter.start(old).get("status"));
         VideoLifecycleRecord old = f.record(); assertEquals("ACTIVE", f.adapter.start(old).get("status"));
+        String handle = old.getAdoptedHandle();
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
-        f.legacy("call-second", false);
-        f.ack(0, "call-first", 200);
+        Request oldBye = f.lastBye("call-first");
+        SSRCInfo next = f.legacy("call-second", false);
+        assertNotEquals(first.getTimeOutTaskKey(), next.getTimeOutTaskKey());
+        SsrcTransaction replacement = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
+        f.byeResponse(oldBye, 200); assertTrue(f.sessions.isByeConfirmed(original));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.status(old).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.status(old).get("status"));
+        assertEquals(handle, old.getAdoptedHandle());
         assertTrue(f.open.contains(STREAM)); assertEquals(1, f.hooks.getAll().size());
         assertTrue(f.open.contains(STREAM)); assertEquals(1, f.hooks.getAll().size());
-        assertEquals("call-second", f.sessions.getSsrcTransactionByStream("rtp", STREAM).getCallId());
+        assertDialogSnapshot(replacement, f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertEquals("call-second", replacement.getCallId()); assertFalse(f.sessions.isByeConfirmed(replacement));
         assertFalse(f.rtp.closeAdoptedRTPServer(f.node, first, "call-first"));
         assertFalse(f.rtp.closeAdoptedRTPServer(f.node, first, "call-first"));
-        assertTrue(f.open.contains(STREAM));
+        assertTrue(f.open.contains(STREAM)); assertEquals(Collections.singletonList(STREAM), f.closeRequests);
     }
     }
 
 
     @Test void changedNodeSsrcOrSipTagsCannotUseAnObservedHandle() throws Exception {
     @Test void changedNodeSsrcOrSipTagsCannotUseAnObservedHandle() throws Exception {
         Fixture f = new Fixture(); f.legacy("call-first", true);
         Fixture f = new Fixture(); f.legacy("call-first", true);
         VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
         VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
+        SsrcTransaction original = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
         SsrcTransaction current = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
         SsrcTransaction current = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
-        current.getSipTransactionInfo().setToTag("different-dialog"); f.sessions.put(current);
+        assertDialogSnapshot(original, current);
+        current.getSipTransactionInfo().setToTag("different-dialog");
+        // Mutating a returned snapshot must not mutate either Redis hash until put is called.
+        assertDialogSnapshot(original, f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        f.sessions.put(current);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        current.getSipTransactionInfo().setToTag("to"); current.setMediaServerId("node-b"); f.sessions.put(current);
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
-        current.getSipTransactionInfo().setToTag("to"); current.setSsrc("9999999999"); f.sessions.put(current);
+        current.setMediaServerId("node-a"); current.setSsrc("9999999999"); f.sessions.put(current);
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
-        assertTrue(f.open.contains(STREAM)); assertTrue(f.acks.isEmpty());
+        assertTrue(f.open.contains(STREAM)); assertTrue(f.byes.isEmpty());
         record.setAdoptedHandle("unknown-after-process-restart");
         record.setAdoptedHandle("unknown-after-process-restart");
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
-        assertTrue(f.open.contains(STREAM));
+        assertTrue(f.open.contains(STREAM)); assertTrue(f.closeRequests.isEmpty());
     }
     }
 
 
     @Test void pendingRtpResponseCannotQueueAnotherNameCloseOrAllowReallocation() throws Exception {
     @Test void pendingRtpResponseCannotQueueAnotherNameCloseOrAllowReallocation() throws Exception {
         Fixture f = new Fixture(); f.legacy("call-first", true);
         Fixture f = new Fixture(); f.legacy("call-first", true);
+        SsrcTransaction owned = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
         VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
         VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
         f.delayClose = true;
         f.delayClose = true;
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
-        f.ack(0, "call-first", 200);
+        f.byeResponse(f.lastBye("call-first"), 200); assertTrue(f.sessions.isByeConfirmed(owned));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
         assertEquals(1, f.pendingCloses.size());
         assertEquals(1, f.pendingCloses.size());
         RTPServerParam next = new RTPServerParam(); next.setMediaServerItem(f.node); next.setStreamId(STREAM);
         RTPServerParam next = new RTPServerParam(); next.setMediaServerItem(f.node); next.setStreamId(STREAM);
         assertNull(f.rtp.openRTPServer(next, (code, msg, result) -> { }));
         assertNull(f.rtp.openRTPServer(next, (code, msg, result) -> { }));
+        assertEquals(1, f.openRequests.get()); assertEquals(Collections.singletonList(STREAM), f.closeRequests);
         f.pendingCloses.get(0).run();
         f.pendingCloses.get(0).run();
         assertEquals("STOPPED", f.adapter.cancel(record).get("status"));
         assertEquals("STOPPED", f.adapter.cancel(record).get("status"));
-        assertEquals(1, f.pendingCloses.size());
+        assertEquals(1, f.pendingCloses.size()); assertEquals(Collections.singletonList(STREAM), f.closeRequests);
     }
     }
 
 
     private static class Fixture extends ManagedGbDeepSeamTest.Fixture {
     private static class Fixture extends ManagedGbDeepSeamTest.Fixture {
-        final SIPSender sender = mock(SIPSender.class);
-        final List<SipSubscribe.Event> acks = new ArrayList<>();
-        final List<Runnable> pendingCloses = new ArrayList<>();
-        boolean delayClose;
         final Gb28181LifecycleMedia adapter;
         final Gb28181LifecycleMedia adapter;
         Fixture() throws Exception {
         Fixture() throws Exception {
-            node.setType("zlm"); node.setStatus(true);
-            SIPCommander commander = new SIPCommander();
-            SIPRequestHeaderProvider headers = mock(SIPRequestHeaderProvider.class);
-            SipLayer layer = mock(SipLayer.class);
-            wire(commander, "sessionManager", sessions); wire(commander, "sipSender", sender);
-            wire(commander, "headerProvider", headers); wire(commander, "sipLayer", layer);
-            wire(play, "cmder", commander);
-            when(headers.createByteRequest(any(), anyString(), any())).thenReturn(mock(Request.class));
-            when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
-            doAnswer(i -> { acks.add(i.getArgument(3)); return null; }).when(sender).transmitRequest(any(), any(), any(), any());
-            IDeviceService devices = mock(IDeviceService.class);
-            IDeviceChannelService channels = mock(IDeviceChannelService.class);
-            when(devices.getDeviceByDeviceId("device")).thenReturn(device);
-            when(channels.getOne("device", "channel")).thenReturn(channel);
-            ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
-            com.ruoyi.wvp.media.zlm.ZLMServerFactory factory = new com.ruoyi.wvp.media.zlm.ZLMServerFactory();
-            wire(factory, "zlmresTfulUtils", zlm);
-            // Exercise the real code=0/hit=1 -> boolean mapping rather than fabricating stop=true.
-            doAnswer(i -> {
-                Map<String, Object> params = i.getArgument(1);
-                String stream = (String) params.get("stream_id");
-                ZLMRESTfulUtils.RequestCallback callback = i.getArgument(2);
-                Runnable response = () -> {
-                    boolean hit = closeAcknowledged && open.remove(stream);
-                    callback.run(JSONObject.parseObject(hit
-                            ? "{\"code\":0,\"hit\":1}" : "{\"code\":0,\"hit\":0}"));
-                };
-                if (delayClose) pendingCloses.add(response); else response.run();
-                return null;
-            }).when(zlm).closeRtpServer(eq(node), anyMap(), any());
-            doAnswer(i -> { factory.closeRtpServer(i.getArgument(0), i.getArgument(1), i.getArgument(2)); return null; })
-                    .when(media).closeRTPServer(any(), anyString(), any());
-            when(zlm.getMediaList(node, "rtp", STREAM)).thenAnswer(i -> JSONObject.parseObject(open.contains(STREAM)
+            when(zlm.getMediaList(any(), eq("rtp"), eq(STREAM))).thenAnswer(i -> JSONObject.parseObject(open.contains(STREAM)
                     ? "{\"code\":0,\"data\":[{\"app\":\"rtp\",\"stream\":\"device_channel\",\"vhost\":\"__defaultVhost__\",\"originType\":3}]}"
                     ? "{\"code\":0,\"data\":[{\"app\":\"rtp\",\"stream\":\"device_channel\",\"vhost\":\"__defaultVhost__\",\"originType\":3}]}"
                     : "{\"code\":0,\"data\":[]}"));
                     : "{\"code\":0,\"data\":[]}"));
             adapter = new Gb28181LifecycleMedia(devices, channels, play, media, zlm, new ObjectMapper());
             adapter = new Gb28181LifecycleMedia(devices, channels, play, media, zlm, new ObjectMapper());
@@ -183,9 +190,13 @@ class AdoptedGbDeepSeamTest {
             InviteInfo invite = InviteInfo.getInviteInfo("device", 7, STREAM, info, "node-a", "127.0.0.1", 30000,
             InviteInfo invite = InviteInfo.getInviteInfo("device", 7, STREAM, info, "node-a", "127.0.0.1", 30000,
                     "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
                     "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
             invites.updateInviteInfo(invite);
             invites.updateInviteInfo(invite);
-            SsrcTransaction tx = dialog(STREAM); tx.setCallId(callId); tx.setSsrc(info.getSsrc()); tx.setType(InviteSessionType.PLAY);
-            tx.getSipTransactionInfo().setCallId(callId); tx.getSipTransactionInfo().setFromTag("from"); tx.getSipTransactionInfo().setToTag("to");
-            sessions.put(tx);
+            // Seed an existing external legacy session, then let the real adoption and BYE modules own it.
+            SsrcTransaction tx = new SsrcTransaction(); tx.setDeviceId("device"); tx.setChannelId(7);
+            tx.setApp("rtp"); tx.setStream(STREAM); tx.setMediaServerId("node-a");
+            tx.setCallId(callId); tx.setSsrc(info.getSsrc()); tx.setType(InviteSessionType.PLAY);
+            SipTransactionInfo sip = new SipTransactionInfo(); sip.setCallId(callId); sip.setFromTag("from");
+            sip.setToTag("to"); sip.setViaBranch("z9hG4bK-legacy-" + callId); tx.setSipTransactionInfo(sip);
+            sessions.put(tx); assertDialogSnapshot(tx, sessions.getSsrcTransactionByStream("rtp", STREAM));
             if (arrival) hooks.onApplicationEvent(arrival(STREAM, node));
             if (arrival) hooks.onApplicationEvent(arrival(STREAM, node));
             return info;
             return info;
         }
         }
@@ -194,9 +205,5 @@ class AdoptedGbDeepSeamTest {
             record.setSourceType("GB28181"); record.setVideoId("cam"); record.setDeviceId("device"); record.setChannelId("channel");
             record.setSourceType("GB28181"); record.setVideoId("cam"); record.setDeviceId("device"); record.setChannelId("channel");
             record.setStream(STREAM); record.setMediaServerId("node-a"); return record;
             record.setStream(STREAM); record.setMediaServerId("node-a"); return record;
         }
         }
-        void ack(int index, String callId, int code) {
-            SipSubscribe.EventResult<?> event = new SipSubscribe.EventResult<>(); event.callId = callId; event.statusCode = code;
-            acks.get(index).response(event);
-        }
     }
     }
 }
 }

+ 261 - 0
video-service/src/test/java/com/zksy/video/lifecycle/FakeStringRedis.java

@@ -0,0 +1,261 @@
+package com.zksy.video.lifecycle;
+
+import org.mockito.invocation.InvocationOnMock;
+import org.springframework.data.redis.RedisSystemException;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.connection.ReturnType;
+import org.springframework.data.redis.core.StringRedisTemplate;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Offline UTF-8 Redis command boundary for SSRC tests. Each strings() call creates a real template,
+ * sharing only this external state. No Factory or release result is mocked.
+ *
+ * EVAL interprets a deliberately small Lua subset (locals, single-line return guards, redis.call,
+ * return). It executes the script's actual commands, rather than selecting a canned allocation /
+ * release implementation by script name. Unknown syntax/commands fail loudly. This is not a Redis
+ * Lua engine, durability test or Redis Cluster test.
+ */
+public final class FakeStringRedis {
+    private static final Pattern GUARD = Pattern.compile("if (.+) then return (.+) end");
+    private static final Pattern CALL = Pattern.compile("redis\\.call\\('([A-Z]+)'(?:,\\s*(.*))?\\)");
+    private static final Pattern ARGUMENT = Pattern.compile("(KEYS|ARGV)\\[(\\d+)\\]");
+
+    private final Map<String, Set<String>> sets = new HashMap<>();
+    private final Map<String, Map<String, String>> hashes = new HashMap<>();
+    private final Map<String, String> values = new HashMap<>();
+
+    /** New real client, same external store; inject only into SSRCFactory in existing fixtures. */
+    public StringRedisTemplate strings() {
+        RedisConnection connection = mock(RedisConnection.class, this::command);
+        RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
+        when(factory.getConnection()).thenReturn(connection);
+        return new StringRedisTemplate(factory);
+    }
+
+    /** Serializes all external commands, including each whole EVAL, across every client. */
+    private synchronized Object command(InvocationOnMock invocation) {
+        String method = invocation.getMethod().getName();
+        Object[] args = invocation.getArguments();
+        switch (method) {
+            case "close": return null;
+            case "isClosed": case "isPipelined": case "isQueueing": return false;
+            case "getNativeConnection": return invocation.getMock();
+            case "toString": return "FakeStringRedisConnection";
+            case "hashCode": return System.identityHashCode(invocation.getMock());
+            case "equals": return invocation.getMock() == args[0];
+            case "evalSha":
+                // Exercise StringRedisTemplate's actual NOSCRIPT -> EVAL fallback and serialization.
+                throw new RedisSystemException("NOSCRIPT No matching script", null);
+            case "eval": {
+                byte[][] wire = tail(args, 3);
+                int keyCount = (Integer) args[2];
+                List<String> keys = texts(Arrays.copyOfRange(wire, 0, keyCount));
+                List<String> argv = texts(Arrays.copyOfRange(wire, keyCount, wire.length));
+                Object result = eval(text((byte[]) args[0]), keys, argv);
+                if (result == null) return null;
+                if (args[1] == ReturnType.VALUE) return bytes((String) result);
+                if (args[1] == ReturnType.INTEGER) return ((Number) result).longValue();
+                throw unsupported("EVAL return type " + args[1]);
+            }
+            case "sAdd": return redis("SADD", withKey(args));
+            case "sPop": return encoded(redis("SPOP", texts((byte[]) args[0])));
+            case "sCard": return redis("SCARD", texts((byte[]) args[0]));
+            case "sIsMember": return Long.valueOf(1).equals(redis("SISMEMBER", texts((byte[]) args[0], (byte[]) args[1])));
+            case "hGet": return encoded(redis("HGET", texts((byte[]) args[0], (byte[]) args[1])));
+            case "hSet": return Long.valueOf(1).equals(redis("HSET", texts((byte[]) args[0], (byte[]) args[1], (byte[]) args[2])));
+            case "hDel": return redis("HDEL", withKey(args));
+            case "hExists": return Long.valueOf(1).equals(redis("HEXISTS", texts((byte[]) args[0], (byte[]) args[1])));
+            case "get": return encoded(redis("GET", texts((byte[]) args[0])));
+            case "set":
+                if (args.length != 2) throw unsupported("SET with expiration/options");
+                redis("SET", texts((byte[]) args[0], (byte[]) args[1])); return true;
+            case "del": return redis("DEL", texts(tail(args, 0)));
+            case "exists":
+                if (args[0] instanceof byte[]) return Long.valueOf(1).equals(redis("EXISTS", texts((byte[]) args[0])));
+                return redis("EXISTS", texts((byte[][]) args[0]));
+            default:
+                if (method.endsWith("Commands")) return invocation.getMock();
+                throw unsupported("connection method " + method);
+        }
+    }
+
+    private static byte[][] tail(Object[] arguments, int first) {
+        return arguments.length == first + 1 && arguments[first] instanceof byte[][]
+                ? (byte[][]) arguments[first] : Arrays.copyOfRange(arguments, first, arguments.length, byte[][].class);
+    }
+
+    private Object eval(String script, List<String> keys, List<String> argv) {
+        Map<String, Object> locals = new HashMap<>();
+        for (String sourceLine : script.split("\n")) {
+            String line = sourceLine.trim();
+            if (line.isEmpty() || line.startsWith("--")) continue;
+            if (line.startsWith("local ")) {
+                int equals = line.indexOf(" = ");
+                if (equals < 0) throw unsupported(line);
+                locals.put(line.substring(6, equals), expression(line.substring(equals + 3), keys, argv, locals));
+                continue;
+            }
+            Matcher guard = GUARD.matcher(line);
+            if (guard.matches()) {
+                if (condition(guard.group(1), keys, argv, locals)) return expression(guard.group(2), keys, argv, locals);
+                continue;
+            }
+            Matcher actionGuard = Pattern.compile("if (.+) then (redis\\.call\\(.+\\)) end").matcher(line);
+            if (actionGuard.matches()) {
+                if (condition(actionGuard.group(1), keys, argv, locals)) expression(actionGuard.group(2), keys, argv, locals);
+                continue;
+            }
+            if (line.startsWith("return ")) return expression(line.substring(7), keys, argv, locals);
+            if (line.startsWith("redis.call(")) { expression(line, keys, argv, locals); continue; }
+            throw unsupported(line);
+        }
+        throw unsupported("script without return");
+    }
+
+    private boolean condition(String source, List<String> keys, List<String> argv, Map<String, Object> locals) {
+        int and = source.indexOf(" and ");
+        if (and >= 0) return condition(source.substring(0, and), keys, argv, locals)
+                && condition(source.substring(and + 5), keys, argv, locals);
+        for (String operator : new String[]{" ~= ", " == "}) {
+            int position = source.indexOf(operator);
+            if (position >= 0) {
+                Object left = expression(source.substring(0, position), keys, argv, locals);
+                Object right = expression(source.substring(position + operator.length()), keys, argv, locals);
+                boolean equal = Objects.equals(left, right);
+                return " == ".equals(operator) ? equal : !equal;
+            }
+        }
+        if (source.startsWith("not ")) return !truthy(expression(source.substring(4), keys, argv, locals));
+        return truthy(expression(source, keys, argv, locals));
+    }
+
+    private Object expression(String source, List<String> keys, List<String> argv, Map<String, Object> locals) {
+        source = source.trim();
+        if ("nil".equals(source) || "false".equals(source)) return null;
+        if ("true".equals(source)) return Boolean.TRUE;
+        if (source.matches("[0-9]+")) return Long.parseLong(source);
+        if (locals.containsKey(source)) return locals.get(source);
+        Matcher argument = ARGUMENT.matcher(source);
+        if (argument.matches()) {
+            List<String> parameters = "KEYS".equals(argument.group(1)) ? keys : argv;
+            return parameters.get(Integer.parseInt(argument.group(2)) - 1);
+        }
+        Matcher call = CALL.matcher(source);
+        if (call.matches()) {
+            List<String> parameters = new ArrayList<>();
+            if (call.group(2) != null) {
+                for (String parameter : call.group(2).split(",")) {
+                    Object value = expression(parameter, keys, argv, locals);
+                    if (value == null) throw unsupported("nil command argument");
+                    parameters.add(value.toString());
+                }
+            }
+            return redis(call.group(1), parameters);
+        }
+        throw unsupported(source);
+    }
+
+    private Object redis(String command, List<String> args) {
+        String key = args.get(0);
+        switch (command) {
+            case "SADD": {
+                setType(key);
+                Set<String> set = sets.computeIfAbsent(key, unused -> new LinkedHashSet<>());
+                long added = 0;
+                for (String member : args.subList(1, args.size())) if (set.add(member)) added++;
+                return added;
+            }
+            case "SPOP": {
+                setType(key);
+                Set<String> set = sets.get(key);
+                if (set == null || set.isEmpty()) return null;
+                Iterator<String> iterator = set.iterator();
+                String member = iterator.next(); iterator.remove();
+                if (set.isEmpty()) sets.remove(key);
+                return member;
+            }
+            case "SCARD": setType(key); return (long) sets.getOrDefault(key, java.util.Collections.emptySet()).size();
+            case "SISMEMBER": setType(key); return sets.getOrDefault(key, java.util.Collections.emptySet()).contains(args.get(1)) ? 1L : 0L;
+            case "HSET": {
+                hashType(key);
+                return hashes.computeIfAbsent(key, unused -> new LinkedHashMap<>()).put(args.get(1), args.get(2)) == null ? 1L : 0L;
+            }
+            case "HGET": hashType(key); return hashes.getOrDefault(key, java.util.Collections.emptyMap()).get(args.get(1));
+            case "HEXISTS": hashType(key); return hashes.getOrDefault(key, java.util.Collections.emptyMap()).containsKey(args.get(1)) ? 1L : 0L;
+            case "HDEL": {
+                hashType(key);
+                Map<String, String> hash = hashes.get(key);
+                if (hash == null) return 0L;
+                long removed = 0;
+                for (String field : args.subList(1, args.size())) if (hash.remove(field) != null) removed++;
+                if (hash.isEmpty()) hashes.remove(key);
+                return removed;
+            }
+            case "GET":
+                if (sets.containsKey(key) || hashes.containsKey(key)) throw unsupported("WRONGTYPE " + key);
+                return values.get(key);
+            case "SET":
+                sets.remove(key); hashes.remove(key); values.put(key, args.get(1)); return "OK";
+            case "EXISTS": {
+                long count = 0;
+                for (String candidate : args) if (sets.containsKey(candidate) || hashes.containsKey(candidate) || values.containsKey(candidate)) count++;
+                return count;
+            }
+            case "DEL": {
+                long count = 0;
+                for (String candidate : args) {
+                    boolean removed = sets.remove(candidate) != null;
+                    removed |= hashes.remove(candidate) != null;
+                    removed |= values.remove(candidate) != null;
+                    if (removed) count++;
+                }
+                return count;
+            }
+            default: throw unsupported("Redis command " + command);
+        }
+    }
+
+    private void setType(String key) {
+        if (hashes.containsKey(key) || values.containsKey(key)) throw unsupported("WRONGTYPE " + key);
+    }
+
+    private void hashType(String key) {
+        if (sets.containsKey(key) || values.containsKey(key)) throw unsupported("WRONGTYPE " + key);
+    }
+
+    private static List<String> withKey(Object[] args) {
+        List<String> values = texts((byte[]) args[0]);
+        values.addAll(texts(tail(args, 1)));
+        return values;
+    }
+
+    private static List<String> texts(byte[]... values) {
+        List<String> result = new ArrayList<>();
+        for (byte[] value : values) result.add(text(value));
+        return result;
+    }
+
+    private static boolean truthy(Object value) { return value != null && !Boolean.FALSE.equals(value); }
+    private static String text(byte[] value) { return new String(value, StandardCharsets.UTF_8); }
+    private static byte[] bytes(String value) { return value.getBytes(StandardCharsets.UTF_8); }
+    private static byte[] encoded(Object value) { return value == null ? null : bytes((String) value); }
+    private static AssertionError unsupported(String operation) { return new AssertionError("FakeStringRedis does not support: " + operation); }
+}

+ 5 - 3
video-service/src/test/java/com/zksy/video/lifecycle/Gb28181LifecycleMediaTest.java

@@ -114,12 +114,14 @@ class Gb28181LifecycleMediaTest {
         verifyNoInteractions(play);
         verifyNoInteractions(play);
     }
     }
 
 
-    @Test void booleanStopProofAndNoLateStartAreBothRequired() {
+    @Test void exactDeepTerminationCanSettleALostInFlightReply() {
         VideoLifecycleRecord record = record(); MediaServer node = onlineNode(); absent(node, record);
         VideoLifecycleRecord record = record(); MediaServer node = onlineNode(); absent(node, record);
-        when(play.stopManaged(node, device, channel, record.getStream())).thenReturn(false, true, true);
-        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
         record.setStartInFlight(true);
         record.setStartInFlight(true);
+        when(play.stopManaged(node, device, channel, record.getStream())).thenReturn(false, true, true);
         assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
         assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        Map<String, Object> confirmed = adapter.cancel(record);
+        assertEquals("STOPPED", confirmed.get("status"));
+        assertEquals(true, confirmed.get("allocationClosed"));
         record.setStartInFlight(false);
         record.setStartInFlight(false);
         assertEquals("STOPPED", adapter.cancel(record).get("status"));
         assertEquals("STOPPED", adapter.cancel(record).get("status"));
         verify(play, times(3)).stopManaged(node, device, channel, record.getStream());
         verify(play, times(3)).stopManaged(node, device, channel, record.getStream());

+ 442 - 0
video-service/src/test/java/com/zksy/video/lifecycle/LateSipRecoveryTest.java

@@ -0,0 +1,442 @@
+package com.zksy.video.lifecycle;
+
+import com.ruoyi.wvp.common.InviteSessionType;
+import com.ruoyi.wvp.conf.UserSetting;
+import com.ruoyi.wvp.gb28181.bean.*;
+import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
+import com.ruoyi.wvp.service.bean.SSRCInfo;
+import org.junit.jupiter.api.Test;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.ReturnType;
+import org.springframework.data.redis.core.*;
+import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/** External Redis substitute retains serialized bytes, never references to application objects. */
+class LateSipRecoveryTest {
+    @Test void adoptionSurvivesManagerReconstructionAndDoesNotShareMutableDialogs() {
+        RedisBytes external = new RedisBytes();
+        SipInviteSessionManager first = external.manager();
+        SsrcTransaction original = dialog("legacy", "call-1");
+        SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1");
+        first.put(original);
+        assertTrue(first.retainAdopted(original, allocation));
+        original.getSipTransactionInfo().setToTag("mutated-after-write");
+        allocation.setTimeOutTaskKey("mutated-after-write");
+        SipInviteSessionManager restarted = external.manager();
+        SsrcTransaction persisted = restarted.getSsrcTransactionByCallId("call-1");
+        assertEquals("to-1", persisted.getSipTransactionInfo().getToTag());
+        assertTrue(restarted.isAdopted(persisted));
+        assertTrue(restarted.isAdoptedRtp("node-a", "call-1",
+                new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1")));
+        assertFalse(restarted.isAdoptedRtp("node-b", "call-1",
+                new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1")));
+    }
+
+    @Test void realByeAfterCallbackLossConfirmsOnlyTheOriginalAllocationAcrossReconstruction() throws Exception {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager first = external.manager();
+        SsrcTransaction original = dialog("managed_11111111111111111111111111111111", "call-1"); first.put(original);
+        javax.sip.message.Request request = request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1");
+        assertTrue(first.rememberBye(request, original));
+        assertFalse(external.manager().isByeConfirmed(original));
+        assertNull(external.manager().confirmBye(response("BYE", "call-1", 42, "z9hG4bK-bye", "to-1")));
+        assertNull(external.manager().confirmBye(response("INVITE", "call-1", 41, "z9hG4bK-bye", "to-1")));
+        assertNull(external.manager().confirmBye(response("BYE", "call-1", 41, "z9hG4bK-wrong", "to-1")));
+        assertNull(external.manager().confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "other-dialog")));
+        SipInviteSessionManager restarted = external.manager();
+        assertNotNull(restarted.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
+        assertTrue(external.manager().isByeConfirmed(original));
+        assertTrue(external.manager().isSipTerminated(original));
+        assertTrue(restarted.removeManagedIfSame(original));
+        SsrcTransaction replacement = dialog(original.getStream(), "call-1"); replacement.setSsrc("9999999999");
+        replacement.getSipTransactionInfo().setToTag("to-new"); restarted.put(replacement);
+        assertNotNull(restarted.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
+        assertFalse(restarted.removeManagedIfSame(original));
+        assertFalse(external.manager().isByeConfirmed(replacement));
+        assertEquals("to-new", restarted.getSsrcTransactionByStream("rtp", original.getStream()).getSipTransactionInfo().getToTag());
+    }
+
+    @Test void pendingInviteRecoversFromBytesWithoutCallbackAndRejectsForeignResponseBindings() throws Exception {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager first = external.manager();
+        SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1");
+        assertTrue(first.rememberInvite(request("INVITE", "invite-1", 9, "z9hG4bK-invite", null),
+                "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
+        SipInviteSessionManager restarted = external.manager();
+        assertNull(restarted.restoreManagedInvite(response("INVITE", "other-call", 9, "z9hG4bK-invite", "to-1")));
+        assertNull(restarted.restoreManagedInvite(response("INVITE", "invite-1", 10, "z9hG4bK-invite", "to-1")));
+        assertNull(restarted.restoreManagedInvite(response("INVITE", "invite-1", 9, "z9hG4bK-foreign", "to-1")));
+        gov.nist.javax.sip.message.SIPResponse wrongFrom = response("INVITE", "invite-1", 9, "z9hG4bK-invite", "to-1");
+        wrongFrom.getFrom().setTag("foreign-from"); assertNull(restarted.restoreManagedInvite(wrongFrom));
+        gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "invite-1", 9, "z9hG4bK-invite", "to-1");
+        SsrcTransaction restored = restarted.restoreManagedInvite(actual);
+        assertNotNull(restored); assertEquals("node-a", restored.getMediaServerId()); assertEquals("device-a", restored.getDeviceId());
+        assertEquals("to-1", restored.getSipTransactionInfo().getToTag()); assertEquals("1234567890", restored.getSsrc());
+        assertEquals("timeout-1", restarted.matchPendingInvite(actual).getTimeoutToken());
+        assertEquals("127.0.0.1", restarted.matchPendingInvite(actual).getLocalIp());
+        assertTrue(restarted.matchPendingInvite(actual).isExpired());
+        SsrcTransaction replacement = dialog(allocation.getStream(), "new-call"); restarted.put(replacement);
+        assertNull(restarted.restoreManagedInvite(actual));
+        assertEquals("new-call", restarted.getSsrcTransactionByStream("rtp", allocation.getStream()).getCallId());
+    }
+
+    @Test void observerRecordsLateByeWithEmptySubscriptionsBeforeDeletingTheDialog() throws Exception {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
+        SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); sessions.put(owned);
+        assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
+        com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver observer = new com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver();
+        ReflectionTestUtils.setField(observer, "sessionManager", external.manager());
+        com.ruoyi.wvp.gb28181.event.SipSubscribe expired = new com.ruoyi.wvp.gb28181.event.SipSubscribe();
+        expired.addSubscribe("call-141", com.ruoyi.wvp.gb28181.event.sip.SipEvent.getInstance("call-141", result -> fail("expired callback must not execute"), null, -1));
+        expired.execute(); assertTrue(expired.isEmpty());
+        ReflectionTestUtils.setField(observer, "sipSubscribe", expired);
+        javax.sip.Dialog sipDialog = mock(javax.sip.Dialog.class);
+        doAnswer(i -> { assertTrue(external.manager().isByeConfirmed(owned)); return null; }).when(sipDialog).delete();
+        observer.processResponse(new javax.sip.ResponseEvent(this, null, sipDialog,
+                response("BYE", "call-1", 41, "z9hG4bK-wrong", "to-1")));
+        verify(sipDialog, never()).delete(); assertFalse(sessions.isByeConfirmed(owned));
+        observer.processResponse(new javax.sip.ResponseEvent(this, null, sipDialog,
+                response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
+        verify(sipDialog).delete(); assertTrue(external.manager().isByeConfirmed(owned));
+        assertNull(external.manager().getSsrcTransactionByStream("rtp", owned.getStream()));
+    }
+
+    @Test void deletionCasCannotEraseAReplacementFromAnotherServiceInstance() throws Exception {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
+        SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); sessions.put(owned);
+        assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
+        assertNotNull(sessions.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
+        SsrcTransaction replacement = dialog(owned.getStream(), "call-2");
+        external.beforeCas = () -> external.manager().put(replacement);
+        assertFalse(sessions.removeManagedIfSame(owned));
+        assertEquals("call-2", sessions.getSsrcTransactionByStream("rtp", owned.getStream()).getCallId());
+        assertNotNull(sessions.getSsrcTransactionByCallId("call-1"), "CAS loses both deletes, not only the stream delete");
+    }
+
+    @Test void inviteRetransmitAfterConfirmedByeDoesNotResurrectTheAllocation() throws Exception {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
+        SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1");
+        assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
+                "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
+        gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
+        SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
+        assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
+        assertNotNull(sessions.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
+        assertTrue(sessions.removeManagedIfSame(owned));
+        assertNull(external.manager().restoreManagedInvite(actual));
+        assertNull(external.manager().getSsrcTransactionByStream("rtp", allocation.getStream()));
+    }
+
+    @Test void lateInviteWithoutCallbackAcksMalformedSdpThenStopsOnlyPersistedOriginalSource() throws Exception {
+        InviteFixture f = new InviteFixture();
+        gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
+        actual.setContent("unparseable SDP\r\ny=do-not-associate-by-body", javax.sip.SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
+        f.processor.process(f.event(actual));
+        org.mockito.InOrder order = inOrder(f.sender, f.play);
+        order.verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
+        order.verify(f.play).stopManaged(f.node, f.device, f.channel, f.stream);
+        SsrcTransaction persisted = f.external.manager().getSsrcTransactionByStream("rtp", f.stream);
+        assertNotNull(persisted); assertEquals("to-1", persisted.getSipTransactionInfo().getToTag());
+        assertEquals("1234567890", persisted.getSsrc());
+        verify(f.media, never()).getDefaultMediaServer();
+        verify(f.channels).getOneForSource("device-a", "channel-a");
+    }
+
+    @Test void unrelatedInviteStillGetsLegacyAckButCannotRecoverOrStopAnOwnedStream() throws Exception {
+        InviteFixture f = new InviteFixture();
+        f.processor.process(f.event(response("INVITE", "foreign-call", 9, "z9hG4bK-invite", "to-1")));
+        verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
+        verifyNoInteractions(f.play, f.media, f.channels, f.devices);
+        assertNull(f.external.manager().getSsrcTransactionByStream("rtp", f.stream));
+    }
+
+    @Test void retransmittedInviteForAnActiveGenerationOnlyResendsAck() throws Exception {
+        InviteFixture f = new InviteFixture();
+        f.generation.setStatus("ACTIVE");
+        // The original start deadline is old, but healthy playback is not a new start attempt.
+        f.processor.process(f.event(response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1")));
+        verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
+        verifyNoInteractions(f.play);
+    }
+
+    @Test void sourceScopedLookupMismatchRetainsTheDialogWithoutStoppingAnotherSource() throws Exception {
+        InviteFixture f = new InviteFixture(); f.channel.setId(99);
+        f.processor.process(f.event(response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1")));
+        verifyNoInteractions(f.play); assertNotNull(f.external.manager().getSsrcTransactionByStream("rtp", f.stream));
+    }
+
+    @Test void peerByePersistsIndependentTerminationAndFencesInviteRetransmit() throws Exception {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
+        SSRCInfo allocation = allocation();
+        assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
+                "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
+        gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
+        SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
+        assertTrue(sessions.rememberPeerBye(peerBye(owned), owned));
+        SipInviteSessionManager restarted = external.manager();
+        assertTrue(restarted.isSipTerminated(owned));
+        assertFalse(restarted.isByeConfirmed(owned), "peer BYE is not an outgoing BYE response");
+        assertTrue(restarted.removeManagedIfSame(owned));
+        assertNull(external.manager().restoreManagedInvite(actual));
+        assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
+    }
+
+    @Test void malformedForeignAndReplacedPeerRequestsCannotBecomeTerminationEvidence() throws Exception {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
+        SsrcTransaction owned = dialog("legacy", "call-1");
+        assertFalse(sessions.rememberPeerBye(peerBye(owned), owned), "unknown dialogs cannot acquire peer evidence");
+        sessions.put(owned);
+        gov.nist.javax.sip.message.SIPRequest wrongTags = peerBye(owned);
+        wrongTags.getFrom().setTag("foreign");
+        assertFalse(sessions.rememberPeerBye(wrongTags, owned));
+        gov.nist.javax.sip.message.SIPRequest wrongCall = peerBye(owned);
+        wrongCall.getCallIdHeader().setCallId("foreign-call");
+        assertFalse(sessions.rememberPeerBye(wrongCall, owned));
+        gov.nist.javax.sip.message.SIPRequest wrongCseq = peerBye(owned);
+        wrongCseq.getCSeqHeader().setMethod("INVITE");
+        assertFalse(sessions.rememberPeerBye(wrongCseq, owned));
+        gov.nist.javax.sip.message.SIPRequest noBranch = peerBye(owned);
+        noBranch.getTopmostViaHeader().removeParameter("branch");
+        assertFalse(sessions.rememberPeerBye(noBranch, owned));
+        assertFalse(sessions.rememberPeerBye(request("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1"), owned));
+        SsrcTransaction replacement = dialog("legacy", "call-1");
+        replacement.getSipTransactionInfo().setToTag("new-tags");
+        external.beforeCas = () -> external.manager().put(replacement);
+        assertFalse(sessions.rememberPeerBye(peerBye(owned), owned));
+        assertFalse(external.manager().isSipTerminated(owned));
+        assertFalse(external.manager().isSipTerminated(replacement));
+        assertFalse(sessions.rememberPeerBye(peerBye(owned), replacement));
+        assertFalse(sessions.removeIfSame(owned));
+        assertEquals("new-tags", external.manager().getSsrcTransactionByCallId("call-1").getSipTransactionInfo().getToTag());
+    }
+
+    @Test void snapshotDeleteIsAtomicAcrossBothIndexesWithoutInventingProtocolEvidence() {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
+        SsrcTransaction owned = dialog("legacy", "call-1"); sessions.put(owned);
+        SsrcTransaction replacement = dialog("legacy", "call-1");
+        replacement.getSipTransactionInfo().setToTag("new-tags");
+        external.beforeCas = () -> external.manager().put(replacement);
+        assertFalse(sessions.removeIfSame(owned));
+        assertTrue(SipInviteSessionManager.sameDialog(replacement, external.manager().getSsrcTransactionByCallId("call-1")));
+        assertTrue(SipInviteSessionManager.sameDialog(replacement, external.manager().getSsrcTransactionByStream("rtp", "legacy")));
+        assertTrue(external.manager().removeIfSame(replacement));
+        assertFalse(external.manager().isSipTerminated(replacement), "offline cleanup is not SIP termination");
+        assertFalse(external.manager().isByeConfirmed(replacement));
+    }
+
+    @Test void peerMarkerArrivingBetweenRestoreReadAndCasCannotResurrectDialog() throws Exception {
+        RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
+        assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
+                "node-a", "device-a", 7, "channel-a", allocation(), "127.0.0.1", 1L));
+        gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
+        SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
+        gov.nist.javax.sip.message.SIPRequest peer = peerBye(owned);
+        external.beforeCas = () -> {
+            assertTrue(external.manager().rememberPeerBye(peer, owned));
+            assertTrue(external.manager().removeIfSame(owned));
+        };
+        assertNull(sessions.restoreManagedInvite(actual));
+        assertTrue(external.manager().isSipTerminated(owned));
+        assertNull(external.manager().getSsrcTransactionByStream("rtp", owned.getStream()));
+    }
+
+    static gov.nist.javax.sip.message.SIPRequest peerBye(SsrcTransaction owned) throws Exception {
+        gov.nist.javax.sip.message.SIPRequest peer = (gov.nist.javax.sip.message.SIPRequest)
+                request("BYE", owned.getCallId(), 77, "z9hG4bK-peer", owned.getSipTransactionInfo().getFromTag());
+        peer.getFrom().setTag(owned.getSipTransactionInfo().getToTag());
+        return peer;
+    }
+
+    static class InviteFixture {
+        final RedisBytes external = new RedisBytes();
+        final String stream = "managed_11111111111111111111111111111111";
+        final com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor processor = new com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor();
+        final com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
+        final com.ruoyi.wvp.gb28181.service.IPlayService play = mock(com.ruoyi.wvp.gb28181.service.IPlayService.class);
+        final com.ruoyi.wvp.media.service.IMediaServerService media = mock(com.ruoyi.wvp.media.service.IMediaServerService.class);
+        final com.ruoyi.wvp.gb28181.service.IDeviceChannelService channels = mock(com.ruoyi.wvp.gb28181.service.IDeviceChannelService.class);
+        final com.ruoyi.wvp.storager.IRedisCatchStorage devices = mock(com.ruoyi.wvp.storager.IRedisCatchStorage.class);
+        final com.ruoyi.wvp.media.bean.MediaServer node = new com.ruoyi.wvp.media.bean.MediaServer();
+        final Device device = new Device(); final DeviceChannel channel = new DeviceChannel();
+        final VideoLifecycleStore lifecycle = mock(VideoLifecycleStore.class);
+        final VideoLifecycleRecord generation = new VideoLifecycleRecord();
+        InviteFixture() throws Exception {
+            generation.setGeneration("11111111-1111-1111-1111-111111111111");
+            generation.setStatus("STARTING"); generation.setDeadline(1L);
+            when(lifecycle.find(generation.getGeneration())).thenReturn(generation);
+            SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", stream, "timeout-1");
+            assertTrue(external.manager().rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
+                    "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
+            node.setId("node-a"); device.setDeviceId("device-a"); channel.setId(7); channel.setDeviceId("channel-a");
+            when(media.getOne("node-a")).thenReturn(node); when(devices.getDevice("device-a")).thenReturn(device);
+            when(channels.getOneForSource("device-a", "channel-a")).thenReturn(channel);
+            com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider headers = mock(com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider.class);
+            when(headers.createAckRequest(anyString(), any(), any())).thenReturn(request("ACK", "call-1", 9, "z9hG4bK-ack", "to-1"));
+            ReflectionTestUtils.setField(processor, "sessionManager", external.manager());
+            ReflectionTestUtils.setField(processor, "sipSender", sender); ReflectionTestUtils.setField(processor, "headerProvider", headers);
+            ReflectionTestUtils.setField(processor, "playService", play); ReflectionTestUtils.setField(processor, "mediaServerService", media);
+            ReflectionTestUtils.setField(processor, "redisCatchStorage", devices); ReflectionTestUtils.setField(processor, "deviceChannelService", channels);
+            ReflectionTestUtils.setField(processor, "videoLifecycleStore", lifecycle);
+        }
+        gov.nist.javax.sip.ResponseEventExt event(gov.nist.javax.sip.message.SIPResponse response) throws Exception {
+            gov.nist.javax.sip.message.SIPResponse received = spy(response);
+            when(received.getLocalAddress()).thenReturn(java.net.InetAddress.getByName("127.0.0.1"));
+            gov.nist.javax.sip.ResponseEventExt event = mock(gov.nist.javax.sip.ResponseEventExt.class);
+            when(event.getResponse()).thenReturn(received); when(event.getRemoteIpAddress()).thenReturn("127.0.0.2"); when(event.getRemotePort()).thenReturn(5060);
+            return event;
+        }
+    }
+
+    @Test void commanderPersistsBeforeInviteSendAndOriginalCallbackAcceptsOnlyBoundResponse() throws Exception {
+        RedisBytes external = new RedisBytes();
+        com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
+        com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
+        java.util.concurrent.atomic.AtomicReference<com.ruoyi.wvp.gb28181.event.SipSubscribe.Event> callback = new java.util.concurrent.atomic.AtomicReference<>();
+        doAnswer(i -> {
+            assertNotNull(external.manager().getPendingInviteByStream("rtp", "managed_11111111111111111111111111111111"));
+            callback.set(i.getArgument(3)); return null;
+        }).when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any(), anyLong());
+        java.util.concurrent.atomic.AtomicInteger published = new java.util.concurrent.atomic.AtomicInteger();
+        commander.playStreamCmd(node(), allocation(), device(), channel(), result -> published.incrementAndGet(), result -> { }, 60000L);
+        callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
+                response("INVITE", "call-1", 9, "z9hG4bK-wrong", "to-1"))));
+        assertEquals(0, published.get()); assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
+        callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
+                response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1"))));
+        assertEquals(1, published.get()); assertNotNull(external.manager().getSsrcTransactionByCallId("call-1"));
+    }
+
+    @Test void commanderNeverSendsInviteWhenPreDispatchPersistenceFails() throws Exception {
+        RedisBytes external = new RedisBytes(); external.rejectCas = true;
+        com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
+        com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
+        assertThrows(javax.sip.SipException.class, () -> commander.playStreamCmd(node(), allocation(), device(), channel(), result -> { }, result -> { }, 60000L));
+        verify(sender, never()).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any(), anyLong());
+    }
+
+    @Test void commanderByeCallbackPersistsConfirmationBeforeNotifyingCaller() throws Exception {
+        RedisBytes external = new RedisBytes(); SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); external.manager().put(owned);
+        com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
+        com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
+        java.util.concurrent.atomic.AtomicReference<com.ruoyi.wvp.gb28181.event.SipSubscribe.Event> callback = new java.util.concurrent.atomic.AtomicReference<>();
+        doAnswer(i -> { assertTrue(external.manager().hasByeRequest(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"))); callback.set(i.getArgument(3)); return null; })
+                .when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any());
+        java.util.concurrent.atomic.AtomicInteger notified = new java.util.concurrent.atomic.AtomicInteger();
+        commander.streamByeCmd(device(), "channel-a", "rtp", owned.getStream(), "call-1", result -> {
+            assertTrue(external.manager().isByeConfirmed(owned)); notified.incrementAndGet();
+        });
+        assertFalse(external.manager().isByeConfirmed(owned));
+        callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
+                response("INVITE", "call-1", 41, "z9hG4bK-bye", "to-1"))));
+        assertEquals(0, notified.get());
+        callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
+                response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"))));
+        assertEquals(1, notified.get()); assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
+    }
+
+    static com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander(RedisBytes external, com.ruoyi.wvp.gb28181.transmit.SIPSender sender) throws Exception {
+        com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = new com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander();
+        com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider headers = mock(com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider.class);
+        when(headers.createInviteRequest(any(), anyString(), anyString(), anyString(), anyString(), isNull(), anyString(), any()))
+                .thenReturn(request("INVITE", "call-1", 9, "z9hG4bK-invite", null));
+        when(headers.createByteRequest(any(), anyString(), any())).thenReturn(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"));
+        com.ruoyi.wvp.gb28181.SipLayer layer = mock(com.ruoyi.wvp.gb28181.SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
+        UserSetting settings = new UserSetting(); settings.setSeniorSdp(false);
+        ReflectionTestUtils.setField(commander, "sessionManager", external.manager()); ReflectionTestUtils.setField(commander, "sipSender", sender);
+        ReflectionTestUtils.setField(commander, "headerProvider", headers); ReflectionTestUtils.setField(commander, "sipLayer", layer);
+        ReflectionTestUtils.setField(commander, "videoLifecycleStore", mock(VideoLifecycleStore.class)); ReflectionTestUtils.setField(commander, "userSetting", settings);
+        return commander;
+    }
+    static Device device() { Device d = new Device(); d.setDeviceId("device-a"); d.setStreamMode("UDP"); return d; }
+    static DeviceChannel channel() { DeviceChannel c = new DeviceChannel(); c.setId(7); c.setDeviceId("channel-a"); return c; }
+    static com.ruoyi.wvp.media.bean.MediaServer node() { com.ruoyi.wvp.media.bean.MediaServer n = new com.ruoyi.wvp.media.bean.MediaServer(); n.setId("node-a"); n.setSdpIp("127.0.0.1"); return n; }
+    static SSRCInfo allocation() { return new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1"); }
+
+    static javax.sip.message.Request request(String method, String call, long seq, String branch, String toTag) throws Exception {
+        return javax.sip.SipFactory.getInstance().createMessageFactory().createRequest(
+                method + " sip:channel@127.0.0.2:5060 SIP/2.0\r\n" + headers(method, call, seq, branch, toTag));
+    }
+    static gov.nist.javax.sip.message.SIPResponse response(String method, String call, long seq, String branch, String toTag) throws Exception {
+        return (gov.nist.javax.sip.message.SIPResponse) javax.sip.SipFactory.getInstance().createMessageFactory()
+                .createResponse("SIP/2.0 200 OK\r\n" + headers(method, call, seq, branch, toTag));
+    }
+    static String headers(String method, String call, long seq, String branch, String toTag) {
+        return "Via: SIP/2.0/UDP 127.0.0.1:5060;branch=" + branch + "\r\n"
+                + "From: <sip:server@127.0.0.1>;tag=from-1\r\nTo: <sip:channel@127.0.0.2>" + (toTag == null ? "" : ";tag=" + toTag)
+                + "\r\nCall-ID: " + call + "\r\nCSeq: " + seq + " " + method + "\r\nMax-Forwards: 70\r\nContent-Length: 0\r\n\r\n";
+    }
+
+    static SsrcTransaction dialog(String stream, String call) {
+        SsrcTransaction tx = new SsrcTransaction();
+        tx.setDeviceId("device-a"); tx.setChannelId(7); tx.setApp("rtp"); tx.setStream(stream);
+        tx.setMediaServerId("node-a"); tx.setSsrc("1234567890"); tx.setCallId(call); tx.setType(InviteSessionType.PLAY);
+        SipTransactionInfo sip = new SipTransactionInfo(); sip.setCallId(call); sip.setFromTag("from-1");
+        sip.setToTag("to-1"); sip.setViaBranch("z9hG4bK-invite"); tx.setSipTransactionInfo(sip); return tx;
+    }
+
+    static class RedisBytes {
+        final Map<String, Map<String, byte[]>> data = new HashMap<>();
+        final StringRedisSerializer strings = new StringRedisSerializer();
+        final GenericJackson2JsonRedisSerializer values = new GenericJackson2JsonRedisSerializer();
+        Runnable beforeCas;
+        boolean rejectCas;
+        @SuppressWarnings({"unchecked", "rawtypes"})
+        RedisTemplate<Object,Object> client() {
+            RedisTemplate<Object,Object> redis = mock(RedisTemplate.class);
+            HashOperations<Object,Object,Object> hashes = mock(HashOperations.class);
+            when(redis.opsForHash()).thenReturn(hashes);
+            when(redis.getKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
+            when(redis.getHashKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
+            doReturn(values).when(redis).getHashValueSerializer();
+            doAnswer(i -> { put(i.getArgument(0).toString(), i.getArgument(1).toString(), values.serialize(i.getArgument(2))); return null; })
+                    .when(hashes).put(any(), any(), any());
+            when(hashes.get(any(), any())).thenAnswer(i -> values.deserialize(get(i.getArgument(0).toString(), i.getArgument(1).toString())));
+            when(hashes.values(any())).thenAnswer(i -> {
+                List<Object> result = new ArrayList<>();
+                for (byte[] bytes : data.getOrDefault(i.getArgument(0).toString(), Collections.emptyMap()).values()) result.add(values.deserialize(bytes));
+                return result;
+            });
+            when(hashes.delete(any(), any())).thenAnswer(i -> data.getOrDefault(i.getArgument(0).toString(), Collections.emptyMap()).remove(i.getArgument(1).toString()) == null ? 0L : 1L);
+            RedisConnection connection = mock(RedisConnection.class);
+            when(redis.execute(any(RedisCallback.class))).thenAnswer(i -> ((RedisCallback<?>) i.getArgument(0)).doInRedis(connection));
+            when(connection.eval(any(byte[].class), eq(ReturnType.INTEGER), anyInt(), org.mockito.ArgumentMatchers.<byte[][]>any())).thenAnswer(i -> {
+                if (rejectCas) return 0L;
+                if (beforeCas != null) { Runnable race = beforeCas; beforeCas = null; race.run(); }
+                int n = i.getArgument(2);
+                Object[] invocation = i.getArguments();
+                byte[][] args = invocation.length == 4 && invocation[3] instanceof byte[][]
+                        ? (byte[][]) invocation[3] : Arrays.copyOfRange(invocation, 3, invocation.length, byte[][].class);
+                // Emulate the generic compare-all-then-write-all Lua at the external Redis boundary.
+                synchronized (data) {
+                    for (int k = 0; k < n; k++) {
+                        int a = n + k * 5;
+                        byte[] expected = "1".equals(text(args[a+1])) ? args[a+2] : null;
+                        if (!Arrays.equals(expected, get(text(args[k]), text(args[a])))) return 0L;
+                    }
+                    for (int k = 0; k < n; k++) {
+                        int a = n + k * 5;
+                        if ("1".equals(text(args[a+3]))) put(text(args[k]), text(args[a]), args[a+4]);
+                        else data.computeIfAbsent(text(args[k]), unused -> new HashMap<>()).remove(text(args[a]));
+                    }
+                    return 1L;
+                }
+            });
+            return redis;
+        }
+        SipInviteSessionManager manager() {
+            SipInviteSessionManager result = new SipInviteSessionManager();
+            UserSetting settings = new UserSetting(); settings.setServerId("late-test");
+            ReflectionTestUtils.setField(result, "userSetting", settings);
+            ReflectionTestUtils.setField(result, "redisTemplate", client()); return result;
+        }
+        byte[] get(String key, String field) { byte[] bytes = data.getOrDefault(key, Collections.emptyMap()).get(field); return bytes == null ? null : bytes.clone(); }
+        void put(String key, String field, byte[] bytes) { data.computeIfAbsent(key, unused -> new HashMap<>()).put(field, bytes.clone()); }
+        static String text(byte[] value) { return new String(value, StandardCharsets.UTF_8); }
+    }
+}

+ 410 - 0
video-service/src/test/java/com/zksy/video/lifecycle/LegacyRtpLifecycleCompatibilityTest.java

@@ -0,0 +1,410 @@
+package com.zksy.video.lifecycle;
+
+import com.ruoyi.wvp.common.InviteInfo;
+import com.ruoyi.wvp.common.InviteSessionStatus;
+import com.ruoyi.wvp.common.InviteSessionType;
+import com.ruoyi.wvp.common.StreamInfo;
+import com.ruoyi.wvp.common.VideoManagerConstants;
+import com.ruoyi.wvp.conf.DynamicTask;
+import com.ruoyi.wvp.conf.UserSetting;
+import com.ruoyi.wvp.gb28181.service.impl.DeviceChannelServiceImpl;
+import com.ruoyi.wvp.gb28181.service.impl.DeviceServiceImpl;
+import com.ruoyi.wvp.gb28181.session.SSRCFactory;
+import com.ruoyi.wvp.gb28181.transmit.event.request.impl.ByeRequestProcessor;
+import com.ruoyi.wvp.mapper.DeviceChannelMapper;
+import com.ruoyi.wvp.mapper.DeviceMapper;
+import com.ruoyi.wvp.media.service.impl.MediaServerServiceImpl;
+import com.ruoyi.wvp.media.zlm.ZLMMediaNodeServerService;
+import com.ruoyi.wvp.media.zlm.ZLMServerFactory;
+import com.ruoyi.wvp.storager.impl.RedisCatchStorageImpl;
+import gov.nist.javax.sip.message.SIPRequest;
+import com.ruoyi.wvp.service.bean.SSRCInfo;
+import org.junit.jupiter.api.Test;
+
+import java.net.InetAddress;
+import java.util.List;
+import java.util.Map;
+import javax.sip.RequestEvent;
+import javax.sip.SipFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+import static com.zksy.video.lifecycle.VideoStopReceiptRestartTest.wire;
+
+/** Exercises old entry points with real Play/RTP/MediaServer and serialized external substitutes. */
+class LegacyRtpLifecycleCompatibilityTest {
+    private static final String LEGACY = "device_channel";
+
+    @Test void unadoptedLegacyOpenIsProvenanceNotAnExclusiveNameLease() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance first = new VideoStopReceiptRestartTest.Instance(world);
+        SSRCInfo old = first.open(LEGACY); assertNotNull(old);
+        VideoStopReceiptRestartTest.Instance restarted = new VideoStopReceiptRestartTest.Instance(world);
+        SSRCInfo replacement = restarted.open(LEGACY); assertNotNull(replacement);
+        assertNotEquals(old.getTimeOutTaskKey(), replacement.getTimeOutTaskKey());
+        first.rtp.closeRTPServer(world.node, old);
+        assertTrue(world.closeRequests.isEmpty());
+        assertTrue(world.open.contains(LEGACY));
+    }
+
+    @Test void adoptedOpenAndUnconfirmedCloseStillFenceSameNameAfterRestart() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance first = new VideoStopReceiptRestartTest.Instance(world);
+        first.legacy("call-old"); String handle = first.adopt(); assertNotNull(handle);
+        assertNull(new VideoStopReceiptRestartTest.Instance(world).open(LEGACY));
+        world.delayClose = true;
+        assertFalse(first.stopAdopted(handle));
+        assertNull(new VideoStopReceiptRestartTest.Instance(world).open(LEGACY));
+        assertEquals(1, world.openRequests.get());
+        assertEquals(List.of(LEGACY), world.closeRequests);
+    }
+
+    @Test void legacyCreatingAndClosingWithoutAcknowledgementCannotReopen() throws Exception {
+        VideoStopReceiptRestartTest.External creating = new VideoStopReceiptRestartTest.External();
+        creating.throwDuringOpen = true;
+        VideoStopReceiptRestartTest.Instance first = new VideoStopReceiptRestartTest.Instance(creating);
+        assertThrows(IllegalStateException.class, () -> first.open(LEGACY));
+        assertNull(new VideoStopReceiptRestartTest.Instance(creating).open(LEGACY));
+        assertEquals(1, creating.openRequests.get());
+
+        VideoStopReceiptRestartTest.External closing = new VideoStopReceiptRestartTest.External();
+        closing.delayClose = true;
+        VideoStopReceiptRestartTest.Instance second = new VideoStopReceiptRestartTest.Instance(closing);
+        SSRCInfo old = second.open(LEGACY); second.rtp.closeRTPServer(closing.node, old);
+        assertNull(new VideoStopReceiptRestartTest.Instance(closing).open(LEGACY));
+        assertEquals(1, closing.openRequests.get());
+    }
+
+    @Test void migrationCasCannotRegisterOldAllocationOverAConcurrentNewToken() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance oldProcess = new VideoStopReceiptRestartTest.Instance(world);
+        VideoStopReceiptRestartTest.Instance newProcess = new VideoStopReceiptRestartTest.Instance(world);
+        SSRCInfo old = new SSRCInfo(30000, "123450001", "rtp", LEGACY, "pre-upgrade-token");
+        world.redis.beforeExec = () -> assertNotNull(newProcess.open(LEGACY));
+        oldProcess.rtp.closeRTPServer(world.node, old);
+        assertTrue(world.closeRequests.isEmpty());
+        assertEquals(1, world.openRequests.get());
+        assertTrue(world.open.contains(LEGACY));
+        oldProcess.rtp.closeRTPServer(world.node, old);
+        assertTrue(world.closeRequests.isEmpty());
+    }
+
+    @Test void missingManagedReceiptIsUnknownAndNeverMigratedFromSsrcInfo() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        SSRCInfo unknown = new SSRCInfo(30000, "123450001", "rtp",
+                "managed_11111111111111111111111111111111", "unknown-token");
+        assertFalse(instance.rtp.closeManagedRTPServer(world.node, unknown));
+        assertTrue(world.closeRequests.isEmpty());
+    }
+
+    @Test void peerByeForAnOldCallCannotCloseTheNewSameNameDialog() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        instance.legacy("call-old");
+        instance.legacy("call-new"); // Old Call-ID index still exists, but no longer owns the stream.
+        peerProcessor(world, instance).process(peerBye("call-old"));
+        assertTrue(world.closeRequests.isEmpty());
+        assertEquals("call-new", instance.sessions.getSsrcTransactionByStream("rtp", LEGACY).getCallId());
+        assertNotNull(instance.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY));
+    }
+
+    @Test void ordinaryPeerByeClosesExactlyAndAllowsSameNameReplay() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        SSRCInfo original = instance.legacy("call-old");
+        InviteInfo running = instance.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY);
+        StreamInfo stream = new StreamInfo(); stream.setMediaServer(world.node);
+        running.setStreamInfo(stream); running.setStatus(InviteSessionStatus.ok); instance.invites.updateInviteInfo(running);
+        ByeRequestProcessor bye = peerProcessor(world, instance);
+        bye.process(peerBye("call-old"));
+        assertEquals(List.of(LEGACY), world.closeRequests);
+        assertNull(instance.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY));
+        assertNull(instance.sessions.getSsrcTransactionByCallId("call-old"));
+        SSRCInfo replacement = instance.legacy("call-new");
+        instance.rtp.closeRTPServer(world.node, original);
+        assertEquals(1, world.closeRequests.size());
+        assertNotEquals(original.getTimeOutTaskKey(), replacement.getTimeOutTaskKey());
+    }
+
+    @Test void pendingPeerCloseRetainsOriginalEvidenceAndBlocksReplayUntilPositiveReply() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        world.delayClose = true;
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        instance.legacy("call-old");
+        ByeRequestProcessor bye = peerProcessor(world, instance);
+        bye.process(peerBye("call-old"));
+        assertNotNull(instance.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY));
+        assertNull(new VideoStopReceiptRestartTest.Instance(world).open(LEGACY));
+        world.closeReplies.get(0).run();
+        bye.process(peerBye("call-old"));
+        assertEquals(1, world.closeRequests.size());
+        assertNotNull(new VideoStopReceiptRestartTest.Instance(world).open(LEGACY));
+    }
+
+    @Test void adoptedPeerByeSettlesRtpWithIndependentSipTerminationAfterRestart() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        instance.legacy("call-old"); String handle = instance.adopt(); assertNotNull(handle);
+        com.ruoyi.wvp.gb28181.bean.SsrcTransaction original = instance.sessions.getSsrcTransactionByCallId("call-old");
+        java.util.concurrent.atomic.AtomicInteger replies = new java.util.concurrent.atomic.AtomicInteger();
+        doAnswer(i -> {
+            javax.sip.message.Response response = i.getArgument(1);
+            assertEquals(200, response.getStatusCode());
+            assertFalse(instance.sessions.isSipTerminated(original), "termination must not be persisted before the 200 reply");
+            replies.incrementAndGet(); return null;
+        }).when(world.sender).transmitRequest(anyString(), any(javax.sip.message.Message.class));
+        peerProcessor(world, instance).process(peerBye("call-old"));
+        assertEquals(1, replies.get());
+        assertEquals(List.of(LEGACY), world.closeRequests);
+        VideoStopReceiptRestartTest.Instance restarted = new VideoStopReceiptRestartTest.Instance(world);
+        assertTrue(restarted.sessions.isSipTerminated(original));
+        assertFalse(restarted.sessions.isByeConfirmed(original), "peer BYE never invents outgoing confirmation");
+        assertNull(restarted.sessions.getSsrcTransactionByCallId("call-old"));
+        assertTrue(restarted.stopAdopted(handle));
+        assertTrue(new VideoStopReceiptRestartTest.Instance(world).stopAdopted(handle));
+        assertTrue(world.requests.isEmpty(), "no outgoing BYE is needed after a real peer termination");
+        SSRCInfo replacement = restarted.legacy("call-new");
+        assertFalse(new VideoStopReceiptRestartTest.Instance(world).stopAdopted(handle));
+        assertEquals(replacement, restarted.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY).getSsrcInfo());
+        assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void adoptedOfflineSettlesOriginalRtpAndDoesNotLockLegacyNameForever() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        instance.legacy("call-old"); String handle = instance.adopt(); assertNotNull(handle);
+        com.ruoyi.wvp.gb28181.bean.SsrcTransaction original = instance.sessions.getSsrcTransactionByCallId("call-old");
+        offlineService(world, instance).offline("device", "test");
+        assertEquals(List.of(LEGACY), world.closeRequests);
+        VideoStopReceiptRestartTest.Instance restarted = new VideoStopReceiptRestartTest.Instance(world);
+        assertFalse(restarted.sessions.isSipTerminated(original));
+        assertFalse(restarted.sessions.isByeConfirmed(original));
+        assertFalse(restarted.stopAdopted(handle), "local offline must remain pending without protocol evidence");
+        assertNull(restarted.sessions.getSsrcTransactionByCallId("call-old"));
+        assertNotNull(restarted.open(LEGACY));
+    }
+
+    private static DeviceServiceImpl offlineService(VideoStopReceiptRestartTest.External world,
+                                                     VideoStopReceiptRestartTest.Instance instance) {
+        MediaServerServiceImpl media = media(world, instance);
+        UserSetting settings = settings();
+        DeviceMapper devices = mock(DeviceMapper.class);
+        when(devices.getDeviceByDeviceId("device")).thenReturn(world.device);
+        RedisCatchStorageImpl cache = new RedisCatchStorageImpl();
+        wire(cache, "redisTemplate", world.redis.client()); wire(cache, "userSetting", settings);
+        DeviceServiceImpl service = new DeviceServiceImpl();
+        wire(service, "deviceMapper", devices); wire(service, "redisCatchStorage", cache);
+        wire(service, "dynamicTask", mock(DynamicTask.class)); wire(service, "userSetting", settings);
+        wire(service, "sessionManager", instance.sessions); wire(service, "inviteStreamService", instance.invites);
+        wire(service, "mediaServerService", media); wire(service, "rtpServerService", instance.rtp);
+        world.device.setSubscribeCycleForCatalog(-1);
+        return service;
+    }
+
+    @Test void managedPeerByeAndDelayedRtpReplyConvergeAfterReconstruction() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        world.delayClose = true;
+        VideoStopReceiptRestartTest.Instance first = new VideoStopReceiptRestartTest.Instance(world); first.managed();
+        String stream = "managed_11111111111111111111111111111111";
+        com.ruoyi.wvp.gb28181.bean.SsrcTransaction original = first.sessions.getSsrcTransactionByStream("rtp", stream);
+        SIPRequest request = LateSipRecoveryTest.peerBye(original);
+        request.setLocalAddress(InetAddress.getByName("127.0.0.1"));
+        peerProcessor(world, first).process(new RequestEvent(this, null, null, request));
+        assertTrue(new VideoStopReceiptRestartTest.Instance(world).sessions.isSipTerminated(original));
+        assertFalse(new VideoStopReceiptRestartTest.Instance(world).stopManaged());
+        world.closeReplies.get(0).run();
+        VideoStopReceiptRestartTest.Instance restarted = new VideoStopReceiptRestartTest.Instance(world);
+        assertTrue(restarted.stopManaged());
+        assertFalse(restarted.sessions.isByeConfirmed(original));
+        assertTrue(world.requests.stream().noneMatch(r -> "BYE".equals(r.getMethod())));
+        assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void failedPeerReplyLeavesProtocolAndRtpPending() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        instance.legacy("call-old"); String handle = instance.adopt(); assertNotNull(handle);
+        com.ruoyi.wvp.gb28181.bean.SsrcTransaction original = instance.sessions.getSsrcTransactionByCallId("call-old");
+        doThrow(new javax.sip.SipException("reply transport failed")).when(world.sender)
+                .transmitRequest(anyString(), any(javax.sip.message.Message.class));
+        peerProcessor(world, instance).process(peerBye("call-old"));
+        assertFalse(instance.sessions.isSipTerminated(original));
+        assertFalse(instance.sessions.isByeConfirmed(original));
+        assertNotNull(instance.sessions.getSsrcTransactionByCallId("call-old"));
+        assertNotNull(instance.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY));
+        assertTrue(world.closeRequests.isEmpty());
+        assertFalse(new VideoStopReceiptRestartTest.Instance(world).stopAdopted(handle));
+    }
+
+    @Test void peerByeCannotTerminateReusedCallWithNewTags() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        instance.legacy("call-old");
+        com.ruoyi.wvp.gb28181.bean.SsrcTransaction replacement = instance.sessions.getSsrcTransactionByCallId("call-old");
+        replacement.getSipTransactionInfo().setToTag("to-new"); instance.sessions.put(replacement);
+        peerProcessor(world, instance).process(peerBye("call-old"));
+        assertFalse(new VideoStopReceiptRestartTest.Instance(world).sessions.isSipTerminated(replacement));
+        assertTrue(world.closeRequests.isEmpty());
+        assertEquals("to-new", instance.sessions.getSsrcTransactionByCallId("call-old").getSipTransactionInfo().getToTag());
+        assertNotNull(instance.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY));
+    }
+
+    @Test void snapshotCasAtBothCleanupBoundariesPreservesConcurrentReplacementForPeerAndOffline() throws Exception {
+        for (boolean offline : List.of(false, true)) {
+            for (String key : List.of(VideoManagerConstants.INVITE_PREFIX,
+                    VideoManagerConstants.SIP_INVITE_SESSION_CALL_ID + "restart-test")) {
+                VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+                VideoStopReceiptRestartTest.Instance first = new VideoStopReceiptRestartTest.Instance(world);
+                first.legacy("call-old");
+                com.ruoyi.wvp.gb28181.bean.SsrcTransaction original = first.sessions.getSsrcTransactionByCallId("call-old");
+                VideoStopReceiptRestartTest.Instance other = new VideoStopReceiptRestartTest.Instance(world);
+                java.util.concurrent.atomic.AtomicReference<SSRCInfo> replacement = new java.util.concurrent.atomic.AtomicReference<>();
+                RedisTemplate<Object, Object> racing = beforeHashDelete(world, key, () -> {
+                    replacement.set(other.legacy("call-old"));
+                    com.ruoyi.wvp.gb28181.bean.SsrcTransaction next = other.sessions.getSsrcTransactionByCallId("call-old");
+                    next.getSipTransactionInfo().setToTag("to-new"); other.sessions.put(next);
+                });
+                wire(first.sessions, "redisTemplate", racing); wire(first.invites, "redisTemplate", racing);
+                if (offline) offlineService(world, first).offline("device", "test race");
+                else peerProcessor(world, first).process(peerBye("call-old"));
+                assertNotNull(replacement.get(), "trace must reach Redis compare-delete: " + key);
+                assertEquals(replacement.get(), other.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY).getSsrcInfo());
+                assertEquals("to-new", other.sessions.getSsrcTransactionByCallId("call-old").getSipTransactionInfo().getToTag());
+                assertEquals("to-new", other.sessions.getSsrcTransactionByStream("rtp", LEGACY).getSipTransactionInfo().getToTag());
+                assertFalse(other.sessions.isSipTerminated(other.sessions.getSsrcTransactionByCallId("call-old")));
+                assertEquals(!offline, other.sessions.isSipTerminated(original));
+                assertEquals(List.of(LEGACY), world.closeRequests); assertTrue(world.open.contains(LEGACY));
+            }
+        }
+    }
+
+    @Test void inviteCompareDeleteRetriesStatusOnlyButRejectsChangedAllocationIdentity() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance first = new VideoStopReceiptRestartTest.Instance(world); first.legacy("call-old");
+        InviteInfo original = first.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY);
+        VideoStopReceiptRestartTest.Instance other = new VideoStopReceiptRestartTest.Instance(world);
+        wire(first.invites, "redisTemplate", beforeHashDelete(world, VideoManagerConstants.INVITE_PREFIX, () -> {
+            InviteInfo current = other.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY);
+            current.setStatus(InviteSessionStatus.ok); other.invites.updateInviteInfo(current);
+        }));
+        assertTrue(first.invites.removeInviteInfoIfSame(original));
+        assertNull(other.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY));
+        for (String dimension : List.of("node", "type", "channel", "stream", "ssrc", "token")) {
+            InviteInfo replacement = com.alibaba.fastjson2.JSON.parseObject(com.alibaba.fastjson2.JSON.toJSONString(original), InviteInfo.class);
+            switch (dimension) {
+                case "node": replacement.setMediaServerId("node-b"); break;
+                case "type": replacement.setType(InviteSessionType.PLAYBACK); break;
+                case "channel": replacement.setChannelId(8); break;
+                case "stream": replacement.setStream("other-stream"); break;
+                case "ssrc": replacement.getSsrcInfo().setSsrc("9999999999"); break;
+                case "token": replacement.getSsrcInfo().setTimeOutTaskKey("new-token"); break;
+                default: fail(dimension);
+            }
+            // Simulate an external writer replacing the exact hash field, not a Java object alias.
+            world.redis.client().opsForHash().put(VideoManagerConstants.INVITE_PREFIX, "PLAY:7:" + LEGACY, replacement);
+            assertFalse(first.invites.removeInviteInfoIfSame(original), dimension);
+            assertNotNull(world.redis.client().opsForHash().get(VideoManagerConstants.INVITE_PREFIX, "PLAY:7:" + LEGACY));
+        }
+    }
+
+    @Test void inviteCompareDeleteStopsAfterBoundedRedisConflictsWithoutDroppingEvidence() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world); instance.legacy("call-old");
+        InviteInfo original = instance.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY);
+        RedisTemplate<Object, Object> conflicting = world.redis.client();
+        java.util.concurrent.atomic.AtomicInteger attempts = new java.util.concurrent.atomic.AtomicInteger();
+        doAnswer(i -> {
+            attempts.incrementAndGet(); return 0L;
+        }).when(conflicting).execute(any(org.springframework.data.redis.core.RedisCallback.class));
+        wire(instance.invites, "redisTemplate", conflicting);
+        assertFalse(instance.invites.removeInviteInfoIfSame(original));
+        assertEquals(3, attempts.get());
+        assertEquals(original.getSsrcInfo(), instance.invites.getInviteInfo(InviteSessionType.PLAY, 7, LEGACY).getSsrcInfo());
+    }
+
+    /** Interleave a second client immediately before the real all-or-nothing Redis CAS substitute. */
+    @SuppressWarnings("unchecked")
+    private static RedisTemplate<Object, Object> beforeHashDelete(VideoStopReceiptRestartTest.External world,
+                                                                   String key, Runnable race) {
+        RedisTemplate<Object, Object> redis = world.redis.client(), delegate = world.redis.client();
+        java.util.concurrent.atomic.AtomicBoolean fired = new java.util.concurrent.atomic.AtomicBoolean();
+        org.springframework.data.redis.connection.RedisConnection connection = mock(org.springframework.data.redis.connection.RedisConnection.class);
+        doAnswer(i -> ((org.springframework.data.redis.core.RedisCallback<?>) i.getArgument(0)).doInRedis(connection))
+                .when(redis).execute(any(org.springframework.data.redis.core.RedisCallback.class));
+        when(connection.eval(any(byte[].class), eq(org.springframework.data.redis.connection.ReturnType.INTEGER), anyInt(),
+                org.mockito.ArgumentMatchers.<byte[][]>any())).thenAnswer(i -> {
+            byte[] script = i.getArgument(0); int n = i.getArgument(2); Object[] invocation = i.getArguments();
+            byte[][] args = invocation.length == 4 && invocation[3] instanceof byte[][] ? (byte[][]) invocation[3]
+                    : java.util.Arrays.copyOfRange(invocation, 3, invocation.length, byte[][].class);
+            for (int k = 0; k < n; k++) {
+                if (key.equals(new String(args[k], java.nio.charset.StandardCharsets.UTF_8))
+                        && "0".equals(new String(args[n + k * 5 + 3], java.nio.charset.StandardCharsets.UTF_8))
+                        && fired.compareAndSet(false, true)) race.run();
+            }
+            return delegate.execute((org.springframework.data.redis.core.RedisCallback<Long>) c ->
+                    c.eval(script, org.springframework.data.redis.connection.ReturnType.INTEGER, n, args));
+        });
+        return redis;
+    }
+
+    private static UserSetting settings() {
+        UserSetting settings = new UserSetting(); settings.setServerId("restart-test"); return settings;
+    }
+
+    private static MediaServerServiceImpl media(VideoStopReceiptRestartTest.External world,
+                                                 VideoStopReceiptRestartTest.Instance instance) {
+        RedisTemplate<Object, Object> redis = world.redis.client();
+        redis.opsForHash().put(VideoManagerConstants.MEDIA_SERVER_PREFIX + "restart-test", "node-a", world.node);
+        ZLMServerFactory zlm = new ZLMServerFactory(); wire(zlm, "zlmresTfulUtils", world.zlm);
+        ZLMMediaNodeServerService node = new ZLMMediaNodeServerService(); wire(node, "zlmServerFactory", zlm);
+        SSRCFactory ssrc = new SSRCFactory(); wire(ssrc, "redisTemplate", world.redis.strings()); wire(ssrc, "userSetting", settings());
+        MediaServerServiceImpl media = new MediaServerServiceImpl();
+        wire(media, "nodeServerServiceMap", Map.of("zlm", node)); wire(media, "redisTemplate", redis);
+        wire(media, "userSetting", settings()); wire(media, "ssrcFactory", ssrc);
+        wire(instance.rtp, "mediaServerService", media); wire(instance.play, "mediaServerService", media);
+        return media;
+    }
+
+    private static ByeRequestProcessor peerProcessor(VideoStopReceiptRestartTest.External world,
+                                                       VideoStopReceiptRestartTest.Instance instance) {
+        ByeRequestProcessor bye = new ByeRequestProcessor();
+        DeviceChannelServiceImpl channels = new DeviceChannelServiceImpl(); wire(channels, "channelMapper", mock(DeviceChannelMapper.class));
+        wire(bye, "sipSender", world.sender); wire(bye, "sessionManager", instance.sessions);
+        wire(bye, "inviteStreamService", instance.invites); wire(bye, "deviceChannelService", channels);
+        wire(bye, "mediaServerService", media(world, instance)); wire(bye, "rtpServerService", instance.rtp);
+        return bye;
+    }
+
+    private static RequestEvent peerBye(String callId) throws Exception {
+        SIPRequest request = (SIPRequest) SipFactory.getInstance().createMessageFactory().createRequest(
+                "BYE sip:device@127.0.0.1:5060 SIP/2.0\r\n"
+                + "Via: SIP/2.0/UDP 127.0.0.2:5060;branch=z9hG4bK-peer-bye\r\n"
+                + "From: <sip:device@127.0.0.2>;tag=to-old\r\n"
+                + "To: <sip:server@127.0.0.1>;tag=from-old\r\n"
+                + "Call-ID: " + callId + "\r\nCSeq: 2 BYE\r\nMax-Forwards: 70\r\nContent-Length: 0\r\n\r\n");
+        request.setLocalAddress(InetAddress.getByName("127.0.0.1"));
+        return new RequestEvent(new Object(), null, null, request);
+    }
+
+    @Test void legacyStopWithoutReceiptClosesTheOriginalNodeAndAllocation() throws Exception {
+        VideoStopReceiptRestartTest.External world = new VideoStopReceiptRestartTest.External();
+        VideoStopReceiptRestartTest.Instance instance = new VideoStopReceiptRestartTest.Instance(world);
+        // A pre-upgrade Invite has its original typed allocation, but no stop-receipt record.
+        SSRCInfo original = new SSRCInfo(30000, "123450001", "rtp", LEGACY, "pre-upgrade-token");
+        InviteInfo invite = InviteInfo.getInviteInfo("device", 7, LEGACY, original, "node-a", "127.0.0.1", 30000,
+                "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
+        StreamInfo stream = new StreamInfo(); stream.setMediaServer(world.node); invite.setStreamInfo(stream);
+        instance.invites.updateInviteInfo(invite);
+        world.open.add(LEGACY);
+
+        instance.play.stop(InviteSessionType.PLAY, world.device, world.channel, LEGACY);
+
+        assertEquals(List.of(LEGACY), world.closeRequests);
+        assertFalse(world.open.contains(LEGACY));
+        verify(world.zlm).closeRtpServer(argThat(node -> "node-a".equals(node.getId())),
+                argThat(params -> LEGACY.equals(params.get("stream_id"))), any());
+    }
+}

+ 258 - 132
video-service/src/test/java/com/zksy/video/lifecycle/ManagedGbDeepSeamTest.java

@@ -1,69 +1,84 @@
 package com.zksy.video.lifecycle;
 package com.zksy.video.lifecycle;
 
 
+import com.alibaba.fastjson2.JSONObject;
 import com.ruoyi.wvp.common.*;
 import com.ruoyi.wvp.common.*;
 import com.ruoyi.wvp.common.InviteInfo;
 import com.ruoyi.wvp.common.InviteInfo;
-import com.ruoyi.wvp.conf.DynamicTask;
-import com.ruoyi.wvp.conf.UserSetting;
+import com.ruoyi.wvp.conf.*;
+import com.ruoyi.wvp.gb28181.SipLayer;
 import com.ruoyi.wvp.gb28181.bean.*;
 import com.ruoyi.wvp.gb28181.bean.*;
 import com.ruoyi.wvp.gb28181.event.SipSubscribe;
 import com.ruoyi.wvp.gb28181.event.SipSubscribe;
-import com.ruoyi.wvp.gb28181.service.IDeviceChannelService;
-import com.ruoyi.wvp.gb28181.service.impl.InviteStreamServiceImpl;
-import com.ruoyi.wvp.gb28181.service.impl.PlayServiceImpl;
+import com.ruoyi.wvp.gb28181.service.impl.*;
 import com.ruoyi.wvp.gb28181.session.SSRCFactory;
 import com.ruoyi.wvp.gb28181.session.SSRCFactory;
 import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
 import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
-import com.ruoyi.wvp.gb28181.transmit.cmd.ISIPCommander;
+import com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver;
+import com.ruoyi.wvp.gb28181.transmit.SIPSender;
+import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
+import com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander;
+import com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor;
+import com.ruoyi.wvp.mapper.*;
 import com.ruoyi.wvp.media.bean.MediaInfo;
 import com.ruoyi.wvp.media.bean.MediaInfo;
 import com.ruoyi.wvp.media.bean.MediaServer;
 import com.ruoyi.wvp.media.bean.MediaServer;
 import com.ruoyi.wvp.media.event.hook.HookSubscribe;
 import com.ruoyi.wvp.media.event.hook.HookSubscribe;
 import com.ruoyi.wvp.media.event.media.MediaArrivalEvent;
 import com.ruoyi.wvp.media.event.media.MediaArrivalEvent;
-import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.media.service.impl.MediaServerServiceImpl;
+import com.ruoyi.wvp.media.zlm.*;
 import com.ruoyi.wvp.service.bean.*;
 import com.ruoyi.wvp.service.bean.*;
 import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
 import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
-import com.ruoyi.wvp.storager.IRedisCatchStorage;
+import com.ruoyi.wvp.storager.impl.RedisCatchStorageImpl;
+import gov.nist.javax.sip.ResponseEventExt;
+import gov.nist.javax.sip.message.SIPResponse;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.Test;
 import org.springframework.data.redis.core.*;
 import org.springframework.data.redis.core.*;
 import org.springframework.test.util.ReflectionTestUtils;
 import org.springframework.test.util.ReflectionTestUtils;
+
+import javax.sip.ResponseEvent;
 import javax.sip.SipException;
 import javax.sip.SipException;
+import javax.sip.SipFactory;
+import javax.sip.header.CallIdHeader;
+import javax.sip.message.Request;
 import java.util.*;
 import java.util.*;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicInteger;
 import static org.junit.jupiter.api.Assertions.*;
 import static org.junit.jupiter.api.Assertions.*;
 import static org.mockito.ArgumentMatchers.*;
 import static org.mockito.ArgumentMatchers.*;
 import static org.mockito.Mockito.*;
 import static org.mockito.Mockito.*;
 
 
-/** Real Play + RTP + Hook + Invite + SIP session registry; substitutes only I/O and the clock. */
+/** Real Play/RTP/Hook/Invite/Session/Commander/header/media modules; only external I/O and timers are substituted. */
 class ManagedGbDeepSeamTest {
 class ManagedGbDeepSeamTest {
     private static final String OLD = "managed_11111111111111111111111111111111";
     private static final String OLD = "managed_11111111111111111111111111111111";
     private static final String NEXT = "managed_22222222222222222222222222222222";
     private static final String NEXT = "managed_22222222222222222222222222222222";
 
 
     @Test void readyWithoutDialogClosesLocalResourcesButRemainsPending() throws Exception {
     @Test void readyWithoutDialogClosesLocalResourcesButRemainsPending() throws Exception {
         Fixture f = new Fixture();
         Fixture f = new Fixture();
-        SSRCInfo info = f.start(OLD);
-        assertNotNull(info);
+        assertNotNull(f.start(OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
         assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
-        assertTrue(f.hooks.getAll().isEmpty());
-        assertFalse(f.open.contains(OLD));
-        assertTrue(f.cancelled.contains(OLD));
+        assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
+        assertTrue(f.store.isStreamCancelled(OLD));
         assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
         assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertTrue(f.byes.isEmpty()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
     }
     }
 
 
     @Test void byeFailureFinallyClosesOnlyOldRtpAndRetainsDialogForRetry() throws Exception {
     @Test void byeFailureFinallyClosesOnlyOldRtpAndRetainsDialogForRetry() throws Exception {
-        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD);
-        doThrow(new SipException("transport down")).when(f.sip).streamByeCmd(any(), anyString(), eq("rtp"), eq(OLD), any(), any());
+        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD); f.failBye = true;
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
-        assertSame(dialog, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertDialogSnapshot(dialog, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertFalse(f.sessions.isByeConfirmed(dialog));
         assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
         assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
         assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
         assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
+        assertEquals(1, f.byeAttempts.get()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
     }
     }
 
 
     @Test void successfulSendWithoutByeResponseIsNotStoppedAndAckAllowsRetryToFinish() throws Exception {
     @Test void successfulSendWithoutByeResponseIsNotStoppedAndAckAllowsRetryToFinish() throws Exception {
-        Fixture f = new Fixture(); f.start(OLD); f.dialog(OLD);
+        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD);
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
-        SipSubscribe.EventResult<?> response = new SipSubscribe.EventResult<>(); response.statusCode = 200;
-        f.byeOk.get(OLD).response(response);
+        Request bye = f.lastBye(dialog.getCallId()); f.assertBye(bye, dialog);
+        assertFalse(f.sessions.isByeConfirmed(dialog));
+        f.byeResponse(bye, 200);
+        assertTrue(f.sessions.isByeConfirmed(dialog));
         assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
         assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
         assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
         assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertNull(f.sessions.getSsrcTransactionByCallId(dialog.getCallId()));
     }
     }
 
 
     @Test void wrongNodeArrivalDoesNotPublishThenCorrectNodeDoes() throws Exception {
     @Test void wrongNodeArrivalDoesNotPublishThenCorrectNodeDoes() throws Exception {
@@ -78,84 +93,84 @@ class ManagedGbDeepSeamTest {
     @Test void cancelledArrivalAndLateSipCallbacksCannotChangeNewSlot() throws Exception {
     @Test void cancelledArrivalAndLateSipCallbacksCannotChangeNewSlot() throws Exception {
         Fixture f = new Fixture(); f.start(OLD);
         Fixture f = new Fixture(); f.start(OLD);
         SipSubscribe.Event oldOk = f.inviteOk.get(OLD), oldError = f.inviteError.get(OLD);
         SipSubscribe.Event oldOk = f.inviteOk.get(OLD), oldError = f.inviteError.get(OLD);
-        f.play.stopManaged(f.node, f.device, f.channel, OLD);
-        // Simulate externally reconciled old slot. Its pending dialog is still not a new generation's slot.
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        // External reconciliation removes only the old Invite entry, never the cancellation receipt.
         f.invites.removeInviteInfo(InviteSessionType.PLAY, f.channel.getId(), OLD);
         f.invites.removeInviteInfo(InviteSessionType.PLAY, f.channel.getId(), OLD);
-        f.start(NEXT);
+        SSRCInfo next = f.start(NEXT); assertNotNull(next);
         f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
         f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
-        f.dialog(OLD);
-        SipSubscribe.EventResult<?> event = new SipSubscribe.EventResult<>(); event.statusCode = 200;
-        oldOk.response(event);
-        event.statusCode = 500; oldError.response(event);
-        assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, NEXT));
-        assertTrue(f.open.contains(NEXT));
-        assertEquals(1, f.hooks.getAll().size());
-        assertEquals(NEXT, f.hooks.getAll().get(0).getStream());
-        assertEquals(0, f.successes.get());
+        SsrcTransaction old = f.dialog(OLD); // actual late INVITE 200 -> ACK -> original-tags BYE
+        oldOk.response(new SipSubscribe.EventResult<>(f.inviteEvent(OLD, 200)));
+        oldError.response(new SipSubscribe.EventResult<>(f.inviteEvent(OLD, 500)));
+        InviteInfo current = f.invites.getInviteInfoByStream(InviteSessionType.PLAY, NEXT);
+        assertNotNull(current); assertAllocation(next, current.getSsrcInfo());
+        assertEquals("device", current.getDeviceId()); assertEquals("node-a", current.getMediaServerId());
+        assertTrue(f.open.contains(NEXT)); assertEquals(1, f.hooks.getAll().size());
+        assertEquals(NEXT, f.hooks.getAll().get(0).getStream()); assertEquals(0, f.successes.get());
+        f.assertBye(f.lastBye(old.getCallId()), old);
+        assertEquals(Collections.singletonList(OLD), f.closeRequests);
     }
     }
 
 
     @Test void cancellationInsideRtpCreationPreventsInviteAndCleansAllocatedPort() throws Exception {
     @Test void cancellationInsideRtpCreationPreventsInviteAndCleansAllocatedPort() throws Exception {
         Fixture f = new Fixture(); f.cancelDuringOpen = true;
         Fixture f = new Fixture(); f.cancelDuringOpen = true;
         assertNull(f.start(OLD));
         assertNull(f.start(OLD));
         assertFalse(f.open.contains(OLD)); assertTrue(f.inviteOk.isEmpty()); assertTrue(f.hooks.getAll().isEmpty());
         assertFalse(f.open.contains(OLD)); assertTrue(f.inviteOk.isEmpty()); assertTrue(f.hooks.getAll().isEmpty());
+        assertEquals(Collections.singletonList(OLD), f.closeRequests);
     }
     }
 
 
     @Test void cancelledBeforeStartAndSinglePortNeverCreateResources() throws Exception {
     @Test void cancelledBeforeStartAndSinglePortNeverCreateResources() throws Exception {
-        Fixture f = new Fixture(); f.cancelled.add(OLD);
+        Fixture f = new Fixture(); f.store.markStreamCancelled(OLD);
         assertNull(f.start(OLD));
         assertNull(f.start(OLD));
         f.node.setRtpEnable(false); assertNull(f.start(NEXT));
         f.node.setRtpEnable(false); assertNull(f.start(NEXT));
-        assertTrue(f.open.isEmpty()); assertTrue(f.inviteOk.isEmpty());
+        assertTrue(f.open.isEmpty()); assertTrue(f.inviteOk.isEmpty()); assertEquals(0, f.openRequests.get());
     }
     }
 
 
     @Test void differentExistingStreamIsNotAdoptedOrStopped() throws Exception {
     @Test void differentExistingStreamIsNotAdoptedOrStopped() throws Exception {
-        Fixture f = new Fixture(); f.start(OLD);
+        Fixture f = new Fixture(); SSRCInfo old = f.start(OLD);
         assertNull(f.start(NEXT));
         assertNull(f.start(NEXT));
         assertTrue(f.open.contains(OLD)); assertFalse(f.open.contains(NEXT));
         assertTrue(f.open.contains(OLD)); assertFalse(f.open.contains(NEXT));
-        assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
+        assertAllocation(old, f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD).getSsrcInfo());
+        assertTrue(f.byes.isEmpty()); assertTrue(f.closeRequests.isEmpty());
     }
     }
 
 
     @Test void localCloseFailureCannotBecomeStopSuccessEvenWithBye200() throws Exception {
     @Test void localCloseFailureCannotBecomeStopSuccessEvenWithBye200() throws Exception {
-        Fixture f = new Fixture(); f.start(OLD); f.dialog(OLD); f.closeAcknowledged = false;
+        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD); f.closeAcknowledged = false;
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
-        SipSubscribe.EventResult<?> response = new SipSubscribe.EventResult<>(); response.statusCode = 200;
-        f.byeOk.get(OLD).response(response);
+        f.byeResponse(f.lastBye(dialog.getCallId()), 200);
+        assertTrue(f.sessions.isByeConfirmed(dialog));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
-        assertTrue(f.hooks.getAll().isEmpty());
+        assertTrue(f.hooks.getAll().isEmpty()); assertTrue(f.open.contains(OLD));
+        assertEquals(Collections.singletonList(OLD), f.closeRequests);
     }
     }
 
 
     @Test void realCommanderKeepsDialogOnByeTransportFailureAndRemovesOnlyOnAck() throws Exception {
     @Test void realCommanderKeepsDialogOnByeTransportFailureAndRemovesOnlyOnAck() throws Exception {
-        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction tx = f.dialog(OLD);
-        com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = new com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander();
-        com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
-        com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider headers = mock(com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider.class);
-        com.ruoyi.wvp.gb28181.SipLayer layer = mock(com.ruoyi.wvp.gb28181.SipLayer.class);
-        Fixture.wire(commander, "sessionManager", f.sessions); Fixture.wire(commander, "sipSender", sender);
-        Fixture.wire(commander, "headerProvider", headers); Fixture.wire(commander, "sipLayer", layer);
-        Fixture.wire(f.play, "cmder", commander);
-        when(headers.createByteRequest(f.device, "channel", tx.getSipTransactionInfo())).thenReturn(mock(javax.sip.message.Request.class));
-        when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
-        doThrow(new SipException("offline")).when(sender).transmitRequest(any(), any(), any(), any());
+        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction tx = f.dialog(OLD); f.failBye = true;
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
-        assertSame(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertDialogSnapshot(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
         assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
         assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
-        reset(sender);
-        java.util.concurrent.atomic.AtomicReference<SipSubscribe.Event> ack = new java.util.concurrent.atomic.AtomicReference<>();
-        doAnswer(i -> { ack.set(i.getArgument(3)); return null; }).when(sender).transmitRequest(any(), any(), any(), any());
+        f.failBye = false;
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
-        assertSame(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
-        SipSubscribe.EventResult<?> event = new SipSubscribe.EventResult<>(); event.statusCode = 200; event.callId = tx.getCallId();
-        ack.get().response(event);
+        assertDialogSnapshot(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        Request bye = f.lastBye(tx.getCallId()); f.assertBye(bye, tx);
+        // Exercise Commander's actual callback (not only the observer's restart fallback).
+        f.byeCallbacks.get(bye).response(new SipSubscribe.EventResult<>(new ResponseEvent(f, null, null, Fixture.reply(bye, 200))));
+        assertTrue(f.sessions.isByeConfirmed(tx));
         assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
         assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertNull(f.sessions.getSsrcTransactionByCallId(tx.getCallId()));
         assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        assertEquals(2, f.byeAttempts.get()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
     }
     }
 
 
     @Test void lateByeAckCannotDeleteReplacementDialog() throws Exception {
     @Test void lateByeAckCannotDeleteReplacementDialog() throws Exception {
         Fixture f = new Fixture(); f.start(OLD); SsrcTransaction old = f.dialog(OLD);
         Fixture f = new Fixture(); f.start(OLD); SsrcTransaction old = f.dialog(OLD);
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
-        SsrcTransaction replacement = f.dialog(OLD); replacement.setCallId("replacement-dialog"); f.sessions.put(replacement);
-        SipSubscribe.EventResult<?> event = new SipSubscribe.EventResult<>(); event.statusCode = 200; event.callId = old.getCallId();
-        f.byeOk.get(OLD).response(event);
-        assertSame(replacement, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        Request oldBye = f.lastBye(old.getCallId());
+        SsrcTransaction replacement = f.sessions.getSsrcTransactionByStream("rtp", OLD);
+        replacement.setCallId("replacement-dialog"); replacement.getSipTransactionInfo().setCallId("replacement-dialog");
+        replacement.getSipTransactionInfo().setToTag("replacement-to"); f.sessions.put(replacement);
+        f.byeResponse(oldBye, 200);
+        assertTrue(f.sessions.isByeConfirmed(old)); assertFalse(f.sessions.isByeConfirmed(replacement));
+        assertDialogSnapshot(replacement, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertDialogSnapshot(replacement, f.sessions.getSsrcTransactionByCallId("replacement-dialog"));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
     }
     }
 
 
@@ -163,53 +178,61 @@ class ManagedGbDeepSeamTest {
         Fixture f = new Fixture(); f.node.setRtpEnable(false);
         Fixture f = new Fixture(); f.node.setRtpEnable(false);
         RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(f.node); param.setStreamId(OLD);
         RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(f.node); param.setStreamId(OLD);
         assertNull(f.rtp.openRTPServer(param, (code, msg, result) -> assertNotEquals(0, code)));
         assertNull(f.rtp.openRTPServer(param, (code, msg, result) -> assertNotEquals(0, code)));
-        assertTrue(f.open.isEmpty()); assertTrue(f.hooks.getAll().isEmpty());
+        assertTrue(f.open.isEmpty()); assertTrue(f.hooks.getAll().isEmpty()); assertEquals(0, f.openRequests.get());
     }
     }
 
 
     @Test void cancellationDuringMediaReadNeverPublishesReady() throws Exception {
     @Test void cancellationDuringMediaReadNeverPublishesReady() throws Exception {
         Fixture f = new Fixture(); f.start(OLD);
         Fixture f = new Fixture(); f.start(OLD);
-        when(f.media.getStreamInfoByAppAndStream(any(), eq("rtp"), eq(OLD), any(), any())).thenAnswer(i -> {
-            f.cancelled.add(OLD);
-            StreamInfo info = new StreamInfo(); info.setStream(OLD); info.setMediaServer(f.node); return info;
-        });
-        f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
+        MediaArrivalEvent event = f.arrival(OLD, f.node);
+        // An external hook payload schedules cancellation while the real media module reads it.
+        AtomicInteger reads = new AtomicInteger();
+        MediaInfo payload = new MediaInfo() {
+            @Override public String getServerId() { reads.incrementAndGet(); f.store.markStreamCancelled(OLD); return "test"; }
+        };
+        payload.setApp("rtp"); payload.setStream(OLD); event.setMediaInfo(payload);
+        f.hooks.onApplicationEvent(event);
+        assertTrue(reads.get() > 0); assertTrue(f.store.isStreamCancelled(OLD));
         assertEquals(0, f.successes.get()); assertFalse(f.open.contains(OLD)); assertTrue(f.hooks.getAll().isEmpty());
         assertEquals(0, f.successes.get()); assertFalse(f.open.contains(OLD)); assertTrue(f.hooks.getAll().isEmpty());
     }
     }
 
 
     @Test void legacyPlayStillReusesItsReadyStreamWithoutManagedAllocation() throws Exception {
     @Test void legacyPlayStillReusesItsReadyStreamWithoutManagedAllocation() throws Exception {
         Fixture f = new Fixture(); String stream = "device_channel";
         Fixture f = new Fixture(); String stream = "device_channel";
-        SSRCInfo ssrc = new SSRCInfo(30000, "0123450001", "rtp", stream, null);
+        SSRCInfo ssrc = new SSRCInfo(30000, "0123450001", "rtp", stream, "legacy-timeout");
         StreamInfo live = new StreamInfo(); live.setStream(stream); live.setApp("rtp"); live.setMediaServer(f.node);
         StreamInfo live = new StreamInfo(); live.setStream(stream); live.setApp("rtp"); live.setMediaServer(f.node);
         InviteInfo existing = InviteInfo.getInviteInfo("device", 7, stream, ssrc, "node-a", "127.0.0.1", 30000,
         InviteInfo existing = InviteInfo.getInviteInfo("device", 7, stream, ssrc, "node-a", "127.0.0.1", 30000,
                 "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
                 "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
         existing.setStreamInfo(live); f.invites.updateInviteInfo(existing);
         existing.setStreamInfo(live); f.invites.updateInviteInfo(existing);
-        when(f.media.isStreamReady(f.node, "rtp", stream)).thenReturn(true);
+        when(f.zlm.getMediaInfo(any(), eq("rtp"), eq("rtsp"), eq(stream))).thenReturn(JSONObject.parseObject("{\"code\":0}"));
         AtomicInteger callbacks = new AtomicInteger();
         AtomicInteger callbacks = new AtomicInteger();
-        assertSame(ssrc, f.play.play(f.node, "device", "channel", null, (code, msg, info) -> {
-            assertEquals(0, code); assertSame(live, info); callbacks.incrementAndGet();
-        }));
-        assertEquals(1, callbacks.get()); assertTrue(f.open.isEmpty());
+        SSRCInfo actual = f.play.play(f.node, "device", "channel", null, (code, msg, info) -> {
+            assertEquals(0, code); assertNotSame(live, info);
+            assertEquals("rtp", info.getApp()); assertEquals(stream, info.getStream());
+            assertEquals("node-a", info.getMediaServer().getId()); callbacks.incrementAndGet();
+        });
+        assertAllocation(ssrc, actual);
+        assertEquals(1, callbacks.get()); assertTrue(f.open.isEmpty()); assertEquals(0, f.openRequests.get());
     }
     }
 
 
     @Test void sameGenerationCanJoinReadyInviteWithoutOpeningAnotherRtp() throws Exception {
     @Test void sameGenerationCanJoinReadyInviteWithoutOpeningAnotherRtp() throws Exception {
         Fixture f = new Fixture(); SSRCInfo first = f.start(OLD);
         Fixture f = new Fixture(); SSRCInfo first = f.start(OLD);
         f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
         f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
-        assertSame(first, f.start(OLD));
+        assertAllocation(first, f.start(OLD));
         assertEquals(Collections.singleton(OLD), f.open);
         assertEquals(Collections.singleton(OLD), f.open);
-        assertEquals(2, f.successes.get());
+        assertEquals(1, f.openRequests.get()); assertEquals(2, f.successes.get());
     }
     }
 
 
     @Test void missingInviteAndDialogIsUnknownNotProofOfStop() throws Exception {
     @Test void missingInviteAndDialogIsUnknownNotProofOfStop() throws Exception {
         Fixture f = new Fixture();
         Fixture f = new Fixture();
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        assertTrue(f.byes.isEmpty()); assertTrue(f.closeRequests.isEmpty());
     }
     }
 
 
     @Test void wrongNodeStopCannotCancelOrCloseOwnedGeneration() throws Exception {
     @Test void wrongNodeStopCannotCancelOrCloseOwnedGeneration() throws Exception {
         Fixture f = new Fixture(); f.start(OLD);
         Fixture f = new Fixture(); f.start(OLD);
         MediaServer wrong = new MediaServer(); wrong.setId("node-b");
         MediaServer wrong = new MediaServer(); wrong.setId("node-b");
         assertFalse(f.play.stopManaged(wrong, f.device, f.channel, OLD));
         assertFalse(f.play.stopManaged(wrong, f.device, f.channel, OLD));
-        assertFalse(f.cancelled.contains(OLD)); assertTrue(f.open.contains(OLD));
-        assertEquals(1, f.hooks.getAll().size());
+        assertFalse(f.store.isStreamCancelled(OLD)); assertTrue(f.open.contains(OLD));
+        assertEquals(1, f.hooks.getAll().size()); assertTrue(f.closeRequests.isEmpty());
     }
     }
 
 
     @Test void mismatchedArrivalPayloadCannotConsumeOwnedSubscription() throws Exception {
     @Test void mismatchedArrivalPayloadCannotConsumeOwnedSubscription() throws Exception {
@@ -222,81 +245,184 @@ class ManagedGbDeepSeamTest {
         assertEquals(1, f.successes.get());
         assertEquals(1, f.successes.get());
     }
     }
 
 
+    static void assertAllocation(SSRCInfo expected, SSRCInfo actual) {
+        assertNotNull(expected); assertNotNull(actual); assertNotSame(expected, actual);
+        assertEquals(expected, actual); // Includes port, SSRC, app, stream AND allocation timeout token.
+        assertNotNull(actual.getTimeOutTaskKey());
+    }
+
+    static void assertDialogSnapshot(SsrcTransaction expected, SsrcTransaction actual) {
+        assertNotNull(actual); assertNotSame(expected, actual);
+        assertNotSame(expected.getSipTransactionInfo(), actual.getSipTransactionInfo());
+        assertEquals(expected.getDeviceId(), actual.getDeviceId()); assertEquals(expected.getChannelId(), actual.getChannelId());
+        assertEquals(expected.getMediaServerId(), actual.getMediaServerId()); assertEquals(expected.getApp(), actual.getApp());
+        assertEquals(expected.getStream(), actual.getStream()); assertEquals(expected.getSsrc(), actual.getSsrc());
+        assertEquals(expected.getType(), actual.getType()); assertEquals(expected.getCallId(), actual.getCallId());
+        SipTransactionInfo a = expected.getSipTransactionInfo(), b = actual.getSipTransactionInfo();
+        assertEquals(a.getCallId(), b.getCallId()); assertEquals(a.getFromTag(), b.getFromTag());
+        assertEquals(a.getToTag(), b.getToTag()); assertEquals(a.getViaBranch(), b.getViaBranch()); assertEquals(a.isAsSender(), b.isAsSender());
+    }
+
     static class Fixture {
     static class Fixture {
         final PlayServiceImpl play = new PlayServiceImpl();
         final PlayServiceImpl play = new PlayServiceImpl();
         final RtpServerServiceImpl rtp = new RtpServerServiceImpl();
         final RtpServerServiceImpl rtp = new RtpServerServiceImpl();
         final HookSubscribe hooks = new HookSubscribe();
         final HookSubscribe hooks = new HookSubscribe();
         final InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
         final InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
         final SipInviteSessionManager sessions = new SipInviteSessionManager();
         final SipInviteSessionManager sessions = new SipInviteSessionManager();
-        final ISIPCommander sip = mock(ISIPCommander.class);
-        final IMediaServerService media = mock(IMediaServerService.class);
-        final VideoLifecycleStore store = mock(VideoLifecycleStore.class);
+        final SIPCommander commander = new SIPCommander();
+        final SIPProcessorObserver observer = new SIPProcessorObserver();
+        final InviteResponseProcessor inviteProcessor = new InviteResponseProcessor();
+        final MediaServerServiceImpl media = new MediaServerServiceImpl();
+        final DeviceChannelServiceImpl channels = new DeviceChannelServiceImpl();
+        final DeviceServiceImpl devices = new DeviceServiceImpl();
+        final DeviceMapper deviceMapper = mock(DeviceMapper.class);
+        final DeviceChannelMapper channelMapper = mock(DeviceChannelMapper.class);
+        final MediaServerMapper mediaMapper = mock(MediaServerMapper.class);
+        final SIPSender sender = mock(SIPSender.class);
+        final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
+        final VideoStopReceiptRestartTest.RedisMemory externalRedis = new VideoStopReceiptRestartTest.RedisMemory();
+        final RedisTemplate<Object, Object> redis = externalRedis.client();
+        final StringRedisTemplate strings = externalRedis.strings();
+        final RedisVideoLifecycleStore store = new RedisVideoLifecycleStore(strings);
+        final VideoStopReceipts receipts = new VideoStopReceipts(redis);
         final MediaServer node = new MediaServer();
         final MediaServer node = new MediaServer();
         final Device device = new Device();
         final Device device = new Device();
         final DeviceChannel channel = new DeviceChannel();
         final DeviceChannel channel = new DeviceChannel();
-        final Set<String> open = new HashSet<>(), cancelled = new HashSet<>();
-        final Map<String, SipSubscribe.Event> inviteOk = new HashMap<>(), inviteError = new HashMap<>(), byeOk = new HashMap<>();
-        final AtomicInteger successes = new AtomicInteger();
-        boolean cancelDuringOpen, closeAcknowledged = true;
+        final Set<String> open = new HashSet<>();
+        final Map<String, Request> inviteRequests = new HashMap<>();
+        final Map<String, SipSubscribe.Event> inviteOk = new HashMap<>(), inviteError = new HashMap<>();
+        final List<Request> byes = new ArrayList<>(), acks = new ArrayList<>();
+        final Map<Request, SipSubscribe.Event> byeCallbacks = new IdentityHashMap<>();
+        final List<String> closeRequests = new ArrayList<>();
+        final List<Runnable> pendingCloses = new ArrayList<>();
+        final AtomicInteger successes = new AtomicInteger(), openRequests = new AtomicInteger(), byeAttempts = new AtomicInteger();
+        boolean cancelDuringOpen, failBye, delayClose, closeAcknowledged = true;
+        String startingStream;
 
 
-        @SuppressWarnings({"unchecked", "rawtypes"})
         Fixture() throws Exception {
         Fixture() throws Exception {
-            node.setId("node-a"); node.setRtpEnable(true); node.setSdpIp("127.0.0.1");
-            device.setDeviceId("device"); device.setStreamMode("UDP");
+            node.setId("node-a"); node.setType("zlm"); node.setStatus(true); node.setRtpEnable(true);
+            node.setSdpIp("127.0.0.1"); node.setStreamIp("127.0.0.1");
+            device.setId(1); device.setDeviceId("device"); device.setStreamMode("UDP");
+            device.setTransport("UDP"); device.setHostAddress("127.0.0.2:5060");
             channel.setId(7); channel.setDeviceId("channel");
             channel.setId(7); channel.setDeviceId("channel");
             UserSetting settings = new UserSetting(); settings.setServerId("test"); settings.setPlayTimeout(30000);
             UserSetting settings = new UserSetting(); settings.setServerId("test"); settings.setPlayTimeout(30000);
-            RedisTemplate<Object, Object> redis = mock(RedisTemplate.class);
-            HashOperations<Object, Object, Object> hash = mock(HashOperations.class);
-            Map<Object, Map<Object, Object>> data = new HashMap<>();
-            when(redis.opsForHash()).thenReturn(hash);
-            doAnswer(i -> { data.computeIfAbsent(i.getArgument(0), k -> new LinkedHashMap<>()).put(i.getArgument(1), i.getArgument(2)); return null; }).when(hash).put(any(), any(), any());
-            when(hash.get(any(), any())).thenAnswer(i -> data.getOrDefault(i.getArgument(0), Collections.emptyMap()).get(i.getArgument(1)));
-            when(hash.values(any())).thenAnswer(i -> new ArrayList<>(data.getOrDefault(i.getArgument(0), Collections.emptyMap()).values()));
-            when(hash.delete(any(), any())).thenAnswer(i -> data.getOrDefault(i.getArgument(0), Collections.emptyMap()).remove(i.getArgument(1)) == null ? 0L : 1L);
-            when(hash.scan(any(), any(ScanOptions.class))).thenAnswer(i -> {
-                String pattern = ((ScanOptions)i.getArgument(1)).getPattern().replace("*", ".*");
-                Iterator<Map.Entry<Object, Object>> iterator = new ArrayList<>(data.getOrDefault(i.getArgument(0), Collections.emptyMap()).entrySet()).stream()
-                        .filter(e -> e.getKey().toString().matches(pattern)).iterator();
-                Cursor<Map.Entry<Object, Object>> cursor = mock(Cursor.class);
-                when(cursor.hasNext()).thenAnswer(a -> iterator.hasNext()); when(cursor.next()).thenAnswer(a -> iterator.next()); return cursor;
-            });
-            StringRedisTemplate strings = mock(StringRedisTemplate.class);
-            SetOperations<String, String> sets = mock(SetOperations.class);
-            AtomicInteger ssrc = new AtomicInteger(1);
-            when(strings.opsForSet()).thenReturn(sets); when(sets.size(anyString())).thenReturn(100L);
-            when(sets.pop(anyString())).thenAnswer(i -> String.format("12345%04d", ssrc.getAndIncrement()));
-            SSRCFactory factory = new SSRCFactory();
-            wire(factory, "redisTemplate", strings); wire(factory, "userSetting", settings);
+            FakeStringRedis ssrcRedis = new FakeStringRedis();
+            for (int i = 1; i <= 100; i++) ssrcRedis.strings().opsForSet().add(
+                    "CITY_VIDEO_VMP_SSRC_INFO_test_node-a", String.format("20000%04d", i));
+            SSRCFactory factory = new SSRCFactory(); wire(factory, "redisTemplate", ssrcRedis.strings()); wire(factory, "userSetting", settings);
             wire(invites, "redisTemplate", redis); wire(invites, "userSetting", settings);
             wire(invites, "redisTemplate", redis); wire(invites, "userSetting", settings);
             wire(sessions, "redisTemplate", redis); wire(sessions, "userSetting", settings);
             wire(sessions, "redisTemplate", redis); wire(sessions, "userSetting", settings);
-            when(store.isStreamCancelled(anyString())).thenAnswer(i -> cancelled.contains(i.getArgument(0)));
-            doAnswer(i -> { cancelled.add(i.getArgument(0)); return null; }).when(store).markStreamCancelled(anyString());
-            when(media.createRTPServer(any(), anyString(), anyLong(), anyInt(), anyBoolean(), anyBoolean(), anyBoolean(), anyInt())).thenAnswer(i -> {
-                String stream = i.getArgument(1); open.add(stream); if (cancelDuringOpen) cancelled.add(stream); return 30000;
-            });
-            doAnswer(i -> { if (closeAcknowledged) open.remove(i.getArgument(1)); ((CommonCallback<Boolean>)i.getArgument(2)).run(closeAcknowledged); return null; })
-                    .when(media).closeRTPServer(any(), anyString(), any());
-            when(media.getStreamInfoByAppAndStream(any(), eq("rtp"), anyString(), any(), any())).thenAnswer(i -> {
-                StreamInfo info = new StreamInfo(); info.setStream(i.getArgument(2)); info.setApp("rtp"); info.setMediaServer(node); return info;
+            RedisCatchStorageImpl cache = new RedisCatchStorageImpl();
+            wire(cache, "redisTemplate", redis); wire(cache, "userSetting", settings); cache.updateDevice(device);
+            redis.opsForHash().put(VideoManagerConstants.MEDIA_SERVER_PREFIX + settings.getServerId(), node.getId(), node);
+            when(deviceMapper.getDeviceByDeviceId("device")).thenReturn(device);
+            when(channelMapper.getOneByDeviceIdForSource(1, "channel")).thenReturn(channel);
+            when(channelMapper.getOneByDeviceId(1, "channel")).thenReturn(channel);
+            wire(channels, "deviceMapper", deviceMapper); wire(channels, "channelMapper", channelMapper);
+            wire(devices, "deviceMapper", deviceMapper); wire(devices, "redisCatchStorage", cache);
+            ZLMServerFactory zlmFactory = new ZLMServerFactory(); wire(zlmFactory, "zlmresTfulUtils", zlm);
+            ZLMMediaNodeServerService zlmNode = new ZLMMediaNodeServerService();
+            wire(zlmNode, "zlmServerFactory", zlmFactory); wire(zlmNode, "zlmresTfulUtils", zlm); wire(zlmNode, "userSetting", settings);
+            wire(media, "nodeServerServiceMap", Map.of("zlm", zlmNode)); wire(media, "redisTemplate", redis);
+            wire(media, "userSetting", settings); wire(media, "mediaServerMapper", mediaMapper); wire(media, "ssrcFactory", factory);
+            when(zlm.getRtpInfo(any(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":0,\"exist\":false}"));
+            when(zlm.openRtpServer(any(), anyMap())).thenAnswer(i -> {
+                String stream = (String) ((Map<?, ?>) i.getArgument(1)).get("stream_id");
+                openRequests.incrementAndGet(); open.add(stream); if (cancelDuringOpen) store.markStreamCancelled(stream);
+                return JSONObject.parseObject("{\"code\":0,\"port\":30000}");
             });
             });
-            when(media.getOne("node-a")).thenReturn(node);
-            doAnswer(i -> { String stream = ((SSRCInfo)i.getArgument(1)).getStream(); inviteOk.put(stream, i.getArgument(4)); inviteError.put(stream, i.getArgument(5)); return null; })
-                    .when(sip).playStreamCmd(any(), any(), any(), any(), any(), any(), anyLong());
-            doAnswer(i -> { byeOk.put(i.getArgument(3), i.getArgument(5)); return null; }).when(sip).streamByeCmd(any(), anyString(), eq("rtp"), anyString(), any(), any());
-            IRedisCatchStorage cache = mock(IRedisCatchStorage.class); when(cache.getDevice("device")).thenReturn(device);
-            IDeviceChannelService channels = mock(IDeviceChannelService.class); when(channels.getOneForSource("device", "channel")).thenReturn(channel);
+            doAnswer(i -> {
+                String stream = (String) ((Map<?, ?>) i.getArgument(1)).get("stream_id"); closeRequests.add(stream);
+                ZLMRESTfulUtils.RequestCallback callback = i.getArgument(2);
+                Runnable response = () -> {
+                    boolean hit = closeAcknowledged && open.remove(stream);
+                    callback.run(JSONObject.parseObject(hit ? "{\"code\":0,\"hit\":1}" : "{\"code\":0,\"hit\":0}"));
+                };
+                if (delayClose) pendingCloses.add(response); else response.run(); return null;
+            }).when(zlm).closeRtpServer(any(), anyMap(), any());
+            when(zlm.getMediaInfo(any(), anyString(), anyString(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":-1}"));
+            SipConfig config = new SipConfig(); config.setId("34020000002000000001"); config.setDomain("3402000000"); config.setPort(5060);
+            SipLayer layer = mock(SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
+            SIPRequestHeaderProvider headers = new SIPRequestHeaderProvider();
+            wire(headers, "sipConfig", config); wire(headers, "sipLayer", layer); wire(headers, "redisCatchStorage", cache);
+            wire(commander, "headerProvider", headers); wire(commander, "sessionManager", sessions);
+            wire(commander, "sipSender", sender); wire(commander, "sipLayer", layer); wire(commander, "sipConfig", config);
+            wire(commander, "userSetting", settings); wire(commander, "videoLifecycleStore", store); wire(commander, "mediaServerService", media);
+            AtomicInteger calls = new AtomicInteger();
+            when(sender.getNewCallIdHeader(anyString(), anyString())).thenAnswer(i -> SipFactory.getInstance().createHeaderFactory().createCallIdHeader("call-" + calls.incrementAndGet()));
+            doAnswer(i -> {
+                Request request = i.getArgument(1); assertEquals(Request.INVITE, request.getMethod());
+                inviteRequests.put(startingStream, request); inviteError.put(startingStream, i.getArgument(2));
+                inviteOk.put(startingStream, i.getArgument(3)); return null;
+            }).when(sender).transmitRequest(any(), any(), any(), any(), anyLong());
+            doAnswer(i -> { acks.add(i.getArgument(1)); return null; }).when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class));
+            doAnswer(i -> {
+                Request request = i.getArgument(1); assertEquals(Request.BYE, request.getMethod()); byeAttempts.incrementAndGet();
+                assertTrue(sessions.hasByeRequest(reply(request, 200)), "The real outgoing BYE must be persisted before transport");
+                if (failBye) throw new SipException("transport down");
+                byes.add(request); byeCallbacks.put(request, i.getArgument(3)); return null;
+            }).when(sender).transmitRequest(any(), any(), any(), any());
+            wire(observer, "sessionManager", sessions); wire(observer, "sipSubscribe", new SipSubscribe());
+            wire(inviteProcessor, "sipSender", sender); wire(inviteProcessor, "headerProvider", headers);
+            wire(inviteProcessor, "sessionManager", sessions); wire(inviteProcessor, "videoLifecycleStore", store);
+            wire(inviteProcessor, "mediaServerService", media); wire(inviteProcessor, "redisCatchStorage", cache);
+            wire(inviteProcessor, "deviceChannelService", channels); wire(inviteProcessor, "playService", play);
             wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class)); wire(rtp, "ssrcFactory", factory);
             wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class)); wire(rtp, "ssrcFactory", factory);
             wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks); wire(rtp, "videoLifecycleStore", store);
             wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks); wire(rtp, "videoLifecycleStore", store);
-            wire(rtp, "sessionManager", sessions);
-            wire(play, "cmder", sip); wire(play, "redisCatchStorage", cache); wire(play, "deviceChannelService", channels);
+            wire(rtp, "sessionManager", sessions); wire(rtp, "stopReceipts", receipts);
+            wire(play, "cmder", commander); wire(play, "redisCatchStorage", cache); wire(play, "deviceChannelService", channels);
             wire(play, "inviteStreamService", invites); wire(play, "sessionManager", sessions); wire(play, "subscribe", hooks);
             wire(play, "inviteStreamService", invites); wire(play, "sessionManager", sessions); wire(play, "subscribe", hooks);
-            wire(play, "receiveRtpServerService", rtp); wire(play, "mediaServerService", media); wire(play, "videoLifecycleStore", store); wire(play, "userSetting", settings);
+            wire(play, "receiveRtpServerService", rtp); wire(play, "mediaServerService", media);
+            wire(play, "videoLifecycleStore", store); wire(play, "userSetting", settings); wire(play, "stopReceipts", receipts);
+            wire(play, "ssrcFactory", factory);
+        }
+
+        SSRCInfo start(String stream) {
+            startingStream = stream;
+            return play.playManaged(node, "device", "channel", stream, (code, msg, result) -> { if (code == 0) successes.incrementAndGet(); });
+        }
+        SsrcTransaction dialog(String stream) throws Exception {
+            ResponseEventExt event = inviteEvent(stream, 200);
+            int before = acks.size(); inviteProcessor.process(event);
+            assertEquals(before + 1, acks.size()); assertEquals(Request.ACK, acks.get(before).getMethod());
+            inviteOk.get(stream).response(new SipSubscribe.EventResult<>(event));
+            SsrcTransaction tx = sessions.getSsrcTransactionByStream("rtp", stream); assertNotNull(tx);
+            assertEquals(callId(inviteRequests.get(stream)), tx.getCallId());
+            assertEquals("to-managed", tx.getSipTransactionInfo().getToTag());
+            assertDialogSnapshot(tx, sessions.getSsrcTransactionByCallId(tx.getCallId())); return tx;
+        }
+        ResponseEventExt inviteEvent(String stream, int status) throws Exception {
+            Request request = inviteRequests.get(stream); assertNotNull(request);
+            SIPResponse response = reply(request, status);
+            response.setContent(request.getContent(), SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
+            // The network metadata is external; the message and all SIP headers are real parsed objects.
+            ResponseEventExt event = mock(ResponseEventExt.class);
+            when(event.getResponse()).thenReturn(response); when(event.getRemoteIpAddress()).thenReturn("127.0.0.2");
+            when(event.getRemotePort()).thenReturn(5060); return event;
+        }
+        void byeResponse(Request request, int status) throws Exception { byeResponse(request, reply(request, status)); }
+        void byeResponse(Request request, SIPResponse response) {
+            assertEquals(Request.BYE, request.getMethod());
+            ResponseEvent event = new ResponseEvent(this, null, null, response);
+            observer.processResponse(event);
+            // Also exercise the live Commander's callback with the same actual response.
+            if (byeCallbacks.containsKey(request)) byeCallbacks.get(request).response(new SipSubscribe.EventResult<>(event));
+        }
+        Request lastBye(String call) {
+            return byes.stream().filter(r -> call.equals(callId(r))).reduce((a, b) -> b).orElseThrow();
         }
         }
-        SSRCInfo start(String stream) { return play.playManaged(node, "device", "channel", stream, (code, msg, result) -> { if (code == 0) successes.incrementAndGet(); }); }
-        SsrcTransaction dialog(String stream) {
-            SsrcTransaction tx = new SsrcTransaction(); tx.setDeviceId("device"); tx.setChannelId(7); tx.setApp("rtp"); tx.setStream(stream);
-            tx.setCallId("call-" + stream); tx.setMediaServerId("node-a"); tx.setSipTransactionInfo(new SipTransactionInfo()); sessions.put(tx); return tx;
+        void assertBye(Request request, SsrcTransaction expected) throws Exception {
+            SIPResponse response = reply(request, 200);
+            assertEquals(Request.BYE, response.getCSeqHeader().getMethod()); assertTrue(response.getCSeqHeader().getSeqNumber() > 0);
+            assertEquals(expected.getCallId(), response.getCallIdHeader().getCallId());
+            assertEquals(expected.getSipTransactionInfo().getFromTag(), response.getFromTag());
+            assertEquals(expected.getSipTransactionInfo().getToTag(), response.getToTag());
+            assertEquals(expected.getSipTransactionInfo().getViaBranch(), response.getTopmostViaHeader().getBranch());
+            assertEquals("channel", ((javax.sip.address.SipURI) request.getRequestURI()).getUser());
+            assertTrue(sessions.hasByeRequest(response));
         }
         }
+        static String callId(Request request) { return ((CallIdHeader) request.getHeader(CallIdHeader.NAME)).getCallId(); }
+        static SIPResponse reply(Request request, int status) throws Exception { return VideoStopReceiptRestartTest.reply(request, status); }
         MediaArrivalEvent arrival(String stream, MediaServer server) {
         MediaArrivalEvent arrival(String stream, MediaServer server) {
             MediaArrivalEvent event = new MediaArrivalEvent(this); event.setApp("rtp"); event.setStream(stream); event.setMediaServer(server); event.setSchema("rtsp");
             MediaArrivalEvent event = new MediaArrivalEvent(this); event.setApp("rtp"); event.setStream(stream); event.setMediaServer(server); event.setSchema("rtsp");
             MediaInfo info = new MediaInfo(); info.setApp("rtp"); info.setStream(stream); event.setMediaInfo(info); return event;
             MediaInfo info = new MediaInfo(); info.setApp("rtp"); info.setStream(stream); event.setMediaInfo(info); return event;

+ 8 - 4
video-service/src/test/java/com/zksy/video/lifecycle/ManualLifecycleMediaTest.java

@@ -103,12 +103,14 @@ class ManualLifecycleMediaTest {
         verify(servers, never()).getDefaultMediaServer();
         verify(servers, never()).getDefaultMediaServer();
     }
     }
 
 
-    @Test void exactKeyDeletionSucceedsButInFlightStartStillPreventsStopped() {
+    @Test void actualKeyAndConfirmedDeletionCanSettleALostInFlightReply() {
         VideoLifecycleRecord record = proxyRecord();
         VideoLifecycleRecord record = proxyRecord();
         MediaServer node = onlineNode();
         MediaServer node = onlineNode();
         when(zlm.delStreamProxy(node, "actual-zlm-key")).thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":{\"flag\":true}}"));
         when(zlm.delStreamProxy(node, "actual-zlm-key")).thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":{\"flag\":true}}"));
         record.setStartInFlight(true);
         record.setStartInFlight(true);
-        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        Map<String, Object> confirmed = adapter.cancel(record);
+        assertEquals("STOPPED", confirmed.get("status"));
+        assertEquals(true, confirmed.get("allocationClosed"));
         record.setStartInFlight(false);
         record.setStartInFlight(false);
         assertEquals("STOPPED", adapter.cancel(record).get("status"));
         assertEquals("STOPPED", adapter.cancel(record).get("status"));
         verify(zlm, times(2)).delStreamProxy(node, "actual-zlm-key");
         verify(zlm, times(2)).delStreamProxy(node, "actual-zlm-key");
@@ -212,14 +214,16 @@ class ManualLifecycleMediaTest {
         verifyNoInteractions(zlm, servers);
         verifyNoInteractions(zlm, servers);
     }
     }
 
 
-    @Test void nativeMediaHasNoProxyButStillHonorsInFlightFence() {
+    @Test void nativeMediaHasNoAllocationEvenWhenTheReplyWasLost() {
         VideoLifecycleRecord record = proxyRecord(); record.setUrl("https://camera.invalid/live.m3u8");
         VideoLifecycleRecord record = proxyRecord(); record.setUrl("https://camera.invalid/live.m3u8");
         record.setStream(null); record.setProxyKey(null); record.setMediaServerId(null);
         record.setStream(null); record.setProxyKey(null); record.setMediaServerId(null);
         adapter.prepare(record);
         adapter.prepare(record);
         assertEquals("ACTIVE", adapter.start(record).get("status"));
         assertEquals("ACTIVE", adapter.start(record).get("status"));
         assertEquals("STOPPED", adapter.cancel(record).get("status"));
         assertEquals("STOPPED", adapter.cancel(record).get("status"));
         record.setStartInFlight(true);
         record.setStartInFlight(true);
-        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        Map<String, Object> confirmed = adapter.cancel(record);
+        assertEquals("STOPPED", confirmed.get("status"));
+        assertEquals(true, confirmed.get("allocationClosed"));
         verifyNoInteractions(zlm, servers);
         verifyNoInteractions(zlm, servers);
     }
     }
 
 

+ 179 - 0
video-service/src/test/java/com/zksy/video/lifecycle/SsrcAllocationTokenTest.java

@@ -0,0 +1,179 @@
+package com.zksy.video.lifecycle;
+
+import com.ruoyi.wvp.conf.SipConfig;
+import com.ruoyi.wvp.conf.UserSetting;
+import com.ruoyi.wvp.gb28181.session.SSRCFactory;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/** Real Factory behavior over a serialized, shared Redis command boundary; no live Redis. */
+class SsrcAllocationTokenTest {
+    private static final String NODE = "node-a";
+    private static final String SERVER = "ssrc-test";
+    private static final String POOL = "CITY_VIDEO_VMP_SSRC_INFO_ssrc-test_node-a";
+
+    @Test
+    void rebuiltFactoryReturnsTheOwnedSnOnceAndCannotReturnItsNewAllocation() {
+        FakeStringRedis redis = new FakeStringRedis();
+        redis.strings().opsForSet().add(POOL, "200000001");
+        SSRCFactory beforeRestart = factory(redis, SERVER);
+        String ssrc = beforeRestart.getPlaySsrc(NODE, "allocation-old");
+        assertEquals("0200000001", ssrc);
+        assertThrows(RuntimeException.class, () -> beforeRestart.getPlaySsrc(NODE, "pool-empty"));
+
+        // A new Factory and new StringRedisTemplate share only the external serialized state.
+        SSRCFactory afterRestart = factory(redis, SERVER);
+        assertTrue(afterRestart.releaseSsrc(NODE, ssrc, "allocation-old"));
+        assertFalse(afterRestart.releaseSsrc(NODE, ssrc, "allocation-old"));
+        String reused = afterRestart.getPlaySsrc(NODE, "allocation-new");
+        assertEquals(ssrc, reused);
+        assertFalse(beforeRestart.releaseSsrc(NODE, ssrc, "allocation-old"));
+        assertThrows(RuntimeException.class, () -> afterRestart.getPlaySsrc(NODE, "must-stay-empty"));
+        assertTrue(afterRestart.releaseSsrc(NODE, reused, "allocation-new"));
+    }
+
+    @Test
+    void legacyReleaseCannotReturnAnSnCurrentlyOwnedByATrackedAllocation() {
+        FakeStringRedis redis = new FakeStringRedis();
+        redis.strings().opsForSet().add(POOL, "200000001");
+        SSRCFactory factory = factory(redis, SERVER);
+        String legacy = factory.getPlaySsrc(NODE);
+        assertEquals("0200000001", legacy);
+        factory.releaseSsrc(NODE, legacy);
+
+        String tracked = factory.getPlaySsrc(NODE, "tracked-owner");
+        assertEquals(legacy, tracked);
+        factory.releaseSsrc(NODE, legacy); // A late, unowned callback must not release tracked work.
+        assertThrows(RuntimeException.class, () -> factory.getPlaySsrc(NODE));
+        assertTrue(factory.releaseSsrc(NODE, tracked, "tracked-owner"));
+
+        String legacyAgain = factory.getPlaySsrc(NODE);
+        assertEquals(legacy, legacyAgain);
+        assertFalse(factory.releaseSsrc(NODE, tracked, "tracked-owner"));
+        assertThrows(RuntimeException.class, () -> factory.getPlaySsrc(NODE, "must-stay-empty"));
+        factory.releaseSsrc(NODE, legacyAgain);
+        assertEquals(legacy, factory.getPlaySsrc(NODE, "next-owner"));
+    }
+
+    @Test
+    void playAndPlaybackKeepTheExistingDomainAndSequenceFormatForBothApis() {
+        FakeStringRedis redis = new FakeStringRedis();
+        SSRCFactory factory = factory(redis, SERVER);
+        factory.initMediaServerSSRC(NODE, null);
+        // The external fake picks the first available member for deterministic SPOP responses.
+        assertEquals("0200000001", factory.getPlaySsrc(NODE, "play"));
+        String playback = factory.getPlayBackSsrc(NODE, "back");
+        assertEquals("1200000002", playback);
+        assertEquals("0200000003", factory.getPlaySsrc(NODE));
+        assertEquals("1200000004", factory.getPlayBackSsrc(NODE));
+        assertTrue(factory(redis, SERVER).releaseSsrc(NODE, playback, "back"));
+    }
+
+    @Test
+    void wrongTokenOrDifferentServerOrNodeCannotReturnTheOwnersSn() {
+        FakeStringRedis redis = new FakeStringRedis();
+        redis.strings().opsForSet().add(POOL, "200000001");
+        SSRCFactory owner = factory(redis, SERVER);
+        String ssrc = owner.getPlaySsrc(NODE, "owner-token");
+        assertFalse(owner.releaseSsrc(NODE, ssrc, "wrong-token"));
+        assertFalse(owner.releaseSsrc("node-b", ssrc, "owner-token"));
+        assertFalse(factory(redis, "other-server").releaseSsrc(NODE, ssrc, "owner-token"));
+        assertThrows(RuntimeException.class, () -> owner.getPlaySsrc(NODE, "must-stay-empty"));
+        assertThrows(RuntimeException.class, () -> owner.getPlaySsrc("node-b", "no-foreign-return"));
+        assertThrows(RuntimeException.class, () -> factory(redis, "other-server").getPlaySsrc(NODE, "no-foreign-return"));
+        assertTrue(factory(redis, SERVER).releaseSsrc(NODE, ssrc, "owner-token"));
+        assertEquals(ssrc, owner.getPlaySsrc(NODE, "next-owner"));
+    }
+
+    @Test
+    void legacyPopClearsStaleOwnershipWhenAnSnIsAlreadyInTheAvailablePool() {
+        FakeStringRedis redis = new FakeStringRedis();
+        // External pre-existing state, e.g. after an explicit legacy pool rebuild.
+        redis.strings().opsForSet().add(POOL, "200000001");
+        redis.strings().opsForHash().put("{" + POOL + "}_OWNERS", "200000001", "stale-owner");
+        SSRCFactory factory = factory(redis, SERVER);
+        String legacy = factory.getPlayBackSsrc(NODE);
+        assertEquals("1200000001", legacy);
+        assertFalse(factory.releaseSsrc(NODE, legacy, "stale-owner"));
+        assertThrows(RuntimeException.class, () -> factory.getPlaySsrc(NODE, "must-stay-empty"));
+        factory.releaseSsrc(NODE, legacy);
+        assertEquals("0200000001", factory.getPlaySsrc(NODE, "new-owner"));
+    }
+
+    @Test
+    void emptyTokensFailBeforeChangingThePoolAndTrackedReleaseDoesNotOwnLegacyAllocations() {
+        FakeStringRedis redis = new FakeStringRedis();
+        redis.strings().opsForSet().add(POOL, "200000001");
+        SSRCFactory factory = factory(redis, SERVER);
+        assertThrows(IllegalArgumentException.class, () -> factory.getPlaySsrc(NODE, null));
+        assertThrows(IllegalArgumentException.class, () -> factory.getPlayBackSsrc(NODE, " "));
+        String legacy = factory.getPlaySsrc(NODE);
+        assertFalse(factory.releaseSsrc(NODE, legacy, "not-an-owner"));
+        assertThrows(IllegalArgumentException.class, () -> factory.releaseSsrc(NODE, legacy, ""));
+        assertFalse(factory.releaseSsrc(NODE, null, "not-an-owner"));
+        assertFalse(factory.releaseSsrc(NODE, "", "not-an-owner"));
+        assertThrows(RuntimeException.class, () -> factory.getPlayBackSsrc(NODE, "must-stay-empty"));
+        factory.releaseSsrc(NODE, legacy);
+        assertEquals("1200000001", factory.getPlayBackSsrc(NODE, "tracked"));
+    }
+
+    @Test void allocationRetryAndReturnReceiptSurviveLostRepliesWithoutReinsertingAReusedSn() {
+        FakeStringRedis redis = new FakeStringRedis();
+        redis.strings().opsForSet().add(POOL, "200000001");
+        SSRCFactory first = factory(redis, SERVER);
+        String original = first.getPlaySsrc(NODE, "stable-token");
+        SSRCFactory rebuilt = factory(redis, SERVER);
+        assertEquals(original, rebuilt.getPlaySsrc(NODE, "stable-token"));
+        assertTrue(rebuilt.hasMediaServerSSRC(NODE), "an exhausted but owned pool is not an uninitialized pool");
+        assertFalse(rebuilt.wasReleased(NODE, original, "stable-token"));
+        assertTrue(rebuilt.releaseSsrc(NODE, original, "stable-token"));
+        String next = rebuilt.getPlaySsrc(NODE, "next-token");
+        assertEquals(original, next);
+        assertTrue(first.wasReleased(NODE, original, "stable-token"));
+        assertFalse(first.releaseSsrc(NODE, original, "stable-token"));
+        assertThrows(RuntimeException.class, () -> first.getPlaySsrc(NODE, "stable-token"));
+        assertThrows(RuntimeException.class, () -> first.getPlaySsrc(NODE, "third-token"));
+    }
+
+    @Test void observedPreUpgradeReturnIsOnceOnlyAndCannotReturnANewerLegacyOwner() {
+        FakeStringRedis redis = new FakeStringRedis();
+        SSRCFactory factory = factory(redis, SERVER);
+        String original = "0200000001";
+        assertTrue(factory.releaseObservedLegacySsrc(NODE, original, "old-observation"));
+        assertTrue(factory.wasReleased(NODE, original, "old-observation"));
+        assertEquals(original, factory.getPlaySsrc(NODE));
+        assertFalse(factory.releaseObservedLegacySsrc(NODE, original, "old-observation"));
+        assertFalse(factory.releaseObservedLegacySsrc(NODE, original, "different-observation"));
+        assertThrows(RuntimeException.class, () -> factory.getPlaySsrc(NODE, "still-busy"));
+    }
+
+    @Test void cancellationFencesAnAcquisitionBeforeOrAfterItsReplyWasLost() {
+        FakeStringRedis redis = new FakeStringRedis();
+        redis.strings().opsForSet().add(POOL, "200000001");
+        SSRCFactory first = factory(redis, SERVER);
+        assertTrue(first.cancelAllocation(NODE, "cancelled-before-pop"));
+        assertThrows(RuntimeException.class, () -> first.getPlaySsrc(NODE, "cancelled-before-pop"));
+        String acquired = first.getPlaySsrc(NODE, "reply-lost");
+        SSRCFactory rebuilt = factory(redis, SERVER);
+        assertTrue(rebuilt.cancelAllocation(NODE, "reply-lost"));
+        assertTrue(rebuilt.wasReleased(NODE, acquired, "reply-lost"));
+        assertEquals(acquired, rebuilt.getPlaySsrc(NODE, "new-owner"));
+        assertTrue(first.cancelAllocation(NODE, "reply-lost"));
+        assertThrows(RuntimeException.class, () -> first.getPlaySsrc(NODE, "must-still-be-busy"));
+    }
+
+    private static SSRCFactory factory(FakeStringRedis redis, String serverId) {
+        UserSetting settings = new UserSetting();
+        settings.setServerId(serverId);
+        SipConfig sip = new SipConfig();
+        sip.setDomain("3402000000");
+        SSRCFactory factory = new SSRCFactory();
+        // Dependency injection only: never read or assert private business state.
+        ReflectionTestUtils.setField(factory, "redisTemplate", redis.strings());
+        ReflectionTestUtils.setField(factory, "userSetting", settings);
+        ReflectionTestUtils.setField(factory, "sipConfig", sip);
+        return factory;
+    }
+}

+ 18 - 0
video-service/src/test/java/com/zksy/video/lifecycle/VideoLifecycleRaceTest.java

@@ -115,6 +115,24 @@ class VideoLifecycleRaceTest {
         verify(media).cancel(any());
         verify(media).cancel(any());
     }
     }
 
 
+    @Test void rebuiltCoordinatorAcceptsExactQuiescenceButNotMerelyAnEmptyMediaResponse() {
+        Snapshots shared = new Snapshots();
+        VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
+        when(media.supports("GB28181")).thenReturn(true);
+        when(media.start(any())).thenThrow(new ProcessLost());
+        Map<String,Object> request = request();
+        VideoLifecycleService first = new VideoLifecycleService(shared, List.of(media));
+        assertThrows(ProcessLost.class, () -> first.start(request));
+        VideoLifecycleService rebuilt = new VideoLifecycleService(shared, List.of(media));
+        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED"));
+        assertEquals("CLEANUP_PENDING", rebuilt.cancel(request).get("status"), "plain STOPPED cannot release an unresolved dispatch");
+        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED", "allocationClosed", true));
+        assertEquals("STOPPED", rebuilt.cancel(request).get("status"), "exact durable media termination can settle a lost dispatch");
+        assertEquals("STOPPED", rebuilt.start(request).get("status"));
+        verify(media, times(1)).start(any());
+    }
+    private static final class ProcessLost extends Error { }
+
     @Test void cancellingDuringStartCannotBeOverwrittenByALateActiveSnapshot() {
     @Test void cancellingDuringStartCannotBeOverwrittenByALateActiveSnapshot() {
         VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
         VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
         when(media.supports("GB28181")).thenReturn(true);
         when(media.supports("GB28181")).thenReturn(true);

+ 444 - 0
video-service/src/test/java/com/zksy/video/lifecycle/VideoStopReceiptRestartTest.java

@@ -0,0 +1,444 @@
+package com.zksy.video.lifecycle;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.ruoyi.wvp.common.*;
+import com.ruoyi.wvp.common.InviteInfo;
+import com.ruoyi.wvp.conf.*;
+import com.ruoyi.wvp.gb28181.SipLayer;
+import com.ruoyi.wvp.gb28181.bean.*;
+import com.ruoyi.wvp.gb28181.event.SipSubscribe;
+import com.ruoyi.wvp.gb28181.service.impl.*;
+import com.ruoyi.wvp.gb28181.session.*;
+import com.ruoyi.wvp.gb28181.transmit.*;
+import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
+import com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander;
+import com.ruoyi.wvp.mapper.*;
+import com.ruoyi.wvp.media.bean.MediaServer;
+import com.ruoyi.wvp.media.event.hook.HookSubscribe;
+import com.ruoyi.wvp.media.service.impl.MediaServerServiceImpl;
+import com.ruoyi.wvp.media.zlm.*;
+import com.ruoyi.wvp.service.bean.*;
+import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
+import com.ruoyi.wvp.storager.impl.RedisCatchStorageImpl;
+import com.ruoyi.wvp.utils.redis.FastJsonRedisSerializer;
+import gov.nist.javax.sip.message.SIPResponse;
+import org.junit.jupiter.api.Test;
+import org.springframework.data.redis.connection.*;
+import org.springframework.data.redis.core.*;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import javax.sip.*;
+import javax.sip.header.*;
+import javax.sip.message.Request;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Predicate;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/** Real Play/RTP/Hook/Invite/Session/Commander/header/media modules; only I/O and timer are substituted. */
+class VideoStopReceiptRestartTest {
+    private static final String STREAM = "managed_11111111111111111111111111111111";
+    private static final String LEGACY = "device_channel";
+
+    @Test void positiveRtpReceiptSurvivesRebuildingBothRtpAndReceiptModule() throws Exception {
+        External world = new External(); Instance first = new Instance(world);
+        SSRCInfo allocation = first.open(STREAM); assertNotNull(allocation);
+        assertTrue(first.rtp.closeManagedRTPServer(world.node, allocation));
+        Instance second = new Instance(world);
+        assertTrue(second.rtp.closeManagedRTPServer(world.node, allocation));
+        assertEquals(1, world.closeRequests.size());
+        assertNull(second.open(STREAM));
+    }
+
+    @Test void rebuiltRtpReturnsItsOriginalSsrcWithoutReturningAReusedNumberAgain() throws Exception {
+        External world = new External();
+        String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
+        world.ssrcRedis.strings().delete(pool);
+        world.ssrcRedis.strings().opsForSet().add(pool, "200000001");
+        SSRCInfo original = new Instance(world).open(STREAM);
+        assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
+        assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, original));
+        assertEquals(1L, world.ssrcRedis.strings().opsForSet().size(pool));
+        SSRCInfo another = new Instance(world).open("other_legacy_stream");
+        assertNotNull(another); assertEquals(original.getSsrc(), another.getSsrc());
+        assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
+        assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, original));
+        assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool), "a duplicate close never makes an occupied number available");
+        assertTrue(world.open.contains("other_legacy_stream"));
+    }
+
+    @Test void negotiatedSsrcKeepsTheOriginalPoolNumberForCloseAndReturn() throws Exception {
+        External world = new External();
+        Instance instance = new Instance(world);
+        String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
+        world.ssrcRedis.strings().delete(pool);
+        world.ssrcRedis.strings().opsForSet().add(pool, "200000001");
+        SSRCInfo original = instance.open(STREAM);
+        // The device renegotiates a different SSRC while the original pool number stays owned.
+        String negotiated = "0999999999";
+        assertTrue(instance.receipts.recordNegotiatedSsrc(world.node.getId(), STREAM, original, negotiated, false));
+        SSRCInfo current = new SSRCInfo(original.getPort(), negotiated, "rtp", STREAM, original.getTimeOutTaskKey());
+        assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, current));
+        assertEquals(1L, world.ssrcRedis.strings().opsForSet().size(pool), "the original pool number is returned once");
+        // The next allocation proves which number came back: the original, never the negotiated one.
+        assertEquals(original.getSsrc(), new Instance(world).open("next_stream").getSsrc());
+        assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
+    }
+
+    @Test void delayedLegacyCloseReturnsSsrcWhenTheCallerNeverRetries() throws Exception {
+        External world = new External(); world.delayClose = true;
+        Instance instance = new Instance(world);
+        SSRCInfo allocation = instance.open(LEGACY);
+        String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
+        assertEquals(99L, world.ssrcRedis.strings().opsForSet().size(pool));
+        instance.rtp.closeRTPServer(world.node, allocation);
+        assertEquals(99L, world.ssrcRedis.strings().opsForSet().size(pool));
+        world.closeReplies.get(0).run();
+        assertEquals(100L, world.ssrcRedis.strings().opsForSet().size(pool), "the positive async receipt must finish pool cleanup without a second stop call");
+        assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void managedStopRecoversOriginalDialogAfterByeReceiptAndLiveDialogDeletion() throws Exception {
+        External world = new External(); Instance first = new Instance(world);
+        first.managed();
+        assertFalse(first.stopManaged());
+        assertTrue(first.hooks.getAll().isEmpty());
+        Request bye = world.lastBye();
+        // Fresh observer has no SipSubscribe callbacks. Only serialized Redis state survives.
+        Instance second = new Instance(world); second.response(bye, 200);
+        assertNull(second.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertTrue(second.stopManaged());
+        assertTrue(new Instance(world).stopManaged());
+        assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void successfulSendAndRtpCloseWithoutBye2xxStayPendingAfterRestart() throws Exception {
+        External world = new External(); Instance first = new Instance(world); first.managed();
+        assertFalse(first.stopManaged());
+        Instance second = new Instance(world);
+        assertFalse(second.stopManaged());
+        second.response(world.lastBye(), 500);
+        assertFalse(new Instance(world).stopManaged());
+        assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void adoptedStopRecoversAndOldHandleCannotCloseSameNameReplacement() throws Exception {
+        External world = new External(); Instance first = new Instance(world);
+        SSRCInfo original = first.legacy("call-old"); String handle = first.adopt(); assertNotNull(handle);
+        assertFalse(first.stopAdopted(handle)); Request bye = world.lastBye();
+        Instance second = new Instance(world); second.response(bye, 200);
+        assertTrue(second.stopAdopted(handle));
+        SSRCInfo replacement = second.legacy("call-new");
+        assertNotEquals(original.getTimeOutTaskKey(), replacement.getTimeOutTaskKey());
+        Instance third = new Instance(world);
+        assertFalse(third.stopAdopted(handle));
+        assertFalse(third.rtp.closeAdoptedRTPServer(world.node, original, "call-old"));
+        third.rtp.closeRTPServer(world.node, original); // a late ordinary timeout uses the same allocation fence
+        assertEquals(1, world.closeRequests.size());
+        assertTrue(world.open.contains(LEGACY));
+        assertEquals("call-new", third.sessions.getSsrcTransactionByStream("rtp", LEGACY).getCallId());
+    }
+
+    @Test void unknownNameCloseIsNotRepeatedAndCannotReopenEvenAfterBye2xxAndRestart() throws Exception {
+        External world = new External(); world.delayClose = true;
+        Instance first = new Instance(world); first.legacy("call-old"); String handle = first.adopt();
+        assertFalse(first.stopAdopted(handle));
+        Instance second = new Instance(world); second.response(world.lastBye(), 200);
+        assertFalse(second.stopAdopted(handle)); assertNull(second.open(LEGACY));
+        assertEquals(1, world.closeRequests.size()); assertEquals(1, world.openRequests.get());
+        world.closeReplies.get(0).run();
+        assertTrue(new Instance(world).stopAdopted(handle));
+    }
+
+    @Test void hitZeroAndNonzeroCodeAreNotDurableCloseEvidence() throws Exception {
+        for (String reply : List.of("{\"code\":0,\"hit\":0}", "{\"code\":-1,\"hit\":1}")) {
+            External world = new External(); world.closeReply = reply;
+            Instance first = new Instance(world); first.managed(); assertFalse(first.stopManaged());
+            Instance second = new Instance(world); second.response(world.lastBye(), 200);
+            assertFalse(second.stopManaged()); assertFalse(new Instance(world).stopManaged());
+            assertEquals(1, world.closeRequests.size());
+        }
+    }
+
+    @Test void positiveCallbackWithFailedReceiptWriteCannotBeMaskedByLocalSuccess() throws Exception {
+        External world = new External(); Instance first = new Instance(world); first.managed();
+        world.redis.failWrite = value -> value.contains("\"state\":\"CLOSED\"");
+        assertFalse(first.stopManaged());
+        world.redis.failWrite = value -> false;
+        first.response(world.lastBye(), 200);
+        assertFalse(first.stopManaged()); assertFalse(new Instance(world).stopManaged());
+        assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void failedIntentWriteNeverDispatchesCreateAndMissingReceiptIsNotStopped() throws Exception {
+        External world = new External(); Instance first = new Instance(world);
+        world.redis.failWrite = value -> true;
+        assertThrows(RuntimeException.class, () -> first.play.playManaged(world.node, "device", "channel", STREAM, (c, m, r) -> { }));
+        world.redis.failWrite = value -> false;
+        assertFalse(new Instance(world).stopManaged());
+        assertEquals(0, world.openRequests.get()); assertTrue(world.requests.isEmpty());
+    }
+
+    @Test void closeCompareAndSetLoserCannotDispatchASecondNameClose() throws Exception {
+        External world = new External(); Instance first = new Instance(world), second = new Instance(world);
+        SSRCInfo allocation = first.open(STREAM);
+        world.redis.beforeExec = () -> assertTrue(second.rtp.closeManagedRTPServer(world.node, allocation));
+        assertFalse(first.rtp.closeManagedRTPServer(world.node, allocation));
+        assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, allocation));
+        assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void managedUuidCannotBeReallocatedOnAnotherNodeAfterReconstruction() throws Exception {
+        External world = new External(); Instance first = new Instance(world);
+        SSRCInfo allocation = first.open(STREAM); assertTrue(first.rtp.closeManagedRTPServer(world.node, allocation));
+        MediaServer other = new MediaServer(); other.setId("node-b"); other.setType("zlm"); other.setRtpEnable(true);
+        RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(other); param.setStreamId(STREAM);
+        Instance second = new Instance(world);
+        assertNull(second.rtp.openRTPServer(param, (c, m, r) -> { }));
+        assertFalse(second.rtp.closeManagedRTPServer(other, allocation));
+        assertEquals(1, world.openRequests.get()); assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void oldConfirmationCannotAuthorizeChangedTagsEvenIfCallIdAndSsrcWereReused() throws Exception {
+        External world = new External(); Instance first = new Instance(world);
+        first.legacy("reused-call"); String handle = first.adopt(); assertFalse(first.stopAdopted(handle));
+        Request oldBye = world.lastBye();
+        Instance second = new Instance(world);
+        SsrcTransaction replacement = second.sessions.getSsrcTransactionByStream("rtp", LEGACY);
+        replacement.getSipTransactionInfo().setToTag("new-dialog-tag"); second.sessions.put(replacement);
+        second.response(oldBye, 200);
+        Instance third = new Instance(world);
+        assertFalse(third.stopAdopted(handle));
+        assertEquals("new-dialog-tag", third.sessions.getSsrcTransactionByStream("rtp", LEGACY).getSipTransactionInfo().getToTag());
+        assertEquals(1, world.closeRequests.size());
+    }
+
+    @Test void lostCreateResultRemainsCreatingAcrossRestartWithoutCloseOrReopen() throws Exception {
+        External world = new External(); world.throwDuringOpen = true;
+        Instance first = new Instance(world); assertNull(first.open(STREAM));
+        Instance second = new Instance(world);
+        assertNull(second.open(STREAM));
+        assertTrue(world.closeRequests.isEmpty()); assertEquals(1, world.openRequests.get());
+    }
+
+    static class Instance {
+        final PlayServiceImpl play = new PlayServiceImpl();
+        final RtpServerServiceImpl rtp = new RtpServerServiceImpl();
+        final HookSubscribe hooks = new HookSubscribe();
+        final InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
+        final SipInviteSessionManager sessions = new SipInviteSessionManager();
+        final SIPProcessorObserver observer = new SIPProcessorObserver();
+        final SIPCommander commander = new SIPCommander();
+        final External world;
+        final VideoStopReceipts receipts;
+        Instance(External world) throws Exception {
+            this.world = world;
+            UserSetting settings = new UserSetting(); settings.setServerId("restart-test"); settings.setPlayTimeout(30000);
+            RedisTemplate<Object,Object> redis = world.redis.client();
+            StringRedisTemplate strings = world.redis.strings();
+            receipts = new VideoStopReceipts(redis);
+            RedisVideoLifecycleStore lifecycle = new RedisVideoLifecycleStore(strings);
+            SSRCFactory ssrc = new SSRCFactory(); wire(ssrc, "redisTemplate", world.ssrcRedis.strings()); wire(ssrc, "userSetting", settings);
+            wire(invites, "redisTemplate", redis); wire(invites, "userSetting", settings);
+            wire(sessions, "redisTemplate", redis); wire(sessions, "userSetting", settings);
+            RedisCatchStorageImpl cache = new RedisCatchStorageImpl();
+            wire(cache, "redisTemplate", redis); wire(cache, "userSetting", settings); cache.updateDevice(world.device);
+            DeviceMapper devices = mock(DeviceMapper.class); DeviceChannelMapper channels = mock(DeviceChannelMapper.class);
+            when(devices.getDeviceByDeviceId("device")).thenReturn(world.device);
+            when(channels.getOneByDeviceIdForSource(1, "channel")).thenReturn(world.channel);
+            DeviceChannelServiceImpl channelService = new DeviceChannelServiceImpl();
+            wire(channelService, "deviceMapper", devices); wire(channelService, "channelMapper", channels);
+            ZLMServerFactory zlm = new ZLMServerFactory(); wire(zlm, "zlmresTfulUtils", world.zlm);
+            ZLMMediaNodeServerService zlmNode = new ZLMMediaNodeServerService(); wire(zlmNode, "zlmServerFactory", zlm);
+            MediaServerServiceImpl media = new MediaServerServiceImpl(); wire(media, "nodeServerServiceMap", Map.of("zlm", zlmNode));
+            wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class));
+            wire(rtp, "ssrcFactory", ssrc); wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks);
+            wire(rtp, "sessionManager", sessions); wire(rtp, "videoLifecycleStore", lifecycle); wire(rtp, "stopReceipts", receipts);
+            SipConfig sipConfig = new SipConfig(); sipConfig.setId("34020000002000000001"); sipConfig.setDomain("3402000000"); sipConfig.setPort(5060);
+            SipLayer layer = mock(SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
+            SIPRequestHeaderProvider headers = new SIPRequestHeaderProvider();
+            wire(headers, "sipConfig", sipConfig); wire(headers, "sipLayer", layer); wire(headers, "redisCatchStorage", cache);
+            wire(commander, "headerProvider", headers); wire(commander, "sessionManager", sessions);
+            wire(commander, "sipSender", world.sender); wire(commander, "sipLayer", layer);
+            wire(commander, "sipConfig", sipConfig); wire(commander, "userSetting", settings); wire(commander, "videoLifecycleStore", lifecycle);
+            wire(observer, "sessionManager", sessions); wire(observer, "sipSubscribe", new SipSubscribe());
+            wire(play, "cmder", commander); wire(play, "redisCatchStorage", cache); wire(play, "deviceChannelService", channelService);
+            wire(play, "inviteStreamService", invites); wire(play, "sessionManager", sessions); wire(play, "subscribe", hooks);
+            wire(play, "receiveRtpServerService", rtp); wire(play, "mediaServerService", media);
+            wire(play, "videoLifecycleStore", lifecycle); wire(play, "userSetting", settings); wire(play, "stopReceipts", receipts);
+        }
+        SSRCInfo open(String stream) {
+            RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(world.node); param.setStreamId(stream);
+            return rtp.openRTPServer(param, (code, msg, result) -> { });
+        }
+        void managed() throws Exception {
+            SSRCInfo info = play.playManaged(world.node, "device", "channel", STREAM, (c, m, r) -> { }); assertNotNull(info);
+            Request invite = world.requests.get(world.requests.size() - 1); assertEquals(Request.INVITE, invite.getMethod());
+            SIPResponse reply = reply(invite, 200);
+            reply.setContent("v=0\r\ns=Play\r\ny=" + info.getSsrc() + "\r\n",
+                    SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
+            world.inviteCallbacks.get(invite).response(new SipSubscribe.EventResult<>(new ResponseEvent(this, null, null, reply)));
+            assertNotNull(sessions.getSsrcTransactionByStream("rtp", STREAM));
+        }
+        SSRCInfo legacy(String call) {
+            SSRCInfo info = open(LEGACY); assertNotNull(info);
+            invites.updateInviteInfo(InviteInfo.getInviteInfo("device", 7, LEGACY, info, "node-a", "127.0.0.1", 30000,
+                    "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false));
+            SsrcTransaction tx = new SsrcTransaction(); tx.setApp("rtp"); tx.setStream(LEGACY); tx.setDeviceId("device");
+            tx.setChannelId(7); tx.setMediaServerId("node-a"); tx.setSsrc(info.getSsrc()); tx.setCallId(call); tx.setType(InviteSessionType.PLAY);
+            SipTransactionInfo sip = new SipTransactionInfo(); sip.setCallId(call); sip.setFromTag("from-old");
+            sip.setToTag("to-old"); sip.setViaBranch("z9hG4bK-old"); tx.setSipTransactionInfo(sip); sessions.put(tx); return info;
+        }
+        String adopt() { return play.adoptStream(world.node, world.device, world.channel, LEGACY, null); }
+        boolean stopAdopted(String handle) { return play.stopAdopted(world.node, world.device, world.channel, LEGACY, handle); }
+        boolean stopManaged() { return play.stopManaged(world.node, world.device, world.channel, STREAM); }
+        void response(Request request, int status) throws Exception { observer.processResponse(new ResponseEvent(this, null, null, reply(request, status))); }
+    }
+
+    static SIPResponse reply(Request request, int status) throws Exception {
+        SIPResponse reply = (SIPResponse) SipFactory.getInstance().createMessageFactory().createResponse(status, request);
+        if (reply.getToTag() == null) reply.getTo().setTag("to-managed");
+        return reply;
+    }
+
+    static class External {
+        final RedisMemory redis = new RedisMemory();
+        final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
+        final SIPSender sender = mock(SIPSender.class);
+        final MediaServer node = new MediaServer(); final Device device = new Device(); final DeviceChannel channel = new DeviceChannel();
+        final Set<String> open = new HashSet<>(); final List<String> closeRequests = new ArrayList<>();
+        final List<Runnable> closeReplies = new ArrayList<>(); final List<Request> requests = new ArrayList<>();
+        final Map<Request, SipSubscribe.Event> inviteCallbacks = new IdentityHashMap<>();
+        final AtomicInteger openRequests = new AtomicInteger(), calls = new AtomicInteger();
+        boolean delayClose, throwDuringOpen;
+        String closeReply = "{\"code\":0,\"hit\":1}";
+        final FakeStringRedis ssrcRedis = new FakeStringRedis();
+        External() throws Exception {
+            for (int i = 1; i <= 100; i++) ssrcRedis.strings().opsForSet().add(
+                    "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a", String.format("20000%04d", i));
+            node.setId("node-a"); node.setType("zlm"); node.setRtpEnable(true); node.setSdpIp("127.0.0.1");
+            device.setId(1); device.setDeviceId("device"); device.setStreamMode("UDP"); device.setTransport("UDP"); device.setHostAddress("127.0.0.2:5060");
+            channel.setId(7); channel.setDeviceId("channel");
+            when(zlm.getRtpInfo(any(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":0,\"exist\":false}"));
+            when(zlm.openRtpServer(any(), anyMap())).thenAnswer(i -> {
+                openRequests.incrementAndGet(); open.add((String) ((Map<?,?>) i.getArgument(1)).get("stream_id"));
+                if (throwDuringOpen) throw new IllegalStateException("response lost after dispatch");
+                return JSONObject.parseObject("{\"code\":0,\"port\":30000}");
+            });
+            doAnswer(i -> {
+                String stream = (String) ((Map<?,?>) i.getArgument(1)).get("stream_id"); closeRequests.add(stream);
+                ZLMRESTfulUtils.RequestCallback callback = i.getArgument(2);
+                Runnable reply = () -> {
+                    JSONObject result = JSONObject.parseObject(closeReply);
+                    if (Integer.valueOf(0).equals(result.getInteger("code")) && Integer.valueOf(1).equals(result.getInteger("hit"))) open.remove(stream);
+                    callback.run(result);
+                };
+                closeReplies.add(reply); if (!delayClose) reply.run(); return null;
+            }).when(zlm).closeRtpServer(any(), anyMap(), any());
+            when(sender.getNewCallIdHeader(anyString(), anyString())).thenAnswer(i -> SipFactory.getInstance().createHeaderFactory().createCallIdHeader("call-" + calls.incrementAndGet()));
+            doAnswer(i -> { requests.add(i.getArgument(1)); return null; }).when(sender).transmitRequest(any(), any(), any(), any());
+            doAnswer(i -> { Request request = i.getArgument(1); requests.add(request); inviteCallbacks.put(request, i.getArgument(3)); return null; })
+                    .when(sender).transmitRequest(any(), any(), any(), any(), anyLong());
+        }
+        Request lastBye() { return requests.stream().filter(r -> Request.BYE.equals(r.getMethod())).reduce((a, b) -> b).orElseThrow(); }
+    }
+
+    static void wire(Object target, String field, Object dependency) {
+        ReflectionTestUtils.setField(target, field, dependency); // dependency injection only, never business state
+    }
+
+    /** Serialized external Redis substitute, including WATCH conflicts and all-or-nothing SIP hash CAS. */
+    static class RedisMemory {
+        final Map<String, byte[]> values = new HashMap<>();
+        final Map<String, Map<String, byte[]>> hashes = new HashMap<>();
+        final Map<String, Long> versions = new HashMap<>();
+        final FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
+        final StringRedisSerializer strings = new StringRedisSerializer();
+        final AtomicInteger ssrc = new AtomicInteger(1), sequence = new AtomicInteger();
+        Predicate<String> failWrite = value -> false;
+        Runnable beforeExec;
+        @SuppressWarnings({"unchecked", "rawtypes"})
+        RedisTemplate<Object,Object> client() {
+            RedisTemplate<Object,Object> redis = mock(RedisTemplate.class);
+            ValueOperations<Object,Object> vals = mock(ValueOperations.class); HashOperations<Object,Object,Object> hash = mock(HashOperations.class);
+            when(redis.opsForValue()).thenReturn(vals); when(redis.opsForHash()).thenReturn(hash);
+            when(redis.getKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
+            when(redis.getHashKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
+            doReturn(serializer).when(redis).getHashValueSerializer();
+            Map<String,Long> watched = new HashMap<>(); List<Runnable> queued = new ArrayList<>(); boolean[] multi = { false };
+            doAnswer(i -> { String key = i.getArgument(0).toString(); watched.put(key, versions.getOrDefault(key, 0L)); return null; }).when(redis).watch(any(Object.class));
+            doAnswer(i -> { multi[0] = true; return null; }).when(redis).multi();
+            doAnswer(i -> { multi[0] = false; queued.clear(); watched.clear(); return null; }).when(redis).discard();
+            doAnswer(i -> { watched.clear(); return null; }).when(redis).unwatch();
+            when(vals.get(any())).thenAnswer(i -> serializer.deserialize(values.get(i.getArgument(0).toString())));
+            when(vals.increment(any(), anyLong())).thenAnswer(i -> (long) sequence.incrementAndGet());
+            doAnswer(i -> {
+                String key = i.getArgument(0).toString(); Object value = i.getArgument(1); byte[] encoded = serializer.serialize(value);
+                Runnable write = () -> {
+                    if (failWrite.test(value.toString())) throw new IllegalStateException("Redis write unavailable");
+                    values.put(key, encoded); versions.merge(key, 1L, Long::sum);
+                };
+                if (multi[0]) queued.add(write); else write.run(); return null;
+            }).when(vals).set(any(), any());
+            when(redis.exec()).thenAnswer(i -> {
+                if (beforeExec != null) { Runnable race = beforeExec; beforeExec = null; race.run(); }
+                synchronized (values) {
+                    boolean conflict = watched.entrySet().stream().anyMatch(e -> !e.getValue().equals(versions.getOrDefault(e.getKey(), 0L)));
+                    if (conflict) { queued.clear(); multi[0] = false; watched.clear(); return null; }
+                    for (Runnable write : queued) write.run(); queued.clear(); multi[0] = false; watched.clear();
+                    return Collections.singletonList(Boolean.TRUE);
+                }
+            });
+            when(redis.execute(any(SessionCallback.class))).thenAnswer(i -> ((SessionCallback) i.getArgument(0)).execute(redis));
+            doAnswer(i -> { hash(i.getArgument(0).toString()).put(i.getArgument(1).toString(), serializer.serialize(i.getArgument(2))); return null; }).when(hash).put(any(), any(), any());
+            when(hash.get(any(), any())).thenAnswer(i -> serializer.deserialize(hash(i.getArgument(0).toString()).get(i.getArgument(1).toString())));
+            when(hash.values(any())).thenAnswer(i -> {
+                List<Object> result = new ArrayList<>(); for (byte[] bytes : hash(i.getArgument(0).toString()).values()) result.add(serializer.deserialize(bytes)); return result;
+            });
+            when(hash.delete(any(), any())).thenAnswer(i -> hash(i.getArgument(0).toString()).remove(i.getArgument(1).toString()) == null ? 0L : 1L);
+            when(hash.scan(any(), any(ScanOptions.class))).thenAnswer(i -> {
+                String pattern = ((ScanOptions) i.getArgument(1)).getPattern().replace("*", ".*");
+                Iterator<Map.Entry<Object,Object>> entries = new ArrayList<>(hash(i.getArgument(0).toString()).entrySet()).stream()
+                        .filter(e -> e.getKey().matches(pattern)).map(e -> (Map.Entry<Object,Object>) new AbstractMap.SimpleEntry<Object,Object>(e.getKey(), serializer.deserialize(e.getValue()))).iterator();
+                Cursor<Map.Entry<Object,Object>> cursor = mock(Cursor.class);
+                when(cursor.hasNext()).thenAnswer(a -> entries.hasNext()); when(cursor.next()).thenAnswer(a -> entries.next()); return cursor;
+            });
+            RedisConnection connection = mock(RedisConnection.class);
+            when(redis.execute(any(RedisCallback.class))).thenAnswer(i -> ((RedisCallback<?>) i.getArgument(0)).doInRedis(connection));
+            when(connection.eval(any(byte[].class), eq(ReturnType.INTEGER), anyInt(), org.mockito.ArgumentMatchers.<byte[][]>any())).thenAnswer(i -> {
+                int n = i.getArgument(2);
+                Object[] invocation = i.getArguments();
+                byte[][] args = invocation.length == 4 && invocation[3] instanceof byte[][]
+                        ? (byte[][]) invocation[3] : Arrays.copyOfRange(invocation, 3, invocation.length, byte[][].class);
+                synchronized (hashes) {
+                    for (int k = 0; k < n; k++) {
+                        int a = n + k * 5; byte[] expected = "1".equals(text(args[a+1])) ? args[a+2] : null;
+                        if (!Arrays.equals(expected, hash(text(args[k])).get(text(args[a])))) return 0L;
+                    }
+                    for (int k = 0; k < n; k++) {
+                        int a = n + k * 5;
+                        if ("1".equals(text(args[a+3]))) hash(text(args[k])).put(text(args[a]), args[a+4].clone());
+                        else hash(text(args[k])).remove(text(args[a]));
+                    }
+                    return 1L;
+                }
+            });
+            return redis;
+        }
+        @SuppressWarnings("unchecked") StringRedisTemplate strings() {
+            StringRedisTemplate redis = mock(StringRedisTemplate.class);
+            ValueOperations<String,String> vals = mock(ValueOperations.class); SetOperations<String,String> sets = mock(SetOperations.class);
+            when(redis.opsForValue()).thenReturn(vals); when(redis.opsForSet()).thenReturn(sets);
+            when(vals.get(anyString())).thenAnswer(i -> (String) serializer.deserialize(values.get(i.getArgument(0))));
+            doAnswer(i -> { values.put(i.getArgument(0), serializer.serialize(i.getArgument(1))); return null; }).when(vals).set(anyString(), anyString());
+            when(sets.size(anyString())).thenReturn(100L); when(sets.pop(anyString())).thenAnswer(i -> String.format("12345%04d", ssrc.getAndIncrement()));
+            return redis;
+        }
+        Map<String,byte[]> hash(String key) { return hashes.computeIfAbsent(key, unused -> new LinkedHashMap<>()); }
+        static String text(byte[] value) { return new String(value, StandardCharsets.UTF_8); }
+    }
+}