adopt-workflow 0.4.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.
@@ -0,0 +1,42 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .pytest_cache/
6
+ .mypy_cache/
7
+ .ruff_cache/
8
+ .hypothesis/
9
+ build/
10
+ dist/
11
+
12
+ # Environments
13
+ .venv/
14
+ .env
15
+ .env.local
16
+ .env.*
17
+ !.env.example
18
+ *.key
19
+ *.p12
20
+ *.pfx
21
+
22
+ # Local store and scratch
23
+ .adopt/
24
+ /tmp/
25
+
26
+ # Never commit a private-repo artifact into the Apache-2.0 repository.
27
+ # `adopt-plane` is a separate repository (handoff index CR-03) and is never
28
+ # vendored here. If this pattern ever matches something, that is the
29
+ # boundary violation the pattern exists to catch.
30
+ adopt-plane/
31
+ plane_*/
32
+
33
+ # The exported locked runtime closure the release job derives the SBOM from.
34
+ # `release.yml` generates it in an ephemeral checkout, so CI never sees this
35
+ # file; a local release rehearsal does, in the repository root, and a generated
36
+ # artefact one `git add -A` away from the first public commit is worth one line.
37
+ runtime-constraints.txt
38
+
39
+ # CI metrics, written per run and uploaded as an artefact (PRD §6)
40
+ ci-metrics.jsonl
41
+ .coverage
42
+ cov.json
@@ -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 reasonable and customary use in describing the
141
+ origin of the Work and 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 Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or 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 [yyyy] [name of copyright owner]
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 implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,39 @@
1
+ Adopt — Adoption-Phase Platform, shared substrate (`adopt-core`)
2
+ Copyright 2026 The Adopt Authors
3
+
4
+ This product includes software developed by The Adopt Authors.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing, software
13
+ distributed under the License is distributed on an "AS IS" BASIS,
14
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ See the License for the specific language governing permissions and
16
+ limitations under the License.
17
+
18
+ --------------------------------------------------------------------------------
19
+ Attribution note
20
+ --------------------------------------------------------------------------------
21
+
22
+ The copyright holder is recorded here as "The Adopt Authors" pending the legal
23
+ entity name. The owner must settle that attribution before the 0.3.0 tag,
24
+ because published package metadata cannot be changed retroactively for a
25
+ release that has already left the machine. The product name itself is settled:
26
+ handoff-index CR-50 keeps `Adopt` distinct from the `onboard` URI namespace.
27
+
28
+ --------------------------------------------------------------------------------
29
+ Third-party dependencies
30
+ --------------------------------------------------------------------------------
31
+
32
+ Every third-party dependency linked into this distribution is permissively
33
+ licensed. The complete list, with licence hash, security status, usage mode,
34
+ owner and re-verification date, is maintained in `licence-verifications.md` and
35
+ enforced by `scripts/licence_gate.py`.
36
+
37
+ Copyleft-licensed tools are invoked as subprocesses only and are never linked
38
+ into this distribution. They are declared in `subprocess-deps.toml` together
39
+ with their invocation sites.
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.5
2
+ Name: adopt-workflow
3
+ Version: 0.4.0
4
+ Summary: The Workflow facade, the in-process test backend, the purity checker.
5
+ Project-URL: Homepage, https://github.com/onboardux/onboard-core
6
+ Project-URL: Source, https://github.com/onboardux/onboard-core
7
+ Project-URL: Issues, https://github.com/onboardux/onboard-core/issues
8
+ Author: The Adopt Authors
9
+ License-Expression: Apache-2.0
10
+ Requires-Python: >=3.12
11
+ Requires-Dist: adopt-const
12
+ Requires-Dist: adopt-obs
13
+ Requires-Dist: pydantic<3,>=2.7
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "adopt-workflow"
3
+ version = "0.4.0"
4
+ description = "The Workflow facade, the in-process test backend, the purity checker."
5
+ requires-python = ">=3.12"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE", "NOTICE"]
8
+ authors = [{ name = "The Adopt Authors" }]
9
+ # `no-dbos` import contract: no DBOS symbol appears in this package. The only
10
+ # DBOS importer in the programme is `plane_workflow.dbos_backend`, in the closed
11
+ # repository.
12
+ #
13
+ # `no-raw-sqlite` also names this package a source module and follows indirect
14
+ # chains, which is why the in-process backend persists to a file journal rather
15
+ # than to a database -- see `inproc/journal.py`.
16
+ dependencies = [
17
+ "adopt-const",
18
+ "adopt-obs",
19
+ "pydantic>=2.7,<3",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/onboardux/onboard-core"
24
+ Source = "https://github.com/onboardux/onboard-core"
25
+ Issues = "https://github.com/onboardux/onboard-core/issues"
26
+
27
+ [build-system]
28
+ requires = ["hatchling"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/adopt_workflow"]
33
+
34
+ # Apache-2.0 4(a) and 4(d): the licence and the NOTICE travel with every
35
+ # redistribution. `uv build` builds the wheel from the sdist, so placing the
36
+ # repository root's single authored copy here puts it in both artefacts and
37
+ # leaves nothing to drift.
38
+ [tool.hatch.build.targets.sdist.force-include]
39
+ "../../LICENSE" = "LICENSE"
40
+ "../../NOTICE" = "NOTICE"
@@ -0,0 +1,63 @@
1
+ """The Workflow facade, the in-process test backend, the purity checker.
2
+
3
+ Contracts §10.2 · implementation spec §4.14 · PRD F14.
4
+
5
+ Invariants this package carries: **no DBOS symbol appears here** -- the only
6
+ importer in the programme is `plane_workflow.dbos_backend`, in the closed
7
+ repository -- workflow bodies are pure, checked at decoration time by
8
+ `assert_pure` and across the tree by the `workflow-body-purity` contract, and
9
+ **no Build 0 OSS-side command uses durable workflows**, so the OSS CLI never
10
+ requires Postgres.
11
+ """
12
+
13
+ from adopt_workflow.api import (
14
+ TERMINAL_STATUSES,
15
+ Backoff,
16
+ RetryPolicy,
17
+ StepContext,
18
+ WorkflowClient,
19
+ WorkflowContext,
20
+ WorkflowHandle,
21
+ WorkflowStatus,
22
+ backoff_delays_ms,
23
+ validate_idempotency_key,
24
+ )
25
+ from adopt_workflow.decorators import (
26
+ REGISTRY,
27
+ ScheduledDefinition,
28
+ StepDefinition,
29
+ WorkflowDefinition,
30
+ clear_registry,
31
+ resolve,
32
+ scheduled,
33
+ step,
34
+ workflow,
35
+ )
36
+ from adopt_workflow.inproc import InProcessWorkflowClient, Journal
37
+ from adopt_workflow.purity import assert_pure, find_impure_workflow_bodies
38
+
39
+ __all__ = [
40
+ "REGISTRY",
41
+ "TERMINAL_STATUSES",
42
+ "Backoff",
43
+ "InProcessWorkflowClient",
44
+ "Journal",
45
+ "RetryPolicy",
46
+ "ScheduledDefinition",
47
+ "StepContext",
48
+ "StepDefinition",
49
+ "WorkflowClient",
50
+ "WorkflowContext",
51
+ "WorkflowDefinition",
52
+ "WorkflowHandle",
53
+ "WorkflowStatus",
54
+ "assert_pure",
55
+ "backoff_delays_ms",
56
+ "clear_registry",
57
+ "find_impure_workflow_bodies",
58
+ "resolve",
59
+ "scheduled",
60
+ "step",
61
+ "validate_idempotency_key",
62
+ "workflow",
63
+ ]
@@ -0,0 +1,262 @@
1
+ """The `Workflow` facade: contracts §10.2, and nothing a backend can widen.
2
+
3
+ **Why a facade at all.** Implementation spec §1.1 locks DBOS for durable
4
+ execution and source spec §13 requires that the documented Temporal migration
5
+ stay a migration. That is only true if no DBOS symbol appears outside one module,
6
+ which means every caller in the programme talks to the shapes declared here.
7
+ `no-dbos` enforces the second half; this file is the first.
8
+
9
+ **What the seam owns and what a backend owns.** The seam owns the vocabulary --
10
+ status values, the retry policy and its caps, the handle, the two contexts. A
11
+ backend owns *when* things run and *where* they are persisted, and nothing else.
12
+ A backend that could add a status value or lift a retry cap would make the
13
+ facade advisory, and the two backends would then differ in ways only production
14
+ discovers.
15
+
16
+ **`run_id` needs no new prefix.** Contracts §1.1 registers `run_` for "one CLI
17
+ invocation or one unit of work" and §10.2 names every keyed parameter `run_id`.
18
+ A workflow run is one unit of work, so it is a `run_` id -- adding a `wf_` prefix
19
+ would have been a §1.1 change made to avoid reusing the entry that already
20
+ describes this.
21
+ """
22
+
23
+ from collections.abc import Callable, Mapping
24
+ from typing import Any, Final, Literal, Protocol, runtime_checkable
25
+
26
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
27
+
28
+ from adopt_const import (
29
+ IDEMPOTENCY_KEY_MAX_CHARS,
30
+ WORKFLOW_STEP_BACKOFF_BASE_MS,
31
+ WORKFLOW_STEP_BACKOFF_MAX_MS,
32
+ WORKFLOW_STEP_MAX_ATTEMPTS,
33
+ )
34
+ from adopt_obs import AdoptError, ErrorCode
35
+
36
+ __all__ = [
37
+ "TERMINAL_STATUSES",
38
+ "Backoff",
39
+ "RetryPolicy",
40
+ "StepContext",
41
+ "WorkflowClient",
42
+ "WorkflowContext",
43
+ "WorkflowHandle",
44
+ "WorkflowStatus",
45
+ "backoff_delays_ms",
46
+ "validate_idempotency_key",
47
+ ]
48
+
49
+ #: The run lifecycle. `completed`, `failed` and `cancelled` are terminal; the
50
+ #: kill-and-resume drill asserts `completed` after a resume, so a resumed run
51
+ #: must reach the same value a run that never died would.
52
+ WorkflowStatus = Literal["pending", "running", "completed", "failed", "cancelled"]
53
+
54
+ #: A run in one of these states will not change again. Both backends are asked
55
+ #: for this set rather than each deciding which of their states are final.
56
+ TERMINAL_STATUSES: Final[frozenset[str]] = frozenset({"completed", "failed", "cancelled"})
57
+
58
+ #: Contracts §10.2 shows `backoff="exponential"`. `none` exists for a step whose
59
+ #: failure is not worth waiting on; there is deliberately no `linear`, because a
60
+ #: third curve is a third thing to reason about at 3 a.m. for no stated need.
61
+ Backoff = Literal["exponential", "none"]
62
+
63
+
64
+ class RetryPolicy(BaseModel):
65
+ """How many times a step is retried, and how long between attempts.
66
+
67
+ `max_attempts` is **capped**, not defaulted, by `WORKFLOW_STEP_MAX_ATTEMPTS`.
68
+ A caller asking for more is refused rather than silently clamped: a step
69
+ declared with 50 attempts was written against an expectation the platform
70
+ does not meet, and clamping hides that until someone reads a log.
71
+ """
72
+
73
+ model_config = ConfigDict(extra="forbid", frozen=True)
74
+
75
+ max_attempts: int = Field(default=WORKFLOW_STEP_MAX_ATTEMPTS, ge=1)
76
+ backoff: Backoff = "exponential"
77
+ base_ms: int = Field(default=WORKFLOW_STEP_BACKOFF_BASE_MS, ge=0)
78
+ max_ms: int = Field(default=WORKFLOW_STEP_BACKOFF_MAX_MS, ge=0)
79
+
80
+ @field_validator("max_attempts")
81
+ @classmethod
82
+ def _within_cap(cls, value: int) -> int:
83
+ if value > WORKFLOW_STEP_MAX_ATTEMPTS:
84
+ raise ValueError(
85
+ f"max_attempts={value} exceeds WORKFLOW_STEP_MAX_ATTEMPTS="
86
+ f"{WORKFLOW_STEP_MAX_ATTEMPTS}. The cap is the platform's, not the "
87
+ f"step's; raise it in implementation spec §2.2 and adopt_const together."
88
+ )
89
+ return value
90
+
91
+ # A cross-field rule, so it runs after the model is built rather than as a
92
+ # `field_validator` taking `ValidationInfo` -- that parameter is generic in
93
+ # `Any`, and `mypy.ini` sets `disallow_any_decorated`.
94
+ @model_validator(mode="after")
95
+ def _max_not_below_base(self) -> "RetryPolicy":
96
+ if self.max_ms < self.base_ms:
97
+ raise ValueError(
98
+ f"max_ms={self.max_ms} is below base_ms={self.base_ms}, so the first "
99
+ f"delay would already exceed the ceiling and every later one would be "
100
+ f"clamped to it."
101
+ )
102
+ return self
103
+
104
+
105
+ def backoff_delays_ms(policy: RetryPolicy) -> tuple[int, ...]:
106
+ """The delay before each retry, in order. Length is `max_attempts - 1`.
107
+
108
+ A pure function of the policy, so the schedule can be asserted without
109
+ running a workflow and without either backend reproducing it independently.
110
+ There is no jitter: this is a per-run schedule for a single-writer local
111
+ backend and a DBOS queue, not a thundering herd of clients against one
112
+ service. Adding jitter would also make the sequence untestable by equality,
113
+ which is the property that keeps the two backends honest about the cap.
114
+ """
115
+ if policy.backoff == "none":
116
+ return tuple(0 for _ in range(policy.max_attempts - 1))
117
+ delays: list[int] = []
118
+ delay = policy.base_ms
119
+ for _ in range(policy.max_attempts - 1):
120
+ delays.append(min(delay, policy.max_ms))
121
+ delay *= 2
122
+ return tuple(delays)
123
+
124
+
125
+ def validate_idempotency_key(key: str) -> str:
126
+ """Contracts §1.5: opaque, non-empty, at most `IDEMPOTENCY_KEY_MAX_CHARS`.
127
+
128
+ Refused at the seam rather than at a backend, so both backends refuse the
129
+ same keys. A key silently truncated by a column width is two different runs
130
+ that look like a replay of each other.
131
+ """
132
+ if not key:
133
+ raise AdoptError(
134
+ ErrorCode.WORKFLOW_DUPLICATE_START,
135
+ message="an idempotency key is required to start a workflow",
136
+ hint=(
137
+ "Contracts §1.5: every retriable operation takes a key, because "
138
+ "every message is assumed to be delivered twice."
139
+ ),
140
+ )
141
+ if len(key) > IDEMPOTENCY_KEY_MAX_CHARS:
142
+ raise AdoptError(
143
+ ErrorCode.WORKFLOW_DUPLICATE_START,
144
+ message=f"idempotency key is {len(key)} characters, over the "
145
+ f"{IDEMPOTENCY_KEY_MAX_CHARS}-character limit",
146
+ hint="Hash the caller's key rather than truncating it; a truncated key collides.",
147
+ )
148
+ return key
149
+
150
+
151
+ class WorkflowHandle(BaseModel):
152
+ """What `start` returns, and what a replayed `start` returns unchanged."""
153
+
154
+ model_config = ConfigDict(extra="forbid", frozen=True)
155
+
156
+ run_id: str
157
+ name: str
158
+ version: int
159
+ idempotency_key: str
160
+ status: WorkflowStatus
161
+
162
+
163
+ @runtime_checkable
164
+ class StepContext(Protocol):
165
+ """Contracts §10.2, verbatim: `run_id`, `attempt`, and `dedupe`."""
166
+
167
+ run_id: str
168
+ attempt: int
169
+
170
+ def dedupe(self, key: str) -> bool:
171
+ """`True` when this is the first commit for `key`; `False` on a replay.
172
+
173
+ The exactly-once boundary. Steps run at least once, so the effect and
174
+ its dedupe record must commit **together** -- a backend that writes the
175
+ record after the effect has a window in which a crash duplicates the
176
+ effect, and that window is exactly what the durability drill opens.
177
+ """
178
+ ...
179
+
180
+
181
+ @runtime_checkable
182
+ class WorkflowContext(Protocol):
183
+ """What a workflow body is handed.
184
+
185
+ Deliberately tiny. Everything non-deterministic reaches the body through
186
+ `step`, because a body is **replayed**: on resume the engine re-executes it
187
+ and expects the same decisions. `workflow-body-purity` enforces the
188
+ negative half of that at lint and import time; this Protocol is the positive
189
+ half -- the only door out of a body.
190
+ """
191
+
192
+ run_id: str
193
+
194
+ def step(self, fn: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Any:
195
+ """Execute `fn` as a durable step, or replay its recorded result."""
196
+ ...
197
+
198
+
199
+ @runtime_checkable
200
+ class WorkflowClient(Protocol):
201
+ """Contracts §10.2, plus `list` *(CR-42)*.
202
+
203
+ `list` is named by PRD F14.1 and omitted from §10.2's Protocol, and
204
+ implementation spec §7.4's rollback surface needs it: flipping
205
+ `ADOPT_FEATURE_DBOS_BACKEND` off requires in-flight runs to drain first, and
206
+ "drain" is unobservable without a way to enumerate them.
207
+ """
208
+
209
+ def start(
210
+ self,
211
+ fn: Callable[..., Any],
212
+ args: Mapping[str, Any],
213
+ *,
214
+ idempotency_key: str,
215
+ ) -> WorkflowHandle: ...
216
+
217
+ def signal(self, run_id: str, name: str, payload: Mapping[str, Any]) -> None: ...
218
+
219
+ def status(self, run_id: str) -> WorkflowStatus: ...
220
+
221
+ def result(self, run_id: str, *, timeout_s: int) -> Any: ...
222
+
223
+ def cancel(self, run_id: str) -> None: ...
224
+
225
+ def close(self) -> None:
226
+ """Stop executing work and release what the client holds *(CR-43)*.
227
+
228
+ **A backend that can start workers must be able to stop them**, and
229
+ §10.2 declared no way to. That is not a test convenience: implementation
230
+ spec §7.4's rollback flips `ADOPT_FEATURE_DBOS_BACKEND` off after
231
+ in-flight runs drain, and "drained" followed by a process that is still
232
+ dequeuing is not drained.
233
+
234
+ The durability drill is where the omission became visible. Its parent
235
+ process holds a client across three tests while each test spawns a child
236
+ that is meant to be the *only* executor -- and a queue is shared by every
237
+ worker pointed at it, so the parent silently dequeued the child's run and
238
+ executed it in the wrong process. That is DBOS behaving correctly and the
239
+ seam giving the caller no way to say "I am no longer a worker".
240
+
241
+ Closing is **idempotent** and does not cancel or roll back running
242
+ work: durable runs outlive the client by design, and the next process to
243
+ recover them picks them up. A backend holding nothing may do nothing.
244
+ """
245
+ ...
246
+
247
+ def recover(self) -> list[WorkflowHandle]:
248
+ """Re-drive every non-terminal run; return what was resumed.
249
+
250
+ Also CR-42. Implementation spec §4.14 says a crash between two step
251
+ records "replays the step", which presumes an entry point where the
252
+ replay begins -- DBOS reaches it at launch, and the in-process backend
253
+ has to be told. Declaring it here is what lets **one** durability suite
254
+ drive both: a drill that called `recover()` on one backend and relied on
255
+ a constructor side effect on the other would be two drills wearing one
256
+ name.
257
+ """
258
+ ...
259
+
260
+ # `list` is declared last: it shadows the builtin for every annotation after
261
+ # it in the class body, and the contract fixes the method name.
262
+ def list(self, *, status: WorkflowStatus | None = None) -> list[WorkflowHandle]: ...