ソースを参照

fix(video): 补偿媒体持久化失败并保护混合观看生命周期

Kazerin 3 週間 前
親
コミット
719fe092e7

+ 8 - 0
docs/video-session-media-node-20261112.sql

@@ -0,0 +1,8 @@
+-- cockpit-video-monitoring/03: precise media-node binding for prepared and adopted streams.
+-- Generated only; NOT executed against a real database. Apply after 01 and prepared-session 03 migration.
+-- Never backfill a guessed default node for old sessions. Unknown legacy handles remain unconfirmed.
+BEGIN;
+ALTER TABLE app_user.video_play_session ADD COLUMN media_server_id varchar(64) NULL;
+COMMENT ON COLUMN app_user.video_play_session.media_server_id
+    IS '媒体创建响应确认的实际节点;释放时禁止猜默认节点,旧未知节点不回填';
+COMMIT;

+ 24 - 0
pipe-network-service/sql/tests/video_session_media_node.test.mjs

@@ -0,0 +1,24 @@
+// In-memory SQL only. PGLITE_MODULE points to an already provisioned test module.
+import { readFile } from 'node:fs/promises'
+import { pathToFileURL } from 'node:url'
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+const { PGlite } = await import(process.env.PGLITE_MODULE ? pathToFileURL(process.env.PGLITE_MODULE).href : '@electric-sql/pglite')
+const sql = await readFile(new URL('../../../docs/video-session-media-node-20261112.sql', import.meta.url), 'utf8')
+
+test('media node migration preserves unknown legacy handles and stores only explicitly confirmed nodes', async () => {
+    const db = new PGlite()
+    try {
+        await db.exec(`CREATE SCHEMA app_user;
+            CREATE TABLE app_user.video_play_session(session_id text PRIMARY KEY, video_id text, stream_id text, status text);
+            INSERT INTO app_user.video_play_session VALUES ('legacy','camera','legacy_stream','ACTIVE');`)
+        await db.exec(sql)
+        assert.deepEqual((await db.query('SELECT * FROM app_user.video_play_session')).rows,
+            [{ session_id: 'legacy', video_id: 'camera', stream_id: 'legacy_stream', status: 'ACTIVE', media_server_id: null }])
+        await db.query("UPDATE app_user.video_play_session SET media_server_id=$1 WHERE session_id=$2", ['confirmed-node-A', 'legacy'])
+        assert.equal((await db.query("SELECT media_server_id FROM app_user.video_play_session WHERE session_id='legacy'")).rows[0].media_server_id, 'confirmed-node-A')
+        await assert.rejects(db.exec(sql)) // One-time migration deliberately refuses heterogeneous/repeated installs.
+        await db.exec('ROLLBACK')
+        assert.equal((await db.query("SELECT media_server_id FROM app_user.video_play_session WHERE session_id='legacy'")).rows[0].media_server_id, 'confirmed-node-A')
+    } finally { await db.close() }
+})

+ 8 - 0
pipe-network-service/zksy-admin/pom.xml

@@ -17,6 +17,14 @@
 
 
     <dependencies>
     <dependencies>
 
 
+        <!-- Only the offline SQL/transaction regression uses H2; never packaged at runtime. -->
+        <dependency>
+            <groupId>com.h2database</groupId>
+            <artifactId>h2</artifactId>
+            <version>2.1.214</version>
+            <scope>test</scope>
+        </dependency>
+
         <!-- spring-boot-devtools -->
         <!-- spring-boot-devtools -->
         <dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <groupId>org.springframework.boot</groupId>

+ 24 - 46
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoPreparedSessionTest.java

@@ -34,13 +34,9 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
 
 
 import javax.servlet.Filter;
 import javax.servlet.Filter;
 import java.nio.charset.StandardCharsets;
 import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.List;
 import java.util.Map;
 import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
 
 
 import static org.junit.jupiter.api.Assertions.*;
 import static org.junit.jupiter.api.Assertions.*;
 import static org.mockito.ArgumentMatchers.*;
 import static org.mockito.ArgumentMatchers.*;
@@ -55,15 +51,15 @@ class VideoPreparedSessionTest {
     private static final String ROOT = "/api/cockpit/v1/video";
     private static final String ROOT = "/api/cockpit/v1/video";
     private static final String CODE = "摄像机/ PREPARED+01";
     private static final String CODE = "摄像机/ PREPARED+01";
     private static final String VIDEO = "prepared-ledger-id";
     private static final String VIDEO = "prepared-ledger-id";
-    private static final java.util.regex.Pattern UUID_PARAM = java.util.regex.Pattern.compile(
-            "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
     private AnnotationConfigWebApplicationContext context;
     private AnnotationConfigWebApplicationContext context;
     private MockMvc mvc;
     private MockMvc mvc;
     private VideoSessionMapper sessions;
     private VideoSessionMapper sessions;
     private VideoCollectorClient media;
     private VideoCollectorClient media;
     private RowTransactions transactions;
     private RowTransactions transactions;
+    private VideoSessionMapper sqlQueries;
+    private org.springframework.jdbc.core.JdbcTemplate queryStorage;
 
 
-    @BeforeEach void setUp() {
+    @BeforeEach void setUp() throws Exception {
         SecurityContextHolder.clearContext();
         SecurityContextHolder.clearContext();
         TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), VideoSession.class);
         TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), VideoSession.class);
         context = new AnnotationConfigWebApplicationContext();
         context = new AnnotationConfigWebApplicationContext();
@@ -77,6 +73,11 @@ class VideoPreparedSessionTest {
         sessions = context.getBean(VideoSessionMapper.class);
         sessions = context.getBean(VideoSessionMapper.class);
         media = context.getBean(VideoCollectorClient.class);
         media = context.getBean(VideoCollectorClient.class);
         transactions = context.getBean(RowTransactions.class);
         transactions = context.getBean(RowTransactions.class);
+        VideoPreparedSqlTransactionTest.SqlConfiguration sqlFixture = new VideoPreparedSqlTransactionTest.SqlConfiguration();
+        javax.sql.DataSource ds = sqlFixture.dataSource();
+        queryStorage = new org.springframework.jdbc.core.JdbcTemplate(ds);
+        VideoPreparedSqlTransactionTest.createSchema(queryStorage);
+        sqlQueries = sqlFixture.sqlSessions(ds);
         EquipmentBase device = new EquipmentBase();
         EquipmentBase device = new EquipmentBase();
         device.setEquipmentId(VIDEO); device.setEquipmentCode(CODE); device.setEquipmentName("准备态摄像机"); device.setEquipmentTypeId(20);
         device.setEquipmentId(VIDEO); device.setEquipmentCode(CODE); device.setEquipmentName("准备态摄像机"); device.setEquipmentTypeId(20);
         when(context.getBean(EquipmentBaseMapper.class).selectList(any())).thenReturn(List.of(device));
         when(context.getBean(EquipmentBaseMapper.class).selectList(any())).thenReturn(List.of(device));
@@ -98,10 +99,14 @@ class VideoPreparedSessionTest {
             assertTrue(TransactionSynchronizationManager.isActualTransactionActive(), "device lock requires a short DB transaction");
             assertTrue(TransactionSynchronizationManager.isActualTransactionActive(), "device lock requires a short DB transaction");
             return VIDEO;
             return VIDEO;
         });
         });
