struct-sdk 0.5.2__tar.gz → 0.5.11__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 (37) hide show
  1. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/PKG-INFO +1 -1
  2. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/pyproject.toml +1 -1
  3. struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation/__init__.py +4 -0
  4. struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation/config.py +569 -0
  5. struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation/export.py +861 -0
  6. struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation/otlp_sender.py +226 -0
  7. struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation/poller.py +519 -0
  8. struct_sdk-0.5.11/src/struct_sdk/_dynamic_instrumentation/snapshot.py +662 -0
  9. struct_sdk-0.5.11/src/struct_sdk/_fork_safe_http.py +70 -0
  10. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/core.py +17 -4
  11. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/.gitignore +0 -0
  12. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/LICENSE +0 -0
  13. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/README.md +0 -0
  14. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/__init__.py +0 -0
  15. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/_auto.py +0 -0
  16. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/_container.py +0 -0
  17. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/_distro.py +0 -0
  18. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/_event_loop.py +0 -0
  19. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/_genai_content.py +0 -0
  20. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/_metrics.py +0 -0
  21. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/_operation_details.py +0 -0
  22. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/_pool.py +0 -0
  23. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/ag2.py +0 -0
  24. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/anthropic.py +0 -0
  25. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/autogen.py +0 -0
  26. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/claude_agent.py +0 -0
  27. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/crewai.py +0 -0
  28. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/gcp.py +0 -0
  29. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/google_genai.py +0 -0
  30. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/langchain.py +0 -0
  31. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/litellm.py +0 -0
  32. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/llamaindex.py +0 -0
  33. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/mcp.py +0 -0
  34. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/openai.py +0 -0
  35. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/openai_agents.py +0 -0
  36. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/pydantic_ai.py +0 -0
  37. {struct_sdk-0.5.2 → struct_sdk-0.5.11}/src/struct_sdk/temporal.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: struct-sdk
3
- Version: 0.5.2
3
+ Version: 0.5.11
4
4
  Summary: Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry
5
5
  Project-URL: Homepage, https://struct.ai
6
6
  Project-URL: Documentation, https://struct.ai/docs
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "struct-sdk"
7
- version = "0.5.2"
7
+ version = "0.5.11"
8
8
  description = "Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1,4 @@
