llm-optimizer-processor 0.1.1

Data processing and transformation pipeline
Documentation
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# Time-Series Normalization Integration

This document describes the integration of time-series normalization into the Stream Processor configuration and pipeline.

## Overview

Time-series normalization has been integrated into the processor crate to provide:
- Configurable time-series data alignment to fixed intervals
- Multiple fill strategies for missing data points
- Out-of-order event handling with buffering
- Outlier detection and removal
- Seamless integration with existing pipeline operators

## Architecture

### Configuration Layer

The normalization system is configured through the `NormalizationConfig` struct, which is part of the main `ProcessorConfig`:

```rust
pub struct ProcessorConfig {
    pub window: WindowConfig,
    pub watermark: WatermarkConfig,
    pub state: StateConfig,
    pub aggregation: AggregationConfig,
    pub deduplication: DeduplicationConfig,
    pub normalization: NormalizationConfig,  // NEW
    // ... other fields
}
```

### NormalizationConfig Structure

```rust
pub struct NormalizationConfig {
    pub enabled: bool,
    pub interval: Duration,
    pub fill_strategy: FillStrategy,
    pub alignment: AlignmentStrategy,
    pub buffer_size: usize,
    pub interpolation_max_gap: Duration,
    pub drop_outliers: bool,
    pub outlier_threshold: f64,
    pub emit_metrics: bool,
}
```

#### Fill Strategies

The system supports multiple strategies for handling missing data:

- **Zero**: Fill with zero value
- **ForwardFill**: Use last known value (default)
- **BackwardFill**: Use next known value
- **LinearInterpolation**: Interpolate linearly between known values
- **Drop**: Skip missing intervals
- **Constant**: Fill with a constant value
- **Mean**: Use mean of surrounding values

#### Alignment Strategies

Timestamps can be aligned to interval boundaries using:

- **Start**: Align to start of interval (default)
- **End**: Align to end of interval
- **Center**: Align to center of interval
- **Nearest**: Round to nearest interval boundary

### Pipeline Integration

The `NormalizationOperator` implements the `StreamOperator` trait and can be inserted into the processing pipeline:

```rust
pub struct NormalizationOperator {
    name: String,
    config: NormalizationConfig,
    buffer: Arc<RwLock<BTreeMap<i64, Vec<f64>>>>,
    last_emitted: Arc<RwLock<Option<DateTime<Utc>>>>,
    stats: Arc<RwLock<NormalizationStats>>,
    recent_values: Arc<RwLock<VecDeque<f64>>>,
}
```

#### Processing Flow

1. **Event Reception**: Timestamped events enter the operator
2. **Outlier Detection**: Events are checked for outliers using z-score
3. **Timestamp Alignment**: Event timestamps are aligned to configured intervals
4. **Buffering**: Events are buffered to handle out-of-order arrivals
5. **Gap Filling**: Missing intervals are filled using the configured strategy
6. **Emission**: Aligned events are emitted at consistent intervals

## Usage

### Basic Configuration

```rust
use processor::config::{NormalizationConfig, FillStrategy, AlignmentStrategy};
use std::time::Duration;

// Create normalization config
let norm_config = NormalizationConfig::new()
    .enabled()
    .with_interval(Duration::from_secs(5))
    .with_fill_strategy(FillStrategy::LinearInterpolation)
    .with_alignment(AlignmentStrategy::Start)
    .with_buffer_size(1000);
```

### Pipeline Builder Integration

```rust
use processor::pipeline::StreamPipelineBuilder;
use std::time::Duration;

let pipeline = StreamPipelineBuilder::new()
    .with_name("normalized-pipeline")
    .with_normalization(true, Duration::from_secs(5))
    .with_fill_strategy(FillStrategy::LinearInterpolation)
    .with_alignment_strategy(AlignmentStrategy::Start)
    .with_normalization_buffer_size(2000)
    .with_interpolation_max_gap(Duration::from_secs(15))
    .with_normalization_outlier_detection(3.0)
    .build()?;
```

