021-python-observability 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,8 @@
1
+ .venv*/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .env*
7
+ !.env.example
8
+ dist/
@@ -0,0 +1,56 @@
1
+ # Changelog
2
+
3
+ ## [0.3.0](https://github.com/from021-io/observability-python/compare/v0.2.0...v0.3.0) (2026-10-21)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * **package:** consumers rename the dependency from 021-observability to 021-python-observability (with its extras) in their project dependencies, [tool.uv.sources] key or requirements line when moving past v0.2.0, then regenerate their lock.
9
+
10
+ ### Build
11
+
12
+ * **package:** publish to PyPI as 021-python-observability ([#11](https://github.com/from021-io/observability-python/issues/11)) ([7c9056f](https://github.com/from021-io/observability-python/commit/7c9056f68a93fdaf31949df79b8da16785c27853))
13
+
14
+ ## [0.2.0](https://github.com/from021-io/observability-python/compare/v0.1.0...v0.2.0) (2026-10-01)
15
+
16
+
17
+ ### Bug fixes
18
+
19
+ * **grafana:** reject duplicate panel ids during validation ([a285659](https://github.com/from021-io/observability-python/commit/a285659816d7e6f653f63f0eb15617bee0286786))
20
+
21
+
22
+ ### Refactors
23
+
24
+ * **grafana:** share synchronization tooling and tests ([2a3cd4c](https://github.com/from021-io/observability-python/commit/2a3cd4c47b8b1e82fa9af49fe5514f5b259cee26))
25
+
26
+
27
+ ### CI
28
+
29
+ * **release:** version and tag the library with release-please ([#8](https://github.com/from021-io/observability-python/issues/8)) ([bdb1a90](https://github.com/from021-io/observability-python/commit/bdb1a90af1996ef24aa5dc3c3f57d0bcfc8ce69c))
30
+
31
+ ## [0.1.0] - 2026-09-23
32
+
33
+ ### Added
34
+
35
+ - Shared Prometheus reader for consumer scrape compatibility, approved domain dimensions and scalar units, typed HTTPX transport surface and a complete-request HTTP context for existing service clients.
36
+ - **Observability**: common FastAPI/ASGI request metrics, correlated JSON logs and configurable OTLP metrics/traces.
37
+ - **Dependencies**: explicit HTTPX and SQLAlchemy instrumentation, process/pool signals, health/readiness and domain operation helpers.
38
+ - **Verification**: local OTLP receiver and Python 3.12/3.14 contract checks; package distribution and consumer deployment remain separate decisions.
39
+
40
+ ### Changed
41
+
42
+ - **Rollout**: document the readiness JSON contract, protobuf headers, log correlation and coordinated consumer pin/monitor migration.
43
+ - **Repository**: rename the GitHub repository to `from021-io/observability-python`; keep the Python distribution and import names unchanged.
44
+ - Keep task progress in workspace documents instead of a repository `PROGRESS.md`.
45
+ - Reapply safe logging at lifespan startup and route Uvicorn errors through the common formatter.
46
+ - Replace outbound correlation headers case-insensitively to avoid conflicting context.
47
+ - Pin setup-uv to the published v9.0.0 tag for the Python contract matrix.
48
+
49
+ ### Fixed
50
+
51
+ - **Logs**: preserve validated domain correlation UUIDs and bounded exception types/frame locations for structlog, stdlib, Uvicorn and unhandled ASGI failures, without exposing exception messages, source lines, locals or absolute directories. IDs remain excluded from metric labels.
52
+ - Preserve FastAPI included-router prefixes and safe structured stdlib failure fields; quiet HTTPX2/Neo4j drivers and skip Vercel continuations when no remote exporter is configured.
53
+ - **Configuration**: explicit empty headers no longer inherit unrelated ambient OTLP credentials from the SDK.
54
+
55
+ [Unreleased]: https://github.com/from021-io/observability-python/compare/v0.1.0...HEAD
56
+ [0.1.0]: https://github.com/from021-io/observability-python/releases/tag/v0.1.0
@@ -0,0 +1,127 @@
1
+ # Signal contract 0.1
2
+
3
+ Resource fields: `service.name`, `service.version`, `service.instance.id`,
4
+ `deployment.environment.name`. Each app owns its providers; none are installed globally.
5
+ Use `app.state.observability.tracer` if infrastructure needs the same explicit tracer.
6
+ The application must remove its old server instrumentation when adopting this package.
7
+
8
+ | Signal | Kind / unit | Dimensions |
9
+ | --- | --- | --- |
10
+ | `http.server.request.count` | Counter / `{request}` | method, route, final status when sent, outcome, bounded error type when applicable |
11
+ | `http.server.request.duration` | Histogram / `s` | same |
12
+ | `http.server.active_requests` | UpDownCounter / `{request}` | method |
13
+ | `http.client.request.count` | Counter / `{request}` | dependency, method, status when received, bounded error type |
14
+ | `http.client.request.duration` | Histogram / `s` | same |
15
+ | `db.client.operation.count` | Counter / `{operation}` | dependency, status, bounded error type |
16
+ | `db.client.operation.duration` | Histogram / `s` | same |
17
+ | `db.client.connection.count` | ObservableGauge / `{connection}` | dependency, state `used`/`idle` |
18
+ | `app.operation.count` | Counter / `{operation}` | operation, status |
19
+ | `app.operation.duration` | Histogram / `s` | operation, status |
20
+ | `app.*` domain counters | Counter / `1` | operation, status |
21
+ | `app.*.duration` domain durations | Histogram / `s` | operation, status |
22
+ | `process.cpu.time` | ObservableCounter / `s` | none |
23
+ | `process.uptime` | ObservableGauge / `s` | none |
24
+ | `process.memory.peak_usage` | ObservableGauge / `By` | none |
25
+ | `process.thread.count` | ObservableGauge / `{thread}` | none |
26
+
27
+ Actual HTTP label names are `http.request.method`, `http.route`,
28
+ `http.response.status_code`, `response.outcome`, `error.type`. Outcomes: `completed`,
29
+ `cancelled`, `disconnected`, `error`. Error types: `timeout`, `cancelled`,
30
+ `connection_error`, `internal_error`. Other instruments use `dependency`, `operation`,
31
+ `status`, `state` as listed. Unknown methods become `_OTHER`; an unresolved route becomes
32
+ `__unresolved__`. Raw URL paths and request/trace/user/document IDs are never metric labels.
33
+
34
+ All duration histograms have finite boundaries in seconds:
35
+ `.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 30, 60, 120, 300`, then +Inf.
36
+
37
+ ## Measurement boundaries
38
+
39
+ - Server: ASGI application entry to return/exception, including streaming and application
40
+ background work. One measurement per HTTP invocation. Final status is captured only after
41
+ response-start is successfully sent. Informational 1xx messages do not finish or add
42
+ requests. Cancellation before headers has no invented status. Runtime/proxy failures
43
+ outside the ASGI application require platform telemetry; WebSockets are not HTTP requests.
44
+ - Client: transport request start to response headers or transport error. Response stream
45
+ consumption is outside this initial client duration/span. Explicitly name dependencies;
46
+ neither destinations nor query strings become telemetry attributes.
47
+ - SQL: cursor execution start to success or error. Does not include acquiring a connection,
48
+ fetching streamed results or transaction duration. Pool counters cover QueuePool and its
49
+ async variant, not NullPool or external poolers. Replacing an engine's pool requires
50
+ reinstrumenting a new engine; process memory is peak RSS, not current heap usage.
51
+ - Local process signals target the macOS/Linux runtimes used by 021. They do not claim
52
+ container-wide saturation, external database capacity or platform-wide health.
53
+ - HTTP request/span resource identity and structured context are library-generated.
54
+ Domain callers are responsible for using static instrument names and safe approved fields.
55
+
56
+ ## Migration mapping (consumer PRs)
57
+
58
+ | Current signal | New signal / change |
59
+ | --- | --- |
60
+ | API `http_requests_total` | `http.server.request.count`; normalized route; real final response |
61
+ | API `http_request_duration_seconds` | `http.server.request.duration`; full ASGI duration and longer buckets |
62
+ | API Prometheus business helpers | `app.operation.*` / explicit `app.*`; operation and result remain separate |
63
+ | Brain request count/duration | middleware observes errors and streaming as well as successful handlers |
64
+ | Brain histograms without units | durations use seconds; convert existing millisecond observations |
65
+ | Existing structlog setup | one common stdout JSON configuration; raw exception strings removed |
66
+ | Existing `/health` / `/ready` | opt-in migration after checking monitors and auth exemptions |
67
+
68
+ OpenTelemetry backends may translate dotted names to Prometheus-style names and suffixes.
69
+ Validate actual ingestion names/queries in staging before changing dashboards or retiring
70
+ `/metrics`. The package does not create dashboards, alerting, auth, quotas or business logic.
71
+ Logs stay in Vercel; internal agent traces and LLM token/cost instrumentation remain excluded.
72
+
73
+ ## Safe log diagnostics
74
+
75
+ Domain correlation in logs accepts only UUID objects/strings for `brain_id`, `job_id`,
76
+ `file_id`, `file_version_id`, `entity_id`, `event_id` and `correlation_id`. Values are
77
+ normalized into JSON and `message`; invalid values are dropped. The metric attribute
78
+ allowlist is unchanged and excludes these IDs.
79
+
80
+ When `exc_info` supplies an exception (instance, tuple or `True` inside an exception
81
+ handler), the formatter derives `error_type` and `exception` entries with `type`,
82
+ `frames` (`file` basename, `function`, `line`) and `frames_truncated`. It follows at most
83
+ 8 causes/unsuppressed contexts and retains the nearest 32 frames per exception; cycles
84
+ and longer chains set `exception_truncated`. Exception-group members are not expanded.
85
+ Type/function names are limited to 128 characters and basenames to 256. No exception
86
+ message, notes, source lines, locals, absolute directories or arbitrary diagnostic extras
87
+ are emitted. This applies to structlog, stdlib and Uvicorn, including unhandled ASGI
88
+ failure logs. Existing explicitly supplied `error_type` is retained only when there is
89
+ no actual exception to derive it from. No traceback metadata is added to spans/metrics.
90
+
91
+ ## Probes and correlation
92
+
93
+ Both routes stay public and registered after adoption:
94
+
95
+ | Route / result | HTTP | JSON |
96
+ | --- | --- | --- |
97
+ | `/health`, process alive | 200 | `{"status":"ok"}` |
98
+ | `/ready`, all declared checks succeed | 200 | `{"status":"ok","checks":{"database":"ok"}}` |
99
+ | `/ready`, any check fails or times out | 503 | `{"status":"unavailable","checks":{"database":"unavailable"}}` |
100
+
101
+ The check names above are examples; each consumer declares its dependencies. A timed-out
102
+ check is `timeout`. `/ready` never returns `status: ready`. Dependency monitors must use
103
+ its HTTP status; `/health` remains 200 when a dependency is down. A consumer that accepts
104
+ disabled adapters as available must verify its intended provider configuration separately.
105
+
106
+ Inbound UUID request IDs are preserved; missing or invalid IDs are replaced and echoed in
107
+ the response. Correlate using that returned value. `http_request(..., headers=...)` mutates
108
+ the supplied headers, replaces W3C trace context case-insensitively and propagates the
109
+ current validated request ID. The Vercel extra is required for post-response export there.
110
+
111
+ ## Consumer adapters
112
+
113
+ The optional `prometheus` extra and `setup_observability(..., prometheus=True)` add a
114
+ Prometheus reader over the same instruments; `obs.prometheus_latest()` exposes its private
115
+ registry. No process-global Prometheus registry or duplicate observations are introduced.
116
+
117
+ `increment`/`observe` accept approved static domain `attributes`: event, code, scope,
118
+ permission, action, reason, mode, channel, provider, dry_run and error_type. Unknown keys
119
+ (including IDs) are omitted; operation and status remain distinct. Callers must use static
120
+ values, not user-provided labels. `observe` defaults to seconds; unit `1` supports existing
121
+ scalar distributions and `USD` preserves existing cost observations. Units cannot change
122
+ for an existing instrument. Only duration instruments use the duration buckets.
123
+
124
+ `obs.http_request(method=..., dependency=..., headers=...)` observes a service-owned HTTP
125
+ call; set its yielded attributes' `http.response.status_code` on success. Wrapping the
126
+ complete HTTPX request also includes reading its body. Transport adapters retain their
127
+ headers-only boundary. Do not combine the two around the same HTTP request.
@@ -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.