Skip to content

Commit 212e47a

Browse files
committed
fix: avoid leaking memory when Client.with_options is used
Fixes openai/openai-python#865.
1 parent 1294213 commit 212e47a

File tree

4 files changed

+141
-17
lines changed

4 files changed

+141
-17
lines changed

pyproject.toml

-2
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,6 @@ select = [
149149
"T203",
150150
]
151151
ignore = [
152-
# lru_cache in methods, will be fixed separately
153-
"B019",
154152
# mutable defaults
155153
"B006",
156154
]

src/orb/_base_client.py

+15-13
Original file line numberDiff line numberDiff line change
@@ -403,14 +403,12 @@ def _build_headers(self, options: FinalRequestOptions) -> httpx.Headers:
403403
headers_dict = _merge_mappings(self.default_headers, custom_headers)
404404
self._validate_headers(headers_dict, custom_headers)
405405

406+
# headers are case-insensitive while dictionaries are not.
406407
headers = httpx.Headers(headers_dict)
407408

408409
idempotency_header = self._idempotency_header
409410
if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers:
410-
if not options.idempotency_key:
411-
options.idempotency_key = self._idempotency_key()
412-
413-
headers[idempotency_header] = options.idempotency_key
411+
headers[idempotency_header] = options.idempotency_key or self._idempotency_key()
414412

415413
return headers
416414

@@ -594,16 +592,8 @@ def base_url(self) -> URL:
594592
def base_url(self, url: URL | str) -> None:
595593
self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url))
596594

597-
@lru_cache(maxsize=None)
598595
def platform_headers(self) -> Dict[str, str]:
599-
return {
600-
"X-Stainless-Lang": "python",
601-
"X-Stainless-Package-Version": self._version,
602-
"X-Stainless-OS": str(get_platform()),
603-
"X-Stainless-Arch": str(get_architecture()),
604-
"X-Stainless-Runtime": platform.python_implementation(),
605-
"X-Stainless-Runtime-Version": platform.python_version(),
606-
}
596+
return platform_headers(self._version)
607597