-        // 内存适配器只做“数据库会给出的答案”,共享/代次判定仍在生产代码里。
-        when(sessions.selectList(any())).thenAnswer(call -> new ArrayList<>(
-                matching(paramsOf(call.getArgument(0))).stream().map(VideoPreparedSessionTest::copy).collect(Collectors.toList())));
-        when(sessions.selectCount(any())).thenAnswer(call -> (long) matching(paramsOf(call.getArgument(0))).size());
+        // Execute the complete production SQL, including field names/operators/NULL/IN/NE/count.
+        // Only row commit outcomes are substituted here; the companion SQL test uses real JDBC commits too.
+        when(sessions.selectList(any())).thenAnswer(call -> {
+            refreshQueryStorage(); return sqlQueries.selectList(call.getArgument(0));
+        });
+        when(sessions.selectCount(any())).thenAnswer(call -> {
+            refreshQueryStorage(); return sqlQueries.selectCount(call.getArgument(0));
+        });
     }
     }
 
 
     @AfterEach void close() {
     @AfterEach void close() {
@@ -196,7 +201,8 @@ class VideoPreparedSessionTest {
 
 
     @Test void anAnonymousViewerJoinsTheLegacyGenerationAndLeavingDoesNotCancelTheSharedStream() throws Exception {
     @Test void anAnonymousViewerJoinsTheLegacyGenerationAndLeavingDoesNotCancelTheSharedStream() throws Exception {
         VideoSession legacy = seed("legacy-business-viewer", "ACTIVE", null, "legacy_stream");
         VideoSession legacy = seed("legacy-business-viewer", "ACTIVE", null, "legacy_stream");
-        legacy.setUserId(7L);        java.util.concurrent.atomic.AtomicReference<Map<String, Object>> started = new java.util.concurrent.atomic.AtomicReference<>();
+        legacy.setUserId(7L);
+        java.util.concurrent.atomic.AtomicReference<Map<String, Object>> started = new java.util.concurrent.atomic.AtomicReference<>();
         when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
         when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
             Map<String, Object> request = call.getArgument(1);
             Map<String, Object> request = call.getArgument(1);
             started.set(request);
             started.set(request);
@@ -206,10 +212,11 @@ class VideoPreparedSessionTest {
         JSONObject viewer = prepare();
         JSONObject viewer = prepare();
         String liveBody = action(viewer, "live", viewer.getString("sessionToken"))
         String liveBody = action(viewer, "live", viewer.getString("sessionToken"))
                 .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8);
                 .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8);
-        assertTrue(liveBody.contains("\"status\":\"ACTIVE\""), "live 响应: " + liveBody);
+        assertEquals("ACTIVE", JSON.parseObject(liveBody).getJSONObject("data").getString("status"), "live 响应: " + liveBody);
         assertNotNull(started.get(), "start 必须被调用一次");
         assertNotNull(started.get(), "start 必须被调用一次");
         assertEquals("legacy_stream", ((Map<?, ?>) started.get().get("existingMedia")).get("stream"),
         assertEquals("legacy_stream", ((Map<?, ?>) started.get().get("existingMedia")).get("stream"),
                 "加入既有代次必须带上真实旧句柄,而不是重建");
                 "加入既有代次必须带上真实旧句柄,而不是重建");
+        assertEquals("legacy-origin-node", ((Map<?, ?>) started.get().get("existingMedia")).get("mediaServerId"));
         VideoSession anonymous = transactions.rows().get(viewer.getString("sessionId"));
         VideoSession anonymous = transactions.rows().get(viewer.getString("sessionId"));
         VideoSession storedLegacy = transactions.rows().get("legacy-business-viewer");
         VideoSession storedLegacy = transactions.rows().get("legacy-business-viewer");
         assertNotNull(storedLegacy.getMediaGeneration(), "旧观看者必须被并入一个代次");
         assertNotNull(storedLegacy.getMediaGeneration(), "旧观看者必须被并入一个代次");
@@ -265,6 +272,7 @@ class VideoPreparedSessionTest {
         VideoSession row = new VideoSession();
         VideoSession row = new VideoSession();
         row.setSessionId(sessionId); row.setVideoId(VIDEO); row.setMode("LIVE"); row.setStatus(status);
         row.setSessionId(sessionId); row.setVideoId(VIDEO); row.setMode("LIVE"); row.setStatus(status);
         row.setMediaGeneration(generation); row.setStreamId(stream);
         row.setMediaGeneration(generation); row.setStreamId(stream);
+        row.setMediaServerId("legacy-origin-node");
         row.setGbDeviceId("34020000002000000001"); row.setGbChannelId("34020000001320000001");
         row.setGbDeviceId("34020000002000000001"); row.setGbChannelId("34020000001320000001");
         java.time.LocalDateTime now = java.time.LocalDateTime.ofInstant(
         java.time.LocalDateTime now = java.time.LocalDateTime.ofInstant(
                 java.time.Instant.parse("2026-11-10T08:00:00Z"), java.time.ZoneOffset.UTC);
                 java.time.Instant.parse("2026-11-10T08:00:00Z"), java.time.ZoneOffset.UTC);
@@ -282,39 +290,9 @@ class VideoPreparedSessionTest {
                 .getJSONObject("data");
                 .getJSONObject("data");
     }
     }
 
 
-    /**
-     * 以 wrapper 的参数值还原生产查询的过滤条件(video_id、mode、status IN、media_generation、session_id <>)。
-     * 区分方式:sessionId 是已存在行的主键,代次不是。
-     */
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    private static Map<String, Object> paramsOf(Object wrapper) {
-        com.baomidou.mybatisplus.core.conditions.AbstractWrapper raw =
-                (com.baomidou.mybatisplus.core.conditions.AbstractWrapper) wrapper;
-        raw.getSqlSegment();   // 先生成片段,MyBatis-Plus 才会填充参数表
-        return raw.getParamNameValuePairs();
-    }
-
-    private List<VideoSession> matching(Map<String, Object> parameters) {
-        Set<Object> params = new HashSet<>(parameters.values());
-        Set<String> statuses = params.stream()
-                .filter(value -> value instanceof String && Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING").contains(value))
-                .map(String.class::cast).collect(Collectors.toSet());
-        Set<String> uuids = params.stream()
-                .filter(value -> value instanceof String && UUID_PARAM.matcher((String) value).matches())
-                .map(String.class::cast).collect(Collectors.toSet());
-        Set<String> excluded = uuids.stream().filter(transactions.rows()::containsKey).collect(Collectors.toSet());
-        Set<String> generations = new HashSet<>(uuids);
-        generations.removeAll(excluded);
-        List<VideoSession> found = new ArrayList<>();
-        for (VideoSession row : transactions.rows().values()) {
-            if (!params.contains(row.getVideoId())) continue;
-            if (params.contains("LIVE") && !"LIVE".equals(row.getMode())) continue;
-            if (!statuses.isEmpty() && !statuses.contains(row.getStatus())) continue;
-            if (excluded.contains(row.getSessionId())) continue;
-            if (!generations.isEmpty() && !generations.contains(row.getMediaGeneration())) continue;
-            found.add(row);
-        }
-        return found;
+    private void refreshQueryStorage() {
+        queryStorage.update("DELETE FROM app_user.video_play_session");
+        transactions.rows().values().forEach(sqlQueries::insert);
     }
     }
 
 
     private ResultActions action(JSONObject viewer, String action, String token) throws Exception {
     private ResultActions action(JSONObject viewer, String action, String token) throws Exception {

+ 595 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoPreparedSqlTransactionTest.java

@@ -0,0 +1,595 @@
+package com.zksy.web.controller.cockpit;
+
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoDeviceService;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.common.core.domain.model.LoginUser;
+import com.zksy.framework.web.service.TokenService;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.Set;
+import java.util.HashMap;
+import java.util.concurrent.TimeUnit;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.mybatis.spring.SqlSessionTemplate;
+import org.springframework.beans.BeanUtils;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.Primary;
+import org.springframework.core.env.MapPropertySource;
+import org.springframework.http.MediaType;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.transaction.TransactionSystemException;
+import org.springframework.transaction.support.DefaultTransactionStatus;
+import org.springframework.mock.web.MockServletContext;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+
+import javax.servlet.Filter;
+import javax.sql.DataSource;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+/** Real HTTP/security/services, production MyBatis SQL and local in-memory SQL transactions.
+ * No server, application scheduler, external database or device is started. Media is the only
+ * lifecycle boundary substitute; it must never be called with a SQL transaction held.
+ */
+class VideoPreparedSqlTransactionTest {
+    private static final String ROOT = "/api/cockpit/v1/video";
+    private static final String VIDEO = "sql-ledger-id";
+    private static final String CODE = "摄像机/ SQL+01";
+    private AnnotationConfigWebApplicationContext context;
+    private MockMvc mvc;
+    private JdbcTemplate sql;
+    private VideoCollectorClient media;
+    private final AtomicReference<Map<String, Object>> start = new AtomicReference<>();
+    private final AtomicReference<Map<String, Object>> cancel = new AtomicReference<>();
+
+    @BeforeEach void setUp() {
+        SecurityContextHolder.clearContext();
+        context = new AnnotationConfigWebApplicationContext();
+        context.setServletContext(new MockServletContext());
+        context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("video-sql-test", Map.of(
+                "token.header", "Authorization", "token.secret", "offline-sql-contract-not-a-production-secret", "token.expireTime", "60")));
+        context.register(SqlConfiguration.class);
+        context.refresh();
+        sql = new JdbcTemplate(context.getBean(DataSource.class));
+        createSchema(sql);
+        sql.update("INSERT INTO app_user.equipment_base VALUES (?)", VIDEO);
+        mvc = MockMvcBuilders.webAppContextSetup(context)
+                .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentId(VIDEO); device.setEquipmentCode(CODE); device.setEquipmentName("SQL摄像机"); device.setEquipmentTypeId(20);
+        when(context.getBean(EquipmentBaseMapper.class).selectList(any())).thenReturn(List.of(device));
+        VideoDeviceRecord binding = new VideoDeviceRecord(); BeanUtils.copyProperties(device, binding);
+        binding.setVideoId(VIDEO); binding.setSourceType("GB28181");
+        binding.setGbDeviceId("34020000002000000001"); binding.setGbChannelId("34020000001320000001");
+        when(context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO)).thenReturn(binding);
+        media = context.getBean(VideoCollectorClient.class);
+        when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1);
+            start.set(new LinkedHashMap<>(body));
+            assertTrue(sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE status='STARTING' AND media_generation=?",
+                    Long.class, body.get("generation")) > 0, "intent must really commit before media starts");
+            return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media",
+                    Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
+        });
+        when(media.post(eq("/internal/video/lifecycle/status"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1);
+            return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media",
+                    Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
+        });
+        when(media.get(eq("/api/play/start/34020000002000000001/34020000001320000001"), any()))
+                .thenReturn(Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
+            return Map.of("generation", body.get("generation"), "status", "STOPPED");
+        });
+    }
+
+    @AfterEach void close() {
+        if (context != null) context.close();
+        SecurityContextHolder.clearContext();
+    }
+
+    @Test void activeSqlFailureCompensatesTheAlreadyStartedGenerationBeforeReturning() throws Exception {
+        JSONObject viewer = prepare();
+        // This is a real failed SQL statement AFTER identity/STARTING commit and AFTER media start.
+        sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_active CHECK (status <> 'ACTIVE')");
+        action(viewer, "live").andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.data.media").doesNotExist());
+        assertNotNull(start.get(), "the test must actually start media before the injected failure");
+        assertNotNull(cancel.get(), "ACTIVE persistence failure must immediately compensate, not leave a STARTING orphan");
+        assertEquals(start.get().get("generation"), cancel.get().get("generation"));
+        assertEquals(start.get().get("source"), cancel.get().get("source"));
+        assertEquals(start.get().get("startDeadline"), cancel.get().get("startDeadline"));
+        action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void activeCommitFailureOrLostAcknowledgementCompensatesExactlyThisGeneration(boolean committed) throws Exception {
+        JSONObject viewer = prepare();
+        CommitFaultTransactions transactions = context.getBean(CommitFaultTransactions.class);
+        transactions.failActiveCommit = true;
+        transactions.commitBeforeFailure = committed;
+        action(viewer, "live").andExpect(status().isServiceUnavailable());
+        assertTrue(transactions.failureInjected, "must fail ACTIVE commit, not prepare or intent commit");
+        assertNotNull(cancel.get(), "commit failure after media creation must compensate immediately");
+        assertEquals(start.get().get("generation"), cancel.get().get("generation"));
+        action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+    }
+
+    @Test void failedCompensationRemainsPendingAndCanBeReclaimedWithoutASecondStart() throws Exception {
+        JSONObject viewer = prepare();
+        sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_active CHECK (status <> 'ACTIVE')");
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
+            throw new IllegalStateException("offline media boundary failure");
+        });
+        action(viewer, "live").andExpect(status().isServiceUnavailable());
+        assertNotNull(cancel.get(), "failed SQL must trigger compensation even when cancel also fails");
+        action(viewer, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("CLEANUP_PENDING"))
+                .andExpect(jsonPath("$.data.media").doesNotExist());
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            Map<String, Object> body = call.getArgument(1);
+            assertEquals(start.get().get("generation"), body.get("generation"));
+            return Map.of("generation", body.get("generation"), "status", "STOPPED");
+        });
+        action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void oldUserAndPreparedAnonymousReleaseOnlyTheLastSharedGeneration(boolean oldUserLast) throws Exception {
+        String bearer = userToken(7);
+        JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
+                .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        JSONObject viewer = prepare();
+        action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        assertEquals("sql_stream", ((Map<?, ?>) start.get().get("existingMedia")).get("stream"));
+        mvc.perform(post("/api/video/sessions/{id}/stop", legacy.getString("sessionId"))
+                .header("Authorization", userToken(8))).andExpect(jsonPath("$.code").value(500));
+        assertNull(cancel.get(), "wrong ownership cannot release any media");
+        if (oldUserLast) {
+            action(viewer, "stop").andExpect(status().isOk());
+            assertNull(cancel.get(), "one remaining user still owns this generation");
+            oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        } else {
+            oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+            assertNull(cancel.get(), "one remaining anonymous viewer still owns this generation");
+            action(viewer, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
+            action(viewer, "stop").andExpect(status().isOk());
+        }
+        assertNotNull(cancel.get());
+        assertEquals(start.get().get("generation"), cancel.get().get("generation"));
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        action(viewer, "stop").andExpect(status().isOk());
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+        verify(media, never()).get(eq("/api/play/stop/34020000002000000001/34020000001320000001"), any());
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"PREPARED", "STARTING", "CLEANUP_PENDING"})
+    void expiryReclaimsEveryNonterminalIntentWithoutAnHttpPoll(String initial) throws Exception {
+        JSONObject viewer = prepare();
+        if (!"PREPARED".equals(initial)) {
+            if ("STARTING".equals(initial)) when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+                Map<String, Object> body = call.getArgument(1); start.set(new LinkedHashMap<>(body));
+                return Map.of("generation", body.get("generation"), "status", "STARTING");
+            });
+            action(viewer, "live");
+            if ("CLEANUP_PENDING".equals(initial)) {
+                when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+                    Map<String, Object> body = call.getArgument(1);
+                    return Map.of("generation", body.get("generation"), "status", "CLEANUP_PENDING");
+                });
+                action(viewer, "stop").andExpect(status().isAccepted());
+                when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+                    assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+                    Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
+                    return Map.of("generation", body.get("generation"), "status", "STOPPED");
+                });
+            }
+        }
+        context.getBean(MutableClock.class).advance("PREPARED".equals(initial) ? 121 : 31);
+        context.getBean(VideoDeviceService.class).expireSessions();
+        // Read persisted outcome before status (which is itself allowed to perform cleanup).
+        assertEquals("STOPPED", sql.queryForObject("SELECT status FROM app_user.video_play_session WHERE session_id=?",
+                String.class, viewer.getString("sessionId")));
+        action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        if ("PREPARED".equals(initial)) verifyNoInteractions(media);
+        else assertEquals(start.get().get("generation"), cancel.get().get("generation"));
+    }
+
+    @ParameterizedTest
+    @CsvSource({"STARTING,false", "UNKNOWN,false", "STARTING,true", "UNKNOWN,true"})
+    void joiningAHealthyGenerationSurvivesItsOldDeadlineUntilTheActivePeerLeaves(String outcome, boolean peerExpires) throws Exception {
+        JSONObject active = prepare();
+        action(active, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        Map<String, Object> original = new LinkedHashMap<>(start.get());
+        MutableClock clock = context.getBean(MutableClock.class);
+        clock.advance(31);
+        action(active, "heartbeat").andExpect(status().isOk());
+        JSONObject joining = prepare();
+        doAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1);
+            assertEquals(original.get("generation"), body.get("generation"));
+            assertEquals(original.get("startDeadline"), body.get("startDeadline"));
+            if ("UNKNOWN".equals(outcome)) throw new IllegalStateException("offline lost start acknowledgement");
+            return Map.of("generation", body.get("generation"), "status", "STARTING");
+        }).when(media).post(eq("/internal/video/lifecycle/start"), any());
+        doAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1);
+            return Map.of("generation", body.get("generation"), "status", "STARTING");
+        }).when(media).post(eq("/internal/video/lifecycle/status"), any());
+        action(joining, "live").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
+        action(joining, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
+        context.getBean(VideoDeviceService.class).expireSessions();
+        action(joining, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
+        assertNull(cancel.get(), "neither status nor the expiry worker may kill a healthy generation's joining viewer");
+        if (peerExpires) clock.advance(121);
+        else action(active, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        context.getBean(VideoDeviceService.class).expireSessions();
+        action(joining, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        assertNotNull(cancel.get(), "without a healthy peer the original expired deadline must reclaim the join");
+        assertEquals(original.get("generation"), cancel.get().get("generation"));
+        assertEquals(original.get("startDeadline"), cancel.get().get("startDeadline"));
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+    }
+
+    @Test void aHealthyPeerDoesNotKeepAnAbandonedJoiningIntentForever() throws Exception {
+        JSONObject active = prepare();
+        action(active, "live").andExpect(status().isOk());
+        Object generation = start.get().get("generation");
+        MutableClock clock = context.getBean(MutableClock.class);
+        clock.advance(31);
+        action(active, "heartbeat").andExpect(status().isOk());
+        JSONObject joining = prepare();
+        doThrow(new IllegalStateException("offline start acknowledgement lost"))
+                .when(media).post(eq("/internal/video/lifecycle/start"), any());
+        action(joining, "live").andExpect(status().isAccepted());
+        clock.advance(119);
+        action(active, "heartbeat").andExpect(status().isOk());
+        clock.advance(2);
+        context.getBean(VideoDeviceService.class).expireSessions();
+        // An abandoned viewer's own lease is bounded even while another viewer renews forever.
+        action(joining, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        assertNull(cancel.get(), "expiring the abandoned join must not cancel its healthy peer");
+        action(active, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        action(active, "stop").andExpect(status().isOk());
+        assertEquals(generation, cancel.get().get("generation"));
+    }
+
+    @Test void legacyAnonymousStopReadsBackTheCommittedStoppedState() throws Exception {
+        JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON)
+                .content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, times(1)).get(eq("/api/play/stop/34020000002000000001/34020000001320000001"), any());
+    }
+
+    @Test void anOldApiViewerJoiningAnExistingPreparedGenerationNeverUsesBlindStart() throws Exception {
+        JSONObject viewer = prepare();
+        action(viewer, "live").andExpect(status().isOk());
+        String generation = (String) start.get().get("generation");
+        Object originalDeadline = start.get().get("startDeadline");
+        context.getBean(MutableClock.class).advance(31);
+        String bearer = userToken(7);
+        JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
+                .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.flv").value("https://media.invalid/sql.flv"))
+                .andExpect(jsonPath("$.data.generation").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        assertEquals(generation, start.get().get("generation"));
+        assertEquals(originalDeadline, start.get().get("startDeadline"), "joining must not extend a generation's start deadline");
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        assertNull(cancel.get());
+        action(viewer, "stop").andExpect(status().isOk());
+        assertEquals(generation, cancel.get().get("generation"));
+        verify(media, never()).get(startsWith("/api/play/start/"), any());
+        verify(media, never()).get(startsWith("/api/play/stop/"), any());
+    }
+
+    @Test void sqlFailureWhileJoiningDoesNotCancelTheOtherActiveViewer() throws Exception {
+        String bearer = userToken(7);
+        JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
+                .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        JSONObject viewer = prepare();
+        String rejectedId = viewer.getString("sessionId");
+        assertNotNull(UUID.fromString(rejectedId));
+        sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_join CHECK (status <> 'ACTIVE' OR session_id <> '"
+                + rejectedId + "')");
+        action(viewer, "live").andExpect(status().isServiceUnavailable());
+        action(viewer, "status").andExpect(jsonPath("$.data.status").value("STOPPED"));
+        assertNull(cancel.get(), "a failed joining viewer must not cancel the existing user's generation");
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        assertNotNull(cancel.get());
+        verify(media, never()).get(startsWith("/api/play/stop/"), any());
+    }
+
+    @Test void unrelatedVideoModeAndGenerationDoNotCountAsOwnersOfThisGeneration() throws Exception {
+        JSONObject viewer = prepare();
+        action(viewer, "live").andExpect(status().isOk());
+        String generation = (String) start.get().get("generation");
+        // Adversarial persisted rows: the actual SQL must filter on all three dimensions.
+        seedOtherOwner(VIDEO, "PLAYBACK", generation);
+        seedOtherOwner("another-video", "LIVE", generation);
+        seedOtherOwner(VIDEO, "LIVE", UUID.randomUUID().toString());
+        action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        assertNotNull(cancel.get(), "unrelated owners must not suppress last-viewer reclamation");
+        assertEquals(generation, cancel.get().get("generation"));
+        assertEquals(3L, sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE status='ACTIVE'", Long.class));
+    }
+
+    private void seedOtherOwner(String videoId, String mode, String generation) {
+        sql.update("INSERT INTO app_user.video_play_session (session_id,video_id,user_id,mode,status,media_generation,create_time,last_seen) "
+                + "VALUES (?,?,7,?,'ACTIVE',?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)", UUID.randomUUID().toString(),videoId,mode,generation);
+    }
+
+    @Test void liveHeartbeatsKeepANonexpiredViewerOutOfTheExpiryScan() throws Exception {
+        JSONObject viewer = prepare();
+        action(viewer, "live").andExpect(status().isOk());
+        context.getBean(MutableClock.class).advance(119);
+        action(viewer, "heartbeat").andExpect(status().isOk());
+        context.getBean(MutableClock.class).advance(2);
+        context.getBean(VideoDeviceService.class).expireSessions();
+        action(viewer, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        assertNull(cancel.get());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    void oldManualStopRetainsOnlyTheKnownOriginAndNeverAcknowledgesUnknownCleanup(boolean knownNode) throws Exception {
+        VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
+        binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/old-camera");
+        Map<String, Object> legacyMedia = new LinkedHashMap<>(Map.of("stream", "old_manual_stream",
+                "proxyKey", "old-private-key", "flv", "https://media.invalid/old.flv"));
+        if (knownNode) legacyMedia.put("mediaServerId", "origin-not-default");
+        when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(legacyMedia);
+        String bearer = userToken(7);
+        JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
+                .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.flv").value("https://media.invalid/old.flv"))
+                .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
+                .andExpect(jsonPath("$.data.mediaServerId").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        AtomicReference<Map<String, Object>> stopBody = new AtomicReference<>();
+        doAnswer(call -> {
+            stopBody.set(new LinkedHashMap<>(call.getArgument(1)));
+            // The external client reports pending/transport-unknown as failure, not confirmed stop.
+            throw new com.zksy.common.exception.ServiceException("offline provider cleanup pending after restart");
+        }).when(media).post(eq("/internal/video/manual/stop"), any());
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(500));
+        Map<String, Object> expected = knownNode ? Map.of("mediaServerId", "origin-not-default", "key", "old-private-key")
+                : Map.of("key", "old-private-key");
+        assertEquals(expected, stopBody.get(), "SQL's source node must survive provider restart; an unknown node must never be invented");
+        doAnswer(call -> {
+            assertEquals(expected, call.getArgument(1));
+            return null; // The existing successful manual-stop envelope has no data.
+        }).when(media).post(eq("/internal/video/manual/stop"), any());
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        verify(media, times(2)).post(eq("/internal/video/manual/stop"), any());
+        verify(media, never()).post(startsWith("/internal/video/lifecycle/"), any());
+    }
+
+    @Test void twoOldManualUsersAdoptOneKnownHandleAndOnlyTheLastUserCancels() throws Exception {
+        VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
+        binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/shared-old-camera");
+        Map<String, Object> knownMedia = Map.of("stream", "shared_old_stream", "mediaServerId", "origin-old-node",
+                "proxyKey", "shared-private-key", "flv", "https://media.invalid/shared-old.flv");
+        when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(knownMedia);
+        doAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1); start.set(new LinkedHashMap<>(body));
+            assertEquals(Map.of("stream", "shared_old_stream", "mediaServerId", "origin-old-node", "proxyKey", "shared-private-key"),
+                    body.get("existingMedia"), "adoption must be bound to the persisted physical handle");
+            return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media", knownMedia);
+        }).when(media).post(eq("/internal/video/lifecycle/start"), any());
+        String firstBearer = userToken(7), secondBearer = userToken(8);
+        JSONObject first = oldManualStart(firstBearer);
+        assertNull(start.get(), "the very first old LIVE request retains its legacy start contract");
+        JSONObject second = oldManualStart(secondBearer);
+        assertNotNull(start.get(), "the second old user must coordinate adoption instead of starting another proxy");
+        String generation = (String) start.get().get("generation");
+        assertEquals(2L, sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE mode='LIVE' AND status='ACTIVE' AND media_generation=?",
+                Long.class, generation));
+        oldStop(first, secondBearer).andExpect(jsonPath("$.code").value(500));
+        assertNull(cancel.get());
+        oldStop(first, firstBearer).andExpect(jsonPath("$.code").value(200));
+        assertNull(cancel.get(), "the second old viewer still owns the adopted handle");
+        doAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
+            return Map.of("generation", body.get("generation"), "status", "CLEANUP_PENDING");
+        }).when(media).post(eq("/internal/video/lifecycle/cancel"), any());
+        oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(500));
+        assertEquals(generation, cancel.get().get("generation"));
+        assertEquals(start.get().get("existingMedia"), cancel.get().get("existingMedia"));
+        doAnswer(call -> {
+            Map<String, Object> body = call.getArgument(1);
+            assertEquals(generation, body.get("generation"));
+            return Map.of("generation", body.get("generation"), "status", "STOPPED");
+        }).when(media).post(eq("/internal/video/lifecycle/cancel"), any());
+        oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(200));
+        oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(200));
+        verify(media, times(1)).post(eq("/internal/video/manual/start"), any());
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+        verify(media, times(2)).post(eq("/internal/video/lifecycle/cancel"), any());
+        verify(media, never()).post(eq("/internal/video/manual/stop"), any());
+    }
+
+    @Test void anUnknownLegacyManualNodeCannotBeGuessedOrBlindlyRestartedForAnotherOldUser() throws Exception {
+        VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
+        binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/unknown-node-camera");
+        when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(Map.of("stream", "shared_old_stream",
+                "proxyKey", "shared-private-key", "flv", "https://media.invalid/shared-old.flv"));
+        String bearer = userToken(7);
+        JSONObject first = oldManualStart(bearer);
+        clearInvocations(media);
+        mvc.perform(post("/api/video/devices/{id}/live", VIDEO).header("Authorization", userToken(8)))
+                .andExpect(jsonPath("$.code").value(500));
+        verifyNoInteractions(media); // No guessed default node, adoption or second legacy start.
+        oldStop(first, bearer).andExpect(jsonPath("$.code").value(200));
+        verify(media).post("/internal/video/manual/stop", Map.of("key", "shared-private-key"));
+    }
+
+    private JSONObject oldManualStart(String bearer) throws Exception {
+        return JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO).header("Authorization", bearer))
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.flv").value("https://media.invalid/shared-old.flv"))
+                .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
+                .andExpect(jsonPath("$.data.mediaServerId").doesNotExist())
+                .andExpect(jsonPath("$.data.generation").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+    }
+
+    private ResultActions oldStop(JSONObject viewer, String bearer) throws Exception {
+        return mvc.perform(post("/api/video/sessions/{id}/stop", viewer.getString("sessionId")).header("Authorization", bearer));
+    }
+
+    private String userToken(long id) {
+        SysUser user = new SysUser(); user.setUserId(id); user.setUserName("sql-viewer-" + id);
+        LoginUser login = new LoginUser(id, 101L, user, Set.of("video:device:play"));
+        MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("127.0.0.1");
+        ServletRequestAttributes attributes = new ServletRequestAttributes(request);
+        RequestContextHolder.setRequestAttributes(attributes);
+        try { return "Bearer " + context.getBean(TokenService.class).createToken(login); }
+        finally { attributes.requestCompleted(); RequestContextHolder.resetRequestAttributes(); }
+    }
+
+    static void createSchema(JdbcTemplate sql) {
+        sql.execute("CREATE SCHEMA app_user");
+        sql.execute("CREATE TABLE app_user.equipment_base (equipment_id varchar(64) PRIMARY KEY)");
+        sql.execute("CREATE TABLE app_user.video_play_session (session_id varchar(36) PRIMARY KEY, "
+                + "video_id varchar(64) NOT NULL, user_id bigint, anonymous_token_hash varchar(43), "
+                + "mode varchar(16) NOT NULL, status varchar(16) NOT NULL, stream_id varchar(200), proxy_key varchar(300), "
+                + "gb_device_id varchar(20), gb_channel_id varchar(20), media_generation varchar(64), media_server_id varchar(64), start_deadline timestamp, "
+                + "create_time timestamp NOT NULL, last_seen timestamp NOT NULL, end_time timestamp)");
+    }
+
+    private JSONObject prepare() throws Exception {
+        return JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare").contentType(MediaType.APPLICATION_JSON)
+                .content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+    }
+
+    private ResultActions action(JSONObject viewer, String action) throws Exception {
+        return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", viewer.getString("sessionToken")))));
+    }
+
+    /** Injects only the external commit outcome; all statements/rollback/normal commits are real JDBC. */
+    static class CommitFaultTransactions extends DataSourceTransactionManager {
+        boolean failActiveCommit;
+        boolean commitBeforeFailure;
+        boolean failureInjected;
+        CommitFaultTransactions(DataSource ds) { super(ds); setRollbackOnCommitFailure(true); }
+        @Override protected void doCommit(DefaultTransactionStatus status) {
+            if (failActiveCommit && new JdbcTemplate(getDataSource()).queryForObject(
+                    "SELECT COUNT(*) FROM app_user.video_play_session WHERE status='ACTIVE'", Long.class) > 0) {
+                failActiveCommit = false;
+                failureInjected = true;
+                if (commitBeforeFailure) super.doCommit(status);
+                throw new TransactionSystemException("offline injected ACTIVE commit failure");
+            }
+            super.doCommit(status);
+        }
+    }
+
+    static class MutableClock extends Clock {
+        private Instant now = Instant.parse("2026-11-10T08:00:00Z");
+        void advance(long seconds) { now = now.plusSeconds(seconds); }
+        @Override public Instant instant() { return now; }
+        @Override public ZoneId getZone() { return ZoneOffset.UTC; }
+        @Override public Clock withZone(ZoneId zone) { return Clock.fixed(now, zone); }
+    }
+
+    @Configuration
+    @EnableTransactionManagement
+    @Import(CockpitVideoControllerTest.HttpConfiguration.class)
+    static class SqlConfiguration {
+        @Bean @Primary MutableClock sqlClock() { return new MutableClock(); }
+        @Bean @Primary @SuppressWarnings("unchecked") RedisTemplate<String, Object> sqlRedis() {
+            Map<String, Object> values = new HashMap<>();
+            RedisTemplate<String, Object> redis = mock(RedisTemplate.class);
+            ValueOperations<String, Object> operations = mock(ValueOperations.class);
+            when(redis.opsForValue()).thenReturn(operations);
+            when(operations.get(anyString())).thenAnswer(call -> values.get(call.getArgument(0)));
+            doAnswer(call -> { values.put(call.getArgument(0), call.getArgument(1)); return null; })
+                    .when(operations).set(anyString(), any(), anyLong(), any(TimeUnit.class));
+            return redis;
+        }
+        @Bean DataSource dataSource() {
+            DriverManagerDataSource ds = new DriverManagerDataSource();
+            ds.setDriverClassName("org.h2.Driver");
+            ds.setUrl("jdbc:h2:mem:video_" + UUID.randomUUID() + ";MODE=PostgreSQL;DB_CLOSE_DELAY=-1");
+            ds.setUsername("sa"); ds.setPassword(""); return ds;
+        }
+        @Bean CommitFaultTransactions transactionManager(DataSource ds) { return new CommitFaultTransactions(ds); }
+        @Bean @Primary VideoSessionMapper sqlSessions(DataSource ds) throws Exception {
+            MybatisConfiguration config = new MybatisConfiguration();
+            config.setMapUnderscoreToCamelCase(true);
+            config.addMapper(VideoSessionMapper.class);
+            MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
+            factory.setDataSource(ds); factory.setConfiguration(config);
+            SqlSessionFactory built = factory.getObject();
+            return new SqlSessionTemplate(built).getMapper(VideoSessionMapper.class);
+        }
+    }
+}

