Watch
0
0
Fork
You've already forked hyperhive
0

hive-agent: keep the last turn's context size in the harness state file and drop the turn sqlite writes

This commit is contained in:
damocles 2026-11-18 02:24:13 +01:00
commit 5e5ff64b3c

View file

@ -6,7 +6,6 @@
use crate::events::Bus;
use crate::turn::{TurnError, TurnOutcome};
use crate::turn_stats::TurnStatRow;
/// Assemble the per-turn wake prompt string. The role/tools/etc. live in the
/// system prompt; this is just the wake signal body. `redelivered` prepends a "may already be handled" banner; `interrupted`
@ -26,15 +25,33 @@ pub fn format_wake_prompt(from: &str, body: &str, redelivered: bool, interrupted
format!("{banner}Incoming message from `{from}`:\n---\n{body}\n---")
}
/// Field-named args for [`build_row`]. Mirrors the turn-stats row
/// columns; `outcome` and `bus` borrow for the duration of the call.
/// `tool_calls` is passed in (rather than pulled from `bus` internally)
/// because the caller needs the same map to check for a `get_loose_ends`
/// call before it's consumed — `Bus::take_tool_calls` resets the counter,
/// so there's only one chance to read it per turn.
/// What one finished turn leaves for the OTEL turn metrics
/// (`otel_turn_metrics::record`).
#[derive(Debug, Clone)]
pub struct TurnStatRow {
pub started_at: i64,
pub duration_ms: i64,
pub model: String,
pub wake_from: String,
/// Prompt tokens billed at the full rate, summed over the turn's inferences.
pub input_tokens: u64,
/// Per-tool breakdown as JSON: `{"Read":12,"Bash":3,...}`; `None` when no
/// tool was called.
pub tool_call_breakdown_json: Option<String>,
/// Post-turn loose-ends snapshot; `None` when the request failed.
pub open_threads_count: Option<u64>,
pub open_reminders_count: Option<u64>,
/// `"ok" | "compacted" | "failed" | ...`, see [`build_row`].
pub result_kind: &'static str,
}
/// Field-named args for [`build_row`]; `outcome` and `bus` borrow for the
/// duration of the call. `tool_calls` is passed in (rather than pulled from
/// `bus` internally) because the caller needs the same map to check for a
/// `get_loose_ends` call before it's consumed — `Bus::take_tool_calls` resets
/// the counter, so there's only one chance to read it per turn.
pub struct TurnRowArgs<'a> {
pub started_at: i64,
pub ended_at: i64,
pub duration_ms: i64,
pub model: String,
pub wake_from: String,
@ -52,7 +69,6 @@ pub struct TurnRowArgs<'a> {
pub fn build_row(args: TurnRowArgs<'_>) -> TurnStatRow {
let TurnRowArgs {
started_at,
ended_at,
duration_ms,
model,
wake_from,
@ -64,50 +80,36 @@ pub fn build_row(args: TurnRowArgs<'_>) -> TurnStatRow {
} = args;
// Prefer the API-resolved model id (e.g. `claude-opus-4-8`) captured
// from this turn's assistant events over the requested `--model`
// name/alias, so the model-mix + cost rollup label the concrete
// version that ran. Falls back to the requested name on a degenerate
// turn that produced no assistant event.
// name/alias, so the model-mix rollup labels the concrete version that
// ran. Falls back to the requested name on a degenerate turn that
// produced no assistant event.
let model = bus.last_resolved_model().unwrap_or(model);
let cost = bus.last_cost_usage().unwrap_or_default();
let ctx = bus.last_ctx_usage().unwrap_or(cost);
let tool_call_count: u64 = tool_calls.values().copied().sum();
let tool_call_breakdown_json = if tool_calls.is_empty() {
None
} else {
serde_json::to_string(&tool_calls).ok()
};
let (result_kind, note) = match outcome {
Ok(false) => ("ok", None),
Ok(true) => ("compacted", None),
Err(TurnError::PromptTooLong) => ("prompt_too_long", None),
Err(TurnError::RateLimited) => ("rate_limited", None),
Err(TurnError::AuthFailed) => ("auth_failed", None),
Err(TurnError::SessionNotFound) => ("session_not_found", None),
Err(TurnError::ApiStall) => ("api_stall", None),
Err(TurnError::AgentStall(note)) => ("api_stall", Some(note.clone())),
Err(TurnError::Failed(e)) => ("failed", Some(format!("{e:#}"))),
let result_kind = match outcome {
Ok(false) => "ok",
Ok(true) => "compacted",
Err(TurnError::PromptTooLong) => "prompt_too_long",
Err(TurnError::RateLimited) => "rate_limited",
Err(TurnError::AuthFailed) => "auth_failed",
Err(TurnError::SessionNotFound) => "session_not_found",
Err(TurnError::ApiStall | TurnError::AgentStall(_)) => "api_stall",
Err(TurnError::Failed(_)) => "failed",
};
TurnStatRow {
started_at,
ended_at,
duration_ms,
model,
wake_from,
input_tokens: cost.input_tokens,
output_tokens: cost.output_tokens,
cache_read_input_tokens: cost.cache_read_input_tokens,
cache_creation_input_tokens: cost.cache_creation_input_tokens,
last_input_tokens: ctx.input_tokens,
last_output_tokens: ctx.output_tokens,
last_cache_read_input_tokens: ctx.cache_read_input_tokens,
last_cache_creation_input_tokens: ctx.cache_creation_input_tokens,
tool_call_count,
tool_call_breakdown_json,
open_threads_count,
open_reminders_count,
result_kind,
note,
session_id: bus.current_session_id(),
}
}
@ -135,3 +137,89 @@ mod wake_prompt_tests {
assert!(plain.starts_with("Incoming message from `a`:"));
}
}
#[cfg(test)]
mod build_row_tests {
use super::{TurnRowArgs, build_row};
use crate::events::Bus;
use crate::turn::TurnError;
fn row_for(
outcome: &crate::turn::TurnOutcome,
tool_calls: &[(&str, u64)],
) -> super::TurnStatRow {
build_row(TurnRowArgs {
started_at: 10,
duration_ms: 2_000,
model: "opus".to_owned(),
wake_from: "todo".to_owned(),
outcome,
bus: &Bus::new(),
tool_calls: tool_calls
.iter()
.map(|(k, v)| ((*k).to_owned(), *v))
.collect(),
open_threads_count: Some(2),
open_reminders_count: None,
})
}
#[test]
fn the_outcome_names_the_result_kind() {
let _dir = crate::paths::harness_dir_guard();
for (outcome, kind) in [
(Ok(false), "ok"),
(Ok(true), "compacted"),
(Err(TurnError::PromptTooLong), "prompt_too_long"),
(Err(TurnError::RateLimited), "rate_limited"),
(Err(TurnError::AuthFailed), "auth_failed"),
(Err(TurnError::SessionNotFound), "session_not_found"),
(Err(TurnError::ApiStall), "api_stall"),
(Err(TurnError::AgentStall("quiet".into())), "api_stall"),
(Err(TurnError::Failed(anyhow::anyhow!("boom"))), "failed"),
] {
assert_eq!(row_for(&outcome, &[]).result_kind, kind);
}
}
#[test]
fn the_row_carries_the_turns_identity_counts_and_tool_breakdown() {
let _dir = crate::paths::harness_dir_guard();
let row = row_for(&Ok(false), &[("Bash", 3)]);
assert_eq!((row.started_at, row.duration_ms), (10, 2_000));
assert_eq!(
(row.model.as_str(), row.wake_from.as_str()),
("opus", "todo")
);
assert_eq!(
(row.open_threads_count, row.open_reminders_count),
(Some(2), None)
);
assert_eq!(
row.tool_call_breakdown_json.as_deref(),
Some(r#"{"Bash":3}"#)
);
assert_eq!(row_for(&Ok(false), &[]).tool_call_breakdown_json, None);
}
/// The model the API resolved wins over the requested alias.
#[test]
fn the_resolved_model_replaces_the_requested_one() {
let _dir = crate::paths::harness_dir_guard();
let bus = Bus::new();
bus.set_resolved_model(Some("claude-opus-4-8".to_owned()));
let row = build_row(TurnRowArgs {
started_at: 0,
duration_ms: 0,
model: "opus".to_owned(),
wake_from: "todo".to_owned(),
outcome: &Ok(false),
bus: &bus,
tool_calls: std::collections::HashMap::new(),
open_threads_count: None,
open_reminders_count: None,
});
assert_eq!(row.model, "claude-opus-4-8");
}
}