tp-trace 0.2.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. tp_trace-0.4.0/PKG-INFO +177 -0
  2. tp_trace-0.4.0/README.md +145 -0
  3. {tp_trace-0.2.0 → tp_trace-0.4.0}/pyproject.toml +1 -1
  4. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/__init__.py +12 -20
  5. tp_trace-0.4.0/src/tp_trace/compat/__init__.py +1 -0
  6. tp_trace-0.4.0/src/tp_trace/compat/attributes.py +191 -0
  7. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/config.py +1 -0
  8. tp_trace-0.4.0/src/tp_trace/exporter.py +280 -0
  9. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/cache.py +5 -1
  10. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/middleware.py +114 -1
  11. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/request.py +104 -71
  12. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/view.py +5 -5
  13. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/postgres/cursor.py +5 -3
  14. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/metrics.py +233 -195
  15. tp_trace-0.4.0/src/tp_trace/normalize.py +130 -0
  16. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/route_context.py +2 -97
  17. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/sanitize.py +126 -23
  18. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/tracing.py +8 -2
  19. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/version.py +1 -1
  20. tp_trace-0.4.0/src/tp_trace.egg-info/PKG-INFO +177 -0
  21. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace.egg-info/SOURCES.txt +6 -2
  22. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_django.py +203 -28
  23. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_django_migration_regressions.py +6 -18
  24. tp_trace-0.4.0/tests/test_django_safety_regressions.py +106 -0
  25. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_init.py +219 -1
  26. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_metrics.py +162 -273
  27. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_n_plus_one.py +55 -8
  28. tp_trace-0.4.0/tests/test_n_plus_one_dashboard_contract.py +290 -0
  29. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_postgres.py +18 -0
  30. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_red_comparison.py +2 -2
  31. tp_trace-0.4.0/tests/test_red_dashboard_contract.py +698 -0
  32. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_safety.py +165 -1
  33. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_sample_telemetry.py +1 -1
  34. tp_trace-0.4.0/tests/test_sanitization_regressions.py +164 -0
  35. tp_trace-0.4.0/tests/test_shared_config.py +57 -0
  36. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_traffic_generator.py +1 -1
  37. tp_trace-0.2.0/PKG-INFO +0 -67
  38. tp_trace-0.2.0/README.md +0 -35
  39. tp_trace-0.2.0/src/tp_trace/exporter.py +0 -228
  40. tp_trace-0.2.0/src/tp_trace/red.py +0 -265
  41. tp_trace-0.2.0/src/tp_trace.egg-info/PKG-INFO +0 -67
  42. tp_trace-0.2.0/tests/test_n_plus_one_dashboard_contract.py +0 -173
  43. tp_trace-0.2.0/tests/test_red.py +0 -817
  44. tp_trace-0.2.0/tests/test_red_dashboard_contract.py +0 -345
  45. {tp_trace-0.2.0 → tp_trace-0.4.0}/setup.cfg +0 -0
  46. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/config_access.py +0 -0
  47. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/__init__.py +0 -0
  48. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/base.py +0 -0
  49. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/boto/__init__.py +0 -0
  50. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/boto/integration.py +0 -0
  51. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/celery/__init__.py +0 -0
  52. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/celery/context.py +0 -0
  53. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/celery/instrumentor.py +0 -0
  54. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/celery/integration.py +0 -0
  55. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/__init__.py +0 -0
  56. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/auth.py +0 -0
  57. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/compat.py +0 -0
  58. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/integration.py +0 -0
  59. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/django/template.py +0 -0
  60. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/manager.py +0 -0
  61. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/postgres/__init__.py +0 -0
  62. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/postgres/integration.py +0 -0
  63. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/redis/__init__.py +0 -0
  64. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/redis/integration.py +0 -0
  65. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/requests/__init__.py +0 -0
  66. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/requests/client.py +0 -0
  67. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/integrations/requests/integration.py +0 -0
  68. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/propagator.py +0 -0
  69. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/safety.py +0 -0
  70. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace/sampler.py +0 -0
  71. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace.egg-info/dependency_links.txt +0 -0
  72. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace.egg-info/requires.txt +0 -0
  73. {tp_trace-0.2.0 → tp_trace-0.4.0}/src/tp_trace.egg-info/top_level.txt +0 -0
  74. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_base_integration.py +0 -0
  75. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_boto.py +0 -0
  76. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_celery_integration.py +0 -0
  77. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_celery_probe.py +0 -0
  78. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_django_advanced.py +0 -0
  79. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_redis.py +0 -0
  80. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_requests.py +0 -0
  81. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_sampling_rules.py +0 -0
  82. {tp_trace-0.2.0 → tp_trace-0.4.0}/tests/test_smoke_probe.py +0 -0
