atlan-application-sdk-api 3.53.2__tar.gz → 3.54.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/PKG-INFO +2 -2
  2. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/api-files.txt +3 -0
  3. atlan_application_sdk_api-3.54.0/application_sdk/_runtime/cgroup.py +96 -0
  4. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/_runtime/offload.py +196 -47
  5. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/base.py +28 -9
  6. atlan_application_sdk_api-3.54.0/application_sdk/common/backoff.py +232 -0
  7. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/sql_filters.py +104 -2
  8. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/constants.py +7 -6
  9. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/contracts/events.py +11 -0
  10. atlan_application_sdk_api-3.54.0/application_sdk/credentials/requirements.py +383 -0
  11. atlan_application_sdk_api-3.54.0/application_sdk/credentials/utils.py +530 -0
  12. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/_warmup.py +8 -6
  13. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/context.py +66 -1
  14. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/metadata_routes.py +215 -9
  15. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/templates/contracts/incremental_sql.py +3 -3
  16. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/templates/contracts/sql_metadata.py +11 -2
  17. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/version.py +2 -2
  18. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/pyproject.toml +2 -2
  19. atlan_application_sdk_api-3.53.2/application_sdk/credentials/utils.py +0 -257
  20. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/.gitignore +0 -0
  21. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/README.md +0 -0
  22. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/__init__.py +0 -0
  23. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/_build_info.py +0 -0
  24. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/_context_errors.py +0 -0
  25. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/_install.py +0 -0
  26. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/_logging.py +0 -0
  27. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/_runtime/__init__.py +0 -0
  28. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/_runtime/progress.py +0 -0
  29. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/__init__.py +0 -0
  30. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/_interface.py +0 -0
  31. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/_sql_failure_classifier.py +0 -0
  32. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/http_errors.py +0 -0
  33. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/models.py +0 -0
  34. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/sql.py +0 -0
  35. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/sql_errors.py +0 -0
  36. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/sql_typecasters.py +0 -0
  37. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/clients/ssl_utils.py +0 -0
  38. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/__init__.py +0 -0
  39. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/_generated_tree.py +0 -0
  40. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/_listing.py +0 -0
  41. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/aws_utils.py +0 -0
  42. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/aws_utils_errors.py +0 -0
  43. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/build_identity.py +0 -0
  44. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/concurrency.py +0 -0
  45. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/errors.py +0 -0
  46. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/filter_matching.py +0 -0
  47. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/logger.py +0 -0
  48. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/models.py +0 -0
  49. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/sql_filters_errors.py +0 -0
  50. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/task_queue.py +0 -0
  51. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/types.py +0 -0
  52. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/common/utils.py +0 -0
  53. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/contracts/__init__.py +0 -0
  54. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/contracts/base.py +0 -0
  55. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/contracts/types.py +0 -0
  56. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/contracts/types_errors.py +0 -0
  57. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/credentials/__init__.py +0 -0
  58. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/credentials/errors.py +0 -0
  59. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/credentials/extra.py +0 -0
  60. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/credentials/ingress.py +0 -0
  61. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/credentials/ref.py +0 -0
  62. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/credentials/spec.py +0 -0
  63. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/credentials/types.py +0 -0
  64. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/errors/__init__.py +0 -0
  65. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/errors/base.py +0 -0
  66. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/errors/categories.py +0 -0
  67. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/errors/http.py +0 -0
  68. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/errors/leaves.py +0 -0
  69. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/errors/wire.py +0 -0
  70. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/__init__.py +0 -0
  71. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/_dispatch.py +0 -0
  72. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/asgi.py +0 -0
  73. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/base.py +0 -0
  74. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/contracts.py +0 -0
  75. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/manifest.py +0 -0
  76. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/object_routes.py +0 -0
  77. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/request_contract.py +0 -0
  78. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/routes.py +0 -0
  79. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/handler/service_errors.py +0 -0
  80. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/server/__init__.py +0 -0
  81. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/server/fastapi/models.py +0 -0
  82. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/templates/__init__.py +0 -0
  83. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/templates/contracts/__init__.py +0 -0
  84. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/templates/contracts/base_metadata_extraction.py +0 -0
  85. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/application_sdk/templates/contracts/sql_query.py +0 -0
  86. {atlan_application_sdk_api-3.53.2 → atlan_application_sdk_api-3.54.0}/hatch_build.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: atlan-application-sdk-api
