logreducer 3.5.4__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.4 → logreducer-3.5.5}/pyproject.toml +8 -8
  4. {logreducer-3.5.4 → logreducer-3.5.5}/pyproject.toml.orig +8 -8
  5. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/core.py +43 -23
  6. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/memory.py +23 -9
  7. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/patterns.py +82 -14
  8. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/sources.py +9 -1
  9. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/template_mining.py +29 -10
  10. logreducer-3.5.4/PKG-INFO +0 -466
  11. logreducer-3.5.4/README.md +0 -424
  12. {logreducer-3.5.4 → logreducer-3.5.5}/LICENSE +0 -0
  13. {logreducer-3.5.4 → logreducer-3.5.5}/NOTICE +0 -0
  14. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/__init__.py +0 -0
  15. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/anomaly.py +0 -0
  16. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/cli.py +0 -0
  17. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/clickhouse.py +0 -0
  18. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/config.py +0 -0
  19. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/kafka.py +0 -0
  20. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/logging_config.py +0 -0
  21. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/py.typed +0 -0
  22. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/sampling.py +0 -0
  23. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/sinks.py +0 -0
  24. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/sql.py +0 -0
  25. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/target.py +0 -0
  26. {logreducer-3.5.4 → logreducer-3.5.5}/src/logreducer/temporal.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.4"
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",
@@ -281,17 +281,17 @@ no_tips = true
281
281
 
282
282
  [tool.hatch.build.targets.sdist]
283
283
  exclude = [
284
+ "/CURSOR.md",
285
+ "/CLAUDE.md",
286
+ "/STATE.md",
284
287
  "/ci",
285
- "/hyperi-ai",
286
- "/GEMINI.md",
288
+ "/.github/copilot-instructions.md",
287
289
  "/.claude",
290
+ "/hyperi-ai",
288
291
  "/.cursor",
289
- "/CURSOR.md",
290
292
  "/.gemini",
291
293
  "/.windsurf",
292
- "/STATE.md",
293
- "/CLAUDE.md",
294
- "/.github/copilot-instructions.md",
294
+ "/GEMINI.md",
295
295
  ]
296
296
 
297
297
  [dependency-groups]
@@ -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.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",
@@ -313,17 +313,17 @@ no_tips = true
313
313
 
314
314
  [tool.hatch.build.targets.sdist]
315
315
  exclude = [
316
+ "/CURSOR.md",
317
+ "/CLAUDE.md",
318
+ "/STATE.md",
316
319
  "/ci",
317
- "/hyperi-ai",
318
- "/GEMINI.md",
320
+ "/.github/copilot-instructions.md",
319
321
  "/.claude",
322
+ "/hyperi-ai",
320
323
  "/.cursor",
321
- "/CURSOR.md",
322
324
  "/.gemini",
323
325
  "/.windsurf",
324
- "/STATE.md",
325
- "/CLAUDE.md",
326
- "/.github/copilot-instructions.md",
326
+ "/GEMINI.md",
327
327
  ]
328
328
 
329
329
  [dependency-groups]
@@ -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
@@ -14,7 +15,7 @@ from .anomaly import AnomalyDetector
14
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, 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
@@ -213,7 +214,13 @@ class LogReducer:
213
214
  # Count input lines for the reduction ratio (one pass over the source).
214
215
  # Note: a size-sampled FileSource yields its sampled line count, so for
215
216
  # very large files the ratio and input_lines stat are approximate.
216
- 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)
217
224
 
218
225
  size_bytes = getattr(source, "size_bytes", None)
219
226
  file_size_mb = size_bytes / (1024 * 1024) if size_bytes else None
@@ -234,6 +241,10 @@ class LogReducer:
234
241
  else: # HYBRID
235
242
  result_lines = self._process_hybrid_mode(source)
236
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
+
237
248
  # Calculate stats
238
249
  processing_time = time.time() - start_time
239
250
  output_lines = len(result_lines)
@@ -330,31 +341,44 @@ class LogReducer:
330
341
  # single generator pipeline, so there is no phase boundary to report.
