Participant left 05792e02-9cd7-494d-bf59-9873158fa...
# ask-ai
l
Participant left 05792e02-9cd7-494d-bf59-9873158fa115. Non-agent participants remaining: 0 All participants left 05792e02-9cd7-494d-bf59-9873158fa115. Will delete room. Deleting room 05792e02-9cd7-494d-bf59-9873158fa115 as only agent remains Stopping recording for room 05792e02-9cd7-494d-bf59-9873158fa115, egress_id: EG_LJkVMYqRMnTT Egress stop response: egress_id: "EG_LJkVMYqRMnTT" room_id: "RM_VEd7rnS66nWi" status: EGRESS_ABORTED room_composite { room_name: "05792e02-9cd7-494d-bf59-9873158fa115" layout: "speaker" preset: H264_720P_30 file_outputs { file_type: MP4 filepath: "05792e02-9cd7-494d-bf59-9873158fa115.mp4" s3 { access_key: "{access_key}" secret: "{secret}" region: "ap-south-1" bucket: "physical-consultation" } } } file { filename: "05792e02-9cd7-494d-bf59-9873158fa115.mp4" started_at: 1764915053430745331 ended_at: 1764915053430745331 } error: "Stop called before pipeline could start" started_at: 1764914998327424312 ended_at: 1764915053430598848 room_name: "05792e02-9cd7-494d-bf59-9873158fa115" file_results { filename: "05792e02-9cd7-494d-bf59-9873158fa115.mp4" started_at: 1764915053430745331 ended_at: 1764915053430745331 } updated_at: 1764915053430598848 details: "End reason: StopEgress API" error_code: 412 Egress status: 5 Egress error: Stop called before pipeline could start Recording was aborted/failed for room 05792e02-9cd7-494d-bf59-9873158fa115, no file uploaded No recording URL available for room 05792e02-9cd7-494d-bf59-9873158fa115 Room 05792e02-9cd7-494d-bf59-9873158fa115 deleted successfully can you provide solution for this
t
Thanks for reaching out, Pavan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I reviewed the room logs you pasted (room 05792e02-9cd7-494d-bf59-9873158fa115). The recording aborted with error "Stop called before pipeline could start" (status EGRESS_ABORTED, error_code 412). That means the egress process was stopped or the room deleted before the recording pipeline (headless Chrome + media connection) had time to initialize, so no file was produced. What you can do to prevent this: • Start egress earlier (ideally when the first participant joins) so the pipeline has time to boot. • Do not delete the room or call StopEgress immediately when the last participant leaves. Wait for the egress lifecycle events. • Rely on webhooks: ◦ Wait for the
egress_started
webhook (confirms recording has actually begun) before allowing room deletion or calling StopEgress. ◦ Only delete the room after
egress_ended
(or after you confirm the file uploaded). • If your workflow auto-deletes rooms when participants leave, add a short delay (start with 5–10 seconds) before deletion, or keep the agent connection alive until you see `egress_started`/`egress_ended`. • If you call StopEgress programmatically, ensure it isn’t triggered by the same event that deletes the room; stop only after
egress_started
and desired recording duration. If you'd like, tell me: • How you currently trigger egress and room deletion (webhook or backend logic), and • Whether you already use `egress_started`/`egress_ended` webhooks. I can then suggest exactly where to add the delay or webhook checks in your flow. Sources: Egress API | LiveKit docs | Recording and export | LiveKit docs | Webhooks | LiveKit docs
l
can you provide solution
t
You're seeing "Stop called before pipeline could start" because egress was stopped (or the room deleted) before the recording pipeline finished initializing. Here's a concise, actionable solution you can implement now. 1. Start egress earlier • Kick off Room Composite egress as soon as the session is established (preferably when the first user joins), not only when the last participant is present. 1. Use webhooks to gate deletion/stop • Wait for the
egress_started
webhook before allowing any room deletion or calling
StopEgress
. • Only delete the room after receiving
egress_ended
(or confirming file upload). 1. Prevent premature room deletion • If your app auto-deletes rooms when non-agent participants leave, add logic to: ◦ Keep the agent (or a lightweight headless participant) in the room until
egress_started
is received, OR ◦ Add a fixed grace period (start with 5–10 seconds) before deleting the room / calling
StopEgress
. 1. Ensure StopEgress timing is safe • Do not call
StopEgress
immediately after starting egress. Wait for
egress_started
and the intended recording duration to complete, then call
StopEgress
(or rely on the agent to leave after
egress_ended
). 1. Test with instrumentation • Add logs for: egress request timestamp,
egress_started
webhook timestamp,
egress_ended
webhook timestamp, room-deletion/StopEgress timestamp. Confirm
egress_started
occurs before any stop/delete action. If you share how you currently trigger egress and room deletion (webhook-driven, backend cron, or agent lifecycle), I’ll give exact code placements or pseudocode to add the webhook checks/delay. Would you like that?
l
@app.get("/join/{room_name}") async def join_meeting( room_name: str, background_tasks: BackgroundTasks, name: Optional[str] = Query(None, description="Participant name (auto-generated if not provided)"), doctor: Optional[str] = Query(None, description="Doctor ID"), org: Optional[str] = Query(None, description="Organization ID") ): try: # Validate environment variables print(f"Joining room: {room_name} with name: {name} doctor: {doctor} org: {org}") if not LIVEKIT_API_KEY or not LIVEKIT_API_SECRET or not LIVEKIT_URL: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="LiveKit configuration is missing. Please check environment variables." ) # Get participant name from query parameter or generate one participant_name = name or f"User_{random.randint(1000, 9999)}" # Generate UNIQUE identity for THIS visitor participant_identity = f"user_{int(time.time())}_{random.randint(100000, 999999)}" # Generate token for this specific participant token = api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET) \ .with_identity(participant_identity) \ .with_name(participant_name) \ .with_grants(api.VideoGrants( room_join=True, room=room_name, )).to_jwt() # Initialize chat storage and room metadata for this room if room_name not in chat_storage: chat_storage[room_name] = [] # Store room metadata including appointment details room_metadata[room_name] = { 'appointment_id': room_name, # room_name is the appointmentId 'patient_id': name, # name parameter is the patientId 'doctor_id': doctor, 'organization_id': org, 'call_started_at': datetime.now() } # Start chat listener as background task background_tasks.add_task(chat_listener_task, room_name) # Create room using LiveKit API async with api.LiveKitAPI(LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET) as lkapi: # Create the room explicitly try: room_info = await lkapi.room.create_room( api.CreateRoomRequest(name=room_name) ) except Exception as e: # Room might already exist, which is fine pass # Start recording with S3 upload using async context manager print(f"Starting recording for room: {room_name}") async with api.LiveKitAPI(LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET) as lkapi: egress_request = api.RoomCompositeEgressRequest( room_name=room_name, layout="speaker", preset=api.EncodingOptionsPreset.H264_720P_30, audio_only=False, file_outputs=[api.EncodedFileOutput( file_type=api.EncodedFileType.MP4, filepath=f"{room_name}.mp4", s3=api.S3Upload( access_key=settings.S3_KEY_ID, secret=settings.S3_KEY_SECRET, region=settings.S3_REGION, bucket=settings.S3_BUCKET, ) )] ) egress_info = await lkapi.egress.start_room_composite_egress(egress_request) # Store the egress ID for this room active_recordings[room_name] = egress_info.egress_id return JSONResponse( status_code=status.HTTP_200_OK, content={ 'token': token, 'egressId': egress_info.egress_id, 'success': True }, headers={"Cache-Control": "no-store"} ) except HTTPException: raise except Exception as e: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to join meeting: {str(e)}" ) async def stop_recording_and_get_url(room_name: str) -> Optional[str]: """Get the recording URL for a room without stopping it - just construct the S3 URL""" try: if room_name not in active_recordings: print(f"No active recording found for room {room_name}") # Still return the URL since recording might have already been stopped or file exists recording_url = f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4" print(f"Returning constructed URL: {recording_url}") return recording_url egress_id = active_recordings[room_name] print(f"Getting recording URL for room {room_name}, egress_id: {egress_id}") # Just construct and return the S3 URL based on the known filename pattern # The recording will be saved to S3 with the room_name as filename recording_url = f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4" # Remove from active recordings tracking if room_name in active_recordings: del active_recordings[room_name] print(f"Recording URL for room {room_name}: {recording_url}") return recording_url except Exception as e: print(f"Error getting recording URL for room {room_name}: {e}") import traceback traceback.print_exc() # Still return the URL even if there's an error recording_url = f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4" # Clean up tracking if room_name in active_recordings: del active_recordings[room_name] return recording_url check this code it is not saving recording in aws
t
Thanks — I reviewed your code and logs. The root cause is that egress is being stopped (or the room deleted) before the Room Composite pipeline finishes initializing, so the recording never uploads to S3. Below are concise, targeted fixes and exact code places to change. 1) Start egress earlier and keep the room alive • Start egress as soon as the room is created or the first participant joins (you already start on join — keep doing that). • Do not delete the room or remove the agent immediately when participants leave. Ensure the agent stays until recording completes. 2) Gate deletion/StopEgress on webhooks • Add webhook handlers for
egress_started
and
egress_ended
. Only delete the room or remove the agent after you receive
egress_ended
(or at least after
egress_started
and desired duration). • Place webhook handling on your backend; do not rely on timing alone. 3) Where to change your code (precise places) • After starting egress: ◦ Store
egress_info.egress_id
(you already do this in
active_recordings
) and do NOT delete the room or call StopEgress until webhook confirms
egress_started
and later
egress_ended
. • In the code path that deletes rooms when participants leave: ◦ If you auto-delete on last non-agent participant leaving, add logic: ▪︎ If room in `active_recordings`: delay deletion until
egress_ended
webhook or at least wait 10 seconds after
egress_started
. ▪︎ Or keep an agent/keepalive participant in the room until egress completes. • For StopEgress calls: ◦ Ensure StopEgress is triggered only after
egress_started
and after desired recording time, or rely on
egress_ended
to signal completion. 4) Fix S3 URL construction (bug in your string) • Your constructed URL is malformed. Replace: ◦ f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4" • With: ◦ f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4" • Use that only after
egress_ended
confirms success; otherwise the file may not exist. 5) Add logging/instrumentation (minimal) • Log timestamps for: ◦ egress start request ◦
egress_started
webhook receipt ◦ any StopEgress call or room deletion ◦
egress_ended
webhook receipt • This will prove ordering and show if Stop/Delete happens before egress can initialize. 6) Quick test plan • Start a test room, start egress, then: ◦ Wait for
egress_started
webhook (confirm in logs). ◦ Wait a few seconds, then call StopEgress or let egress finish. ◦ Confirm
egress_ended
webhook and S3 file exists at the corrected URL. If you want, I can: • Provide a small webhook handler snippet (FastAPI) to process
egress_started
/
egress_ended
and tie it to your room-deletion logic, or • Show the exact code changes to your leave/delete logic to add the 10-second grace and webhook checks. Which would you prefer?
l
can you propvide code for appropriate solution
t
Below is a concise FastAPI-focused code patch you can drop into your service to: • Start Room Composite egress on join (you already do this). • Verify and handle
egress_started
/
egress_ended
webhooks. • Delay/delete rooms only after egress completes. • Fix the S3 URL construction. • Track active egress IDs and pending deletions. Add or adapt the following to your codebase. 1) Webhook handler and small helper state (FastAPI):
Copy code
from fastapi import FastAPI, Request, BackgroundTasks, HTTPException
from fastapi.responses import JSONResponse
import asyncio
import logging
from typing import Dict

