Skip to content

Commit 661afc2

Browse files
authored
fix(bedrock): release streaming clients (#117039)
1 parent 3cadc08 commit 661afc2

2 files changed

Lines changed: 103 additions & 1 deletion

File tree

‎extensions/amazon-bedrock/stream.runtime.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,104 @@ afterEach(() => {
6767
vi.restoreAllMocks();
6868
});
6969

70+
describe("Bedrock stream client lifecycle", () => {
71+
const context = {
72+
messages: [{ role: "user", content: "Hello", timestamp: 0 }],
73+
} as never;
74+
75+
function expectDestroyedClient(
76+
send: ReturnType<typeof vi.spyOn>,
77+
destroy: ReturnType<typeof vi.spyOn>,
78+
) {
79+
expect(send).toHaveBeenCalledOnce();
80+
expect(destroy).toHaveBeenCalledOnce();
81+
expect(destroy.mock.contexts[0]).toBe(send.mock.contexts[0]);
82+
expect(destroy.mock.invocationCallOrder[0]).toBeGreaterThan(
83+
send.mock.invocationCallOrder[0] ?? 0,
84+
);
85+
}
86+
87+
it("destroys the client after a successful stream", async () => {
88+
let markStreamBlocked!: () => void;
89+
const streamBlocked = new Promise<void>((resolve) => {
90+
markStreamBlocked = resolve;
91+
});
92+
let releaseStream!: () => void;
93+
const streamReleased = new Promise<void>((resolve) => {
94+
releaseStream = resolve;
95+
});
96+
async function* successfulStream() {
97+
yield { messageStart: { role: ConversationRole.ASSISTANT } };
98+
markStreamBlocked();
99+
await streamReleased;
100+
yield { messageStop: { stopReason: BedrockStopReason.END_TURN } };
101+
}
102+
const send = vi.spyOn(BedrockRuntimeClient.prototype, "send").mockResolvedValue({
103+
$metadata: { httpStatusCode: 200 },
104+
stream: successfulStream(),
105+
} as never);
106+
const destroy = vi.spyOn(BedrockRuntimeClient.prototype, "destroy");
107+
108+
const resultPromise = streamBedrockForTest(bedrockModel({}), context).result();
109+
await streamBlocked;
110+
expect(destroy).not.toHaveBeenCalled();
111+
112+
releaseStream();
113+
const result = await resultPromise;
114+
115+
expect(result.stopReason).toBe("stop");
116+
expectDestroyedClient(send, destroy);
117+
});
118+
119+
it("destroys the client after a provider error", async () => {
120+
const send = vi
121+
.spyOn(BedrockRuntimeClient.prototype, "send")
122+
.mockRejectedValue(new Error("synthetic provider failure"));
123+
const destroy = vi.spyOn(BedrockRuntimeClient.prototype, "destroy");
124+
125+
const result = await streamBedrockForTest(bedrockModel({}), context).result();
126+
127+
expect(result.stopReason).toBe("error");
128+
expect(result.errorMessage).toBe("synthetic provider failure");
129+
expectDestroyedClient(send, destroy);
130+
});
131+
132+
it("destroys the client when response stream iteration fails", async () => {
133+
async function* failingStream() {
134+
yield { messageStart: { role: ConversationRole.ASSISTANT } };
135+
throw new Error("synthetic iterator failure");
136+
}
137+
const send = vi.spyOn(BedrockRuntimeClient.prototype, "send").mockResolvedValue({
138+
$metadata: { httpStatusCode: 200 },
139+
stream: failingStream(),
140+
} as never);
141+
const destroy = vi.spyOn(BedrockRuntimeClient.prototype, "destroy");
142+
143+
const result = await streamBedrockForTest(bedrockModel({}), context).result();
144+
145+
expect(result.stopReason).toBe("error");
146+
expect(result.errorMessage).toBe("synthetic iterator failure");
147+
expectDestroyedClient(send, destroy);
148+
});
149+
150+
it("destroys the client after an aborted request", async () => {
151+
const controller = new AbortController();
152+
controller.abort();
153+
const send = vi
154+
.spyOn(BedrockRuntimeClient.prototype, "send")
155+
.mockRejectedValue(new Error("synthetic abort"));
156+
const destroy = vi.spyOn(BedrockRuntimeClient.prototype, "destroy");
157+
158+
const result = await streamBedrockForTest(bedrockModel({}), context, {
159+
signal: controller.signal,
160+
}).result();
161+
162+
expect(result.stopReason).toBe("aborted");
163+
expect(result.errorMessage).toBe("synthetic abort");
164+
expectDestroyedClient(send, destroy);
165+
});
166+
});
167+
70168
describe("Bedrock inbound image base64", () => {
71169
const model = () => bedrockModel({ input: ["text", "image"] });
72170
const userImage = (data: string) =>

‎extensions/amazon-bedrock/stream.runtime.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,9 @@ const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOptions> =
239239
config.authSchemePreference = ["httpBearerAuth"];
240240
}
241241

242+
let client: BedrockRuntimeClient | undefined;
242243
try {
243-
const client = new BedrockRuntimeClient(config);
244+
client = new BedrockRuntimeClient(config);
244245
const cacheRetention = resolveCacheRetention(options.cacheRetention);
245246
const additionalModelRequestFields = buildAdditionalModelRequestFields(model, options);
246247
const thinking = (additionalModelRequestFields as Record<string, unknown> | undefined)
@@ -373,6 +374,9 @@ const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOptions> =
373374
output.errorMessage = formatBedrockError(error);
374375
stream.push({ type: "error", reason: output.stopReason, error: output });
375376
stream.end();
377+
} finally {
378+
// The SDK client owns pooled HTTP resources; release them only after its async stream settles.
379+
client?.destroy();
376380
}
377381
})();
378382

0 commit comments

Comments
 (0)