mainsequence 9.0.36.dev83__py3-none-any.whl → 9.0.36.dev85__py3-none-any.whl

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.
mainsequence/__init__.py CHANGED
@@ -1,8 +1,11 @@
1
1
  # ruff: noqa: E402
2
2
  from .bootstrap import prime_runtime_env
3
+ from .instrumentation.utils import _attach_environment_context
3
4
 
4
5
  # Restore CLI credentials before any client module freezes its endpoint/provider.
5
6
  prime_runtime_env()
7
+ # A Job run's TRACEPARENT and BAGGAGE, before its first log line or call (ADR 0040).
8
+ _attach_environment_context()
6
9
 
7
10
  from .logconf import (
8
11
  logger as logger,
@@ -12,6 +12,8 @@ from requests.adapters import HTTPAdapter
12
12
  from urllib3.exceptions import InvalidHeader
13
13
  from urllib3.util import Retry, Timeout
14
14
 
15
+ from .instrumentation import tracer_instrumentator
16
+
15
17
  DEFAULT_ALLOWED_METHODS = frozenset({"HEAD", "GET", "OPTIONS"})
16
18
  DEFAULT_STATUS_FORCELIST = (429, 500, 502, 503, 504)
17
19
  DEFAULT_TIMEOUT = (5.0, 120.0)
@@ -97,7 +99,13 @@ def request_within_budget(method, url, *, timeout, **kwargs):
97
99
  deadline. Then the response, when it has started, is shut down and
98
100
  ``requests.Timeout`` is raised. The request may already have reached the
99
101
  server.
102
+
103
+ The current ``traceparent`` and ``baggage`` go with the request; a header
104
+ the caller sets wins (ADR 0040).
100
105
  """
106
+ carrier = tracer_instrumentator.get_telemetry_carrier()
107
+ if carrier:
108
+ kwargs["headers"] = {**carrier, **(kwargs.get("headers") or {})}
101
109
  with request_budget(timeout) as budget:
102
110
  attempt_timeout = budget.timeout()
103
111
  lock = threading.Lock()
@@ -9,6 +9,7 @@ from uuid import UUID
9
9
  import requests
10
10
  from pydantic import BaseModel, ConfigDict, Field, ValidationError
11
11
 
12
+ from ..instrumentation import tracer_instrumentator
12
13
  from . import utils
13
14
  from .exceptions import raise_for_response
14
15
 
@@ -74,7 +75,9 @@ class InferenceClient:
74
75
  # Inference opts out of safe-read retries as well: an uncertain outcome
75
76
  # must preserve the caller's explicit idempotency key.
76
77
  with utils.build_session(loaders=utils.loaders, retries=0) as session:
77
- headers = dict(utils.loaders.refresh_headers(force=False, session=session))
78
+ # The caller context goes with the call (ADR 0040).
79
+ headers = dict(tracer_instrumentator.get_telemetry_carrier())
80
+ headers.update(utils.loaders.refresh_headers(force=False, session=session))
78
81
  if key is not None:
79
82
  headers["Idempotency-Key"] = key
80
83
  try:
@@ -20,6 +20,7 @@ import requests
20
20
  from requests.structures import CaseInsensitiveDict
21
21
 
22
22
  from mainsequence.defaults import resolve_backend_endpoint
23
+ from mainsequence.instrumentation import tracer_instrumentator
23
24
  from mainsequence.logconf import logger
24
25
  from mainsequence.runtime_credential_exchange import (
25
26
  RUNTIME_CREDENTIAL_ID_ENV,
@@ -876,6 +877,11 @@ def make_request(
876
877
  else:
877
878
  request_kwargs = dict(payload)
878
879
  request_kwargs.setdefault("allow_redirects", False)
880
+ # The caller context goes with the call, per request: the session is shared.
881
+ # A header the caller sets wins (ADR 0040).
882
+ carrier = tracer_instrumentator.get_telemetry_carrier()
883
+ if carrier:
884
+ request_kwargs["headers"] = {**carrier, **(request_kwargs.get("headers") or {})}
879
885
  req = getattr(s, r_type.lower())
880
886
 
881
887
  if accept_gzip:
@@ -1,7 +1,11 @@
1
+ import logging
1
2
  import os
3
+ from contextvars import ContextVar
2
4
 
3
5
  import structlog
4
- from opentelemetry import trace
6
+ from opentelemetry import baggage, trace
7
+ from opentelemetry import context as otel_context
8
+ from opentelemetry.baggage.propagation import W3CBaggagePropagator
5
9
  from opentelemetry.sdk.trace import (
6
10
  TracerProvider,
7
11
  )
@@ -54,9 +58,14 @@ class TracerInstrumentator:
54
58
  return format(current_span.context.trace_id, "032x")
55
59
 
56
60
  def get_telemetry_carrier(self):
57
- prop = TraceContextTextMapPropagator()
61
+ """The W3C ``traceparent`` and ``baggage`` headers of the current context.
62
+
63
+ Empty when the current context has neither. The SDK sends them on its
64
+ calls to Main Sequence and to the applications on it (ADR 0040).
65
+ """
58
66
  telemetry_carrier = {}
59
- prop.inject(carrier=telemetry_carrier)
67
+ TraceContextTextMapPropagator().inject(carrier=telemetry_carrier)
68
+ W3CBaggagePropagator().inject(carrier=telemetry_carrier)
60
69
  return telemetry_carrier
61
70
 
62
71
  def append_attribute_to_current_span(self, attribute_key, attribute_value):
@@ -97,3 +106,92 @@ class OTelJSONRenderer(structlog.processors.JSONRenderer):
97
106
 
98
107
  # 3) Now call the base JSONRenderer to produce final JSON
99
108
  return super().__call__(logger, method_name, event_dict)
109
+
110
+
111
+ # Caller context (ADR 0040): the W3C ``traceparent`` and ``baggage`` an
112
+ # application receives and passes on. The SDK carries every baggage key the
113
+ # same way and gives none of them a meaning.
114
+
115
+ _parsing_baggage: ContextVar[bool] = ContextVar("mainsequence_parsing_baggage", default=False)
116
+
117
+
118
+ class _QuietBaggageParser(logging.Filter):
119
+ """Drop the parser's warnings while the SDK parses: they quote the header."""
120
+
121
+ def filter(self, record):
122
+ return not _parsing_baggage.get()
123
+
124
+
125
+ logging.getLogger("opentelemetry.baggage.propagation").addFilter(_QuietBaggageParser())
126
+
127
+
128
+ def _with_baggage_header(header, context):
129
+ """``context`` with the members of one W3C ``baggage`` header added.
130
+
131
+ The parser's limits apply: a header over 8192 bytes is ignored whole, a
132
+ member over 4096 bytes is skipped and at most 180 members are read. W3C
133
+ properties, after a member's ``;``, are dropped, as the platform drops them,
134
+ so each value reads as the platform records it. Malformed input is skipped
135
+ and never raises.
136
+ """
137
+ if not header or len(header.encode()) > W3CBaggagePropagator._MAX_HEADER_LENGTH:
138
+ return context
139
+ # Properties follow an unencoded ';', so an encoded ';' inside a value survives.
140
+ members = ",".join(member.split(";", 1)[0] for member in header.split(","))
141
+ token = _parsing_baggage.set(True)
142
+ try:
143
+ return W3CBaggagePropagator().extract({"baggage": members}, context=context)
144
+ except Exception:
145
+ return context
146
+ finally:
147
+ _parsing_baggage.reset(token)
148
+
149
+
150
+ def _request_context(carrier, *, with_baggage):
151
+ """The OpenTelemetry context of one inbound request, from its headers.
152
+
153
+ Its baggage is exactly the request's ``baggage`` header, or none without
154
+ ``with_baggage``: never the process's or another request's. Its trace
155
+ parent is the request's ``traceparent``, unless instrumentation already
156
+ records a span for the request.
157
+ """
158
+ context = baggage.clear(context=otel_context.get_current())
159
+ if with_baggage:
160
+ context = _with_baggage_header(carrier.get("baggage"), context)
161
+ if not trace.get_current_span(context).is_recording():
162
+ context = TraceContextTextMapPropagator().extract(carrier, context=context)
163
+ return context
164
+
165
+
166
+ def _attach_environment_context():
167
+ """Attach a Job run's ``TRACEPARENT`` and ``BAGGAGE`` as the process's context.
168
+
169
+ The platform starts a run created by a request that carried caller context
170
+ with both variables, in W3C header format. Without either, nothing changes.
171
+ The context is attached to the calling thread, as any OpenTelemetry context.
172
+ """
173
+ traceparent = os.environ.get("TRACEPARENT")
174
+ baggage_header = os.environ.get("BAGGAGE")
175
+ if not traceparent and not baggage_header:
176
+ return
177
+ context = _with_baggage_header(
178
+ baggage_header, baggage.clear(context=otel_context.get_current())
179
+ )
180
+ if traceparent:
181
+ context = TraceContextTextMapPropagator().extract(
182
+ {"traceparent": traceparent}, context=context
183
+ )
184
+ otel_context.attach(context)
185
+
186
+
187
+ def _add_log_baggage(logger, method_name, event_dict):
188
+ """Add the current context's ``mainsequence.`` baggage keys as ``baggage``."""
189
+ if "baggage" not in event_dict:
190
+ members = {
191
+ key: str(value)
192
+ for key, value in baggage.get_all().items()
193
+ if key.startswith("mainsequence.")
194
+ }
195
+ if members:
196
+ event_dict["baggage"] = members
197
+ return event_dict
mainsequence/logconf.py CHANGED
@@ -22,6 +22,7 @@ from structlog.stdlib import BoundLogger
22
22
  from ._transport import DeadlineHTTPAdapter, request_budget
23
23
  from .defaults import resolve_backend_endpoint
24
24
  from .instrumentation import OTelJSONRenderer
25
+ from .instrumentation.utils import _add_log_baggage
25
26
  from .repository_identity_security import UNSUPPORTED_SOURCE_IDENTITY_ENV_NAMES
26
27
  from .runtime_credential_exchange import (
27
28
  RUNTIME_CREDENTIAL_ID_ENV,
@@ -345,6 +346,7 @@ def build_application_logger(application_name: str = "ms-sdk", **metadata):
345
346
  pre_chain = [
346
347
  structlog.stdlib.add_log_level,
347
348
  structlog.stdlib.ExtraAdder(),
349
+ _add_log_baggage,
348
350
  timestamper,
349
351
  ]
350
352
 
@@ -413,6 +415,7 @@ def build_application_logger(application_name: str = "ms-sdk", **metadata):
413
415
  structlog.configure(
414
416
  processors=[
415
417
  structlog.contextvars.merge_contextvars, # context that always appears in the logs
418
+ _add_log_baggage, # the caller context's mainsequence. keys (ADR 0040)
416
419
  structlog.stdlib.add_log_level,
417
420
  structlog.stdlib.PositionalArgumentsFormatter(),
418
421
  structlog.processors.CallsiteParameterAdder(
@@ -12,6 +12,7 @@ from urllib.parse import urlsplit
12
12
  from uuid import UUID
13
13
 
14
14
  import requests
15
+ from opentelemetry import context as otel_context
15
16
 
16
17
  from mainsequence._request_identity import (
17
18
  RequestIdentityError,
@@ -21,6 +22,7 @@ from mainsequence._request_identity import (
21
22
  )
22
23
  from mainsequence._team_memberships import TeamMembershipCache
23
24
  from mainsequence.client.models_user import RequestUserIdentity
25
+ from mainsequence.instrumentation.utils import _request_context
24
26
 
25
27
  from .caller_assertions import (
26
28
  ASSERTION_HEADER,
@@ -107,6 +109,17 @@ def _header(scope, name):
107
109
  return values[0] if values else None
108
110
 
109
111
 
112
+ def _trace_carrier(scope):
113
+ """The request's W3C trace context and baggage headers; repeated fields are joined."""
114
+ carrier = {}
115
+ for key, value in scope.get("headers", ()):
116
+ name = key.lower()
117
+ if name in {b"traceparent", b"tracestate", b"baggage"}:
118
+ name, value = name.decode("latin-1"), value.decode("latin-1")
119
+ carrier[name] = f"{carrier[name]},{value}" if name in carrier else value
120
+ return carrier
121
+
122
+
110
123
  def _local_user(scope):
111
124
  authorization = _header(scope, b"authorization") or ""
112
125
  scheme, separator, token = authorization.partition(" ")
@@ -201,6 +214,7 @@ class _RequestIdentityMiddleware:
201
214
  return
202
215
  state = scope.setdefault("state", {})
203
216
  state.update(user=None, user_uid=None, auth_outcome="anonymous")
217
+ caller_verified = False
204
218
  with _request_scope() as context:
205
219
  try:
206
220
  public = (
@@ -248,6 +262,7 @@ class _RequestIdentityMiddleware:
248
262
  else:
249
263
  user = await asyncio.to_thread(_local_user, scope)
250
264
  context.user = user
265
+ caller_verified = True
251
266
  state.update(user=user, user_uid=user.uid, auth_outcome="authenticated")
252
267
  scope["headers"] = [
253
268
  (k, v)
@@ -264,7 +279,15 @@ class _RequestIdentityMiddleware:
264
279
  state["auth_outcome"] = "unavailable" if error.status == 503 else "rejected"
265
280
  await _deny(scope, receive, send, error)
266
281
  return
267
- await self.app(scope, receive, send)
282
+ # The caller context arrives next to the caller verified above, and
283
+ # only with one: a public or preflight request has no baggage (ADR 0040).
284
+ context_token = otel_context.attach(
285
+ _request_context(_trace_carrier(scope), with_baggage=caller_verified)
286
+ )
287
+ try:
288
+ await self.app(scope, receive, send)
289
+ finally:
290
+ otel_context.detach(context_token)
268
291
 
269
292
 
270
293
  def install_request_identity(app, *, team_membership_cache_seconds=0):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mainsequence
3
- Version: 9.0.36.dev83
3
+ Version: 9.0.36.dev85
4
4
  Summary: Main Sequence SDK
5
5
  Author-email: Main Sequence GmbH <dev@main-sequence.io>
6
6
  License-Expression: MIT
@@ -7,16 +7,16 @@ agent_scaffold/skills/maintenance/metatables_transition/SKILL.md,sha256=Pisgpytc
7
7
  agent_scaffold/skills/platform_operations/access_control_and_sharing/SKILL.md,sha256=k3SYqiU-IuWm1IunlrAQY9NaCANlq6EjqCFN0gGcuiQ,29673
8
8
  agent_scaffold/skills/platform_operations/orchestration_and_releases/SKILL.md,sha256=hdGavnuDYYN8aBM3xWjOaKV3w7rc5rrLTRouRGnffc4,17670
9
9
  agent_scaffold/skills/sdk_code_repository_execution/SKILL.md,sha256=7hBAJuDOKdZUcGoqR7Y4nMHZ9kX5fuY6CMOcgdDaPWI,7046
10
- mainsequence/__init__.py,sha256=70CbIo7ZG1mzi5uwkqDtVESunBE0RanHjeFg4ptfsA0,385
10
+ mainsequence/__init__.py,sha256=lC_XotSSB3IBMjilFUUJpq_QGoaCoTN9AocNPapNkNo,563
11
11
  mainsequence/__main__.py,sha256=KuAP69uduS2ImrPIgNMzbGBRepZzjqvUONu5vFh4v4A,176
12
12
  mainsequence/_request_identity.py,sha256=suRjESLA_YY_TAxE2htWHd07gvPhJGr-1GtpFnjaVTc,5543
13
13
  mainsequence/_team_memberships.py,sha256=LQsn635Qw2VwhUQ4Ld8qa7utqXsAhO_0IFrf-kqzVk0,1771
14
- mainsequence/_transport.py,sha256=gFSw5bl4O2o3NwZOk-ueNnTQvySBecyhC2-7OPb-BPk,8425
14
+ mainsequence/_transport.py,sha256=K52a1AhOVLfSSR0C6k0rn2-VbF2VnAkfVBc3iSy8PM0,8742
15
15
  mainsequence/bootstrap.py,sha256=TY1vsn4TYE_5HGDg2do6czZjauTMi1GoSA1kTEKS2gw,3209
16
16
  mainsequence/code_repository_context.py,sha256=JRrWjwpnUy8I-OjSd9hHlrcq8-Ow3Zeh_N6cYvmtA3o,28545
17
17
  mainsequence/code_repository_skills.py,sha256=AyC1HFAxQXHXNBGbarVUJS2cHd4X5HwDx6u8XBophbE,23611
18
18
  mainsequence/defaults.py,sha256=5r6s7AI-X40rpm1D3IgcNsWam7iJg4_lIxB3F_1u2z0,408
19
- mainsequence/logconf.py,sha256=q4aTXScwR3lW1nOB3KdamwUDRR7dNeKvmfFtp36msI0,20274
19
+ mainsequence/logconf.py,sha256=LosTSjilPpT5d3i4SOjtQkYOGzoB_AhqP6ImEJlEDvc,20436
20
20
  mainsequence/repository_identity_security.py,sha256=Cdywndhiy1zJFUPh-FfM90RjZ3Hg3tjhxBr64FRhmXs,1035
21
21
  mainsequence/runtime_credential_exchange.py,sha256=WxSj2qpWWsuSeaNpPgfJkhpmFdjdzLWSjEQDMpzq7Ic,6928
22
22
  mainsequence/runtime_flags.py,sha256=1eTM7VRRhnuZ_GXcmFhqAmdEKwyQYMyZcPsio88vJRQ,378
@@ -44,26 +44,26 @@ mainsequence/client/client.py,sha256=Jaw9RYObdVDS5J2O0pln99-XpuW9e4vW-SsbJRNldfw
44
44
  mainsequence/client/compute_validation.py,sha256=ByeX0CkIE7qq06ggZFfN92U3Qp2e9cvo2RTIGWa5_Vw,6662
45
45
  mainsequence/client/exceptions.py,sha256=xx2L4l3OMNsTybbYkiTKK398ahnutEascM0It35tGr0,3815
46
46
  mainsequence/client/github_issues.py,sha256=pSTUw3UPrmE6wqnpoJctartTaNSq6iu6PQRrd8hip6I,14568
47
- mainsequence/client/inference.py,sha256=tYKHRxLR6mA5iLmgd3qURwweWc2OPQuw0__tD3LQgSI,7748
47
+ mainsequence/client/inference.py,sha256=BwwZSQ0auih58fQ0HmBeTAwIx8Od2uIsoRJrmyNN5PA,7938
48
48
  mainsequence/client/models_foundry.py,sha256=aHks-RcJtqNz-ZxZjxbd6x8B2Y79cV16G7GIEicYk-o,46397
49
49
  mainsequence/client/models_helpers.py,sha256=6we2XFTyp_G_EHXEcGiXHKgeDFplW135RFljgIN7v2o,52310
50
50
  mainsequence/client/models_user.py,sha256=txBjrW81jP1JvTwu_qMwiCgZZMaDc1X5C6SxBD9-zBw,53608
51
51
  mainsequence/client/object_access.py,sha256=OUZvhOQNfe3Q6sr4K9tz3X35Myp1LteIX8IiAvo1W_4,22900
52
52
  mainsequence/client/observability.py,sha256=_WrDKCaNk_TXmKElKCXC1inork6Exxxe8FRY4m1GI9s,16008
53
- mainsequence/client/utils.py,sha256=67k1MWAj6ElsTdj-C_b8vox7q39KRYRrNsLSU5TALMc,38278
53
+ mainsequence/client/utils.py,sha256=BoCyp8g28MTYa4e7sHmBkE92-_B0UBtM9QCw-1-6eEc,38635
54
54
  mainsequence/client/value_sets.py,sha256=7TA-mpuAd3hOduNgO1WTQQTuNOGaFgue-VqCsDWKaC8,6181
55
55
  mainsequence/instrumentation/__init__.py,sha256=J_9XmfjprElvz0u2t9rTyJT0kFdyKpxdbkdQiaw28_U,316
56
- mainsequence/instrumentation/utils.py,sha256=b-ihjSioAepeLfMpudM2SqCtvnxMqIXileHx3klBCQU,3377
56
+ mainsequence/instrumentation/utils.py,sha256=Syn07w0LFV3XTMkElUetNt_uguQeB4t-rvAFxvivPmE,7351
57
57
  mainsequence/server/__init__.py,sha256=BHUAhtdWPDRdxX07NYO_6wrBv5mf0GsXflecO52PmUc,73
58
58
  mainsequence/server/caller_assertions.py,sha256=IUQ74UL3VqCAAuujTGk3DzCPogRYhWRD9rVoWezdWdU,11979
59
- mainsequence/server/fastapi.py,sha256=M5zDoFIu9MzuQZdLOXvQPU9Yyqyf_GyXWVn_aravHH4,20123
59
+ mainsequence/server/fastapi.py,sha256=uwdO67LltkKWKsdZ-pKvWWAdtJ-2hcgGSAmIZ6gVNTk,21174
60
60
  mainsequence/server/mcp_skills.py,sha256=-krRwAHCAMipScgGJ19uVkzznhTop1Nz4C_wRY1GUpw,16690
61
61
  mainsequence/server/_mcp_skills_upstream/__init__.py,sha256=px283qBMf3z1nxCfN3WHrH9v8Y8jOb1xoBqZMRZcaD8,2694
62
62
  mainsequence/server/_mcp_skills_upstream/server.py,sha256=laHsfpoaYX3LcwQ04-GN7r0_C63fG6CzyXDci2rmbHE,7695
63
63
  mainsequence/server/_mcp_skills_upstream/shared.py,sha256=JmnX9PoLoyi93nBYnUEPWCdPXor_nQHjHptQDXpFzPs,11978
64
- mainsequence-9.0.36.dev83.dist-info/licenses/LICENSE,sha256=b6Ecsk8wjsEby3lbSzdljR6hHiFGHBizt9iWV2p1c_I,1074
65
- mainsequence-9.0.36.dev83.dist-info/METADATA,sha256=tvNcmF12Iac4vQ2nKFYOa2LLXWp8h6usjvRDtLJzQJY,7867
66
- mainsequence-9.0.36.dev83.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
67
- mainsequence-9.0.36.dev83.dist-info/entry_points.txt,sha256=XGAOq3-mF2lWWpeRJvoaWyMarRcK167mH1g124aGdUs,88
68
- mainsequence-9.0.36.dev83.dist-info/top_level.txt,sha256=BFeblM_Q9q0cUWBvTxnfWcWQEHtf5XZi9nOS-Gdfwus,28
69
- mainsequence-9.0.36.dev83.dist-info/RECORD,,
64
+ mainsequence-9.0.36.dev85.dist-info/licenses/LICENSE,sha256=b6Ecsk8wjsEby3lbSzdljR6hHiFGHBizt9iWV2p1c_I,1074
65
+ mainsequence-9.0.36.dev85.dist-info/METADATA,sha256=WaX7YBl54k0b5pSChGTb1_JSihOgu-KdyImTvWGjqrY,7867
66
+ mainsequence-9.0.36.dev85.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
67
+ mainsequence-9.0.36.dev85.dist-info/entry_points.txt,sha256=XGAOq3-mF2lWWpeRJvoaWyMarRcK167mH1g124aGdUs,88
68
+ mainsequence-9.0.36.dev85.dist-info/top_level.txt,sha256=BFeblM_Q9q0cUWBvTxnfWcWQEHtf5XZi9nOS-Gdfwus,28
69
+ mainsequence-9.0.36.dev85.dist-info/RECORD,,