1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//! Configuration: `Options` (resolved) and `MinerBuilder`.
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::error::LogdrainError;
use crate::mask::Mask;
/// Resolved, validated miner configuration. Immutable for a miner's lifetime.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Options {
/// Similarity threshold in `[0.0, 1.0]` for joining an existing cluster.
pub sim_threshold: f64,
/// Prefix-tree depth (`>= 2`). Token levels below the shard root = `depth - 2`.
pub depth: usize,
/// Max clusters kept per leaf bucket before LRU eviction.
pub max_clusters_per_leaf: usize,
/// Replace pure-numeric tokens with the wildcard during tree descent.
pub parametrize_numeric_tokens: bool,
/// Placeholder string used for generalized positions.
pub wildcard: Arc<str>,
/// Characters that split a token into path sub-tokens (e.g. `'/'`).
pub path_delimiters: Vec<char>,
/// Path delimiters used when tokenizing the first line in `first_line_only` mode.
pub first_line_path_delimiters: Vec<char>,
/// Cluster on the first line only; the remainder is kept verbatim as a suffix.
pub first_line_only: bool,
/// Pre-tokenization masks. Not serialized (regex is not serializable; `restore`
/// does not re-apply options).
#[serde(skip)]
pub masks: Vec<Mask>,
}
impl Default for Options {
fn default() -> Self {
Options {
sim_threshold: 0.4,
depth: 4,
max_clusters_per_leaf: 100,
parametrize_numeric_tokens: true,
wildcard: Arc::from("<*>"),
path_delimiters: Vec::new(),
first_line_path_delimiters: Vec::new(),
first_line_only: false,
masks: Vec::new(),
}
}
}
impl Options {
/// Number of token levels below the token-count shard root.
pub(crate) fn prefix_len(&self) -> usize {
self.depth - 2
}
/// The delimiter set used for tokenization: in `first_line_only` mode the
/// first-line set is preferred (falling back to `path_delimiters` if empty),
/// otherwise `path_delimiters`.
pub(crate) fn active_path_delimiters(&self) -> &[char] {
if self.first_line_only && !self.first_line_path_delimiters.is_empty() {
&self.first_line_path_delimiters
} else {
&self.path_delimiters
}
}
}
/// Fluent builder for [`Options`] / [`crate::Miner`].
#[derive(Debug, Clone, Default)]
pub struct MinerBuilder {
opts: Options,
}
impl MinerBuilder {
/// Start from defaults.
pub fn new() -> Self {
Self::default()
}
/// Set the similarity threshold (validated to `[0.0, 1.0]` at build time).
pub fn sim_threshold(mut self, v: f64) -> Self {
self.opts.sim_threshold = v;
self
}
/// Set the prefix-tree depth (validated `>= 2` at build time).
pub fn depth(mut self, v: usize) -> Self {
self.opts.depth = v;
self
}
/// Set the per-leaf cluster cap (validated `>= 1`).
pub fn max_clusters_per_leaf(mut self, v: usize) -> Self {
self.opts.max_clusters_per_leaf = v;
self
}
/// Toggle numeric-token parametrization.
pub fn parametrize_numeric_tokens(mut self, v: bool) -> Self {
self.opts.parametrize_numeric_tokens = v;
self
}
/// Set the wildcard placeholder string.
pub fn wildcard(mut self, v: &str) -> Self {
self.opts.wildcard = Arc::from(v);
self
}
/// Set the path delimiter characters (e.g. `&['/']`).
pub fn path_delimiters(mut self, delims: &[char]) -> Self {
self.opts.path_delimiters = delims.to_vec();
self
}
/// Set the first-line path delimiter characters (used in `first_line_only` mode).
pub fn first_line_path_delimiters(mut self, delims: &[char]) -> Self {
self.opts.first_line_path_delimiters = delims.to_vec();
self
}
/// Cluster each record by its **first line only**, keeping the remainder as a
/// per-cluster suffix (taken from the first occurrence).
///
/// Off (default): the whole record - every line - is tokenized and clustered.
/// On: the record is split at the first newline; only the first line drives
/// tokenization, matching, and the template. The rest is stored as the suffix,
/// readable via [`Cluster::suffix`](crate::Cluster::suffix), and does not affect
/// clustering.
///
/// This is how stack traces collapse: the frames differ every time, but the
/// first line (exception type + message) is stable. Only meaningful for records
/// that contain newlines. Masks still apply to the whole record, suffix included.
pub fn first_line_only(mut self, v: bool) -> Self {
self.opts.first_line_only = v;
self
}
/// Set the pre-tokenization masks (e.g. `[builtin_masks::uuid(), ...]`).
pub fn masks(mut self, masks: impl IntoIterator<Item = Mask>) -> Self {
self.opts.masks = masks.into_iter().collect();
self
}
/// Validate and produce resolved [`Options`].
pub fn build_options(self) -> Result<Options, LogdrainError> {
let o = &self.opts;
if o.depth < 2 {
return Err(LogdrainError::InvalidConfig(format!(
"depth must be >= 2, got {}",
o.depth
)));
}
if !(0.0..=1.0).contains(&o.sim_threshold) {
return Err(LogdrainError::InvalidConfig(format!(
"sim_threshold must be in [0.0, 1.0], got {}",
o.sim_threshold
)));
}
if o.max_clusters_per_leaf == 0 {
return Err(LogdrainError::InvalidConfig(
"max_clusters_per_leaf must be >= 1".into(),
));
}
Ok(self.opts)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults() {
let o = Options::default();
assert_eq!(o.sim_threshold, 0.4);
assert_eq!(o.depth, 4);
assert_eq!(o.max_clusters_per_leaf, 100);
assert!(o.parametrize_numeric_tokens);
assert_eq!(&*o.wildcard, "<*>");
assert!(o.path_delimiters.is_empty());
assert!(o.first_line_path_delimiters.is_empty());
assert!(!o.first_line_only);
assert!(o.masks.is_empty());
}
#[test]
fn builder_sets_all_fields() {
let o = MinerBuilder::new()
.sim_threshold(0.6)
.depth(5)
.max_clusters_per_leaf(50)
.parametrize_numeric_tokens(false)
.wildcard("<?>")
.path_delimiters(&['/'])
.first_line_path_delimiters(&['/', ':'])
.first_line_only(true)
.masks([crate::builtin_masks::uuid()])
.build_options()
.unwrap();
assert_eq!(o.sim_threshold, 0.6);
assert_eq!(o.depth, 5);
assert_eq!(o.max_clusters_per_leaf, 50);
assert!(!o.parametrize_numeric_tokens);
assert_eq!(&*o.wildcard, "<?>");
assert_eq!(o.path_delimiters, vec!['/']);
assert_eq!(o.first_line_path_delimiters, vec!['/', ':']);
assert!(o.first_line_only);
assert_eq!(o.masks.len(), 1);
}
#[test]
fn rejects_invalid_config() {
assert!(MinerBuilder::new().depth(1).build_options().is_err());
assert!(MinerBuilder::new()
.sim_threshold(1.5)
.build_options()
.is_err());
assert!(MinerBuilder::new()
.sim_threshold(-0.1)
.build_options()
.is_err());
assert!(MinerBuilder::new()
.max_clusters_per_leaf(0)
.build_options()
.is_err());
// depth == 2 is the minimum valid value and must build.
assert!(MinerBuilder::new().depth(2).build_options().is_ok());
}
#[test]
fn active_delimiters_prefer_first_line_when_enabled() {
// first_line_only + non-empty first-line set -> first-line set.
let o = MinerBuilder::new()
.path_delimiters(&['/'])
.first_line_path_delimiters(&[':'])
.first_line_only(true)
.build_options()
.unwrap();
assert_eq!(o.active_path_delimiters(), &[':']);
// first_line_only but empty first-line set -> fall back to path_delimiters.
let o2 = MinerBuilder::new()
.path_delimiters(&['/'])
.first_line_only(true)
.build_options()
.unwrap();
assert_eq!(o2.active_path_delimiters(), &['/']);
// not first_line_only -> path_delimiters regardless.
let o3 = MinerBuilder::new()
.path_delimiters(&['/'])
.first_line_path_delimiters(&[':'])
.build_options()
.unwrap();
assert_eq!(o3.active_path_delimiters(), &['/']);
}
}