synadia-durable 0.2.0__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 (42) hide show
  1. synadia_durable-0.2.0/LICENSE +201 -0
  2. synadia_durable-0.2.0/PKG-INFO +179 -0
  3. synadia_durable-0.2.0/README.md +151 -0
  4. synadia_durable-0.2.0/pyproject.toml +124 -0
  5. synadia_durable-0.2.0/src/synadia_durable/__init__.py +119 -0
  6. synadia_durable-0.2.0/src/synadia_durable/_engine/__init__.py +6 -0
  7. synadia_durable-0.2.0/src/synadia_durable/_engine/blobs.py +277 -0
  8. synadia_durable-0.2.0/src/synadia_durable/_engine/client.py +305 -0
  9. synadia_durable-0.2.0/src/synadia_durable/_engine/errors.py +219 -0
  10. synadia_durable-0.2.0/src/synadia_durable/_engine/names.py +39 -0
  11. synadia_durable-0.2.0/src/synadia_durable/_engine/payload.py +203 -0
  12. synadia_durable-0.2.0/src/synadia_durable/_engine/transport.py +231 -0
  13. synadia_durable-0.2.0/src/synadia_durable/_engine/worker.py +1020 -0
  14. synadia_durable-0.2.0/src/synadia_durable/_internal/__init__.py +1 -0
  15. synadia_durable-0.2.0/src/synadia_durable/_internal/backoff.py +22 -0
  16. synadia_durable-0.2.0/src/synadia_durable/_internal/invariant.py +43 -0
  17. synadia_durable-0.2.0/src/synadia_durable/_internal/json.py +76 -0
  18. synadia_durable-0.2.0/src/synadia_durable/_internal/logger.py +53 -0
  19. synadia_durable-0.2.0/src/synadia_durable/_internal/metrics.py +94 -0
  20. synadia_durable-0.2.0/src/synadia_durable/_internal/token.py +29 -0
  21. synadia_durable-0.2.0/src/synadia_durable/_nats/__init__.py +6 -0
  22. synadia_durable-0.2.0/src/synadia_durable/_nats/connect.py +29 -0
  23. synadia_durable-0.2.0/src/synadia_durable/_nats/protocol.py +106 -0
  24. synadia_durable-0.2.0/src/synadia_durable/core/__init__.py +6 -0
  25. synadia_durable-0.2.0/src/synadia_durable/core/children.py +54 -0
  26. synadia_durable-0.2.0/src/synadia_durable/core/ctx.py +1297 -0
  27. synadia_durable-0.2.0/src/synadia_durable/core/execute.py +268 -0
  28. synadia_durable-0.2.0/src/synadia_durable/core/inbound.py +194 -0
  29. synadia_durable-0.2.0/src/synadia_durable/core/registry.py +65 -0
  30. synadia_durable-0.2.0/src/synadia_durable/core/scheduler.py +36 -0
  31. synadia_durable-0.2.0/src/synadia_durable/core/work_item.py +57 -0
  32. synadia_durable-0.2.0/src/synadia_durable/core/workflow.py +61 -0
  33. synadia_durable-0.2.0/src/synadia_durable/errors.py +228 -0
  34. synadia_durable-0.2.0/src/synadia_durable/journal/__init__.py +1 -0
  35. synadia_durable-0.2.0/src/synadia_durable/journal/blobs.py +551 -0
  36. synadia_durable-0.2.0/src/synadia_durable/journal/codec.py +103 -0
  37. synadia_durable-0.2.0/src/synadia_durable/journal/entry.py +372 -0
  38. synadia_durable-0.2.0/src/synadia_durable/journal/payload_codec.py +98 -0
  39. synadia_durable-0.2.0/src/synadia_durable/journal/store.py +182 -0
  40. synadia_durable-0.2.0/src/synadia_durable/py.typed +0 -0
  41. synadia_durable-0.2.0/src/synadia_durable/types.py +258 -0
  42. synadia_durable-0.2.0/src/synadia_durable/version.py +26 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a fee