@@ -0,0 +1,177 @@
1
+ Metadata-Version: 2.4
2
+ Name: tp_trace
3
+ Version: 0.4.0
4
+ Summary: tp_trace: High-performance Python Observability SDK for OpenTelemetry
5
+ Requires-Python: >=3.8
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: opentelemetry-api>=1.20.0
8
+ Requires-Dist: opentelemetry-sdk>=1.20.0
9
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.20.0
10
+ Requires-Dist: opentelemetry-instrumentation-requests>=0.44b0
11
+ Requires-Dist: opentelemetry-instrumentation-psycopg2>=0.44b0
12
+ Requires-Dist: opentelemetry-instrumentation-redis>=0.44b0
13
+ Requires-Dist: opentelemetry-instrumentation-botocore>=0.44b0
14
+ Requires-Dist: opentelemetry-instrumentation-celery>=0.54b1
15
+ Requires-Dist: opentelemetry-instrumentation-django>=0.44b0
16
+ Requires-Dist: wrapt>=1.14.0
17
+ Requires-Dist: urllib3<2,>=1.26.0; python_version < "3.9"
18
+ Provides-Extra: django
19
+ Requires-Dist: django>=4.2; extra == "django"
20
+ Requires-Dist: opentelemetry-instrumentation-django>=0.44b0; extra == "django"
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
23
+ Requires-Dist: botocore>=1.37.38; extra == "dev"
24
+ Requires-Dist: build>=1.0.0; extra == "dev"
25
+ Requires-Dist: requests>=2.25.0; extra == "dev"
26
+ Requires-Dist: redis>=3.5.0; extra == "dev"
27
+ Requires-Dist: celery>=5.0; extra == "dev"
28
+ Requires-Dist: django>=4.2; extra == "dev"
29
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
30
+ Requires-Dist: mypy>=1.0.0; python_version >= "3.10" and extra == "dev"
31
+ Requires-Dist: pre-commit>=3.0.0; extra == "dev"
32
+
33
+ # tp_trace
34
+
35
+ `tp_trace` is a production Python APM library built on OpenTelemetry. It provides distributed tracing and native RED (Rate, Errors, Duration) metrics instrumentation for Django, PostgreSQL, Redis, Celery, and HTTP clients, paired with a complete local development observability stack.
36
+
37
+ ---
38
+
39
+ ## Repository Structure
40
+
41
+ ```text
42
+ tp_trace/
43
+ ├── src/tp_trace/ # Core Python SDK and framework integrations
44
+ ├── config/ # Shared canonical configuration (Collector, Tempo, Prometheus)
45
+ ├── dev/ # Local development stack (docker-compose.yml and dev configs)
46
+ │ └── sample-app/ # Instrumented Django sample application and traffic generator
47
+ ├── setup/ # Standalone Tempo trace store deployment (Docker Compose)
48
+ ├── ansible/ # Ansible playbooks and roles for fleet Collector deployment
49
+ ├── grafana/ # Canonical Grafana dashboards and datasource provisioning
50
+ ├── docs/ # Core documentation
51
+ │ ├── 01-basics.md # Observability concepts (traces, metrics, context propagation)
52
+ │ ├── 02-architecture.md # End-to-end lifecycle from tp_trace.init() to Grafana
53
+ │ └── 03-integration.md # SDK setup, Docker Tempo setup, and Ansible Collector setup
54
+ └── tests/ # SDK test suite and e2e validation probes
55
+ ```
56
+
57
+ ---
58
+
59
+ ## Local Setup
60
+
61
+ ### Prerequisites
62
+
63
+ - Docker with Docker Compose support
64
+ - Python 3.8+ (for running the host SDK; Python 3.10+ required for `make lint`)
65
+
66
+ ### Start the Local Observability Stack
67
+
68
+ From the repository root:
69
+
70
+ ```bash
71
+ # 1. Copy local environment defaults
72
+ cp .env.example .env
73
+
74
+ # 2. Set up host virtual environment and install development tools
75
+ make install
76
+
77
+ # 3. Validate shared configuration files
78
+ make check-config
79
+ make check-collector-config
80
+
81
+ # 4. Build images and start the local services
82
+ make rebuild
83
+ ```
84
+
85
+ > **Note:** Root Makefile commands target `dev/docker-compose.yml` automatically. If you modify application dependencies or Dockerfiles, run `make rebuild`. For everyday restarts without rebuilding images, use `make up`.
86
+
87
+ ---
88
+
89
+ ## How to Work With It
90
+
91
+ ### Service Endpoints
92
+
93
+ Once `make rebuild` or `make up` completes, local services are accessible at:
94
+
95
+ | Service | Host URL / Port | Notes |
96
+ | --- | --- | --- |
97
+ | **Sample Django App** | <http://localhost:8002/api/> | Instrumented Django application |
98
+ | **Grafana** | <http://localhost:3001> | Anonymous admin access enabled |
99
+ | **Prometheus** | <http://localhost:9090> | TSDB metrics engine |
100
+ | **Tempo Query API** | <http://localhost:3200> | Trace store query API |
101
+ | **Tempo OTLP/gRPC** | `localhost:4327` | Traces ingress |
102
+ | **Collector OTLP** | `localhost:4318` (HTTP) / `4317` (gRPC) | Application telemetry ingress |
103
+ | **Collector Health** | <http://localhost:13133/> | Health probe endpoint |
104
+ | **MinIO Console** | <http://localhost:9003> | S3-compatible trace object storage |
105
+
106
+ ### Generate and Inspect Telemetry
107
+
108
+ 1. **Send synthetic traffic** to the sample application:
109
+ ```bash
110
+ # Run standard traffic generator workload
111
+ make traffic
112
+
113
+ # Or run specific workload flags
114
+ make traffic ARGS='--count 20 --redis --http'
115
+ ```
116
+
117
+ 2. **Run end-to-end smoke verification**:
118
+ ```bash
119
+ make smoke
120
+ ```
121
+ `make smoke` verifies that spans and metrics have reached Prometheus and Tempo storage.
122
+
123
+ 3. **View Dashboards in Grafana**:
124
+ - Open <http://localhost:3001>.
125
+ - Navigate to **Dashboards > TP Trace Dashboards**.
126
+ - Filter by Project: `otel-sample`, Cluster: `Dummy`.
127
+ - Inspect request rates, error ratios, latency distributions, and trace waterfalls.
128
+
129
+ ### Managing the Stack
130
+
131
+ ```bash
132
+ # Check container status
133
+ make ps
134
+
135
+ # View service logs
136
+ make logs SERVICE=sample-app
137
+ make logs SERVICE=otel-collector
138
+
139
+ # Restart a specific service (e.g. after changing collector config)
140
+ make restart SERVICE=otel-collector
141
+
142
+ # Stop services (preserves database and trace volumes)
143
+ make down
144
+
145
+ # Complete teardown (removes all volumes and persistent data)
146
+ make nuke
147
+ ```
148
+
149
+ ---
150
+
151
+ ## Shared Telemetry Configuration (`config/`)
152
+
153
+ To prevent drift between development and production, canonical service configurations reside in `config/`:
154
+
155
+ | File | Shared Usage |
156
+ | --- | --- |
157
+ | `config/otel-collector.yaml` | Mounted by local Compose; copied by Ansible to production application servers |
158
+ | `config/tempo.yaml` | Mounted by local Compose; mounted by standalone Tempo in `setup/` |
159
+ | `config/prometheus.yml` | Mounted by local Compose; reference scrape configuration for production Prometheus |
160
+
161
+ The Collector uses `${env:VAR_NAME}` substitutions for endpoints and identities. Local Compose provides environment variables through `.env` and `dev/docker-compose.yml`, while Ansible injects inventory variables during fleet deployment.
162
+
163
+ To validate configuration syntax across all environments:
164
+
165
+ ```bash
166
+ make check-config
167
+ make check-collector-config
168
+ docker compose -f setup/docker-compose.yml config --quiet
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Documentation
174
+
175
+ - **[01. Observability Basics](docs/01-basics.md)**: Fundamental observability concepts — traces, spans, RED metrics, context propagation, and cardinality.
176
+ - **[02. Architecture](docs/02-architecture.md)**: Complete lifecycle walkthrough from `tp_trace.init()` to metrics and traces rendered in Grafana.
177
+ - **[03. Integration and Deployment](docs/03-integration.md)**: Application SDK integration, Docker Tempo setup, and Ansible fleet Collector deployment.
@@ -0,0 +1,145 @@
1
+ # tp_trace
2
+
3
+ `tp_trace` is a production Python APM library built on OpenTelemetry. It provides distributed tracing and native RED (Rate, Errors, Duration) metrics instrumentation for Django, PostgreSQL, Redis, Celery, and HTTP clients, paired with a complete local development observability stack.
4
+
5
+ ---
6
+
7
+ ## Repository Structure
8
+
9
+ ```text
10
+ tp_trace/
11
+ ├── src/tp_trace/ # Core Python SDK and framework integrations
12
+ ├── config/ # Shared canonical configuration (Collector, Tempo, Prometheus)
13
+ ├── dev/ # Local development stack (docker-compose.yml and dev configs)
14
+ │ └── sample-app/ # Instrumented Django sample application and traffic generator
15
+ ├── setup/ # Standalone Tempo trace store deployment (Docker Compose)
16
+ ├── ansible/ # Ansible playbooks and roles for fleet Collector deployment
17
+ ├── grafana/ # Canonical Grafana dashboards and datasource provisioning
18
+ ├── docs/ # Core documentation
19
+ │ ├── 01-basics.md # Observability concepts (traces, metrics, context propagation)
20
+ │ ├── 02-architecture.md # End-to-end lifecycle from tp_trace.init() to Grafana
21
+ │ └── 03-integration.md # SDK setup, Docker Tempo setup, and Ansible Collector setup
22
+ └── tests/ # SDK test suite and e2e validation probes
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Local Setup
28
+
29
+ ### Prerequisites
30
+
31
+ - Docker with Docker Compose support
32
+ - Python 3.8+ (for running the host SDK; Python 3.10+ required for `make lint`)
33
+
34
+ ### Start the Local Observability Stack
35
+
36
+ From the repository root:
37
+
38
+ ```bash
39
+ # 1. Copy local environment defaults
40
+ cp .env.example .env
41
+
42
+ # 2. Set up host virtual environment and install development tools
43
+ make install
44
+
45
+ # 3. Validate shared configuration files
46
+ make check-config
47
+ make check-collector-config
48
+
49
+ # 4. Build images and start the local services
50
+ make rebuild
51
+ ```
52
+
53
+ > **Note:** Root Makefile commands target `dev/docker-compose.yml` automatically. If you modify application dependencies or Dockerfiles, run `make rebuild`. For everyday restarts without rebuilding images, use `make up`.
54
+
55
+ ---
56
+
57
+ ## How to Work With It
58
+
59
+ ### Service Endpoints
60
+
61
+ Once `make rebuild` or `make up` completes, local services are accessible at:
62
+
63
+ | Service | Host URL / Port | Notes |
64
+ | --- | --- | --- |
65
+ | **Sample Django App** | <http://localhost:8002/api/> | Instrumented Django application |
66
+ | **Grafana** | <http://localhost:3001> | Anonymous admin access enabled |
67
+ | **Prometheus** | <http://localhost:9090> | TSDB metrics engine |
68
+ | **Tempo Query API** | <http://localhost:3200> | Trace store query API |
69
+ | **Tempo OTLP/gRPC** | `localhost:4327` | Traces ingress |
70
+ | **Collector OTLP** | `localhost:4318` (HTTP) / `4317` (gRPC) | Application telemetry ingress |
71
+ | **Collector Health** | <http://localhost:13133/> | Health probe endpoint |
72
+ | **MinIO Console** | <http://localhost:9003> | S3-compatible trace object storage |
73
+
74
+ ### Generate and Inspect Telemetry
75
+
76
+ 1. **Send synthetic traffic** to the sample application:
77
+ ```bash
78
+ # Run standard traffic generator workload
79
+ make traffic
80
+
81
+ # Or run specific workload flags
82
+ make traffic ARGS='--count 20 --redis --http'
83
+ ```
84
+
85
+ 2. **Run end-to-end smoke verification**:
86
+ ```bash
87
+ make smoke
88
+ ```
89
+ `make smoke` verifies that spans and metrics have reached Prometheus and Tempo storage.
90
+
91
+ 3. **View Dashboards in Grafana**:
92
+ - Open <http://localhost:3001>.
93
+ - Navigate to **Dashboards > TP Trace Dashboards**.
94
+ - Filter by Project: `otel-sample`, Cluster: `Dummy`.
95
+ - Inspect request rates, error ratios, latency distributions, and trace waterfalls.
96
+
97
+ ### Managing the Stack
98
+
99
+ ```bash
100
+ # Check container status
101
+ make ps
102
+
103
+ # View service logs
104
+ make logs SERVICE=sample-app
105
+ make logs SERVICE=otel-collector
106
+
107
+ # Restart a specific service (e.g. after changing collector config)
108
+ make restart SERVICE=otel-collector
109
+
110
+ # Stop services (preserves database and trace volumes)
111
+ make down
112
+
113
+ # Complete teardown (removes all volumes and persistent data)
114
+ make nuke
115
+ ```
116
+
117
+ ---
118
+
119
+ ## Shared Telemetry Configuration (`config/`)
120
+
121
+ To prevent drift between development and production, canonical service configurations reside in `config/`:
122
+
123
+ | File | Shared Usage |
124
+ | --- | --- |
125
+ | `config/otel-collector.yaml` | Mounted by local Compose; copied by Ansible to production application servers |
126
+ | `config/tempo.yaml` | Mounted by local Compose; mounted by standalone Tempo in `setup/` |
127
+ | `config/prometheus.yml` | Mounted by local Compose; reference scrape configuration for production Prometheus |
128
+
129
+ The Collector uses `${env:VAR_NAME}` substitutions for endpoints and identities. Local Compose provides environment variables through `.env` and `dev/docker-compose.yml`, while Ansible injects inventory variables during fleet deployment.
130
+
131
+ To validate configuration syntax across all environments:
132
+
133
+ ```bash
134
+ make check-config
135
+ make check-collector-config
136
+ docker compose -f setup/docker-compose.yml config --quiet
137
+ ```
138
+
139
+ ---
140
+
141
+ ## Documentation
142
+
143
+ - **[01. Observability Basics](docs/01-basics.md)**: Fundamental observability concepts — traces, spans, RED metrics, context propagation, and cardinality.
144
+ - **[02. Architecture](docs/02-architecture.md)**: Complete lifecycle walkthrough from `tp_trace.init()` to metrics and traces rendered in Grafana.
145
+ - **[03. Integration and Deployment](docs/03-integration.md)**: Application SDK integration, Docker Tempo setup, and Ansible fleet Collector deployment.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tp_trace"
7
- version = "0.2.0"
7
+ version = "0.4.0"
8
8
  description = "tp_trace: High-performance Python Observability SDK for OpenTelemetry"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -13,7 +13,7 @@ from opentelemetry import trace