331
342
  self.logger.info("Streaming pipeline: dedup -> fuzzy dedup -> pattern mining")
332
343
 
333
- unique_stream = self.deduplicator.deduplicate_counted(source)
344
+ quiet_lines = (line for line in source if not is_severe(line))
345
+ unique_stream = self.deduplicator.deduplicate_counted(quiet_lines)
334
346
  if self.fuzzy_dedup:
335
347
  unique_stream = self.fuzzy_dedup.deduplicate_pairs(unique_stream)
336
348
  patterns = self.pattern_extractor.extract_counted_patterns(unique_stream)
337
349
 
338
- # 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.
339
352
  result = []
340
- for pattern in patterns[: self.config.max_patterns]:
341
- result.extend(pattern.examples)
353
+ for pattern in patterns:
354
+ result.extend(line for line in pattern.examples if not is_severe(line))
342
355
 
343
356
  return result
344
357
 
345
- def _cap_for_anomaly(self, unique_lines: list[str]) -> list[str]:
358
+ def _cap_for_anomaly(self, unique_lines: Iterable[str]) -> list[str]:
346
359
  """Reservoir-cap unique lines to anomaly_max_rows to bound the ML matrix.
347
360
 
348
361
  Anomaly detection (Isolation Forest over a TF-IDF matrix) is batch ML and
349
362
  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.
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.
353
367
  """
354
368
  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
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))
358
382
 
359
383
  def _process_anomaly_mode(self, source: Source) -> list[str]:
360
384
  """Process using anomaly detection."""
@@ -364,14 +388,10 @@ class LogReducer:
364
388
  return self._process_pattern_mode(source)
365
389
 
366
390
  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)
391
+ self.logger.info("Reading, deduplicating and anomaly detection")
392
+ anomalous, normal = self._detect_quiet_anomalies(self.anomaly_detector, source)
373
393
 
374
- # Keep all anomalies + sample of normal
394
+ # Keep all anomalies (capped) + sample of normal
375
395
  result = anomalous[: self.config.max_patterns // 2]
376
396
 
377
397
  # Add some normal lines for context. Seeded RNG so a re-run over the
@@ -392,7 +412,8 @@ class LogReducer:
392
412
 
393
413
  if self.config.enable_logging:
394
414
  self.logger.info("Phase 1/2: Reading lines")
395
- 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)]
396
417
 
397
418
  if self.config.enable_logging:
398
419
  self.logger.info("Phase 2/2: Temporal processing")
@@ -421,8 +442,7 @@ 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
447
  # Combine, preferring anomalies