3
- Version: 3.53.2
3
+ Version: 3.54.0
4
4
  Summary: Experimental: the handler surface of the Atlan Application SDK, for the consolidated API host
5
5
  Project-URL: Homepage, https://github.com/atlanhq/application-sdk
6
6
  Project-URL: Source, https://github.com/atlanhq/application-sdk/tree/main/packages/api
@@ -29,7 +29,7 @@ Provides-Extra: pandas
29
29
  Requires-Dist: pandas<3.0.0,>=2.2.3; extra == 'pandas'
30
30
  Provides-Extra: pyatlan
31
31
  Requires-Dist: authlib<2,>=1.9.1; extra == 'pyatlan'
32
- Requires-Dist: pyatlan<12,>=11.6.0; extra == 'pyatlan'
32
+ Requires-Dist: pyatlan<12,>=11.7.0; extra == 'pyatlan'
33
33
  Provides-Extra: sql
34
34
  Requires-Dist: httpx<0.29.0,>=0.27.0; extra == 'sql'
35
35
  Requires-Dist: python-dotenv<2.0.0,>=1.2.2; extra == 'sql'
@@ -7,6 +7,7 @@ application_sdk/_context_errors.py
7
7
  application_sdk/_install.py
8
8
  application_sdk/_logging.py
9
9
  application_sdk/_runtime/__init__.py
10
+ application_sdk/_runtime/cgroup.py
10
11
  application_sdk/_runtime/offload.py
11
12
  application_sdk/_runtime/progress.py
12
13
  application_sdk/clients/__init__.py
@@ -24,6 +25,7 @@ application_sdk/common/_generated_tree.py
24
25
  application_sdk/common/_listing.py
25
26
  application_sdk/common/aws_utils.py
26
27
  application_sdk/common/aws_utils_errors.py
28
+ application_sdk/common/backoff.py
27
29
  application_sdk/common/build_identity.py
28
30
  application_sdk/common/concurrency.py
29
31
  application_sdk/common/errors.py
@@ -46,6 +48,7 @@ application_sdk/credentials/errors.py
46
48
  application_sdk/credentials/extra.py
47
49
  application_sdk/credentials/ingress.py
48
50
  application_sdk/credentials/ref.py
51
+ application_sdk/credentials/requirements.py
49
52
  application_sdk/credentials/spec.py
50
53
  application_sdk/credentials/types.py
51
54
  application_sdk/credentials/utils.py
