tp-trace 0.4.0__tar.gz → 0.4.2__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 (79) hide show
  1. {tp_trace-0.4.0 → tp_trace-0.4.2}/PKG-INFO +26 -21
  2. {tp_trace-0.4.0 → tp_trace-0.4.2}/README.md +24 -19
  3. {tp_trace-0.4.0 → tp_trace-0.4.2}/pyproject.toml +1 -1
  4. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/__init__.py +8 -0
  5. tp_trace-0.4.2/src/tp_trace/breakdown.py +346 -0
  6. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/metrics.py +171 -9
  7. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/version.py +1 -1
  8. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace.egg-info/PKG-INFO +26 -21
  9. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace.egg-info/SOURCES.txt +4 -0
  10. tp_trace-0.4.2/tests/test_dashboard_datasource_contract.py +53 -0
  11. tp_trace-0.4.2/tests/test_issue_routing.py +66 -0
  12. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_metrics.py +40 -1
  13. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_n_plus_one.py +19 -2
  14. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_n_plus_one_dashboard_contract.py +110 -24
  15. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_red_dashboard_contract.py +381 -96
  16. tp_trace-0.4.2/tests/test_request_breakdown.py +401 -0
  17. tp_trace-0.4.2/tests/test_shared_config.py +42 -0
  18. tp_trace-0.4.0/tests/test_shared_config.py +0 -57
  19. {tp_trace-0.4.0 → tp_trace-0.4.2}/setup.cfg +0 -0
  20. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/compat/__init__.py +0 -0
  21. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/compat/attributes.py +0 -0
  22. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/config.py +0 -0
  23. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/config_access.py +0 -0
  24. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/exporter.py +0 -0
  25. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/__init__.py +0 -0
  26. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/base.py +0 -0
  27. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/boto/__init__.py +0 -0
  28. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/boto/integration.py +0 -0
  29. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/celery/__init__.py +0 -0
  30. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/celery/context.py +0 -0
  31. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/celery/instrumentor.py +0 -0
  32. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/celery/integration.py +0 -0
  33. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/__init__.py +0 -0
  34. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/auth.py +0 -0
  35. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/cache.py +0 -0
  36. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/compat.py +0 -0
  37. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/integration.py +0 -0
  38. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/middleware.py +0 -0
  39. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/request.py +0 -0
  40. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/template.py +0 -0
  41. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/django/view.py +0 -0
  42. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/manager.py +0 -0
  43. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/postgres/__init__.py +0 -0
  44. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/postgres/cursor.py +0 -0
  45. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/postgres/integration.py +0 -0
  46. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/redis/__init__.py +0 -0
  47. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/redis/integration.py +0 -0
  48. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/requests/__init__.py +0 -0
  49. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/requests/client.py +0 -0
  50. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/integrations/requests/integration.py +0 -0
  51. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/normalize.py +0 -0
  52. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/propagator.py +0 -0
  53. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/route_context.py +0 -0
  54. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/safety.py +0 -0
  55. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/sampler.py +0 -0
  56. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/sanitize.py +0 -0
  57. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace/tracing.py +0 -0
  58. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace.egg-info/dependency_links.txt +0 -0
  59. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace.egg-info/requires.txt +0 -0
  60. {tp_trace-0.4.0 → tp_trace-0.4.2}/src/tp_trace.egg-info/top_level.txt +0 -0
  61. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_base_integration.py +0 -0
  62. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_boto.py +0 -0
  63. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_celery_integration.py +0 -0
  64. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_celery_probe.py +0 -0
  65. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_django.py +0 -0
  66. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_django_advanced.py +0 -0
  67. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_django_migration_regressions.py +0 -0
  68. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_django_safety_regressions.py +0 -0
  69. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_init.py +0 -0
  70. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_postgres.py +0 -0
  71. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_red_comparison.py +0 -0
  72. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_redis.py +0 -0
  73. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_requests.py +0 -0
  74. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_safety.py +0 -0
  75. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_sample_telemetry.py +0 -0
  76. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_sampling_rules.py +0 -0
  77. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_sanitization_regressions.py +0 -0
  78. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_smoke_probe.py +0 -0
  79. {tp_trace-0.4.0 → tp_trace-0.4.2}/tests/test_traffic_generator.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.1
2
2
  Name: tp_trace
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: tp_trace: High-performance Python Observability SDK for OpenTelemetry
5
5
  Requires-Python: >=3.8
6
6
  Description-Content-Type: text/markdown
@@ -41,16 +41,13 @@ Requires-Dist: pre-commit>=3.0.0; extra == "dev"
41
41
  ```text
42
42
  tp_trace/
43
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)
44
+ ├── dev/ # Local development stack (docker-compose.yml, otel-collector.yaml, dev configs)
46
45
  │ └── 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
46
  ├── grafana/ # Canonical Grafana dashboards and datasource provisioning
50
47
  ├── docs/ # Core documentation
51
48
  │ ├── 01-basics.md # Observability concepts (traces, metrics, context propagation)
52
49
  │ ├── 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
50
+ │ └── 03-integration.md # SDK setup and integration guide
54
51
  └── tests/ # SDK test suite and e2e validation probes
55
52
  ```
56
53
 
@@ -74,7 +71,7 @@ cp .env.example .env
74
71
  # 2. Set up host virtual environment and install development tools
75
72
  make install
76
73
 
77
- # 3. Validate shared configuration files
74
+ # 3. Validate local Compose and Collector configuration files
78
75
  make check-config
79
76
  make check-collector-config
80
77
 
@@ -148,30 +145,38 @@ make nuke
148
145
 
149
146
  ---
150
147
 
151
- ## Shared Telemetry Configuration (`config/`)
148
+ ## Local Telemetry Configuration (`dev/otel-collector.yaml`)
152
149
 
153
- To prevent drift between development and production, canonical service configurations reside in `config/`:
150
+ The local OpenTelemetry Collector pipeline configuration lives in `dev/otel-collector.yaml` and is mounted by `dev/docker-compose.yml`.
154
151
 
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 |
152
+ Local development service configurations for Tempo and Prometheus are synced dynamically from [testpress/observability-infra](https://github.com/testpress/observability-infra).
160
153
 
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.
154
+ The Collector uses `${env:VAR_NAME}` substitutions for endpoints and identities. Local Compose provides environment variables through `.env` and `dev/docker-compose.yml`.
162
155
 
163
- To validate configuration syntax across all environments:
156
+ To validate configuration syntax locally:
164
157
 
165
158
  ```bash
166
159
  make check-config
167
160
  make check-collector-config
168
- docker compose -f setup/docker-compose.yml config --quiet
169
161
  ```
170
162
 
171
163
  ---
172
164
 
173
165
  ## Documentation
174
166
 
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.
167
+ ### Working on tp_trace
168
+
169
+ 1. [Observability Basics](docs/01-basics.md) introduces the telemetry concepts
170
+ used throughout the codebase.
171
+ 2. [Architecture](docs/02-architecture.md) follows telemetry from the SDK to
172
+ Grafana and points to the code and configuration at each stage.
173
+
174
+ ### Using tp_trace in an application
175
+
176
+ 1. [Integrate tp_trace into a Django app](docs/03-integration.md) to configure
177
+ the SDK and verify that your application emits telemetry.
178
+ 2. [Investigate application services in Grafana](grafana/dashboards/README.md)
179
+ to diagnose slow requests, error spikes, and missing telemetry.
180
+
181
+ Fleet Collector deployment is managed in the `testpress` repository Ansible configuration.
182
+ Central observability server infrastructure (Tempo, Prometheus, Loki, Grafana) is managed in `observability-infra`.
@@ -9,16 +9,13 @@
9
9
  ```text
10
10
  tp_trace/
11
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)
12
+ ├── dev/ # Local development stack (docker-compose.yml, otel-collector.yaml, dev configs)
14
13
  │ └── 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
14
  ├── grafana/ # Canonical Grafana dashboards and datasource provisioning
18
15
  ├── docs/ # Core documentation
19
16
  │ ├── 01-basics.md # Observability concepts (traces, metrics, context propagation)
20
17
  │ ├── 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
18
+ │ └── 03-integration.md # SDK setup and integration guide
22
19
  └── tests/ # SDK test suite and e2e validation probes
23
20
  ```
24
21
 
@@ -42,7 +39,7 @@ cp .env.example .env
42
39
  # 2. Set up host virtual environment and install development tools
43
40
  make install
44
41
 
45
- # 3. Validate shared configuration files
42
+ # 3. Validate local Compose and Collector configuration files
46
43
  make check-config
47
44
  make check-collector-config
48
45
 
@@ -116,30 +113,38 @@ make nuke
116
113
 
117
114
  ---
118
115
 
119
- ## Shared Telemetry Configuration (`config/`)
116
+ ## Local Telemetry Configuration (`dev/otel-collector.yaml`)
120
117
 
121
- To prevent drift between development and production, canonical service configurations reside in `config/`:
118
+ The local OpenTelemetry Collector pipeline configuration lives in `dev/otel-collector.yaml` and is mounted by `dev/docker-compose.yml`.
122
119
 
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 |
120
+ Local development service configurations for Tempo and Prometheus are synced dynamically from [testpress/observability-infra](https://github.com/testpress/observability-infra).
128
121
 
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.
122
+ The Collector uses `${env:VAR_NAME}` substitutions for endpoints and identities. Local Compose provides environment variables through `.env` and `dev/docker-compose.yml`.
130
123
 
131
- To validate configuration syntax across all environments:
124
+ To validate configuration syntax locally:
132
125
 
133
126
  ```bash
134
127
  make check-config
135
128
  make check-collector-config
136
- docker compose -f setup/docker-compose.yml config --quiet
137
129
  ```
138
130
 
139
131
  ---
140
132
 
141
133
  ## Documentation
142
134
 
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.
135
+ ### Working on tp_trace
136
+
137
+ 1. [Observability Basics](docs/01-basics.md) introduces the telemetry concepts
138
+ used throughout the codebase.
139
+ 2. [Architecture](docs/02-architecture.md) follows telemetry from the SDK to
140
+ Grafana and points to the code and configuration at each stage.
141
+
142
+ ### Using tp_trace in an application
143
+
144
+ 1. [Integrate tp_trace into a Django app](docs/03-integration.md) to configure
145
+ the SDK and verify that your application emits telemetry.
146
+ 2. [Investigate application services in Grafana](grafana/dashboards/README.md)
147
+ to diagnose slow requests, error spikes, and missing telemetry.
148
+
149
+ Fleet Collector deployment is managed in the `testpress` repository Ansible configuration.
150
+ Central observability server infrastructure (Tempo, Prometheus, Loki, Grafana) is managed in `observability-infra`.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tp_trace"
7
- version = "0.4.0"
7
+ version = "0.4.2"
8
8
  description = "tp_trace: High-performance Python Observability SDK for OpenTelemetry"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -197,6 +197,14 @@ def init(
197
197
  except Exception as exc:
198
198
  logger.debug("tp_trace: Failed to register RouteEnrichingSpanProcessor: %s", exc)
199
199
 
200
+ if not config.disabled:
201
+ try:
202
+ from tp_trace.breakdown import RequestBreakdownSpanProcessor
203
+
204
+ provider.add_span_processor(RequestBreakdownSpanProcessor())
205
+ except Exception as exc:
206
+ logger.debug("tp_trace: Failed to register RequestBreakdownSpanProcessor: %s", exc)
207
+
200
208
  # Configure Exporter and Processor if not disabled
201
209
  if not config.disabled:
202
210
  if exporter is None:
@@ -0,0 +1,346 @@
1
+ """Exact per-request time breakdown tracking for Django HTTP requests."""
2
+
3
+ import logging
4
+ import threading
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+
7
+ from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor
8
+ from opentelemetry.trace import SpanKind, get_current_span
9
+
10
+ from tp_trace.compat.attributes import get_attributes_view
11
+
12
+ logger = logging.getLogger("tp_trace.breakdown")
13
+
14
+ BreakdownKey = Tuple[str, str, str] # (normalized_service, db_instance, db_connection_pool)
15
+ SpanInterval = Tuple[int, int, str, str, str] # (start_ns, end_ns, service, db_instance, db_pool)
16
+
17
+ _EXCLUDED_DEPENDENCY_SERVICES = frozenset({"", "django", "celery", "pgbouncer"})
18
+ _MAX_ACTIVE_REQUESTS = 10000
19
+ _MAX_INTERVALS_PER_REQUEST = 2000
20
+ _MAX_SPAN_PARENTS = 50000
21
+ _MAX_ANCESTOR_HOPS = 64
22
+
23
+
24
+ class _RequestBucket:
25
+ __slots__ = ("trace_id", "intervals", "dropped_intervals")
26
+
27
+ def __init__(self, trace_id: int) -> None:
28
+ self.trace_id = trace_id
29
+ self.intervals: List[SpanInterval] = []
30
+ self.dropped_intervals = 0
31
+
32
+
33
+ class RequestBreakdownSpanProcessor(SpanProcessor):
34
+ """Track child CLIENT span intervals per Django SERVER request and emit exact breakdown metrics."""
35
+
36
+ def __init__(
37
+ self,
38
+ max_active_requests: int = _MAX_ACTIVE_REQUESTS,
39
+ max_intervals_per_request: int = _MAX_INTERVALS_PER_REQUEST,
40
+ max_span_parents: int = _MAX_SPAN_PARENTS,
41
+ ) -> None:
42
+ self._lock = threading.Lock()
43
+ self._server_buckets: Dict[int, _RequestBucket] = {}
44
+ self._active_trace_counts: Dict[int, int] = {}
45
+ self._span_parents: Dict[int, int] = {}
46
+ self._max_active_requests = max(1, int(max_active_requests))
47
+ self._max_intervals_per_request = max(1, int(max_intervals_per_request))
48
+ self._max_span_parents = max(1, int(max_span_parents))
49
+
50
+ def on_start(self, span: Span, parent_context: Optional[Any] = None) -> None:
51
+ try:
52
+ ctx = _get_span_context(span)
53
+ trace_id = getattr(ctx, "trace_id", 0) if ctx is not None else 0
54
+ span_id = getattr(ctx, "span_id", 0) if ctx is not None else 0
55
+ if not trace_id or not span_id:
56
+ return
57
+
58
+ kind = _get_span_kind(span)
59
+ parent_span_id = _get_parent_span_id(span, parent_context)
60
+
61
+ evicted_parent = False
62
+ evicted_bucket = False
63
+ with self._lock:
64
+ if kind == SpanKind.SERVER:
65
+ if span_id not in self._server_buckets:
66
+ if len(self._server_buckets) >= self._max_active_requests:
67
+ oldest = self._server_buckets.pop(next(iter(self._server_buckets)))
68
+ self._decrement_trace_count_locked(oldest.trace_id)
69
+ evicted_bucket = True
70
+ self._server_buckets[span_id] = _RequestBucket(trace_id=trace_id)
71
+ self._active_trace_counts[trace_id] = self._active_trace_counts.get(trace_id, 0) + 1
72
+ evicted_parent = self._track_parent_locked(span_id, parent_span_id)
73
+ elif trace_id in self._active_trace_counts:
74
+ evicted_parent = self._track_parent_locked(span_id, parent_span_id)
75
+
76
+ if evicted_parent or evicted_bucket:
77
+ from tp_trace.metrics import record_request_time_breakdown_dropped
78
+
79
+ if evicted_parent:
80
+ record_request_time_breakdown_dropped(reason="parent_map_eviction", count=1)
81
+ if evicted_bucket:
82
+ record_request_time_breakdown_dropped(reason="server_bucket_eviction", count=1)
83
+ except Exception:
84
+ logger.debug("tp_trace: RequestBreakdownSpanProcessor.on_start failed", exc_info=True)
85
+
86
+ def on_end(self, span: ReadableSpan) -> None:
87
+ try:
88
+ ctx = _get_span_context(span)
89
+ trace_id = getattr(ctx, "trace_id", 0) if ctx is not None else 0
90
+ span_id = getattr(ctx, "span_id", 0) if ctx is not None else 0
91
+ if not trace_id or not span_id:
92
+ return
93
+
94
+ kind = _get_span_kind(span)
95
+ if kind == SpanKind.CLIENT:
96
+ self._record_client_span(trace_id, span_id, span)
97
+ elif kind == SpanKind.SERVER:
98
+ self._finalize_server_span(trace_id, span_id, span)
99
+ else:
100
+ with self._lock:
101
+ self._span_parents.pop(span_id, None)
102
+ except Exception:
103
+ logger.debug("tp_trace: RequestBreakdownSpanProcessor.on_end failed", exc_info=True)
104
+
105
+ def shutdown(self) -> None:
106
+ with self._lock:
107
+ self._server_buckets.clear()
108
+ self._active_trace_counts.clear()
109
+ self._span_parents.clear()
110
+
111
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
112
+ return True
113
+
114
+ def _record_client_span(self, trace_id: int, span_id: int, span: ReadableSpan) -> None:
115
+ direct_parent_id = _get_parent_span_id(span)
116
+ start_ns = getattr(span, "start_time", None)
117
+ end_ns = getattr(span, "end_time", None)
118
+ if start_ns is None or end_ns is None or end_ns <= start_ns:
119
+ with self._lock:
120
+ self._span_parents.pop(span_id, None)
121
+ return
122
+
123
+ with self._lock:
124
+ has_bucket = (
125
+ trace_id in self._active_trace_counts
126
+ and self._find_nearest_server_bucket_locked(span_id, direct_parent_id) is not None
127
+ )
128
+ if not has_bucket:
129
+ self._span_parents.pop(span_id, None)
130
+ return
131
+
132
+ attrs = get_attributes_view(span)
133
+ dep_service = _normalize_dependency_service(attrs)
134
+ if dep_service in _EXCLUDED_DEPENDENCY_SERVICES:
135
+ with self._lock:
136
+ self._span_parents.pop(span_id, None)
137
+ return
138
+
139
+ interval: SpanInterval = (
140
+ int(start_ns),
141
+ int(end_ns),
142
+ dep_service,
143
+ str(attrs.get("db.instance") or ""),
144
+ str(attrs.get("db.connection.pool") or ""),
145
+ )
146
+
147
+ with self._lock:
148
+ bucket = self._find_nearest_server_bucket_locked(span_id, direct_parent_id)
149
+ self._span_parents.pop(span_id, None)
150
+ if bucket is not None:
151
+ if len(bucket.intervals) < self._max_intervals_per_request:
152
+ bucket.intervals.append(interval)
153
+ else:
154
+ bucket.dropped_intervals += 1
155
+
156
+ def _finalize_server_span(self, trace_id: int, span_id: int, span: ReadableSpan) -> None:
157
+ with self._lock:
158
+ self._span_parents.pop(span_id, None)
159
+ bucket = self._server_buckets.pop(span_id, None)
160
+ if bucket is None:
161
+ return
162
+ self._decrement_trace_count_locked(trace_id)
163
+
164
+ attrs = get_attributes_view(span)
165
+ norm_svc = str(attrs.get("normalized.service") or "")
166
+ norm_op = str(attrs.get("normalized.operation") or "")
167
+ if norm_svc != "django" or norm_op.startswith("django.command."):
168
+ return
169
+
170
+ if bucket.dropped_intervals > 0:
171
+ logger.debug(
172
+ "tp_trace: request %s dropped %d client intervals beyond cap (%d)",
173
+ norm_op or span_id,
174
+ bucket.dropped_intervals,
175
+ self._max_intervals_per_request,
176
+ )
177
+ from tp_trace.metrics import record_request_time_breakdown_dropped
178
+
179
+ record_request_time_breakdown_dropped(
180
+ reason="interval_cap",
181
+ count=bucket.dropped_intervals,
182
+ normalized_service=norm_svc,
183
+ project_name=attrs.get("project_name"),
184
+ cluster_name=attrs.get("cluster_name"),
185
+ )
186
+
187
+ start_ns = getattr(span, "start_time", None)
188
+ end_ns = getattr(span, "end_time", None)
189
+ if start_ns is None or end_ns is None or end_ns <= start_ns:
190
+ return
191
+
192
+ breakdown = compute_request_breakdown(int(start_ns), int(end_ns), bucket.intervals)
193
+ if not breakdown:
194
+ return
195
+
196
+ from tp_trace.metrics import record_request_time_breakdown
197
+
198
+ record_request_time_breakdown(
199
+ breakdown=breakdown,
200
+ project_name=attrs.get("project_name"),
201
+ cluster_name=attrs.get("cluster_name"),
202
+ )
203
+
204
+ def _find_nearest_server_bucket_locked(self, span_id: int, direct_parent_id: int) -> Optional[_RequestBucket]:
205
+ curr = direct_parent_id or self._span_parents.get(span_id, 0)
206
+ for _ in range(_MAX_ANCESTOR_HOPS):
207
+ if not curr:
208
+ return None
209
+ bucket = self._server_buckets.get(curr)
210
+ if bucket is not None:
211
+ return bucket
212
+ curr = self._span_parents.get(curr, 0)
213
+ return None
214
+
215
+ def _track_parent_locked(self, span_id: int, parent_span_id: int) -> bool:
216
+ if not parent_span_id:
217
+ return False
218
+ evicted = False
219
+ if len(self._span_parents) >= self._max_span_parents:
220
+ self._span_parents.pop(next(iter(self._span_parents)))
221
+ evicted = True
222
+ self._span_parents[span_id] = parent_span_id
223
+ return evicted
224
+
225
+ def _decrement_trace_count_locked(self, trace_id: int) -> None:
226
+ rem = self._active_trace_counts.get(trace_id, 0) - 1
227
+ if rem > 0:
228
+ self._active_trace_counts[trace_id] = rem
229
+ else:
230
+ self._active_trace_counts.pop(trace_id, None)
231
+
232
+
233
+ def compute_request_breakdown(
234
+ request_start_ns: int,
235
+ request_end_ns: int,
236
+ intervals: List[SpanInterval],
237
+ ) -> Dict[BreakdownKey, float]:
238
+ """Compute exact per-component millisecond breakdown for one request.
239
+
240
+ Uses an O(N log N) event sweep over clamped child CLIENT intervals so
241
+ concurrent or overlapping calls never exceed 100% of the request duration.
242
+ Overlapped segments are split equally across active child intervals, and
243
+ remaining wall-clock time is attributed to ``("django", "", "")``.
244
+ """
245
+ total_ns = request_end_ns - request_start_ns
246
+ if total_ns <= 0:
247
+ return {}
248
+
249
+ events: List[Tuple[int, int, BreakdownKey]] = []
250
+ for start_ns, end_ns, svc, db_inst, db_pool in intervals:
251
+ s = max(start_ns, request_start_ns)
252
+ e = min(end_ns, request_end_ns)
253
+ if e > s:
254
+ key: BreakdownKey = (svc, db_inst, db_pool)
255
+ events.append((s, 1, key))
256
+ events.append((e, -1, key))
257
+
258
+ if not events:
259
+ return {("django", "", ""): total_ns / 1_000_000.0}
260
+
261
+ events.sort(key=lambda ev: ev[0])
262
+
263
+ active_counts: Dict[BreakdownKey, int] = {}
264
+ total_active = 0
265
+ ns_by_key: Dict[BreakdownKey, float] = {}
266
+ total_dep_ns = 0
267
+ n_events = len(events)
268
+ idx = 0
269
+ prev_t: Optional[int] = None
270
+
271
+ while idx < n_events:
272
+ curr_t = events[idx][0]
273
+ if prev_t is not None and curr_t > prev_t and total_active > 0:
274
+ seg_len = curr_t - prev_t
275
+ total_dep_ns += seg_len
276
+ share = seg_len / float(total_active)
277
+ for key, cnt in active_counts.items():
278
+ ns_by_key[key] = ns_by_key.get(key, 0.0) + share * cnt
279
+
280
+ while idx < n_events and events[idx][0] == curr_t:
281
+ _, delta, key = events[idx]
282
+ new_cnt = active_counts.get(key, 0) + delta
283
+ if new_cnt > 0:
284
+ active_counts[key] = new_cnt
285
+ else:
286
+ active_counts.pop(key, None)
287
+ total_active += delta
288
+ idx += 1
289
+
290
+ prev_t = curr_t
291
+
292
+ django_ns = max(total_ns - total_dep_ns, 0)
293
+ result: Dict[BreakdownKey, float] = {}
294
+ if django_ns > 0:
295
+ result[("django", "", "")] = django_ns / 1_000_000.0
296
+ for key, dep_ns in ns_by_key.items():
297
+ if dep_ns > 0:
298
+ result[key] = dep_ns / 1_000_000.0
299
+ return result
300
+
301
+
302
+ def _get_span_context(span: Any) -> Any:
303
+ ctx = getattr(span, "context", None)
304
+ if ctx is None and hasattr(span, "get_span_context"):
305
+ try:
306
+ ctx = span.get_span_context()
307
+ except Exception:
308
+ ctx = None
309
+ return ctx
310
+
311
+
312
+ def _get_parent_span_id(span: Any, parent_context: Optional[Any] = None) -> int:
313
+ parent = getattr(span, "parent", None)
314
+ pid = getattr(parent, "span_id", 0) if parent is not None else 0
315
+ if pid:
316
+ return int(pid)
317
+ if parent_context is not None:
318
+ try:
319
+ pid = getattr(get_current_span(parent_context).get_span_context(), "span_id", 0)
320
+ if pid:
321
+ return int(pid)
322
+ except Exception:
323
+ pass
324
+ return 0
325
+
326
+
327
+ def _get_span_kind(span: Any) -> Any:
328
+ kind = getattr(span, "kind", None)
329
+ return getattr(span, "_kind", None) if kind is None else kind
330
+
331
+
332
+ def _normalize_dependency_service(attrs: Dict[str, Any]) -> str:
333
+ svc = (
334
+ attrs.get("normalized.service")
335
+ or attrs.get("peer.service")
336
+ or attrs.get("db.system")
337
+ or attrs.get("rpc.system")
338
+ or attrs.get("component")
339
+ or ""
340
+ )
341
+ svc_str = str(svc).strip()
342
+ if svc_str == "postgresql":
343
+ return "postgres"
344
+ if svc_str == "aws-api":
345
+ return "aws-s3"
346
+ return svc_str