1
+"""Parsing, formatting and once-per-process emission of the
2
+``Composio-Deprecated-Toolkits`` response header.
3
+
4
+The end-to-end path through ``Composio(...)`` and the generated client lives in
5
+``tests/test_sdk_logging.py``; this file pins the pure helpers.
6
+"""
7
+
8
+import threading
9
+import typing as t
10
+import warnings
11
+from datetime import datetime, timezone
12
+
13
+import httpx
14
+import pytest
15
+
16
+from composio import ComposioDeprecationWarning
17
+from composio.utils import toolkit_deprecation as td
18
+from composio.utils.toolkit_deprecation import (
19
+ DOCS_URL,
20
+ HEADER,
21
+ DeprecatedToolkit,
22
+ format_warnings,
23
+ install_hook,
24
+ parse_deprecated_toolkits_header,
25
+ response_hook,
26
+ warn_deprecated_toolkits,
27
+)
28
+
29
+FULL_ITEM = (
30
+ '"GMAIL";version="20250114_00";deprecated=@1779840000;'
31
+ 'sunset=@1787788800;reason="lifecycle"'
32
+)
33
+BARE_ITEM = '"STRAVA";version="20240902_00"'
34
+DOCS = "https://docs.example/deprecation"
35
+
36
+
37
+def _utc(seconds: int) -> datetime:
38
+ return datetime.fromtimestamp(seconds, tz=timezone.utc)
39
+
40
+
41
+def _entry(**overrides: t.Any) -> DeprecatedToolkit:
42
+ values: dict[str, t.Any] = {"slug": "GMAIL", "version": "20250114_00"}
43
+ values.update(overrides)
44
+ return DeprecatedToolkit(**values)
45
+
46
+
47
+@pytest.fixture(autouse=True)
48
+def _reset_warned() -> t.Iterator[None]:
49
+ td._reset_for_tests()
50
+ yield
51
+ td._reset_for_tests()
52
+
53
+
54
+def _deprecations(caught: list[warnings.WarningMessage]) -> list[str]:
55
+ return [
56
+ str(w.message)
57
+ for w in caught
58
+ if issubclass(w.category, ComposioDeprecationWarning)
59
+ ]
60
+
61
+
62
+class TestParse:
63
+ def test_full_item(self):
64
+ assert parse_deprecated_toolkits_header(FULL_ITEM) == [
65
+ DeprecatedToolkit(
66
+ slug="GMAIL",
67
+ version="20250114_00",
68
+ deprecated_at=_utc(1779840000),
69
+ sunset_at=_utc(1787788800),
70
+ reason="lifecycle",
71
+ )
72
+ ]
73
+
74
+ def test_dates_are_timezone_aware_utc(self):
75
+ (entry,) = parse_deprecated_toolkits_header(FULL_ITEM)
76
+ assert entry.deprecated_at is not None
77
+ assert entry.deprecated_at.tzinfo is timezone.utc
78
+ assert entry.deprecated_at.isoformat() == "2026-05-27T00:00:00+00:00"
79
+
80
+ def test_bare_item(self):
81
+ assert parse_deprecated_toolkits_header(BARE_ITEM) == [
82
+ DeprecatedToolkit(slug="STRAVA", version="20240902_00")
83
+ ]
84
+
85
+ def test_two_items(self):
86
+ entries = parse_deprecated_toolkits_header(f"{FULL_ITEM}, {BARE_ITEM}")
87
+ assert [e.key for e in entries] == ["GMAIL@20250114_00", "STRAVA@20240902_00"]
88
+
89
+ def test_escaped_quote_and_backslash_in_slug(self):
90
+ entries = parse_deprecated_toolkits_header(
91
+ '"ODD\\"SLUG\\\\";version="20250101_00", "GMAIL";version="20250114_00"'
92
+ )
93
+ assert [e.slug for e in entries] == ['ODD"SLUG\\', "GMAIL"]
94
+
95
+ def test_whitespace_variations(self):
96
+ entries = parse_deprecated_toolkits_header(
97
+ ' "GMAIL" ; version = "20250114_00" ; sunset = @1787788800 ,'
98
+ '"STRAVA";version="20240902_00" '
99
+ )
100
+ assert entries == [
101
+ DeprecatedToolkit(
102
+ slug="GMAIL", version="20250114_00", sunset_at=_utc(1787788800)
103
+ ),
104
+ DeprecatedToolkit(slug="STRAVA", version="20240902_00"),
105
+ ]
106
+
107
+ @pytest.mark.parametrize(
108
+ "value",
109
+ [
110
+ "",
111
+ " ",
112
+ "not a structured field",
113
+ "GMAIL;version=20250114_00",
114
+ '"GMAIL";version="unterminated',
115
+ ",,,;;;===",
116
+ '"GMAIL;version=;;@@',
117
+ ],
118
+ )
119
+ def test_garbage_yields_empty_list(self, value: str):
120
+ assert parse_deprecated_toolkits_header(value) == []
121
+
122
+ def test_unknown_parameters_are_ignored(self):
123
+ assert parse_deprecated_toolkits_header(
124
+ '"GMAIL";version="20250114_00";severity=3;flag;note="x"'
125
+ ) == [DeprecatedToolkit(slug="GMAIL", version="20250114_00")]
126
+
127
+ def test_item_without_version_is_dropped_but_siblings_kept(self):
128
+ assert parse_deprecated_toolkits_header(
129
+ f'"GMAIL";deprecated=@1779840000, {BARE_ITEM}'
130
+ ) == [DeprecatedToolkit(slug="STRAVA", version="20240902_00")]
131
+
132
+ @pytest.mark.parametrize(
133
+ "value",
134
+ [
135
+ '"GMAIL";version=20250114_00',
136
+ '"GMAIL";version="1";deprecated="2026-05-27"',
137
+ '"GMAIL";version="1";reason=lifecycle',
138
+ '"GM\\nAIL";version="1"',
139
+ ],
140
+ )
141
+ def test_wrong_type_or_bad_escape_drops_item(self, value: str):
142
+ assert parse_deprecated_toolkits_header(value) == []
143
+
144
+
145
+class TestFormat:
146
+ def test_full_message(self):
147
+ (line,) = format_warnings(parse_deprecated_toolkits_header(FULL_ITEM), DOCS)
148
+ assert line == (
149
+ "[Deprecation] Toolkit GMAIL version 20250114_00 was deprecated on "
150
+ "2026-05-27 (lifecycle) and will stop working on 2026-08-27. "
151
+ 'Pin a newer version with toolkit_versions={"gmail": "<version>"} '
152
+ f"or COMPOSIO_TOOLKIT_VERSION_GMAIL. See {DOCS}."
153
+ )
154
+
155
+ def test_omits_reason_and_sunset_when_absent(self):
156
+ (line,) = format_warnings([_entry(slug="STRAVA", version="20240902_00")], DOCS)
157
+ assert line == (
158
+ "[Deprecation] Toolkit STRAVA version 20240902_00 was deprecated. "
159
+ 'Pin a newer version with toolkit_versions={"strava": "<version>"} '
160
+ f"or COMPOSIO_TOOLKIT_VERSION_STRAVA. See {DOCS}."
161
+ )
162
+
163
+ def test_keeps_deprecation_date_when_only_sunset_missing(self):
164
+ (line,) = format_warnings(
165
+ [_entry(deprecated_at=_utc(1779840000), reason="security")], DOCS
166
+ )
167
+ assert "was deprecated on 2026-05-27 (security). Pin" in line
168
+ assert "stop working" not in line
169
+
170
+ def test_default_docs_url(self):
171
+ (line,) = format_warnings([_entry()])
172
+ assert line.endswith(f"See {DOCS_URL}.")
173
+ assert DOCS_URL == (
174
+ "https://docs.composio.dev/docs/tools-direct/toolkit-versioning"
175
+ "#deprecation-and-sunset"
176
+ )
177
+
178
+ def test_groups_six_versions_into_one_line_naming_five(self):
179
+ entries = [
180
+ _entry(
181
+ version=f"202501{suffix:02d}_00",
182
+ sunset_at=datetime(2026, 8, 20 + suffix, tzinfo=timezone.utc),
183
+ )
184
+ for suffix in range(1, 7)
185
+ ]
186
+ lines = format_warnings(entries, DOCS)
187
+ assert lines == [
188
+ "[Deprecation] Toolkit GMAIL versions 20250101_00, 20250102_00, "
189
+ "20250103_00, 20250104_00, 20250105_00 and 1 more are deprecated and "
190
+ "the earliest will stop working on 2026-08-21. "
191
+ 'Pin a newer version with toolkit_versions={"gmail": "<version>"} '
192
+ f"or COMPOSIO_TOOLKIT_VERSION_GMAIL. See {DOCS}."
193
+ ]
194
+
195
+ def test_one_line_per_slug_grouped_case_insensitively(self):
196
+ lines = format_warnings(
197
+ [
198
+ _entry(slug="GMAIL", version="1"),
199
+ _entry(slug="STRAVA", version="1"),
200
+ _entry(slug="gmail", version="2"),
201
+ ],
202
+ DOCS,
203
+ )
204
+ assert len(lines) == 2
205
+ assert "Toolkit GMAIL versions 1, 2 are deprecated." in lines[0]
206
+ assert "Toolkit STRAVA version 1 was deprecated." in lines[1]
207
+
208
+ def test_no_entries_no_lines(self):
209
+ assert format_warnings([], DOCS) == []
210
+
211
+
212
+class TestWarnOnce:
213
+ def test_warns_once_per_key_across_calls(self):
214
+ headers = httpx.Headers({HEADER: FULL_ITEM})
215
+ with warnings.catch_warnings(record=True) as caught:
216
+ warnings.simplefilter("always")
217
+ warn_deprecated_toolkits(headers)
218
+ warn_deprecated_toolkits(headers)
219
+ messages = _deprecations(caught)
220
+ assert len(messages) == 1
221
+ assert "GMAIL version 20250114_00" in messages[0]
222
+
223
+ def test_second_version_still_warns_after_first_was_deduped(self):
224
+ with warnings.catch_warnings(record=True) as caught:
225
+ warnings.simplefilter("always")
226
+ warn_deprecated_toolkits(
227
+ httpx.Headers({HEADER: f"{FULL_ITEM}, {BARE_ITEM}"})
228
+ )
229
+ warn_deprecated_toolkits(
230
+ httpx.Headers({HEADER: '"GMAIL";version="20250201_00"'})
231
+ )
232
+ assert len(_deprecations(caught)) == 3
233
+
234
+ def test_header_name_is_case_insensitive(self):
235
+ with warnings.catch_warnings(record=True) as caught:
236
+ warnings.simplefilter("always")
237
+ warn_deprecated_toolkits(
238
+ httpx.Headers({"Composio-Deprecated-Toolkits": BARE_ITEM})
239
+ )
240
+ assert len(_deprecations(caught)) == 1
241
+
242
+ def test_no_header_or_garbage_is_silent(self):
243
+ with warnings.catch_warnings(record=True) as caught:
244
+ warnings.simplefilter("always")
245
+ warn_deprecated_toolkits(httpx.Headers({}))
246
+ warn_deprecated_toolkits(httpx.Headers({HEADER: "%%% nope"}))
247
+ assert _deprecations(caught) == []
248
+
249
+ def test_reset_allows_warning_again(self):
250
+ headers = httpx.Headers({HEADER: BARE_ITEM})
251
+ with warnings.catch_warnings(record=True) as caught:
252
+ warnings.simplefilter("always")
253
+ warn_deprecated_toolkits(headers)
254
+ td._reset_for_tests()
255
+ warn_deprecated_toolkits(headers)
256
+ assert len(_deprecations(caught)) == 2
257
+
258
+ def test_two_threads_one_warning(self):
259
+ headers = httpx.Headers({HEADER: FULL_ITEM})
260
+ barrier = threading.Barrier(2)
261
+
262
+ def worker() -> None:
263
+ barrier.wait()
264
+ warn_deprecated_toolkits(headers)
265
+
266
+ with warnings.catch_warnings(record=True) as caught:
267
+ warnings.simplefilter("always")
268
+ threads = [threading.Thread(target=worker) for _ in range(2)]
269
+ for thread in threads:
270
+ thread.start()
271
+ for thread in threads:
272
+ thread.join()
273
+ assert len(_deprecations(caught)) == 1
274
+
275
+
276
+class TestResponseHook:
277
+ def test_warns_from_response_headers(self):
278
+ response = httpx.Response(200, headers={HEADER: BARE_ITEM})
279
+ with warnings.catch_warnings(record=True) as caught:
280
+ warnings.simplefilter("always")
281
+ response_hook(response)
282
+ assert len(_deprecations(caught)) == 1
283
+
284
+ def test_never_raises(self, caplog: pytest.LogCaptureFixture):
285
+ class _Broken:
286
+ @property
287
+ def headers(self) -> httpx.Headers:
288
+ raise RuntimeError("headers unavailable")
289
+
290
+ with caplog.at_level("DEBUG", logger="composio.utils.toolkit_deprecation"):
291
+ response_hook(t.cast(httpx.Response, _Broken()))
292
+ assert "Failed to inspect the toolkit deprecation header" in caplog.text
293
+
294
+
295
+class TestInstallHook:
296
+ def test_appends_once(self):
297
+ client = httpx.Client()
298
+ install_hook(client)
299
+ install_hook(client)
300
+ assert client.event_hooks["response"] == [response_hook]
301
+
302
+ def test_preserves_user_hooks(self):
303
+ def user_request(request: httpx.Request) -> None:
304
+ pass
305
+
306
+ def user_response(response: httpx.Response) -> None:
307
+ pass
308
+
309
+ client = httpx.Client(
310
+ event_hooks={"request": [user_request], "response": [user_response]}
311
+ )
312
+ install_hook(client)
313
+ assert client.event_hooks["request"] == [user_request]
314
+ assert client.event_hooks["response"] == [user_response, response_hook]
315
+
316
+ def test_installed_hook_fires_on_send(self):
317
+ def handler(request: httpx.Request) -> httpx.Response:
318
+ return httpx.Response(200, headers={HEADER: BARE_ITEM}, json={})
319
+
320
+ client = httpx.Client(transport=httpx.MockTransport(handler))
321
+ install_hook(client)
322
+ with warnings.catch_warnings(record=True) as caught:
323
+ warnings.simplefilter("always")
324
+ response = client.get("https://backend.invalid/api/v3/toolkits/strava")
325
+ assert response.json() == {}
326
+ assert len(_deprecations(caught)) == 1