stepcache 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,12 @@
1
+ # Internal notes: consumer names, issue numbers, package index, production host.
2
+ internal/
3
+
4
+ # Claude Code agent worktrees and local settings.
5
+ .claude/
6
+
7
+ .DS_Store
8
+ .venv/
9
+ __pycache__/
10
+ *.egg-info/
11
+ dist/
12
+ .pytest_cache/
@@ -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
+
@@ -0,0 +1,235 @@
1
+ Metadata-Version: 2.5
2
+ Name: stepcache
3
+ Version: 0.1.0
4
+ Summary: Content-addressed cache for multi-step processing pipelines, with early cutoff.
5
+ Project-URL: Repository, https://github.com/karlla1220/stepcache
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Operating System :: MacOS
9
+ Classifier: Operating System :: POSIX :: Linux
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+
17
+ # stepcache
18
+
19
+ Content-addressed cache for multi-step processing pipelines, with early cutoff.
20
+
21
+ Each step's result is keyed by the content hashes of its inputs and the identity of
22
+ the step (its code, tools and settings). When a step changes, only the items whose
23
+ inputs or step identity changed run again, and items whose output comes out
24
+ byte-identical stop the re-run there: later steps keep their cached results.
25
+
26
+ Status: 0.1.0. The API may still change before 1.0.
27
+
28
+ ## Install
29
+
30
+ ```
31
+ pip install stepcache
32
+ ```
33
+
34
+ To install a tagged version from this repository instead, you need `git` on the machine.
35
+ Slim container images such as `python:3.12-slim` do not have it.
36
+
37
+ ```
38
+ pip install git+https://github.com/karlla1220/stepcache@v0.1.0
39
+ ```
40
+
41
+ stepcache has no dependencies outside the standard library.
42
+
43
+ ## Example
44
+
45
+ This pipeline has two steps. `render` turns a text into a page `Blob`, and `count` reads the
46
+ page and counts its words. Each document is a subject, so the cache can say later which
47
+ documents to process again. The same code is in
48
+ [examples/quickstart.py](examples/quickstart.py), and the comments show what it prints.
49
+
50
+ ```python
51
+ import tempfile
52
+ from pathlib import Path
53
+
54
+ from stepcache import Blob, Refused, SqliteStore, Step, StepCache, Version
55
+
56
+
57
+ def render(inputs):
58
+ words = inputs['text'].split()
59
+ if not words:
60
+ return Refused('empty text')
61
+ return {'page': Blob(' '.join(words).encode())}
62
+
63
+
64
+ def count(inputs):
65
+ return {'words': len(inputs['page'].read().split())}
66
+
67
+
68
+ render_v1 = Step('render', Version.of(tools={'renderer': '1.0'}, rev='1'), render)
69
+ count_step = Step('count', Version.of(rev='1'), count)
70
+
71
+
72
+ def process(cache, render_step, subject, text):
73
+ with cache.subject(subject) as s:
74
+ page = s.run(render_step, {'text': text})
75
+ if page.status == 'refused':
76
+ return [page]
77
+ return [page, s.run(count_step, {'page': page.outputs['page']})]
78
+
79
+
80
+ with tempfile.TemporaryDirectory() as root:
81
+ cache = StepCache(SqliteStore(Path(root, 'stepcache.db'), files=Path(root, 'blobs')))
82
+
83
+ for attempt in (1, 2):
84
+ results = process(cache, render_v1, 'doc:hello', 'hello world')
85
+ print(attempt, [r.hit for r in results], results[-1].outputs)
86
+ # 1 [False, False] {'words': 2}
87
+ # 2 [True, True] {'words': 2}
88
+
89
+ empty = process(cache, render_v1, 'doc:empty', ' ')
90
+ print(empty[0].status, empty[0].refusal.reason)
91
+ # refused empty text
92
+
93
+ # A new renderer makes every subject rendered with the old one stale.
94
+ render_v2 = Step('render', Version.of(tools={'renderer': '1.1'}, rev='1'), render)
95
+ pipeline = [render_v2, count_step]
96
+ for subject, reasons in cache.stale_subjects(pipeline):
97
+ print(subject, [(r.kind, r.step, r.detail['changed']) for r in reasons])
98
+ # doc:empty [('version', 'render', {'tools': {'added': [], 'removed': [], 'changed': ['renderer']}})]
99
+ # doc:hello [('version', 'render', {'tools': {'added': [], 'removed': [], 'changed': ['renderer']}})]
100
+
101
+ # render runs again. Its page has the same bytes, so count is a hit.
102
+ results = process(cache, render_v2, 'doc:hello', 'hello world')
103
+ print([r.hit for r in results])
104
+ # [False, True]
105
+
106
+ process(cache, render_v2, 'doc:empty', ' ')
107
+ print(cache.stale_subjects(pipeline))
108
+ # []
109
+ ```
110
+
111
+ ## Keys and versions
112
+
113
+ `Step(name, version, run, run_batch=None, cache=True)` has a name, a `Version` and a `run`
114
+ function. `run` takes a dict of inputs and returns a dict of outputs or a `Refused`. Each
115
+ input and output value is a `Blob` or a JSON value. A JSON output can be at most 4096
116
+ bytes, so return longer data as a `Blob`. A longer one makes `StepCache.run` raise
117
+ `ValueError`, and nothing is stored. A `Result` of a stored or reused run has
118
+ `status == 'ok'`.
119
+
120
+ The key of a run is the sha256 of the step name, the version's sha and the inputs. A `Blob`
121
+ enters the key by its sha256 and a JSON value as it is. File names and paths do not enter
122
+ the key. When a step's output has the same bytes as before, the next step gets the same
123
+ input and its key does not change. That is the early cutoff.
124
+
125
+ `Version.of(files=None, tools=None, rev='0', code=True)` builds the version from four parts:
126
+
127
+ - `code` is the sha256 of the module file that defines `run`. When `run_batch` is in another
128
+ file, it is a hash over both files. `Step` adds it. Other modules that those files import
129
+ are not in it.
130
+ - `files` maps relative paths to sha256 values. `Version.files(root, patterns)` hashes the
131
+ files under `root` that match the glob patterns.
132
+ - `tools` maps names to strings that identify external programs or models, such as a version
133
+ string or a binary's hash. The application chooses the strings.
134
+ - `rev` is a string that you change by hand for a change that the other parts do not show.
135
+
136
+ `code=False` leaves the code out. Use it when `run` has no source file, such as a function
137
+ defined in an interactive shell. `Step` raises `ValueError` in that case. When any part
138
+ changes, every key of the step changes.
139
+
140
+ ## Refusals and errors
141
+
142
+ A step returns `Refused(reason, detail=None)` when it cannot process an input and the same
143
+ input will always get the same answer. The cache stores a refusal like a result, and the
144
+ `Result` has `status == 'refused'` and the refusal in `refusal`. `StepCache.run` does not
145
+ raise for a refusal. A step raises an exception for an error. The cache stores nothing, the
146
+ exception propagates, and the next run tries again.
147
+
148
+ ## `run_many` and `async_run`
149
+
150
+ `StepCache.run_many(step, inputs_list)` returns one `Result` per inputs dict, in input order.
151
+ Hits come from the cache. The misses run in one call of the step's `run_batch`, or one
152
+ `run` call each when the step has no `run_batch`. Identical inputs run once. A miss whose
153
+ step raised, or whose `run_batch` item is an exception, gets a result with
154
+ `status == 'error'` and the exception in `error`. The cache stores nothing for it.
155
+
156
+ `run_batch(inputs_list)` takes a list of inputs dicts and returns a list of the same length,
157
+ in the same order. Each item is a dict of outputs, a `Refused`, or an exception. When
158
+ `run_batch` itself raises, every item it was given gets an `'error'` result. When it returns
159
+ a list of another length, `run_many` raises `ValueError`.
160
+
161
+ `StepCache.async_run(step, inputs)` is `run` for async code. It awaits an `async def` step
162
+ and calls a sync step directly. An async step runs only through `async_run`, and `run`
163
+ raises `TypeError` for one.
164
+
165
+ ## Manifests and stale subjects
166
+
167
+ A subject is a unit that the application processes, such as one document. Inside
168
+ `with cache.subject(name, source=None) as s:`, the calls `s.run`, `s.run_many` and
169
+ `s.async_run` work like the `StepCache` methods and record each result in the subject's
170
+ manifest. When the block ends normally, the new manifest replaces the old one. When the
171
+ block raises, the old manifest stays. `cache.manifest(name)` returns the latest manifest,
172
+ or `None`. The manifest has the `source` you passed, so you can compare it with the current
173
+ source.
174
+
175
+ `cache.stale_subjects(pipeline, complete=False)` compares every manifest with the steps in
176
+ `pipeline` and returns `(subject, reasons)` pairs, sorted by subject. Each `Reason` has a
177
+ `kind`, a `step` and a `detail`:
178
+
179
+ - `version`: the manifest used another version of the step. `detail['old']` and
180
+ `detail['new']` are the two version shas, and `detail['changed']` lists the parts that
181
+ differ. `changed` is `None` when the old version's parts were never stored.
182
+ - `record`: the stored result is gone, for example after `cache.invalidate(step, key)`, or
183
+ another run stored a different result for the key.
184
+ - `failed`: the step failed in the block that made the manifest. The failure counts even
185
+ when the block caught the exception and went on. For a cached step, a failure retried
186
+ successfully in the same block is cleared. Any failure of a `cache=False` step in the
187
+ block leaves the subject stale, because a step with no key cannot tell a retry from
188
+ another input.
189
+ - `missing_step`: the manifest has no entry for the step. This kind appears only with
190
+ `complete=True`.
191
+
192
+ A step with `cache=False` runs every time and stores no result. A subject still records its
193
+ version, so a change of that version makes the subject stale.
194
+
195
+ ## Concurrency
196
+
197
+ Several processes on one machine can share one cache. `SqliteStore(path, files)` keeps the
198
+ records in a SQLite database at `path` and blobs over 256 KiB in the folder `files`.
199
+ Opening a cache made by another schema version raises `SchemaMismatch`, and there is
200
+ no migration yet, so delete that cache and let stepcache build a new one.
201
+
202
+ On a miss, a process claims the key before it runs the step. Other processes that need the
203
+ same key wait for the result and do not compute it again. Each claim names a lock file that
204
+ the claiming process holds with `flock`. When that process dies, even by `SIGKILL`, the
205
+ kernel releases the lock. A waiting process checks the owner every half second, sees
206
+ that it is dead, and takes over the claim. stepcache does not release the claim of a process
207
+ that is alive but stuck. Stop that process to release its claim.
208
+
209
+ ## Supported environments
210
+
211
+ - Python 3.12 or later.
212
+ - macOS and Linux, and Docker containers on them.
213
+ - Windows is not supported, because it has no `flock`.
214
+ - Network file systems such as NFS and SMB are not supported, because their file locks are
215
+ not reliable. Put the cache on a local disk.
216
+ - Containers can share a cache on one volume or bind mount. On Docker Desktop for Mac, host
217
+ processes and containers must not share one cache. The bind mount does not pass file
218
+ locks between the host and the containers. In a test, the host did not see a lock that a
219
+ container held, and the database became corrupt (`database disk image is malformed`).
220
+ Let one cache be used only by host processes or only by containers.
221
+
222
+ ## Development
223
+
224
+ Run the tests with [uv](https://docs.astral.sh/uv/):
225
+
226
+ ```
227
+ uv run pytest
228
+ ```
229
+
230
+ The design and the build plan are in [docs/design.md](docs/design.md) and
231
+ [docs/plan.md](docs/plan.md), in Korean.
232
+
233
+ ## License
234
+
235
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,219 @@
1
+ # stepcache
2
+
3
+ Content-addressed cache for multi-step processing pipelines, with early cutoff.
4
+
5
+ Each step's result is keyed by the content hashes of its inputs and the identity of
6
+ the step (its code, tools and settings). When a step changes, only the items whose
7
+ inputs or step identity changed run again, and items whose output comes out
8
+ byte-identical stop the re-run there: later steps keep their cached results.
9
+
10
+ Status: 0.1.0. The API may still change before 1.0.
11
+
12
+ ## Install
13
+
14
+ ```
15
+ pip install stepcache
16
+ ```
17
+
18
+ To install a tagged version from this repository instead, you need `git` on the machine.
19
+ Slim container images such as `python:3.12-slim` do not have it.
20
+
21
+ ```
22
+ pip install git+https://github.com/karlla1220/stepcache@v0.1.0
23
+ ```
24
+
25
+ stepcache has no dependencies outside the standard library.
26
+
27
+ ## Example
28
+
29
+ This pipeline has two steps. `render` turns a text into a page `Blob`, and `count` reads the
30
+ page and counts its words. Each document is a subject, so the cache can say later which
31
+ documents to process again. The same code is in
32
+ [examples/quickstart.py](examples/quickstart.py), and the comments show what it prints.
33
+
34
+ ```python
35
+ import tempfile
36
+ from pathlib import Path
37
+
38
+ from stepcache import Blob, Refused, SqliteStore, Step, StepCache, Version
39
+
40
+
41
+ def render(inputs):
42
+ words = inputs['text'].split()
43
+ if not words:
44
+ return Refused('empty text')
45
+ return {'page': Blob(' '.join(words).encode())}
46
+
47
+
48
+ def count(inputs):
49
+ return {'words': len(inputs['page'].read().split())}
50
+
51
+
52
+ render_v1 = Step('render', Version.of(tools={'renderer': '1.0'}, rev='1'), render)
53
+ count_step = Step('count', Version.of(rev='1'), count)
54
+
55
+
56
+ def process(cache, render_step, subject, text):
57
+ with cache.subject(subject) as s:
58
+ page = s.run(render_step, {'text': text})
59
+ if page.status == 'refused':
60
+ return [page]
61
+ return [page, s.run(count_step, {'page': page.outputs['page']})]
62
+
63
+
64
+ with tempfile.TemporaryDirectory() as root:
65
+ cache = StepCache(SqliteStore(Path(root, 'stepcache.db'), files=Path(root, 'blobs')))
66
+
67
+ for attempt in (1, 2):
68
+ results = process(cache, render_v1, 'doc:hello', 'hello world')
69
+ print(attempt, [r.hit for r in results], results[-1].outputs)
70
+ # 1 [False, False] {'words': 2}
71
+ # 2 [True, True] {'words': 2}
72
+
73
+ empty = process(cache, render_v1, 'doc:empty', ' ')
74
+ print(empty[0].status, empty[0].refusal.reason)
75
+ # refused empty text
76
+
77
+ # A new renderer makes every subject rendered with the old one stale.
78
+ render_v2 = Step('render', Version.of(tools={'renderer': '1.1'}, rev='1'), render)
79
+ pipeline = [render_v2, count_step]
80
+ for subject, reasons in cache.stale_subjects(pipeline):
81
+ print(subject, [(r.kind, r.step, r.detail['changed']) for r in reasons])
82
+ # doc:empty [('version', 'render', {'tools': {'added': [], 'removed': [], 'changed': ['renderer']}})]
83
+ # doc:hello [('version', 'render', {'tools': {'added': [], 'removed': [], 'changed': ['renderer']}})]
84
+
85
+ # render runs again. Its page has the same bytes, so count is a hit.
86
+ results = process(cache, render_v2, 'doc:hello', 'hello world')
87
+ print([r.hit for r in results])
88
+ # [False, True]
89
+
90
+ process(cache, render_v2, 'doc:empty', ' ')
91
+ print(cache.stale_subjects(pipeline))
92
+ # []
93
+ ```
94
+
95
+ ## Keys and versions
96
+
97
+ `Step(name, version, run, run_batch=None, cache=True)` has a name, a `Version` and a `run`
98
+ function. `run` takes a dict of inputs and returns a dict of outputs or a `Refused`. Each
99
+ input and output value is a `Blob` or a JSON value. A JSON output can be at most 4096
100
+ bytes, so return longer data as a `Blob`. A longer one makes `StepCache.run` raise
101
+ `ValueError`, and nothing is stored. A `Result` of a stored or reused run has
102
+ `status == 'ok'`.
103
+
104
+ The key of a run is the sha256 of the step name, the version's sha and the inputs. A `Blob`
105
+ enters the key by its sha256 and a JSON value as it is. File names and paths do not enter
106
+ the key. When a step's output has the same bytes as before, the next step gets the same
107
+ input and its key does not change. That is the early cutoff.
108
+
109
+ `Version.of(files=None, tools=None, rev='0', code=True)` builds the version from four parts:
110
+
111
+ - `code` is the sha256 of the module file that defines `run`. When `run_batch` is in another
112
+ file, it is a hash over both files. `Step` adds it. Other modules that those files import
113
+ are not in it.
114
+ - `files` maps relative paths to sha256 values. `Version.files(root, patterns)` hashes the
115
+ files under `root` that match the glob patterns.
116
+ - `tools` maps names to strings that identify external programs or models, such as a version
117
+ string or a binary's hash. The application chooses the strings.
118
+ - `rev` is a string that you change by hand for a change that the other parts do not show.
119
+
120
+ `code=False` leaves the code out. Use it when `run` has no source file, such as a function
121
+ defined in an interactive shell. `Step` raises `ValueError` in that case. When any part
122
+ changes, every key of the step changes.
123
+
124
+ ## Refusals and errors
125
+
126
+ A step returns `Refused(reason, detail=None)` when it cannot process an input and the same
127
+ input will always get the same answer. The cache stores a refusal like a result, and the
128
+ `Result` has `status == 'refused'` and the refusal in `refusal`. `StepCache.run` does not
129
+ raise for a refusal. A step raises an exception for an error. The cache stores nothing, the
130
+ exception propagates, and the next run tries again.
131
+
132
+ ## `run_many` and `async_run`
133
+
134
+ `StepCache.run_many(step, inputs_list)` returns one `Result` per inputs dict, in input order.
135
+ Hits come from the cache. The misses run in one call of the step's `run_batch`, or one
136
+ `run` call each when the step has no `run_batch`. Identical inputs run once. A miss whose
137
+ step raised, or whose `run_batch` item is an exception, gets a result with
138
+ `status == 'error'` and the exception in `error`. The cache stores nothing for it.
139
+
140
+ `run_batch(inputs_list)` takes a list of inputs dicts and returns a list of the same length,
141
+ in the same order. Each item is a dict of outputs, a `Refused`, or an exception. When
142
+ `run_batch` itself raises, every item it was given gets an `'error'` result. When it returns
143
+ a list of another length, `run_many` raises `ValueError`.
144
+
145
+ `StepCache.async_run(step, inputs)` is `run` for async code. It awaits an `async def` step
146
+ and calls a sync step directly. An async step runs only through `async_run`, and `run`
147
+ raises `TypeError` for one.
148
+
149
+ ## Manifests and stale subjects
150
+
151
+ A subject is a unit that the application processes, such as one document. Inside
152
+ `with cache.subject(name, source=None) as s:`, the calls `s.run`, `s.run_many` and
153
+ `s.async_run` work like the `StepCache` methods and record each result in the subject's
154
+ manifest. When the block ends normally, the new manifest replaces the old one. When the
155
+ block raises, the old manifest stays. `cache.manifest(name)` returns the latest manifest,
156
+ or `None`. The manifest has the `source` you passed, so you can compare it with the current
157
+ source.
158
+
159
+ `cache.stale_subjects(pipeline, complete=False)` compares every manifest with the steps in
160
+ `pipeline` and returns `(subject, reasons)` pairs, sorted by subject. Each `Reason` has a
161
+ `kind`, a `step` and a `detail`:
162
+
163
+ - `version`: the manifest used another version of the step. `detail['old']` and
164
+ `detail['new']` are the two version shas, and `detail['changed']` lists the parts that
165
+ differ. `changed` is `None` when the old version's parts were never stored.
166
+ - `record`: the stored result is gone, for example after `cache.invalidate(step, key)`, or
167
+ another run stored a different result for the key.
168
+ - `failed`: the step failed in the block that made the manifest. The failure counts even
169
+ when the block caught the exception and went on. For a cached step, a failure retried
170
+ successfully in the same block is cleared. Any failure of a `cache=False` step in the
171
+ block leaves the subject stale, because a step with no key cannot tell a retry from
172
+ another input.
173
+ - `missing_step`: the manifest has no entry for the step. This kind appears only with
174
+ `complete=True`.
175
+
176
+ A step with `cache=False` runs every time and stores no result. A subject still records its
177
+ version, so a change of that version makes the subject stale.
178
+
179
+ ## Concurrency
180
+
181
+ Several processes on one machine can share one cache. `SqliteStore(path, files)` keeps the
182
+ records in a SQLite database at `path` and blobs over 256 KiB in the folder `files`.
183
+ Opening a cache made by another schema version raises `SchemaMismatch`, and there is
184
+ no migration yet, so delete that cache and let stepcache build a new one.
185
+
186
+ On a miss, a process claims the key before it runs the step. Other processes that need the
187
+ same key wait for the result and do not compute it again. Each claim names a lock file that
188
+ the claiming process holds with `flock`. When that process dies, even by `SIGKILL`, the
189
+ kernel releases the lock. A waiting process checks the owner every half second, sees
190
+ that it is dead, and takes over the claim. stepcache does not release the claim of a process
191
+ that is alive but stuck. Stop that process to release its claim.
192
+
193
+ ## Supported environments
194
+
195
+ - Python 3.12 or later.
196
+ - macOS and Linux, and Docker containers on them.
197
+ - Windows is not supported, because it has no `flock`.
198
+ - Network file systems such as NFS and SMB are not supported, because their file locks are
199
+ not reliable. Put the cache on a local disk.
200
+ - Containers can share a cache on one volume or bind mount. On Docker Desktop for Mac, host
201
+ processes and containers must not share one cache. The bind mount does not pass file
202
+ locks between the host and the containers. In a test, the host did not see a lock that a
203
+ container held, and the database became corrupt (`database disk image is malformed`).
204
+ Let one cache be used only by host processes or only by containers.
205
+
206
+ ## Development
207
+
208
+ Run the tests with [uv](https://docs.astral.sh/uv/):
209
+
210
+ ```
211
+ uv run pytest
212
+ ```
213
+
214
+ The design and the build plan are in [docs/design.md](docs/design.md) and
215
+ [docs/plan.md](docs/plan.md), in Korean.
216
+
217
+ ## License
218
+
219
+ Apache-2.0. See [LICENSE](LICENSE).