fourtheorem-tempo-worker 0.3.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: fourtheorem-tempo-worker
3
+ Version: 0.3.0
4
+ Summary: Tempo worker SDK: failure reporting, logging, and custom metrics for worker tasks
5
+ Author: fourTheorem
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Dist: opentelemetry-api>=1.25
9
+ Requires-Python: >=3.11
10
+ Project-URL: Homepage, https://fourtheorem.com/high-performance-compute/
11
+ Description-Content-Type: text/markdown
12
+
13
+ # Tempo Worker SDK (Python)
14
+
15
+ A Tempo **worker** is a process that Tempo runs on its compute backends to
16
+ execute tasks. A **task** is your own custom business logic, packaged as a
17
+ function with this signature:
18
+
19
+ ```python
20
+ from pathlib import Path
21
+
22
+ def run(working_dir: Path, params: dict) -> None: ...
23
+ ```
24
+
25
+ Tempo calls `run` with a working directory (inputs under
26
+ `working_dir/inputs/`, outputs written to `working_dir/outputs/`) and the
27
+ job parameters. Task code needs no platform imports, so you do not need an
28
+ SDK to write a task. An SDK is still convenient: it gives you easy,
29
+ standardised access to the job run context, structured logging, custom
30
+ metrics, and failure reporting. `fourtheorem-tempo-worker` (import name
31
+ `tempo_worker`) provides all of this.
32
+
33
+ ```bash
34
+ pip install fourtheorem-tempo-worker
35
+ ```
36
+
37
+ When you run task code yourself (locally, or in unit tests) instead of on a
38
+ Tempo worker, this is a **standalone run**: the SDK detects it and falls
39
+ back to the safe defaults noted in each section below.
40
+
41
+ ## Features
42
+
43
+ Here is the list of features you find in the SDK.
44
+
45
+ ### Run context
46
+
47
+ `current_context()` returns the identifiers of the running job attempt.
48
+
49
+ ```python
50
+ from tempo_worker import current_context
51
+
52
+ def run(working_dir, params):
53
+ ctx = current_context()
54
+ if ctx is not None:
55
+ print(ctx.workload_id, ctx.job_id, ctx.attempt, ctx.worker_id)
56
+ ```
57
+
58
+ The context object carries four properties:
59
+
60
+ - `workload_id`: the workload the job belongs to.
61
+ - `job_id`: the job the worker is executing.
62
+ - `attempt`: the zero-based retry attempt number.
63
+ - `worker_id`: the worker process running the job.
64
+
65
+ In a standalone run, `current_context()` returns `None`.
66
+
67
+ ### Logging
68
+
69
+ `get_logger` returns a standard library logger that emits structured,
70
+ single-line JSON records, ready for observability and monitoring tools. On a
71
+ Tempo worker each record automatically carries `workload_id`, `job_id`,
72
+ `attempt`, and `worker_id`, so you can filter and correlate task logs with
73
+ the rest of the platform logs.
74
+
75
+ ```python
76
+ from tempo_worker import get_logger
77
+
78
+ logger = get_logger(__name__)
79
+
80
+ def run(working_dir, params):
81
+ logger.info("Pricing started", extra={"scenario_count": len(params["scenarios"])})
82
+ ```
83
+
84
+ In a standalone run the SDK installs a JSON handler with the same field
85
+ shape, so log lines look identical in both environments. Standalone runs
86
+ read the service name from `TEMPO_SERVICE_NAME` (default `tempo-task`) and
87
+ the level from `LOG_LEVEL` (default `INFO`).
88
+
89
+ ### Custom metrics
90
+
91
+ The `tempo_worker.metrics` module provides `counter`, `histogram`, and
92
+ `up_down_counter`. They create instruments that export through the worker's
93
+ metrics pipeline. Tempo prefixes each name with `tr_custom_` and attaches
94
+ the `workload_id` label from the run context. The series appear in the
95
+ Tempo Grafana dashboard under "Custom task metrics".
96
+
97
+ ```python
98
+ from tempo_worker import metrics
99
+
100
+ rows = metrics.counter("rows_processed", description="Rows processed per job.")
101
+ latency = metrics.histogram("pricing_seconds", unit="s")
102
+
103
+ def run(working_dir, params):
104
+ rows.add(1_000)
105
+ latency.record(2.31)
106
+ ```
107
+
108
+ The attribute keys `job_id` and `worker_id` are rejected: their cardinality
109
+ is unbounded and would overload the time-series store.
110
+
111
+ A standalone run has no configured metrics provider, so every call is a
112
+ no-op.
113
+
114
+ > **A note on naming.** You might have noticed that logging has a factory
115
+ > function, `get_logger`, while metrics is a module namespace. This is
116
+ > deliberate: each follows the strongest convention in its own domain.
117
+ > `get_logger(__name__)` mirrors the stdlib `logging.getLogger(__name__)`
118
+ > idiom, and `metrics.counter(...)` mirrors the OpenTelemetry module-style
119
+ > API. A logger is a stateful object you keep; the metrics functions are
120
+ > factories for named instruments.
121
+
122
+ ### Explicit failure reporting
123
+
124
+ Raise `TaskFailure` to report a failure with structured context. Set
125
+ `retriable=False` to tell the scheduler not to retry the job, even when retry
126
+ budget remains. Use it when a retry cannot change the outcome, for example
127
+ corrupt input data or invalid parameters: every attempt would fail the same
128
+ way, so skipping the retries saves time and compute, and the workload
129
+ reaches its final state sooner.
130
+
131
+ The `detail` dict is stored in the job attempt record, so
132
+ keep its values JSON-serialisable.
133
+
134
+ ```python
135
+ from tempo_worker import TaskFailure
136
+
137
+ def run(working_dir, params):
138
+ if "rate_table" not in params:
139
+ raise TaskFailure(
140
+ "missing rate_table parameter",
141
+ retriable=False,
142
+ detail={"missing_field": "rate_table"},
143
+ )
144
+ ```
145
+
146
+ By default, any exception other than `TaskFailure` is reported as a
147
+ retriable failure.
148
+
149
+ In a standalone run, `TaskFailure` is a plain exception and propagates
150
+ normally.
151
+
152
+ ## Versioning
153
+
154
+ The SDK follows the Tempo platform release version.
@@ -0,0 +1,142 @@
1
+ # Tempo Worker SDK (Python)
2
+
3
+ A Tempo **worker** is a process that Tempo runs on its compute backends to
4
+ execute tasks. A **task** is your own custom business logic, packaged as a
5
+ function with this signature:
6
+
7
+ ```python
8
+ from pathlib import Path
9
+
10
+ def run(working_dir: Path, params: dict) -> None: ...
11
+ ```
12
+
13
+ Tempo calls `run` with a working directory (inputs under
14
+ `working_dir/inputs/`, outputs written to `working_dir/outputs/`) and the
15
+ job parameters. Task code needs no platform imports, so you do not need an
16
+ SDK to write a task. An SDK is still convenient: it gives you easy,
17
+ standardised access to the job run context, structured logging, custom
18
+ metrics, and failure reporting. `fourtheorem-tempo-worker` (import name
19
+ `tempo_worker`) provides all of this.
20
+
21
+ ```bash
22
+ pip install fourtheorem-tempo-worker
23
+ ```
24
+
25
+ When you run task code yourself (locally, or in unit tests) instead of on a
26
+ Tempo worker, this is a **standalone run**: the SDK detects it and falls
27
+ back to the safe defaults noted in each section below.
28
+
29
+ ## Features
30
+
31
+ Here is the list of features you find in the SDK.
32
+
33
+ ### Run context
34
+
35
+ `current_context()` returns the identifiers of the running job attempt.
36
+
37
+ ```python
38
+ from tempo_worker import current_context
39
+
40
+ def run(working_dir, params):
41
+ ctx = current_context()
42
+ if ctx is not None:
43
+ print(ctx.workload_id, ctx.job_id, ctx.attempt, ctx.worker_id)
44
+ ```
45
+
46
+ The context object carries four properties:
47
+
48
+ - `workload_id`: the workload the job belongs to.
49
+ - `job_id`: the job the worker is executing.
50
+ - `attempt`: the zero-based retry attempt number.
51
+ - `worker_id`: the worker process running the job.
52
+
53
+ In a standalone run, `current_context()` returns `None`.
54
+
55
+ ### Logging
56
+
57
+ `get_logger` returns a standard library logger that emits structured,
58
+ single-line JSON records, ready for observability and monitoring tools. On a
59
+ Tempo worker each record automatically carries `workload_id`, `job_id`,
60
+ `attempt`, and `worker_id`, so you can filter and correlate task logs with
61
+ the rest of the platform logs.
62
+
63
+ ```python
64
+ from tempo_worker import get_logger
65
+
66
+ logger = get_logger(__name__)
67
+
68
+ def run(working_dir, params):
69
+ logger.info("Pricing started", extra={"scenario_count": len(params["scenarios"])})
70
+ ```
71
+
72
+ In a standalone run the SDK installs a JSON handler with the same field
73
+ shape, so log lines look identical in both environments. Standalone runs
74
+ read the service name from `TEMPO_SERVICE_NAME` (default `tempo-task`) and
75
+ the level from `LOG_LEVEL` (default `INFO`).
76
+
77
+ ### Custom metrics
78
+
79
+ The `tempo_worker.metrics` module provides `counter`, `histogram`, and
80
+ `up_down_counter`. They create instruments that export through the worker's
81
+ metrics pipeline. Tempo prefixes each name with `tr_custom_` and attaches
82
+ the `workload_id` label from the run context. The series appear in the
83
+ Tempo Grafana dashboard under "Custom task metrics".
84
+
85
+ ```python
86
+ from tempo_worker import metrics
87
+
88
+ rows = metrics.counter("rows_processed", description="Rows processed per job.")
89
+ latency = metrics.histogram("pricing_seconds", unit="s")
90
+
91
+ def run(working_dir, params):
92
+ rows.add(1_000)
93
+ latency.record(2.31)
94
+ ```
95
+
96
+ The attribute keys `job_id` and `worker_id` are rejected: their cardinality
97
+ is unbounded and would overload the time-series store.
98
+
99
+ A standalone run has no configured metrics provider, so every call is a
100
+ no-op.
101
+
102
+ > **A note on naming.** You might have noticed that logging has a factory
103
+ > function, `get_logger`, while metrics is a module namespace. This is
104
+ > deliberate: each follows the strongest convention in its own domain.
105
+ > `get_logger(__name__)` mirrors the stdlib `logging.getLogger(__name__)`
106
+ > idiom, and `metrics.counter(...)` mirrors the OpenTelemetry module-style
107
+ > API. A logger is a stateful object you keep; the metrics functions are
108
+ > factories for named instruments.
109
+
110
+ ### Explicit failure reporting
111
+
112
+ Raise `TaskFailure` to report a failure with structured context. Set
113
+ `retriable=False` to tell the scheduler not to retry the job, even when retry
114
+ budget remains. Use it when a retry cannot change the outcome, for example
115
+ corrupt input data or invalid parameters: every attempt would fail the same
116
+ way, so skipping the retries saves time and compute, and the workload
117
+ reaches its final state sooner.
118
+
119
+ The `detail` dict is stored in the job attempt record, so
120
+ keep its values JSON-serialisable.
121
+
122
+ ```python
123
+ from tempo_worker import TaskFailure
124
+
125
+ def run(working_dir, params):
126
+ if "rate_table" not in params:
127
+ raise TaskFailure(
128
+ "missing rate_table parameter",
129
+ retriable=False,
130
+ detail={"missing_field": "rate_table"},
131
+ )
132
+ ```
133
+
134
+ By default, any exception other than `TaskFailure` is reported as a
135
+ retriable failure.
136
+
137
+ In a standalone run, `TaskFailure` is a plain exception and propagates
138
+ normally.
139
+
140
+ ## Versioning
141
+
142
+ The SDK follows the Tempo platform release version.
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "fourtheorem-tempo-worker"
3
+ version = "0.3.0"
4
+ description = "Tempo worker SDK: failure reporting, logging, and custom metrics for worker tasks"
5
+ authors = [{ name = "fourTheorem" }]
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ readme = "README.md"
10
+ dependencies = [
11
+ "opentelemetry-api>=1.25",
12
+ ]
13
+
14
+ [tool.uv.build-backend]
15
+ module-name = "tempo_worker"
16
+
17
+ [build-system]
18
+ requires = ["uv_build>=0.11.0,<0.12.0"]
19
+ build-backend = "uv_build"
20
+
21
+ [tool.ruff]
22
+ line-length = 120
23
+
24
+ [tool.ruff.lint]
25
+ select = ["F", "I", "UP"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://fourtheorem.com/high-performance-compute/"
@@ -0,0 +1,18 @@
1
+ """Tempo worker SDK.
2
+
3
+ Public surface for customer task code: explicit failure reporting
4
+ (:class:`TaskFailure`), Tempo-shaped logging (:func:`get_logger`), custom
5
+ metrics (:mod:`tempo_worker.metrics`), and read access to the per-job run
6
+ context (:func:`current_context`).
7
+ """
8
+
9
+ from tempo_worker.context import TaskRunContext, current_context
10
+ from tempo_worker.errors import TaskFailure
11
+ from tempo_worker.logging import get_logger
12
+
13
+ __all__ = [
14
+ "TaskFailure",
15
+ "TaskRunContext",
16
+ "current_context",
17
+ "get_logger",
18
+ ]
@@ -0,0 +1,43 @@
1
+ """Per-job run context exposed to task code.
2
+
3
+ The worker harness sets the context around each task invocation. Task code
4
+ reads it through :func:`current_context`; the ``_set_run_context`` /
5
+ ``_reset_run_context`` pair is the harness integration surface.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from contextvars import ContextVar, Token
11
+ from dataclasses import dataclass
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class TaskRunContext:
16
+ """Identifiers for the job attempt that is currently executing.
17
+
18
+ :param workload_id: Workload the job belongs to.
19
+ :param job_id: Job identifier.
20
+ :param attempt: Zero-based retry attempt number.
21
+ :param worker_id: Identifier of the worker process running the job.
22
+ """
23
+
24
+ workload_id: str
25
+ job_id: str
26
+ attempt: int
27
+ worker_id: str
28
+
29
+
30
+ _CURRENT: ContextVar[TaskRunContext | None] = ContextVar("tempo_worker_run_context", default=None)
31
+
32
+
33
+ def current_context() -> TaskRunContext | None:
34
+ """Return the context of the running job, or ``None`` outside the harness."""
35
+ return _CURRENT.get()
36
+
37
+
38
+ def _set_run_context(ctx: TaskRunContext) -> Token[TaskRunContext | None]:
39
+ return _CURRENT.set(ctx)
40
+
41
+
42
+ def _reset_run_context(token: Token[TaskRunContext | None]) -> None:
43
+ _CURRENT.reset(token)
@@ -0,0 +1,27 @@
1
+ """Explicit failure reporting for worker tasks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class TaskFailure(Exception):
9
+ """Explicit task failure raised by task code.
10
+
11
+ The Tempo worker harness maps this exception to a failed completion.
12
+ ``retriable=False`` tells the scheduler not to retry the job, even when
13
+ retry budget remains. ``detail`` is persisted in the job attempt record,
14
+ so keep its values JSON-serialisable.
15
+
16
+ Outside the harness this is a plain exception and propagates normally.
17
+
18
+ :param message: Human-readable failure description.
19
+ :param retriable: ``False`` marks the failure as permanent.
20
+ :param detail: Optional structured context stored with the attempt record.
21
+ """
22
+
23
+ def __init__(self, message: str, *, retriable: bool = True, detail: dict[str, Any] | None = None) -> None:
24
+ super().__init__(message)
25
+ self.message = message
26
+ self.retriable = retriable
27
+ self.detail = detail
@@ -0,0 +1,136 @@
1
+ """Tempo-shaped structured logging for worker tasks.
2
+
3
+ Under the worker harness the root logger already emits single-line JSON, so
4
+ :func:`get_logger` only attaches a filter that injects the run context into
5
+ each record. In a standalone run (no handlers configured) it also installs a
6
+ JSON handler with the same field shape, so task logs look identical in both
7
+ environments.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ import os
15
+ import sys
16
+ from datetime import UTC, datetime
17
+ from typing import Any
18
+
19
+ from tempo_worker.context import current_context
20
+
21
+ # Keep in sync with ts_common.logging._RESERVED_LOG_RECORD_FIELDS. The SDK
22
+ # stays dependency-free, so the set is duplicated rather than imported.
23
+ _RESERVED_LOG_RECORD_FIELDS = {
24
+ "args",
25
+ "asctime",
26
+ "created",
27
+ "exc_info",
28
+ "exc_text",
29
+ "filename",
30
+ "funcName",
31
+ "levelname",
32
+ "levelno",
33
+ "lineno",
34
+ "module",
35
+ "msecs",
36
+ "message",
37
+ "msg",
38
+ "name",
39
+ "pathname",
40
+ "process",
41
+ "processName",
42
+ "relativeCreated",
43
+ "stack_info",
44
+ "thread",
45
+ "threadName",
46
+ "taskName",
47
+ }
48
+
49
+
50
+ def _normalise_log_value(value: Any) -> Any:
51
+ if isinstance(value, str | int | float | bool) or value is None:
52
+ return value
53
+ if isinstance(value, dict):
54
+ return {str(key): _normalise_log_value(item) for key, item in value.items()}
55
+ if isinstance(value, list | tuple | set | frozenset):
56
+ return [_normalise_log_value(item) for item in value]
57
+ return str(value)
58
+
59
+
60
+ class JsonFormatter(logging.Formatter):
61
+ """Render log records as single-line JSON objects.
62
+
63
+ Keep in sync with ``ts_common.logging.JsonFormatter`` (same field shape),
64
+ duplicated so the SDK needs no platform dependency.
65
+ """
66
+
67
+ def __init__(self, service_name: str) -> None:
68
+ super().__init__()
69
+ self._service_name = service_name
70
+
71
+ def format(self, record: logging.LogRecord) -> str:
72
+ """Serialise the record to a compact JSON string."""
73
+ payload: dict[str, Any] = {
74
+ "timestamp": datetime.fromtimestamp(record.created, tz=UTC).isoformat(timespec="milliseconds"),
75
+ "level": record.levelname,
76
+ "logger": record.name,
77
+ "service": self._service_name,
78
+ "message": record.getMessage(),
79
+ }
80
+ for key, value in record.__dict__.items():
81
+ if key.startswith("_") or key in _RESERVED_LOG_RECORD_FIELDS:
82
+ continue
83
+ payload[key] = _normalise_log_value(value)
84
+ if record.exc_info is not None:
85
+ payload["exception"] = self.formatException(record.exc_info)
86
+ if record.stack_info is not None:
87
+ payload["stack"] = self.formatStack(record.stack_info)
88
+ return json.dumps(payload, separators=(",", ":"), sort_keys=True)
89
+
90
+
91
+ class _ContextInjectionFilter(logging.Filter):
92
+ """Copy the run-context identifiers onto each record.
93
+
94
+ Explicit ``extra`` values win over injected ones. Outside the harness the
95
+ filter is a no-op.
96
+ """
97
+
98
+ def filter(self, record: logging.LogRecord) -> bool:
99
+ ctx = current_context()
100
+ if ctx is None:
101
+ return True
102
+ for key, value in (
103
+ ("workload_id", ctx.workload_id),
104
+ ("job_id", ctx.job_id),
105
+ ("attempt", ctx.attempt),
106
+ ("worker_id", ctx.worker_id),
107
+ ):
108
+ if not hasattr(record, key):
109
+ setattr(record, key, value)
110
+ return True
111
+
112
+
113
+ def get_logger(name: str | None = None) -> logging.Logger:
114
+ """Return a stdlib logger wired for Tempo-shaped structured output.
115
+
116
+ The logger carries a filter that injects ``workload_id``, ``job_id``,
117
+ ``attempt``, and ``worker_id`` from the current run context. When no
118
+ handler is configured on the root logger (a standalone run), a JSON
119
+ handler with the Tempo field shape is installed: the service name comes
120
+ from ``TEMPO_SERVICE_NAME`` (default ``tempo-task``) and the level from
121
+ ``LOG_LEVEL`` (default ``INFO``).
122
+
123
+ :param name: Logger name, usually ``__name__``.
124
+ """
125
+ logger = logging.getLogger(name)
126
+ if not any(isinstance(f, _ContextInjectionFilter) for f in logger.filters):
127
+ logger.addFilter(_ContextInjectionFilter())
128
+
129
+ root_logger = logging.getLogger()
130
+ if not root_logger.handlers:
131
+ handler = logging.StreamHandler(sys.stdout)
132
+ handler.setFormatter(JsonFormatter(service_name=os.environ.get("TEMPO_SERVICE_NAME", "tempo-task")))
133
+ root_logger.addHandler(handler)
134
+ root_logger.setLevel(os.environ.get("LOG_LEVEL", "INFO").upper())
135
+
136
+ return logger
@@ -0,0 +1,151 @@
1
+ """Custom metrics emission for worker tasks.
2
+
3
+ Instruments are created from the ``tempo`` meter, so they export through the
4
+ MeterProvider the worker harness initialises. Without a configured provider
5
+ (a standalone run) every call is a no-op.
6
+
7
+ Guardrails keep customer series compatible with the platform conventions:
8
+ names get the ``tr_custom_`` prefix, ``workload_id`` is attached from the run
9
+ context, and the unbounded-cardinality keys ``job_id`` and ``worker_id`` are
10
+ rejected as attributes.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from typing import Any
17
+
18
+ from opentelemetry import metrics as otel_metrics
19
+
20
+ from tempo_worker.context import current_context
21
+
22
+ _PREFIX = "tr_custom_"
23
+ # Keep in sync with ts_adapters.metrics.catalog._METER_NAME.
24
+ _METER_NAME = "tempo"
25
+ _FORBIDDEN_ATTRIBUTE_KEYS = frozenset({"job_id", "worker_id"})
26
+ _NAME_RE = re.compile(r"^[a-z][a-z0-9_]*$")
27
+
28
+ _instruments: dict[tuple[str, str], Any] = {}
29
+
30
+
31
+ def _full_name(name: str) -> str:
32
+ if name.startswith("tr_"):
33
+ raise ValueError(f"Metric name {name!r} must not start with 'tr_'; the prefix is added automatically")
34
+ if not _NAME_RE.match(name):
35
+ raise ValueError(f"Metric name {name!r} must match {_NAME_RE.pattern}")
36
+ return _PREFIX + name
37
+
38
+
39
+ def _merged_attributes(attributes: dict[str, Any] | None) -> dict[str, Any]:
40
+ merged = dict(attributes) if attributes else {}
41
+ forbidden = _FORBIDDEN_ATTRIBUTE_KEYS & merged.keys()
42
+ if forbidden:
43
+ raise ValueError(f"Attribute keys {sorted(forbidden)} are not allowed: their cardinality is unbounded")
44
+ ctx = current_context()
45
+ if ctx is not None:
46
+ merged["workload_id"] = ctx.workload_id
47
+ return merged
48
+
49
+
50
+ class Counter:
51
+ """Monotonic counter named ``tr_custom_<name>``."""
52
+
53
+ def __init__(self, instrument: otel_metrics.Counter) -> None:
54
+ self._instrument = instrument
55
+
56
+ def add(self, amount: int | float = 1, attributes: dict[str, Any] | None = None) -> None:
57
+ """Add a non-negative amount to the counter.
58
+
59
+ :param amount: Increment to record.
60
+ :param attributes: Optional labels. ``workload_id`` is added from the
61
+ run context; ``job_id`` and ``worker_id`` are rejected.
62
+ :raises ValueError: If a forbidden attribute key is present.
63
+ """
64
+ self._instrument.add(amount, _merged_attributes(attributes))
65
+
66
+
67
+ class UpDownCounter:
68
+ """Non-monotonic counter named ``tr_custom_<name>``."""
69
+
70
+ def __init__(self, instrument: otel_metrics.UpDownCounter) -> None:
71
+ self._instrument = instrument
72
+
73
+ def add(self, amount: int | float, attributes: dict[str, Any] | None = None) -> None:
74
+ """Add a positive or negative amount to the counter.
75
+
76
+ :param amount: Increment or decrement to record.
77
+ :param attributes: Optional labels. ``workload_id`` is added from the
78
+ run context; ``job_id`` and ``worker_id`` are rejected.
79
+ :raises ValueError: If a forbidden attribute key is present.
80
+ """
81
+ self._instrument.add(amount, _merged_attributes(attributes))
82
+
83
+
84
+ class Histogram:
85
+ """Distribution instrument named ``tr_custom_<name>``."""
86
+
87
+ def __init__(self, instrument: otel_metrics.Histogram) -> None:
88
+ self._instrument = instrument
89
+
90
+ def record(self, value: int | float, attributes: dict[str, Any] | None = None) -> None:
91
+ """Record one observed value.
92
+
93
+ :param value: Observation to record.
94
+ :param attributes: Optional labels. ``workload_id`` is added from the
95
+ run context; ``job_id`` and ``worker_id`` are rejected.
96
+ :raises ValueError: If a forbidden attribute key is present.
97
+ """
98
+ self._instrument.record(value, _merged_attributes(attributes))
99
+
100
+
101
+ def counter(name: str, *, unit: str = "1", description: str = "") -> Counter:
102
+ """Return the counter ``tr_custom_<name>``, creating it on first use.
103
+
104
+ ``unit`` and ``description`` apply only on first creation.
105
+
106
+ :param name: Metric name without the ``tr_custom_`` prefix. Must match
107
+ ``^[a-z][a-z0-9_]*$``.
108
+ :raises ValueError: If the name is invalid or already carries a ``tr_`` prefix.
109
+ """
110
+ full_name = _full_name(name)
111
+ key = ("counter", full_name)
112
+ if key not in _instruments:
113
+ instrument = otel_metrics.get_meter(_METER_NAME).create_counter(full_name, unit=unit, description=description)
114
+ _instruments[key] = Counter(instrument)
115
+ return _instruments[key]
116
+
117
+
118
+ def up_down_counter(name: str, *, unit: str = "1", description: str = "") -> UpDownCounter:
119
+ """Return the up-down counter ``tr_custom_<name>``, creating it on first use.
120
+
121
+ ``unit`` and ``description`` apply only on first creation.
122
+
123
+ :param name: Metric name without the ``tr_custom_`` prefix. Must match
124
+ ``^[a-z][a-z0-9_]*$``.
125
+ :raises ValueError: If the name is invalid or already carries a ``tr_`` prefix.
126
+ """
127
+ full_name = _full_name(name)
128
+ key = ("up_down_counter", full_name)
129
+ if key not in _instruments:
130
+ instrument = otel_metrics.get_meter(_METER_NAME).create_up_down_counter(
131
+ full_name, unit=unit, description=description
132
+ )
133
+ _instruments[key] = UpDownCounter(instrument)
134
+ return _instruments[key]
135
+
136
+
137
+ def histogram(name: str, *, unit: str = "1", description: str = "") -> Histogram:
138
+ """Return the histogram ``tr_custom_<name>``, creating it on first use.
139
+
140
+ ``unit`` and ``description`` apply only on first creation.
141
+
142
+ :param name: Metric name without the ``tr_custom_`` prefix. Must match
143
+ ``^[a-z][a-z0-9_]*$``.
144
+ :raises ValueError: If the name is invalid or already carries a ``tr_`` prefix.
145
+ """
146
+ full_name = _full_name(name)
147
+ key = ("histogram", full_name)
148
+ if key not in _instruments:
149
+ instrument = otel_metrics.get_meter(_METER_NAME).create_histogram(full_name, unit=unit, description=description)
150
+ _instruments[key] = Histogram(instrument)
151
+ return _instruments[key]