mitosis-db 0.2.0

Copy-on-write Postgres clones for AI agent tasks on macOS APFS
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
use crate::error::MitosisError;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

pub const PROTOCOL_VERSION: u32 = 2;

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TemplateSource {
    Url {
        url: String,
    },
    Seed {
        command: String,
        /// Folder the command runs in; the daemon's own cwd when absent.
        #[serde(default)]
        cwd: Option<PathBuf>,
        /// The caller's `PATH`, so the command finds the same tools as in the caller's shell;
        /// the daemon's own `PATH` when absent.
        #[serde(default)]
        path: Option<String>,
    },
    /// Made by `promote` from a running clone; there is no source to rebuild it from.
    Promoted {
        clone_id: String,
    },
}

/// How a template generation was made.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum GenKind {
    Full,
    Layered,
    Promoted,
    Upgraded,
}

#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum RefreshMode {
    #[default]
    Full,
    Layered,
}

#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum OnStale {
    #[default]
    Warn,
    Refresh,
}

/// A migration command run against a template, in `cwd`, with the caller's `PATH`.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct MigrateCmd {
    pub command: String,
    pub cwd: PathBuf,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GenerationInfo {
    pub gen: u32,
    pub kind: GenKind,
    pub built_at: i64,
    pub pg_major: u32,
    pub size_bytes: u64,
    pub current: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from_clone: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from_gen: Option<u32>,
}