13
13
  from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
14
14
  from opentelemetry.sdk.resources import Resource
15
15
  from opentelemetry.sdk.trace import TracerProvider, SpanProcessor
16
- from opentelemetry.sdk.trace.export import BatchSpanProcessor, SimpleSpanProcessor, SpanExporter
16
+ from opentelemetry.sdk.trace.export import SpanExporter
17
17
  from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, Sampler
18
18
  from opentelemetry.trace import get_current_span, get_tracer
19
19
  from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
@@ -21,8 +21,7 @@ from opentelemetry.baggage.propagation import W3CBaggagePropagator
21
21
  from opentelemetry.propagate import set_global_textmap
22
22
 
23
23
  from tp_trace.config import SDKConfig
24
- from tp_trace.exporter import SafeSpanExporter
25
- from tp_trace.red import RedSpanProcessor, SampledOnlySpanProcessor
24
+ from tp_trace.exporter import AllSpansBatchSpanProcessor, AllSpansSimpleSpanProcessor, SafeSpanExporter, batch_export_options
26
25
  from tp_trace.route_context import RouteEnrichingSpanProcessor
27
26
  from tp_trace.integrations import BaseIntegration, get_integration_manager
28
27
  from tp_trace.sanitize import sanitize_query_string, sanitize_sql, sanitize_url