+ 75 - 32
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoDeviceService.java

@@ -182,19 +182,7 @@ public class VideoDeviceService {
         RANDOM.nextBytes(secret);
         RANDOM.nextBytes(secret);
         String token = Base64.getUrlEncoder().withoutPadding().encodeToString(secret);
         String token = Base64.getUrlEncoder().withoutPadding().encodeToString(secret);
         if (rollbackCleanup == null) throw new ServiceException("视频事务未配置");
         if (rollbackCleanup == null) throw new ServiceException("视频事务未配置");
-        VideoSession session = rollbackCleanup.execute(transaction -> {
-            find(id);
-            VideoSession prepared = new VideoSession();
-            prepared.setSessionId(UUID.randomUUID().toString());
-            prepared.setVideoId(id);
-            prepared.setAnonymousTokenHash(tokenHash(token));
-            prepared.setMode("LIVE");
-            prepared.setStatus("PREPARED");
-            prepared.setCreateTime(LocalDateTime.now(clock));
-            prepared.setLastSeen(prepared.getCreateTime());
-            if (sessions.insert(prepared) != 1) throw new ServiceException("播放会话登记失败");
-            return prepared;
-        });
+        VideoSession session = liveLifecycle.prepare(id, null, tokenHash(token));
         Map<String,Object> data = sessionState(session);
         Map<String,Object> data = sessionState(session);
         data.put("sessionToken", token);
         data.put("sessionToken", token);
         return data;
         return data;
@@ -208,7 +196,6 @@ public class VideoDeviceService {
         return liveLifecycle.start(() -> ownedAnonymous(id, token));
         return liveLifecycle.start(() -> ownedAnonymous(id, token));
     }
     }
 
 
