use super::*;
pub(super) async fn get_context_budget(
registry: &SessionRegistry,
params: Value,
_ctx: ConnectionContext,
) -> Result<Value, RpcError> {
let p: SessionIdParams = parse(params, "session.get_context_budget")?;
Ok(json!(registry.get_context_budget(&p.session_id)?))
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::mpsc;
fn test_ctx() -> ConnectionContext {
let (tx, _rx) = mpsc::unbounded_channel();
ConnectionContext::new(tx)
}
fn measurement() -> crate::agent_loop::ContextBudgetSnapshot {
crate::agent_loop::ContextBudgetSnapshot {
context_window: 200_000,
overhead_tokens: 50_000,
overhead_cap_tokens: 80_000,
working_context_pct: 75,
overhead_pct: 25,
within_budget: true,
fired: false,
rounds: 1,
}
}
#[tokio::test]
async fn get_context_budget_never_recorded_session_returns_never_recorded() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap();
assert_eq!(result["status"], "never_recorded");
}
#[tokio::test]
async fn get_context_budget_returns_recorded_snapshot_after_recording() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
registry
.record_context_budget(&session.id, &measurement())
.unwrap();
let result = get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap();
assert_eq!(result["status"], "recorded");
assert_eq!(result["working_context_pct"], 75);
assert_eq!(result["within_budget"], true);
assert_eq!(result["context_window_tokens"], 200_000);
}
#[tokio::test]
async fn get_context_budget_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = get_context_budget(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
fn telemetry_temp_dir(label: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
"tcode-protocol-budget-alarm-test-{label}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[tokio::test]
async fn get_context_budget_reflects_lifetime_compaction_alarm_count() {
let dir = telemetry_temp_dir("reflects");
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = crate::agent_loop::telemetry::with_data_dir_env_fut(&dir, async {
crate::agent_loop::telemetry::record_compaction_alarm(&dir);
registry
.record_context_budget(&session.id, &measurement())
.unwrap();
get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap()
})
.await;
assert_eq!(result["status"], "recorded");
assert!(
result["lifetime_compaction_alarm_count"].as_u64().unwrap() >= 1,
"expected a non-zero alarm count, got {result:?}"
);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn get_context_budget_alarm_count_zero_without_a_fire() {
let dir = telemetry_temp_dir("zero");
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = crate::agent_loop::telemetry::with_data_dir_env_fut(&dir, async {
registry
.record_context_budget(&session.id, &measurement())
.unwrap();
get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap()
})
.await;
assert_eq!(result["lifetime_compaction_alarm_count"], 0);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn get_context_budget_alarm_count_survives_fresh_registry() {
let dir = telemetry_temp_dir("survives-restart");
let result = crate::agent_loop::telemetry::with_data_dir_env_fut(&dir, async {
crate::agent_loop::telemetry::record_compaction_alarm(&dir);
crate::agent_loop::telemetry::record_compaction_alarm(&dir);
let fresh_registry = SessionRegistry::new();
let session =
fresh_registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
fresh_registry
.record_context_budget(&session.id, &measurement())
.unwrap();
get_context_budget(
&fresh_registry,
json!({"session_id": session.id}),
test_ctx(),
)
.await
.unwrap()
})
.await;
assert_eq!(
result["lifetime_compaction_alarm_count"], 2,
"a fresh registry must read the SAME durable count, not reset to 0"
);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn get_context_budget_reflects_working_context_floor() {
let dir = telemetry_temp_dir("floor-reflects");
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = crate::agent_loop::telemetry::with_data_dir_env_fut(&dir, async {
for pct in [90, 48, 75] {
let mut sample = measurement();
sample.working_context_pct = pct;
registry
.record_context_budget(&session.id, &sample)
.unwrap();
}
get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap()
})
.await;
assert_eq!(
result["working_context_pct"], 75,
"the point-in-time snapshot still reports the latest turn"
);
assert_eq!(
result["working_context_pct_low_water_mark"], 48,
"the low-water mark must surface the real floor the snapshot alone hides"
);
assert_eq!(result["working_context_pct_sample_count"], 3);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn get_context_budget_floor_ignores_durable_log() {
let dir = telemetry_temp_dir("floor-ignores-log");
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = crate::agent_loop::telemetry::with_data_dir_env_fut(&dir, async {
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("compression.jsonl"), "{not-json}\n".repeat(10_000)).unwrap();
let mut sample = measurement();
sample.working_context_pct = 73;
registry
.record_context_budget(&session.id, &sample)
.unwrap();
get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap()
})
.await;
assert_eq!(result["working_context_pct_low_water_mark"], 73);
assert_eq!(result["working_context_pct_sample_count"], 1);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn get_context_budget_floor_without_durable_log() {
let dir = telemetry_temp_dir("floor-no-log");
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = crate::agent_loop::telemetry::with_data_dir_env_fut(&dir, async {
registry
.record_context_budget(&session.id, &measurement())
.unwrap();
get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap()
})
.await;
assert!(!dir.join("compression.jsonl").exists());
assert_eq!(result["working_context_pct_low_water_mark"], 75);
assert_eq!(result["working_context_pct_sample_count"], 1);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn get_context_budget_reflects_cadence_floor_breach_count() {
let dir = telemetry_temp_dir("floor-breach-reflects");
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = crate::agent_loop::telemetry::with_data_dir_env_fut(&dir, async {
crate::agent_loop::telemetry::record_cadence_floor_breach_alarm(&dir);
crate::agent_loop::telemetry::record_cadence_floor_breach_alarm(&dir);
registry
.record_context_budget(&session.id, &measurement())
.unwrap();
get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap()
})
.await;
assert_eq!(result["lifetime_cadence_floor_breach_count"], 2);
assert_eq!(
result["lifetime_compaction_alarm_count"], 0,
"the two alarm counters must never conflate — this scenario never \
recorded a threshold-under-cadence fire"
);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn get_context_budget_floor_breach_count_zero_without_a_fire() {
let dir = telemetry_temp_dir("floor-breach-zero");
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = crate::agent_loop::telemetry::with_data_dir_env_fut(&dir, async {
registry
.record_context_budget(&session.id, &measurement())
.unwrap();
get_context_budget(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap()
})
.await;
assert_eq!(result["lifetime_cadence_floor_breach_count"], 0);
std::fs::remove_dir_all(&dir).ok();
}
}