### Using NormalizationConfig Directly

```rust
let norm_config = NormalizationConfig::new()
    .enabled()
    .with_interval(Duration::from_secs(5))
    .with_fill_strategy(FillStrategy::ForwardFill)
    .with_alignment(AlignmentStrategy::End)
    .with_outlier_detection(2.5);

let pipeline = StreamPipelineBuilder::new()
    .with_name("pipeline")
    .with_normalization_config(norm_config)
    .build()?;
```

### Creating a Normalization Operator

```rust
use processor::pipeline::NormalizationOperator;

let config = NormalizationConfig::new()
    .enabled()
    .with_interval(Duration::from_secs(5));

let operator = NormalizationOperator::new("normalization", config);

// Add to pipeline
pipeline.add_operator(operator);
```

## Builder Methods

The `StreamPipelineBuilder` provides the following normalization-related methods:

### Basic Configuration

- `with_normalization(enabled: bool, interval: Duration)` - Enable normalization with interval
- `with_normalization_config(config: NormalizationConfig)` - Set complete config
- `with_normalization_interval(interval: Duration)` - Set alignment interval

### Strategy Configuration

- `with_fill_strategy(strategy: FillStrategy)` - Set fill strategy
- `with_alignment_strategy(strategy: AlignmentStrategy)` - Set alignment strategy

### Advanced Options

- `with_normalization_buffer_size(size: usize)` - Set buffer size for out-of-order events
- `with_interpolation_max_gap(gap: Duration)` - Set max gap for interpolation
- `with_normalization_outlier_detection(threshold: f64)` - Enable outlier detection

## Statistics

The `NormalizationOperator` tracks the following statistics:

```rust
pub struct NormalizationStats {
    pub events_processed: u64,
    pub events_aligned: u64,
    pub intervals_filled: u64,
    pub outliers_dropped: u64,
    pub out_of_order_events: u64,
    pub events_dropped: u64,
}
```

Access statistics via:

```rust
let stats = operator.stats();
println!("Events processed: {}", stats.events_processed);
println!("Outliers dropped: {}", stats.outliers_dropped);
```

## Configuration Validation

The configuration is automatically validated when building a pipeline:

```rust
impl NormalizationConfig {
    pub fn validate(&self) -> Result<()> {
        // Validates:
        // - interval > 0
        // - buffer_size > 0
        // - interpolation_max_gap > 0
        // - outlier_threshold > 0
        // - interpolation_max_gap >= interval
    }
}
```

## Integration Points

### Before Windowing

Normalization should be applied **before** windowing operations to ensure:
- Consistent event time alignment
- Reduced skew in time-based aggregations
- Proper handling of out-of-order events

### Pipeline Position

Recommended operator order:
1. Deduplication (optional)
2. **Normalization** (if enabled)
3. Key-by (partitioning)
4. Windowing
5. Aggregation

### Example Complete Pipeline

```rust
use processor::pipeline::{StreamPipelineBuilder, NormalizationOperator, DeduplicationOperator};
use processor::config::{
    DeduplicationConfig, NormalizationConfig,
    FillStrategy, AlignmentStrategy
};
use std::time::Duration;

// Configure deduplication
let dedup_config = DeduplicationConfig::new()
    .enabled()
    .with_ttl(Duration::from_secs(3600));

// Configure normalization
let norm_config = NormalizationConfig::new()
    .enabled()
    .with_interval(Duration::from_secs(5))
    .with_fill_strategy(FillStrategy::LinearInterpolation)
    .with_alignment(AlignmentStrategy::Start);

// Build pipeline
let mut pipeline = StreamPipelineBuilder::new()
    .with_name("production-pipeline")
    .with_deduplication_config(dedup_config)
    .with_normalization_config(norm_config)
    .with_tumbling_window(60_000)  // 1-minute windows
    .with_parallelism(8)
    .build()?;

// Add operators in order
pipeline.add_operator(DeduplicationOperator::new("dedup", dedup_config));
pipeline.add_operator(NormalizationOperator::new("norm", norm_config));
// ... add other operators
```

