meld 0.1.1

Deterministic filesystem state management using Merkle trees
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! Integration tests for Frame Generation Queue
//!
//! Tests cover:
//! - Priority queue ordering
//! - Enqueue/dequeue operations
//! - Rate limiting
//! - Retry logic
//! - Concurrent access
//! - Queue size limits
//! - Worker lifecycle

use meld::api::ContextApi;
use meld::error::ApiError;
use meld::context::frame::storage::FrameStorage;
use meld::context::queue::{
    FrameGenerationQueue, GenerationConfig, GenerationRequest, GenerationRequestOptions, Priority,
    QueueEventContext,
};
use meld::heads::HeadIndex;
use meld::store::persistence::SledNodeRecordStore;
use meld::telemetry::ProgressRuntime;
use meld::types::Hash;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tempfile::TempDir;

fn create_test_api() -> (ContextApi, TempDir) {
    let temp_dir = TempDir::new().unwrap();
    let store_path = temp_dir.path().join("store");
    let node_store = Arc::new(SledNodeRecordStore::new(&store_path).unwrap());
    let frame_storage_path = temp_dir.path().join("frames");
    std::fs::create_dir_all(&frame_storage_path).unwrap();
    let frame_storage = Arc::new(FrameStorage::new(&frame_storage_path).unwrap());
    let head_index = Arc::new(parking_lot::RwLock::new(HeadIndex::new()));
    let agent_registry = Arc::new(parking_lot::RwLock::new(meld::agent::AgentRegistry::new()));
    let mut provider_registry = meld::provider::ProviderRegistry::new();
    // Add a test provider
    let mut config = meld::config::MerkleConfig::default();
    config.providers.insert(
        "test-provider".to_string(),
        meld::config::ProviderConfig {
            provider_name: Some("test-provider".to_string()),
            provider_type: meld::config::ProviderType::Ollama,
            model: "test-model".to_string(),
            api_key: None,
            endpoint: None,
            default_options: meld::provider::CompletionOptions::default(),
        },
    );
    provider_registry.load_from_config(&config).unwrap();
    let provider_registry = Arc::new(parking_lot::RwLock::new(provider_registry));
    let lock_manager = Arc::new(meld::concurrency::NodeLockManager::new());

    let api = ContextApi::new(
        node_store,
        frame_storage,
        head_index,
        agent_registry,
        provider_registry,
        lock_manager,
    );

    (api, temp_dir)
}

fn create_test_queue() -> (FrameGenerationQueue, TempDir) {
    let (api, temp_dir) = create_test_api();
    let api = Arc::new(api);
    let config = GenerationConfig::default();
    let queue = FrameGenerationQueue::new(api, config);
    (queue, temp_dir)
}

fn create_test_queue_with_config(config: GenerationConfig) -> (FrameGenerationQueue, TempDir) {
    let (api, temp_dir) = create_test_api();
    let api = Arc::new(api);
    let queue = FrameGenerationQueue::new(api, config);
    (queue, temp_dir)
}

#[tokio::test]
async fn test_priority_ordering() {
    let (queue, _temp_dir) = create_test_queue();

    // Enqueue requests with different priorities
    let node1 = Hash::from([1u8; 32]);
    let node2 = Hash::from([2u8; 32]);
    let node3 = Hash::from([3u8; 32]);
    let node4 = Hash::from([4u8; 32]);

    queue
        .enqueue(
            node1,
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Low,
        )
        .await
        .unwrap();
    queue
        .enqueue(
            node2,
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::High,
        )
        .await
        .unwrap();
    queue
        .enqueue(
            node3,
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Urgent,
        )
        .await
        .unwrap();
    queue
        .enqueue(
            node4,
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Normal,
        )
        .await
        .unwrap();

    // Verify ordering by checking stats and testing dequeue behavior
    // Since we can't directly access the internal queue, we verify through
    // the public API. The priority ordering is tested through the Ord implementation.
    let stats = queue.stats();
    assert_eq!(stats.pending, 4);
}

#[tokio::test]
async fn test_enqueue_dequeue() {
    let (queue, _temp_dir) = create_test_queue();

    let node_id = Hash::from([1u8; 32]);
    queue
        .enqueue(
            node_id,
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Normal,
        )
        .await
        .unwrap();

    let stats = queue.stats();
    assert_eq!(stats.pending, 1);
    assert_eq!(stats.processing, 0);
    assert_eq!(stats.completed, 0);
    assert_eq!(stats.failed, 0);
}

#[tokio::test]
async fn test_enqueue_deduplicates_pending_identity() {
    let (queue, _temp_dir) = create_test_queue();
    let node_id = Hash::from([9u8; 32]);

    let first = queue
        .enqueue(
            node_id,
            "agent1".to_string(),
            "test-provider".to_string(),
            Some("context-agent1".to_string()),
            Priority::Normal,
        )
        .await
        .unwrap();

    let second = queue
        .enqueue(
            node_id,
            "agent1".to_string(),
            "test-provider".to_string(),
            Some("context-agent1".to_string()),
            Priority::Urgent,
        )
        .await
        .unwrap();

    assert_eq!(first, second);
    assert_eq!(queue.stats().pending, 1);
}

#[tokio::test]
async fn test_enqueue_and_wait_deduplicates_pending_request() {
    let (queue, _temp_dir) = create_test_queue();
    let node_id = Hash::from([11u8; 32]);

    queue
        .enqueue(
            node_id,
            "agent1".to_string(),
            "test-provider".to_string(),
            Some("context-agent1".to_string()),
            Priority::Normal,
        )
        .await
        .unwrap();

    let result = queue
        .enqueue_and_wait(
            node_id,
            "agent1".to_string(),
            "test-provider".to_string(),
            Some("context-agent1".to_string()),
            Priority::Urgent,
            Some(Duration::from_millis(20)),
        )
        .await;

    assert!(result.is_err());
    assert!(matches!(result.unwrap_err(), ApiError::ConfigError(_)));
    assert_eq!(queue.stats().pending, 1);
}

#[tokio::test]
async fn test_enqueue_deduplicates_during_retry_backoff_window() {
    let mut config = GenerationConfig::default();
    config.max_retry_attempts = 1;
    config.retry_delay_ms = 500;
    let (queue, _temp_dir) = create_test_queue_with_config(config);
    queue.start().unwrap();

    let node_id = Hash::from([77u8; 32]);
    let first = queue
        .enqueue(
            node_id,
            "missing-agent".to_string(),
            "test-provider".to_string(),
            Some("context-missing-agent".to_string()),
            Priority::Normal,
        )
        .await
        .unwrap();

    let deadline = Instant::now() + Duration::from_secs(2);
    loop {
        let stats = queue.stats();
        if stats.pending == 0 && stats.processing == 0 {
            break;
        }
        assert!(
            Instant::now() < deadline,
            "request did not enter retry backoff window in time"
        );
        tokio::time::sleep(Duration::from_millis(10)).await;
    }

    let second = queue
        .enqueue(
            node_id,
            "missing-agent".to_string(),
            "test-provider".to_string(),
            Some("context-missing-agent".to_string()),
            Priority::High,
        )
        .await
        .unwrap();

    assert_eq!(first, second);
    assert_eq!(queue.stats().pending, 0);

    queue.stop().await.unwrap();
}

#[tokio::test]
async fn test_queue_size_limit() {
    let mut config = GenerationConfig::default();
    config.max_queue_size = 3;
    let (queue, _temp_dir) = create_test_queue_with_config(config);

    // Fill queue to capacity
    for i in 0..3 {
        let node_id = Hash::from([i as u8; 32]);
        queue
            .enqueue(
                node_id,
                "agent1".to_string(),
                "test-provider".to_string(),
                None,
                Priority::Normal,
            )
            .await
            .unwrap();
    }

    // Next enqueue should fail
    let node_id = Hash::from([4u8; 32]);
    let result = queue
        .enqueue(
            node_id,
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Normal,
        )
        .await;
    assert!(result.is_err());
    assert!(matches!(result.unwrap_err(), ApiError::ConfigError(_)));

    let stats = queue.stats();
    assert_eq!(stats.pending, 3);
}

#[tokio::test]
async fn test_batch_enqueue() {
    let (queue, _temp_dir) = create_test_queue();

    let requests = vec![
        (
            Hash::from([1u8; 32]),
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Normal,
        ),
        (
            Hash::from([2u8; 32]),
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::High,
        ),
        (
            Hash::from([3u8; 32]),
            "agent2".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Urgent,
        ),
    ];

    queue.enqueue_batch(requests).await.unwrap();

    let stats = queue.stats();
    assert_eq!(stats.pending, 3);
}

#[tokio::test]
async fn test_batch_enqueue_size_limit() {
    let mut config = GenerationConfig::default();
    config.max_queue_size = 2;
    let (queue, _temp_dir) = create_test_queue_with_config(config);

    // Try to enqueue batch that exceeds limit
    let requests = vec![
        (
            Hash::from([1u8; 32]),
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Normal,
        ),
        (
            Hash::from([2u8; 32]),
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Normal,
        ),
        (
            Hash::from([3u8; 32]),
            "agent1".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Normal,
        ),
    ];

    let result = queue.enqueue_batch(requests).await;
    assert!(result.is_err());
    assert!(matches!(result.unwrap_err(), ApiError::ConfigError(_)));
}

#[tokio::test]
async fn test_generation_request_ordering() {
    // Test that GenerationRequest implements Ord correctly
    let now = Instant::now();

    use meld::context::queue::RequestId;
    let req1 = GenerationRequest {
        request_id: RequestId::next(),
        node_id: Hash::from([1u8; 32]),
        agent_id: "agent1".to_string(),
        provider_name: "test-provider".to_string(),
        frame_type: "test".to_string(),
        priority: Priority::High,
        retry_count: 0,
        created_at: now,
        completion_tx: None,
        options: GenerationRequestOptions::default(),
    };

    let req2 = GenerationRequest {
        request_id: RequestId::next(),
        node_id: Hash::from([2u8; 32]),
        agent_id: "agent1".to_string(),
        provider_name: "test-provider".to_string(),
        frame_type: "test".to_string(),
        priority: Priority::Low,
        retry_count: 0,
        created_at: now,
        completion_tx: None,
        options: GenerationRequestOptions::default(),
    };

    // Higher priority should be greater
    assert!(req1 > req2);

    // Same priority, older should be greater (processed first)
    let req3 = GenerationRequest {
        request_id: RequestId::next(),
        node_id: Hash::from([3u8; 32]),
        agent_id: "agent1".to_string(),
        provider_name: "test-provider".to_string(),
        frame_type: "test".to_string(),
        priority: Priority::Normal,
        retry_count: 0,
        created_at: now,
        completion_tx: None,
        options: GenerationRequestOptions::default(),
    };

    let req4 = GenerationRequest {
        request_id: RequestId::next(),
        node_id: Hash::from([4u8; 32]),
        agent_id: "agent1".to_string(),
        provider_name: "test-provider".to_string(),
        frame_type: "test".to_string(),
        priority: Priority::Normal,
        retry_count: 0,
        created_at: now + Duration::from_millis(100),
        completion_tx: None,
        options: GenerationRequestOptions::default(),
    };

    // Same priority, older (req3) should be greater
    assert!(req3 > req4);
}

#[tokio::test]
async fn test_queue_stats() {
    let (queue, _temp_dir) = create_test_queue();

    let stats = queue.stats();
    assert_eq!(stats.pending, 0);
    assert_eq!(stats.processing, 0);
    assert_eq!(stats.completed, 0);
    assert_eq!(stats.failed, 0);

    // Enqueue some items
    for i in 0..5 {
        let node_id = Hash::from([i as u8; 32]);
        queue
            .enqueue(
                node_id,
                "agent1".to_string(),
                "test-provider".to_string(),
                None,
                Priority::Normal,
            )
            .await
            .unwrap();
    }

    let stats = queue.stats();
    assert_eq!(stats.pending, 5);
}

#[tokio::test]
async fn test_worker_start_stop() {
    let (queue, _temp_dir) = create_test_queue();

    // Start workers
    queue.start().unwrap();

    // Should be able to start again (idempotent)
    queue.start().unwrap();

    // Stop workers
    queue.stop().await.unwrap();

    // Should be able to stop again (idempotent)
    queue.stop().await.unwrap();
}

#[tokio::test]
async fn test_frame_type_default() {
    let (queue, _temp_dir) = create_test_queue();

    let node_id = Hash::from([1u8; 32]);
    queue
        .enqueue(
            node_id,
            "my-agent".to_string(),
            "test-provider".to_string(),
            None,
            Priority::Normal,
        )
        .await
        .unwrap();

    // Frame type is set during enqueue, verify through stats
    let stats = queue.stats();
    assert_eq!(stats.pending, 1);
}

#[tokio::test]
async fn test_frame_type_custom() {
    let (queue, _temp_dir) = create_test_queue();

    let node_id = Hash::from([1u8; 32]);
    queue
        .enqueue(
            node_id,
            "my-agent".to_string(),
            "test-provider".to_string(),
            Some("custom-type".to_string()),
            Priority::Normal,
        )
        .await
        .unwrap();

    // Frame type is set during enqueue, verify through stats
    let stats = queue.stats();
    assert_eq!(stats.pending, 1);
}

#[tokio::test]
async fn test_priority_enum_ordering() {
    // Verify Priority enum ordering
    assert!(Priority::Urgent > Priority::High);
    assert!(Priority::High > Priority::Normal);
    assert!(Priority::Normal > Priority::Low);

    // Verify Ord implementation
    assert_eq!(
        Priority::Urgent.cmp(&Priority::High),
        std::cmp::Ordering::Greater
    );
    assert_eq!(
        Priority::Low.cmp(&Priority::Normal),
        std::cmp::Ordering::Less
    );
}

#[tokio::test]
async fn test_concurrent_enqueue() {
    let (queue, _temp_dir) = create_test_queue();
    let queue = Arc::new(queue);

    // Spawn multiple tasks to enqueue concurrently
    let mut handles = vec![];
    for i in 0..10 {
        let queue = Arc::clone(&queue);
        let handle = tokio::spawn(async move {
            let node_id = Hash::from([i as u8; 32]);
            queue
                .enqueue(
                    node_id,
                    "agent1".to_string(),
                    "test-provider".to_string(),
                    None,
                    Priority::Normal,
                )
                .await
        });
        handles.push(handle);
    }

    // Wait for all enqueues to complete
    for handle in handles {
        assert!(handle.await.unwrap().is_ok());
    }

    let stats = queue.stats();
    assert_eq!(stats.pending, 10);
}

#[tokio::test]
async fn test_enqueue_emits_observability_events() {
    let (api, temp_dir) = create_test_api();
    let db_path = temp_dir.path().join("progress_db");
    std::fs::create_dir_all(&db_path).unwrap();
    let db = sled::open(&db_path).unwrap();
    let progress = Arc::new(ProgressRuntime::new(db).unwrap());
    let session_id = progress
        .start_command_session("queue.test".to_string())
        .unwrap();

    let queue = FrameGenerationQueue::with_event_context(
        Arc::new(api),
        GenerationConfig::default(),
        Some(QueueEventContext {
            session_id: session_id.clone(),
            progress: Arc::clone(&progress),
        }),
    );

    queue
        .enqueue(
            Hash::from([42u8; 32]),
            "agent1".to_string(),
            "test-provider".to_string(),
            Some("context-agent1".to_string()),
            Priority::Normal,
        )
        .await
        .unwrap();

    progress
        .finish_command_session(&session_id, true, None)
        .unwrap();
    let events = progress.store().read_events(&session_id).unwrap();
    assert!(events.iter().any(|e| e.event_type == "request_enqueued"));
    assert!(events.iter().any(|e| e.event_type == "queue_stats"));
}

#[tokio::test]
async fn test_batch_enqueue_emits_request_enqueued_per_item() {
    let (api, temp_dir) = create_test_api();
    let db_path = temp_dir.path().join("progress_db");
    std::fs::create_dir_all(&db_path).unwrap();
    let db = sled::open(&db_path).unwrap();
    let progress = Arc::new(ProgressRuntime::new(db).unwrap());
    let session_id = progress
        .start_command_session("queue.batch.test".to_string())
        .unwrap();

    let queue = FrameGenerationQueue::with_event_context(
        Arc::new(api),
        GenerationConfig::default(),
        Some(QueueEventContext {
            session_id: session_id.clone(),
            progress: Arc::clone(&progress),
        }),
    );

    let requests = vec![
        (
            Hash::from([21u8; 32]),
            "agent1".to_string(),
            "test-provider".to_string(),
            Some("context-agent1".to_string()),
            Priority::Normal,
        ),
        (
            Hash::from([22u8; 32]),
            "agent1".to_string(),
            "test-provider".to_string(),
            Some("context-agent1".to_string()),
            Priority::High,
        ),
        (
            Hash::from([23u8; 32]),
            "agent2".to_string(),
            "test-provider".to_string(),
            Some("context-agent2".to_string()),
            Priority::Urgent,
        ),
    ];

    queue.enqueue_batch(requests).await.unwrap();

    progress
        .finish_command_session(&session_id, true, None)
        .unwrap();
    let events = progress.store().read_events(&session_id).unwrap();
    let enqueued_count = events
        .iter()
        .filter(|e| e.event_type == "request_enqueued")
        .count();
    assert_eq!(enqueued_count, 3);
}

// Note: Full integration tests with actual frame generation would require
// mocking the adapter and API, which is more complex. These tests focus
// on the queue structure and operations themselves.