logreducer 3.5.4__tar.gz → 3.5.6__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.
Files changed (27) hide show
  1. logreducer-3.5.6/PKG-INFO +100 -0
  2. logreducer-3.5.6/docs/pypi.md +58 -0
  3. {logreducer-3.5.4 → logreducer-3.5.6}/pyproject.toml +17 -14
  4. {logreducer-3.5.4 → logreducer-3.5.6}/pyproject.toml.orig +17 -14
  5. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/anomaly.py +4 -1
  6. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/cli.py +2 -2
  7. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/config.py +2 -1
  8. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/core.py +74 -53
  9. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/kafka.py +118 -56
  10. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/memory.py +23 -9
  11. logreducer-3.5.6/src/logreducer/patterns.py +428 -0
  12. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/sampling.py +59 -28
  13. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/sources.py +9 -1
  14. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/sql.py +31 -6
  15. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/target.py +5 -4
  16. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/template_mining.py +29 -10
  17. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/temporal.py +29 -14
  18. logreducer-3.5.4/PKG-INFO +0 -466
  19. logreducer-3.5.4/README.md +0 -424
  20. logreducer-3.5.4/src/logreducer/patterns.py +0 -241
  21. {logreducer-3.5.4 → logreducer-3.5.6}/LICENSE +0 -0
  22. {logreducer-3.5.4 → logreducer-3.5.6}/NOTICE +0 -0
  23. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/__init__.py +0 -0
  24. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/clickhouse.py +0 -0
  25. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/logging_config.py +0 -0
  26. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/py.typed +0 -0
  27. {logreducer-3.5.4 → logreducer-3.5.6}/src/logreducer/sinks.py +0 -0
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: logreducer
3
+ Version: 3.5.6
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: psutil>=7.2.2
21
+ Requires-Dist: numpy>=2.5.3
22
+ Requires-Dist: scikit-learn>=1.9.1
23
+ Requires-Dist: typer>=0.27.3
24
+ Requires-Dist: clickhouse-connect>=1.9.0 ; extra == 'clickhouse'
25
+ Requires-Dist: xxhash>=4.0.1 ; extra == 'enhanced'
26
+ Requires-Dist: datasketch>=2.0.0 ; extra == 'enhanced'
27
+ Requires-Dist: confluent-kafka>=2.15.1 ; extra == 'kafka'
28
+ Requires-Dist: sqlalchemy>=2.1.3 ; extra == 'sql'
29
+ Maintainer: HyperI Team
30
+ Maintainer-email: HyperI Team <dev@hyperi.io>
31
+ Requires-Python: >=3.14
32
+ Project-URL: Homepage, https://github.com/hyperi-io/logreducer
33
+ Project-URL: Documentation, https://github.com/hyperi-io/logreducer#readme
34
+ Project-URL: Repository, https://github.com/hyperi-io/logreducer
35
+ Project-URL: Bug Reports, https://github.com/hyperi-io/logreducer/issues
36
+ Project-URL: Changelog, https://github.com/hyperi-io/logreducer/blob/main/CHANGELOG.md
37
+ Provides-Extra: clickhouse
38
+ Provides-Extra: enhanced
39
+ Provides-Extra: kafka
40
+ Provides-Extra: sql
41
+ Description-Content-Type: text/markdown
42
+
43
+ # logreducer
44
+
45
+ Reduce gigabytes of logs to a small, representative sample. By default you get a couple of examples of each recurring pattern, and the repeats are dropped.
46
+
47
+ It ships as a CLI and as a Python library with an IO-agnostic core.
48
+
49
+ ## What it gives you
50
+
51
+ - A `logreducer` command that reduces a file, a SQL or ClickHouse query, or a Kafka topic, straight from the shell.
52
+ - Pattern mode streams through a bounded dedup cache, fuzzy index and template store, so memory does not grow with the line count or the number of distinct lines.
53
+ - A memory budget that decides how a file is read: whole, in chunks, or reservoir-sampled once it passes five times the budget.
54
+ - Four modes: pattern (Drain3 template mining), anomaly (Isolation Forest), temporal (one example per template per time window) and hybrid.
55
+ - Lines naming ERROR, FATAL or CRITICAL as a whole word, in any case, always come through, one per distinct shape and ahead of the reduced output, in every mode and however a file is read. A SQL or ClickHouse source samples in the database first, so only the lines it returns are seen.
56
+ - A core with no IO dependencies: anything re-iterable that yields `str` lines is a source, and anything with `write(lines)` is a sink.
57
+ - Seeded SQL sampling and ClickHouse `SAMPLE` for tables too big to scan in full.
58
+ - `reduce_to_target` to collect about N representative lines from a large source, holding roughly one batch in memory.
59
+ - Injection points for a host application's own config cascade and logging.
60
+
61
+ ## Example
62
+
63
+ ```console
64
+ uv add logreducer
65
+ ```
66
+
67
+ ```python
68
+ from logreducer import LogReducer
69
+
70
+ lines = [f"INFO GET /health 200 req={i}" for i in range(500)]
71
+ lines += [f"WARN slow query table=events ms={300 + i}" for i in range(40)]
72
+
73
+ reduced = LogReducer().reduce(lines)
74
+ print(len(lines), "->", len(reduced))
75
+ for line in reduced:
76
+ print(line)
77
+ ```
78
+
79
+ ```text
80
+ 540 -> 4
81
+ WARN slow query table=events ms=300
82
+ WARN slow query table=events ms=301
83
+ INFO GET /health 200 req=0
84
+ INFO GET /health 200 req=1
85
+ ```
86
+
87
+ From the shell it is `logreducer app.log -o reduced.log`. `level` is `standard`, `enhanced` or `maximum`, trading speed for wider coverage on a 0.5, 1 or 2 GB budget.
88
+
89
+ ## Extras
90
+
91
+ | Extra | Adds |
92
+ |---|---|
93
+ | `enhanced` | Fuzzy dedup with MinHash LSH, whose index holds the last `dedup_cache_size` near-unique lines, and faster hashing |
94
+ | `sql` | `SQLSource` over SQLAlchemy, with your own DBAPI driver |
95
+ | `clickhouse` | `ClickHouseSource` over clickhouse-connect |
96
+ | `kafka` | `KafkaSource` and `KafkaSink` over confluent-kafka |
97
+
98
+ Template mining is derived from [Drain3](https://github.com/logpai/Drain3), MIT licence, with its licence text in the module header.
99
+
100
+ Docs and source are at <https://github.com/hyperi-io/logreducer>. Requires Python 3.14 or later. Licensed Apache-2.0: <https://github.com/hyperi-io/logreducer/blob/main/LICENSE>.
@@ -0,0 +1,58 @@
1
+ # logreducer
2
+
3
+ Reduce gigabytes of logs to a small, representative sample. By default you get a couple of examples of each recurring pattern, and the repeats are dropped.
4
+
5
+ It ships as a CLI and as a Python library with an IO-agnostic core.
6
+
7
+ ## What it gives you
8
+
9
+ - A `logreducer` command that reduces a file, a SQL or ClickHouse query, or a Kafka topic, straight from the shell.
10
+ - Pattern mode streams through a bounded dedup cache, fuzzy index and template store, so memory does not grow with the line count or the number of distinct lines.
11
+ - A memory budget that decides how a file is read: whole, in chunks, or reservoir-sampled once it passes five times the budget.
12
+ - Four modes: pattern (Drain3 template mining), anomaly (Isolation Forest), temporal (one example per template per time window) and hybrid.
13
+ - Lines naming ERROR, FATAL or CRITICAL as a whole word, in any case, always come through, one per distinct shape and ahead of the reduced output, in every mode and however a file is read. A SQL or ClickHouse source samples in the database first, so only the lines it returns are seen.
14
+ - A core with no IO dependencies: anything re-iterable that yields `str` lines is a source, and anything with `write(lines)` is a sink.
15
+ - Seeded SQL sampling and ClickHouse `SAMPLE` for tables too big to scan in full.
16
+ - `reduce_to_target` to collect about N representative lines from a large source, holding roughly one batch in memory.
17
+ - Injection points for a host application's own config cascade and logging.
18
+
19
+ ## Example
20
+
21
+ ```console
22
+ uv add logreducer
23
+ ```
24
+
25
+ ```python
26
+ from logreducer import LogReducer
27
+
28
+ lines = [f"INFO GET /health 200 req={i}" for i in range(500)]
29
+ lines += [f"WARN slow query table=events ms={300 + i}" for i in range(40)]
30
+
31
+ reduced = LogReducer().reduce(lines)
32
+ print(len(lines), "->", len(reduced))
33
+ for line in reduced:
34
+ print(line)
35
+ ```
36
+
37
+ ```text
38
+ 540 -> 4
39
+ WARN slow query table=events ms=300
40
+ WARN slow query table=events ms=301
41
+ INFO GET /health 200 req=0
42
+ INFO GET /health 200 req=1
43
+ ```
44
+
45
+ From the shell it is `logreducer app.log -o reduced.log`. `level` is `standard`, `enhanced` or `maximum`, trading speed for wider coverage on a 0.5, 1 or 2 GB budget.
46
+
47
+ ## Extras
48
+
49
+ | Extra | Adds |
50
+ |---|---|
51
+ | `enhanced` | Fuzzy dedup with MinHash LSH, whose index holds the last `dedup_cache_size` near-unique lines, and faster hashing |
52
+ | `sql` | `SQLSource` over SQLAlchemy, with your own DBAPI driver |
53
+ | `clickhouse` | `ClickHouseSource` over clickhouse-connect |
54
+ | `kafka` | `KafkaSource` and `KafkaSink` over confluent-kafka |
55
+
56
+ Template mining is derived from [Drain3](https://github.com/logpai/Drain3), MIT licence, with its licence text in the module header.
57
+
58
+ Docs and source are at <https://github.com/hyperi-io/logreducer>. Requires Python 3.14 or later. Licensed Apache-2.0: <https://github.com/hyperi-io/logreducer/blob/main/LICENSE>.
@@ -4,9 +4,9 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "logreducer"
7
- version = "3.5.4"
7
+ version = "3.5.6"
8
8
  description = "Reduce GB-scale logs to a representative sample - streaming Python library and CLI with pattern mining and anomaly detection"
9
- readme = "README.md"
9
+ readme = "docs/pypi.md"
10
10
  license = "Apache-2.0"
11
11
  license-files = [
12
12
  "LICENSE",
@@ -83,10 +83,10 @@ module-name = "logreducer"
83
83
  module-root = "src"
84
84
 
85
85
  [tool.uv.exclude-newer-package]
86
- certifi = "2026-10-21T00:00:00Z"
86
+ scalo = "2026-11-01T06:00:00Z"
87
87
 
88
88
  [tool.ruff]
89
- target-version = "py312"
89
+ target-version = "py314"
90
90
  line-length = 120
91
91
  indent-width = 4
92
92
  src = ["src"]
@@ -187,7 +187,7 @@ skip-magic-trailing-comma = false
187
187
  line-ending = "auto"
188
188
 
189
189
  [tool.mypy]
190
- python_version = "3.12"
190
+ python_version = "3.14"
191
191
  ignore_missing_imports = true
192
192
  warn_return_any = true
193
193
  warn_unused_configs = true
@@ -216,6 +216,7 @@ markers = [
216
216
  """slow: marks tests as slow (deselect with '-m "not slow"')""",
217
217
  "integration: marks tests as integration tests",
218
218
  ]
219
+ shared_service_repo = "logreducer"
219
220
 
220
221
  [tool.coverage.run]
221
222
  source = ["logreducer"]
@@ -263,35 +264,36 @@ skips = [
263
264
  ]
264
265
 
265
266
  [tool.ty.environment]
266
- python-version = "3.12"
267
+ python-version = "3.14"
267
268
 
268
269
  [tool.ty.src]
269
270
  exclude = [
270
271
  "examples/",
271
272
  "docs/",
272
273
  "scripts/",
274
+ "tests/testdata/build_quiet_golden.py",
273
275
  ]
274
276
 
275
277
  [tool.vulture]
276
278
  min_confidence = 80
277
279
 
278
280
  [tool.vermin]
279
- targets = ["3.12"]
281
+ targets = ["3.14"]
280
282
  no_tips = true
281
283
 
282
284
  [tool.hatch.build.targets.sdist]
283
285
  exclude = [
284
- "/ci",
285
- "/hyperi-ai",
286
- "/GEMINI.md",
287
286
  "/.claude",
288
- "/.cursor",
287
+ "/GEMINI.md",
289
288
  "/CURSOR.md",
290
- "/.gemini",
291
289
  "/.windsurf",
292
- "/STATE.md",
293
290
  "/CLAUDE.md",
291
+ "/.gemini",
292
+ "/hyperi-ai",
294
293
  "/.github/copilot-instructions.md",
294
+ "/.cursor",
295
+ "/STATE.md",
296
+ "/ci",
295
297
  ]
296
298
 
297
299
  [dependency-groups]
@@ -311,7 +313,8 @@ dev = [
311
313
  "sqlalchemy>=2.1.3",
312
314
  "clickhouse-connect>=1.9.0",
313
315
  "confluent-kafka>=2.15.1",
314
- "testcontainers[clickhouse,kafka,postgres,mysql]>=4.15.0",
316
+ "scalo>=2.32.4",
317
+ "testcontainers[postgres,mysql]>=4.15.0",
315
318
  "psycopg[binary]>=3.2",
316
319
  "pymysql>=1.1.0",
317
320
  "python-dotenv>=1.0.0",
@@ -6,7 +6,7 @@ build-backend = "uv_build"
6
6
 
7
7
  [project]
8
8
  name = "logreducer"
9
- version = "3.5.4"
9
+ version = "3.5.6"
10
10
  authors = [
11
11
  { name = "HyperI Team", email = "dev@hyperi.io" },
12
12
  ]
@@ -14,7 +14,7 @@ maintainers = [
14
14
  { name = "HyperI Team", email = "dev@hyperi.io" },
15
15
  ]
16
16
  description = "Reduce GB-scale logs to a representative sample - streaming Python library and CLI with pattern mining and anomaly detection"
17
- readme = "README.md"
17
+ readme = "docs/pypi.md"
18
18
  license = "Apache-2.0"
19
19
  license-files = [
20
20
  "LICENSE",
@@ -87,10 +87,10 @@ module-name = "logreducer"
87
87
  module-root = "src"
88
88
 
89
89
  [tool.uv.exclude-newer-package]
90
- certifi = "2026-10-21T00:00:00Z"
90
+ scalo = "2026-11-01T06:00:00Z"
91
91
 
92
92
  [tool.ruff]
93
- target-version = "py312"
93
+ target-version = "py314"
94
94
  line-length = 120
95
95
  indent-width = 4
96
96
  src = [
@@ -209,7 +209,7 @@ skip-magic-trailing-comma = false
209
209
  line-ending = "auto"
210
210
 
211
211
  [tool.mypy]
212
- python_version = "3.12"
212
+ python_version = "3.14"
213
213
  ignore_missing_imports = true
214
214
  warn_return_any = true
215
215
  warn_unused_configs = true
@@ -244,6 +244,7 @@ markers = [
244
244
  "slow: marks tests as slow (deselect with '-m \"not slow\"')",
245
245
  "integration: marks tests as integration tests",
246
246
  ]
247
+ shared_service_repo = "logreducer"
247
248
 
248
249
  [tool.coverage.run]
249
250
  source = [
@@ -293,13 +294,14 @@ skips = [
293
294
  ]
294
295
 
295
296
  [tool.ty.environment]
296
- python-version = "3.12"
297
+ python-version = "3.14"
297
298
 
298
299
  [tool.ty.src]
299
300
  exclude = [
300
301
  "examples/",
301
302
  "docs/",
302
303
  "scripts/",
304
+ "tests/testdata/build_quiet_golden.py",
303
305
  ]
304
306
 
305
307
  [tool.vulture]
@@ -307,23 +309,23 @@ min_confidence = 80
307
309
 
308
310
  [tool.vermin]
309
311
  targets = [
310
- "3.12",
312
+ "3.14",
311
313
  ]
312
314
  no_tips = true
313
315
 
314
316
  [tool.hatch.build.targets.sdist]
315
317
  exclude = [
316
- "/ci",
317
- "/hyperi-ai",
318
- "/GEMINI.md",
319
318
  "/.claude",
320
- "/.cursor",
319
+ "/GEMINI.md",
321
320
  "/CURSOR.md",
322
- "/.gemini",
323
321
  "/.windsurf",
324
- "/STATE.md",
325
322
  "/CLAUDE.md",
323
+ "/.gemini",
324
+ "/hyperi-ai",
326
325
  "/.github/copilot-instructions.md",
326
+ "/.cursor",
327
+ "/STATE.md",
328
+ "/ci",
327
329
  ]
328
330
 
329
331
  [dependency-groups]
@@ -343,7 +345,8 @@ dev = [
343
345
  "sqlalchemy>=2.1.3",
344
346
  "clickhouse-connect>=1.9.0",
345
347
  "confluent-kafka>=2.15.1",
346
- "testcontainers[clickhouse,kafka,postgres,mysql]>=4.15.0",
348
+ "scalo>=2.32.4",
349
+ "testcontainers[postgres,mysql]>=4.15.0",
347
350
  "psycopg[binary]>=3.2",
348
351
  "pymysql>=1.1.0",
349
352
  "python-dotenv>=1.0.0",
@@ -4,6 +4,9 @@ import logging
4
4
 
5
5
  logger = logging.getLogger(__name__)
6
6
 
7
+ # Fewer lines than this are returned unscored, all of them normal.
8
+ MIN_SCORED_LINES = 10
9
+
7
10
  # Try optional imports
8
11
  try:
9
12
  from sklearn.ensemble import IsolationForest
@@ -30,7 +33,7 @@ class AnomalyDetector:
30
33
  Returns:
31
34
  (anomalous_lines, normal_lines)
32
35
  """
33
- if not self.enabled or len(lines) < 10:
36
+ if not self.enabled or len(lines) < MIN_SCORED_LINES:
34
37
  return [], lines
35
38
 
36
39
  # Vectorize
@@ -189,7 +189,7 @@ def _reduce(
189
189
  else:
190
190
  _err("Error: provide a log file, or --dsn with --query (SQL/ClickHouse) or --topic/--group (Kafka)")
191
191
  raise typer.Exit(1)
192
- except (typer.Exit, typer.BadParameter):
192
+ except typer.Exit, typer.BadParameter:
193
193
  raise # our control-flow exit / typer usage errors - let typer format them
194
194
  except KeyboardInterrupt:
195
195
  _err("Processing interrupted by user")
@@ -276,7 +276,7 @@ def _run_target(
276
276
  close = getattr(source, "close", None)
277
277
  if callable(close):
278
278
  close()
279
- except (typer.Exit, typer.BadParameter):
279
+ except typer.Exit, typer.BadParameter:
280
280
  raise
281
281
  except KeyboardInterrupt:
282
282
  _err("Processing interrupted by user")
@@ -47,6 +47,7 @@ class BigDialConfig:
47
47
  # measured reductions use tens of MB, so the default is deliberately low
48
48
  # and container-friendly.
49
49
  max_memory_gb: float = 1.0
50
+ # Lines exact dedup remembers, and lines the fuzzy index holds. Both drop the oldest first.
50
51
  dedup_cache_size: int = 100000
51
52
 
52
53
  # Speed Control
@@ -101,7 +102,7 @@ class BigDialConfig:
101
102
  self.max_memory_gb = clamped
102
103
 
103
104
  @classmethod
104
- def from_env(cls, *prefixes: str) -> "BigDialConfig":
105
+ def from_env(cls, *prefixes: str) -> BigDialConfig:
105
106
  """Build a config from environment variables, cascade-aware.
106
107
 
107
108
  ``from_env()`` reads ``LOGREDUCER_<FIELD>`` (upper-cased field names,
@@ -4,17 +4,18 @@ import json
4
4
  import os
5
5
  import random
6
6
  import time
7
+ from collections.abc import Iterable
7
8
  from dataclasses import replace
8
9
  from datetime import datetime
9
10
  from enum import Enum
10
11
  from pathlib import Path
11
12
  from typing import Any, Literal, overload
12
13
 
13
- from .anomaly import AnomalyDetector
14
- from .config import BigDialConfig, OutputFormat, ProcessingLevel, ProcessingMode, get_preset_config, validate_config
14
+ from .anomaly import MIN_SCORED_LINES, AnomalyDetector
15
+ from .config import BigDialConfig, OutputFormat, ProcessingLevel, ProcessingMode, get_preset_config
15
16
  from .logging_config import get_logger, setup_logging
16
17
  from .memory import BoundedDeduplicator, MemoryMonitor
17
- from .patterns import FuzzyDeduplicator, PatternExtractor, pattern_priority
18
+ from .patterns import FuzzyDeduplicator, PatternExtractor, SevereShapes, is_severe, pattern_priority
18
19
  from .sampling import reservoir_sample
19
20
  from .sinks import Sink
20
21
  from .sources import FileSource, Source
@@ -63,24 +64,23 @@ class LogReducer:
63
64
  self.mode = mode
64
65
 
65
66
  # Base config: an injected one wins over the level preset.
66
- self.config = replace(config) if config is not None else get_preset_config(level)
67
+ base = config if config is not None else get_preset_config(level)
67
68
 
68
- # Apply overrides BEFORE setting up logging
69
+ overrides: dict[str, Any] = {}
69
70
  if max_memory_gb is not None:
70
- self.config.max_memory_gb = max_memory_gb
71
+ overrides["max_memory_gb"] = max_memory_gb
71
72
  if max_patterns is not None:
72
- self.config.max_patterns = max_patterns
73
-
73
+ overrides["max_patterns"] = max_patterns
74
74
  for key, value in kwargs.items():
75
75
  # Fail fast on typos: silently dropping an unknown override means a
76
76
  # user's tuning quietly does nothing.
77
- if not hasattr(self.config, key):
77
+ if not hasattr(base, key):
78
78
  raise ValueError(f"Unknown config option {key!r} (see BigDialConfig for valid fields)")
79
- # Special handling for output_format to convert string to enum
80
79
  if key == "output_format" and isinstance(value, str):
81
80
  value = OutputFormat(value.lower())
82
- setattr(self.config, key, value)
83
- validate_config(self.config)
81
+ overrides[key] = value
82
+ # replace() builds a new config, so overrides are validated and memory-clamped like any other.
83
+ self.config = replace(base, **overrides)
84
84
 
85
85
  # Setup logging based on config (after overrides applied)
86
86
  setup_logging(
@@ -123,7 +123,7 @@ class LogReducer:
123
123
  self.deduplicator = BoundedDeduplicator(self.config.dedup_cache_size, self.config.hash_algorithm)
124
124
  self.pattern_extractor = PatternExtractor(self.config)
125
125
  if self.config.fuzzy_threshold and self.level != ProcessingLevel.STANDARD:
126
- self.fuzzy_dedup = FuzzyDeduplicator(self.config.fuzzy_threshold)
126
+ self.fuzzy_dedup = FuzzyDeduplicator(self.config.fuzzy_threshold, self.config.dedup_cache_size)
127
127
  else:
128
128
  self.fuzzy_dedup = None
129
129
  if self.mode in [ProcessingMode.TEMPORAL, ProcessingMode.HYBRID]:
@@ -213,7 +213,13 @@ class LogReducer:
213
213
  # Count input lines for the reduction ratio (one pass over the source).
214
214
  # Note: a size-sampled FileSource yields its sampled line count, so for
215
215
  # very large files the ratio and input_lines stat are approximate.
216
- input_lines = sum(1 for _ in source)
216
+ shapes = SevereShapes()
217
+ input_lines = 0
218
+ for line in source:
219
+ input_lines += 1
220
+ shapes.add(line)
221
+ # A FileSource taps its own reads, which see the lines it samples away.
222
+ shapes = getattr(source, "severe_shapes", shapes)
217
223
 
218
224
  size_bytes = getattr(source, "size_bytes", None)
219
225
  file_size_mb = size_bytes / (1024 * 1024) if size_bytes else None
@@ -234,6 +240,10 @@ class LogReducer:
234
240
  else: # HYBRID
235
241
  result_lines = self._process_hybrid_mode(source)
236
242
 
243
+ # Modes return quiet lines under their caps. Severe lines are one per shape, outside every
244
+ # cap, so the output is bounded by the caps plus the number of distinct severe shapes.
245
+ result_lines = shapes.lines + result_lines
246
+
237
247
  # Calculate stats
238
248
  processing_time = time.time() - start_time
239
249
  output_lines = len(result_lines)
@@ -330,31 +340,44 @@ class LogReducer:
330
340
  # single generator pipeline, so there is no phase boundary to report.
331
341
  self.logger.info("Streaming pipeline: dedup -> fuzzy dedup -> pattern mining")
332
342
 
333
- unique_stream = self.deduplicator.deduplicate_counted(source)
343
+ quiet_lines = (line for line in source if not is_severe(line))
344
+ unique_stream = self.deduplicator.deduplicate_counted(quiet_lines)
334
345
  if self.fuzzy_dedup:
335
346
  unique_stream = self.fuzzy_dedup.deduplicate_pairs(unique_stream)
336
347
  patterns = self.pattern_extractor.extract_counted_patterns(unique_stream)
337
348
 
338
- # Collect examples
339
- result = []
340
- for pattern in patterns[: self.config.max_patterns]:
341
- result.extend(pattern.examples)
349
+ # Collect the examples of quiet patterns (the extractor has already applied max_patterns to
350
+ # them). Severe lines come from the severe shapes that reduce() adds, one per shape.
351
+ result: list[str] = []
352
+ for pattern in patterns:
353
+ result.extend(line for line in pattern.examples if not is_severe(line))
342
354
 
343
355
  return result
344
356
 
345
- def _cap_for_anomaly(self, unique_lines: list[str]) -> list[str]:
357
+ def _cap_for_anomaly(self, unique_lines: Iterable[str]) -> list[str]:
346
358
  """Reservoir-cap unique lines to anomaly_max_rows to bound the ML matrix.
347
359
 
348
360
  Anomaly detection (Isolation Forest over a TF-IDF matrix) is batch ML and
349
361
  cannot stream, so a huge unique-line set is the one place a hard memory
350
- cap needs an explicit sample. Fixed seed = reproducible across passes.
351
- Trades anomaly recall (a rare line may be sampled out) for bounded memory;
352
- off unless anomaly_max_rows is set.
362
+ cap needs an explicit sample. The sample is drawn in one pass over the
363
+ stream, so the full set is never held. Fixed seed = reproducible across
364
+ passes. Trades anomaly recall (a rare line may be sampled out) for bounded
365
+ memory. With no anomaly_max_rows the lines are kept whole.
353
366
  """
354
367
  cap = self.config.anomaly_max_rows
355
- if cap and len(unique_lines) > cap:
356
- return reservoir_sample(unique_lines, cap, random.Random(0))
357
- return unique_lines
368
+ if not cap:
369
+ return unique_lines if isinstance(unique_lines, list) else list(unique_lines)
370
+ if isinstance(unique_lines, list) and len(unique_lines) <= cap:
371
+ return unique_lines
372
+ return reservoir_sample(unique_lines, cap, random.Random(0))
373
+
374
+ def _detect_quiet_anomalies(self, detector: AnomalyDetector, source: Source) -> tuple[list[str], list[str]]:
375
+ """Return (anomalous, normal) among the quiet unique lines of ``source``.
376
+
377
+ Severe lines are left out of the detector's input, since reduce() adds one per shape.
378
+ """
379
+ quiet_unique = (line for line in self.deduplicator.deduplicate_lines(source) if not is_severe(line))
380
+ return detector.detect_anomalies(self._cap_for_anomaly(quiet_unique))
358
381
 
359
382
  def _process_anomaly_mode(self, source: Source) -> list[str]:
360
383
  """Process using anomaly detection."""
@@ -364,20 +387,21 @@ class LogReducer:
364
387
  return self._process_pattern_mode(source)
365
388
 
366
389
  if self.config.enable_logging:
367
- self.logger.info("Phase 1/2: Reading and deduplicating")
368
- unique_lines = self._cap_for_anomaly(list(self.deduplicator.deduplicate_lines(source)))
369
-
370
- if self.config.enable_logging:
371
- self.logger.info("Phase 2/2: Anomaly detection")
372
- anomalous, normal = self.anomaly_detector.detect_anomalies(unique_lines)
373
-
374
- # Keep all anomalies + sample of normal
375
- result = anomalous[: self.config.max_patterns // 2]
390
+ self.logger.info("Reading, deduplicating and anomaly detection")
391
+ anomalous, normal = self._detect_quiet_anomalies(self.anomaly_detector, source)
392
+
393
+ cap = self.config.max_patterns
394
+ if not anomalous and len(normal) < MIN_SCORED_LINES:
395
+ # Too few lines to score, so they fill the cap.
396
+ result = []
397
+ normal_budget = cap
398
+ else:
399
+ # Half the cap (rounded up) for anomalies, then a quarter, at least one, for normal context.
400
+ result = anomalous[: (cap + 1) // 2]
401
+ normal_budget = min(cap - len(result), max(cap // 4, 1))
376
402
 
377
- # Add some normal lines for context. Seeded RNG so a re-run over the
378
- # same input yields the same sample (consistent with the reproducibility
379
- # guarantees elsewhere); there is no security requirement here.
380
- normal_sample_size = min(len(normal), self.config.max_patterns // 4)
403
+ # Seeded so a re-run over the same input yields the same sample.
404
+ normal_sample_size = min(len(normal), normal_budget)
381
405
  if normal_sample_size > 0:
382
406
  result.extend(random.Random(0).sample(normal, normal_sample_size))
383
407
 
@@ -392,20 +416,17 @@ class LogReducer:
392
416
 
393
417
  if self.config.enable_logging:
394
418
  self.logger.info("Phase 1/2: Reading lines")
395
- lines = list(source)
419
+ # Severe lines never reach the miner: reduce() adds one line per severe shape, not one per window.
420
+ lines = [line for line in source if not is_severe(line)]
396
421
 
397
422
  if self.config.enable_logging:
398
423
  self.logger.info("Phase 2/2: Temporal processing")
399
424
  temporal_results = self.temporal_processor.process_temporal(lines)
400
425
 
401
- # One example per (window, template), the most important first.
402
- def rank(patterns: list[dict]) -> list[dict]:
403
- return sorted(patterns, key=lambda p: pattern_priority(p["template"], p["count"]), reverse=True)
404
-
405
- result = [p["example"] for p in rank(temporal_results["temporal_patterns"])[: self.config.max_patterns]]
406
- result.extend(p["example"] for p in rank(temporal_results["timeless_patterns"])[:100])
407
-
408
- return result
426
+ # One example per (window, template) or timeless template, the most important first, under one cap.
427
+ candidates = temporal_results["temporal_patterns"] + temporal_results["timeless_patterns"]
428
+ ranked = sorted(candidates, key=lambda p: pattern_priority(p["template"], p["count"]), reverse=True)
429
+ return [p["example"] for p in ranked[: self.config.max_patterns]]
409
430
 
410
431
  def _process_hybrid_mode(self, source: Source) -> list[str]:
411
432
  """Process using combined approach."""
@@ -421,12 +442,12 @@ class LogReducer:
421
442
  # anomaly pass needs a fresh deduplicator - otherwise every line reads
422
443
  # as already-seen and no anomalies survive (hybrid -> pattern-only).
423
444
  self.deduplicator = BoundedDeduplicator(self.config.dedup_cache_size, self.config.hash_algorithm)
424
- unique_lines = self._cap_for_anomaly(list(self.deduplicator.deduplicate_lines(source)))
425
- anomalous, _ = self.anomaly_detector.detect_anomalies(unique_lines)
445
+ anomalous, _ = self._detect_quiet_anomalies(self.anomaly_detector, source)
426
446
 
427
- # Combine, preferring anomalies
428
- result = anomalous[: self.config.max_patterns // 2]
429
- result.extend(pattern_lines[: self.config.max_patterns // 2])
447
+ # Anomalies take half the cap (rounded up), patterns half, at least one, of what is left.
448
+ cap = self.config.max_patterns
449
+ result = anomalous[: (cap + 1) // 2]
450
+ result.extend(pattern_lines[: min(cap - len(result), max(cap // 2, 1))])
430
451
  else:
431
452
  result = pattern_lines
432
453