logreducer 3.5.3__tar.gz → 3.5.4__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.
- {logreducer-3.5.3 → logreducer-3.5.4}/PKG-INFO +14 -9
- {logreducer-3.5.3 → logreducer-3.5.4}/README.md +13 -8
- {logreducer-3.5.3 → logreducer-3.5.4}/pyproject.toml +13 -7
- {logreducer-3.5.3 → logreducer-3.5.4}/pyproject.toml.orig +13 -7
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/clickhouse.py +3 -1
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/config.py +41 -5
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/core.py +18 -15
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/kafka.py +34 -8
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/memory.py +59 -10
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/patterns.py +70 -29
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/sampling.py +58 -5
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/sources.py +7 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/temporal.py +24 -24
- {logreducer-3.5.3 → logreducer-3.5.4}/LICENSE +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/NOTICE +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/__init__.py +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/anomaly.py +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/cli.py +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/logging_config.py +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/py.typed +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/sinks.py +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/sql.py +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/target.py +0 -0
- {logreducer-3.5.3 → logreducer-3.5.4}/src/logreducer/template_mining.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: logreducer
|
|
3
|
-
Version: 3.5.
|
|
3
|
+
Version: 3.5.4
|
|
4
4
|
Summary: Reduce GB-scale logs to a representative sample - streaming Python library and CLI with pattern mining and anomaly detection
|
|
5
5
|
Keywords: log,logging,reduction,analysis,pattern-extraction,memory-efficient,streaming,anomaly-detection
|
|
6
6
|
Author: HyperI Team
|
|
@@ -43,7 +43,7 @@ Description-Content-Type: text/markdown
|
|
|
43
43
|
# LogReducer
|
|
44
44
|
|
|
45
45
|
[](https://pypi.org/project/logreducer/)
|
|
46
|
-
[](https://www.python.org/)
|
|
47
47
|
[](LICENSE)
|
|
48
48
|
|
|
49
49
|
Reduce gigabytes of logs to a small, representative sample - keeping the patterns and anomalies that matter and dropping the repetition that does not. Memory-safe streaming, temporal awareness, and ML-based anomaly detection.
|
|
@@ -66,7 +66,7 @@ Reduce gigabytes of logs to a small, representative sample - keeping the pattern
|
|
|
66
66
|
|
|
67
67
|
### As a CLI tool
|
|
68
68
|
|
|
69
|
-
Install it as an isolated tool so its dependencies never clash with your other Python projects (needs Python 3.
|
|
69
|
+
Install it as an isolated tool so its dependencies never clash with your other Python projects (needs Python 3.14+):
|
|
70
70
|
|
|
71
71
|
```bash
|
|
72
72
|
uv tool install logreducer # recommended (uv)
|
|
@@ -131,7 +131,7 @@ reduced = reducer.reduce(lines)
|
|
|
131
131
|
|
|
132
132
|
## How it works
|
|
133
133
|
|
|
134
|
-
|
|
134
|
+
Pattern mode streams: lines flow through dedup and template mining as one generator pipeline, so the unique-line set is never materialised and memory stays near-constant regardless of input size.
|
|
135
135
|
|
|
136
136
|
```mermaid
|
|
137
137
|
flowchart LR
|
|
@@ -170,7 +170,7 @@ flowchart TD
|
|
|
170
170
|
|------|-------------|----------|
|
|
171
171
|
| `pattern` | Drain3 template mining | Structured / application logs (fastest) |
|
|
172
172
|
| `anomaly` | Isolation Forest outlier detection | Security and error logs |
|
|
173
|
-
| `temporal` |
|
|
173
|
+
| `temporal` | One example per time window and template, most important first (`temporal_window_minutes`, capped by `max_patterns`) | Time-series and monitoring logs |
|
|
174
174
|
| `hybrid` | Pattern + anomaly combined | Maximum coverage |
|
|
175
175
|
|
|
176
176
|
| Level | Speed | Memory cap | Features |
|
|
@@ -266,10 +266,10 @@ logreducer --dsn postgresql://user@host/db --query "SELECT msg FROM logs" \
|
|
|
266
266
|
|
|
267
267
|
## Bounding memory
|
|
268
268
|
|
|
269
|
-
|
|
269
|
+
Pattern mode streams and runs in near-constant memory. Temporal mode holds the whole source in memory, and anomaly mode holds its unique lines. The knobs:
|
|
270
270
|
|
|
271
271
|
- `max_memory_gb` - the overall cap (also sizes file read strategy and the watchdog). Presets: 0.5 / 1 / 2 GB by level; values above 70% of available RAM are clamped with a warning.
|
|
272
|
-
- `max_clusters` - LRU-bound the Drain3 template store (
|
|
272
|
+
- `max_clusters` - LRU-bound the Drain3 template store (10,000 by default, `None` for unbounded). Mining time grows with the square of the number of templates a line is compared with, so a lower value also speeds up high-cardinality sources.
|
|
273
273
|
- `anomaly_max_rows` - reservoir-cap the rows fed to anomaly detection (off by default; trades anomaly recall for a bounded matrix).
|
|
274
274
|
|
|
275
275
|
```python
|
|
@@ -356,6 +356,7 @@ reducer = LogReducer(
|
|
|
356
356
|
anomaly_contamination=0.1, # expected anomaly fraction
|
|
357
357
|
temporal_window_minutes=60, # grouping window for temporal mode
|
|
358
358
|
max_patterns=2000, # cap on extracted patterns
|
|
359
|
+
min_pattern_occurrences=2, # patterns seen fewer times are dropped, except CRITICAL/FATAL/ERROR ones
|
|
359
360
|
)
|
|
360
361
|
```
|
|
361
362
|
|
|
@@ -445,11 +446,11 @@ Individually: `uv run ruff format`, `uv run ruff check --fix`,
|
|
|
445
446
|
|
|
446
447
|
### Where this sits
|
|
447
448
|
|
|
448
|
-
One declared edge in `dfe-infra/suite.yaml
|
|
449
|
+
One declared edge in `dfe-infra/suite.yaml`.
|
|
449
450
|
|
|
450
451
|
| Repo | Direction | Kind | Mechanism |
|
|
451
452
|
|---|---|---|---|
|
|
452
|
-
| dfe-engine | outbound | `python-dep
|
|
453
|
+
| dfe-engine | outbound | `python-dep` | dfe-engine declares `logreducer[enhanced]` by range in its `pyproject.toml` and imports it lazily, inside the `smart` and `anomaly` sampler modes: `LogReducer` and `logreducer.clickhouse` in `sampling/service.py`, `logreducer.kafka` in `sampling/kafka_reader.py`. A new release is checked against that range, then taken with `uv lock --upgrade-package logreducer` and the engine's tests |
|
|
453
454
|
|
|
454
455
|
`dfe-stack suite --consumer logreducer` returns an empty edge list: no repo in
|
|
455
456
|
that graph is something this library depends on. The runtime dependencies
|
|
@@ -459,3 +460,7 @@ that graph is something this library depends on. The runtime dependencies
|
|
|
459
460
|
The reason dfe-engine gives for not declaring the dependency -- pin it "once it
|
|
460
461
|
hits public PyPI" -- has been met since 3.4.0 was published on 2026-07-03, so
|
|
461
462
|
expect that edge to become an ordinary pinned dependency.
|
|
463
|
+
|
|
464
|
+
## Issues
|
|
465
|
+
|
|
466
|
+
Open bugs: [this repo](https://github.com/hyperi-io/logreducer/issues?q=is%3Aopen+is%3Aissue+type%3ABug+-label%3Abacklog+-label%3Anext-minor) | [whole DFE suite](https://github.com/search?type=issues&q=is%3Aopen+is%3Aissue+type%3ABug+-label%3Abacklog+-label%3Anext-minor+repo%3Ahyperi-io%2Fdfe-infra+repo%3Ahyperi-io%2Fdfe-docker+repo%3Ahyperi-io%2Fdfe-deploy+repo%3Ahyperi-io%2Fdfe-engine+repo%3Ahyperi-io%2Fdfe-loader+repo%3Ahyperi-io%2Fdfe-receiver+repo%3Ahyperi-io%2Fdfe-fetcher+repo%3Ahyperi-io%2Fdfe-archiver+repo%3Ahyperi-io%2Fdfe-transform-vrl+repo%3Ahyperi-io%2Fdfe-transform-vector+repo%3Ahyperi-io%2Fdfe-transform-elastic+repo%3Ahyperi-io%2Fdfe-ui+repo%3Ahyperi-io%2Fdfe-hyperdx+repo%3Ahyperi-io%2Fscalo-rs+repo%3Ahyperi-io%2Fscalo-py+repo%3Ahyperi-io%2Flogreducer+repo%3Ahyperi-io%2Fdfe-schemas+repo%3Ahyperi-io%2Fvector-vrl+repo%3Ahyperi-io%2Fculvert+repo%3Ahyperi-io%2Fclickhouse-dfe+repo%3Ahyperi-io%2Ffactbook-rs)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# LogReducer
|
|
2
2
|
|
|
3
3
|
[](https://pypi.org/project/logreducer/)
|
|
4
|
-
[](https://www.python.org/)
|
|
5
5
|
[](LICENSE)
|
|
6
6
|
|
|
7
7
|
Reduce gigabytes of logs to a small, representative sample - keeping the patterns and anomalies that matter and dropping the repetition that does not. Memory-safe streaming, temporal awareness, and ML-based anomaly detection.
|
|
@@ -24,7 +24,7 @@ Reduce gigabytes of logs to a small, representative sample - keeping the pattern
|
|
|
24
24
|
|
|
25
25
|
### As a CLI tool
|
|
26
26
|
|
|
27
|
-
Install it as an isolated tool so its dependencies never clash with your other Python projects (needs Python 3.
|
|
27
|
+
Install it as an isolated tool so its dependencies never clash with your other Python projects (needs Python 3.14+):
|
|
28
28
|
|
|
29
29
|
```bash
|
|
30
30
|
uv tool install logreducer # recommended (uv)
|
|
@@ -89,7 +89,7 @@ reduced = reducer.reduce(lines)
|
|
|
89
89
|
|
|
90
90
|
## How it works
|
|
91
91
|
|
|
92
|
-
|
|
92
|
+
Pattern mode streams: lines flow through dedup and template mining as one generator pipeline, so the unique-line set is never materialised and memory stays near-constant regardless of input size.
|
|
93
93
|
|
|
94
94
|
```mermaid
|
|
95
95
|
flowchart LR
|
|
@@ -128,7 +128,7 @@ flowchart TD
|
|
|
128
128
|
|------|-------------|----------|
|
|
129
129
|
| `pattern` | Drain3 template mining | Structured / application logs (fastest) |
|
|
130
130
|
| `anomaly` | Isolation Forest outlier detection | Security and error logs |
|
|
131
|
-
| `temporal` |
|
|
131
|
+
| `temporal` | One example per time window and template, most important first (`temporal_window_minutes`, capped by `max_patterns`) | Time-series and monitoring logs |
|
|
132
132
|
| `hybrid` | Pattern + anomaly combined | Maximum coverage |
|
|
133
133
|
|
|
134
134
|
| Level | Speed | Memory cap | Features |
|
|
@@ -224,10 +224,10 @@ logreducer --dsn postgresql://user@host/db --query "SELECT msg FROM logs" \
|
|
|
224
224
|
|
|
225
225
|
## Bounding memory
|
|
226
226
|
|
|
227
|
-
|
|
227
|
+
Pattern mode streams and runs in near-constant memory. Temporal mode holds the whole source in memory, and anomaly mode holds its unique lines. The knobs:
|
|
228
228
|
|
|
229
229
|
- `max_memory_gb` - the overall cap (also sizes file read strategy and the watchdog). Presets: 0.5 / 1 / 2 GB by level; values above 70% of available RAM are clamped with a warning.
|
|
230
|
-
- `max_clusters` - LRU-bound the Drain3 template store (
|
|
230
|
+
- `max_clusters` - LRU-bound the Drain3 template store (10,000 by default, `None` for unbounded). Mining time grows with the square of the number of templates a line is compared with, so a lower value also speeds up high-cardinality sources.
|
|
231
231
|
- `anomaly_max_rows` - reservoir-cap the rows fed to anomaly detection (off by default; trades anomaly recall for a bounded matrix).
|
|
232
232
|
|
|
233
233
|
```python
|
|
@@ -314,6 +314,7 @@ reducer = LogReducer(
|
|
|
314
314
|
anomaly_contamination=0.1, # expected anomaly fraction
|
|
315
315
|
temporal_window_minutes=60, # grouping window for temporal mode
|
|
316
316
|
max_patterns=2000, # cap on extracted patterns
|
|
317
|
+
min_pattern_occurrences=2, # patterns seen fewer times are dropped, except CRITICAL/FATAL/ERROR ones
|
|
317
318
|
)
|
|
318
319
|
```
|
|
319
320
|
|
|
@@ -403,11 +404,11 @@ Individually: `uv run ruff format`, `uv run ruff check --fix`,
|
|
|
403
404
|
|
|
404
405
|
### Where this sits
|
|
405
406
|
|
|
406
|
-
One declared edge in `dfe-infra/suite.yaml
|
|
407
|
+
One declared edge in `dfe-infra/suite.yaml`.
|
|
407
408
|
|
|
408
409
|
| Repo | Direction | Kind | Mechanism |
|
|
409
410
|
|---|---|---|---|
|
|
410
|
-
| dfe-engine | outbound | `python-dep
|
|
411
|
+
| dfe-engine | outbound | `python-dep` | dfe-engine declares `logreducer[enhanced]` by range in its `pyproject.toml` and imports it lazily, inside the `smart` and `anomaly` sampler modes: `LogReducer` and `logreducer.clickhouse` in `sampling/service.py`, `logreducer.kafka` in `sampling/kafka_reader.py`. A new release is checked against that range, then taken with `uv lock --upgrade-package logreducer` and the engine's tests |
|
|
411
412
|
|
|
412
413
|
`dfe-stack suite --consumer logreducer` returns an empty edge list: no repo in
|
|
413
414
|
that graph is something this library depends on. The runtime dependencies
|
|
@@ -417,3 +418,7 @@ that graph is something this library depends on. The runtime dependencies
|
|
|
417
418
|
The reason dfe-engine gives for not declaring the dependency -- pin it "once it
|
|
418
419
|
hits public PyPI" -- has been met since 3.4.0 was published on 2026-07-03, so
|
|
419
420
|
expect that edge to become an ordinary pinned dependency.
|
|
421
|
+
|
|
422
|
+
## Issues
|
|
423
|
+
|
|
424
|
+
Open bugs: [this repo](https://github.com/hyperi-io/logreducer/issues?q=is%3Aopen+is%3Aissue+type%3ABug+-label%3Abacklog+-label%3Anext-minor) | [whole DFE suite](https://github.com/search?type=issues&q=is%3Aopen+is%3Aissue+type%3ABug+-label%3Abacklog+-label%3Anext-minor+repo%3Ahyperi-io%2Fdfe-infra+repo%3Ahyperi-io%2Fdfe-docker+repo%3Ahyperi-io%2Fdfe-deploy+repo%3Ahyperi-io%2Fdfe-engine+repo%3Ahyperi-io%2Fdfe-loader+repo%3Ahyperi-io%2Fdfe-receiver+repo%3Ahyperi-io%2Fdfe-fetcher+repo%3Ahyperi-io%2Fdfe-archiver+repo%3Ahyperi-io%2Fdfe-transform-vrl+repo%3Ahyperi-io%2Fdfe-transform-vector+repo%3Ahyperi-io%2Fdfe-transform-elastic+repo%3Ahyperi-io%2Fdfe-ui+repo%3Ahyperi-io%2Fdfe-hyperdx+repo%3Ahyperi-io%2Fscalo-rs+repo%3Ahyperi-io%2Fscalo-py+repo%3Ahyperi-io%2Flogreducer+repo%3Ahyperi-io%2Fdfe-schemas+repo%3Ahyperi-io%2Fvector-vrl+repo%3Ahyperi-io%2Fculvert+repo%3Ahyperi-io%2Fclickhouse-dfe+repo%3Ahyperi-io%2Ffactbook-rs)
|
|
@@ -4,7 +4,7 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "logreducer"
|
|
7
|
-
version = "3.5.
|
|
7
|
+
version = "3.5.4"
|
|
8
8
|
description = "Reduce GB-scale logs to a representative sample - streaming Python library and CLI with pattern mining and anomaly detection"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
@@ -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
|
|
@@ -278,23 +281,24 @@ no_tips = true
|
|
|
278
281
|
|
|
279
282
|
[tool.hatch.build.targets.sdist]
|
|
280
283
|
exclude = [
|
|
281
|
-
"/
|
|
284
|
+
"/ci",
|
|
285
|
+
"/hyperi-ai",
|
|
282
286
|
"/GEMINI.md",
|
|
287
|
+
"/.claude",
|
|
283
288
|
"/.cursor",
|
|
284
|
-
"
|
|
289
|
+
"/CURSOR.md",
|
|
285
290
|
"/.gemini",
|
|
291
|
+
"/.windsurf",
|
|
292
|
+
"/STATE.md",
|
|
286
293
|
"/CLAUDE.md",
|
|
287
294
|
"/.github/copilot-instructions.md",
|
|
288
|
-
"/.claude",
|
|
289
|
-
"/ci",
|
|
290
|
-
"/hyperi-ai",
|
|
291
|
-
"/STATE.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.
|
|
9
|
+
version = "3.5.4"
|
|
10
10
|
authors = [
|
|
11
11
|
{ name = "HyperI Team", email = "dev@hyperi.io" },
|
|
12
12
|
]
|
|
@@ -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
|
|
@@ -310,23 +313,24 @@ no_tips = true
|
|
|
310
313
|
|
|
311
314
|
[tool.hatch.build.targets.sdist]
|
|
312
315
|
exclude = [
|
|
313
|
-
"/
|
|
316
|
+
"/ci",
|
|
317
|
+
"/hyperi-ai",
|
|
314
318
|
"/GEMINI.md",
|
|
319
|
+
"/.claude",
|
|
315
320
|
"/.cursor",
|
|
316
|
-
"
|
|
321
|
+
"/CURSOR.md",
|
|
317
322
|
"/.gemini",
|
|
323
|
+
"/.windsurf",
|
|
324
|
+
"/STATE.md",
|
|
318
325
|
"/CLAUDE.md",
|
|
319
326
|
"/.github/copilot-instructions.md",
|
|
320
|
-
"/.claude",
|
|
321
|
-
"/ci",
|
|
322
|
-
"/hyperi-ai",
|
|
323
|
-
"/STATE.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}
|
|
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 (
|
|
61
|
-
max_clusters: int | 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
|
-
|
|
120
|
+
variable = f"{prefix.rstrip('_')}_{field.name.upper()}"
|
|
121
|
+
raw = os.environ.get(variable)
|
|
119
122
|
if raw is not None:
|
|
120
|
-
|
|
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
|
-
|
|
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:
|
|
@@ -11,10 +11,10 @@ from pathlib import Path
|
|
|
11
11
|
from typing import Any, Literal, overload
|
|
12
12
|
|
|
13
13
|
from .anomaly import AnomalyDetector
|
|
14
|
-
from .config import BigDialConfig, OutputFormat, ProcessingLevel, ProcessingMode, get_preset_config
|
|
14
|
+
from .config import BigDialConfig, OutputFormat, ProcessingLevel, ProcessingMode, get_preset_config, validate_config
|
|
15
15
|
from .logging_config import get_logger, setup_logging
|
|
16
16
|
from .memory import BoundedDeduplicator, MemoryMonitor
|
|
17
|
-
from .patterns import FuzzyDeduplicator, PatternExtractor
|
|
17
|
+
from .patterns import FuzzyDeduplicator, PatternExtractor, pattern_priority
|
|
18
18
|
from .sampling import reservoir_sample
|
|
19
19
|
from .sinks import Sink
|
|
20
20
|
from .sources import FileSource, Source
|
|
@@ -66,9 +66,9 @@ class LogReducer:
|
|
|
66
66
|
self.config = replace(config) if config is not None else get_preset_config(level)
|
|
67
67
|
|
|
68
68
|
# Apply overrides BEFORE setting up logging
|
|
69
|
-
if max_memory_gb:
|
|
69
|
+
if max_memory_gb is not None:
|
|
70
70
|
self.config.max_memory_gb = max_memory_gb
|
|
71
|
-
if max_patterns:
|
|
71
|
+
if max_patterns is not None:
|
|
72
72
|
self.config.max_patterns = max_patterns
|
|
73
73
|
|
|
74
74
|
for key, value in kwargs.items():
|
|
@@ -80,6 +80,7 @@ class LogReducer:
|
|
|
80
80
|
if key == "output_format" and isinstance(value, str):
|
|
81
81
|
value = OutputFormat(value.lower())
|
|
82
82
|
setattr(self.config, key, value)
|
|
83
|
+
validate_config(self.config)
|
|
83
84
|
|
|
84
85
|
# Setup logging based on config (after overrides applied)
|
|
85
86
|
setup_logging(
|
|
@@ -191,6 +192,11 @@ class LogReducer:
|
|
|
191
192
|
# re-reads the source to process it (hybrid re-reads again). A one-shot
|
|
192
193
|
# iterator (a bare generator) would be drained by the count and leave
|
|
193
194
|
# nothing to process - fail loudly rather than return an empty result.
|
|
195
|
+
if isinstance(source, str | bytes):
|
|
196
|
+
raise TypeError(
|
|
197
|
+
f"source must be an iterable of lines, got a single {type(source).__name__}; "
|
|
198
|
+
"use process_file() for a path, or pass a list of lines."
|
|
199
|
+
)
|
|
194
200
|
if iter(source) is source:
|
|
195
201
|
raise TypeError(
|
|
196
202
|
"source must be re-iterable (a fresh iterator on each pass); got a "
|
|
@@ -324,10 +330,10 @@ class LogReducer:
|
|
|
324
330
|
# single generator pipeline, so there is no phase boundary to report.
|
|
325
331
|
self.logger.info("Streaming pipeline: dedup -> fuzzy dedup -> pattern mining")
|
|
326
332
|
|
|
327
|
-
unique_stream = self.deduplicator.
|
|
333
|
+
unique_stream = self.deduplicator.deduplicate_counted(source)
|
|
328
334
|
if self.fuzzy_dedup:
|
|
329
|
-
unique_stream = self.fuzzy_dedup.
|
|
330
|
-
patterns = self.pattern_extractor.
|
|
335
|
+
unique_stream = self.fuzzy_dedup.deduplicate_pairs(unique_stream)
|
|
336
|
+
patterns = self.pattern_extractor.extract_counted_patterns(unique_stream)
|
|
331
337
|
|
|
332
338
|
# Collect examples
|
|
333
339
|
result = []
|
|
@@ -392,15 +398,12 @@ class LogReducer:
|
|
|
392
398
|
self.logger.info("Phase 2/2: Temporal processing")
|
|
393
399
|
temporal_results = self.temporal_processor.process_temporal(lines)
|
|
394
400
|
|
|
395
|
-
#
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
if "example" in pattern:
|
|
399
|
-
result.append(pattern["example"])
|
|
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)
|
|
400
404
|
|
|
401
|
-
for
|
|
402
|
-
|
|
403
|
-
result.append(pattern["example"])
|
|
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])
|
|
404
407
|
|
|
405
408
|
return result
|
|
406
409
|
|
|
@@ -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
|
|
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
|
|
274
|
-
|
|
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
|
-
|
|
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
|
-
|
|
282
|
-
self.flush()
|
|
283
|
-
|
|
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."""
|
|
@@ -5,7 +5,7 @@ import os
|
|
|
5
5
|
import random
|
|
6
6
|
from collections import deque
|
|
7
7
|
from collections.abc import Iterable, Iterator
|
|
8
|
-
from typing import Any
|
|
8
|
+
from typing import Any, Protocol
|
|
9
9
|
|
|
10
10
|
import psutil
|
|
11
11
|
|
|
@@ -111,7 +111,7 @@ class StreamingProcessor:
|
|
|
111
111
|
strategy = self.memory_monitor.estimate_file_strategy(file_size)
|
|
112
112
|
|
|
113
113
|
if strategy == "full":
|
|
114
|
-
with open(file_path, encoding="utf-8", errors="
|
|
114
|
+
with open(file_path, encoding="utf-8", errors="replace") as f:
|
|
115
115
|
for line in f:
|
|
116
116
|
line = line.strip()
|
|
117
117
|
if line:
|
|
@@ -134,7 +134,7 @@ class StreamingProcessor:
|
|
|
134
134
|
check_every = 100_000
|
|
135
135
|
next_check = check_every
|
|
136
136
|
|
|
137
|
-
with open(file_path, encoding="utf-8", errors="
|
|
137
|
+
with open(file_path, encoding="utf-8", errors="replace") as f:
|
|
138
138
|
for line_num, raw in enumerate(line.strip() for line in f):
|
|
139
139
|
if not raw:
|
|
140
140
|
continue
|
|
@@ -169,7 +169,7 @@ class StreamingProcessor:
|
|
|
169
169
|
reservoir_size = min(self.chunk_size, 100000)
|
|
170
170
|
|
|
171
171
|
def _lines() -> Iterator[str]:
|
|
172
|
-
with open(file_path, encoding="utf-8", errors="
|
|
172
|
+
with open(file_path, encoding="utf-8", errors="replace") as f:
|
|
173
173
|
for line in f:
|
|
174
174
|
stripped = line.strip()
|
|
175
175
|
if stripped:
|
|
@@ -190,6 +190,31 @@ class StreamingProcessor:
|
|
|
190
190
|
yield from reservoir_sample(_lines(), 10000, random.Random(0))
|
|
191
191
|
|
|
192
192
|
|
|
193
|
+
class _Counted(Protocol):
|
|
194
|
+
"""Anything with a running ``count`` (a ``LogPattern``)."""
|
|
195
|
+
|
|
196
|
+
count: int
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class Occurrence:
|
|
200
|
+
"""Ties a line that survived exact dedup to the pattern it was merged into.
|
|
201
|
+
|
|
202
|
+
Dedup drops later repeats of the line. Once a consumer sets ``target``, each
|
|
203
|
+
dropped repeat adds one to ``target.count``, so a line seen 100 times
|
|
204
|
+
counts 100 towards its pattern instead of 1.
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
__slots__ = ("target",)
|
|
208
|
+
|
|
209
|
+
def __init__(self) -> None:
|
|
210
|
+
self.target: _Counted | None = None
|
|
211
|
+
|
|
212
|
+
def repeat(self) -> None:
|
|
213
|
+
"""Record one dropped repeat of the line."""
|
|
214
|
+
if self.target is not None:
|
|
215
|
+
self.target.count += 1
|
|
216
|
+
|
|
217
|
+
|
|
193
218
|
class BoundedDeduplicator:
|
|
194
219
|
"""Memory-bounded exact deduplication (sliding-window semantics).
|
|
195
220
|
|
|
@@ -199,47 +224,71 @@ class BoundedDeduplicator:
|
|
|
199
224
|
"""
|
|
200
225
|
|
|
201
226
|
def __init__(self, max_cache_size: int = 100000, hash_algorithm: str = "xxhash"):
|
|
227
|
+
if max_cache_size < 1:
|
|
228
|
+
raise ValueError(f"max_cache_size must be at least 1, got {max_cache_size!r}")
|
|
202
229
|
self.max_cache_size = max_cache_size
|
|
203
230
|
|
|
204
|
-
# Choose hash function
|
|
231
|
+
# Choose hash function. surrogatepass keeps a lone surrogate in a
|
|
232
|
+
# caller-supplied line hashable instead of raising mid-run.
|
|
205
233
|
if hash_algorithm == "xxhash":
|
|
206
234
|
try:
|
|
207
235
|
import xxhash
|
|
208
236
|
|
|
209
|
-
self.hash_func = lambda x: xxhash.xxh64(x.encode()).hexdigest()
|
|
237
|
+
self.hash_func = lambda x: xxhash.xxh64(x.encode("utf-8", "surrogatepass")).hexdigest()
|
|
210
238
|
except ImportError:
|
|
211
239
|
import hashlib
|
|
212
240
|
|
|
213
|
-
self.hash_func = lambda x: hashlib.blake2b(
|
|
241
|
+
self.hash_func = lambda x: hashlib.blake2b(
|
|
242
|
+
x.encode("utf-8", "surrogatepass"), digest_size=16
|
|
243
|
+
).hexdigest()
|
|
214
244
|
else:
|
|
215
245
|
import hashlib
|
|
216
246
|
|
|
217
|
-
self.hash_func = lambda x: hashlib.md5(
|
|
247
|
+
self.hash_func = lambda x: hashlib.md5(
|
|
248
|
+
x.encode("utf-8", "surrogatepass"), usedforsecurity=False
|
|
249
|
+
).hexdigest()
|
|
218
250
|
|
|
219
251
|
self.seen_hashes: deque[str] = deque(maxlen=max_cache_size)
|
|
220
252
|
self.seen_set: set[str] = set()
|
|
253
|
+
self._occurrences: dict[str, Occurrence] = {}
|
|
221
254
|
self.stats = {"total": 0, "unique": 0, "duplicates": 0}
|
|
222
255
|
|
|
223
256
|
def is_duplicate(self, line: str) -> bool:
|
|
224
257
|
"""Check if line is duplicate."""
|
|
258
|
+
return self._observe(line)[0]
|
|
259
|
+
|
|
260
|
+
def _observe(self, line: str) -> tuple[bool, Occurrence]:
|
|
261
|
+
"""Record ``line``, returning (is_duplicate, the Occurrence of its first sighting)."""
|
|
225
262
|
self.stats["total"] += 1
|
|
226
263
|
line_hash = self.hash_func(line)
|
|
227
264
|
|
|
228
265
|
if line_hash in self.seen_set:
|
|
229
266
|
self.stats["duplicates"] += 1
|
|
230
|
-
|
|
267
|
+
occurrence = self._occurrences[line_hash]
|
|
268
|
+
occurrence.repeat()
|
|
269
|
+
return True, occurrence
|
|
231
270
|
|
|
232
271
|
if len(self.seen_hashes) >= self.max_cache_size:
|
|
233
272
|
old_hash = self.seen_hashes[0]
|
|
234
273
|
self.seen_set.discard(old_hash)
|
|
274
|
+
self._occurrences.pop(old_hash, None)
|
|
235
275
|
|
|
276
|
+
occurrence = Occurrence()
|
|
236
277
|
self.seen_hashes.append(line_hash)
|
|
237
278
|
self.seen_set.add(line_hash)
|
|
279
|
+
self._occurrences[line_hash] = occurrence
|
|
238
280
|
self.stats["unique"] += 1
|
|
239
|
-
return False
|
|
281
|
+
return False, occurrence
|
|
240
282
|
|
|
241
283
|
def deduplicate_lines(self, lines: Iterable[str]) -> Iterator[str]:
|
|
242
284
|
"""Deduplicate a stream of lines."""
|
|
243
285
|
for line in lines:
|
|
244
286
|
if not self.is_duplicate(line):
|
|
245
287
|
yield line
|
|
288
|
+
|
|
289
|
+
def deduplicate_counted(self, lines: Iterable[str]) -> Iterator[tuple[str, Occurrence]]:
|
|
290
|
+
"""Deduplicate a stream, pairing each kept line with its ``Occurrence``."""
|
|
291
|
+
for line in lines:
|
|
292
|
+
duplicate, occurrence = self._observe(line)
|
|
293
|
+
if not duplicate:
|
|
294
|
+
yield line, occurrence
|
|
@@ -5,6 +5,7 @@ from collections.abc import Iterable, Iterator
|
|
|
5
5
|
from dataclasses import dataclass, field
|
|
6
6
|
from typing import TYPE_CHECKING
|
|
7
7
|
|
|
8
|
+
from .memory import Occurrence
|
|
8
9
|
from .template_mining import MaskingInstruction, TemplateMiner, TemplateMinerConfig
|
|
9
10
|
|
|
10
11
|
if TYPE_CHECKING:
|
|
@@ -73,6 +74,37 @@ def _typed_masking_instructions() -> tuple[MaskingInstruction, ...]:
|
|
|
73
74
|
return tuple(MaskingInstruction(f"{start}(?:{pattern}){end}", name) for pattern, name in shapes)
|
|
74
75
|
|
|
75
76
|
|
|
77
|
+
_ALWAYS_KEPT_LEVELS = ("CRITICAL", "FATAL", "ERROR")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _is_severe(template: str) -> bool:
|
|
81
|
+
"""True for a template that names a CRITICAL, FATAL or ERROR level."""
|
|
82
|
+
upper = template.upper()
|
|
83
|
+
return any(level in upper for level in _ALWAYS_KEPT_LEVELS)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def pattern_priority(template: str, count: int) -> float:
|
|
87
|
+
"""Rank score for a template seen ``count`` times.
|
|
88
|
+
|
|
89
|
+
Severity boosts are checked highest-first so a template containing both
|
|
90
|
+
(e.g. "CRITICAL: write FAILED") scores as critical, not merely error.
|
|
91
|
+
"""
|
|
92
|
+
priority: float = count
|
|
93
|
+
|
|
94
|
+
template_upper = template.upper()
|
|
95
|
+
if "CRITICAL" in template_upper or "FATAL" in template_upper:
|
|
96
|
+
priority *= 200
|
|
97
|
+
elif "ERROR" in template_upper or "FAIL" in template_upper:
|
|
98
|
+
priority *= 100
|
|
99
|
+
elif "WARN" in template_upper:
|
|
100
|
+
priority *= 50
|
|
101
|
+
|
|
102
|
+
# Boost complex patterns
|
|
103
|
+
priority *= 1 + template.count("<*>") * 0.5
|
|
104
|
+
priority *= 1 + len(template.split()) * 0.1
|
|
105
|
+
return priority
|
|
106
|
+
|
|
107
|
+
|
|
76
108
|
class PatternExtractor:
|
|
77
109
|
"""Extract patterns using the online template miner (see template_mining)."""
|
|
78
110
|
|
|
@@ -102,9 +134,18 @@ class PatternExtractor:
|
|
|
102
134
|
generator - no need to materialise the whole line set. Memory is bounded
|
|
103
135
|
by the number of clusters (see ``max_clusters``), not the line count.
|
|
104
136
|
"""
|
|
137
|
+
return self.extract_counted_patterns((line, None) for line in lines)
|
|
138
|
+
|
|
139
|
+
def extract_counted_patterns(self, pairs: Iterable[tuple[str, Occurrence | None]]) -> list[LogPattern]:
|
|
140
|
+
"""Like ``extract_patterns``, for lines paired with their dedup ``Occurrence``.
|
|
141
|
+
|
|
142
|
+
Repeats that exact dedup drops after a line was kept still count towards
|
|
143
|
+
the pattern that line joined, so 100 identical errors make one pattern
|
|
144
|
+
with ``count == 100``.
|
|
145
|
+
"""
|
|
105
146
|
pattern_map: dict[int, LogPattern] = {}
|
|
106
147
|
|
|
107
|
-
for line in
|
|
148
|
+
for line, occurrence in pairs:
|
|
108
149
|
cluster = self.miner.add_log_message(line)
|
|
109
150
|
pattern = pattern_map.get(cluster.cluster_id)
|
|
110
151
|
if pattern is None:
|
|
@@ -112,6 +153,8 @@ class PatternExtractor:
|
|
|
112
153
|
pattern_map[cluster.cluster_id] = pattern
|
|
113
154
|
|
|
114
155
|
pattern.count += 1
|
|
156
|
+
if occurrence is not None:
|
|
157
|
+
occurrence.target = pattern
|
|
115
158
|
|
|
116
159
|
if len(pattern.examples) < self.config.examples_per_pattern:
|
|
117
160
|
pattern.examples.append(line)
|
|
@@ -134,31 +177,13 @@ class PatternExtractor:
|
|
|
134
177
|
return patterns[: self.config.max_patterns]
|
|
135
178
|
|
|
136
179
|
def _filter_by_occurrence(self, patterns: list[LogPattern]) -> list[LogPattern]:
|
|
137
|
-
"""Filter patterns by minimum occurrence."""
|
|
138
|
-
return [p for p in patterns if p.count >= self.config.min_pattern_occurrences]
|
|
180
|
+
"""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)]
|
|
139
182
|
|
|
140
183
|
def _calculate_priority(self, patterns: list[LogPattern]) -> list[LogPattern]:
|
|
141
|
-
"""
|
|
142
|
-
|
|
143
|
-
Severity boosts are checked highest-first so a template containing both
|
|
144
|
-
(e.g. "CRITICAL: write FAILED") scores as critical, not merely error.
|
|
145
|
-
"""
|
|
184
|
+
"""Set each pattern's priority score (see ``pattern_priority``)."""
|
|
146
185
|
for pattern in patterns:
|
|
147
|
-
priority
|
|
148
|
-
|
|
149
|
-
template_upper = pattern.template.upper()
|
|
150
|
-
if "CRITICAL" in template_upper or "FATAL" in template_upper:
|
|
151
|
-
priority *= 200
|
|
152
|
-
elif "ERROR" in template_upper or "FAIL" in template_upper:
|
|
153
|
-
priority *= 100
|
|
154
|
-
elif "WARN" in template_upper:
|
|
155
|
-
priority *= 50
|
|
156
|
-
|
|
157
|
-
# Boost complex patterns
|
|
158
|
-
priority *= 1 + pattern.template.count("<*>") * 0.5
|
|
159
|
-
priority *= 1 + len(pattern.template.split()) * 0.1
|
|
160
|
-
|
|
161
|
-
pattern.priority = priority
|
|
186
|
+
pattern.priority = pattern_priority(pattern.template, pattern.count)
|
|
162
187
|
|
|
163
188
|
return patterns
|
|
164
189
|
|
|
@@ -187,14 +212,30 @@ class FuzzyDeduplicator:
|
|
|
187
212
|
return
|
|
188
213
|
|
|
189
214
|
for i, line in enumerate(lines):
|
|
190
|
-
|
|
191
|
-
for word in line.split():
|
|
192
|
-
m.update(word.encode("utf8"))
|
|
193
|
-
|
|
194
|
-
if not self.lsh.query(m):
|
|
195
|
-
self.lsh.insert(f"line_{i}", m)
|
|
215
|
+
if self._admit(i, line):
|
|
196
216
|
yield line
|
|
197
217
|
|
|
218
|
+
def deduplicate_pairs(self, pairs: Iterable[tuple[str, Occurrence]]) -> Iterator[tuple[str, Occurrence]]:
|
|
219
|
+
"""``deduplicate_stream`` over (line, Occurrence) pairs, keeping each pair intact."""
|
|
220
|
+
if not self.enabled:
|
|
221
|
+
yield from pairs
|
|
222
|
+
return
|
|
223
|
+
|
|
224
|
+
for i, pair in enumerate(pairs):
|
|
225
|
+
if self._admit(i, pair[0]):
|
|
226
|
+
yield pair
|
|
227
|
+
|
|
228
|
+
def _admit(self, index: int, line: str) -> bool:
|
|
229
|
+
"""True (and remembered) when no near-duplicate of ``line`` was admitted before."""
|
|
230
|
+
m = MinHash(num_perm=64)
|
|
231
|
+
for word in line.split():
|
|
232
|
+
m.update(word.encode("utf-8", "surrogatepass"))
|
|
233
|
+
|
|
234
|
+
if self.lsh.query(m):
|
|
235
|
+
return False
|
|
236
|
+
self.lsh.insert(f"line_{index}", m)
|
|
237
|
+
return True
|
|
238
|
+
|
|
198
239
|
def deduplicate(self, lines: Iterable[str]) -> list[str]:
|
|
199
240
|
"""Remove near-duplicates, returning a list (eager wrapper of the stream)."""
|
|
200
241
|
return list(self.deduplicate_stream(lines))
|
|
@@ -35,6 +35,59 @@ RANDOM_FN: dict[str, str] = {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
|
|
38
|
+
def _terminator_index(query: str) -> int | None:
|
|
39
|
+
"""Index of a ``;`` followed only by whitespace and comments, else None.
|
|
40
|
+
|
|
41
|
+
One forward pass in linear time that skips quoted text and comments, so a
|
|
42
|
+
``;`` or ``--`` inside a string literal is never mistaken for syntax.
|
|
43
|
+
"""
|
|
44
|
+
end = len(query)
|
|
45
|
+
last_semicolon: int | None = None
|
|
46
|
+
i = 0
|
|
47
|
+
while i < end:
|
|
48
|
+
char = query[i]
|
|
49
|
+
if char == ";":
|
|
50
|
+
last_semicolon = i
|
|
51
|
+
i += 1
|
|
52
|
+
elif char.isspace():
|
|
53
|
+
i += 1
|
|
54
|
+
elif query.startswith("--", i):
|
|
55
|
+
newline = query.find("\n", i)
|
|
56
|
+
i = end if newline < 0 else newline + 1
|
|
57
|
+
elif query.startswith("/*", i):
|
|
58
|
+
close = query.find("*/", i + 2)
|
|
59
|
+
i = end if close < 0 else close + 2
|
|
60
|
+
elif char in "'\"`":
|
|
61
|
+
i += 1
|
|
62
|
+
while i < end:
|
|
63
|
+
if query[i] == char:
|
|
64
|
+
if query.startswith(char, i + 1): # a doubled quote is an escaped quote
|
|
65
|
+
i += 2
|
|
66
|
+
continue
|
|
67
|
+
break
|
|
68
|
+
i += 1
|
|
69
|
+
i += 1
|
|
70
|
+
last_semicolon = None
|
|
71
|
+
else:
|
|
72
|
+
last_semicolon = None
|
|
73
|
+
i += 1
|
|
74
|
+
return last_semicolon
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def wrap_subquery(query: str) -> str:
|
|
78
|
+
"""The query as text safe to place inside ``( ... )``.
|
|
79
|
+
|
|
80
|
+
A trailing ``;`` is a syntax error inside a subquery, and a trailing ``--``
|
|
81
|
+
comment swallows the closing parenthesis, so the terminator is dropped and
|
|
82
|
+
the text ends on a newline.
|
|
83
|
+
"""
|
|
84
|
+
query = query.strip()
|
|
85
|
+
terminator = _terminator_index(query)
|
|
86
|
+
if terminator is not None:
|
|
87
|
+
query = query[:terminator]
|
|
88
|
+
return query.rstrip() + "\n"
|
|
89
|
+
|
|
90
|
+
|
|
38
91
|
def _pg_sample(query: str, fraction: float, seed: int | None) -> tuple[str | None, str]:
|
|
39
92
|
# setseed makes random() deterministic for the rest of the connection; it
|
|
40
93
|
# takes a value in [-1, 1]. Each pass opens a fresh connection and re-seeds,
|
|
@@ -46,13 +99,13 @@ def _pg_sample(query: str, fraction: float, seed: int | None) -> tuple[str | Non
|
|
|
46
99
|
if seed is not None:
|
|
47
100
|
s = ((seed % 2_000_000) / 1_000_000.0) - 1.0
|
|
48
101
|
setup = f"SELECT setseed({s!r})"
|
|
49
|
-
return setup, f"SELECT * FROM ({query}) AS _lr_sample WHERE random() < {float(fraction)!r}"
|
|
102
|
+
return setup, f"SELECT * FROM ({wrap_subquery(query)}) AS _lr_sample WHERE random() < {float(fraction)!r}"
|
|
50
103
|
|
|
51
104
|
|
|
52
105
|
def _mysql_sample(query: str, fraction: float, seed: int | None) -> tuple[str | None, str]:
|
|
53
106
|
# RAND(seed) with a constant seed is a repeatable per-row sequence.
|
|
54
107
|
rand = f"rand({int(seed)})" if seed is not None else "rand()"
|
|
55
|
-
return None, f"SELECT * FROM ({query}) AS _lr_sample WHERE {rand} < {float(fraction)!r}"
|
|
108
|
+
return None, f"SELECT * FROM ({wrap_subquery(query)}) AS _lr_sample WHERE {rand} < {float(fraction)!r}"
|
|
56
109
|
|
|
57
110
|
|
|
58
111
|
def _sqlite_sample(query: str, fraction: float, seed: int | None) -> tuple[str | None, str]:
|
|
@@ -62,7 +115,7 @@ def _sqlite_sample(query: str, fraction: float, seed: int | None) -> tuple[str |
|
|
|
62
115
|
"omit sample_seed for best-effort sampling, or use a seedable engine (postgresql, mysql)"
|
|
63
116
|
)
|
|
64
117
|
threshold = int(float(fraction) * 1_000_000)
|
|
65
|
-
return None, f"SELECT * FROM ({query}) AS _lr_sample WHERE (abs(random()) % 1000000) < {threshold}"
|
|
118
|
+
return None, f"SELECT * FROM ({wrap_subquery(query)}) AS _lr_sample WHERE (abs(random()) % 1000000) < {threshold}"
|
|
66
119
|
|
|
67
120
|
|
|
68
121
|
# dialect.name -> builder. ClickHouse is handled by its own source (native
|
|
@@ -107,7 +160,7 @@ def build_sample_batch_sql(dialect: str, query: str, n: int) -> str:
|
|
|
107
160
|
rand = RANDOM_FN.get(dialect)
|
|
108
161
|
if rand is None:
|
|
109
162
|
raise SamplingNotSupported(f"no random function for dialect {dialect!r} (supported: {sorted(RANDOM_FN)})")
|
|
110
|
-
return f"SELECT * FROM ({query}) AS _lr_batch ORDER BY {rand} LIMIT {int(n)}"
|
|
163
|
+
return f"SELECT * FROM ({wrap_subquery(query)}) AS _lr_batch ORDER BY {rand} LIMIT {int(n)}"
|
|
111
164
|
|
|
112
165
|
|
|
113
166
|
def build_table_sample_query(
|
|
@@ -202,7 +255,7 @@ def estimate_batch_rows(
|
|
|
202
255
|
"""
|
|
203
256
|
if not sample_lines or budget_bytes <= 0:
|
|
204
257
|
return floor
|
|
205
|
-
avg_bytes = sum(len(s.encode("utf-8")) for s in sample_lines) / len(sample_lines)
|
|
258
|
+
avg_bytes = sum(len(s.encode("utf-8", "surrogatepass")) for s in sample_lines) / len(sample_lines)
|
|
206
259
|
per_row = max(1.0, avg_bytes * overhead)
|
|
207
260
|
rows = int(budget_bytes / per_row)
|
|
208
261
|
if align > 1:
|
|
@@ -61,6 +61,13 @@ class FileSource:
|
|
|
61
61
|
|
|
62
62
|
def __init__(self, path: str | os.PathLike[str], *, max_memory_gb: float = 1.0) -> None:
|
|
63
63
|
self.path = os.fspath(path)
|
|
64
|
+
# A pipe or device can be read once, but reduce() reads a source more than
|
|
65
|
+
# once, so the second pass would see nothing and return an empty result.
|
|
66
|
+
if os.path.exists(self.path) and not os.path.isfile(self.path):
|
|
67
|
+
raise ValueError(
|
|
68
|
+
f"{self.path!r} is not a regular file. A pipe or device cannot be re-read, "
|
|
69
|
+
"so write it to a file first (e.g. redirect into a temp file)."
|
|
70
|
+
)
|
|
64
71
|
self._processor = StreamingProcessor(MemoryMonitor(max_memory_gb))
|
|
65
72
|
|
|
66
73
|
def __iter__(self) -> Iterator[str]:
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import re
|
|
4
4
|
from collections import defaultdict
|
|
5
5
|
from dataclasses import dataclass
|
|
6
|
-
from datetime import datetime
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
7
|
from typing import Any
|
|
8
8
|
|
|
9
9
|
from .template_mining import TemplateMiner
|
|
@@ -62,6 +62,8 @@ class TemporalProcessor:
|
|
|
62
62
|
"""Time-aware log processing."""
|
|
63
63
|
|
|
64
64
|
def __init__(self, window_minutes: int = 60):
|
|
65
|
+
if window_minutes < 1:
|
|
66
|
+
raise ValueError(f"window_minutes must be at least 1, got {window_minutes!r}")
|
|
65
67
|
self.window_minutes = window_minutes
|
|
66
68
|
self.parser = TimestampParser()
|
|
67
69
|
self.miners_by_window: dict[int, TemplateMiner] = {}
|
|
@@ -96,42 +98,40 @@ class TemporalProcessor:
|
|
|
96
98
|
# Group by time window
|
|
97
99
|
for entry in entries:
|
|
98
100
|
if entry.timestamp:
|
|
99
|
-
|
|
101
|
+
# Read the naive timestamp as UTC: local-time conversion raises on
|
|
102
|
+
# sentinels like 0001-01-01 and 9999-12-31 and shifts with DST.
|
|
103
|
+
epoch_seconds = entry.timestamp.replace(tzinfo=UTC).timestamp()
|
|
104
|
+
window_key = int(epoch_seconds // (self.window_minutes * 60))
|
|
100
105
|
windows[window_key].append(entry)
|
|
101
106
|
|
|
102
|
-
#
|
|
107
|
+
# One pattern per template within each window.
|
|
103
108
|
for window_key, window_entries in windows.items():
|
|
104
109
|
if window_key not in self.miners_by_window:
|
|
105
110
|
self.miners_by_window[window_key] = TemplateMiner()
|
|
106
111
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
# Templates are read once the window is fed, after later lines have widened their slots.
|
|
111
|
-
for entry, cluster in zip(window_entries, clusters, strict=True):
|
|
112
|
-
patterns.append(
|
|
113
|
-
{
|
|
114
|
-
"template": cluster.get_template(),
|
|
115
|
-
"window": window_key,
|
|
116
|
-
"count": 1,
|
|
117
|
-
"example": entry.raw_line,
|
|
118
|
-
}
|
|
119
|
-
)
|
|
112
|
+
for pattern in self._summarise(self.miners_by_window[window_key], window_entries):
|
|
113
|
+
patterns.append({**pattern, "window": window_key})
|
|
120
114
|
|
|
121
115
|
return patterns
|
|
122
116
|
|
|
123
117
|
def _extract_timeless_patterns(self, entries: list[LogEntry]) -> list[dict]:
|
|
124
118
|
"""Extract patterns without timestamps."""
|
|
125
|
-
|
|
126
|
-
|
|
119
|
+
return self._summarise(TemplateMiner(), entries)
|
|
120
|
+
|
|
121
|
+
@staticmethod
|
|
122
|
+
def _summarise(miner: TemplateMiner, entries: list[LogEntry]) -> list[dict]:
|
|
123
|
+
"""One dict per template: its final template, how many entries share it, and the first of them."""
|
|
124
|
+
by_cluster: dict[int, dict] = {}
|
|
125
|
+
clusters = {}
|
|
126
|
+
for entry in entries:
|
|
127
|
+
cluster = miner.add_log_message(entry.raw_line)
|
|
128
|
+
clusters[cluster.cluster_id] = cluster
|
|
129
|
+
summary = by_cluster.setdefault(cluster.cluster_id, {"count": 0, "example": entry.raw_line})
|
|
130
|
+
summary["count"] += 1
|
|
127
131
|
|
|
128
|
-
# Templates are read once
|
|
132
|
+
# Templates are read once the feed ends, after later lines have widened their slots.
|
|
129
133
|
return [
|
|
130
|
-
{
|
|
131
|
-
"template": cluster.get_template(),
|
|
132
|
-
"example": entry.raw_line,
|
|
133
|
-
}
|
|
134
|
-
for entry, cluster in zip(entries, clusters, strict=True)
|
|
134
|
+
{"template": clusters[cluster_id].get_template(), **summary} for cluster_id, summary in by_cluster.items()
|
|
135
135
|
]
|
|
136
136
|
|
|
137
137
|
def _analyze_distribution(self, entries: list[LogEntry]) -> dict:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|