converge-analytics 3.7.6

Analytics and ML pipeline for Converge agents
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
412
413
414
415
416
417
418
419
420
421
422
423
//! Negative tests: analytics packs reject invalid input and handle edge cases.

use converge_analytics::packs::{
    AnomalyDetectionPack, ClassificationPack, DescriptiveStatsPack, ForecastingPack, RankingPack,
    RegressionPack, SegmentationPack, SimilarityPack, TrendDetectionPack,
};
use converge_kernel::{Budget, ContextKey, ContextState, Engine};
use converge_pack::Pack;
use converge_pack::PackSuggestor;

fn budget() -> Budget {
    Budget {
        max_cycles: 5,
        max_facts: 100,
    }
}

// ── Validation rejects invalid inputs at the Pack level ──

#[test]
fn anomaly_detection_rejects_empty_values() {
    let input = serde_json::json!({"values": [], "threshold": 2.0});
    assert!(AnomalyDetectionPack.validate_inputs(&input).is_err());
}

#[test]
fn anomaly_detection_rejects_negative_threshold() {
    let input = serde_json::json!({"values": [1.0, 2.0], "threshold": -1.0});
    assert!(AnomalyDetectionPack.validate_inputs(&input).is_err());
}

#[test]
fn anomaly_detection_rejects_mismatched_labels() {
    let input = serde_json::json!({
        "values": [1.0, 2.0, 3.0],
        "threshold": 2.0,
        "labels": ["a", "b"]
    });
    assert!(AnomalyDetectionPack.validate_inputs(&input).is_err());
}

#[test]
fn segmentation_rejects_empty_records() {
    let input = serde_json::json!({"records": [], "k": 2});
    assert!(SegmentationPack.validate_inputs(&input).is_err());
}

#[test]
fn segmentation_rejects_k_zero() {
    let input = serde_json::json!({"records": [[1.0, 2.0]], "k": 0});
    assert!(SegmentationPack.validate_inputs(&input).is_err());
}

#[test]
fn segmentation_rejects_k_exceeds_records() {
    let input = serde_json::json!({"records": [[1.0], [2.0]], "k": 5});
    assert!(SegmentationPack.validate_inputs(&input).is_err());
}

#[test]
fn segmentation_rejects_inconsistent_dimensions() {
    let input = serde_json::json!({"records": [[1.0, 2.0], [3.0]], "k": 2});
    assert!(SegmentationPack.validate_inputs(&input).is_err());
}

#[test]
fn ranking_rejects_empty_items() {
    let input = serde_json::json!({
        "items": [],
        "weights": [0.5],
        "higher_is_better": [true]
    });
    assert!(RankingPack.validate_inputs(&input).is_err());
}

#[test]
fn ranking_rejects_negative_weight() {
    let input = serde_json::json!({
        "items": [{"id": "a", "scores": [1.0]}],
        "weights": [-1.0],
        "higher_is_better": [true]
    });
    assert!(RankingPack.validate_inputs(&input).is_err());
}

#[test]
fn ranking_rejects_dimension_mismatch() {
    let input = serde_json::json!({
        "items": [{"id": "a", "scores": [1.0, 2.0]}],
        "weights": [0.5],
        "higher_is_better": [true]
    });
    assert!(RankingPack.validate_inputs(&input).is_err());
}

#[test]
fn forecasting_rejects_single_value() {
    let input = serde_json::json!({"values": [1.0], "horizon": 3, "alpha": 0.3});
    assert!(ForecastingPack.validate_inputs(&input).is_err());
}

#[test]
fn forecasting_rejects_zero_horizon() {
    let input = serde_json::json!({"values": [1.0, 2.0, 3.0], "horizon": 0, "alpha": 0.3});
    assert!(ForecastingPack.validate_inputs(&input).is_err());
}

#[test]
fn forecasting_rejects_alpha_out_of_range() {
    let input = serde_json::json!({"values": [1.0, 2.0, 3.0], "horizon": 1, "alpha": 1.5});
    assert!(ForecastingPack.validate_inputs(&input).is_err());
}

#[test]
fn classification_rejects_empty_records() {
    let input = serde_json::json!({
        "records": [],
        "weights": [1.0],
        "bias": 0.0,
        "threshold": 0.5
    });
    assert!(ClassificationPack.validate_inputs(&input).is_err());
}

#[test]
fn classification_rejects_threshold_out_of_range() {
    let input = serde_json::json!({
        "records": [[1.0]],
        "weights": [1.0],
        "bias": 0.0,
        "threshold": 2.0
    });
    assert!(ClassificationPack.validate_inputs(&input).is_err());
}

