logreducer 3.5.3__tar.gz → 3.5.5__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 (26) hide show
  1. logreducer-3.5.5/PKG-INFO +100 -0
  2. logreducer-3.5.5/docs/pypi.md +58 -0
  3. {logreducer-3.5.3 → logreducer-3.5.5}/pyproject.toml +14 -8
  4. {logreducer-3.5.3 → logreducer-3.5.5}/pyproject.toml.orig +14 -8
  5. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/clickhouse.py +3 -1
  6. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/config.py +41 -5
  7. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/core.py +59 -36
  8. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/kafka.py +34 -8
  9. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/memory.py +82 -19
  10. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/patterns.py +144 -35
  11. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/sampling.py +58 -5
  12. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/sources.py +16 -1
  13. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/template_mining.py +29 -10
  14. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/temporal.py +24 -24
  15. logreducer-3.5.3/PKG-INFO +0 -461
  16. logreducer-3.5.3/README.md +0 -419
  17. {logreducer-3.5.3 → logreducer-3.5.5}/LICENSE +0 -0
  18. {logreducer-3.5.3 → logreducer-3.5.5}/NOTICE +0 -0
  19. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/__init__.py +0 -0
  20. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/anomaly.py +0 -0
  21. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/cli.py +0 -0
  22. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/logging_config.py +0 -0
  23. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/py.typed +0 -0
  24. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/sinks.py +0 -0
  25. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/sql.py +0 -0
  26. {logreducer-3.5.3 → logreducer-3.5.5}/src/logreducer/target.py +0 -0
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: logreducer
3
+ Version: 3.5.5
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 and template store, so memory grows with the number of distinct templates, not with the line count.
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
+ - ERROR, FATAL and CRITICAL lines 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 grows with 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 and template store, so memory grows with the number of distinct templates, not with the line count.
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
+ - ERROR, FATAL and CRITICAL lines 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 grows with 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.3"
7
+ version = "3.5.5"
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",
@@ -82,6 +82,9 @@ default = true
82
82
  module-name = "logreducer"
83
83
  module-root = "src"
84
84
 
85
+ [tool.uv.exclude-newer-package]
86
+ certifi = "2026-10-21T00:00:00Z"
87
+
85
88
  [tool.ruff]
86
89
  target-version = "py312"
87
90
  line-length = 120
@@ -279,22 +282,23 @@ no_tips = true
279
282
  [tool.hatch.build.targets.sdist]
280
283
  exclude = [
281
284
  "/CURSOR.md",
282
- "/GEMINI.md",
283
- "/.cursor",
284
- "/.windsurf",
285
- "/.gemini",
286
285
  "/CLAUDE.md",
286
+ "/STATE.md",
287
+ "/ci",
287
288
  "/.github/copilot-instructions.md",
288
289
  "/.claude",
289
- "/ci",
290
290
  "/hyperi-ai",
291
- "/STATE.md",
291
+ "/.cursor",
292
+ "/.gemini",
293
+ "/.windsurf",
294
+ "/GEMINI.md",
292
295
  ]
293
296
 
294
297
  [dependency-groups]