-    @Transactional
     public Map<String,Object> stopAnonymousState(String id, String token) {
     public Map<String,Object> stopAnonymousState(String id, String token) {
         VideoSession current = ownedAnonymous(id, token);
         VideoSession current = ownedAnonymous(id, token);
         if ("PREPARED".equals(current.getStatus()) || current.getMediaGeneration() != null)
         if ("PREPARED".equals(current.getStatus()) || current.getMediaGeneration() != null)
@@ -227,8 +214,14 @@ public class VideoDeviceService {
 
 
     @SuppressWarnings("unchecked")
     @SuppressWarnings("unchecked")
     private Map<String,Object> startSession(String id,VideoRequests.Range range,Long userId,String anonymousTokenHash) {
     private Map<String,Object> startSession(String id,VideoRequests.Range range,Long userId,String anonymousTokenHash) {
+        // Managed or legacy ACTIVE LIVE streams must join through coordinated adoption,
+        // never another blind proxy start. No device lock is held before this I/O path.
+        if(range==null && managedLivePresent(id))return startManagedCompatibility(id,userId,anonymousTokenHash);
         VideoDeviceRecord row=find(id);
         VideoDeviceRecord row=find(id);
         sessions.lockVideo(id);
         sessions.lockVideo(id);
+        // A generation may have been created between the optimistic read and this lock.
+        // Fail safely instead of starting the old physical stream over a new generation.
+        if(range==null && managedLivePresent(id))throw new ServiceException("视频代次已变化,请重试播放");
         String mode=range==null?"LIVE":"PLAYBACK";
         String mode=range==null?"LIVE":"PLAYBACK";
         // Capture under the video lock, before an insert error can abort the DB transaction.
         // Capture under the video lock, before an insert error can abort the DB transaction.
         long existingLive=range==null?activeLiveCount(id,null):0;
         long existingLive=range==null?activeLiveCount(id,null):0;
@@ -266,6 +259,8 @@ public class VideoDeviceService {
             if(!(response instanceof Map))throw new ServiceException("媒体服务没有返回有效播放信息");
             if(!(response instanceof Map))throw new ServiceException("媒体服务没有返回有效播放信息");
             Map<String,Object> data=new HashMap<>((Map<String,Object>)response);
             Map<String,Object> data=new HashMap<>((Map<String,Object>)response);
             session.setStreamId(data.get("stream") instanceof String?(String)data.get("stream"):null);
             session.setStreamId(data.get("stream") instanceof String?(String)data.get("stream"):null);
+            Object mediaServerId = data.remove("mediaServerId");
+            session.setMediaServerId(mediaServerId instanceof String ? (String) mediaServerId : null);
             Object proxyKey=data.remove("proxyKey");
             Object proxyKey=data.remove("proxyKey");
             session.setProxyKey(proxyKey instanceof String?(String)proxyKey:null);
             session.setProxyKey(proxyKey instanceof String?(String)proxyKey:null);
             if(!List.of("url","flv","https_flv","ws_flv","wss_flv","hls","https_hls","webrtc").stream()
             if(!List.of("url","flv","https_flv","ws_flv","wss_flv","hls","https_hls","webrtc").stream()
@@ -290,6 +285,32 @@ public class VideoDeviceService {
         }
         }
     }
     }
 
 
+    private boolean managedLivePresent(String videoId) {
+        return !sessions.selectList(new LambdaQueryWrapper<VideoSession>()
+                .eq(VideoSession::getVideoId,videoId).eq(VideoSession::getMode,"LIVE")
+                .in(VideoSession::getStatus,"STARTING","ACTIVE","CLEANUP_PENDING")
+                .and(q -> q.isNotNull(VideoSession::getMediaGeneration).or().eq(VideoSession::getStatus,"ACTIVE"))).isEmpty();
+    }
+
+    @SuppressWarnings("unchecked")
+    private Map<String,Object> startManagedCompatibility(String videoId,Long userId,String tokenHash) {
+        VideoSession prepared=liveLifecycle.prepare(videoId,userId,tokenHash);
+        java.util.function.Supplier<VideoSession> current=() -> sessions.selectById(prepared.getSessionId());
+        Map<String,Object> state;
+        try {
+            state=liveLifecycle.start(current);
+            if(!"ACTIVE".equals(state.get("status")) || !(state.get("media") instanceof Map))
+                throw new ServiceException("视频尚未就绪,请等待回收后重试");
+        } catch(RuntimeException failure) {
+            try { liveLifecycle.stop(current); } catch(RuntimeException cleanupUnknown) { failure.addSuppressed(cleanupUnknown); }
+            throw failure;
+        }
+        Map<String,Object> result=new HashMap<>((Map<String,Object>)state.get("media"));
+        result.remove("proxyKey"); result.remove("mediaServerId");
+        result.put("sessionId",prepared.getSessionId()); result.put("mode","LIVE");
+        return result;
+    }
+
     private boolean cleanupOnRollback(VideoSession session,boolean nativeStream) {
     private boolean cleanupOnRollback(VideoSession session,boolean nativeStream) {
         if(!TransactionSynchronizationManager.isActualTransactionActive())return false;
         if(!TransactionSynchronizationManager.isActualTransactionActive())return false;
         if(rollbackCleanup==null||!TransactionSynchronizationManager.isSynchronizationActive())
         if(rollbackCleanup==null||!TransactionSynchronizationManager.isSynchronizationActive())
@@ -383,7 +404,6 @@ public class VideoDeviceService {
         sessions.updateById(s);
         sessions.updateById(s);
     }
     }
 
 
-    @Transactional
     public void stop(String id,String token) {
     public void stop(String id,String token) {
         finish(ownedAnonymous(id,token));
         finish(ownedAnonymous(id,token));
     }
     }
@@ -404,8 +424,6 @@ public class VideoDeviceService {
             sessions.updateById(s);
             sessions.updateById(s);
         }
         }
     }
     }
-    @Transactional
-
     public void stop(String id) {
     public void stop(String id) {
         finish(owned(id));
         finish(owned(id));
     }
     }
@@ -414,20 +432,35 @@ public class VideoDeviceService {
     }
     }
 
 
     private void finish(VideoSession session,LocalDateTime expiredBefore) {
     private void finish(VideoSession session,LocalDateTime expiredBefore) {
-        if(!"ACTIVE".equals(session.getStatus()))return;
-        sessions.lockVideo(session.getVideoId());
-        VideoSession current=sessions.selectById(session.getSessionId());
-        if(current==null||!"ACTIVE".equals(current.getStatus()))return;
-        if(expiredBefore!=null&&current.getLastSeen()!=null&&!current.getLastSeen().isBefore(expiredBefore))return;
-        stopMedia(current,activeLiveCount(current.getVideoId(),current.getSessionId()));
-        current.setStatus("STOPPED");
-        current.setEndTime(LocalDateTime.now(clock));
-        sessions.updateById(current);
+        // The old user stop can race with adoption into a managed generation. Decide only
+        // after a fresh locked read, then release this transaction before lifecycle I/O.
+        java.util.function.Supplier<VideoSession> releaseLegacy = () -> {
+            sessions.lockVideo(session.getVideoId());
+            VideoSession current=sessions.selectById(session.getSessionId());
+            if(current==null)return null;
+            if("LIVE".equals(current.getMode()) && (current.getMediaGeneration()!=null
+                    || Set.of("PREPARED", "STARTING", "CLEANUP_PENDING").contains(current.getStatus()))) return current;
+            if(!"ACTIVE".equals(current.getStatus()))return null;
+            if(expiredBefore!=null&&current.getLastSeen()!=null&&!current.getLastSeen().isBefore(expiredBefore))return null;
+            stopMedia(current,activeLiveCount(current.getVideoId(),current.getSessionId()));
+            current.setStatus("STOPPED");
+            current.setEndTime(LocalDateTime.now(clock));
+            if(sessions.updateById(current)!=1)throw new ServiceException("播放会话状态登记失败");
+            return null;
+        };
+        VideoSession managed = rollbackCleanup == null ? releaseLegacy.get()
+                : rollbackCleanup.execute(transaction -> releaseLegacy.get());
+        if(managed!=null) {
+            java.util.function.Supplier<VideoSession> current = () -> sessions.selectById(managed.getSessionId());
+            Map<String,Object> result = expiredBefore==null ? liveLifecycle.stop(current) : liveLifecycle.expire(current);
+            if(expiredBefore==null && "CLEANUP_PENDING".equals(result.get("status")))
+                throw new ServiceException("媒体清理未确认,请等待回收");
+        }
     }
     }
 
 
     private long activeLiveCount(String videoId,String excludingSessionId) {
     private long activeLiveCount(String videoId,String excludingSessionId) {
         return sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,videoId)
         return sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,videoId)
-                .eq(VideoSession::getStatus,"ACTIVE").eq(VideoSession::getMode,"LIVE")
+                .in(VideoSession::getStatus,"STARTING","ACTIVE","CLEANUP_PENDING").eq(VideoSession::getMode,"LIVE")
                 .ne(excludingSessionId!=null,VideoSession::getSessionId,excludingSessionId));
                 .ne(excludingSessionId!=null,VideoSession::getSessionId,excludingSessionId));
     }
     }
 
 
