Skip to content

Commit 133a8a6

Browse files
committed
fix(voice-call): bound replay memory during long-running calls (#117437)
* origin/fix/voice-call-replay-bounds-20260801: fix(voice-call): keep replay caps production-owned test(voice-call): share replay cap constants test(voice-call): assert replay collection bounds test(voice-call): cover replay ownership bounds fix(voice-call): bound manager replay ownership
2 parents 3146736 + 02c8e76 commit 133a8a6

9 files changed

Lines changed: 349 additions & 24 deletions

File tree

‎extensions/voice-call/src/manager.restore.test.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
makePersistedCall,
1414
writeCallsToStore,
1515
} from "./manager.test-harness.js";
16+
import { MAX_CALL_REPLAY_KEYS } from "./manager/replay-keys.js";
1617
import { loadActiveCallsFromStore } from "./manager/store.js";
1718
import { setVoiceCallStateRuntime } from "./runtime-state.js";
1819

@@ -391,11 +392,15 @@ describe("CallManager verification on restore", () => {
391392

392393
it("restores dedupe keys from terminal persisted calls so replayed webhooks stay ignored", async () => {
393394
const storePath = createTestStorePath();
395+
const replayKeys = Array.from(
396+
{ length: MAX_CALL_REPLAY_KEYS + 2 },
397+
(_, index) => `evt-terminal-${index}`,
398+
);
394399
const persisted = makePersistedCall({
395400
state: "completed",
396401
endedAt: Date.now() - 5_000,
397402
endReason: "completed",
398-
processedEventIds: ["evt-terminal-init"],
403+
processedEventIds: replayKeys,
399404
});
400405
writeCallsToStore(storePath, [persisted]);
401406

@@ -409,7 +414,7 @@ describe("CallManager verification on restore", () => {
409414
await manager.initialize(provider, "https://example.com/voice/webhook");
410415

411416
manager.processEvent({
412-
id: "evt-terminal-init",
417+
id: replayKeys.at(-1) as string,
413418
type: "call.initiated",
414419
callId: String(persisted.providerCallId),
415420
providerCallId: String(persisted.providerCallId),
@@ -420,5 +425,18 @@ describe("CallManager verification on restore", () => {
420425
});
421426

422427
expect(manager.getActiveCalls()).toHaveLength(0);
428+
429+
manager.processEvent({
430+
id: replayKeys[0] as string,
431+
type: "call.initiated",
432+
callId: String(persisted.providerCallId),
433+
providerCallId: String(persisted.providerCallId),
434+
timestamp: Date.now(),
435+
direction: "outbound",
436+
from: "+15550000000",
437+
to: "+15550000001",
438+
});
439+
440+
expect(manager.getActiveCalls()).toHaveLength(1);
423441
});
424442
});

‎extensions/voice-call/src/manager.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ export class CallManager {
7070
private activeCalls = new Map<CallId, CallRecord>();
7171
private providerCallIdMap = new Map<string, CallId>();
7272
private processedEventIds = new Set<string>();
73-
private rejectedProviderCallIds = new Set<string>();
73+
private rejectedProviderCallIds = new Map<string, symbol>();
7474
private provider: VoiceCallProvider | null = null;
7575
private config: VoiceCallConfig;
7676
private coreSession: VoiceCallCoreSessionConfig | undefined;
@@ -117,7 +117,7 @@ export class CallManager {
117117

118118
const persisted = loadActiveCallsFromStore(this.storePath);
119119
this.processedEventIds = persisted.processedEventIds;
120-
this.rejectedProviderCallIds = persisted.rejectedProviderCallIds;
120+
this.rejectedProviderCallIds = new Map();
121121

122122
const verified = await this.verifyRestoredCalls(provider, persisted.activeCalls);
123123
this.activeCalls = verified;

‎extensions/voice-call/src/manager/context.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ type CallManagerRuntimeState = {
1414
activeCalls: Map<CallId, CallRecord>;
1515
providerCallIdMap: Map<string, CallId>;
1616
processedEventIds: Set<string>;
17-
/** Provider call IDs we already sent a reject hangup for; avoids duplicate hangup calls. */
18-
rejectedProviderCallIds: Set<string>;
17+
/** Provider call IDs reserved for reject hangup; avoids duplicate hangup calls. */
18+
rejectedProviderCallIds: Map<string, symbol>;
1919
};
2020

2121
type CallManagerRuntimeDeps = {

‎extensions/voice-call/src/manager/events.test.ts‎

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ import type { AnswerCallInput, HangupCallInput, NormalizedEvent } from "../types
1515
import type { CallManagerContext } from "./context.js";
1616
import { processEvent } from "./events.js";
1717
import { speakInitialMessage } from "./outbound.js";
18+
import { MAX_CALL_REPLAY_KEYS } from "./replay-keys.js";
1819

20+
const MANAGER_REPLAY_KEY_LIMIT = 10_000;
1921
const logSpy = vi.hoisted(() => {
2022
const logEntries: string[] = [];
2123
return {
@@ -93,7 +95,7 @@ function createContext(overrides: Partial<CallManagerContext> = {}): CallManager
9395
activeCalls: new Map(),
9496
providerCallIdMap: new Map(),
9597
processedEventIds: new Set(),
96-
rejectedProviderCallIds: new Set(),
98+
rejectedProviderCallIds: new Map(),
9799
provider: null,
98100
config: VoiceCallConfigSchema.parse({
99101
enabled: true,
@@ -771,6 +773,91 @@ describe("processEvent (functional)", () => {
771773
expect(replayResult).toEqual({ kind: "ignored" });
772774
});
773775

776+
it("bounds committed replay keys in both manager and persisted call owners", () => {
777+
const now = Date.now();
778+
const managerKeys = Array.from(
779+
{ length: MANAGER_REPLAY_KEY_LIMIT },
780+
(_, index) => `manager-${index}`,
781+
);
782+
const callKeys = Array.from({ length: MAX_CALL_REPLAY_KEYS }, (_, index) => `call-${index}`);
783+
const ctx = createContext({ processedEventIds: new Set(managerKeys) });
784+
ctx.activeCalls.set("call-bounded", {
785+
callId: "call-bounded",
786+
providerCallId: "provider-bounded",
787+
provider: "plivo",
788+
direction: "outbound",
789+
state: "active",
790+
from: "+15550000000",
791+
to: "+15550000001",
792+
startedAt: now,
793+
transcript: [],
794+
processedEventIds: callKeys,
795+
metadata: {},
796+
});
797+
ctx.providerCallIdMap.set("provider-bounded", "call-bounded");
798+
799+
const result = processEvent(ctx, {
800+
id: "evt-bounded-new",
801+
type: "call.dtmf",
802+
callId: "call-bounded",
803+
providerCallId: "provider-bounded",
804+
timestamp: now + 1,
805+
digits: "1",
806+
});
807+
808+
const call = ctx.activeCalls.get("call-bounded");
809+
expect(result).toEqual({ kind: "processed" });
810+
expect(ctx.processedEventIds.size).toBe(MANAGER_REPLAY_KEY_LIMIT);
811+
expect(ctx.processedEventIds.has("manager-0")).toBe(false);
812+
expect(ctx.processedEventIds.has("evt-bounded-new")).toBe(true);
813+
expect(call?.processedEventIds).toHaveLength(MAX_CALL_REPLAY_KEYS);
814+
expect(call?.processedEventIds[0]).toBe("call-1");
815+
expect(call?.processedEventIds.at(-1)).toBe("evt-bounded-new");
816+
expect(
817+
processEvent(ctx, {
818+
id: "evt-bounded-new",
819+
type: "call.dtmf",
820+
callId: "call-bounded",
821+
providerCallId: "provider-bounded",
822+
timestamp: now + 2,
823+
digits: "1",
824+
}),
825+
).toEqual({ kind: "ignored" });
826+
});
827+
828+
it("bounds rejected provider calls while retaining hangup-once behavior", () => {
829+
const rejectedProviderCallIds = new Map<string, symbol>(
830+
Array.from(
831+
{ length: MANAGER_REPLAY_KEY_LIMIT },
832+
(_, index) => [`provider-${index}`, Symbol(`provider-${index}`)] as const,
833+
),
834+
);
835+
const { ctx, hangupCalls } = createRejectingInboundContext();
836+
ctx.rejectedProviderCallIds = rejectedProviderCallIds;
837+
838+
processEvent(
839+
ctx,
840+
createInboundInitiatedEvent({
841+
id: "evt-rejected-new",
842+
providerCallId: "provider-new",
843+
from: "+15552222222",
844+
}),
845+
);
846+
processEvent(
847+
ctx,
848+
createInboundInitiatedEvent({
849+
id: "evt-rejected-new-replay",
850+
providerCallId: "provider-new",
851+
from: "+15552222222",
852+
}),
853+
);
854+
855+
expect(ctx.rejectedProviderCallIds.size).toBe(MANAGER_REPLAY_KEY_LIMIT);
856+
expect(ctx.rejectedProviderCallIds.has("provider-0")).toBe(false);
857+
expect(ctx.rejectedProviderCallIds.has("provider-new")).toBe(true);
858+
expect(hangupCalls).toHaveLength(1);
859+
});
860+
774861
it("keeps retryable call.error events replayable", () => {
775862
const now = Date.now();
776863
const ctx = createContext();

‎extensions/voice-call/src/manager/events.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ import type { CallManagerContext } from "./context.js";
1111
import { finalizeCall } from "./lifecycle.js";
1212
import { findCall } from "./lookup.js";
1313
import { endCall } from "./outbound.js";
14+
import {
15+
appendCallReplayKey,
16+
releaseRejectedProviderCall,
17+
rememberManagerReplayKey,
18+
reserveRejectedProviderCall,
19+
} from "./replay-keys.js";
1420
import { addTranscriptEntry, transitionState } from "./state.js";
1521
import { persistCallRecord } from "./store.js";
1622
import {
@@ -182,11 +188,11 @@ export function processEvent(ctx: EventContext, event: NormalizedEvent): Process
182188
);
183189
return { kind: "ignored" };
184190
}
185-
ctx.processedEventIds.add(dedupeKey);
186-
if (ctx.rejectedProviderCallIds.has(pid)) {
191+
rememberManagerReplayKey(ctx.processedEventIds, dedupeKey);
192+
const rejectionReservation = reserveRejectedProviderCall(ctx.rejectedProviderCallIds, pid);
193+
if (rejectionReservation === undefined) {
187194
return { kind: "ignored" };
188195
}
189-
ctx.rejectedProviderCallIds.add(pid);
190196
const callId = event.callId ?? pid;
191197
persistRejectedInboundCall({ ctx, event, dedupeKey, providerCallId: pid });
192198
log.info(`Rejecting inbound call by policy: ${pid}`);
@@ -197,7 +203,7 @@ export function processEvent(ctx: EventContext, event: NormalizedEvent): Process
197203
reason: "hangup-bot",
198204
})
199205
.catch((err: unknown) => {
200-
ctx.rejectedProviderCallIds.delete(pid);
206+
releaseRejectedProviderCall(ctx.rejectedProviderCallIds, pid, rejectionReservation);
201207
const message = formatErrorMessage(err);
202208
log.warn(`Failed to reject inbound call ${pid}: ${message}`);
203209
});
@@ -234,8 +240,8 @@ export function processEvent(ctx: EventContext, event: NormalizedEvent): Process
234240

235241
const shouldCommitReplayKey = !(event.type === "call.error" && event.retryable);
236242
if (shouldCommitReplayKey) {
237-
ctx.processedEventIds.add(dedupeKey);
238-
call.processedEventIds.push(dedupeKey);
243+
rememberManagerReplayKey(ctx.processedEventIds, dedupeKey);
244+
appendCallReplayKey(call.processedEventIds, dedupeKey);
239245
}
240246

241247
let result: ProcessEventResult = { kind: "processed" };
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { describe, expect, it } from "vitest";
2+
import {
3+
appendCallReplayKey,
4+
releaseRejectedProviderCall,
5+
rememberManagerReplayKey,
6+
reserveRejectedProviderCall,
7+
trimCallReplayKeys,
8+
} from "./replay-keys.js";
9+
10+
describe("voice-call manager replay keys", () => {
11+
it("evicts the oldest unique manager key without refreshing duplicates", () => {
12+
const keys = new Set<string>();
13+
14+
for (const key of ["a", "b", "c", "a", "d"]) {
15+
rememberManagerReplayKey(keys, key, 3);
16+
}
17+
18+
expect([...keys]).toEqual(["b", "c", "d"]);
19+
});
20+
21+
it("keeps the newest per-call replay keys in insertion order", () => {
22+
const keys = ["a", "b", "c", "d"];
23+
24+
trimCallReplayKeys(keys, 3);
25+
appendCallReplayKey(keys, "e", 3);
26+
27+
expect(keys).toEqual(["c", "d", "e"]);
28+
});
29+
30+
it("does not let a stale failed rejection release a newer reservation", () => {
31+
const calls = new Map<string, symbol>();
32+
const firstReservation = reserveRejectedProviderCall(calls, "provider-a", 1);
33+
expect(firstReservation).toBeDefined();
34+
35+
reserveRejectedProviderCall(calls, "provider-b", 1);
36+
const newerReservation = reserveRejectedProviderCall(calls, "provider-a", 1);
37+
expect(newerReservation).toBeDefined();
38+
39+
releaseRejectedProviderCall(calls, "provider-a", firstReservation as symbol);
40+
41+
expect(calls.get("provider-a")).toBe(newerReservation);
42+
});
43+
});
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Voice Call manager helpers own bounded webhook replay identity.
2+
3+
/** Match the existing voice-call webhook replay-cache cardinality. */
4+
const MAX_MANAGER_REPLAY_KEYS = 10_000;
5+
/** Keep typical provider replay IDs near one raw persisted-record chunk. */
6+
export const MAX_CALL_REPLAY_KEYS = 500;
7+
8+
function pruneOldestSetEntries(keys: Set<string>, maxEntries: number): void {
9+
while (keys.size > maxEntries) {
10+
const oldest = keys.values().next().value;
11+
if (oldest === undefined) {
12+
break;
13+
}
14+
keys.delete(oldest);
15+
}
16+
}
17+
18+
function pruneOldestMapEntries(keys: Map<string, symbol>, maxEntries: number): void {
19+
while (keys.size > maxEntries) {
20+
const oldest = keys.keys().next().value;
21+
if (oldest === undefined) {
22+
break;
23+
}
24+
keys.delete(oldest);
25+
}
26+
}
27+
28+
/** Remember one manager replay key without refreshing duplicate insertion order. */
29+
export function rememberManagerReplayKey(
30+
keys: Set<string>,
31+
key: string,
32+
maxEntries = MAX_MANAGER_REPLAY_KEYS,
33+
): void {
34+
keys.add(key);
35+
pruneOldestSetEntries(keys, maxEntries);
36+
}
37+
38+
/** Append one per-call replay key and retain only the newest bounded suffix. */
39+
export function appendCallReplayKey(
40+
keys: string[],
41+
key: string,
42+
maxEntries = MAX_CALL_REPLAY_KEYS,
43+
): void {
44+
keys.push(key);
45+
trimCallReplayKeys(keys, maxEntries);
46+
}
47+
48+
/** Normalize restored or externally constructed call replay history in place. */
49+
export function trimCallReplayKeys(keys: string[], maxEntries = MAX_CALL_REPLAY_KEYS): void {
50+
const overflow = keys.length - maxEntries;
51+
if (overflow > 0) {
52+
keys.splice(0, overflow);
53+
}
54+
}
55+
56+
/**
57+
* Reserve one rejected provider call. The token prevents a stale failed
58+
* hangup from deleting a newer reservation after bounded eviction and reuse.
59+
*/
60+
export function reserveRejectedProviderCall(
61+
calls: Map<string, symbol>,
62+
providerCallId: string,
63+
maxEntries = MAX_MANAGER_REPLAY_KEYS,
64+
): symbol | undefined {
65+
if (calls.has(providerCallId)) {
66+
return undefined;
67+
}
68+
const reservation = Symbol(providerCallId);
69+
calls.set(providerCallId, reservation);
70+
pruneOldestMapEntries(calls, maxEntries);
71+
return reservation;
72+
}
73+
74+
/** Release a rejected-call reservation only when the failing attempt still owns it. */
75+
export function releaseRejectedProviderCall(
76+
calls: Map<string, symbol>,
77+
providerCallId: string,
78+
reservation: symbol,
79+
): void {
80+
if (calls.get(providerCallId) === reservation) {
81+
calls.delete(providerCallId);
82+
}
83+
}

0 commit comments

Comments
 (0)