1use serde::{Deserialize, Serialize};
2
3use crate::{
4 types::{
5 EndCause, Holder, JobClass, JobProfile, JobRun, Lease, LeaseKind, LeaseState, NoiseReport,
6 SessionKey, SessionUsage,
7 },
8 ui::Notice,
9};
10
11#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct HealthResponse {
15 pub version: String,
17 pub pid: u32,
19 pub uptime_secs: u64,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub config_error: Option<String>,
25}
26
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30#[non_exhaustive]
31pub enum ProfileSpec {
32 Class(JobClass),
34 Preset(String),
37 Custom(JobProfile),
39}
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct CanFitRequest {
44 pub profile: ProfileSpec,
46 pub kind: LeaseKind,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub min_cores: Option<f32>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub label: Option<String>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub cwd: Option<String>,
58}
59
60pub const REASON_BEYOND_LEASES: &str = "more than the machine can free";
63
64#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct Verdict {
68 pub fits: bool,
70 pub reasons: Vec<String>,
72 pub wait_estimate_secs: Option<u64>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub benchmark: Option<BenchmarkProgress>,
77}
78
79#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
81#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
82#[serde(tag = "phase", rename_all = "snake_case")]
83#[non_exhaustive]
84pub enum BenchmarkProgress {
85 Draining {
87 active_leases: u32,
89 },
90 Measuring {
92 measured_secs: u64,
94 needed_secs: u64,
96 cpu_avg_pct: f32,
98 gpu_avg_pct: f32,
100 },
101 Noisy {
104 cpu_avg_pct: f32,
106 gpu_avg_pct: f32,
108 cpu_limit_pct: f32,
110 gpu_limit_pct: f32,
112 grant_anyway_in_secs: u64,
114 },
115}
116
117#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119pub struct AcquireRequest {
120 pub holder: Holder,
122 pub profile: ProfileSpec,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub min_cores: Option<f32>,
128 pub kind: LeaseKind,
130 pub label: String,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub cwd: Option<String>,
135 pub wait_timeout_secs: u64,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct AcquireResponse {
142 pub lease: Lease,
144 pub verdict: Verdict,
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150pub struct WaitRequest {
151 pub wait_timeout_secs: u64,
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161pub struct LeaseOwner {
162 pub session: SessionKey,
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168pub struct HeartbeatResponse {
169 pub state: LeaseState,
171 pub expires_at_ms: i64,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub end_cause: Option<EndCause>,
177}
178
179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181pub struct ReleaseResponse {
182 pub lease: Lease,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub noise: Option<NoiseReport>,
188 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub run: Option<RunReport>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub next: Option<NextReservation>,
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
200pub struct RunReport {
201 pub used: JobProfile,
204 pub counted: bool,
207}
208
209#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211pub struct NextReservation {
212 pub profile: JobProfile,
214 pub reasons: Vec<String>,
216}
217
218#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
221pub struct KillResponse {
222 pub lease: Lease,
224 pub terminated: Vec<KilledProcess>,
226 pub failed: Vec<UnkilledProcess>,
228 pub spared: Vec<UnkilledProcess>,
230 pub untouched_reason: Option<String>,
233}
234
235#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238pub struct KilledProcess {
239 pub pid: u32,
241 pub name: String,
243}
244
245#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248pub struct UnkilledProcess {
249 pub pid: u32,
251 pub name: String,
253 pub reason: String,
255}
256
257#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260pub struct RemoveResponse {
261 pub lease: Lease,
263}
264
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub struct BindRequest {
268 pub tool_use_id: String,
270 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub command: Option<String>,
273}
274
275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277pub struct NoticesResponse {
278 pub notices: Vec<Notice>,
280}
281
282#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
284pub struct DeliveredResponse {
285 pub delivered: bool,
288}
289
290#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
292pub struct LeaseQuery {
293 pub session: Option<SessionKey>,
295 pub state: Option<LeaseState>,
297}
298
299#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301pub struct LeasesResponse {
302 pub leases: Vec<Lease>,
304}
305
306#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
308pub struct SessionsResponse {
309 pub sessions: Vec<SessionUsage>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub struct RegisterSessionRequest {
317 pub holder: Holder,
319}
320
321#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
323pub struct HistoryResponse {
324 pub jobs: Vec<JobSummary>,
326}
327
328#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
331pub struct JobSummary {
332 pub fingerprint: String,
334 pub command: String,
336 pub cwd: String,
338 pub runs: u32,
340 pub estimate_runs: u32,
342 pub last_ended_at_ms: i64,
344 pub learned: Option<JobProfile>,
347 #[serde(default)]
350 pub stats: Option<RunStats>,
351}
352
353#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
358#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
359pub struct RunStats {
360 pub runs: u32,
362 pub median: JobProfile,
364 pub p90: JobProfile,
366 pub max: JobProfile,
368}
369
370#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
372pub struct HistoryRunsQuery {
373 pub fingerprint: String,
375 pub limit: Option<u32>,
377}
378
379#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
381pub struct HistoryRunsResponse {
382 pub runs: Vec<JobRun>,
384 #[serde(default)]
387 pub stats: Option<RunStats>,
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393 use crate::test_support::{
394 assert_json_round_trip, sample_holder, sample_lease, sample_session_usage,
395 };
396
397 fn sample_verdict() -> Verdict {
398 Verdict {
399 fits: false,
400 reasons: vec!["RAM: 6144 MB requested, 4096 MB free after headroom".into()],
401 wait_estimate_secs: Some(90),
402 benchmark: None,
403 }
404 }
405
406 fn custom_profile() -> ProfileSpec {
407 ProfileSpec::Custom(JobProfile {
408 cores: 3.5,
409 ram_mb: 6144,
410 gpu_pct: 40.0,
411 vram_mb: 2048,
412 est_secs: 120,
413 })
414 }
415
416 #[test]
417 fn test_health_response_json_round_trip_preserves_every_field() {
418 assert_json_round_trip(&HealthResponse {
419 version: "0.1.0".into(),
420 pid: 4242,
421 uptime_secs: 3600,
422 config_error: Some("config.toml: invalid configuration: x".into()),
423 });
424 }
425
426 #[test]
427 fn test_can_fit_request_json_round_trip_preserves_both_profile_forms() {
428 assert_json_round_trip(&CanFitRequest {
429 profile: ProfileSpec::Class(JobClass::GpuHeavy),
430 kind: LeaseKind::Normal,
431 min_cores: None,
432 label: None,
433 cwd: None,
434 });
435 assert_json_round_trip(&CanFitRequest {
436 profile: custom_profile(),
437 kind: LeaseKind::BenchmarkExclusive,
438 min_cores: Some(2.0),
439 label: Some("cargo bench".into()),
440 cwd: Some(r"E:\work\app".into()),
441 });
442 }
443
444 #[test]
445 fn test_can_fit_request_without_label_and_cwd_deserializes_as_none() {
446 let request: CanFitRequest =
447 serde_json::from_str(r#"{"profile":{"class":"light"},"kind":"normal"}"#).unwrap();
448 assert_eq!((request.label, request.cwd), (None, None));
449 }
450
451 #[test]
452 fn test_profile_spec_json_is_externally_tagged() {
453 let class = serde_json::to_value(ProfileSpec::Class(JobClass::CpuHeavy)).unwrap();
454 assert_eq!(class, serde_json::json!({ "class": "cpu_heavy" }));
455 let custom = serde_json::to_value(custom_profile()).unwrap();
456 assert_eq!(custom["custom"]["ram_mb"], 6144);
457 }
458
459 #[test]
460 fn test_verdict_json_round_trip_preserves_every_field() {
461 assert_json_round_trip(&sample_verdict());
462 assert_json_round_trip(&Verdict {
463 fits: true,
464 reasons: vec![],
465 wait_estimate_secs: None,
466 benchmark: None,
467 });
468 }
469
470 #[test]
471 fn test_verdict_benchmark_progress_round_trips_every_phase() {
472 let phases = [
473 BenchmarkProgress::Draining { active_leases: 2 },
474 BenchmarkProgress::Measuring {
475 measured_secs: 4,
476 needed_secs: 10,
477 cpu_avg_pct: 6.5,
478 gpu_avg_pct: 0.0,
479 },
480 BenchmarkProgress::Noisy {
481 cpu_avg_pct: 12.5,
482 gpu_avg_pct: 1.0,
483 cpu_limit_pct: 10.0,
484 gpu_limit_pct: 10.0,
485 grant_anyway_in_secs: 35,
486 },
487 ];
488 for phase in phases {
489 assert_json_round_trip(&Verdict {
490 benchmark: Some(phase),
491 ..sample_verdict()
492 });
493 }
494 let value = serde_json::to_value(phases[0]).unwrap();
495 assert_eq!(
496 value,
497 serde_json::json!({ "phase": "draining", "active_leases": 2 })
498 );
499 }
500
501 #[test]
502 fn test_verdict_without_benchmark_field_deserializes_as_none() {
503 let verdict: Verdict =
504 serde_json::from_str(r#"{"fits":true,"reasons":[],"wait_estimate_secs":null}"#)
505 .unwrap();
506 assert_eq!(verdict.benchmark, None);
507 }
508
509 #[test]
510 fn test_acquire_request_json_round_trip_preserves_every_field() {
511 assert_json_round_trip(&AcquireRequest {
512 holder: sample_holder(),
513 profile: custom_profile(),
514 min_cores: Some(1.5),
515 kind: LeaseKind::Normal,
516 label: "cargo build --release".into(),
517 cwd: Some(r"E:\work\app".into()),
518 wait_timeout_secs: 30,
519 });
520 }
521
522 #[test]
523 fn test_acquire_response_json_round_trip_preserves_every_field() {
524 assert_json_round_trip(&AcquireResponse {
525 lease: sample_lease(),
526 verdict: sample_verdict(),
527 });
528 }
529
530 #[test]
531 fn test_lease_owner_json_round_trip_preserves_every_field() {
532 assert_json_round_trip(&LeaseOwner {
533 session: sample_holder().session,
534 });
535 }
536
537 #[test]
538 fn test_heartbeat_response_json_round_trip_preserves_every_field() {
539 assert_json_round_trip(&HeartbeatResponse {
540 state: LeaseState::Queued,
541 expires_at_ms: 1_793_000_060_000,
542 end_cause: None,
543 });
544 assert_json_round_trip(&HeartbeatResponse {
545 state: LeaseState::Expired,
546 expires_at_ms: 1_793_000_060_000,
547 end_cause: Some(EndCause::Killed),
548 });
549 }
550
551 #[test]
552 fn test_heartbeat_response_from_an_older_allotd_has_no_cause() {
553 let old: HeartbeatResponse =
554 serde_json::from_str(r#"{"state":"expired","expires_at_ms":5}"#).unwrap();
555 assert_eq!(old.end_cause, None);
556 }
557
558 #[test]
559 fn test_release_response_json_round_trip_preserves_every_field() {
560 assert_json_round_trip(&ReleaseResponse {
561 lease: sample_lease(),
562 noise: None,
563 run: None,
564 next: None,
565 });
566 let profile = sample_lease().profile;
567 assert_json_round_trip(&ReleaseResponse {
568 lease: sample_lease(),
569 noise: Some(NoiseReport {
570 avg_cpu_pct: 1.5,
571 peak_cpu_pct: 4.0,
572 avg_gpu_pct: 0.0,
573 peak_gpu_pct: 2.0,
574 quiet_at_start: true,
575 }),
576 run: Some(RunReport {
577 used: profile,
578 counted: true,
579 }),
580 next: Some(NextReservation {
581 profile,
582 reasons: vec!["cores 2.2 from p90 of 3 past run(s) plus 10% (declared 8.0)".into()],
583 }),
584 });
585 }
586
587 #[test]
588 fn test_release_response_from_an_older_allotd_has_no_run_or_next() {
589 let mut json = serde_json::to_value(ReleaseResponse {
590 lease: sample_lease(),
591 noise: None,
592 run: None,
593 next: None,
594 })
595 .unwrap();
596 assert!(
597 json.get("run").is_none() && json.get("next").is_none(),
598 "{json}"
599 );
600 json.as_object_mut().unwrap().remove("noise");
601 let old: ReleaseResponse = serde_json::from_value(json).unwrap();
602 assert_eq!((old.run, old.next), (None, None));
603 }
604
605 #[test]
606 fn test_wait_request_json_round_trip_preserves_every_field() {
607 assert_json_round_trip(&WaitRequest {
608 wait_timeout_secs: 90,
609 });
610 }
611
612 #[test]
613 fn test_lease_query_json_round_trip_preserves_empty_and_full_filters() {
614 assert_json_round_trip(&LeaseQuery::default());
615 assert_json_round_trip(&LeaseQuery {
616 session: Some(sample_holder().session),
617 state: Some(LeaseState::Active),
618 });
619 }
620
621 #[test]
622 fn test_lease_query_missing_fields_deserialize_as_none() {
623 let query: LeaseQuery = serde_json::from_str("{}").unwrap();
624 assert_eq!(query, LeaseQuery::default());
625 }
626
627 #[test]
628 fn test_leases_response_json_round_trip_preserves_every_field() {
629 assert_json_round_trip(&LeasesResponse {
630 leases: vec![sample_lease()],
631 });
632 }
633
634 #[test]
635 fn test_sessions_response_json_round_trip_preserves_every_field() {
636 assert_json_round_trip(&SessionsResponse {
637 sessions: vec![sample_session_usage()],
638 });
639 }
640
641 #[test]
642 fn test_history_dtos_json_round_trip_preserve_every_field() {
643 let ProfileSpec::Custom(p90) = custom_profile() else {
644 panic!("the custom profile fixture is not custom");
645 };
646 let stats = RunStats {
647 runs: 4,
648 median: JobProfile {
649 cores: 2.5,
650 ram_mb: 900,
651 ..p90
652 },
653 p90,
654 max: JobProfile {
655 est_secs: p90.est_secs * 2,
656 ..p90
657 },
658 };
659 let summary = JobSummary {
660 fingerprint: r"cargo build|e:\work\app".into(),
661 command: "cargo build".into(),
662 cwd: r"E:\work\app".into(),
663 runs: 5,
664 estimate_runs: 4,
665 last_ended_at_ms: 1_793_000_095_000,
666 learned: Some(stats.p90),
667 stats: Some(stats),
668 };
669 assert_json_round_trip(&HistoryResponse {
670 jobs: vec![
671 summary.clone(),
672 JobSummary {
673 learned: None,
674 stats: None,
675 ..summary
676 },
677 ],
678 });
679 assert_json_round_trip(&HistoryRunsQuery {
680 fingerprint: "cargo build|".into(),
681 limit: Some(10),
682 });
683 assert_json_round_trip(&HistoryRunsResponse {
684 runs: Vec::new(),
685 stats: None,
686 });
687 assert_json_round_trip(&HistoryRunsResponse {
688 runs: Vec::new(),
689 stats: Some(stats),
690 });
691 }
692
693 #[test]
694 fn test_history_responses_from_an_older_allotd_have_no_stats() {
695 let summary: JobSummary = serde_json::from_str(
696 r#"{"fingerprint":"x|","command":"x","cwd":"","runs":1,"estimate_runs":0,
697 "last_ended_at_ms":5,"learned":null}"#,
698 )
699 .unwrap();
700 assert_eq!(summary.stats, None);
701 let runs: HistoryRunsResponse = serde_json::from_str(r#"{"runs":[]}"#).unwrap();
702 assert_eq!(runs.stats, None);
703 }
704
705 #[test]
706 fn test_kill_and_remove_responses_json_round_trip_preserve_every_field() {
707 assert_json_round_trip(&KillResponse {
708 lease: sample_lease(),
709 terminated: vec![KilledProcess {
710 pid: 30_112,
711 name: "bash.exe".into(),
712 }],
713 failed: vec![UnkilledProcess {
714 pid: 30_140,
715 name: "cargo.exe".into(),
716 reason: "Access is denied.".into(),
717 }],
718 spared: vec![UnkilledProcess {
719 pid: 30_150,
720 name: "claude.exe".into(),
721 reason: "protected".into(),
722 }],
723 untouched_reason: None,
724 });
725 let untouched = KillResponse {
726 lease: sample_lease(),
727 terminated: Vec::new(),
728 failed: Vec::new(),
729 spared: Vec::new(),
730 untouched_reason: Some("the lease has no bound process tree".into()),
731 };
732 assert_json_round_trip(&untouched);
733 assert_json_round_trip(&RemoveResponse {
734 lease: sample_lease(),
735 });
736 }
737
738 #[test]
739 fn test_bind_request_without_command_omits_it() {
740 let request = BindRequest {
741 tool_use_id: "toolu_01AbC".into(),
742 command: None,
743 };
744 assert_json_round_trip(&request);
745 let value = serde_json::to_value(&request).unwrap();
746 assert_eq!(value, serde_json::json!({ "tool_use_id": "toolu_01AbC" }));
747 assert_json_round_trip(&BindRequest {
748 command: Some("cargo build".into()),
749 ..request
750 });
751 }
752
753 #[test]
754 fn test_notice_dtos_json_round_trip_preserve_every_field() {
755 assert_json_round_trip(&NoticesResponse {
756 notices: Vec::new(),
757 });
758 assert_json_round_trip(&DeliveredResponse { delivered: true });
759 }
760
761 #[test]
762 fn test_register_session_request_json_round_trip_preserves_every_field() {
763 assert_json_round_trip(&RegisterSessionRequest {
764 holder: sample_holder(),
765 });
766 }
767}