limited-planet-15554
11/21/2025, 5:22 AMRoomInputOptions.close_on_disconnect=False)
3. rotate_segment called while previous segment is still being rotated"
이후에 shutdown callback이 실행되지 않는데, 이유를 알수 있을까?tall-airline-16756
11/21/2025, 5:22 AMtall-airline-16756
11/21/2025, 5:23 AMRoomInputOptions.close_on_disconnect=False)"는 이 동작을 말합니다.
• 세션이 자동 종료되면 shutdown callback이 등록되기 전이거나, 종료 절차가 비동기 작업(예: 세그먼트 회전/egress)으로 인해 중단되어 콜백이 실행되지 않을 수 있습니다.
• "rotate_segment called while previous segment is still being rotated" 메시지는 egress/segment 처리 중에 강제 종료가 발생해 정리 루틴이 완료되지 않았음을 나타냅니다. 이 경우 shutdown callback이 실행되지 않거나 생략될 가능성이 큽니다.
권장 확인사항(간단 체크리스트)
1. RoomInputOptions.close_on_disconnect 값 확인 — 기본은 True. 자동 종료를 원치 않으면 RoomInputOptions(close_on_disconnect=False) 로 설정하세요.
2. shutdown callback 등록 시점 — 엔트리포인트(세션 시작 직후)에 `ctx.add_shutdown_callback(...)`를 등록했는지 확인하세요.
3. Egress/segment 정리 보장 — 세션 종료 전 현재 진행 중인 세그먼트 회전이나 egress 작업이 완료되었는지 확인하고, 필요하면 종료 전에 해당 작업을 await 하거나 egress.stop() 같은 정리 호출을 추가하세요.
4. 로그 순서와 타임스탬프 확인 — participant_disconnect → 자동 close → rotate_segment 충돌 순서인지, 혹은 rotate 실패 뒤 disconnect가 발생했는지 파악하면 원인 좁히는 데 도움이 됩니다.
원하시면 제가 도와드릴 수 있는 것
• 현재 RoomInputOptions 설정과 shutdown callback이 등록된 코드 위치(간단한 코드 스니펫)를 보내주시면 더 정확한 원인 분석 및 수정 예시를 드리겠습니다.
• 진행 중인 egress/segment 관련 로그(관련 에러/타임스탬프)도 함께 보내주시면 어떤 정리 로직이 빠졌는지 구체적으로 안내해드리겠습니다. Sources: How to capture real-time agent transcriptions during conversations | Automation & Knowledge Management Tools | livekit/livekit_composite | DeepW... | Session recording and transcripts | LiveKit Docs | Egress examples | LiveKit docs | Observability data hooks | LiveKit docslimited-planet-15554
11/21/2025, 5:29 AMlimited-planet-15554
11/21/2025, 5:29 AMlimited-planet-15554
11/21/2025, 5:29 AMlimited-planet-15554
11/21/2025, 5:29 AMtall-airline-16756
11/21/2025, 5:30 AMengine: connection error: engine is closed, failed to send transcription, room closed: channel closed)은 음성/텍스트를 전송하려 할 때 이미 WebRTC 엔진(방 연결)이 닫혀 있음을 의미합니다.
• 참가자 연결 해제가 트리거되어 방 또는 엔진이 먼저 종료되면, 이후에 남아 있는 비동기 작업(전사 전송, 세그먼트 회전 등)이 실행되다가 위 에러가 발생하거나 shutdown callback이 정상 실행되지 않습니다.
• 로그의 "rotate_segment called while previous segment is still being rotated"는 egress/세그먼트 처리와 종료가 경쟁 상태(race)에 있다는 신호입니다.
권장 조치(우선순위별) 1) participant disconnect 발생 즉시 전사 전송 중단
• participant_disconnected 이벤트 핸들러에서 STT 전송/쓰기 작업을 즉시 닫고(또는 취소) 새로운 전송 시도를 막으세요.
• 예: 전송을 담당하는 writer/task가 있다면 이벤트에서 await writer.close() 또는 task.cancel() 수행.
2) shutdown callback 등록 위치 확인
• 세션 시작(엔트리 포인트) 직후 `ctx.add_shutdown_callback(...)`를 등록해 종료 로직이 항상 설치되도록 하세요.
• shutdown 내부에서는 엔진이 이미 닫혔을 경우를 대비해 `ConnectionError`를 잡아 무시하도록 처리하세요.
3) 전송 시점에 엔진 상태 확인
• publish/ write 직전에 연결 상태(예: if room.is_connected: 같은 플래그 또는 try/except) 확인 후, 닫혀 있으면 전송하지 않도록 하세요.
• 예외 처리로 `PublishTranscriptionError`/`ConnectionError`를 잡아 로깅만 하고 재시도나 후속 작업을 차단합니다.
4) egress/rotate 작업 정리 보장
• 세그먼트 회전이나 egress가 진행 중이면 세션 종료 전에 해당 작업을 안전히 완료하거나 중단하도록 await/정리 로직을 추가하세요.
• 필요시 await egress.stop() 또는 관련 정리 API를 호출해 중간 상태를 정리하세요.
5) 자동 종료 동작 조정(옵션)
• 자동으로 세션이 닫히는 동작을 원치 않으면 `RoomInputOptions(close_on_disconnect=False)`로 설정해 자동 종료를 방지하고, 종료는 명시적 호출(예: session.aclose() 또는 ctx.shutdown())으로 제어하세요.
추가로 제가 도와드릴 수 있는 것
• 관련 코드(특히 participant_disconnected 핸들러, shutdown callback 등록 부분, 전사 publish/write 부분) 짧게 붙여주시면 정확히 어느 지점에서 race가 나는지 보고 구체적인 코드 수정을 제안드리겠습니다.
• 최근 타임스탬프가 있는 로그(disconnect → rotate_segment → publish 에러 순서)를 공유해주시면 문제 발생 순서를 더 정확히 분석하겠습니다.limited-planet-15554
11/21/2025, 5:31 AMtall-airline-16756
11/21/2025, 5:31 AM# 엔트리포인트: 세션/룸 생성 직후에 등록
def register_shutdown(ctx, agent):
async def on_shutdown():
# 전사 writer가 있으면 닫기 시도 (engine 닫힘 예외 안전 처리)
try:
if getattr(agent, "transcription_writer", None):
await agent.transcription_writer.close()
agent.transcription_writer = None
except ConnectionError:
# 엔진이 이미 닫혔으면 무시
pass
# 추가 정리 로직(예: egress 정지)도 동일하게 감싸기
try:
if getattr(agent, "egress", None):
await agent.egress.stop()
except ConnectionError:
pass
ctx.add_shutdown_callback(on_shutdown)
• 설명: 엔트리포인트(세션 시작 직후)에 `ctx.add_shutdown_callback(...)`로 등록합니다. shutdown 내부에서 `ConnectionError`를 잡아 엔진이 이미 닫혀 있어도 예외가 흐르지 않도록 합니다.
4) egress / 세그먼트 회전 정리 — 진행 중 작업 완료 대기 또는 안전하게 중단
import asyncio
async def stop_egress_gracefully(agent, timeout=5.0):
"""
- 진행 중인 egress/segment 회전을 안전하게 정리하려 시도.
- timeout 내 완료되지 않으면 강제 중단.
"""
if not getattr(agent, "egress_task", None):
return
task = agent.egress_task
# 1) 먼저 정상 종료 신호 전송 (egress API가 있다면 호출)
try:
if getattr(agent, "egress", None):
await agent.egress.stop() # egress 라이브러리의 안전한 정지 호출
except ConnectionError:
# 엔진 닫힘으로 이미 실패한 경우 무시
return
# 2) 내부 작업(task)가 끝날 때까지 대기하되 timeout 적용
try:
await asyncio.wait_for(task, timeout=timeout)
except asyncio.TimeoutError:
# 타임아웃: 작업이 끝나지 않으면 강제 취소
if not task.done():
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# participant_disconnected 핸들러에서 호출 예
@ctx.room.on("participant_disconnected")
async def on_participant_disconnected(participant):
# 즉시 STT 전송 중지
if getattr(agent, "transcription_writer", None):
try:
await agent.transcription_writer.close()
except ConnectionError:
pass
# egress 정리 시도 (짧은 타임아웃으로 빠르게 정리)
await stop_egress_gracefully(agent, timeout=3.0)
• 설명:
◦ 우선 egress의 공식 정지 API(egress.stop() 등)를 호출해 정상 종료를 시도합니다.
◦ 내부적으로 egress 작업이 백그라운드 태스크로 실행 중이면 해당 태스크를 `await`하되, 타임아웃을 두어 무한 대기를 방지합니다.
◦ 타임아웃 시 `task.cancel()`로 강제 중단하고 `CancelledError`를 안전하게 처리합니다.
원하시면 귀하 코드의 실제 변수/구조를 붙여주시면 예시를 그에 맞춰 더 구체적으로 맞춰드리겠습니다.limited-planet-15554
11/21/2025, 7:52 AMtall-airline-16756
11/21/2025, 7:52 AMPublishTranscriptionError: engine: connection error: engine is closed 에러가 왜 나는지 간단명료하게 설명드립니다.
핵심 원인
• 이 에러는 전사를 전송하려 시도할 때 방의 WebRTC 엔진(연결)이 이미 닫혀 있어서 전송이 실패했음을 뜻합니다.
• 일반적으로 participant(또는 마지막 non-agent 참가자) 연결 해제 → 방/엔진이 닫힘 → 그 이후에 전사 publish 시도가 일어나면 발생합니다.
자주 발생하는 시나리오
• participant_disconnect 이벤트로 방이 자동 종료되어 엔진이 닫힌 뒤에도 백그라운드 작업(전사 전송, 세그먼트 회전 등)이 남아 있어 전송 호출이 발생하는 경우.
• shutdown 또는 정리 로직이 늦게 실행되거나, shutdown 내부에서 전송을 시도하는 경우.
• 전사 전송을 담당하는 task/스트림이 participant_disconnect 시점에 취소/중단되지 않아 이후에도 write/publish를 시도하는 경우.
간단한 대응책(즉시 적용 권장)
1. participant_disconnect 이벤트에서 즉시 전사 전송을 닫기/취소하기
◦ writer.close() 또는 stt task.cancel()을 호출해서 이후 publish 시도 자체를 막습니다.
1. shutdown 콜백은 엔진이 닫혀 있어도 안전하게 동작하도록 예외 처리하기
◦ `ConnectionError`/`PublishTranscriptionError`를 잡아 무시하거나 로깅만 하세요.
1. publish 전에 연결 상태 확인 또는 예외 처리 강화
◦ publish 호출을 try/except로 감싸고, 실패하면 재시도 대신 안전하게 중단합니다.
1. 필요시 자동 종료 비활성화 후 명시적 종료 사용
◦ `RoomInputOptions(close_on_disconnect=False)`로 자동 닫힘을 막고, 원하는 시점에 정리 로직을 실행하면 race를 줄일 수 있습니다.
원하시면 지금 사용 중인 participant_disconnected 핸들러와 전사 publish 코드(간단한 스니펫)를 보내주세요. 해당 코드에 맞춰 정확한 수정 예시를 드리겠습니다.limited-planet-15554
11/21/2025, 7:56 AMtall-airline-16756
11/21/2025, 7:57 AMparticipant_disconnected 핸들러 코드가 왜 전사(publish) 실패로 이어지는지와 수정 권장사항을 간단히 안내드립니다.
문제 요약
• 현재 핸들러는 로그 기록과 `job_ctx.shutdown(reason="Session ended")`만 호출합니다.
• `job_ctx.shutdown()`이 실행되더라도 즉시 방의 WebRTC 엔진이 닫히고, 백그라운드에서 남아있던 전사 쓰기/퍼블리시 시도가 그 직후에 발생하면 engine is closed 오류가 납니다.
• 즉, 종료 신호는 보냈지만 전사 전송을 안전하게 중단하거나 관련 태스크를 취소/정리하지 않아 race가 발생합니다.
권장 수정(간단 코드 조각) 1) participant_disconnected에서 전사 관련 writer/task를 즉시 닫거나 취소한 뒤 shutdown 호출
@room.on("participant_disconnected")
async def _on_participant_disconnected(event: rtc.RemoteParticipant):
logger.bind(...).info("Participant disconnected")
session.history.add_message(...)
# 1) 전사 writer/작업 안전 종료
if getattr(session, "transcription_writer", None):
try:
await session.transcription_writer.close()
except ConnectionError:
pass
session.transcription_writer = None
if getattr(session, "stt_task", None) and not session.stt_task.done():
session.stt_task.cancel()
try:
await session.stt_task
except asyncio.CancelledError:
pass
# 2) 짧은 정리 대기(옵션)
# await stop_egress_gracefully(session, timeout=2.0)
# 3) 세션 종료 호출 (이제 안전하게 shutdown)
await job_ctx.shutdown(reason="Session ended")
2) 엔트리포인트에서 shutdown callback 등록 — shutdown 시 추가 정리 보장
def register_shutdown_callbacks(ctx, session):
async def on_shutdown():
# 재시도 없이 안전히 닫기만 함
try:
if getattr(session, "transcription_writer", None):
await session.transcription_writer.close()
except ConnectionError:
pass
# egress 정리(있으면)
try:
if getattr(session, "egress", None):
await session.egress.stop()
except ConnectionError:
pass
ctx.add_shutdown_callback(on_shutdown)
추가 권장
• publish 호출 직전에도 try/except로 `PublishTranscriptionError`/`ConnectionError`를 잡아 재시도 대신 안전히 중단하세요.
• 자동으로 방을 닫히는 동작을 원치 않으면 `RoomInputOptions(close_on_disconnect=False)`로 설정하고, 필요할 때만 명시적으로 방 삭제/종료(예: ctx.api.room.delete_room(...))하세요.
• 로그 타임스탬프 순서(Disconnect → writer close → publish 시도)를 확인해 실제 race 발생 지점을 정확히 파악하면 더 정밀한 수정이 가능합니다.
원하시면 현재 코드에서 `transcription_writer`/`stt_task` 정의 부분과 엔트리포인트(또는 shutdown 콜백 등록 코드)를 붙여주시면, 귀하 코드에 맞춘 정확한 수정안을 드리겠습니다.
Sources: Operational Best Practices | livekit/livekit_composite | DeepWiki | Agents telephony integration | LiveKit Docslimited-planet-15554
11/21/2025, 7:58 AMtall-airline-16756
11/21/2025, 7:58 AMentrypoint 코드와 shutdown callback 등록 흐름에 맞춰, 엔트리포인트에서 shutdown을 안전하게 등록하고 participant_disconnect 시 전사/egress 정리를 보장하는 구체적 예시와 설명을 드립니다.
핵심 포인트(간단)
• shutdown 콜백은 엔트리포인트에서 반드시 등록해야 합니다(이미 하셨습니다).
• participant_disconnect 시점에 전사 쓰기/백그라운드 작업을 즉시 닫거나 취소해야 engine is closed 에러를 방지할 수 있습니다.
• shutdown 콜백 안에서는 엔진이 닫혔을 가능성을 고려해 `ConnectionError`/`PublishTranscriptionError`를 무시하도록 안전하게 처리하세요.
권장 예시 코드 (entrypoint, shutdown 콜백 등록, participant_disconnected 처리 포함)
import asyncio
import json
async def entrypoint(ctx: JobContext):
# 1) 메타데이터 파싱
try:
dial_info = json.loads(ctx.job.metadata)
except json.JSONDecodeError as e:
logger.bind(...).opt(exception=e).error("Outbound call metadata invalid")
await ctx.shutdown() # 비동기 호출로 변경
return
# 2) 세션 관련 객체 초기화 (예: transcription writer, stt_task, egress_task)
session = SimpleNamespace()
session.transcription_writer = None
session.stt_task = None
session.egress_task = None
ctx.session = session
# 3) shutdown callback 등록 (엔트리포인트 초기에 반드시)
async def shutdown_callback(reason: str):
logger.info("shutdown callback running", reason=reason)
# 안전하게 전사 writer 닫기
try:
if getattr(session, "transcription_writer", None):
await session.transcription_writer.close()
session.transcription_writer = None
except ConnectionError:
pass
# egress 정리 시도
try:
if getattr(session, "egress", None):
await session.egress.stop()
except ConnectionError:
pass
# 백그라운드 태스크 취소
for tname in ("stt_task", "egress_task"):
task = getattr(session, tname, None)
if task and not task.done():
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
ctx.add_shutdown_callback(shutdown_callback)
# 4) 참가자 이벤트 핸들러 등록 (비동기 핸들러 권장)
@ctx.room.on("participant_disconnected")
async def _on_participant_disconnected(event):
logger.bind(...).info("Participant disconnected")
# 즉시 전사 전송 중지
try:
if getattr(session, "transcription_writer", None):
await session.transcription_writer.close()
session.transcription_writer = None
except ConnectionError:
pass
# STT 백그라운드 태스크 취소
if getattr(session, "stt_task", None) and not session.stt_task.done():
session.stt_task.cancel()
try:
await session.stt_task
except asyncio.CancelledError:
pass
# 짧은 정리 대기(옵션)
try:
await asyncio.wait_for(_stop_egress_gracefully(session), timeout=2.0)
except asyncio.TimeoutError:
pass
# 안전하게 세션 종료 요청
await ctx.shutdown(reason="Session ended")
# 나머지 엔트리포인트 로직...
보조 함수: egress 정리 예시
async def _stop_egress_gracefully(session):
# egress API로 정상 중지 시도
try:
if getattr(session, "egress", None):
await session.egress.stop()
except ConnectionError:
return
# 백그라운드 egress_task가 있으면 대기
task = getattr(session, "egress_task", None)
if not task:
return
try:
await asyncio.wait_for(task, timeout=3.0)
except asyncio.TimeoutError:
if not task.done():
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
추가 권장사항
• 현재 코드에서 `ctx.shutdown()`을 synchronous하게 호출하고 있다면 `await ctx.shutdown()`으로 변경하세요. 비동기 컨텍스트에서 즉시 반환하면 정리 작업 흐름이 깨질 수 있습니다.
• publish 직전에도 항상 try/except로 `PublishTranscriptionError`/`ConnectionError`를 잡아 재시도 대신 안전히 중단하도록 하세요.
• 자동으로 방이 닫히는 것을 원치 않으면 `RoomInputOptions(close_on_disconnect=False)`를 사용하고 명시적으로 방을 삭제할지(ctx.api.room.delete_room) 결정하세요.
원하시면 session 객체의 실제 정의(특히 transcription_writer, stt_task, `egress`가 어떻게 생성되는지)나 현재 사용 중인 publish 코드 스니펫을 붙여주세요. 그에 맞춰 더 정확한 수정안을 드리겠습니다.limited-planet-15554
11/21/2025, 8:04 AMtall-airline-16756
11/21/2025, 8:04 AMctx.room.local_participant.send_text(..., topic="lk.transcription") 같은 방식으로 전송하거나, RoomOutputOptions로 전사 포워딩을 활성화해야 합니다.
• 따라서 participant_disconnect 시점에서 닫아야 할 대상은 (1) 당신이 직접 만든 전사 출력을 담당하는 task/object, 또는 (2) 백그라운드 STT 태스크입니다 — 존재하는 이름으로 참조/취소해야 합니다.
할 일(간단 체크리스트)
• 전사 전송을 어디서/어떻게 하고 있는지 알려주세요: `send_text(...)`를 쓰는지, 외부 STT를 background task로 돌리는지, 혹은 LiveKit의 자동 전사 포워딩을 사용하는지.
• 전사를 담당하는 객체/태스크 이름(예: stt_task, publish_task, writer 등)을 공유해 주세요. 그러면 participant_disconnected와 shutdown 콜백에서 정확히 무엇을 닫고 취소해야 할지 코드로 보여드리겠습니다.
간단 예시(당신의 구현이 send_text 기반일 때)
# 전사 전송을 background task에서 수행한다면
async def stt_loop(session):
while True:
text = await get_next_transcript()
try:
await session.room.local_participant.send_text(text, topic="lk.transcription")
except Exception:
break
# entrypoint에서
session.stt_task = asyncio.create_task(stt_loop(session))
# participant_disconnected에서
if getattr(session, "stt_task", None):
session.stt_task.cancel()
try:
await session.stt_task
except asyncio.CancelledError:
pass
원하시면 현재 전사 전송 관련 코드(전사 생성/퍼블리시 부분) 붙여주시면 그 코드에 맞춰 정확한 cleanup 예시를 만들어 드리겠습니다.
Sources: Text and transcriptions | LiveKit docs | Sending text | LiveKit docs