axonml-server 0.6.2

REST API server for AxonML Machine Learning Framework
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Training Notebooks Database Operations — Notebook and Checkpoint Persistence
//!
//! Provides document-store-backed persistence for training notebooks and their
//! checkpoints via `NotebookRepository`. Uses two Aegis-DB collections:
//!
//! - `axonml_notebooks` — `TrainingNotebook` records containing an ordered list
//!   of `NotebookCell` items (Code or Markdown), per-cell execution status and
//!   outputs (`CellOutput`), notebook-level metadata (`NotebookMetadata` with
//!   kernel, language, framework, tags), and lifecycle status
//!   (Draft/Running/Completed/Failed/Stopped).
//! - `axonml_checkpoints` — `NotebookCheckpoint` records with epoch, step,
//!   metrics JSON, and paths to model/optimizer state files.
//!
//! Repository methods cover full CRUD for notebooks, individual cell-level
//! mutations (update/add/delete), checkpoint creation and listing, and a
//! `get_best_checkpoint()` helper that selects the checkpoint with the best
//! value for a given metric key (minimize or maximize).
//!
//! # File
//! `crates/axonml-server/src/db/notebooks.rs`
//!
//! # Author
//! Andrew Jewell Sr. — AutomataNexus LLC
//! ORCID: 0009-0005-2158-7060
//!
//! # Updated
//! April 16, 2026 11:15 PM EST
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

// =============================================================================
// Imports
// =============================================================================

use super::{Database, DbError, DocumentQuery};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

// =============================================================================
// Constants
// =============================================================================

/// Collection name for notebooks
const COLLECTION: &str = "axonml_notebooks";

/// Collection name for checkpoints
const CHECKPOINTS_COLLECTION: &str = "axonml_checkpoints";

// =============================================================================
// Types — Cell Enums
// =============================================================================

/// Cell type enum
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum CellType {
    #[default]
    Code,
    Markdown,
}

/// Cell execution status
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum CellStatus {
    #[default]
    Idle,
    Running,
    Completed,
    Error,
}

/// Notebook status
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum NotebookStatus {
    #[default]
    Draft,
    Running,
    Completed,
    Failed,
    Stopped,
}

// =============================================================================
// Types — Cell and Output
// =============================================================================

/// Cell output
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CellOutput {
    pub output_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_count: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_value: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub traceback: Option<Vec<String>>,
}

/// Notebook cell
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotebookCell {
    pub id: String,
    #[serde(default)]
    pub cell_type: CellType,
    pub source: String,
    #[serde(default)]
    pub outputs: Vec<CellOutput>,
    #[serde(default)]
    pub status: CellStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_count: Option<u32>,
    #[serde(default)]
    pub metadata: HashMap<String, serde_json::Value>,
}

impl Default for NotebookCell {
    fn default() -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            cell_type: CellType::Code,
            source: String::new(),
            outputs: vec![],
            status: CellStatus::Idle,
            execution_count: None,
            metadata: HashMap::new(),
        }
    }
}

// =============================================================================
// Types — Notebook Metadata
// =============================================================================

/// Notebook metadata
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NotebookMetadata {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kernel: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub framework: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub extra: HashMap<String, serde_json::Value>,
}

// =============================================================================
// Types — Training Notebook
// =============================================================================

/// Training notebook
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingNotebook {
    pub id: String,
    pub user_id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub cells: Vec<NotebookCell>,
    #[serde(default)]
    pub metadata: NotebookMetadata,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dataset_id: Option<String>,
    #[serde(default)]
    pub status: NotebookStatus,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

// =============================================================================
// Types — Checkpoint
// =============================================================================

/// Training checkpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotebookCheckpoint {
    pub id: String,
    pub notebook_id: String,
    pub epoch: u32,
    pub step: u32,
    pub metrics: serde_json::Value,
    pub model_state_path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub optimizer_state_path: Option<String>,
    pub created_at: DateTime<Utc>,
}

// =============================================================================
// Types — Creation and Update Payloads
// =============================================================================

/// New notebook data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewNotebook {
    pub user_id: String,
    pub name: String,
    pub description: Option<String>,
    pub cells: Vec<NotebookCell>,
    pub model_id: Option<String>,
    pub dataset_id: Option<String>,
}

/// New checkpoint data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewCheckpoint {
    pub notebook_id: String,
    pub epoch: u32,
    pub step: u32,
    pub metrics: serde_json::Value,
    pub model_state_path: String,
    pub optimizer_state_path: Option<String>,
}

/// Update notebook data
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UpdateNotebook {
    pub name: Option<String>,
    pub description: Option<String>,
    pub cells: Option<Vec<NotebookCell>>,
    pub model_id: Option<String>,
    pub dataset_id: Option<String>,
    pub status: Option<NotebookStatus>,
}