@@ -435,7 +468,13 @@ public class VideoDeviceService {
     private void stopMedia(VideoSession session,long others) {
     private void stopMedia(VideoSession session,long others) {
         if("PLAYBACK".equals(session.getMode()))collector.get("/api/playback/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId()+"/"+safeStream(session.getStreamId()),Map.of());
         if("PLAYBACK".equals(session.getMode()))collector.get("/api/playback/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId()+"/"+safeStream(session.getStreamId()),Map.of());
         else if(others==0&&session.getGbDeviceId()!=null)collector.get("/api/play/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId(),Map.of());
         else if(others==0&&session.getGbDeviceId()!=null)collector.get("/api/play/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId(),Map.of());
-        else if(others==0&&session.getProxyKey()!=null)collector.post("/internal/video/manual/stop",Map.of("key",session.getProxyKey()));
+        else if(others==0&&session.getProxyKey()!=null) {
+            Map<String,Object> body=new LinkedHashMap<>();
+            body.put("key",session.getProxyKey());
+            if(session.getMediaServerId()!=null&&!session.getMediaServerId().isBlank())
+                body.put("mediaServerId",session.getMediaServerId());
+            collector.post("/internal/video/manual/stop",body);
+        }
     }
     }
 
 
     @Transactional
     @Transactional
@@ -462,10 +501,12 @@ public class VideoDeviceService {
         collector.get("/api/playback/"+input.getAction()+"/"+safeStream(s.getStreamId())+suffix,Map.of());
         collector.get("/api/playback/"+input.getAction()+"/"+safeStream(s.getStreamId())+suffix,Map.of());
     }
     }
     @Scheduled(fixedDelay=30000)
     @Scheduled(fixedDelay=30000)
-    @Transactional public void expireSessions() {
+    public void expireSessions() {
         LocalDateTime expiredBefore=LocalDateTime.now(clock).minusSeconds(120);
         LocalDateTime expiredBefore=LocalDateTime.now(clock).minusSeconds(120);
-        for(VideoSession s:sessions.selectList(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getStatus,"ACTIVE").lt(VideoSession::getLastSeen,expiredBefore)))try {
-            finish(s,expiredBefore);
+        // Select nonterminal candidates only; HTTP and the locked recheck use this same policy.
+        for(VideoSession s:sessions.selectList(new LambdaQueryWrapper<VideoSession>()
+                .in(VideoSession::getStatus,"ACTIVE","PREPARED","STARTING","CLEANUP_PENDING")))try {
+            if(liveLifecycle.shouldExpire(s))finish(s,expiredBefore);
         }
         }
         catch(Exception e) {
         catch(Exception e) {
             log.warn("视频会话回收失败,稍后重试: {}",s.getSessionId());
             log.warn("视频会话回收失败,稍后重试: {}",s.getSessionId());
@@ -477,7 +518,9 @@ public class VideoDeviceService {
         return row;
         return row;
     }
     }
     private void ensureIdle(String id) {
     private void ensureIdle(String id) {
-        if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id).eq(VideoSession::getStatus,"ACTIVE"))>0)throw new ServiceException("设备正在播放,请结束播放后再修改或移除");
+        if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id)
+                .in(VideoSession::getStatus,"PREPARED","STARTING","ACTIVE","CLEANUP_PENDING"))>0)
+            throw new ServiceException("设备正在播放或等待回收,请结束播放后再修改或移除");
     }
     }
 
 
     static void requireGbId(String value) {
     static void requireGbId(String value) {

+ 3 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoSession.java

@@ -18,6 +18,9 @@ public class VideoSession {
     private String mode;
     private String mode;
     private String streamId;
     private String streamId;
     private String proxyKey;
     private String proxyKey;
+    @com.fasterxml.jackson.annotation.JsonIgnore
+    @com.alibaba.fastjson2.annotation.JSONField(serialize = false, deserialize = false)
+    private String mediaServerId;
     private String gbDeviceId;
     private String gbDeviceId;
     private String gbChannelId;
     private String gbChannelId;
     private String status;
     private String status;

+ 63 - 12
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/VideoLiveLifecycle.java

@@ -59,12 +59,15 @@ public final class VideoLiveLifecycle {
             VideoSession intent = transaction(() -> {
             VideoSession intent = transaction(() -> {
                 VideoSession row = locked(owned);
                 VideoSession row = locked(owned);
                 if (TERMINAL.contains(row.getStatus())) return row;
                 if (TERMINAL.contains(row.getStatus())) return row;
-                if ("PREPARED".equals(row.getStatus()) && expired(row)) return finish(row, "FAILED");
+                if ("PREPARED".equals(row.getStatus()) && shouldExpire(row)) return finish(row, "FAILED");
                 if ("PREPARED".equals(row.getStatus())) bindGeneration(row, true);
                 if ("PREPARED".equals(row.getStatus())) bindGeneration(row, true);
                 return row;
                 return row;
             });
             });
             if (TERMINAL.contains(intent.getStatus())) return result(intent, null);
             if (TERMINAL.contains(intent.getStatus())) return result(intent, null);
-            if ("CLEANUP_PENDING".equals(intent.getStatus()) || expired(intent)) return stop(owned);
+            if ("CLEANUP_PENDING".equals(intent.getStatus())) return stop(owned);
+            // A new viewer may join a still-ACTIVE generation after its original creation
+            // deadline; do not extend that deadline or treat a join as a new media start.
+            if (shouldExpire(intent)) return expire(owned);
             return invoke("ACTIVE".equals(intent.getStatus()) ? "status" : "start", owned, intent);
             return invoke("ACTIVE".equals(intent.getStatus()) ? "status" : "start", owned, intent);
         });
         });
     }
     }