@@ -0,0 +1,96 @@
1
+ """The container's CPU limit, readable from the bottom layer (ADR-0019).
2
+
3
+ ``os.cpu_count()`` reports the node's cores, not the pod's: a worker limited to
4
+ one CPU on a 16-core node sees 16. Anything the substrate sizes by CPU — the
5
+ fault-isolation process pool in :mod:`application_sdk._runtime.offload` — reads
6
+ the limit here instead. :mod:`application_sdk.observability.cgroup` reports the
7
+ same number for sizing telemetry and delegates to this module, so the two can
8
+ never disagree about what the limit is.
9
+
10
+ Readers return ``None`` for "no usable limit", never a guessed number.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ import os
17
+
18
+ from application_sdk._logging import get_logger
19
+
20
+ logger = get_logger(__name__)
21
+
22
+ # v2 first: a host with both mounted must read v2, which is what the kernel enforces.
23
+ CPU_MAX_V2 = "/sys/fs/cgroup/cpu.max"
24
+ CPU_QUOTA_V1 = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
25
+ CPU_PERIOD_V1 = "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
26
+
27
+
28
+ def _read(path: str) -> str | None:
29
+ try:
30
+ with open(path, encoding="utf-8") as fh:
31
+ return fh.read().strip()
32
+ # conformance: ignore[E014] a missing cgroup file is the expected case off Linux and under partial hierarchies; None is the meaningful answer, and logging per read would fire on every call
33
+ except OSError:
34
+ return None
35
+
36
+
37
+ def _read_positive_int(path: str) -> int | None:
38
+ raw = _read(path)
39
+ if not raw:
40
+ return None
41
+ try:
42
+ value = int(raw)
43
+ # conformance: ignore[E014] an unparseable v1 file means "no usable number", the same answer as a missing one
44
+ except ValueError:
45
+ return None
46
+ # v1 writes -1 for unlimited.
47
+ return value if value > 0 else None
48
+
49
+
50
+ def cpu_quota_cores(cpu_max_v2: str, quota_v1: str, period_v1: str) -> float | None:
51
+ """The container's CPU limit in cores, or ``None`` when there is none.
52
+
53
+ The paths are parameters so a caller that keeps its own (patchable) copies
54
+ reads through the same parser rather than a second one; pass this module's
55
+ ``CPU_MAX_V2`` / ``CPU_QUOTA_V1`` / ``CPU_PERIOD_V1`` for the real ones.
56
+ """
57
+ raw = _read(cpu_max_v2)
58
+ if raw:
59
+ parts = raw.split()
60
+ if len(parts) == 2 and parts[0] != "max":
61
+ try:
62
+ quota, period = float(parts[0]), float(parts[1])
63
+ except ValueError:
64
+ logger.debug("unparseable cpu.max: %r", raw, exc_info=True)
65
+ else:
66
+ if quota > 0 and period > 0:
67
+ return quota / period
68
+
69
+ quota_us = _read_positive_int(quota_v1)
70
+ period_us = _read_positive_int(period_v1)
71
+ if quota_us and period_us:
72
+ return quota_us / period_us
73
+ return None
74
+
75
+
76
+ def _affinity_count() -> int:
77
+ """CPUs in this process's affinity mask, or the node's count without one."""
78
+ try:
79
+ return len(os.sched_getaffinity(0)) or 1 # type: ignore[attr-defined]
80
+ except AttributeError:
81
+ # No affinity API (macOS, Windows): the node's count is all there is.
82
+ return os.cpu_count() or 1
83
+
84
+
85
+ def available_cpus() -> int:
86
+ """Whole CPUs this process may use: the tighter of affinity and the CFS quota.
87
+
88
+ A fractional quota rounds down (1.5 cores → 1), never below 1: a pool sized
89
+ to the rounded-up figure would run more CPU-bound children than the quota
90
+ can schedule at once, and the extra ones only add memory and throttling.
91
+ """
92
+ cpus = _affinity_count()
93
+ quota = cpu_quota_cores(CPU_MAX_V2, CPU_QUOTA_V1, CPU_PERIOD_V1)
94
+ if quota is not None:
95
+ cpus = min(cpus, max(1, math.floor(quota)))
96
+ return cpus
@@ -33,6 +33,7 @@ from concurrent.futures.process import BrokenProcessPool
33
33
  from typing import Any, Generic, ParamSpec, TypeVar
34
34
 
35
35
  from application_sdk._logging import get_logger
36
+ from application_sdk._runtime.cgroup import available_cpus
36
37
  from application_sdk._runtime.progress import (
37
38
  DEFAULT_MAX_NO_PROGRESS_SECONDS,
38
39
  ProgressTracker,
@@ -1088,47 +1089,177 @@ def _report_detached_failure(future: "concurrent.futures.Future[Any]") -> None:
1088
1089
  # single thread but every lock, in whatever state the other threads left
1089
1090
  # them — a deadlock/corruption factory. spawn starts a clean interpreter.
1090
1091
  #
1091
- # Lazy and cached by width: callers passing the same max_workers share one
1092
- # ProcessPoolExecutor of that width, created on first use; distinct widths get
1093
- # distinct pools, so discarding one width's pool on a crash never disturbs
1094
- # another's. Processes that never need isolation never pay for a child.
1092
+ # Lazy, keyed by width, and reaped when idle: callers passing the same
1093
+ # max_workers share one ProcessPoolExecutor of that width, created on first use;
1094
+ # distinct widths get distinct pools, so discarding one width's pool on a crash
1095
+ # never disturbs another's. Processes that never need isolation never pay for a
1096
+ # child.
1097
+ #
1098
+ # Why reaped (FND-4278)? Each spawn child re-imports the parent's main module
1099
+ # and the decode stack — ~175 MiB apiece before it decodes a byte — and a pool
1100
+ # never shut down keeps every child it ever started for the worker's lifetime:
1101
+ # ~700 MiB of idle children sitting under the pod's memory limit after a single
1102
+ # burst of uploads. So once a pool has had nothing in flight for
1103
+ # FAULT_ISOLATION_IDLE_SECONDS it is shut down and its children exit; the next
1104
+ # call spawns afresh. That spawn cost lands on best-effort work with a
1105
+ # minutes-long timeout, which is the right side of the trade.
1106
+ #
1107
+ # Why not ``max_tasks_per_child=1``? CPython replaces a retired child eagerly,
1108
+ # as soon as the old one exits, not when the next task arrives — so the pool
1109
+ # still holds max_workers idle children between bursts. It only trades a warm
1110
+ # child for a cold one; it does not give the memory back.
1095
1111
  #
1096
1112
  # Concurrency: the default pool runs several children so concurrent best-effort
1097
1113
  # callers decode in PARALLEL, not serialised behind one child. Isolation here is
1098
- # purely fault containment — NOT a serialisation crutch to dodge the msgspec
1099
- # 0.20.0 concurrent-decode segfault: that bug is same-process (a shared
1100
- # in-process decoder across threads); separate child processes don't share that
1101
- # state, and once msgspec 0.21.1 lands even same-process concurrent decode is
1102
- # safe. The default width is capped low because each spawn child re-imports the
1103
- # decode stack (pyatlan/msgspec), which costs memory under a pod limit. A caller
1104
- # that wants to bound — or serialise (max_workers=1) — its own work passes an
1105
- # explicit width. (A crash in any one child breaks the whole ProcessPoolExecutor
1106
- # — inherent to the executor — so concurrent callers on that width then see
1107
- # BrokenProcessPool; for best-effort work that is a benign skip.)
1108
- _DEFAULT_PROCESS_POOL_MAX_WORKERS = min(4, (os.cpu_count() or 1))
1109
- _PROCESS_EXECUTORS: dict[int, concurrent.futures.ProcessPoolExecutor] = {}
1110
- _PROCESS_EXECUTORS_LOCK = threading.Lock()
1111
-
1112
-
1113
- def _get_process_executor(max_workers: int) -> concurrent.futures.ProcessPoolExecutor:
1114
- with _PROCESS_EXECUTORS_LOCK:
1115
- executor = _PROCESS_EXECUTORS.get(max_workers)
1116
- if executor is None:
1117
- executor = concurrent.futures.ProcessPoolExecutor(
1118
- max_workers=max_workers,
1119
- mp_context=multiprocessing.get_context("spawn"),
1120
- )
1121
- _PROCESS_EXECUTORS[max_workers] = executor
1122
- return executor
1114
+ # purely fault containment. It was introduced while msgspec 0.20.0 could
1115
+ # segfault on concurrent decode (CNCT-85); that bug was same-process and the
1116
+ # lock now pins 0.21.1, which fixes it. Isolation stays the default anyway:
1117
+ # ADR-0017's reason is that a native fault in *any* C extension on the decode
1118
+ # path must not take the worker down, and that holds whatever the msgspec
1119
+ # version. Now that the children exist only while there is work, keeping them
1120
+ # costs spawn latency, not resident memory.
1121
+ #
1122
+ # Width: ``min(4, CPUs available to the container)`` — the CFS quota, not
1123
+ # ``os.cpu_count()``, which reports the node's cores. A caller that wants to
1124
+ # bound — or serialise (max_workers=1) — its own work passes an explicit width.
1125
+ # (A crash in any one child breaks the whole ProcessPoolExecutor — inherent to
1126
+ # the executor — so concurrent callers on that width then see BrokenProcessPool;
1127
+ # for best-effort work that is a benign skip.)
1128
+ _MAX_DEFAULT_PROCESS_POOL_WIDTH = 4
1123
1129
 
1130
+ #: Env var: seconds a fault-isolation pool with nothing in flight keeps its
1131
+ #: children before shutting down. ``0`` shuts it down as soon as it goes idle.
1132
+ FAULT_ISOLATION_IDLE_SECONDS_ENV = "ATLAN_FAULT_ISOLATION_IDLE_SECONDS"
1133
+ _DEFAULT_FAULT_ISOLATION_IDLE_SECONDS = 30.0
1134
+ _REPORTED_BAD_IDLE_SECONDS: set[str] = set()
1124
1135
 
1125
- def _discard_process_executor(max_workers: int) -> None:
1126
- """Drop the width-``max_workers`` pool (and kill its children) so the next
1127
- call at that width starts fresh."""
1128
- with _PROCESS_EXECUTORS_LOCK:
1129
- executor = _PROCESS_EXECUTORS.pop(max_workers, None)
1130
- if executor is None:
1131
- return
1136
+
1137
+ @functools.cache
1138
+ def _default_process_pool_max_workers() -> int:
1139
+ """``min(4, CPUs the container may use)``, read once per process."""
1140
+ return min(_MAX_DEFAULT_PROCESS_POOL_WIDTH, available_cpus())
1141
+
1142
+
1143
+ def _idle_seconds() -> float:
1144
+ """The configured idle period, read on every release so it can be retuned.
1145
+
1146
+ An unparseable or negative value is logged once and replaced by the
1147
+ default rather than raised: raising here would fail isolated work over a
1148
+ configuration typo.
1149
+ """
1150
+ raw = os.environ.get(FAULT_ISOLATION_IDLE_SECONDS_ENV, "").strip()
1151
+ if not raw:
1152
+ return _DEFAULT_FAULT_ISOLATION_IDLE_SECONDS
1153
+ try:
1154
+ value = float(raw)
1155
+ except ValueError:
1156
+ value = -1.0
1157
+ if value >= 0 and value != float("inf"):
1158
+ return value
1159
+ if raw not in _REPORTED_BAD_IDLE_SECONDS:
1160
+ _REPORTED_BAD_IDLE_SECONDS.add(raw)
1161
+ logger.warning(
1162
+ "Ignoring %s=%r: expected a non-negative number of seconds; using %ss",
1163
+ FAULT_ISOLATION_IDLE_SECONDS_ENV,
1164
+ raw,
1165
+ _DEFAULT_FAULT_ISOLATION_IDLE_SECONDS,
1166
+ )
1167
+ return _DEFAULT_FAULT_ISOLATION_IDLE_SECONDS
1168
+
1169
+
1170
+ class _IsolationPool:
1171
+ """One width's executor and its in-flight count. Guarded by the pools lock.
1172
+
1173
+ ``in_flight`` counts submitted calls until their *child* finishes, not until
1174
+ their caller stops waiting: a caller that is cancelled leaves its child
1175
+ running, and reaping the pool under it would kill work still in progress.
1176
+ ``idle_generation`` invalidates an idle timer the moment new work arrives,
1177
+ so a timer that fires late can never reap a pool that has been busy since.
1178
+ ``reaped`` is set once an idle shutdown has joined every child, so a reader
1179
+ can observe the children's exit without calling ``waitpid`` itself (a second
1180
+ ``waitpid`` racing the executor's own join can misreport a reaped child as
1181
+ still running).
1182
+ """
1183
+
1184
+ __slots__ = ("executor", "in_flight", "idle_generation", "idle_timer", "reaped")
1185
+
1186
+ def __init__(self, max_workers: int) -> None:
1187
+ self.executor = concurrent.futures.ProcessPoolExecutor(
1188
+ max_workers=max_workers,
1189
+ mp_context=multiprocessing.get_context("spawn"),
1190
+ )
1191
+ self.in_flight = 0
1192
+ self.idle_generation = 0
1193
+ self.idle_timer: threading.Timer | None = None
1194
+ self.reaped = threading.Event()
1195
+
1196
+ def stop_idle_timer(self) -> None:
1197
+ self.idle_generation += 1
1198
+ if self.idle_timer is not None:
1199
+ self.idle_timer.cancel()
1200
+ self.idle_timer = None
1201
+
1202
+
1203
+ _PROCESS_POOLS: dict[int, _IsolationPool] = {}
1204
+ _PROCESS_POOLS_LOCK = threading.Lock()
1205
+
1206
+
1207
+ def _acquire_process_pool(max_workers: int) -> _IsolationPool:
1208
+ """The width-``max_workers`` pool, with one more call counted in flight."""
1209
+ with _PROCESS_POOLS_LOCK:
1210
+ pool = _PROCESS_POOLS.get(max_workers)
1211
+ if pool is None:
1212
+ pool = _IsolationPool(max_workers)
1213
+ _PROCESS_POOLS[max_workers] = pool
1214
+ pool.in_flight += 1
1215
+ pool.stop_idle_timer()
1216
+ return pool
1217
+
1218
+
1219
+ def _release_process_pool(max_workers: int, pool: _IsolationPool) -> None:
1220
+ """Count one call out; start the idle timer when the pool has none left."""
1221
+ with _PROCESS_POOLS_LOCK:
1222
+ pool.in_flight -= 1
1223
+ if pool.in_flight or _PROCESS_POOLS.get(max_workers) is not pool:
1224
+ return
1225
+ pool.stop_idle_timer()
1226
+ timer = threading.Timer(
1227
+ _idle_seconds(),
1228
+ _reap_idle_pool,
1229
+ args=(max_workers, pool, pool.idle_generation),
1230
+ )
1231
+ timer.daemon = True
1232
+ timer.name = f"sdk-isolation-idle-{max_workers}"
1233
+ pool.idle_timer = timer
1234
+ timer.start()
1235
+
1236
+
1237
+ def _reap_idle_pool(max_workers: int, pool: _IsolationPool, generation: int) -> None:
1238
+ """Shut the pool down if it is still the live, idle pool this timer was for."""
1239
+ with _PROCESS_POOLS_LOCK:
1240
+ if (
1241
+ pool.in_flight
1242
+ or pool.idle_generation != generation
1243
+ or _PROCESS_POOLS.get(max_workers) is not pool
1244
+ ):
1245
+ return
1246
+ del _PROCESS_POOLS[max_workers]
1247
+ pool.idle_timer = None
1248
+ # Outside the lock: a caller arriving now builds a fresh pool rather than
1249
+ # waiting for this one's children to exit. Nothing is queued or running, so
1250
+ # the children take the sentinel and exit, and joining them leaves no zombie.
1251
+ pool.executor.shutdown(wait=True)
1252
+ pool.reaped.set()
1253
+
1254
+
1255
+ def _discard_process_pool(max_workers: int, pool: _IsolationPool) -> None:
1256
+ """Drop ``pool`` (and kill its children) so the next call at this width
1257
+ starts fresh."""
1258
+ with _PROCESS_POOLS_LOCK:
1259
+ if _PROCESS_POOLS.get(max_workers) is pool:
1260
+ del _PROCESS_POOLS[max_workers]
1261
+ pool.stop_idle_timer()
1262
+ executor = pool.executor
1132
1263
  # Kill the children BEFORE shutdown(): a dead child is the pool's
1133
1264
  # well-trodden unwind path — the manager thread sees it, marks the pool
1134
1265
  # broken, resolves every still-queued work item with BrokenProcessPool,
@@ -1174,8 +1305,11 @@ async def run_fault_isolated(
1174
1305
  ``func`` must be a module-level function (pickled by reference).
1175
1306
  - ContextVars do **not** propagate — the child is a fresh interpreter.
1176
1307
  Have the child return data and log from the parent.
1177
- - The child imports ``func``'s module on first use (one-time cost,
1178
- amortized by the pooled worker).
1308
+ - The child imports ``func``'s module on first use. Children are pooled
1309
+ while calls keep arriving and exit once the pool has been idle for
1310
+ ``ATLAN_FAULT_ISOLATION_IDLE_SECONDS`` (default 30), so a call after a
1311
+ quiet spell pays a fresh spawn and import; idle children never hold
1312
+ memory for the worker's lifetime.
1179
1313
 
1180
1314
  Like :func:`run_in_thread`, the call is automatically wrapped in a progress
1181
1315
  hold (ADR-0018) so an isolated call — which emits nothing at all until the
@@ -1189,8 +1323,9 @@ async def run_fault_isolated(
1189
1323
  timeout: Seconds to wait before killing the child and raising
1190
1324
  ``TimeoutError``. ``None`` waits forever.
1191
1325
  max_workers: Width of the (width-keyed) process pool this call runs on.
1192
- ``None`` (default) uses ``min(4, cpu_count)`` so concurrent callers
1193
- decode in parallel. Pass ``1`` to opt into sequential execution —
1326
+ ``None`` (default) uses ``min(4, CPUs available to the container)``
1327
+ — the cgroup CPU limit, not the node's core count — so concurrent
1328
+ callers decode in parallel. Pass ``1`` to opt into sequential execution —
1194
1329
  all ``max_workers=1`` callers share a single child and queue behind
1195
1330
  one another; pass another integer to bound concurrency at a
1196
1331
  different width. Must be >= 1.
@@ -1204,7 +1339,9 @@ async def run_fault_isolated(
1204
1339
  discarded.
1205
1340
  InvalidInputValueError: ``max_workers`` is < 1 (also a ``ValueError``).
1206
1341
  """