app = FastAPI()
logger = logging.getLogger("livekit")
logging.basicConfig(level=logging.INFO)

# In-memory stores (persist to DB in production)
active_egresses: Dict[str, str] = {}        # room_name -> egress_id
egress_to_room: Dict[str, str] = {}         # egress_id -> room_name
pending_deletions: Dict[str, asyncio.Task] = {}  # room_name -> cancellation task

# configurable grace time to wait before deleting a room when last participant leaves
ROOM_DELETE_GRACE_SECONDS = 10
2) Webhook endpoint to track egress lifecycle (handle
egress_started
and
egress_ended
):
Copy code
@app.post("/livekit/webhook")
async def livekit_webhook(request: Request):
    body = await request.json()
    event_type = body.get("event")
    egress_info = body.get("egress_info") or {}

    logger.info(f"webhook received: {event_type} for egress_info={egress_info}")

    if event_type == "egress_started":
        egress_id = egress_info.get("egress_id")
        room_name = egress_info.get("room_name")
        if egress_id and room_name:
            active_egresses[room_name] = egress_id
            egress_to_room[egress_id] = room_name
            # if there's a pending deletion scheduled for this room, keep it until egress ends
            if room_name in pending_deletions:
                # do not cancel here; keep pending deletion but ensure it waits for egress_ended
                logger.info(f"egress_started: tracked {egress_id} for room {room_name}")

    elif event_type == "egress_ended":
        egress_id = egress_info.get("egress_id")
        room_name = egress_to_room.get(egress_id) or egress_info.get("room_name")
        if egress_id:
            # cleanup tracking
            if egress_id in egress_to_room:
                del egress_to_room[egress_id]
            if room_name and room_name in active_egresses:
                del active_egresses[room_name]
            logger.info(f"egress_ended: {egress_id} for room {room_name}")

            # If we have a pending deletion scheduled for this room, cancel the scheduled task and delete the room now
            task = pending_deletions.pop(room_name, None)
            if task:
                task.cancel()
                # call actual delete logic now (run in background)
                asyncio.create_task(delete_room_and_cleanup(room_name))

    return JSONResponse({"status": "ok"})
