Dungeon tests: CountingPort keeps usage per model and app_over's AppState assembly move to one test-support module

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 23:58:56 +01:00
commit 1fcd68f9c6
4 changed files with 190 additions and 81 deletions

View file

@ -812,7 +812,6 @@ async fn auth_logout(headers: HeaderMap, State(state): State<AppState>) -> Respo
mod tests {
use super::*;
use crate::{
app_session::AppSessionOwner,
begin::tests::{Rig, author, deferred_rig, eventually, one_vault, principal, rig},
heimdall::{
AccountSummary, AuthBeginReceipt, AuthCompletionReceipt, AuthNavigation, AuthProvider,
@ -953,41 +952,16 @@ mod tests {
}
async fn app_over(rig: Rig, accounts: &[&str]) -> App {
let key = rig.directory.path().join("session.key");
std::fs::write(&key, [17_u8; 32]).unwrap();
let mut sessions =
AppSessionOwner::open(rig.directory.path().join("service/app-sessions-v2.cc"), &key)
.unwrap();
let cookies = accounts
.iter()
.enumerate()
.map(|(index, account)| {
sessions
.create_session(VerifiedSessionAdmission::fixture(
*account,
format!("heimdall-session-{index}"),
1,
Utc::now() + chrono::Duration::hours(1),
Utc::now() + chrono::Duration::days(1),
"fixture-refresh",
))
.unwrap()
})
.collect();
let heimdall = Arc::new(FakeHeimdall::default());
let (fatal, fatal_events) = tokio::sync::mpsc::unbounded_channel();
let state = AppState {
catalog: rig.catalog.clone(),
timelines: rig.timelines.clone(),
vaults: one_vault(),
scale: rig.scale.clone(),
sessions: Arc::new(Mutex::new(sessions)),
heimdall: heimdall.clone(),
auth: Arc::default(),
runtime_id: "ghostlight-test".into(),
runtime_health: None,
fatal,
};
let (state, cookies, fatal_events) = crate::test_support::assemble(
rig.directory.path(),
rig.catalog.clone(),
rig.timelines.clone(),
rig.scale.clone(),
one_vault(),
heimdall.clone(),
accounts,
);
App {
router: service_router(state.clone()),
state,

View file

@ -12,6 +12,8 @@ mod run_ahead;
mod runtime;
mod session_refresh;
mod state_layout;
#[cfg(test)]
mod test_support;
mod timelines;
mod turn_log;
mod vaults;

View file

@ -129,7 +129,7 @@ fn lane_models_from(read: impl Fn(&str) -> Option<String>) -> (ControllerModels,
}
/// The one routed inference port every timeline and lane shares.
fn open_shared() -> anyhow::Result<Shared> {
pub(crate) fn open_shared() -> anyhow::Result<Shared> {
let (models, play_model) = lane_models();
let mut all: Vec<&str> = models.each().to_vec();
all.push(&play_model);
@ -599,37 +599,6 @@ fn require_no_runtime_custody_failure(
mod tests {
use super::*;
/// Counts every call and the usage the connector reports, around the real
/// port, for the live check.
struct CountingPort {
inner: Arc<dyn InferencePort>,
calls: std::sync::atomic::AtomicU64,
usage: std::sync::Mutex<(u64, u64)>,
}
#[async_trait::async_trait]
impl InferencePort for CountingPort {
fn prepare(
&self,
request: ghostlight::InferenceRequest,
) -> Result<ghostlight::PreparedInference, ghostlight::InferenceFault> {
self.inner.prepare(request)
}
async fn infer(
&self,
request: ghostlight::PreparedInference,
) -> Result<ghostlight::InferenceOutput, ghostlight::InferenceFault> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let output = self.inner.infer(request).await?;
let seen = serde_json::to_value(&output).unwrap_or_default();
let mut usage = self.usage.lock().unwrap();
usage.0 += seen["usage"]["prompt"].as_u64().unwrap_or(0);
usage.1 += seen["usage"]["completion"].as_u64().unwrap_or(0);
Ok(output)
}
}
/// Live: Begin on an imported snapshot through the real connector.
/// `GHOSTLIGHT_LIVE_STATE_ROOT` holds `snapshots/` from `import-vault`,
/// `GHOSTLIGHT_LIVE_PROFILE` names the profile, and the connector address
@ -648,11 +617,7 @@ mod tests {
let profile = std::env::var("GHOSTLIGHT_LIVE_PROFILE").unwrap();
prepare_admitted_state_layout(&root).unwrap();
let shared = open_shared().unwrap();
let counting = Arc::new(CountingPort {
inner: shared.inference.clone(),
calls: Default::default(),
usage: Default::default(),
});
let counting = crate::test_support::CountingPort::new(shared.inference.clone());
let shared = Shared { inference: counting.clone(), ..shared };
let (fatal, _fatal_events) = mpsc::unbounded_channel();
let timelines = Timelines::new(root.clone(), shared, fatal);
@ -691,8 +656,8 @@ mod tests {
Some(SeedStatus::Seeding) => tokio::time::sleep(Duration::from_secs(2)).await,
}
};
let (calls, usage) = (counting.calls.load(std::sync::atomic::Ordering::SeqCst), *counting.usage.lock().unwrap());
println!("LIVE ready after {ready:?}; calls={calls} prompt_tokens={} completion_tokens={}", usage.0, usage.1);
let used = counting.totals();
println!("LIVE ready after {ready:?}; calls={} prompt_tokens={} completion_tokens={}", used.calls, used.prompt, used.completion);
let host = timelines.host(&begun.timeline).await.unwrap();
// A position is not public on the snapshot; the Debug text names it by
// the same entity id a place carries.
@ -726,13 +691,8 @@ mod tests {
while host.sweeping.try_lock().is_err() && sweep_started.elapsed() < Duration::from_secs(1800) {
tokio::time::sleep(Duration::from_secs(2)).await;
}
let (calls, usage) = (counting.calls.load(std::sync::atomic::Ordering::SeqCst), *counting.usage.lock().unwrap());
println!(
"LIVE after run-ahead at {:?}: calls={calls} prompt_tokens={} completion_tokens={}",
started.elapsed(),
usage.0,
usage.1
);
let used = counting.totals();
println!("LIVE after run-ahead at {:?}: calls={} prompt_tokens={} completion_tokens={}", started.elapsed(), used.calls, used.prompt, used.completion);
report("after run-ahead", &host.world.snapshot().await.unwrap());
}

View file

@ -0,0 +1,173 @@
//! Test support the API tests, the live runtime check and the playtest
//! harness share: a counting port that keeps usage per model, and the one
//! assembly of an `AppState` with signed-in test sessions.
use crate::{
app_session::AppSessionOwner,
begin::{Scale, Vaults},
catalog::Catalog,
heimdall::{HeimdallPort, VerifiedSessionAdmission},
runtime::AppState,
timelines::Timelines,
};
use chrono::Utc;
use ghostlight::{
InferenceFault, InferenceOutput, InferencePort, InferenceRequest, PreparedInference,
};
use serde_json::Value;
use std::{
collections::BTreeMap,
path::Path,
sync::{Arc, Mutex as StdMutex},
};
use tokio::sync::{Mutex, mpsc};
/// What one model was asked and what the provider says it spent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct ModelUsage {
pub(crate) calls: u64,
pub(crate) prompt: u64,
pub(crate) cached_prompt: u64,
pub(crate) completion: u64,
}
/// Counts every call and the usage the connector reports, per model, around
/// the real port.
pub(crate) struct CountingPort {
inner: Arc<dyn InferencePort>,
usage: StdMutex<BTreeMap<String, ModelUsage>>,
}
impl CountingPort {
pub(crate) fn new(inner: Arc<dyn InferencePort>) -> Arc<Self> {
Arc::new(Self { inner, usage: StdMutex::new(BTreeMap::new()) })
}
pub(crate) fn by_model(&self) -> BTreeMap<String, ModelUsage> {
self.usage.lock().unwrap().clone()
}
pub(crate) fn totals(&self) -> ModelUsage {
self.by_model().values().fold(ModelUsage::default(), |sum, each| ModelUsage {
calls: sum.calls + each.calls,
prompt: sum.prompt + each.prompt,
cached_prompt: sum.cached_prompt + each.cached_prompt,
completion: sum.completion + each.completion,
})
}
}
/// The model a prepared request names: the `model` key wherever the request's
/// serialization keeps it, including inside a string that holds JSON.
fn model_of(value: &Value) -> Option<String> {
match value {
Value::Object(map) => map
.get("model")
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| map.values().find_map(model_of)),
Value::Array(items) => items.iter().find_map(model_of),
Value::String(text) if text.starts_with('{') => {
serde_json::from_str::<Value>(text).ok().and_then(|inner| model_of(&inner))
}
_ => None,
}
}
#[async_trait::async_trait]
impl InferencePort for CountingPort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.inner.prepare(request)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
let model = serde_json::to_value(&request)
.ok()
.and_then(|seen| model_of(&seen))
.unwrap_or_else(|| "unknown".into());
let output = self.inner.infer(request).await?;
let usage = output.usage();
let mut table = self.usage.lock().unwrap();
let row = table.entry(model).or_default();
row.calls += 1;
if let Some(usage) = usage {
row.prompt += usage.prompt;
row.cached_prompt += usage.cached_prompt.unwrap_or(0);
row.completion += usage.completion;
}
Ok(output)
}
}
/// An `AppState` over the given pieces with one signed-in session per entry of
/// `accounts` (the same account twice is the same player on two devices), the
/// session cookies in order, and the receiver of the fatal signals. Session
/// custody lives under `directory`.
pub(crate) fn assemble(
directory: &Path,
catalog: Arc<Mutex<Catalog>>,
timelines: Arc<Timelines>,
scale: Arc<Scale>,
vaults: Arc<dyn Vaults>,
heimdall: Arc<dyn HeimdallPort>,
accounts: &[&str],
) -> (AppState, Vec<String>, mpsc::UnboundedReceiver<String>) {
let key = directory.join("session.key");
std::fs::write(&key, [17_u8; 32]).unwrap();
let mut sessions =
AppSessionOwner::open(directory.join("service/app-sessions-v2.cc"), &key).unwrap();
let cookies = accounts
.iter()
.enumerate()
.map(|(index, account)| {
sessions
.create_session(VerifiedSessionAdmission::fixture(
*account,
format!("heimdall-session-{index}"),
1,
Utc::now() + chrono::Duration::hours(1),
Utc::now() + chrono::Duration::days(1),
"fixture-refresh",
))
.unwrap()
})
.collect();
let (fatal, fatal_events) = mpsc::unbounded_channel();
let state = AppState {
catalog,
timelines,
vaults,
scale,
sessions: Arc::new(Mutex::new(sessions)),
heimdall,
auth: Arc::default(),
runtime_id: "ghostlight-test".into(),
runtime_health: None,
fatal,
};
(state, cookies, fatal_events)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::play::tests::ScriptedPort;
#[test]
fn a_prepared_request_names_its_model() {
let port = ScriptedPort::new(vec![]);
let request = InferenceRequest::play(
ghostlight::CommandId::new(),
0,
"claude-opus-5-5",
"be brief",
vec![],
vec![],
100,
)
.unwrap();
let prepared = port.prepare(request).unwrap();
let seen = serde_json::to_value(&prepared).unwrap();
assert_eq!(model_of(&seen).as_deref(), Some("claude-opus-5-5"));
}
}