cendor-squeeze 0.5.1__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.
- cendor_squeeze-0.5.1/.gitignore +19 -0
- cendor_squeeze-0.5.1/CHANGELOG.md +59 -0
- cendor_squeeze-0.5.1/LICENSE +201 -0
- cendor_squeeze-0.5.1/NOTICE +7 -0
- cendor_squeeze-0.5.1/PKG-INFO +42 -0
- cendor_squeeze-0.5.1/README.md +30 -0
- cendor_squeeze-0.5.1/pyproject.toml +16 -0
- cendor_squeeze-0.5.1/src/cendor/squeeze/__init__.py +445 -0
- cendor_squeeze-0.5.1/src/cendor/squeeze/py.typed +0 -0
- cendor_squeeze-0.5.1/src/cendor/squeeze/store.py +75 -0
- cendor_squeeze-0.5.1/tests/test_squeeze.py +236 -0
- cendor_squeeze-0.5.1/tests/test_squeeze_properties.py +32 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
*.egg-info/
|
|
4
|
+
build/
|
|
5
|
+
dist/
|
|
6
|
+
.venv/
|
|
7
|
+
.uv/
|
|
8
|
+
.ruff_cache/
|
|
9
|
+
.pytest_cache/
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.coverage
|
|
12
|
+
htmlcov/
|
|
13
|
+
.idea/
|
|
14
|
+
.vscode/
|
|
15
|
+
.DS_Store
|
|
16
|
+
*.log
|
|
17
|
+
|
|
18
|
+
# MkDocs build output (local preview only)
|
|
19
|
+
site/
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Changelog — cendor-squeeze
|
|
2
|
+
|
|
3
|
+
Format: [Keep a Changelog](https://keepachangelog.com).
|
|
4
|
+
|
|
5
|
+
## [0.5.1] — 2026-06-27
|
|
6
|
+
### Changed
|
|
7
|
+
- Docs only: headline compression ratios are the benchmark-harness figures (`docs/benchmarks.md`: JSON ~49% / logs ~97% / code ~53% / prose ~51% on realistic corpora) — synthetic, highly-repetitive demo figures (e.g. ~94% on one repeated string) are not representative. Also clarified that `target_tokens` truncation is lossy in the emitted output but fully reversible via `handle.expand()` (the content-addressed store keeps the byte-exact original).
|
|
8
|
+
|
|
9
|
+
## [0.5.0] — 2026-06-24
|
|
10
|
+
### Fixed
|
|
11
|
+
- **`target_tokens` is now never exceeded — for every kind, including prose.** The prose compressor always keeps its top-ranked sentence; it previously returned that sentence (and the ≤1-sentence / `fidelity="lossless"` / invalid-JSON-fallback paths) *without* truncating, so the output could blow past the budget (e.g. 23 tokens for a `target_tokens=5`). All paths now apply a final truncate. A new property test asserts `count(small) <= target` across json/logs/code/prose.
|
|
12
|
+
- **The code compressor no longer corrupts string literals.** Comment stripping was a blind regex (`(?://|#).*`) that cut inside strings — `"https://example.com"` became `"https:` and `"color #ff0000"` became `"color`. It's now a string-aware, single-pass scanner (single/double/backtick quotes with escapes); `#` preprocessor directives (`#include`, `#define`, …) and `#!` shebang lines are preserved. Reversibility was always intact; now the *compressed* text is valid too.
|
|
13
|
+
- **Log dedup keeps chronological order under a `target_tokens` budget.** It used to re-sort surviving lines by frequency (scrambling the timeline); it now selects the noisiest patterns to keep but renders them back in original order.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
- `Handle.to_dict()` / `Handle.from_dict()` — serialize a handle (not the original) so, paired with a durable `SQLiteStore`, you can `expand()` after the process restarts. `Handle.technique` exposes the recorded technique.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
- `SQLiteStore` opens with `check_same_thread=False` (usable from a threaded server; CCR writes are idempotent) and gained `__len__` for parity with `MemoryStore`.
|
|
20
|
+
- Internal truncation uses a binary search over the cut length instead of an iterative shrink — far fewer tokenizer calls on large inputs.
|
|
21
|
+
|
|
22
|
+
## [0.4.3] — 2026-06-23
|
|
23
|
+
### Changed
|
|
24
|
+
- Packaging: `LICENSE` and `NOTICE` are now bundled in the distribution (`dist-info/licenses/`), so the Apache-2.0 terms — including the §7 warranty disclaimer and §8 liability limitation — travel inside every wheel/sdist. The README footer states the "as is" / no-warranty / use-at-your-own-risk terms. No code changes.
|
|
25
|
+
|
|
26
|
+
## [0.4.2] — 2026-06-23
|
|
27
|
+
### Changed
|
|
28
|
+
- README repositioned around squeeze's lane: the **deterministic, zero-dependency, no-model-download** compressor that is the default backend behind contextkit's `Compressor` protocol — swap in any other backend (e.g. an ML-based compressor) via `contextkit.use_compressor(...)`. Honest, content-dependent ratio framing (see the benchmarks). No code changes.
|
|
29
|
+
|
|
30
|
+
## [0.4.1] — 2026-06-23
|
|
31
|
+
### Changed
|
|
32
|
+
- Relicensed from MIT to Apache-2.0 — adds an explicit patent grant and contribution terms, a better fit for a public library suite.
|
|
33
|
+
- README links to the docs page and CHANGELOG are now absolute GitHub URLs so they resolve on PyPI (they previously broke as repo-relative paths).
|
|
34
|
+
|
|
35
|
+
## [0.4.0] — 2026-06-23
|
|
36
|
+
### Added
|
|
37
|
+
- Bounded CCR store: `MemoryStore(max_items=...)` evicts oldest originals (FIFO) so the store doesn't grow unbounded. Expanding an evicted handle raises `KeyError` (documented trade-off).
|
|
38
|
+
|
|
39
|
+
## [0.3.0] — 2026-06-23
|
|
40
|
+
### Added
|
|
41
|
+
- Pluggable CCR store backends via `use_store(...)`: `store.MemoryStore` (default) and `store.SQLiteStore` (originals persist across processes, deduped by hash).
|
|
42
|
+
|
|
43
|
+
## [0.2.0] — 2026-06-23
|
|
44
|
+
### Added
|
|
45
|
+
- `code` compressor (strip comments / blank lines; keep structure) + code detection in `kind="auto"`.
|
|
46
|
+
- `fidelity` dial (`lossless` / `balanced` / `aggressive`) across json / prose / code.
|
|
47
|
+
|
|
48
|
+
## [0.1.0] — 2026-06-23
|
|
49
|
+
### Added
|
|
50
|
+
- Initial release: `compress()`/`decompress()`/`detect()` for JSON (minify + drop nulls), logs (normalize + dedup), and prose (extractive), with a reversible `Handle`/`expand()` backed by a content-addressed store. `SqueezeCompressor` satisfies core's `Compressor`; wires into contextkit via `contextkit[squeeze]`.
|
|
51
|
+
|
|
52
|
+
[0.5.0]: https://pypi.org/project/cendor-squeeze/0.5.0/
|
|
53
|
+
[0.4.3]: https://pypi.org/project/cendor-squeeze/0.4.3/
|
|
54
|
+
[0.4.2]: https://pypi.org/project/cendor-squeeze/0.4.2/
|
|
55
|
+
[0.4.1]: https://pypi.org/project/cendor-squeeze/0.4.1/
|
|
56
|
+
[0.4.0]: https://pypi.org/project/cendor-squeeze/0.4.0/
|
|
57
|
+
[0.3.0]: https://pypi.org/project/cendor-squeeze/0.3.0/
|
|
58
|
+
[0.2.0]: https://pypi.org/project/cendor-squeeze/0.2.0/
|
|
59
|
+
[0.1.0]: https://pypi.org/project/cendor-squeeze/0.1.0/
|
|
@@ -0,0 +1,201 @@
|
|
|
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 2026 Raghav Mishra (PowerAI Labs)
|
|
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.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cendor-squeeze
|
|
3
|
+
Version: 0.5.1
|
|
4
|
+
Summary: Compress: shrink verbose context (JSON/logs/prose) 60-90% — reversibly. compress() returns a handle; expand() restores the original.
|
|
5
|
+
Author: Raghav Mishra
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
License-File: NOTICE
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Requires-Dist: cendor-core<0.2,>=0.1
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# cendor-squeeze
|
|
14
|
+
|
|
15
|
+
Shrink verbose context — JSON, logs, code, prose — without throwing anything away. Compression
|
|
16
|
+
returns a *handle*; the original is always restorable. Content-aware: each type gets a
|
|
17
|
+
purpose-built, **deterministic** compressor — **no LLM, no model download, byte-reproducible**.
|
|
18
|
+
|
|
19
|
+
**Up to 97% smaller, 100% reversible — zero dependencies, deterministic output.**
|
|
20
|
+
|
|
21
|
+
  · `pip install cendor-squeeze`
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from cendor.squeeze import compress
|
|
25
|
+
|
|
26
|
+
small, handle = compress(huge_json, kind="auto") # detect + route
|
|
27
|
+
small, handle = compress(source_code, kind="code", fidelity="aggressive")
|
|
28
|
+
small, handle = compress(logs, kind="logs", target_tokens=400) # compress to a budget
|
|
29
|
+
original = handle.expand() # restore, byte-for-byte
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Highlights
|
|
33
|
+
|
|
34
|
+
- **Four purpose-built compressors** — JSON (minify + drop nulls), logs (normalize timestamps/UUIDs + dedup repeats into `(×N)`, chronological), code (strip comments — *string-aware*, so a `//` or `#` inside a literal stays put; keeps preprocessor & shebang), prose (extractive ranking). `detect()` auto-routes.
|
|
35
|
+
- **Compress to a budget** — `target_tokens` is **never exceeded**; `fidelity="lossless" | "balanced" | "aggressive"`. No LLM, no download, byte-reproducible.
|
|
36
|
+
- **100% reversible** — a content-addressed store (deduped by hash) keeps every original; `handle.expand()` restores it byte-for-byte no matter how hard you squeeze.
|
|
37
|
+
- **Survives restarts** — `handle.to_dict()` / `Handle.from_dict()` next to a durable `squeeze.store.SQLiteStore`; or a bounded `MemoryStore(max_items=…)` via `use_store(...)`.
|
|
38
|
+
- **The deterministic default, swappable** — wired through core's `Compressor` protocol (not a hard import), so `contextkit.use_compressor(...)` can replace it globally with any backend (even a heavier ML compressor). squeeze stays the pick for reproducible, offline, audit-friendly output.
|
|
39
|
+
|
|
40
|
+
**Inbound** — usually `contextkit` calls it for you (`Block(evict="compress")`). Ratios are content-dependent (logs compress most, structured JSON least) — see the [benchmarks](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/benchmarks.md).
|
|
41
|
+
|
|
42
|
+
See [`docs/squeeze.md`](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/squeeze.md) · [CHANGELOG](https://github.com/PowerAI-Labs/Cendor/blob/main/packages/cendor-squeeze/CHANGELOG.md). *Part of the Cendor stack — [github.com/PowerAI-Labs/Cendor](https://github.com/PowerAI-Labs/Cendor). Powered by PowerAI Labs. Apache-2.0; provided "as is", without warranty — use at your own risk (LICENSE §7–8).*
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# cendor-squeeze
|
|
2
|
+
|
|
3
|
+
Shrink verbose context — JSON, logs, code, prose — without throwing anything away. Compression
|
|
4
|
+
returns a *handle*; the original is always restorable. Content-aware: each type gets a
|
|
5
|
+
purpose-built, **deterministic** compressor — **no LLM, no model download, byte-reproducible**.
|
|
6
|
+
|
|
7
|
+
**Up to 97% smaller, 100% reversible — zero dependencies, deterministic output.**
|
|
8
|
+
|
|
9
|
+
  · `pip install cendor-squeeze`
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from cendor.squeeze import compress
|
|
13
|
+
|
|
14
|
+
small, handle = compress(huge_json, kind="auto") # detect + route
|
|
15
|
+
small, handle = compress(source_code, kind="code", fidelity="aggressive")
|
|
16
|
+
small, handle = compress(logs, kind="logs", target_tokens=400) # compress to a budget
|
|
17
|
+
original = handle.expand() # restore, byte-for-byte
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Highlights
|
|
21
|
+
|
|
22
|
+
- **Four purpose-built compressors** — JSON (minify + drop nulls), logs (normalize timestamps/UUIDs + dedup repeats into `(×N)`, chronological), code (strip comments — *string-aware*, so a `//` or `#` inside a literal stays put; keeps preprocessor & shebang), prose (extractive ranking). `detect()` auto-routes.
|
|
23
|
+
- **Compress to a budget** — `target_tokens` is **never exceeded**; `fidelity="lossless" | "balanced" | "aggressive"`. No LLM, no download, byte-reproducible.
|
|
24
|
+
- **100% reversible** — a content-addressed store (deduped by hash) keeps every original; `handle.expand()` restores it byte-for-byte no matter how hard you squeeze.
|
|
25
|
+
- **Survives restarts** — `handle.to_dict()` / `Handle.from_dict()` next to a durable `squeeze.store.SQLiteStore`; or a bounded `MemoryStore(max_items=…)` via `use_store(...)`.
|
|
26
|
+
- **The deterministic default, swappable** — wired through core's `Compressor` protocol (not a hard import), so `contextkit.use_compressor(...)` can replace it globally with any backend (even a heavier ML compressor). squeeze stays the pick for reproducible, offline, audit-friendly output.
|
|
27
|
+
|
|
28
|
+
**Inbound** — usually `contextkit` calls it for you (`Block(evict="compress")`). Ratios are content-dependent (logs compress most, structured JSON least) — see the [benchmarks](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/benchmarks.md).
|
|
29
|
+
|
|
30
|
+
See [`docs/squeeze.md`](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/squeeze.md) · [CHANGELOG](https://github.com/PowerAI-Labs/Cendor/blob/main/packages/cendor-squeeze/CHANGELOG.md). *Part of the Cendor stack — [github.com/PowerAI-Labs/Cendor](https://github.com/PowerAI-Labs/Cendor). Powered by PowerAI Labs. Apache-2.0; provided "as is", without warranty — use at your own risk (LICENSE §7–8).*
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "cendor-squeeze"
|
|
3
|
+
version = "0.5.1"
|
|
4
|
+
description = "Compress: shrink verbose context (JSON/logs/prose) 60-90% — reversibly. compress() returns a handle; expand() restores the original."
|
|
5
|
+
requires-python = ">=3.11"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
authors = [{ name = "Raghav Mishra" }]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
dependencies = ["cendor-core>=0.1,<0.2"]
|
|
10
|
+
|
|
11
|
+
[build-system]
|
|
12
|
+
requires = ["hatchling"]
|
|
13
|
+
build-backend = "hatchling.build"
|
|
14
|
+
|
|
15
|
+
[tool.hatch.build.targets.wheel]
|
|
16
|
+
packages = ["src/cendor"] # contributes cendor/squeeze only — NEVER add src/cendor/__init__.py
|
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
"""cendor.squeeze — content-aware, reversible context compression.
|
|
2
|
+
|
|
3
|
+
Shrink verbose context without throwing anything away: :func:`compress` returns ``(small, handle)``
|
|
4
|
+
and ``handle.expand()`` restores the original on demand. Content is routed by type — JSON, logs,
|
|
5
|
+
and prose each get a purpose-built, deterministic compressor (no LLM). Reversibility is guaranteed
|
|
6
|
+
by a **content-addressed store** (CCR): every original is kept keyed by its hash, deduped across
|
|
7
|
+
calls, so ``expand()`` is always exact no matter how hard we squeeze.
|
|
8
|
+
|
|
9
|
+
Satisfies ``cendor.core.protocols.Compressor`` by shape, so ``contextkit`` uses it for
|
|
10
|
+
``Block(evict="compress")`` via the ``contextkit[squeeze]`` extra — without importing this package.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import uuid
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from cendor.core import tokens
|
|
23
|
+
|
|
24
|
+
from .store import MemoryStore
|
|
25
|
+
|
|
26
|
+
__all__ = ["compress", "decompress", "detect", "use_store", "Handle", "SqueezeCompressor"]
|
|
27
|
+
|
|
28
|
+
# Active content-addressed store (CCR): sha256(original) -> original. Deduped; the basis of
|
|
29
|
+
# reversibility. Default in-process; swap via use_store() for a persistent backend.
|
|
30
|
+
_backend: Any = MemoryStore()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def use_store(store: Any) -> Any:
|
|
34
|
+
"""Swap the CCR backend (e.g. ``store.SQLiteStore``); returns the previous one. (docs §5)
|
|
35
|
+
|
|
36
|
+
A backend is any object with ``get(key) -> str`` and ``put(key, value) -> None``. Handles
|
|
37
|
+
expand against whichever backend is active at expand time.
|
|
38
|
+
"""
|
|
39
|
+
global _backend
|
|
40
|
+
previous, _backend = _backend, store
|
|
41
|
+
return previous
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Handle:
|
|
46
|
+
"""Restore handle for a compression. ``expand()`` returns the exact original. (docs §5)"""
|
|
47
|
+
|
|
48
|
+
id: str
|
|
49
|
+
kind: str
|
|
50
|
+
original_ref: str # CCR key into the content store
|
|
51
|
+
restore_map: dict = field(default_factory=dict)
|
|
52
|
+
|
|
53
|
+
def expand(self) -> str:
|
|
54
|
+
"""Return the original content, byte-for-byte (from the active CCR backend)."""
|
|
55
|
+
return _backend.get(self.original_ref)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def technique(self) -> str:
|
|
59
|
+
"""The compression technique recorded for this handle (e.g. ``"minify+dropnulls"``)."""
|
|
60
|
+
return str(self.restore_map.get("technique", ""))
|
|
61
|
+
|
|
62
|
+
def to_dict(self) -> dict:
|
|
63
|
+
"""Serialize the handle (not the original). Persist it alongside a durable store
|
|
64
|
+
(e.g. :class:`store.SQLiteStore`) to :meth:`expand` after the process restarts."""
|
|
65
|
+
return {
|
|
66
|
+
"id": self.id,
|
|
67
|
+
"kind": self.kind,
|
|
68
|
+
"original_ref": self.original_ref,
|
|
69
|
+
"restore_map": dict(self.restore_map),
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_dict(cls, data: dict) -> Handle:
|
|
74
|
+
"""Rebuild a handle from :meth:`to_dict`; ``expand()`` resolves via the active store."""
|
|
75
|
+
return cls(
|
|
76
|
+
id=data["id"],
|
|
77
|
+
kind=data["kind"],
|
|
78
|
+
original_ref=data["original_ref"],
|
|
79
|
+
restore_map=dict(data.get("restore_map", {})),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _store(original: str) -> str:
|
|
84
|
+
key = hashlib.sha256(original.encode("utf-8")).hexdigest()
|
|
85
|
+
_backend.put(key, original)
|
|
86
|
+
return key
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# --------------------------------------------------------------------------- detection
|
|
90
|
+
|
|
91
|
+
_TS = re.compile(r"\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b")
|
|
92
|
+
_UUID = re.compile(r"\b[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}\b")
|
|
93
|
+
_LEVEL = re.compile(r"\b(?:DEBUG|INFO|WARN|WARNING|ERROR|CRITICAL|TRACE|FATAL)\b")
|
|
94
|
+
|
|
95
|
+
_FIDELITY = ("lossless", "balanced", "aggressive")
|
|
96
|
+
_CODE_MARKERS = (
|
|
97
|
+
"def ",
|
|
98
|
+
"class ",
|
|
99
|
+
"function ",
|
|
100
|
+
"func ",
|
|
101
|
+
"import ",
|
|
102
|
+
"from ",
|
|
103
|
+
"return ",
|
|
104
|
+
"const ",
|
|
105
|
+
"let ",
|
|
106
|
+
"var ",
|
|
107
|
+
"public ",
|
|
108
|
+
"private ",
|
|
109
|
+
"#include",
|
|
110
|
+
"=>",
|
|
111
|
+
"</",
|
|
112
|
+
)
|
|
113
|
+
# Preprocessor/import directives that begin with `#` but must NOT be stripped as comments.
|
|
114
|
+
_PREPROC = re.compile(
|
|
115
|
+
r"#\s*(?:include|define|undef|ifdef|ifndef|endif|else|elif|if|pragma|error|line|import)\b"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _strip_comments(code: str) -> str:
|
|
120
|
+
"""Remove ``//``, ``/* */`` and ``#`` comments while leaving string/char literals intact.
|
|
121
|
+
|
|
122
|
+
A single-pass, string-aware scanner (handles single/double/backtick quotes with escapes),
|
|
123
|
+
so a ``//`` or ``#`` *inside* a literal — a URL, a color, a path — is preserved instead of
|
|
124
|
+
being cut. ``#`` preprocessor directives (``#include``, ``#define``, …) and shebang (``#!``)
|
|
125
|
+
lines are kept; otherwise ``#`` begins a line comment (Python/shell style). Not a parser — a
|
|
126
|
+
deterministic heuristic; reversibility is unaffected (the original is always in the CCR store).
|
|
127
|
+
"""
|
|
128
|
+
out: list[str] = []
|
|
129
|
+
i, n = 0, len(code)
|
|
130
|
+
quote: str | None = None
|
|
131
|
+
in_block = False
|
|
132
|
+
at_line_start = True # no non-space char seen yet on the current line
|
|
133
|
+
while i < n:
|
|
134
|
+
ch = code[i]
|
|
135
|
+
nxt = code[i + 1] if i + 1 < n else ""
|
|
136
|
+
if in_block:
|
|
137
|
+
if ch == "*" and nxt == "/":
|
|
138
|
+
in_block = False
|
|
139
|
+
i += 2
|
|
140
|
+
else:
|
|
141
|
+
if ch == "\n":
|
|
142
|
+
out.append(ch)
|
|
143
|
+
i += 1
|
|
144
|
+
continue
|
|
145
|
+
if quote is not None:
|
|
146
|
+
out.append(ch)
|
|
147
|
+
if ch == "\\" and i + 1 < n:
|
|
148
|
+
out.append(nxt)
|
|
149
|
+
i += 2
|
|
150
|
+
continue
|
|
151
|
+
if ch == quote:
|
|
152
|
+
quote = None
|
|
153
|
+
i += 1
|
|
154
|
+
continue
|
|
155
|
+
if ch in "\"'`":
|
|
156
|
+
quote = ch
|
|
157
|
+
out.append(ch)
|
|
158
|
+
at_line_start = False
|
|
159
|
+
i += 1
|
|
160
|
+
continue
|
|
161
|
+
if ch == "/" and nxt == "/":
|
|
162
|
+
while i < n and code[i] != "\n":
|
|
163
|
+
i += 1
|
|
164
|
+
continue
|
|
165
|
+
if ch == "/" and nxt == "*":
|
|
166
|
+
in_block = True
|
|
167
|
+
i += 2
|
|
168
|
+
continue
|
|
169
|
+
if ch == "#" and not ((at_line_start and nxt == "!") or _PREPROC.match(code, i)):
|
|
170
|
+
while i < n and code[i] != "\n":
|
|
171
|
+
i += 1
|
|
172
|
+
continue
|
|
173
|
+
if ch == "\n":
|
|
174
|
+
at_line_start = True
|
|
175
|
+
elif not ch.isspace():
|
|
176
|
+
at_line_start = False
|
|
177
|
+
out.append(ch)
|
|
178
|
+
i += 1
|
|
179
|
+
return "".join(out)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def detect(content: str) -> str:
|
|
183
|
+
"""Detect the content kind: ``"json"`` | ``"logs"`` | ``"code"`` | ``"prose"``. (docs §4)"""
|
|
184
|
+
s = content.strip()
|
|
185
|
+
if not s:
|
|
186
|
+
return "prose"
|
|
187
|
+
if s[0] in "{[":
|
|
188
|
+
try:
|
|
189
|
+
json.loads(s)
|
|
190
|
+
return "json"
|
|
191
|
+
except (ValueError, TypeError):
|
|
192
|
+
pass
|
|
193
|
+
if _looks_like_logs(s):
|
|
194
|
+
return "logs"
|
|
195
|
+
if _looks_like_code(s):
|
|
196
|
+
return "code"
|
|
197
|
+
return "prose"
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _looks_like_logs(s: str) -> bool:
|
|
201
|
+
lines = [ln for ln in s.splitlines() if ln.strip()]
|
|
202
|
+
if len(lines) < 3:
|
|
203
|
+
return False
|
|
204
|
+
hits = sum(1 for ln in lines if _TS.search(ln) or _LEVEL.search(ln))
|
|
205
|
+
return hits >= len(lines) * 0.5
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _looks_like_code(s: str) -> bool:
|
|
209
|
+
lines = [ln for ln in s.splitlines() if ln.strip()]
|
|
210
|
+
if not lines:
|
|
211
|
+
return False
|
|
212
|
+
hits = sum(
|
|
213
|
+
1
|
|
214
|
+
for ln in lines
|
|
215
|
+
if any(m in ln for m in _CODE_MARKERS) or ln.strip().endswith(("{", "}", ";", ":"))
|
|
216
|
+
)
|
|
217
|
+
return hits >= max(1, len(lines) * 0.3)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
# --------------------------------------------------------------------------- public API
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def compress(
|
|
224
|
+
content: Any,
|
|
225
|
+
kind: str = "auto",
|
|
226
|
+
target_tokens: int | None = None,
|
|
227
|
+
model: str = "gpt-4o",
|
|
228
|
+
fidelity: str = "balanced",
|
|
229
|
+
) -> tuple[str, Handle]:
|
|
230
|
+
"""Compress ``content`` and return ``(small, handle)``. ``handle.expand()`` restores it.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
content: A string, or a JSON-serializable object (dict/list).
|
|
234
|
+
kind: ``"auto"`` (detect) or one of ``"json"`` | ``"logs"`` | ``"code"`` | ``"prose"``.
|
|
235
|
+
target_tokens: If given, compress *to* this budget (best effort, never exceeds it).
|
|
236
|
+
model: Model id used for token counting.
|
|
237
|
+
fidelity: How hard to squeeze — ``"lossless"`` (structural only), ``"balanced"`` (default),
|
|
238
|
+
or ``"aggressive"``. Reversibility is unaffected; the original is always in the handle.
|
|
239
|
+
"""
|
|
240
|
+
if fidelity not in _FIDELITY:
|
|
241
|
+
raise ValueError(f"fidelity must be one of {_FIDELITY}, got {fidelity!r}")
|
|
242
|
+
if isinstance(content, str):
|
|
243
|
+
original = content
|
|
244
|
+
else:
|
|
245
|
+
original = json.dumps(content, ensure_ascii=False, separators=(",", ":"))
|
|
246
|
+
if kind == "auto":
|
|
247
|
+
kind = "json"
|
|
248
|
+
|
|
249
|
+
if kind == "auto":
|
|
250
|
+
kind = detect(original)
|
|
251
|
+
|
|
252
|
+
if kind == "json":
|
|
253
|
+
small, restore_map = _compress_json(original, target_tokens, model, fidelity)
|
|
254
|
+
elif kind == "logs":
|
|
255
|
+
small, restore_map = _compress_logs(original, target_tokens, model)
|
|
256
|
+
elif kind == "code":
|
|
257
|
+
small, restore_map = _compress_code(original, target_tokens, model, fidelity)
|
|
258
|
+
else:
|
|
259
|
+
small, restore_map = _compress_prose(original, target_tokens, model, fidelity)
|
|
260
|
+
|
|
261
|
+
handle = Handle(
|
|
262
|
+
id=uuid.uuid4().hex,
|
|
263
|
+
kind=kind,
|
|
264
|
+
original_ref=_store(original),
|
|
265
|
+
restore_map=restore_map,
|
|
266
|
+
)
|
|
267
|
+
return small, handle
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def decompress(handle: Handle) -> str:
|
|
271
|
+
"""Restore the original content for a handle (same as ``handle.expand()``)."""
|
|
272
|
+
return handle.expand()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class SqueezeCompressor:
|
|
276
|
+
"""Object form satisfying ``core.protocols.Compressor`` (delegates to :func:`compress`)."""
|
|
277
|
+
|
|
278
|
+
def compress(
|
|
279
|
+
self,
|
|
280
|
+
content: Any,
|
|
281
|
+
*,
|
|
282
|
+
target_tokens: int | None = None,
|
|
283
|
+
model: str | None = None,
|
|
284
|
+
kind: str = "auto",
|
|
285
|
+
fidelity: str = "balanced",
|
|
286
|
+
) -> tuple[str, Handle]:
|
|
287
|
+
return compress(
|
|
288
|
+
content,
|
|
289
|
+
kind=kind,
|
|
290
|
+
target_tokens=target_tokens,
|
|
291
|
+
model=model or "gpt-4o",
|
|
292
|
+
fidelity=fidelity,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
# --------------------------------------------------------------------------- compressors
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _strip_nulls(obj: Any) -> Any:
|
|
300
|
+
if isinstance(obj, dict):
|
|
301
|
+
return {k: _strip_nulls(v) for k, v in obj.items() if v is not None}
|
|
302
|
+
if isinstance(obj, list):
|
|
303
|
+
return [_strip_nulls(v) for v in obj]
|
|
304
|
+
return obj
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _compress_json(
|
|
308
|
+
text: str, target_tokens: int | None, model: str, fidelity: str = "balanced"
|
|
309
|
+
) -> tuple[str, dict]:
|
|
310
|
+
"""Minify whitespace; drop null-valued keys unless ``fidelity="lossless"``. Original in CCR."""
|
|
311
|
+
try:
|
|
312
|
+
obj = json.loads(text)
|
|
313
|
+
except (ValueError, TypeError):
|
|
314
|
+
return _compress_prose(text, target_tokens, model)
|
|
315
|
+
shaped = obj if fidelity == "lossless" else _strip_nulls(obj)
|
|
316
|
+
small = json.dumps(shaped, ensure_ascii=False, separators=(",", ":"))
|
|
317
|
+
if target_tokens is not None and tokens.count(small, model) > target_tokens:
|
|
318
|
+
small = _truncate_to_tokens(small, target_tokens, model)
|
|
319
|
+
technique = "minify" if fidelity == "lossless" else "minify+dropnulls"
|
|
320
|
+
return small, {"technique": technique}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _compress_code(
|
|
324
|
+
text: str, target_tokens: int | None, model: str, fidelity: str = "balanced"
|
|
325
|
+
) -> tuple[str, dict]:
|
|
326
|
+
"""Strip comments + blank lines (and, when aggressive, internal whitespace); keep structure."""
|
|
327
|
+
code = text
|
|
328
|
+
if fidelity != "lossless":
|
|
329
|
+
code = _strip_comments(code)
|
|
330
|
+
out: list[str] = []
|
|
331
|
+
for raw in code.splitlines():
|
|
332
|
+
line = raw.rstrip()
|
|
333
|
+
if not line.strip():
|
|
334
|
+
continue
|
|
335
|
+
if fidelity == "aggressive":
|
|
336
|
+
stripped = line.lstrip()
|
|
337
|
+
indent = line[: len(line) - len(stripped)]
|
|
338
|
+
line = indent + re.sub(r"[ \t]{2,}", " ", stripped)
|
|
339
|
+
out.append(line)
|
|
340
|
+
small = "\n".join(out)
|
|
341
|
+
if target_tokens is not None and tokens.count(small, model) > target_tokens:
|
|
342
|
+
small = _truncate_to_tokens(small, target_tokens, model)
|
|
343
|
+
return small, {"technique": f"code:{fidelity}"}
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _compress_logs(text: str, target_tokens: int | None, model: str) -> tuple[str, dict]:
|
|
347
|
+
"""Normalize volatile fields (timestamps/UUIDs) then dedup repeated lines into ``(×N)``.
|
|
348
|
+
|
|
349
|
+
Under a ``target_tokens`` budget, the noisiest patterns are kept (most repeats first) but they
|
|
350
|
+
are rendered back in original **chronological** order, so the timeline stays readable.
|
|
351
|
+
"""
|
|
352
|
+
counts: dict[str, int] = {}
|
|
353
|
+
order: list[str] = []
|
|
354
|
+
for line in text.splitlines():
|
|
355
|
+
norm = _UUID.sub("<uuid>", _TS.sub("<ts>", line))
|
|
356
|
+
if norm not in counts:
|
|
357
|
+
order.append(norm)
|
|
358
|
+
counts[norm] = counts.get(norm, 0) + 1
|
|
359
|
+
|
|
360
|
+
rendered = {norm: f"{norm} (×{counts[norm]})" if counts[norm] > 1 else norm for norm in order}
|
|
361
|
+
if target_tokens is None:
|
|
362
|
+
kept = order
|
|
363
|
+
else:
|
|
364
|
+
# Select which patterns survive by frequency (cheap additive estimate), then restore
|
|
365
|
+
# chronological order; the final truncate enforces the hard token cap.
|
|
366
|
+
chosen: set[str] = set()
|
|
367
|
+
running = 0
|
|
368
|
+
for norm in sorted(order, key=lambda ln: counts[ln], reverse=True):
|
|
369
|
+
cost = tokens.count(rendered[norm], model) + 1 # +1 for the line separator
|
|
370
|
+
if running + cost > target_tokens and chosen:
|
|
371
|
+
break
|
|
372
|
+
chosen.add(norm)
|
|
373
|
+
running += cost
|
|
374
|
+
kept = [norm for norm in order if norm in chosen]
|
|
375
|
+
|
|
376
|
+
small = "\n".join(rendered[norm] for norm in kept)
|
|
377
|
+
if target_tokens is not None and tokens.count(small, model) > target_tokens:
|
|
378
|
+
small = _truncate_to_tokens(small, target_tokens, model)
|
|
379
|
+
return small, {"technique": "normalize+dedup", "patterns": len(order)}
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
_SENT = re.compile(r"(?<=[.!?])\s+")
|
|
383
|
+
_STOP = frozenset(
|
|
384
|
+
"the a an and or but of to in on for with is are was were be been it this that as at by".split()
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _compress_prose(
|
|
389
|
+
text: str, target_tokens: int | None, model: str, fidelity: str = "balanced"
|
|
390
|
+
) -> tuple[str, dict]:
|
|
391
|
+
"""Extractive: rank sentences by keyword density, keep the top ones in original order."""
|
|
392
|
+
sentences = [s for s in _SENT.split(text.strip()) if s.strip()]
|
|
393
|
+
if len(sentences) <= 1 or fidelity == "lossless":
|
|
394
|
+
# Nothing to rank, but still honor the budget (e.g. one long sentence, or lossless).
|
|
395
|
+
small = text
|
|
396
|
+
if target_tokens is not None and tokens.count(small, model) > target_tokens:
|
|
397
|
+
small = _truncate_to_tokens(small, target_tokens, model)
|
|
398
|
+
return small, {"technique": "extractive", "kept": len(sentences), "of": len(sentences)}
|
|
399
|
+
|
|
400
|
+
freq: dict[str, int] = {}
|
|
401
|
+
for word in re.findall(r"[a-zA-Z']+", text.lower()):
|
|
402
|
+
if word not in _STOP:
|
|
403
|
+
freq[word] = freq.get(word, 0) + 1
|
|
404
|
+
|
|
405
|
+
def score(sentence: str) -> float:
|
|
406
|
+
words = re.findall(r"[a-zA-Z']+", sentence.lower())
|
|
407
|
+
if not words:
|
|
408
|
+
return 0.0
|
|
409
|
+
return sum(freq.get(w, 0) for w in words) / len(words)
|
|
410
|
+
|
|
411
|
+
ranked = sorted(range(len(sentences)), key=lambda i: score(sentences[i]), reverse=True)
|
|
412
|
+
|
|
413
|
+
if target_tokens is not None:
|
|
414
|
+
keep: set[int] = set()
|
|
415
|
+
for i in ranked:
|
|
416
|
+
trial = " ".join(sentences[j] for j in sorted(keep | {i}))
|
|
417
|
+
if tokens.count(trial, model) > target_tokens and keep:
|
|
418
|
+
break
|
|
419
|
+
keep.add(i)
|
|
420
|
+
else:
|
|
421
|
+
divisor = 3 if fidelity == "aggressive" else 2 # aggressive: top third, balanced: top half
|
|
422
|
+
keep = set(ranked[: max(1, len(sentences) // divisor)])
|
|
423
|
+
|
|
424
|
+
small = " ".join(sentences[i] for i in sorted(keep))
|
|
425
|
+
# The top-ranked sentence is always kept; truncate so target_tokens is never exceeded.
|
|
426
|
+
if target_tokens is not None and tokens.count(small, model) > target_tokens:
|
|
427
|
+
small = _truncate_to_tokens(small, target_tokens, model)
|
|
428
|
+
return small, {"technique": "extractive", "kept": len(keep), "of": len(sentences)}
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _truncate_to_tokens(text: str, target: int, model: str) -> str:
|
|
432
|
+
"""Binary-search the longest prefix of ``text`` that fits ``target`` tokens (deterministic)."""
|
|
433
|
+
if target <= 0:
|
|
434
|
+
return ""
|
|
435
|
+
if tokens.count(text, model) <= target:
|
|
436
|
+
return text
|
|
437
|
+
lo, hi, best = 0, len(text), ""
|
|
438
|
+
while lo <= hi:
|
|
439
|
+
mid = (lo + hi) // 2
|
|
440
|
+
cand = text[:mid]
|
|
441
|
+
if tokens.count(cand, model) <= target:
|
|
442
|
+
best, lo = cand, mid + 1
|
|
443
|
+
else:
|
|
444
|
+
hi = mid - 1
|
|
445
|
+
return best
|
|
File without changes
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Content-addressed store (CCR) backends for squeeze. docs/squeeze.md §5, §7.
|
|
2
|
+
|
|
3
|
+
The original of every compression is kept keyed by its hash so ``handle.expand()`` is exact.
|
|
4
|
+
``MemoryStore`` (the default) keeps originals in-process; ``SQLiteStore`` persists them to a local
|
|
5
|
+
file so they survive the process and dedupe across runs — both stdlib, no network. A backend is
|
|
6
|
+
any object with ``get(key) -> str`` and ``put(key, value) -> None``; swap one in via
|
|
7
|
+
``squeeze.use_store(...)``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import sqlite3
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MemoryStore:
|
|
16
|
+
"""In-process CCR store (the default). Fast, ephemeral, deduped by key.
|
|
17
|
+
|
|
18
|
+
``max_items`` bounds the store: once exceeded, the oldest originals are evicted (FIFO) so it
|
|
19
|
+
doesn't grow unbounded. Expanding a handle whose original was evicted raises ``KeyError`` —
|
|
20
|
+
the documented trade-off of a capped store. ``None`` (default) means unbounded.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, max_items: int | None = None) -> None:
|
|
24
|
+
self._data: dict[str, str] = {}
|
|
25
|
+
self._max = max_items
|
|
26
|
+
|
|
27
|
+
def get(self, key: str) -> str:
|
|
28
|
+
return self._data[key]
|
|
29
|
+
|
|
30
|
+
def put(self, key: str, value: str) -> None:
|
|
31
|
+
if key in self._data:
|
|
32
|
+
return
|
|
33
|
+
self._data[key] = value
|
|
34
|
+
if self._max is not None:
|
|
35
|
+
while len(self._data) > self._max:
|
|
36
|
+
del self._data[next(iter(self._data))] # evict oldest insertion (FIFO)
|
|
37
|
+
|
|
38
|
+
def __contains__(self, key: str) -> bool:
|
|
39
|
+
return key in self._data
|
|
40
|
+
|
|
41
|
+
def __len__(self) -> int:
|
|
42
|
+
return len(self._data)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SQLiteStore:
|
|
46
|
+
"""Local SQLite CCR store: originals persist across processes, deduped by key (stdlib).
|
|
47
|
+
|
|
48
|
+
Opened with ``check_same_thread=False`` so a single store can serve a threaded server; writes
|
|
49
|
+
are idempotent ``INSERT OR IGNORE``s (content-addressed), so concurrent puts of the same content
|
|
50
|
+
are safe.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, path: str) -> None:
|
|
54
|
+
self.conn = sqlite3.connect(path, check_same_thread=False)
|
|
55
|
+
self.conn.execute("CREATE TABLE IF NOT EXISTS ccr (key TEXT PRIMARY KEY, value TEXT)")
|
|
56
|
+
self.conn.commit()
|
|
57
|
+
|
|
58
|
+
def get(self, key: str) -> str:
|
|
59
|
+
row = self.conn.execute("SELECT value FROM ccr WHERE key = ?", (key,)).fetchone()
|
|
60
|
+
if row is None:
|
|
61
|
+
raise KeyError(key)
|
|
62
|
+
return row[0]
|
|
63
|
+
|
|
64
|
+
def put(self, key: str, value: str) -> None:
|
|
65
|
+
self.conn.execute("INSERT OR IGNORE INTO ccr (key, value) VALUES (?, ?)", (key, value))
|
|
66
|
+
self.conn.commit()
|
|
67
|
+
|
|
68
|
+
def __contains__(self, key: str) -> bool:
|
|
69
|
+
return self.conn.execute("SELECT 1 FROM ccr WHERE key = ?", (key,)).fetchone() is not None
|
|
70
|
+
|
|
71
|
+
def __len__(self) -> int:
|
|
72
|
+
return int(self.conn.execute("SELECT count(*) FROM ccr").fetchone()[0])
|
|
73
|
+
|
|
74
|
+
def close(self) -> None:
|
|
75
|
+
self.conn.close()
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Compression is content-aware, deterministic, and 100% reversible. No network."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from cendor.core import protocols, tokens
|
|
7
|
+
from cendor.squeeze import SqueezeCompressor, compress, decompress, detect
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.fixture(autouse=True)
|
|
11
|
+
def _heuristic_tokens(monkeypatch):
|
|
12
|
+
monkeypatch.setattr(tokens, "_tiktoken_encoding", lambda model: None)
|
|
13
|
+
yield
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_detect():
|
|
17
|
+
assert detect('{"a": 1}') == "json"
|
|
18
|
+
assert detect("[1, 2, 3]") == "json"
|
|
19
|
+
logs = "\n".join(f"2026-06-01T00:00:0{i} INFO started worker" for i in range(5))
|
|
20
|
+
assert detect(logs) == "logs"
|
|
21
|
+
assert detect("The cat sat on the mat. It was a sunny day.") == "prose"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_json_compression_is_smaller_and_reversible():
|
|
25
|
+
obj = {"name": "alice", "age": 30, "note": None, "tags": ["x", "y"], "extra": None}
|
|
26
|
+
pretty = json.dumps(obj, indent=4)
|
|
27
|
+
small, handle = compress(pretty, kind="auto")
|
|
28
|
+
assert detect(pretty) == "json"
|
|
29
|
+
assert len(small) < len(pretty) # whitespace + nulls gone
|
|
30
|
+
assert "note" not in small and "null" not in small # nulls dropped
|
|
31
|
+
assert handle.expand() == pretty # exact original restored
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_logs_dedup_collapses_repeats():
|
|
35
|
+
logs = "\n".join(["2026-06-01T00:00:00Z INFO retry attempt"] * 20)
|
|
36
|
+
small, handle = compress(logs, kind="logs")
|
|
37
|
+
assert "(×20)" in small
|
|
38
|
+
assert tokens.count(small, "gpt-4o") < tokens.count(logs, "gpt-4o")
|
|
39
|
+
assert handle.expand() == logs
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_prose_extractive_hits_target_tokens():
|
|
43
|
+
text = (
|
|
44
|
+
"Refunds are processed within five business days. "
|
|
45
|
+
"The weather today is mild and pleasant. "
|
|
46
|
+
"Customers must contact support to request a refund. "
|
|
47
|
+
"Our office cat is named Mittens. "
|
|
48
|
+
"Refund eligibility depends on the purchase date."
|
|
49
|
+
)
|
|
50
|
+
target = 20
|
|
51
|
+
small, handle = compress(text, kind="prose", target_tokens=target)
|
|
52
|
+
assert tokens.count(small, "gpt-4o") <= target
|
|
53
|
+
assert len(small) < len(text)
|
|
54
|
+
assert handle.expand() == text # original always restorable
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_object_input_serialized_and_restored():
|
|
58
|
+
small, handle = compress({"k": "v", "n": None}, kind="auto")
|
|
59
|
+
assert "null" not in small
|
|
60
|
+
restored = json.loads(handle.expand())
|
|
61
|
+
assert restored == {"k": "v", "n": None}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_decompress_matches_expand():
|
|
65
|
+
small, handle = compress("hello world. goodbye world.", kind="prose")
|
|
66
|
+
assert decompress(handle) == handle.expand()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_ccr_store_dedupes_identical_originals():
|
|
70
|
+
import cendor.squeeze as sq
|
|
71
|
+
|
|
72
|
+
before = len(sq._backend)
|
|
73
|
+
_, h1 = compress("identical content here", kind="prose")
|
|
74
|
+
_, h2 = compress("identical content here", kind="prose")
|
|
75
|
+
assert h1.original_ref == h2.original_ref # same hash key
|
|
76
|
+
assert len(sq._backend) == before + 1 # stored once
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_memory_store_eviction_cap():
|
|
80
|
+
import cendor.squeeze as sq
|
|
81
|
+
from cendor.squeeze.store import MemoryStore
|
|
82
|
+
|
|
83
|
+
previous = sq.use_store(MemoryStore(max_items=2))
|
|
84
|
+
try:
|
|
85
|
+
_, h1 = compress("first original content here", kind="prose")
|
|
86
|
+
_, h2 = compress("second original content here", kind="prose")
|
|
87
|
+
_, h3 = compress("third original content here", kind="prose") # evicts the first
|
|
88
|
+
assert len(sq._backend) == 2
|
|
89
|
+
assert h2.expand() and h3.expand() # newest two survive
|
|
90
|
+
with pytest.raises(KeyError):
|
|
91
|
+
h1.expand() # oldest was evicted (documented trade-off of a capped store)
|
|
92
|
+
finally:
|
|
93
|
+
sq.use_store(previous)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_sqlite_store_backend_persists_and_expands(tmp_path):
|
|
97
|
+
import cendor.squeeze as sq
|
|
98
|
+
from cendor.squeeze.store import SQLiteStore
|
|
99
|
+
|
|
100
|
+
store = SQLiteStore(str(tmp_path / "ccr.db"))
|
|
101
|
+
previous = sq.use_store(store)
|
|
102
|
+
try:
|
|
103
|
+
original = '{"name": "alice", "age": 30, "note": null}'
|
|
104
|
+
small, handle = compress(original, kind="json")
|
|
105
|
+
assert len(small) < len(original)
|
|
106
|
+
assert handle.original_ref in store # original persisted to SQLite
|
|
107
|
+
assert handle.expand() == original # restored from the SQLite backend
|
|
108
|
+
finally:
|
|
109
|
+
sq.use_store(previous)
|
|
110
|
+
store.close()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_satisfies_core_compressor_protocol():
|
|
114
|
+
assert isinstance(SqueezeCompressor(), protocols.Compressor)
|
|
115
|
+
small, handle = SqueezeCompressor().compress("a. b. c. d.", target_tokens=5, model="gpt-4o")
|
|
116
|
+
assert isinstance(handle.expand(), str)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_detect_code():
|
|
120
|
+
src = "def add(a, b):\n # sum them\n return a + b\n"
|
|
121
|
+
assert detect(src) == "code"
|
|
122
|
+
js = "function f(x) {\n return x * 2;\n}\n"
|
|
123
|
+
assert detect(js) == "code"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_code_compression_strips_comments_and_is_reversible():
|
|
127
|
+
src = "def add(a, b):\n # add two numbers\n return a + b\n\n// trailing\n"
|
|
128
|
+
small, handle = compress(src, kind="code")
|
|
129
|
+
assert "# add two numbers" not in small
|
|
130
|
+
assert "// trailing" not in small
|
|
131
|
+
assert "" not in small.split("\n") # blank lines gone
|
|
132
|
+
assert "return a + b" in small # structure kept
|
|
133
|
+
assert handle.expand() == src # exact original restorable
|
|
134
|
+
assert tokens.count(small, "gpt-4o") < tokens.count(src, "gpt-4o")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def test_code_lossless_keeps_comments():
|
|
138
|
+
src = "def f():\n # keep me\n return 1\n"
|
|
139
|
+
small, _ = compress(src, kind="code", fidelity="lossless")
|
|
140
|
+
assert "# keep me" in small # comments preserved at lossless fidelity
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_fidelity_dial_on_prose():
|
|
144
|
+
text = ". ".join(f"Sentence {i} about refunds and billing matters" for i in range(12)) + "."
|
|
145
|
+
lossless, _ = compress(text, kind="prose", fidelity="lossless")
|
|
146
|
+
balanced, _ = compress(text, kind="prose", fidelity="balanced")
|
|
147
|
+
aggressive, _ = compress(text, kind="prose", fidelity="aggressive")
|
|
148
|
+
assert lossless == text # lossless prose is a no-op (whitespace aside)
|
|
149
|
+
t = lambda s: tokens.count(s, "gpt-4o") # noqa: E731
|
|
150
|
+
assert t(aggressive) <= t(balanced) <= t(lossless)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_invalid_fidelity_rejected():
|
|
154
|
+
with pytest.raises(ValueError):
|
|
155
|
+
compress("x", fidelity="ultra")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def test_json_lossless_keeps_nulls():
|
|
159
|
+
small, _ = compress('{"a": 1, "b": null}', kind="json", fidelity="lossless")
|
|
160
|
+
assert "null" in small # nulls retained at lossless fidelity
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_prose_never_exceeds_target_even_with_one_dominant_sentence():
|
|
164
|
+
# The top-ranked sentence is always kept; it must still be truncated to honor target_tokens.
|
|
165
|
+
text = (
|
|
166
|
+
"refund refund refund refund refund refund refund refund refund refund policy here. "
|
|
167
|
+
"The cat sat. A dog ran. Birds fly."
|
|
168
|
+
)
|
|
169
|
+
small, handle = compress(text, kind="prose", target_tokens=5)
|
|
170
|
+
assert tokens.count(small, "gpt-4o") <= 5
|
|
171
|
+
assert handle.expand() == text # still fully reversible
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def test_code_comment_stripping_preserves_string_literals():
|
|
175
|
+
src = 'url = "https://example.com/path" // trailing\nkey = "color #ff0000"\nreturn url\n'
|
|
176
|
+
small, handle = compress(src, kind="code")
|
|
177
|
+
assert "https://example.com/path" in small # // inside a string is not a comment
|
|
178
|
+
assert "#ff0000" in small # # inside a string is not a comment
|
|
179
|
+
assert "// trailing" not in small # the real comment is gone
|
|
180
|
+
assert handle.expand() == src
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def test_code_keeps_preprocessor_and_shebang():
|
|
184
|
+
src = "#!/usr/bin/env python\n#include <stdio.h>\nx = 1 # a real comment\nreturn x\n"
|
|
185
|
+
small, _ = compress(src, kind="code")
|
|
186
|
+
assert "#!/usr/bin/env python" in small # shebang kept
|
|
187
|
+
assert "#include <stdio.h>" in small # preprocessor directive kept
|
|
188
|
+
assert "# a real comment" not in small # ordinary # comment stripped
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def test_logs_preserve_chronological_order_under_target():
|
|
192
|
+
logs = "\n".join(
|
|
193
|
+
[
|
|
194
|
+
"2026-06-01T00:00:01Z INFO alpha first",
|
|
195
|
+
"2026-06-01T00:00:02Z INFO beta second",
|
|
196
|
+
"2026-06-01T00:00:03Z ERROR gamma",
|
|
197
|
+
"2026-06-01T00:00:04Z ERROR gamma",
|
|
198
|
+
"2026-06-01T00:00:05Z ERROR gamma",
|
|
199
|
+
]
|
|
200
|
+
)
|
|
201
|
+
small, _ = compress(logs, kind="logs", target_tokens=1000)
|
|
202
|
+
assert small.splitlines()[0].endswith("INFO alpha first") # chronological, not freq-sorted
|
|
203
|
+
assert tokens.count(small, "gpt-4o") <= 1000
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def test_handle_to_dict_round_trips_with_persistent_store():
|
|
207
|
+
import cendor.squeeze as sq
|
|
208
|
+
from cendor.squeeze import Handle
|
|
209
|
+
from cendor.squeeze.store import SQLiteStore
|
|
210
|
+
|
|
211
|
+
store = SQLiteStore(":memory:")
|
|
212
|
+
previous = sq.use_store(store)
|
|
213
|
+
try:
|
|
214
|
+
original = '{"a": 1, "b": null}'
|
|
215
|
+
_small, handle = compress(original, kind="json")
|
|
216
|
+
rebuilt = Handle.from_dict(handle.to_dict()) # e.g. loaded from disk next process
|
|
217
|
+
assert rebuilt.expand() == original
|
|
218
|
+
assert rebuilt.technique == handle.technique
|
|
219
|
+
assert len(store) == 1
|
|
220
|
+
finally:
|
|
221
|
+
sq.use_store(previous)
|
|
222
|
+
store.close()
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def test_contextkit_compress_routes_through_squeeze():
|
|
226
|
+
# End-to-end: contextkit discovers squeeze by shape via the [squeeze] extra (both installed).
|
|
227
|
+
from cendor.contextkit import Block, Context
|
|
228
|
+
|
|
229
|
+
ctx = Context(budget_tokens=30, model="gpt-4o")
|
|
230
|
+
ctx.add(Block("keep me", priority=10, role="system"))
|
|
231
|
+
big = " ".join(f"Sentence number {i} about refunds and billing." for i in range(20))
|
|
232
|
+
ctx.add(Block(big, priority=1, role="user", evict="compress"))
|
|
233
|
+
ctx.assemble()
|
|
234
|
+
decision = next(d for d in ctx.report().decisions if d.role == "user")
|
|
235
|
+
assert decision.action == "compressed"
|
|
236
|
+
assert decision.tokens_after < decision.tokens_before
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Property test (Layer E): compression is always exactly reversible, for any input. No network."""
|
|
2
|
+
|
|
3
|
+
from cendor.core import tokens
|
|
4
|
+
from cendor.squeeze import compress
|
|
5
|
+
from hypothesis import given
|
|
6
|
+
from hypothesis import strategies as st
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@given(s=st.text(max_size=2000))
|
|
10
|
+
def test_compress_then_expand_round_trips(s):
|
|
11
|
+
# Whatever the content (and however hard it's squeezed), the original restores byte-for-byte.
|
|
12
|
+
_small, handle = compress(s, kind="auto")
|
|
13
|
+
assert handle.expand() == s
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@given(
|
|
17
|
+
s=st.text(min_size=1, max_size=2000),
|
|
18
|
+
kind=st.sampled_from(["json", "logs", "code", "prose"]),
|
|
19
|
+
target=st.integers(1, 200),
|
|
20
|
+
)
|
|
21
|
+
def test_target_tokens_is_never_exceeded(s, kind, target):
|
|
22
|
+
# "compress to a budget, never exceeds it" — for every content kind, including prose.
|
|
23
|
+
small, _handle = compress(s, kind=kind, target_tokens=target)
|
|
24
|
+
assert tokens.count(small, "gpt-4o") <= target
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@given(
|
|
28
|
+
s=st.text(min_size=1, max_size=2000), kind=st.sampled_from(["json", "logs", "code", "prose"])
|
|
29
|
+
)
|
|
30
|
+
def test_reversible_for_every_kind(s, kind):
|
|
31
|
+
_small, handle = compress(s, kind=kind)
|
|
32
|
+
assert handle.expand() == s
|