threadify-sdk 0.2.9__tar.gz → 0.3.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 (33) hide show
  1. {threadify_sdk-0.2.9/threadify_sdk.egg-info → threadify_sdk-0.3.1}/PKG-INFO +106 -2
  2. threadify_sdk-0.3.1/README.md +310 -0
  3. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/pyproject.toml +4 -1
  4. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/tests/test_connection.py +91 -43
  5. threadify_sdk-0.3.1/tests/test_management.py +115 -0
  6. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/tests/test_notification.py +2 -2
  7. threadify_sdk-0.3.1/tests/test_parity.py +320 -0
  8. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/tests/test_thread.py +2 -2
  9. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/__init__.py +9 -1
  10. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/client.py +40 -12
  11. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/connection.py +159 -32
  12. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/data_retriever.py +15 -4
  13. threadify_sdk-0.3.1/threadify/management.py +134 -0
  14. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/models.py +57 -1
  15. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/step.py +81 -12
  16. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/thread.py +16 -1
  17. threadify_sdk-0.3.1/threadify/waiting.py +205 -0
  18. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1/threadify_sdk.egg-info}/PKG-INFO +106 -2
  19. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify_sdk.egg-info/SOURCES.txt +4 -0
  20. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify_sdk.egg-info/requires.txt +5 -0
  21. threadify_sdk-0.2.9/README.md +0 -210
  22. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/CHANGELOG.md +0 -0
  23. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/LICENSE +0 -0
  24. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/MANIFEST.in +0 -0
  25. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/setup.cfg +0 -0
  26. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/tests/test_client.py +0 -0
  27. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/tests/test_data_retriever.py +0 -0
  28. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/tests/test_models.py +0 -0
  29. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/tests/test_step.py +0 -0
  30. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/notification.py +0 -0
  31. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify/otel_exporter.py +0 -0
  32. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify_sdk.egg-info/dependency_links.txt +0 -0
  33. {threadify_sdk-0.2.9 → threadify_sdk-0.3.1}/threadify_sdk.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: threadify-sdk
3
- Version: 0.2.9
3
+ Version: 0.3.1
4
4
  Summary: Python SDK for Threadify — Service-delivery intelligence. Track every customer request from start to finish across every system, team, and partner. Visit: https://threadify.dev
5
5
  Author-email: Threadify Team <team@threadify.dev>
6
6
  License: MIT
@@ -19,10 +19,14 @@ Description-Content-Type: text/markdown
19
19
  License-File: LICENSE
20
20
  Requires-Dist: websockets>=12.0
21
21
  Requires-Dist: httpx>=0.27.0
22
+ Requires-Dist: PyYAML>=6.0
23
+ Provides-Extra: otel
24
+ Requires-Dist: opentelemetry-sdk>=1.20; extra == "otel"
22
25
  Provides-Extra: dev
23
26
  Requires-Dist: pytest>=8.0; extra == "dev"
24
27
  Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
25
28
  Requires-Dist: ruff>=0.3; extra == "dev"
29
+ Requires-Dist: opentelemetry-sdk>=1.20; extra == "dev"
26
30
  Dynamic: license-file
27
31
 
28
32
  # Threadify Python SDK
@@ -88,7 +92,55 @@ if __name__ == "__main__":
88
92
  asyncio.run(main())