167
+ for, acceptance of support, warranty, indemnity, or other liability
168
+ obligations and/or rights consistent with this License. However, in
169
+ accepting such obligations, You may act only on Your own behalf and
170
+ on Your sole responsibility, not on behalf of any other Contributor,
171
+ and only if You agree to indemnify, defend, and hold each Contributor
172
+ harmless for any liability incurred by, or claims asserted against,
173
+ such Contributor by reason of your accepting any such warranty or
174
+ additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Synadia Communications
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing permissions
201
+ and limitations under the License.
@@ -0,0 +1,179 @@
1
+ Metadata-Version: 2.5
2
+ Name: synadia-durable
3
+ Version: 0.2.0
4
+ Summary: Durable execution for Python on NATS: workflows as async functions, every step journaled, durable-engine behind it.
5
+ Project-URL: Homepage, https://github.com/synadia-ai/durable-sdk/tree/main/python
6
+ Project-URL: Repository, https://github.com/synadia-ai/durable-sdk
7
+ Project-URL: Issues, https://github.com/synadia-ai/durable-sdk/issues
8
+ Project-URL: Changelog, https://github.com/synadia-ai/durable-sdk/blob/main/CHANGELOG.md
9
+ Author: Synadia Communications
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: durable,durable-execution,nats,workflow
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: System :: Distributed Computing
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: nats-py>=2.15.0
25
+ Provides-Extra: crypto
26
+ Requires-Dist: cryptography>=42; extra == 'crypto'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # `synadia-durable` (Python)
30
+
31
+ Durable execution for Python on NATS. Workflows are ordinary async functions over a `ctx`: every step is journaled, and after a crash a run resumes where it was, without repeating finished steps. Your workflow code runs in your process. The journal, the timers and the work queue are kept by **durable-engine**, which Synadia ships to you, or which the Synadia Agent Fabric runs for you.
32
+
33
+ ```sh
34
+ pip install synadia-durable # or: uv add synadia-durable
35
+ ```
36
+
37
+ This is the thin durable execution SDK for Python, the twin of the TypeScript SDK (`@synadia-ai/durable` on npm); both live in the [durable-sdk repository](https://github.com/synadia-ai/durable-sdk). Its replay core, with the determinism guards and the out-of-band halts, runs in your process. Behind the core's seams sits a request/reply client for the engine, which owns the streams: nothing runs without the engine.
38
+
39
+ **It runs in two places, with the same code:**
40
+
41
+ | Where | The engine | Start here |
42
+ | ------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
43
+ | **standalone** | yours, next to your NATS, with a licence | the Quickstart below |
44
+ | **on the Synadia Agent Fabric** | the fabric runs it; your account reaches it through an import | [`docs/FABRIC.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/FABRIC.md) |
45
+
46
+ - **The public API:** `@workflow` / `define_workflow`, `create_client`, `create_worker`, and `ctx.run/sleep/wait/call/start_call/race/now/random/uuid/key/continue_as_new/on_cancel`.
47
+ - **The only dependency is `nats-py`**, used for core request/reply alone: every call is one request to `{prefix}.api.v1.<op>` (the engine's `API.md`, the document delivered with the engine). There are no consumers, streams or buckets here, and no JetStream client. `cryptography` is the optional `crypto` extra, for `aes_gcm_payload_codec` (`pip install 'synadia-durable[crypto]'`).
48
+ - **Documentation** is this README, [`docs/FABRIC.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/FABRIC.md) (on the fabric), the [examples](https://github.com/synadia-ai/durable-sdk/blob/main/python/examples/README.md) and [`docs/DEVELOPING.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/DEVELOPING.md) (the test suites). The engine's operator has the documents shipped with the engine, `QUICKSTART.md` and `API.md`.
49
+
50
+ **Version:** `0.2.0`, the TypeScript SDK's twin.
51
+
52
+ ## Quickstart
53
+
54
+ A workflow on your laptop: NATS with JetStream, the engine next to it, and a workflow in a project of your own. You need `nats-server` ≥ 2.14 on `PATH`, Python ≥ 3.11 with [`uv`](https://docs.astral.sh/uv/), and from Synadia **the engine for your platform** (the archive `durable-engine_<version>_<os>_<arch>.tar.gz`, or the container image) and **a licence file**. On the Synadia Agent Fabric you need neither: the engine is already there ([`docs/FABRIC.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/FABRIC.md)).
55
+
56
+ ```sh
57
+ nats-server -js & # 1. NATS with JetStream, on 127.0.0.1:4222
58
+ tar xzf durable-engine_<version>_<os>_<arch>.tar.gz # 2. the engine Synadia sent you
59
+ ./durable-engine_<version>_<os>_<arch>/durable-engine serve \
60
+ --nats nats://127.0.0.1:4222 --licence durable.licence & # 3. the engine, with your licence
61
+ uv init --bare order && cd order && uv add synadia-durable # 4. a project of your own
62
+ NATS_URL=nats://127.0.0.1:4222 uv run python order.py # 5. the file below
63
+ ```
64
+
65
+ With pip instead of uv, step 4 is `mkdir order && cd order && python3 -m venv .venv && .venv/bin/pip install synadia-durable`, and step 5 runs `.venv/bin/python order.py`.
66
+
67
+ `order.py`:
68
+
69
+ ```python
70
+ import asyncio
71
+ import os
72
+
73
+ import nats
74
+
75
+ from synadia_durable import Ctx, create_client, create_worker, with_reconnect_defaults, workflow
76
+
77
+
78
+ @workflow(name="order")
79
+ async def order(ctx: Ctx, cart: dict) -> dict:
80
+ order_id = await ctx.run("reserve", lambda: f"ord-{cart['cartId']}") # journaled, never re-run
81
+ payment = await ctx.wait("payment") # parks until a signal
82
+ if not payment["approved"]:
83
+ return {"status": "abandoned", "orderId": order_id}
84
+ await ctx.sleep("settle", 500) # a durable timer
85
+ return {"status": "paid", "orderId": order_id}
86
+
87
+
88
+ async def main() -> None:
89
+ nc = await nats.connect(
90
+ os.environ.get("NATS_URL", "nats://127.0.0.1:4222"), **with_reconnect_defaults()
91
+ )
92
+ worker = create_worker(nc, [order])
93
+ try:
94
+ await worker.start()
95
+ client = create_client(nc)
96
+ handle = await client.start(order, {"cartId": "c-42"})
97
+ await client.signal(handle.run_id, "payment", {"approved": True})
98
+ print(await handle.result(20_000)) # {'status': 'paid', 'orderId': 'ord-c-42'}
99
+ finally:
100
+ await worker.stop() # on any error too: its polls withdrawn, their items handed back
101
+ await nc.drain()
102
+
103
+
104
+ asyncio.run(main())
105
+ ```
106
+
107
+ It prints `{'status': 'paid', 'orderId': 'ord-c-42'}`. The engine logs `licence … licensee=<you>` and `serving` at start; it creates its streams and buckets on the first start and answers on `de.api.v1.*` (`nats req de.api.v1.info '{}'` shows it, with the `nats` CLI). Without a valid licence it exits at once and says why. Stop the engine and the server with `kill %2 %1`.
108
+
109
+ **With the container image** instead of the archive, step 3 is `docker run --rm --network host -v $PWD/durable.licence:/etc/durable-engine/licence:ro durable-engine:<version>` (on Docker Desktop add `--nats nats://host.docker.internal:4222` and drop `--network host`).
110
+
111
+ **Which engine:** this SDK needs an engine that announces `withdrawn-remembered` in `info.capabilities` (a worker withdrawn by `stop()` is remembered 5 s, so `stop()` sends one `cancelPoll`); the repository's `engine.pin` names the engine version the suites were last run against. `worker.start()` raises `UnsupportedEngineError` on an older one, naming the engine by its `engine` and `commit` as `info` gives them; a worker whose start found no engine checks at its first answered poll and stops there, logged at error (`health()` says stopped). The floor is read from `info.capabilities`, never from the version: every build so far says `0.2.0-dev`.
112
+
113
+ **A signal's id.** Every `client.signal` carries an id, a generated UUID unless you pass your own: `await client.signal(run_id, "payment", data, id="pay-c-42")` (`[A-Za-z0-9_-]+`, checked before any request). A retry passes the same id: if you send a signal again after an `EngineUnavailableError`, a timeout, or a restart of your own process, pass the id of the first try, and the engine answers `ok` and journals nothing more. Without an id each call is a new signal. The id is looked for in two journals only: the run the request names and the generation current when the request arrives. A signal journaled in any other generation (one that was current at the first try and has continued since) is not recognised, and is journaled again. The id dedups one signal: two signals with the same name and different ids are two signals.
114
+
115
+ ### Installing
116
+
117
+ ```sh
118
+ pip install synadia-durable # or: uv add synadia-durable
119
+ pip install 'synadia-durable[crypto]' # with aes_gcm_payload_codec, for encryption at rest
120
+ ```
121
+
122
+ `nats-py` comes with it; a creds file needs `nkeys` beside it (`pip install 'nats-py[nkeys]'`).
123
+
124
+ ## The examples
125
+
126
+ From a clone of the repository, each runs with `uv run python examples/<name>.py` in its `python/` directory, against the Quickstart's `nats-server -js` and engine. The examples' [README](https://github.com/synadia-ai/durable-sdk/blob/main/python/examples/README.md) has each one's command line, and what changes on the fabric (the connection, never the workflow).
127
+
128
+ | Example | Shows |
129
+ | -------------- | -------------------------------------------------------------------------------------------------------------------- |
130
+ | `charge` | `run`, `wait`, `sleep`, `call`; `start`, `signal`, `result`, `status` |
131
+ | `saga` | compensations in reverse on failure |
132
+ | `crash_replay` | a worker killed mid-run; a fresh one resumes without re-running finished steps (run the engine with `--ack-wait 2s`) |
133
+ | `fan_out` | `ctx.start_call` + `asyncio.gather`, and `ctx.race` |
134
+ | `cancel` | `client.cancel` and `ctx.on_cancel` |
135
+
136
+ ## What moved to the engine
137
+
138
+ The worker is the API's loop: one `poll` per concurrency slot; for each item the journal (paged with `load`), the core's `execute_run` with its seams as `append`, `wake` and `child` under the item's lease, `extend` every third of the ack wait, then `done`; every poll names the worker, and `stop()` withdraws its waiting polls (`poll {cancelPoll}`), so a stop takes as long as the items in flight; it returns once every poll has returned, an item one was handed in the instant before handed back (`done retry`), so a process may exit right after it. Stop the worker in a `finally`, as the examples do: a process that exits on an error without `stop()` leaves its polls to the engine for their wait, and an item handed to one waits out its ack wait. A value too large for one request goes up in `put` parts and travels as a ref; a ref the engine hands back, for a value too large for a reply, comes down in `get` parts, its digest checked. Everything else is the engine's: the consumers, provisioning, the inbound event, the run lease, the ack matrix, `child-done`, the cascade of a cancel, the forward across continue-as-new, the parked index and the lost-wake repair, the maintenance pass, offload.
139
+
140
+ So `create_worker` takes `nc`, `workflows`, `prefix`, `dependencies`, `concurrency` (default 16 poll slots), `poll_wait_ms` (default 30 000), `logger`, `metrics` and `payload_codec`. Older options are accepted and ignored, each named for the `serve` flag it became: `ack_wait_ms` → `--ack-wait`, `max_work_ms` → `--max-work`, `lease=False` → `--no-lease`, `lease_ttl_ms` → `--lease-ttl`, `stream_max_bytes` → `--stream-max-bytes`, `maintenance_interval_ms` → `--maintenance-interval`, `reconcile_grace_ms` → `--reconcile-grace`, and `offload`'s threshold → `--offload-threshold`; `offload=False` keeps its meaning (nothing goes up in parts, a value too large for a request fails loud). `create_client` takes `nc`, `prefix`, `payload_codec`, `logger`, `metrics` (`blob.put`, `blob.get`) and `offload=False`.
141
+
142
+ ### Errors
143
+
144
+ A refusal from the engine is a typed error, one per code of the engine's closed set (the engine's `API.md`, the document shipped with the engine, "Errors"; mirrored as `ENGINE_ERROR_CODES` in `synadia_durable._engine.errors`, and in the TypeScript SDK):
145
+
146
+ | `code` | Error | What the SDK does with it |
147
+ | ------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
148
+ | `invalid` | `InvalidRequestError` (inside an execution `SerializationError`) | never retried; inside an execution the run fails |
149
+ | `fenced` | `FencedError` (`EngineFencedError`, with `expect_last_seq` and `server_code`) | the pure core's halt |
150
+ | `expired` | `LeaseExpiredError` | the worker drops the item; it redelivers |
151
+ | `not_found` | `RunNotFoundError` (also a `LookupError`) | raised to the caller |
152
+ | `too_large` | `PayloadTooLargeError` | deterministic: raised, or the run fails |
153
+ | `blob_gone` | `BlobMissingError` / `BlobIntegrityError` | the worker parks the run, loud (`done retry`) |
154
+ | `unavailable`, `internal` | `EngineUnavailableError` (also no responders, a timeout) | transient: `result()` asks again, inside an execution `done retry`; `internal` is logged at error |
155
+ | `tenant_limit` | `LimitError` (`code`, `limit`: `bytes`, `runs`, `workflows`, `polls`, `rate`) | **a refusal, never retried**: a client's call raises it; `worker.start()` raises it when its first poll is refused (`rate` aside); a refused poll is logged at error naming the limit and polled again after 30 s (`rate`: 1 s) |
156
+ | `licence_limit` | `LimitError` (`limit`: `workflows`, `workers`, `runs`, `runsPerDay`, `tenants`, `expired`) | the same; inside an execution (a `child` at `runs`, an `append` at `bytes`) the item goes back (`done retry`), logged at error |
157
+
158
+ A closed connection is `ConnectionClosedError`. An engine older than this SDK's floor (no `withdrawn-remembered` in `info.capabilities`) is `UnsupportedEngineError` (`code` `unsupported`, this SDK's, with `engine`, `commit`, `capabilities`, `missing`), never retried (Which engine, in the Quickstart). A code the SDK does not know (an engine newer than it) stays `EngineUnavailableError`, logged at warn. A worker whose polls fail (no engine, a slow link) says `poll failed; retrying` once a minute, with the count of failures since.
159
+
160
+ **Sizes:** a value of any size the blob store holds; one larger than a request (`request_max`, about `max_payload` − 16 KiB) takes a `put` round trip per part of about 6 MiB on an 8 MiB server. After `result()`, `status()` can read the previous state for a round trip of the worker's.
161
+
162
+ ## Running a worker
163
+
164
+ The user's half of running it; the engine's operator has the other.
165
+
166
+ | Concern | What to do | Mechanism |
167
+ | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
168
+ | the connection | connect with `nats.connect(url, **with_reconnect_defaults())` | nats-py gives up after 60 reconnect attempts (~2 min) and closes the connection for good; the helper sets the limit to −1 and never overrides an option you set |
169
+ | a connection closed for good | restart the process; point a readiness probe at `worker.health()` | a waiting `result()` raises `ConnectionClosedError` (the run is unaffected); the worker reports `running=False`, `connection_closed=True` |
170
+ | no engine, or a slow link | nothing | `worker.start()` warns `no engine answered info; polling until one does`, and the first answered poll checks the engine's floor; a failing poll says `poll failed; retrying` once a minute with a count |
171
+ | a crash mid-step | make a step's effect idempotent, keyed by `ctx.key()` | a finished step is journaled and never re-run; a step in flight runs again on the next worker (at-least-once) |
172
+ | a step longer than the ack wait | nothing, up to the engine's `--max-work` (5 min by default) | the worker `extend`s the lease every third of the ack wait; past `--max-work` the item redelivers. Raising it is the engine operator's flag |
173
+ | how soon a dead worker's run moves | the engine's `--ack-wait` (30 s by default) | the item redelivers once the lease lapses |
174
+ | plaintext values in the journal | `payload_codec=aes_gcm_payload_codec(key)` on **every** worker and client of the prefix (32 bytes, from your secret store; `pip install 'synadia-durable[crypto]'`) | it transforms the payload slot only; the engine and the console see a run's shape and never a value. Not retroactive, one-way in practice, and the key's rotation is yours (the engine's protocol specification) |
175
+ | who may start, signal or cancel | the account's authorization (standalone), or your tenant's users ([on the fabric](https://github.com/synadia-ai/durable-sdk/blob/main/docs/FABRIC.md#standalone-and-the-fabric)) | every call is a request on `{prefix}.api.v1.<op>` |
176
+
177
+ ## Contributing
178
+
179
+ How the SDK works with the engine, the test suites in both languages, the harness's modes and the interop worker: the repository's [`docs/DEVELOPING.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/DEVELOPING.md).
@@ -0,0 +1,151 @@
1
+ # `synadia-durable` (Python)
2
+
3
+ Durable execution for Python on NATS. Workflows are ordinary async functions over a `ctx`: every step is journaled, and after a crash a run resumes where it was, without repeating finished steps. Your workflow code runs in your process. The journal, the timers and the work queue are kept by **durable-engine**, which Synadia ships to you, or which the Synadia Agent Fabric runs for you.
4
+
5
+ ```sh
6
+ pip install synadia-durable # or: uv add synadia-durable
7
+ ```
8
+
9
+ This is the thin durable execution SDK for Python, the twin of the TypeScript SDK (`@synadia-ai/durable` on npm); both live in the [durable-sdk repository](https://github.com/synadia-ai/durable-sdk). Its replay core, with the determinism guards and the out-of-band halts, runs in your process. Behind the core's seams sits a request/reply client for the engine, which owns the streams: nothing runs without the engine.
10
+
11
+ **It runs in two places, with the same code:**
12
+
13
+ | Where | The engine | Start here |
14
+ | ------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
15
+ | **standalone** | yours, next to your NATS, with a licence | the Quickstart below |
16
+ | **on the Synadia Agent Fabric** | the fabric runs it; your account reaches it through an import | [`docs/FABRIC.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/FABRIC.md) |
17
+
18
+ - **The public API:** `@workflow` / `define_workflow`, `create_client`, `create_worker`, and `ctx.run/sleep/wait/call/start_call/race/now/random/uuid/key/continue_as_new/on_cancel`.
19
+ - **The only dependency is `nats-py`**, used for core request/reply alone: every call is one request to `{prefix}.api.v1.<op>` (the engine's `API.md`, the document delivered with the engine). There are no consumers, streams or buckets here, and no JetStream client. `cryptography` is the optional `crypto` extra, for `aes_gcm_payload_codec` (`pip install 'synadia-durable[crypto]'`).
20
+ - **Documentation** is this README, [`docs/FABRIC.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/FABRIC.md) (on the fabric), the [examples](https://github.com/synadia-ai/durable-sdk/blob/main/python/examples/README.md) and [`docs/DEVELOPING.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/DEVELOPING.md) (the test suites). The engine's operator has the documents shipped with the engine, `QUICKSTART.md` and `API.md`.
21
+
22
+ **Version:** `0.2.0`, the TypeScript SDK's twin.
23
+
24
+ ## Quickstart
25
+
26
+ A workflow on your laptop: NATS with JetStream, the engine next to it, and a workflow in a project of your own. You need `nats-server` ≥ 2.14 on `PATH`, Python ≥ 3.11 with [`uv`](https://docs.astral.sh/uv/), and from Synadia **the engine for your platform** (the archive `durable-engine_<version>_<os>_<arch>.tar.gz`, or the container image) and **a licence file**. On the Synadia Agent Fabric you need neither: the engine is already there ([`docs/FABRIC.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/FABRIC.md)).
27
+
28
+ ```sh
29
+ nats-server -js & # 1. NATS with JetStream, on 127.0.0.1:4222
30
+ tar xzf durable-engine_<version>_<os>_<arch>.tar.gz # 2. the engine Synadia sent you
31
+ ./durable-engine_<version>_<os>_<arch>/durable-engine serve \
32
+ --nats nats://127.0.0.1:4222 --licence durable.licence & # 3. the engine, with your licence
33
+ uv init --bare order && cd order && uv add synadia-durable # 4. a project of your own
34
+ NATS_URL=nats://127.0.0.1:4222 uv run python order.py # 5. the file below
35
+ ```
36
+
37
+ With pip instead of uv, step 4 is `mkdir order && cd order && python3 -m venv .venv && .venv/bin/pip install synadia-durable`, and step 5 runs `.venv/bin/python order.py`.
38
+
39
+ `order.py`:
40
+
41
+ ```python
42
+ import asyncio
43
+ import os
44
+
45
+ import nats
46
+
47
+ from synadia_durable import Ctx, create_client, create_worker, with_reconnect_defaults, workflow
48
+
49
+
50
+ @workflow(name="order")
51
+ async def order(ctx: Ctx, cart: dict) -> dict:
52
+ order_id = await ctx.run("reserve", lambda: f"ord-{cart['cartId']}") # journaled, never re-run
53
+ payment = await ctx.wait("payment") # parks until a signal
54
+ if not payment["approved"]:
55
+ return {"status": "abandoned", "orderId": order_id}
56
+ await ctx.sleep("settle", 500) # a durable timer
57
+ return {"status": "paid", "orderId": order_id}
58
+
59
+
60
+ async def main() -> None:
61
+ nc = await nats.connect(
62
+ os.environ.get("NATS_URL", "nats://127.0.0.1:4222"), **with_reconnect_defaults()
63
+ )
64
+ worker = create_worker(nc, [order])
65
+ try:
66
+ await worker.start()
67
+ client = create_client(nc)
68
+ handle = await client.start(order, {"cartId": "c-42"})
69
+ await client.signal(handle.run_id, "payment", {"approved": True})
70
+ print(await handle.result(20_000)) # {'status': 'paid', 'orderId': 'ord-c-42'}
71
+ finally:
72
+ await worker.stop() # on any error too: its polls withdrawn, their items handed back
73
+ await nc.drain()
74
+
75
+
76
+ asyncio.run(main())
77
+ ```
78
+
79
+ It prints `{'status': 'paid', 'orderId': 'ord-c-42'}`. The engine logs `licence … licensee=<you>` and `serving` at start; it creates its streams and buckets on the first start and answers on `de.api.v1.*` (`nats req de.api.v1.info '{}'` shows it, with the `nats` CLI). Without a valid licence it exits at once and says why. Stop the engine and the server with `kill %2 %1`.
80
+
81
+ **With the container image** instead of the archive, step 3 is `docker run --rm --network host -v $PWD/durable.licence:/etc/durable-engine/licence:ro durable-engine:<version>` (on Docker Desktop add `--nats nats://host.docker.internal:4222` and drop `--network host`).
82
+
83
+ **Which engine:** this SDK needs an engine that announces `withdrawn-remembered` in `info.capabilities` (a worker withdrawn by `stop()` is remembered 5 s, so `stop()` sends one `cancelPoll`); the repository's `engine.pin` names the engine version the suites were last run against. `worker.start()` raises `UnsupportedEngineError` on an older one, naming the engine by its `engine` and `commit` as `info` gives them; a worker whose start found no engine checks at its first answered poll and stops there, logged at error (`health()` says stopped). The floor is read from `info.capabilities`, never from the version: every build so far says `0.2.0-dev`.
84
+
85
+ **A signal's id.** Every `client.signal` carries an id, a generated UUID unless you pass your own: `await client.signal(run_id, "payment", data, id="pay-c-42")` (`[A-Za-z0-9_-]+`, checked before any request). A retry passes the same id: if you send a signal again after an `EngineUnavailableError`, a timeout, or a restart of your own process, pass the id of the first try, and the engine answers `ok` and journals nothing more. Without an id each call is a new signal. The id is looked for in two journals only: the run the request names and the generation current when the request arrives. A signal journaled in any other generation (one that was current at the first try and has continued since) is not recognised, and is journaled again. The id dedups one signal: two signals with the same name and different ids are two signals.
86
+
87
+ ### Installing
88
+
89
+ ```sh
90
+ pip install synadia-durable # or: uv add synadia-durable
91
+ pip install 'synadia-durable[crypto]' # with aes_gcm_payload_codec, for encryption at rest
92
+ ```
93
+
94
+ `nats-py` comes with it; a creds file needs `nkeys` beside it (`pip install 'nats-py[nkeys]'`).
95
+
96
+ ## The examples
97
+
98
+ From a clone of the repository, each runs with `uv run python examples/<name>.py` in its `python/` directory, against the Quickstart's `nats-server -js` and engine. The examples' [README](https://github.com/synadia-ai/durable-sdk/blob/main/python/examples/README.md) has each one's command line, and what changes on the fabric (the connection, never the workflow).
99
+
100
+ | Example | Shows |
101
+ | -------------- | -------------------------------------------------------------------------------------------------------------------- |
102
+ | `charge` | `run`, `wait`, `sleep`, `call`; `start`, `signal`, `result`, `status` |
103
+ | `saga` | compensations in reverse on failure |
104
+ | `crash_replay` | a worker killed mid-run; a fresh one resumes without re-running finished steps (run the engine with `--ack-wait 2s`) |
105
+ | `fan_out` | `ctx.start_call` + `asyncio.gather`, and `ctx.race` |
106
+ | `cancel` | `client.cancel` and `ctx.on_cancel` |
107
+
108
+ ## What moved to the engine
109
+
110
+ The worker is the API's loop: one `poll` per concurrency slot; for each item the journal (paged with `load`), the core's `execute_run` with its seams as `append`, `wake` and `child` under the item's lease, `extend` every third of the ack wait, then `done`; every poll names the worker, and `stop()` withdraws its waiting polls (`poll {cancelPoll}`), so a stop takes as long as the items in flight; it returns once every poll has returned, an item one was handed in the instant before handed back (`done retry`), so a process may exit right after it. Stop the worker in a `finally`, as the examples do: a process that exits on an error without `stop()` leaves its polls to the engine for their wait, and an item handed to one waits out its ack wait. A value too large for one request goes up in `put` parts and travels as a ref; a ref the engine hands back, for a value too large for a reply, comes down in `get` parts, its digest checked. Everything else is the engine's: the consumers, provisioning, the inbound event, the run lease, the ack matrix, `child-done`, the cascade of a cancel, the forward across continue-as-new, the parked index and the lost-wake repair, the maintenance pass, offload.
111
+
112
+ So `create_worker` takes `nc`, `workflows`, `prefix`, `dependencies`, `concurrency` (default 16 poll slots), `poll_wait_ms` (default 30 000), `logger`, `metrics` and `payload_codec`. Older options are accepted and ignored, each named for the `serve` flag it became: `ack_wait_ms` → `--ack-wait`, `max_work_ms` → `--max-work`, `lease=False` → `--no-lease`, `lease_ttl_ms` → `--lease-ttl`, `stream_max_bytes` → `--stream-max-bytes`, `maintenance_interval_ms` → `--maintenance-interval`, `reconcile_grace_ms` → `--reconcile-grace`, and `offload`'s threshold → `--offload-threshold`; `offload=False` keeps its meaning (nothing goes up in parts, a value too large for a request fails loud). `create_client` takes `nc`, `prefix`, `payload_codec`, `logger`, `metrics` (`blob.put`, `blob.get`) and `offload=False`.
113
+
114
+ ### Errors
115
+
116
+ A refusal from the engine is a typed error, one per code of the engine's closed set (the engine's `API.md`, the document shipped with the engine, "Errors"; mirrored as `ENGINE_ERROR_CODES` in `synadia_durable._engine.errors`, and in the TypeScript SDK):
117
+
118
+ | `code` | Error | What the SDK does with it |
119
+ | ------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
120
+ | `invalid` | `InvalidRequestError` (inside an execution `SerializationError`) | never retried; inside an execution the run fails |
121
+ | `fenced` | `FencedError` (`EngineFencedError`, with `expect_last_seq` and `server_code`) | the pure core's halt |
122
+ | `expired` | `LeaseExpiredError` | the worker drops the item; it redelivers |
123
+ | `not_found` | `RunNotFoundError` (also a `LookupError`) | raised to the caller |
124
+ | `too_large` | `PayloadTooLargeError` | deterministic: raised, or the run fails |
125
+ | `blob_gone` | `BlobMissingError` / `BlobIntegrityError` | the worker parks the run, loud (`done retry`) |
126
+ | `unavailable`, `internal` | `EngineUnavailableError` (also no responders, a timeout) | transient: `result()` asks again, inside an execution `done retry`; `internal` is logged at error |
127
+ | `tenant_limit` | `LimitError` (`code`, `limit`: `bytes`, `runs`, `workflows`, `polls`, `rate`) | **a refusal, never retried**: a client's call raises it; `worker.start()` raises it when its first poll is refused (`rate` aside); a refused poll is logged at error naming the limit and polled again after 30 s (`rate`: 1 s) |
128
+ | `licence_limit` | `LimitError` (`limit`: `workflows`, `workers`, `runs`, `runsPerDay`, `tenants`, `expired`) | the same; inside an execution (a `child` at `runs`, an `append` at `bytes`) the item goes back (`done retry`), logged at error |
129
+
130
+ A closed connection is `ConnectionClosedError`. An engine older than this SDK's floor (no `withdrawn-remembered` in `info.capabilities`) is `UnsupportedEngineError` (`code` `unsupported`, this SDK's, with `engine`, `commit`, `capabilities`, `missing`), never retried (Which engine, in the Quickstart). A code the SDK does not know (an engine newer than it) stays `EngineUnavailableError`, logged at warn. A worker whose polls fail (no engine, a slow link) says `poll failed; retrying` once a minute, with the count of failures since.
131
+
132
+ **Sizes:** a value of any size the blob store holds; one larger than a request (`request_max`, about `max_payload` − 16 KiB) takes a `put` round trip per part of about 6 MiB on an 8 MiB server. After `result()`, `status()` can read the previous state for a round trip of the worker's.
133
+
134
+ ## Running a worker
135
+
136
+ The user's half of running it; the engine's operator has the other.
137
+
138
+ | Concern | What to do | Mechanism |
139
+ | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
140
+ | the connection | connect with `nats.connect(url, **with_reconnect_defaults())` | nats-py gives up after 60 reconnect attempts (~2 min) and closes the connection for good; the helper sets the limit to −1 and never overrides an option you set |
141
+ | a connection closed for good | restart the process; point a readiness probe at `worker.health()` | a waiting `result()` raises `ConnectionClosedError` (the run is unaffected); the worker reports `running=False`, `connection_closed=True` |
142
+ | no engine, or a slow link | nothing | `worker.start()` warns `no engine answered info; polling until one does`, and the first answered poll checks the engine's floor; a failing poll says `poll failed; retrying` once a minute with a count |
143
+ | a crash mid-step | make a step's effect idempotent, keyed by `ctx.key()` | a finished step is journaled and never re-run; a step in flight runs again on the next worker (at-least-once) |
144
+ | a step longer than the ack wait | nothing, up to the engine's `--max-work` (5 min by default) | the worker `extend`s the lease every third of the ack wait; past `--max-work` the item redelivers. Raising it is the engine operator's flag |
145
+ | how soon a dead worker's run moves | the engine's `--ack-wait` (30 s by default) | the item redelivers once the lease lapses |
146
+ | plaintext values in the journal | `payload_codec=aes_gcm_payload_codec(key)` on **every** worker and client of the prefix (32 bytes, from your secret store; `pip install 'synadia-durable[crypto]'`) | it transforms the payload slot only; the engine and the console see a run's shape and never a value. Not retroactive, one-way in practice, and the key's rotation is yours (the engine's protocol specification) |
147
+ | who may start, signal or cancel | the account's authorization (standalone), or your tenant's users ([on the fabric](https://github.com/synadia-ai/durable-sdk/blob/main/docs/FABRIC.md#standalone-and-the-fabric)) | every call is a request on `{prefix}.api.v1.<op>` |
148
+
149
+ ## Contributing
150
+
151
+ How the SDK works with the engine, the test suites in both languages, the harness's modes and the interop worker: the repository's [`docs/DEVELOPING.md`](https://github.com/synadia-ai/durable-sdk/blob/main/docs/DEVELOPING.md).