/// Template settings a request may change; `None` / `false` leaves a setting as it is.
/// An `_off` flag turns its setting off and must not come with a value.
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub struct TemplateSettings {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub every_secs: Option<u64>,
    #[serde(default)]
    pub every_off: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub every_mode: Option<RefreshMode>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub migrate: Option<MigrateCmd>,
    #[serde(default)]
    pub migrate_off: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_migrate: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_stale: Option<OnStale>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TemplateInitArgs {
    pub name: String,
    pub source: TemplateSource,
    pub database: Option<String>,
    pub migrations: Option<PathBuf>,
    pub max_age_secs: Option<u64>,
    pub pg_major: Option<u32>,
    /// Applied with the first generation.
    #[serde(flatten)]
    pub settings: TemplateSettings,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TemplateSetArgs {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_age_secs: Option<u64>,
    #[serde(flatten)]
    pub settings: TemplateSettings,
    /// Clears `paused`, so automatic builds run again.
    #[serde(default)]
    pub resume: bool,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CloneCreateArgs {
    pub template: String,
    pub name: Option<String>,
    pub ttl_secs: u64,
    pub durable: bool,
    pub parent_pid: Option<i32>,
    /// Destroy a running clone of this name first (its reservation is kept), then create it.
    #[serde(default)]
    pub fresh: bool,
    /// Needs a name; no parent, no TTL, and `destroy` needs `force`.
    #[serde(default)]
    pub protect: bool,
    /// A `.env` entry the client will point at the clone; the daemon records it so a destroy can
    /// put `previous` back.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub env: Option<EnvTarget>,
    /// How long to wait for room under the limits; `None` uses the daemon's `queue_wait`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wait_secs: Option<u64>,
}

/// One variable in one `.env` file that holds a clone's URL.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct EnvTarget {
    /// Absolute path.
    pub file: PathBuf,
    pub var: String,
    /// The value the variable had before (`None`: the line did not exist).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous: Option<String>,
}

/// A `.env` restore the daemon could not do (e.g. a read-only file); a client finishes it.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct PendingRestore {
    pub id: i64,
    pub file: PathBuf,
    pub var: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous: Option<String>,
    /// The clone URL the file must still hold for the restore to apply.
    pub url: String,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Request {
    TemplateInit(TemplateInitArgs),
    TemplateRefresh {
        name: String,
        /// The refreshing caller's `PATH`; for a seed template it replaces the recorded one.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
        /// Copy the current generation and run only the migrate command on it.
        #[serde(default)]
        layered: bool,
    },
    TemplateSet(TemplateSetArgs),
    TemplateList,
    TemplateHistory {
        name: String,
    },
    /// Points the template at generation `to`, or the newest one older than the current.
    TemplateRollback {
        name: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        to: Option<u32>,
    },
    /// Moves the template to Postgres `to` with pg_upgrade: a new generation, or with `as_name`
    /// a new template (same database and settings, schedule off).
    TemplateUpgrade {
        name: String,
        to: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        as_name: Option<String>,
    },
    CloneCreate(CloneCreateArgs),
    CloneList,
    CloneDestroy {
        id_or_name: String,
        /// Needed to destroy a protected clone.
        #[serde(default)]
        force: bool,
        /// Also drop the name's reserved port and password.
        #[serde(default)]
        forget: bool,
    },
    /// Makes a running clone the newest generation of its template, or of `template`.
    ClonePromote {
        id_or_name: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        template: Option<String>,
    },
    /// `.env` restores the daemon could not finish.
    PendingRestores,
    PendingRestoreDone {
        id: i64,
    },
    Gc,
    Status,
    /// Resource use of all clones against the limits.
    Usage,
    /// Re-read `config.toml` and the environment; later requests use the new settings.
    ConfigReload,
    Shutdown,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TemplateInfo {
    pub name: String,
    pub pg_major: u32,
    pub source: TemplateSource,
    pub database: String,
    pub size_bytes: u64,
    pub built_at: i64,
    pub age_secs: u64,
    pub warnings: Vec<String>,
    #[serde(default)]
    pub current_gen: u32,
    /// How many generations the template keeps on disk.
    #[serde(default)]
    pub generations: u32,
    #[serde(default)]
    pub paused: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub every_secs: Option<u64>,
    #[serde(default)]
    pub every_mode: RefreshMode,
    /// The migrate command, passwords masked.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub migrate: Option<String>,
    #[serde(default)]
    pub auto_migrate: bool,
    #[serde(default)]
    pub on_stale: OnStale,
    #[serde(default)]
    pub keep: u32,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CloneInfo {
    pub id: String,
    pub name: Option<String>,
    pub template: String,
    pub url: String,
    pub port: u16,
    pub socket_dir: PathBuf,
    pub template_age_secs: u64,
    pub created_at: i64,
    pub expires_at: i64,
    pub durable: bool,
    pub parent_pid: Option<i32>,
    pub rss_bytes: Option<u64>,
    pub own_disk_bytes: Option<u64>,
    /// The template generation this clone was made from.
    #[serde(default)]
    pub generation: u32,
    /// The template was older than its max age when this clone was made.
    #[serde(default)]
    pub stale: bool,
    /// A background refresh of the template was running (or was started) when this clone was made.
    #[serde(default)]
    pub refreshing: bool,
    /// A named clone that was already running was returned instead of a new one.
    #[serde(default)]
    pub existing: bool,
    /// Never expires and is not destroyed with a parent; `destroy` needs `--force`.
    #[serde(default)]
    pub protected: bool,
    #[serde(default)]
    pub warnings: Vec<String>,
    /// Wall time of the create request.
    #[serde(default)]
    pub duration_ms: u64,
    /// Time the create spent queued for room under the limits.
    #[serde(default)]
    pub waited_ms: u64,
    /// The clone's own disk use is past `clone_disk_warn`.
    #[serde(default)]
    pub disk_warn: bool,
    /// Restarted after an unclean shutdown with fsync off: recent writes may be lost or corrupt.
    #[serde(default)]
    pub suspect: bool,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct GcReport {
    pub adopted: Vec<String>,
    pub destroyed: Vec<String>,
    pub orphan_folders_removed: Vec<PathBuf>,
    pub records_dropped: Vec<String>,
    /// Entries gc could not clean up; they are retried on the next gc.
    #[serde(default)]
    pub failed: Vec<GcFailure>,
    /// Things the caller should know, such as a restarted clone that is suspect.
    #[serde(default)]
    pub warnings: Vec<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct GcFailure {
    /// Clone id or folder path.
    pub item: String,
    pub error: String,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct DaemonStatus {
    pub pid: u32,
    pub home: PathBuf,
    pub clones: usize,
    pub templates: usize,
    pub uptime_secs: u64,
    /// Crate version of the daemon binary.
    #[serde(default)]
    pub version: String,
    /// Started by the launchd login service.
    #[serde(default)]
    pub service: bool,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Response {
    TemplateBuilt(TemplateInfo),
    Templates {
        templates: Vec<TemplateInfo>,
    },
    Generations {
        template: String,
        generations: Vec<GenerationInfo>,
        /// Automatic builds are stopped (after a rollback).
        #[serde(default)]
        paused: bool,
    },
    CloneCreated(CloneInfo),
    Clones {
        clones: Vec<CloneInfo>,
    },
    Destroyed {
        id: String,
    },
    PendingRestores {
        items: Vec<PendingRestore>,
    },
    Gc(GcReport),
    Status(DaemonStatus),
    Usage(crate::budget::Usage),
    Ok,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct RequestEnvelope {
    pub v: u32,
    pub request: Request,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ResponseEnvelope {
    pub v: u32,
    pub result: std::result::Result<Response, MitosisError>,
}

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

    #[test]
    fn gc_is_tagged_only() {
        assert_eq!(
            serde_json::to_string(&Request::Gc).unwrap(),
            r#"{"type":"gc"}"#
        );
    }

    #[test]
    fn request_envelope_round_trip() {
        let env = RequestEnvelope {
            v: PROTOCOL_VERSION,
            request: Request::CloneCreate(CloneCreateArgs {
                template: "main".into(),
                name: Some("feat".into()),
                ttl_secs: 7200,
                durable: false,
                parent_pid: Some(42),
                fresh: false,
                protect: false,
                env: None,
                wait_secs: None,
            }),
        };
        let line = serde_json::to_string(&env).unwrap();
        assert!(!line.contains('\n'));
        let back: RequestEnvelope = serde_json::from_str(&line).unwrap();
        assert_eq!(back.v, PROTOCOL_VERSION);
        assert_eq!(PROTOCOL_VERSION, 2);
        match back.request {
            Request::CloneCreate(a) => {
                assert_eq!(a.template, "main");
                assert_eq!(a.name.as_deref(), Some("feat"));
                assert_eq!(a.ttl_secs, 7200);
                assert_eq!(a.parent_pid, Some(42));
            }
            other => panic!("wrong variant: {other:?}"),
        }
    }

    #[test]
    fn err_response_round_trip() {
        let env = ResponseEnvelope {
            v: PROTOCOL_VERSION,
            result: Err(
                MitosisError::new(ErrorCode::CapReached, "too many").with_hint("destroy one")
            ),
        };
        let line = serde_json::to_string(&env).unwrap();
        let back: ResponseEnvelope = serde_json::from_str(&line).unwrap();
        let e = back.result.unwrap_err();
        assert_eq!(e.code, ErrorCode::CapReached);
        assert_eq!(e.hint.as_deref(), Some("destroy one"));
    }

    fn template_info() -> TemplateInfo {
        TemplateInfo {
            name: "main".into(),
            pg_major: 16,
            source: TemplateSource::Url {
                url: "postgres://x".into(),
            },
            database: "app".into(),
            size_bytes: 1024,
            built_at: 1_700_000_000,
            age_secs: 5,
            warnings: vec!["w".into()],
            current_gen: 2,
            generations: 2,
            paused: true,
            last_error: Some("boom".into()),
            every_secs: Some(86_400),
            every_mode: RefreshMode::Layered,
            migrate: Some("make migrate".into()),
            auto_migrate: true,
            on_stale: OnStale::Refresh,
            keep: 3,
        }
    }

    fn clone_info() -> CloneInfo {
        CloneInfo {
            id: "abc123".into(),
            name: Some("feat".into()),
            template: "main".into(),
            url: "postgres://localhost:5500/app".into(),
            port: 5500,
            socket_dir: "/tmp/s".into(),
            template_age_secs: 5,
            created_at: 1,
            expires_at: 2,
            durable: false,
            parent_pid: Some(7),
            rss_bytes: None,
            own_disk_bytes: Some(9),
            generation: 2,
            stale: true,
            refreshing: true,
            existing: false,
            protected: false,
            warnings: Vec::new(),
            duration_ms: 0,
            waited_ms: 0,
            disk_warn: false,
            suspect: false,
        }
    }

    fn round_trip(r: Response) {
        let env = ResponseEnvelope {
            v: PROTOCOL_VERSION,
            result: Ok(r),
        };
        let line = serde_json::to_string(&env).unwrap();
        let back: ResponseEnvelope = serde_json::from_str(&line).unwrap();
        assert_eq!(
            serde_json::to_value(&env).unwrap(),
            serde_json::to_value(&back).unwrap()
        );
    }

    #[test]
    fn list_and_newtype_responses_round_trip() {
        round_trip(Response::Templates {
            templates: vec![template_info()],
        });
        round_trip(Response::Clones {
            clones: vec![clone_info()],
        });
        round_trip(Response::TemplateBuilt(template_info()));
        round_trip(Response::CloneCreated(clone_info()));
        round_trip(Response::Generations {
            template: "main".into(),
            generations: vec![GenerationInfo {
                gen: 1,
                kind: GenKind::Promoted,
                built_at: 1,
                pg_major: 16,
                size_bytes: 2,
                current: true,
                from_clone: Some("feat".into()),
                from_gen: Some(3),
            }],
            paused: true,
        });
    }

    #[test]
    fn v01_shapes_still_parse() {
        let t: TemplateInfo = serde_json::from_str(
            r#"{"name":"main","pg_major":16,"source":{"kind":"url","url":"postgres://h/db"},
                "database":"db","size_bytes":1,"built_at":1,"age_secs":1,"warnings":[]}"#,
        )
        .unwrap();
        assert_eq!((t.current_gen, t.paused, t.last_error), (0, false, None));
        let r: Request =
            serde_json::from_str(r#"{"type":"template_rollback","name":"main"}"#).unwrap();
        assert!(matches!(r, Request::TemplateRollback { to: None, .. }));
        assert_eq!(
            serde_json::to_string(&GenKind::Upgraded).unwrap(),
            r#""upgraded""#
        );
    }

    #[test]
    fn seed_cwd_is_optional() {
        let s: TemplateSource =
            serde_json::from_str(r#"{"kind":"seed","command":"make seed"}"#).unwrap();
        assert_eq!(
            s,
            TemplateSource::Seed {
                command: "make seed".into(),
                cwd: None,
                path: None
            }
        );
        let s = TemplateSource::Seed {
            command: "x".into(),
            cwd: Some("/w".into()),
            path: Some("/usr/bin:/bin".into()),
        };
        assert_eq!(
            serde_json::from_str::<TemplateSource>(&serde_json::to_string(&s).unwrap()).unwrap(),
            s
        );
    }

    #[test]
    fn refresh_path_is_optional() {
        let r: Request =
            serde_json::from_str(r#"{"type":"template_refresh","name":"main"}"#).unwrap();
        assert!(matches!(
            r,
            Request::TemplateRefresh {
                path: None,
                layered: false,
                ..
            }
        ));
        let r: GcReport = serde_json::from_str(
            r#"{"adopted":[],"destroyed":[],"orphan_folders_removed":[],"records_dropped":[]}"#,
        )
        .unwrap();
        assert!(r.failed.is_empty());
    }

    #[test]
    fn template_settings_are_flat_and_optional() {
        let r: Request = serde_json::from_str(
            r#"{"type":"template_init","name":"main","source":{"kind":"seed","command":"x"},
                "database":null,"migrations":null,"max_age_secs":null,"pg_major":null}"#,
        )
        .unwrap();
        let Request::TemplateInit(a) = r else {
            panic!("wrong variant")
        };
        assert_eq!(a.settings, TemplateSettings::default());

        let set = Request::TemplateSet(TemplateSetArgs {
            name: "main".into(),
            max_age_secs: Some(60),
            settings: TemplateSettings {
                keep: Some(2),
                every_secs: Some(3600),
                every_mode: Some(RefreshMode::Layered),
                migrate: Some(MigrateCmd {
                    command: "make migrate".into(),
                    cwd: "/w".into(),
                    path: None,
                }),
                auto_migrate: Some(true),
                on_stale: Some(OnStale::Refresh),
                ..Default::default()
            },
            resume: true,
        });
        let line = serde_json::to_string(&set).unwrap();
        assert!(line.contains(r#""keep":2"#), "{line}");
        let Request::TemplateSet(back) = serde_json::from_str(&line).unwrap() else {
            panic!("wrong variant")
        };
        assert_eq!(back.settings.keep, Some(2));
        assert_eq!(back.settings.every_mode, Some(RefreshMode::Layered));
        assert_eq!(back.settings.migrate.unwrap().command, "make migrate");
        assert!(back.resume && !back.settings.every_off);
        let r: Response =
            serde_json::from_str(r#"{"type":"generations","template":"main","generations":[]}"#)
                .unwrap();
        assert!(matches!(r, Response::Generations { paused: false, .. }));
    }

    #[test]
    fn ok_response_round_trip() {
        let env = ResponseEnvelope {
            v: PROTOCOL_VERSION,
            result: Ok(Response::Ok),
        };
        let line = serde_json::to_string(&env).unwrap();
        let back: ResponseEnvelope = serde_json::from_str(&line).unwrap();
        assert!(matches!(back.result, Ok(Response::Ok)));
    }
}