## Event Types

The normalization operator works with `TimestampedEvent`:

```rust
pub struct TimestampedEvent {
    pub timestamp: DateTime<Utc>,
    pub value: f64,
}
```

Events are serialized/deserialized using bincode for efficient processing.

## Outlier Detection

Outlier detection uses z-score method:

1. Maintains a rolling window of recent values (up to 100)
2. Calculates mean and standard deviation
3. Computes z-score: `|value - mean| / std_dev`
4. Drops events where z-score > threshold

Default threshold: 3.0 standard deviations

## Performance Considerations

### Buffer Management

- Buffer size limits memory usage
- Oldest events dropped on overflow
- Configurable via `buffer_size` parameter
- Default: 1000 events

### Gap Filling

- Only fills gaps up to `interpolation_max_gap`
- Linear interpolation most CPU-intensive
- ForwardFill/BackwardFill most efficient
- Drop strategy skips gap filling entirely

### Metrics Emission

- Can be disabled to reduce overhead
- Set `emit_metrics: false` in config

## Testing

Comprehensive tests are included:

- Configuration validation
- Alignment strategy tests
- Fill strategy tests
- Outlier detection
- Buffer overflow handling
- Statistics tracking
- Builder API fluency

Run tests with:

```bash
cargo test --package processor normalization
```

## Backward Compatibility

The integration maintains backward compatibility:

- Normalization disabled by default
- All existing pipelines work unchanged
- Optional configuration field
- No breaking changes to existing APIs

## Example Use Cases

### High-Frequency Metrics

```rust
// Normalize high-frequency metrics to 1-second intervals
let config = NormalizationConfig::new()
    .enabled()
    .with_interval(Duration::from_secs(1))
    .with_fill_strategy(FillStrategy::LinearInterpolation)
    .with_outlier_detection(3.0);
```

### Sparse Data

```rust
// Handle sparse data with forward fill
let config = NormalizationConfig::new()
    .enabled()
    .with_interval(Duration::from_secs(60))
    .with_fill_strategy(FillStrategy::ForwardFill)
    .with_interpolation_max_gap(Duration::from_secs(300));
```

### Real-Time Analytics

```rust
// Real-time with large buffer for out-of-order tolerance
let config = NormalizationConfig::new()
    .enabled()
    .with_interval(Duration::from_secs(5))
    .with_buffer_size(5000)
    .with_fill_strategy(FillStrategy::LinearInterpolation)
    .with_alignment(AlignmentStrategy::Start);
```

## Files Modified

### New Files

- `crates/processor/src/pipeline/normalization_operator.rs` - Normalization operator implementation

### Modified Files

- `crates/processor/src/config.rs` - Added NormalizationConfig, FillStrategy, AlignmentStrategy
- `crates/processor/src/lib.rs` - Exported new types
- `crates/processor/src/pipeline/mod.rs` - Added normalization operator module
- `crates/processor/src/pipeline/builder.rs` - Added builder methods

## Future Enhancements

Potential improvements:

1. **Advanced Interpolation**: Spline, polynomial interpolation
2. **Adaptive Intervals**: Dynamic interval adjustment based on data density
3. **Multi-value Aggregation**: Support for events with multiple metric values
4. **Persistence**: Save/restore operator state for recovery
5. **Metrics Integration**: Deeper integration with existing metrics framework
6. **Custom Fill Functions**: User-defined fill strategies

## References

- Main config: `crates/processor/src/config.rs`
- Operator implementation: `crates/processor/src/pipeline/normalization_operator.rs`
- Builder API: `crates/processor/src/pipeline/builder.rs`
- Tests: Included in each file's test module