stagepipe 0.0.2__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.
- stagepipe-0.0.2/LICENSE +202 -0
- stagepipe-0.0.2/PKG-INFO +348 -0
- stagepipe-0.0.2/README.md +325 -0
- stagepipe-0.0.2/pyproject.toml +36 -0
- stagepipe-0.0.2/setup.cfg +4 -0
- stagepipe-0.0.2/src/stagepipe/__init__.py +5 -0
- stagepipe-0.0.2/src/stagepipe/pipeline.py +136 -0
- stagepipe-0.0.2/src/stagepipe/py.typed +0 -0
- stagepipe-0.0.2/src/stagepipe.egg-info/PKG-INFO +348 -0
- stagepipe-0.0.2/src/stagepipe.egg-info/SOURCES.txt +10 -0
- stagepipe-0.0.2/src/stagepipe.egg-info/dependency_links.txt +1 -0
- stagepipe-0.0.2/src/stagepipe.egg-info/top_level.txt +1 -0
stagepipe-0.0.2/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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 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 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 those 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
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
stagepipe-0.0.2/PKG-INFO
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: stagepipe
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: Staged pipelines for blocking Python code: per-stage thread workers, no stage barrier, ordered stages, bounded in-flight. Standard library only.
|
|
5
|
+
Author: Rafael Borja
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/rafaelborja/stagepipe
|
|
8
|
+
Project-URL: Issues, https://github.com/rafaelborja/stagepipe/issues
|
|
9
|
+
Project-URL: Source, https://github.com/rafaelborja/stagepipe
|
|
10
|
+
Project-URL: Author, https://github.com/rafaelborja
|
|
11
|
+
Keywords: pipeline,threads,concurrency,parallel,batch,producer-consumer,ocr,etl
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# stagepipe
|
|
25
|
+
|
|
26
|
+
**Run your slow, blocking steps in parallel, and let every item move on the moment the next step is free.**
|
|
27
|
+
|
|
28
|
+
A tiny pipeline for plain Python: no event loop, no server, no dependencies, about 130 lines of
|
|
29
|
+
standard library. You say how many workers each stage gets; stagepipe keeps them all busy.
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from stagepipe import Stage, run
|
|
33
|
+
|
|
34
|
+
pages = run(files, [
|
|
35
|
+
Stage("render", render_page, workers=4), # fast, CPU
|
|
36
|
+
Stage("ocr", read_text, workers=3), # medium, native code
|
|
37
|
+
Stage("llm", ask_model, workers=8), # slow, waiting on the network
|
|
38
|
+
Stage("save", write_out, workers=1, ordered=True), # must see pages in order
|
|
39
|
+
], max_in_flight=12)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Page 1 can be saving while page 9 is still being rendered. Nobody waits for the slowest page,
|
|
43
|
+
and memory stays bounded.
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Why stagepipe
|
|
48
|
+
|
|
49
|
+
**Lightweight.** One file, standard library only (`threading` and `queue`). Nothing to run,
|
|
50
|
+
nothing to configure, nothing written to disk. It lives inside your process and disappears
|
|
51
|
+
when the call returns. It adds about **2 MB** to a bare Python process, and the machinery itself
|
|
52
|
+
costs roughly **10 microseconds per item per stage** (around 100,000 items per second through a
|
|
53
|
+
single no-op stage; the figure is noisy, between 7 and 50 us on a busy desktop).
|
|
54
|
+
|
|
55
|
+
**Fast, where it counts.** Real pipelines are limited by the slowest stage, not by the framework.
|
|
56
|
+
stagepipe makes sure the slow stage is never starved and the fast stages never sit idle waiting
|
|
57
|
+
for it. Same workload, three ways (40 items through stages of 0.02 s, 0.30 s and 0.05 s):
|
|
58
|
+
|
|
59
|
+
| Approach | Total time | First result after |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| One item at a time | 14.8 s | 0.4 s |
|
|
62
|
+
| Parallel, but stage by stage (wait for all items before the next stage) | 3.7 s | 1.7 s |
|
|
63
|
+
| **stagepipe** | **2.3 s** | **0.4 s** |
|
|
64
|
+
|
|
65
|
+
The 2.3 s is close to the floor for this workload: the last stage has one worker and 40 items at
|
|
66
|
+
0.05 s each, which alone takes 2.0 s. (Measured on Windows 11, CPython 3.12.10 and 3.15.0rc2;
|
|
67
|
+
the script is `bench/` in the repo.)
|
|
68
|
+
|
|
69
|
+
**Reliable by being small.** Few moving parts, no global state, every run is independent
|
|
70
|
+
(you can run several at once). Shutdown, errors and cancel paths are covered by a stress suite
|
|
71
|
+
that runs randomized pipelines (random sizes, worker counts and window sizes), failures in the
|
|
72
|
+
first and last stage, bad configuration, and checks that no threads are left behind. Known gaps
|
|
73
|
+
are listed honestly [below](#status-and-known-limits).
|
|
74
|
+
|
|
75
|
+
**Built for small memory.** The target is serverless functions, containers with a few hundred MB,
|
|
76
|
+
and small devices. That is why there is no broker, no database and no event loop: nothing to
|
|
77
|
+
start, nothing resident. `max_in_flight` caps how many items exist at once, so a fast first stage
|
|
78
|
+
cannot render 500 page images while a slow stage is still on page 3. Measured in a fresh process
|
|
79
|
+
(CPython 3.12, Windows), 2,000 items of 20 KB each through two stages:
|
|
80
|
+
|
|
81
|
+
| | Process memory after the run | Python heap peak |
|
|
82
|
+
|---|---|---|
|
|
83
|
+
| bare Python | 16.8 MB | |
|
|
84
|
+
| **stagepipe** | **19.5 MB** (+2.7) | **2.3 MB** |
|
|
85
|
+
| aiostream (`task_limit=2`) | 25.1 MB (+8.3) | 4.8 MB |
|
|
86
|
+
|
|
87
|
+
aiostream is excellent and well maintained, and most of that difference is simply `asyncio`
|
|
88
|
+
being loaded. If you already run an event loop it costs you nothing extra. If you do not, and
|
|
89
|
+
memory is tight, a thread-and-queue design is the lighter tool. Reproduce with `bench/memory.py`.
|
|
90
|
+
|
|
91
|
+
**Seconds, not nanoseconds.** stagepipe is for pipelines whose steps take milliseconds to minutes
|
|
92
|
+
(an OCR page, an API call, a transcode), where running in parallel saves *seconds*. Ten
|
|
93
|
+
microseconds of bookkeeping per item disappears next to that. So whenever speed and footprint
|
|
94
|
+
pull in different directions, footprint wins: we are happy to spend a few milliseconds to save
|
|
95
|
+
kilobytes.
|
|
96
|
+
|
|
97
|
+
**Where today's ~2 MB goes.** Measured by importing each module alone in a fresh process
|
|
98
|
+
(the numbers overlap, because these modules share dependencies, so they do not add up):
|
|
99
|
+
|
|
100
|
+
| Import | Extra resident memory | Why it is here |
|
|
101
|
+
|---|---|---|
|
|
102
|
+
| `dataclasses` | about 1.7 MB | Pulls in `inspect`, `re` and more, just to generate `__init__` for the small `Stage` class. |
|
|
103
|
+
| `typing` | about 0.7 MB | Only for type hints, which are never evaluated at run time. |
|
|
104
|
+
| `queue` | about 0.4 MB | The thread-safe queue; the C implementation underneath is much smaller. |
|
|
105
|
+
| stagepipe's own code | close to 0 | |
|
|
106
|
+
|
|
107
|
+
Neither `dataclasses` nor `typing` is needed to run a pipeline. They are conveniences, and
|
|
108
|
+
removing them is the first item on the [roadmap](#roadmap). A prototype already brings the import
|
|
109
|
+
cost from about 2.4 MB to about 0.2 MB: `Stage` becomes a few lines of plain Python, the type
|
|
110
|
+
hints are only read by type checkers, and `threading` plus the C queue load on the first `run()`
|
|
111
|
+
instead of at import. The same prototype also feeds items lazily and can drop results as they
|
|
112
|
+
are consumed, so memory stays flat however many items go through.
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## The idea in one picture
|
|
117
|
+
|
|
118
|
+
Most hand-rolled parallel code processes **stage by stage**: do all the rendering, then all the
|
|
119
|
+
OCR, then all the saving. The slowest stage sets the pace for everyone, and nothing finishes
|
|
120
|
+
until nearly the end.
|
|
121
|
+
|
|
122
|
+

|
|
123
|
+
|
|
124
|
+
Same six items, same workers, same stage durations. The only difference is that stagepipe does
|
|
125
|
+
not hold an item back to wait for its siblings.
|
|
126
|
+
|
|
127
|
+
With stagepipe each stage has its own pool of workers and its own queue. A finished item goes
|
|
128
|
+
straight onto the next stage's queue.
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## Quick start
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
pip install stagepipe
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
import time
|
|
140
|
+
from stagepipe import Stage, run
|
|
141
|
+
|
|
142
|
+
def download(url, i): # slow, waits on the network
|
|
143
|
+
time.sleep(0.3)
|
|
144
|
+
return f"<html for {url}>"
|
|
145
|
+
|
|
146
|
+
def parse(html, i): # fast
|
|
147
|
+
return html.upper()
|
|
148
|
+
|
|
149
|
+
def store(doc, i): # needs the original order
|
|
150
|
+
print("stored", i, doc)
|
|
151
|
+
return doc
|
|
152
|
+
|
|
153
|
+
urls = [f"https://example.org/{n}" for n in range(10)]
|
|
154
|
+
|
|
155
|
+
docs = run(urls, [
|
|
156
|
+
Stage("download", download, workers=5),
|
|
157
|
+
Stage("parse", parse, workers=2),
|
|
158
|
+
Stage("store", store, workers=1, ordered=True),
|
|
159
|
+
], max_in_flight=8)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
- Each stage function is called as `fn(value, index)` and returns the value for the next stage.
|
|
163
|
+
- `run()` returns the final values **in input order**.
|
|
164
|
+
- Ten downloads that would take 3 s one by one take about 0.6 s here.
|
|
165
|
+
|
|
166
|
+
### The knobs
|
|
167
|
+
|
|
168
|
+
| Option | What it does |
|
|
169
|
+
|---|---|
|
|
170
|
+
| `Stage(name, fn, workers=N)` | N threads work on this stage in parallel. Give slow stages more. |
|
|
171
|
+
| `ordered=True` | The stage sees items in index order (needs `workers=1`). Use it when a stage carries state across items. Earlier stages still run out of order. |
|
|
172
|
+
| `max_in_flight=M` | At most M items are being processed at any moment. Bounds memory and keeps stages balanced. |
|
|
173
|
+
| `cancelled=callable` | Checked before every call; when it returns true the run stops and raises `Cancelled`. |
|
|
174
|
+
| `on_done=callable` | Called with `(index, value)` as each item leaves the last stage. Good for progress bars. **It runs in a worker thread**, and concurrently if the last stage has several workers, so it must be thread-safe (or make the last stage `ordered`, which has exactly one worker). |
|
|
175
|
+
|
|
176
|
+
If any stage raises, new work stops, workers drain, and the first exception is re-raised from `run()`.
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
## Where it fits
|
|
181
|
+
|
|
182
|
+
stagepipe is for **blocking work that spends its time waiting or in native code**, which is
|
|
183
|
+
exactly where threads help:
|
|
184
|
+
|
|
185
|
+
- **Document and image pipelines**: render, OCR, vision-model call, save, per page.
|
|
186
|
+
- **Calling APIs at scale**: fetch, transform, upload, with different limits per stage.
|
|
187
|
+
- **ETL on files**: read, decode, enrich, write, without loading the dataset into memory.
|
|
188
|
+
- **ML inference around a model**: prepare on CPU, run on one GPU worker, post-process on CPU.
|
|
189
|
+
- **Media and archive jobs**: transcode, hash, compress, upload.
|
|
190
|
+
- **Scraping**: fetch pages, parse, store, with a polite worker count at the network stage.
|
|
191
|
+
|
|
192
|
+
Python threads run native code (NumPy, onnxruntime, torch, image libraries, HTTP, subprocesses)
|
|
193
|
+
in parallel because those release the GIL. Pure-Python number crunching will not speed up in a
|
|
194
|
+
thread. Use a process pool inside a stage function for that.
|
|
195
|
+
|
|
196
|
+
### Threads, shared resources, and cancelling: what to know
|
|
197
|
+
|
|
198
|
+
These come from running stagepipe on a real five-stage document pipeline.
|
|
199
|
+
|
|
200
|
+
- **Threads only help when the work releases the GIL** (I/O, onnxruntime, PyTorch). One trap that
|
|
201
|
+
was measured: PyTorch's CPU thread count is global to the process, so several threads each
|
|
202
|
+
running a CPU model share a single thread pool. For CPU-bound PyTorch, separate processes
|
|
203
|
+
scaled better (1.7x in that test). For a GPU, use a stage with one worker.
|
|
204
|
+
- **A resource that is not thread-safe** (a PDF library, a database handle) goes behind a lock
|
|
205
|
+
inside the stage function, or in a stage with `workers=1`.
|
|
206
|
+
- **One model or session per worker thread.** Until `Stage(init=...)` exists (see the roadmap),
|
|
207
|
+
build it lazily in the stage function with `threading.local()`:
|
|
208
|
+
|
|
209
|
+
```python
|
|
210
|
+
import threading
|
|
211
|
+
_mine = threading.local()
|
|
212
|
+
|
|
213
|
+
def ocr(page, i):
|
|
214
|
+
if not hasattr(_mine, "session"):
|
|
215
|
+
_mine.session = load_model() # once per worker thread
|
|
216
|
+
return _mine.session.read(page)
|
|
217
|
+
```
|
|
218
|
+
- **Cancel, then resume.** When a run is cancelled or fails, items that were in flight are
|
|
219
|
+
dropped, not committed. So let the last stage save each item atomically (write to a temporary
|
|
220
|
+
file, then rename), and on the next run skip the items already saved. That makes a cancelled
|
|
221
|
+
run safe to restart.
|
|
222
|
+
- **`on_done` runs in a worker thread**, not in the thread that called `run()`. See the table above.
|
|
223
|
+
|
|
224
|
+
### What it is not
|
|
225
|
+
|
|
226
|
+
- Not a job queue or scheduler: no broker, no workers on other machines, no persistence (yet, see the roadmap).
|
|
227
|
+
- Not a workflow engine with branching graphs (yet): stages form a straight line.
|
|
228
|
+
- Not async. If your code is already `async`, use [aiostream](https://github.com/vxgmichel/aiostream).
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
|
|
232
|
+
## Why not something else?
|
|
233
|
+
|
|
234
|
+
Checked on Python 3.12 in a clean virtual environment, with blocking functions.
|
|
235
|
+
|
|
236
|
+
| Option | Verdict |
|
|
237
|
+
|---|---|
|
|
238
|
+
| **concurrent.futures** by hand | The right foundation, and stagepipe is a thin layer over threads and queues. Wiring several stages yourself means re-deriving queues, shutdown, error propagation and the in-flight cap in every project. |
|
|
239
|
+
| **[aiostream](https://github.com/vxgmichel/aiostream)** | Maintained and good for async code. For blocking functions it rejects parallelism: `stream.map(sync_fn, task_limit=4)` raises `ValueError: The 'task_limit' argument can only be used when the provided function is asynchronous`. Wrapping every stage in `asyncio.to_thread` works (8 x 0.3 s in 0.61 s) but needs an event loop and an async wrapper per function, and loading `asyncio` alone costs about 6 MB more than stagepipe's whole footprint. |
|
|
240
|
+
| **[pypeln](https://github.com/cgarciae/pypeln)** | The closest idea (`pl.thread.map(f, workers=4)`), but unmaintained since January 2022. On a clean Python 3.12 environment `import pypeln` fails with `No module named 'pkg_resources'` until you install `setuptools<81`, and output order is not preserved by default. |
|
|
241
|
+
| **Dask, Ray, Celery, Prefect, Airflow** | Excellent, and a different class of tool: schedulers, clusters and brokers. Right when you need machines and dashboards, heavy when you need a function call. |
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
## Status and known limits
|
|
246
|
+
|
|
247
|
+
**Alpha, version 0.0.2.** It was extracted from a working document-processing pipeline where it
|
|
248
|
+
replaces a hand-rolled look-ahead loop, and it passes its stress suite on CPython 3.12 and 3.15.
|
|
249
|
+
In its first real use, five stages with different worker counts and at most 8 items in flight
|
|
250
|
+
gave output identical to the sequential loop, and cancelling then resuming worked.
|
|
251
|
+
|
|
252
|
+
Things this first version does **not** do well yet. They are tracked as
|
|
253
|
+
[issues](https://github.com/rafaelborja/stagepipe/issues) and are the first things on the roadmap:
|
|
254
|
+
|
|
255
|
+
- **Ctrl-C does not cancel promptly.** If the calling thread is interrupted, queued work is still
|
|
256
|
+
drained before `run()` returns (measured: a 5 s job returned after 5.0 s).
|
|
257
|
+
- **Memory is not bounded as designed.** `run()` keeps every input until it returns, an idle
|
|
258
|
+
worker keeps a reference to the last item it handled, and all results collect in one list.
|
|
259
|
+
Fine for hundreds of pages; not yet for streams of large objects.
|
|
260
|
+
- **No failure recovery.** The first exception stops the whole run; there are no retries, and a
|
|
261
|
+
rerun starts from the beginning.
|
|
262
|
+
|
|
263
|
+
---
|
|
264
|
+
|
|
265
|
+
## Roadmap
|
|
266
|
+
|
|
267
|
+
**Design rule for everything below: memory grows with `max_in_flight`, never with the number of
|
|
268
|
+
items, and nothing needs a database or a server.** Features that would break that rule do not ship.
|
|
269
|
+
Persistence, for example, will be plain files on disk (one small file per item per stage plus an
|
|
270
|
+
append-only journal), read back as a stream; at most one bit per item is kept in memory to
|
|
271
|
+
remember what is done, which is 125 KB for a million items.
|
|
272
|
+
|
|
273
|
+
The aim: stay tiny and dependable, and become the best answer for *"I have blocking code in
|
|
274
|
+
stages and I want it parallel, safe and observable"*, the niche that async libraries
|
|
275
|
+
do not cover and that the older thread-based libraries have left behind.
|
|
276
|
+
|
|
277
|
+
### Next: make the basics trustworthy (0.1)
|
|
278
|
+
- [ ] Ctrl-C and cancel stop promptly and cleanly.
|
|
279
|
+
- [ ] **Smaller footprint**, because memory is the point of this library:
|
|
280
|
+
- drop `dataclasses` and `typing` at run time, and replace the little we use of them with a few
|
|
281
|
+
lines of our own (about 2.4 MB less);
|
|
282
|
+
- import nothing until the first `run()`; on Python 3.15 this also plays well with the new
|
|
283
|
+
lazy-import flag (`-X lazy_imports`) and `__lazy_modules__`;
|
|
284
|
+
- use the C queue directly instead of the `queue` module;
|
|
285
|
+
- pull input lazily instead of copying it into a list, so a generator is never materialised;
|
|
286
|
+
- `keep_results=False` and streaming results (`for r in stream(...)`): nothing is kept, results
|
|
287
|
+
are handed over as they finish;
|
|
288
|
+
- workers let go of the last item they handled as soon as they are idle;
|
|
289
|
+
- optional smaller thread stacks for very small containers.
|
|
290
|
+
- [ ] Failure policy per run: `collect` failed items and finish the rest, `skip`, or `retry(n, backoff)`.
|
|
291
|
+
- [ ] Per-worker setup: `Stage(init=...)`, run once in each worker thread, e.g. one model
|
|
292
|
+
session per worker. *Asked for by the first real user, who had to build it by hand with
|
|
293
|
+
`threading.local()`.*
|
|
294
|
+
- [ ] A bottleneck report after every run: per stage, busy time against waiting time, items
|
|
295
|
+
done and queue depth, so the stage to scale is obvious. *Also asked for by the first real
|
|
296
|
+
user, who timed inside their stage functions.*
|
|
297
|
+
|
|
298
|
+
### Then: make it safe to rerun and easy to watch (0.2)
|
|
299
|
+
- [ ] **Resume after a crash**, with the lightest possible persistence: one small file per item
|
|
300
|
+
per stage, written atomically, plus an append-only journal. No database. A rerun skips
|
|
301
|
+
work that is already done.
|
|
302
|
+
- [ ] **Events for dashboards**: a stable, versioned event stream (enter/exit per stage, worker,
|
|
303
|
+
duration, queue depth) written as JSON lines or sent to a callback. A dashboard can be a
|
|
304
|
+
separate project that just reads it.
|
|
305
|
+
- [ ] Shared limits across stages, e.g. a `gpu=1` slot that three stages compete for.
|
|
306
|
+
- [ ] A memory budget in bytes, not only an item count.
|
|
307
|
+
|
|
308
|
+
### Later: bigger shapes (0.3 and beyond)
|
|
309
|
+
- [ ] One-to-many stages (a page becomes several regions) and parallel branches that join again.
|
|
310
|
+
- [ ] Process-backed stages for CPU-bound Python, with workers recycled after N items to contain
|
|
311
|
+
leaks. (Measured in a real pipeline: CPU-bound PyTorch ran 1.7x faster in separate
|
|
312
|
+
processes than in threads.)
|
|
313
|
+
- [ ] Adaptive concurrency for rate-limited APIs (back off on errors, speed up when healthy).
|
|
314
|
+
- [ ] Mixed sync and async stages.
|
|
315
|
+
- [ ] Verified on free-threaded Python builds.
|
|
316
|
+
|
|
317
|
+
### Python versions
|
|
318
|
+
Developed against CPython 3.12 and tested on 3.15 (release candidate). Python 3.15's lazy
|
|
319
|
+
imports (PEP 810) are on the list: the optional features above will load only when used, so
|
|
320
|
+
`import stagepipe` stays near-instant.
|
|
321
|
+
|
|
322
|
+
Want something on this list sooner, or something that is missing? Open an
|
|
323
|
+
[issue](https://github.com/rafaelborja/stagepipe/issues) and describe your pipeline.
|
|
324
|
+
|
|
325
|
+
---
|
|
326
|
+
|
|
327
|
+
## Development
|
|
328
|
+
|
|
329
|
+
```bash
|
|
330
|
+
git clone https://github.com/rafaelborja/stagepipe
|
|
331
|
+
cd stagepipe
|
|
332
|
+
pip install -e .
|
|
333
|
+
python tests/stress.py # plain script, no pytest needed
|
|
334
|
+
python bench/bench.py # speed numbers above
|
|
335
|
+
python bench/memory.py # memory numbers above (needs psutil; aiostream optional)
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
## Changelog
|
|
339
|
+
|
|
340
|
+
See [CHANGELOG.md](https://github.com/rafaelborja/stagepipe/blob/main/CHANGELOG.md).
|
|
341
|
+
|
|
342
|
+
## Author
|
|
343
|
+
|
|
344
|
+
Built and maintained by [Rafael Borja](https://github.com/rafaelborja).
|
|
345
|
+
|
|
346
|
+
## License
|
|
347
|
+
|
|
348
|
+
Apache License 2.0. See [LICENSE](https://github.com/rafaelborja/stagepipe/blob/main/LICENSE).
|