// =============================================================================
// Repository
// =============================================================================

/// Notebook repository
pub struct NotebookRepository<'a> {
    db: &'a Database,
}

impl<'a> NotebookRepository<'a> {
    /// Create a new notebook repository
    pub fn new(db: &'a Database) -> Self {
        Self { db }
    }

    // -------------------------------------------------------------------------
    // Notebook CRUD
    // -------------------------------------------------------------------------

    /// Create a new training notebook
    pub async fn create(&self, new_notebook: NewNotebook) -> Result<TrainingNotebook, DbError> {
        let now = Utc::now();
        let notebook = TrainingNotebook {
            id: Uuid::new_v4().to_string(),
            user_id: new_notebook.user_id,
            name: new_notebook.name,
            description: new_notebook.description,
            cells: if new_notebook.cells.is_empty() {
                // Create default starter cells
                vec![
                    NotebookCell {
                        id: Uuid::new_v4().to_string(),
                        cell_type: CellType::Markdown,
                        source: "# Training Notebook\n\nDescribe your training experiment here.".to_string(),
                        ..Default::default()
                    },
                    NotebookCell {
                        id: Uuid::new_v4().to_string(),
                        cell_type: CellType::Code,
                        source: "# Import AxonML\nimport axonml\nfrom axonml import nn, optim, data\n\nprint(f\"AxonML version: {axonml.__version__}\")".to_string(),
                        ..Default::default()
                    },
                ]
            } else {
                new_notebook.cells
            },
            metadata: NotebookMetadata {
                kernel: Some("axonml".to_string()),
                language: Some("rust".to_string()),
                framework: Some("axonml".to_string()),
                tags: vec![],
                extra: HashMap::new(),
            },
            model_id: new_notebook.model_id,
            dataset_id: new_notebook.dataset_id,
            status: NotebookStatus::Draft,
            created_at: now,
            updated_at: now,
        };

        let notebook_json = serde_json::to_value(&notebook)?;
        self.db
            .doc_insert(COLLECTION, Some(&notebook.id), notebook_json)
            .await?;

        Ok(notebook)
    }

    /// Find notebook by ID
    pub async fn find_by_id(&self, id: &str) -> Result<Option<TrainingNotebook>, DbError> {
        let doc = self.db.doc_get(COLLECTION, id).await?;

        match doc {
            Some(data) => {
                let notebook: TrainingNotebook = serde_json::from_value(data)?;
                Ok(Some(notebook))
            }
            None => Ok(None),
        }
    }

    // -------------------------------------------------------------------------
    // Notebook Listing
    // -------------------------------------------------------------------------