1207
- workers = _DEFAULT_PROCESS_POOL_MAX_WORKERS if max_workers is None else max_workers
1342
+ workers = (
1343
+ _default_process_pool_max_workers() if max_workers is None else max_workers
1344
+ )
1208
1345
  if workers < 1:
1209
1346
  raise InvalidInputValueError(
1210
1347
  message=f"max_workers must be >= 1, got {workers}",
@@ -1234,9 +1371,21 @@ async def run_fault_isolated(
1234
1371
  # the child, so the call returns at its deadline whether or not a hold is
1235
1372
  # watching.
1236
1373
  with _auto_hold(_ISOLATED_HOLD_PREFIX + _offloaded_callable_name(func), timeout):
1237
- future = loop.run_in_executor(
1238
- _get_process_executor(workers), functools.partial(func, *args, **kwargs)
1374
+ pool = _acquire_process_pool(workers)
1375
+ try:
1376
+ child_future = pool.executor.submit(
1377
+ functools.partial(func, *args, **kwargs)
1378
+ )
1379
+ except BaseException:
1380
+ # Never submitted (pool broken or shut down): nothing will release
1381
+ # the in-flight count, so release it here.
1382
+ _release_process_pool(workers, pool)
1383
+ raise
1384
+ # Released when the *child* is done, not when this caller stops waiting.
1385
+ child_future.add_done_callback(
1386
+ lambda _done: _release_process_pool(workers, pool)
1239
1387
  )
1388
+ future = asyncio.wrap_future(child_future, loop=loop)
1240
1389
  if timeout is not None:
1241
1390
  # Not asyncio.wait_for: on timeout it cancels the future and then
1242
1391
  # waits for the cancellation to land — but a running executor call
@@ -1245,7 +1394,7 @@ async def run_fault_isolated(
1245
1394
  # ourselves.
1246
1395
  done, _ = await asyncio.wait({future}, timeout=timeout)
1247
1396
  if not done:
1248
- _discard_process_executor(workers)
1397
+ _discard_process_pool(workers, pool)
1249
1398
  # The kill resolves the abandoned future with BrokenProcessPool;
1250
1399
  # consume it so asyncio never logs "exception was never
1251
1400
  # retrieved".
@@ -1256,7 +1405,7 @@ async def run_fault_isolated(
1256
1405
  try:
1257
1406
  return await future
1258
1407
  except BrokenProcessPool:
1259
- _discard_process_executor(workers)
1408
+ _discard_process_pool(workers, pool)
1260
1409
  raise
1261
1410
  except asyncio.CancelledError:
1262
1411
  task = asyncio.current_task()
@@ -1303,8 +1452,8 @@ async def run_best_effort(
1303
1452
  caller's module (OTel source) rather than this one.
1304
1453
  timeout: Seconds before the child is killed and the run is skipped.
1305
1454
  max_workers: Pool width, forwarded to :func:`run_fault_isolated`. ``None``
1306
- uses the default ``min(4, cpu_count)``; pass ``1`` to serialise this
1307
- work.
1455
+ uses the default ``min(4, CPUs available to the container)``; pass
1456
+ ``1`` to serialise this work.
1308
1457
 
1309
1458
  Returns:
1310
1459
  ``func``'s result, or ``None`` if the run crashed, timed out, or errored.
@@ -68,8 +68,10 @@ class BaseClient(ClientInterface):
68
68
  credentials (Dict[str, Any]): Client credentials for authentication.
69
69
  http_headers (HeaderTypes): HTTP headers for all http requests made by this client. Supports dict, Headers object, or list of tuples.
70
70
  http_retry_transport (httpx.AsyncBaseTransport): HTTP transport for requests. Defaults to an
71
- httpx transport that retries connection setup up to 3 times. Can be overridden in load()
72
- for custom retry behavior.
71
+ httpx transport that retries connection setup up to 3 times and verifies TLS with
72
+ ``get_ssl_context()``. Can be overridden in load() for custom retry behavior; a
73
+ replacement transport owns TLS verification, so build it with
74
+ ``verify=get_ssl_context()`` to keep trusting CAs from ``SSL_CERT_DIR``.
73
75
 
74
76
  Extending the Client:
75
77
  To customize retry behavior, subclasses can override the http_retry_transport
@@ -87,9 +89,14 @@ class BaseClient(ClientInterface):
87
89
  ... }
88
90
  ... # Optionally override retry transport with custom configuration
89
91
  ... # For advanced retry logic with status code handling, use httpx-retries:
92
+ ... # import httpx
90
93
  ... # from httpx_retries import Retry, RetryTransport
94
+ ... # from application_sdk.clients import get_ssl_context
91
95
  ... # retry = Retry(total=5, backoff_factor=20)
92
- ... # self.http_retry_transport = RetryTransport(retry=retry) #replace transport with custom transport if needed
96
+ ... # self.http_retry_transport = RetryTransport(
97
+ ... # retry=retry,
98
+ ... # transport=httpx.AsyncHTTPTransport(verify=get_ssl_context()),
99
+ ... # ) # replace transport with custom transport if needed
93
100
 
94
101
  Advanced Retry Configuration:
95
102
  For applications requiring advanced retry logic (e.g., status code-based retries,
@@ -101,7 +108,9 @@ class BaseClient(ClientInterface):
101
108
  ... self.http_headers = {"Authorization": f"Bearer {kwargs.get('token')}"}
102
109
  ...
103
110
  ... # Install httpx-retries: pip install httpx-retries
111
+ ... import httpx
104
112
  ... from httpx_retries import Retry, RetryTransport
113
+ ... from application_sdk.clients import get_ssl_context
105
114
  ...
106
115
  ... # Configure retry for status codes and network errors
107
116
  ... retry = Retry(
@@ -109,7 +118,11 @@ class BaseClient(ClientInterface):
109
118
  ... backoff_factor=10,
110
119
  ... status_forcelist=[429, 500, 502, 503, 504]
111
120
  ... )
112
- ... self.http_retry_transport = RetryTransport(retry=retry)
121
+ ... # The replacement transport owns TLS verification.
122
+ ... self.http_retry_transport = RetryTransport(
123
+ ... retry=retry,
124
+ ... transport=httpx.AsyncHTTPTransport(verify=get_ssl_context()),
125
+ ... )
113
126
 
114
127
  Header Management:
115
128
  The client supports a two-level header system using httpx Headers for merging headers:
@@ -145,7 +158,11 @@ class BaseClient(ClientInterface):
145
158
  # BLDX-1153). httpcore retries only connection setup (ConnectError,
146
159
  # ConnectTimeout), before any request bytes are sent, so the retries
147
160
  # are safe for POST.
161
+ # TLS verification lives on the transport: httpx ignores
162
+ # ``AsyncClient(verify=...)`` whenever ``transport=`` is also passed,
163
+ # so the SDK context (default CAs plus SSL_CERT_DIR) must be set here.
148
164
  self.http_retry_transport: httpx.AsyncBaseTransport = httpx.AsyncHTTPTransport(
165
+ verify=get_ssl_context(),
149
166
  limits=_HTTP_POOL_LIMITS,
150
167
  retries=_HTTP_CONNECT_RETRIES,
151
168
  )
@@ -208,9 +225,15 @@ class BaseClient(ClientInterface):
208
225
  ... self.http_headers = {"Authorization": f"Bearer {kwargs.get('token')}"}
209
226
  ...
210
227
  ... # For advanced retry logic, install httpx-retries: pip install httpx-retries
228
+ ... import httpx
211
229
  ... from httpx_retries import Retry, RetryTransport
230
+ ... from application_sdk.clients import get_ssl_context
212
231
  ... retry = Retry(total=5, backoff_factor=10, status_forcelist=[429, 500, 502, 503, 504])
213
- ... self.http_retry_transport = RetryTransport(retry=retry)
232
+ ... # The replacement transport owns TLS verification.
233
+ ... self.http_retry_transport = RetryTransport(
234
+ ... retry=retry,
235
+ ... transport=httpx.AsyncHTTPTransport(verify=get_ssl_context()),
236
+ ... )
214
237
 
215
238
  Args:
216
239
  **kwargs: Additional keyword arguments, typically including credentials.
@@ -333,12 +356,10 @@ class BaseClient(ClientInterface):
333
356
  ... )
334
357
  """
335
358
  _warn_if_raise_on_error_unset("execute_http_get_request", raise_on_error)
336
- ssl_context = get_ssl_context()
337
359
  transport = await self._borrow_transport()
338
360
  async with httpx.AsyncClient(
339
361
  timeout=httpx.Timeout(timeout, pool=_HTTP_POOL_TIMEOUT_SECONDS),
340
362
  transport=transport,
341
- verify=ssl_context,
342
363
  ) as client:
343
364
  merged_headers = Headers(self.http_headers)
344
365
  if headers:
@@ -470,12 +491,10 @@ class BaseClient(ClientInterface):
470
491
  ... )
471
492
  """
472
493
  _warn_if_raise_on_error_unset("execute_http_post_request", raise_on_error)
473
- ssl_context = get_ssl_context()
474
494
  transport = await self._borrow_transport()
475
495
  async with httpx.AsyncClient(
476
496
  timeout=httpx.Timeout(timeout, pool=_HTTP_POOL_TIMEOUT_SECONDS),
477
497
  transport=transport,
478
- verify=ssl_context,
479
498
  ) as client:
480
499
  merged_headers = Headers(self.http_headers)
481
500
  if headers: