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

@ -31,7 +31,6 @@ mod reminders;
mod router_todos;
mod schedule_timer;
mod serve_common;
mod sqlite_writer;
mod state_entry_watch;
mod stats;
mod subagent_role_watch;
@ -52,7 +51,6 @@ mod todos;
mod todos_gauge;
mod transcribe;
mod turn;
mod turn_stats;
mod vacuum;
mod web_ui;
@ -107,7 +105,6 @@ use std::time::Duration;
use crate::events::{Bus, LiveEvent, TurnState};
use crate::login::LoginState;
use crate::turn_stats::TurnStats;
use anyhow::Result;
use clap::Parser;
use hive_core_agent_sock::{Request, Response};
@ -526,12 +523,11 @@ async fn serve_main<S: Surface>(socket: &Path, poll_ms: u64) -> Result<()> {
// `hive_sh4re::inbox::INTERRUPTED_HINT`. Shared between the web server task and
// the serve loop the same way `bus`/`todo_wake` are.
let interrupted = Arc::new(std::sync::atomic::AtomicBool::new(false));
let stats = TurnStats::open_default();
if let Some(s) = &stats {
let (ctx, cost) = s.last_usage();
if ctx.is_some() || cost.is_some() {
bus.seed_usage(ctx, cost);
}
if let Some(tokens) = harness_state::read_context_tokens() {
// Only the total is kept; it is the one figure anything reads.
let mut ctx = hive_claude::TokenUsage::default();
ctx.input_tokens = tokens;
bus.seed_usage(Some(ctx), None);
}
let files = turn::TurnFiles::prepare(socket, &label).await?;
plugins::install_configured().await;
@ -612,7 +608,6 @@ async fn serve_main<S: Surface>(socket: &Path, poll_ms: u64) -> Result<()> {
login_state,
claude_dir,
bus,
stats,
&files,
todo_wake,
todos_store,
@ -729,7 +724,6 @@ async fn serve_loop<S: Surface>(
login_state: Arc<Mutex<LoginState>>,
claude_dir: std::path::PathBuf,
bus: Bus,
stats: Option<TurnStats>,
files: &turn::TurnFiles,
todo_wake: Arc<tokio::sync::Notify>,
todos_store: Option<Arc<todos::Todos>>,
@ -863,7 +857,6 @@ async fn serve_loop<S: Surface>(
let _ = handle_turn::<S>(
socket,
&bus,
stats.as_ref(),
files,
&session,
graceful_stop_message(),
@ -877,7 +870,6 @@ async fn serve_loop<S: Surface>(
let turn_ctx = TurnCtx {
socket,
bus: &bus,
stats: stats.as_ref(),
files,
session: &session,
interrupted: &interrupted,
@ -897,7 +889,6 @@ async fn serve_loop<S: Surface>(
struct TurnCtx<'a> {
socket: &'a Path,
bus: &'a Bus,
stats: Option<&'a TurnStats>,
files: &'a turn::TurnFiles,
session: &'a turn::AgentSession,
interrupted: &'a Arc<std::sync::atomic::AtomicBool>,
@ -923,7 +914,6 @@ async fn drive_turn_and_wake_chain<S: Surface>(
let ctrl = handle_turn::<S>(
ctx.socket,
ctx.bus,
ctx.stats,
ctx.files,
ctx.session,
next,
@ -1005,12 +995,11 @@ fn apply_todo_wake_checked(checked: Option<bool>, todo_miss_streak: &mut u32, bu
/// Drive a single turn: emit boot-of-turn events, run claude, ack on
/// success / requeue on rate-limit-or-401 / log `turn failed` on a hard
/// failure (the line the `hh-agent-turn-failed` Grafana rule alerts on),
/// record stats. Returns a `TurnControl` carrying the auth-failed flag and
/// keep the context size. Returns a `TurnControl` carrying the auth-failed flag and
/// the todo-wake-checked signal — the serve loop decides what to do next.
async fn handle_turn<S: Surface>(
socket: &Path,
bus: &Bus,
stats: Option<&TurnStats>,
files: &turn::TurnFiles,
session: &turn::AgentSession,
first: hive_sh4re::inbox::DeliveredMessage,
@ -1045,37 +1034,20 @@ async fn handle_turn<S: Surface>(
handle_turn_error_recovery::<S>(&outcome, bus, socket).await;
// Single read of the per-turn tool-call counter: `take_tool_calls`
// resets it, so this is the only chance to see which tools this turn
// invoked. Used both for the stats row below (if stats are configured)
// and for the todo-miss-streak signal returned to the serve loop —
// deliberately unconditional (not gated on `stats.is_some()`) so the
// counter is reset every turn regardless, and so a stats-less harness
// (tests, or a future config without a stats sink) still gets the
// miss-streak signal.
// invoked. Used both for the OTEL tool counts below and for the
// todo-miss-streak signal returned to the serve loop.
let tool_calls = bus.take_tool_calls();
let todo_wake_checked =
(from == "todo").then(|| tool_calls.contains_key("mcp__hyperhive__get_loose_ends"));
// Read-and-clear once per turn unconditionally (same rationale as
// `take_tool_calls` above — the harness gets exactly one chance to
// observe this flag) rather than only when the sqlite sink happens to be
// configured: the OTEL turn-metrics exporter's session-boundary counter
// needs it too, independent of `stats`.
// Read-and-clear once per turn (same rationale as `take_tool_calls`
// above — the harness gets exactly one chance to observe this flag): the
// OTEL turn-metrics exporter's session-boundary counter needs it.
let fresh_session = bus.take_fresh_session();
if let Some(stats) = stats {
// Fresh session this turn → mint a `sessions` row and set its id on
// the bus so this turn (and subsequent ones until the next fresh
// start) stamp `turn_stats.session_id`.
if fresh_session {
let sid = stats.start_session(started_at, &model_at_start);
bus.set_session_id(sid);
}
}
let ended_at = chrono::Utc::now().timestamp();
let duration_ms = i64::try_from(started_instant.elapsed().as_millis()).unwrap_or(i64::MAX);
let (open_threads, open_reminders) = S::post_turn_counts(socket).await;
let context_window = bus.api_context_window();
let row = serve_common::build_row(serve_common::TurnRowArgs {
started_at,
ended_at,
duration_ms,
model: model_at_start,
wake_from: from.clone(),
@ -1086,8 +1058,8 @@ async fn handle_turn<S: Surface>(
open_reminders_count: open_reminders,
});
// Harness-only OTEL metrics (duration/wake_from/result_kind/loose-ends/
// session boundaries/context fill) — independent of the sqlite sink
// below, and a cheap no-op when OTEL isn't configured. See
// session boundaries/context fill), a cheap no-op when OTEL isn't
// configured. See
// `otel_turn_metrics`'s module doc for why token/tool-count are
// deliberately not here, and why cost is only ever an ACP agent's.
otel_turn_metrics::record(&row, fresh_session);
@ -1097,8 +1069,8 @@ async fn handle_turn<S: Surface>(
for cost in hive_runtime::Runtime::take_reported_cost(session) {
otel_turn_metrics::record_reported_cost(&row.model, &cost);
}
if let Some(stats) = stats {
stats.record(&row);
if let Some(ctx) = bus.last_ctx_usage() {
harness_state::write_context_tokens(ctx.context_tokens());
}
let pending = S::inbox_unread(socket).await;
if pending > 0 {