macss-modular-api-postgres 0.6.0__tar.gz → 0.7.1__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 (19) hide show
  1. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/PKG-INFO +4 -1
  2. macss_modular_api_postgres-0.7.1/pyproject.toml +95 -0
  3. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/src/macss_modular_api_postgres.egg-info/PKG-INFO +4 -1
  4. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/src/macss_modular_api_postgres.egg-info/SOURCES.txt +5 -1
  5. macss_modular_api_postgres-0.7.1/src/macss_modular_api_postgres.egg-info/requires.txt +6 -0
  6. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/src/modular_api_postgres/__init__.py +4 -1
  7. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/src/modular_api_postgres/db_client.py +33 -33
  8. macss_modular_api_postgres-0.7.1/src/modular_api_postgres/db_tracing.py +341 -0
  9. macss_modular_api_postgres-0.7.1/src/modular_api_postgres/py.typed +0 -0
  10. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/tests/test_db_client.py +16 -3
  11. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/tests/test_db_conformance.py +6 -3
  12. macss_modular_api_postgres-0.7.1/tests/test_dependency_boundary.py +120 -0
  13. macss_modular_api_postgres-0.7.1/tests/test_tracing.py +532 -0
  14. macss_modular_api_postgres-0.6.0/pyproject.toml +0 -46
  15. macss_modular_api_postgres-0.6.0/src/macss_modular_api_postgres.egg-info/requires.txt +0 -3
  16. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/README.md +0 -0
  17. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/setup.cfg +0 -0
  18. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/src/macss_modular_api_postgres.egg-info/dependency_links.txt +0 -0
  19. {macss_modular_api_postgres-0.6.0 → macss_modular_api_postgres-0.7.1}/src/macss_modular_api_postgres.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api-postgres
3
- Version: 0.6.0
3
+ Version: 0.7.1
4
4
  Summary: Official MACSS Postgres integration package for Python.
5
5
  Author: ccisne.dev
6
6
  License-Expression: MIT
@@ -19,7 +19,10 @@ Classifier: Topic :: Database
19
19
  Classifier: Typing :: Typed
20
20
  Requires-Python: >=3.11
21
21
  Description-Content-Type: text/markdown
22
+ Requires-Dist: opentelemetry-api<2,>=1.44
22
23
  Provides-Extra: dev
24
+ Requires-Dist: opentelemetry-sdk<2,>=1.44; extra == "dev"
25
+ Requires-Dist: pyright>=1.1.400; extra == "dev"
23
26
  Requires-Dist: pytest>=8.0; extra == "dev"
24
27
 
25
28
  # macss-modular-api-postgres