428
448
  result = anomalous[: self.config.max_patterns // 2]
@@ -4,7 +4,7 @@ import gc
4
4
  import os
5
5
  import random
6
6
  from collections import deque
7
- from collections.abc import Iterable, Iterator
7
+ from collections.abc import Callable, Iterable, Iterator
8
8
  from typing import Any, Protocol
9
9
 
10
10
  import psutil
@@ -105,8 +105,14 @@ class StreamingProcessor:
105
105
  self.memory_monitor = memory_monitor
106
106
  self.chunk_size = memory_monitor.safe_chunk_size
107
107
 
108
- def read_file_streaming(self, file_path: str) -> Iterator[str]:
109
- """Read file with minimal memory usage."""
108
+ def read_file_streaming(self, file_path: str, tap: Callable[[str], None] | None = None) -> Iterator[str]:
109
+ """Read file with minimal memory usage.
110
+
111
+ Args:
112
+ file_path: The file to read.
113
+ tap: Called with every non-empty stripped line as it is read, before any sampling
114
+ drops it, whichever strategy the file's size and the memory left select.
115
+ """
110
116
  file_size = os.path.getsize(file_path)
111
117
  strategy = self.memory_monitor.estimate_file_strategy(file_size)
112
118
 
@@ -115,15 +121,17 @@ class StreamingProcessor:
115
121
  for line in f:
116
122
  line = line.strip()
117
123
  if line:
124
+ if tap:
125
+ tap(line)
118
126
  yield line
119
127
 
120
128
  elif strategy == "chunked":
121
- yield from self._read_chunked(file_path)
129
+ yield from self._read_chunked(file_path, tap)
122
130
 
123
131
  else: # sampled
124
- yield from self._read_sampled(file_path)
132
+ yield from self._read_sampled(file_path, tap)
125
133
 
126
- def _read_chunked(self, file_path: str) -> Iterator[str]:
134
+ def _read_chunked(self, file_path: str, tap: Callable[[str], None] | None = None) -> Iterator[str]:
127
135
  """Read file in chunks, degrading to sampling under memory pressure.
128
136
 
129
137
  The memory check runs on its own line counter, NOT on chunk-flush
@@ -139,6 +147,8 @@ class StreamingProcessor:
139
147
  if not raw:
140
148
  continue
141
149
 
150
+ if tap:
151
+ tap(raw)
142
152
  chunk.append(raw)
143
153
 
144
154
  if len(chunk) >= self.chunk_size:
@@ -150,13 +160,13 @@ class StreamingProcessor:
150
160
  _, is_safe = self.memory_monitor.check_memory()
151
161
  if not is_safe:
152
162
  yield from chunk
153
- yield from self._read_sampled_remainder(f)
163
+ yield from self._read_sampled_remainder(f, tap)
154
164
  return
155
165
 
156
166
  if chunk:
157
167
  yield from chunk
158
168
 
159
- def _read_sampled(self, file_path: str) -> Iterator[str]:
169
+ def _read_sampled(self, file_path: str, tap: Callable[[str], None] | None = None) -> Iterator[str]:
160
170
  """Reservoir sampling for huge files (uniform, reproducible).
161
171
 
162
172
  Uses Algorithm L with a fixed-seed RNG so every pass over this
@@ -173,11 +183,13 @@ class StreamingProcessor:
173
183
  for line in f:
174
184
  stripped = line.strip()
175
185
  if stripped:
186
+ if tap:
187
+ tap(stripped)
176
188
  yield stripped
177
189
 
178
190
  yield from reservoir_sample(_lines(), reservoir_size, random.Random(0))
179
191
 
180
- def _read_sampled_remainder(self, file_handle: Any) -> Iterator[str]:
192
+ def _read_sampled_remainder(self, file_handle: Any, tap: Callable[[str], None] | None = None) -> Iterator[str]:
181
193
  """Reservoir-sample the rest of an already-open file (mid-chunk fallback)."""
182
194
  from .sampling import reservoir_sample
183
195
 
@@ -185,6 +197,8 @@ class StreamingProcessor:
185
197
  for line in file_handle:
186
198
  stripped = line.strip()
187
199
  if stripped:
200
+ if tap:
201
+ tap(stripped)
188
202
  yield stripped
189
203
 
190
204
  yield from reservoir_sample(_lines(), 10000, random.Random(0))
@@ -1,7 +1,7 @@
1
1
  """Pattern extraction (Drain3 template mining) and fuzzy deduplication."""
2
2
 
3
3
  import logging
4
- from collections.abc import Iterable, Iterator
4
+ from collections.abc import Callable, Iterable, Iterator, Sequence
5
5
  from dataclasses import dataclass, field
6
6
  from typing import TYPE_CHECKING
7
7
 
@@ -25,7 +25,18 @@ except ImportError:
25
25
 
26
26
  @dataclass
27
27
  class LogPattern:
28
- """Represents a unique log pattern."""
28
+ """Represents a unique log pattern.
29
+
30
+ Attributes:
31
+ template: The pattern, with ``<*>`` for the slots that vary.
32
+ examples: Lines kept as examples.
33
+ count: Lines that joined the pattern.
34
+ priority: Rank score (see ``pattern_priority``).
35
+ anomaly_score: Score from anomaly detection.
36
+ metadata: Free-form extras.
37
+ severe: Whether its lines are CRITICAL, FATAL or ERROR. Kept when the
38
+ template has widened the level word to ``<*>``.
39
+ """
29
40
 
30
41
  template: str
31
42
  examples: list[str] = field(default_factory=list)
@@ -33,9 +44,10 @@ class LogPattern:
33
44
  priority: float = 0.0
34
45
  anomaly_score: float = 0.0
35
46
  metadata: dict = field(default_factory=dict)
47
+ severe: bool = False
36
48
 
37
49
 
38
- def _typed_masking_instructions() -> tuple[MaskingInstruction, ...]:
50
+ def _typed_masking_instructions(timestamp: bool = False) -> tuple[MaskingInstruction, ...]:
39
51
  """Build the curated masking set for typed template slots.
40
52
 
41
53
  The miner applies these to each line before clustering, so masked values
@@ -43,13 +55,21 @@ def _typed_masking_instructions() -> tuple[MaskingInstruction, ...]:
43
55
  collapsing to the bare ``<*>`` wildcard. Instructions run sequentially
44
56
  over already-masked text, so the specific shapes (IP, UUID, MAC, IPv6)
45
57
  precede the greedy catch-alls (HEX, NUM).
58
+
59
+ Args:
60
+ timestamp: Also mask ISO-8601 timestamps. Only the severe-shape key
61
+ sets it, so the miner's typed templates stay as they are.
46
62
  """
47
63
  # Zero-width token boundaries (drain3's documented idiom): mask a value
48
64
  # delimited by non-alphanumerics, never a substring of a word.
49
65
  start = r"(?:(?<=[^A-Za-z0-9])|^)"
50
66
  end = r"(?:(?=[^A-Za-z0-9])|$)"
51
67
  hex4 = r"[0-9A-Fa-f]{1,4}"
68
+ # ISO-8601 date and time, with optional fraction and Z or offset. Listed first because the
69
+ # NUM mask stops at letters and would leave the "T10" and "07Z" of a stamp unmasked.
70
+ iso_timestamp = (r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}(?::?\d{2})?)?", "TIMESTAMP")
52
71
  shapes = [
72
+ *([iso_timestamp] if timestamp else []),
53
73
  # IPv4 dotted quad.
54
74
  (r"\d{1,3}(?:\.\d{1,3}){3}", "IP"),
55
75
  # UUID before HEX, which would otherwise eat its 8/12-char runs.
@@ -77,24 +97,71 @@ def _typed_masking_instructions() -> tuple[MaskingInstruction, ...]:
77
97
  _ALWAYS_KEPT_LEVELS = ("CRITICAL", "FATAL", "ERROR")
78
98
 
79
99
 
80
- def _is_severe(template: str) -> bool:
81
- """True for a template that names a CRITICAL, FATAL or ERROR level."""
82
- upper = template.upper()
100
+ def is_severe(text: str) -> bool:
101
+ """True for a line or template that names a CRITICAL, FATAL or ERROR level."""
102
+ upper = text.upper()
83
103
  return any(level in upper for level in _ALWAYS_KEPT_LEVELS)
84
104
 
85
105
 
86
- def pattern_priority(template: str, count: int) -> float:
106
+ class SevereShapes:
107
+ """The first severe line of each shape, fed one line at a time.
108
+
109
+ Numbers, IPs, hex runs and ISO-8601 timestamps do not change a shape, and digits inside an
110
+ identifier do (``E1`` and ``E2`` are two shapes). The reducer feeds it every line as the
111
+ source is read, before any sampling or dedup, so a severe line cannot be lost to either.
112
+ It holds one line per distinct shape.
113
+ """
114
+
115
+ def __init__(self) -> None:
116
+ self._masks = _typed_masking_instructions(timestamp=True)
117
+ self._first_of_shape: dict[str, str] = {}
118
+
119
+ def add(self, line: str) -> None:
120
+ """Remember ``line`` when it is severe and its shape is new."""
121
+ if not is_severe(line):
122
+ return
123
+ shape = line
124
+ for mask in self._masks:
125
+ shape = mask.mask(shape)
126
+ self._first_of_shape.setdefault(shape, line)
127
+
128
+ @property
129
+ def lines(self) -> list[str]:
130
+ """The remembered lines, in the order their shapes first appeared."""
131
+ return list(self._first_of_shape.values())
132
+
133
+
134
+ def cap_outside_severe[T](ranked: Sequence[T], cap: int, severe: Callable[[T], bool]) -> list[T]:
135
+ """Keep every severe item and the first ``cap`` others, in ranked order.
136
+
137
+ A severity boost is a finite multiplier, so a frequent quiet item can outrank a rare
138
+ severe one. Severe items sit outside the cap instead.
139
+ """
140
+ kept: list[T] = []
141
+ others = 0
142
+ for item in ranked:
143
+ if severe(item):
144
+ kept.append(item)
145
+ elif others < cap:
146
+ kept.append(item)
147
+ others += 1
148
+ return kept
149
+
150
+
151
+ def pattern_priority(template: str, count: int, severe: bool = False) -> float:
87
152
  """Rank score for a template seen ``count`` times.
88
153
 
89
154
  Severity boosts are checked highest-first so a template containing both
90
- (e.g. "CRITICAL: write FAILED") scores as critical, not merely error.
155
+ (e.g. "CRITICAL: write FAILED") scores as critical, not merely error. A
156
+ ``severe`` pattern scores as error at least, because its template may have
157
+ widened the level word to ``<*>``.
91
158
  """
92
159
  priority: float = count
93
160
 
94
161
  template_upper = template.upper()
95
162
  if "CRITICAL" in template_upper or "FATAL" in template_upper:
96
163
  priority *= 200
97
- elif "ERROR" in template_upper or "FAIL" in template_upper:
164
+ elif severe or "ERROR" in template_upper or "FAIL" in template_upper:
98
165
  priority *= 100
99
166
  elif "WARN" in template_upper:
100
167
  priority *= 50
@@ -124,6 +191,7 @@ class PatternExtractor:
124
191
  # drain_max_clusters, keeping memory flat on high-cardinality logs.
125
192
  drain_max_clusters=self.config.max_clusters,
126
193
  masking_instructions=masking,
194
+ drain_is_severe=is_severe,
127
195
  )