1
+ """Dynamic instrumentation: configuration the SDK receives from the Struct API.
2
+
3
+ Nothing imports this package yet. ``struct.init()`` starts the client in a later change.
4
+ """
@@ -0,0 +1,569 @@
1
+ """Verify a ``struct-config/1`` package and build the state it produces.
2
+
3
+ A package is a descriptor (JSON) plus a gzip payload of JSON lines. Everything here is pure: no
4
+ network, no threads and no shared state. ``apply_package`` builds a whole new ``ReceivedConfig``
5
+ or raises ``ConfigRejected``, so a bad package can never leave a half-applied state behind.
6
+
7
+ Records stay as the bytes they arrived in and are parsed only when asked for, because a Python
8
+ object tree for a large scope costs several times the size of its JSON.
9
+
10
+ Fixtures: ``packages/sil-contracts/config/``. Decision: ADR-20261105-1303.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import math
18
+ import re
19
+ import sys
20
+ import time
21
+ import zlib
22
+ from dataclasses import dataclass
23
+ from datetime import datetime
24
+ from typing import Any, Callable, Iterator, Mapping, Optional
25
+
26
+ FORMAT = "struct-config/1"
27
+ DEFINITION_FORMAT = "sil-definition/1"
28
+
29
+ # Where each code leads: the health reason a later change reports it under.
30
+ CONFIGURATION_FORBIDDEN = "configuration_forbidden"
31
+ CONFIGURATION_UNAVAILABLE = "configuration_unavailable"
32
+ CAPACITY_REJECTED = "capacity_rejected"
33
+
34
+ _SHA256 = re.compile(r"[0-9a-f]{64}")
35
+ # Goes into URLs and a header, so a value that can't be sent must not reach the state.
36
+ _ARTIFACT_ID = re.compile(r"[A-Za-z0-9_-]{1,64}")
37
+ _INFLATE_CHUNK = 64 * 1024
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class ConfigLimits:
42
+ """Starting defaults from the design. Observations follow the dogfood limit, 10k with 4 offers."""
43
+
44
+ max_compressed_bytes: int = 256 * 1024 * 1024
45
+ max_decoded_bytes: int = 1024 * 1024 * 1024
46
+ max_record_bytes: int = 1024 * 1024
47
+ max_observations: int = 10_000
48
+ max_offers: int = 4
49
+ max_overlays: int = 100_000
50
+
51
+
52
+ class ConfigRejected(Exception):
53
+ """A package failed verification. The previous verified state stays in force."""
54
+
55
+ def __init__(self, code: str, reason: str = CONFIGURATION_UNAVAILABLE) -> None:
56
+ super().__init__(code)
57
+ self.code = code
58
+ self.reason = reason
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class ConfigScope:
63
+ tenant_id: str
64
+ service: str
65
+ environment: str
66
+ incarnation: str
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class ArtifactRef:
71
+ revision: int
72
+ artifact_id: str
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class Descriptor:
77
+ scope: ConfigScope
78
+ kind: str
79
+ base: Optional[ArtifactRef]
80
+ result: ArtifactRef
81
+ head_revision: int
82
+ compressed_bytes: int
83
+ decoded_bytes: int
84
+ payload_sha256: str
85
+ server_now: datetime
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Overlay:
90
+ """A group of temporary contributions. ``deadline`` is on the client's suspend-aware clock.
91
+
92
+ ``deadline`` is None when this machine has no reliable clock: temporary capture is then
93
+ unavailable, because nothing could end it on time. ``record_bytes`` is the size of the record it
94
+ came from, which is what it counts for against the limit on retained state.
95
+ """
96
+
97
+ overlay_id: str
98
+ revision: int
99
+ expires_at: str
100
+ expiry_generation: int
101
+ deadline: Optional[float]
102
+ record_bytes: int
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class ReceivedConfig:
107
+ """One verified configuration, as received. Says nothing about what got installed."""
108
+
109
+ scope: ConfigScope
110
+ revision: int
111
+ artifact_id: str
112
+ definitions: Mapping[str, bytes]
113
+ observations: Mapping[str, bytes]
114
+ overlays: Mapping[str, Overlay]
115
+ # The definition IDs each observation uses, to check removals without parsing every record.
116
+ _definitions_used: Mapping[str, frozenset[str]]
117
+
118
+ def definition(self, definition_id: str) -> dict[str, Any]:
119
+ """The ``sil-definition/1`` artifact, parsed now. Raises KeyError if it isn't here."""
120
+ artifact: dict[str, Any] = json.loads(self.definitions[definition_id])["artifact"]
121
+ return artifact
122
+
123
+ def observation(self, observation_id: str) -> dict[str, Any]:
124
+ """The observation record, parsed now. Raises KeyError if it isn't here."""
125
+ record: dict[str, Any] = json.loads(self.observations[observation_id])
126
+ return record
127
+
128
+
129
+ def suspend_aware_clock() -> Optional[Callable[[], float]]:
130
+ """A clock that keeps counting while the machine sleeps, or None if there isn't one.
131
+
132
+ ``time.monotonic`` stops during suspend on Linux, so an overlay would outlive its deadline.
133
+ On macOS ``CLOCK_MONOTONIC`` keeps counting, unlike ``CLOCK_UPTIME_RAW``.
134
+ """
135
+ clock_id = {"linux": "CLOCK_BOOTTIME", "darwin": "CLOCK_MONOTONIC"}.get(sys.platform)
136
+ identifier = getattr(time, clock_id, None) if clock_id else None
137
+ if identifier is None:
138
+ return None
139
+
140
+ def read() -> float:
141
+ return time.clock_gettime(identifier)
142
+
143
+ try:
144
+ read()
145
+ except OSError: # A sandbox can refuse the call even where the constant exists.
146
+ return None
147
+ return read
148
+
149
+
150
+ def _invalid(code: str = "invalid_record") -> ConfigRejected:
151
+ return ConfigRejected(code)
152
+
153
+
154
+ def _strict_json(raw: bytes) -> Any:
155
+ def no_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
156
+ result: dict[str, Any] = {}
157
+ for key, value in pairs:
158
+ if key in result:
159
+ raise ValueError("duplicate key")
160
+ result[key] = value
161
+ return result
162
+
163
+ def no_constants(_: str) -> None:
164
+ raise ValueError("not JSON")
165
+
166
+ # The same number rules as the SIL contract's parser (R43), which the compiler follows. Types stay
167
+ # as written, because a definition's identity tells 1 and 1.0 apart.
168
+ def finite(text: str) -> float:
169
+ number = float(text)
170
+ if math.isinf(number):
171
+ raise ValueError("not finite")
172
+ return number
173
+
174
+ def signed_64_bit(text: str) -> int:
175
+ if len(text) > 20: # A sign and 19 digits, checked first so int() never sees a long run.
176
+ raise ValueError("out of range")
177
+ number = int(text)
178
+ if not -(2**63) <= number < 2**63:
179
+ raise ValueError("out of range")
180
+ return number
181
+
182
+ try:
183
+ return json.loads(
184
+ raw.decode("utf-8"),
185
+ object_pairs_hook=no_duplicate_keys,
186
+ parse_constant=no_constants,
187
+ parse_float=finite,
188
+ parse_int=signed_64_bit,
189
+ )
190
+ except (ValueError, RecursionError) as exc:
191
+ raise _invalid() from exc
192
+
193
+
194
+ def _canonical(value: Any) -> str:
195
+ """Stable text for comparing parsed JSON. Keeps ``1`` and ``1.0`` different, unlike ``==``."""
196
+ return json.dumps(value, sort_keys=True, separators=(",", ":"))
197
+
198
+
199
+ def _object(value: Any) -> dict[str, Any]:
200
+ if not isinstance(value, dict):
201
+ raise _invalid()
202
+ return value
203
+
204
+
205
+ def _text(record: Mapping[str, Any], key: str) -> str:
206
+ value = record.get(key)
207
+ if not isinstance(value, str) or not value:
208
+ raise _invalid()
209
+ return value
210
+
211
+
212
+ def _count(record: Mapping[str, Any], key: str) -> int:
213
+ value = record.get(key)
214
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
215
+ raise _invalid()
216
+ return value
217
+
218
+
219
+ def _time(value: Any) -> datetime:
220
+ if not isinstance(value, str):
221
+ raise _invalid()
222
+ try:
223
+ parsed = datetime.fromisoformat(value[:-1] + "+00:00" if value.endswith("Z") else value)
224
+ except ValueError as exc:
225
+ raise _invalid() from exc
226
+ if parsed.tzinfo is None:
227
+ raise _invalid()
228
+ return parsed
229
+
230
+
231
+ def _artifact_ref(value: Any) -> ArtifactRef:
232
+ record = _object(value)
233
+ artifact_id = _text(record, "artifactId")
234
+ if _ARTIFACT_ID.fullmatch(artifact_id) is None:
235
+ raise _invalid()
236
+ return ArtifactRef(revision=_count(record, "revision"), artifact_id=artifact_id)
237
+
238
+
239
+ def parse_descriptor(raw: bytes, *, service: str, environment: str, limits: ConfigLimits) -> Descriptor:
240
+ """Check a descriptor on its own, before any payload is downloaded."""
241
+ record = _strict_json(raw)
242
+ if not isinstance(record, dict):
243
+ raise _invalid("invalid_descriptor")
244
+ if record.get("format") != FORMAT:
245
+ raise _invalid("unsupported_format")
246
+ try:
247
+ scope_record = _object(record.get("scope"))
248
+ scope = ConfigScope(
249
+ tenant_id=_text(scope_record, "tenantId"),
250
+ service=_text(scope_record, "service"),
251
+ environment=_text(scope_record, "environment"),
252
+ incarnation=_text(scope_record, "incarnation"),
253
+ )
254
+ kind = record.get("kind")
255
+ if kind not in ("full", "changes") or not isinstance(kind, str):
256
+ raise _invalid()
257
+ base_record = record.get("base")
258
+ if (base_record is None) != (kind == "full"):
259
+ raise _invalid()
260
+ descriptor = Descriptor(
261
+ scope=scope,
262
+ kind=kind,
263
+ base=None if base_record is None else _artifact_ref(base_record),
264
+ result=_artifact_ref(record.get("result")),
265
+ head_revision=_count(_object(record.get("head")), "revision"),
266
+ compressed_bytes=_count(record, "compressedBytes"),
267
+ decoded_bytes=_count(record, "decodedBytes"),
268
+ payload_sha256=_text(record, "payloadSha256"),
269
+ server_now=_time(record.get("serverNow")),
270
+ )
271
+ except ConfigRejected as exc:
272
+ raise _invalid("invalid_descriptor") from exc
273
+ if _SHA256.fullmatch(descriptor.payload_sha256) is None:
274
+ raise _invalid("invalid_descriptor")
275
+ if descriptor.head_revision < descriptor.result.revision:
276
+ raise _invalid("invalid_descriptor")
277
+ if descriptor.base is not None and descriptor.base.revision >= descriptor.result.revision:
278
+ raise _invalid("invalid_descriptor")
279
+ if scope.service != service or scope.environment != environment:
280
+ raise _invalid("wrong_scope")
281
+ if descriptor.compressed_bytes > limits.max_compressed_bytes or descriptor.decoded_bytes > limits.max_decoded_bytes:
282
+ raise _invalid("payload_too_large")
283
+ return descriptor
284
+
285
+
286
+ def needs_download(current: Optional[ReceivedConfig], descriptor: Descriptor) -> bool:
287
+ """Whether this descriptor moves us forward. False if it names what we already hold."""
288
+ if current is None:
289
+ if descriptor.kind != "full":
290
+ raise _invalid("base_mismatch")
291
+ return True
292
+ if descriptor.scope.tenant_id != current.scope.tenant_id:
293
+ raise _invalid("wrong_scope")
294
+ if descriptor.scope.incarnation != current.scope.incarnation:
295
+ # The scope was recreated: its revisions start again, and only a full package can apply.
296
+ if descriptor.kind != "full":
297
+ raise _invalid("wrong_scope")
298
+ return True
299
+ if descriptor.result.revision < current.revision:
300
+ raise _invalid("stale_response")
301
+ if descriptor.result == ArtifactRef(current.revision, current.artifact_id):
302
+ return False
303
+ # A full snapshot can share a revision with the changes package that got us there, under its
304
+ # own artifact ID. It describes the same state, so it applies like any other full package.
305
+ if descriptor.kind == "changes" and descriptor.base != ArtifactRef(current.revision, current.artifact_id):
306
+ raise _invalid("base_mismatch")
307
+ return True
308
+
309
+
310
+ def _payload_lines(descriptor: Descriptor, compressed: bytes, limits: ConfigLimits) -> Iterator[bytes]:
311
+ """Check size and hash, then inflate a chunk at a time, stopping as soon as a limit is passed."""
312
+ if len(compressed) != descriptor.compressed_bytes:
313
+ raise _invalid("size_mismatch")
314
+ if hashlib.sha256(compressed).hexdigest() != descriptor.payload_sha256:
315
+ raise _invalid("hash_mismatch")
316
+ inflater = zlib.decompressobj(wbits=31) # gzip framing
317
+ decoded = 0
318
+ pending = b""
319
+ fed = 0
320
+ remaining = b""
321
+ try:
322
+ while not inflater.eof:
323
+ # Bounded input too: zlib copies whatever it doesn't consume back out on every call.
324
+ if not remaining:
325
+ remaining = compressed[fed : fed + _INFLATE_CHUNK]
326
+ fed += len(remaining)
327
+ # Bounded output: a payload that inflates past its declared size stops within one chunk.
328
+ chunk = inflater.decompress(remaining, _INFLATE_CHUNK)
329
+ remaining = inflater.unconsumed_tail
330
+ decoded += len(chunk)
331
+ if decoded > descriptor.decoded_bytes:
332
+ raise _invalid("size_mismatch")
333
+ if not chunk and not remaining and fed == len(compressed):
334
+ break
335
+ pending += chunk
336
+ *lines, pending = pending.split(b"\n")
337
+ for line in lines:
338
+ if len(line) > limits.max_record_bytes:
339
+ raise _invalid("record_too_large")
340
+ yield line
341
+ if len(pending) > limits.max_record_bytes:
342
+ raise _invalid("record_too_large")
343
+ except zlib.error as exc:
344
+ raise _invalid("invalid_payload") from exc
345
+ if not inflater.eof or inflater.unused_data or fed != len(compressed):
346
+ raise _invalid("invalid_payload")
347
+ if decoded != descriptor.decoded_bytes:
348
+ raise _invalid("size_mismatch")
349
+ if pending:
350
+ yield pending
351
+
352
+
353
+ class _Staging:
354
+ """The state being built. Discarded on any rejection, so nothing here touches ``current``."""
355
+
356
+ def __init__(
357
+ self,
358
+ current: Optional[ReceivedConfig],
359
+ descriptor: Descriptor,
360
+ request_started: Optional[float],
361
+ limits: ConfigLimits,
362
+ ) -> None:
363
+ self.descriptor = descriptor
364
+ self.limits = limits
365
+ self.request_started = request_started
366
+ same_epoch = current is not None and current.scope.incarnation == descriptor.scope.incarnation
367
+ # What this scope already held: IDs in it are immutable whichever kind of package arrives.
368
+ self.known = current
369
+ self.known_in_epoch = current if same_epoch else None
370
+ carry = current if descriptor.kind == "changes" else None
371
+ self.definitions: dict[str, bytes] = dict(carry.definitions) if carry else {}
372
+ self.observations: dict[str, bytes] = dict(carry.observations) if carry else {}
373
+ self.overlays: dict[str, Overlay] = dict(carry.overlays) if carry else {}
374
+ self.used: dict[str, frozenset[str]] = dict(carry._definitions_used) if carry else {}
375
+ self.seen: set[tuple[str, str]] = set()
376
+ # Only what ``finish`` needs. Holding parsed records here would cost far more than the JSON.
377
+ self.touched: set[str] = set()
378
+ self.overlays_used: set[str] = set()
379
+ self.definitions_added = 0
380
+
381
+ def _first_sight(self, record_kind: str, identifier: str) -> None:
382
+ if (record_kind, identifier) in self.seen:
383
+ raise _invalid("duplicate_record")
384
+ self.seen.add((record_kind, identifier))
385
+
386
+ def add(self, line: bytes) -> None:
387
+ record = _object(_strict_json(line))
388
+ kind = record.get("kind")
389
+ if kind == "definition":
390
+ self._add_definition(record, line)
391
+ elif kind == "observation":
392
+ self._add_observation(record, line)
393
+ elif kind == "overlay":
394
+ self._add_overlay(record, line)
395
+ elif kind == "removal":
396
+ self._remove(record)
397
+ else:
398
+ raise _invalid("unknown_record")
399
+
400
+ def _add_definition(self, record: dict[str, Any], line: bytes) -> None:
401
+ artifact = _object(record.get("artifact"))
402
+ if artifact.get("artifact_format") != DEFINITION_FORMAT:
403
+ raise _invalid("unsupported_format")
404
+ definition_id = _text(artifact, "definition_id")
405
+ self._first_sight("definition", definition_id)
406
+ known = self.known.definitions.get(definition_id) if self.known else None
407
+ # Identical bytes are the usual case on a full update, and need no parsing to confirm.
408
+ if known is not None and known != line and _canonical(json.loads(known)["artifact"]) != _canonical(artifact):
409
+ raise _invalid("immutable_id_mutated")
410
+ # Each one must end up in use, or ``finish`` refuses it as an orphan, so no valid package adds
411
+ # more than can be offered. This counts additions only: a replacement may arrive before the
412
+ # removal of what it replaces.
413
+ self.definitions_added += 1
414
+ if self.definitions_added > self.limits.max_observations * self.limits.max_offers:
415
+ raise ConfigRejected("too_many_definitions", CAPACITY_REJECTED)
416
+ self.definitions[definition_id] = line
417
+
418
+ def _add_observation(self, record: dict[str, Any], line: bytes) -> None:
419
+ observation_id = _text(record, "observationId")
420
+ self._first_sight("observation", observation_id)
421
+ incarnation = _text(record, "incarnation")
422
+ stop_serial = _count(record, "stopSerial")
423
+ _count(record, "baselineRevision")
424
+ if not isinstance(record.get("enabled"), bool):
425
+ raise _invalid()
426
+ memberships = record.get("memberships")
427
+ if not isinstance(memberships, list):
428
+ raise _invalid()
429
+ if len(memberships) > self.limits.max_offers:
430
+ raise ConfigRejected("too_many_offers", CAPACITY_REJECTED)
431
+ members: dict[str, tuple[str, str, Optional[str]]] = {}
432
+ for item in memberships:
433
+ membership = _object(item)
434
+ token = _text(membership, "token")
435
+ if token in members:
436
+ raise _invalid("duplicate_record")
437
+ _count(membership, "retirementGeneration")
438
+ owner = _object(membership.get("owner"))
439
+ owner_kind = owner.get("kind")
440
+ if owner_kind not in ("baseline", "overlay") or not isinstance(owner_kind, str):
441
+ raise _invalid()
442
+ overlay_id = _text(owner, "overlayId") if owner_kind == "overlay" else None
443
+ members[token] = (_text(membership, "definitionId"), owner_kind, overlay_id)
444
+ self._check_against_known(observation_id, line, incarnation, stop_serial, members)
445
+ self.touched.add(observation_id)
446
+ if len(self.touched) > self.limits.max_observations:
447
+ raise ConfigRejected("too_many_observations", CAPACITY_REJECTED)
448
+ self.observations[observation_id] = line
449
+ self.used[observation_id] = frozenset(member[0] for member in members.values())
450
+ self.overlays_used.update(member[2] for member in members.values() if member[2] is not None)
451
+
452
+ def _check_against_known(
453
+ self,
454
+ observation_id: str,
455
+ line: bytes,
456
+ incarnation: str,
457
+ stop_serial: int,
458
+ members: Mapping[str, tuple[str, str, Optional[str]]],
459
+ ) -> None:
460
+ raw = self.known_in_epoch.observations.get(observation_id) if self.known_in_epoch else None
461
+ if raw is None or raw == line:
462
+ return
463
+ known = json.loads(raw)
464
+ if known["incarnation"] != incarnation:
465
+ return
466
+ if stop_serial < known["stopSerial"]:
467
+ raise _invalid("stale_response")
468
+ for membership in known["memberships"]:
469
+ member = members.get(membership["token"])
470
+ owner = membership["owner"]
471
+ if member is not None and member != (membership["definitionId"], owner["kind"], owner.get("overlayId")):
472
+ raise _invalid("immutable_id_mutated")
473
+
474
+ def _add_overlay(self, record: dict[str, Any], line: bytes) -> None:
475
+ overlay_id = _text(record, "overlayId")
476
+ self._first_sight("overlay", overlay_id)
477
+ generation = _count(record, "expiryGeneration")
478
+ expires_at = record.get("expiresAt")
479
+ remaining = max(0.0, (_time(expires_at) - self.descriptor.server_now).total_seconds())
480
+ deadline = None if self.request_started is None else self.request_started + remaining
481
+ known = self.known_in_epoch.overlays.get(overlay_id) if self.known_in_epoch else None
482
+ if known is not None:
483
+ if generation < known.expiry_generation:
484
+ raise _invalid("stale_response")
485
+ # Only a new generation may move a deadline, so repeated polls can't extend one.
486
+ if generation == known.expiry_generation and known.deadline is not None and deadline is not None:
487
+ deadline = min(deadline, known.deadline)
488
+ self.overlays[overlay_id] = Overlay(
489
+ overlay_id=overlay_id,
490
+ revision=_count(record, "revision"),
491
+ expires_at=str(expires_at),
492
+ expiry_generation=generation,
493
+ deadline=deadline,
494
+ record_bytes=len(line),
495
+ )
496
+ if len(self.overlays) > self.limits.max_overlays:
497
+ raise ConfigRejected("too_many_overlays", CAPACITY_REJECTED)
498
+
499
+ def _remove(self, record: dict[str, Any]) -> None:
500
+ if self.descriptor.kind != "changes":
501
+ raise _invalid()
502
+ record_kind = record.get("recordKind")
503
+ if record_kind == "observation":
504
+ observation_id = _text(record, "observationId")
505
+ self._first_sight("observation", observation_id)
506
+ if observation_id not in self.observations:
507
+ raise _invalid("missing_reference")
508
+ del self.observations[observation_id]
509
+ del self.used[observation_id]
510
+ elif record_kind == "definition":
511
+ definition_id = _text(record, "definitionId")
512
+ self._first_sight("definition", definition_id)
513
+ if definition_id not in self.definitions:
514
+ raise _invalid("missing_reference")
515
+ del self.definitions[definition_id]
516
+ else:
517
+ raise _invalid("unknown_record")
518
+
519
+ def finish(self) -> ReceivedConfig:
520
+ if len(self.observations) > self.limits.max_observations:
521
+ raise ConfigRejected("too_many_observations", CAPACITY_REJECTED)
522
+ # A long run of change packages must not outgrow what one full snapshot may hold. Change
523
+ # packages can't remove an overlay, so only a full package clears them: going over asks for one.
524
+ retained = (
525
+ sum(map(len, self.definitions.values()))
526
+ + sum(map(len, self.observations.values()))
527
+ + sum(overlay.record_bytes for overlay in self.overlays.values())
528
+ )
529
+ if retained > self.limits.max_decoded_bytes:
530
+ raise ConfigRejected("too_much_retained", CAPACITY_REJECTED)
531
+ # Records can arrive in any order, so references are only checked once all have arrived.
532
+ if not self.overlays_used <= self.overlays.keys():
533
+ raise _invalid("missing_reference")
534
+ used = frozenset().union(*self.used.values())
535
+ if not used <= self.definitions.keys():
536
+ raise _invalid("missing_reference")
537
+ # A definition nothing uses would stay in memory for the life of the process.
538
+ if used != self.definitions.keys():
539
+ raise _invalid("orphan_definition")
540
+ return ReceivedConfig(
541
+ scope=self.descriptor.scope,
542
+ revision=self.descriptor.result.revision,
543
+ artifact_id=self.descriptor.result.artifact_id,
544
+ definitions=self.definitions,
545
+ observations=self.observations,
546
+ overlays=self.overlays,
547
+ _definitions_used=self.used,
548
+ )
549
+
550
+
551
+ def apply_package(
552
+ current: Optional[ReceivedConfig],
553
+ descriptor: Descriptor,
554
+ compressed: bytes,
555
+ *,
556
+ request_started: Optional[float],
557
+ limits: ConfigLimits,
558
+ ) -> ReceivedConfig:
559
+ """Build the state this package produces, or raise ``ConfigRejected``.
560
+
561
+ ``request_started`` is the suspend-aware clock reading from just before the descriptor request.
562
+ ``serverNow`` is later than that moment, so transit delay can only make an overlay end early.
563
+ It is None when there is no reliable clock.
564
+ """
565
+ needs_download(current, descriptor)
566
+ staging = _Staging(current, descriptor, request_started, limits)
567
+ for line in _payload_lines(descriptor, compressed, limits):
568
+ staging.add(line)
569
+ return staging.finish()