logreducer 3.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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 Derivative
95
+ 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 HYPERI PTY LIMITED
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,53 @@
1
+ logreducer
2
+ Copyright 2026 HYPERI PTY LIMITED
3
+
4
+ This product includes software developed at HYPERI PTY LIMITED
5
+ (https://hyperi.io/).
6
+
7
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
8
+
9
+ -------------------------------------------------------------------------------
10
+ Third-party data
11
+ -------------------------------------------------------------------------------
12
+
13
+ The sample log files under data/samples/ are drawn from LogHub, a collection of
14
+ system log datasets for research:
15
+
16
+ Jieming Zhu, Shilin He, Pinjia He, Jinyang Liu, Michael R. Lyu.
17
+ "Loghub: A Large Collection of System Log Datasets for AI-driven Log
18
+ Analytics." ISSRE 2023.
19
+ https://github.com/logpai/loghub
20
+
21
+ Some LogHub datasets originate from public sources, including the USENIX CFDR
22
+ computer failure data repository (BGL and Thunderbird traces, Sandia National
23
+ Laboratories). The datasets are redistributed here unmodified for demonstration
24
+ and testing. See data/samples/README.md for the per-file mapping.
25
+
26
+ -------------------------------------------------------------------------------
27
+ Integration-test corpora (tests/testdata/)
28
+ -------------------------------------------------------------------------------
29
+
30
+ The gzipped log corpora under tests/testdata/ are truncated slices of REAL
31
+ public datasets, PII-cleansed (IPs/IPv6/emails/MAC addresses and specific
32
+ hostnames deterministically rewritten to synthetic values; structure and
33
+ repetition preserved). Each is redistributed under its own licence. See
34
+ tests/testdata/manifest.json for the per-dataset source URL, licence, and
35
+ cleansing status. Sources and licences:
36
+
37
+ LogHub (loghub_*): Zhu et al., "Loghub", ISSRE 2023.
38
+ https://github.com/logpai/loghub - Zenodo 10.5281/zenodo.8196385,
39
+ CC-BY-4.0. BGL/Thunderbird upstream: Oliner and Stearley, DSN 2007.
40
+
41
+ The Internet Traffic Archive (ita_*): NASA-HTTP and Calgary-HTTP web-server
42
+ access logs. https://ita.ee.lbl.gov/ - per-trace "may be freely
43
+ redistributed". Use is limited to general traffic-pattern analysis.
44
+
45
+ Security Repo (secrepo_*): Security Repo by Mike Sconzo, https://www.secrepo.com/
46
+ - Creative Commons Attribution 4.0 International (CC-BY-4.0).
47
+
48
+ elastic/examples (elastic_*): nginx JSON logs from https://github.com/elastic/examples
49
+ - Apache License, Version 2.0.
50
+
51
+ These corpora are used only for testing and are not part of the distributed
52
+ package. The build script tests/testdata/build.py records how each was fetched
53
+ and cleansed.
@@ -0,0 +1,387 @@
1
+ Metadata-Version: 2.4
2
+ Name: logreducer
3
+ Version: 3.4.0
4
+ Summary: Reduce GB-scale logs to a representative sample - streaming Python library and CLI with pattern mining and anomaly detection
5
+ Keywords: log,logging,reduction,analysis,pattern-extraction,memory-efficient,streaming,anomaly-detection
6
+ Author: HyperI Team
7
+ Author-email: HyperI Team <dev@hyperi.io>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Topic :: System :: Logging
15
+ Classifier: Topic :: System :: Systems Administration
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Operating System :: OS Independent
20
+ Requires-Dist: drain3>=0.9.0
21
+ Requires-Dist: psutil>=7.2.0
22
+ Requires-Dist: loguru>=0.7.3
23
+ Requires-Dist: numpy>=2.0.0
24
+ Requires-Dist: scikit-learn>=1.5.0
25
+ Requires-Dist: typer>=0.25.0
26
+ Requires-Dist: clickhouse-connect>=1.0 ; extra == 'clickhouse'
27
+ Requires-Dist: xxhash>=3.0.0 ; extra == 'enhanced'
28
+ Requires-Dist: datasketch>=1.5.0 ; extra == 'enhanced'
29
+ Requires-Dist: confluent-kafka>=2.14.0 ; extra == 'kafka'
30
+ Requires-Dist: sqlalchemy>=2.0.30 ; extra == 'sql'
31
+ Maintainer: HyperI Team
32
+ Maintainer-email: HyperI Team <dev@hyperi.io>
33
+ Requires-Python: >=3.12
34
+ Project-URL: Homepage, https://github.com/hyperi-io/logreducer
35
+ Project-URL: Documentation, https://github.com/hyperi-io/logreducer#readme
36
+ Project-URL: Repository, https://github.com/hyperi-io/logreducer
37
+ Project-URL: Bug Reports, https://github.com/hyperi-io/logreducer/issues
38
+ Project-URL: Changelog, https://github.com/hyperi-io/logreducer/blob/main/CHANGELOG.md
39
+ Provides-Extra: clickhouse
40
+ Provides-Extra: enhanced
41
+ Provides-Extra: kafka
42
+ Provides-Extra: sql
43
+ Description-Content-Type: text/markdown
44
+
45
+ # LogReducer
46
+
47
+ [![PyPI](https://img.shields.io/pypi/v/logreducer?logo=pypi)](https://pypi.org/project/logreducer/)
48
+ [![Python Version](https://img.shields.io/badge/python-3.12%2B-blue)](https://www.python.org/)
49
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green)](LICENSE)
50
+
51
+ Reduce gigabytes of logs to a small, representative sample - keeping the patterns and anomalies that matter and dropping the repetition that does not. Memory-safe streaming, temporal awareness, and ML-based anomaly detection.
52
+
53
+ **LogReducer is two tools in one package:**
54
+
55
+ - **A CLI you can use right now.** `logreducer app.log` reduces a file - or a SQL, ClickHouse, or Kafka source - straight from the shell. No code to write.
56
+ - **A library with an IO-agnostic core.** The engine has zero IO dependencies and reduces any re-iterable stream of `str` lines (a `Source`). Embed it in your own pipeline; the engine never manages the connection.
57
+
58
+ ## Features
59
+
60
+ - **Memory-safe streaming**: near-constant memory on multi-GB inputs; low, container-friendly defaults
61
+ - **Four reduction modes**: pattern (Drain3), anomaly (Isolation Forest), temporal, and hybrid
62
+ - **IO-agnostic core**: reduce a file, a `list[str]`, a database cursor, or a Kafka stream through one `Source` seam
63
+ - **Optional adapters**: SQL (SQLAlchemy), ClickHouse (clickhouse-connect), Kafka (confluent-kafka) - install only what you use
64
+ - **Engine-side sampling**: seeded, dialect-aware SQL sampling and native `TABLESAMPLE` for cheap reduction of huge tables
65
+ - **Embeddable**: injection seams for a host application's own config cascade and logging standard
66
+
67
+ ## Installation
68
+
69
+ ### As a CLI tool
70
+
71
+ Install it as an isolated tool so its dependencies never clash with your other Python projects (needs Python 3.12+):
72
+
73
+ ```bash
74
+ uv tool install logreducer # recommended (uv)
75
+ # or
76
+ pipx install logreducer # recommended (pipx)
77
+ ```
78
+
79
+ To bundle an adapter extra with the tool: `uv tool install "logreducer[clickhouse]"`.
80
+
81
+ ### As a library
82
+
83
+ ```bash
84
+ uv add logreducer
85
+ # or
86
+ pip install logreducer
87
+ ```
88
+
89
+ Optional extras (install only what you need):
90
+
91
+ ```bash
92
+ uv add "logreducer[enhanced]" # fuzzy dedup, faster hashing
93
+ uv add "logreducer[sql]" # SQLSource (SQLAlchemy) - bring your own DBAPI driver
94
+ uv add "logreducer[clickhouse]" # ClickHouseSource (clickhouse-connect)
95
+ uv add "logreducer[kafka]" # KafkaSource / KafkaSink (confluent-kafka)
96
+ ```
97
+
98
+ > The `logreducer` command works under any install method (project venv, `pip install --user`, pipx/uv tool, system-wide). `pipx` / `uv tool` is the recommendation for end users - isolation without a manual venv.
99
+
100
+ ## Quick Start
101
+
102
+ ### Command line
103
+
104
+ ```bash
105
+ # Reduce a file to stdout, or to a file with -o
106
+ logreducer app.log
107
+ logreducer app.log -o reduced.log -l enhanced -m hybrid
108
+
109
+ # JSON output, with run stats on stderr
110
+ logreducer app.log --format json -o result.json --stats
111
+
112
+ # Cap memory, estimate first
113
+ logreducer huge.log --max-memory 2 --estimate
114
+ ```
115
+
116
+ ### Library
117
+
118
+ ```python
119
+ from logreducer import LogReducer
120
+
121
+ reducer = LogReducer(level="standard")
122
+
123
+ # Reduce a file (writes reduced.log + reduced.meta.json)
124
+ reduced = reducer.process_file("app.log", output_file="reduced.log")
125
+ print(f"{len(reduced)} representative lines")
126
+
127
+ # Reduce any re-iterable of lines - no file needed
128
+ lines = ["ERROR timeout upstream=payments", "INFO ok", "ERROR timeout upstream=payments"]
129
+ reduced = reducer.reduce(lines)
130
+ ```
131
+
132
+ `reduce()` returns the reduced lines in memory. Pass `return_metadata=True` for a dict of `{"lines", "stats", "config"}`.
133
+
134
+ ## How it works
135
+
136
+ Everything streams: lines flow through dedup and template mining as one generator pipeline, so the unique-line set is never materialised. Memory stays near-constant regardless of input size.
137
+
138
+ ```mermaid
139
+ flowchart LR
140
+ subgraph sources ["Source (re-iterable str lines)"]
141
+ direction TB
142
+ F[file]
143
+ L["list[str]"]
144
+ Q[SQL / ClickHouse query]
145
+ K[Kafka topic]
146
+ end
147
+ sources --> D["exact dedup<br/>(bounded hash cache)"]
148
+ D --> FZ["fuzzy dedup<br/>(MinHash LSH, enhanced+)"]
149
+ FZ --> DR["Drain3 template mining<br/>(LRU-bounded clusters)"]
150
+ DR --> P["rank patterns<br/>(CRITICAL > ERROR > WARN)"]
151
+ P --> O["top patterns<br/>x examples"]
152
+ D -. "anomaly / hybrid" .-> A["TF-IDF + Isolation Forest<br/>(batch, capped by anomaly_max_rows)"]
153
+ A --> O
154
+ O --> out["stdout / file + meta.json / Sink"]
155
+ ```
156
+
157
+ The anomaly branch is the one part that cannot stream (Isolation Forest is batch ML); cap its input with `anomaly_max_rows` when reducing very high-cardinality sources.
158
+
159
+ ## Choosing a mode and level
160
+
161
+ ```mermaid
162
+ flowchart TD
163
+ Q{"What matters<br/>in the output?"} -->|"recurring structure,<br/>smallest output"| P["mode=pattern<br/>(default, fastest)"]
164
+ Q -->|"rare or unusual<br/>events"| A["mode=anomaly"]
165
+ Q -->|"bursts and<br/>time windows"| T["mode=temporal"]
166
+ Q -->|"unsure /<br/>maximum coverage"| H["mode=hybrid"]
167
+ A -.-> N1["needs >= 10 unique lines,<br/>else everything passes through"]
168
+ P -.-> N2["fuzzy dedup joins in<br/>at enhanced/maximum"]
169
+ ```
170
+
171
+ | Mode | Description | Best for |
172
+ |------|-------------|----------|
173
+ | `pattern` | Drain3 template mining | Structured / application logs (fastest) |
174
+ | `anomaly` | Isolation Forest outlier detection | Security and error logs |
175
+ | `temporal` | Time-aware pattern analysis | Time-series and monitoring logs |
176
+ | `hybrid` | Pattern + anomaly combined | Maximum coverage |
177
+
178
+ | Level | Speed | Memory cap | Features |
179
+ |-------|-------|-----------|----------|
180
+ | `standard` | Fast | 0.5 GB | Deduplication + pattern extraction |
181
+ | `enhanced` | Moderate | 1 GB | + fuzzy dedup |
182
+ | `maximum` | Thorough | 2 GB | + wider pattern budget |
183
+
184
+ ## Reducing from a database or Kafka
185
+
186
+ The CLI dispatches on the `--dsn` scheme; a library caller constructs the source directly.
187
+
188
+ ```bash
189
+ # PostgreSQL / MySQL / SQLite via SQLAlchemy (needs logreducer[sql] + a driver)
190
+ logreducer --dsn postgresql://user@host/db --query "SELECT message FROM logs"
191
+
192
+ # ClickHouse via the native driver (needs logreducer[clickhouse])
193
+ logreducer --dsn clickhouse://user@host:8123/db --query "SELECT message FROM logs"
194
+
195
+ # Kafka topic (needs logreducer[kafka])
196
+ logreducer --dsn kafka://broker:9092 --topic app-logs --group logreducer
197
+ ```
198
+
199
+ ```python
200
+ from logreducer import LogReducer
201
+ from logreducer.clickhouse import ClickHouseSource
202
+
203
+ reducer = LogReducer(level="enhanced", mode="hybrid")
204
+ with ClickHouseSource("clickhouse://user@host:8123/db", "SELECT message FROM logs") as source:
205
+ reduced = reducer.reduce(source)
206
+ ```
207
+
208
+ The query selects the log line as its **first column**. Sources are re-iterable (the engine makes multiple passes), so a database source re-runs its query per pass and a Kafka source re-reads from the earliest offset without committing.
209
+
210
+ ## Sampling large sources
211
+
212
+ For a table too large to scan in full, sample a fraction of rows. SQL sampling is deterministic when you pass a seed (so the reducer's multi-pass modes see a stable input); ClickHouse uses its native `SAMPLE` clause.
213
+
214
+ ```python
215
+ from logreducer.sql import SQLSource
216
+
217
+ # Wrap any query in a seeded random predicate (PostgreSQL/MySQL)
218
+ source = SQLSource("postgresql://user@host/db", "SELECT msg FROM logs", sample=0.01, sample_seed=42)
219
+
220
+ # Or sample a TABLE with the engine's native sampler - PostgreSQL
221
+ # TABLESAMPLE SYSTEM is page-level and genuinely sub-linear:
222
+ source = SQLSource.from_table("postgresql://user@host/db", "logs", "msg", sample=0.01, sample_seed=42)
223
+ ```
224
+
225
+ ```bash
226
+ logreducer --dsn postgresql://user@host/db --query "SELECT msg FROM logs" --sample 0.01 --sample-seed 42
227
+ ```
228
+
229
+ Notes: SQLite has no seedable RNG, so a seeded sample raises `SamplingNotSupported` (unseeded, best-effort sampling still works). ClickHouse `SAMPLE` needs the table to declare a `SAMPLE BY` key. For an arbitrary complex query, put the sampling clause in your own SQL instead.
230
+
231
+ ## Collecting a target number of lines
232
+
233
+ When you want *about N* representative lines rather than "reduce everything", `reduce_to_target` pulls fresh random batches and reduces each, accumulating distinct representatives until a stop condition fires. Peak memory is bounded to roughly one batch plus the accumulator.
234
+
235
+ ```mermaid
236
+ flowchart TD
237
+ PULL["pull fresh random batch<br/>(sample_batch in-engine,<br/>else client-side reservoir)"] --> E{empty?}
238
+ E -->|yes| SE([stop: exhausted])
239
+ E -->|no| SIZE["resize next batch from<br/>observed avg row bytes"]
240
+ SIZE --> RED["reduce the batch"]
241
+ RED --> ACC["add new distinct<br/>representatives"]
242
+ ACC --> TGT{"target<br/>reached?"}
243
+ TGT -->|yes| ST([stop: target])
244
+ TGT -->|no| PLAT{"no new lines for<br/>plateau_rounds?"}
245
+ PLAT -->|yes| SP([stop: plateau])
246
+ PLAT -->|no| MEM{"memory<br/>watchdog"}
247
+ MEM -->|"soft: shrink batch"| FET
248
+ MEM -->|"hard limit"| SM([stop: memory])
249
+ FET{"max_fetches<br/>hit?"} -->|yes| SF([stop: max_fetches])
250
+ FET -->|no| PULL
251
+ ```
252
+
253
+ ```python
254
+ from logreducer import LogReducer, reduce_to_target
255
+ from logreducer.sql import SQLSource
256
+
257
+ reducer = LogReducer(level="enhanced", mode="hybrid")
258
+ source = SQLSource("postgresql://user@host/db", "SELECT msg FROM logs")
259
+ outcome = reduce_to_target(source, reducer, target_rows=5000, max_batch_memory_gb=1.0)
260
+ print(outcome["stats"]["stop_reason"]) # target / exhausted / max_fetches / plateau / memory
261
+ lines = outcome["lines"]
262
+ ```
263
+
264
+ ```bash
265
+ logreducer --dsn postgresql://user@host/db --query "SELECT msg FROM logs" \
266
+ --target-rows 5000 --max-fetches 50 --max-batch-memory 1.0
267
+ ```
268
+
269
+ ## Bounding memory
270
+
271
+ The core streams, so pattern/temporal modes run in near-constant memory. The knobs:
272
+
273
+ - `max_memory_gb` - the overall cap (also sizes file read strategy and the watchdog). Presets: 0.5 / 1 / 2 GB by level; values above 70% of available RAM are clamped with a warning.
274
+ - `max_clusters` - LRU-bound the Drain3 template store (unbounded by default).
275
+ - `anomaly_max_rows` - reservoir-cap the rows fed to anomaly detection (off by default; trades anomaly recall for a bounded matrix).
276
+
277
+ ```python
278
+ reducer = LogReducer(level="enhanced", mode="hybrid", max_clusters=50_000, anomaly_max_rows=200_000)
279
+ ```
280
+
281
+ ## Sources and sinks
282
+
283
+ The engine is built around two tiny structural protocols - that is the whole integration surface:
284
+
285
+ ```mermaid
286
+ flowchart LR
287
+ subgraph inputs ["Sources"]
288
+ direction TB
289
+ FS["FileSource"]
290
+ SS["SQLSource [sql]"]
291
+ CS["ClickHouseSource [clickhouse]"]
292
+ KS["KafkaSource [kafka]"]
293
+ MY["your own re-iterable"]
294
+ end
295
+ subgraph core ["LogReducer core"]
296
+ C["zero IO dependencies<br/>Source in -> list[str] out"]
297
+ end
298
+ subgraph outputs ["Sinks"]
299
+ direction TB
300
+ FK["FileSink"]
301
+ KK["KafkaSink [kafka]"]
302
+ MS["your own write()"]
303
+ end
304
+ inputs -->|"__iter__() -> str<br/>fresh iterator per pass"| core
305
+ core -->|"write(lines) -> int"| outputs
306
+ ```
307
+
308
+ An application can hand the reducer its own IO - anything that yields `str` and can be iterated more than once is a `Source`:
309
+
310
+ ```python
311
+ class MySource:
312
+ def __iter__(self):
313
+ yield from open_my_stream() # must return a FRESH iterator each call
314
+
315
+ reducer.reduce(MySource())
316
+ ```
317
+
318
+ Output works the same way through a `Sink` (`write(lines) -> int`):
319
+
320
+ ```python
321
+ from logreducer import LogReducer, FileSink
322
+
323
+ reducer.reduce(source, sink=FileSink("reduced.jsonl", output_format="jsonl"))
324
+ ```
325
+
326
+ ## Embedding in a host application
327
+
328
+ A host app that owns its own config cascade and logging standard drives logreducer with three seams - no logreducer-side knowledge of the host required:
329
+
330
+ ```python
331
+ import logreducer
332
+
333
+ # 1. Config: build it from YOUR cascade and inject it (kwargs still win on top)...
334
+ cfg = logreducer.BigDialConfig(max_memory_gb=0.5, max_patterns=800)
335
+ reducer = logreducer.LogReducer(mode="hybrid", config=cfg)
336
+
337
+ # ...or let logreducer read your env cascade directly: prefixed beats bare.
338
+ cfg = logreducer.BigDialConfig.from_env("MYAPP", "LOGREDUCER") # MYAPP_MAX_MEMORY_GB wins
339
+
340
+ # 2. Logging: your app owns the loguru sinks; logreducer registers nothing and
341
+ # its records flow through YOUR handlers, formatted by YOUR standard.
342
+ logreducer.setup_logging(enable=True, own_sinks=False)
343
+ ```
344
+
345
+ ## Configuration
346
+
347
+ Override any config field as a keyword argument (unknown names raise - typos never silently no-op):
348
+
349
+ ```python
350
+ reducer = LogReducer(
351
+ level="enhanced",
352
+ mode="hybrid",
353
+ max_memory_gb=1.0, # memory ceiling (clamped to 70% of available RAM)
354
+ dedup_cache_size=100000, # bounded dedup cache
355
+ drain_similarity=0.4, # pattern similarity threshold
356
+ fuzzy_threshold=0.8, # fuzzy-dedup threshold (enhanced/maximum)
357
+ anomaly_contamination=0.1, # expected anomaly fraction
358
+ temporal_window_minutes=60, # grouping window for temporal mode
359
+ max_patterns=2000, # cap on extracted patterns
360
+ )
361
+ ```
362
+
363
+ ## Logging
364
+
365
+ Logging is off by default. Enable it and pick a format via env vars:
366
+
367
+ ```bash
368
+ LOG_LEVEL=DEBUG LOG_FORMAT=json logreducer app.log --log
369
+ ```
370
+
371
+ `LOG_FORMAT=json` emits one JSON object per line for log aggregators; the default is human-readable (coloured in a terminal, plain in CI/containers). Embedding? See `own_sinks=False` above.
372
+
373
+ ## Development
374
+
375
+ ```bash
376
+ git clone https://github.com/hyperi-io/logreducer.git
377
+ cd logreducer
378
+ uv sync --all-extras
379
+ ```
380
+
381
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the toolchain, test layout (including the real-log corpora under `tests/testdata/`) and how the integration tests find their services.
382
+
383
+ ## License
384
+
385
+ [Apache-2.0](LICENSE). Third-party attributions are recorded in [NOTICE](NOTICE).
386
+
387
+ Copyright 2026 HYPERI PTY LIMITED.