@@ -0,0 +1,95 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "macss-modular-api-postgres"
7
+ version = "0.7.1"
8
+ description = "Official MACSS Postgres integration package for Python."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "ccisne.dev" }]
13
+ keywords = ["macss", "postgres", "database"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Database",
22
+ "Typing :: Typed",
23
+ ]
24
+ # OpenTelemetry API only — never the SDK, an exporter, grpcio or protobuf. Declared
25
+ # directly rather than inherited, because this package does not depend on
26
+ # macss-modular-api (runbook D21). The API is no-op without an SDK, so a consumer who
27
+ # never enables tracing pays a resolution entry and nothing else.
28
+ #
29
+ # This is the first runtime dependency the package has ever had. ADR-0004 keeps it free
30
+ # of any *database driver*, which is untouched: an instrumentation API is not a driver,
31
+ # and a new test asserts no driver is present.
32
+ dependencies = ["opentelemetry-api>=1.44,<2"]
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ # The SDK is what makes spans observable at all — the API alone is no-op (runbook D22).
37
+ "opentelemetry-sdk>=1.44,<2",
38
+ # Configured below at `typeCheckingMode = "strict"`. Declared here because a checker the
39
+ # repo configures and never installs is a checker that has never run.
40
+ "pyright>=1.1.400",
41
+ "pytest>=8.0",
42
+ ]
43
+
44
+ [project.urls]
45
+ Homepage = "https://github.com/macss-dev/modular_api"
46
+ Repository = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_postgres"
47
+ Issues = "https://github.com/macss-dev/modular_api/issues"
48
+ Documentation = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_postgres#readme"
49
+
50
+ [tool.setuptools.packages.find]
51
+ where = ["src"]
52
+
53
+ [tool.pytest.ini_options]
54
+ testpaths = ["tests"]
55
+ pythonpath = ["src"]
56
+
57
+ [tool.pyright]
58
+ pythonVersion = "3.11"
59
+ # `src/` is checked at full strict, because it is what a consumer's own type checker sees: these
60
+ # packages ship `py.typed`, so every annotation here becomes part of the public contract.
61
+ typeCheckingMode = "strict"
62
+
63
+ # `tests/` is strict too, minus the family that means "annotate this expression". Test code binds
64
+ # only this repo, and most of those diagnostics come from incomplete third-party stubs — annotating
65
+ # around them adds noise to a test without making anything more correct. Everything that can indicate
66
+ # a real defect stays on.
67
+ [[tool.pyright.executionEnvironments]]
68
+ root = "tests"
69
+ reportUnknownMemberType = false
70
+ reportUnknownArgumentType = false
71
+ reportUnknownVariableType = false
72
+ reportUnknownParameterType = false
73
+ reportUnknownLambdaType = false
74
+ reportMissingParameterType = false
75
+ reportMissingTypeArgument = false
76
+ # A pytest fixture is called by name through collection, never by a reference the checker can see, so
77
+ # `reportUnusedFunction` reports every `autouse` fixture in this tree. That is the tool not modelling
78
+ # pytest, not dead code. `reportUnusedImport` and `reportUnusedVariable` stay on — those do find dead
79
+ # code, and they did.
80
+ reportUnusedFunction = false
81
+ reportUnusedClass = false
82
+ # Tests legitimately reach into internals to exercise them directly. In `src/` this rule found real
83
+ # coupling and it was fixed rather than silenced.
84
+ reportPrivateUsage = false
85
+ # `example/` is documentation a consumer copies, not a published typed surface — same relaxed family
86
+ # as `tests/`, and the same expectation that nothing which can indicate a real defect is silenced.
87
+ [[tool.pyright.executionEnvironments]]
88
+ root = "example"
89
+ reportUnknownMemberType = false
90
+ reportUnknownArgumentType = false
91
+ reportUnknownVariableType = false
92
+ reportUnknownParameterType = false
93
+ reportUnknownLambdaType = false
94
+ reportMissingParameterType = false
95
+ reportMissingTypeArgument = false
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api-postgres
3
- Version: 0.6.0
3
+ Version: 0.7.1
4
4
  Summary: Official MACSS Postgres integration package for Python.
5
5
  Author: ccisne.dev
6
6
  License-Expression: MIT
@@ -19,7 +19,10 @@ Classifier: Topic :: Database
19
19
  Classifier: Typing :: Typed
20
20
  Requires-Python: >=3.11
21
21
  Description-Content-Type: text/markdown
22
+ Requires-Dist: opentelemetry-api<2,>=1.44
22
23
  Provides-Extra: dev
24
+ Requires-Dist: opentelemetry-sdk<2,>=1.44; extra == "dev"
25
+ Requires-Dist: pyright>=1.1.400; extra == "dev"
23
26
  Requires-Dist: pytest>=8.0; extra == "dev"
24
27
 
25
28
  # macss-modular-api-postgres
@@ -7,5 +7,9 @@ src/macss_modular_api_postgres.egg-info/requires.txt
7
7
  src/macss_modular_api_postgres.egg-info/top_level.txt
8
8
  src/modular_api_postgres/__init__.py
9
9
  src/modular_api_postgres/db_client.py
10
+ src/modular_api_postgres/db_tracing.py
11
+ src/modular_api_postgres/py.typed
10
12
  tests/test_db_client.py
11
- tests/test_db_conformance.py
13
+ tests/test_db_conformance.py
14
+ tests/test_dependency_boundary.py
15
+ tests/test_tracing.py
@@ -0,0 +1,6 @@
1
+ opentelemetry-api<2,>=1.44
2
+
3
+ [dev]
4
+ opentelemetry-sdk<2,>=1.44
5
+ pyright>=1.1.400
6
+ pytest>=8.0
@@ -28,8 +28,10 @@ from .db_client import (
28
28
  DbTransactionContext,
29
29
  DbTransactionRunner,
30
30
  )
31
+ from .db_tracing import DbTracingOptions, trace_db_client
31
32
 
