budgetpool 0.1.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.
@@ -0,0 +1,22 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .eggs/
8
+ *.egg
9
+ .venv/
10
+ venv/
11
+ .env
12
+ .env.*
13
+ *.pem
14
+ *.key
15
+ .tokens
16
+ .mypy_cache/
17
+ .pytest_cache/
18
+ .ruff_cache/
19
+ .coverage
20
+ htmlcov/
21
+ *.log
22
+ .DS_Store
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,161 @@
1
+ Metadata-Version: 2.4
2
+ Name: budgetpool
3
+ Version: 0.1.0
4
+ Summary: Memory-budget-aware parallel execution pool for Python
5
+ Project-URL: Homepage, https://github.com/ajtgjmdjp/budgetpool
6
+ Project-URL: Repository, https://github.com/ajtgjmdjp/budgetpool
7
+ Project-URL: Issues, https://github.com/ajtgjmdjp/budgetpool/issues
8
+ Author: ajtgjmdjp
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: ProcessPoolExecutor,memory,multiprocessing,parallel,resource-management
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Topic :: System :: Monitoring
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: psutil>=5.9.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: mypy; extra == 'dev'
28
+ Requires-Dist: pytest-cov; extra == 'dev'
29
+ Requires-Dist: pytest>=7.0; extra == 'dev'
30
+ Requires-Dist: ruff; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # budgetpool
34
+
35
+ [![CI](https://github.com/ajtgjmdjp/budgetpool/actions/workflows/ci.yml/badge.svg)](https://github.com/ajtgjmdjp/budgetpool/actions/workflows/ci.yml)
36
+ [![PyPI](https://img.shields.io/pypi/v/budgetpool)](https://pypi.org/project/budgetpool/)
37
+ [![Python](https://img.shields.io/pypi/pyversions/budgetpool)](https://pypi.org/project/budgetpool/)
38
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
39
+
40
+ Memory-budget-aware parallel execution pool for Python.
41
+
42
+ A drop-in replacement for `ProcessPoolExecutor` that calculates safe worker counts based on available memory, prevents OOM crashes, and provides backpressure on task submission.
43
+
44
+ ## Why?
45
+
46
+ `ProcessPoolExecutor` spawns workers based on CPU count, ignoring memory.
47
+ When each worker loads a large dataset or model, this easily causes OOM kills:
48
+
49
+ ```python
50
+ # Dangerous — 8 workers × 3GB each = 24GB on a 16GB machine
51
+ with ProcessPoolExecutor(max_workers=os.cpu_count()) as pool:
52
+ results = list(pool.map(run_backtest, param_grid))
53
+ ```
54
+
55
+ `BudgetPool` fixes this by computing safe worker counts from your memory budget:
56
+
57
+ ```python
58
+ from budgetpool import BudgetPool
59
+
60
+ # Safe — fits within 12GB, 2GB per worker → 6 workers max
61
+ with BudgetPool(memory_budget_gb=12.0, memory_per_worker_gb=2.0) as pool:
62
+ results = list(pool.map(run_backtest, param_grid))
63
+ ```
64
+
65
+ ## Install
66
+
67
+ ```bash
68
+ pip install budgetpool
69
+ ```
70
+
71
+ ## Quick Start
72
+
73
+ ### Basic Usage
74
+
75
+ ```python
76
+ from budgetpool import BudgetPool
77
+
78
+ with BudgetPool(memory_per_worker_gb=2.0) as pool:
79
+ results = list(pool.map(heavy_func, items))
80
+ print(f"Used {pool.num_workers} workers")
81
+ ```
82
+
83
+ ### With Explicit Budget
84
+
85
+ ```python
86
+ with BudgetPool(
87
+ memory_budget_gb=12.0, # Total budget for all workers
88
+ memory_per_worker_gb=2.0, # Estimated peak per worker
89
+ max_workers=8, # CPU cap (optional)
90
+ ) as pool:
91
+ futures = [pool.submit(process, item) for item in items]
92
+ results = [f.result() for f in futures]
93
+ ```
94
+
95
+ ### Memory Monitoring
96
+
97
+ ```python
98
+ from budgetpool import get_memory_info, safe_worker_count
99
+
100
+ # Check system memory
101
+ info = get_memory_info()
102
+ print(f"Total: {info.total_gb:.1f}GB, Available: {info.available_gb:.1f}GB")
103
+ print(f"Safe for workers: {info.free_for_workers_gb:.1f}GB")
104
+
105
+ # Calculate worker count without creating a pool
106
+ n = safe_worker_count(memory_per_worker_gb=3.0)
107
+ print(f"Safe worker count: {n}")
108
+ ```
109
+
110
+ ## How It Works
111
+
112
+ 1. **Startup**: Reads system memory (via `psutil`), respects cgroup limits in containers
113
+ 2. **Worker calculation**: `min(budget ÷ per_worker, cpu_count, max_workers)`
114
+ 3. **Backpressure**: Blocks `submit()` when pending tasks exceed `max_pending` (default: 2× workers)
115
+ 4. **Runtime checks**: Warns at 85% memory usage, raises `MemoryBudgetExceeded` at 95%
116
+
117
+ ## API Reference
118
+
119
+ ### `BudgetPool`
120
+
121
+ | Parameter | Type | Default | Description |
122
+ |---|---|---|---|
123
+ | `memory_budget_gb` | `float \| None` | Auto-detect | Total memory budget for all workers |
124
+ | `memory_per_worker_gb` | `float` | `1.0` | Estimated peak memory per worker |
125
+ | `max_workers` | `int \| None` | CPU count | Hard cap on worker count |
126
+ | `max_pending` | `int \| None` | `2 × workers` | Backpressure threshold |
127
+ | `warn_at_percent` | `float \| None` | `85.0` | Log warning at this memory % |
128
+ | `fail_at_percent` | `float \| None` | `95.0` | Raise error at this memory % |
129
+ | `mp_context` | | `None` | Multiprocessing start method |
130
+
131
+ **Methods**: `submit()`, `map()`, `shutdown()` — same signatures as `ProcessPoolExecutor`.
132
+
133
+ **Properties**: `num_workers`, `memory_budget_gb`, `memory_info`.
134
+
135
+ ### `safe_worker_count(memory_per_worker_gb, max_workers=None) → int`
136
+
137
+ Standalone function to calculate safe worker count without creating a pool.
138
+
139
+ ### `get_memory_info() → MemoryInfo`
140
+
141
+ Returns a `MemoryInfo` dataclass with `total_gb`, `available_gb`, `used_gb`, `percent`, and `free_for_workers_gb`.
142
+
143
+ ## Container Support
144
+
145
+ budgetpool automatically detects cgroup v1/v2 memory limits, so it works correctly inside Docker containers where `psutil.virtual_memory().total` would report host memory:
146
+
147
+ ```bash
148
+ docker run --memory=4g python -c "
149
+ from budgetpool import get_memory_info
150
+ print(get_memory_info().total_gb) # → 4.0, not host memory
151
+ "
152
+ ```
153
+
154
+ ## Requirements
155
+
156
+ - Python 3.10+
157
+ - [psutil](https://pypi.org/project/psutil/) ≥ 5.9.0
158
+
159
+ ## License
160
+
161
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,129 @@
1
+ # budgetpool
2
+
3
+ [![CI](https://github.com/ajtgjmdjp/budgetpool/actions/workflows/ci.yml/badge.svg)](https://github.com/ajtgjmdjp/budgetpool/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/budgetpool)](https://pypi.org/project/budgetpool/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/budgetpool)](https://pypi.org/project/budgetpool/)
6
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
7
+
8
+ Memory-budget-aware parallel execution pool for Python.
9
+
10
+ A drop-in replacement for `ProcessPoolExecutor` that calculates safe worker counts based on available memory, prevents OOM crashes, and provides backpressure on task submission.
11
+
12
+ ## Why?
13
+
14
+ `ProcessPoolExecutor` spawns workers based on CPU count, ignoring memory.
15
+ When each worker loads a large dataset or model, this easily causes OOM kills:
16
+
17
+ ```python
18
+ # Dangerous — 8 workers × 3GB each = 24GB on a 16GB machine
19
+ with ProcessPoolExecutor(max_workers=os.cpu_count()) as pool:
20
+ results = list(pool.map(run_backtest, param_grid))
21
+ ```
22
+
23
+ `BudgetPool` fixes this by computing safe worker counts from your memory budget:
24
+
25
+ ```python
26
+ from budgetpool import BudgetPool
27
+
28
+ # Safe — fits within 12GB, 2GB per worker → 6 workers max
29
+ with BudgetPool(memory_budget_gb=12.0, memory_per_worker_gb=2.0) as pool:
30
+ results = list(pool.map(run_backtest, param_grid))
31
+ ```
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install budgetpool
37
+ ```
38
+
39
+ ## Quick Start
40
+
41
+ ### Basic Usage
42
+
43
+ ```python
44
+ from budgetpool import BudgetPool
45
+
46
+ with BudgetPool(memory_per_worker_gb=2.0) as pool:
47
+ results = list(pool.map(heavy_func, items))
48
+ print(f"Used {pool.num_workers} workers")
49
+ ```
50
+
51
+ ### With Explicit Budget
52
+
53
+ ```python
54
+ with BudgetPool(
55
+ memory_budget_gb=12.0, # Total budget for all workers
56
+ memory_per_worker_gb=2.0, # Estimated peak per worker
57
+ max_workers=8, # CPU cap (optional)
58
+ ) as pool:
59
+ futures = [pool.submit(process, item) for item in items]
60
+ results = [f.result() for f in futures]
61
+ ```
62
+
63
+ ### Memory Monitoring
64
+
65
+ ```python
66
+ from budgetpool import get_memory_info, safe_worker_count
67
+
68
+ # Check system memory
69
+ info = get_memory_info()
70
+ print(f"Total: {info.total_gb:.1f}GB, Available: {info.available_gb:.1f}GB")
71
+ print(f"Safe for workers: {info.free_for_workers_gb:.1f}GB")
72
+
73
+ # Calculate worker count without creating a pool
74
+ n = safe_worker_count(memory_per_worker_gb=3.0)
75
+ print(f"Safe worker count: {n}")
76
+ ```
77
+
78
+ ## How It Works
79
+
80
+ 1. **Startup**: Reads system memory (via `psutil`), respects cgroup limits in containers
81
+ 2. **Worker calculation**: `min(budget ÷ per_worker, cpu_count, max_workers)`
82
+ 3. **Backpressure**: Blocks `submit()` when pending tasks exceed `max_pending` (default: 2× workers)
83
+ 4. **Runtime checks**: Warns at 85% memory usage, raises `MemoryBudgetExceeded` at 95%
84
+
85
+ ## API Reference
86
+
87
+ ### `BudgetPool`
88
+
89
+ | Parameter | Type | Default | Description |
90
+ |---|---|---|---|
91
+ | `memory_budget_gb` | `float \| None` | Auto-detect | Total memory budget for all workers |
92
+ | `memory_per_worker_gb` | `float` | `1.0` | Estimated peak memory per worker |
93
+ | `max_workers` | `int \| None` | CPU count | Hard cap on worker count |
94
+ | `max_pending` | `int \| None` | `2 × workers` | Backpressure threshold |
95
+ | `warn_at_percent` | `float \| None` | `85.0` | Log warning at this memory % |
96
+ | `fail_at_percent` | `float \| None` | `95.0` | Raise error at this memory % |
97
+ | `mp_context` | | `None` | Multiprocessing start method |
98
+
99
+ **Methods**: `submit()`, `map()`, `shutdown()` — same signatures as `ProcessPoolExecutor`.
100
+
101
+ **Properties**: `num_workers`, `memory_budget_gb`, `memory_info`.
102
+
103
+ ### `safe_worker_count(memory_per_worker_gb, max_workers=None) → int`
104
+
105
+ Standalone function to calculate safe worker count without creating a pool.
106
+
107
+ ### `get_memory_info() → MemoryInfo`
108
+
109
+ Returns a `MemoryInfo` dataclass with `total_gb`, `available_gb`, `used_gb`, `percent`, and `free_for_workers_gb`.
110
+
111
+ ## Container Support
112
+
113
+ budgetpool automatically detects cgroup v1/v2 memory limits, so it works correctly inside Docker containers where `psutil.virtual_memory().total` would report host memory:
114
+
115
+ ```bash
116
+ docker run --memory=4g python -c "
117
+ from budgetpool import get_memory_info
118
+ print(get_memory_info().total_gb) # → 4.0, not host memory
119
+ "
120
+ ```
121
+
122
+ ## Requirements
123
+
124
+ - Python 3.10+
125
+ - [psutil](https://pypi.org/project/psutil/) ≥ 5.9.0
126
+
127
+ ## License
128
+
129
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,62 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "budgetpool"
7
+ version = "0.1.0"
8
+ description = "Memory-budget-aware parallel execution pool for Python"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "ajtgjmdjp" }]
13
+ keywords = [
14
+ "parallel",
15
+ "multiprocessing",
16
+ "memory",
17
+ "resource-management",
18
+ "ProcessPoolExecutor",
19
+ ]
20
+ classifiers = [
21
+ "Development Status :: 3 - Alpha",
22
+ "Intended Audience :: Developers",
23
+ "Intended Audience :: Science/Research",
24
+ "License :: OSI Approved :: Apache Software License",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.10",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Programming Language :: Python :: 3.13",
30
+ "Topic :: Software Development :: Libraries",
31
+ "Topic :: System :: Monitoring",
32
+ "Typing :: Typed",
33
+ ]
34
+ dependencies = ["psutil>=5.9.0"]
35
+
36
+ [project.optional-dependencies]
37
+ dev = ["pytest>=7.0", "pytest-cov", "mypy", "ruff"]
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/ajtgjmdjp/budgetpool"
41
+ Repository = "https://github.com/ajtgjmdjp/budgetpool"
42
+ Issues = "https://github.com/ajtgjmdjp/budgetpool/issues"
43
+
44
+ [tool.hatch.build.targets.sdist]
45
+ include = ["src/budgetpool/"]
46
+
47
+ [tool.hatch.build.targets.wheel]
48
+ packages = ["src/budgetpool"]
49
+
50
+ [tool.ruff]
51
+ target-version = "py310"
52
+ line-length = 88
53
+
54
+ [tool.ruff.lint]
55
+ select = ["E", "F", "I", "N", "W", "UP", "B", "SIM"]
56
+
57
+ [tool.mypy]
58
+ python_version = "3.10"
59
+ strict = true
60
+
61
+ [tool.pytest.ini_options]
62
+ testpaths = ["tests"]
@@ -0,0 +1,13 @@
1
+ """budgetpool - Memory-budget-aware parallel execution pool for Python."""
2
+
3
+ from budgetpool._pool import BudgetPool
4
+ from budgetpool._monitor import MemoryInfo, get_memory_info, safe_worker_count
5
+
6
+ __all__ = [
7
+ "BudgetPool",
8
+ "MemoryInfo",
9
+ "get_memory_info",
10
+ "safe_worker_count",
11
+ ]
12
+
13
+ __version__ = "0.1.0"
@@ -0,0 +1,105 @@
1
+ """Memory monitoring utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+
8
+ import psutil
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class MemoryInfo:
13
+ """Snapshot of system memory state."""
14
+
15
+ total_gb: float
16
+ available_gb: float
17
+ used_gb: float
18
+ percent: float
19
+
20
+ @property
21
+ def free_for_workers_gb(self) -> float:
22
+ """Estimate of memory available for worker processes.
23
+
24
+ Reserves 20% of total or 2GB (whichever is smaller) for OS and
25
+ other processes.
26
+ """
27
+ reserve = min(self.total_gb * 0.2, 2.0)
28
+ return max(0.0, self.available_gb - reserve)
29
+
30
+
31
+ def get_memory_info() -> MemoryInfo:
32
+ """Get current system memory information.
33
+
34
+ On Linux, respects cgroup memory limits (e.g. inside Docker containers).
35
+ """
36
+ cgroup_limit = _read_cgroup_limit()
37
+ vm = psutil.virtual_memory()
38
+
39
+ if cgroup_limit is not None and cgroup_limit < vm.total:
40
+ # Inside a cgroup-limited container
41
+ total_gb = cgroup_limit / (1024**3)
42
+ available_gb = (cgroup_limit - vm.used) / (1024**3)
43
+ available_gb = max(0.0, available_gb)
44
+ used_gb = vm.used / (1024**3)
45
+ percent = (vm.used / cgroup_limit) * 100
46
+ else:
47
+ total_gb = vm.total / (1024**3)
48
+ available_gb = vm.available / (1024**3)
49
+ used_gb = vm.used / (1024**3)
50
+ percent = vm.percent
51
+
52
+ return MemoryInfo(
53
+ total_gb=round(total_gb, 2),
54
+ available_gb=round(available_gb, 2),
55
+ used_gb=round(used_gb, 2),
56
+ percent=round(percent, 1),
57
+ )
58
+
59
+
60
+ def safe_worker_count(
61
+ memory_per_worker_gb: float = 1.0,
62
+ max_workers: int | None = None,
63
+ ) -> int:
64
+ """Calculate safe number of workers based on available memory.
65
+
66
+ Args:
67
+ memory_per_worker_gb: Estimated peak memory per worker process in GB.
68
+ max_workers: Optional upper bound (defaults to CPU count).
69
+
70
+ Returns:
71
+ Safe number of workers (always >= 1).
72
+ """
73
+ if memory_per_worker_gb <= 0:
74
+ raise ValueError("memory_per_worker_gb must be positive")
75
+
76
+ info = get_memory_info()
77
+ max_by_memory = int(info.free_for_workers_gb / memory_per_worker_gb)
78
+ max_by_cpu = max_workers if max_workers is not None else (os.cpu_count() or 4)
79
+
80
+ workers = max(1, min(max_by_memory, max_by_cpu))
81
+ return workers
82
+
83
+
84
+ def _read_cgroup_limit() -> int | None:
85
+ """Read cgroup v2/v1 memory limit, if available."""
86
+ # cgroup v2
87
+ try:
88
+ with open("/sys/fs/cgroup/memory.max") as f:
89
+ val = f.read().strip()
90
+ if val != "max":
91
+ return int(val)
92
+ except (FileNotFoundError, PermissionError, ValueError):
93
+ pass
94
+
95
+ # cgroup v1
96
+ try:
97
+ with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
98
+ val = int(f.read().strip())
99
+ # Very large values mean "no limit"
100
+ if val < 2**62:
101
+ return val
102
+ except (FileNotFoundError, PermissionError, ValueError):
103
+ pass
104
+
105
+ return None
@@ -0,0 +1,230 @@
1
+ """BudgetPool - Memory-budget-aware process pool executor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import threading
8
+ import time
9
+ from concurrent.futures import Future, ProcessPoolExecutor
10
+ from concurrent.futures._base import FIRST_COMPLETED
11
+ from typing import Any, Callable, Iterable, Iterator
12
+
13
+ import psutil
14
+
15
+ from budgetpool._monitor import MemoryInfo, get_memory_info, safe_worker_count
16
+
17
+ logger = logging.getLogger("budgetpool")
18
+
19
+ _UNSET = object()
20
+
21
+
22
+ class MemoryBudgetExceeded(RuntimeError):
23
+ """Raised when memory usage exceeds the configured budget."""
24
+
25
+ def __init__(self, budget_gb: float, current_gb: float) -> None:
26
+ self.budget_gb = budget_gb
27
+ self.current_gb = current_gb
28
+ super().__init__(
29
+ f"Memory budget exceeded: {current_gb:.1f}GB used, "
30
+ f"budget is {budget_gb:.1f}GB"
31
+ )
32
+
33
+
34
+ class BudgetPool:
35
+ """A memory-budget-aware drop-in replacement for ProcessPoolExecutor.
36
+
37
+ Calculates a safe number of workers at startup based on available
38
+ memory and the estimated per-worker memory usage. Provides
39
+ backpressure by limiting the number of concurrently pending tasks.
40
+
41
+ Example::
42
+
43
+ with BudgetPool(memory_budget_gb=12.0, memory_per_worker_gb=2.0) as pool:
44
+ results = list(pool.map(heavy_func, items))
45
+
46
+ Args:
47
+ memory_budget_gb: Total memory budget for all workers combined.
48
+ If None, uses available memory minus OS reserve.
49
+ memory_per_worker_gb: Estimated peak memory per worker process.
50
+ max_workers: Hard upper bound on worker count (regardless of
51
+ memory). Defaults to CPU count.
52
+ max_pending: Maximum number of tasks queued beyond active workers.
53
+ Provides backpressure to prevent memory spikes from queued
54
+ data. Defaults to 2x worker count.
55
+ warn_at_percent: Log a warning when system memory usage exceeds
56
+ this percentage. Set to None to disable.
57
+ fail_at_percent: Raise MemoryBudgetExceeded when system memory
58
+ exceeds this percentage on task submission. Set to None to
59
+ disable.
60
+ mp_context: Multiprocessing context (e.g. ``"spawn"``).
61
+ Defaults to None (system default).
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ memory_budget_gb: float | None = None,
67
+ memory_per_worker_gb: float = 1.0,
68
+ max_workers: int | None = None,
69
+ max_pending: int | None = None,
70
+ warn_at_percent: float | None = 85.0,
71
+ fail_at_percent: float | None = 95.0,
72
+ mp_context: Any = None,
73
+ ) -> None:
74
+ if memory_per_worker_gb <= 0:
75
+ raise ValueError("memory_per_worker_gb must be positive")
76
+
77
+ self._memory_per_worker_gb = memory_per_worker_gb
78
+ self._warn_at_percent = warn_at_percent
79
+ self._fail_at_percent = fail_at_percent
80
+
81
+ # Determine memory budget
82
+ info = get_memory_info()
83
+ if memory_budget_gb is not None:
84
+ self._budget_gb = memory_budget_gb
85
+ else:
86
+ self._budget_gb = info.free_for_workers_gb
87
+
88
+ # Calculate worker count from budget
89
+ budget_workers = max(1, int(self._budget_gb / memory_per_worker_gb))
90
+ cpu_limit = max_workers if max_workers is not None else (os.cpu_count() or 4)
91
+ self._num_workers = min(budget_workers, cpu_limit)
92
+
93
+ # Backpressure: limit pending futures
94
+ self._max_pending = (
95
+ max_pending if max_pending is not None else self._num_workers * 2
96
+ )
97
+
98
+ logger.info(
99
+ "BudgetPool: budget=%.1fGB, per_worker=%.1fGB, workers=%d "
100
+ "(cpu_limit=%d, budget_limit=%d), system=%.1f/%.1fGB (%.0f%%)",
101
+ self._budget_gb,
102
+ memory_per_worker_gb,
103
+ self._num_workers,
104
+ cpu_limit,
105
+ budget_workers,
106
+ info.used_gb,
107
+ info.total_gb,
108
+ info.percent,
109
+ )
110
+
111
+ self._executor = ProcessPoolExecutor(
112
+ max_workers=self._num_workers,
113
+ mp_context=mp_context,
114
+ )
115
+ self._pending_futures: set[Future[Any]] = set()
116
+ self._lock = threading.Lock()
117
+ self._closed = False
118
+
119
+ @property
120
+ def num_workers(self) -> int:
121
+ """Number of worker processes."""
122
+ return self._num_workers
123
+
124
+ @property
125
+ def memory_budget_gb(self) -> float:
126
+ """Configured memory budget in GB."""
127
+ return self._budget_gb
128
+
129
+ @property
130
+ def memory_info(self) -> MemoryInfo:
131
+ """Current system memory snapshot."""
132
+ return get_memory_info()
133
+
134
+ def submit(
135
+ self, fn: Callable[..., Any], /, *args: Any, **kwargs: Any
136
+ ) -> Future[Any]:
137
+ """Submit a task, with backpressure and memory checks.
138
+
139
+ Blocks if the number of pending futures exceeds ``max_pending``.
140
+ """
141
+ if self._closed:
142
+ raise RuntimeError("BudgetPool is shut down")
143
+
144
+ self._check_memory()
145
+ self._apply_backpressure()
146
+
147
+ future = self._executor.submit(fn, *args, **kwargs)
148
+
149
+ with self._lock:
150
+ self._pending_futures.add(future)
151
+
152
+ future.add_done_callback(self._on_future_done)
153
+ return future
154
+
155
+ def map(
156
+ self,
157
+ fn: Callable[..., Any],
158
+ *iterables: Iterable[Any],
159
+ timeout: float | None = None,
160
+ chunksize: int = 1,
161
+ ) -> Iterator[Any]:
162
+ """Memory-aware version of ProcessPoolExecutor.map.
163
+
164
+ Submits tasks with backpressure to avoid overwhelming memory.
165
+ """
166
+ if self._closed:
167
+ raise RuntimeError("BudgetPool is shut down")
168
+
169
+ futures: list[Future[Any]] = []
170
+ for args in zip(*iterables):
171
+ future = self.submit(fn, *args)
172
+ futures.append(future)
173
+
174
+ # Yield results in submission order
175
+ for future in futures:
176
+ result = future.result(timeout=timeout)
177
+ yield result
178
+
179
+ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None:
180
+ """Shut down the pool."""
181
+ self._closed = True
182
+ self._executor.shutdown(wait=wait, cancel_futures=cancel_futures)
183
+
184
+ def __enter__(self) -> BudgetPool:
185
+ return self
186
+
187
+ def __exit__(self, *args: Any) -> None:
188
+ self.shutdown(wait=True)
189
+
190
+ def __repr__(self) -> str:
191
+ info = get_memory_info()
192
+ return (
193
+ f"BudgetPool(workers={self._num_workers}, "
194
+ f"budget={self._budget_gb:.1f}GB, "
195
+ f"system={info.available_gb:.1f}GB free)"
196
+ )
197
+
198
+ def _check_memory(self) -> None:
199
+ """Check memory and warn/fail if thresholds exceeded."""
200
+ info = get_memory_info()
201
+
202
+ if self._fail_at_percent is not None and info.percent >= self._fail_at_percent:
203
+ raise MemoryBudgetExceeded(
204
+ budget_gb=self._budget_gb,
205
+ current_gb=info.used_gb,
206
+ )
207
+
208
+ if self._warn_at_percent is not None and info.percent >= self._warn_at_percent:
209
+ logger.warning(
210
+ "BudgetPool: memory at %.1f%% (%s/%sGB). "
211
+ "Consider reducing workload.",
212
+ info.percent,
213
+ info.used_gb,
214
+ info.total_gb,
215
+ )
216
+
217
+ def _apply_backpressure(self) -> None:
218
+ """Block until pending futures drop below max_pending."""
219
+ while True:
220
+ with self._lock:
221
+ pending = len(self._pending_futures)
222
+ if pending < self._max_pending:
223
+ return
224
+ # Wait for at least one to complete
225
+ time.sleep(0.01)
226
+
227
+ def _on_future_done(self, future: Future[Any]) -> None:
228
+ """Remove completed future from pending set."""
229
+ with self._lock:
230
+ self._pending_futures.discard(future)
File without changes