use serde::{Deserialize, Serialize};
use crate::{
types::{
EndCause, Holder, JobClass, JobProfile, JobRun, Lease, LeaseKind, LeaseState, NoiseReport,
SessionKey, SessionUsage,
},
ui::Notice,
};
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HealthResponse {
pub version: String,
pub pid: u32,
pub uptime_secs: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub config_error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProfileSpec {
Class(JobClass),
Preset(String),
Custom(JobProfile),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanFitRequest {
pub profile: ProfileSpec,
pub kind: LeaseKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min_cores: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
}
pub const REASON_BEYOND_LEASES: &str = "more than the machine can free";
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Verdict {
pub fits: bool,
pub reasons: Vec<String>,
pub wait_estimate_secs: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub benchmark: Option<BenchmarkProgress>,
}
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(tag = "phase", rename_all = "snake_case")]
#[non_exhaustive]
pub enum BenchmarkProgress {
Draining {
active_leases: u32,
},
Measuring {
measured_secs: u64,
needed_secs: u64,
cpu_avg_pct: f32,
gpu_avg_pct: f32,
},
Noisy {
cpu_avg_pct: f32,
gpu_avg_pct: f32,
cpu_limit_pct: f32,
gpu_limit_pct: f32,
grant_anyway_in_secs: u64,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AcquireRequest {
pub holder: Holder,
pub profile: ProfileSpec,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min_cores: Option<f32>,
pub kind: LeaseKind,
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
pub wait_timeout_secs: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AcquireResponse {
pub lease: Lease,
pub verdict: Verdict,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct WaitRequest {
pub wait_timeout_secs: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaseOwner {
pub session: SessionKey,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeartbeatResponse {
pub state: LeaseState,
pub expires_at_ms: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_cause: Option<EndCause>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReleaseResponse {
pub lease: Lease,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub noise: Option<NoiseReport>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run: Option<RunReport>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next: Option<NextReservation>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct RunReport {
pub used: JobProfile,
pub counted: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NextReservation {
pub profile: JobProfile,
pub reasons: Vec<String>,
}
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KillResponse {
pub lease: Lease,
pub terminated: Vec<KilledProcess>,
pub failed: Vec<UnkilledProcess>,
pub spared: Vec<UnkilledProcess>,
pub untouched_reason: Option<String>,
}
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KilledProcess {
pub pid: u32,
pub name: String,
}
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnkilledProcess {
pub pid: u32,
pub name: String,
pub reason: String,
}
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RemoveResponse {
pub lease: Lease,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BindRequest {
pub tool_use_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub command: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NoticesResponse {
pub notices: Vec<Notice>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeliveredResponse {
pub delivered: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct LeaseQuery {
pub session: Option<SessionKey>,
pub state: Option<LeaseState>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LeasesResponse {
pub leases: Vec<Lease>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionsResponse {
pub sessions: Vec<SessionUsage>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegisterSessionRequest {
pub holder: Holder,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HistoryResponse {
pub jobs: Vec<JobSummary>,
}
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobSummary {
pub fingerprint: String,
pub command: String,
pub cwd: String,
pub runs: u32,
pub estimate_runs: u32,
pub last_ended_at_ms: i64,
pub learned: Option<JobProfile>,
#[serde(default)]
pub stats: Option<RunStats>,
}
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct RunStats {
pub runs: u32,
pub median: JobProfile,
pub p90: JobProfile,
pub max: JobProfile,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HistoryRunsQuery {
pub fingerprint: String,
pub limit: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HistoryRunsResponse {
pub runs: Vec<JobRun>,
#[serde(default)]
pub stats: Option<RunStats>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::{
assert_json_round_trip, sample_holder, sample_lease, sample_session_usage,
};
fn sample_verdict() -> Verdict {
Verdict {
fits: false,
reasons: vec!["RAM: 6144 MB requested, 4096 MB free after headroom".into()],
wait_estimate_secs: Some(90),
benchmark: None,
}
}
fn custom_profile() -> ProfileSpec {
ProfileSpec::Custom(JobProfile {
cores: 3.5,
ram_mb: 6144,
gpu_pct: 40.0,
vram_mb: 2048,
est_secs: 120,
})
}
#[test]
fn test_health_response_json_round_trip_preserves_every_field() {
assert_json_round_trip(&HealthResponse {
version: "0.1.0".into(),
pid: 4242,
uptime_secs: 3600,
config_error: Some("config.toml: invalid configuration: x".into()),
});
}
#[test]
fn test_can_fit_request_json_round_trip_preserves_both_profile_forms() {
assert_json_round_trip(&CanFitRequest {
profile: ProfileSpec::Class(JobClass::GpuHeavy),
kind: LeaseKind::Normal,
min_cores: None,
label: None,
cwd: None,
});
assert_json_round_trip(&CanFitRequest {
profile: custom_profile(),
kind: LeaseKind::BenchmarkExclusive,
min_cores: Some(2.0),
label: Some("cargo bench".into()),
cwd: Some(r"E:\work\app".into()),
});
}
#[test]
fn test_can_fit_request_without_label_and_cwd_deserializes_as_none() {
let request: CanFitRequest =
serde_json::from_str(r#"{"profile":{"class":"light"},"kind":"normal"}"#).unwrap();
assert_eq!((request.label, request.cwd), (None, None));
}
#[test]
fn test_profile_spec_json_is_externally_tagged() {
let class = serde_json::to_value(ProfileSpec::Class(JobClass::CpuHeavy)).unwrap();
assert_eq!(class, serde_json::json!({ "class": "cpu_heavy" }));
let custom = serde_json::to_value(custom_profile()).unwrap();
assert_eq!(custom["custom"]["ram_mb"], 6144);
}
#[test]
fn test_verdict_json_round_trip_preserves_every_field() {
assert_json_round_trip(&sample_verdict());
assert_json_round_trip(&Verdict {
fits: true,
reasons: vec![],
wait_estimate_secs: None,
benchmark: None,
});
}
#[test]
fn test_verdict_benchmark_progress_round_trips_every_phase() {
let phases = [
BenchmarkProgress::Draining { active_leases: 2 },
BenchmarkProgress::Measuring {
measured_secs: 4,
needed_secs: 10,
cpu_avg_pct: 6.5,
gpu_avg_pct: 0.0,
},
BenchmarkProgress::Noisy {
cpu_avg_pct: 12.5,
gpu_avg_pct: 1.0,
cpu_limit_pct: 10.0,
gpu_limit_pct: 10.0,
grant_anyway_in_secs: 35,
},
];
for phase in phases {
assert_json_round_trip(&Verdict {
benchmark: Some(phase),
..sample_verdict()
});
}
let value = serde_json::to_value(phases[0]).unwrap();
assert_eq!(
value,
serde_json::json!({ "phase": "draining", "active_leases": 2 })
);
}
#[test]
fn test_verdict_without_benchmark_field_deserializes_as_none() {
let verdict: Verdict =
serde_json::from_str(r#"{"fits":true,"reasons":[],"wait_estimate_secs":null}"#)
.unwrap();
assert_eq!(verdict.benchmark, None);
}
#[test]
fn test_acquire_request_json_round_trip_preserves_every_field() {
assert_json_round_trip(&AcquireRequest {
holder: sample_holder(),
profile: custom_profile(),
min_cores: Some(1.5),
kind: LeaseKind::Normal,
label: "cargo build --release".into(),
cwd: Some(r"E:\work\app".into()),
wait_timeout_secs: 30,
});
}
#[test]
fn test_acquire_response_json_round_trip_preserves_every_field() {
assert_json_round_trip(&AcquireResponse {
lease: sample_lease(),
verdict: sample_verdict(),
});
}
#[test]
fn test_lease_owner_json_round_trip_preserves_every_field() {
assert_json_round_trip(&LeaseOwner {
session: sample_holder().session,
});
}
#[test]
fn test_heartbeat_response_json_round_trip_preserves_every_field() {
assert_json_round_trip(&HeartbeatResponse {
state: LeaseState::Queued,
expires_at_ms: 1_793_000_060_000,
end_cause: None,
});
assert_json_round_trip(&HeartbeatResponse {
state: LeaseState::Expired,
expires_at_ms: 1_793_000_060_000,
end_cause: Some(EndCause::Killed),
});
}
#[test]
fn test_heartbeat_response_from_an_older_allotd_has_no_cause() {
let old: HeartbeatResponse =
serde_json::from_str(r#"{"state":"expired","expires_at_ms":5}"#).unwrap();
assert_eq!(old.end_cause, None);
}
#[test]
fn test_release_response_json_round_trip_preserves_every_field() {
assert_json_round_trip(&ReleaseResponse {
lease: sample_lease(),
noise: None,
run: None,
next: None,
});
let profile = sample_lease().profile;
assert_json_round_trip(&ReleaseResponse {
lease: sample_lease(),
noise: Some(NoiseReport {
avg_cpu_pct: 1.5,
peak_cpu_pct: 4.0,
avg_gpu_pct: 0.0,
peak_gpu_pct: 2.0,
quiet_at_start: true,
}),
run: Some(RunReport {
used: profile,
counted: true,
}),
next: Some(NextReservation {
profile,
reasons: vec!["cores 2.2 from p90 of 3 past run(s) plus 10% (declared 8.0)".into()],
}),
});
}
#[test]
fn test_release_response_from_an_older_allotd_has_no_run_or_next() {
let mut json = serde_json::to_value(ReleaseResponse {
lease: sample_lease(),
noise: None,
run: None,
next: None,
})
.unwrap();
assert!(
json.get("run").is_none() && json.get("next").is_none(),
"{json}"
);
json.as_object_mut().unwrap().remove("noise");
let old: ReleaseResponse = serde_json::from_value(json).unwrap();
assert_eq!((old.run, old.next), (None, None));
}
#[test]
fn test_wait_request_json_round_trip_preserves_every_field() {
assert_json_round_trip(&WaitRequest {
wait_timeout_secs: 90,
});
}
#[test]
fn test_lease_query_json_round_trip_preserves_empty_and_full_filters() {
assert_json_round_trip(&LeaseQuery::default());
assert_json_round_trip(&LeaseQuery {
session: Some(sample_holder().session),
state: Some(LeaseState::Active),
});
}
#[test]
fn test_lease_query_missing_fields_deserialize_as_none() {
let query: LeaseQuery = serde_json::from_str("{}").unwrap();
assert_eq!(query, LeaseQuery::default());
}
#[test]
fn test_leases_response_json_round_trip_preserves_every_field() {
assert_json_round_trip(&LeasesResponse {
leases: vec![sample_lease()],
});
}
#[test]
fn test_sessions_response_json_round_trip_preserves_every_field() {
assert_json_round_trip(&SessionsResponse {
sessions: vec![sample_session_usage()],
});
}
#[test]
fn test_history_dtos_json_round_trip_preserve_every_field() {
let ProfileSpec::Custom(p90) = custom_profile() else {
panic!("the custom profile fixture is not custom");
};
let stats = RunStats {
runs: 4,
median: JobProfile {
cores: 2.5,
ram_mb: 900,
..p90
},
p90,
max: JobProfile {
est_secs: p90.est_secs * 2,
..p90
},
};
let summary = JobSummary {
fingerprint: r"cargo build|e:\work\app".into(),
command: "cargo build".into(),
cwd: r"E:\work\app".into(),
runs: 5,
estimate_runs: 4,
last_ended_at_ms: 1_793_000_095_000,
learned: Some(stats.p90),
stats: Some(stats),
};
assert_json_round_trip(&HistoryResponse {
jobs: vec![
summary.clone(),
JobSummary {
learned: None,
stats: None,
..summary
},
],
});
assert_json_round_trip(&HistoryRunsQuery {
fingerprint: "cargo build|".into(),
limit: Some(10),
});
assert_json_round_trip(&HistoryRunsResponse {
runs: Vec::new(),
stats: None,
});
assert_json_round_trip(&HistoryRunsResponse {
runs: Vec::new(),
stats: Some(stats),
});
}
#[test]
fn test_history_responses_from_an_older_allotd_have_no_stats() {
let summary: JobSummary = serde_json::from_str(
r#"{"fingerprint":"x|","command":"x","cwd":"","runs":1,"estimate_runs":0,
"last_ended_at_ms":5,"learned":null}"#,
)
.unwrap();
assert_eq!(summary.stats, None);
let runs: HistoryRunsResponse = serde_json::from_str(r#"{"runs":[]}"#).unwrap();
assert_eq!(runs.stats, None);
}
#[test]
fn test_kill_and_remove_responses_json_round_trip_preserve_every_field() {
assert_json_round_trip(&KillResponse {
lease: sample_lease(),
terminated: vec![KilledProcess {
pid: 30_112,
name: "bash.exe".into(),
}],
failed: vec![UnkilledProcess {
pid: 30_140,
name: "cargo.exe".into(),
reason: "Access is denied.".into(),
}],
spared: vec![UnkilledProcess {
pid: 30_150,
name: "claude.exe".into(),
reason: "protected".into(),
}],
untouched_reason: None,
});
let untouched = KillResponse {
lease: sample_lease(),
terminated: Vec::new(),
failed: Vec::new(),
spared: Vec::new(),
untouched_reason: Some("the lease has no bound process tree".into()),
};
assert_json_round_trip(&untouched);
assert_json_round_trip(&RemoveResponse {
lease: sample_lease(),
});
}
#[test]
fn test_bind_request_without_command_omits_it() {
let request = BindRequest {
tool_use_id: "toolu_01AbC".into(),
command: None,
};
assert_json_round_trip(&request);
let value = serde_json::to_value(&request).unwrap();
assert_eq!(value, serde_json::json!({ "tool_use_id": "toolu_01AbC" }));
assert_json_round_trip(&BindRequest {
command: Some("cargo build".into()),
..request
});
}
#[test]
fn test_notice_dtos_json_round_trip_preserve_every_field() {
assert_json_round_trip(&NoticesResponse {
notices: Vec::new(),
});
assert_json_round_trip(&DeliveredResponse { delivered: true });
}
#[test]
fn test_register_session_request_json_round_trip_preserves_every_field() {
assert_json_round_trip(&RegisterSessionRequest {
holder: sample_holder(),
});
}
}