mind-recursive 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,433 @@
1
+ """HTTP transport: auth headers, retries, error mapping, connection pools.
2
+
3
+ Three things here are load-bearing:
4
+
5
+ **Auth.** The Mind Recursive API key goes into ``X-API-Key`` verbatim. No prefix check, no
6
+ disguise. The stock Tinker SDK validates ``tml-``/``eyJ`` locally in
7
+ Tinker's auth token provider, which forced callers to
8
+ subclass ``str`` and override ``startswith`` to smuggle a ``sk-`` key past it.
9
+ Owning the transport is what makes that patch unnecessary.
10
+
11
+ **Connection pools.** Upstream separates training traffic from everything else
12
+ (``ClientConnectionPoolType.TRAIN``). We do the same: a long-lived pool for
13
+ training, a separate one for control and metadata calls, so a stalled
14
+ ``forward_backward`` cannot starve a heartbeat.
15
+
16
+ **Byte fidelity.** ``forward_backward`` sends protobuf and its future resolves
17
+ to protobuf, so bodies are passed as raw bytes and responses are never
18
+ re-encoded. Decompression is disabled for the same reason the relay's own
19
+ proxy disables it: a response may be binary and must arrive byte-exact.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import json
26
+ import logging
27
+ import random
28
+ import time
29
+ from typing import Any, Mapping
30
+
31
+ import httpx
32
+
33
+ from ._config import Config
34
+ from ._errors import (
35
+ APIConnectionError,
36
+ APIError,
37
+ APITimeoutError,
38
+ RateLimitError,
39
+ status_to_error,
40
+ )
41
+
42
+ __all__ = ["Transport", "AsyncTransport", "JSON_CONTENT_TYPE", "PROTO_CONTENT_TYPE"]
43
+
44
+ log = logging.getLogger("mind_recursive.transport")
45
+
46
+ JSON_CONTENT_TYPE = "application/json"
47
+ PROTO_CONTENT_TYPE = "application/x-protobuf"
48
+
49
+ #: Retry on transport faults, 429, and 5xx. Never on 4xx (other than 429):
50
+ #: replaying a rejected request only burns quota.
51
+ _RETRY_STATUSES = frozenset({408, 429, 500, 502, 503, 504, 507, 509})
52
+
53
+ _BACKOFF_BASE = 0.5
54
+ _BACKOFF_CAP = 30.0
55
+
56
+
57
+ def _backoff_delay(attempt: int, retry_after: float | None = None) -> float:
58
+ """Exponential backoff with full jitter; ``Retry-After`` wins when sent."""
59
+ if retry_after is not None and retry_after >= 0:
60
+ return min(retry_after, _BACKOFF_CAP)
61
+ ceiling = min(_BACKOFF_BASE * (2**attempt), _BACKOFF_CAP)
62
+ return random.uniform(0, ceiling)
63
+
64
+
65
+ def _parse_retry_after(value: str | None) -> float | None:
66
+ if not value:
67
+ return None
68
+ try:
69
+ return float(value)
70
+ except ValueError:
71
+ return None # HTTP-date form; fall back to our own backoff
72
+
73
+
74
+ class Transport:
75
+ """Synchronous HTTP transport against one relay origin.
76
+
77
+ Not thread-safe for configuration changes, but safe for concurrent
78
+ requests: ``httpx.Client`` is, and we keep no per-request state.
79
+ """
80
+
81
+ def __init__(self, config: Config, *, user_agent: str | None = None) -> None:
82
+ self._config = config
83
+ self._user_agent = user_agent or "mind-recursive-python"
84
+ self._clients: dict[str, httpx.Client] = {}
85
+ self._closed = False
86
+
87
+ # -- headers --------------------------------------------------------------
88
+ def _base_headers(self) -> dict[str, str]:
89
+ """Headers on every request.
90
+
91
+ ``X-API-Key`` carries the raw key. We deliberately do not also send
92
+ ``Authorization: Bearer``: the relay accepts either, and sending one
93
+ credential by one name keeps 401s unambiguous.
94
+ """
95
+ return {
96
+ "X-API-Key": self._config.api_key,
97
+ "User-Agent": self._user_agent,
98
+ "Accept": JSON_CONTENT_TYPE,
99
+ }
100
+
101
+ # -- client pools ---------------------------------------------------------
102
+ def _client(self, pool: str, base_url: str) -> httpx.Client:
103
+ """Get or build the client for a pool.
104
+
105
+ ``pool`` is the isolation key -- ``"train"`` for the training hot path,
106
+ ``"control"`` for everything else.
107
+ """
108
+ if self._closed:
109
+ raise RuntimeError("transport is closed")
110
+ key = f"{pool}:{base_url}"
111
+ client = self._clients.get(key)
112
+ if client is None:
113
+ client = httpx.Client(
114
+ base_url=base_url,
115
+ timeout=httpx.Timeout(
116
+ self._config.timeout, connect=self._config.connect_timeout
117
+ ),
118
+ # trust_env=False: a local SOCKS proxy inherited from the
119
+ # ambient environment has hijacked this traffic before.
120
+ trust_env=self._config.trust_env,
121
+ follow_redirects=False,
122
+ limits=httpx.Limits(max_connections=64, max_keepalive_connections=16),
123
+ headers={"Accept-Encoding": "identity"},
124
+ )
125
+ self._clients[key] = client
126
+ return client
127
+
128
+ # -- requests -------------------------------------------------------------
129
+ def request(
130
+ self,
131
+ method: str,
132
+ path: str,
133
+ *,
134
+ base_url: str,
135
+ pool: str = "control",
136
+ json_body: Any | None = None,
137
+ content: bytes | None = None,
138
+ content_type: str | None = None,
139
+ params: Mapping[str, Any] | None = None,
140
+ accept: str = JSON_CONTENT_TYPE,
141
+ extra_headers: Mapping[str, str] | None = None,
142
+ timeout: float | None = None,
143
+ max_retries: int | None = None,
144
+ allow_statuses: frozenset[int] | None = None,
145
+ ) -> httpx.Response:
146
+ """Issue a request, retrying retryable failures.
147
+
148
+ Exactly one of ``json_body`` or ``content`` may be given. ``content``
149
+ is sent verbatim, which is what the protobuf path needs. ``params``
150
+ becomes the query string; the relay appends it to the upstream URL
151
+ unchanged.
152
+
153
+ ``allow_statuses`` returns those HTTP statuses to the caller instead of
154
+ treating them as errors. ``retrieve_future`` needs this for 408: there,
155
+ 408 is the normal "still pending" signal, not a retryable failure.
156
+
157
+ Returns:
158
+ The successful response.
159
+
160
+ Raises:
161
+ APIError: a non-retryable status, or the retry budget ran out.
162
+ APIConnectionError: the request never produced a response.
163
+ """
164
+ if self._closed:
165
+ raise RuntimeError("transport is closed")
166
+ if json_body is not None and content is not None:
167
+ raise ValueError("pass json_body or content, not both")
168
+
169
+ headers = self._base_headers()
170
+ headers["Accept"] = accept
171
+ if content is not None:
172
+ headers["Content-Type"] = content_type or PROTO_CONTENT_TYPE
173
+ body = content
174
+ elif json_body is not None:
175
+ headers["Content-Type"] = JSON_CONTENT_TYPE
176
+ # separators: compact, and stable for any fingerprinting upstream.
177
+ body = json.dumps(json_body, separators=(",", ":")).encode("utf-8")
178
+ else:
179
+ body = None
180
+ if extra_headers:
181
+ headers.update(extra_headers)
182
+
183
+ budget = self._config.max_retries if max_retries is None else max_retries
184
+ client = self._client(pool, base_url)
185
+ request_timeout = (
186
+ httpx.Timeout(timeout, connect=self._config.connect_timeout)
187
+ if timeout is not None
188
+ else httpx.USE_CLIENT_DEFAULT
189
+ )
190
+
191
+ last_error: Exception | None = None
192
+ for attempt in range(budget + 1):
193
+ try:
194
+ response = client.request(
195
+ method,
196
+ path,
197
+ content=body,
198
+ params=params,
199
+ headers=headers,
200
+ timeout=request_timeout,
201
+ )
202
+ except httpx.TimeoutException as exc:
203
+ last_error = APITimeoutError(f"{method} {path} timed out", path=path)
204
+ if attempt >= budget:
205
+ raise last_error from exc
206
+ except httpx.HTTPError as exc:
207
+ last_error = APIConnectionError(
208
+ f"{method} {path} failed to reach the relay: {exc}", path=path
209
+ )
210
+ if attempt >= budget:
211
+ raise last_error from exc
212
+ else:
213
+ if response.status_code < 400 or (
214
+ allow_statuses and response.status_code in allow_statuses
215
+ ):
216
+ return response
217
+ if response.status_code in _RETRY_STATUSES and attempt < budget:
218
+ retry_after = _parse_retry_after(response.headers.get("Retry-After"))
219
+ delay = _backoff_delay(attempt, retry_after)
220
+ log.debug(
221
+ "retrying %s %s after status %s in %.2fs (attempt %d/%d)",
222
+ method, path, response.status_code, delay, attempt + 1, budget,
223
+ )
224
+ response.close()
225
+ time.sleep(delay)
226
+ continue
227
+ raise self._to_error(response, method, path)
228
+
229
+ # Transport fault with budget remaining.
230
+ time.sleep(_backoff_delay(attempt))
231
+
232
+ raise last_error or APIError(f"{method} {path} exhausted its retry budget", path=path)
233
+
234
+ def _to_error(self, response: httpx.Response, method: str, path: str) -> APIError:
235
+ """Turn an error response into the right exception.
236
+
237
+ Two envelope shapes exist on these endpoints: the Tinker-style shape
238
+ ``{"error": ..., "category": ...}`` and the relay's ``{"message": ...}``.
239
+ We read both so the message is never swallowed.
240
+ """
241
+ raw = b""
242
+ try:
243
+ raw = response.content
244
+ except Exception: # pragma: no cover - body already consumed/aborted
245
+ pass
246
+
247
+ message = ""
248
+ category: str | None = None
249
+ try:
250
+ payload = json.loads(raw.decode("utf-8"))
251
+ except (ValueError, UnicodeDecodeError):
252
+ payload = None
253
+ if isinstance(payload, dict):
254
+ for key in ("error", "message", "detail"):
255
+ value = payload.get(key)
256
+ if isinstance(value, str) and value.strip():
257
+ message = value.strip()
258
+ break
259
+ raw_category = payload.get("category")
260
+ if isinstance(raw_category, str):
261
+ category = raw_category
262
+ if not message:
263
+ snippet = raw[:200].decode("utf-8", "replace").strip()
264
+ message = snippet or f"HTTP {response.status_code}"
265
+
266
+ status = response.status_code
267
+ if status == 404:
268
+ # The single most common 404 is a base URL carrying the old plane
269
+ # suffix or a full endpoint, not an absent resource. Say so, since
270
+ # the bare status sends people hunting the wrong problem.
271
+ message = (
272
+ f"{message} -- check the base URL is the relay origin; the SDK "
273
+ f"appends the fixed /api/mindrsi/v1 root itself "
274
+ f"(requested {base_hint(response)})"
275
+ )
276
+ if status == 429:
277
+ return RateLimitError(
278
+ message,
279
+ status=status,
280
+ category=category,
281
+ path=path,
282
+ body=raw,
283
+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),
284
+ )
285
+ return status_to_error(status)(
286
+ message, status=status, category=category, path=path, body=raw
287
+ )
288
+
289
+ # -- lifecycle ------------------------------------------------------------
290
+ def close(self) -> None:
291
+ for client in self._clients.values():
292
+ client.close()
293
+ self._clients.clear()
294
+ self._closed = True
295
+
296
+ def __enter__(self) -> Transport:
297
+ return self
298
+
299
+ def __exit__(self, *_exc: object) -> None:
300
+ self.close()
301
+
302
+
303
+ class AsyncTransport(Transport):
304
+ """Async twin of :class:`Transport`, using ``httpx.AsyncClient``.
305
+
306
+ Same headers, pools, retry budget and error mapping as the sync transport;
307
+ only the waiting is different. The backend sees identical requests.
308
+ """
309
+
310
+ def __init__(self, config: Config, *, user_agent: str | None = None) -> None:
311
+ super().__init__(config, user_agent=user_agent)
312
+ self._clients = {}
313
+
314
+ def _client(self, pool: str, base_url: str) -> httpx.AsyncClient:
315
+ if self._closed:
316
+ raise RuntimeError("transport is closed")
317
+ key = f"{pool}:{base_url}"
318
+ client = self._clients.get(key)
319
+ if client is None:
320
+ client = httpx.AsyncClient(
321
+ base_url=base_url,
322
+ timeout=httpx.Timeout(
323
+ self._config.timeout, connect=self._config.connect_timeout
324
+ ),
325
+ trust_env=self._config.trust_env,
326
+ follow_redirects=False,
327
+ limits=httpx.Limits(max_connections=64, max_keepalive_connections=16),
328
+ headers={"Accept-Encoding": "identity"},
329
+ )
330
+ self._clients[key] = client
331
+ return client
332
+
333
+ async def request( # type: ignore[override]
334
+ self,
335
+ method: str,
336
+ path: str,
337
+ *,
338
+ base_url: str,
339
+ pool: str = "control",
340
+ json_body: Any | None = None,
341
+ content: bytes | None = None,
342
+ content_type: str | None = None,
343
+ params: Mapping[str, Any] | None = None,
344
+ accept: str = JSON_CONTENT_TYPE,
345
+ extra_headers: Mapping[str, str] | None = None,
346
+ timeout: float | None = None,
347
+ max_retries: int | None = None,
348
+ allow_statuses: frozenset[int] | None = None,
349
+ ) -> httpx.Response:
350
+ if self._closed:
351
+ raise RuntimeError("transport is closed")
352
+ if json_body is not None and content is not None:
353
+ raise ValueError("pass json_body or content, not both")
354
+
355
+ headers = self._base_headers()
356
+ headers["Accept"] = accept
357
+ if content is not None:
358
+ headers["Content-Type"] = content_type or PROTO_CONTENT_TYPE
359
+ body = content
360
+ elif json_body is not None:
361
+ headers["Content-Type"] = JSON_CONTENT_TYPE
362
+ body = json.dumps(json_body, separators=(",", ":")).encode("utf-8")
363
+ else:
364
+ body = None
365
+ if extra_headers:
366
+ headers.update(extra_headers)
367
+
368
+ budget = self._config.max_retries if max_retries is None else max_retries
369
+ client = self._client(pool, base_url)
370
+ request_timeout = (
371
+ httpx.Timeout(timeout, connect=self._config.connect_timeout)
372
+ if timeout is not None
373
+ else httpx.USE_CLIENT_DEFAULT
374
+ )
375
+
376
+ last_error: Exception | None = None
377
+ for attempt in range(budget + 1):
378
+ try:
379
+ response = await client.request(
380
+ method,
381
+ path,
382
+ content=body,
383
+ params=params,
384
+ headers=headers,
385
+ timeout=request_timeout,
386
+ )
387
+ except httpx.TimeoutException as exc:
388
+ last_error = APITimeoutError(f"{method} {path} timed out", path=path)
389
+ if attempt >= budget:
390
+ raise last_error from exc
391
+ except httpx.HTTPError as exc:
392
+ last_error = APIConnectionError(
393
+ f"{method} {path} failed to reach the relay: {exc}", path=path
394
+ )
395
+ if attempt >= budget:
396
+ raise last_error from exc
397
+ else:
398
+ if response.status_code < 400 or (
399
+ allow_statuses and response.status_code in allow_statuses
400
+ ):
401
+ return response
402
+ if response.status_code in _RETRY_STATUSES and attempt < budget:
403
+ retry_after = _parse_retry_after(response.headers.get("Retry-After"))
404
+ delay = _backoff_delay(attempt, retry_after)
405
+ log.debug(
406
+ "retrying %s %s after status %s in %.2fs (attempt %d/%d)",
407
+ method, path, response.status_code, delay, attempt + 1, budget,
408
+ )
409
+ await response.aclose()
410
+ await asyncio.sleep(delay)
411
+ continue
412
+ raise self._to_error(response, method, path)
413
+
414
+ await asyncio.sleep(_backoff_delay(attempt))
415
+
416
+ raise last_error or APIError(f"{method} {path} exhausted its retry budget", path=path)
417
+
418
+ async def aclose(self) -> None:
419
+ for client in self._clients.values():
420
+ await client.aclose()
421
+ self._clients.clear()
422
+ self._closed = True
423
+
424
+ def close(self) -> None: # pragma: no cover - async callers use aclose()
425
+ raise RuntimeError("AsyncTransport must be closed with await aclose()")
426
+
427
+
428
+ def base_hint(response: httpx.Response) -> str:
429
+ """The absolute URL a response came from, for error messages."""
430
+ try:
431
+ return str(response.request.url)
432
+ except Exception: # pragma: no cover
433
+ return "unknown URL"
@@ -0,0 +1,26 @@
1
+ """Package version, read from installed metadata.
2
+
3
+ Single source of truth is ``pyproject.toml``. Nothing here is hand-written:
4
+ a second hard-coded literal silently drifts, and ``SDK_VERSION`` is sent to
5
+ the server to resolve version-gated flags, so a stale value changes behaviour
6
+ rather than just printing wrong.
7
+
8
+ Lives in its own module because ``mind_recursive/__init__`` imports from
9
+ ``mind_recursive.service``, so ``service`` cannot import back from ``mind_recursive``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from importlib.metadata import PackageNotFoundError, version as _metadata_version
15
+
16
+ try:
17
+ __version__ = _metadata_version("mind-recursive")
18
+ except PackageNotFoundError: # pragma: no cover - only when run from an uninstalled tree
19
+ __version__ = "0.0.0"
20
+
21
+ #: Sent in ``create_session`` and ``client/config``. Honest about which client
22
+ #: this is: pretending to be the stock SDK would make server-side debugging
23
+ #: harder for everyone.
24
+ SDK_VERSION = f"mind-recursive-python/{__version__}"
25
+
26
+ __all__ = ["SDK_VERSION", "__version__"]