3) Helper to schedule room deletion with grace period and respect egress lifecycle:
Copy code
async def delete_room_and_cleanup(room_name: str):
    """
    Run actual room deletion and cleanup here.
    Replace the body with your LiveKit delete room API call and any app cleanup.
    """
    try:
        logger.info(f"Deleting room now: {room_name}")
        # TODO: Call LiveKit API to delete the room, e.g. lkapi.room.delete_room(...)
        # await lkapi.room.delete_room(api.DeleteRoomRequest(name=room_name))
    except Exception as e:
        logger.exception(f"Error deleting room {room_name}: {e}")
    finally:
        # remove from tracking maps
        active_egresses.pop(room_name, None)
        logger.info(f"Room deleted and cleaned up: {room_name}")

async def schedule_room_deletion(room_name: str):
    """
    Called when last non-agent participant leaves.
    If an egress is active for the room, wait for egress to finish (egress_ended).
    Otherwise wait ROOM_DELETE_GRACE_SECONDS then delete.
    """
    # if there is an active egress, schedule deletion but do not delete until egress_ended webhook arrives
    if room_name in active_egresses:
        logger.info(f"Room {room_name} has active egress {active_egresses[room_name]}; deferring deletion until egress ends")
        # create a task that waits for a hard timeout in case egress never ends
        async def fallback_delete():
            try:
                await asyncio.sleep(300)  # hard timeout (5 min) to avoid leaked rooms; adjust as needed
                # if still active, force delete
                if room_name in active_egresses:
                    logger.info(f"Hard timeout reached; forcing delete for room {room_name}")
                    await delete_room_and_cleanup(room_name)
            except asyncio.CancelledError:
                logger.info(f"Pending deletion for {room_name} cancelled due to egress_ended")
        task = asyncio.create_task(fallback_delete())
        pending_deletions[room_name] = task
    else:
        # no active egress: delete after short grace period
        async def grace_and_delete():
            try:
                logger.info(f"Grace period {ROOM_DELETE_GRACE_SECONDS}s before deleting room {room_name}")
                await asyncio.sleep(ROOM_DELETE_GRACE_SECONDS)
                await delete_room_and_cleanup(room_name)
            except asyncio.CancelledError:
                logger.info(f"Pending grace deletion cancelled for {room_name}")
        task = asyncio.create_task(grace_and_delete())
        pending_deletions[room_name] = task