608598
def _calculate_retry_timeout(
609599
self,
@@ -1691,6 +1681,18 @@ def get_platform() -> Platform:
16911681
return "Unknown"
16921682

16931683

1684+
@lru_cache(maxsize=None)
1685+
def platform_headers(version: str) -> Dict[str, str]:
1686+
return {
1687+
"X-Stainless-Lang": "python",
1688+
"X-Stainless-Package-Version": version,
1689+
"X-Stainless-OS": str(get_platform()),
1690+
"X-Stainless-Arch": str(get_architecture()),
1691+
"X-Stainless-Runtime": platform.python_implementation(),
1692+
"X-Stainless-Runtime-Version": platform.python_version(),
1693+
}
1694+
1695+
16941696
class OtherArch:
16951697
def __init__(self, name: str) -> None:
16961698
self.name = name

src/orb/_client.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def copy(
181181
http_client = http_client or self._client
182182
return self.__class__(
183183
api_key=api_key or self.api_key,
184-
base_url=base_url or str(self.base_url),
184+
base_url=base_url or self.base_url,
185185
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
186186
http_client=http_client,
187187
max_retries=max_retries if is_given(max_retries) else self.max_retries,
@@ -427,7 +427,7 @@ def copy(
427427
http_client = http_client or self._client
428428
return self.__class__(
429429
api_key=api_key or self.api_key,
430-
base_url=base_url or str(self.base_url),
430+
base_url=base_url or self.base_url,
431431
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
432432
http_client=http_client,
433433
max_retries=max_retries if is_given(max_retries) else self.max_retries,

tests/test_client.py

+124
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22

33
from __future__ import annotations
44

5+
import gc
56
import os
67
import json
78
import asyncio
89
import inspect
10+
import tracemalloc
911
from typing import Any, Union, cast
1012
from unittest import mock
1113

@@ -192,6 +194,67 @@ def test_copy_signature(self) -> None:
192194
copy_param = copy_signature.parameters.get(name)
193195
assert copy_param is not None, f"copy() signature is missing the {name} param"
194196

197+
def test_copy_build_request(self) -> None:
198+
options = FinalRequestOptions(method="get", url="/foo")
199+
200+
def build_request(options: FinalRequestOptions) -> None:
201+
client = self.client.copy()
202+
client._build_request(options)
203+
204+
# ensure that the machinery is warmed up before tracing starts.
205+
build_request(options)
206+
gc.collect()
207+
208+
tracemalloc.start(1000)
209+
210+
snapshot_before = tracemalloc.take_snapshot()
211+
212+
ITERATIONS = 10
213+
for _ in range(ITERATIONS):
214+
build_request(options)
215+
gc.collect()
216+
217+
snapshot_after = tracemalloc.take_snapshot()
218+
219+
tracemalloc.stop()
220+
221+
def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None:
222+
if diff.count == 0:
223+
# Avoid false positives by considering only leaks (i.e. allocations that persist).
224+
return
225+
226+
if diff.count % ITERATIONS != 0:
227+
# Avoid false positives by considering only leaks that appear per iteration.
228+
return
229+
230+
for frame in diff.traceback:
231+
if any(
232+
frame.filename.endswith(fragment)
233+
for fragment in [
234+
# to_raw_response_wrapper leaks through the @functools.wraps() decorator.
235+
#
236+
# removing the decorator fixes the leak for reasons we don't understand.
237+
"orb/_response.py",
238+
# pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason.
239+
"orb/_compat.py",
240+
# Standard library leaks we don't care about.
241+
"/logging/__init__.py",
242+
]
243+
):
244+
return
245+
246+
leaks.append(diff)
247+
248+
leaks: list[tracemalloc.StatisticDiff] = []
249+
for diff in snapshot_after.compare_to(snapshot_before, "traceback"):
250+
add_leak(leaks, diff)
251+
if leaks:
252+
for leak in leaks:
253+
print("MEMORY LEAK:", leak)
254+
for frame in leak.traceback:
255+
print(frame)
256+
raise AssertionError()
257+
195258
def test_request_timeout(self) -> None:
196259
request = self.client._build_request(FinalRequestOptions(method="get", url="/foo"))
197260
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
@@ -846,6 +909,67 @@ def test_copy_signature(self) -> None:
846909
copy_param = copy_signature.parameters.get(name)
847910
assert copy_param is not None, f"copy() signature is missing the {name} param"
848911

912+
def test_copy_build_request(self) -> None:
913+
options = FinalRequestOptions(method="get", url="/foo")
914+
915+
def build_request(options: FinalRequestOptions) -> None:
916+
client = self.client.copy()
917+
client._build_request(options)
918+
919+
# ensure that the machinery is warmed up before tracing starts.
920+
build_request(options)
921+
gc.collect()
922+
923+
tracemalloc.start(1000)
924+
925+
snapshot_before = tracemalloc.take_snapshot()
926+
927+
ITERATIONS = 10
928+
for _ in range(ITERATIONS):
929+
build_request(options)
930+
gc.collect()
931+
932+
snapshot_after = tracemalloc.take_snapshot()
933+
934+
tracemalloc.stop()
935+
936+
def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None:
937+
if diff.count == 0:
938+
# Avoid false positives by considering only leaks (i.e. allocations that persist).
939+
return
940+
941+
if diff.count % ITERATIONS != 0:
942+
# Avoid false positives by considering only leaks that appear per iteration.
943+
return
944+
945+
for frame in diff.traceback:
946+
if any(
947+
frame.filename.endswith(fragment)
948+
for fragment in [
949+
# to_raw_response_wrapper leaks through the @functools.wraps() decorator.
950+
#
951+
# removing the decorator fixes the leak for reasons we don't understand.
952+
"orb/_response.py",
953+
# pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason.
954+
"orb/_compat.py",
955+
# Standard library leaks we don't care about.
956+
"/logging/__init__.py",
957+
]
958+
):
959+
return
960+
961+
leaks.append(diff)
962+
963+
leaks: list[tracemalloc.StatisticDiff] = []
964+
for diff in snapshot_after.compare_to(snapshot_before, "traceback"):
965+
add_leak(leaks, diff)
966+
if leaks:
967+
for leak in leaks:
968+
print("MEMORY LEAK:", leak)
969+
for frame in leak.traceback:
970+
print(frame)
971+
raise AssertionError()
972+
849973
async def test_request_timeout(self) -> None:
850974
request = self.client._build_request(FinalRequestOptions(method="get", url="/foo"))
851975
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore

0 commit comments

Comments
 (0)