@@ -42,8 +41,6 @@ __all__ = [
42
41
  "BaseIntegration",
43
42
  "get_integration_manager",
44
43
  "RouteEnrichingSpanProcessor",
45
- "RedSpanProcessor",
46
- "SampledOnlySpanProcessor",
47
44
  "SafeSpanExporter",
48
45
  ]
49
46
 
@@ -200,12 +197,6 @@ def init(
200
197
  except Exception as exc:
201
198
  logger.debug("tp_trace: Failed to register RouteEnrichingSpanProcessor: %s", exc)
202
199
 
203
- # Register RED metrics aggregator: computes 100% RED metrics for all dependencies
204
- try:
205
- provider.add_span_processor(RedSpanProcessor())
206
- except Exception as exc:
207
- logger.debug("tp_trace: Failed to register RedSpanProcessor: %s", exc)
208
-
209
200
  # Configure Exporter and Processor if not disabled
210
201
  if not config.disabled:
211
202
  if exporter is None:
@@ -233,17 +224,18 @@ def init(
233
224
 
234
225
  if span_processor is None:
235
226
  if export_batch:
236
- span_processor = BatchSpanProcessor(
227
+ batch_options = batch_export_options()
228
+ span_processor = AllSpansBatchSpanProcessor(
237
229
  safe_exporter,
238
- max_queue_size=2048,
239
- max_export_batch_size=256,
240
- schedule_delay_millis=1000,
230
+ max_queue_size=batch_options["max_queue_size"],
231
+ max_export_batch_size=batch_options["max_export_batch_size"],
232
+ schedule_delay_millis=batch_options["schedule_delay_millis"],
241
233
  )
242
234
  else:
243
- span_processor = SimpleSpanProcessor(safe_exporter)
235
+ span_processor = AllSpansSimpleSpanProcessor(safe_exporter)
244
236
 
245
- # Gate exports: only spans with trace_flags.sampled=True are serialized/transmitted
246
- provider.add_span_processor(SampledOnlySpanProcessor(span_processor))
237
+ # Export spans to local Collector (spanmetrics computes metrics; filter drops unsampled before Tempo)
238
+ provider.add_span_processor(span_processor)
247
239
 
248
240
  # Set as global tracer provider
249
241
  trace.set_tracer_provider(provider)
@@ -266,13 +258,13 @@ def init(
266
258
  except Exception as exc:
267
259
  logger.debug("Failed to auto-apply integrations during init: %s", exc)
268
260
 
269
- # Initialize independent RED metrics recorder
261
+ # Initialize custom metrics recorder
270
262
  try:
271
263
  from tp_trace.metrics import init_metrics
272
264
 
273
265
  init_metrics(config=config, metric_readers=metric_readers, resource=resource)
274
266
  except Exception as exc:
275
- logger.debug("tp_trace: Failed to initialize independent RED metrics: %s", exc)
267
+ logger.debug("tp_trace: Failed to initialize custom metrics: %s", exc)
276
268
 
277
269
  # Register shutdown on process exit exactly once
278
270
  global _ATEXIT_REGISTERED
@@ -0,0 +1 @@
1
+ """Compatibility shims for OpenTelemetry internals."""
@@ -0,0 +1,191 @@
1
+ """Compatibility layer for mutating span attributes across OTel SDK versions.
2
+
3
+ OpenTelemetry Python SDK exposes no public API to mutate attributes on an ended
4
+ ReadableSpan. tp_trace only does this as a last resort for third-party
5
+ instrumentors that add attributes after our control points. All access to
6
+ private internals goes through this module with version checks and a kill-switch.
7
+ """
8
+
9
+ import logging
10
+ import os
11
+ from typing import Any, Dict, MutableMapping, Optional, Tuple
12
+
13
+ logger = logging.getLogger("tp_trace.compat.attributes")
14
+
15
+ try:
16
+ from importlib import metadata
17
+
18
+ _OTEL_SDK_VERSION = metadata.version("opentelemetry-sdk")
19
+ except Exception:
20
+ _OTEL_SDK_VERSION = "unknown"
21
+
22
+
23
+ def _parse_version(v: str) -> Optional[Tuple[int, int, int]]:
24
+ if not v or v == "unknown":
25
+ return None
26
+ # Strip common suffixes like b0, rc1
27
+ try:
28
+ # Take only digits and dots
29
+ parts = []
30
+ for token in v.replace("-", ".").replace("_", ".").split("."):
31
+ # Extract leading digits
32
+ num = ""
33
+ for ch in token:
34
+ if ch.isdigit():
35
+ num += ch
36
+ else:
37
+ break
38
+ if num:
39
+ parts.append(int(num))
40
+ if len(parts) >= 3:
41
+ break
42
+ if len(parts) >= 2:
43
+ while len(parts) < 3:
44
+ parts.append(0)
45
+ return (parts[0], parts[1], parts[2])
46
+ except Exception:
47
+ pass
48
+ return None
49
+
50
+
51
+ _OTEL_SDK_VER_TUPLE = _parse_version(_OTEL_SDK_VERSION)
52
+
53
+ _ATTR_MUTATION_DISABLED = os.environ.get("TP_TRACE_DISABLE_ATTR_MUTATION", "").strip().lower() in (
54
+ "1",
55
+ "true",
56
+ "yes",
57
+ "on",
58
+ )
59
+ _WARNED_DISABLED = False
60
+
61
+
62
+ def _sdk_version_ok() -> bool:
63
+ global _WARNED_DISABLED
64
+ if _ATTR_MUTATION_DISABLED:
65
+ if not _WARNED_DISABLED:
66
+ logger.debug("tp_trace: attribute mutation disabled via TP_TRACE_DISABLE_ATTR_MUTATION")
67
+ _WARNED_DISABLED = True
68
+ return False
69
+ if _OTEL_SDK_VER_TUPLE is None:
70
+ if not _WARNED_DISABLED:
71
+ logger.debug("tp_trace: could not parse opentelemetry-sdk version; disabling ended-span attribute mutation")
72
+ _WARNED_DISABLED = True
73
+ return False
74
+ try:
75
+ major, minor, _ = _OTEL_SDK_VER_TUPLE
76
+ if (major, minor) < (1, 20):
77
+ if not _WARNED_DISABLED:
78
+ logger.debug("tp_trace: opentelemetry-sdk %s too old for ended-span mutation", _OTEL_SDK_VERSION)
79
+ _WARNED_DISABLED = True
80
+ return False
81
+ # Don't fail closed on newer versions - rely on structure checks
82
+ return True
83
+ except Exception:
84
+ if not _WARNED_DISABLED:
85
+ logger.debug("tp_trace: attribute mutation disabled due to version check failure")
86
+ _WARNED_DISABLED = True
87
+ return False
88
+
89
+
90
+ def _is_recording_span(span: Any) -> bool:
91
+ try:
92
+ if hasattr(span, "is_recording") and span.is_recording():
93
+ return True
94
+ except Exception:
95
+ pass
96
+ return False
97
+
98
+
99
+ def _get_attrs_obj(span: Any) -> Any:
100
+ attrs = getattr(span, "_attributes", None)
101
+ if attrs is not None:
102
+ return attrs
103
+ attrs = getattr(span, "attributes", None)
104
+ return attrs
105
+
106
+
107
+ def _find_mutable_dict(attrs_obj: Any) -> Optional[MutableMapping]:
108
+ if attrs_obj is None:
109
+ return None
110
+ if isinstance(attrs_obj, dict):
111
+ return attrs_obj
112
+ # Prefer known internal names for BoundedAttributes
113
+ for name in ("_dict",):
114
+ try:
115
+ cand = getattr(attrs_obj, name, None)
116
+ if isinstance(cand, dict):
117
+ return cand
118
+ if isinstance(cand, MutableMapping):
119
+ return cand
120
+ except Exception:
121
+ continue
122
+ return None
123
+
124
+
125
+ def get_mutable_attributes(span: Any) -> Optional[MutableMapping]:
126
+ """Get a mutable attribute mapping if possible."""
127
+ if not _sdk_version_ok():
128
+ return None
129
+ attrs_obj = _get_attrs_obj(span)
130
+ target = _find_mutable_dict(attrs_obj)
131
+ if target is not None:
132
+ return target
133
+ return None
134
+
135
+
136
+ def set_attribute_safe(span: Any, key: str, value: Any) -> bool:
137
+ # For recording spans, use public API. For ended spans, write via compat first.
138
+ try:
139
+ if _is_recording_span(span):
140
+ try:
141
+ if hasattr(span, "set_attribute"):
142
+ span.set_attribute(key, value)
143
+ return True
144
+ except Exception:
145
+ pass
146
+ return False
147
+ except Exception:
148
+ pass
149
+ target = get_mutable_attributes(span)
150
+ if target is not None:
151
+ try:
152
+ target[key] = value
153
+ return True
154
+ except Exception:
155
+ pass
156
+ return False
157
+
158
+
159
+ def delete_attribute_safe(span: Any, key: str) -> bool:
160
+ target = get_mutable_attributes(span)
161
+ if target is None:
162
+ return False
163
+ try:
164
+ if key in target:
165
+ del target[key]
166
+ return True
167
+ except Exception:
168
+ pass
169
+ return False
170
+
171
+
172
+ def get_attributes_view(span: Any) -> Dict[str, Any]:
173
+ try:
174
+ attrs = getattr(span, "attributes", None)
175
+ if attrs is not None:
176
+ try:
177
+ return dict(attrs)
178
+ except Exception:
179
+ pass
180
+ except Exception:
181
+ pass
182
+ try:
183
+ attrs_obj = _get_attrs_obj(span)
184
+ if attrs_obj is not None:
185
+ try:
186
+ return dict(attrs_obj)
187
+ except Exception:
188
+ pass
189
+ except Exception:
190
+ pass
191
+ return {}
@@ -10,6 +10,7 @@ from tp_trace.version import __version__
10
10
 
11
11
  logger = logging.getLogger("tp_trace.config")
12
12
 
13
+
13
14
  # Deprecated inputs that name the *project* after a *service*. Warned once each so
14
15
  # operators learn the canonical name without log spam.
15
16
  _warned_project_aliases: set = set()