    /// List notebooks for a user
    pub async fn list_by_user(
        &self,
        user_id: &str,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Vec<TrainingNotebook>, DbError> {
        let filter = serde_json::json!({
            "user_id": { "$eq": user_id }
        });

        let query = DocumentQuery {
            filter: Some(filter),
            sort: Some(serde_json::json!({ "field": "updated_at", "ascending": false })),
            limit,
            skip: offset,
        };

        let docs = self.db.doc_query(COLLECTION, query).await?;

        let mut notebooks = Vec::new();
        for doc in docs {
            let notebook: TrainingNotebook = serde_json::from_value(doc)?;
            notebooks.push(notebook);
        }

        Ok(notebooks)
    }

    /// List all notebooks (admin)
    pub async fn list_all(
        &self,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Vec<TrainingNotebook>, DbError> {
        let query = DocumentQuery {
            filter: None,
            sort: Some(serde_json::json!({ "field": "updated_at", "ascending": false })),
            limit,
            skip: offset,
        };

        let docs = self.db.doc_query(COLLECTION, query).await?;

        let mut notebooks = Vec::new();
        for doc in docs {
            let notebook: TrainingNotebook = serde_json::from_value(doc)?;
            notebooks.push(notebook);
        }

        Ok(notebooks)
    }

    // -------------------------------------------------------------------------
    // Notebook Updates
    // -------------------------------------------------------------------------

    /// Update notebook
    pub async fn update(
        &self,
        id: &str,
        updates: UpdateNotebook,
    ) -> Result<TrainingNotebook, DbError> {
        let mut notebook = self
            .find_by_id(id)
            .await?
            .ok_or_else(|| DbError::NotFound(format!("Notebook {} not found", id)))?;

        if let Some(name) = updates.name {
            notebook.name = name;
        }
        if let Some(description) = updates.description {
            notebook.description = Some(description);
        }
        if let Some(cells) = updates.cells {
            notebook.cells = cells;
        }
        if let Some(model_id) = updates.model_id {
            notebook.model_id = Some(model_id);
        }
        if let Some(dataset_id) = updates.dataset_id {
            notebook.dataset_id = Some(dataset_id);
        }
        if let Some(status) = updates.status {
            notebook.status = status;
        }

        notebook.updated_at = Utc::now();

        let notebook_json = serde_json::to_value(&notebook)?;
        self.db.doc_update(COLLECTION, id, notebook_json).await?;

        Ok(notebook)
    }

    /// Update notebook status
    pub async fn update_status(
        &self,
        id: &str,
        status: NotebookStatus,
    ) -> Result<TrainingNotebook, DbError> {
        self.update(
            id,
            UpdateNotebook {
                status: Some(status),
                ..Default::default()
            },
        )
        .await
    }

    // -------------------------------------------------------------------------
    // Cell-Level Operations
    // -------------------------------------------------------------------------

    /// Update a single cell in a notebook
    pub async fn update_cell(
        &self,
        notebook_id: &str,
        cell: NotebookCell,
    ) -> Result<TrainingNotebook, DbError> {
        let mut notebook = self
            .find_by_id(notebook_id)
            .await?
            .ok_or_else(|| DbError::NotFound(format!("Notebook {} not found", notebook_id)))?;

        // Find and update the cell
        let mut found = false;
        for c in &mut notebook.cells {
            if c.id == cell.id {
                *c = cell.clone();
                found = true;
                break;
            }
        }

        if !found {
            return Err(DbError::NotFound(format!(
                "Cell {} not found in notebook",
                cell.id
            )));
        }

        notebook.updated_at = Utc::now();

        let notebook_json = serde_json::to_value(&notebook)?;
        self.db
            .doc_update(COLLECTION, notebook_id, notebook_json)
            .await?;

        Ok(notebook)
    }

    /// Add a cell to a notebook
    pub async fn add_cell(
        &self,
        notebook_id: &str,
        cell: NotebookCell,
        position: Option<usize>,
    ) -> Result<TrainingNotebook, DbError> {
        let mut notebook = self
            .find_by_id(notebook_id)
            .await?
            .ok_or_else(|| DbError::NotFound(format!("Notebook {} not found", notebook_id)))?;

        match position {
            Some(pos) if pos < notebook.cells.len() => {
                notebook.cells.insert(pos, cell);
            }
            _ => {
                notebook.cells.push(cell);
            }
        }

        notebook.updated_at = Utc::now();

        let notebook_json = serde_json::to_value(&notebook)?;
        self.db
            .doc_update(COLLECTION, notebook_id, notebook_json)
            .await?;

        Ok(notebook)
    }

    /// Delete a cell from a notebook
    pub async fn delete_cell(
        &self,
        notebook_id: &str,
        cell_id: &str,
    ) -> Result<TrainingNotebook, DbError> {
        let mut notebook = self
            .find_by_id(notebook_id)
            .await?
            .ok_or_else(|| DbError::NotFound(format!("Notebook {} not found", notebook_id)))?;

        let original_len = notebook.cells.len();
        notebook.cells.retain(|c| c.id != cell_id);

        if notebook.cells.len() == original_len {
            return Err(DbError::NotFound(format!(
                "Cell {} not found in notebook",
                cell_id
            )));
        }

        notebook.updated_at = Utc::now();

        let notebook_json = serde_json::to_value(&notebook)?;
        self.db
            .doc_update(COLLECTION, notebook_id, notebook_json)
            .await?;

        Ok(notebook)
    }

    // -------------------------------------------------------------------------
    // Notebook Deletion
    // -------------------------------------------------------------------------

    /// Delete notebook
    pub async fn delete(&self, id: &str) -> Result<(), DbError> {
        // Check if notebook exists
        let _ = self
            .find_by_id(id)
            .await?
            .ok_or_else(|| DbError::NotFound(format!("Notebook {} not found", id)))?;

        // Delete all associated checkpoints
        self.delete_checkpoints_for_notebook(id).await?;

        // Delete the notebook
        self.db.doc_delete(COLLECTION, id).await?;

        Ok(())
    }

    // =========================================================================
    // Checkpoint Operations
    // =========================================================================

    /// Create a checkpoint
    pub async fn create_checkpoint(
        &self,
        new_checkpoint: NewCheckpoint,
    ) -> Result<NotebookCheckpoint, DbError> {
        let checkpoint = NotebookCheckpoint {
            id: Uuid::new_v4().to_string(),
            notebook_id: new_checkpoint.notebook_id,
            epoch: new_checkpoint.epoch,
            step: new_checkpoint.step,
            metrics: new_checkpoint.metrics,
            model_state_path: new_checkpoint.model_state_path,
            optimizer_state_path: new_checkpoint.optimizer_state_path,
            created_at: Utc::now(),
        };

        let checkpoint_json = serde_json::to_value(&checkpoint)?;
        self.db
            .doc_insert(
                CHECKPOINTS_COLLECTION,
                Some(&checkpoint.id),
                checkpoint_json,
            )
            .await?;

        Ok(checkpoint)
    }

    /// Get checkpoint by ID
    pub async fn get_checkpoint(&self, id: &str) -> Result<Option<NotebookCheckpoint>, DbError> {
        let doc = self.db.doc_get(CHECKPOINTS_COLLECTION, id).await?;

        match doc {
            Some(data) => {
                let checkpoint: NotebookCheckpoint = serde_json::from_value(data)?;
                Ok(Some(checkpoint))
            }
            None => Ok(None),
        }
    }

    /// List checkpoints for a notebook
    pub async fn list_checkpoints(
        &self,
        notebook_id: &str,
    ) -> Result<Vec<NotebookCheckpoint>, DbError> {
        let filter = serde_json::json!({
            "notebook_id": { "$eq": notebook_id }
        });

        let query = DocumentQuery {
            filter: Some(filter),
            sort: Some(serde_json::json!({ "field": "created_at", "ascending": false })),
            limit: None,
            skip: None,
        };

        let docs = self.db.doc_query(CHECKPOINTS_COLLECTION, query).await?;

        let mut checkpoints = Vec::new();
        for doc in docs {
            let checkpoint: NotebookCheckpoint = serde_json::from_value(doc)?;
            checkpoints.push(checkpoint);
        }

        Ok(checkpoints)
    }

    // -------------------------------------------------------------------------
    // Best Checkpoint Selection
    // -------------------------------------------------------------------------

    /// Get best checkpoint by metric
    pub async fn get_best_checkpoint(
        &self,
        notebook_id: &str,
        metric_key: &str,
        minimize: bool,
    ) -> Result<Option<NotebookCheckpoint>, DbError> {
        let checkpoints = self.list_checkpoints(notebook_id).await?;

        let best = checkpoints
            .into_iter()
            .filter_map(|cp| {
                let value = cp.metrics.get(metric_key)?.as_f64()?;
                Some((cp, value))
            })
            .reduce(|a, b| {
                if minimize {
                    if a.1 < b.1 { a } else { b }
                } else {
                    if a.1 > b.1 { a } else { b }
                }
            })
            .map(|(cp, _)| cp);

        Ok(best)
    }

    // -------------------------------------------------------------------------
    // Checkpoint Deletion
    // -------------------------------------------------------------------------

    /// Delete checkpoint
    pub async fn delete_checkpoint(&self, id: &str) -> Result<(), DbError> {
        self.db.doc_delete(CHECKPOINTS_COLLECTION, id).await
    }

    /// Delete all checkpoints for a notebook
    async fn delete_checkpoints_for_notebook(&self, notebook_id: &str) -> Result<(), DbError> {
        let checkpoints = self.list_checkpoints(notebook_id).await?;
        for checkpoint in checkpoints {
            self.delete_checkpoint(&checkpoint.id).await?;
        }
        Ok(())
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_notebook_serialization() {
        let notebook = TrainingNotebook {
            id: "nb-123".to_string(),
            user_id: "user-456".to_string(),
            name: "Test Notebook".to_string(),
            description: Some("A test notebook".to_string()),
            cells: vec![NotebookCell {
                id: "cell-1".to_string(),
                cell_type: CellType::Markdown,
                source: "# Hello".to_string(),
                ..Default::default()
            }],
            metadata: NotebookMetadata::default(),
            model_id: None,
            dataset_id: None,
            status: NotebookStatus::Draft,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        let json = serde_json::to_string(&notebook).unwrap();
        assert!(json.contains("nb-123"));
        assert!(json.contains("\"status\":\"draft\""));
    }

    #[test]
    fn test_checkpoint_serialization() {
        let checkpoint = NotebookCheckpoint {
            id: "cp-123".to_string(),
            notebook_id: "nb-456".to_string(),
            epoch: 10,
            step: 1000,
            metrics: serde_json::json!({"loss": 0.234, "accuracy": 0.89}),
            model_state_path: "/checkpoints/cp-123/model.bin".to_string(),
            optimizer_state_path: Some("/checkpoints/cp-123/optimizer.bin".to_string()),
            created_at: Utc::now(),
        };

        let json = serde_json::to_string(&checkpoint).unwrap();
        assert!(json.contains("cp-123"));
        assert!(json.contains("0.234"));
    }
}