32
33
  __all__ = [
34
+ "DbTracingOptions",
33
35
  "DbClient",
34
36
  "DbCommand",
35
37
  "DbCommandExecutor",
@@ -56,4 +58,5 @@ __all__ = [
56
58
  "DbSessionProvider",
57
59
  "DbTransactionContext",
58
60
  "DbTransactionRunner",
59
- ]
61
+ "trace_db_client",
62
+ ]
@@ -7,6 +7,8 @@ from enum import Enum
7
7
  from typing import Callable, Generic, Mapping, Protocol, TypeVar, cast
8
8
 
9
9
  S = TypeVar("S")
10
+ #: Contravariant because the protocols below only ever *accept* a session, never return one.
11
+ S_contra = TypeVar("S_contra", contravariant=True)
10
12
  T = TypeVar("T")
11
13
  R = TypeVar("R")
12
14
  _MISSING = object()
@@ -52,7 +54,7 @@ class DbConnectionSettings:
52
54
  username: str
53
55
  password: str
54
56
  ssl_mode: str
55
- options: Mapping[str, object] = field(default_factory=dict)
57
+ options: Mapping[str, object] = field(default_factory=dict[str, object])
56
58
 
57
59
  @classmethod
58
60
  def from_environment(
@@ -203,18 +205,18 @@ class DbResult(Generic[T]):
203
205
 
204
206
  def map(self, transform: Callable[[T], R]) -> DbResult[R]:
205
207
  if self.is_failure:
206
- return DbResult.from_failure(self.failure)
207
- return DbResult.success(transform(self.value))
208
+ return DbResult[R].from_failure(self.failure)
209
+ return DbResult[R].success(transform(self.value))
208
210
 
209
211
  def flat_map(self, transform: Callable[[T], DbResult[R]]) -> DbResult[R]:
210
212
  if self.is_failure:
211
- return DbResult.from_failure(self.failure)
213
+ return DbResult[R].from_failure(self.failure)
212
214
  return transform(self.value)
213
215
 
214
216
  def map_failure(self, transform: Callable[[DbFailure], DbFailure]) -> DbResult[T]:
215
217
  if self.is_success:
216
- return DbResult.success(self.value)
217
- return DbResult.from_failure(transform(self.failure))
218
+ return DbResult[T].success(self.value)
219
+ return DbResult[T].from_failure(transform(self.failure))
218
220
 
219
221
  def get_or_throw(self, message: str | None = None) -> T:
220
222
  if self.is_failure:
@@ -244,7 +246,7 @@ class DbSessionLease(Generic[S]):
244
246
 
245
247
  def release(self) -> DbResult[None]:
246
248
  if not self.owned_by_package:
247
- return DbResult.success(None)
249
+ return DbResult[None].success(None)
248
250
  return self._releaser()
249
251
 
250
252
 
@@ -256,12 +258,16 @@ class DbSessionProvider(Protocol[S]):
256
258
  def describe(self) -> DbProviderDescription: ...
257
259
 
258
260
 
259
- class DbCommandExecutor(Protocol[S]):
260
- def query(self, session: S, command: DbCommand) -> DbResult[DbRowSet]: ...
261
+ class DbCommandExecutor(Protocol[S_contra]):
262
+ def query(self, session: S_contra, command: DbCommand) -> DbResult[DbRowSet]: ...
261
263
 
262
- def execute(self, session: S, command: DbCommand) -> DbResult[DbExecutionSummary]: ...
264
+ def execute(
265
+ self, session: S_contra, command: DbCommand
266
+ ) -> DbResult[DbExecutionSummary]: ...
263
267
 
264
- def scalar(self, session: S, command: DbCommand) -> DbResult[DbScalar[object]]: ...
268
+ def scalar(
269
+ self, session: S_contra, command: DbCommand
270
+ ) -> DbResult[DbScalar[object]]: ...
265
271
 
266
272
 
267
273
  @dataclass(frozen=True, slots=True)
@@ -276,8 +282,8 @@ class DbTransactionContext(Generic[S]):
276
282
  def execute(self, command: DbCommand) -> DbResult[DbExecutionSummary]:
277
283
  return self.command_executor.execute(self.session, command)
278
284
 
279
- def scalar(self, command: DbCommand) -> DbResult[DbScalar[T]]:
280
- return cast(DbResult[DbScalar[T]], self.command_executor.scalar(self.session, command))
285
+ def scalar(self, command: DbCommand) -> DbResult[DbScalar[object]]:
286
+ return self.command_executor.scalar(self.session, command)
281
287
 
282
288
 
283
289
  class DbTransactionRunner(Protocol[S]):
@@ -312,13 +318,10 @@ class DbRepository(Generic[S]):
312
318
  lambda lease: self.context.command_executor.execute(lease.session, command),
313
319
  )
