Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(voice): claim transcript epochs from TeamHub so a restarted job resumes

muterCe8923515d571
diff --git a/apps/teamhub/internal/app/contract_server_voice_runtime.go b/apps/teamhub/internal/app/contract_server_voice_runtime.go
index a871cef4..a6796e8c 100644
--- a/apps/teamhub/internal/app/contract_server_voice_runtime.go
+++ b/apps/teamhub/internal/app/contract_server_voice_runtime.go
@@ -55,6 +55,19 @@ func (a *App) reportVoiceObservationRoute(c *gin.Context) {
a.reportVoiceObservation(c, request)
}
+func (a *App) claimVoiceMediaEpoch(c *gin.Context) {
+ epoch, err := a.voice.ClaimMediaEpoch(c.Request.Context(), c.Param("voiceSessionId"))
+ switch {
+ case errors.Is(err, voice.ErrVoiceSessionNotFound):
+ c.JSON(http.StatusNotFound, teamhubinternal.VoiceError{Code: "NOT_FOUND", Message: "VoiceSession was not found"})
+ return
+ case err != nil:
+ a.internalVoiceRuntimeError(c, "claim Voice media epoch", err)
+ return
+ }
+ c.JSON(http.StatusOK, teamhubinternal.VoiceMediaEpochClaim{MediaEpoch: epoch})
+}
+
// reportVoiceObservation applies one Voice Runtime observation. Every write is
// keyed by the event ID, the transcript window or a monotonic offset, so a
// retried observation applies again without a receipt table.
diff --git a/apps/teamhub/internal/app/routes_internal.go b/apps/teamhub/internal/app/routes_internal.go
index 086b505e..69aa06d8 100644
--- a/apps/teamhub/internal/app/routes_internal.go
+++ b/apps/teamhub/internal/app/routes_internal.go
@@ -105,5 +105,6 @@ func (a *App) voiceRuntimeRoutes() []contractRoute {
route(http.MethodGet, "/internal/v1/voice/sessions/:voiceSessionId/live-context", nil, a.getVoiceLiveContext),
route(http.MethodGet, "/internal/v1/voice/sessions/:voiceSessionId/live-task-events", nil, a.streamVoiceLiveTaskEvents),
route(http.MethodGet, "/internal/v1/voice/sessions/:voiceSessionId/live-tasks", nil, a.listVoiceLiveTasksRoute),
+ route(http.MethodPost, "/internal/v1/voice/sessions/:voiceSessionId/media-epochs", nil, a.claimVoiceMediaEpoch),
}
}
diff --git a/apps/teamhub/internal/store/models.go b/apps/teamhub/internal/store/models.go
index 77c9a25e..5788c56a 100644
--- a/apps/teamhub/internal/store/models.go
+++ b/apps/teamhub/internal/store/models.go
@@ -1882,6 +1882,7 @@ type VoiceSession struct {
AuthSessionID pgtype.Text `json:"auth_session_id"`
LiveAgentActorID pgtype.Text `json:"live_agent_actor_id"`
LiveLeaseUntil pgtype.Timestamptz `json:"live_lease_until"`
+ NextMediaEpoch int32 `json:"next_media_epoch"`
}
type VoiceTranscriptSegment struct {
diff --git a/apps/teamhub/internal/store/queries/voice_media.sql b/apps/teamhub/internal/store/queries/voice_media.sql
index 1171f864..d127c9e9 100644
--- a/apps/teamhub/internal/store/queries/voice_media.sql
+++ b/apps/teamhub/internal/store/queries/voice_media.sql
@@ -115,6 +115,15 @@ SELECT coalesce(extract(epoch FROM min(updated_at+CASE
FROM voice_sessions
WHERE id=sqlc.arg(id)::text AND status IN ('provisioning','connected','reconnecting','closing');
+-- name: ClaimVoiceTranscriptEpoch :one
+-- Each claim returns a number no earlier claim for the session returned, even
+-- across runtime restarts, so transcript coverage streams never collide. It
+-- leaves updated_at alone: the reconcile worker reads it as publisher activity.
+UPDATE voice_sessions
+SET next_media_epoch=next_media_epoch+1
+WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing')
+RETURNING (next_media_epoch-1)::integer AS media_epoch;
+
-- name: MarkVoiceSessionPublisherAbsent :exec
UPDATE voice_sessions
SET status='reconnecting',last_failure_code='publisher_absent',updated_at=clock_timestamp()
diff --git a/apps/teamhub/internal/store/voice_live.sql.go b/apps/teamhub/internal/store/voice_live.sql.go
index d33164ca..09e1d597 100644
--- a/apps/teamhub/internal/store/voice_live.sql.go
+++ b/apps/teamhub/internal/store/voice_live.sql.go
@@ -433,7 +433,7 @@ func (q *Queries) GetVoiceLiveReplyAgent(ctx context.Context, arg GetVoiceLiveRe
}
const getVoiceLiveReplySessionContext = `-- name: GetVoiceLiveReplySessionContext :one
-SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until,actor.account_id
+SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch,actor.account_id
FROM voice_sessions voice
JOIN actors actor
ON actor.id=voice.created_by_actor_id AND actor.tenant_id=voice.tenant_id AND actor.kind='human'
@@ -467,6 +467,7 @@ type GetVoiceLiveReplySessionContextRow struct {
AuthSessionID pgtype.Text `json:"auth_session_id"`
LiveAgentActorID pgtype.Text `json:"live_agent_actor_id"`
LiveLeaseUntil pgtype.Timestamptz `json:"live_lease_until"`
+ NextMediaEpoch int32 `json:"next_media_epoch"`
AccountID pgtype.Text `json:"account_id"`
}
@@ -498,6 +499,7 @@ func (q *Queries) GetVoiceLiveReplySessionContext(ctx context.Context, voiceSess
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
&i.AccountID,
)
return i, err
diff --git a/apps/teamhub/internal/store/voice_media.sql.go b/apps/teamhub/internal/store/voice_media.sql.go
index 0b6c1316..df9699b3 100644
--- a/apps/teamhub/internal/store/voice_media.sql.go
+++ b/apps/teamhub/internal/store/voice_media.sql.go
@@ -61,7 +61,7 @@ const activateVoiceSession = `-- name: ActivateVoiceSession :one
UPDATE voice_sessions
SET status='connected',last_failure_code=NULL,updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','reconnecting')
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
func (q *Queries) ActivateVoiceSession(ctx context.Context, id string) (VoiceSession, error) {
@@ -90,6 +90,7 @@ func (q *Queries) ActivateVoiceSession(ctx context.Context, id string) (VoiceSes
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -151,7 +152,7 @@ const advanceVoiceSessionCredentialGeneration = `-- name: AdvanceVoiceSessionCre
UPDATE voice_sessions
SET credential_generation=credential_generation+1,updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting')
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
func (q *Queries) AdvanceVoiceSessionCredentialGeneration(ctx context.Context, id string) (VoiceSession, error) {
@@ -180,6 +181,7 @@ func (q *Queries) AdvanceVoiceSessionCredentialGeneration(ctx context.Context, i
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -263,7 +265,7 @@ WHERE id=$1::text
WHEN last_failure_code='publisher_absent' AND status<>'closing' THEN interval '60 seconds'
ELSE $2::interval
END
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
type ClaimVoiceSessionReconcileParams struct {
@@ -299,10 +301,28 @@ func (q *Queries) ClaimVoiceSessionReconcile(ctx context.Context, arg ClaimVoice
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
+const claimVoiceTranscriptEpoch = `-- name: ClaimVoiceTranscriptEpoch :one
+UPDATE voice_sessions
+SET next_media_epoch=next_media_epoch+1
+WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing')
+RETURNING (next_media_epoch-1)::integer AS media_epoch
+`
+
+// Each claim returns a number no earlier claim for the session returned, even
+// across runtime restarts, so transcript coverage streams never collide. It
+// leaves updated_at alone: the reconcile worker reads it as publisher activity.
+func (q *Queries) ClaimVoiceTranscriptEpoch(ctx context.Context, id string) (int32, error) {
+ row := q.db.QueryRow(ctx, claimVoiceTranscriptEpoch, id)
+ var media_epoch int32
+ err := row.Scan(&media_epoch)
+ return media_epoch, err
+}
+
const clearConfirmedVoicePartialTranscript = `-- name: ClearConfirmedVoicePartialTranscript :exec
UPDATE voice_sessions
SET latest_partial_text=NULL,latest_partial_start_offset_ms=NULL,
@@ -325,7 +345,7 @@ UPDATE voice_sessions
SET latest_partial_text=NULL,latest_partial_start_offset_ms=NULL,
latest_partial_end_offset_ms=NULL,latest_partial_updated_at=NULL,updated_at=clock_timestamp()
WHERE id=$1
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
func (q *Queries) ClearVoiceSessionPartialTranscript(ctx context.Context, id string) (VoiceSession, error) {
@@ -354,6 +374,7 @@ func (q *Queries) ClearVoiceSessionPartialTranscript(ctx context.Context, id str
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -364,7 +385,7 @@ SET status='closed',closed_at=coalesce(closed_at,clock_timestamp()),updated_at=c
latest_partial_text=NULL,latest_partial_start_offset_ms=NULL,
latest_partial_end_offset_ms=NULL,latest_partial_updated_at=NULL
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing','closed')
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
// A closed session keeps no partial text (M11-N16).
@@ -394,6 +415,7 @@ func (q *Queries) CloseVoiceSession(ctx context.Context, id string) (VoiceSessio
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -501,7 +523,7 @@ func (q *Queries) CreateCaptureMediaRange(ctx context.Context, arg CreateCapture
const createLiveKitCaptureSession = `-- name: CreateLiveKitCaptureSession :one
WITH voice AS (
- SELECT session.id, session.tenant_id, session.room_id, session.created_by_actor_id, session.status, session.provider_room_name, session.participant_identity, session.credential_generation, session.last_failure_code, session.created_at, session.updated_at, session.closed_at, session.latest_partial_text, session.latest_partial_start_offset_ms, session.latest_partial_end_offset_ms, session.latest_partial_updated_at, session.last_input_started_ms, session.last_input_ended_ms, session.purpose, session.auth_session_id, session.live_agent_actor_id, session.live_lease_until
+ SELECT session.id, session.tenant_id, session.room_id, session.created_by_actor_id, session.status, session.provider_room_name, session.participant_identity, session.credential_generation, session.last_failure_code, session.created_at, session.updated_at, session.closed_at, session.latest_partial_text, session.latest_partial_start_offset_ms, session.latest_partial_end_offset_ms, session.latest_partial_updated_at, session.last_input_started_ms, session.last_input_ended_ms, session.purpose, session.auth_session_id, session.live_agent_actor_id, session.live_lease_until, session.next_media_epoch
FROM voice_sessions session
JOIN actors caller
ON caller.id=session.created_by_actor_id
@@ -665,7 +687,7 @@ SELECT $1::text,authority.tenant_id,$2::text,authority.actor_id,
'provisioning',$3::text,$4::text,
$5::text,$6::text
FROM authority
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
type CreateVoiceSessionParams struct {
@@ -712,6 +734,7 @@ func (q *Queries) CreateVoiceSession(ctx context.Context, arg CreateVoiceSession
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -1149,7 +1172,7 @@ func (q *Queries) GetActiveLiveKitCaptureForVoiceSession(ctx context.Context, vo
}
const getActiveRecordingSessionForAuthSessionRoom = `-- name: GetActiveRecordingSessionForAuthSessionRoom :one
-SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until
+SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch
FROM voice_sessions voice
JOIN actors caller
ON caller.id=voice.created_by_actor_id
@@ -1197,6 +1220,7 @@ func (q *Queries) GetActiveRecordingSessionForAuthSessionRoom(ctx context.Contex
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -1517,7 +1541,7 @@ func (q *Queries) GetVoiceMediaPolicyForAccount(ctx context.Context, arg GetVoic
}
const getVoiceRuntimeSessionContext = `-- name: GetVoiceRuntimeSessionContext :one
-SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until,actor.account_id
+SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch,actor.account_id
FROM voice_sessions voice
JOIN actors actor
ON actor.id=voice.created_by_actor_id AND actor.tenant_id=voice.tenant_id AND actor.kind='human'
@@ -1554,6 +1578,7 @@ type GetVoiceRuntimeSessionContextRow struct {
AuthSessionID pgtype.Text `json:"auth_session_id"`
LiveAgentActorID pgtype.Text `json:"live_agent_actor_id"`
LiveLeaseUntil pgtype.Timestamptz `json:"live_lease_until"`
+ NextMediaEpoch int32 `json:"next_media_epoch"`
AccountID pgtype.Text `json:"account_id"`
}
@@ -1583,13 +1608,14 @@ func (q *Queries) GetVoiceRuntimeSessionContext(ctx context.Context, id string)
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
&i.AccountID,
)
return i, err
}
const getVoiceSessionForAccount = `-- name: GetVoiceSessionForAccount :one
-SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until
+SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch
FROM voice_sessions voice
JOIN actors caller
ON caller.id=voice.created_by_actor_id AND caller.tenant_id=voice.tenant_id
@@ -1637,6 +1663,7 @@ func (q *Queries) GetVoiceSessionForAccount(ctx context.Context, arg GetVoiceSes
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -1720,7 +1747,7 @@ WITH revoked AS (
WHERE member.room_id=voice.room_id AND member.actor_id=voice.created_by_actor_id
AND actor.kind='human' AND actor.account_id IS NOT NULL
)
- RETURNING voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until
+ RETURNING voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch
), failed_captures AS (
UPDATE capture_sessions capture SET status='failed',updated_at=clock_timestamp()
FROM revoked voice
@@ -2067,7 +2094,7 @@ func (q *Queries) ListVoiceTranscriptEventsForAccount(ctx context.Context, arg L
}
const lockVoiceSession = `-- name: LockVoiceSession :one
-SELECT id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until FROM voice_sessions WHERE id=$1 FOR NO KEY UPDATE
+SELECT id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch FROM voice_sessions WHERE id=$1 FOR NO KEY UPDATE
`
// NO KEY: commit-time foreign-key checks from children take KEY SHARE on
@@ -2099,6 +2126,7 @@ func (q *Queries) LockVoiceSession(ctx context.Context, id string) (VoiceSession
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -2233,7 +2261,7 @@ const markVoiceSessionReconnecting = `-- name: MarkVoiceSessionReconnecting :one
UPDATE voice_sessions
SET status='reconnecting',last_failure_code=$2,updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting')
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
type MarkVoiceSessionReconnectingParams struct {
@@ -2267,6 +2295,7 @@ func (q *Queries) MarkVoiceSessionReconnecting(ctx context.Context, arg MarkVoic
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -2509,7 +2538,7 @@ func (q *Queries) RequestVoiceCaptureStop(ctx context.Context, id string) (Captu
const requestVoiceSessionClose = `-- name: RequestVoiceSessionClose :one
UPDATE voice_sessions SET status='closing',updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing')
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
func (q *Queries) RequestVoiceSessionClose(ctx context.Context, id string) (VoiceSession, error) {
@@ -2538,6 +2567,7 @@ func (q *Queries) RequestVoiceSessionClose(ctx context.Context, id string) (Voic
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
@@ -2710,7 +2740,7 @@ UPDATE voice_sessions
SET latest_partial_text=$2,latest_partial_start_offset_ms=$3,
latest_partial_end_offset_ms=$4,latest_partial_updated_at=clock_timestamp(),updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing')
-RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until
+RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`
type UpdateVoiceSessionPartialTranscriptParams struct {
@@ -2751,6 +2781,7 @@ func (q *Queries) UpdateVoiceSessionPartialTranscript(ctx context.Context, arg U
&i.AuthSessionID,
&i.LiveAgentActorID,
&i.LiveLeaseUntil,
+ &i.NextMediaEpoch,
)
return i, err
}
diff --git a/apps/teamhub/internal/voice/voice_runtime.go b/apps/teamhub/internal/voice/voice_runtime.go
index 76b772f9..581e0ddc 100644
--- a/apps/teamhub/internal/voice/voice_runtime.go
+++ b/apps/teamhub/internal/voice/voice_runtime.go
@@ -134,6 +134,20 @@ func (s *Service) applyVoiceFinalObservation(
// ErrVoiceSessionNotFound reports an observation for an unknown VoiceSession.
var ErrVoiceSessionNotFound = errors.New("VoiceSession was not found")
+// ClaimMediaEpoch returns the next transcript media epoch of an open
+// VoiceSession. The counter lives in PostgreSQL so a restarted runtime job
+// never reuses an epoch whose coverage stream an earlier job already started.
+func (s *Service) ClaimMediaEpoch(ctx context.Context, voiceSessionID string) (int, error) {
+ epoch, err := s.queries.ClaimVoiceTranscriptEpoch(ctx, voiceSessionID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return 0, ErrVoiceSessionNotFound
+ }
+ if err != nil {
+ return 0, fmt.Errorf("claim Voice media epoch: %w", err)
+ }
+ return int(epoch), nil
+}
+
// ErrVoicePurposeConflict reports a dictation turn outside a live chat
// dictation session.
var ErrVoicePurposeConflict = errors.New("dictation turns require a live chat dictation session")
diff --git a/apps/teamhub/migrations/00873_claim_voice_transcript_epochs.sql b/apps/teamhub/migrations/00873_claim_voice_transcript_epochs.sql
new file mode 100644
index 00000000..3377c980
--- /dev/null
+++ b/apps/teamhub/migrations/00873_claim_voice_transcript_epochs.sql
@@ -0,0 +1,18 @@
+-- +goose Up
+-- TeamHub hands out each Voice Runtime transcript epoch so a restarted runtime
+-- job never reuses a number an earlier job already wrote coverage or segments
+-- under. Open sessions resume after the highest epoch they already used.
+ALTER TABLE voice_sessions
+ ADD COLUMN next_media_epoch integer NOT NULL DEFAULT 0 CHECK (next_media_epoch >= 0);
+
+UPDATE voice_sessions voice
+SET next_media_epoch = 1 + coalesce(greatest(
+ (SELECT max(segment.media_epoch)
+ FROM voice_transcript_segments segment
+ WHERE segment.voice_session_id = voice.id),
+ (SELECT max(substring(coverage.stream_id FROM '^voice-runtime-v2:[^:]+:([0-9]+)$')::integer)
+ FROM capture_transcript_coverage coverage
+ JOIN capture_sessions capture ON capture.id = coverage.session_id
+ WHERE capture.voice_session_id = voice.id)
+), -1)
+WHERE voice.status <> 'closed';
diff --git a/apps/teamhub/tests/integration/voice_media_epoch_claim_test.go b/apps/teamhub/tests/integration/voice_media_epoch_claim_test.go
new file mode 100644
index 00000000..dff94a68
--- /dev/null
+++ b/apps/teamhub/tests/integration/voice_media_epoch_claim_test.go
@@ -0,0 +1,255 @@
+package integration_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+const voiceEpochTestToken = "voice-test-service-token"
+
+type voiceEpochHarness struct {
+ t *testing.T
+ env *testEnv
+}
+
+func (h voiceEpochHarness) post(ctx context.Context, path string, payload any) (int, []byte) {
+ h.t.Helper()
+ var body io.Reader
+ if payload != nil {
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ h.t.Fatal(err)
+ }
+ body = bytes.NewReader(encoded)
+ }
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, h.env.server.URL+path, body)
+ if err != nil {
+ h.t.Fatal(err)
+ }
+ if payload != nil {
+ request.Header.Set("Content-Type", "application/json")
+ }
+ request.Header.Set("Authorization", "Bearer "+voiceEpochTestToken)
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ h.t.Fatal(err)
+ }
+ defer response.Body.Close()
+ responseBody, _ := io.ReadAll(response.Body)
+ return response.StatusCode, responseBody
+}
+
+func (h voiceEpochHarness) claim(ctx context.Context, voiceSessionID string) (int, int) {
+ h.t.Helper()
+ status, body := h.post(ctx, "/internal/v1/voice/sessions/"+voiceSessionID+"/media-epochs", nil)
+ if status != http.StatusOK {
+ return status, -1
+ }
+ var claim struct {
+ MediaEpoch int `json:"media_epoch"`
+ }
+ if err := json.Unmarshal(body, &claim); err != nil {
+ h.t.Fatalf("claim body %s: %v", body, err)
+ }
+ return status, claim.MediaEpoch
+}
+
+func (h voiceEpochHarness) progress(ctx context.Context, voiceSessionID string, epoch int, start, through int64) (int, string) {
+ h.t.Helper()
+ status, body := h.post(ctx, "/internal/v1/voice/observations", map[string]any{
+ "event_id": fmt.Sprintf("voice_event_progress_%s_%d", voiceSessionID, epoch), "kind": "progress",
+ "voice_session_id": voiceSessionID, "media_epoch": epoch, "lane": "live",
+ "start_offset_ms": start, "end_offset_ms": through, "committed_through_ms": through,
+ })
+ return status, string(body)
+}
+
+func createRecordingVoiceSession(t *testing.T, env *testEnv, q *store.Queries, roomID, id string) store.VoiceSession {
+ t.Helper()
+ ctx := t.Context()
+ voice, err := q.CreateVoiceSession(ctx, store.CreateVoiceSessionParams{ID: id, AccountID: "account_alice", AuthSessionID: loginSessionOf(t, env, "account_alice"), RoomID: roomID, ProviderRoomName: "room-" + id, ParticipantIdentity: "publisher-" + id, Purpose: "hardware_control"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ capture, err := q.CreateLiveKitCaptureSession(ctx, store.CreateLiveKitCaptureSessionParams{ID: "capture_" + id, AccountID: "account_alice", RoomID: roomID, VoiceSessionID: voice.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = env.pool.Exec(ctx, "UPDATE capture_sessions SET status='recording',transcript_start_offset_ms=0 WHERE id=$1", capture.ID); err != nil {
+ t.Fatal(err)
+ }
+ return voice
+}
+
+// A runtime job restarted mid-recording claims a new epoch, so its progress
+// opens a new coverage stream instead of colliding with the earlier job's.
+// Claims never repeat under concurrency, leave the publisher-activity clock
+// alone, and end with the session.
+func TestVoiceMediaEpochClaimsSurviveRuntimeRestart(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ env, alice, _ := newVoiceServiceEnv(t, func(cfg *config.Config) { cfg.Voice.RuntimeToken = voiceEpochTestToken })
+ ctx := t.Context()
+ q := store.New(env.pool)
+ h := voiceEpochHarness{t: t, env: env}
+ roomID := env.createRoom(alice, acmeTenant, "Voice epochs", "voice-epochs")
+ voice := createRecordingVoiceSession(t, env, q, roomID, "voice_epochs")
+
+ if status, epoch := h.claim(ctx, voice.ID); status != http.StatusOK || epoch != 0 {
+ t.Fatalf("first claim=%d epoch=%d", status, epoch)
+ }
+ if status, body := h.progress(ctx, voice.ID, 0, 100, 500); status != http.StatusAccepted {
+ t.Fatalf("first job progress=%d %s", status, body)
+ }
+ // The restarted job starts its track later on the session clock.
+ status, restarted := h.claim(ctx, voice.ID)
+ if status != http.StatusOK || restarted != 1 {
+ t.Fatalf("restart claim=%d epoch=%d", status, restarted)
+ }
+ if status, body := h.progress(ctx, voice.ID, restarted, 2000, 2500); status != http.StatusAccepted {
+ t.Fatalf("restarted job progress=%d %s", status, body)
+ }
+ var streams []string
+ rows, err := env.pool.Query(ctx, "SELECT stream_id FROM capture_transcript_coverage WHERE session_id=$1 ORDER BY stream_id", "capture_"+voice.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for rows.Next() {
+ var stream string
+ if err = rows.Scan(&stream); err != nil {
+ t.Fatal(err)
+ }
+ streams = append(streams, stream)
+ }
+ if err = rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ want := []string{"voice-runtime-v2:" + voice.ID + ":0", "voice-runtime-v2:" + voice.ID + ":1"}
+ if strings.Join(streams, ",") != strings.Join(want, ",") {
+ t.Fatalf("coverage streams=%v want %v", streams, want)
+ }
+
+ updatedAt := func() time.Time {
+ t.Helper()
+ var at time.Time
+ if err := env.pool.QueryRow(ctx, "SELECT updated_at FROM voice_sessions WHERE id=$1", voice.ID).Scan(&at); err != nil {
+ t.Fatal(err)
+ }
+ return at
+ }
+ before := updatedAt()
+ const concurrent = 20
+ claimed := make([]int, concurrent)
+ var wait sync.WaitGroup
+ for index := range concurrent {
+ wait.Add(1)
+ go func() {
+ defer wait.Done()
+ if status, epoch := h.claim(ctx, voice.ID); status == http.StatusOK {
+ claimed[index] = epoch
+ } else {
+ claimed[index] = -status
+ }
+ }()
+ }
+ wait.Wait()
+ sort.Ints(claimed)
+ for index, epoch := range claimed {
+ if epoch != index+2 {
+ t.Fatalf("concurrent claims=%v", claimed)
+ }
+ }
+ if after := updatedAt(); !after.Equal(before) {
+ t.Fatalf("claims moved updated_at from %v to %v", before, after)
+ }
+
+ if _, err = env.pool.Exec(ctx, "UPDATE voice_sessions SET status='closed',closed_at=clock_timestamp() WHERE id=$1", voice.ID); err != nil {
+ t.Fatal(err)
+ }
+ if status, _ := h.claim(ctx, voice.ID); status != http.StatusNotFound {
+ t.Fatalf("closed session claim=%d", status)
+ }
+ if status, _ := h.claim(ctx, "voice_missing"); status != http.StatusNotFound {
+ t.Fatalf("missing session claim=%d", status)
+ }
+}
+
+// The migration resumes each open session after the highest epoch it already
+// used in segments or coverage, and leaves closed and unused sessions at 0.
+func TestVoiceMediaEpochMigrationResumesOpenSessions(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ env, alice, _ := newVoiceServiceEnv(t, func(cfg *config.Config) { cfg.Voice.RuntimeToken = voiceEpochTestToken })
+ ctx := t.Context()
+ q := store.New(env.pool)
+ h := voiceEpochHarness{t: t, env: env}
+ roomID := env.createRoom(alice, acmeTenant, "Voice epoch backfill", "voice-epoch-backfill")
+ // One login holds one active VoiceSession; the runtime callbacks used here
+ // do not read that link, so each seeded session releases it.
+ openSession := func(id string) store.VoiceSession {
+ t.Helper()
+ voice := createRecordingVoiceSession(t, env, q, roomID, id)
+ if _, err := env.pool.Exec(ctx, "UPDATE voice_sessions SET auth_session_id=NULL WHERE id=$1", voice.ID); err != nil {
+ t.Fatal(err)
+ }
+ return voice
+ }
+ used := openSession("voice_backfill_used")
+ unused := openSession("voice_backfill_unused")
+ closed := openSession("voice_backfill_closed")
+
+ final := func(voiceSessionID string, epoch int) {
+ t.Helper()
+ status, body := h.post(ctx, "/internal/v1/voice/observations", map[string]any{
+ "event_id": "voice_event_final_" + voiceSessionID, "kind": "final", "voice_session_id": voiceSessionID,
+ "media_epoch": epoch, "lane": "live", "start_offset_ms": 100, "end_offset_ms": 400, "text": "Hello",
+ })
+ if status != http.StatusAccepted {
+ t.Fatalf("final=%d %s", status, body)
+ }
+ }
+ final(used.ID, 3)
+ if status, body := h.progress(ctx, used.ID, 5, 100, 400); status != http.StatusAccepted {
+ t.Fatalf("progress=%d %s", status, body)
+ }
+ final(closed.ID, 2)
+ if _, err := env.pool.Exec(ctx, "UPDATE voice_sessions SET status='closed',closed_at=clock_timestamp() WHERE id=$1", closed.ID); err != nil {
+ t.Fatal(err)
+ }
+
+ migration, err := os.ReadFile(filepath.Join(teamHubMigrationDirectory(t), "00873_claim_voice_transcript_epochs.sql"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, backfill, found := strings.Cut(string(migration), "UPDATE voice_sessions voice")
+ if !found {
+ t.Fatal("migration has no voice_sessions backfill")
+ }
+ if _, err = env.pool.Exec(ctx, "UPDATE voice_sessions SET next_media_epoch=0 WHERE room_id=$1", roomID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = env.pool.Exec(ctx, "UPDATE voice_sessions voice"+backfill); err != nil {
+ t.Fatal(err)
+ }
+ for id, want := range map[string]int32{used.ID: 6, unused.ID: 0, closed.ID: 0} {
+ var next int32
+ if err = env.pool.QueryRow(ctx, "SELECT next_media_epoch FROM voice_sessions WHERE id=$1", id).Scan(&next); err != nil {
+ t.Fatal(err)
+ }
+ if next != want {
+ t.Fatalf("%s next_media_epoch=%d want %d", id, next, want)
+ }
+ }
+}
diff --git a/apps/voice-runtime/AGENTS.md b/apps/voice-runtime/AGENTS.md
index 75ae3a5c..45a9aafb 100644
--- a/apps/voice-runtime/AGENTS.md
+++ b/apps/voice-runtime/AGENTS.md
@@ -31,6 +31,7 @@
- Never log audio bytes, transcript text, LiveKit tokens, TeamHub tokens, or provider credentials.
- Partial observations are transient; TeamHub decides which final observations become product truth.
- A duplicated provider event reuses the same stable `event_id`.
+- Every track consumer attempt claims its transcript media epoch from TeamHub (`claimVoiceMediaEpoch`) and never counts epochs in memory: a job restarted mid-session (deploy, crash, key change) must not reuse an epoch whose coverage stream an earlier job started.
- Backpressure is bounded. Failure must stop or reconnect the affected track instead of accumulating unbounded PCM.
- Shutdown waits for accepted final/progress callbacks up to a fixed deadline and then exits non-zero if state is uncertain.
- Never move recording back into the ASR job process; ASR load or failure must never stall the Capture recorder. A recorder never extends an epoch it did not start; TeamHub rejects the conflicting segment and the recorder reports failure.
diff --git a/apps/voice-runtime/src/dictation-worker.test.ts b/apps/voice-runtime/src/dictation-worker.test.ts
index af443a4f..7f27190c 100644
--- a/apps/voice-runtime/src/dictation-worker.test.ts
+++ b/apps/voice-runtime/src/dictation-worker.test.ts
@@ -57,6 +57,12 @@ import {
voicePurposeFromMetadata,
} from "./livekit-worker.js";
+// Hands out media epochs the way TeamHub does: every claim takes a new number.
+function claimEpochs() {
+ let next = 0;
+ return async (_voiceSessionId: string) => next++;
+}
+
afterEach(() => vi.restoreAllMocks());
const payload = (requestId: string) =>
@@ -109,6 +115,7 @@ async function harness(finalAck?: Promise<void>, startSpeaking = true) {
end_offset_ms: number;
}> = [];
const client = {
+ claimMediaEpoch: claimEpochs(),
reportObservation: vi.fn(async (event) => {
observations.push(event);
if (event.kind === "final") await finalAck;
diff --git a/apps/voice-runtime/src/livekit-worker.test.ts b/apps/voice-runtime/src/livekit-worker.test.ts
index 6a5e7d66..a670cece 100644
--- a/apps/voice-runtime/src/livekit-worker.test.ts
+++ b/apps/voice-runtime/src/livekit-worker.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import type { ASREvent, ASRStream } from "./asr.js";
import {
+ claimVoiceMediaEpochWithRetry,
eventId,
publisherAbsence,
reportVoiceObservationWithRetry,
@@ -18,6 +19,12 @@ import {
import { VoiceFailure } from "./voice-failure.js";
import { TeamHubVoiceRuntimeError } from "@linger/wire-contracts/teamhub-internal/client";
+// Hands out media epochs the way TeamHub does: every claim takes a new number.
+function claimEpochs() {
+ let next = 0;
+ return async (_voiceSessionId: string) => next++;
+}
+
describe("VoiceTrackWorker identities", () => {
it("reports the code carried by a typed failure", () => {
expect(
@@ -102,6 +109,7 @@ describe("VoiceTrackWorker identities", () => {
end_offset_ms: number;
}> = [];
const client = {
+ claimMediaEpoch: claimEpochs(),
reportObservation: async (event: (typeof observations)[number]) => {
observations.push(event);
return { status: "accepted" };
@@ -151,22 +159,21 @@ describe("VoiceTrackWorker identities", () => {
const controller = new AbortController();
const current = { input, controller, track: {}, commits: [] };
// Exercise the real consumer, including callback ordering and ASR cleanup.
- const consume = (epoch: number) =>
+ const consume = () =>
(
worker as unknown as { consume(...args: unknown[]): Promise<void> }
).consume(
{ room: {} },
"voice_session_retry",
- epoch,
{},
input,
{ attributes: {} },
controller.signal,
current,
);
- await expect(consume(0)).rejects.toThrow("ASR connection timed out");
+ await expect(consume()).rejects.toThrow("ASR connection timed out");
if (lost) oldest = 1200;
- await consume(1);
+ await consume();
expect(
observations.filter((event) => event.kind === "track_started"),
).toHaveLength(1);
@@ -484,4 +491,104 @@ describe("VoiceTrackWorker identities", () => {
),
).rejects.toMatchObject({ status: 400 });
});
+
+ it("retries a transient epoch claim and gives up on a missing session", async () => {
+ let calls = 0;
+ const flaky = {
+ claimMediaEpoch: async () => {
+ if (++calls < 3) throw new TeamHubVoiceRuntimeError(503);
+ return 7;
+ },
+ };
+ await expect(
+ claimVoiceMediaEpochWithRetry(flaky, "voice_session_1", [0, 0]),
+ ).resolves.toBe(7);
+ expect(calls).toBe(3);
+
+ let missingCalls = 0;
+ const missing = {
+ claimMediaEpoch: async () => {
+ missingCalls += 1;
+ throw new TeamHubVoiceRuntimeError(404);
+ },
+ };
+ await expect(
+ claimVoiceMediaEpochWithRetry(missing, "voice_session_1", [0, 0]),
+ ).rejects.toMatchObject({ status: 404 });
+ expect(missingCalls).toBe(1);
+ });
+
+ it("gives a restarted job a fresh epoch for the same session", async () => {
+ // One TeamHub counter outlives both worker instances, as PostgreSQL does.
+ const teamHubClaims = claimEpochs();
+ const observations: Array<{ kind: string; media_epoch: number }> = [];
+ const client = {
+ claimMediaEpoch: teamHubClaims,
+ reportObservation: async (event: (typeof observations)[number]) => {
+ observations.push(event);
+ return { status: "accepted" };
+ },
+ };
+ const provider = {
+ open: async () => {
+ let end!: () => void;
+ const done = new Promise<void>((resolve) => {
+ end = resolve;
+ });
+ return {
+ sendPCM: async () => undefined,
+ finish: async () => end(),
+ close: async () => end(),
+ async *events() {
+ await done;
+ yield* [];
+ },
+ };
+ },
+ };
+ const consumeOneTrack = async (worker: VoiceTrackWorker) => {
+ let sent = false;
+ const input = {
+ waitForFirstFrame: async () => undefined,
+ oldestRetainedAtMs: () => 1000,
+ firstFrameAtMs: () => 1000,
+ takeDroppedSamples: () => 0,
+ next: async () => {
+ if (sent) return undefined;
+ sent = true;
+ return {
+ data: new Int16Array(1600),
+ samplesPerChannel: 1600,
+ sampleRate: 16000,
+ };
+ },
+ stop: () => undefined,
+ };
+ const controller = new AbortController();
+ await (
+ worker as unknown as { consume(...args: unknown[]): Promise<void> }
+ ).consume(
+ { room: {} },
+ "voice_session_restart",
+ {},
+ input,
+ { attributes: {} },
+ controller.signal,
+ { input, controller, track: {}, commits: [] },
+ );
+ };
+
+ await consumeOneTrack(new VoiceTrackWorker(client as never, provider));
+ const beforeRestart = observations.length;
+ await consumeOneTrack(new VoiceTrackWorker(client as never, provider));
+
+ expect(
+ observations
+ .filter((event) => event.kind === "track_started")
+ .map((event) => event.media_epoch),
+ ).toEqual([0, 1]);
+ expect(
+ observations.slice(beforeRestart).map((event) => event.media_epoch),
+ ).toEqual(observations.slice(beforeRestart).map(() => 1));
+ });
});
diff --git a/apps/voice-runtime/src/livekit-worker.ts b/apps/voice-runtime/src/livekit-worker.ts
index 2809e65e..d2f66c32 100644
--- a/apps/voice-runtime/src/livekit-worker.ts
+++ b/apps/voice-runtime/src/livekit-worker.ts
@@ -52,7 +52,6 @@ interface CurrentVoiceTrack {
}
export class VoiceTrackWorker {
- private nextEpoch = 0;
private readonly active = new Set<Promise<void>>();
private readonly shutdownController = new AbortController();
private sessionCreatedAtMs = 0;
@@ -151,7 +150,6 @@ export class VoiceTrackWorker {
this.consume(
ctx,
voiceSessionId,
- this.nextEpoch++,
track,
input,
participant,
@@ -279,7 +277,6 @@ export class VoiceTrackWorker {
private async consume(
ctx: JobContext,
voiceSessionId: string,
- epoch: number,
track: RemoteAudioTrack,
input: TrackAudioInput,
participant: RemoteParticipant,
@@ -297,6 +294,12 @@ export class VoiceTrackWorker {
);
if (!Number.isSafeInteger(publisherGeneration) || publisherGeneration < 0)
throw new Error("Voice publisher generation is invalid");
+ // Every attempt opens its own coverage stream. TeamHub hands out the
+ // number so a job restarted mid-session never reuses an earlier job's.
+ const epoch = await claimVoiceMediaEpochWithRetry(
+ this.client,
+ voiceSessionId,
+ );
const epochStartMs = await this.startEpoch(
voiceSessionId,
epoch,
@@ -975,22 +978,42 @@ export const reportVoiceObservationWithRetry = async (
observation: VoiceObservation,
retryDelaysMs: readonly number[] = teamHubCallbackRetryDelaysMs,
) => {
+ // A newer snapshot replaces a partial or progress, so those never wait out
+ // a retry; finals retain their retry budget.
+ const snapshot =
+ observation.kind === "partial" || observation.kind === "progress";
+ try {
+ return await callTeamHubWithRetry(
+ (signal) => client.reportObservation(observation, signal),
+ snapshot ? [] : retryDelaysMs,
+ );
+ } catch (error) {
+ if (snapshot && isTransientObservationError(error)) return;
+ throw error;
+ }
+};
+
+/** Claims a fresh transcript epoch; a lost response only skips a number. */
+export const claimVoiceMediaEpochWithRetry = (
+ client: Pick<TeamHubVoiceRuntimeClient, "claimMediaEpoch">,
+ voiceSessionId: string,
+ retryDelaysMs: readonly number[] = teamHubCallbackRetryDelaysMs,
+) =>
+ callTeamHubWithRetry(
+ (signal) => client.claimMediaEpoch(voiceSessionId, signal),
+ retryDelaysMs,
+ );
+
+async function callTeamHubWithRetry<T>(
+ call: (signal: AbortSignal) => Promise<T>,
+ retryDelaysMs: readonly number[],
+): Promise<T> {
const budget = AbortSignal.timeout(teamHubCallbackBudgetMs);
for (let attempt = 0; ; attempt += 1) {
try {
budget.throwIfAborted();
- return await client.reportObservation(
- observation,
- AbortSignal.any([budget, AbortSignal.timeout(2_000)]),
- );
+ return await call(AbortSignal.any([budget, AbortSignal.timeout(2_000)]));
} catch (error) {
- if (
- (observation.kind === "partial" || observation.kind === "progress") &&
- isTransientObservationError(error)
- ) {
- // A newer snapshot replaces this one; finals retain their retry budget.
- return;
- }
if (
budget.aborted ||
attempt >= retryDelaysMs.length ||
@@ -1001,7 +1024,7 @@ export const reportVoiceObservationWithRetry = async (
await waitForAbortableDelay(retryDelaysMs[attempt] ?? 0, budget);
}
}
-};
+}
const isTransientObservationError = (error: unknown) =>
error instanceof TypeError ||
diff --git a/apps/voice-runtime/src/track-lifecycle.test.ts b/apps/voice-runtime/src/track-lifecycle.test.ts
index d2a48de1..caed3ada 100644
--- a/apps/voice-runtime/src/track-lifecycle.test.ts
+++ b/apps/voice-runtime/src/track-lifecycle.test.ts
@@ -11,6 +11,12 @@ import {
import { VoiceTrackWorker } from "./livekit-worker.js";
import { ASREventQueue } from "./event-queue.js";
+// Hands out media epochs the way TeamHub does: every claim takes a new number.
+function claimEpochs() {
+ let next = 0;
+ return async (_voiceSessionId: string) => next++;
+}
+
const audioInputs = vi.hoisted(
() => new Map<object, ReadableStreamDefaultController<AudioFrame>>(),
);
@@ -50,6 +56,7 @@ describe("Voice publisher track lifecycle", () => {
let shutdown!: () => Promise<void>;
const worker = new VoiceTrackWorker(
{
+ claimMediaEpoch: claimEpochs(),
reportObservation: async (event: VoiceObservation) => {
accepted.push(event);
return { event_id: event.event_id, status: "accepted" };
@@ -169,6 +176,7 @@ describe("Voice publisher track lifecycle", () => {
let shutdown!: () => Promise<void>;
const worker = new VoiceTrackWorker(
{
+ claimMediaEpoch: claimEpochs(),
reportObservation: async (event: VoiceObservation) => {
if (
slow &&
@@ -301,6 +309,7 @@ describe("Voice publisher track lifecycle", () => {
}));
const worker = new VoiceTrackWorker(
{
+ claimMediaEpoch: claimEpochs(),
reportObservation: async (event: VoiceObservation) => {
if (event.kind === "final") {
await new Promise((resolve) => setTimeout(resolve, 1_900));
@@ -405,6 +414,7 @@ describe("Voice publisher track lifecycle", () => {
}));
const worker = new VoiceTrackWorker(
{
+ claimMediaEpoch: claimEpochs(),
reportObservation: async (event: VoiceObservation) => {
if (event.kind === "partial" || event.kind === "progress")
throw new DOMException("callback timed out", "TimeoutError");
@@ -514,6 +524,7 @@ describe("Voice publisher track lifecycle", () => {
let opened = 0;
const worker = new VoiceTrackWorker(
{
+ claimMediaEpoch: claimEpochs(),
reportObservation: async (event: VoiceObservation) => {
observations.push(event);
return { event_id: event.event_id, status: "accepted" };
@@ -662,6 +673,7 @@ describe("Voice publisher input retention and absence evidence", () => {
});
const worker = new VoiceTrackWorker(
{
+ claimMediaEpoch: claimEpochs(),
reportObservation: async (event: VoiceObservation) => {
accepted.push(event);
return { event_id: event.event_id, status: "accepted" };
@@ -761,6 +773,7 @@ describe("Voice publisher input retention and absence evidence", () => {
const accepted: VoiceObservation[] = [];
const worker = new VoiceTrackWorker(
{
+ claimMediaEpoch: claimEpochs(),
reportObservation: async (event: VoiceObservation) => {
accepted.push(event);
return { event_id: event.event_id, status: "accepted" };
diff --git a/contracts/generated/go/teamhubinternal/openapi.gen.go b/contracts/generated/go/teamhubinternal/openapi.gen.go
index 58f61d18..a1db98c0 100644
--- a/contracts/generated/go/teamhubinternal/openapi.gen.go
+++ b/contracts/generated/go/teamhubinternal/openapi.gen.go
@@ -3705,6 +3705,11 @@ type VoiceLiveToolResult struct {
Output string `json:"output"`
}
+// VoiceMediaEpochClaim defines model for VoiceMediaEpochClaim.
+type VoiceMediaEpochClaim struct {
+ MediaEpoch int `json:"media_epoch"`
+}
+
// VoiceMediaObjectKey defines model for VoiceMediaObjectKey.
type VoiceMediaObjectKey = string
diff --git a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts
index 1a111a2d..f4d432ce 100644
--- a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts
@@ -1237,6 +1237,26 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/internal/v1/voice/sessions/{voiceSessionId}/media-epochs": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Claim the next transcript media epoch for one open VoiceSession.
+ * @description Every claim returns a number no earlier claim for the session returned, including claims made by a runtime job that has since restarted. Observations of a track carry the epoch claimed for it.
+ */
+ post: operations["claimVoiceMediaEpoch"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/internal/v1/voice/sessions/{voiceSessionId}/live-context": {
parameters: {
query?: never;
@@ -1377,6 +1397,9 @@ export interface components {
/** @enum {string} */
status: "accepted" | "ignored";
};
+ VoiceMediaEpochClaim: {
+ media_epoch: number;
+ };
VoiceMediaObjectKey: string;
VoiceRecordingReport: {
staging_prefix: string;
@@ -5262,6 +5285,30 @@ export interface operations {
404: components["responses"]["VoiceNotFound"];
};
};
+ claimVoiceMediaEpoch: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ voiceSessionId: components["schemas"]["VoiceId"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The claimed epoch. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["VoiceMediaEpochClaim"];
+ };
+ };
+ 401: components["responses"]["VoiceUnauthenticated"];
+ 404: components["responses"]["VoiceNotFound"];
+ };
+ };
getVoiceLiveContext: {
parameters: {
query?: never;
diff --git a/contracts/generated/typescript/src/teamhub-internal/client.ts b/contracts/generated/typescript/src/teamhub-internal/client.ts
index f99586d3..64d63155 100644
--- a/contracts/generated/typescript/src/teamhub-internal/client.ts
+++ b/contracts/generated/typescript/src/teamhub-internal/client.ts
@@ -740,6 +740,8 @@ export type VoiceDictationCommitRequest =
export type VoiceSessionPurpose = components["schemas"]["VoiceSessionPurpose"];
export type VoiceObservationReceipt =
components["schemas"]["VoiceObservationReceipt"];
+export type VoiceMediaEpochClaim =
+ components["schemas"]["VoiceMediaEpochClaim"];
export type VoiceMediaObjectKey = components["schemas"]["VoiceMediaObjectKey"];
export type VoiceRecordingReport =
components["schemas"]["VoiceRecordingReport"];
@@ -770,6 +772,19 @@ export class TeamHubVoiceRuntimeClient {
);
}
+ async claimMediaEpoch(
+ voiceSessionId: string,
+ signal?: AbortSignal,
+ ): Promise<number> {
+ const claim = await this.request<VoiceMediaEpochClaim>(
+ "POST",
+ `/internal/v1/voice/sessions/${encodeURIComponent(voiceSessionId)}/media-epochs`,
+ undefined,
+ signal,
+ );
+ return claim.media_epoch;
+ }
+
async putMediaObject(
key: VoiceMediaObjectKey,
bytes: Uint8Array,
diff --git a/contracts/openapi/teamhub-internal/openapi.yaml b/contracts/openapi/teamhub-internal/openapi.yaml
index d9eecf56..0a93aaa2 100644
--- a/contracts/openapi/teamhub-internal/openapi.yaml
+++ b/contracts/openapi/teamhub-internal/openapi.yaml
@@ -871,6 +871,32 @@ paths:
$ref: "#/components/responses/VoiceNotFound"
security:
- voiceRuntimeBearer: []
+ /internal/v1/voice/sessions/{voiceSessionId}/media-epochs:
+ post:
+ operationId: claimVoiceMediaEpoch
+ summary: Claim the next transcript media epoch for one open VoiceSession.
+ description: >-
+ Every claim returns a number no earlier claim for the session returned, including claims made by a runtime
+ job that has since restarted. Observations of a track carry the epoch claimed for it.
+ parameters:
+ - name: voiceSessionId
+ in: path
+ required: true
+ schema:
+ $ref: "#/components/schemas/VoiceId"
+ responses:
+ "200":
+ description: The claimed epoch.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/VoiceMediaEpochClaim"
+ "401":
+ $ref: "#/components/responses/VoiceUnauthenticated"
+ "404":
+ $ref: "#/components/responses/VoiceNotFound"
+ security:
+ - voiceRuntimeBearer: []
/internal/v1/voice/sessions/{voiceSessionId}/live-context:
get:
operationId: getVoiceLiveContext
@@ -1200,6 +1226,15 @@ components:
x-enum-varnames:
- VoiceObservationReceiptStatusAccepted
- VoiceObservationReceiptStatusIgnored
+ VoiceMediaEpochClaim:
+ type: object
+ additionalProperties: false
+ required:
+ - media_epoch
+ properties:
+ media_epoch:
+ type: integer
+ minimum: 0
VoiceMediaObjectKey:
type: string
minLength: 1