128
196
  self.miner = TemplateMiner(drain_config)
129
197
 
@@ -149,7 +217,7 @@ class PatternExtractor:
149
217
  cluster = self.miner.add_log_message(line)
150
218
  pattern = pattern_map.get(cluster.cluster_id)
151
219
  if pattern is None:
152
- pattern = LogPattern(template=cluster.get_template(), count=0)
220
+ pattern = LogPattern(template=cluster.get_template(), count=0, severe=cluster.severe)
153
221
  pattern_map[cluster.cluster_id] = pattern
154
222
 
155
223
  pattern.count += 1
@@ -172,18 +240,18 @@ class PatternExtractor:
172
240
  patterns = self._filter_by_occurrence(patterns)
173
241
  patterns = self._calculate_priority(patterns)
174
242
 
175
- # Sort by priority and limit
243
+ # Sort by priority and limit, with severe patterns outside the limit
176
244
  patterns.sort(key=lambda p: p.priority, reverse=True)
177
- return patterns[: self.config.max_patterns]
245
+ return cap_outside_severe(patterns, self.config.max_patterns, lambda p: p.severe)
178
246
 
179
247
  def _filter_by_occurrence(self, patterns: list[LogPattern]) -> list[LogPattern]:
180
248
  """Filter patterns by minimum occurrence, keeping every CRITICAL, FATAL or ERROR one."""
181
- return [p for p in patterns if p.count >= self.config.min_pattern_occurrences or _is_severe(p.template)]
249
+ return [p for p in patterns if p.count >= self.config.min_pattern_occurrences or p.severe]
182
250
 
183
251
  def _calculate_priority(self, patterns: list[LogPattern]) -> list[LogPattern]:
184
252
  """Set each pattern's priority score (see ``pattern_priority``)."""
185
253
  for pattern in patterns:
186
- pattern.priority = pattern_priority(pattern.template, pattern.count)
254
+ pattern.priority = pattern_priority(pattern.template, pattern.count, pattern.severe)
187
255
 
188
256
  return patterns
189
257