#[test]
fn regression_rejects_dimension_mismatch() {
    let input = serde_json::json!({
        "records": [[1.0, 2.0], [3.0]],
        "weights": [1.0, 2.0],
        "bias": 0.0
    });
    assert!(RegressionPack.validate_inputs(&input).is_err());
}

#[test]
fn similarity_rejects_single_item() {
    let input = serde_json::json!({
        "items": [{"id": "a", "features": [1.0]}],
        "metric": "cosine"
    });
    assert!(SimilarityPack.validate_inputs(&input).is_err());
}

#[test]
fn similarity_rejects_zero_top_k() {
    let input = serde_json::json!({
        "items": [
            {"id": "a", "features": [1.0]},
            {"id": "b", "features": [2.0]}
        ],
        "metric": "cosine",
        "top_k": 0
    });
    assert!(SimilarityPack.validate_inputs(&input).is_err());
}

#[test]
fn trend_detection_rejects_too_few_values() {
    let input = serde_json::json!({"values": [1.0, 2.0], "window": 3});
    assert!(TrendDetectionPack.validate_inputs(&input).is_err());
}

#[test]
fn trend_detection_rejects_window_exceeds_values() {
    let input = serde_json::json!({"values": [1.0, 2.0, 3.0], "window": 5});
    assert!(TrendDetectionPack.validate_inputs(&input).is_err());
}

#[test]
fn descriptive_stats_rejects_empty_values() {
    let input = serde_json::json!({"values": []});
    assert!(DescriptiveStatsPack.validate_inputs(&input).is_err());
}

#[test]
fn descriptive_stats_rejects_invalid_percentile() {
    let input = serde_json::json!({"values": [1.0, 2.0], "percentiles": [150.0]});
    assert!(DescriptiveStatsPack.validate_inputs(&input).is_err());
}

// ── Engine-level: invalid JSON seed → pack returns empty effect, engine converges ──

async fn run_with_garbage<P: Pack + 'static>(pack: P) {
    let mut engine = Engine::with_budget(budget());
    engine.register_suggestor(PackSuggestor::new(
        pack,
        ContextKey::Seeds,
        ContextKey::Strategies,
    ));
    let mut ctx = ContextState::new();
    let _ = ctx.add_input(ContextKey::Seeds, "garbage", "not valid json {{{");
    let result = engine.run(ctx).await.expect("should converge gracefully");
    assert!(result.converged);
    // No strategies produced from invalid input
    assert!(result.context.get(ContextKey::Strategies).is_empty());
}

#[tokio::test]
async fn anomaly_detection_garbage_input_converges_empty() {
    run_with_garbage(AnomalyDetectionPack).await;
}

#[tokio::test]
async fn segmentation_garbage_input_converges_empty() {
    run_with_garbage(SegmentationPack).await;
}

#[tokio::test]
async fn ranking_garbage_input_converges_empty() {
    run_with_garbage(RankingPack).await;
}

#[tokio::test]
async fn forecasting_garbage_input_converges_empty() {
    run_with_garbage(ForecastingPack).await;
}

#[tokio::test]
async fn classification_garbage_input_converges_empty() {
    run_with_garbage(ClassificationPack).await;
}

#[tokio::test]
async fn regression_garbage_input_converges_empty() {
    run_with_garbage(RegressionPack).await;
}

#[tokio::test]
async fn similarity_garbage_input_converges_empty() {
    run_with_garbage(SimilarityPack).await;
}

#[tokio::test]
async fn trend_detection_garbage_input_converges_empty() {
    run_with_garbage(TrendDetectionPack).await;
}

#[tokio::test]
async fn descriptive_stats_garbage_input_converges_empty() {
    run_with_garbage(DescriptiveStatsPack).await;
}

// ── Idempotency: running same input twice yields same output (no duplication) ──

async fn run_idempotent<P: Pack + 'static>(pack: P, input: serde_json::Value) {
    let mut engine = Engine::with_budget(Budget {
        max_cycles: 10,
        max_facts: 100,
    });
    engine.register_suggestor(PackSuggestor::new(
        pack,
        ContextKey::Seeds,
        ContextKey::Strategies,
    ));
    let mut ctx = ContextState::new();
    let _ = ctx.add_input(ContextKey::Seeds, "input-1", input.to_string());
    let result = engine.run(ctx).await.expect("should converge");

    // Should converge quickly (2 cycles: seed present → solve → output present → stop)
    assert!(result.converged);
    assert!(
        result.cycles <= 3,
        "took {} cycles, expected <= 3",
        result.cycles
    );
    // Exactly one strategy produced (no duplicates from re-running)
    assert_eq!(result.context.get(ContextKey::Strategies).len(), 1);
}

#[tokio::test]
async fn anomaly_detection_idempotent() {
    run_idempotent(
        AnomalyDetectionPack,
        serde_json::json!({"values": [1.0, 2.0, 3.0, 100.0], "threshold": 2.0}),
    )
    .await;
}

#[tokio::test]
async fn segmentation_idempotent() {
    run_idempotent(
        SegmentationPack,
        serde_json::json!({"records": [[1.0], [2.0], [10.0]], "k": 2}),
    )
    .await;
}

#[tokio::test]
async fn ranking_idempotent() {
    run_idempotent(
        RankingPack,
        serde_json::json!({
            "items": [{"id": "a", "scores": [1.0]}, {"id": "b", "scores": [2.0]}],
            "weights": [1.0],
            "higher_is_better": [true]
        }),
    )
    .await;
}

#[tokio::test]
async fn forecasting_idempotent() {
    run_idempotent(
        ForecastingPack,
        serde_json::json!({"values": [1.0, 2.0, 3.0, 4.0], "horizon": 2, "alpha": 0.3}),
    )
    .await;
}

#[tokio::test]
async fn classification_idempotent() {
    run_idempotent(
        ClassificationPack,
        serde_json::json!({
            "records": [[1.0], [-1.0]],
            "weights": [1.0],
            "bias": 0.0,
            "threshold": 0.5
        }),
    )
    .await;
}

#[tokio::test]
async fn regression_idempotent() {
    run_idempotent(
        RegressionPack,
        serde_json::json!({"records": [[1.0], [2.0]], "weights": [5.0], "bias": 1.0}),
    )
    .await;
}

#[tokio::test]
async fn similarity_idempotent() {
    run_idempotent(
        SimilarityPack,
        serde_json::json!({
            "items": [
                {"id": "a", "features": [1.0, 0.0]},
                {"id": "b", "features": [0.0, 1.0]}
            ],
            "metric": "cosine"
        }),
    )
    .await;
}

#[tokio::test]
async fn trend_detection_idempotent() {
    run_idempotent(
        TrendDetectionPack,
        serde_json::json!({"values": [1.0, 2.0, 3.0, 4.0, 5.0], "window": 3}),
    )
    .await;
}

#[tokio::test]
async fn descriptive_stats_idempotent() {
    run_idempotent(
        DescriptiveStatsPack,
        serde_json::json!({"values": [10.0, 20.0, 30.0]}),
    )
    .await;
}

// ── Constant data: anomaly detection handles zero std_dev gracefully ──

#[tokio::test]
async fn anomaly_detection_constant_data_produces_no_anomalies() {
    let mut engine = Engine::with_budget(budget());
    engine.register_suggestor(PackSuggestor::new(
        AnomalyDetectionPack,
        ContextKey::Seeds,
        ContextKey::Strategies,
    ));
    let mut ctx = ContextState::new();
    let _ = ctx.add_input(
        ContextKey::Seeds,
        "input-1",
        serde_json::json!({"values": [5.0, 5.0, 5.0, 5.0, 5.0], "threshold": 2.0}).to_string(),
    );
    let result = engine.run(ctx).await.expect("should converge");
    assert!(result.converged);
    let strategies = result.context.get(ContextKey::Strategies);
    assert_eq!(strategies.len(), 1);
    // Zero std_dev → no anomalies detected
    assert!(strategies[0].content.contains("\"anomaly_count\":0"));
}

// ── Single-element edge cases ──

#[tokio::test]
async fn descriptive_stats_single_value() {
    let mut engine = Engine::with_budget(budget());
    engine.register_suggestor(PackSuggestor::new(
        DescriptiveStatsPack,
        ContextKey::Seeds,
        ContextKey::Strategies,
    ));
    let mut ctx = ContextState::new();
    let _ = ctx.add_input(
        ContextKey::Seeds,
        "input-1",
        serde_json::json!({"values": [42.0]}).to_string(),
    );
    let result = engine.run(ctx).await.expect("should converge");
    assert!(result.converged);
    let content = &result.context.get(ContextKey::Strategies)[0].content;
    // Single value: mean = median = 42, std = 0
    assert!(content.contains("42"));
    assert!(content.contains("\"std_dev\":0"));
}