@@ -73,7 +76,7 @@ public final class VideoLiveLifecycle {
         return outside(() -> {
         return outside(() -> {
             VideoSession row = owned.get();
             VideoSession row = owned.get();
             if (TERMINAL.contains(row.getStatus())) return result(row, null);
             if (TERMINAL.contains(row.getStatus())) return result(row, null);
-            if (expired(row) || "CLEANUP_PENDING".equals(row.getStatus())) return stop(owned);
+            if (shouldExpire(row)) return expire(owned);
             if ("PREPARED".equals(row.getStatus())) return result(row, null);
             if ("PREPARED".equals(row.getStatus())) return result(row, null);
             if (row.getMediaGeneration() == null) row = transaction(() -> {
             if (row.getMediaGeneration() == null) row = transaction(() -> {
                 VideoSession locked = locked(owned); bindGeneration(locked, false); return locked;
                 VideoSession locked = locked(owned); bindGeneration(locked, false); return locked;
@@ -83,10 +86,21 @@ public final class VideoLiveLifecycle {
     }
     }
 
 
     public Map<String,Object> stop(Supplier<VideoSession> owned) {
     public Map<String,Object> stop(Supplier<VideoSession> owned) {
+        return stop(owned, null, false);
+    }
+
+    /** Re-read expiry under the same device lock as heartbeat; a stale scan must not stop a renewed viewer. */
+    public Map<String,Object> expire(Supplier<VideoSession> owned) {
+        return stop(owned, null, true);
+    }
+
+    private Map<String,Object> stop(Supplier<VideoSession> owned, String expectedGeneration, boolean expiredOnly) {
         return outside(() -> {
         return outside(() -> {
             VideoSession intent = transaction(() -> {
             VideoSession intent = transaction(() -> {
                 VideoSession row = locked(owned);
                 VideoSession row = locked(owned);
                 if (TERMINAL.contains(row.getStatus())) return row;
                 if (TERMINAL.contains(row.getStatus())) return row;
+                if (expectedGeneration != null && !Objects.equals(expectedGeneration, row.getMediaGeneration())) return row;
+                if (expiredOnly && !shouldExpire(row)) return row;
                 if ("PREPARED".equals(row.getStatus())) return finish(row, "STOPPED");
                 if ("PREPARED".equals(row.getStatus())) return finish(row, "STOPPED");
                 if (row.getMediaGeneration() == null) bindGeneration(row, false);
                 if (row.getMediaGeneration() == null) bindGeneration(row, false);
                 row.setStatus("CLEANUP_PENDING"); update(row);
                 row.setStatus("CLEANUP_PENDING"); update(row);
@@ -96,7 +110,9 @@ public final class VideoLiveLifecycle {
                         .in(VideoSession::getStatus, "STARTING", "ACTIVE").ne(VideoSession::getSessionId, row.getSessionId()));
                         .in(VideoSession::getStatus, "STARTING", "ACTIVE").ne(VideoSession::getSessionId, row.getSessionId()));
                 return others > 0 ? finish(row, "STOPPED") : row;
                 return others > 0 ? finish(row, "STOPPED") : row;
             });
             });
-            if (TERMINAL.contains(intent.getStatus())) return result(intent, null);
+            if (!"CLEANUP_PENDING".equals(intent.getStatus())
+                    || expectedGeneration != null && !Objects.equals(expectedGeneration, intent.getMediaGeneration()))
+                return result(intent, null);
             return invoke("cancel", owned, intent);
             return invoke("cancel", owned, intent);
         });
         });
     }
     }
@@ -111,7 +127,7 @@ public final class VideoLiveLifecycle {
             resources.add(row);
             resources.add(row);
         if (activating && resources.stream().anyMatch(value -> "CLEANUP_PENDING".equals(value.getStatus())))
         if (activating && resources.stream().anyMatch(value -> "CLEANUP_PENDING".equals(value.getStatus())))
             throw new ServiceException("视频资源回收中,请等待确认");
             throw new ServiceException("视频资源回收中,请等待确认");
-        Set<String> generations = new HashSet<>(), streams = new HashSet<>(), keys = new HashSet<>();
+        Set<String> generations = new HashSet<>(), streams = new HashSet<>(), keys = new HashSet<>(), nodes = new HashSet<>();
         Set<LocalDateTime> deadlines = new HashSet<>();
         Set<LocalDateTime> deadlines = new HashSet<>();
         boolean nativeSource = nativeSource(source);
         boolean nativeSource = nativeSource(source);
         for (VideoSession value : resources) {
         for (VideoSession value : resources) {
@@ -120,15 +136,17 @@ public final class VideoLiveLifecycle {
             if ("GB28181".equals(source.getSourceType()) && (!Objects.equals(source.getGbDeviceId(), value.getGbDeviceId())
             if ("GB28181".equals(source.getSourceType()) && (!Objects.equals(source.getGbDeviceId(), value.getGbDeviceId())
                     || !Objects.equals(source.getGbChannelId(), value.getGbChannelId())))
                     || !Objects.equals(source.getGbChannelId(), value.getGbChannelId())))
                 throw new ServiceException("现存视频来源不一致,需人工核查");
                 throw new ServiceException("现存视频来源不一致,需人工核查");
+            if (value.getMediaServerId() != null) nodes.add(value.getMediaServerId());
             if (value.getStreamId() != null) streams.add(value.getStreamId());
             if (value.getStreamId() != null) streams.add(value.getStreamId());
             if (!"GB28181".equals(source.getSourceType()) && value.getProxyKey() != null) keys.add(value.getProxyKey());
             if (!"GB28181".equals(source.getSourceType()) && value.getProxyKey() != null) keys.add(value.getProxyKey());
             if (value.getMediaGeneration() == null && "ACTIVE".equals(value.getStatus()) && !nativeSource) {
             if (value.getMediaGeneration() == null && "ACTIVE".equals(value.getStatus()) && !nativeSource) {
-                if (!safeStream(value.getStreamId()) || (!"GB28181".equals(source.getSourceType())
+                if (value.getMediaServerId() == null || value.getMediaServerId().isBlank()
+                        || !safeStream(value.getStreamId()) || (!"GB28181".equals(source.getSourceType())
                         && (value.getProxyKey() == null || value.getProxyKey().isBlank())))
                         && (value.getProxyKey() == null || value.getProxyKey().isBlank())))
                     throw new ServiceException("旧视频资源句柄未确认,需人工核查");
                     throw new ServiceException("旧视频资源句柄未确认,需人工核查");
             }
             }
         }
         }
-        if (generations.size() > 1 || deadlines.size() > 1 || streams.size() > 1 || keys.size() > 1)
+        if (generations.size() > 1 || deadlines.size() > 1 || streams.size() > 1 || keys.size() > 1 || nodes.size() > 1)
             throw new ServiceException("现存视频代次或句柄不一致,需人工核查");
             throw new ServiceException("现存视频代次或句柄不一致,需人工核查");
         String generation = generations.isEmpty() ? UUID.randomUUID().toString() : generations.iterator().next();
         String generation = generations.isEmpty() ? UUID.randomUUID().toString() : generations.iterator().next();
         LocalDateTime deadline = deadlines.isEmpty() ? LocalDateTime.ofInstant(clock.instant().plusSeconds(30), ZoneOffset.UTC)
         LocalDateTime deadline = deadlines.isEmpty() ? LocalDateTime.ofInstant(clock.instant().plusSeconds(30), ZoneOffset.UTC)
@@ -139,6 +157,7 @@ public final class VideoLiveLifecycle {
         row.setMediaGeneration(generation); row.setStartDeadline(deadline);
         row.setMediaGeneration(generation); row.setStartDeadline(deadline);
         row.setGbDeviceId("GB28181".equals(source.getSourceType()) ? source.getGbDeviceId() : null);
         row.setGbDeviceId("GB28181".equals(source.getSourceType()) ? source.getGbDeviceId() : null);
         row.setGbChannelId("GB28181".equals(source.getSourceType()) ? source.getGbChannelId() : null);
         row.setGbChannelId("GB28181".equals(source.getSourceType()) ? source.getGbChannelId() : null);
+        if (!nodes.isEmpty()) row.setMediaServerId(nodes.iterator().next());
         if (!streams.isEmpty()) row.setStreamId(streams.iterator().next());
         if (!streams.isEmpty()) row.setStreamId(streams.iterator().next());
         if (!keys.isEmpty()) row.setProxyKey(keys.iterator().next());
         if (!keys.isEmpty()) row.setProxyKey(keys.iterator().next());
         if (activating) row.setStatus("STARTING");
         if (activating) row.setStatus("STARTING");
@@ -154,6 +173,22 @@ public final class VideoLiveLifecycle {
             // A transport failure cannot establish whether this generation was created or stopped.
             // A transport failure cannot establish whether this generation was created or stopped.
         }
         }
         Map<String,Object> observed = response;
         Map<String,Object> observed = response;
+        try {
+            return apply(owned, intent, observed);
+        } catch (RuntimeException persistenceFailure) {
+            // The media effect happened outside SQL: a failed UPDATE or commit is not a failed start.
+            // Stop only this persisted generation after rollback, and re-count current shared viewers.
+            // If storage is still unavailable, the previously committed STARTING/PENDING intent is
+            // deliberately retained for the expiry worker. Never guess a channel-wide stop.
+            if (!"cancel".equals(action)) {
+                try { stop(owned, intent.getMediaGeneration(), false); }
+                catch (RuntimeException cleanupUnknown) { persistenceFailure.addSuppressed(cleanupUnknown); }
+            }
+            throw persistenceFailure;
+        }
+    }
+
+    private Map<String,Object> apply(Supplier<VideoSession> owned, VideoSession intent, Map<String,Object> observed) {
         return transaction(() -> {
         return transaction(() -> {
             VideoSession current = locked(owned);
             VideoSession current = locked(owned);
             if (!Objects.equals(current.getMediaGeneration(), intent.getMediaGeneration()) || TERMINAL.contains(current.getStatus()))
             if (!Objects.equals(current.getMediaGeneration(), intent.getMediaGeneration()) || TERMINAL.contains(current.getStatus()))
@@ -171,6 +206,7 @@ public final class VideoLiveLifecycle {
                 if (!validMedia(binding(current.getVideoId()), media)) return result(current, null);
                 if (!validMedia(binding(current.getVideoId()), media)) return result(current, null);
                 boolean newlyActive = !"ACTIVE".equals(current.getStatus());
                 boolean newlyActive = !"ACTIVE".equals(current.getStatus());
                 current.setStatus("ACTIVE");
                 current.setStatus("ACTIVE");
+                current.setMediaServerId(media.get("mediaServerId") instanceof String ? (String) media.get("mediaServerId") : current.getMediaServerId());
                 current.setStreamId(media.get("stream") instanceof String ? (String) media.get("stream") : null);
                 current.setStreamId(media.get("stream") instanceof String ? (String) media.get("stream") : null);
                 current.setProxyKey(media.get("proxyKey") instanceof String ? (String) media.get("proxyKey") : null);
                 current.setProxyKey(media.get("proxyKey") instanceof String ? (String) media.get("proxyKey") : null);
                 if (newlyActive) current.setLastSeen(LocalDateTime.now(clock));
                 if (newlyActive) current.setLastSeen(LocalDateTime.now(clock));
@@ -193,17 +229,32 @@ public final class VideoLiveLifecycle {
         body.put("startDeadline", row.getStartDeadline().toInstant(ZoneOffset.UTC).toEpochMilli());
         body.put("startDeadline", row.getStartDeadline().toInstant(ZoneOffset.UTC).toEpochMilli());
         if (!nativeSource(binding) && row.getStreamId() != null) {
         if (!nativeSource(binding) && row.getStreamId() != null) {
             Map<String,Object> existing = new LinkedHashMap<>(); existing.put("stream", row.getStreamId());
             Map<String,Object> existing = new LinkedHashMap<>(); existing.put("stream", row.getStreamId());
+            if (row.getMediaServerId() != null) existing.put("mediaServerId", row.getMediaServerId());
             if (!"GB28181".equals(binding.getSourceType()) && row.getProxyKey() != null) existing.put("proxyKey", row.getProxyKey());
             if (!"GB28181".equals(binding.getSourceType()) && row.getProxyKey() != null) existing.put("proxyKey", row.getProxyKey());
             body.put("existingMedia", existing);
             body.put("existingMedia", existing);
         }
         }
         return body;
         return body;
     }
     }
 
 
-    private boolean expired(VideoSession row) {
-        if ("STARTING".equals(row.getStatus())) return row.getStartDeadline() == null
-                || !clock.instant().isBefore(row.getStartDeadline().toInstant(ZoneOffset.UTC));
-        return ("PREPARED".equals(row.getStatus()) || "ACTIVE".equals(row.getStatus()))
-                && (row.getLastSeen() == null || row.getLastSeen().isBefore(LocalDateTime.now(clock).minusSeconds(120)));
+    private boolean hasActivePeer(VideoSession row) {
+        return "STARTING".equals(row.getStatus()) && row.getMediaGeneration() != null
+                && sessions.selectCount(new LambdaQueryWrapper<VideoSession>()
+                .eq(VideoSession::getVideoId,row.getVideoId()).eq(VideoSession::getMode,"LIVE")
+                .eq(VideoSession::getMediaGeneration,row.getMediaGeneration()).eq(VideoSession::getStatus,"ACTIVE")
+                .ge(VideoSession::getLastSeen, LocalDateTime.now(clock).minusSeconds(120))
+                .ne(VideoSession::getSessionId,row.getSessionId())) > 0;
+    }
+
+    /** One expiry policy for HTTP, scan selection and the locked recheck. Joining a healthy
+     * generation does not restart its media deadline; once the peer leaves, that deadline applies.
+     * The joining viewer's own lease still bounds an abandoned/unknown request. */
+    public boolean shouldExpire(VideoSession row) {
+        if ("CLEANUP_PENDING".equals(row.getStatus())) return true;
+        boolean leaseExpired = row.getLastSeen() == null
+                || row.getLastSeen().isBefore(LocalDateTime.now(clock).minusSeconds(120));
+        if ("STARTING".equals(row.getStatus())) return leaseExpired || (row.getStartDeadline() == null
+                || !clock.instant().isBefore(row.getStartDeadline().toInstant(ZoneOffset.UTC))) && !hasActivePeer(row);
+        return ("PREPARED".equals(row.getStatus()) || "ACTIVE".equals(row.getStatus())) && leaseExpired;
     }
     }
 
 
     private VideoSession locked(Supplier<VideoSession> owned) {
     private VideoSession locked(Supplier<VideoSession> owned) {