riffsdk 0.22.0__tar.gz → 0.22.1__tar.gz

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.
Files changed (71) hide show
  1. {riffsdk-0.22.0 → riffsdk-0.22.1}/CHANGELOG.md +16 -0
  2. {riffsdk-0.22.0 → riffsdk-0.22.1}/PKG-INFO +1 -1
  3. {riffsdk-0.22.0 → riffsdk-0.22.1}/mise.toml +4 -0
  4. {riffsdk-0.22.0 → riffsdk-0.22.1}/pyproject.toml +1 -1
  5. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/_internal/transport.py +47 -17
  6. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/ai/v0.py +5 -6
  7. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_async_client.py +8 -2
  8. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_client.py +8 -2
  9. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_common.py +6 -7
  10. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_http.py +6 -0
  11. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_ai_v0.py +20 -0
  12. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_async_client.py +27 -13
  13. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_client.py +39 -25
  14. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_http.py +102 -10
  15. {riffsdk-0.22.0 → riffsdk-0.22.1}/.github/workflows/ci.yml +0 -0
  16. {riffsdk-0.22.0 → riffsdk-0.22.1}/.github/workflows/pr-comment.yml +0 -0
  17. {riffsdk-0.22.0 → riffsdk-0.22.1}/.github/workflows/release.yml +0 -0
  18. {riffsdk-0.22.0 → riffsdk-0.22.1}/.gitignore +0 -0
  19. {riffsdk-0.22.0 → riffsdk-0.22.1}/.python-version +0 -0
  20. {riffsdk-0.22.0 → riffsdk-0.22.1}/AGENTS.md +0 -0
  21. {riffsdk-0.22.0 → riffsdk-0.22.1}/CLAUDE.md +0 -0
  22. {riffsdk-0.22.0 → riffsdk-0.22.1}/LICENCE +0 -0
  23. {riffsdk-0.22.0 → riffsdk-0.22.1}/LOCAL-TESTING.md +0 -0
  24. {riffsdk-0.22.0 → riffsdk-0.22.1}/README.md +0 -0
  25. {riffsdk-0.22.0 → riffsdk-0.22.1}/USAGE_PROMPT.md +0 -0
  26. {riffsdk-0.22.0 → riffsdk-0.22.1}/examples/async_client.py +0 -0
  27. {riffsdk-0.22.0 → riffsdk-0.22.1}/examples/basic_crud.py +0 -0
  28. {riffsdk-0.22.0 → riffsdk-0.22.1}/examples/email_notice.py +0 -0
  29. {riffsdk-0.22.0 → riffsdk-0.22.1}/examples/file_upload_download.py +0 -0
  30. {riffsdk-0.22.0 → riffsdk-0.22.1}/examples/get_task.py +0 -0
  31. {riffsdk-0.22.0 → riffsdk-0.22.1}/examples/interpret_document.py +0 -0
  32. {riffsdk-0.22.0 → riffsdk-0.22.1}/examples/optimistic_concurrency.py +0 -0
  33. {riffsdk-0.22.0 → riffsdk-0.22.1}/new-sdk-url-schema.md +0 -0
  34. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/__init__.py +0 -0
  35. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/__main__.py +0 -0
  36. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/_cli.py +0 -0
  37. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/_internal/__init__.py +0 -0
  38. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/_internal/auth.py +0 -0
  39. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/_internal/config.py +0 -0
  40. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/ai/__init__.py +0 -0
  41. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/client.py +0 -0
  42. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/context.py +0 -0
  43. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/email/__init__.py +0 -0
  44. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/email/v0.py +0 -0
  45. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/__init__.py +0 -0
  46. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_mime.py +0 -0
  47. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_models.py +0 -0
  48. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_session.py +0 -0
  49. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_streaming.py +0 -0
  50. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/_upload.py +0 -0
  51. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/exceptions.py +0 -0
  52. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/storage/py.typed +0 -0
  53. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/tasks/__init__.py +0 -0
  54. {riffsdk-0.22.0 → riffsdk-0.22.1}/src/riffsdk/tasks/v0.py +0 -0
  55. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/__init__.py +0 -0
  56. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/conftest.py +0 -0
  57. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_auth.py +0 -0
  58. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_cli.py +0 -0
  59. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_config.py +0 -0
  60. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_context.py +0 -0
  61. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_email_v0.py +0 -0
  62. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_exceptions.py +0 -0
  63. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_imports.py +0 -0
  64. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_integration.py +0 -0
  65. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_mime.py +0 -0
  66. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_models.py +0 -0
  67. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_session.py +0 -0
  68. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_streaming.py +0 -0
  69. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_tasks_v0.py +0 -0
  70. {riffsdk-0.22.0 → riffsdk-0.22.1}/tests/test_upload.py +0 -0
  71. {riffsdk-0.22.0 → riffsdk-0.22.1}/uv.lock +0 -0
@@ -2,6 +2,22 @@
2
2
 
3
3
  <!-- version list -->
