Skip to content

fix: send attributes_to_headers and EndCall headers on ringing CANCEL - #854

Open
lixuanqun wants to merge 1 commit into
livekit:mainfrom
lixuanqun:fix/cancel-headers
Open

lixuanqun wants to merge 1 commit into
livekit:mainfrom
lixuanqun:fix/cancel-headers

Conversation

@lixuanqun

Copy link
Copy Markdown

Summary

The CANCEL sent for a still-ringing outbound call carried none of the trunk's attributes_to_headers mappings, and none of the headers passed to lk.sip.EndCall. There was no way to send an RFC 3326 Reason header (e.g. Reason: SIP;cause=200;text="Call completed elsewhere"), the standard signal for "another endpoint answered" in a parallel ring.

Closes #846.

Root cause

sendCancel (which applies attributes_to_headers and caller headers) was unreachable in the ringing state. It is only called from sipOutbound.Close when c.invite != nil && c.inviteOk == nil, but c.invite was only set after the final 200 OK:

// outbound.go (before)
c.invite, c.inviteOk = req, resp   // only after 200 OK

So while ringing, c.invite == nil, sipOutbound.Close took the drop() branch, and the actual CANCEL on the wire came from tx.Cancel() inside sipResponse — built by the transaction layer, which copies only the mandatory INVITE headers (Via/Route/Max-Forwards/From/To/Call-ID/CSeq).

What changed

pkg/sip/outbound.go

  • Remember the INVITE as soon as its transaction is created. attemptInvite now sets c.invite = req right after TransactionRequest succeeds, so the ringing state can build a header-aware CANCEL from it.
  • sipResponse takes an optional onCancel hook. When set, context cancellation / service shutdown sends the header-aware CANCEL via sendCancel instead of the bare tx.Cancel(). c.mu is held by the same goroutine up the stack (the Invite method), so sendCancel is called directly without re-locking.
  • Clear the remembered INVITE once the transaction completes. If the final response is not 2xx (or there's a timeout), c.invite is set back to nil so nothing else can cancel a dead transaction.
  • watchCancelledInvite drops the call state. A racing 2xx that arrives after the cancel would previously leave c.invite set; now watchCancelledInvite calls drop() on completion so a stray CANCEL can never be sent against an answered call.

pkg/sip/protocol.go

  • Updated the two existing sipResponse call sites (sendBye, sendRefer) to pass nil for the new onCancel parameter — their behavior is unchanged.

Tests

Three new tests in pkg/sip/outbound_test.go:

  • TestSIPResponseCancelUsesHook — verifies sipResponse invokes the onCancel hook instead of tx.Cancel() when one is provided.
  • TestOutboundCloseWhileRingingSendsCancelWithHeaders — unit test: a sipOutbound with a remembered INVITE, when closed while ringing, sends a CANCEL carrying both attributes_to_headers mappings and caller-supplied headers (e.g. Reason), with the correct CSeq and Via.
  • TestOutboundCancelWhileRinging — end-to-end: CreateSIPParticipant(wait_until_answered=true) is cancelled while the remote is still sending 180 Ringing; the wire shows a CANCEL with User-Agent: LiveKit.

Existing tests updated for the new sipResponse/watchCancelledInvite signatures; all pass.

Why this approach

The issue suggests two alternatives: (a) let the sipgo transaction cancel accept extra headers, or (b) set c.invite early so Close() → sendCancel applies. Option (b) is entirely within livekit/sip — no coordinated sipgo dependency bump needed — and reuses the existing header-aware sendCancel path. The only subtlety is that sipResponse, not Close, is what detects the ringing-state cancel, so the onCancel hook lets that path reach sendCancel without re-locking c.mu (held by the Invite goroutine).

Verified locally with golangci-lint v2.13.1 (same as CI, 0 issues) and the full go test ./pkg/... suite.

The CANCEL sent for a still-ringing outbound call was built by the
transaction layer (tx.Cancel), which copies only the mandatory INVITE
headers. sendCancel, which applies attributes_to_headers and caller
headers, was unreachable in the ringing state because c.invite was only
set after the final 200 OK. As a result there was no way to send an RFC
3326 Reason header (e.g. 'Call completed elsewhere') or any other mapped
header on that CANCEL.

See: livekit#846

- remember the INVITE as soon as its transaction is created, so the
  ringing state can build a header-aware CANCEL from it
- give sipResponse an optional onCancel hook so context cancellation
  sends the header-aware CANCEL instead of the bare transaction one
  (c.mu is held by the same goroutine, so sendCancel is called directly)
- clear the remembered INVITE once the transaction completes, and drop
  it in watchCancelledInvite so a racing 2xx never gets a stray CANCEL
@lixuanqun
lixuanqun requested a review from a team as a code owner September 17, 2026 09:19

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 potential issue.

Devin Review

Comment thread pkg/sip/outbound.go
Comment on lines +1222 to +1227
resp, err := sipResponse(ctx, tx, c.c.closing.Watch(), setState, func() {
// Cancel with attributes_to_headers applied (e.g. RFC 3326 Reason).
// NOTE: c.mu is held by this goroutine higher up the stack (Invite),
// so all other mutators are blocked on it; call sendCancel directly
// instead of re-locking (which would deadlock).
c.sendCancel(context.WithoutCancel(ctx), nil)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Ringing EndCall headers remain dropped

When EndCall closes a ringing call, onCancel invokes sendCancel without its headers. sendCancel clears c.invite, so the blocked Close cannot send them later.

Learn more

Invite holds the signaling mutex while waiting for the INVITE response. EndCall first closes the outer call, which cancels the INVITE context, then blocks in stopSIP waiting to call sipOutbound.Close under that mutex. The cancellation hook therefore runs first with nil headers and sendCancel clears the remembered INVITE. Once Invite releases the mutex, sipOutbound.Close sees no INVITE and cannot send the EndCall headers.

Example: An RPC ends a ringing call with Reason: SIP;cause=200. The hook sends a CANCEL containing mapped participant attributes but no Reason; the later close sends nothing.

Recommended fix: Stage the EndCall headers where the cancellation hook can consume them, or restructure cancellation so sipOutbound.Close builds the single CANCEL after receiving those headers. Add an end-to-end ringing lk.sip.EndCall test that asserts its Reason header on the wire.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@codecov

codecov Bot commented Sep 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.00000% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.58%. Comparing base (0460b40) to head (12a7aa1).
⚠️ Report is 374 commits behind head on main.

Files with missing lines Patch % Lines
pkg/sip/outbound.go 82.60% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #854      +/-   ##
==========================================
+ Coverage   65.25%   68.58%   +3.32%     
==========================================
  Files          51       43       -8     
  Lines        6588     8581    +1993     
==========================================
+ Hits         4299     5885    +1586     
- Misses       1915     2175     +260     
- Partials      374      521     +147     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lixuanqun

Copy link
Copy Markdown
Author

Hi @hechen-eng, gentle review request on this small fix — it makes sure attributes_to_headers and custom EndCall headers are also sent on the CANCEL sent while a call is still ringing, not just on the BYE. CI is green and the branch is mergeable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Outbound CANCEL for a ringing call ignores attributes_to_headers and EndCall headers (no way to send RFC 3326 Reason)

1 participant