89
93
  ```
90
94
 
91
- `ws_url` defaults to `wss://eng.threadify.dev/threads`. Override it if you are using a self-hosted or regional endpoint.
95
+ For self-hosting, pass `engine_url="https://threadify.example.com"`. WebSocket and GraphQL paths are derived from that base, including reverse-proxy prefixes. Explicit `ws_url` and `graphql_url` remain available for split deployments.
96
+
97
+ ## Entity profile config as code
98
+
99
+ The management client sends a complete desired declaration to Threadify. The
100
+ server performs metric reconciliation by name; SDK callers do not send database
101
+ metric IDs or calculate deletions.
102
+
103
+ ```python
104
+ profiles = Threadify.entity_profiles(
105
+ "your-service-api-key",
106
+ web_api_url="https://web.threadify.dev/api",
107
+ )
108
+
109
+ declaration = {
110
+ "name": "Customer",
111
+ "description": "Customer delivery intelligence",
112
+ "type": ["customer_id", "customer_email"],
113
+ "metrics": [
114
+ {
115
+ "name": "Delivery success rate",
116
+ "template_id": "delivery_success_rate",
117
+ "parameters": {"window": "30d"},
118
+ }
119
+ ],
120
+ }
121
+
122
+ plan = await profiles.apply(declaration, dry_run=True)
123
+ result = await profiles.apply(declaration)
124
+ await profiles.rename("Customer", "Account") # explicit identity change
125
+ await profiles.close()
126
+ ```
127
+
128
+ The SDK can also load the declaration directly from YAML:
129
+
130
+ ```yaml
131
+ # threadify-profile.yaml
132
+ name: Customer
133
+ description: Customer delivery intelligence
134
+ type:
135
+ - customer_id
136
+ - customer_email
137
+ metrics: []
138
+ ```
139
+
140
+ ```python
141
+ plan = await profiles.apply_file("threadify-profile.yaml", dry_run=True)
142
+ result = await profiles.apply_file("threadify-profile.yaml")
143
+ ```
92
144
 
93
145
  ## Configuration
94
146
 
@@ -97,6 +149,7 @@ if __name__ == "__main__":
97
149
  Use keyword arguments with `Threadify.connect(...)`:
98
150
 
99
151
  - `service_name`
152
+ - `engine_url` (one HTTP(S) deployment base, including any proxy prefix)
100
153
  - `ws_url` (optional, defaults to production)
101
154
  - `graphql_url`
102
155
  - `debug`
@@ -235,3 +288,54 @@ Alternatively, use `pytest`:
235
288
  ```bash
236
289
  python3 -m pytest
237
290
  ```