4) Integrate with your join endpoint and last-participant-leave handler: • On join: you already start egress. Keep storing egress id returned by LiveKit in
active_egresses
and
egress_to_room
if you want immediate tracking. But real tracking comes from webhooks. • On last non-agent participant leaving: call
schedule_room_deletion(room_name)
instead of calling delete immediately. Example snippet showing where to call schedule:
Copy code
# when you detect the last non-agent participant left:
await schedule_room_deletion(room_name)
5) Fix S3 URL construction when returning recording link: Replace your incorrect string:
Copy code
# wrong:
f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.[amazonaws.com/{room_name}.mp4](http://amazonaws.com/{room_name}.mp4)"
With correct form:
Copy code
recording_url = f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4"
Only return that URL after you see
egress_ended
for the egress that produced the file — or verify the file exists in S3 before returning. 6) Optional: stop egress safely (if you call StopEgress manually) • Only call StopEgress after receiving
egress_started
AND the desired recording duration has elapsed. If you need to force stop after some timeout, ensure you do not call it immediately when last participant leaves. 7) Logging and testing • Add logs around: starting egress request, storing egress_id, scheduling deletion, webhook receipts, and actual delete call. Test the flow: a. Join room, start egress. b. Leave room (simulate last participant exit) — scheduler should run. c. Confirm
egress_started
arrives (webhook). d. Confirm
egress_ended
arrives (webhook) and deletion runs afterwards. e. Confirm file in S3 at corrected URL. If you want, I can provide a quick sample for the delete-room LiveKit API call you use in your code (showing how to call lkapi.room.delete_room) and a small example of verifying S3 file existence before returning the URL. Which of those would you like next?
l
how many time it will take to return this event
t
egress_started is usually delivered within a few seconds after the egress process begins; egress_ended is sent once the recording is finalized and uploaded to S3 — typically within a few seconds after stop, but can take longer depending on recording length and upload speed. In practice: • Expect egress_started within ~1–10 seconds of starting egress. • Expect egress_ended within a few seconds to a minute after stopping (longer for large files or slow uploads). If you want exact behavior for your flow, tell me: • Typical recording duration and file sizes, and • Whether your storage is S3 in the same region as LiveKit. I can then suggest timeout values (grace period / hard timeout) to use in your scheduler. Sources: Quotas and limits | LiveKit docs | Webhooks | LiveKit docs | Web Egress | LiveKit Docs
l
INFOlivekit serviceEGRESS_ENDED: egress_id=EG_Gg9F9siru9gL, room=05792e02-9cd7-494d-bf59-9873158fa115, status=5, error=Start signal not received i am getting this error
t
Thanks — that error means the egress renderer never signaled it was ready, so LiveKit aborted. Two actions will fix it: 1) Add the START signal in your egress template/page • Ensure the page Chrome loads for Room Composite logs exactly this to console after it’s connected and layout is ready: ◦ console.log("START_RECORDING") • Place it after the LiveKit room connection and after your layout/render pipeline is ready (or immediately after successful
room.connect(...)
for testing). Example (JS, after connect succeeds):
Copy code
room.connect(url, token).then(() => {
  // layout/render setup...
  console.log("START_RECORDING");
});
2) Don’t delete/stop before egress finishes • Use webhooks to gate deletion: wait for
egress_started
(recording active) and especially
egress_ended
(file finalized + uploaded) before deleting the room or removing agent participants. • If your flow auto-deletes on last participant leave, change it to: ◦ If an active egress exists: schedule deletion but wait for
egress_ended
(or keep an agent in-room). ◦ Else: use a short grace (5–10s) before delete. Quick checklist to validate: • Your template is reachable (no 404/CORS) from the egress Chrome instance. • Template prints console.log("START_RECORDING") after connect. • Your webhook endpoint receives
egress_started
then
egress_ended
. • You only delete room/StopEgress after
egress_ended
. • Correct S3 URL format when checking file: ◦ https://{bucket}.s3.{region}.amazonaws.com/{room_name}.mp4 If you want, I can: • Provide a minimal egress template HTML/JS that connects and logs START_RECORDING, or • Show the exact webhook handler snippet to gate room deletion. Which would help you most? Sources: Custom recording templates | LiveKit docs | Webhooks | LiveKit docs
l
what i need to do in frontend for recording
t
You're on the right track — here’s exactly what your frontend must do to ensure Room Composite egress records and uploads successfully. 1) Connect and render • Use the LiveKit client to connect the page to the room with the egress token/URL. • Render the participant tracks/layout the egress expects (speaker/grid). 2) Signal the recorder to start • After the room is connected and the layout is ready, log the exact string: ◦ console.log("START_RECORDING") • This must be printed to the page's console that headless Chrome loads. Without it, egress will not start and will fail with "Start signal not received". 3) (Optional) Signal the recorder to end • When you want to end recording from the page, log: ◦ console.log("END_RECORDING") • Otherwise stop via the StopEgress API or let your backend handle it; still wait for egress_ended webhook before cleanup. 4) Minimal example (JS) • After successful connect, call START_RECORDING:
Copy code
room.connect(wsUrl, token).then(() => {
  // render layout / attach tracks...
  console.log("START_RECORDING");
}).catch(err => console.error(err));
5) Test and verify • Use
lk egress test-template
or deploy the template and watch the headless Chrome console (or webhook events). • Confirm you receive
egress_started
then
egress_ended
webhooks before deleting the room. • Only return/fetch S3 URL after
egress_ended
(or verify file exists). If you want, I can provide a minimal HTML template (with LiveKit client setup, simple layout, and the START/END logs) you can host for egress to load — would you like that? Sources: RoomComposite Egress | LiveKit Docs | Custom recording templates | LiveKit docs