295
298
  dev = [
296
299
  "pytest>=9.0.0",
297
300
  "pytest-cov>=7.0.0",
301
+ "pytest-xdist>=3.8.0",
298
302
  "ruff>=0.16.10",
299
303
  "ty>=0.0.34",
300
304
  "mypy>=2.0",
@@ -302,6 +306,8 @@ dev = [
302
306
  "pip-audit>=2.6.0",
303
307
  "vulture>=2.16",
304
308
  "vermin>=1.6.0",
309
+ "xxhash>=4.0.2",
310
+ "datasketch>=2.0.0",
305
311
  "sqlalchemy>=2.1.3",
306
312
  "clickhouse-connect>=1.9.0",
307
313
  "confluent-kafka>=2.15.1",
@@ -6,7 +6,7 @@ build-backend = "uv_build"
6
6
 
7
7
  [project]
8
8
  name = "logreducer"
9
- version = "3.5.3"
9
+ version = "3.5.5"
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",
@@ -86,6 +86,9 @@ index = [
86
86
  module-name = "logreducer"
87
87
  module-root = "src"
88
88
 
89
+ [tool.uv.exclude-newer-package]
90
+ certifi = "2026-10-21T00:00:00Z"
91
+
89
92
  [tool.ruff]
90
93
  target-version = "py312"
91
94
  line-length = 120
@@ -311,22 +314,23 @@ no_tips = true
311
314
  [tool.hatch.build.targets.sdist]
312
315
  exclude = [
313
316
  "/CURSOR.md",
314
- "/GEMINI.md",
315
- "/.cursor",
316
- "/.windsurf",
317
- "/.gemini",
318
317
  "/CLAUDE.md",
318
+ "/STATE.md",
319
+ "/ci",
319
320
  "/.github/copilot-instructions.md",
320
321
  "/.claude",
321
- "/ci",
322
322
  "/hyperi-ai",
323
- "/STATE.md",
323
+ "/.cursor",
324
+ "/.gemini",
325
+ "/.windsurf",
326
+ "/GEMINI.md",
324
327
  ]
325
328
 
326
329
  [dependency-groups]
327
330
  dev = [
328
331
  "pytest>=9.0.0",
329
332
  "pytest-cov>=7.0.0",
333
+ "pytest-xdist>=3.8.0",
330
334
  "ruff>=0.16.10",
331
335
  "ty>=0.0.34",
332
336
  "mypy>=2.0",
@@ -334,6 +338,8 @@ dev = [
334
338
  "pip-audit>=2.6.0",
335
339
  "vulture>=2.16",
336
340
  "vermin>=1.6.0",
341
+ "xxhash>=4.0.2",
342
+ "datasketch>=2.0.0",
337
343
  "sqlalchemy>=2.1.3",
338
344
  "clickhouse-connect>=1.9.0",
339
345
  "confluent-kafka>=2.15.1",
@@ -23,6 +23,8 @@ import re
23
23
  from collections.abc import Iterator
24
24
  from typing import TYPE_CHECKING, Any
25
25
 
26
+ from .sampling import wrap_subquery
27
+
26
28
  if TYPE_CHECKING:
27
29
  from clickhouse_connect.driver.client import Client
28
30
 
@@ -97,7 +99,7 @@ class ClickHouseSource:
97
99
  self.parameters = parameters
98
100
  self.settings = settings
99
101
  self.sample = sample
100
- self._query = f"{query} SAMPLE {float(sample)!r}" if sample is not None else query
102
+ self._query = f"{wrap_subquery(query)}SAMPLE {float(sample)!r}" if sample is not None else query
101
103
 
102
104
  @classmethod
103
105
  def from_table(
@@ -1,6 +1,7 @@
1
1
  """Configuration and tuning parameters for LogReducer."""
2
2
 
3
3
  import logging
4
+ import math
4
5
  import os
5
6
  import types
6
7
  import typing
@@ -57,8 +58,8 @@ class BigDialConfig:
57
58
  min_pattern_occurrences: int = 2
58
59
  anomaly_contamination: float = 0.1
59
60
  # Bound the Drain3 template store (LRU-evict beyond this many templates).
60
- # None = unbounded (default; the store grows with distinct templates).
61
- max_clusters: int | None = None
61
+ # None = unbounded (the store then grows with distinct templates).
62
+ max_clusters: int | None = 10_000
62
63
  # Cap the rows fed to anomaly detection (reservoir-sampled). Bounds the
63
64
  # TF-IDF matrix on a huge unique-line set, at the cost of anomaly recall
64
65
  # (rare lines may be sampled out). None = no cap (use every unique line).
@@ -88,6 +89,7 @@ class BigDialConfig:
88
89
  pretty_json: bool = False # Pretty print JSON output
89
90
 
90
91
  def __post_init__(self) -> None:
92
+ validate_config(self)
91
93
  # Never promise more memory than the host can give: clamp to 70% of
92
94
  # what is currently available, and say so rather than silently mutate.
93
95
  available_gb = psutil.virtual_memory().available / (1024**3)
@@ -115,13 +117,44 @@ class BigDialConfig:
115
117
  overrides: dict[str, typing.Any] = {}
116
118
  for field in fields(cls):
117
119
  for prefix in prefixes:
118
- raw = os.environ.get(f"{prefix.rstrip('_')}_{field.name.upper()}")
120
+ variable = f"{prefix.rstrip('_')}_{field.name.upper()}"
121
+ raw = os.environ.get(variable)
119
122
  if raw is not None:
120
- overrides[field.name] = _coerce_env_value(raw, field.name)
123
+ try:
124
+ overrides[field.name] = _coerce_env_value(raw, field.name)
125
+ except ValueError as exc:
126
+ raise ValueError(f"{variable}={raw!r}: {exc}") from exc
121
127
  break
122
128
  return cls(**overrides)
123
129
 
124
130
 
131
+ def validate_config(config: BigDialConfig) -> None:
132
+ """Reject values that would crash a run later or silently empty its output.
133
+
134
+ Raises:
135
+ ValueError: Naming the first field that is out of range.
136
+ """
137
+ for name in ("dedup_cache_size", "temporal_window_minutes", "max_patterns", "examples_per_pattern"):
138
+ if getattr(config, name) < 1:
139
+ raise ValueError(f"{name} must be at least 1, got {getattr(config, name)!r}")
140
+ for name in ("max_clusters", "anomaly_max_rows"):
141
+ value = getattr(config, name)
142
+ if value is not None and value < 1:
143
+ raise ValueError(f"{name} must be at least 1 or None, got {value!r}")
144
+ if not 0 < config.max_memory_gb < math.inf:
145
+ raise ValueError(f"max_memory_gb must be finite and greater than 0, got {config.max_memory_gb!r}")
146
+ if not 0.0 <= config.drain_similarity <= 1.0:
147
+ raise ValueError(f"drain_similarity must be between 0 and 1, got {config.drain_similarity!r}")
148
+ if config.fuzzy_threshold is not None and not 0.0 < config.fuzzy_threshold <= 1.0:
149
+ raise ValueError(f"fuzzy_threshold must be in (0, 1] or None, got {config.fuzzy_threshold!r}")
150
+ if not 0.0 < config.anomaly_contamination <= 0.5:
151
+ raise ValueError(f"anomaly_contamination must be in (0, 0.5], got {config.anomaly_contamination!r}")
152
+
153
+
154
+ _TRUE_WORDS = frozenset({"1", "true", "yes", "on"})
155
+ _FALSE_WORDS = frozenset({"0", "false", "no", "off", ""})
156
+
157
+
125
158
  def _coerce_env_value(raw: str, field_name: str) -> object:
126
159
  """Coerce an env string to the annotated type of a BigDialConfig field."""
127
160
  hints = typing.get_type_hints(BigDialConfig)
@@ -133,7 +166,10 @@ def _coerce_env_value(raw: str, field_name: str) -> object:
133
166
  return None
134
167
  target = args[0]
135
168
  if target is bool:
136
- return raw.strip().lower() in ("1", "true", "yes", "on")
169
+ word = raw.strip().lower()
170
+ if word not in _TRUE_WORDS | _FALSE_WORDS:
171
+ raise ValueError("expected a boolean (true/false, yes/no, on/off, 1/0)")
172
+ return word in _TRUE_WORDS
137
173
  if target is int:
138
174
  return int(raw)
139
175
  if target is float:
@@ -4,6 +4,7 @@ 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
@@ -11,10 +12,10 @@ from pathlib import Path
11
12
  from typing import Any, Literal, overload
12
13
 
13
14
  from .anomaly import AnomalyDetector
14
- from .config import BigDialConfig, OutputFormat, ProcessingLevel, ProcessingMode, get_preset_config
15
+ from .config import BigDialConfig, OutputFormat, ProcessingLevel, ProcessingMode, get_preset_config, validate_config
15
16
  from .logging_config import get_logger, setup_logging
16
17
  from .memory import BoundedDeduplicator, MemoryMonitor
17
- from .patterns import FuzzyDeduplicator, PatternExtractor
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
@@ -66,9 +67,9 @@ class LogReducer:
66
67
  self.config = replace(config) if config is not None else get_preset_config(level)
67
68
 
68
69
  # Apply overrides BEFORE setting up logging
69
- if max_memory_gb:
70
+ if max_memory_gb is not None:
70
71
  self.config.max_memory_gb = max_memory_gb
71
- if max_patterns:
72
+ if max_patterns is not None:
72
73
  self.config.max_patterns = max_patterns
73
74
 
74
75
  for key, value in kwargs.items():
@@ -80,6 +81,7 @@ class LogReducer:
80
81
  if key == "output_format" and isinstance(value, str):
81
82
  value = OutputFormat(value.lower())
82
83
  setattr(self.config, key, value)
84
+ validate_config(self.config)
83
85
 
84
86
  # Setup logging based on config (after overrides applied)
85
87
  setup_logging(
@@ -191,6 +193,11 @@ class LogReducer:
191
193
  # re-reads the source to process it (hybrid re-reads again). A one-shot
192
194
  # iterator (a bare generator) would be drained by the count and leave
193
195
  # nothing to process - fail loudly rather than return an empty result.
196
+ if isinstance(source, str | bytes):
197
+ raise TypeError(
198
+ f"source must be an iterable of lines, got a single {type(source).__name__}; "
199
+ "use process_file() for a path, or pass a list of lines."
200
+ )
194
201
  if iter(source) is source:
195
202
  raise TypeError(
196
203
  "source must be re-iterable (a fresh iterator on each pass); got a "
@@ -207,7 +214,13 @@ class LogReducer:
207
214
  # Count input lines for the reduction ratio (one pass over the source).
208
215
  # Note: a size-sampled FileSource yields its sampled line count, so for
209
216
  # very large files the ratio and input_lines stat are approximate.
210
- input_lines = sum(1 for _ in source)
217
+ shapes = SevereShapes()
218
+ input_lines = 0
219
+ for line in source:
220
+ input_lines += 1
221
+ shapes.add(line)
222
+ # A FileSource taps its own reads, which see the lines it samples away.
223
+ shapes = getattr(source, "severe_shapes", shapes)
211
224
 
212
225
  size_bytes = getattr(source, "size_bytes", None)
213
226
  file_size_mb = size_bytes / (1024 * 1024) if size_bytes else None
@@ -228,6 +241,10 @@ class LogReducer:
228
241
  else: # HYBRID
229
242
  result_lines = self._process_hybrid_mode(source)
230
243
 
244
+ # Modes return quiet lines under their caps. Severe lines are one per shape, outside every
245
+ # cap, so the output is bounded by the caps plus the number of distinct severe shapes.
246
+ result_lines = shapes.lines + result_lines
247
+
231
248
  # Calculate stats
232
249
  processing_time = time.time() - start_time
233
250
  output_lines = len(result_lines)
@@ -324,31 +341,44 @@ class LogReducer:
324
341
  # single generator pipeline, so there is no phase boundary to report.
325
342
  self.logger.info("Streaming pipeline: dedup -> fuzzy dedup -> pattern mining")
326
343
 
327
- unique_stream = self.deduplicator.deduplicate_lines(source)
344
+ quiet_lines = (line for line in source if not is_severe(line))
345
+ unique_stream = self.deduplicator.deduplicate_counted(quiet_lines)
328
346
  if self.fuzzy_dedup:
329
- unique_stream = self.fuzzy_dedup.deduplicate_stream(unique_stream)
330
- patterns = self.pattern_extractor.extract_patterns(unique_stream)
347
+ unique_stream = self.fuzzy_dedup.deduplicate_pairs(unique_stream)
348
+ patterns = self.pattern_extractor.extract_counted_patterns(unique_stream)
331
349
 
332
- # Collect examples
350
+ # Collect the examples of quiet patterns (the extractor has already applied max_patterns to
351
+ # them). Severe lines come from the severe shapes that reduce() adds, one per shape.
333
352
  result = []
334
- for pattern in patterns[: self.config.max_patterns]:
335
- result.extend(pattern.examples)
353
+ for pattern in patterns:
354
+ result.extend(line for line in pattern.examples if not is_severe(line))
336
355
 
337
356
  return result
338
357
 
339
- def _cap_for_anomaly(self, unique_lines: list[str]) -> list[str]:
358
+ def _cap_for_anomaly(self, unique_lines: Iterable[str]) -> list[str]:
340
359
  """Reservoir-cap unique lines to anomaly_max_rows to bound the ML matrix.
341
360
 
342
361
  Anomaly detection (Isolation Forest over a TF-IDF matrix) is batch ML and
343
362
  cannot stream, so a huge unique-line set is the one place a hard memory
344
- cap needs an explicit sample. Fixed seed = reproducible across passes.
345
- Trades anomaly recall (a rare line may be sampled out) for bounded memory;
346
- off unless anomaly_max_rows is set.
363
+ cap needs an explicit sample. The sample is drawn in one pass over the
364
+ stream, so the full set is never held. Fixed seed = reproducible across
365
+ passes. Trades anomaly recall (a rare line may be sampled out) for bounded
366
+ memory. With no anomaly_max_rows the lines are kept whole.
347
367
  """
348
368
  cap = self.config.anomaly_max_rows
349
- if cap and len(unique_lines) > cap:
350
- return reservoir_sample(unique_lines, cap, random.Random(0))
351
- return unique_lines
369
+ if not cap:
370
+ return unique_lines if isinstance(unique_lines, list) else list(unique_lines)
371
+ if isinstance(unique_lines, list) and len(unique_lines) <= cap:
372
+ return unique_lines
373
+ return reservoir_sample(unique_lines, cap, random.Random(0))
374
+
375
+ def _detect_quiet_anomalies(self, detector: AnomalyDetector, source: Source) -> tuple[list[str], list[str]]:
376
+ """Return (anomalous, normal) among the quiet unique lines of ``source``.
377
+
378
+ Severe lines are left out of the detector's input, since reduce() adds one per shape.
379
+ """
380
+ quiet_unique = (line for line in self.deduplicator.deduplicate_lines(source) if not is_severe(line))
381
+ return detector.detect_anomalies(self._cap_for_anomaly(quiet_unique))
352
382
 
353
383
  def _process_anomaly_mode(self, source: Source) -> list[str]:
354
384
  """Process using anomaly detection."""
@@ -358,14 +388,10 @@ class LogReducer:
358
388
  return self._process_pattern_mode(source)
359
389
 
360
390
  if self.config.enable_logging:
361
- self.logger.info("Phase 1/2: Reading and deduplicating")
362
- unique_lines = self._cap_for_anomaly(list(self.deduplicator.deduplicate_lines(source)))
363
-
364
- if self.config.enable_logging:
365
- self.logger.info("Phase 2/2: Anomaly detection")
366
- anomalous, normal = self.anomaly_detector.detect_anomalies(unique_lines)
391
+ self.logger.info("Reading, deduplicating and anomaly detection")
392
+ anomalous, normal = self._detect_quiet_anomalies(self.anomaly_detector, source)
367
393
 
368
- # Keep all anomalies + sample of normal
394
+ # Keep all anomalies (capped) + sample of normal
369
395
  result = anomalous[: self.config.max_patterns // 2]
370
396
 
371
397
  # Add some normal lines for context. Seeded RNG so a re-run over the
@@ -386,21 +412,19 @@ class LogReducer:
386
412
 
387
413
  if self.config.enable_logging:
388
414
  self.logger.info("Phase 1/2: Reading lines")
389
- lines = list(source)
415
+ # Severe lines never reach the miner: reduce() adds one line per severe shape, not one per window.
416
+ lines = [line for line in source if not is_severe(line)]
390
417
 
391
418
  if self.config.enable_logging:
392
419
  self.logger.info("Phase 2/2: Temporal processing")
393
420
  temporal_results = self.temporal_processor.process_temporal(lines)
394
421
 
395
- # Collect examples from temporal patterns
396
- result = []
397
- for pattern in temporal_results.get("temporal_patterns", [])[: self.config.max_patterns]:
398
- if "example" in pattern:
399
- result.append(pattern["example"])
422
+ # One example per (window, template), the most important first.
423
+ def rank(patterns: list[dict]) -> list[dict]:
424
+ return sorted(patterns, key=lambda p: pattern_priority(p["template"], p["count"]), reverse=True)
400
425
 
401
- for pattern in temporal_results.get("timeless_patterns", [])[:100]:
402
- if "example" in pattern:
403
- result.append(pattern["example"])
426
+ result = [p["example"] for p in rank(temporal_results["temporal_patterns"])[: self.config.max_patterns]]
427
+ result.extend(p["example"] for p in rank(temporal_results["timeless_patterns"])[:100])
404
428
 
405
429
  return result
406
430
 
@@ -418,8 +442,7 @@ class LogReducer:
418
442
  # anomaly pass needs a fresh deduplicator - otherwise every line reads
419
443
  # as already-seen and no anomalies survive (hybrid -> pattern-only).
420
444
  self.deduplicator = BoundedDeduplicator(self.config.dedup_cache_size, self.config.hash_algorithm)
421
- unique_lines = self._cap_for_anomaly(list(self.deduplicator.deduplicate_lines(source)))
422
- anomalous, _ = self.anomaly_detector.detect_anomalies(unique_lines)
445
+ anomalous, _ = self._detect_quiet_anomalies(self.anomaly_detector, source)
423
446
 
424
447
  # Combine, preferring anomalies
425
448
  result = anomalous[: self.config.max_patterns // 2]
@@ -100,6 +100,15 @@ class KafkaConsumerError(Exception):
100
100
  super().__init__(message)
101
101
 
102
102
 
103
+ class KafkaDeliveryError(Exception):
104
+ """One or more produced messages were not delivered to the broker."""
105
+
106
+ def __init__(self, message: str, failed: int, undelivered: int) -> None:
107
+ self.failed = failed
108
+ self.undelivered = undelivered
109
+ super().__init__(message)
110
+
111
+
103
112
  def _normalise_config(config: str | dict[str, Any]) -> dict[str, Any]:
104
113
  """A bare string is treated as ``bootstrap.servers``; a dict is copied."""
105
114
  if isinstance(config, str):
@@ -267,20 +276,37 @@ class KafkaSink:
267
276
  self._producer = Producer(self._config)
268
277
 
269
278
  def write(self, lines: Iterable[str]) -> int:
270
- """Produce each line to the topic and flush; return the number produced.
279
+ """Produce each line to the topic and flush; return the number delivered.
271
280
 
272
281
  With the default ``flush_timeout=None`` the final flush blocks until the
273
- queue drains, so the count is effectively a delivery count. With a finite
274
- ``flush_timeout`` some messages may still be in flight when flush returns.
282
+ queue drains.
283
+
284
+ Raises:
285
+ KafkaDeliveryError: A message was rejected by the broker, expired
286
+ before delivery, or was still queued when a finite
287
+ ``flush_timeout`` ran out.
275
288
  """
276
289
  key_bytes = self.key.encode(self.encoding) if self.key is not None else None
277
- count = 0
290
+ produced = 0
291
+ errors: list[str] = []
292
+
293
+ def on_delivery(err: Any, _msg: Any) -> None:
294
+ if err is not None:
295
+ errors.append(str(err))
296
+
278
297
  for line in lines:
279
- self._producer.produce(self.topic, value=line.encode(self.encoding), key=key_bytes)
298
+ self._producer.produce(self.topic, value=line.encode(self.encoding), key=key_bytes, on_delivery=on_delivery)
280
299
  self._producer.poll(0) # Trigger delivery callbacks (non-blocking)
281
- count += 1
282
- self.flush()
283
- return count
300
+ produced += 1
301
+ undelivered = self.flush()
302
+ if errors or undelivered:
303
+ raise KafkaDeliveryError(
304
+ f"{len(errors)} of {produced} messages failed and {undelivered} were still queued "
305
+ f"for topic {self.topic!r}" + (f" (first error: {errors[0]})" if errors else ""),
306
+ failed=len(errors),
307
+ undelivered=undelivered,
308
+ )
309
+ return produced
284
310
 
285
311
  def flush(self) -> int:
286
312
  """Wait for outstanding messages; return the count still in queue."""