adopt-workflow 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ ]
adopt_workflow/api.py ADDED
@@ -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]: ...
@@ -0,0 +1,176 @@
1
+ """`@workflow`, `@step`, `@scheduled` -- contracts §10.2 and PRD F14.
2
+
3
+ **Registration, not execution.** A decorator here records what a function *is*
4
+ and validates that it may be one. Running it is a backend's job, and keeping the
5
+ two apart is what lets one suite run against both backends: the registry is
6
+ shared, so `inproc` and DBOS are handed identical definitions.
7
+
8
+ **`@workflow` refuses an impure body at import time.** PRD F14.4 requires the
9
+ purity check "at import time", and this is where import time happens. The
10
+ alternative -- checking on the first run -- means the failure appears in whatever
11
+ environment first executes the workflow, which is usually production, and the
12
+ symptom there is a divergent replay rather than an error naming the line.
13
+
14
+ **`@scheduled` is not a workflow, and that is the point.** PRD F14.5 says
15
+ periodic single-step work uses cron rather than a workflow, and calls registering
16
+ one as the other "a review rejection". A review line catches it when someone
17
+ reads carefully; this decorator catches it always -- `@scheduled` refuses to
18
+ decorate a `@workflow`, so the rejection is mechanical and does not depend on the
19
+ reviewer having F14.5 in mind.
20
+ """
21
+
22
+ from collections.abc import Callable
23
+ from dataclasses import dataclass
24
+ from typing import Any, Final, TypeVar
25
+
26
+ from adopt_obs import AdoptError, ErrorCode
27
+ from adopt_workflow.api import RetryPolicy
28
+ from adopt_workflow.purity import assert_pure
29
+
30
+ __all__ = [
31
+ "REGISTRY",
32
+ "ScheduledDefinition",
33
+ "StepDefinition",
34
+ "WorkflowDefinition",
35
+ "clear_registry",
36
+ "resolve",
37
+ "scheduled",
38
+ "step",
39
+ "workflow",
40
+ ]
41
+
42
+ F = TypeVar("F", bound=Callable[..., Any])
43
+
44
+ #: Marks set on the decorated function. Read by the backends and by `@scheduled`
45
+ #: when it refuses a workflow; kept as dunder-free attributes so a definition is
46
+ #: inspectable from a test without reaching into a private registry.
47
+ WORKFLOW_ATTR: Final[str] = "__adopt_workflow__"
48
+ STEP_ATTR: Final[str] = "__adopt_step__"
49
+ SCHEDULED_ATTR: Final[str] = "__adopt_scheduled__"
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class WorkflowDefinition:
54
+ """What `@workflow` records. `(name, version)` is the identity."""
55
+
56
+ name: str
57
+ version: int
58
+ fn: Callable[..., Any]
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class StepDefinition:
63
+ """What `@step` records, including the policy its retries are capped by."""
64
+
65
+ name: str
66
+ retries: RetryPolicy
67
+ fn: Callable[..., Any]
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class ScheduledDefinition:
72
+ """A periodic single-step job. Cron, deliberately not a workflow."""
73
+
74
+ name: str
75
+ cron: str
76
+ fn: Callable[..., Any]
77
+
78
+
79
+ #: One registry for the programme, keyed by `(kind, name, version)`.
80
+ #:
81
+ #: A backend resolves a definition from here rather than from a closure, which is
82
+ #: what makes a resumed run able to find the body it was executing: after a
83
+ #: process death there is no closure left, only a name in a journal.
84
+ REGISTRY: Final[dict[tuple[str, str, int], object]] = {}
85
+
86
+
87
+ def clear_registry() -> None:
88
+ """Empty the registry. For tests that declare throwaway workflows."""
89
+ REGISTRY.clear()
90
+
91
+
92
+ def resolve(kind: str, name: str, version: int = 1) -> Any:
93
+ """The definition registered under `(kind, name, version)`.
94
+
95
+ Raises rather than returning `None`: a resumed run that cannot find its body
96
+ must fail loudly, because the alternative is a run that silently never
97
+ completes and a queue that never drains.
98
+ """
99
+ key = (kind, name, version)
100
+ if key not in REGISTRY:
101
+ known = ", ".join(sorted(f"{k[0]}:{k[1]}@{k[2]}" for k in REGISTRY))
102
+ raise AdoptError(
103
+ ErrorCode.WORKFLOW_STEP_EXHAUSTED,
104
+ message=f"no {kind} registered as {name!r} version {version}",
105
+ hint=(
106
+ f"A resumed run resolves its body by name; the module declaring it "
107
+ f"must be imported before the backend starts. Registered: {known or 'none'}"
108
+ ),
109
+ )
110
+ return REGISTRY[key]
111
+
112
+
113
+ def workflow(*, name: str, version: int = 1) -> Callable[[F], F]:
114
+ """Register a deterministic, replayable workflow body.
115
+
116
+ The body is checked for purity **now**, at decoration time.
117
+ """
118
+
119
+ def decorate(fn: F) -> F:
120
+ assert_pure(fn)
121
+ definition = WorkflowDefinition(name=name, version=version, fn=fn)
122
+ key = ("workflow", name, version)
123
+ if key in REGISTRY:
124
+ raise AdoptError(
125
+ ErrorCode.WORKFLOW_DUPLICATE_START,
126
+ message=f"a workflow named {name!r} version {version} is already registered",
127
+ hint=(
128
+ "`(name, version)` is the identity a resumed run resolves through. "
129
+ "Two bodies under one key means a resume can execute the wrong one."
130
+ ),
131
+ )
132
+ REGISTRY[key] = definition
133
+ setattr(fn, WORKFLOW_ATTR, definition)
134
+ return fn
135
+
136
+ return decorate
137
+
138
+
139
+ def step(*, name: str, retries: RetryPolicy | None = None) -> Callable[[F], F]:
140
+ """Register a step: the only place non-deterministic work may live."""
141
+
142
+ def decorate(fn: F) -> F:
143
+ definition = StepDefinition(name=name, retries=retries or RetryPolicy(), fn=fn)
144
+ REGISTRY[("step", name, 1)] = definition
145
+ setattr(fn, STEP_ATTR, definition)
146
+ return fn
147
+
148
+ return decorate
149
+
150
+
151
+ def scheduled(*, name: str, cron: str) -> Callable[[F], F]:
152
+ """Register periodic single-step work. **Not** a workflow -- PRD F14.5.
153
+
154
+ Refuses to decorate a function that is already a workflow. The durable
155
+ machinery exists for work that must survive a crash mid-sequence; a single
156
+ step that runs every hour survives by running again next hour, and putting it
157
+ on the engine buys retention, replay and a queue nobody needed.
158
+ """
159
+
160
+ def decorate(fn: F) -> F:
161
+ if hasattr(fn, WORKFLOW_ATTR):
162
+ raise AdoptError(
163
+ ErrorCode.WORKFLOW_BODY_IMPURE,
164
+ message=f"{name!r} is registered as both a workflow and a scheduled job",
165
+ hint=(
166
+ "PRD F14.5: periodic single-step work uses cron, not a workflow. "
167
+ "If the job really is a multi-step sequence that must survive a "
168
+ "crash halfway, drop @scheduled and start it from cron instead."
169
+ ),
170
+ )
171
+ definition = ScheduledDefinition(name=name, cron=cron, fn=fn)
172
+ REGISTRY[("scheduled", name, 1)] = definition
173
+ setattr(fn, SCHEDULED_ATTR, definition)
174
+ return fn
175
+
176
+ return decorate
@@ -0,0 +1,6 @@
1
+ """The in-process backend: no external dependency, for CI and local dev."""
2
+
3
+ from adopt_workflow.inproc.client import InProcessStepContext, InProcessWorkflowClient
4
+ from adopt_workflow.inproc.journal import Journal
5
+
6
+ __all__ = ["InProcessStepContext", "InProcessWorkflowClient", "Journal"]