314
320
 
315
- def scalar(self, command: DbCommand) -> DbResult[DbScalar[T]]:
316
- return cast(
317
- DbResult[DbScalar[T]],
318
- _with_lease(
319
- self.context.session_provider,
320
- lambda lease: self.context.command_executor.scalar(lease.session, command),
321
- ),
321
+ def scalar(self, command: DbCommand) -> DbResult[DbScalar[object]]:
322
+ return _with_lease(
323
+ self.context.session_provider,
324
+ lambda lease: self.context.command_executor.scalar(lease.session, command),
322
325
  )
323
326
 
324
327
  def transaction(self, body: Callable[[DbTransactionContext[S]], DbResult[T]]) -> DbResult[T]:
@@ -357,19 +360,16 @@ class DbClient(Generic[S]):
357
360
  lambda lease: self.command_executor.execute(lease.session, command),
358
361
  )
359
362
 
360
- def scalar(self, command: DbCommand) -> DbResult[DbScalar[T]]:
361
- return cast(
362
- DbResult[DbScalar[T]],
363
- _with_lease(
364
- self.session_provider,
365
- lambda lease: self.command_executor.scalar(lease.session, command),
366
- ),
363
+ def scalar(self, command: DbCommand) -> DbResult[DbScalar[object]]:
364
+ return _with_lease(
365
+ self.session_provider,
366
+ lambda lease: self.command_executor.scalar(lease.session, command),
367
367
  )
368
368
 
369
369
  def transaction(self, body: Callable[[DbTransactionContext[S]], DbResult[T]]) -> DbResult[T]:
370
370
  lease_result = self.session_provider.acquire()
371
371
  if lease_result.is_failure:
372
- return DbResult.from_failure(lease_result.failure)
372
+ return DbResult[T].from_failure(lease_result.failure)
373
373
 
374
374
  lease = lease_result.value
375
375
  context = DbTransactionContext(
@@ -381,9 +381,9 @@ class DbClient(Generic[S]):
381
381
  release_result = lease.release()
382
382
 
383
383
  if result.is_failure:
384
- return DbResult.from_failure(result.failure)
384
+ return DbResult[T].from_failure(result.failure)
385
385
  if release_result.is_failure:
386
- return DbResult.from_failure(release_result.failure)
386
+ return DbResult[T].from_failure(release_result.failure)
387
387
  return result
388
388
 
389
389
  def repository_context(self) -> DbRepositoryContext[S]:
@@ -454,14 +454,14 @@ def _with_lease(
454
454
  ) -> DbResult[T]:
455
455
  lease_result = session_provider.acquire()
456
456
  if lease_result.is_failure:
457
- return DbResult.from_failure(lease_result.failure)
457
+ return DbResult[T].from_failure(lease_result.failure)
458
458
 
459
459
  lease = lease_result.value
460
460
  operation_result = operation(lease)
461
461
  release_result = lease.release()
462
462
 
463
463
  if operation_result.is_failure:
464
- return DbResult.from_failure(operation_result.failure)
464
+ return DbResult[T].from_failure(operation_result.failure)
465
465
  if release_result.is_failure:
466
- return DbResult.from_failure(release_result.failure)
466
+ return DbResult[T].from_failure(release_result.failure)
467
467
  return operation_result
@@ -0,0 +1,341 @@
1
+ """Database spans for the contracts this package ships.
2
+
3
+ **Instrumentation is a decorator over the contract, not a change to ``DbClient``.** ADR-0004 makes
4
+ this package contracts-only, and ``DbClient``, ``DbRepository`` and ``DbTransactionContext`` all
5
+ delegate to the same application-supplied ``DbCommandExecutor``. Wrapping that one collaborator
6
+ instruments every call path at once — including commands issued inside a transaction body, which
7
+ ``DbClient.transaction`` routes through a freshly built ``DbTransactionContext`` carrying the same
8
+ executor.
9
+
10
+ It follows that **not wrapping is how you turn tracing off**, so the cost of not using it is zero
11
+ rather than a branch per call (gate G3).
12
+
13
+ The Dart and TypeScript counterparts are ``lib/src/db_tracing.dart`` and ``src/dbTracing.ts``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from dataclasses import dataclass
20
+ from typing import Any, Callable, Generic, TypeVar
21
+
22
+ from opentelemetry import trace
23
+ from opentelemetry.trace import Span, SpanKind, Status, StatusCode, Tracer
24
+ from opentelemetry.util.types import AttributeValue
25
+
26
+ from modular_api_postgres.db_client import (
27
+ DbClient,
28
+ DbCommand,
29
+ DbCommandExecutor,
30
+ DbCommandKind,
31
+ DbConnectionSettings,
32
+ DbExecutionSummary,
33
+ DbProviderDescription,
34
+ DbResult,
35
+ DbRowSet,
36
+ DbScalar,
37
+ DbSessionLease,
38
+ DbSessionProvider,
39
+ DbTransactionContext,
40
+ DbTransactionRunner,
41
+ )
42
+
43
+ S = TypeVar("S")
44
+ T = TypeVar("T")
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class DbTracingOptions:
49
+ """How much a database span is allowed to say.
50
+
51
+ ``include_query_text`` is **off by default** (runbook D9). SQL can carry personal or financial
52
+ data in a literal, and a span is not a place that is reviewed for that. Parameter *values* are
53
+ never recorded regardless of this setting: the text is a template, the parameters are the data.
54
+ """
55
+
56
+ include_query_text: bool = False
57
+ instrumentation_name: str = "modular_api_postgres"
58
+
59
+
60
+ def trace_db_client(
61
+ client: DbClient[S],
62
+ options: DbTracingOptions | None = None,
63
+ ) -> DbClient[S]:
64
+ """Wrap ``client`` so its commands, transactions and session acquisitions produce spans.
65
+
66
+ The wrapped client is a drop-in replacement: same settings, same ``DbProviderDescription``, so
67
+ ``DbHealthContributor`` and GraphQL support keep working unchanged. A repository built from the
68
+ wrapped client is instrumented too — call ``repository_context()`` on the result rather than on
69
+ the original.
70
+ """
71
+ resolved = options or DbTracingOptions()
72
+ tracer = trace.get_tracer(resolved.instrumentation_name)
73
+ target = _DbTarget(client.settings)
74
+
75
+ return DbClient(
76
+ settings=client.settings,
77
+ session_provider=_TracedSessionProvider(client.session_provider, tracer, target),
78
+ command_executor=_TracedCommandExecutor(
79
+ client.command_executor, tracer, target, resolved
80
+ ),
81
+ transaction_runner=_TracedTransactionRunner(client.transaction_runner, tracer, target),
82
+ )
83
+
84
+
85
+ class _DbTarget:
86
+ """The attributes that describe *where* the database is, computed once per client."""
87
+
88
+ #: The value the semantic conventions register for Postgres.
89
+ #:
90
+ #: Deliberately not ``settings.engine_id``, which is ``postgres``: a backend keying its Postgres
91
+ #: dashboards off ``db.system.name`` would not match on that.
92
+ SYSTEM_NAME = "postgresql"
93
+
94
+ __slots__ = ("host", "namespace", "port")
95
+
96
+ def __init__(self, settings: DbConnectionSettings) -> None:
97
+ self.namespace = settings.database
98
+ self.host = settings.host
99
+ self.port = settings.port
100
+
101
+
102
+ #: The SQL verbs an operation name may take.
103
+ #:
104
+ #: An allowlist rather than "the first word", so an unusual leading token — a comment, a driver
105
+ #: directive — is dropped instead of emitted. That keeps the attribute low-cardinality and makes it
106
+ #: impossible for a fragment of a query to arrive as an operation name.
107
+ _SQL_OPERATIONS = frozenset(
108
+ {
109
+ "SELECT",
110
+ "INSERT",
111
+ "UPDATE",
112
+ "DELETE",
113
+ "MERGE",
114
+ "UPSERT",
115
+ "CALL",
116
+ "WITH",
117
+ "CREATE",
118
+ "ALTER",
119
+ "DROP",
120
+ "TRUNCATE",
121
+ "GRANT",
122
+ "REVOKE",
123
+ "EXPLAIN",
124
+ "ANALYZE",
125
+ "VACUUM",
126
+ "COPY",
127
+ "BEGIN",
128
+ "COMMIT",
129
+ "ROLLBACK",
130
+ "SET",
131
+ "SHOW",
132
+ "LISTEN",
133
+ "NOTIFY",
134
+ "REFRESH",
135
+ }
136
+ )
137
+
138
+ _LEADING_WORD = re.compile(r"^\s*([A-Za-z_]+)")
139
+
140
+
141
+ def _operation_name(command: DbCommand) -> str | None:
142
+ match = _LEADING_WORD.match(command.text)
143
+ if match is None:
144
+ return None
145
+
146
+ candidate = match.group(1).upper()
147
+ return candidate if candidate in _SQL_OPERATIONS else None
148
+
149
+
150
+ def _start_db_span(
151
+ tracer: Tracer,
152
+ *,
153
+ target: _DbTarget,
154
+ operation: str | None = None,
155
+ summary: str | None = None,
156
+ query_text: str | None = None,
157
+ batch_size: int | None = None,
158
+ ) -> Span | None:
159
+ """Start a span for one database operation, or return ``None`` when tracing is off.
160
+
161
+ ``None`` rather than a non-recording span: with no recording parent there is nothing to attach
162
+ to, and a span nobody will read is cost with no benefit.
163
+ """
164
+ parent = trace.get_current_span()
165
+ if not parent.is_recording():
166
+ return None
167
+
168
+ # `AttributeValue`, not `object`: OpenTelemetry accepts only primitives and sequences of
169
+ # primitives, and silently drops an attribute whose value is anything else. Naming the type
170
+ # turns a dropped attribute — invisible at runtime, and exactly the kind of gap that makes an
171
+ # instrumentation look broken — into an error here.
172
+ attributes: dict[str, AttributeValue] = {
173
+ "db.system.name": _DbTarget.SYSTEM_NAME,
174
+ "db.namespace": target.namespace,
175
+ "server.address": target.host,
176
+ "server.port": target.port,
177
+ }
178
+ if operation is not None:
179
+ attributes["db.operation.name"] = operation
180
+ if summary is not None:
181
+ attributes["db.query.summary"] = summary
182
+ if query_text is not None:
183
+ attributes["db.query.text"] = query_text
184
+ if batch_size is not None:
185
+ attributes["db.operation.batch.size"] = batch_size
186
+
187
+ return tracer.start_span(
188
+ # The conventions ask for ``{operation} {target}``, and prefer ``db.query.summary`` when one
189
+ # exists. ``DbCommand.label`` is exactly that — application-supplied and stable — so it wins
190
+ # over anything derived from the SQL. Never the SQL text itself: unbounded cardinality, and
191
+ # possibly personal data.
192
+ summary or f"{operation or 'QUERY'} {target.namespace}",
193
+ kind=SpanKind.CLIENT, # A database call leaves the process.
194
+ attributes=attributes,
195
+ )
196
+
197
+
198
+ def _end_db_span(
199
+ span: Span | None,
200
+ # `DbResult[Any]`, not `DbResult[object]`: this helper never touches the value, only `is_failure`
201
+ # and `failure` — but `DbResult` is invariant, so `DbResult[object]` accepts none of the concrete
202
+ # results its five call sites hold.
203
+ result: DbResult[Any],
204
+ returned_rows: int | None = None,
205
+ ) -> None:
206
+ """Record the outcome on ``span`` and end it.
207
+
208
+ Failures arrive as a ``DbResult``, never as a raised exception, so this inspects the result. A
209
+ decorator that only wrapped a ``try``/``except`` would report every timeout as a success.
210
+
211
+ The failure *message* is deliberately not copied: a driver message can quote the offending row.
212
+ The code and the kind are what diagnose the problem.
213
+ """
214
+ if span is None:
215
+ return
216
+
217
+ if result.is_failure:
218
+ failure = result.failure
219
+ span.set_attribute("db.response.status_code", failure.code)
220
+ span.set_attribute("modular_api.db.failure_kind", failure.kind.value)
221
+ span.set_status(Status(StatusCode.ERROR))
222
+ elif returned_rows is not None:
223
+ span.set_attribute("db.response.returned_rows", returned_rows)
224
+
225
+ span.end()
226
+
227
+
228
+ class _TracedCommandExecutor(Generic[S]):
229
+ __slots__ = ("_inner", "_options", "_target", "_tracer")
230
+
231
+ def __init__(
232
+ self,
233
+ inner: DbCommandExecutor[S],
234
+ tracer: Tracer,
235
+ target: _DbTarget,
236
+ options: DbTracingOptions,
237
+ ) -> None:
238
+ self._inner = inner
239
+ self._tracer = tracer
240
+ self._target = target
241
+ self._options = options
242
+
243
+ def _start(self, command: DbCommand) -> Span | None:
244
+ return _start_db_span(
245
+ self._tracer,
246
+ target=self._target,
247
+ operation=_operation_name(command),
248
+ summary=command.label,
249
+ query_text=command.text if self._options.include_query_text else None,
250
+ batch_size=(
251
+ len(command.parameters) if command.kind is DbCommandKind.BATCH else None
252
+ ),
253
+ )
254
+
255
+ def query(self, session: S, command: DbCommand) -> DbResult[DbRowSet]:
256
+ span = self._start(command)
257
+ result = self._inner.query(session, command)
258
+ rows = None
259
+ if result.is_success:
260
+ rows = result.value.metadata.row_count
261
+ if rows is None:
262
+ rows = len(result.value.rows)
263
+ _end_db_span(span, result, rows)
264
+ return result
265
+
266
+ def execute(self, session: S, command: DbCommand) -> DbResult[DbExecutionSummary]:
267
+ span = self._start(command)
268
+ result = self._inner.execute(session, command)
269
+ _end_db_span(span, result)
270
+ return result
271
+
272
+ def scalar(self, session: S, command: DbCommand) -> DbResult[DbScalar[object]]:
273
+ span = self._start(command)
274
+ result = self._inner.scalar(session, command)
275
+ _end_db_span(span, result)
276
+ return result
277
+
278
+
279
+ class _TracedTransactionRunner(Generic[S]):
280
+ __slots__ = ("_inner", "_target", "_tracer")
281
+
282
+ def __init__(
283
+ self,
284
+ inner: DbTransactionRunner[S],
285
+ tracer: Tracer,
286
+ target: _DbTarget,
287
+ ) -> None:
288
+ self._inner = inner
289
+ self._tracer = tracer
290
+ self._target = target
291
+
292
+ def run(
293
+ self,
294
+ context: DbTransactionContext[S],
295
+ body: Callable[[DbTransactionContext[S]], DbResult[T]],
296
+ ) -> DbResult[T]:
297
+ span = _start_db_span(self._tracer, target=self._target, operation="TRANSACTION")
298
+ if span is None:
299
+ return self._inner.run(context, body)
300
+
301
+ # Made ambient so commands issued through the transaction context become its children
302
+ # rather than siblings — the nesting is what makes a transaction readable in a waterfall.
303
+ # ``end_on_exit=False`` because ``_end_db_span`` records the outcome first.
304
+ with trace.use_span(span, end_on_exit=False):
305
+ result = self._inner.run(context, body)
306
+
307
+ _end_db_span(span, result)
308
+ return result
309
+
310
+
311
+ class _TracedSessionProvider(Generic[S]):
312
+ __slots__ = ("_inner", "_target", "_tracer")
313
+
314
+ def __init__(
315
+ self,
316
+ inner: DbSessionProvider[S],
317
+ tracer: Tracer,
318
+ target: _DbTarget,
319
+ ) -> None:
320
+ self._inner = inner
321
+ self._tracer = tracer
322
+ self._target = target
323
+
324
+ def acquire(self) -> DbResult[DbSessionLease[S]]:
325
+ """Acquisition gets its own span (runbook D28).
326
+
327
+ Without it, time spent waiting for a connection lands in no span at all — an unattributed
328
+ gap that reads as nothing having happened rather than as queueing for the pool. Pool
329
+ exhaustion is a live hypothesis for ``socia``, so this is the number that confirms or kills
330
+ it.
331
+ """
332
+ span = _start_db_span(self._tracer, target=self._target, operation="CONNECT")
333
+ result = self._inner.acquire()
334
+ _end_db_span(span, result)
335
+ return result
336
+
337
+ def close(self) -> DbResult[None]:
338
+ return self._inner.close()
339
+
340
+ def describe(self) -> DbProviderDescription:
341
+ return self._inner.describe()