291
+
292
+
293
+ ## Contract coordination (0.3)
294
+
295
+ ```python
296
+ from threadify import Threadify, WaitOptions, ThreadifyError
297
+
298
+ connection = await Threadify.connect(api_key, engine_url="https://threadify.example.com", service_name="payments")
299
+ threads = await connection.get_threads_by_ref({"order_id": "ORD-1001"}, status="active", limit=25)
300
+ thread = await connection.join(thread_id, "processor")
301
+ grant = await thread.wait_for("charge", WaitOptions(timeout=15))
302
+ # Execute the permitted business operation here.
303
+ result = await thread.step("charge").add_context({"amount": 42}).success("charged", wait_for=True, timeout=15)
304
+ assert result.validation.decision == "passed"
305
+ # Resume validation of exactly this event if a previous caller stopped waiting.
306
+ await thread.wait_for_validation("charge", result.step_id)
307
+ ```
308
+
309
+ `wait_for()` now asks the Engine for a permission grant, carrying an invocation
310
+ ID into the subsequent step report and its default idempotency key. It sends one
311
+ request and waits for a final correlated response. The old notification-only
312
+ helper is named `wait_for_notification()`; it does not authorize execution.
313
+
314
+ Timeouts are in **seconds**, at most 300. Cancelling the Python task or reaching
315
+ its timeout cancels the remote wait. Before reporting a granted operation, use
316
+ `await grant.cancel()` if you decide not to execute it. Cancellation does not
317
+ restore consumed fresh prerequisites; another invocation may need a new
318
+ successful predecessor. A disconnect rejects
319
+ pending requests immediately. No write is automatically retried; timeout errors
320
+ retain `invocation_id`, `idempotency_key`, or `step_id` where available for recovery.
321
+ A submitted event can still be persisted after its caller times out.
322
+
323
+ With `wait_for=True`, duplicate, violated, unavailable, and mismatched validation
324
+ responses raise `ThreadifyError` with a stable `code`; an ordinary acknowledgement
325
+ is not a validation result. Normal non-waiting duplicate reports keep the existing
326
+ `StepResult.duplicate` behavior. Contract definitions and Gherkin are enforced by
327
+ the Engine; SDKs select the contract and role rather than parsing contracts.
328
+
329
+ Install `threadify-sdk[otel]` to use the OTEL exporter. It preserves the recorded
330
+ span start/end and span-event timestamps, including spans exported later.
331
+
332
+ ## Package CI and publishing
333
+
334
+ CI tests Python 3.10, 3.12, and 3.13, including OTEL and wait-protocol regressions.
335
+ The `pypi-publish.yml` workflow validates a matching `vX.Y.Z` tag, builds a wheel
336
+ and source archive, checks metadata and wheel imports, then publishes using
337
+ [PyPI Trusted Publishing](https://docs.pypi.org/trusted-publishers/using-a-publisher/).
338
+ Configure a trusted publisher for owner `ThreadifyDev`, repository `python-sdk`,
339
+ workflow `pypi-publish.yml`, environment `pypi` in the `threadify-sdk` PyPI project.
340
+ A manual workflow run builds artifacts without publishing. No release is created
341
+ by running local tests or pushing an ordinary branch.
@@ -0,0 +1,310 @@
1
+ # Threadify Python SDK
2
+
3
+ Python SDK for [Threadify](https://threadify.dev) — Service-delivery intelligence that tracks every customer request from start to finish across every system, team, and partner.
4
+
5
+ - **Documentation:** [https://docs.threadify.dev](https://docs.threadify.dev)
6
+ - **Create an account:** [https://threadify.dev](https://threadify.dev)
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ pip install threadify-sdk
12
+ ```
13
+
14
+ For local development:
15
+
16
+ ```bash
17
+ pip install -e ".[dev]"
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```python
23
+ import asyncio
24
+ import logging
25
+ from threadify import Threadify
26
+
27
+
28
+ async def main():
29
+ try:
30
+ conn = await Threadify.connect(
31
+ "your-api-key",
32
+ service_name="orders-service",
33
+ )
34
+ except Exception as e:
35
+ logging.error(f"Failed to connect: {e}")
36
+ return
37
+
38
+ try:
39
+ thread = await conn.start(
40
+ contract_name="order_processing",
41
+ role="customer",
42
+ refs={"order_id": "ORD-123"},
43
+ tags=["priority"],
44
+ )
45
+
46
+ await thread.add_refs({"crm_id": "CRM-456"})
47
+
48
+ # Easy chaining!
49
+ await (
50
+ thread.step("order_received")
51
+ .add_context({"orderId": "ORD-123"})
52
+ .success("Order accepted")
53
+ )
54
+ except Exception as e:
55
+ logging.error(f"Error in thread: {e}")
56
+ finally:
57
+ await conn.close()
58
+
59
+
60
+ if __name__ == "__main__":
61
+ asyncio.run(main())
62
+ ```
63
+
64
+ For self-hosting, pass `engine_url="https://threadify.example.com"`. WebSocket and GraphQL paths are derived from that base, including reverse-proxy prefixes. Explicit `ws_url` and `graphql_url` remain available for split deployments.
65
+
66
+ ## Entity profile config as code
67
+
68
+ The management client sends a complete desired declaration to Threadify. The
69
+ server performs metric reconciliation by name; SDK callers do not send database
70
+ metric IDs or calculate deletions.
71
+
72
+ ```python
73
+ profiles = Threadify.entity_profiles(
74
+ "your-service-api-key",
75
+ web_api_url="https://web.threadify.dev/api",
76
+ )
77
+
78
+ declaration = {
79
+ "name": "Customer",
80
+ "description": "Customer delivery intelligence",
81
+ "type": ["customer_id", "customer_email"],
82
+ "metrics": [
83
+ {
84
+ "name": "Delivery success rate",
85
+ "template_id": "delivery_success_rate",
86
+ "parameters": {"window": "30d"},
87
+ }
88
+ ],
89
+ }
90
+
91
+ plan = await profiles.apply(declaration, dry_run=True)
92
+ result = await profiles.apply(declaration)
93
+ await profiles.rename("Customer", "Account") # explicit identity change
94
+ await profiles.close()
95
+ ```
96
+
97
+ The SDK can also load the declaration directly from YAML:
98
+
99
+ ```yaml
100
+ # threadify-profile.yaml
101
+ name: Customer
102
+ description: Customer delivery intelligence
103
+ type:
104
+ - customer_id
105
+ - customer_email
106
+ metrics: []
107
+ ```
108
+
109
+ ```python
110
+ plan = await profiles.apply_file("threadify-profile.yaml", dry_run=True)
111
+ result = await profiles.apply_file("threadify-profile.yaml")
112
+ ```
113
+
114
+ ## Configuration
115
+
116
+ ### Connect options
117
+
118
+ Use keyword arguments with `Threadify.connect(...)`:
119
+
120
+ - `service_name`
121
+ - `engine_url` (one HTTP(S) deployment base, including any proxy prefix)
122
+ - `ws_url` (optional, defaults to production)
123
+ - `graphql_url`
124
+ - `debug`
125
+ - `max_in_flight`
126
+ - `connect_timeout`
127
+
128
+ Example:
129
+
130
+ ```python
131
+ from threadify import Threadify
132
+
133
+ conn = await Threadify.connect(
134
+ "your-api-key",
135
+ service_name="inventory-service",
136
+ debug=True,
137
+ )
138
+ ```
139
+
140
+ ### Join options
141
+
142
+ Use `Connection.join(...)` with keyword arguments:
143
+
144
+ - `token=...`
145
+ - `thread_id=...` and `role=...`
146
+
147
+ Example:
148
+
149
+ ```python
150
+ thread = await conn.join(token="jwt-token")
151
+ ```
152
+
153
+ Or:
154
+
155
+ ```python
156
+ thread = await conn.join(
157
+ thread_id="thread-123",
158
+ role="supplier",
159
+ )
160
+ ```
161
+
162
+ ### Start options
163
+
164
+ `Connection.start(...)` supports named options for contract, role, refs, and tags, while preserving the older positional forms:
165
+
166
+ ```python
167
+ thread = await conn.start(
168
+ contract_name="order_processing",
169
+ role="customer",
170
+ refs={"customer_id": "123"},
171
+ tags=["priority"],
172
+ )
173
+ thread = await conn.start("Order-123", "customer")
174
+ thread = await conn.start({"customer_id": "123"}, "customer")
175
+ thread = await conn.start("Order-123") # contract is optional
176
+ ```
177
+
178
+ ## Subscriptions
179
+
180
+ Preferred API:
181
+
182
+ - `subscribe(event, step_name, handler)`
183
+ - `unsubscribe(event, step_name)`
184
+
185
+ Supported event patterns:
186
+
187
+ - `step.success`
188
+ - `step.failed`
189
+ - `step.*`
190
+ - `rule.passed`
191
+ - `rule.violated`
192
+ - `rule.*`
193
+ - `*`
194
+
195
+ Example:
196
+
197
+ ```python
198
+ def handle_notification(notification):
199
+ if notification.is_violated:
200
+ print(notification.message)
201
+
202
+
203
+
204
+ conn.subscribe("rule.violated", "payment_step", handle_notification)
205
+ ```
206
+
207
+ ## Versioning & Releases
208
+
209
+ This SDK follows [Semantic Versioning](https://semver.org/) and [Conventional Commits](https://www.conventionalcommits.org/). Releases are automated via GitHub Actions.
210
+
211
+ - `fix: ...` -> Patch bump
212
+ - `feat: ...` -> Minor bump
213
+ - `feat!: ...` or `BREAKING CHANGE: ...` -> Major bump
214
+
215
+ ## OpenTelemetry Integration
216
+
217
+ The Python SDK includes the OpenTelemetry SpanExporter in the core package.
218
+
219
+ ```python
220
+ from opentelemetry import trace
221
+ from opentelemetry.sdk.trace import TracerProvider
222
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
223
+ from threadify import Threadify
224
+
225
+ conn = await Threadify.connect("api-key", service_name="checkout-service")
226
+
227
+ # Create exporter
228
+ exporter = conn.create_span_exporter(options={"refs": ["order.id", "customer.id"]})
229
+
230
+ # Filter spans by name — exact match or prefix wildcard with *
231
+ exporter = conn.create_span_exporter(options={
232
+ "refs": ["order.id", "customer.id"],
233
+ "filters": ["invoke_llm", "adk.before*", "llm.*"],
234
+ })
235
+
236
+ provider = TracerProvider()
237
+ provider.add_span_processor(BatchSpanProcessor(exporter))
238
+ trace.set_tracer_provider(provider)
239
+ ```
240
+
241
+ **Filter patterns:**
242
+
243
+ - `"invoke_llm"` — exact match
244
+ - `"adk.before*"` — prefix wildcard, drops any span starting with `adk.before`
245
+ - `"llm.*"` — prefix wildcard, drops any span starting with `llm.`
246
+
247
+ ## Testing
248
+
249
+ To run the SDK tests, execute:
250
+
251
+ ```bash
252
+ make test
253
+ ```
254
+
255
+ Alternatively, use `pytest`:
256
+
257
+ ```bash
258
+ python3 -m pytest
259
+ ```
260
+
261
+
262
+ ## Contract coordination (0.3)
263
+
264
+ ```python
265
+ from threadify import Threadify, WaitOptions, ThreadifyError
266
+
267
+ connection = await Threadify.connect(api_key, engine_url="https://threadify.example.com", service_name="payments")
268
+ threads = await connection.get_threads_by_ref({"order_id": "ORD-1001"}, status="active", limit=25)
269
+ thread = await connection.join(thread_id, "processor")
270
+ grant = await thread.wait_for("charge", WaitOptions(timeout=15))
271
+ # Execute the permitted business operation here.
272
+ result = await thread.step("charge").add_context({"amount": 42}).success("charged", wait_for=True, timeout=15)
273
+ assert result.validation.decision == "passed"
274
+ # Resume validation of exactly this event if a previous caller stopped waiting.
275
+ await thread.wait_for_validation("charge", result.step_id)
276
+ ```
277
+
278
+ `wait_for()` now asks the Engine for a permission grant, carrying an invocation
279
+ ID into the subsequent step report and its default idempotency key. It sends one
280
+ request and waits for a final correlated response. The old notification-only
281
+ helper is named `wait_for_notification()`; it does not authorize execution.
282
+
283
+ Timeouts are in **seconds**, at most 300. Cancelling the Python task or reaching
284
+ its timeout cancels the remote wait. Before reporting a granted operation, use
285
+ `await grant.cancel()` if you decide not to execute it. Cancellation does not
286
+ restore consumed fresh prerequisites; another invocation may need a new
287
+ successful predecessor. A disconnect rejects
288
+ pending requests immediately. No write is automatically retried; timeout errors
289
+ retain `invocation_id`, `idempotency_key`, or `step_id` where available for recovery.
290
+ A submitted event can still be persisted after its caller times out.
291
+
292
+ With `wait_for=True`, duplicate, violated, unavailable, and mismatched validation
293
+ responses raise `ThreadifyError` with a stable `code`; an ordinary acknowledgement
294
+ is not a validation result. Normal non-waiting duplicate reports keep the existing
295
+ `StepResult.duplicate` behavior. Contract definitions and Gherkin are enforced by
296
+ the Engine; SDKs select the contract and role rather than parsing contracts.
297
+
298
+ Install `threadify-sdk[otel]` to use the OTEL exporter. It preserves the recorded
299
+ span start/end and span-event timestamps, including spans exported later.
300
+
301
+ ## Package CI and publishing
302
+
303
+ CI tests Python 3.10, 3.12, and 3.13, including OTEL and wait-protocol regressions.
304
+ The `pypi-publish.yml` workflow validates a matching `vX.Y.Z` tag, builds a wheel
305
+ and source archive, checks metadata and wheel imports, then publishes using
306
+ [PyPI Trusted Publishing](https://docs.pypi.org/trusted-publishers/using-a-publisher/).
307
+ Configure a trusted publisher for owner `ThreadifyDev`, repository `python-sdk`,
308
+ workflow `pypi-publish.yml`, environment `pypi` in the `threadify-sdk` PyPI project.
309
+ A manual workflow run builds artifacts without publishing. No release is created
310
+ by running local tests or pushing an ordinary branch.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "threadify-sdk"
7
- version = "0.2.9"
7
+ version = "0.3.1"
8
8
  description = "Python SDK for Threadify — Service-delivery intelligence. Track every customer request from start to finish across every system, team, and partner. Visit: https://threadify.dev"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -28,13 +28,16 @@ classifiers = [
28
28
  dependencies = [
29
29
  "websockets>=12.0",
30
30
  "httpx>=0.27.0",
31
+ "PyYAML>=6.0",
31
32
  ]
32
33
 
33
34
  [project.optional-dependencies]
35
+ otel = ["opentelemetry-sdk>=1.20"]
34
36
  dev = [
35
37
  "pytest>=8.0",
36
38
  "pytest-asyncio>=0.23",
37
39
  "ruff>=0.3",
40
+ "opentelemetry-sdk>=1.20",
38
41
  ]
39
42
 
40
43
  [tool.pytest.ini_options]
@@ -1,5 +1,5 @@
1
1
  import asyncio
2
- from unittest.mock import AsyncMock, MagicMock
2
+ from unittest.mock import AsyncMock
3
3
 
4
4
  import pytest
5
5
 
@@ -17,35 +17,25 @@ def _make_mock_ws():
17
17
  ws.send = AsyncMock()
18
18
  ws.close = AsyncMock()
19
19
  # Mock async iteration (empty by default).
20
- ws.__aiter__ = MagicMock(return_value=iter([]))
20
+ ws.__aiter__.return_value = []
21
21
  return ws
22
22
 
23
23
 
24
24
  def _make_connection():
25
- """Create a Connection with mocked WebSocket (listener disabled)."""
25
+ """Create a Connection with mocked WebSocket (listener/heartbeat disabled)."""
26
26
  ws = _make_mock_ws()
27
27
  conn = Connection.__new__(Connection)
28
- conn._ws = ws
29
- conn._api_key = "test-key"
30
- conn._service_name = "test-service"
31
- conn._graphql_url = "https://example.com/graphql"
32
- conn._debug = False
33
- conn._max_in_flight = 10
34
- conn._connected = True
35
- conn._threads = {}
36
- conn._notification_handlers = {}
37
- conn._active_subscriptions = {}
38
- conn._processed_notifications = set()
39
- conn._processed_notifications_max_size = 10_000
40
- conn._recv_queue = asyncio.Queue()
41
- conn._data_retriever = None
42
- import logging
43
-
44
- conn._logger = logging.getLogger("threadify-test")
45
- # Create a completed listener task.
28
+ # Call __init__ to set all fields, then override tasks so they don't run.
29
+ conn.__init__(ws, "test-key", "test-service", "https://example.com/graphql", debug=False, max_in_flight=10)
30
+ # Cancel the actual tasks before replacing their handles. Otherwise the
31
+ # listener can close the connection while response-queue tests are running.
32
+ conn._listener_task.cancel()
33
+ conn._heartbeat_task.cancel()
46
34
  loop = asyncio.get_event_loop()
47
35
  conn._listener_task = loop.create_future()
48
36
  conn._listener_task.set_result(None)
37
+ conn._heartbeat_task = loop.create_future()
38
+ conn._heartbeat_task.set_result(None)
49
39
  return conn
50
40
 
51
41
 
@@ -53,12 +43,12 @@ class TestParseEvent:
53
43
  @pytest.mark.parametrize(
54
44
  "event,expected_source,expected_type",
55
45
  [
56
- ("step.success", "execution", "success"),
57
- ("step.failed", "execution", "failed"),
58
- ("rule.violated", "validation", "violated"),
59
- ("rule.passed", "validation", "passed"),
60
- ("step.*", "execution", "*"),
61
- ("rule.*", "validation", "*"),
46
+ ("step.success", "step", "success"),
47
+ ("step.failed", "step", "failed"),
48
+ ("rule.violated", "rule", "violated"),
49
+ ("rule.passed", "rule", "passed"),
50
+ ("step.*", "step", "*"),
51
+ ("rule.*", "rule", "*"),
62
52
  ("*", "*", "*"),
63
53
  ],
64
54
  )
@@ -67,28 +57,32 @@ class TestParseEvent:
67
57
  assert source == expected_source
68
58
  assert etype == expected_type
69
59
 
60
+ def test_unsupported_source_is_rejected(self):
61
+ with pytest.raises(ValueError, match="Unsupported notification source"):
62
+ _parse_event("unsupported.success")
63
+
70
64
 
71
65
  class TestBuildEventTypes:
72
66
  def test_wildcard_all(self):
73
67
  result = _build_event_types("*", "*")
74
68
  assert set(result) == {
75
- "execution.success",
76
- "execution.failed",
77
- "validation.passed",
78
- "validation.violated",
69
+ "step.success",
70
+ "step.failed",
71
+ "rule.passed",
72
+ "rule.violated",
79
73
  }
80
74
 
81
- def test_execution_wildcard(self):
82
- result = _build_event_types("execution", "*")
83
- assert set(result) == {"execution.success", "execution.failed"}
75
+ def test_step_wildcard(self):
76
+ result = _build_event_types("step", "*")
77
+ assert set(result) == {"step.success", "step.failed"}
84
78
 
85
- def test_validation_wildcard(self):
86
- result = _build_event_types("validation", "*")
87
- assert set(result) == {"validation.passed", "validation.violated"}
79
+ def test_rule_wildcard(self):
80
+ result = _build_event_types("rule", "*")
81
+ assert set(result) == {"rule.passed", "rule.violated"}
88
82
 
89
83
  def test_specific(self):
90
- result = _build_event_types("execution", "success")
91
- assert result == ["execution.success"]
84
+ result = _build_event_types("step", "success")
85
+ assert result == ["step.success"]
92
86
 
93
87
 
94
88
  class TestMergeUnique:
@@ -121,6 +115,60 @@ class TestConnectionProperties:
121
115
  assert conn.is_connected is True
122
116
 
123
117
 
118
+ class TestWaitResponse:
119
+ def test_skips_unmatched_responses_without_spinning(self):
120
+ async def scenario():
121
+ conn = _make_connection()
122
+ heartbeat = {"action": "heartbeat", "status": "success"}
123
+ joined = {
124
+ "action": "joinThread",
125
+ "status": "success",
126
+ "threadId": "thread-123",
127
+ }
128
+ conn._recv_queue.put_nowait(heartbeat)
129
+ conn._recv_queue.put_nowait(joined)
130
+
131
+ result = await conn._wait_response(
132
+ lambda message: message.get("action") == "joinThread",
133
+ timeout=0.1,
134
+ )
135
+
136
+ assert result == joined
137
+ assert conn._recv_queue.get_nowait() == heartbeat
138
+
139
+ asyncio.run(scenario())
140
+
141
+ def test_serializes_concurrent_waiters_and_preserves_other_response(self):
142
+ async def scenario():
143
+ conn = _make_connection()
144
+ join_waiter = asyncio.create_task(
145
+ conn._wait_response(
146
+ lambda message: message.get("action") == "joinThread",
147
+ timeout=0.1,
148
+ )
149
+ )
150
+ start_waiter = asyncio.create_task(
151
+ conn._wait_response(
152
+ lambda message: message.get("action") == "startThread",
153
+ timeout=0.1,
154
+ )
155
+ )
156
+ await asyncio.sleep(0)
157
+ conn._recv_queue.put_nowait(
158
+ {"action": "startThread", "status": "success", "threadId": "two"}
159
+ )
160
+ conn._recv_queue.put_nowait(
161
+ {"action": "joinThread", "status": "success", "threadId": "one"}
162
+ )
163
+
164
+ joined, started = await asyncio.gather(join_waiter, start_waiter)
165
+
166
+ assert joined["threadId"] == "one"
167
+ assert started["threadId"] == "two"
168
+
169
+ asyncio.run(scenario())
170
+
171
+
124
172
  class TestStart:
125
173
  @pytest.mark.asyncio
126
174
  async def test_start_with_label_and_optional_contract(self):
@@ -328,8 +376,8 @@ class TestNotificationHandling:
328
376
  "notificationId": "n-001",
329
377
  "threadId": "t-1",
330
378
  "stepName": "order_placed",
331
- "source": "execution",
332
- "notificationType": "execution.success",
379
+ "source": "step",
380
+ "notificationType": "step.success",
333
381
  "stepStatus": "success",
334
382
  }
335
383
 
@@ -359,8 +407,8 @@ class TestNotificationHandling:
359
407
  "notificationId": "n-err",
360
408
  "threadId": "t-1",
361
409
  "stepName": "broken_step",
362
- "source": "execution",
363
- "notificationType": "execution.failed",
410
+ "source": "step",
411
+ "notificationType": "step.failed",
364
412
  "stepStatus": "failed",
365
413
  }
366
414