cauli 0.2.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.
cauli/__init__.py ADDED
@@ -0,0 +1,42 @@
1
+ """cauli: Python client for the cauli Rust background worker runtime.
2
+
3
+ Define tasks with ``@app.task(...)``, enqueue with ``.delay()`` /
4
+ ``.apply_async()``, read results with ``AsyncResult``. The heavy lifting
5
+ (execution, retries, timeouts) happens in the Rust ``cauli-worker`` process.
6
+ See PROTOCOL.md for the full wire contract.
7
+ """
8
+
9
+ from cauli._context import TaskContext, current_task
10
+ from cauli.app import AsyncCauli, Cauli
11
+ from cauli.exceptions import Retry, SoftTimeLimitExceeded, TaskFailedError
12
+ from cauli.result import AsyncResult
13
+ from cauli.schedules import (
14
+ CrontabSchedule,
15
+ IntervalSchedule,
16
+ Schedule,
17
+ ScheduleEntry,
18
+ crontab,
19
+ interval,
20
+ )
21
+ from cauli.task import TaskDef
22
+
23
+ __version__ = "0.2.0"
24
+
25
+ __all__ = [
26
+ "Cauli",
27
+ "AsyncCauli",
28
+ "Retry",
29
+ "SoftTimeLimitExceeded",
30
+ "TaskFailedError",
31
+ "AsyncResult",
32
+ "TaskDef",
33
+ "TaskContext",
34
+ "current_task",
35
+ "Schedule",
36
+ "ScheduleEntry",
37
+ "IntervalSchedule",
38
+ "CrontabSchedule",
39
+ "crontab",
40
+ "interval",
41
+ "__version__",
42
+ ]
cauli/_broker.py ADDED
@@ -0,0 +1,296 @@
1
+ """RabbitMQ and SQS publishers for the ready queue (PROTOCOL.md section 14).
2
+
3
+ Redis stays the store for results, delayed tasks, idempotency claims and beat.
4
+ Only an enqueue that is due now goes to the broker, and a publish is at least
5
+ once: a connection lost mid publish is retried and can deliver twice.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import threading
12
+ from typing import Any, Sequence
13
+ from urllib.parse import unquote, urlsplit
14
+
15
+ #: Seconds for a connect, a publish and its confirm; the worker's
16
+ #: ``--redis-timeout`` default.
17
+ PUBLISH_TIMEOUT = 5
18
+ #: Declared by every producer and worker, so both sides must send the same.
19
+ AMQP_QUEUE_ARGUMENTS = {"x-queue-type": "quorum"}
20
+ #: SendMessageBatch limits: entries per call, and bytes over the whole call.
21
+ SQS_BATCH_ENTRIES = 10
22
+ SQS_BATCH_BYTES = 1_048_576
23
+ SQS_QUEUE_NAME_MAX = 80
24
+
25
+ _SCHEMES = ("amqp", "amqps", "sqs")
26
+
27
+
28
+ def amqp_queue_name(queue: str) -> str:
29
+ return f"cauli.q.{queue}"
30
+
31
+
32
+ def sqs_queue_name(queue: str) -> str:
33
+ name = f"cauli-{queue}"
34
+ if "." in queue or len(name) > SQS_QUEUE_NAME_MAX:
35
+ raise ValueError(
36
+ f"queue {queue!r} cannot be an SQS queue: SQS names allow letters, "
37
+ f"digits, '-' and '_' only, and {name!r} must fit in "
38
+ f"{SQS_QUEUE_NAME_MAX} characters"
39
+ )
40
+ return name
41
+
42
+
43
+ def check_url(url: str) -> None:
44
+ """Raise ValueError for a broker URL no publisher here can open."""
45
+ parts = urlsplit(url)
46
+ if parts.scheme not in _SCHEMES:
47
+ raise ValueError(
48
+ f"broker_url scheme {parts.scheme!r} is not supported: use amqp://, "
49
+ "amqps:// or sqs://. Redis is the broker when broker_url is unset "
50
+ "(configure it with redis_url)"
51
+ )
52
+ if parts.scheme == "sqs" and (
53
+ parts.username or parts.password or parts.path.strip("/")
54
+ ):
55
+ raise ValueError(
56
+ "an sqs:// broker_url is sqs:// or sqs://<region> and nothing else. "
57
+ "Credentials come from the AWS credential chain (environment, "
58
+ "profile, instance or task role), never from the URL"
59
+ )
60
+
61
+
62
+ def open_broker(url: str) -> "AmqpBroker | SqsBroker":
63
+ check_url(url)
64
+ return SqsBroker(url) if url.startswith("sqs:") else AmqpBroker(url)
65
+
66
+
67
+ def redact_url(url: str) -> str:
68
+ """The URL without its userinfo, for logs and repr."""
69
+ parts = urlsplit(url)
70
+ if parts.username is None:
71
+ return url
72
+ host = parts.hostname or ""
73
+ port = f":{parts.port}" if parts.port else ""
74
+ return f"{parts.scheme}://***@{host}{port}{parts.path}"
75
+
76
+
77
+ class AmqpBroker:
78
+ """Confirmed, persistent publishes to quorum queues over one connection.
79
+
80
+ A batch is written first and its confirms read after, which is what makes
81
+ a large ``enqueue_many`` cost one round of fsyncs instead of one each.
82
+ py-amqp connections are not thread safe, so a lock serializes publishers.
83
+ A forked child opens its own connection: the inherited socket is the
84
+ parent's.
85
+ """
86
+
87
+ def __init__(self, url: str) -> None:
88
+ parts = urlsplit(url)
89
+ self._tls = parts.scheme == "amqps"
90
+ self._host = parts.hostname or "localhost"
91
+ self._port = parts.port or (5671 if self._tls else 5672)
92
+ self._user = unquote(parts.username or "guest")
93
+ self._password = unquote(parts.password or "guest")
94
+ self._vhost = unquote(parts.path[1:]) or "/"
95
+ self._lock = threading.Lock()
96
+ self._connection: Any = None
97
+ self._channel: Any = None
98
+ self._declared: set[str] = set()
99
+ self._pid = 0
100
+ self._next_tag = 1
101
+ # Delivery tag to message index, for publishes awaiting a confirm.
102
+ self._unconfirmed: dict[int, int] = {}
103
+ # Message indexes of the current call with no confirm yet, sent or not.
104
+ self._outstanding: set[int] = set()
105
+ self._nacked = 0
106
+
107
+ def _open(self) -> None:
108
+ try:
109
+ import amqp
110
+ except ImportError as exc:
111
+ raise ImportError(
112
+ "an amqp:// broker_url needs py-amqp: pip install 'cauli[rabbitmq]'"
113
+ ) from exc
114
+ connection = amqp.Connection(
115
+ host=f"{self._host}:{self._port}",
116
+ userid=self._user,
117
+ password=self._password,
118
+ virtual_host=self._vhost,
119
+ # Verifies the certificate and the hostname against the system CAs.
120
+ ssl={"server_hostname": self._host} if self._tls else False,
121
+ connect_timeout=PUBLISH_TIMEOUT,
122
+ read_timeout=PUBLISH_TIMEOUT,
123
+ write_timeout=PUBLISH_TIMEOUT,
124
+ )
125
+ connection.connect()
126
+ channel = connection.channel()
127
+ channel.confirm_select()
128
+ channel.events["basic_ack"].add(self._on_ack)
129
+ channel.events["basic_nack"].add(self._on_nack)
130
+ self._connection, self._channel = connection, channel
131
+ self._declared = set()
132
+ self._pid = os.getpid()
133
+ self._next_tag = 1
134
+ self._unconfirmed = {}
135
+
136
+ def _settle(self, delivery_tag: int, multiple: bool) -> int:
137
+ """Forget the publishes a confirm covers; returns how many."""
138
+ tags = (
139
+ [tag for tag in self._unconfirmed if tag <= delivery_tag]
140
+ if multiple
141
+ else [delivery_tag]
142
+ )
143
+ settled = [
144
+ self._unconfirmed.pop(tag) for tag in tags if tag in self._unconfirmed
145
+ ]
146
+ self._outstanding.difference_update(settled)
147
+ return len(settled)
148
+
149
+ def _on_ack(self, delivery_tag: int, multiple: bool) -> None:
150
+ self._settle(delivery_tag, multiple)
151
+
152
+ def _on_nack(self, delivery_tag: int, multiple: bool) -> None:
153
+ self._nacked += self._settle(delivery_tag, multiple)
154
+
155
+ def _publish_and_confirm(
156
+ self, messages: Sequence[tuple[str, bytes]], indexes: list[int]
157
+ ) -> None:
158
+ import amqp
159
+
160
+ for index in indexes:
161
+ queue, raw = messages[index]
162
+ name = amqp_queue_name(queue)
163
+ if name not in self._declared:
164
+ self._channel.queue_declare(
165
+ queue=name,
166
+ durable=True,
167
+ auto_delete=False,
168
+ arguments=AMQP_QUEUE_ARGUMENTS,
169
+ )
170
+ self._declared.add(name)
171
+ self._unconfirmed[self._next_tag] = index
172
+ self._next_tag += 1
173
+ self._channel.basic_publish(
174
+ amqp.Message(raw, delivery_mode=2, content_type="application/json"),
175
+ exchange="",
176
+ routing_key=name,
177
+ mandatory=True,
178
+ )
179
+ while self._unconfirmed:
180
+ self._connection.drain_events(timeout=PUBLISH_TIMEOUT)
181
+
182
+ def publish_many(self, messages: Sequence[tuple[str, bytes]]) -> None:
183
+ """Publish ``(queue, envelope)`` pairs and wait for every confirm.
184
+
185
+ A connection that fails is reopened once and the unconfirmed
186
+ messages are sent again, so one of them may be delivered twice.
187
+ """
188
+ import amqp
189
+
190
+ with self._lock:
191
+ self._outstanding = set(range(len(messages)))
192
+ self._nacked = 0
193
+ for attempt in (1, 2):
194
+ try:
195
+ if self._channel is None or self._pid != os.getpid():
196
+ self._open()
197
+ self._publish_and_confirm(messages, sorted(self._outstanding))
198
+ break
199
+ except (OSError, amqp.exceptions.ConnectionError):
200
+ self._channel = None
201
+ if attempt == 2:
202
+ raise
203
+ except BaseException:
204
+ # A channel error closes the channel on the server side.
205
+ self._channel = None
206
+ raise
207
+ if self._nacked:
208
+ raise RuntimeError(
209
+ f"RabbitMQ refused {self._nacked} of {len(messages)} publishes "
210
+ "(a nack: a queue is over its length limit or the broker "
211
+ "could not persist the message). Those tasks were not enqueued"
212
+ )
213
+
214
+
215
+ class SqsBroker:
216
+ """SendMessageBatch to standard queues through boto3."""
217
+
218
+ def __init__(self, url: str) -> None:
219
+ self._region = urlsplit(url).hostname or None
220
+ self._lock = threading.Lock()
221
+ self._client: Any = None
222
+ self._queue_urls: dict[str, str] = {}
223
+ self._pid = 0
224
+
225
+ def _sqs(self) -> Any:
226
+ if self._client is None or self._pid != os.getpid():
227
+ with self._lock:
228
+ if self._client is None or self._pid != os.getpid():
229
+ self._client = self._new_client()
230
+ self._queue_urls = {}
231
+ self._pid = os.getpid()
232
+ return self._client
233
+
234
+ def _new_client(self) -> Any:
235
+ try:
236
+ import boto3
237
+ from botocore.config import Config
238
+ except ImportError as exc:
239
+ raise ImportError(
240
+ "an sqs:// broker_url needs boto3: pip install 'cauli[sqs]'"
241
+ ) from exc
242
+ return boto3.client(
243
+ "sqs",
244
+ region_name=self._region,
245
+ config=Config(
246
+ connect_timeout=PUBLISH_TIMEOUT,
247
+ read_timeout=PUBLISH_TIMEOUT,
248
+ retries={"mode": "standard", "max_attempts": 3},
249
+ ),
250
+ )
251
+
252
+ def _queue_url(self, client: Any, queue: str) -> str:
253
+ name = sqs_queue_name(queue)
254
+ url = self._queue_urls.get(name)
255
+ if url is None:
256
+ try:
257
+ url = client.get_queue_url(QueueName=name)["QueueUrl"]
258
+ except client.exceptions.QueueDoesNotExist:
259
+ url = client.create_queue(QueueName=name)["QueueUrl"]
260
+ self._queue_urls[name] = url
261
+ return url
262
+
263
+ def publish_many(self, messages: Sequence[tuple[str, bytes]]) -> None:
264
+ """Send ``(queue, envelope)`` pairs, batched per queue within the SQS limits."""
265
+ client = self._sqs()
266
+ batch: list[dict[str, str]] = []
267
+ batch_queue = ""
268
+ batch_bytes = 0
269
+ for queue, raw in messages:
270
+ if batch and (
271
+ queue != batch_queue
272
+ or len(batch) == SQS_BATCH_ENTRIES
273
+ or batch_bytes + len(raw) > SQS_BATCH_BYTES
274
+ ):
275
+ self._send_batch(client, batch_queue, batch)
276
+ batch, batch_bytes = [], 0
277
+ batch_queue = queue
278
+ batch_bytes += len(raw)
279
+ batch.append({"Id": str(len(batch)), "MessageBody": raw.decode("utf-8")})
280
+ if batch:
281
+ self._send_batch(client, batch_queue, batch)
282
+
283
+ def _send_batch(
284
+ self, client: Any, queue: str, entries: list[dict[str, str]]
285
+ ) -> None:
286
+ reply = client.send_message_batch(
287
+ QueueUrl=self._queue_url(client, queue), Entries=entries
288
+ )
289
+ failed = reply.get("Failed")
290
+ if failed:
291
+ first = failed[0]
292
+ raise RuntimeError(
293
+ f"SQS refused {len(failed)} of {len(entries)} messages for queue "
294
+ f"{sqs_queue_name(queue)!r}: {first.get('Code')}: {first.get('Message')}. "
295
+ "Those tasks were not enqueued"
296
+ )
cauli/_codec.py ADDED
@@ -0,0 +1,172 @@
1
+ """JSON encode and decode for the wire format (PROTOCOL.md sections 2, 5.1, 8).
2
+
3
+ msgspec is required, with no stdlib ``json`` fallback: the two disagree on
4
+ lone surrogates, dict key coercion and exception types. msgspec is also
5
+ permissive (``NaN`` to ``null``, ``set`` as array, ``bytes`` as base64, int
6
+ keys coerced), so :func:`_validate_json_types` enforces the JSON type set
7
+ before every encode.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from typing import Any
14
+
15
+ try:
16
+ import msgspec
17
+ import msgspec.json as _msgspec_json
18
+ except ImportError as exc: # pragma: no cover - environment error, not logic
19
+ raise ImportError(
20
+ "cauli requires msgspec. Install it with: pip install msgspec\n"
21
+ "(it is a declared dependency, so `pip install cauli` normally brings "
22
+ "it in; this usually means an editable/partial install)"
23
+ ) from exc
24
+
25
+ __all__ = [
26
+ "backend",
27
+ "encode",
28
+ "encode_str",
29
+ "encode_bytes",
30
+ "decode",
31
+ "ENCODE_ERRORS",
32
+ "DECODE_ERRORS",
33
+ ]
34
+
35
+ backend = "msgspec"
36
+
37
+ # msgspec.EncodeError is not a ValueError, so MsgspecError must be listed.
38
+ # RecursionError covers cyclic or very deep trees in the validator.
39
+ ENCODE_ERRORS: tuple = (TypeError, ValueError, RecursionError, msgspec.MsgspecError)
40
+ DECODE_ERRORS: tuple = (TypeError, ValueError, RecursionError, msgspec.MsgspecError)
41
+
42
+ _encoder = _msgspec_json.Encoder()
43
+ _decoder = _msgspec_json.Decoder()
44
+
45
+ _ALLOWED = "allowed types: str, int, float, bool, None, list, tuple, dict with str keys"
46
+
47
+ # serde_json's recursion limit in the worker: deeper JSON fails to parse and
48
+ # is dead lettered as malformed, so the client rejects it at the call site.
49
+ _MAX_NESTING = 127
50
+
51
+
52
+ def _push_path(exc: BaseException, segment: object) -> None:
53
+ """Record one location segment on a validation failure as the walk unwinds.
54
+
55
+ Carrying the path on the exception keeps string building off the success
56
+ path, which runs on every enqueue. Only this module's plain ``TypeError``
57
+ and ``ValueError`` are annotated, so :func:`encode` can rebuild them as
58
+ ``type(exc)(msg)``.
59
+ """
60
+ if type(exc) is not TypeError and type(exc) is not ValueError:
61
+ return
62
+ path = getattr(exc, "_cauli_path", None)
63
+ if path is None:
64
+ exc._cauli_path = [segment] # type: ignore[attr-defined]
65
+ else:
66
+ path.append(segment)
67
+
68
+
69
+ def _render_path(segments: list[Any]) -> str:
70
+ """Render innermost first segments as e.g. ``args[0]['meta']``."""
71
+ parts: list[str] = []
72
+ for i, seg in enumerate(reversed(segments)):
73
+ if isinstance(seg, str):
74
+ parts.append(seg if i == 0 else f"[{seg!r}]")
75
+ else:
76
+ parts.append(f"[{seg}]")
77
+ return "".join(parts)
78
+
79
+
80
+ def _validate_json_types(obj: Any, depth: int = 1) -> None:
81
+ """Reject non JSON types, non finite floats and non str dict keys.
82
+
83
+ Keys are not coerced: ``{1: "a", "1": "b"}`` would collapse to one entry.
84
+ ``RecursionError`` is not annotated: a cycle has no finite path.
85
+ """
86
+ t = type(obj)
87
+ if t is str or t is int or t is bool or obj is None:
88
+ return
89
+ if t is float:
90
+ if math.isfinite(obj):
91
+ return
92
+ raise ValueError("Out of range float values are not JSON compliant")
93
+ if depth > _MAX_NESTING and isinstance(obj, (dict, list, tuple)):
94
+ raise ValueError(f"nested deeper than {_MAX_NESTING} arrays/objects")
95
+ if t is dict:
96
+ for k, v in obj.items():
97
+ if type(k) is not str:
98
+ raise TypeError(f"dict keys must be str, got {type(k).__name__}")
99
+ try:
100
+ _validate_json_types(v, depth + 1)
101
+ except (TypeError, ValueError) as exc:
102
+ _push_path(exc, k)
103
+ raise
104
+ return
105
+ if t is list or t is tuple:
106
+ for i, v in enumerate(obj):
107
+ try:
108
+ _validate_json_types(v, depth + 1)
109
+ except (TypeError, ValueError) as exc:
110
+ _push_path(exc, i)
111
+ raise
112
+ return
113
+ # Subclasses of the builtin types, after the exact type fast path.
114
+ if isinstance(obj, (str, int)):
115
+ return
116
+ if isinstance(obj, float):
117
+ if math.isfinite(obj):
118
+ return
119
+ raise ValueError("Out of range float values are not JSON compliant")
120
+ if isinstance(obj, dict):
121
+ for k, v in obj.items():
122
+ if not isinstance(k, str):
123
+ raise TypeError(f"dict keys must be str, got {type(k).__name__}")
124
+ try:
125
+ _validate_json_types(v, depth + 1)
126
+ except (TypeError, ValueError) as exc:
127
+ _push_path(exc, k)
128
+ raise
129
+ return
130
+ if isinstance(obj, (list, tuple)):
131
+ for i, v in enumerate(obj):
132
+ try:
133
+ _validate_json_types(v, depth + 1)
134
+ except (TypeError, ValueError) as exc:
135
+ _push_path(exc, i)
136
+ raise
137
+ return
138
+ raise TypeError(
139
+ f"Object of type {t.__name__} is not JSON serializable ({_ALLOWED})"
140
+ )
141
+
142
+
143
+ def encode(obj: Any) -> bytes:
144
+ """Encode ``obj`` as compact UTF-8 JSON bytes.
145
+
146
+ Raises one of :data:`ENCODE_ERRORS`; a rejection inside a container names
147
+ its location, e.g. ``args[0]: Object of type UUID is not JSON
148
+ serializable (allowed types: ...)``.
149
+ """
150
+ try:
151
+ _validate_json_types(obj)
152
+ except (TypeError, ValueError) as exc:
153
+ segments = getattr(exc, "_cauli_path", None)
154
+ if not segments:
155
+ raise
156
+ raise type(exc)(f"{_render_path(segments)}: {exc}") from exc
157
+ return _encoder.encode(obj)
158
+
159
+
160
+ def decode(data: bytes | str) -> Any:
161
+ """Parse JSON from bytes or str. Raises on malformed input."""
162
+ return _decoder.decode(data)
163
+
164
+
165
+ def encode_str(obj: Any) -> str:
166
+ """:func:`encode`, as ``str``."""
167
+ return encode(obj).decode("utf-8")
168
+
169
+
170
+ def encode_bytes(obj: Any) -> bytes:
171
+ """:func:`encode`, named for the cpu child's byte socket path."""
172
+ return encode(obj)
cauli/_context.py ADDED
@@ -0,0 +1,117 @@
1
+ """What a running task knows about itself.
2
+
3
+ .. code-block:: python
4
+
5
+ from cauli import current_task
6
+
7
+ @app.task()
8
+ def charge(order_id):
9
+ ctx = current_task()
10
+ log.info("charging %s (task %s, attempt %s)", order_id, ctx.id, ctx.retries)
11
+
12
+ Backed by a :class:`contextvars.ContextVar`: a thread local would leak
13
+ between coroutines on one loop thread, a global between pool threads.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from contextvars import ContextVar, Token
19
+ from typing import Any
20
+
21
+ __all__ = ["TaskContext", "current_task", "set_current_task", "reset_current_task"]
22
+
23
+
24
+ class TaskContext:
25
+ """Read only facts about the task executing on this thread or coroutine.
26
+
27
+ ``id``
28
+ The task id, the same as the caller's ``AsyncResult.id``.
29
+ ``retries``
30
+ Retries so far, ``0`` on the first attempt, ``None`` if unreported.
31
+ ``max_retries``
32
+ The task's retry ceiling, ``None`` if unreported.
33
+ ``task``
34
+ The registered task name.
35
+ ``queue``
36
+ The queue the envelope was published to, ``None`` if unreported.
37
+ """
38
+
39
+ __slots__ = ("id", "task", "retries", "max_retries", "queue")
40
+
41
+ def __init__(
42
+ self,
43
+ id: str | None,
44
+ task: str | None = None,
45
+ retries: int | None = None,
46
+ max_retries: int | None = None,
47
+ queue: str | None = None,
48
+ ) -> None:
49
+ self.id = id
50
+ self.task = task
51
+ self.retries = retries
52
+ self.max_retries = max_retries
53
+ self.queue = queue
54
+
55
+ def is_last_attempt(self) -> bool:
56
+ """True when this attempt is the last before the dead letter queue.
57
+
58
+ ``False`` when either count is unreported.
59
+ """
60
+ if self.retries is None or self.max_retries is None:
61
+ return False
62
+ return self.retries >= self.max_retries
63
+
64
+ def __repr__(self) -> str:
65
+ return (
66
+ f"<TaskContext id={self.id!r} task={self.task!r} "
67
+ f"retries={self.retries!r} queue={self.queue!r}>"
68
+ )
69
+
70
+
71
+ _current: ContextVar[TaskContext | None] = ContextVar(
72
+ "cauli_current_task", default=None
73
+ )
74
+
75
+
76
+ def current_task() -> TaskContext | None:
77
+ """The :class:`TaskContext` for the task running here, or ``None`` outside one."""
78
+ return _current.get()
79
+
80
+
81
+ def set_current_task(ctx: "TaskContext | None") -> "Token[TaskContext | None]":
82
+ """Install ``ctx`` as the current task context and return a reset token.
83
+
84
+ For execution lanes (worker/src/shim.py, ``cauli._exec``), which pass the
85
+ token to :func:`reset_current_task` in a ``finally``.
86
+ """
87
+ return _current.set(ctx)
88
+
89
+
90
+ def reset_current_task(token: "Token[TaskContext | None]") -> None:
91
+ """Undo a :func:`set_current_task`.
92
+
93
+ A token from another context clears the value instead of raising: the
94
+ sync pool reuses threads, and a stale id must not reach the next task.
95
+ """
96
+ try:
97
+ _current.reset(token)
98
+ except ValueError:
99
+ _current.set(None)
100
+
101
+
102
+ def make_context(request: dict[str, Any], task_id: str | None = None) -> TaskContext:
103
+ """Build a :class:`TaskContext` from a cpu lane request dict.
104
+
105
+ ``task_id`` overrides the request ``id``, which carries a per attempt
106
+ suffix (``{envelope id}.{seq}``, worker/src/exec.rs).
107
+ """
108
+ raw_id = task_id if task_id is not None else request.get("id")
109
+ retries = request.get("retries")
110
+ max_retries = request.get("max_retries")
111
+ return TaskContext(
112
+ id=None if raw_id is None else str(raw_id),
113
+ task=request.get("task"),
114
+ retries=None if retries is None else int(retries),
115
+ max_retries=None if max_retries is None else int(max_retries),
116
+ queue=request.get("queue"),
117
+ )