4
4
 
5
+ ## v0.22.1 (2026-09-23)
6
+
7
+ ### Bug Fixes
8
+
9
+ - Add mise setup task ([#46](https://github.com/databutton/riff-sdk-python/pull/46),
10
+ [`360e57b`](https://github.com/databutton/riff-sdk-python/commit/360e57b48e96063300be73c4650d7572fbf9a40e))
11
+
12
+ - Default client could pick up task and session ids from first instantiation
13
+ ([#46](https://github.com/databutton/riff-sdk-python/pull/46),
14
+ [`360e57b`](https://github.com/databutton/riff-sdk-python/commit/360e57b48e96063300be73c4650d7572fbf9a40e))
15
+
16
+ - Resolve session/task headers per request from the bound RiffContext
17
+ ([#46](https://github.com/databutton/riff-sdk-python/pull/46),
18
+ [`360e57b`](https://github.com/databutton/riff-sdk-python/commit/360e57b48e96063300be73c4650d7572fbf9a40e))
19
+
20
+
5
21
  ## v0.22.0 (2026-09-18)
6
22
 
7
23
  ### Features
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: riffsdk
3
- Version: 0.22.0
3
+ Version: 0.22.1
4
4
  Summary: Python SDK for the Riff Storage API
5
5
  Project-URL: Homepage, https://riff.ai
6
6
  Author-email: Martin Sandve Alnæs <msa@databutton.io>
@@ -2,6 +2,10 @@
2
2
  python = "3.11"
3
3
  uv = "latest"
4
4
 
5
+ [tasks.setup]
6
+ description = "Initial package installs etc"
7
+ run = "uv sync --locked --all-groups"
8
+
5
9
  [tasks.test]
6
10
  description = "Run tests"
7
11
  run = "uv run pytest"
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "riffsdk"
7
- version = "0.22.0"
7
+ version = "0.22.1"
8
8
  description = "Python SDK for the Riff Storage API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -71,22 +71,16 @@ def resolve_connection_params(
71
71
  task_id: str | None,
72
72
  uds: str | None,
73
73
  ) -> ConnectionParams:
74
+ """Resolve construction-time connection settings.
75
+
76
+ ``session_id``/``task_id`` stay exactly as passed (explicit or ``None``):
77
+ the ambient ids are resolved per request by :func:`resolve_tracking_ids`,
78
+ so a long-lived client (e.g. ``RiffClient.default()``) follows whatever
79
+ context is bound at call time instead of the one bound when it was built.
80
+ """
74
81
  auth, uds = resolve_auth_and_uds(auth, uds)
75
82
  if base_url is None:
76
83
  base_url = default_base_url()
77
- if session_id is None:
78
- session_id = os.environ.get("RIFF_SESSION_ID")
79
- if task_id is None:
80
- task_id = os.environ.get("RIFF_TASK_ID")
81
-
82
- if session_id is None or task_id is None:
83
- ctx = get_context_or_none()
84
- if ctx is not None:
85
- if session_id is None:
86
- session_id = ctx.session_id
87
- if task_id is None:
88
- task_id = ctx.task_id
89
-
90
84
  return ConnectionParams(
91
85
  auth=auth,
92
86
  base_url=base_url,
@@ -96,6 +90,26 @@ def resolve_connection_params(
96
90
  )
97
91
 
98
92
 
93
+ def resolve_tracking_ids(
94
+ session_id: str | None, task_id: str | None
95
+ ) -> tuple[str | None, str | None]:
96
+ """Resolve the session/task id for one request.
97
+
98
+ Precedence per id: the explicit value (a client constructor argument) >
99
+ the bound :class:`~riffsdk.context.RiffContext` > ``RIFF_SESSION_ID``/
100
+ ``RIFF_TASK_ID``. The context beats env because a server binds it per
101
+ call (devx binds the MCP call's session), while env is process-wide.
102
+ """
103
+ ctx = get_context_or_none()
104
+ if session_id is None:
105
+ session_id = (ctx.session_id if ctx else None) or os.environ.get(
106
+ "RIFF_SESSION_ID"
107
+ )
108
+ if task_id is None:
109
+ task_id = (ctx.task_id if ctx else None) or os.environ.get("RIFF_TASK_ID")
110
+ return session_id, task_id
111
+
112
+
99
113
  def tracking_headers(
100
114
  session_id: str | None,
101
115
  task_id: str | None,
@@ -159,7 +173,9 @@ class Transport:
159
173
  self._auth = auth
160
174
  self._base_url = base_url.rstrip("/")
161
175
  self._max_retries = max_retries
162
- headers = tracking_headers(session_id, task_id, client_version=client_version)
176
+ self._session_id = session_id
177
+ self._task_id = task_id
178
+ headers = tracking_headers(None, None, client_version=client_version)
163
179
  transport = httpx.HTTPTransport(uds=uds) if uds else None
164
180
  self._client = httpx.Client(
165
181
  timeout=timeout, headers=headers, transport=transport
@@ -181,6 +197,10 @@ class Transport:
181
197
  def auth(self) -> httpx.Auth | None:
182
198
  return self._auth
183
199
 
200
+ def tracking_ids(self) -> tuple[str | None, str | None]:
201
+ """The session/task id the next request sends, resolved now."""
202
+ return resolve_tracking_ids(self._session_id, self._task_id)
203
+
184
204
  def close(self) -> None:
185
205
  self._client.close()
186
206
 
@@ -207,7 +227,9 @@ class Transport:
207
227
  wrap_transport_error: Callable[[str], Exception] = RetryableTransportError,
208
228
  ) -> httpx.Response:
209
229
  url = f"{self._base_url}{path}"
210
- req_headers = dict(headers) if headers else {}
230
+ # Per-request tracking headers first, so a caller's explicit header
231
+ # (e.g. interpret_document's X-Riff-Session-Id) still wins.
232
+ req_headers = {**tracking_headers(*self.tracking_ids()), **(headers or {})}
211
233
 
212
234
  _log.debug(
213
235
  "%s %s auth=%s",
@@ -265,7 +287,9 @@ class AsyncTransport:
265
287
  self._auth = auth
266
288
  self._base_url = base_url.rstrip("/")
267
289
  self._max_retries = max_retries
268
- headers = tracking_headers(session_id, task_id, client_version=client_version)
290
+ self._session_id = session_id
291
+ self._task_id = task_id
292
+ headers = tracking_headers(None, None, client_version=client_version)
269
293
  transport = httpx.AsyncHTTPTransport(uds=uds) if uds else None
270
294
  self._client = httpx.AsyncClient(
271
295
  timeout=timeout, headers=headers, transport=transport
@@ -287,6 +311,10 @@ class AsyncTransport:
287
311
  def auth(self) -> httpx.Auth | None:
288
312
  return self._auth
289
313
 
314
+ def tracking_ids(self) -> tuple[str | None, str | None]:
315
+ """The session/task id the next request sends, resolved now."""
316
+ return resolve_tracking_ids(self._session_id, self._task_id)
317
+
290
318
  async def close(self) -> None:
291
319
  await self._client.aclose()
292
320
 
@@ -313,7 +341,9 @@ class AsyncTransport:
313
341
  wrap_transport_error: Callable[[str], Exception] = RetryableTransportError,
314
342
  ) -> httpx.Response:
315
343
  url = f"{self._base_url}{path}"
316
- req_headers = dict(headers) if headers else {}
344
+ # Per-request tracking headers first, so a caller's explicit header
345
+ # (e.g. interpret_document's X-Riff-Session-Id) still wins.
346
+ req_headers = {**tracking_headers(*self.tracking_ids()), **(headers or {})}
317
347
 
318
348
  _log.debug(
319
349
  "%s %s auth=%s",
@@ -29,12 +29,10 @@ nothing to share beyond the key::
29
29
 
30
30
  from __future__ import annotations
31
31
 
32
- import os
33
-
34
32
  import httpx
35
33
 
36
34
  from riffsdk._internal.config import sdk_domain_path
37
- from riffsdk._internal.transport import RetryableTransportError
35
+ from riffsdk._internal.transport import RetryableTransportError, resolve_tracking_ids
38
36
  from riffsdk.client import AsyncRiffClient, RiffClient
39
37
  from riffsdk.storage._models import Scope
40
38
 
@@ -89,11 +87,12 @@ def _resolve_scope(scope: Scope) -> tuple[str, str | None]:
89
87
  effective = scope or "project"
90
88
  if effective == "session" or effective.startswith("session:"):
91
89
  _, _, explicit_session_id = effective.partition(":")
92
- session_id = explicit_session_id or os.environ.get("RIFF_SESSION_ID")
90
+ session_id = explicit_session_id or resolve_tracking_ids(None, None)[0]
93
91
  if not session_id:
94
92
  raise ValueError(
95
- "session_id is required when using session scope — "
96
- "pass a session id to session_scope() or set RIFF_SESSION_ID"
93
+ "session_id is required when using session scope — pass a "
94
+ "session id to session_scope(), bind a RiffContext with a "
95
+ "session_id, or set RIFF_SESSION_ID"
97
96
  )
98
97
  return "session", session_id
99
98
  return effective, None
@@ -133,7 +133,6 @@ class AsyncStorageClient:
133
133
  self._complete_timeout = complete_timeout
134
134
  self._auto_refresh = auto_refresh_sessions
135
135
  self._scope = scope
136
- self._session_id = p.session_id
137
136
  self._transport = AsyncTransport(
138
137
  auth=p.auth,
139
138
  base_url=p.base_url.rstrip("/"),
@@ -145,8 +144,11 @@ class AsyncStorageClient:
145
144
  )
146
145
  self._sessions = SessionStore()
147
146
 
147
+ def _current_session_id(self) -> str | None:
148
+ return self._transport.tracking_ids()[0]
149
+
148
150
  def _scope_headers(self, scope: Scope = None) -> dict[str, str]:
149
- return scope_headers(scope, self._scope, self._session_id)
151
+ return scope_headers(scope, self._scope, self._current_session_id())
150
152
 
151
153
  async def close(self) -> None:
152
154
  await self._transport.close()
@@ -762,6 +764,10 @@ class AsyncStorageClient:
762
764
  # the cache key, a token issued for one scope would be reused for the
763
765
  # same key under a different scope, leaking content across scopes.
764
766
  effective_scope = scope or self._scope or "project"
767
+ # Bare "session" resolves to whichever session is current for this
768
+ # request, so the session id is part of the key too.
769
+ if effective_scope == "session":
770
+ effective_scope = f"session:{self._current_session_id()}"
765
771
  session_id = f"download:{effective_scope}:{key}"
766
772
  token = self._sessions.get(session_id) if self._auto_refresh else None
767
773
 
@@ -134,7 +134,6 @@ class StorageClient:
134
134
  self._complete_timeout = complete_timeout
135
135
  self._auto_refresh = auto_refresh_sessions
136
136
  self._scope = scope
137
- self._session_id = p.session_id
138
137
  self._transport = SyncTransport(
139
138
  auth=p.auth,
140
139
  base_url=p.base_url.rstrip("/"),
@@ -146,8 +145,11 @@ class StorageClient:
146
145
  )
147
146
  self._sessions = SessionStore()
148
147
 
148
+ def _current_session_id(self) -> str | None:
149
+ return self._transport.tracking_ids()[0]
150
+
149
151
  def _scope_headers(self, scope: Scope = None) -> dict[str, str]:
150
- return scope_headers(scope, self._scope, self._session_id)
152
+ return scope_headers(scope, self._scope, self._current_session_id())
151
153
 
152
154
  def close(self) -> None:
153
155
  self._transport.close()
@@ -792,6 +794,10 @@ class StorageClient:
792
794
  # the cache key, a token issued for one scope would be reused for the
793
795
  # same key under a different scope, leaking content across scopes.
794
796
  effective_scope = scope or self._scope or "project"
797
+ # Bare "session" resolves to whichever session is current for this
798
+ # request, so the session id is part of the key too.
799
+ if effective_scope == "session":
800
+ effective_scope = f"session:{self._current_session_id()}"
795
801
  session_id = f"download:{effective_scope}:{key}"
796
802
  token = self._sessions.get(session_id) if self._auto_refresh else None
797
803
 
@@ -50,14 +50,13 @@ def scope_headers(
50
50
  scope: Scope, default_scope: Scope, session_id: str | None
51
51
  ) -> dict[str, str]:
52
52
  effective = scope or default_scope
53
- if (
54
- effective is not None
55
- and (effective == "session" or effective.startswith("session:"))
56
- and not session_id
57
- ):
53
+ # An explicit "session:<id>" names its session; only bare "session" needs
54
+ # an ambient one (sent as X-Riff-Session-Id).
55
+ if effective == "session" and not session_id:
58
56
  raise ValueError(
59
- "session_id is required when using session scope — "
60
- "pass session_id to the client or set RIFF_SESSION_ID"
57
+ "session_id is required when using session scope — pass "
58
+ "session_scope(<id>), session_id to the client, bind a RiffContext "
59
+ "with a session_id, or set RIFF_SESSION_ID"
61
60
  )
62
61
  if effective is None:
63
62
  _warn_missing_scope()
@@ -179,6 +179,9 @@ class SyncTransport:
179
179
  httpx.Client(timeout=timeout) if uds else None
180
180
  )
181
181
 
182
+ def tracking_ids(self) -> tuple[str | None, str | None]:
183
+ return self._base.tracking_ids()
184
+
182
185
  def close(self) -> None:
183
186
  self._base.close()
184
187
  if self._external_client:
@@ -342,6 +345,9 @@ class AsyncTransport:
342
345
  httpx.AsyncClient(timeout=timeout) if uds else None
343
346
  )
344
347
 
348
+ def tracking_ids(self) -> tuple[str | None, str | None]:
349
+ return self._base.tracking_ids()
350
+
345
351
  async def close(self) -> None:
346
352
  await self._base.close()
347
353
  if self._external_client:
@@ -14,6 +14,7 @@ from riffsdk.ai.v0 import (
14
14
  interpret_document_async,
15
15
  )
16
16
  from riffsdk.client import AsyncRiffClient, RiffClient
17
+ from riffsdk.context import RiffContext, with_context
17
18
  from riffsdk.storage import account_scope, project_scope, session_scope
18
19
 
19
20
  BASE_URL = "https://test.example.com"
@@ -262,6 +263,25 @@ class TestSessionScope:
262
263
  assert json.loads(seen[0].content)["scope"] == "session"
263
264
  assert seen[0].headers["X-Riff-Session-Id"] == "ambient-sess"
264
265
 
266
+ def test_bare_session_scope_prefers_bound_context_over_env(self):
267
+ seen: list[httpx.Request] = []
268
+
269
+ def handler(request: httpx.Request) -> httpx.Response:
270
+ seen.append(request)
271
+ return httpx.Response(200, json=_response_body())
272
+
273
+ env = {**ENV, "RIFF_SESSION_ID": "env-sess"}
274
+ with patch.dict(os.environ, env, clear=True), _mock_transport(handler):
275
+ client = RiffClient(auth=_FakeAuth())
276
+ with with_context(RiffContext(session_id="ctx-sess")):
277
+ interpret_document(
278
+ "invoice.pdf",
279
+ scope=session_scope(),
280
+ client=client,
281
+ )
282
+
283
+ assert seen[0].headers["X-Riff-Session-Id"] == "ctx-sess"
284
+
265
285
  def test_bare_session_scope_without_any_session_id_raises(self):
266
286
  with patch.dict(os.environ, ENV, clear=True):
267
287
  with pytest.raises(ValueError, match="session_id is required"):
@@ -6,6 +6,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
6
6
 
7
7
  import pytest
8
8
 
9
+ from riffsdk._internal.transport import tracking_headers
10
+ from riffsdk.context import RiffContext, with_context
9
11
  from riffsdk.storage._async_client import AsyncStorageClient
10
12
  from riffsdk.storage._models import ObjectMeta, UploadResult
11
13
  from riffsdk.storage.exceptions import (
@@ -24,6 +26,10 @@ def _mock_response(json_data: dict) -> MagicMock:
24
26
  return resp
25
27
 
26
28
 
29
+ def _tracking(client) -> dict[str, str]:
30
+ return tracking_headers(*client._transport.tracking_ids())
31
+
32
+
27
33
  def _make_client(**kwargs) -> AsyncStorageClient:
28
34
  defaults = {"auth": MagicMock()}
29
35
  defaults.update(kwargs)
@@ -51,34 +57,42 @@ class TestAsyncStorageClientInit:
51
57
 
52
58
  def test_session_id_from_param(self):
53
59
  client = _make_client(session_id="s1")
54
- assert client._session_id == "s1"
55
- assert client._transport._client.headers["X-Riff-Session-Id"] == "s1"
60
+ assert client._current_session_id() == "s1"
61
+ assert _tracking(client)["X-Riff-Session-Id"] == "s1"
56
62
 
57
63
  def test_task_id_from_param(self):
58
64
  client = _make_client(task_id="t1")
59
- assert client._transport._client.headers["X-Riff-Task-Id"] == "t1"
65
+ assert _tracking(client)["X-Riff-Task-Id"] == "t1"
60
66
 
61
67
  def test_session_id_from_env(self):
62
- import os
63
-
64
68
  with patch.dict(os.environ, {"RIFF_SESSION_ID": "env-sess"}):
65
69
  client = _make_client()
66
- assert client._session_id == "env-sess"
70
+ assert client._current_session_id() == "env-sess"
67
71
 
68
72
  def test_param_overrides_env(self):
69
- import os
70
-
71
73
  with patch.dict(os.environ, {"RIFF_SESSION_ID": "env"}):
72
74
  client = _make_client(session_id="param")
73
- assert client._session_id == "param"
75
+ assert client._current_session_id() == "param"
74
76
 
75
- def test_session_scope_without_session_id_raises(self):
76
- import os
77
+ def test_context_overrides_env_and_is_read_per_call(self):
78
+ with patch.dict(os.environ, {"RIFF_SESSION_ID": "env"}):
79
+ client = _make_client()
80
+ with with_context(RiffContext(session_id="ctx")):
81
+ assert _tracking(client)["X-Riff-Session-Id"] == "ctx"
82
+ assert _tracking(client)["X-Riff-Session-Id"] == "env"
83
+
84
+ def test_explicit_session_scope_needs_no_ambient_session(self):
85
+ with patch.dict(os.environ, {"RIFF_PROJECT_ID": "proj-1"}, clear=True):
86
+ client = _make_client()
87
+ assert client._scope_headers("session:abc") == {
88
+ "X-Riff-Storage-Scope": "session:abc"
89
+ }
77
90
 
91
+ def test_bare_session_scope_without_session_id_raises(self):
78
92
  with patch.dict(os.environ, {"RIFF_PROJECT_ID": "proj-1"}, clear=True):
79
93
  client = _make_client()
80
- with pytest.raises(ValueError, match="session_id is required"):
81
- client._scope_headers("session:abc")
94
+ with pytest.raises(ValueError, match="session_id is required"):
95
+ client._scope_headers("session")
82
96
 
83
97
  def test_uds_from_param(self):
84
98
  import httpx
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
7
7
  import httpx
8
8
  import pytest
9
9
 
10
+ from riffsdk._internal.transport import tracking_headers
10
11
  from riffsdk.context import RiffContext, with_context
11
12
  from riffsdk.storage._client import StorageClient
12
13
  from riffsdk.storage._models import ObjectMeta, UploadResult
@@ -28,6 +29,11 @@ def _mock_response(json_data: dict) -> MagicMock:
28
29
  return resp
29
30
 
30
31
 
32
+ def _tracking(client) -> dict[str, str]:
33
+ """The tracking headers the client's next request would send."""
34
+ return tracking_headers(*client._transport.tracking_ids())
35
+
36
+
31
37
  def _make_client(**kwargs) -> StorageClient:
32
38
  defaults = {"auth": MagicMock()}
33
39
  defaults.update(kwargs)
@@ -65,71 +71,79 @@ class TestStorageClientInit:
65
71
 
66
72
  def test_session_id_from_param(self):
67
73
  client = _make_client(session_id="s1")
68
- assert client._session_id == "s1"
69
- assert client._transport._client.headers["X-Riff-Session-Id"] == "s1"
74
+ assert client._current_session_id() == "s1"
75
+ assert _tracking(client)["X-Riff-Session-Id"] == "s1"
70
76
 
71
77
  def test_task_id_from_param(self):
72
78
  client = _make_client(task_id="t1")
73
- assert client._transport._client.headers["X-Riff-Task-Id"] == "t1"
79
+ assert _tracking(client)["X-Riff-Task-Id"] == "t1"
74
80
 
75
81
  def test_session_id_from_env(self):
76
82
  with patch.dict(os.environ, {"RIFF_SESSION_ID": "env-sess"}):
77
83
  client = _make_client()
78
- assert client._session_id == "env-sess"
79
- assert client._transport._client.headers["X-Riff-Session-Id"] == "env-sess"
84
+ assert client._current_session_id() == "env-sess"
85
+ assert _tracking(client)["X-Riff-Session-Id"] == "env-sess"
80
86
 
81
87
  def test_task_id_from_env(self):
82
88
  with patch.dict(os.environ, {"RIFF_TASK_ID": "env-task"}):
83
89
  client = _make_client()
84
- assert client._transport._client.headers["X-Riff-Task-Id"] == "env-task"
90
+ assert _tracking(client)["X-Riff-Task-Id"] == "env-task"
85
91
 
86
92
  def test_param_overrides_env(self):
87
93
  with patch.dict(os.environ, {"RIFF_SESSION_ID": "env"}):
88
94
  client = _make_client(session_id="param")
89
- assert client._session_id == "param"
90
- assert client._transport._client.headers["X-Riff-Session-Id"] == "param"
95
+ assert _tracking(client)["X-Riff-Session-Id"] == "param"
91
96
 
92
97
  def test_no_headers_when_absent(self):
93
98
  with patch.dict(os.environ, {"RIFF_PROJECT_ID": "proj-1"}, clear=True):
94
99
  client = _make_client()
95
- assert "X-Riff-Session-Id" not in client._transport._client.headers
96
- assert "X-Riff-Task-Id" not in client._transport._client.headers
100
+ assert "X-Riff-Session-Id" not in _tracking(client)
101
+ assert "X-Riff-Task-Id" not in _tracking(client)
97
102
 
98
103
  def test_session_id_from_context(self):
99
104
  with patch.dict(os.environ, {"RIFF_PROJECT_ID": "proj-1"}, clear=True):
100
105
  with with_context(RiffContext(session_id="ctx-sess")):
101
106
  client = _make_client()
102
- assert client._session_id == "ctx-sess"
103
- assert client._transport._client.headers["X-Riff-Session-Id"] == "ctx-sess"
107
+ assert client._current_session_id() == "ctx-sess"
108
+ assert _tracking(client)["X-Riff-Session-Id"] == "ctx-sess"
104
109
 
105
110
  def test_task_id_from_context(self):
106
111
  with patch.dict(os.environ, {"RIFF_PROJECT_ID": "proj-1"}, clear=True):
107
112
  with with_context(RiffContext(task_id="ctx-task")):
108
113
  client = _make_client()
109
- assert client._transport._client.headers["X-Riff-Task-Id"] == "ctx-task"
114
+ assert _tracking(client)["X-Riff-Task-Id"] == "ctx-task"
110
115
 
111
116
  def test_param_overrides_context(self):
112
117
  with with_context(RiffContext(session_id="ctx", task_id="ctx-t")):
113
118
  client = _make_client(session_id="param", task_id="param-t")
114
- assert client._session_id == "param"
115
- assert client._transport._client.headers["X-Riff-Session-Id"] == "param"
116
- assert client._transport._client.headers["X-Riff-Task-Id"] == "param-t"
119
+ assert _tracking(client)["X-Riff-Session-Id"] == "param"
120
+ assert _tracking(client)["X-Riff-Task-Id"] == "param-t"
117
121
 
118
- def test_env_overrides_context(self):
122
+ def test_context_overrides_env(self):
119
123
  with patch.dict(
120
124
  os.environ, {"RIFF_SESSION_ID": "env", "RIFF_TASK_ID": "env-t"}
121
125
  ):
122
126
  with with_context(RiffContext(session_id="ctx", task_id="ctx-t")):
123
127
  client = _make_client()
124
- assert client._session_id == "env"
125
- assert client._transport._client.headers["X-Riff-Session-Id"] == "env"
126
- assert client._transport._client.headers["X-Riff-Task-Id"] == "env-t"
128
+ assert _tracking(client)["X-Riff-Session-Id"] == "ctx"
129
+ assert _tracking(client)["X-Riff-Task-Id"] == "ctx-t"
127
130
 
128
- def test_session_scope_without_session_id_raises(self):
131
+ def test_context_bound_after_construction_is_used(self):
132
+ with patch.dict(os.environ, {"RIFF_PROJECT_ID": "proj-1"}, clear=True):
133
+ client = _make_client()
134
+ with with_context(RiffContext(session_id="later")):
135
+ assert _tracking(client)["X-Riff-Session-Id"] == "later"
136
+ assert client._scope_headers("session") == {
137
+ "X-Riff-Storage-Scope": "session"
138
+ }
139
+ assert "X-Riff-Session-Id" not in _tracking(client)
140
+
141
+ def test_explicit_session_scope_needs_no_ambient_session(self):
129
142
  with patch.dict(os.environ, {"RIFF_PROJECT_ID": "proj-1"}, clear=True):
130
143
  client = _make_client(scope=None)
131
- with pytest.raises(ValueError, match="session_id is required"):
132
- client._scope_headers("session:abc")
144
+ assert client._scope_headers("session:abc") == {
145
+ "X-Riff-Storage-Scope": "session:abc"
146
+ }
133
147
 
134
148
  def test_session_scope_with_session_id_ok(self):
135
149
  client = _make_client(session_id="s1")
@@ -144,8 +158,8 @@ class TestStorageClientInit:
144
158
  def test_session_magic_string_without_session_id_raises(self):
145
159
  with patch.dict(os.environ, {"RIFF_PROJECT_ID": "proj-1"}, clear=True):
146
160
  client = _make_client(scope=None)
147
- with pytest.raises(ValueError, match="session_id is required"):
148
- client._scope_headers("session")
161
+ with pytest.raises(ValueError, match="session_id is required"):
162
+ client._scope_headers("session")
149
163
 
150
164
  def test_uds_from_param(self):
151
165
  client = _make_client(uds="/tmp/test.sock")
@@ -5,6 +5,7 @@ import httpx
5
5
  import pytest
6
6
 
7
7
  from riffsdk._internal.auth import _StaticTokenAuth
8
+ from riffsdk.context import RiffContext, with_context
8
9
  from riffsdk.storage._http import (
9
10
  AsyncTransport,
10
11
  SyncTransport,
@@ -208,28 +209,92 @@ class TestRaiseForStatus:
208
209
  assert exc_info.value.request_id == "req-abc"
209
210
 
210
211
 
212
+ def _sent_headers(t) -> dict[str, str]:
213
+ """Headers a SyncTransport actually passes for one request."""
214
+ t._base._client.request = MagicMock(return_value=_make_response(200, {}))
215
+ t.request("GET", "/x")
216
+ return t._base._client.request.call_args.kwargs["headers"]
217
+
218
+
219
+ async def _sent_headers_async(t) -> dict[str, str]:
220
+ t._base._client.request = AsyncMock(return_value=_make_response(200, {}))
221
+ await t.request("GET", "/x")
222
+ return t._base._client.request.call_args.kwargs["headers"]
223
+
224
+
211
225
  class TestTransportHeaders:
212
- def test_session_id_in_default_headers(self):
226
+ def test_session_id_sent_per_request(self):
213
227
  t = _make_transport(session_id="sess-1")
214
- assert t._client.headers["X-Riff-Session-Id"] == "sess-1"
228
+ assert _sent_headers(t)["X-Riff-Session-Id"] == "sess-1"
215
229
 
216
- def test_task_id_in_default_headers(self):
230
+ def test_task_id_sent_per_request(self):
217
231
  t = _make_transport(task_id="task-1")
218
- assert t._client.headers["X-Riff-Task-Id"] == "task-1"
232
+ assert _sent_headers(t)["X-Riff-Task-Id"] == "task-1"
219
233
 
220
234
  def test_both_headers(self):
221
235
  t = _make_transport(session_id="s", task_id="t")
222
- assert t._client.headers["X-Riff-Session-Id"] == "s"
223
- assert t._client.headers["X-Riff-Task-Id"] == "t"
236
+ headers = _sent_headers(t)
237
+ assert headers["X-Riff-Session-Id"] == "s"
238
+ assert headers["X-Riff-Task-Id"] == "t"
224
239
 
225
- def test_no_headers_when_omitted(self):
226
- t = _make_transport()
240
+ def test_not_frozen_into_default_headers(self):
241
+ t = _make_transport(session_id="s", task_id="t")
227
242
  assert "X-Riff-Session-Id" not in t._client.headers
228
243
  assert "X-Riff-Task-Id" not in t._client.headers
229
244
 
230
- def test_async_session_id_in_default_headers(self):
245
+ def test_no_headers_when_omitted(self):
246
+ with patch.dict("os.environ", {}, clear=True):
247
+ t = _make_transport()
248
+ headers = _sent_headers(t)
249
+ assert "X-Riff-Session-Id" not in headers
250
+ assert "X-Riff-Task-Id" not in headers
251
+
252
+ def test_explicit_request_header_wins(self):
253
+ t = _make_transport(session_id="ambient")
254
+ t._base._client.request = MagicMock(return_value=_make_response(200, {}))
255
+ t.request("GET", "/x", headers={"X-Riff-Session-Id": "explicit"})
256
+ sent = t._base._client.request.call_args.kwargs["headers"]
257
+ assert sent["X-Riff-Session-Id"] == "explicit"
258
+
259
+ def test_context_bound_after_construction_is_used(self):
260
+ with patch.dict("os.environ", {}, clear=True):
261
+ t = _make_transport()
262
+ with with_context(RiffContext(session_id="a", task_id="ta")):
263
+ first = _sent_headers(t)
264
+ with with_context(RiffContext(session_id="b")):
265
+ second = _sent_headers(t)
266
+ assert first["X-Riff-Session-Id"] == "a"
267
+ assert first["X-Riff-Task-Id"] == "ta"
268
+ assert second["X-Riff-Session-Id"] == "b"
269
+ assert "X-Riff-Task-Id" not in second
270
+
271
+ def test_context_beats_env(self):
272
+ with patch.dict("os.environ", {"RIFF_SESSION_ID": "env"}, clear=True):
273
+ t = _make_transport()
274
+ with with_context(RiffContext(session_id="ctx")):
275
+ assert _sent_headers(t)["X-Riff-Session-Id"] == "ctx"
276
+ assert _sent_headers(t)["X-Riff-Session-Id"] == "env"
277
+
278
+ def test_explicit_beats_context(self):
279
+ t = _make_transport(session_id="explicit")
280
+ with with_context(RiffContext(session_id="ctx")):
281
+ assert _sent_headers(t)["X-Riff-Session-Id"] == "explicit"
282
+
283
+ @pytest.mark.asyncio
284
+ async def test_async_session_id_sent_per_request(self):
231
285
  t = _make_transport(cls=AsyncTransport, session_id="sess-a")
232
- assert t._client.headers["X-Riff-Session-Id"] == "sess-a"
286
+ assert (await _sent_headers_async(t))["X-Riff-Session-Id"] == "sess-a"
287
+
288
+ @pytest.mark.asyncio
289
+ async def test_async_context_bound_after_construction_is_used(self):
290
+ with patch.dict("os.environ", {}, clear=True):
291
+ t = _make_transport(cls=AsyncTransport)
292
+ with with_context(RiffContext(session_id="a")):
293
+ first = await _sent_headers_async(t)
294
+ with with_context(RiffContext(session_id="b")):
295
+ second = await _sent_headers_async(t)
296
+ assert first["X-Riff-Session-Id"] == "a"
297
+ assert second["X-Riff-Session-Id"] == "b"
233
298
 
234
299
  def test_async_no_headers_when_omitted(self):
235
300
  t = _make_transport(cls=AsyncTransport)
@@ -237,6 +302,33 @@ class TestTransportHeaders:
237
302
  assert "X-Riff-Task-Id" not in t._client.headers
238
303
 
239
304
 
305
+ class TestRiffClientDefaultSingleton:
306
+ def test_default_client_follows_context_bound_after_construction(self):
307
+ from riffsdk.client import RiffClient
308
+
309
+ RiffClient._default = None
310
+ try:
311
+ with patch.dict(
312
+ "os.environ",
313
+ {"RIFF_PROJECT_ID": "p", "RIFF_SDK_EGRESS_SOCKET": "/tmp/x.sock"},
314
+ clear=True,
315
+ ):
316
+ client = RiffClient.default()
317
+ assert RiffClient.default() is client
318
+ mock = MagicMock(return_value=_make_response(200, {}))
319
+ client._transport._client.request = mock
320
+ with with_context(RiffContext(session_id="first")):
321
+ client.request("GET", "/x")
322
+ with with_context(RiffContext(session_id="second")):
323
+ client.request("GET", "/x")
324
+ sent = [
325
+ c.kwargs["headers"]["X-Riff-Session-Id"] for c in mock.call_args_list
326
+ ]
327
+ assert sent == ["first", "second"]
328
+ finally:
329
+ RiffClient._default = None
330
+
331
+
240
332
  class TestTransportUDS:
241
333
  def test_sync_uds_sets_transport(self):
242
334
  t = _make_transport(uds="/tmp/test.sock")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes