cognis-core 0.2.1

Core traits and types for the Cognis LLM framework
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
688
689
690
691
692
693
694
695
use std::collections::HashMap;
use std::sync::Arc;

use serde_json::Value;
use uuid::Uuid;

use super::base::CallbackHandler;
use super::events::{ToolEndEvent, ToolErrorEvent, ToolStartEvent};
use crate::agents::{AgentAction, AgentFinish};
use crate::error::Result;
use crate::outputs::LLMResult;
use crate::runnables::config::RunnableConfig;

/// Manager that dispatches callback events to multiple handlers.
///
/// Supports inheritable handlers, tags, and metadata that propagate
/// to child managers created via `get_child()`.
pub struct CallbackManager {
    handlers: Vec<Arc<dyn CallbackHandler>>,
    inheritable_handlers: Vec<Arc<dyn CallbackHandler>>,
    parent_run_id: Option<Uuid>,
    tags: Vec<String>,
    inheritable_tags: Vec<String>,
    metadata: HashMap<String, Value>,
    inheritable_metadata: HashMap<String, Value>,
}

impl CallbackManager {
    /// Create a new CallbackManager with the given handlers and optional parent run ID.
    ///
    /// All provided handlers are also set as inheritable by default.
    pub fn new(handlers: Vec<Arc<dyn CallbackHandler>>, parent_run_id: Option<Uuid>) -> Self {
        Self {
            inheritable_handlers: handlers.clone(),
            handlers,
            parent_run_id,
            tags: Vec::new(),
            inheritable_tags: Vec::new(),
            metadata: HashMap::new(),
            inheritable_metadata: HashMap::new(),
        }
    }

    /// Returns a reference to all handlers.
    pub fn handlers(&self) -> &[Arc<dyn CallbackHandler>] {
        &self.handlers
    }

    /// Returns a reference to inheritable handlers.
    pub fn inheritable_handlers(&self) -> &[Arc<dyn CallbackHandler>] {
        &self.inheritable_handlers
    }

    /// Returns the parent run ID, if set.
    pub fn parent_run_id(&self) -> Option<Uuid> {
        self.parent_run_id
    }

    /// Returns a reference to the tags.
    pub fn tags(&self) -> &[String] {
        &self.tags
    }

    /// Returns a reference to the inheritable tags.
    pub fn inheritable_tags(&self) -> &[String] {
        &self.inheritable_tags
    }

    /// Returns a reference to the metadata.
    pub fn metadata(&self) -> &HashMap<String, Value> {
        &self.metadata
    }

    /// Returns a reference to the inheritable metadata.
    pub fn inheritable_metadata(&self) -> &HashMap<String, Value> {
        &self.inheritable_metadata
    }

    /// Builder method to set the parent run ID.
    pub fn with_parent_run_id(mut self, id: Uuid) -> Self {
        self.parent_run_id = Some(id);
        self
    }

    /// Add a handler. If `inherit` is true, it will also be added to inheritable handlers.
    pub fn add_handler(&mut self, handler: Arc<dyn CallbackHandler>, inherit: bool) {
        self.handlers.push(handler.clone());
        if inherit {
            self.inheritable_handlers.push(handler);
        }
    }

    /// Remove a handler by index.
    pub fn remove_handler(&mut self, index: usize) {
        if index < self.handlers.len() {
            self.handlers.remove(index);
        }
    }

    /// Remove all handlers whose `name()` matches the given name.
    ///
    /// Removes from both the handlers and inheritable handlers lists.
    /// Returns the number of handlers removed.
    pub fn remove_handler_by_name(&mut self, name: &str) -> usize {
        let before = self.handlers.len() + self.inheritable_handlers.len();
        self.handlers.retain(|h| h.name() != name);
        self.inheritable_handlers.retain(|h| h.name() != name);
        let after = self.handlers.len() + self.inheritable_handlers.len();
        before - after
    }

    /// Populate this manager from a `RunnableConfig`.
    ///
    /// Adds all callbacks, tags, and metadata from the config.
    /// Tags and metadata are added as inheritable.
    pub fn configure(&mut self, config: &RunnableConfig) {
        for handler in &config.callbacks {
            self.add_handler(handler.clone(), true);
        }
        if !config.tags.is_empty() {
            self.add_tags(config.tags.clone(), true);
        }
        if !config.metadata.is_empty() {
            self.add_metadata(config.metadata.clone(), true);
        }
        if let Some(run_id) = config.run_id {
            self.parent_run_id = Some(run_id);
        }
    }

    /// Add tags. If `inherit` is true, they will also be added to inheritable tags.
    pub fn add_tags(&mut self, tags: Vec<String>, inherit: bool) {
        for tag in tags {
            self.tags.push(tag.clone());
            if inherit {
                self.inheritable_tags.push(tag);
            }
        }
    }

    /// Add metadata. If `inherit` is true, entries will also be added to inheritable metadata.
    pub fn add_metadata(&mut self, metadata: HashMap<String, Value>, inherit: bool) {
        for (k, v) in metadata {
            self.metadata.insert(k.clone(), v.clone());
            if inherit {
                self.inheritable_metadata.insert(k, v);
            }
        }
    }

    /// Create a child CallbackManager that inherits handlers, tags, and metadata.
    pub fn get_child(&self, parent_run_id: Uuid) -> Self {
        Self {
            handlers: self.inheritable_handlers.clone(),
            inheritable_handlers: self.inheritable_handlers.clone(),
            parent_run_id: Some(parent_run_id),
            tags: self.inheritable_tags.clone(),
            inheritable_tags: self.inheritable_tags.clone(),
            metadata: self.inheritable_metadata.clone(),
            inheritable_metadata: self.inheritable_metadata.clone(),
        }
    }

    // --- Dispatch methods ---

    pub async fn on_llm_start(
        &self,
        serialized: &Value,
        prompts: &[String],
        run_id: Uuid,
    ) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_llm() {
                handler
                    .on_llm_start(serialized, prompts, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_llm_new_token(&self, token: &str, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_llm() {
                handler
                    .on_llm_new_token(token, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_llm_end(&self, response: &LLMResult, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_llm() {
                handler
                    .on_llm_end(response, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_llm_error(&self, error: &str, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_llm() {
                handler
                    .on_llm_error(error, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_chain_start(
        &self,
        serialized: &Value,
        inputs: &Value,
        run_id: Uuid,
    ) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_chain() {
                handler
                    .on_chain_start(serialized, inputs, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_chain_end(&self, outputs: &Value, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_chain() {
                handler
                    .on_chain_end(outputs, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_chain_error(&self, error: &str, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_chain() {
                handler
                    .on_chain_error(error, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_tool_start(&self, event: ToolStartEvent) -> Result<()> {
        for handler in &self.handlers {
            handler.on_tool_start(event.clone()).await?;
        }
        Ok(())
    }

    pub async fn on_tool_end(&self, event: ToolEndEvent) -> Result<()> {
        for handler in &self.handlers {
            handler.on_tool_end(event.clone()).await?;
        }
        Ok(())
    }

    pub async fn on_tool_error(&self, event: ToolErrorEvent) -> Result<()> {
        for handler in &self.handlers {
            handler.on_tool_error(event.clone()).await?;
        }
        Ok(())
    }

    pub async fn on_agent_action(&self, action: &AgentAction, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_agent() {
                handler
                    .on_agent_action(action, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_agent_finish(&self, finish: &AgentFinish, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_agent() {
                handler
                    .on_agent_finish(finish, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    /// Dispatch an agent-cancellation event to every non-ignoring handler.
    pub async fn on_agent_cancelled(&self, reason: &str, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_agent() {
                handler
                    .on_agent_cancelled(reason, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_text(&self, text: &str, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            handler.on_text(text, run_id, self.parent_run_id).await?;
        }
        Ok(())
    }

    pub async fn on_retry(&self, retry_state: &Value, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_retry() {
                handler
                    .on_retry(retry_state, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }

    pub async fn on_custom_event(&self, name: &str, data: &Value, run_id: Uuid) -> Result<()> {
        for handler in &self.handlers {
            if !handler.ignore_custom_event() {
                handler
                    .on_custom_event(name, data, run_id, self.parent_run_id)
                    .await?;
            }
        }
        Ok(())
    }
}

impl Default for CallbackManager {
    fn default() -> Self {
        Self::new(vec![], None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::callbacks::handlers::{LogLevel, LoggingCallbackHandler, MetricsCallbackHandler};
    use crate::outputs::{Generation, LLMResult};
    use serde_json::json;

    fn make_llm_result() -> LLMResult {
        LLMResult {
            generations: vec![vec![Generation::new("hello")]],
            llm_output: None,
            run: None,
        }
    }

    fn start_event(run_id: Uuid, input: &str) -> ToolStartEvent {
        ToolStartEvent {
            tool: "test".into(),
            serialized: json!({}),
            input_str: input.into(),
            inputs: json!({}),
            tool_call_id: None,
            run_id,
            parent_run_id: None,
            tags: vec![],
            metadata: HashMap::new(),
        }
    }

    fn end_event(run_id: Uuid, out: &str) -> ToolEndEvent {
        ToolEndEvent {
            tool: "test".into(),
            output_str: out.into(),
            output_value: Value::String(out.into()),
            artifact: None,
            tool_call_id: None,
            run_id,
            parent_run_id: None,
        }
    }

    fn error_event(run_id: Uuid, err: &str) -> ToolErrorEvent {
        ToolErrorEvent {
            tool: "test".into(),
            error: err.into(),
            error_kind: crate::callbacks::ToolErrorKind::Execution,
            tool_call_id: None,
            run_id,
            parent_run_id: None,
        }
    }

    #[tokio::test]
    async fn test_dispatch_to_multiple_handlers() {
        let logging = Arc::new(LoggingCallbackHandler::new(LogLevel::Info));
        let metrics = Arc::new(MetricsCallbackHandler::new());

        let manager = CallbackManager::new(vec![logging.clone(), metrics.clone()], None);

        let run_id = Uuid::new_v4();
        manager
            .on_llm_start(&json!({}), &["prompt1".to_string()], run_id)
            .await
            .unwrap();

        // Logging handler should have captured the event
        assert_eq!(logging.get_logs().len(), 1);
        assert!(logging.get_logs()[0].contains("llm/start"));

        // Metrics handler should have counted the call
        let m = metrics.get_metrics();
        assert_eq!(m.total_llm_calls, 1);
    }

    #[tokio::test]
    async fn test_add_and_remove_handlers() {
        let mut manager = CallbackManager::default();
        assert_eq!(manager.handlers().len(), 0);

        let logging = Arc::new(LoggingCallbackHandler::new(LogLevel::Info));
        manager.add_handler(logging.clone(), true);
        assert_eq!(manager.handlers().len(), 1);

        let removed = manager.remove_handler_by_name("LoggingCallbackHandler");
        assert_eq!(removed, 2); // removed from both handlers and inheritable_handlers
        assert_eq!(manager.handlers().len(), 0);
        assert_eq!(manager.inheritable_handlers().len(), 0);
    }

    #[tokio::test]
    async fn test_logging_handler_captures_events() {
        let handler = Arc::new(LoggingCallbackHandler::new(LogLevel::Debug));
        let manager = CallbackManager::new(vec![handler.clone()], None);
        let run_id = Uuid::new_v4();

        manager
            .on_chain_start(&json!({}), &json!({"key": "value"}), run_id)
            .await
            .unwrap();
        manager
            .on_chain_end(&json!({"result": 42}), run_id)
            .await
            .unwrap();
        manager
            .on_tool_start(start_event(run_id, "search query"))
            .await
            .unwrap();

        let logs = handler.get_logs();
        assert_eq!(logs.len(), 3);
        assert!(logs[0].contains("chain/start"));
        assert!(logs[1].contains("chain/end"));
        assert!(logs[2].contains("tool/start"));
        // Verify log level prefix
        assert!(logs[0].contains("[DEBUG]"));
    }

    #[tokio::test]
    async fn test_metrics_handler_tracks_counts() {
        let handler = Arc::new(MetricsCallbackHandler::new());
        let manager = CallbackManager::new(vec![handler.clone()], None);
        let run_id = Uuid::new_v4();

        // Two LLM calls
        manager
            .on_llm_start(&json!({}), &["p1".into()], run_id)
            .await
            .unwrap();
        manager
            .on_llm_start(&json!({}), &["p2".into()], run_id)
            .await
            .unwrap();

        // One chain call
        manager
            .on_chain_start(&json!({}), &json!({}), run_id)
            .await
            .unwrap();

        // One tool call
        manager
            .on_tool_start(start_event(run_id, "input"))
            .await
            .unwrap();

        // One error
        manager.on_llm_error("oops", run_id).await.unwrap();

        let m = handler.get_metrics();
        assert_eq!(m.total_llm_calls, 2);
        assert_eq!(m.total_chain_calls, 1);
        assert_eq!(m.total_tool_calls, 1);
        assert_eq!(m.total_errors, 1);
    }

    #[tokio::test]
    async fn test_metrics_reset() {
        let handler = Arc::new(MetricsCallbackHandler::new());
        let manager = CallbackManager::new(vec![handler.clone()], None);
        let run_id = Uuid::new_v4();

        manager
            .on_llm_start(&json!({}), &["p".into()], run_id)
            .await
            .unwrap();
        assert_eq!(handler.get_metrics().total_llm_calls, 1);

        handler.reset();
        let m = handler.get_metrics();
        assert_eq!(m.total_llm_calls, 0);
        assert_eq!(m.total_tool_calls, 0);
        assert_eq!(m.total_chain_calls, 0);
        assert_eq!(m.total_errors, 0);
        assert_eq!(m.total_tokens, 0);
    }

    #[tokio::test]
    async fn test_child_manager_inherits_handlers() {
        let metrics = Arc::new(MetricsCallbackHandler::new());
        let manager = CallbackManager::new(vec![metrics.clone()], None);

        let parent_run_id = Uuid::new_v4();
        let child = manager.get_child(parent_run_id);

        assert_eq!(child.handlers().len(), 1);
        assert_eq!(child.parent_run_id(), Some(parent_run_id));

        // Events dispatched through child should still reach the shared handler
        let run_id = Uuid::new_v4();
        child
            .on_llm_start(&json!({}), &["p".into()], run_id)
            .await
            .unwrap();
        assert_eq!(metrics.get_metrics().total_llm_calls, 1);
    }

    #[tokio::test]
    async fn test_empty_manager_is_noop() {
        let manager = CallbackManager::default();
        let run_id = Uuid::new_v4();

        // All dispatch methods should succeed without handlers
        manager
            .on_llm_start(&json!({}), &["p".into()], run_id)
            .await
            .unwrap();
        manager
            .on_llm_end(&make_llm_result(), run_id)
            .await
            .unwrap();
        manager.on_llm_error("err", run_id).await.unwrap();
        manager
            .on_chain_start(&json!({}), &json!({}), run_id)
            .await
            .unwrap();
        manager.on_chain_end(&json!({}), run_id).await.unwrap();
        manager.on_chain_error("err", run_id).await.unwrap();
        manager
            .on_tool_start(start_event(run_id, "in"))
            .await
            .unwrap();
        manager.on_tool_end(end_event(run_id, "out")).await.unwrap();
        manager
            .on_tool_error(error_event(run_id, "err"))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_tags_and_metadata_propagation() {
        let mut manager = CallbackManager::default();
        manager.add_tags(vec!["tag1".into(), "tag2".into()], true);
        let mut meta = HashMap::new();
        meta.insert("key".into(), json!("value"));
        manager.add_metadata(meta, true);

        let child = manager.get_child(Uuid::new_v4());
        assert_eq!(child.tags(), &["tag1".to_string(), "tag2".to_string()]);
        assert_eq!(child.metadata().get("key"), Some(&json!("value")));

        // Grandchild should also inherit
        let grandchild = child.get_child(Uuid::new_v4());
        assert_eq!(grandchild.tags(), &["tag1".to_string(), "tag2".to_string()]);
        assert_eq!(grandchild.metadata().get("key"), Some(&json!("value")));
    }

    #[tokio::test]
    async fn test_all_event_types_dispatched() {
        let logging = Arc::new(LoggingCallbackHandler::new(LogLevel::Info));
        let manager = CallbackManager::new(vec![logging.clone()], None);
        let run_id = Uuid::new_v4();

        manager
            .on_llm_start(&json!({}), &["p".into()], run_id)
            .await
            .unwrap();
        manager
            .on_llm_end(&make_llm_result(), run_id)
            .await
            .unwrap();
        manager.on_llm_error("err", run_id).await.unwrap();
        manager
            .on_chain_start(&json!({}), &json!({}), run_id)
            .await
            .unwrap();
        manager.on_chain_end(&json!({}), run_id).await.unwrap();
        manager.on_chain_error("err", run_id).await.unwrap();
        manager
            .on_tool_start(start_event(run_id, "in"))
            .await
            .unwrap();
        manager.on_tool_end(end_event(run_id, "out")).await.unwrap();
        manager
            .on_tool_error(error_event(run_id, "err"))
            .await
            .unwrap();

        let logs = logging.get_logs();
        assert_eq!(logs.len(), 9);
        assert!(logs[0].contains("llm/start"));
        assert!(logs[1].contains("llm/end"));
        assert!(logs[2].contains("llm/error"));
        assert!(logs[3].contains("chain/start"));
        assert!(logs[4].contains("chain/end"));
        assert!(logs[5].contains("chain/error"));
        assert!(logs[6].contains("tool/start"));
        assert!(logs[7].contains("tool/end"));
        assert!(logs[8].contains("tool/error"));
    }

    #[tokio::test]
    async fn test_configure_from_runnable_config() {
        let metrics = Arc::new(MetricsCallbackHandler::new());
        let run_id = Uuid::new_v4();

        let config = RunnableConfig {
            tags: vec!["config_tag".into()],
            metadata: {
                let mut m = HashMap::new();
                m.insert("source".into(), json!("test"));
                m
            },
            callbacks: vec![metrics.clone() as Arc<dyn CallbackHandler>],
            run_id: Some(run_id),
            ..RunnableConfig::default()
        };

        let mut manager = CallbackManager::default();
        manager.configure(&config);

        assert_eq!(manager.handlers().len(), 1);
        assert_eq!(manager.tags(), &["config_tag".to_string()]);
        assert_eq!(manager.metadata().get("source"), Some(&json!("test")));
        assert_eq!(manager.parent_run_id(), Some(run_id));

        // Dispatch should work
        let id = Uuid::new_v4();
        manager
            .on_llm_start(&json!({}), &["p".into()], id)
            .await
            .unwrap();
        assert_eq!(metrics.get_metrics().total_llm_calls, 1);
    }

    #[tokio::test]
    async fn test_metrics_token_estimation() {
        let handler = Arc::new(MetricsCallbackHandler::new());
        let manager = CallbackManager::new(vec![handler.clone()], None);
        let run_id = Uuid::new_v4();

        // "hello world" = 11 chars, estimated ~2 tokens (11/4 = 2)
        manager
            .on_llm_start(&json!({}), &["hello world".into()], run_id)
            .await
            .unwrap();

        let m = handler.get_metrics();
        assert!(m.total_tokens > 0, "should estimate some tokens");
        assert_eq!(m.total_tokens, 2); // 11/4 = 2
    }

    #[tokio::test]
    async fn test_remove_nonexistent_handler() {
        let mut manager = CallbackManager::default();
        let logging = Arc::new(LoggingCallbackHandler::new(LogLevel::Info));
        manager.add_handler(logging, true);

        let removed = manager.remove_handler_by_name("NonExistentHandler");
        assert_eq!(removed, 0);
        assert_eq!(manager.handlers().len(), 1);
    }
}