chunk-invariance 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.
- chunk_invariance-0.1.0/LICENSE +190 -0
- chunk_invariance-0.1.0/PKG-INFO +111 -0
- chunk_invariance-0.1.0/README.md +81 -0
- chunk_invariance-0.1.0/chunk_invariance/__init__.py +26 -0
- chunk_invariance-0.1.0/chunk_invariance/adapters.py +54 -0
- chunk_invariance-0.1.0/chunk_invariance/core.py +156 -0
- chunk_invariance-0.1.0/chunk_invariance/examples.py +75 -0
- chunk_invariance-0.1.0/chunk_invariance/py.typed +0 -0
- chunk_invariance-0.1.0/chunk_invariance/strategies.py +40 -0
- chunk_invariance-0.1.0/chunk_invariance.egg-info/PKG-INFO +111 -0
- chunk_invariance-0.1.0/chunk_invariance.egg-info/SOURCES.txt +14 -0
- chunk_invariance-0.1.0/chunk_invariance.egg-info/dependency_links.txt +1 -0
- chunk_invariance-0.1.0/chunk_invariance.egg-info/requires.txt +3 -0
- chunk_invariance-0.1.0/chunk_invariance.egg-info/top_level.txt +1 -0
- chunk_invariance-0.1.0/pyproject.toml +63 -0
- chunk_invariance-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,190 @@
|
|
|
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
|
+
Copyright 2026 Ninad Phalak
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: chunk-invariance
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Assert that a streaming filter gives the same output however its input is split into chunks.
|
|
5
|
+
Author-email: Ninad Phalak <ninadphalak@gmail.com>
|
|
6
|
+
Maintainer-email: Ninad Phalak <ninadphalak@gmail.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://github.com/ninadphalak/LLM-Shield-Proxy/tree/main/chunk-invariance
|
|
9
|
+
Project-URL: Repository, https://github.com/ninadphalak/LLM-Shield-Proxy
|
|
10
|
+
Project-URL: Bug Tracker, https://github.com/ninadphalak/LLM-Shield-Proxy/issues
|
|
11
|
+
Keywords: streaming,testing,redaction,guardrails,chunk-boundary,property-based-testing
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Framework :: Hypothesis
|
|
15
|
+
Classifier: Framework :: Pytest
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Testing
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Provides-Extra: hypothesis
|
|
28
|
+
Requires-Dist: hypothesis>=6; extra == "hypothesis"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# chunk-invariance
|
|
32
|
+
|
|
33
|
+
A streaming filter (a redactor, a guardrail, a rewriter) is correct only if, for every way of
|
|
34
|
+
splitting an input into chunks, the concatenated streamed output equals the output of filtering
|
|
35
|
+
the whole input at once. This package turns that rule into one assertion.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from chunk_invariance import assert_chunk_invariant
|
|
39
|
+
|
|
40
|
+
def redact(text): # your filter on the whole input
|
|
41
|
+
return text.replace("sk-AbCd1234", "[KEY]")
|
|
42
|
+
|
|
43
|
+
def redact_stream(chunks): # your filter on a stream: takes chunks, yields chunks
|
|
44
|
+
for chunk in chunks:
|
|
45
|
+
yield redact(chunk) # redacts each chunk alone
|
|
46
|
+
|
|
47
|
+
def test_streaming_redaction():
|
|
48
|
+
assert_chunk_invariant(redact_stream, redact, "use sk-AbCd1234 now")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
That test fails, and names the smallest split that breaks it:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
chunk_invariance.core.ChunkInvarianceError: stream filter is not chunk-invariant
|
|
55
|
+
input: 'use sk-AbCd1234 now'
|
|
56
|
+
split: ['use s', 'k-AbCd1234 now'] (cut at 5)
|
|
57
|
+
whole: 'use [KEY] now'
|
|
58
|
+
streamed: 'use sk-AbCd1234 now'
|
|
59
|
+
split #6 in the order tried; generated splits run fewest parts first
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install chunk-invariance
|
|
64
|
+
pip install "chunk-invariance[hypothesis]" # optional Hypothesis strategies
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## What it catches
|
|
68
|
+
|
|
69
|
+
- A filter that evaluates each chunk alone, so a value cut across two chunks matches neither half.
|
|
70
|
+
- A filter that prepends a fixed carryover from the previous chunk. The match fires, but the start
|
|
71
|
+
of the value was already emitted with the previous chunk.
|
|
72
|
+
- A hold-back that is shorter than the pattern, a missing end-of-stream flush, and output that is
|
|
73
|
+
corrupted rather than leaked (any difference from the whole-input output fails).
|
|
74
|
+
|
|
75
|
+
`chunk_invariance.examples` has one correct filter (`hold_back`) and the two wrong designs
|
|
76
|
+
(`design_a`, `design_b`) for the same pattern, as a worked comparison.
|
|
77
|
+
|
|
78
|
+
## What it does not catch
|
|
79
|
+
|
|
80
|
+
It tests a filter you can call in-process. It does not test a running gateway, where the chunks
|
|
81
|
+
are decided by an upstream model, a network and an SSE parser. For that, use
|
|
82
|
+
[`pii-leak-benchmark`](https://pypi.org/project/pii-leak-benchmark/), which sends
|
|
83
|
+
fragmented responses through the gateway and checks what reaches the client.
|
|
84
|
+
|
|
85
|
+
It checks the splits you ask for. The default is the whole input plus every single cut, which
|
|
86
|
+
catches a value cut in two. `splits="all"` tries every split of a short input (up to 16
|
|
87
|
+
characters); `splits=3` tries every split into at most three parts; an explicit list of chunk
|
|
88
|
+
lists runs exactly those. It cannot prove a filter correct for inputs you did not give it.
|
|
89
|
+
|
|
90
|
+
## API
|
|
91
|
+
|
|
92
|
+
| Name | Does |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `assert_chunk_invariant(stream_filter, whole_filter, text, *, splits="all-two-part")` | Raises `ChunkInvarianceError` (an `AssertionError`) on the first failing split, fewest parts first. Returns the number of splits checked. Works on `str` and `bytes`. |
|
|
95
|
+
| `assert_chunk_invariant_async(...)` | The same, for an async generator filter, inside an async test. |
|
|
96
|
+
| `two_part_splits(text)` | Every split into two non-empty parts. |
|
|
97
|
+
| `all_splits(text, max_parts=None)` | Every split into at most `max_parts` non-empty parts, the whole input first. |
|
|
98
|
+
| `per_chunk(process, *, state=dict, flush=None)` | Adapts `process(chunk, state) -> output` and `flush(state) -> output`, with fresh state per stream. |
|
|
99
|
+
| `from_async(async_stream_filter)` | Adapts an async generator filter for the synchronous assertion. |
|
|
100
|
+
| `strategies.splits_of(text, max_parts=None)` | Hypothesis strategy: random splits of `text`, shrinking toward fewer cuts. |
|
|
101
|
+
| `strategies.text_and_splits(texts, max_parts=None)` | Hypothesis strategy: `(text, chunks)` pairs. |
|
|
102
|
+
|
|
103
|
+
`stream_filter` is called once per split, so it must start from fresh state each time.
|
|
104
|
+
|
|
105
|
+
## Background
|
|
106
|
+
|
|
107
|
+
The invariant and the two wrong designs are described in Phalak, N. (2026), *Split-Boundary
|
|
108
|
+
Leaks in Streaming Guardrails*, Zenodo, [10.5281/zenodo.22909585](https://doi.org/10.5281/zenodo.22909585).
|
|
109
|
+
|
|
110
|
+
Standard library only. Apache-2.0. A TypeScript version with the same API is published on npm
|
|
111
|
+
as `chunk-invariance`.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# chunk-invariance
|
|
2
|
+
|
|
3
|
+
A streaming filter (a redactor, a guardrail, a rewriter) is correct only if, for every way of
|
|
4
|
+
splitting an input into chunks, the concatenated streamed output equals the output of filtering
|
|
5
|
+
the whole input at once. This package turns that rule into one assertion.
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from chunk_invariance import assert_chunk_invariant
|
|
9
|
+
|
|
10
|
+
def redact(text): # your filter on the whole input
|
|
11
|
+
return text.replace("sk-AbCd1234", "[KEY]")
|
|
12
|
+
|
|
13
|
+
def redact_stream(chunks): # your filter on a stream: takes chunks, yields chunks
|
|
14
|
+
for chunk in chunks:
|
|
15
|
+
yield redact(chunk) # redacts each chunk alone
|
|
16
|
+
|
|
17
|
+
def test_streaming_redaction():
|
|
18
|
+
assert_chunk_invariant(redact_stream, redact, "use sk-AbCd1234 now")
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
That test fails, and names the smallest split that breaks it:
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
chunk_invariance.core.ChunkInvarianceError: stream filter is not chunk-invariant
|
|
25
|
+
input: 'use sk-AbCd1234 now'
|
|
26
|
+
split: ['use s', 'k-AbCd1234 now'] (cut at 5)
|
|
27
|
+
whole: 'use [KEY] now'
|
|
28
|
+
streamed: 'use sk-AbCd1234 now'
|
|
29
|
+
split #6 in the order tried; generated splits run fewest parts first
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install chunk-invariance
|
|
34
|
+
pip install "chunk-invariance[hypothesis]" # optional Hypothesis strategies
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## What it catches
|
|
38
|
+
|
|
39
|
+
- A filter that evaluates each chunk alone, so a value cut across two chunks matches neither half.
|
|
40
|
+
- A filter that prepends a fixed carryover from the previous chunk. The match fires, but the start
|
|
41
|
+
of the value was already emitted with the previous chunk.
|
|
42
|
+
- A hold-back that is shorter than the pattern, a missing end-of-stream flush, and output that is
|
|
43
|
+
corrupted rather than leaked (any difference from the whole-input output fails).
|
|
44
|
+
|
|
45
|
+
`chunk_invariance.examples` has one correct filter (`hold_back`) and the two wrong designs
|
|
46
|
+
(`design_a`, `design_b`) for the same pattern, as a worked comparison.
|
|
47
|
+
|
|
48
|
+
## What it does not catch
|
|
49
|
+
|
|
50
|
+
It tests a filter you can call in-process. It does not test a running gateway, where the chunks
|
|
51
|
+
are decided by an upstream model, a network and an SSE parser. For that, use
|
|
52
|
+
[`pii-leak-benchmark`](https://pypi.org/project/pii-leak-benchmark/), which sends
|
|
53
|
+
fragmented responses through the gateway and checks what reaches the client.
|
|
54
|
+
|
|
55
|
+
It checks the splits you ask for. The default is the whole input plus every single cut, which
|
|
56
|
+
catches a value cut in two. `splits="all"` tries every split of a short input (up to 16
|
|
57
|
+
characters); `splits=3` tries every split into at most three parts; an explicit list of chunk
|
|
58
|
+
lists runs exactly those. It cannot prove a filter correct for inputs you did not give it.
|
|
59
|
+
|
|
60
|
+
## API
|
|
61
|
+
|
|
62
|
+
| Name | Does |
|
|
63
|
+
|---|---|
|
|
64
|
+
| `assert_chunk_invariant(stream_filter, whole_filter, text, *, splits="all-two-part")` | Raises `ChunkInvarianceError` (an `AssertionError`) on the first failing split, fewest parts first. Returns the number of splits checked. Works on `str` and `bytes`. |
|
|
65
|
+
| `assert_chunk_invariant_async(...)` | The same, for an async generator filter, inside an async test. |
|
|
66
|
+
| `two_part_splits(text)` | Every split into two non-empty parts. |
|
|
67
|
+
| `all_splits(text, max_parts=None)` | Every split into at most `max_parts` non-empty parts, the whole input first. |
|
|
68
|
+
| `per_chunk(process, *, state=dict, flush=None)` | Adapts `process(chunk, state) -> output` and `flush(state) -> output`, with fresh state per stream. |
|
|
69
|
+
| `from_async(async_stream_filter)` | Adapts an async generator filter for the synchronous assertion. |
|
|
70
|
+
| `strategies.splits_of(text, max_parts=None)` | Hypothesis strategy: random splits of `text`, shrinking toward fewer cuts. |
|
|
71
|
+
| `strategies.text_and_splits(texts, max_parts=None)` | Hypothesis strategy: `(text, chunks)` pairs. |
|
|
72
|
+
|
|
73
|
+
`stream_filter` is called once per split, so it must start from fresh state each time.
|
|
74
|
+
|
|
75
|
+
## Background
|
|
76
|
+
|
|
77
|
+
The invariant and the two wrong designs are described in Phalak, N. (2026), *Split-Boundary
|
|
78
|
+
Leaks in Streaming Guardrails*, Zenodo, [10.5281/zenodo.22909585](https://doi.org/10.5281/zenodo.22909585).
|
|
79
|
+
|
|
80
|
+
Standard library only. Apache-2.0. A TypeScript version with the same API is published on npm
|
|
81
|
+
as `chunk-invariance`.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Test that a streaming filter gives the same output however its input is split into chunks.
|
|
2
|
+
|
|
3
|
+
Standard library only. The optional Hypothesis strategies live in ``chunk_invariance.strategies``
|
|
4
|
+
and need the ``hypothesis`` extra.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .adapters import from_async, per_chunk
|
|
8
|
+
from .core import (
|
|
9
|
+
ChunkInvarianceError,
|
|
10
|
+
all_splits,
|
|
11
|
+
assert_chunk_invariant,
|
|
12
|
+
assert_chunk_invariant_async,
|
|
13
|
+
two_part_splits,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__version__ = "0.1.0"
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ChunkInvarianceError",
|
|
20
|
+
"all_splits",
|
|
21
|
+
"assert_chunk_invariant",
|
|
22
|
+
"assert_chunk_invariant_async",
|
|
23
|
+
"from_async",
|
|
24
|
+
"per_chunk",
|
|
25
|
+
"two_part_splits",
|
|
26
|
+
]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Turn common streaming-filter shapes into the ``stream_filter`` the assertion calls."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import Any, AsyncIterable, AsyncIterator, Callable, Iterable, Iterator, Optional
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def per_chunk(
|
|
10
|
+
process: Callable[[Any, Any], Any],
|
|
11
|
+
*,
|
|
12
|
+
state: Callable[[], Any] = dict,
|
|
13
|
+
flush: Optional[Callable[[Any], Any]] = None,
|
|
14
|
+
) -> Callable[[Iterable[Any]], Iterator[Any]]:
|
|
15
|
+
"""Adapt ``process(chunk, state) -> output`` plus an optional ``flush(state) -> output``.
|
|
16
|
+
|
|
17
|
+
``state`` is a factory called once per stream, so every split starts clean. ``flush`` is
|
|
18
|
+
called after the last chunk; leave it out only if the filter really has no end-of-stream step.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def stream_filter(chunks: Iterable[Any]) -> Iterator[Any]:
|
|
22
|
+
current = state()
|
|
23
|
+
for chunk in chunks:
|
|
24
|
+
yield process(chunk, current)
|
|
25
|
+
if flush is not None:
|
|
26
|
+
yield flush(current)
|
|
27
|
+
|
|
28
|
+
return stream_filter
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def from_async(
|
|
32
|
+
async_stream_filter: Callable[[AsyncIterable[Any]], AsyncIterable[Any]],
|
|
33
|
+
) -> Callable[[Iterable[Any]], Iterator[Any]]:
|
|
34
|
+
"""Adapt an async generator function that takes an async iterable of chunks.
|
|
35
|
+
|
|
36
|
+
Each stream runs to completion in its own event loop. Inside a running loop (an async test),
|
|
37
|
+
use ``assert_chunk_invariant_async`` instead.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
async def feed(chunks: Iterable[Any]) -> AsyncIterator[Any]:
|
|
41
|
+
for chunk in chunks:
|
|
42
|
+
yield chunk
|
|
43
|
+
|
|
44
|
+
async def collect(chunks: Iterable[Any]) -> list:
|
|
45
|
+
return [piece async for piece in async_stream_filter(feed(chunks))]
|
|
46
|
+
|
|
47
|
+
def stream_filter(chunks: Iterable[Any]) -> Iterator[Any]:
|
|
48
|
+
try:
|
|
49
|
+
asyncio.get_running_loop()
|
|
50
|
+
except RuntimeError:
|
|
51
|
+
return iter(asyncio.run(collect(list(chunks))))
|
|
52
|
+
raise RuntimeError("from_async cannot run inside an event loop; use assert_chunk_invariant_async")
|
|
53
|
+
|
|
54
|
+
return stream_filter
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""The invariant, the splits it is checked over, and the assertion."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from itertools import combinations
|
|
7
|
+
from typing import Any, AsyncIterable, AsyncIterator, Callable, Iterable, Iterator, List, Optional, Sequence, Union
|
|
8
|
+
|
|
9
|
+
Text = Union[str, bytes]
|
|
10
|
+
StreamFilter = Callable[[Iterable[Any]], Iterable[Any]]
|
|
11
|
+
WholeFilter = Callable[[Any], Any]
|
|
12
|
+
Splits = Union[str, int, Iterable[Sequence[Any]]]
|
|
13
|
+
|
|
14
|
+
# `splits="all"` enumerates 2 ** (len(text) - 1) splits; past this length that is too many
|
|
15
|
+
# to run in a test. Pass an int (the most parts per split) for longer inputs.
|
|
16
|
+
ALL_SPLITS_MAX_LENGTH = 16
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ChunkInvarianceError(AssertionError):
|
|
20
|
+
"""The streamed output for one split differs from filtering the whole input at once."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, text: Text, chunks: Sequence[Text], expected: Text, actual: Text, splits_tried: int) -> None:
|
|
23
|
+
self.text = text
|
|
24
|
+
self.chunks = list(chunks)
|
|
25
|
+
self.expected = expected
|
|
26
|
+
self.actual = actual
|
|
27
|
+
self.splits_tried = splits_tried
|
|
28
|
+
cuts = _cut_points(self.chunks)
|
|
29
|
+
super().__init__(
|
|
30
|
+
"stream filter is not chunk-invariant\n"
|
|
31
|
+
f" input: {text!r}\n"
|
|
32
|
+
f" split: {self.chunks!r} (cut at {', '.join(map(str, cuts)) or 'nothing: one chunk'})\n"
|
|
33
|
+
f" whole: {expected!r}\n"
|
|
34
|
+
f" streamed: {actual!r}\n"
|
|
35
|
+
f" split #{splits_tried} in the order tried; generated splits run fewest parts first"
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _cut_points(chunks: Sequence[Text]) -> List[int]:
|
|
40
|
+
cuts, offset = [], 0
|
|
41
|
+
for chunk in chunks[:-1]:
|
|
42
|
+
offset += len(chunk)
|
|
43
|
+
cuts.append(offset)
|
|
44
|
+
return cuts
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _split_at(text: Text, cuts: Sequence[int]) -> List[Text]:
|
|
48
|
+
bounds = [0, *cuts, len(text)]
|
|
49
|
+
return [text[a:b] for a, b in zip(bounds, bounds[1:])]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def two_part_splits(text: Text) -> Iterator[List[Text]]:
|
|
53
|
+
"""Every split of ``text`` into two non-empty parts, left cut first."""
|
|
54
|
+
for cut in range(1, len(text)):
|
|
55
|
+
yield [text[:cut], text[cut:]]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def all_splits(text: Text, max_parts: Optional[int] = None) -> Iterator[List[Text]]:
|
|
59
|
+
"""Every split of ``text`` into at most ``max_parts`` non-empty parts (all of them when None).
|
|
60
|
+
|
|
61
|
+
Ordered by number of parts, then by cut positions, so the first failure found is a minimal one.
|
|
62
|
+
The single-part split ``[text]`` comes first.
|
|
63
|
+
"""
|
|
64
|
+
if max_parts is not None and max_parts < 1:
|
|
65
|
+
raise ValueError("max_parts must be at least 1")
|
|
66
|
+
positions = range(1, len(text))
|
|
67
|
+
most = len(text) if max_parts is None else min(max_parts, max(len(text), 1))
|
|
68
|
+
for parts in range(1, most + 1):
|
|
69
|
+
for cuts in combinations(positions, parts - 1):
|
|
70
|
+
yield _split_at(text, cuts)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _resolve_splits(text: Text, splits: Splits) -> Iterable[Sequence[Text]]:
|
|
74
|
+
if splits == "all-two-part":
|
|
75
|
+
return all_splits(text, 2)
|
|
76
|
+
if splits == "all":
|
|
77
|
+
if len(text) > ALL_SPLITS_MAX_LENGTH:
|
|
78
|
+
raise ValueError(
|
|
79
|
+
f'splits="all" is 2 ** {len(text) - 1} splits for a {len(text)}-character input; '
|
|
80
|
+
f"use it up to {ALL_SPLITS_MAX_LENGTH} characters, or pass an int (the most parts per split)"
|
|
81
|
+
)
|
|
82
|
+
return all_splits(text)
|
|
83
|
+
if isinstance(splits, bool):
|
|
84
|
+
raise TypeError("splits must be 'all-two-part', 'all', an int, or an iterable of chunk lists")
|
|
85
|
+
if isinstance(splits, int):
|
|
86
|
+
return all_splits(text, splits)
|
|
87
|
+
if isinstance(splits, (str, bytes)):
|
|
88
|
+
raise ValueError(f"unknown splits value {splits!r}; use 'all-two-part', 'all', an int, or chunk lists")
|
|
89
|
+
return splits
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _join(text: Text, pieces: Iterable[Text]) -> Text:
|
|
93
|
+
return text[:0].join(pieces)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def assert_chunk_invariant(
|
|
97
|
+
stream_filter: StreamFilter,
|
|
98
|
+
whole_filter: WholeFilter,
|
|
99
|
+
text: Text,
|
|
100
|
+
*,
|
|
101
|
+
splits: Splits = "all-two-part",
|
|
102
|
+
) -> int:
|
|
103
|
+
"""Assert that streaming ``text`` in any of ``splits`` gives what filtering it whole gives.
|
|
104
|
+
|
|
105
|
+
``stream_filter`` takes an iterable of input chunks and returns or yields output chunks; it is
|
|
106
|
+
called once per split, so it must start from fresh state each call. ``whole_filter`` takes the
|
|
107
|
+
whole input. ``splits`` is ``"all-two-part"`` (the default: the input whole, then every single
|
|
108
|
+
cut), ``"all"`` (every split, for short inputs), an int (every split into at most that many
|
|
109
|
+
parts), or an iterable of explicit chunk lists, which must each join back to ``text``.
|
|
110
|
+
|
|
111
|
+
Raises ``ChunkInvarianceError`` on the first split, fewest parts first, whose concatenated
|
|
112
|
+
output differs. Returns the number of splits checked.
|
|
113
|
+
"""
|
|
114
|
+
expected = whole_filter(text)
|
|
115
|
+
tried = 0
|
|
116
|
+
for chunks in _resolve_splits(text, splits):
|
|
117
|
+
chunks = list(chunks)
|
|
118
|
+
if _join(text, chunks) != text:
|
|
119
|
+
raise ValueError(f"explicit split {chunks!r} does not join back to the input")
|
|
120
|
+
tried += 1
|
|
121
|
+
actual = _join(text, stream_filter(iter(chunks)))
|
|
122
|
+
if actual != expected:
|
|
123
|
+
raise ChunkInvarianceError(text, chunks, expected, actual, tried)
|
|
124
|
+
return tried
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
async def assert_chunk_invariant_async(
|
|
128
|
+
stream_filter: Callable[[AsyncIterable[Any]], AsyncIterable[Any]],
|
|
129
|
+
whole_filter: Callable[[Any], Any],
|
|
130
|
+
text: Text,
|
|
131
|
+
*,
|
|
132
|
+
splits: Splits = "all-two-part",
|
|
133
|
+
) -> int:
|
|
134
|
+
"""``assert_chunk_invariant`` for an async generator filter, for use inside an async test.
|
|
135
|
+
|
|
136
|
+
``stream_filter`` takes an async iterable of chunks and yields output chunks. ``whole_filter``
|
|
137
|
+
may return the output or an awaitable of it.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
async def feed(chunks: Sequence[Text]) -> AsyncIterator[Text]:
|
|
141
|
+
for chunk in chunks:
|
|
142
|
+
yield chunk
|
|
143
|
+
|
|
144
|
+
expected = whole_filter(text)
|
|
145
|
+
if inspect.isawaitable(expected):
|
|
146
|
+
expected = await expected
|
|
147
|
+
tried = 0
|
|
148
|
+
for chunks in _resolve_splits(text, splits):
|
|
149
|
+
chunks = list(chunks)
|
|
150
|
+
if _join(text, chunks) != text:
|
|
151
|
+
raise ValueError(f"explicit split {chunks!r} does not join back to the input")
|
|
152
|
+
tried += 1
|
|
153
|
+
actual = _join(text, [piece async for piece in stream_filter(feed(chunks))])
|
|
154
|
+
if actual != expected:
|
|
155
|
+
raise ChunkInvarianceError(text, chunks, expected, actual, tried)
|
|
156
|
+
return tried
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Three streaming redactors for one pattern: one correct, two that leak across a chunk boundary.
|
|
2
|
+
|
|
3
|
+
The pattern is a fixed-length key, ``sk-`` plus eight letters or digits, replaced by ``[KEY]``.
|
|
4
|
+
``redact`` is the whole-input filter all three are compared against.
|
|
5
|
+
|
|
6
|
+
- ``hold_back`` is correct. It holds back the last ``KEY_LENGTH - 1`` characters, the longest
|
|
7
|
+
tail that could still be the start of a key, and redacts before it emits.
|
|
8
|
+
- ``design_a`` redacts each chunk on its own. A key cut in two is never seen whole.
|
|
9
|
+
- ``design_b`` prepends a fixed carryover from the previous chunk and redacts the join. The match
|
|
10
|
+
fires, but the start of the key already left with the previous chunk.
|
|
11
|
+
|
|
12
|
+
Run ``assert_chunk_invariant(design_a, redact, "use sk-AbCd1234 now")`` to see the failure.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from typing import Dict, Iterable, Iterator
|
|
19
|
+
|
|
20
|
+
from .adapters import per_chunk
|
|
21
|
+
|
|
22
|
+
KEY = re.compile(r"sk-[A-Za-z0-9]{8}")
|
|
23
|
+
KEY_LENGTH = 11
|
|
24
|
+
MASK = "[KEY]"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def redact(text: str) -> str:
|
|
28
|
+
"""The whole-input filter: every key replaced."""
|
|
29
|
+
return KEY.sub(MASK, text)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _hold_back_process(chunk: str, state: Dict[str, str]) -> str:
|
|
33
|
+
buffer = state.get("buffer", "") + chunk
|
|
34
|
+
# A key that starts before `safe` ends inside the buffer, so it is already complete.
|
|
35
|
+
safe = len(buffer) - (KEY_LENGTH - 1)
|
|
36
|
+
out, emitted = [], 0
|
|
37
|
+
for match in KEY.finditer(buffer):
|
|
38
|
+
if match.start() >= safe:
|
|
39
|
+
break
|
|
40
|
+
out.append(buffer[emitted : match.start()])
|
|
41
|
+
out.append(MASK)
|
|
42
|
+
emitted = match.end()
|
|
43
|
+
keep_from = max(emitted, safe)
|
|
44
|
+
out.append(buffer[emitted:keep_from])
|
|
45
|
+
state["buffer"] = buffer[keep_from:]
|
|
46
|
+
return "".join(out)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _hold_back_flush(state: Dict[str, str]) -> str:
|
|
50
|
+
rest, state["buffer"] = state.get("buffer", ""), ""
|
|
51
|
+
return redact(rest)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
hold_back = per_chunk(_hold_back_process, state=dict, flush=_hold_back_flush)
|
|
55
|
+
hold_back.__doc__ = "Correct: holds back a possible key prefix and redacts before emitting."
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def design_a(chunks: Iterable[str]) -> Iterator[str]:
|
|
59
|
+
"""Leaks: each chunk is redacted alone, so a key split across two chunks passes."""
|
|
60
|
+
for chunk in chunks:
|
|
61
|
+
yield redact(chunk)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def design_b(chunks: Iterable[str], carry: int = KEY_LENGTH - 1) -> Iterator[str]:
|
|
65
|
+
"""Leaks: prepends the last ``carry`` characters of the previous chunk and redacts the join.
|
|
66
|
+
|
|
67
|
+
The match now fires, but the carried characters were already emitted with the previous
|
|
68
|
+
chunk, so the start of a split key has gone out unredacted, and cutting the carry off the
|
|
69
|
+
redacted join corrupts what follows.
|
|
70
|
+
"""
|
|
71
|
+
previous = ""
|
|
72
|
+
for chunk in chunks:
|
|
73
|
+
joined = previous + chunk
|
|
74
|
+
yield redact(joined)[len(previous) :]
|
|
75
|
+
previous = joined[-carry:] if carry else ""
|
|
File without changes
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Hypothesis strategies for splits. Needs ``pip install chunk-invariance[hypothesis]``.
|
|
2
|
+
|
|
3
|
+
from hypothesis import given
|
|
4
|
+
from chunk_invariance import assert_chunk_invariant
|
|
5
|
+
from chunk_invariance.strategies import splits_of
|
|
6
|
+
|
|
7
|
+
@given(splits_of("use sk-AbCd1234 now"))
|
|
8
|
+
def test_filter(chunks):
|
|
9
|
+
assert_chunk_invariant(my_filter, redact, "".join(chunks), splits=[chunks])
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Any, List, Optional
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from hypothesis import strategies as st
|
|
18
|
+
except ImportError as exc: # pragma: no cover - exercised only without the extra
|
|
19
|
+
raise ImportError("chunk_invariance.strategies needs Hypothesis: pip install 'chunk-invariance[hypothesis]'") from exc
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def splits_of(text: Any, max_parts: Optional[int] = None) -> "st.SearchStrategy[List[Any]]":
|
|
23
|
+
"""Random splits of one fixed input into non-empty parts; shrinks toward fewer cuts."""
|
|
24
|
+
positions = list(range(1, len(text)))
|
|
25
|
+
most = len(positions) if max_parts is None else max(max_parts - 1, 0)
|
|
26
|
+
|
|
27
|
+
def build(cuts: List[int]) -> List[Any]:
|
|
28
|
+
bounds = [0, *sorted(cuts), len(text)]
|
|
29
|
+
return [text[a:b] for a, b in zip(bounds, bounds[1:])]
|
|
30
|
+
|
|
31
|
+
if not positions or most == 0:
|
|
32
|
+
return st.just([text])
|
|
33
|
+
return st.lists(st.sampled_from(positions), unique=True, max_size=most).map(build)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@st.composite
|
|
37
|
+
def text_and_splits(draw: Any, texts: "st.SearchStrategy[Any]", max_parts: Optional[int] = None) -> Any:
|
|
38
|
+
"""Draw an input from ``texts``, then a split of it. Returns ``(text, chunks)``."""
|
|
39
|
+
text = draw(texts)
|
|
40
|
+
return text, draw(splits_of(text, max_parts))
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: chunk-invariance
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Assert that a streaming filter gives the same output however its input is split into chunks.
|
|
5
|
+
Author-email: Ninad Phalak <ninadphalak@gmail.com>
|
|
6
|
+
Maintainer-email: Ninad Phalak <ninadphalak@gmail.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://github.com/ninadphalak/LLM-Shield-Proxy/tree/main/chunk-invariance
|
|
9
|
+
Project-URL: Repository, https://github.com/ninadphalak/LLM-Shield-Proxy
|
|
10
|
+
Project-URL: Bug Tracker, https://github.com/ninadphalak/LLM-Shield-Proxy/issues
|
|
11
|
+
Keywords: streaming,testing,redaction,guardrails,chunk-boundary,property-based-testing
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Framework :: Hypothesis
|
|
15
|
+
Classifier: Framework :: Pytest
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Testing
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Provides-Extra: hypothesis
|
|
28
|
+
Requires-Dist: hypothesis>=6; extra == "hypothesis"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# chunk-invariance
|
|
32
|
+
|
|
33
|
+
A streaming filter (a redactor, a guardrail, a rewriter) is correct only if, for every way of
|
|
34
|
+
splitting an input into chunks, the concatenated streamed output equals the output of filtering
|
|
35
|
+
the whole input at once. This package turns that rule into one assertion.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from chunk_invariance import assert_chunk_invariant
|
|
39
|
+
|
|
40
|
+
def redact(text): # your filter on the whole input
|
|
41
|
+
return text.replace("sk-AbCd1234", "[KEY]")
|
|
42
|
+
|
|
43
|
+
def redact_stream(chunks): # your filter on a stream: takes chunks, yields chunks
|
|
44
|
+
for chunk in chunks:
|
|
45
|
+
yield redact(chunk) # redacts each chunk alone
|
|
46
|
+
|
|
47
|
+
def test_streaming_redaction():
|
|
48
|
+
assert_chunk_invariant(redact_stream, redact, "use sk-AbCd1234 now")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
That test fails, and names the smallest split that breaks it:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
chunk_invariance.core.ChunkInvarianceError: stream filter is not chunk-invariant
|
|
55
|
+
input: 'use sk-AbCd1234 now'
|
|
56
|
+
split: ['use s', 'k-AbCd1234 now'] (cut at 5)
|
|
57
|
+
whole: 'use [KEY] now'
|
|
58
|
+
streamed: 'use sk-AbCd1234 now'
|
|
59
|
+
split #6 in the order tried; generated splits run fewest parts first
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install chunk-invariance
|
|
64
|
+
pip install "chunk-invariance[hypothesis]" # optional Hypothesis strategies
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## What it catches
|
|
68
|
+
|
|
69
|
+
- A filter that evaluates each chunk alone, so a value cut across two chunks matches neither half.
|
|
70
|
+
- A filter that prepends a fixed carryover from the previous chunk. The match fires, but the start
|
|
71
|
+
of the value was already emitted with the previous chunk.
|
|
72
|
+
- A hold-back that is shorter than the pattern, a missing end-of-stream flush, and output that is
|
|
73
|
+
corrupted rather than leaked (any difference from the whole-input output fails).
|
|
74
|
+
|
|
75
|
+
`chunk_invariance.examples` has one correct filter (`hold_back`) and the two wrong designs
|
|
76
|
+
(`design_a`, `design_b`) for the same pattern, as a worked comparison.
|
|
77
|
+
|
|
78
|
+
## What it does not catch
|
|
79
|
+
|
|
80
|
+
It tests a filter you can call in-process. It does not test a running gateway, where the chunks
|
|
81
|
+
are decided by an upstream model, a network and an SSE parser. For that, use
|
|
82
|
+
[`pii-leak-benchmark`](https://pypi.org/project/pii-leak-benchmark/), which sends
|
|
83
|
+
fragmented responses through the gateway and checks what reaches the client.
|
|
84
|
+
|
|
85
|
+
It checks the splits you ask for. The default is the whole input plus every single cut, which
|
|
86
|
+
catches a value cut in two. `splits="all"` tries every split of a short input (up to 16
|
|
87
|
+
characters); `splits=3` tries every split into at most three parts; an explicit list of chunk
|
|
88
|
+
lists runs exactly those. It cannot prove a filter correct for inputs you did not give it.
|
|
89
|
+
|
|
90
|
+
## API
|
|
91
|
+
|
|
92
|
+
| Name | Does |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `assert_chunk_invariant(stream_filter, whole_filter, text, *, splits="all-two-part")` | Raises `ChunkInvarianceError` (an `AssertionError`) on the first failing split, fewest parts first. Returns the number of splits checked. Works on `str` and `bytes`. |
|
|
95
|
+
| `assert_chunk_invariant_async(...)` | The same, for an async generator filter, inside an async test. |
|
|
96
|
+
| `two_part_splits(text)` | Every split into two non-empty parts. |
|
|
97
|
+
| `all_splits(text, max_parts=None)` | Every split into at most `max_parts` non-empty parts, the whole input first. |
|
|
98
|
+
| `per_chunk(process, *, state=dict, flush=None)` | Adapts `process(chunk, state) -> output` and `flush(state) -> output`, with fresh state per stream. |
|
|
99
|
+
| `from_async(async_stream_filter)` | Adapts an async generator filter for the synchronous assertion. |
|
|
100
|
+
| `strategies.splits_of(text, max_parts=None)` | Hypothesis strategy: random splits of `text`, shrinking toward fewer cuts. |
|
|
101
|
+
| `strategies.text_and_splits(texts, max_parts=None)` | Hypothesis strategy: `(text, chunks)` pairs. |
|
|
102
|
+
|
|
103
|
+
`stream_filter` is called once per split, so it must start from fresh state each time.
|
|
104
|
+
|
|
105
|
+
## Background
|
|
106
|
+
|
|
107
|
+
The invariant and the two wrong designs are described in Phalak, N. (2026), *Split-Boundary
|
|
108
|
+
Leaks in Streaming Guardrails*, Zenodo, [10.5281/zenodo.22909585](https://doi.org/10.5281/zenodo.22909585).
|
|
109
|
+
|
|
110
|
+
Standard library only. Apache-2.0. A TypeScript version with the same API is published on npm
|
|
111
|
+
as `chunk-invariance`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
chunk_invariance/__init__.py
|
|
5
|
+
chunk_invariance/adapters.py
|
|
6
|
+
chunk_invariance/core.py
|
|
7
|
+
chunk_invariance/examples.py
|
|
8
|
+
chunk_invariance/py.typed
|
|
9
|
+
chunk_invariance/strategies.py
|
|
10
|
+
chunk_invariance.egg-info/PKG-INFO
|
|
11
|
+
chunk_invariance.egg-info/SOURCES.txt
|
|
12
|
+
chunk_invariance.egg-info/dependency_links.txt
|
|
13
|
+
chunk_invariance.egg-info/requires.txt
|
|
14
|
+
chunk_invariance.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
chunk_invariance
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "chunk-invariance"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Assert that a streaming filter gives the same output however its input is split into chunks."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Ninad Phalak", email = "ninadphalak@gmail.com"}
|
|
14
|
+
]
|
|
15
|
+
maintainers = [
|
|
16
|
+
{name = "Ninad Phalak", email = "ninadphalak@gmail.com"}
|
|
17
|
+
]
|
|
18
|
+
keywords = [
|
|
19
|
+
"streaming",
|
|
20
|
+
"testing",
|
|
21
|
+
"redaction",
|
|
22
|
+
"guardrails",
|
|
23
|
+
"chunk-boundary",
|
|
24
|
+
"property-based-testing",
|
|
25
|
+
]
|
|
26
|
+
classifiers = [
|
|
27
|
+
"Development Status :: 4 - Beta",
|
|
28
|
+
"Intended Audience :: Developers",
|
|
29
|
+
"Framework :: Hypothesis",
|
|
30
|
+
"Framework :: Pytest",
|
|
31
|
+
"Programming Language :: Python :: 3",
|
|
32
|
+
"Programming Language :: Python :: 3.9",
|
|
33
|
+
"Programming Language :: Python :: 3.10",
|
|
34
|
+
"Programming Language :: Python :: 3.11",
|
|
35
|
+
"Programming Language :: Python :: 3.12",
|
|
36
|
+
"Programming Language :: Python :: 3.13",
|
|
37
|
+
"Topic :: Software Development :: Testing",
|
|
38
|
+
"Typing :: Typed",
|
|
39
|
+
]
|
|
40
|
+
# No runtime dependencies. Hypothesis is optional and only chunk_invariance.strategies imports it.
|
|
41
|
+
dependencies = []
|
|
42
|
+
|
|
43
|
+
[project.optional-dependencies]
|
|
44
|
+
hypothesis = ["hypothesis>=6"]
|
|
45
|
+
|
|
46
|
+
[project.urls]
|
|
47
|
+
Homepage = "https://github.com/ninadphalak/LLM-Shield-Proxy/tree/main/chunk-invariance"
|
|
48
|
+
Repository = "https://github.com/ninadphalak/LLM-Shield-Proxy"
|
|
49
|
+
"Bug Tracker" = "https://github.com/ninadphalak/LLM-Shield-Proxy/issues"
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.packages.find]
|
|
52
|
+
include = ["chunk_invariance*"]
|
|
53
|
+
|
|
54
|
+
[tool.setuptools.package-data]
|
|
55
|
+
chunk_invariance = ["py.typed"]
|
|
56
|
+
|
|
57
|
+
[tool.ruff]
|
|
58
|
+
line-length = 120
|
|
59
|
+
target-version = "py39"
|
|
60
|
+
|
|
61
|
+
[tool.ruff.lint]
|
|
62
|
+
select = ["E", "W", "F", "I"]
|
|
63
|
+
ignore = ["E501"]
|